Repository: coredao-org/dapp-tutorial Branch: master Commit: 563e6b3b0b97 Files: 1601 Total size: 9.7 MB Directory structure: gitextract_cf9vv67o/ ├── .gitignore ├── 01-Simple Storage Full Stack Dapp/ │ ├── .babelrc │ ├── .editorconfig │ ├── .eslintrc │ ├── .gitignore │ ├── .jest/ │ │ └── setup.ts │ ├── .prettierrc │ ├── README.md │ ├── index.html │ ├── jest.config.js │ ├── package.json │ ├── postcss.config.js │ ├── src/ │ │ ├── components/ │ │ │ └── App.tsx │ │ ├── contract/ │ │ │ ├── Storage.json │ │ │ └── Storage.sol │ │ ├── index.tsx │ │ ├── style/ │ │ │ └── index.css │ │ ├── utils/ │ │ │ └── index.ts │ │ └── vite-env.d.ts │ ├── tailwind.config.js │ ├── tsconfig.json │ └── vite.config.ts ├── 02-Basic Staking Full Stack Dapp/ │ ├── .gitignore │ ├── README.md │ ├── contracts/ │ │ ├── RewardToken.sol │ │ ├── StakingDapp.sol │ │ └── StakingToken.sol │ ├── frontend/ │ │ ├── .gitignore │ │ ├── README.md │ │ ├── package.json │ │ ├── public/ │ │ │ ├── index.html │ │ │ ├── manifest.json │ │ │ └── robots.txt │ │ └── src/ │ │ ├── App.css │ │ ├── App.js │ │ ├── App.test.js │ │ ├── components/ │ │ │ ├── Modal.css │ │ │ └── Modal.js │ │ ├── contracts/ │ │ │ ├── IRewardToken.json │ │ │ ├── RewardToken.json │ │ │ ├── StakingDapp.json │ │ │ └── StakingToken.json │ │ ├── index.css │ │ ├── index.js │ │ ├── reportWebVitals.js │ │ └── setupTests.js │ ├── hardhat.config.js │ ├── ignition/ │ │ └── modules/ │ │ └── Lock.js │ ├── package.json │ └── scripts/ │ └── deploy.js ├── 03-Decentralized Guestbook/ │ ├── .gitignore │ ├── README.md │ ├── contracts/ │ │ └── Guestbook.sol │ ├── frontend/ │ │ ├── .gitignore │ │ ├── README.md │ │ ├── package.json │ │ ├── public/ │ │ │ ├── index.html │ │ │ ├── manifest.json │ │ │ └── robots.txt │ │ └── src/ │ │ ├── App.css │ │ ├── App.js │ │ ├── GuestbookAbi.json │ │ ├── index.css │ │ ├── index.js │ │ ├── reportWebVitals.js │ │ └── setupTests.js │ ├── hardhat.config.js │ ├── package.json │ └── scripts/ │ └── deploy.js ├── 04-Pyth Pull Oracles/ │ ├── .gitignore │ ├── README.md │ ├── contracts/ │ │ └── PythFeedBoilerplate.sol │ ├── frontend/ │ │ ├── .gitignore │ │ ├── README.md │ │ ├── package.json │ │ ├── public/ │ │ │ ├── index.html │ │ │ ├── manifest.json │ │ │ └── robots.txt │ │ └── src/ │ │ ├── App.css │ │ ├── App.js │ │ ├── App.test.js │ │ ├── PythFeedBoilerplateAbi.json │ │ ├── index.css │ │ ├── index.js │ │ ├── reportWebVitals.js │ │ └── setupTests.js │ ├── hardhat.config.js │ ├── package.json │ └── scripts/ │ └── deploy.js ├── 05-Hello-World-Dapp/ │ ├── .gitignore │ ├── README.md │ ├── contracts/ │ │ ├── HelloWorld.sol │ │ └── Lock.sol │ ├── frontend/ │ │ ├── .gitignore │ │ ├── README.md │ │ ├── package.json │ │ ├── public/ │ │ │ ├── index.html │ │ │ ├── manifest.json │ │ │ └── robots.txt │ │ └── src/ │ │ ├── App.css │ │ ├── App.js │ │ ├── App.test.js │ │ ├── Contract-ABI/ │ │ │ └── HelloWorld.json │ │ ├── HelloWorld.css │ │ ├── HelloWorld.js │ │ ├── index.css │ │ ├── index.js │ │ ├── reportWebVitals.js │ │ └── setupTests.js │ ├── hardhat.config.js │ ├── ignition/ │ │ └── modules/ │ │ └── Lock.js │ ├── npx │ ├── package.json │ ├── scripts/ │ │ └── deploy.js │ └── test/ │ └── HelloWorld.js ├── 06-Subgraphs-on-Core/ │ ├── README.md │ ├── abis/ │ │ └── Guestbook.json │ ├── build/ │ │ ├── Guestbook/ │ │ │ ├── Guestbook.json │ │ │ └── Guestbook.wasm │ │ ├── schema.graphql │ │ └── subgraph.yaml │ ├── docker-compose.yml │ ├── generated/ │ │ ├── Guestbook/ │ │ │ └── Guestbook.ts │ │ └── schema.ts │ ├── networks.json │ ├── package.json │ ├── schema.graphql │ ├── src/ │ │ └── guestbook.ts │ ├── subgraph.yaml │ ├── tests/ │ │ ├── guestbook-utils.ts │ │ └── guestbook.test.ts │ └── tsconfig.json ├── 07-NFT Minitng dApp on Core/ │ ├── .gitignore │ ├── README.md │ ├── assets/ │ │ └── metadata.json │ ├── contracts/ │ │ ├── Lock.sol │ │ └── MyNFT.sol │ ├── frontend/ │ │ ├── .gitignore │ │ ├── README.md │ │ ├── index.html │ │ ├── package.json │ │ ├── src/ │ │ │ ├── App.css │ │ │ ├── App.jsx │ │ │ ├── abis/ │ │ │ │ └── MyNFTAbi.json │ │ │ ├── index.css │ │ │ └── main.jsx │ │ └── vite.config.js │ ├── hardhat.config.js │ ├── ignition/ │ │ └── modules/ │ │ └── Lock.js │ ├── package.json │ ├── scripts/ │ │ └── deploy.js │ └── test/ │ └── Lock.js ├── 08-Guess-Game/ │ ├── .gitignore │ ├── Frontend/ │ │ ├── .eslintrc.json │ │ ├── .gitignore │ │ ├── README.md │ │ ├── app/ │ │ │ ├── components/ │ │ │ │ └── ui/ │ │ │ │ ├── button.tsx │ │ │ │ ├── card.tsx │ │ │ │ └── input.tsx │ │ │ ├── constants/ │ │ │ │ ├── config.json │ │ │ │ └── solidityABI.json │ │ │ ├── globals.css │ │ │ ├── layout.tsx │ │ │ └── page.tsx │ │ ├── components.json │ │ ├── lib/ │ │ │ └── utils.ts │ │ ├── next.config.ts │ │ ├── package.json │ │ ├── postcss.config.mjs │ │ ├── tailwind.config.ts │ │ └── tsconfig.json │ ├── README.md │ ├── contracts/ │ │ ├── GuessTheNumber.sol │ │ └── GuessToken.sol │ ├── hardhat.config.js │ ├── ignition/ │ │ └── modules/ │ │ └── Lock.js │ ├── package.json │ ├── scripts/ │ │ └── deploy-guess-game.js │ └── test/ │ └── Lock.js ├── 09-Token-swap-Dapp/ │ ├── .gitignore │ ├── README.md │ ├── contracts/ │ │ ├── Swap.sol │ │ └── Token.sol │ ├── frontend/ │ │ ├── .gitignore │ │ ├── README.md │ │ ├── package.json │ │ ├── public/ │ │ │ ├── index.html │ │ │ ├── manifest.json │ │ │ └── robots.txt │ │ └── src/ │ │ ├── App.css │ │ ├── App.js │ │ ├── App.test.js │ │ ├── contracts/ │ │ │ ├── Swap.json │ │ │ └── Token.json │ │ ├── index.css │ │ ├── index.js │ │ ├── reportWebVitals.js │ │ └── setupTests.js │ ├── hardhat.config.js │ ├── package.json │ ├── scripts/ │ │ └── deploy.js │ └── test/ │ └── Swap.js ├── 10-Advanced-Stake-Dapp/ │ ├── .gitignore │ ├── Frontend/ │ │ ├── .eslintrc.json │ │ ├── .gitignore │ │ ├── README.md │ │ ├── app/ │ │ │ ├── globals.css │ │ │ ├── layout.tsx │ │ │ └── page.tsx │ │ ├── components/ │ │ │ ├── connect-wallet.tsx │ │ │ ├── global-overview.tsx │ │ │ ├── header.tsx │ │ │ ├── info-tooltip.tsx │ │ │ ├── mode-toggle.tsx │ │ │ ├── stake-form.tsx │ │ │ ├── staker-directory.tsx │ │ │ ├── staking-dashboard.tsx │ │ │ ├── staking-form.tsx │ │ │ ├── theme-provider.tsx │ │ │ ├── theme-toggle.tsx │ │ │ ├── ui/ │ │ │ │ ├── button.tsx │ │ │ │ ├── card.tsx │ │ │ │ ├── dropdown-menu.tsx │ │ │ │ ├── input.tsx │ │ │ │ ├── label.tsx │ │ │ │ ├── progress.tsx │ │ │ │ ├── slider.tsx │ │ │ │ ├── tabs.tsx │ │ │ │ ├── toast.tsx │ │ │ │ ├── toaster.tsx │ │ │ │ └── tooltip.tsx │ │ │ ├── user-dashboard.tsx │ │ │ ├── user-list.tsx │ │ │ ├── user-stats.tsx │ │ │ ├── wallet-connect.tsx │ │ │ ├── wallet-provider.tsx │ │ │ └── withdraw-form.tsx │ │ ├── components.json │ │ ├── constants/ │ │ │ └── constansts.tsx │ │ ├── hooks/ │ │ │ ├── use-staking-contract.tsx │ │ │ └── use-toast.ts │ │ ├── lib/ │ │ │ └── utils.ts │ │ ├── next.config.ts │ │ ├── package.json │ │ ├── postcss.config.mjs │ │ ├── tailwind.config.ts │ │ ├── tsconfig.json │ │ └── types/ │ │ └── global.d.ts │ ├── README.md │ ├── contracts/ │ │ ├── RewardToken.sol │ │ └── Stake.sol │ ├── hardhat.config.js │ ├── ignition/ │ │ └── modules/ │ │ └── Lock.js │ ├── package.json │ ├── scripts/ │ │ ├── deploy-stake.js │ │ └── mint.js │ └── test/ │ └── Lock.js ├── 11-Bridge-Token-Using-Chainlink/ │ ├── License │ ├── README.md │ ├── foundry/ │ │ ├── .github/ │ │ │ └── workflows/ │ │ │ └── test.yml │ │ ├── .gitignore │ │ ├── README.md │ │ ├── foundry.toml │ │ ├── remappings.txt │ │ ├── script/ │ │ │ ├── CrosschainBridge.s.sol │ │ │ └── HelperConfig.s.sol │ │ └── src/ │ │ ├── CrosschainBridge.sol │ │ ├── LinkTokenInterface.sol │ │ └── USDC.sol │ └── frontend/ │ ├── .gitignore │ ├── ABI/ │ │ ├── CrosschainBridge.json │ │ └── USDC.json │ ├── README.md │ ├── WalletConfig.tsx │ ├── app/ │ │ ├── Provider.tsx │ │ ├── globals.css │ │ ├── layout.tsx │ │ └── page.tsx │ ├── components/ │ │ └── ui/ │ │ ├── alert.tsx │ │ ├── button.tsx │ │ ├── card.tsx │ │ ├── input.tsx │ │ └── label.tsx │ ├── components.json │ ├── eslint.config.mjs │ ├── lib/ │ │ └── utils.ts │ ├── next.config.ts │ ├── package.json │ ├── postcss.config.mjs │ └── tsconfig.json ├── 12-Core-MultiSig/ │ ├── .gitignore │ ├── Frontend/ │ │ ├── .eslintrc.json │ │ ├── .gitignore │ │ ├── README.md │ │ ├── app/ │ │ │ ├── client.ts │ │ │ ├── constants/ │ │ │ │ ├── MultiSigFactory.json │ │ │ │ └── config.json │ │ │ ├── create/ │ │ │ │ ├── createmultisig.tsx │ │ │ │ └── multisigcreation.tsx │ │ │ ├── dashboard/ │ │ │ │ └── page.tsx │ │ │ ├── globals.css │ │ │ ├── layout.tsx │ │ │ ├── linkdash.tsx │ │ │ ├── owners/ │ │ │ │ └── page.tsx │ │ │ ├── page.tsx │ │ │ └── wallet/ │ │ │ ├── DialogBoxes/ │ │ │ │ ├── Confirm.tsx │ │ │ │ ├── Execute.tsx │ │ │ │ ├── Revoke.tsx │ │ │ │ └── Submit.tsx │ │ │ └── page.tsx │ │ ├── components/ │ │ │ ├── DashboardLayout.tsx │ │ │ └── ui/ │ │ │ ├── button.tsx │ │ │ ├── card.tsx │ │ │ ├── dialog.tsx │ │ │ ├── input.tsx │ │ │ ├── label.tsx │ │ │ └── table.tsx │ │ ├── components.json │ │ ├── lib/ │ │ │ └── utils.ts │ │ ├── next.config.ts │ │ ├── package.json │ │ ├── postcss.config.mjs │ │ ├── tailwind.config.js │ │ ├── tailwind.config.ts │ │ └── tsconfig.json │ ├── README.md │ ├── contracts/ │ │ ├── MultiSig.sol │ │ ├── MultiSigFactory.sol │ │ └── interfaces/ │ │ └── IMultiSig.sol │ ├── hardhat.config.js │ ├── ignition/ │ │ └── modules/ │ │ └── Lock.js │ ├── package.json │ ├── scripts/ │ │ └── deploy-multisig.js │ └── test/ │ └── Lock.js ├── 13-Core-Test-Token-Faucet/ │ ├── .gitignore │ ├── Frontend/ │ │ ├── .eslintrc.json │ │ ├── .gitignore │ │ ├── README.md │ │ ├── app/ │ │ │ ├── globals.css │ │ │ ├── layout.tsx │ │ │ └── page.tsx │ │ ├── components/ │ │ │ ├── badge.tsx │ │ │ ├── dialog.tsx │ │ │ ├── dropdown-menu.tsx │ │ │ ├── navbar.tsx │ │ │ ├── network-modal.tsx │ │ │ ├── select.tsx │ │ │ ├── toast.tsx │ │ │ ├── toaster.tsx │ │ │ ├── token-selector.tsx │ │ │ └── ui/ │ │ │ ├── badge.tsx │ │ │ ├── button.tsx │ │ │ ├── card.tsx │ │ │ ├── dialog.tsx │ │ │ ├── dropdown-menu.tsx │ │ │ ├── input.tsx │ │ │ ├── select.tsx │ │ │ ├── toast.tsx │ │ │ └── toaster.tsx │ │ ├── components.json │ │ ├── hooks/ │ │ │ └── use-toast.ts │ │ ├── lib/ │ │ │ ├── constants.ts │ │ │ ├── tokens.ts │ │ │ └── utils.ts │ │ ├── next.config.js │ │ ├── next.config.mjs │ │ ├── package.json │ │ ├── postcss.config.js │ │ ├── postcss.config.mjs │ │ ├── tailwind.config.ts │ │ └── tsconfig.json │ ├── README.md │ ├── contracts/ │ │ ├── tDai.sol │ │ ├── tUSD.sol │ │ └── tUSDC.sol │ ├── hardhat.config.js │ ├── ignition/ │ │ └── modules/ │ │ └── Lock.js │ ├── package.json │ ├── scripts/ │ │ └── deploy.js │ └── test/ │ └── Lock.js ├── 14-Corelend/ │ ├── .gitignore │ ├── Frontend/ │ │ ├── .eslintrc.json │ │ ├── .gitignore │ │ ├── README.md │ │ ├── app/ │ │ │ ├── borrow/ │ │ │ │ └── page.tsx │ │ │ ├── constants/ │ │ │ │ └── constants.tsx │ │ │ ├── globals.css │ │ │ ├── layout.tsx │ │ │ ├── lend/ │ │ │ │ └── page.tsx │ │ │ ├── loans/ │ │ │ │ ├── page.tsx │ │ │ │ ├── store.tsx │ │ │ │ └── test.tsx │ │ │ └── page.tsx │ │ ├── components/ │ │ │ ├── navbar.tsx │ │ │ ├── ui/ │ │ │ │ ├── badge.tsx │ │ │ │ ├── button.tsx │ │ │ │ ├── card.tsx │ │ │ │ ├── input.tsx │ │ │ │ ├── select.tsx │ │ │ │ ├── table.tsx │ │ │ │ ├── toast.tsx │ │ │ │ └── toaster.tsx │ │ │ └── wallet-provider.tsx │ │ ├── components.json │ │ ├── hooks/ │ │ │ └── use-toast.ts │ │ ├── lib/ │ │ │ └── utils.ts │ │ ├── next.config.ts │ │ ├── package.json │ │ ├── postcss.config.mjs │ │ ├── tailwind.config.ts │ │ └── tsconfig.json │ ├── README.md │ ├── contracts/ │ │ └── CoreLend.sol │ ├── hardhat.config.js │ ├── ignition/ │ │ └── modules/ │ │ └── Lock.js │ ├── package.json │ ├── scripts/ │ │ └── deploy.js │ └── test/ │ └── Lock.js ├── 15-dns-protocol/ │ ├── .gitignore │ ├── Frontend/ │ │ ├── .eslintrc.json │ │ ├── .gitignore │ │ ├── README.md │ │ ├── app/ │ │ │ ├── dashboard/ │ │ │ │ └── page.tsx │ │ │ ├── globals.css │ │ │ ├── layout.tsx │ │ │ ├── page.tsx │ │ │ └── registry/ │ │ │ ├── loading.tsx │ │ │ └── page.tsx │ │ ├── components/ │ │ │ ├── alert.tsx │ │ │ ├── domain-card.tsx │ │ │ ├── domain-details.tsx │ │ │ ├── domain-search.tsx │ │ │ ├── header.tsx │ │ │ ├── mode-toggle.tsx │ │ │ ├── network-switcher.tsx │ │ │ ├── theme-provider.tsx │ │ │ ├── tooltip.tsx │ │ │ ├── ui/ │ │ │ │ ├── alert.tsx │ │ │ │ ├── badge.tsx │ │ │ │ ├── button.tsx │ │ │ │ ├── card.tsx │ │ │ │ ├── dialog.tsx │ │ │ │ ├── dropdown-menu.tsx │ │ │ │ ├── input.tsx │ │ │ │ └── skeleton.tsx │ │ │ └── wallet-provider.tsx │ │ ├── components.json │ │ ├── constants/ │ │ │ └── config.json │ │ ├── hooks/ │ │ │ └── use-wallet.tsx │ │ ├── lib/ │ │ │ ├── core-contract.ts │ │ │ └── utils.ts │ │ ├── next.config.js │ │ ├── package.json │ │ ├── postcss.config.mjs │ │ ├── tailwind.config.ts │ │ ├── tsconfig.json │ │ └── types/ │ │ └── global.d.ts │ ├── README.md │ ├── contracts/ │ │ ├── ENS-Registry.sol │ │ ├── RegistrationContract.sol │ │ └── ResolverContract.sol │ ├── hardhat.config.js │ ├── ignition/ │ │ └── modules/ │ │ └── Lock.js │ ├── package.json │ ├── scripts/ │ │ └── deploy.js │ └── test/ │ └── Lock.js ├── 16-Pump.Core/ │ ├── .gitignore │ ├── Frontend/ │ │ ├── .eslintrc.json │ │ ├── .gitignore │ │ ├── README.md │ │ ├── app/ │ │ │ ├── dashboard/ │ │ │ │ └── page.tsx │ │ │ ├── globals.css │ │ │ ├── layout.tsx │ │ │ ├── page.tsx │ │ │ └── scss/ │ │ │ ├── _layout.scss │ │ │ ├── _mixins.scss │ │ │ ├── _reset.scss │ │ │ ├── _typography.scss │ │ │ ├── _utilities.scss │ │ │ ├── _variables.scss │ │ │ ├── components/ │ │ │ │ ├── _badges.scss │ │ │ │ ├── _buttons.scss │ │ │ │ ├── _cards.scss │ │ │ │ ├── _dialogs.scss │ │ │ │ ├── _dropdown.scss │ │ │ │ ├── _forms.scss │ │ │ │ ├── _launch-dialog.scss │ │ │ │ ├── _navbar.scss │ │ │ │ ├── _progress.scss │ │ │ │ ├── _toast.scss │ │ │ │ └── _token-listing.scss │ │ │ └── main.scss │ │ ├── components/ │ │ │ ├── buy-token-dialog.tsx │ │ │ ├── connect-wallet.tsx │ │ │ ├── creator-dashboard.tsx │ │ │ ├── dialog.tsx │ │ │ ├── launch-token-button.tsx │ │ │ ├── launch-token-dialog.tsx │ │ │ ├── navbar.tsx │ │ │ ├── network-switcher.tsx │ │ │ ├── owner-dashboard.tsx │ │ │ ├── token-listing.tsx │ │ │ └── ui/ │ │ │ ├── badge.tsx │ │ │ ├── button.tsx │ │ │ ├── card.tsx │ │ │ ├── dialog.tsx │ │ │ ├── dropdown-menu.tsx │ │ │ ├── input.tsx │ │ │ ├── label.tsx │ │ │ ├── progress.tsx │ │ │ ├── sheet.tsx │ │ │ ├── slider.tsx │ │ │ ├── tabs.tsx │ │ │ ├── toast.tsx │ │ │ └── toaster.tsx │ │ ├── components.json │ │ ├── constants/ │ │ │ └── constansts.tsx │ │ ├── hooks/ │ │ │ ├── use-toast.ts │ │ │ └── use-web3.tsx │ │ ├── lib/ │ │ │ └── utils.ts │ │ ├── next.config.ts │ │ ├── package.json │ │ ├── postcss.config.mjs │ │ ├── providers/ │ │ │ └── web3-provider.tsx │ │ ├── tailwind.config.ts │ │ ├── tsconfig.json │ │ └── types/ │ │ └── global.d.ts │ ├── README.md │ ├── contracts/ │ │ ├── MemeFactory.sol │ │ └── MemeToken.sol │ ├── hardhat.config.js │ ├── ignition/ │ │ └── modules/ │ │ └── Lock.js │ ├── package.json │ ├── scripts/ │ │ └── deploy.js │ └── test/ │ └── Lock.js ├── 17-Crowd-Funding-Dapp/ │ ├── Contract/ │ │ ├── .gitignore │ │ ├── README.md │ │ ├── contracts/ │ │ │ ├── CrowdFunding.sol │ │ │ └── CrowdFundingFactory.sol │ │ ├── hardhat.config.js │ │ ├── package.json │ │ └── scripts/ │ │ └── verify/ │ │ └── my-contract.js │ ├── Frontend/ │ │ ├── .gitignore │ │ ├── .prettierrc │ │ ├── .vite/ │ │ │ └── deps_temp_6cf5ba4c/ │ │ │ ├── AllWalletsUI-27PR6NO2.js │ │ │ ├── BuyScreen-N3MCCV33.js │ │ │ ├── CoinbaseSDKConnection-PPK2JHPJ.js │ │ │ ├── EcosystemWalletConnectUI-ANAXYA53.js │ │ │ ├── InAppWalletConnectUI-IYEPIHHJ.js │ │ │ ├── InAppWalletSelectionUI-QJ7CQPJG.js │ │ │ ├── ModelViewer-GZZWO7FG.js │ │ │ ├── QRCodeRenderer-ZNSMXL36.js │ │ │ ├── adapter-F5WOI5K5.js │ │ │ ├── ai-M4CK2DAC.js │ │ │ ├── ai.spotonchain-Q44G73RV.js │ │ │ ├── app-3BIDNXMN.js │ │ │ ├── app-4OQAM2FO.js │ │ │ ├── app-4WB6G67C.js │ │ │ ├── app-5BPIXU3J.js │ │ │ ├── app-5PJX72YN.js │ │ │ ├── app-6X4TWE2O.js │ │ │ ├── app-BJYH6WND.js │ │ │ ├── app-C6AFF7V2.js │ │ │ ├── app-CEHOPHKL.js │ │ │ ├── app-FEBEDQ5O.js │ │ │ ├── app-FXWSJIOW.js │ │ │ ├── app-HGBIYGYJ.js │ │ │ ├── app-HRMMGDE2.js │ │ │ ├── app-IC2A3RDS.js │ │ │ ├── app-ICREXY5T.js │ │ │ ├── app-IEYL7BOV.js │ │ │ ├── app-IVIV25DE.js │ │ │ ├── app-J7XLYP5E.js │ │ │ ├── app-JGIJQHBM.js │ │ │ ├── app-JPKIQZES.js │ │ │ ├── app-KCNXS7XQ.js │ │ │ ├── app-LUGTXPGI.js │ │ │ ├── app-M6LRY2SK.js │ │ │ ├── app-MFHNNKPC.js │ │ │ ├── app-MS6Z5MIK.js │ │ │ ├── app-O5DHUCKC.js │ │ │ ├── app-OXRH4XRW.js │ │ │ ├── app-PUVYKP42.js │ │ │ ├── app-QASKZRBP.js │ │ │ ├── app-R4JLN24B.js │ │ │ ├── app-RQXR7MZ5.js │ │ │ ├── app-RRYWU2T6.js │ │ │ ├── app-SFALV7Q7.js │ │ │ ├── app-VCRSWMVS.js │ │ │ ├── app-XKLTXZZ5.js │ │ │ ├── app-XMYPKI5F.js │ │ │ ├── app-YG5QZHYU.js │ │ │ ├── app-Z3ZKSY2N.js │ │ │ ├── app.core-FOKZSNJL.js │ │ │ ├── app.qubic-45GFYY2N.js │ │ │ ├── arweave-57OCWZ5C.js │ │ │ ├── auth-ZNEFTCXD.js │ │ │ ├── baby-VXQWXU2X.js │ │ │ ├── balanceOf-77XLALLF.js │ │ │ ├── biconomy-PIJEZ3DY.js │ │ │ ├── buyFromListing-NAQIOY7I.js │ │ │ ├── cc-VULA5ISR.js │ │ │ ├── cc-XODV5KUP.js │ │ │ ├── cc.localtrade-QLM7DIOM.js │ │ │ ├── ccip-BECV2KBX.js │ │ │ ├── ch-DJKOH7L6.js │ │ │ ├── checkContractWalletSignature-6DFUQS7E.js │ │ │ ├── checkContractWalletSignedTypedData-SEVCYJA7.js │ │ │ ├── chunk-253DMNI3.js │ │ │ ├── chunk-2HYPHUAF.js │ │ │ ├── chunk-2MTJELC7.js │ │ │ ├── chunk-2RRVHQYX.js │ │ │ ├── chunk-35YKZJSE.js │ │ │ ├── chunk-36FW3ZLE.js │ │ │ ├── chunk-3DBHE3NE.js │ │ │ ├── chunk-3GSJ2FQJ.js │ │ │ ├── chunk-3ZOYRTTJ.js │ │ │ ├── chunk-4BCIASJM.js │ │ │ ├── chunk-4OCU6WGG.js │ │ │ ├── chunk-4PEUWIWY.js │ │ │ ├── chunk-4RRAU5V7.js │ │ │ ├── chunk-4U2YWK76.js │ │ │ ├── chunk-5CO5G7XZ.js │ │ │ ├── chunk-5EFACFVF.js │ │ │ ├── chunk-5THTWD2M.js │ │ │ ├── chunk-5U5XBS6S.js │ │ │ ├── chunk-65EUCVOP.js │ │ │ ├── chunk-673YCYST.js │ │ │ ├── chunk-67BSOYLQ.js │ │ │ ├── chunk-6FLJU7W7.js │ │ │ ├── chunk-6LAJV43E.js │ │ │ ├── chunk-6RU56BH7.js │ │ │ ├── chunk-6WNCTW75.js │ │ │ ├── chunk-6XF6HOWC.js │ │ │ ├── chunk-7AY3QZZV.js │ │ │ ├── chunk-7ETS5GH6.js │ │ │ ├── chunk-7EY5MWB2.js │ │ │ ├── chunk-7QDK5KLB.js │ │ │ ├── chunk-7VZHRFCE.js │ │ │ ├── chunk-7ZCK2FX5.js │ │ │ ├── chunk-7ZNEOXS2.js │ │ │ ├── chunk-AARWH2GQ.js │ │ │ ├── chunk-ADIC4TC2.js │ │ │ ├── chunk-AG4NO6K6.js │ │ │ ├── chunk-AWMNEQRO.js │ │ │ ├── chunk-B7XHB4Z2.js │ │ │ ├── chunk-BBNNHC5G.js │ │ │ ├── chunk-BZXRHH4X.js │ │ │ ├── chunk-CLN3QXW2.js │ │ │ ├── chunk-CNLOA7AS.js │ │ │ ├── chunk-CXAZLQ2Z.js │ │ │ ├── chunk-CYVKJMZE.js │ │ │ ├── chunk-DYKFWRMQ.js │ │ │ ├── chunk-EGJT3UEX.js │ │ │ ├── chunk-EHYTL2NA.js │ │ │ ├── chunk-EIBOABXT.js │ │ │ ├── chunk-EIVAOYE5.js │ │ │ ├── chunk-F2BEZVSV.js │ │ │ ├── chunk-FHZU65JA.js │ │ │ ├── chunk-FNI7M3UI.js │ │ │ ├── chunk-FXBAO7K3.js │ │ │ ├── chunk-G26WKBGM.js │ │ │ ├── chunk-GGVPULQZ.js │ │ │ ├── chunk-GHAZ34ED.js │ │ │ ├── chunk-GINVHONX.js │ │ │ ├── chunk-GOA7IGSB.js │ │ │ ├── chunk-HI6IFF64.js │ │ │ ├── chunk-HJ6E36KT.js │ │ │ ├── chunk-HL2TAEA2.js │ │ │ ├── chunk-HO57TQQM.js │ │ │ ├── chunk-I2GEMA2B.js │ │ │ ├── chunk-I5DK3TWY.js │ │ │ ├── chunk-IMSXM5CF.js │ │ │ ├── chunk-J7FYPWA5.js │ │ │ ├── chunk-JBQP4JIV.js │ │ │ ├── chunk-JTR2PIFP.js │ │ │ ├── chunk-JZC47WAY.js │ │ │ ├── chunk-KWA5PGSC.js │ │ │ ├── chunk-LO5SQBMX.js │ │ │ ├── chunk-M3WBOOWW.js │ │ │ ├── chunk-ME5GAE4N.js │ │ │ ├── chunk-MGEBXLXC.js │ │ │ ├── chunk-MWAIX6LF.js │ │ │ ├── chunk-N24CESYN.js │ │ │ ├── chunk-NJUWOGZE.js │ │ │ ├── chunk-NKFQ2LZT.js │ │ │ ├── chunk-NOA36MVL.js │ │ │ ├── chunk-NPJBMLFY.js │ │ │ ├── chunk-NPXNISXJ.js │ │ │ ├── chunk-O6KA6WKL.js │ │ │ ├── chunk-O6LGEXJ4.js │ │ │ ├── chunk-O6UZ65WN.js │ │ │ ├── chunk-O7UPLLUM.js │ │ │ ├── chunk-OHYFITXC.js │ │ │ ├── chunk-P7ZDTV2E.js │ │ │ ├── chunk-PB7CMXGP.js │ │ │ ├── chunk-PHVX3XOV.js │ │ │ ├── chunk-PK5NRJAC.js │ │ │ ├── chunk-PWFRCBEK.js │ │ │ ├── chunk-Q3TN3POE.js │ │ │ ├── chunk-QC3K2OKT.js │ │ │ ├── chunk-QHKZ43P6.js │ │ │ ├── chunk-QIUEWTOP.js │ │ │ ├── chunk-QLCPWJYR.js │ │ │ ├── chunk-QLJVAXYD.js │ │ │ ├── chunk-QVNJVROL.js │ │ │ ├── chunk-R554PO5S.js │ │ │ ├── chunk-R76ND7QY.js │ │ │ ├── chunk-RC344ZND.js │ │ │ ├── chunk-RF65TSG5.js │ │ │ ├── chunk-S4ZGHGPT.js │ │ │ ├── chunk-S6VQW2VI.js │ │ │ ├── chunk-SEVZ5PBP.js │ │ │ ├── chunk-SJKAB62J.js │ │ │ ├── chunk-SNQ54XRM.js │ │ │ ├── chunk-SPELR2RL.js │ │ │ ├── chunk-SWMZXE3E.js │ │ │ ├── chunk-TFBEDS4S.js │ │ │ ├── chunk-TTOANXGP.js │ │ │ ├── chunk-U3QNWT4A.js │ │ │ ├── chunk-U55JVTZU.js │ │ │ ├── chunk-U7TO6S3N.js │ │ │ ├── chunk-UY2SRO54.js │ │ │ ├── chunk-UZVZQZEM.js │ │ │ ├── chunk-VIBS7Y3M.js │ │ │ ├── chunk-VJFQPB47.js │ │ │ ├── chunk-VJOHABJ4.js │ │ │ ├── chunk-VUXPTMXZ.js │ │ │ ├── chunk-XB34LHR5.js │ │ │ ├── chunk-XC5J5ANL.js │ │ │ ├── chunk-XTOEMUZK.js │ │ │ ├── chunk-Y3WKETHV.js │ │ │ ├── chunk-YG7T4W43.js │ │ │ ├── chunk-YGRUPXVB.js │ │ │ ├── chunk-YPFLLHK6.js │ │ │ ├── chunk-YXQ5KEQC.js │ │ │ ├── chunk-ZDZJSHMF.js │ │ │ ├── chunk-ZLJ6VYSG.js │ │ │ ├── chunk-ZNEQLT5Q.js │ │ │ ├── claimCondition-FZ3EKW2M.js │ │ │ ├── claimCondition-WJYCFSKY.js │ │ │ ├── claimTo-3OGSZAGD.js │ │ │ ├── claimTo-7N7PJK5O.js │ │ │ ├── claimTo-LNJZHHT3.js │ │ │ ├── co-2W272KST.js │ │ │ ├── co-4KSSMBL6.js │ │ │ ├── co-4QEGB6VV.js │ │ │ ├── co-7LLLWALO.js │ │ │ ├── co-A2VHPEPT.js │ │ │ ├── co-CVN2M45H.js │ │ │ ├── co-Y7ICLZEM.js │ │ │ ├── co.cyber-W3ZB2PHU.js │ │ │ ├── coinbaseWebSDK-RVHYUQN6.js │ │ │ ├── com-2C4IBZJC.js │ │ │ ├── com-2FMSNEYI.js │ │ │ ├── com-2M7N6F5U.js │ │ │ ├── com-3M4YXHEP.js │ │ │ ├── com-4GPSLLOX.js │ │ │ ├── com-4MAE4SLL.js │ │ │ ├── com-5EVQS4IZ.js │ │ │ ├── com-5NZOMD6O.js │ │ │ ├── com-66Q6X2AN.js │ │ │ ├── com-6DTOF6TL.js │ │ │ ├── com-6OK3IP35.js │ │ │ ├── com-6OLGJVDZ.js │ │ │ ├── com-6SKA46QA.js │ │ │ ├── com-77L55XPO.js │ │ │ ├── com-7CFZD43L.js │ │ │ ├── com-7ESFL2XC.js │ │ │ ├── com-7FNIVOH3.js │ │ │ ├── com-7Y4S6AXS.js │ │ │ ├── com-7ZICZNFF.js │ │ │ ├── com-ABZNTRLZ.js │ │ │ ├── com-AKMGTE6O.js │ │ │ ├── com-AODZYQWL.js │ │ │ ├── com-BA67M6JA.js │ │ │ ├── com-BJY3WLWU.js │ │ │ ├── com-BLXPUI47.js │ │ │ ├── com-CADNHKSZ.js │ │ │ ├── com-CAZP4XAV.js │ │ │ ├── com-CHX2N46L.js │ │ │ ├── com-CMFYLJ3T.js │ │ │ ├── com-D37EIKB4.js │ │ │ ├── com-DJRJPGME.js │ │ │ ├── com-DMBFR3TM.js │ │ │ ├── com-DXBW5XU7.js │ │ │ ├── com-EC74KZVH.js │ │ │ ├── com-ECD626HL.js │ │ │ ├── com-EDWOBHQ5.js │ │ │ ├── com-EW5K7JF2.js │ │ │ ├── com-FE3NAAEW.js │ │ │ ├── com-FIMPM75U.js │ │ │ ├── com-FLBLVTBY.js │ │ │ ├── com-FTU5JU6L.js │ │ │ ├── com-FUBWL26I.js │ │ │ ├── com-G4PABABE.js │ │ │ ├── com-GGEHZ3ML.js │ │ │ ├── com-GHGCPYMS.js │ │ │ ├── com-GPM5NTEM.js │ │ │ ├── com-GY4RR463.js │ │ │ ├── com-HIQMW3M5.js │ │ │ ├── com-HQ3ZNBVK.js │ │ │ ├── com-HUVDUN75.js │ │ │ ├── com-I4GOOXU3.js │ │ │ ├── com-IATVSYRF.js │ │ │ ├── com-ICJNKASS.js │ │ │ ├── com-IDR25SRZ.js │ │ │ ├── com-IF7AHQFJ.js │ │ │ ├── com-IF7EFBYY.js │ │ │ ├── com-IQ3TTO6K.js │ │ │ ├── com-IVJ4ODXS.js │ │ │ ├── com-JCVLXBH6.js │ │ │ ├── com-KFSYP3UK.js │ │ │ ├── com-KPWIFBRV.js │ │ │ ├── com-KW7LIQVX.js │ │ │ ├── com-KWK64UB7.js │ │ │ ├── com-L5FHGFHX.js │ │ │ ├── com-LFG2VXGV.js │ │ │ ├── com-M5EROV3A.js │ │ │ ├── com-MIWCOGLD.js │ │ │ ├── com-MPMYNQIR.js │ │ │ ├── com-MT3HKQ3R.js │ │ │ ├── com-NFP3O76O.js │ │ │ ├── com-NSXJ3MYN.js │ │ │ ├── com-O32AFMCX.js │ │ │ ├── com-O7HEL5UM.js │ │ │ ├── com-OKQHPEYA.js │ │ │ ├── com-OLXXEOCB.js │ │ │ ├── com-P73TZQWI.js │ │ │ ├── com-PK4DXA46.js │ │ │ ├── com-Q4R5QXMD.js │ │ │ ├── com-Q7LI3IVT.js │ │ │ ├── com-QNHV5LXE.js │ │ │ ├── com-QQPVG7PP.js │ │ │ ├── com-QUF6BW3N.js │ │ │ ├── com-RCO2EJCO.js │ │ │ ├── com-RVMYGOTN.js │ │ │ ├── com-SD7QZXVI.js │ │ │ ├── com-SGLYOLT6.js │ │ │ ├── com-SGOLCA56.js │ │ │ ├── com-SH3JOPDV.js │ │ │ ├── com-SKB3SMG6.js │ │ │ ├── com-SMDDEG7M.js │ │ │ ├── com-SPRTZXVD.js │ │ │ ├── com-TDMJBI2M.js │ │ │ ├── com-TE3IRJVG.js │ │ │ ├── com-TH3B64WW.js │ │ │ ├── com-TV4K6JFU.js │ │ │ ├── com-UGZ7W7CO.js │ │ │ ├── com-UJZJA6SZ.js │ │ │ ├── com-URZWZY6W.js │ │ │ ├── com-USI3H3ZY.js │ │ │ ├── com-UUE4VT6F.js │ │ │ ├── com-UWJR5TCW.js │ │ │ ├── com-UYAKF2N2.js │ │ │ ├── com-V5JX4VHE.js │ │ │ ├── com-VCBNOXWU.js │ │ │ ├── com-VMFG63WD.js │ │ │ ├── com-VV2KAHH7.js │ │ │ ├── com-WWOKZBON.js │ │ │ ├── com-X7JZBOMI.js │ │ │ ├── com-XBDXJT7H.js │ │ │ ├── com-XCMJDOF3.js │ │ │ ├── com-XIFKBSI7.js │ │ │ ├── com-XUD7P7EW.js │ │ │ ├── com-YMKJ5J5V.js │ │ │ ├── com-Z7KH6LCA.js │ │ │ ├── com-ZCJBLCGU.js │ │ │ ├── com-ZFAFSEQR.js │ │ │ ├── com-ZL3AON34.js │ │ │ ├── com-ZRV5E3J2.js │ │ │ ├── com-ZU576A7T.js │ │ │ ├── com-ZXAV47A3.js │ │ │ ├── com.bitget-2APLDUWF.js │ │ │ ├── com.blanqlabs-SYJXQAS6.js │ │ │ ├── com.blazpay-G2RYDJ7L.js │ │ │ ├── com.brave-D3ZUHE7V.js │ │ │ ├── com.coinbase-XCXEA6KF.js │ │ │ ├── com.coolbitx-54F2B4QS.js │ │ │ ├── com.crypto-53A63ZCL.js │ │ │ ├── com.elrond.maiar-CPDDYEOU.js │ │ │ ├── com.fastex-OSMD2QUY.js │ │ │ ├── com.feralfile-6FVJKEDQ.js │ │ │ ├── com.hashpack-VBVIF33I.js │ │ │ ├── com.meld-U3J7XNQI.js │ │ │ ├── com.moongate-IFYOW5HA.js │ │ │ ├── com.mpcvault-5RS5XOJS.js │ │ │ ├── com.okex-ASVE2B3U.js │ │ │ ├── com.poolsmobility-MPUANJAV.js │ │ │ ├── com.robinhood-ZVFBQFK2.js │ │ │ ├── com.roninchain-VOI4TK6H.js │ │ │ ├── com.saakuru-3DH4OCRJ.js │ │ │ ├── com.sabay-NHKDAQVI.js │ │ │ ├── com.trustwallet-QTE52ZJ2.js │ │ │ ├── com.walletconnect-QWEQRBQR.js │ │ │ ├── concat-hex-2F4R6DIF.js │ │ │ ├── contract-GEGWMZWS.js │ │ │ ├── controller-W2QS5UC4.js │ │ │ ├── de-BT7LP6QO.js │ │ │ ├── de-IU2DXG5T.js │ │ │ ├── de-OKZ4QL64.js │ │ │ ├── de-WT7ZYIRL.js │ │ │ ├── decimals-OWVEHM45.js │ │ │ ├── dev-CGZJG7WM.js │ │ │ ├── digital-TWPYUQDY.js │ │ │ ├── dist-7FXCYDP5.js │ │ │ ├── dist-JQ3EDHJY.js │ │ │ ├── dist-UZFCJX5W.js │ │ │ ├── download-F3MJUB7B.js │ │ │ ├── embedded-5JDH6LO6.js │ │ │ ├── en-BRYFEMZN.js │ │ │ ├── en-GF35UFXC.js │ │ │ ├── en-SB77EPNW.js │ │ │ ├── en-YMFAQ6ZL.js │ │ │ ├── encode-4DQKNRWC.js │ │ │ ├── encodeAbiParameters-UF4TQP7R.js │ │ │ ├── engine-L3LTYQXR.js │ │ │ ├── es-7RULN4RE.js │ │ │ ├── es-LKAELXTV.js │ │ │ ├── es-RWVLHLPZ.js │ │ │ ├── es-UEK7RLXG.js │ │ │ ├── estimate-l1-fee-B2LECVR2.js │ │ │ ├── eth_estimateGas-FTRTBPEZ.js │ │ │ ├── eth_getTransactionCount-ITCGR7E4.js │ │ │ ├── extractIPFS-GFMPIVLN.js │ │ │ ├── fetch-proofs-for-claimers-NQNU6O2D.js │ │ │ ├── fi-AVCNJCZU.js │ │ │ ├── fi-MH46U2IW.js │ │ │ ├── finance-43KN2CYS.js │ │ │ ├── finance-B7FMBRBP.js │ │ │ ├── finance-BPBXKFLP.js │ │ │ ├── finance-GAXWYNOQ.js │ │ │ ├── finance-ROSDRD4N.js │ │ │ ├── finance-TUEUOJYQ.js │ │ │ ├── finance-XE4OWK2N.js │ │ │ ├── finance.soulswap-JBPBKOGF.js │ │ │ ├── fr-2PO34MSK.js │ │ │ ├── fr-DKOBC2XB.js │ │ │ ├── fr-HCZLKSNB.js │ │ │ ├── fr-HZ64NS6B.js │ │ │ ├── fun-LYGVTTTP.js │ │ │ ├── get-ecosystem-wallet-info-HRASHZ5U.js │ │ │ ├── getActiveClaimCondition-235FYDU5.js │ │ │ ├── getActiveClaimCondition-5NTTTBA4.js │ │ │ ├── getActiveClaimCondition-X4R3SWY5.js │ │ │ ├── getApprovalForTransaction-RG2PM2ZX.js │ │ │ ├── getApproved-UMVYKWJJ.js │ │ │ ├── getBalance-X6K77NBX.js │ │ │ ├── getContractMetadata-X5DE2MGS.js │ │ │ ├── getCurrencyMetadata-VXZEATQ4.js │ │ │ ├── getInstalledModules-WVGJ43EF.js │ │ │ ├── getNFT-CWYYXL36.js │ │ │ ├── getNFT-T7TVIXIV.js │ │ │ ├── gg-7LOCEDJU.js │ │ │ ├── global-ASRTB772.js │ │ │ ├── group.com.flowfoundation-Y5NGFX4Q.js │ │ │ ├── hashMessage-NHJEFPJB.js │ │ │ ├── id-JCDDJMLP.js │ │ │ ├── id-UVORZUHE.js │ │ │ ├── id.co-KFRG5HP3.js │ │ │ ├── im-ALROWXFB.js │ │ │ ├── image-22XCL4QC.js │ │ │ ├── image-24U2WBYW.js │ │ │ ├── image-25FYMXPP.js │ │ │ ├── image-2C6TWMD7.js │ │ │ ├── image-2DLIROHM.js │ │ │ ├── image-2DVLCOT5.js │ │ │ ├── image-2MC3OA63.js │ │ │ ├── image-2NWF3JOZ.js │ │ │ ├── image-2O2NSLAV.js │ │ │ ├── image-2P2TSVGP.js │ │ │ ├── image-2TID5QYA.js │ │ │ ├── image-2VBH6P4I.js │ │ │ ├── image-2XQ227AO.js │ │ │ ├── image-3BBR6ZUL.js │ │ │ ├── image-3BYLTMYN.js │ │ │ ├── image-3J2YWWMT.js │ │ │ ├── image-3NR45HO4.js │ │ │ ├── image-3PHNAY7F.js │ │ │ ├── image-3QRD6CSU.js │ │ │ ├── image-3RZJFPYY.js │ │ │ ├── image-3SSVXVQA.js │ │ │ ├── image-3WCIGCJE.js │ │ │ ├── image-3XPXEUVI.js │ │ │ ├── image-43VCVTQW.js │ │ │ ├── image-45QC47QJ.js │ │ │ ├── image-47XQBRNK.js │ │ │ ├── image-4B3NOTPE.js │ │ │ ├── image-4BA3AXSR.js │ │ │ ├── image-4E3QCNWY.js │ │ │ ├── image-4KSYJONE.js │ │ │ ├── image-4MUDZ5WJ.js │ │ │ ├── image-4NVIL47X.js │ │ │ ├── image-4R5252N7.js │ │ │ ├── image-4TRY3NEW.js │ │ │ ├── image-4UXLJEY6.js │ │ │ ├── image-4XAPYK5Y.js │ │ │ ├── image-4ZXADMKV.js │ │ │ ├── image-52SKIAAZ.js │ │ │ ├── image-53R3T2KM.js │ │ │ ├── image-5B72RBCK.js │ │ │ ├── image-5C7T5MCW.js │ │ │ ├── image-5DMCMTIS.js │ │ │ ├── image-5EEVHG37.js │ │ │ ├── image-5ESOAIQD.js │ │ │ ├── image-5KGJZFSW.js │ │ │ ├── image-5N5BSRVW.js │ │ │ ├── image-5QOWOT7K.js │ │ │ ├── image-5ZJILWQW.js │ │ │ ├── image-63JBKI3J.js │ │ │ ├── image-64EL5CZZ.js │ │ │ ├── image-6GWDZO4B.js │ │ │ ├── image-6HQIDK6K.js │ │ │ ├── image-6MCAWLUJ.js │ │ │ ├── image-6ORYMNNS.js │ │ │ ├── image-6PJHCB7N.js │ │ │ ├── image-6UEQME7W.js │ │ │ ├── image-6V6UQQYW.js │ │ │ ├── image-6VDTM3JY.js │ │ │ ├── image-6VK7QNZB.js │ │ │ ├── image-77YEUPFU.js │ │ │ ├── image-7EORRWO4.js │ │ │ ├── image-7FZSFD63.js │ │ │ ├── image-7KY4GSTR.js │ │ │ ├── image-7O3C362W.js │ │ │ ├── image-7OU6UVPL.js │ │ │ ├── image-7Q42EE45.js │ │ │ ├── image-7SUEPBLK.js │ │ │ ├── image-7TE6IAEE.js │ │ │ ├── image-7TSPO7Y6.js │ │ │ ├── image-7U7UXPGY.js │ │ │ ├── image-7YYGXP6N.js │ │ │ ├── image-7ZYGDOS3.js │ │ │ ├── image-A3KPWLYO.js │ │ │ ├── image-AHWRIMZI.js │ │ │ ├── image-AI7WZWEM.js │ │ │ ├── image-AR3FQDWK.js │ │ │ ├── image-ARHGIDNB.js │ │ │ ├── image-ARYWL2OH.js │ │ │ ├── image-AXBX7NPH.js │ │ │ ├── image-AZATAZUW.js │ │ │ ├── image-B42LGYLK.js │ │ │ ├── image-BAPZ7ZQ5.js │ │ │ ├── image-BAWNJLDB.js │ │ │ ├── image-BAWP6F3E.js │ │ │ ├── image-BERR6HPQ.js │ │ │ ├── image-BFCLTXKV.js │ │ │ ├── image-BG36EIFN.js │ │ │ ├── image-BG7Q7U5Z.js │ │ │ ├── image-BKAIFC5N.js │ │ │ ├── image-BNSPIEBR.js │ │ │ ├── image-BNWDNWZ7.js │ │ │ ├── image-BPJ747KI.js │ │ │ ├── image-BZHOLM24.js │ │ │ ├── image-C3DYJZTD.js │ │ │ ├── image-CFMPEXUH.js │ │ │ ├── image-CIXW5BVB.js │ │ │ ├── image-CJLAIZ3U.js │ │ │ ├── image-CP6E35DJ.js │ │ │ ├── image-CPWAGIZP.js │ │ │ ├── image-CTC6AICN.js │ │ │ ├── image-CTUNVIGS.js │ │ │ ├── image-CTWYLNEW.js │ │ │ ├── image-CVFAIAQD.js │ │ │ ├── image-CVW43WHN.js │ │ │ ├── image-CWA3VVUM.js │ │ │ ├── image-CX4RMA4S.js │ │ │ ├── image-CZEVKSDD.js │ │ │ ├── image-D2BFLLX6.js │ │ │ ├── image-D3PKEAGG.js │ │ │ ├── image-D5ZHP4L6.js │ │ │ ├── image-D6HXSW23.js │ │ │ ├── image-DFLQ2XFN.js │ │ │ ├── image-DGAWLDDT.js │ │ │ ├── image-DJJHB4NK.js │ │ │ ├── image-DQRQW2SI.js │ │ │ ├── image-DX3LHC5E.js │ │ │ ├── image-DXG4ARNI.js │ │ │ ├── image-DZDKYDL2.js │ │ │ ├── image-EA2TAA73.js │ │ │ ├── image-EA6HZGAP.js │ │ │ ├── image-EHTA7ND2.js │ │ │ ├── image-EIETVCAX.js │ │ │ ├── image-ENIPULMK.js │ │ │ ├── image-EQG2WO73.js │ │ │ ├── image-EWL7XSZS.js │ │ │ ├── image-EZTUCZIK.js │ │ │ ├── image-F3W3U35F.js │ │ │ ├── image-FAAEH6VN.js │ │ │ ├── image-FAMMBKWU.js │ │ │ ├── image-FC2BPU25.js │ │ │ ├── image-FFW5ALAV.js │ │ │ ├── image-FIGWZRNB.js │ │ │ ├── image-FK2QQOEC.js │ │ │ ├── image-FL2436IW.js │ │ │ ├── image-FNGTNT45.js │ │ │ ├── image-FT5E5S2S.js │ │ │ ├── image-FUZODB6Q.js │ │ │ ├── image-FX3DIZMC.js │ │ │ ├── image-FY6NEZXX.js │ │ │ ├── image-G3UZPUMP.js │ │ │ ├── image-G4OOMJFL.js │ │ │ ├── image-G4VVMDLA.js │ │ │ ├── image-G566PLZR.js │ │ │ ├── image-G77AOOTY.js │ │ │ ├── image-GK45NHUD.js │ │ │ ├── image-GN5KL5XH.js │ │ │ ├── image-GNG4HAZI.js │ │ │ ├── image-GRZ6ITK5.js │ │ │ ├── image-GSMGI7VJ.js │ │ │ ├── image-GSTKM7MD.js │ │ │ ├── image-GTS26XGE.js │ │ │ ├── image-GXMDZVE7.js │ │ │ ├── image-H66KD67W.js │ │ │ ├── image-HN4UT2MP.js │ │ │ ├── image-HNJVUIHP.js │ │ │ ├── image-HOZVYDVK.js │ │ │ ├── image-HRDDJY2V.js │ │ │ ├── image-HTVYZ4M3.js │ │ │ ├── image-HVHSAD3I.js │ │ │ ├── image-HXAPNAO4.js │ │ │ ├── image-I2EVY3PN.js │ │ │ ├── image-I2F4TK64.js │ │ │ ├── image-I63OXZPK.js │ │ │ ├── image-IEQIMBFO.js │ │ │ ├── image-IFJOAVNI.js │ │ │ ├── image-IGUKS27J.js │ │ │ ├── image-IK4KYWSE.js │ │ │ ├── image-IKZ2FUDX.js │ │ │ ├── image-IO2WKRLV.js │ │ │ ├── image-IW5JZSWC.js │ │ │ ├── image-IXHLX5GF.js │ │ │ ├── image-J26M6VNU.js │ │ │ ├── image-J3BDNCMB.js │ │ │ ├── image-J3VWG5MZ.js │ │ │ ├── image-J5PWF63O.js │ │ │ ├── image-J6OTD3HY.js │ │ │ ├── image-J72YUI7L.js │ │ │ ├── image-JBLGJN6S.js │ │ │ ├── image-JCM4SCK7.js │ │ │ ├── image-JCMNNBDZ.js │ │ │ ├── image-JGVAVBEO.js │ │ │ ├── image-JIBY7LRH.js │ │ │ ├── image-JRV26T7R.js │ │ │ ├── image-JVTGPVY4.js │ │ │ ├── image-JVUHELHQ.js │ │ │ ├── image-K423YJHO.js │ │ │ ├── image-K675SLCQ.js │ │ │ ├── image-KAKKP25H.js │ │ │ ├── image-KBI4EQQC.js │ │ │ ├── image-KDIH7RV7.js │ │ │ ├── image-KERZY3VS.js │ │ │ ├── image-KFBVQYIK.js │ │ │ ├── image-KFCJWUYA.js │ │ │ ├── image-KHNJTNG5.js │ │ │ ├── image-KI6G2NXA.js │ │ │ ├── image-KLR4DGUS.js │ │ │ ├── image-KMUGR2JC.js │ │ │ ├── image-KNB5HTQS.js │ │ │ ├── image-KRKMGIRW.js │ │ │ ├── image-KTCD3ACC.js │ │ │ ├── image-KVUL54ZL.js │ │ │ ├── image-KWDZM3JO.js │ │ │ ├── image-KXOZP327.js │ │ │ ├── image-KYZRZXTL.js │ │ │ ├── image-L64YUXOP.js │ │ │ ├── image-L7CIHOLP.js │ │ │ ├── image-L7F3ZTNT.js │ │ │ ├── image-L7XMXCCE.js │ │ │ ├── image-LDYJOQU6.js │ │ │ ├── image-LH6FUJDR.js │ │ │ ├── image-LIVCGAOB.js │ │ │ ├── image-LLODPB4V.js │ │ │ ├── image-LOHR2RIE.js │ │ │ ├── image-LPCCHEBL.js │ │ │ ├── image-LPMTTLXQ.js │ │ │ ├── image-LRZBNW6B.js │ │ │ ├── image-LVVWGSGE.js │ │ │ ├── image-LY3RZ44R.js │ │ │ ├── image-LZY7JTRH.js │ │ │ ├── image-M3IUK3S6.js │ │ │ ├── image-M4Z3YR4Z.js │ │ │ ├── image-MBAEXQG7.js │ │ │ ├── image-MBFXNJFS.js │ │ │ ├── image-MDU42EYU.js │ │ │ ├── image-MJ7T6PNW.js │ │ │ ├── image-MJJT532J.js │ │ │ ├── image-MO47H6ZA.js │ │ │ ├── image-MOU2RL63.js │ │ │ ├── image-MRBGWX2E.js │ │ │ ├── image-MTJY6UAP.js │ │ │ ├── image-MUVOHF4W.js │ │ │ ├── image-MYNVEIRO.js │ │ │ ├── image-N53KCP2W.js │ │ │ ├── image-NAO2HSQA.js │ │ │ ├── image-NBHYUHD2.js │ │ │ ├── image-NBPCTXNN.js │ │ │ ├── image-NDYGNMMC.js │ │ │ ├── image-NEI5WDWA.js │ │ │ ├── image-NFV4FTVS.js │ │ │ ├── image-NG66JYBW.js │ │ │ ├── image-NG6MRBT7.js │ │ │ ├── image-NJXZFZEG.js │ │ │ ├── image-NOPIDNPE.js │ │ │ ├── image-O3FWYAMJ.js │ │ │ ├── image-O63UCCVG.js │ │ │ ├── image-OAPLK3NK.js │ │ │ ├── image-OCLQH6ET.js │ │ │ ├── image-ODMYDNAD.js │ │ │ ├── image-OGVGI6IX.js │ │ │ ├── image-OI2FPOZK.js │ │ │ ├── image-OMOLG6BP.js │ │ │ ├── image-OMOWTLJH.js │ │ │ ├── image-OOBSXLNR.js │ │ │ ├── image-ORMFBD3D.js │ │ │ ├── image-OROPDYCP.js │ │ │ ├── image-OS6F5ASF.js │ │ │ ├── image-OX5V2TE5.js │ │ │ ├── image-OYVSS2NW.js │ │ │ ├── image-P3F6JWUP.js │ │ │ ├── image-P5CCQF6U.js │ │ │ ├── image-P7A7UY6Q.js │ │ │ ├── image-PFLIBWNB.js │ │ │ ├── image-PG2LM3EN.js │ │ │ ├── image-PIHQFTZW.js │ │ │ ├── image-PJ56ZJZI.js │ │ │ ├── image-PNENEROM.js │ │ │ ├── image-POSUEFBS.js │ │ │ ├── image-PPYVKDO3.js │ │ │ ├── image-PRRYYAGC.js │ │ │ ├── image-PX7PII22.js │ │ │ ├── image-PXXJ7YGR.js │ │ │ ├── image-PY3RCMKE.js │ │ │ ├── image-PYNIXTYI.js │ │ │ ├── image-Q5EEGXM4.js │ │ │ ├── image-QBQHKWYU.js │ │ │ ├── image-QEGCG76B.js │ │ │ ├── image-QEJ5TH25.js │ │ │ ├── image-QFDO4ERO.js │ │ │ ├── image-QMD3UXYM.js │ │ │ ├── image-QTWRL6IY.js │ │ │ ├── image-QZKB4QH2.js │ │ │ ├── image-R2PA3K44.js │ │ │ ├── image-R3QO5B5O.js │ │ │ ├── image-R5DDRXEO.js │ │ │ ├── image-R5MXAYSI.js │ │ │ ├── image-R65TRIAG.js │ │ │ ├── image-R6MZNPDW.js │ │ │ ├── image-R6ZY7ODL.js │ │ │ ├── image-RBD6CLZB.js │ │ │ ├── image-RCPUSQIA.js │ │ │ ├── image-RCVINJ4L.js │ │ │ ├── image-RJ6X2NMJ.js │ │ │ ├── image-RLLVBJI7.js │ │ │ ├── image-RPHSLWEQ.js │ │ │ ├── image-RUAKVMHJ.js │ │ │ ├── image-SDS6MUPN.js │ │ │ ├── image-SFV565LD.js │ │ │ ├── image-SHZEEMLS.js │ │ │ ├── image-SKFBWVXM.js │ │ │ ├── image-SON77BIL.js │ │ │ ├── image-SPBIVFWA.js │ │ │ ├── image-SQEC6SWZ.js │ │ │ ├── image-SZ53EEZI.js │ │ │ ├── image-SZDGRZKO.js │ │ │ ├── image-T4K2HHHO.js │ │ │ ├── image-T5624ZCD.js │ │ │ ├── image-T7NA4A2Y.js │ │ │ ├── image-TBQHCWRX.js │ │ │ ├── image-TCNXR5Y6.js │ │ │ ├── image-TGDIBLJ5.js │ │ │ ├── image-TJPXCNVF.js │ │ │ ├── image-TLCK7IBC.js │ │ │ ├── image-TLL7ZWDJ.js │ │ │ ├── image-TLQGVZIE.js │ │ │ ├── image-TVOSPHN4.js │ │ │ ├── image-TW36VKLS.js │ │ │ ├── image-U2DNOUXB.js │ │ │ ├── image-U74NACFH.js │ │ │ ├── image-UEMJEQYK.js │ │ │ ├── image-UFGCOQGW.js │ │ │ ├── image-UGV6XSD5.js │ │ │ ├── image-UHZP3BTN.js │ │ │ ├── image-UR6R66GX.js │ │ │ ├── image-UT6D5LIM.js │ │ │ ├── image-UY6RYQ2N.js │ │ │ ├── image-V5HQDG55.js │ │ │ ├── image-V5M6SPNZ.js │ │ │ ├── image-V7OWVN52.js │ │ │ ├── image-VB7IUURT.js │ │ │ ├── image-VF6EIX5D.js │ │ │ ├── image-VKEDKKKR.js │ │ │ ├── image-VLI6ZCKX.js │ │ │ ├── image-VMYFLQHY.js │ │ │ ├── image-VNMGUJNB.js │ │ │ ├── image-VTXLRGUL.js │ │ │ ├── image-VUQ2UL4L.js │ │ │ ├── image-VVOWBOZ5.js │ │ │ ├── image-VW2FN7E5.js │ │ │ ├── image-VYS6PNRX.js │ │ │ ├── image-WAEURFBG.js │ │ │ ├── image-WCQARS7C.js │ │ │ ├── image-WD5JWD6U.js │ │ │ ├── image-WE7PFB2W.js │ │ │ ├── image-WEIHHJID.js │ │ │ ├── image-WFPL2XOD.js │ │ │ ├── image-WFYTTEWO.js │ │ │ ├── image-WGY4E5ZS.js │ │ │ ├── image-WJBIEWRP.js │ │ │ ├── image-WLVFTPS6.js │ │ │ ├── image-WRJBQNVE.js │ │ │ ├── image-WRTS63PY.js │ │ │ ├── image-WXZTVPXW.js │ │ │ ├── image-WZMMOWKO.js │ │ │ ├── image-X6M72D7S.js │ │ │ ├── image-X75OW5JK.js │ │ │ ├── image-XA4X52SC.js │ │ │ ├── image-XD5TFSHC.js │ │ │ ├── image-XFK44ZH7.js │ │ │ ├── image-XIC6EKNY.js │ │ │ ├── image-XIG5YKUC.js │ │ │ ├── image-XLAW77N3.js │ │ │ ├── image-XMKRZUH2.js │ │ │ ├── image-XMXXH2OG.js │ │ │ ├── image-XNCYDJC5.js │ │ │ ├── image-XOUIMWYP.js │ │ │ ├── image-XPJLKRRI.js │ │ │ ├── image-XUGPYK2I.js │ │ │ ├── image-XWTER34E.js │ │ │ ├── image-Y6FK2F2P.js │ │ │ ├── image-YA6DLLJV.js │ │ │ ├── image-YB4GRPL2.js │ │ │ ├── image-YBCZSQ3A.js │ │ │ ├── image-YBPOXOCZ.js │ │ │ ├── image-YBTBDTUR.js │ │ │ ├── image-YCZSZUXE.js │ │ │ ├── image-YFLBT3YJ.js │ │ │ ├── image-YFUELAZQ.js │ │ │ ├── image-YJF46UIP.js │ │ │ ├── image-Z2CATCDR.js │ │ │ ├── image-Z5YWXRKQ.js │ │ │ ├── image-ZEXGTQP2.js │ │ │ ├── image-ZIEWC7ZM.js │ │ │ ├── image-ZNKOF6C2.js │ │ │ ├── image-ZOCXRE6K.js │ │ │ ├── image-ZPU7UHI2.js │ │ │ ├── image-ZTVWJS7Y.js │ │ │ ├── image-ZZDK3IJV.js │ │ │ ├── in-app-core-HIWEYDMM.js │ │ │ ├── in-app-wallet-calls-GQSQW7CK.js │ │ │ ├── in-app-wallet-capabilities-4KBZBWHO.js │ │ │ ├── inApp-RQNC3GM2.js │ │ │ ├── inc-2JDOS23Q.js │ │ │ ├── index.es-AMKWX7QZ.js │ │ │ ├── injected-LISAWEIO.js │ │ │ ├── io-24QRWA4Y.js │ │ │ ├── io-24YA5BRN.js │ │ │ ├── io-2GPQFRQF.js │ │ │ ├── io-2OUEZVZU.js │ │ │ ├── io-2ZBQUD2Z.js │ │ │ ├── io-3FD4NDEY.js │ │ │ ├── io-3SGNGSBU.js │ │ │ ├── io-3U2SLLGY.js │ │ │ ├── io-4K37O2UO.js │ │ │ ├── io-57PCDAYK.js │ │ │ ├── io-5FGKYHDW.js │ │ │ ├── io-6HD3H3FJ.js │ │ │ ├── io-6JQ4CHJH.js │ │ │ ├── io-6LSXSNGH.js │ │ │ ├── io-7F2E4V7R.js │ │ │ ├── io-ANOLLYWK.js │ │ │ ├── io-B43YO5G7.js │ │ │ ├── io-BH2JNQLL.js │ │ │ ├── io-CTRCTP32.js │ │ │ ├── io-CWMDB2MU.js │ │ │ ├── io-D255FR7U.js │ │ │ ├── io-D6Z3AKMH.js │ │ │ ├── io-DIWAXNTD.js │ │ │ ├── io-DK5QUX7W.js │ │ │ ├── io-DNXFQ4K2.js │ │ │ ├── io-DXHXE7IX.js │ │ │ ├── io-E2M2HE5Z.js │ │ │ ├── io-E6S6IBUY.js │ │ │ ├── io-EA2JOUTZ.js │ │ │ ├── io-FVLW4E3K.js │ │ │ ├── io-GQDRISAH.js │ │ │ ├── io-H2C73JK2.js │ │ │ ├── io-H454JI3W.js │ │ │ ├── io-HBM5KOQE.js │ │ │ ├── io-J7ET3CPL.js │ │ │ ├── io-JGARBW27.js │ │ │ ├── io-JWG2DSVL.js │ │ │ ├── io-K5M75KPN.js │ │ │ ├── io-KUZCCGFO.js │ │ │ ├── io-KZJ22VPA.js │ │ │ ├── io-L6UQ2STJ.js │ │ │ ├── io-LVXFK7U5.js │ │ │ ├── io-LX45HK7A.js │ │ │ ├── io-MMDEOZ3N.js │ │ │ ├── io-N5RGMBCH.js │ │ │ ├── io-NH2GD2IR.js │ │ │ ├── io-NVBZJAWM.js │ │ │ ├── io-O7JBQJEM.js │ │ │ ├── io-PJ4YO55N.js │ │ │ ├── io-PV6OW5YR.js │ │ │ ├── io-PVGHQBA3.js │ │ │ ├── io-QLQLOVVJ.js │ │ │ ├── io-RSWIM3NG.js │ │ │ ├── io-RZ7W5PGA.js │ │ │ ├── io-S3TORZWD.js │ │ │ ├── io-T6NWZUPR.js │ │ │ ├── io-TLH32OUQ.js │ │ │ ├── io-TLTTCINM.js │ │ │ ├── io-TRTOW6FM.js │ │ │ ├── io-TRUR62J5.js │ │ │ ├── io-TZCRE2KR.js │ │ │ ├── io-UP4NGDBV.js │ │ │ ├── io-UTHDBEVN.js │ │ │ ├── io-WHYZVMCN.js │ │ │ ├── io-WTWNTQY2.js │ │ │ ├── io-X4AWA27Q.js │ │ │ ├── io-X54FGMH5.js │ │ │ ├── io-XAR6YN2H.js │ │ │ ├── io-XEVP2DVS.js │ │ │ ├── io-XFMVSGBX.js │ │ │ ├── io-XMCECLIZ.js │ │ │ ├── io-XXPRYPG2.js │ │ │ ├── io-YAK5FOPT.js │ │ │ ├── io-YKR37A4G.js │ │ │ ├── io-YSSN6F3W.js │ │ │ ├── io-Z5GSMWWC.js │ │ │ ├── io-ZIBKO2EM.js │ │ │ ├── io.1inch-3Q4NZZ2L.js │ │ │ ├── io.alpha-u.wallet-RANY436R.js │ │ │ ├── io.armana-FQHHA7CM.js │ │ │ ├── io.leapwallet-GH33NGTJ.js │ │ │ ├── io.loopring-BX5AMZUR.js │ │ │ ├── io.magiceden-H3CGBW6M.js │ │ │ ├── io.unagi-YSJDUHMV.js │ │ │ ├── io.uptn-GWS6HTWS.js │ │ │ ├── io.zerion-DKRTCZVY.js │ │ │ ├── is-UU4FXVPC.js │ │ │ ├── is-contract-deployed-AZVYEI5B.js │ │ │ ├── isApprovedForAll-CG3FQCVQ.js │ │ │ ├── isApprovedForAll-JGBKL36G.js │ │ │ ├── it-Y3SJTOXS.js │ │ │ ├── ja-6MH4WP2Z.js │ │ │ ├── ja-HG2757OL.js │ │ │ ├── ja-MCXBRC6G.js │ │ │ ├── ja-PZYAXXAL.js │ │ │ ├── kr-LSVS4UQW.js │ │ │ ├── kr-O56ZYU3R.js │ │ │ ├── kr-QIL3MJCP.js │ │ │ ├── kr-XDCZ7IIG.js │ │ │ ├── land-CKBS6ZRZ.js │ │ │ ├── live-5DC3MAHO.js │ │ │ ├── llc-JHHSY2C6.js │ │ │ ├── me-3MEDDZC5.js │ │ │ ├── me-KVZQT25O.js │ │ │ ├── me-KZ3JFV6V.js │ │ │ ├── me-N5NHUYM7.js │ │ │ ├── me-NGGLTLQU.js │ │ │ ├── me.komet-E7D6F2JB.js │ │ │ ├── mipdStore-HEJSLGN7.js │ │ │ ├── money-5LMST26O.js │ │ │ ├── money-E4VOZHJR.js │ │ │ ├── money-SUJPFHWI.js │ │ │ ├── native-NEGONUYD.js │ │ │ ├── net-4I6DBKNS.js │ │ │ ├── net-KQRWOTI5.js │ │ │ ├── net-Q5SVTUAO.js │ │ │ ├── net-TAG5PSHX.js │ │ │ ├── net-Z743Z374.js │ │ │ ├── net.spatium-EBSLJIM4.js │ │ │ ├── network-3HZ5XME7.js │ │ │ ├── network-64V4ODDY.js │ │ │ ├── network-7CN3ZGB5.js │ │ │ ├── network-FCNDYIML.js │ │ │ ├── network-FHGUIPWM.js │ │ │ ├── network-OTQ66RXU.js │ │ │ ├── network-WFECV2ZU.js │ │ │ ├── nl.greenhood-2VCIICQQ.js │ │ │ ├── one.metapro-JZZTCOTQ.js │ │ │ ├── one.mixin-AYEP2MDG.js │ │ │ ├── online-4UBMQVRH.js │ │ │ ├── openzeppelin-3CQYP2BQ.js │ │ │ ├── org-3WSS4ISS.js │ │ │ ├── org-5JOGDD4T.js │ │ │ ├── org-6JIS4GGD.js │ │ │ ├── org-BHEY6VU5.js │ │ │ ├── org-DASW2CEB.js │ │ │ ├── org-IQR2KWLE.js │ │ │ ├── org-JCLIAWVT.js │ │ │ ├── org-NOFWJHNU.js │ │ │ ├── org-PJ6LCHSF.js │ │ │ ├── org-Q7GOFRGY.js │ │ │ ├── org-RVVOAAYD.js │ │ │ ├── org-U6MXPNQX.js │ │ │ ├── org-XS7DVMFS.js │ │ │ ├── ownerOf-JJ32SN7R.js │ │ │ ├── package.json │ │ │ ├── passkeys-TWQKIUUE.js │ │ │ ├── pk-OX3FADHO.js │ │ │ ├── prepare-transaction-ENVXVTJF.js │ │ │ ├── pro-GX6XLDQ3.js │ │ │ ├── pro-PKIFCXCH.js │ │ │ ├── pro-VKWWWAVU.js │ │ │ ├── pub-BCM6XBN4.js │ │ │ ├── react-dom_client.js │ │ │ ├── react-router-dom.js │ │ │ ├── react.js │ │ │ ├── read-contract-EXVZZYXE.js │ │ │ ├── resolveImplementation-EUNLHKQW.js │ │ │ ├── rpc-TW3OP7F4.js │ │ │ ├── secp256k1-AHVFPDVA.js │ │ │ ├── send-eip712-transaction-GJNL63UQ.js │ │ │ ├── send-gasless-transaction-VPJQYCQ5.js │ │ │ ├── send-transaction-3VCDCFKW.js │ │ │ ├── session-proposal-FKZO7EJB.js │ │ │ ├── session-request-E5B34J42.js │ │ │ ├── setApprovalForAll-WRU2AIHP.js │ │ │ ├── setApprovalForAll-YKTONSHG.js │ │ │ ├── sign-login-payload-EEOP3RDN.js │ │ │ ├── smart-7AYCEGLU.js │ │ │ ├── smart-GOSZ6KLE.js │ │ │ ├── smart-wallet-5WA47S2O.js │ │ │ ├── smart-wallet-capabilities-TZBEJHWD.js │ │ │ ├── so.onekey.app-3NGOLXP4.js │ │ │ ├── social-IGLKXP3O.js │ │ │ ├── social-WQVOUPQP.js │ │ │ ├── supported-sms-countries-MILFNFSC.js │ │ │ ├── switch-chain-UAQT4AB6.js │ │ │ ├── tech-4UEY76KS.js │ │ │ ├── tech-C727ACOE.js │ │ │ ├── tech-NOIENMRJ.js │ │ │ ├── technology-4ON2FUI4.js │ │ │ ├── technology-NIZQELB7.js │ │ │ ├── thirdweb.js │ │ │ ├── thirdweb_react.js │ │ │ ├── tl-AVOH7Y5Z.js │ │ │ ├── tl-B6Y73PTZ.js │ │ │ ├── tl-DDFVDALG.js │ │ │ ├── tl-O6CWFXUB.js │ │ │ ├── trade.flooz-RHPEJ2TY.js │ │ │ ├── units-OLWSIMOC.js │ │ │ ├── upload-U3ZHZXSH.js │ │ │ ├── us-A63RIC6G.js │ │ │ ├── utils-QE6HZ2TS.js │ │ │ ├── utils-RIDKW7H5.js │ │ │ ├── vc.uincubator-4WN5IZUJ.js │ │ │ ├── vi-4HLVRM5V.js │ │ │ ├── vi-6NOSFFF7.js │ │ │ ├── vi-7VOZ2AS3.js │ │ │ ├── vi-JLTPQX3P.js │ │ │ ├── wallet-ZUZOMGPE.js │ │ │ ├── walletConnect-4SOZLMQZ.js │ │ │ ├── web-connector-5CMXT4ED.js │ │ │ ├── web-node-NK4RL5GU.js │ │ │ ├── world-AAINEXQX.js │ │ │ ├── world-IQ7VTL27.js │ │ │ ├── world-ZNOYGYAZ.js │ │ │ ├── world.dosi-Y2A7IFAO.js │ │ │ ├── xyz-3DUFJPG6.js │ │ │ ├── xyz-6TGRCCCS.js │ │ │ ├── xyz-C2SGGGJN.js │ │ │ ├── xyz-H7ZRM2VE.js │ │ │ ├── xyz-JTTBORVS.js │ │ │ ├── xyz-N4RTWSXS.js │ │ │ ├── xyz-P3VWILEP.js │ │ │ ├── xyz-QSKGFGJW.js │ │ │ ├── xyz-WOO5ZF56.js │ │ │ ├── xyz-ZHYDMTP5.js │ │ │ ├── xyz.frontier-GCK2SAXV.js │ │ │ ├── xyz.roam-5PWBMVLT.js │ │ │ ├── xyz.uniultra-YQ7QTAVX.js │ │ │ └── zone-DAJ2TSNU.js │ │ ├── LICENSE.md │ │ ├── index.html │ │ ├── package.json │ │ ├── postcss.config.js │ │ ├── src/ │ │ │ ├── App.tsx │ │ │ ├── Campaign/ │ │ │ │ └── [campainAddress]/ │ │ │ │ └── Page.tsx │ │ │ ├── chains.ts │ │ │ ├── client.ts │ │ │ ├── components/ │ │ │ │ ├── Campaign.tsx │ │ │ │ ├── CampaignDetail.tsx │ │ │ │ ├── CreateCampaign.tsx │ │ │ │ ├── Home.tsx │ │ │ │ ├── Navbar.tsx │ │ │ │ └── TierCard.tsx │ │ │ ├── contants/ │ │ │ │ └── contract.tsx │ │ │ ├── dashboard/ │ │ │ │ └── [walletAddress]/ │ │ │ │ └── page.tsx │ │ │ ├── index.css │ │ │ ├── main.tsx │ │ │ └── vite-env.d.ts │ │ ├── tailwind.config.js │ │ ├── tsconfig.json │ │ ├── tsconfig.node.json │ │ └── vite.config.ts │ └── README.md └── README.md ================================================ FILE CONTENTS ================================================ ================================================ FILE: .gitignore ================================================ node_modules .env secret.json # Hardhat files /cache /artifacts # TypeChain files /typechain /typechain-types # solidity-coverage files /coverage /coverage.json # Hardhat Ignition default folder for deployments against a local node ignition/deployments/chain-31337 ================================================ FILE: 01-Simple Storage Full Stack Dapp/.babelrc ================================================ { "presets": [ "@babel/preset-env", ["@babel/preset-react", { "runtime": "automatic" }], "@babel/preset-typescript" ] } ================================================ FILE: 01-Simple Storage Full Stack Dapp/.editorconfig ================================================ root = true [*] indent_style = spaces indent_size = 2 end_of_line = lf charset = utf-8 trim_trailing_whitespace = true insert_final_newline = true ================================================ FILE: 01-Simple Storage Full Stack Dapp/.eslintrc ================================================ { "env": { "browser": true, "es2020": true, "jest": true, "node": true }, "settings": { "react": { "version": "detect" } }, "extends": [ "eslint:recommended", "plugin:react/recommended", "plugin:@typescript-eslint/eslint-recommended", "plugin:@typescript-eslint/recommended", "plugin:prettier/recommended", "plugin:tailwindcss/recommended" ], "parser": "@typescript-eslint/parser", "parserOptions": { "ecmaFeatures": { "jsx": true }, "ecmaVersion": 11, "sourceType": "module" }, "plugins": ["react", "react-hooks", "@typescript-eslint", "tailwindcss"], "rules": { "react-hooks/rules-of-hooks": "error", "react-hooks/exhaustive-deps": "warn", "react/prop-types": "off", "react/react-in-jsx-scope": "off", "@typescript-eslint/explicit-module-boundary-types": "off", "@typescript-eslint/no-non-null-assertion": "off", "tailwindcss/classnames-order": "warn", "tailwindcss/no-custom-classname": "warn", "tailwindcss/no-contradicting-classname": "error" } } ================================================ FILE: 01-Simple Storage Full Stack Dapp/.gitignore ================================================ dist dist-ssr *.local # dependencies /node_modules /.pnp .pnp.js # testing /coverage # next.js /.next/ /out/ # production /build # misc .DS_Store *.pem # debug npm-debug.log* yarn-debug.log* yarn-error.log* # local env files .env.local .env.development.local .env.test.local .env.production.local # vercel .vercel .vscode package-lock.json ================================================ FILE: 01-Simple Storage Full Stack Dapp/.jest/setup.ts ================================================ import '@testing-library/jest-dom' ================================================ FILE: 01-Simple Storage Full Stack Dapp/.prettierrc ================================================ { "trailingComma": "none", "semi": false, "singleQuote": true } ================================================ FILE: 01-Simple Storage Full Stack Dapp/README.md ================================================ # Simple Storage dApp on Core Decentralized applications (dApps) use a blockchain or on-chain smart contracts to store and reference data, rather than relying on traditional centralized databases. A common, simple dApp structure generally consists of a React.js or Vue.js front-end using Web3.js or Ethers.js to interact with smart contracts deployed to an EVM-compatible blockchain. ## What Are We Building In this tutorial, we'll develop a simple dApp using React.js and Ethers.js that stores data in a smart contract on the Core blockchain and displays it to users. It also has the functionality to retrieve the stored number and display it to the user. ## Learning Takeaways This tutorial will help you gain knowledge on the following learning points: * MetaMask Wallet connectivity to Core Testnet; * Smart contract development and deployment on Core Testnet; * Front-end integration with the smart contract using Ethers.js library; * Read data from a smart contract; * Write data to a smart contract; ## Software Prerequisites * [Git](https://git-scm.com/) v2.44.0 * [Node.js](https://nodejs.org/en) v20.11.1 * [npm](https://docs.npmjs.com/downloading-and-installing-node-js-and-npm) v10.2.4 * [Hardhat](https://hardhat.org/hardhat-runner/docs/getting-started#installation) v10.2.4 * [MetaMask Web Wallet Extension](https://metamask.io/download/) ## Setting up the development environment 1. Create a new directory for the project and navigate into it ```bash mkdir dapp- cd dapp-tutorial ``` 2. Install [Hardhat](https://hardhat.org/) and [Waffle](https://getwaffle.io/) ```bash npm init --yes npm install --save-dev hardhat npm install --save-dev chai @nomiclabs/hardhat-waffle ``` 3. Initialize Hardhat project by running the following command ```bash npx hardhat ``` ![dapp-tutorial-1](https://github.com/coredao-org/dapp-tutorial/assets/35759187/60930a6b-6e7a-49fc-a748-d1fd20930837) :::note As we will using Waffle for this project and make sure to select **No** for the option "_Do you want to install this sample project's dependencies with npm (@nomicfoundation/hardhat-toolbox)? (Y/n)_" ::: 4. Once this project is initialized, you'll find the following project structure: ```bash dapp-tutorial. | .gitignore | hardhat-config.js (HardHat configuration file.) | package-lock.json | package.json | README.md | +---contracts (For Solidity Smart Contracts) | Lock.sol | +---ignition (Scripts in previous versions, contains config files that specify how smart contracts should be deployed) | \---modules | Lock.js | +---node_modules | +---test (For writing and Running Tests) | Lock.js | ``` 5. Install and configure MetaMask Chrome Extension to use with Core Testnet. Refer [here](https://docs.coredao.org/docs/Dev-Guide/core-testnet-wallet-config) for a detailed guide. 6. Create a secret.json file in the root folder and store the private key of your MetaMask wallet in it. Refer [here](https://metamask.zendesk.com/hc/en-us/articles/360015290032-How-to-reveal-your-Secret-Recovery-Phrase) for details on how to get MetaMask account's private key. ```json {"PrivateKey":"you private key, do not leak this file, do keep it absolutely safe"} ``` :::caution Do not forget to add this file to the `.gitignore` file in the root folder of your project so that you don't accidentally check your private keys/secret phrases into a public repository. Make sure you keep this file in an absolutely safe place! ::: 7. Copy the following into your `hardhat.config.js` file ```js /** * @type import('hardhat/config').HardhatUserConfig */ require('@nomiclabs/hardhat-ethers'); require("@nomiclabs/hardhat-waffle"); const { PrivateKey } = require('./secret.json'); module.exports = { defaultNetwork: 'testnet', networks: { hardhat: { }, testnet: { url: 'https://rpc.test.btcs.network', accounts: [PrivateKey], chainId: 1115, } }, solidity: { compilers: [ { version: '0.8.9', settings: { evmVersion: 'paris', optimizer: { enabled: true, runs: 200, }, }, }, ], }, paths: { sources: './contracts', cache: './cache', artifacts: './artifacts', }, mocha: { timeout: 20000, }, }; ``` ## Writing Smart Contract 1. Navigate to the `contracts` folder in the root directory of your project. 2. Delete the `Lock.sol` file; create a new file `Storage.sol` and paste the following contents into it. ```javascript // SPDX-License-Identifier: GPL-3.0 pragma solidity >=0.7.0 <0.9.0; /** * @title Storage * @dev Store & retrieve value in a variable */ contract Storage { uint256 number; /** * @dev Store value in variable * @param num value to store */ function store(uint256 num) public { number = num; } /** * @dev Return value * @return value of 'number' */ function retrieve() public view returns (uint256){ return number; } } ``` ### Explanation The `Storage` contract is a simple example that demonstrates how to store and retrieve a value using a Solidity smart contract. It consists of a state variable to hold the value and two functions to update and read this value. The `store` function allows any user to set the value, while the `retrieve` function allows any user to read the current value. This contract can be useful for understanding the basics of state variables and function visibility in Solidity. This Solidity smart contract, named `Storage`, is a simple contract that allows storing and retrieving a single `uint256` value. Here’s a detailed breakdown of its components and functionality: #### Contract Components 1. **State Variable**: - `number`: A `uint256` variable that is used to store the value. #### Contract Functions 1. **Store Function**: - `store(uint256 num) public`: A function that allows users to store a new value in the `number` variable. This function takes a single parameter, `num`, which is the value to be stored. The function updates the `number` variable with the provided value. - **Visibility**: The function is marked as `public`, meaning it can be called by any user or contract. - **State Change**: This function modifies the state of the contract by updating the `number` variable. 2. **Retrieve Function**: - `retrieve() public view returns (uint256)`: A function that returns the current value stored in the `number` variable. This function does not take any parameters and returns a `uint256` value. - **Visibility**: The function is marked as `public`, meaning it can be called by any user or contract. - **View**: The function is marked as `view`, indicating that it does not modify the state of the contract. It only reads the state. - **Return Value**: The function returns the value of the `number` variable. ## Compiling Smart Contract 1. To compile the `Storage` smart contract defined in the `Storage.sol`, from the root directory run the following command ```bash npx hardhat compile ``` ## Deploy and Interact with Smart Contract 1. Before deploying your smart contract on the Core Chain, it is best adviced to first run a series of tests making sure that the smart contract is working as desired. Refer to the detailed guide [here](https://docs.coredao.org/docs/Dev-Guide/hardhat#contract-testing) for more details. 2. Create a `scripts` folder in the root directory of your project. Inside this folder, create a file `deploy-and-call.js`; paste the following script into it. ```javascript const hre = require("hardhat"); async function main() { const Storage = await hre.ethers.getContractFactory("Storage"); const storage = await Storage.deploy(); await storage.deployed(); console.log("Storage contract deployed to:", storage.address); console.log("call retrieve():", await storage.retrieve()) console.log("call store(), set value to 100") const tx = await storage.store(100) await tx.wait() console.log("call retrieve() again:", await storage.retrieve()) } // We recommend this pattern to be able to use async/await everywhere // and properly handle errors. main().catch((error) => { console.error(error); process.exitCode = 1; }); ``` 3. Make sure your MetaMask wallet has tCORE test tokens for the Core Testnet. Refer [here](https://docs.coredao.org/docs/Dev-Guide/core-faucet) for details on how to get tCORE tokens from Core Faucet. 4. Run the following command from the root directory of your project, to deploy your smart contract on the Core Chain. ```bash npx hardhat run scripts/deploy-and-call.js ``` If succesfully deployed, you will get the following output ```bash >npx hardhat run scripts/deploy-and-call.js Storage contract deployed to: 0x9e1326fB351FbC4efaa88F0040708F0C0d315109 call retrieve(): BigNumber { value: "0" } call store(), set value to 100 call retrieve() again: BigNumber { value: "100" } ``` 5. Make sure to save the Address of Storage Contract at which is deployed, as obtained above, this will be used for interacting with smart contract from the dApp's frontend. 🎉 Congratulations! You have successfully learned how to create, compile, and deploy a smart contract on the Core Chain Testnet using the Hardhat. ## Interacting with Smart Contract through Frontend ⚡️ Let's create a frontend interface for interacting with the smart contract. ### Setting up Frontend 1. Clone the `dApp-tutorial` repository from GitHub using the following command. ```bash git clone https://github.com/coredao-org/dapp-tutorial.git ``` 2. Navigate into the folder `01-Basic Full Stack Dapp on Core` in the cloned `dapp-tutorial` repo. ```bash cd dapp-tutorial cd "01-Basic Full Stack Dapp on Core" ``` 3. Install all the dependencies, i.e., node modules. ```bash npm install ``` 4. To test if things are working fine, run the application by using the following command. This will serve applciation with hot reload feature at [http://localhost:5173](http://localhost:5173/) ```bash npm run dev ``` ### Key Implementations The application's key blockchain logic is implemented in [App.tsx](https://github.com/coredao-org/dapp-tutorial/blob/master/01-Simple%20Storage%20Full%20Stack%20Dapp/src/components/App.tsx) 1. [App.tsx (Wallet)](https://github.com/coredao-org/dapp-tutorial/blob/master/01-Simple%20Storage%20Full%20Stack%20Dapp/src/components/App.tsx#L20): logic for connecting the application to MetaMask wallet. 2. [App.tsx (Store)](https://github.com/coredao-org/dapp-tutorial/blob/master/01-Simple%20Storage%20Full%20Stack%20Dapp/src/components/App.tsx#L58): logic to write data to the Storage smart contract. 3. [App.tsx (Retrieve)](https://github.com/coredao-org/dapp-tutorial/blob/master/01-Simple%20Storage%20Full%20Stack%20Dapp/src/components/App.tsx#L87): logic to read data from the Storage smart contract. ### Adding Smart Contract Details 1. Copy the `Storage.sol` file from the `contracts` folder in the root of oyur project and paste it into the `frontend/src/contracts` folder. 2. Copy the address of the Storage smart contract as obtained in the section [above](#deploy-and-interact-with-smart-contract). 3. Paste this into [Line 10 of App.tsx](https://github.com/coredao-org/dapp-tutorial/blob/master/01-Simple%20Storage%20Full%20Stack%20Dapp/src/components/App.tsx#L10). ```javascript const contractAddress = '0x48F68BF4A1b1fE6589B9D0a5ad0dF0520582edA2' ``` 4. Additionally, we'll need the ABI metadata to interact with the contract from our dApp. From the `artifacts/contracts` folder in the root of your project. Copy the `Storage.json` file and save it to the `/src/contracts` folder. ## Test Locally Using MetaMask 1. Run the command `npm run dev` from teh root of the project to start the application. This will serve applciation with at [http://localhost:5173](http://localhost:5173/) 2. Make sure that your MetaMask wallet is correctly installed and switched to Core Testnet as described in our [Core Testnet user guide](https://docs.coredao.org/docs/Dev-Guide/core-testnet-wallet-config). You'll also need to connect your MetaMask wallet to the local site. ![dapp-1](https://github.com/coredao-org/dapp-tutorial/assets/35759187/1c493569-1899-4cfe-a051-02579549f916) 3. Enter a number in the input field and click the **store** button to save it to the contract. A write action on the smart contract invokes the MetaMask wallet. Click the **Confirm** button to sign the transaction and wait for confirmation on the blockchain. ![dapp-2](https://github.com/coredao-org/dapp-tutorial/assets/35759187/21aeeb00-a2b7-402d-9909-a2d3cdb36a5d) 4. After the transaction is confirmed on the blockchain, click the **retrieve** button to read the value from the smart contract. You will notice the value has been updated. ![dapp-3](https://github.com/coredao-org/dapp-tutorial/assets/35759187/f284a64d-16dd-44ef-9f24-cd9175465e0a) 🎉 Congratulations! You've just interacted with your newly-deployed contract using your dApp's front end! You can build on the codebase by deploying and interacting with different contracts, and by adding new UI components to the website for your users. ================================================ FILE: 01-Simple Storage Full Stack Dapp/index.html ================================================ Core DAO Dapp tutorial
================================================ FILE: 01-Simple Storage Full Stack Dapp/jest.config.js ================================================ module.exports = { testEnvironment: 'jsdom', testPathIgnorePatterns: ['/node_modules/'], collectCoverage: true, collectCoverageFrom: ['src/**/*.ts(x)'], setupFilesAfterEnv: ['/.jest/setup.ts'], modulePaths: ['/src/', '/.jest'] } ================================================ FILE: 01-Simple Storage Full Stack Dapp/package.json ================================================ { "name": "Tutorial", "description": "This tutorial provides a step-by-step guide on how to store and retrieve data from the Core blockchain.", "version": "0.1.0", "private": true, "scripts": { "dev": "vite", "build": "tsc && vite build", "serve": "vite preview", "test": "jest", "lint": "eslint src --max-warnings=0", "typecheck": "tsc --project tsconfig.json --noEmit" }, "dependencies": { "ethers": "5.6.9", "react": "18.2.0", "react-dom": "18.2.0" }, "devDependencies": { "@babel/core": "7.18.6", "@babel/preset-env": "7.18.6", "@babel/preset-react": "7.18.6", "@babel/preset-typescript": "7.18.6", "@testing-library/jest-dom": "5.16.4", "@testing-library/react": "13.3.0", "@types/jest": "28.1.6", "@types/node": "18.0.5", "@typescript-eslint/eslint-plugin": "5.30.6", "@typescript-eslint/parser": "5.30.6", "@vitejs/plugin-react": "2.0.0", "autoprefixer": "10.4.7", "babel-jest": "28.1.3", "eslint": "8.20.0", "eslint-config-prettier": "8.5.0", "eslint-plugin-prettier": "4.2.1", "eslint-plugin-react": "7.30.1", "eslint-plugin-react-hooks": "4.6.0", "eslint-plugin-tailwindcss": "3.6.0", "jest": "28.1.3", "jest-environment-jsdom": "28.1.3", "postcss": "8.4.14", "prettier": "2.7.1", "tailwindcss": "3.1.6", "typescript": "4.7.4", "vite": "3.0.0", "vite-tsconfig-paths": "3.5.0" } } ================================================ FILE: 01-Simple Storage Full Stack Dapp/postcss.config.js ================================================ module.exports = { plugins: { tailwindcss: {}, autoprefixer: {} } } ================================================ FILE: 01-Simple Storage Full Stack Dapp/src/components/App.tsx ================================================ /* eslint-disable tailwindcss/no-custom-classname */ /* eslint-disable tailwindcss/classnames-order */ /* eslint-disable react/no-unescaped-entities */ import { useEffect, useState } from 'react' import { ethers } from 'ethers' import storage from '../contract/Storage.json' // Contract information const contractAddress = '0x9e1326fB351FbC4efaa88F0040708F0C0d315109' const abi = storage.abi // Constants const CORESCAN_BASE_URL = 'https://scan.test2.btcs.network/address/' function App() { const [currentAccount, setCurrentAccount] = useState(null) const [storeNumber, setStoreNumber] = useState('') const [retrievedNumber, setRetrievedNumber] = useState('') const checkWalletIsConnected = async () => { const { ethereum } = window if (!ethereum) { console.log('Make sure you have Metamask installed!') return } else { console.log("Wallet exists! We're ready to go!") } const accounts = await ethereum.request({ method: 'eth_accounts' }) if (accounts.length !== 0) { const account = accounts[0] console.log('Found an authorized account: ', account) setCurrentAccount(account) } else { console.log('No authorized account found') } } const connectWalletHandler = async () => { const { ethereum } = window if (!ethereum) { alert('Please install Metamask!') } try { const accounts = await ethereum.request({ method: 'eth_requestAccounts' }) console.log(accounts[0]) console.log('Found an account! Address: ', accounts[0]) setCurrentAccount(accounts[0]) } catch (err) { console.log(err) } } const store = async () => { try { const { ethereum } = window if (ethereum) { const provider = new ethers.providers.Web3Provider(ethereum) const signer = provider.getSigner() const storageContract = new ethers.Contract( contractAddress, abi, signer ) console.log('Write to contract') const tx = await storageContract.store(storeNumber) console.log('Wait for the transaction to be confirmed') await tx.wait() console.log( `Transaction confirmed: https://scan.test2.btcs.network/tx/${tx.hash}` ) } else { console.log('Ethereum object does not exist') } } catch (err) { console.log(err) } } const retrieve = async () => { try { const { ethereum } = window if (!ethereum) { console.log('Ethereum object does not exist') alert('Please install MetaMask!') return } // Check if wallet is connected if (!currentAccount) { alert('Please connect your wallet first!') return } const provider = new ethers.providers.Web3Provider(ethereum) // Check if we're on the correct network const network = await provider.getNetwork() console.log('Connected to network:', network) // Verify we're on Core Testnet (Chain ID: 1115) if (network.chainId !== 1114) { alert('Please switch to Core Testnet in MetaMask!') return } // Check if contract exists at the address const code = await provider.getCode(contractAddress) if (code === '0x') { throw new Error(`No contract found at address ${contractAddress}`) } // For view functions, use provider instead of signer const storageContract = new ethers.Contract( contractAddress, abi, provider ) console.log('Reading from contract...') setRetrievedNumber('Loading...') const res = await storageContract.retrieve() const retrievedValue = res.toString() console.log('Retrieved value:', retrievedValue) setRetrievedNumber(retrievedValue) } catch (err) { console.error('Error retrieving data:', err) setRetrievedNumber('Error') if ((err as Error).message.includes('No contract found')) { alert('Contract not found! Please check the contract address.') } else if ((err as Error).message.includes('network')) { alert('Network error! Please check your connection.') } else { alert(`Error: ${(err as Error).message}`) } } } const connectWalletButton = () => { return ( ) } const storageButton = () => { return (

Click "write" or "read" to call the smart contract

setStoreNumber(e.target.value)} className="rounded-l-none border-2 border-solid border-orange-500 caret-orange-500 focus:caret-indigo-500 py-1 px-2 h-10" />
Contract address: {contractAddress}
) } useEffect(() => { checkWalletIsConnected() }, []) return (

Core

Dapp Starter

{currentAccount ? storageButton() : connectWalletButton()}
Fund your account: tCORE faucet
) } export default App ================================================ FILE: 01-Simple Storage Full Stack Dapp/src/contract/Storage.json ================================================ { "abi": [ { "inputs": [], "name": "retrieve", "outputs": [ { "internalType": "uint256", "name": "", "type": "uint256" } ], "stateMutability": "view", "type": "function" }, { "inputs": [ { "internalType": "uint256", "name": "num", "type": "uint256" } ], "name": "store", "outputs": [], "stateMutability": "nonpayable", "type": "function" } ] } ================================================ FILE: 01-Simple Storage Full Stack Dapp/src/contract/Storage.sol ================================================ // SPDX-License-Identifier: GPL-3.0 pragma solidity ^0.8.7; /** * @title Storage * @dev Store & retrieve value in a variable * @custom:dev-run-script ./scripts/deploy_with_ethers.ts */ contract Storage { uint256 number; /** * @dev Store value in variable * @param num value to store */ function store(uint256 num) public { number = num; } /** * @dev Return value * @return value of 'number' */ function retrieve() public view returns (uint256){ return number; } } ================================================ FILE: 01-Simple Storage Full Stack Dapp/src/index.tsx ================================================ import { createRoot } from 'react-dom/client' import 'tailwindcss/tailwind.css' import './style/index.css' import App from 'components/App' const container = document.getElementById('root') as HTMLDivElement const root = createRoot(container) root.render() ================================================ FILE: 01-Simple Storage Full Stack Dapp/src/style/index.css ================================================ @tailwind base; @tailwind components; @tailwind utilities; @layer components { :root{ } .btn-primary { @apply py-2 px-4 bg-orange-500 text-white font-semibold rounded-lg shadow-md hover:bg-orange-700 focus:outline-none focus:ring-2 focus:ring-blue-400 focus:ring-opacity-75; } } ================================================ FILE: 01-Simple Storage Full Stack Dapp/src/utils/index.ts ================================================ export function classNames(...classes: unknown[]): string { return classes.filter(Boolean).join(' ') } ================================================ FILE: 01-Simple Storage Full Stack Dapp/src/vite-env.d.ts ================================================ /* eslint-disable @typescript-eslint/no-explicit-any */ /// /// interface Window { ethereum: any } ================================================ FILE: 01-Simple Storage Full Stack Dapp/tailwind.config.js ================================================ /** @type {import('tailwindcss').Config} */ module.exports = { content: ['./src/**/*.{js,ts,jsx,tsx}'], theme: { extend: {}, }, plugins: [] } ================================================ FILE: 01-Simple Storage Full Stack Dapp/tsconfig.json ================================================ { "compilerOptions": { "baseUrl": "./src", "target": "esnext", "lib": ["dom", "dom.iterable", "esnext"], "allowJs": true, "skipLibCheck": true, "esModuleInterop": true, "allowSyntheticDefaultImports": true, "strict": true, "forceConsistentCasingInFileNames": true, "module": "esnext", "moduleResolution": "node", "resolveJsonModule": true, "isolatedModules": true, "noEmit": true, "jsx": "react-jsx" }, "include": ["src"], "exclude": ["node_modules"] } ================================================ FILE: 01-Simple Storage Full Stack Dapp/vite.config.ts ================================================ import { defineConfig } from 'vite' import react from '@vitejs/plugin-react' import tsconfigPaths from 'vite-tsconfig-paths' // https://vitejs.dev/config/ export default defineConfig({ plugins: [react(), tsconfigPaths()] }) ================================================ FILE: 02-Basic Staking Full Stack Dapp/.gitignore ================================================ node_modules .env secret.json # Hardhat files /cache /artifacts # TypeChain files /typechain /typechain-types # solidity-coverage files /coverage /coverage.json # Hardhat Ignition default folder for deployments against a local node ignition/deployments/chain-31337 ================================================ FILE: 02-Basic Staking Full Stack Dapp/README.md ================================================ # Building a Staking Dapp on Core ## What are we building Welcome to this tutorial on building a simple staking dApp on the Core blockchain. In this guide, we'll walk through the process of creating a basic staking dApp that allows users to stake, unstake, and claim rewards. By the end of this tutorial, you'll have a functional dApp that interacts with smart contracts on the Core Testnet. In this staking dapp, 2 custom ERC20 tokens are used namely, `Staking Token - STK` and `Reward Token - RTK`. While, `STK` is used for staking, the `RTK` token is used for rewarding the users for staking their `STK` tokens. ## Learning Takeaways * Smart Contract Development and deployment * Building a frontend for integration with smart contracts * Using Ethers.js library for communicating with smart contracts * Integrating Metamask for secure user transactions and interactions * Read and Write data to/from smart contracts ## Software Prerequisites * [Git](https://git-scm.com/) v2.44.0 * [Node.js](https://nodejs.org/en) v20.11.1 * [npm](https://docs.npmjs.com/downloading-and-installing-node-js-and-npm) v10.2.4 * [Hardhat](https://hardhat.org/hardhat-runner/docs/getting-started#installation) v2.22.6 * [MetaMask Web Wallet Extension](https://metamask.io/download/)Git v2.44.0 * **Core Testnet Configuration:** Configure MetaMask to connect to the Core Testnet. Refer [here](https://docs.coredao.org/docs/Dev-Guide/core-testnet-wallet-config#adding-core-testnet-to-metamask) for more details. * **Network Name:** Core Testnet * **New RPC URL:** https://rpc.test.btcs.network * **Chain ID:** 1115 * **Currency Symbol:** CORE * **Core Faucet:** To get test CORE tokens for transactions, visit the [Core Faucet](https://scan.test.btcs.network/faucet), refer [here] (https://docs.coredao.org/docs/Dev-Guide/core-faucet) for more details. ## Setting up Dev Environment ### 1. Initialize the Project ``` mkdir staking-dapp cd staking-dapp npm init -y npm install --save-dev hardhat npx hardhat init ``` ![img](./assets/hardhat-init.png) ### 2. Install and Configure MetaMask * Install and configure MetaMask Chrome Extension to use with Core Testnet. * Refer [here](https://docs.coredao.org/docs/Dev-Guide/core-testnet-wallet-config) for a detailed guide. ### 3. Create a Secret File * Create a `secret.json` file in the root folder and store the private key of your MetaMask wallet in it. * Refer [here](https://metamask.zendesk.com/hc/en-us/articles/360015290032-How-to-reveal-your-Secret-Recovery-Phrase) for details on how to get MetaMask account's private key. ```json {"PrivateKey":"you private key, do not leak this file, do keep it absolutely safe"} ``` > _Do not forget to add this file to the `.gitignore` file in the root folder of your project so that you don't accidentally check your private keys/secret phrases into a public repository. Make sure you keep this file in an absolutely safe place!_ ### 4. Update .gitignore * Update your .gitignore file to ensure that your secret.json file and other sensitive files are not committed to version control. * Make sure to add `secret.json` to the `.gitignore` file. ``` node_modules .env secret.json # Hardhat files /cache /artifacts # TypeChain files /typechain /typechain-types # solidity-coverage files /coverage /coverage.json # Hardhat Ignition default folder for deployments against a local node ignition/deployments/chain-31337 ``` ### 5. Update Hardhat.config Replace the contents of `hardhat.config.js` with the following configuration. Ensure that the network settings are configured correctly for Core Testnet. ``` /** * @type import('hardhat/config').HardhatUserConfig */ require('@nomiclabs/hardhat-ethers'); require("@nomiclabs/hardhat-waffle"); const { PrivateKey } = require('./secret.json'); module.exports = { defaultNetwork: 'core_testnet', networks: { hardhat: { }, core_testnet: { url: 'https://rpc.test2.btcs.network', accounts: [PRIVATE_KEY], chainId: 1115, } }, solidity: { compilers: [ { version: '0.8.24', settings: { evmVersion: 'paris', optimizer: { enabled: true, runs: 200, }, }, }, ], }, paths: { sources: './contracts', cache: './cache', artifacts: './artifacts', }, mocha: { timeout: 20000, }, }; ``` ## Writing Smart Contracts In the `contracts` folder, create the following smart contracts. ### Staking Token Contract * For this dapp, we create a custom ERC20 token, named as `Staking Token - STK`. Users will stake their `STK` tokens to earn rewards. * Create a `StakingToken.sol` file and udpate its contents with the following. ```js // SPDX-License-Identifier: MIT // Compatible with OpenZeppelin Contracts ^5.0.0 pragma solidity ^0.8.20; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/token/ERC20/extensions/ERC20Permit.sol"; contract StakingToken is ERC20, Ownable, ERC20Permit { constructor(string memory name, string memory symbol) ERC20(name, symbol) Ownable(msg.sender) ERC20Permit(name) {} function mint(address to, uint256 amount) public { require(amount <= 100 * 10 ** 18, "amount must be less than 100"); _mint(to, amount); } } ``` ### Reward Token Contract * For this dapp, we create a custom ERC20 token, named as `Reward Token - RTK`. Users will earn rewards as `RTK` tokens for staking their `STK` tokens. * Create a `RewardToken.sol` file and udpate its contents with the following. ```js // SPDX-License-Identifier: MIT // Compatible with OpenZeppelin Contracts ^5.0.0 pragma solidity ^0.8.20; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/token/ERC20/extensions/ERC20Permit.sol"; contract RewardToken is ERC20, Ownable, ERC20Permit { constructor(string memory name, string memory symbol) ERC20(name, symbol) Ownable(msg.sender) ERC20Permit(name) {} function mint(address to, uint256 amount) public { _mint(to, amount); } } ``` ### Staking Dapp Contract * Create a `StakingDapp.sol` file and udpate its contents with the following. ```js // SPDX-License-Identifier: MIT pragma solidity 0.8.24; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; interface IRewardToken is IERC20 { function mint(address to, uint256 amount) external; } contract StakingDapp is Ownable { using SafeERC20 for IERC20; IERC20 public stakingToken; IRewardToken public rewardToken; struct Stake { uint256 amount; uint256 lastRewardTime; // Track the last time rewards were calculated } mapping(address => Stake) public stakes; mapping(address => uint256) public rewardBalance; uint256 public constant REWARD_AMOUNT = 5; // Reward tokens per interval uint256 public constant REWARD_INTERVAL = 10; // 10 seconds per reward interval event Staked(address indexed user, uint256 amount); event Unstaked(address indexed user, uint256 amount); event RewardClaimed(address indexed user, uint256 amount); constructor(address _stakingToken, address _rewardToken) Ownable(msg.sender) { require(_stakingToken != address(0) && _rewardToken != address(0), "Invalid token addresses"); stakingToken = IERC20(_stakingToken); rewardToken = IRewardToken(_rewardToken); } function getStakedAmount(address user) external view returns (uint256) { return stakes[user].amount; } function stake(uint256 amount) external { require(amount > 0, "Amount must be greater than 0"); if (stakes[msg.sender].amount > 0) { // Calculate and update reward balance before changing the stake uint256 pendingReward = calculateReward(msg.sender); rewardBalance[msg.sender] += pendingReward; } stakingToken.safeTransferFrom(msg.sender, address(this), amount); // Update the stake amount and last reward time stakes[msg.sender].amount += amount; stakes[msg.sender].lastRewardTime = block.timestamp; emit Staked(msg.sender, amount); } function unstake(uint256 amount) external { require(stakes[msg.sender].amount >= amount, "Insufficient balance"); uint256 pendingReward = calculateReward(msg.sender); rewardBalance[msg.sender] += pendingReward; // Update the stake amount and last reward time stakes[msg.sender].amount -= amount; stakes[msg.sender].lastRewardTime = block.timestamp; stakingToken.safeTransfer(msg.sender, amount); emit Unstaked(msg.sender, amount); } function claimReward() external { uint256 reward = calculateReward(msg.sender) + rewardBalance[msg.sender]; require(reward > 0, "No reward available"); // Reset reward data rewardBalance[msg.sender] = 0; stakes[msg.sender].lastRewardTime = block.timestamp; // Mint reward tokens rewardToken.mint(msg.sender, reward); emit RewardClaimed(msg.sender, reward); } function calculateReward(address user) internal view returns (uint256) { Stake memory userStake = stakes[user]; if (userStake.amount == 0) { return 0; } uint256 currentTime = block.timestamp; uint256 timeSinceLastReward = currentTime - userStake.lastRewardTime; uint256 intervalsPassed = timeSinceLastReward / REWARD_INTERVAL; // Calculate reward based on intervals passed and staked amount return intervalsPassed * REWARD_AMOUNT * userStake.amount; // 1e18; // Assumes REWARD_AMOUNT and staked amount are in the same decimal place } function getRewardAmount(address user) external view returns (uint256) { uint256 reward = calculateReward(user); return reward; } } ``` #### Explanation The StakingDapp contract is a basic implementation of a staking mechanism in Solidity. It allows users to stake an ERC20 token (stakingToken), earn rewards in another ERC20 token (rewardToken), and claim those rewards. ##### State Variables * **stakingToken:** The ERC-20 token that users will stake. * **rewardToken:** The ERC-20 token used to distribute rewards. * **stakes:** A mapping from user addresses to their staking details, including the amount staked and the last time rewards were calculated. * **rewardBalance:** A mapping to keep track of the reward balance for each user that they have accumulated but not yet claimed. * **REWARD_AMOUNT:** The amount of reward tokens distributed per reward interval. * **REWARD_INTERVAL:** The time interval (in seconds) between reward distributions. ##### Functions 1. **getStakedAmount(address user)**: Returns the amount of STK tokens staked by a user. 2. **stake(uint256 amount)**: Allows users to stake a specified amount of staking tokens. * Updates the user's reward balance before modifying the stake. * Transfers the tokens from the user to the contract. * Updates the staking details and the last reward calculation time. * Emits the Staked event. 3. **unstake(uint256 amount)**: Allows users to unstake a specified amount of stakingToken. * Ensures the user has sufficient staked tokens. * Updates the reward balance before modifying the stake. * Transfers the STK tokens back to the user. * Updates the staking details and the last reward calculation time. * Emits the Unstaked event. 4. **claimReward()**: Allows users to claim their accumulated rewards. * Calculates the total reward available for the user. * Mints the reward tokens and transfers them to the user. * Resets the user's reward balance. * Updates the last reward calculation time. * Emits the RewardClaimed event. 5. **calculateReward(address user)**: Calculates the reward amount for a user based on the time elapsed since the last reward calculation and the amount staked. * Uses the REWARD_AMOUNT and REWARD_INTERVAL to compute how many reward intervals have passed. * Calculates the total reward based on the number of intervals and the amount staked. * Visibility: Internal, used by other functions within the contract. 6. **getRewardAmount(address user)**: Allows anyone to query the amount of reward available for a specific user. ## Compile and Deploy Smart Contracts ### Compiling Smart Contracts To compile the smart contracts, run the command `npx hardhat compile` ### Deploying Smart Contracts * Create a `scritps` folder in the root of your project. * Create a file `deploy.js` in the `scripts` folder. * Update the contents of the `deploy.js` file with the following: ```js const { ethers } = require("hardhat"); async function main() { const [deployer] = await ethers.getSigners(); console.log("Deploying contracts with the account:", deployer.address); const StakingToken = await ethers.getContractFactory("StakingToken"); const stakingToken = await StakingToken.deploy("Staking Token", "STK"); const RewardToken = await ethers.getContractFactory("RewardToken"); const rewardToken = await RewardToken.deploy("Reward Token", "RTK"); const StakingDapp = await ethers.getContractFactory("StakingDapp"); const stakingDapp = await StakingDapp.deploy(stakingToken.address, rewardToken.address); console.log("Contracts deployed:"); console.log("Staking Token:", stakingToken.address); console.log("Reward Token:", rewardToken.address); console.log("Staking Dapp:", stakingDapp.address); } main() .then(() => process.exit(0)) .catch((error) => { console.error(error); process.exit(1); }); ``` * Make sure your MetaMask wallet has tCORE test tokens for the Core Testnet. Refer [here](https://docs.coredao.org/docs/Dev-Guide/core-faucet) for details on how to get tCORE tokens from Core Faucet. * Run the following command from the root directory of your project, to deploy smart contracts on the Core blockchain. ```bash npx hardhat run scripts/deploy.js ``` * If succesfully deployed, you will get the following output ![img](./assets/deploy-contracts.png) * Save the addresses for the deploed contracts for use with the frontend. ## Interacting with Smart Contract through Frontend ⚡️ Let's create a frontend interface for interacting with the smart contract. ### Setting up frontend * Create a simple react application using the following command ```bash npx create-react-app frontend cd frontend ``` * Install Dependencies, the Ethers.js library for communicating with the deployed smart contracts. ```bash npm install --save-dev ethers@5.6.9 ``` * Create a `contracts` folder inside the `frontend/src` folder. ```bash mkdir components mkdir contracts ``` Copy the ABIs in the form of `.json` files, of your deployed smart contracts, from `artifacts/contracts/RewardToken.sol` `artifacts/contracts/StakingToken.sol` and `artifacts/contracts/RewardToken.sol` directories into the `frontend/src/contracts` directory. * Create a `components` folder in the `frontend/src` directory. ```bash mkdir components cd components ``` ### Adding Frontend Fuctionality * Update the `App.js` with the contents of the [App.js](./frontend/src/App.js) in the boilerplate repo. * Update the `App.css` with the contents of the [App.css](./frontend/src/App.css) in the boilerplate repo. * Create a `Modal.js` file inside the `components` directory. Update the file with the contents of the [Modal.js](./frontend/src/components/Modal.js) in the boilerplate repo. * Create a `Modal.css` file in the `components` directory. Update the file with the contents of the [Modal.csss](./frontend/src/components/Modal.css) in the boilerplate repo. ### Key Implementation The application's key blockchain logic is implemented in [App.js](./frontend/src/App.js) 1. **App.js (Wallet):** Line#31 onwards is the logic for connecting the application to MetaMask wallet. 2. **App.js (Stake):** Line#180 is the logic to stake the STK tokens. 3. **App.js (Unstake):** Line#211 is the logic to unstake the STK tokens. 4. **App.js (Claim Reward):** Line#275 is the logic to claim the rewards as the RTK tokens. 5. **App.js (STK Faucet):** Line#311 is the logic for the faucet to get STK tokens. ### Adding Smart Contract Details * Paste this into Lines 12, 13, and 14 the addresses of the deployed contracts of StakingToken, RewardToken and StakingDapp. ```js const stakingDappAddress = '0xAddress_of_Staking_Dapp_Contract'; const stakingTokenAddress = '0xAddreess_of_Staking_Token_Contract'; const rewardTokenAddress = '0xAddreess_of_Reward_Token_Contract'; ``` ### Testing Locally * From the `frontend` directory, run the command `npm run start` * Make sure that your MetaMask wallet is correctly installed and switched to Core Testnet as described in our [Core Testnet user guide](https://docs.coredao.org/docs/Dev-Guide/core-testnet-wallet-config). You'll also need to connect your MetaMask wallet to the local site. * Navigate to `http://localhost:3000/` in your browser. ![dapp-ui](./assets/dapp-ui-1.png) * Enter an amount less than 100 and click on the `STK Faucet` to get STK tokens. ![dapp-ui](./assets/dapp-ui-2.png) * Enter an amount greater than 0 and less than or equal to your STK balance and click `Stake` to stake tokens. ![dapp-ui](./assets/dapp-ui-3.png) * On clicking the `Stake` button, Metamask notification will pop up, allow the stakingdapp contract to spend your STK tokens, then click next and on the next notificxation click on `Edit` and give a higher gas limiti value, say 6000000, then click save and approve the transaction. ![metamask-approve](./assets/dapp-metamask-approve-STK-1.png) * Enter an amount greater than 0 and less than or equal to your staked balance and click `Unstake` to unstake tokens. ![dapp-ui](./assets/dapp-ui-4.png) ## 🎉 **Congratulations!** You've just interacted with your deployed contract using your dApp's front end! You can build on the codebase by adding new UI components or more functionality to the staking dapp. ================================================ FILE: 02-Basic Staking Full Stack Dapp/contracts/RewardToken.sol ================================================ // SPDX-License-Identifier: MIT // Compatible with OpenZeppelin Contracts ^5.0.0 pragma solidity ^0.8.20; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/token/ERC20/extensions/ERC20Permit.sol"; contract RewardToken is ERC20, Ownable, ERC20Permit { constructor(string memory name, string memory symbol) ERC20(name, symbol) Ownable(msg.sender) ERC20Permit(name) {} function mint(address to, uint256 amount) public { _mint(to, amount); } } ================================================ FILE: 02-Basic Staking Full Stack Dapp/contracts/StakingDapp.sol ================================================ // SPDX-License-Identifier: MIT pragma solidity 0.8.24; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; interface IRewardToken is IERC20 { function mint(address to, uint256 amount) external; } contract StakingDapp is Ownable { using SafeERC20 for IERC20; IERC20 public stakingToken; IRewardToken public rewardToken; struct Stake { uint256 amount; uint256 lastRewardTime; // Track the last time rewards were calculated } mapping(address => Stake) public stakes; mapping(address => uint256) public rewardBalance; uint256 public constant REWARD_AMOUNT = 5; // Reward tokens per interval uint256 public constant REWARD_INTERVAL = 10; // 10 seconds per reward interval event Staked(address indexed user, uint256 amount); event Unstaked(address indexed user, uint256 amount); event RewardClaimed(address indexed user, uint256 amount); constructor(address _stakingToken, address _rewardToken) Ownable(msg.sender) { require(_stakingToken != address(0) && _rewardToken != address(0), "Invalid token addresses"); stakingToken = IERC20(_stakingToken); rewardToken = IRewardToken(_rewardToken); } function getStakedAmount(address user) external view returns (uint256) { return stakes[user].amount; } function stake(uint256 amount) external { require(amount > 0, "Amount must be greater than 0"); if (stakes[msg.sender].amount > 0) { // Calculate and update reward balance before changing the stake uint256 pendingReward = calculateReward(msg.sender); rewardBalance[msg.sender] += pendingReward; } stakingToken.safeTransferFrom(msg.sender, address(this), amount); // Update the stake amount and last reward time stakes[msg.sender].amount += amount; stakes[msg.sender].lastRewardTime = block.timestamp; emit Staked(msg.sender, amount); } function unstake(uint256 amount) external { require(stakes[msg.sender].amount >= amount, "Insufficient balance"); uint256 pendingReward = calculateReward(msg.sender); rewardBalance[msg.sender] += pendingReward; // Update the stake amount and last reward time stakes[msg.sender].amount -= amount; stakes[msg.sender].lastRewardTime = block.timestamp; stakingToken.safeTransfer(msg.sender, amount); emit Unstaked(msg.sender, amount); } function claimReward() external { uint256 reward = calculateReward(msg.sender) + rewardBalance[msg.sender]; require(reward > 0, "No reward available"); // Reset reward data rewardBalance[msg.sender] = 0; stakes[msg.sender].lastRewardTime = block.timestamp; // Mint reward tokens rewardToken.mint(msg.sender, reward); emit RewardClaimed(msg.sender, reward); } function calculateReward(address user) internal view returns (uint256) { Stake memory userStake = stakes[user]; if (userStake.amount == 0) { return 0; } uint256 currentTime = block.timestamp; uint256 timeSinceLastReward = currentTime - userStake.lastRewardTime; uint256 intervalsPassed = timeSinceLastReward / REWARD_INTERVAL; // Calculate reward based on intervals passed and staked amount return intervalsPassed * REWARD_AMOUNT * userStake.amount; // 1e18; // Assumes REWARD_AMOUNT and staked amount are in the same decimal place } function getRewardAmount(address user) external view returns (uint256) { uint256 reward = calculateReward(user); return reward; } } ================================================ FILE: 02-Basic Staking Full Stack Dapp/contracts/StakingToken.sol ================================================ // SPDX-License-Identifier: MIT // Compatible with OpenZeppelin Contracts ^5.0.0 pragma solidity ^0.8.20; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/token/ERC20/extensions/ERC20Permit.sol"; contract StakingToken is ERC20, Ownable, ERC20Permit { constructor(string memory name, string memory symbol) ERC20(name, symbol) Ownable(msg.sender) ERC20Permit(name) {} function mint(address to, uint256 amount) public { require(amount <= 100 * 10 ** 18, "amount must be less than 100"); _mint(to, amount); } } ================================================ FILE: 02-Basic Staking Full Stack Dapp/frontend/.gitignore ================================================ # See https://help.github.com/articles/ignoring-files/ for more about ignoring files. # dependencies /node_modules /.pnp .pnp.js # testing /coverage # production /build # misc .DS_Store .env.local .env.development.local .env.test.local .env.production.local npm-debug.log* yarn-debug.log* yarn-error.log* ================================================ FILE: 02-Basic Staking Full Stack Dapp/frontend/README.md ================================================ # Getting Started with Create React App This project was bootstrapped with [Create React App](https://github.com/facebook/create-react-app). ## Available Scripts In the project directory, you can run: ### `npm start` Runs the app in the development mode.\ Open [http://localhost:3000](http://localhost:3000) to view it in your browser. The page will reload when you make changes.\ You may also see any lint errors in the console. ### `npm test` Launches the test runner in the interactive watch mode.\ See the section about [running tests](https://facebook.github.io/create-react-app/docs/running-tests) for more information. ### `npm run build` Builds the app for production to the `build` folder.\ It correctly bundles React in production mode and optimizes the build for the best performance. The build is minified and the filenames include the hashes.\ Your app is ready to be deployed! See the section about [deployment](https://facebook.github.io/create-react-app/docs/deployment) for more information. ### `npm run eject` **Note: this is a one-way operation. Once you `eject`, you can't go back!** If you aren't satisfied with the build tool and configuration choices, you can `eject` at any time. This command will remove the single build dependency from your project. Instead, it will copy all the configuration files and the transitive dependencies (webpack, Babel, ESLint, etc) right into your project so you have full control over them. All of the commands except `eject` will still work, but they will point to the copied scripts so you can tweak them. At this point you're on your own. You don't have to ever use `eject`. The curated feature set is suitable for small and middle deployments, and you shouldn't feel obligated to use this feature. However we understand that this tool wouldn't be useful if you couldn't customize it when you are ready for it. ## Learn More You can learn more in the [Create React App documentation](https://facebook.github.io/create-react-app/docs/getting-started). To learn React, check out the [React documentation](https://reactjs.org/). ### Code Splitting This section has moved here: [https://facebook.github.io/create-react-app/docs/code-splitting](https://facebook.github.io/create-react-app/docs/code-splitting) ### Analyzing the Bundle Size This section has moved here: [https://facebook.github.io/create-react-app/docs/analyzing-the-bundle-size](https://facebook.github.io/create-react-app/docs/analyzing-the-bundle-size) ### Making a Progressive Web App This section has moved here: [https://facebook.github.io/create-react-app/docs/making-a-progressive-web-app](https://facebook.github.io/create-react-app/docs/making-a-progressive-web-app) ### Advanced Configuration This section has moved here: [https://facebook.github.io/create-react-app/docs/advanced-configuration](https://facebook.github.io/create-react-app/docs/advanced-configuration) ### Deployment This section has moved here: [https://facebook.github.io/create-react-app/docs/deployment](https://facebook.github.io/create-react-app/docs/deployment) ### `npm run build` fails to minify This section has moved here: [https://facebook.github.io/create-react-app/docs/troubleshooting#npm-run-build-fails-to-minify](https://facebook.github.io/create-react-app/docs/troubleshooting#npm-run-build-fails-to-minify) ================================================ FILE: 02-Basic Staking Full Stack Dapp/frontend/package.json ================================================ { "name": "frontend_ui", "version": "0.1.0", "private": true, "dependencies": { "@testing-library/jest-dom": "5.17.0", "@testing-library/react": "13.4.0", "@testing-library/user-event": "13.5.0", "bootstrap": "5.2.3", "react": "18.3.1", "react-dom": "18.3.1", "react-scripts": "5.0.1", "react-toastify": "10.0.5", "web-vitals": "2.1.4" }, "scripts": { "start": "react-scripts start", "build": "react-scripts build", "test": "react-scripts test", "eject": "react-scripts eject" }, "eslintConfig": { "extends": [ "react-app", "react-app/jest" ] }, "browserslist": { "production": [ ">0.2%", "not dead", "not op_mini all" ], "development": [ "last 1 chrome version", "last 1 firefox version", "last 1 safari version" ] }, "devDependencies": { "ethers": "^5.6.9" } } ================================================ FILE: 02-Basic Staking Full Stack Dapp/frontend/public/index.html ================================================ React App
================================================ FILE: 02-Basic Staking Full Stack Dapp/frontend/public/manifest.json ================================================ { "short_name": "React App", "name": "Create React App Sample", "icons": [ { "src": "favicon.ico", "sizes": "64x64 32x32 24x24 16x16", "type": "image/x-icon" }, { "src": "logo192.png", "type": "image/png", "sizes": "192x192" }, { "src": "logo512.png", "type": "image/png", "sizes": "512x512" } ], "start_url": ".", "display": "standalone", "theme_color": "#000000", "background_color": "#ffffff" } ================================================ FILE: 02-Basic Staking Full Stack Dapp/frontend/public/robots.txt ================================================ # https://www.robotstxt.org/robotstxt.html User-agent: * Disallow: ================================================ FILE: 02-Basic Staking Full Stack Dapp/frontend/src/App.css ================================================ @import url('https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700&display=swap'); :root { /* Light Mode Colors */ --light-bg: #f5f7fa; --light-card: #ffffff; --light-text: #2d3748; --light-text-secondary: #4a5568; --light-border: #e2e8f0; --light-primary: #ff9211; --light-primary-hover: #ed6a2e; /* Dark Mode Colors */ --dark-bg: #1a202c; --dark-card: #2d3748; --dark-text: #f7fafc; --dark-text-secondary: #cbd5e0; --dark-border: #ff9501; --dark-primary: #ff9211; --dark-primary-hover: #ed6a2e; } * { margin: 0; padding: 0; box-sizing: border-box; transition: background-color 0.3s, color 0.3s; } body { font-family: 'Inter', sans-serif; } .App { min-height: 100vh; padding: 0 2rem; } /* Theme Styles */ .light-mode { background-color: var(--light-bg); color: var(--light-text); } .dark-mode { background-color: var(--dark-bg); color: var(--dark-text); } /* Header Styles */ .App-header { display: flex; justify-content: space-between; align-items: center; padding: 1.5rem 0; border-bottom: 1px solid; } .light-mode .App-header { border-color: var(--light-border); } .dark-mode .App-header { border-color: var(--dark-border); } .logo-container img { height: 40px; } .header-right { display: flex; align-items: center; gap: 1rem; } .theme-toggle { background: transparent; border: none; font-size: 1.5rem; cursor: pointer; padding: 0.5rem; border-radius: 50%; } .light-mode .theme-toggle { background-color: rgba(0, 0, 0, 0.05); width: 45px; height: 45px; display: flex; justify-content: center; align-items: center; } .dark-mode .theme-toggle { background-color: rgba(255, 255, 255, 0.05); width: 45px; height: 45px; display: flex; justify-content: center; align-items: center; } /* Button Styles */ .btn-wallet { padding: 0.75rem 1.5rem; border-radius: 0.5rem; font-weight: 600; cursor: pointer; border: none; display: flex; align-items: center; gap: 0.5rem; } .light-mode .btn-wallet { background-color: var(--light-primary); color: white; } .dark-mode .btn-wallet { background-color: var(--dark-primary); color: white; } .btn-wallet:hover { transform: translateY(-1px); } .light-mode .btn-wallet:hover { background-color: var(--light-primary-hover); } .dark-mode .btn-wallet:hover { background-color: var(--dark-primary-hover); } .btn-wallet.large { padding: 1rem 2rem; font-size: 1.1rem; } /* Main Content Styles */ main { padding: 2rem 0; } .main-title { font-size: 2rem; margin-bottom: 2rem; font-weight: 700; } /* Connect Prompt Styles */ .connect-prompt { display: flex; flex-direction: column; align-items: center; justify-content: center; text-align: center; padding: 3rem 0; } .connect-illustration { margin-bottom: 2rem; } .connect-illustration img { max-width: 100%; border-radius: 1rem; } .connect-prompt p { margin-bottom: 2rem; font-size: 1.2rem; max-width: 600px; line-height: 1.6; } .light-mode .connect-prompt p { color: var(--light-text-secondary); } .dark-mode .connect-prompt p { color: var(--dark-text-secondary); } /* Dashboard Styles */ .dashboard { max-width: 1200px; margin: 0 auto; } .wallet-info { display: flex; justify-content: flex-end; margin-bottom: 1.5rem; } .wallet-address { padding: 0.5rem 1rem; border-radius: 0.5rem; font-family: monospace; font-size: 0.9rem; } .light-mode .wallet-address { background-color: rgba(0, 0, 0, 0.05); } .dark-mode .wallet-address { background-color: rgba(255, 255, 255, 0.05); } /* Stats Grid Styles */ .stats-grid { display: grid; grid-template-columns: repeat(auto-fit, minmax(300px, 1fr)); gap: 1.5rem; margin-bottom: 2rem; } .stat-card { padding: 1.5rem; border-radius: 1rem; display: flex; flex-direction: column; align-items: center; text-align: center; } .light-mode .stat-card { background-color: var(--light-card); box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1), 0 2px 4px -1px rgba(0, 0, 0, 0.06); } .dark-mode .stat-card { background-color: var(--dark-card); } .stat-card.highlight { border: 2px solid; } .light-mode .stat-card.highlight { border-color: var(--light-primary); } .dark-mode .stat-card.highlight { border-color: var(--dark-primary); } .stat-icon { font-size: 2rem; margin-bottom: 1rem; } .stat-card h3 { font-size: 1.1rem; margin-bottom: 0.5rem; font-weight: 600; } .stat-value { font-size: 1.5rem; font-weight: 700; margin-bottom: 1rem; } .light-mode .stat-value { color: var(--light-primary); } .dark-mode .stat-value { color: var(--dark-primary); } .claim-btn { padding: 0.5rem 1rem; border-radius: 0.5rem; font-weight: 600; cursor: pointer; border: none; width: 100%; } .light-mode .claim-btn { background-color: var(--light-primary); color: white; } .dark-mode .claim-btn { background-color: var(--dark-primary); color: white; } .claim-btn:hover { transform: translateY(-1px); } .light-mode .claim-btn:hover { background-color: var(--light-primary-hover); } .dark-mode .claim-btn:hover { background-color: var(--dark-primary-hover); } /* Action Cards css */ .action-cards { display: grid; grid-template-columns: repeat(auto-fit, minmax(300px, 1fr)); gap: 1.5rem; } .action-card { padding: 1.5rem; border-radius: 1rem; } .light-mode .action-card { background-color: var(--light-card); box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1), 0 2px 4px -1px rgba(0, 0, 0, 0.06); } .dark-mode .action-card { background-color: var(--dark-card); } .action-card h3 { font-size: 1.1rem; margin-bottom: 1rem; font-weight: 600; } .input-group { display: flex; gap: 0.5rem; } .input-field { flex: 1; padding: 0.75rem 1rem; border-radius: 0.5rem; border: 1px solid; font-size: 1rem; } .light-mode .input-field { border-color: var(--light-border); background-color: white; color: var(--light-text); } .dark-mode .input-field { border-color: var(--dark-border); background-color: #1a202c; color: var(--dark-text); } .input-field:focus { outline: none; border-width: 2px; } .light-mode .input-field:focus { border-color: var(--light-primary); } .dark-mode .input-field:focus { border-color: var(--dark-primary); } .btn-action { padding: 0.75rem 1.5rem; border-radius: 0.5rem; font-weight: 600; cursor: pointer; border: none; white-space: nowrap; } .light-mode .btn-action { background-color: var(--light-primary); color: white; } .dark-mode .btn-action { background-color: var(--dark-primary); color: white; } .btn-action:hover { transform: translateY(-1px); } .light-mode .btn-action:hover { background-color: var(--light-primary-hover); } .dark-mode .btn-action:hover { background-color: var(--dark-primary-hover); } /* Responsive css */ @media (max-width: 768px) { .App { padding: 0 1rem; } .stats-grid, .action-cards { grid-template-columns: 1fr; } .input-group { flex-direction: column; } .btn-action { width: 100%; } } ================================================ FILE: 02-Basic Staking Full Stack Dapp/frontend/src/App.js ================================================ import { useEffect, useState, useCallback } from "react"; import { ethers } from "ethers"; import StakingToken from "./contracts/StakingToken.json"; import StakingDapp from "./contracts/StakingDapp.json"; import RewardToken from "./contracts/RewardToken.json"; import { ToastContainer, toast } from "react-toastify"; import "react-toastify/dist/ReactToastify.css"; import Modal from "./components/Modal"; import "./App.css"; import darkLogo from "./assets/dark_logo.webp"; import lightLogo from "./assets/light_logo.webp"; import "../node_modules/bootstrap/dist/css/bootstrap.min.css"; const stakingDappAddress = "0x341B5aC2189e73d444883CB608FfF7d8e8AC4F93"; const stakingTokenAddress = "0x9Ba37DAA676B30599B67093FACDA8b3B7BD0Fb44"; const rewardTokenAddress = "0xDa0bBC600188Bf2C995de241Cb3B50f62Da925B5"; function App() { const [stakingAmount, setStakingAmount] = useState(""); const [unstakingAmount, setUnstakingAmount] = useState(""); const [currentAccount, setCurrentAccount] = useState(null); const [stakedAmount, setStakedAmount] = useState("0"); const [rewardAmount, setRewardAmount] = useState("0"); const [totalStkBalance, setTotalStkBalance] = useState("0"); const [network, setNetwork] = useState(""); const [faucetAmount, setFaucetAmount] = useState(""); const [isModalOpen, setIsModalOpen] = useState(false); const [stakingTokenDecimals, setStakingTokenDecimals] = useState(18); const [rewardTokenDecimals, setRewardTokenDecimals] = useState(18); const [darkMode, setDarkMode] = useState(true); // Check if wallet is connected const checkWalletIsConnected = async () => { const { ethereum } = window; if (!ethereum) { console.log("Make sure you have Metamask installed!"); return; } try { const accounts = await ethereum.request({ method: "eth_accounts" }); if (accounts.length !== 0) { const account = accounts[0]; setCurrentAccount(account); } else { console.log("No authorized account found ..."); } } catch (error) { console.error("Error fetching accounts:", error); } }; // Check network const checkNetwork = async () => { const { ethereum } = window; if (!ethereum) { console.log("Ethereum object does not exist"); return; } try { const provider = new ethers.providers.Web3Provider(ethereum); const { chainId } = await provider.getNetwork(); if (chainId !== 1115) { console.log("Please connect to the Core Testnet"); } else { setNetwork("Core Testnet"); } } catch (error) { console.error("Error fetching network:", error); } }; // Connect wallet const connectWalletHandler = async () => { const { ethereum } = window; if (!ethereum) { alert("Please install Metamask!"); return; } try { const accounts = await ethereum.request({ method: "eth_requestAccounts", }); setCurrentAccount(accounts[0]); } catch (error) { console.error("Error connecting wallet:", error); } }; // Disconnect wallet const disconnectWalletHandler = () => { setCurrentAccount(null); setStakedAmount("0"); setRewardAmount("0"); setTotalStkBalance("0"); setNetwork(""); }; // Fetch staked and reward amounts const fetchStakedAndRewardAmounts = useCallback(async () => { try { const { ethereum } = window; if (ethereum) { const provider = new ethers.providers.Web3Provider(ethereum); const signer = provider.getSigner(); const stakingDappContract = new ethers.Contract( stakingDappAddress, StakingDapp.abi, signer ); const stakedAmount = await stakingDappContract.getStakedAmount( currentAccount ); const rewardAmount = await stakingDappContract.getRewardAmount( currentAccount ); setStakedAmount( ethers.utils.formatUnits(stakedAmount, stakingTokenDecimals) ); setRewardAmount( ethers.utils.formatUnits(rewardAmount, rewardTokenDecimals) ); } else { console.log("Ethereum object does not exist"); } } catch (error) { console.error("Error fetching staked and reward amounts:", error); } }, [currentAccount, stakingTokenDecimals, rewardTokenDecimals]); // Fetch staking token balance const fetchStkBalance = useCallback(async () => { try { const { ethereum } = window; if (ethereum) { const provider = new ethers.providers.Web3Provider(ethereum); const stakingTokenContract = new ethers.Contract( stakingTokenAddress, StakingToken.abi, provider ); const balance = await stakingTokenContract.balanceOf(currentAccount); const decimals = await stakingTokenContract.decimals(); setStakingTokenDecimals(decimals); setTotalStkBalance(ethers.utils.formatUnits(balance, decimals)); console.log('balance',balance) } else { console.log("Ethereum object does not exist"); } } catch (error) { console.error("Error fetching token balance:", error); } }, [currentAccount]); // Fetch reward token decimals const fetchRewardTokenDecimals = useCallback(async () => { try { const { ethereum } = window; if (ethereum) { const provider = new ethers.providers.Web3Provider(ethereum); const rewardTokenContract = new ethers.Contract( rewardTokenAddress, RewardToken.abi, provider ); const decimals = await rewardTokenContract.decimals(); setRewardTokenDecimals(decimals); } else { console.log("Ethereum object does not exist"); } } catch (error) { console.error("Error fetching reward token decimals:", error); } }, []); useEffect(() => { checkWalletIsConnected(); }, []); useEffect(() => { if (currentAccount) { checkNetwork(); fetchStakedAndRewardAmounts(); fetchStkBalance(); fetchRewardTokenDecimals(); } }, [ currentAccount, fetchStakedAndRewardAmounts, fetchStkBalance, fetchRewardTokenDecimals, ]); // Stake tokens const stakeTokens = async () => { try { if (!isValidAmount(stakingAmount)) { toast.error("Invalid staking amount. Please enter a positive number."); return; } const { ethereum } = window; if (ethereum) { const provider = new ethers.providers.Web3Provider(ethereum); const signer = provider.getSigner(); const stakingDappContract = new ethers.Contract( stakingDappAddress, StakingDapp.abi, signer ); const tokenContract = new ethers.Contract( stakingTokenAddress, StakingToken.abi, signer ); await tokenContract.approve( stakingDappAddress, ethers.utils.parseUnits(stakingAmount, stakingTokenDecimals) ); const tx = await stakingDappContract.stake( ethers.utils.parseUnits(stakingAmount, stakingTokenDecimals) ); await tx.wait(); toast.success("Staked successfully"); fetchStakedAndRewardAmounts(); fetchStkBalance(); } else { console.log("Ethereum object does not exist"); } } catch (error) { console.error("Error staking tokens:", error); toast.error("Error staking tokens"); } }; // Unstake tokens const unstakeTokens = async () => { try { if (!isValidAmount(unstakingAmount)) { toast.error( "Invalid unstaking amount. Please enter a positive number." ); return; } // Check if unstaking amount is greater than the staked amount if (parseFloat(unstakingAmount) > parseFloat(stakedAmount)) { toast.error("Enter value equal to or less than the Staked STK."); return; } const { ethereum } = window; if (ethereum) { const provider = new ethers.providers.Web3Provider(ethereum); const signer = provider.getSigner(); const stakingDappContract = new ethers.Contract( stakingDappAddress, StakingDapp.abi, signer ); const amount = ethers.utils.parseUnits( unstakingAmount, stakingTokenDecimals ); const tx = await stakingDappContract.unstake(amount); await tx.wait(); toast.success("Unstaked successfully"); fetchStakedAndRewardAmounts(); fetchStkBalance(); } else { console.log("Ethereum object does not exist"); } } catch (error) { console.error("Error unstaking tokens:", error); toast.error("Error unstaking tokens"); } }; // Open reward modal const openRewardModal = async () => { try { const { ethereum } = window; if (ethereum) { const provider = new ethers.providers.Web3Provider(ethereum); const signer = provider.getSigner(); const stakingDappContract = new ethers.Contract( stakingDappAddress, StakingDapp.abi, signer ); const reward = await stakingDappContract.getRewardAmount( currentAccount ); const formattedReward = ethers.utils.formatUnits( reward, rewardTokenDecimals ); console.log(formattedReward); if (parseFloat(formattedReward) > 0) { setRewardAmount(formattedReward); setIsModalOpen(true); } else { toast.info("No rewards available to claim."); } } else { console.log("Ethereum object does not exist"); } } catch (error) { console.error("Error fetching reward amount:", error); toast.error("Error fetching reward amount"); } }; // Claim reward const claimReward = async () => { try { if (parseFloat(rewardAmount) <= 0) { toast.error("Cannot claim reward. Amount must be greater than zero."); return; } const { ethereum } = window; if (ethereum) { const provider = new ethers.providers.Web3Provider(ethereum); const signer = provider.getSigner(); const stakingDappContract = new ethers.Contract( stakingDappAddress, StakingDapp.abi, signer ); // Set a high manual gas limit const gasLimit = 5000000; // Higher limit to ensure success // Try sending the transaction with a higher gas limit const tx = await stakingDappContract.claimReward({ gasLimit: gasLimit, }); await tx.wait(); toast.success("Reward claimed successfully"); setIsModalOpen(false); fetchStakedAndRewardAmounts(); fetchStkBalance(); } else { console.log("Ethereum object does not exist"); } } catch (error) { console.error("Error claiming reward:", error); toast.error( "Error claiming reward. Please check the console for details." ); } }; // Faucet tokens const faucetTokens = async (amount) => { try { if (!isValidAmount(amount)) { toast.error( "Invalid faucet amount. Please enter a positive number less than 100." ); return; } const parsedAmount = parseFloat(amount); if (parsedAmount >= 100) { toast.error("Request amount must be less than 100."); return; } const { ethereum } = window; if (ethereum) { const provider = new ethers.providers.Web3Provider(ethereum); const signer = provider.getSigner(); const stakingTokenContract = new ethers.Contract( stakingTokenAddress, StakingToken.abi, signer ); const gasLimit = 600000; const tx = await stakingTokenContract.mint( currentAccount, ethers.utils.parseUnits(amount, stakingTokenDecimals), { gasLimit: gasLimit, } ); await tx.wait(); toast.success("Tokens minted successfully"); fetchStkBalance(); } else { console.log("Ethereum object does not exist"); } } catch (error) { console.error("Error minting tokens:", error); toast.error("Error minting tokens"); } }; // Validate amount const isValidAmount = (amount) => { return !isNaN(Number(amount)) && parseFloat(amount) > 0; }; // Toggle dark/light mode const toggleTheme = () => { setDarkMode(!darkMode); }; return (
Core Logo
{currentAccount ? ( ) : ( )}

Staking Dashboard

{!currentAccount ? (

Please connect your wallet to access the staking dashboard

) : (
Wallet Connected: {currentAccount.slice(0, 6)}...{currentAccount.slice(-4)}
💰

STK Balance

{totalStkBalance} STK

🔒

Staked Amount

{stakedAmount} STK

🎁

Rewards

{rewardAmount} RTK

Stake Tokens

setStakingAmount(e.target.value)} className="input-field" />

Unstake Tokens

setUnstakingAmount(e.target.value)} className="input-field" />

Get Test Tokens

setFaucetAmount(e.target.value)} className="input-field" />
)}
setIsModalOpen(false)} onClaim={claimReward} rewardAmount={rewardAmount} />
); } export default App; ================================================ FILE: 02-Basic Staking Full Stack Dapp/frontend/src/App.test.js ================================================ import { render, screen } from '@testing-library/react'; import App from './App'; test('renders learn react link', () => { render(); const linkElement = screen.getByText(/learn react/i); expect(linkElement).toBeInTheDocument(); }); ================================================ FILE: 02-Basic Staking Full Stack Dapp/frontend/src/components/Modal.css ================================================ /* components/Modal.module.css */ .modalOverlay { position: fixed; top: 0; left: 0; right: 0; bottom: 0; background: rgba(0, 0, 0, 0.5); display: flex; justify-content: center; align-items: center; } .modalContent { background: white; padding: 20px; border-radius: 8px; width: 400px; text-align: center; } .inputField { width: 100%; padding: 10px; margin-top: 10px; border: 1px solid #ccc; border-radius: 4px; } .btnPrimary { background-color: #007bff; color: white; border: none; padding: 10px 20px; margin: 10px; border-radius: 4px; cursor: pointer; } .btnSecondary { background-color: #6c757d; color: white; border: none; padding: 10px 20px; margin: 10px; border-radius: 4px; cursor: pointer; } .errorMessage { color: red; margin-top: 10px; } ================================================ FILE: 02-Basic Staking Full Stack Dapp/frontend/src/components/Modal.js ================================================ import React from 'react'; const Modal = ({ isOpen, onClose, onClaim, rewardAmount }) => { if (!isOpen) return null; return (

Claim Reward

Your reward amount is: {rewardAmount} REWARD

); }; export default Modal; ================================================ FILE: 02-Basic Staking Full Stack Dapp/frontend/src/contracts/IRewardToken.json ================================================ { "_format": "hh-sol-artifact-1", "contractName": "IRewardToken", "sourceName": "contracts/StakingDapp.sol", "abi": [ { "anonymous": false, "inputs": [ { "indexed": true, "internalType": "address", "name": "owner", "type": "address" }, { "indexed": true, "internalType": "address", "name": "spender", "type": "address" }, { "indexed": false, "internalType": "uint256", "name": "value", "type": "uint256" } ], "name": "Approval", "type": "event" }, { "anonymous": false, "inputs": [ { "indexed": true, "internalType": "address", "name": "from", "type": "address" }, { "indexed": true, "internalType": "address", "name": "to", "type": "address" }, { "indexed": false, "internalType": "uint256", "name": "value", "type": "uint256" } ], "name": "Transfer", "type": "event" }, { "inputs": [ { "internalType": "address", "name": "owner", "type": "address" }, { "internalType": "address", "name": "spender", "type": "address" } ], "name": "allowance", "outputs": [ { "internalType": "uint256", "name": "", "type": "uint256" } ], "stateMutability": "view", "type": "function" }, { "inputs": [ { "internalType": "address", "name": "spender", "type": "address" }, { "internalType": "uint256", "name": "value", "type": "uint256" } ], "name": "approve", "outputs": [ { "internalType": "bool", "name": "", "type": "bool" } ], "stateMutability": "nonpayable", "type": "function" }, { "inputs": [ { "internalType": "address", "name": "account", "type": "address" } ], "name": "balanceOf", "outputs": [ { "internalType": "uint256", "name": "", "type": "uint256" } ], "stateMutability": "view", "type": "function" }, { "inputs": [ { "internalType": "address", "name": "to", "type": "address" }, { "internalType": "uint256", "name": "amount", "type": "uint256" } ], "name": "mint", "outputs": [], "stateMutability": "nonpayable", "type": "function" }, { "inputs": [], "name": "totalSupply", "outputs": [ { "internalType": "uint256", "name": "", "type": "uint256" } ], "stateMutability": "view", "type": "function" }, { "inputs": [ { "internalType": "address", "name": "to", "type": "address" }, { "internalType": "uint256", "name": "value", "type": "uint256" } ], "name": "transfer", "outputs": [ { "internalType": "bool", "name": "", "type": "bool" } ], "stateMutability": "nonpayable", "type": "function" }, { "inputs": [ { "internalType": "address", "name": "from", "type": "address" }, { "internalType": "address", "name": "to", "type": "address" }, { "internalType": "uint256", "name": "value", "type": "uint256" } ], "name": "transferFrom", "outputs": [ { "internalType": "bool", "name": "", "type": "bool" } ], "stateMutability": "nonpayable", "type": "function" } ], "bytecode": "0x", "deployedBytecode": "0x", "linkReferences": {}, "deployedLinkReferences": {} } ================================================ FILE: 02-Basic Staking Full Stack Dapp/frontend/src/contracts/RewardToken.json ================================================ { "_format": "hh-sol-artifact-1", "contractName": "RewardToken", "sourceName": "contracts/RewardToken.sol", "abi": [ { "inputs": [ { "internalType": "string", "name": "name", "type": "string" }, { "internalType": "string", "name": "symbol", "type": "string" } ], "stateMutability": "nonpayable", "type": "constructor" }, { "inputs": [], "name": "ECDSAInvalidSignature", "type": "error" }, { "inputs": [ { "internalType": "uint256", "name": "length", "type": "uint256" } ], "name": "ECDSAInvalidSignatureLength", "type": "error" }, { "inputs": [ { "internalType": "bytes32", "name": "s", "type": "bytes32" } ], "name": "ECDSAInvalidSignatureS", "type": "error" }, { "inputs": [ { "internalType": "address", "name": "spender", "type": "address" }, { "internalType": "uint256", "name": "allowance", "type": "uint256" }, { "internalType": "uint256", "name": "needed", "type": "uint256" } ], "name": "ERC20InsufficientAllowance", "type": "error" }, { "inputs": [ { "internalType": "address", "name": "sender", "type": "address" }, { "internalType": "uint256", "name": "balance", "type": "uint256" }, { "internalType": "uint256", "name": "needed", "type": "uint256" } ], "name": "ERC20InsufficientBalance", "type": "error" }, { "inputs": [ { "internalType": "address", "name": "approver", "type": "address" } ], "name": "ERC20InvalidApprover", "type": "error" }, { "inputs": [ { "internalType": "address", "name": "receiver", "type": "address" } ], "name": "ERC20InvalidReceiver", "type": "error" }, { "inputs": [ { "internalType": "address", "name": "sender", "type": "address" } ], "name": "ERC20InvalidSender", "type": "error" }, { "inputs": [ { "internalType": "address", "name": "spender", "type": "address" } ], "name": "ERC20InvalidSpender", "type": "error" }, { "inputs": [ { "internalType": "uint256", "name": "deadline", "type": "uint256" } ], "name": "ERC2612ExpiredSignature", "type": "error" }, { "inputs": [ { "internalType": "address", "name": "signer", "type": "address" }, { "internalType": "address", "name": "owner", "type": "address" } ], "name": "ERC2612InvalidSigner", "type": "error" }, { "inputs": [ { "internalType": "address", "name": "account", "type": "address" }, { "internalType": "uint256", "name": "currentNonce", "type": "uint256" } ], "name": "InvalidAccountNonce", "type": "error" }, { "inputs": [], "name": "InvalidShortString", "type": "error" }, { "inputs": [ { "internalType": "address", "name": "owner", "type": "address" } ], "name": "OwnableInvalidOwner", "type": "error" }, { "inputs": [ { "internalType": "address", "name": "account", "type": "address" } ], "name": "OwnableUnauthorizedAccount", "type": "error" }, { "inputs": [ { "internalType": "string", "name": "str", "type": "string" } ], "name": "StringTooLong", "type": "error" }, { "anonymous": false, "inputs": [ { "indexed": true, "internalType": "address", "name": "owner", "type": "address" }, { "indexed": true, "internalType": "address", "name": "spender", "type": "address" }, { "indexed": false, "internalType": "uint256", "name": "value", "type": "uint256" } ], "name": "Approval", "type": "event" }, { "anonymous": false, "inputs": [], "name": "EIP712DomainChanged", "type": "event" }, { "anonymous": false, "inputs": [ { "indexed": true, "internalType": "address", "name": "previousOwner", "type": "address" }, { "indexed": true, "internalType": "address", "name": "newOwner", "type": "address" } ], "name": "OwnershipTransferred", "type": "event" }, { "anonymous": false, "inputs": [ { "indexed": true, "internalType": "address", "name": "from", "type": "address" }, { "indexed": true, "internalType": "address", "name": "to", "type": "address" }, { "indexed": false, "internalType": "uint256", "name": "value", "type": "uint256" } ], "name": "Transfer", "type": "event" }, { "inputs": [], "name": "DOMAIN_SEPARATOR", "outputs": [ { "internalType": "bytes32", "name": "", "type": "bytes32" } ], "stateMutability": "view", "type": "function" }, { "inputs": [ { "internalType": "address", "name": "owner", "type": "address" }, { "internalType": "address", "name": "spender", "type": "address" } ], "name": "allowance", "outputs": [ { "internalType": "uint256", "name": "", "type": "uint256" } ], "stateMutability": "view", "type": "function" }, { "inputs": [ { "internalType": "address", "name": "spender", "type": "address" }, { "internalType": "uint256", "name": "value", "type": "uint256" } ], "name": "approve", "outputs": [ { "internalType": "bool", "name": "", "type": "bool" } ], "stateMutability": "nonpayable", "type": "function" }, { "inputs": [ { "internalType": "address", "name": "account", "type": "address" } ], "name": "balanceOf", "outputs": [ { "internalType": "uint256", "name": "", "type": "uint256" } ], "stateMutability": "view", "type": "function" }, { "inputs": [], "name": "decimals", "outputs": [ { "internalType": "uint8", "name": "", "type": "uint8" } ], "stateMutability": "view", "type": "function" }, { "inputs": [], "name": "eip712Domain", "outputs": [ { "internalType": "bytes1", "name": "fields", "type": "bytes1" }, { "internalType": "string", "name": "name", "type": "string" }, { "internalType": "string", "name": "version", "type": "string" }, { "internalType": "uint256", "name": "chainId", "type": "uint256" }, { "internalType": "address", "name": "verifyingContract", "type": "address" }, { "internalType": "bytes32", "name": "salt", "type": "bytes32" }, { "internalType": "uint256[]", "name": "extensions", "type": "uint256[]" } ], "stateMutability": "view", "type": "function" }, { "inputs": [ { "internalType": "address", "name": "to", "type": "address" }, { "internalType": "uint256", "name": "amount", "type": "uint256" } ], "name": "mint", "outputs": [], "stateMutability": "nonpayable", "type": "function" }, { "inputs": [], "name": "name", "outputs": [ { "internalType": "string", "name": "", "type": "string" } ], "stateMutability": "view", "type": "function" }, { "inputs": [ { "internalType": "address", "name": "owner", "type": "address" } ], "name": "nonces", "outputs": [ { "internalType": "uint256", "name": "", "type": "uint256" } ], "stateMutability": "view", "type": "function" }, { "inputs": [], "name": "owner", "outputs": [ { "internalType": "address", "name": "", "type": "address" } ], "stateMutability": "view", "type": "function" }, { "inputs": [ { "internalType": "address", "name": "owner", "type": "address" }, { "internalType": "address", "name": "spender", "type": "address" }, { "internalType": "uint256", "name": "value", "type": "uint256" }, { "internalType": "uint256", "name": "deadline", "type": "uint256" }, { "internalType": "uint8", "name": "v", "type": "uint8" }, { "internalType": "bytes32", "name": "r", "type": "bytes32" }, { "internalType": "bytes32", "name": "s", "type": "bytes32" } ], "name": "permit", "outputs": [], "stateMutability": "nonpayable", "type": "function" }, { "inputs": [], "name": "renounceOwnership", "outputs": [], "stateMutability": "nonpayable", "type": "function" }, { "inputs": [], "name": "symbol", "outputs": [ { "internalType": "string", "name": "", "type": "string" } ], "stateMutability": "view", "type": "function" }, { "inputs": [], "name": "totalSupply", "outputs": [ { "internalType": "uint256", "name": "", "type": "uint256" } ], "stateMutability": "view", "type": "function" }, { "inputs": [ { "internalType": "address", "name": "to", "type": "address" }, { "internalType": "uint256", "name": "value", "type": "uint256" } ], "name": "transfer", "outputs": [ { "internalType": "bool", "name": "", "type": "bool" } ], "stateMutability": "nonpayable", "type": "function" }, { "inputs": [ { "internalType": "address", "name": "from", "type": "address" }, { "internalType": "address", "name": "to", "type": "address" }, { "internalType": "uint256", "name": "value", "type": "uint256" } ], "name": "transferFrom", "outputs": [ { "internalType": "bool", "name": "", "type": "bool" } ], "stateMutability": "nonpayable", "type": "function" }, { "inputs": [ { "internalType": "address", "name": "newOwner", "type": "address" } ], "name": "transferOwnership", "outputs": [], "stateMutability": "nonpayable", "type": "function" } ], "bytecode": "0x6101606040523480156200001257600080fd5b506040516200161b3803806200161b83398101604081905262000035916200030a565b6040805180820190915260018152603160f81b602082015282908190338285600362000062838262000405565b50600462000071828262000405565b5050506001600160a01b038116620000a457604051631e4fbdf760e01b8152600060048201526024015b60405180910390fd5b620000af816200016f565b50620000bd826006620001c1565b61012052620000ce816007620001c1565b61014052815160208084019190912060e052815190820120610100524660a0526200015c60e05161010051604080517f8b73c3c69bb8fe3d512ecc4cf759cc79239f7b179b0ffacaa9a75d522b39400f60208201529081019290925260608201524660808201523060a082015260009060c00160405160208183030381529060405280519060200120905090565b60805250503060c052506200052b915050565b600580546001600160a01b038381166001600160a01b0319831681179093556040519116919082907f8be0079c531659141344cd1fd0a4f28419497f9722a3daafe3b4186f6b6457e090600090a35050565b6000602083511015620001e157620001d983620001fa565b9050620001f4565b81620001ee848262000405565b5060ff90505b92915050565b600080829050601f8151111562000228578260405163305a27a960e01b81526004016200009b9190620004d1565b8051620002358262000506565b179392505050565b634e487b7160e01b600052604160045260246000fd5b60005b838110156200027057818101518382015260200162000256565b50506000910152565b600082601f8301126200028b57600080fd5b81516001600160401b0380821115620002a857620002a86200023d565b604051601f8301601f19908116603f01168101908282118183101715620002d357620002d36200023d565b81604052838152866020858801011115620002ed57600080fd5b6200030084602083016020890162000253565b9695505050505050565b600080604083850312156200031e57600080fd5b82516001600160401b03808211156200033657600080fd5b620003448683870162000279565b935060208501519150808211156200035b57600080fd5b506200036a8582860162000279565b9150509250929050565b600181811c908216806200038957607f821691505b602082108103620003aa57634e487b7160e01b600052602260045260246000fd5b50919050565b601f82111562000400576000816000526020600020601f850160051c81016020861015620003db5750805b601f850160051c820191505b81811015620003fc57828155600101620003e7565b5050505b505050565b81516001600160401b038111156200042157620004216200023d565b620004398162000432845462000374565b84620003b0565b602080601f831160018114620004715760008415620004585750858301515b600019600386901b1c1916600185901b178555620003fc565b600085815260208120601f198616915b82811015620004a25788860151825594840194600190910190840162000481565b5085821015620004c15787850151600019600388901b60f8161c191681555b5050505050600190811b01905550565b6020815260008251806020840152620004f281604085016020870162000253565b601f01601f19169190910160400192915050565b80516020808301519190811015620003aa5760001960209190910360031b1b16919050565b60805160a05160c05160e0516101005161012051610140516110956200058660003960006108980152600061086b0152600061075e0152600061073601526000610691015260006106bb015260006106e501526110956000f3fe608060405234801561001057600080fd5b506004361061010b5760003560e01c8063715018a6116100a257806395d89b411161007157806395d89b411461021c578063a9059cbb14610224578063d505accf14610237578063dd62ed3e1461024a578063f2fde38b1461028357600080fd5b8063715018a6146101cb5780637ecebe00146101d357806384b0196e146101e65780638da5cb5b1461020157600080fd5b8063313ce567116100de578063313ce567146101765780633644e5151461018557806340c10f191461018d57806370a08231146101a257600080fd5b806306fdde0314610110578063095ea7b31461012e57806318160ddd1461015157806323b872dd14610163575b600080fd5b610118610296565b6040516101259190610df8565b60405180910390f35b61014161013c366004610e2e565b610328565b6040519015158152602001610125565b6002545b604051908152602001610125565b610141610171366004610e58565b610342565b60405160128152602001610125565b610155610366565b6101a061019b366004610e2e565b610375565b005b6101556101b0366004610e94565b6001600160a01b031660009081526020819052604090205490565b6101a0610383565b6101556101e1366004610e94565b610397565b6101ee6103b5565b6040516101259796959493929190610eaf565b6005546040516001600160a01b039091168152602001610125565b6101186103fb565b610141610232366004610e2e565b61040a565b6101a0610245366004610f48565b610418565b610155610258366004610fbb565b6001600160a01b03918216600090815260016020908152604080832093909416825291909152205490565b6101a0610291366004610e94565b610557565b6060600380546102a590610fee565b80601f01602080910402602001604051908101604052809291908181526020018280546102d190610fee565b801561031e5780601f106102f35761010080835404028352916020019161031e565b820191906000526020600020905b81548152906001019060200180831161030157829003601f168201915b5050505050905090565b600033610336818585610595565b60019150505b92915050565b6000336103508582856105a7565b61035b858585610625565b506001949350505050565b6000610370610684565b905090565b61037f82826107af565b5050565b61038b6107e5565b6103956000610812565b565b6001600160a01b03811660009081526008602052604081205461033c565b6000606080600080600060606103c9610864565b6103d1610891565b60408051600080825260208201909252600f60f81b9b939a50919850469750309650945092509050565b6060600480546102a590610fee565b600033610336818585610625565b834211156104415760405163313c898160e11b8152600481018590526024015b60405180910390fd5b60007f6e71edae12b1b97f4d1f60370fef10105fa2faae0126114a169c64845d6126c988888861048e8c6001600160a01b0316600090815260086020526040902080546001810190915590565b6040805160208101969096526001600160a01b0394851690860152929091166060840152608083015260a082015260c0810186905260e00160405160208183030381529060405280519060200120905060006104e9826108be565b905060006104f9828787876108eb565b9050896001600160a01b0316816001600160a01b031614610540576040516325c0072360e11b81526001600160a01b0380831660048301528b166024820152604401610438565b61054b8a8a8a610595565b50505050505050505050565b61055f6107e5565b6001600160a01b03811661058957604051631e4fbdf760e01b815260006004820152602401610438565b61059281610812565b50565b6105a28383836001610919565b505050565b6001600160a01b03838116600090815260016020908152604080832093861683529290522054600019811461061f578181101561061057604051637dc7a0d960e11b81526001600160a01b03841660048201526024810182905260448101839052606401610438565b61061f84848484036000610919565b50505050565b6001600160a01b03831661064f57604051634b637e8f60e11b815260006004820152602401610438565b6001600160a01b0382166106795760405163ec442f0560e01b815260006004820152602401610438565b6105a28383836109ee565b6000306001600160a01b037f0000000000000000000000000000000000000000000000000000000000000000161480156106dd57507f000000000000000000000000000000000000000000000000000000000000000046145b1561070757507f000000000000000000000000000000000000000000000000000000000000000090565b610370604080517f8b73c3c69bb8fe3d512ecc4cf759cc79239f7b179b0ffacaa9a75d522b39400f60208201527f0000000000000000000000000000000000000000000000000000000000000000918101919091527f000000000000000000000000000000000000000000000000000000000000000060608201524660808201523060a082015260009060c00160405160208183030381529060405280519060200120905090565b6001600160a01b0382166107d95760405163ec442f0560e01b815260006004820152602401610438565b61037f600083836109ee565b6005546001600160a01b031633146103955760405163118cdaa760e01b8152336004820152602401610438565b600580546001600160a01b038381166001600160a01b0319831681179093556040519116919082907f8be0079c531659141344cd1fd0a4f28419497f9722a3daafe3b4186f6b6457e090600090a35050565b60606103707f00000000000000000000000000000000000000000000000000000000000000006006610b18565b60606103707f00000000000000000000000000000000000000000000000000000000000000006007610b18565b600061033c6108cb610684565b8360405161190160f01b8152600281019290925260228201526042902090565b6000806000806108fd88888888610bc3565b92509250925061090d8282610c92565b50909695505050505050565b6001600160a01b0384166109435760405163e602df0560e01b815260006004820152602401610438565b6001600160a01b03831661096d57604051634a1406b160e11b815260006004820152602401610438565b6001600160a01b038085166000908152600160209081526040808320938716835292905220829055801561061f57826001600160a01b0316846001600160a01b03167f8c5be1e5ebec7d5bd14f71427d1e84f3dd0314c0f7b2291e5b200ac8c7c3b925846040516109e091815260200190565b60405180910390a350505050565b6001600160a01b038316610a19578060026000828254610a0e9190611028565b90915550610a8b9050565b6001600160a01b03831660009081526020819052604090205481811015610a6c5760405163391434e360e21b81526001600160a01b03851660048201526024810182905260448101839052606401610438565b6001600160a01b03841660009081526020819052604090209082900390555b6001600160a01b038216610aa757600280548290039055610ac6565b6001600160a01b03821660009081526020819052604090208054820190555b816001600160a01b0316836001600160a01b03167fddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef83604051610b0b91815260200190565b60405180910390a3505050565b606060ff8314610b3257610b2b83610d4b565b905061033c565b818054610b3e90610fee565b80601f0160208091040260200160405190810160405280929190818152602001828054610b6a90610fee565b8015610bb75780601f10610b8c57610100808354040283529160200191610bb7565b820191906000526020600020905b815481529060010190602001808311610b9a57829003601f168201915b5050505050905061033c565b600080807f7fffffffffffffffffffffffffffffff5d576e7357a4501ddfe92f46681b20a0841115610bfe5750600091506003905082610c88565b604080516000808252602082018084528a905260ff891692820192909252606081018790526080810186905260019060a0016020604051602081039080840390855afa158015610c52573d6000803e3d6000fd5b5050604051601f1901519150506001600160a01b038116610c7e57506000925060019150829050610c88565b9250600091508190505b9450945094915050565b6000826003811115610ca657610ca6611049565b03610caf575050565b6001826003811115610cc357610cc3611049565b03610ce15760405163f645eedf60e01b815260040160405180910390fd5b6002826003811115610cf557610cf5611049565b03610d165760405163fce698f760e01b815260048101829052602401610438565b6003826003811115610d2a57610d2a611049565b0361037f576040516335e2f38360e21b815260048101829052602401610438565b60606000610d5883610d8a565b604080516020808252818301909252919250600091906020820181803683375050509182525060208101929092525090565b600060ff8216601f81111561033c57604051632cd44ac360e21b815260040160405180910390fd5b6000815180845260005b81811015610dd857602081850181015186830182015201610dbc565b506000602082860101526020601f19601f83011685010191505092915050565b602081526000610e0b6020830184610db2565b9392505050565b80356001600160a01b0381168114610e2957600080fd5b919050565b60008060408385031215610e4157600080fd5b610e4a83610e12565b946020939093013593505050565b600080600060608486031215610e6d57600080fd5b610e7684610e12565b9250610e8460208501610e12565b9150604084013590509250925092565b600060208284031215610ea657600080fd5b610e0b82610e12565b60ff60f81b881681526000602060e06020840152610ed060e084018a610db2565b8381036040850152610ee2818a610db2565b606085018990526001600160a01b038816608086015260a0850187905284810360c08601528551808252602080880193509091019060005b81811015610f3657835183529284019291840191600101610f1a565b50909c9b505050505050505050505050565b600080600080600080600060e0888a031215610f6357600080fd5b610f6c88610e12565b9650610f7a60208901610e12565b95506040880135945060608801359350608088013560ff81168114610f9e57600080fd5b9699959850939692959460a0840135945060c09093013592915050565b60008060408385031215610fce57600080fd5b610fd783610e12565b9150610fe560208401610e12565b90509250929050565b600181811c9082168061100257607f821691505b60208210810361102257634e487b7160e01b600052602260045260246000fd5b50919050565b8082018082111561033c57634e487b7160e01b600052601160045260246000fd5b634e487b7160e01b600052602160045260246000fdfea264697066735822122058aceb15c5f9ab16678b7846629c6034bcc6687b7db72fb51fda48bc4787f5b464736f6c63430008180033", "deployedBytecode": "0x608060405234801561001057600080fd5b506004361061010b5760003560e01c8063715018a6116100a257806395d89b411161007157806395d89b411461021c578063a9059cbb14610224578063d505accf14610237578063dd62ed3e1461024a578063f2fde38b1461028357600080fd5b8063715018a6146101cb5780637ecebe00146101d357806384b0196e146101e65780638da5cb5b1461020157600080fd5b8063313ce567116100de578063313ce567146101765780633644e5151461018557806340c10f191461018d57806370a08231146101a257600080fd5b806306fdde0314610110578063095ea7b31461012e57806318160ddd1461015157806323b872dd14610163575b600080fd5b610118610296565b6040516101259190610df8565b60405180910390f35b61014161013c366004610e2e565b610328565b6040519015158152602001610125565b6002545b604051908152602001610125565b610141610171366004610e58565b610342565b60405160128152602001610125565b610155610366565b6101a061019b366004610e2e565b610375565b005b6101556101b0366004610e94565b6001600160a01b031660009081526020819052604090205490565b6101a0610383565b6101556101e1366004610e94565b610397565b6101ee6103b5565b6040516101259796959493929190610eaf565b6005546040516001600160a01b039091168152602001610125565b6101186103fb565b610141610232366004610e2e565b61040a565b6101a0610245366004610f48565b610418565b610155610258366004610fbb565b6001600160a01b03918216600090815260016020908152604080832093909416825291909152205490565b6101a0610291366004610e94565b610557565b6060600380546102a590610fee565b80601f01602080910402602001604051908101604052809291908181526020018280546102d190610fee565b801561031e5780601f106102f35761010080835404028352916020019161031e565b820191906000526020600020905b81548152906001019060200180831161030157829003601f168201915b5050505050905090565b600033610336818585610595565b60019150505b92915050565b6000336103508582856105a7565b61035b858585610625565b506001949350505050565b6000610370610684565b905090565b61037f82826107af565b5050565b61038b6107e5565b6103956000610812565b565b6001600160a01b03811660009081526008602052604081205461033c565b6000606080600080600060606103c9610864565b6103d1610891565b60408051600080825260208201909252600f60f81b9b939a50919850469750309650945092509050565b6060600480546102a590610fee565b600033610336818585610625565b834211156104415760405163313c898160e11b8152600481018590526024015b60405180910390fd5b60007f6e71edae12b1b97f4d1f60370fef10105fa2faae0126114a169c64845d6126c988888861048e8c6001600160a01b0316600090815260086020526040902080546001810190915590565b6040805160208101969096526001600160a01b0394851690860152929091166060840152608083015260a082015260c0810186905260e00160405160208183030381529060405280519060200120905060006104e9826108be565b905060006104f9828787876108eb565b9050896001600160a01b0316816001600160a01b031614610540576040516325c0072360e11b81526001600160a01b0380831660048301528b166024820152604401610438565b61054b8a8a8a610595565b50505050505050505050565b61055f6107e5565b6001600160a01b03811661058957604051631e4fbdf760e01b815260006004820152602401610438565b61059281610812565b50565b6105a28383836001610919565b505050565b6001600160a01b03838116600090815260016020908152604080832093861683529290522054600019811461061f578181101561061057604051637dc7a0d960e11b81526001600160a01b03841660048201526024810182905260448101839052606401610438565b61061f84848484036000610919565b50505050565b6001600160a01b03831661064f57604051634b637e8f60e11b815260006004820152602401610438565b6001600160a01b0382166106795760405163ec442f0560e01b815260006004820152602401610438565b6105a28383836109ee565b6000306001600160a01b037f0000000000000000000000000000000000000000000000000000000000000000161480156106dd57507f000000000000000000000000000000000000000000000000000000000000000046145b1561070757507f000000000000000000000000000000000000000000000000000000000000000090565b610370604080517f8b73c3c69bb8fe3d512ecc4cf759cc79239f7b179b0ffacaa9a75d522b39400f60208201527f0000000000000000000000000000000000000000000000000000000000000000918101919091527f000000000000000000000000000000000000000000000000000000000000000060608201524660808201523060a082015260009060c00160405160208183030381529060405280519060200120905090565b6001600160a01b0382166107d95760405163ec442f0560e01b815260006004820152602401610438565b61037f600083836109ee565b6005546001600160a01b031633146103955760405163118cdaa760e01b8152336004820152602401610438565b600580546001600160a01b038381166001600160a01b0319831681179093556040519116919082907f8be0079c531659141344cd1fd0a4f28419497f9722a3daafe3b4186f6b6457e090600090a35050565b60606103707f00000000000000000000000000000000000000000000000000000000000000006006610b18565b60606103707f00000000000000000000000000000000000000000000000000000000000000006007610b18565b600061033c6108cb610684565b8360405161190160f01b8152600281019290925260228201526042902090565b6000806000806108fd88888888610bc3565b92509250925061090d8282610c92565b50909695505050505050565b6001600160a01b0384166109435760405163e602df0560e01b815260006004820152602401610438565b6001600160a01b03831661096d57604051634a1406b160e11b815260006004820152602401610438565b6001600160a01b038085166000908152600160209081526040808320938716835292905220829055801561061f57826001600160a01b0316846001600160a01b03167f8c5be1e5ebec7d5bd14f71427d1e84f3dd0314c0f7b2291e5b200ac8c7c3b925846040516109e091815260200190565b60405180910390a350505050565b6001600160a01b038316610a19578060026000828254610a0e9190611028565b90915550610a8b9050565b6001600160a01b03831660009081526020819052604090205481811015610a6c5760405163391434e360e21b81526001600160a01b03851660048201526024810182905260448101839052606401610438565b6001600160a01b03841660009081526020819052604090209082900390555b6001600160a01b038216610aa757600280548290039055610ac6565b6001600160a01b03821660009081526020819052604090208054820190555b816001600160a01b0316836001600160a01b03167fddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef83604051610b0b91815260200190565b60405180910390a3505050565b606060ff8314610b3257610b2b83610d4b565b905061033c565b818054610b3e90610fee565b80601f0160208091040260200160405190810160405280929190818152602001828054610b6a90610fee565b8015610bb75780601f10610b8c57610100808354040283529160200191610bb7565b820191906000526020600020905b815481529060010190602001808311610b9a57829003601f168201915b5050505050905061033c565b600080807f7fffffffffffffffffffffffffffffff5d576e7357a4501ddfe92f46681b20a0841115610bfe5750600091506003905082610c88565b604080516000808252602082018084528a905260ff891692820192909252606081018790526080810186905260019060a0016020604051602081039080840390855afa158015610c52573d6000803e3d6000fd5b5050604051601f1901519150506001600160a01b038116610c7e57506000925060019150829050610c88565b9250600091508190505b9450945094915050565b6000826003811115610ca657610ca6611049565b03610caf575050565b6001826003811115610cc357610cc3611049565b03610ce15760405163f645eedf60e01b815260040160405180910390fd5b6002826003811115610cf557610cf5611049565b03610d165760405163fce698f760e01b815260048101829052602401610438565b6003826003811115610d2a57610d2a611049565b0361037f576040516335e2f38360e21b815260048101829052602401610438565b60606000610d5883610d8a565b604080516020808252818301909252919250600091906020820181803683375050509182525060208101929092525090565b600060ff8216601f81111561033c57604051632cd44ac360e21b815260040160405180910390fd5b6000815180845260005b81811015610dd857602081850181015186830182015201610dbc565b506000602082860101526020601f19601f83011685010191505092915050565b602081526000610e0b6020830184610db2565b9392505050565b80356001600160a01b0381168114610e2957600080fd5b919050565b60008060408385031215610e4157600080fd5b610e4a83610e12565b946020939093013593505050565b600080600060608486031215610e6d57600080fd5b610e7684610e12565b9250610e8460208501610e12565b9150604084013590509250925092565b600060208284031215610ea657600080fd5b610e0b82610e12565b60ff60f81b881681526000602060e06020840152610ed060e084018a610db2565b8381036040850152610ee2818a610db2565b606085018990526001600160a01b038816608086015260a0850187905284810360c08601528551808252602080880193509091019060005b81811015610f3657835183529284019291840191600101610f1a565b50909c9b505050505050505050505050565b600080600080600080600060e0888a031215610f6357600080fd5b610f6c88610e12565b9650610f7a60208901610e12565b95506040880135945060608801359350608088013560ff81168114610f9e57600080fd5b9699959850939692959460a0840135945060c09093013592915050565b60008060408385031215610fce57600080fd5b610fd783610e12565b9150610fe560208401610e12565b90509250929050565b600181811c9082168061100257607f821691505b60208210810361102257634e487b7160e01b600052602260045260246000fd5b50919050565b8082018082111561033c57634e487b7160e01b600052601160045260246000fd5b634e487b7160e01b600052602160045260246000fdfea264697066735822122058aceb15c5f9ab16678b7846629c6034bcc6687b7db72fb51fda48bc4787f5b464736f6c63430008180033", "linkReferences": {}, "deployedLinkReferences": {} } ================================================ FILE: 02-Basic Staking Full Stack Dapp/frontend/src/contracts/StakingDapp.json ================================================ { "_format": "hh-sol-artifact-1", "contractName": "StakingDapp", "sourceName": "contracts/StakingDapp.sol", "abi": [ { "inputs": [ { "internalType": "address", "name": "_stakingToken", "type": "address" }, { "internalType": "address", "name": "_rewardToken", "type": "address" } ], "stateMutability": "nonpayable", "type": "constructor" }, { "inputs": [ { "internalType": "address", "name": "target", "type": "address" } ], "name": "AddressEmptyCode", "type": "error" }, { "inputs": [ { "internalType": "address", "name": "account", "type": "address" } ], "name": "AddressInsufficientBalance", "type": "error" }, { "inputs": [], "name": "FailedInnerCall", "type": "error" }, { "inputs": [ { "internalType": "address", "name": "owner", "type": "address" } ], "name": "OwnableInvalidOwner", "type": "error" }, { "inputs": [ { "internalType": "address", "name": "account", "type": "address" } ], "name": "OwnableUnauthorizedAccount", "type": "error" }, { "inputs": [ { "internalType": "address", "name": "token", "type": "address" } ], "name": "SafeERC20FailedOperation", "type": "error" }, { "anonymous": false, "inputs": [ { "indexed": true, "internalType": "address", "name": "previousOwner", "type": "address" }, { "indexed": true, "internalType": "address", "name": "newOwner", "type": "address" } ], "name": "OwnershipTransferred", "type": "event" }, { "anonymous": false, "inputs": [ { "indexed": true, "internalType": "address", "name": "user", "type": "address" }, { "indexed": false, "internalType": "uint256", "name": "amount", "type": "uint256" } ], "name": "RewardClaimed", "type": "event" }, { "anonymous": false, "inputs": [ { "indexed": true, "internalType": "address", "name": "user", "type": "address" }, { "indexed": false, "internalType": "uint256", "name": "amount", "type": "uint256" } ], "name": "Staked", "type": "event" }, { "anonymous": false, "inputs": [ { "indexed": true, "internalType": "address", "name": "user", "type": "address" }, { "indexed": false, "internalType": "uint256", "name": "amount", "type": "uint256" } ], "name": "Unstaked", "type": "event" }, { "inputs": [], "name": "REWARD_AMOUNT", "outputs": [ { "internalType": "uint256", "name": "", "type": "uint256" } ], "stateMutability": "view", "type": "function" }, { "inputs": [], "name": "REWARD_INTERVAL", "outputs": [ { "internalType": "uint256", "name": "", "type": "uint256" } ], "stateMutability": "view", "type": "function" }, { "inputs": [], "name": "claimReward", "outputs": [], "stateMutability": "nonpayable", "type": "function" }, { "inputs": [ { "internalType": "address", "name": "user", "type": "address" } ], "name": "getRewardAmount", "outputs": [ { "internalType": "uint256", "name": "", "type": "uint256" } ], "stateMutability": "view", "type": "function" }, { "inputs": [ { "internalType": "address", "name": "user", "type": "address" } ], "name": "getStakedAmount", "outputs": [ { "internalType": "uint256", "name": "", "type": "uint256" } ], "stateMutability": "view", "type": "function" }, { "inputs": [], "name": "owner", "outputs": [ { "internalType": "address", "name": "", "type": "address" } ], "stateMutability": "view", "type": "function" }, { "inputs": [], "name": "renounceOwnership", "outputs": [], "stateMutability": "nonpayable", "type": "function" }, { "inputs": [ { "internalType": "address", "name": "", "type": "address" } ], "name": "rewardBalance", "outputs": [ { "internalType": "uint256", "name": "", "type": "uint256" } ], "stateMutability": "view", "type": "function" }, { "inputs": [], "name": "rewardToken", "outputs": [ { "internalType": "contract IRewardToken", "name": "", "type": "address" } ], "stateMutability": "view", "type": "function" }, { "inputs": [ { "internalType": "uint256", "name": "amount", "type": "uint256" } ], "name": "stake", "outputs": [], "stateMutability": "nonpayable", "type": "function" }, { "inputs": [ { "internalType": "address", "name": "", "type": "address" } ], "name": "stakes", "outputs": [ { "internalType": "uint256", "name": "amount", "type": "uint256" }, { "internalType": "uint256", "name": "lastRewardTime", "type": "uint256" } ], "stateMutability": "view", "type": "function" }, { "inputs": [], "name": "stakingToken", "outputs": [ { "internalType": "contract IERC20", "name": "", "type": "address" } ], "stateMutability": "view", "type": "function" }, { "inputs": [ { "internalType": "address", "name": "newOwner", "type": "address" } ], "name": "transferOwnership", "outputs": [], "stateMutability": "nonpayable", "type": "function" }, { "inputs": [ { "internalType": "uint256", "name": "amount", "type": "uint256" } ], "name": "unstake", "outputs": [], "stateMutability": "nonpayable", "type": "function" } ], "bytecode": "0x608060405234801561001057600080fd5b50604051610c34380380610c3483398101604081905261002f91610169565b338061005657604051631e4fbdf760e01b8152600060048201526024015b60405180910390fd5b61005f816100fd565b506001600160a01b0382161580159061008057506001600160a01b03811615155b6100cc5760405162461bcd60e51b815260206004820152601760248201527f496e76616c696420746f6b656e20616464726573736573000000000000000000604482015260640161004d565b600180546001600160a01b039384166001600160a01b0319918216179091556002805492909316911617905561019c565b600080546001600160a01b038381166001600160a01b0319831681178455604051919092169283917f8be0079c531659141344cd1fd0a4f28419497f9722a3daafe3b4186f6b6457e09190a35050565b80516001600160a01b038116811461016457600080fd5b919050565b6000806040838503121561017c57600080fd5b6101858361014d565b91506101936020840161014d565b90509250929050565b610a89806101ab6000396000f3fe608060405234801561001057600080fd5b50600436106100ea5760003560e01c806372f702f31161008c578063b88a802f11610066578063b88a802f1461020e578063cf84944214610216578063f2fde38b1461021e578063f7c618c11461023157600080fd5b806372f702f3146101bf5780638da5cb5b146101ea578063a694fc3a146101fb57600080fd5b80634da6a556116100c85780634da6a556146101665780635dbdda691461018f57806367b40cf714610197578063715018a6146101b757600080fd5b806316934fc4146100ef5780632e17de781461013057806344a040f514610145575b600080fd5b6101166100fd36600461094b565b6003602052600090815260409020805460019091015482565b604080519283526020830191909152015b60405180910390f35b61014361013e366004610974565b610244565b005b61015861015336600461094b565b61035d565b604051908152602001610127565b61015861017436600461094b565b6001600160a01b031660009081526003602052604090205490565b610158600a81565b6101586101a536600461094b565b60046020526000908152604090205481565b610143610370565b6001546101d2906001600160a01b031681565b6040516001600160a01b039091168152602001610127565b6000546001600160a01b03166101d2565b610143610209366004610974565b610384565b6101436104ae565b610158600581565b61014361022c36600461094b565b6105d4565b6002546101d2906001600160a01b031681565b3360009081526003602052604090205481111561029f5760405162461bcd60e51b8152602060048201526014602482015273496e73756666696369656e742062616c616e636560601b60448201526064015b60405180910390fd5b60006102aa33610612565b336000908152600460205260408120805492935083929091906102ce9084906109a3565b909155505033600090815260036020526040812080548492906102f29084906109b6565b90915550503360008181526003602052604090204260019182015554610324916001600160a01b03909116908461069e565b60405182815233907f0f5bb82176feb1b5e747e28471aa92156a04d9f3ab9f45f28e2d704232b93f759060200160405180910390a25050565b60008061036983610612565b9392505050565b610378610702565b610382600061072f565b565b600081116103d45760405162461bcd60e51b815260206004820152601d60248201527f416d6f756e74206d7573742062652067726561746572207468616e20300000006044820152606401610296565b336000908152600360205260409020541561041f5760006103f433610612565b336000908152600460205260408120805492935083929091906104189084906109a3565b9091555050505b600154610437906001600160a01b031633308461077f565b33600090815260036020526040812080548392906104569084906109a3565b9091555050336000818152600360205260409081902042600190910155517f9e71bc8eea02a63969f509818f2dafb9254532904319f9dbda79b67bd34a5f3d906104a39084815260200190565b60405180910390a250565b3360008181526004602052604081205490916104c990610612565b6104d391906109a3565b90506000811161051b5760405162461bcd60e51b81526020600482015260136024820152724e6f2072657761726420617661696c61626c6560681b6044820152606401610296565b3360008181526004602081815260408084208490556003909152918290204260019091015560025491516340c10f1960e01b815290810192909252602482018390526001600160a01b0316906340c10f1990604401600060405180830381600087803b15801561058a57600080fd5b505af115801561059e573d6000803e3d6000fd5b50506040518381523392507f106f923f993c2149d49b4255ff723acafa1f2d94393f561d3eda32ae348f724191506020016104a3565b6105dc610702565b6001600160a01b03811661060657604051631e4fbdf760e01b815260006004820152602401610296565b61060f8161072f565b50565b6001600160a01b038116600090815260036020908152604080832081518083019092528054808352600190910154928201929092529082036106575750600092915050565b6020810151429060009061066b90836109b6565b9050600061067a600a836109c9565b845190915061068a6005836109eb565b61069491906109eb565b9695505050505050565b6040516001600160a01b038381166024830152604482018390526106fd91859182169063a9059cbb906064015b604051602081830303815290604052915060e01b6020820180516001600160e01b0383818316178352505050506107be565b505050565b6000546001600160a01b031633146103825760405163118cdaa760e01b8152336004820152602401610296565b600080546001600160a01b038381166001600160a01b0319831681178455604051919092169283917f8be0079c531659141344cd1fd0a4f28419497f9722a3daafe3b4186f6b6457e09190a35050565b6040516001600160a01b0384811660248301528381166044830152606482018390526107b89186918216906323b872dd906084016106cb565b50505050565b60006107d36001600160a01b03841683610821565b905080516000141580156107f85750808060200190518101906107f69190610a02565b155b156106fd57604051635274afe760e01b81526001600160a01b0384166004820152602401610296565b606061082f83836000610838565b90505b92915050565b60608147101561085d5760405163cd78605960e01b8152306004820152602401610296565b600080856001600160a01b031684866040516108799190610a24565b60006040518083038185875af1925050503d80600081146108b6576040519150601f19603f3d011682016040523d82523d6000602084013e6108bb565b606091505b50915091506106948683836060826108db576108d682610922565b610369565b81511580156108f257506001600160a01b0384163b155b1561091b57604051639996b31560e01b81526001600160a01b0385166004820152602401610296565b5080610369565b8051156109325780518082602001fd5b604051630a12f52160e11b815260040160405180910390fd5b60006020828403121561095d57600080fd5b81356001600160a01b038116811461036957600080fd5b60006020828403121561098657600080fd5b5035919050565b634e487b7160e01b600052601160045260246000fd5b808201808211156108325761083261098d565b818103818111156108325761083261098d565b6000826109e657634e487b7160e01b600052601260045260246000fd5b500490565b80820281158282048414176108325761083261098d565b600060208284031215610a1457600080fd5b8151801515811461036957600080fd5b6000825160005b81811015610a455760208186018101518583015201610a2b565b50600092019182525091905056fea2646970667358221220f3921a408b8e35be31fb9b731a00916ad51e7bbebbd2b498e54d7d7e78acab0d64736f6c63430008180033", "deployedBytecode": "0x608060405234801561001057600080fd5b50600436106100ea5760003560e01c806372f702f31161008c578063b88a802f11610066578063b88a802f1461020e578063cf84944214610216578063f2fde38b1461021e578063f7c618c11461023157600080fd5b806372f702f3146101bf5780638da5cb5b146101ea578063a694fc3a146101fb57600080fd5b80634da6a556116100c85780634da6a556146101665780635dbdda691461018f57806367b40cf714610197578063715018a6146101b757600080fd5b806316934fc4146100ef5780632e17de781461013057806344a040f514610145575b600080fd5b6101166100fd36600461094b565b6003602052600090815260409020805460019091015482565b604080519283526020830191909152015b60405180910390f35b61014361013e366004610974565b610244565b005b61015861015336600461094b565b61035d565b604051908152602001610127565b61015861017436600461094b565b6001600160a01b031660009081526003602052604090205490565b610158600a81565b6101586101a536600461094b565b60046020526000908152604090205481565b610143610370565b6001546101d2906001600160a01b031681565b6040516001600160a01b039091168152602001610127565b6000546001600160a01b03166101d2565b610143610209366004610974565b610384565b6101436104ae565b610158600581565b61014361022c36600461094b565b6105d4565b6002546101d2906001600160a01b031681565b3360009081526003602052604090205481111561029f5760405162461bcd60e51b8152602060048201526014602482015273496e73756666696369656e742062616c616e636560601b60448201526064015b60405180910390fd5b60006102aa33610612565b336000908152600460205260408120805492935083929091906102ce9084906109a3565b909155505033600090815260036020526040812080548492906102f29084906109b6565b90915550503360008181526003602052604090204260019182015554610324916001600160a01b03909116908461069e565b60405182815233907f0f5bb82176feb1b5e747e28471aa92156a04d9f3ab9f45f28e2d704232b93f759060200160405180910390a25050565b60008061036983610612565b9392505050565b610378610702565b610382600061072f565b565b600081116103d45760405162461bcd60e51b815260206004820152601d60248201527f416d6f756e74206d7573742062652067726561746572207468616e20300000006044820152606401610296565b336000908152600360205260409020541561041f5760006103f433610612565b336000908152600460205260408120805492935083929091906104189084906109a3565b9091555050505b600154610437906001600160a01b031633308461077f565b33600090815260036020526040812080548392906104569084906109a3565b9091555050336000818152600360205260409081902042600190910155517f9e71bc8eea02a63969f509818f2dafb9254532904319f9dbda79b67bd34a5f3d906104a39084815260200190565b60405180910390a250565b3360008181526004602052604081205490916104c990610612565b6104d391906109a3565b90506000811161051b5760405162461bcd60e51b81526020600482015260136024820152724e6f2072657761726420617661696c61626c6560681b6044820152606401610296565b3360008181526004602081815260408084208490556003909152918290204260019091015560025491516340c10f1960e01b815290810192909252602482018390526001600160a01b0316906340c10f1990604401600060405180830381600087803b15801561058a57600080fd5b505af115801561059e573d6000803e3d6000fd5b50506040518381523392507f106f923f993c2149d49b4255ff723acafa1f2d94393f561d3eda32ae348f724191506020016104a3565b6105dc610702565b6001600160a01b03811661060657604051631e4fbdf760e01b815260006004820152602401610296565b61060f8161072f565b50565b6001600160a01b038116600090815260036020908152604080832081518083019092528054808352600190910154928201929092529082036106575750600092915050565b6020810151429060009061066b90836109b6565b9050600061067a600a836109c9565b845190915061068a6005836109eb565b61069491906109eb565b9695505050505050565b6040516001600160a01b038381166024830152604482018390526106fd91859182169063a9059cbb906064015b604051602081830303815290604052915060e01b6020820180516001600160e01b0383818316178352505050506107be565b505050565b6000546001600160a01b031633146103825760405163118cdaa760e01b8152336004820152602401610296565b600080546001600160a01b038381166001600160a01b0319831681178455604051919092169283917f8be0079c531659141344cd1fd0a4f28419497f9722a3daafe3b4186f6b6457e09190a35050565b6040516001600160a01b0384811660248301528381166044830152606482018390526107b89186918216906323b872dd906084016106cb565b50505050565b60006107d36001600160a01b03841683610821565b905080516000141580156107f85750808060200190518101906107f69190610a02565b155b156106fd57604051635274afe760e01b81526001600160a01b0384166004820152602401610296565b606061082f83836000610838565b90505b92915050565b60608147101561085d5760405163cd78605960e01b8152306004820152602401610296565b600080856001600160a01b031684866040516108799190610a24565b60006040518083038185875af1925050503d80600081146108b6576040519150601f19603f3d011682016040523d82523d6000602084013e6108bb565b606091505b50915091506106948683836060826108db576108d682610922565b610369565b81511580156108f257506001600160a01b0384163b155b1561091b57604051639996b31560e01b81526001600160a01b0385166004820152602401610296565b5080610369565b8051156109325780518082602001fd5b604051630a12f52160e11b815260040160405180910390fd5b60006020828403121561095d57600080fd5b81356001600160a01b038116811461036957600080fd5b60006020828403121561098657600080fd5b5035919050565b634e487b7160e01b600052601160045260246000fd5b808201808211156108325761083261098d565b818103818111156108325761083261098d565b6000826109e657634e487b7160e01b600052601260045260246000fd5b500490565b80820281158282048414176108325761083261098d565b600060208284031215610a1457600080fd5b8151801515811461036957600080fd5b6000825160005b81811015610a455760208186018101518583015201610a2b565b50600092019182525091905056fea2646970667358221220f3921a408b8e35be31fb9b731a00916ad51e7bbebbd2b498e54d7d7e78acab0d64736f6c63430008180033", "linkReferences": {}, "deployedLinkReferences": {} } ================================================ FILE: 02-Basic Staking Full Stack Dapp/frontend/src/contracts/StakingToken.json ================================================ { "_format": "hh-sol-artifact-1", "contractName": "StakingToken", "sourceName": "contracts/StakingToken.sol", "abi": [ { "inputs": [ { "internalType": "string", "name": "name", "type": "string" }, { "internalType": "string", "name": "symbol", "type": "string" } ], "stateMutability": "nonpayable", "type": "constructor" }, { "inputs": [], "name": "ECDSAInvalidSignature", "type": "error" }, { "inputs": [ { "internalType": "uint256", "name": "length", "type": "uint256" } ], "name": "ECDSAInvalidSignatureLength", "type": "error" }, { "inputs": [ { "internalType": "bytes32", "name": "s", "type": "bytes32" } ], "name": "ECDSAInvalidSignatureS", "type": "error" }, { "inputs": [ { "internalType": "address", "name": "spender", "type": "address" }, { "internalType": "uint256", "name": "allowance", "type": "uint256" }, { "internalType": "uint256", "name": "needed", "type": "uint256" } ], "name": "ERC20InsufficientAllowance", "type": "error" }, { "inputs": [ { "internalType": "address", "name": "sender", "type": "address" }, { "internalType": "uint256", "name": "balance", "type": "uint256" }, { "internalType": "uint256", "name": "needed", "type": "uint256" } ], "name": "ERC20InsufficientBalance", "type": "error" }, { "inputs": [ { "internalType": "address", "name": "approver", "type": "address" } ], "name": "ERC20InvalidApprover", "type": "error" }, { "inputs": [ { "internalType": "address", "name": "receiver", "type": "address" } ], "name": "ERC20InvalidReceiver", "type": "error" }, { "inputs": [ { "internalType": "address", "name": "sender", "type": "address" } ], "name": "ERC20InvalidSender", "type": "error" }, { "inputs": [ { "internalType": "address", "name": "spender", "type": "address" } ], "name": "ERC20InvalidSpender", "type": "error" }, { "inputs": [ { "internalType": "uint256", "name": "deadline", "type": "uint256" } ], "name": "ERC2612ExpiredSignature", "type": "error" }, { "inputs": [ { "internalType": "address", "name": "signer", "type": "address" }, { "internalType": "address", "name": "owner", "type": "address" } ], "name": "ERC2612InvalidSigner", "type": "error" }, { "inputs": [ { "internalType": "address", "name": "account", "type": "address" }, { "internalType": "uint256", "name": "currentNonce", "type": "uint256" } ], "name": "InvalidAccountNonce", "type": "error" }, { "inputs": [], "name": "InvalidShortString", "type": "error" }, { "inputs": [ { "internalType": "address", "name": "owner", "type": "address" } ], "name": "OwnableInvalidOwner", "type": "error" }, { "inputs": [ { "internalType": "address", "name": "account", "type": "address" } ], "name": "OwnableUnauthorizedAccount", "type": "error" }, { "inputs": [ { "internalType": "string", "name": "str", "type": "string" } ], "name": "StringTooLong", "type": "error" }, { "anonymous": false, "inputs": [ { "indexed": true, "internalType": "address", "name": "owner", "type": "address" }, { "indexed": true, "internalType": "address", "name": "spender", "type": "address" }, { "indexed": false, "internalType": "uint256", "name": "value", "type": "uint256" } ], "name": "Approval", "type": "event" }, { "anonymous": false, "inputs": [], "name": "EIP712DomainChanged", "type": "event" }, { "anonymous": false, "inputs": [ { "indexed": true, "internalType": "address", "name": "previousOwner", "type": "address" }, { "indexed": true, "internalType": "address", "name": "newOwner", "type": "address" } ], "name": "OwnershipTransferred", "type": "event" }, { "anonymous": false, "inputs": [ { "indexed": true, "internalType": "address", "name": "from", "type": "address" }, { "indexed": true, "internalType": "address", "name": "to", "type": "address" }, { "indexed": false, "internalType": "uint256", "name": "value", "type": "uint256" } ], "name": "Transfer", "type": "event" }, { "inputs": [], "name": "DOMAIN_SEPARATOR", "outputs": [ { "internalType": "bytes32", "name": "", "type": "bytes32" } ], "stateMutability": "view", "type": "function" }, { "inputs": [ { "internalType": "address", "name": "owner", "type": "address" }, { "internalType": "address", "name": "spender", "type": "address" } ], "name": "allowance", "outputs": [ { "internalType": "uint256", "name": "", "type": "uint256" } ], "stateMutability": "view", "type": "function" }, { "inputs": [ { "internalType": "address", "name": "spender", "type": "address" }, { "internalType": "uint256", "name": "value", "type": "uint256" } ], "name": "approve", "outputs": [ { "internalType": "bool", "name": "", "type": "bool" } ], "stateMutability": "nonpayable", "type": "function" }, { "inputs": [ { "internalType": "address", "name": "account", "type": "address" } ], "name": "balanceOf", "outputs": [ { "internalType": "uint256", "name": "", "type": "uint256" } ], "stateMutability": "view", "type": "function" }, { "inputs": [], "name": "decimals", "outputs": [ { "internalType": "uint8", "name": "", "type": "uint8" } ], "stateMutability": "view", "type": "function" }, { "inputs": [], "name": "eip712Domain", "outputs": [ { "internalType": "bytes1", "name": "fields", "type": "bytes1" }, { "internalType": "string", "name": "name", "type": "string" }, { "internalType": "string", "name": "version", "type": "string" }, { "internalType": "uint256", "name": "chainId", "type": "uint256" }, { "internalType": "address", "name": "verifyingContract", "type": "address" }, { "internalType": "bytes32", "name": "salt", "type": "bytes32" }, { "internalType": "uint256[]", "name": "extensions", "type": "uint256[]" } ], "stateMutability": "view", "type": "function" }, { "inputs": [ { "internalType": "address", "name": "to", "type": "address" }, { "internalType": "uint256", "name": "amount", "type": "uint256" } ], "name": "mint", "outputs": [], "stateMutability": "nonpayable", "type": "function" }, { "inputs": [], "name": "name", "outputs": [ { "internalType": "string", "name": "", "type": "string" } ], "stateMutability": "view", "type": "function" }, { "inputs": [ { "internalType": "address", "name": "owner", "type": "address" } ], "name": "nonces", "outputs": [ { "internalType": "uint256", "name": "", "type": "uint256" } ], "stateMutability": "view", "type": "function" }, { "inputs": [], "name": "owner", "outputs": [ { "internalType": "address", "name": "", "type": "address" } ], "stateMutability": "view", "type": "function" }, { "inputs": [ { "internalType": "address", "name": "owner", "type": "address" }, { "internalType": "address", "name": "spender", "type": "address" }, { "internalType": "uint256", "name": "value", "type": "uint256" }, { "internalType": "uint256", "name": "deadline", "type": "uint256" }, { "internalType": "uint8", "name": "v", "type": "uint8" }, { "internalType": "bytes32", "name": "r", "type": "bytes32" }, { "internalType": "bytes32", "name": "s", "type": "bytes32" } ], "name": "permit", "outputs": [], "stateMutability": "nonpayable", "type": "function" }, { "inputs": [], "name": "renounceOwnership", "outputs": [], "stateMutability": "nonpayable", "type": "function" }, { "inputs": [], "name": "symbol", "outputs": [ { "internalType": "string", "name": "", "type": "string" } ], "stateMutability": "view", "type": "function" }, { "inputs": [], "name": "totalSupply", "outputs": [ { "internalType": "uint256", "name": "", "type": "uint256" } ], "stateMutability": "view", "type": "function" }, { "inputs": [ { "internalType": "address", "name": "to", "type": "address" }, { "internalType": "uint256", "name": "value", "type": "uint256" } ], "name": "transfer", "outputs": [ { "internalType": "bool", "name": "", "type": "bool" } ], "stateMutability": "nonpayable", "type": "function" }, { "inputs": [ { "internalType": "address", "name": "from", "type": "address" }, { "internalType": "address", "name": "to", "type": "address" }, { "internalType": "uint256", "name": "value", "type": "uint256" } ], "name": "transferFrom", "outputs": [ { "internalType": "bool", "name": "", "type": "bool" } ], "stateMutability": "nonpayable", "type": "function" }, { "inputs": [ { "internalType": "address", "name": "newOwner", "type": "address" } ], "name": "transferOwnership", "outputs": [], "stateMutability": "nonpayable", "type": "function" } ], "bytecode": "0x6101606040523480156200001257600080fd5b50604051620016743803806200167483398101604081905262000035916200030a565b6040805180820190915260018152603160f81b602082015282908190338285600362000062838262000405565b50600462000071828262000405565b5050506001600160a01b038116620000a457604051631e4fbdf760e01b8152600060048201526024015b60405180910390fd5b620000af816200016f565b50620000bd826006620001c1565b61012052620000ce816007620001c1565b61014052815160208084019190912060e052815190820120610100524660a0526200015c60e05161010051604080517f8b73c3c69bb8fe3d512ecc4cf759cc79239f7b179b0ffacaa9a75d522b39400f60208201529081019290925260608201524660808201523060a082015260009060c00160405160208183030381529060405280519060200120905090565b60805250503060c052506200052b915050565b600580546001600160a01b038381166001600160a01b0319831681179093556040519116919082907f8be0079c531659141344cd1fd0a4f28419497f9722a3daafe3b4186f6b6457e090600090a35050565b6000602083511015620001e157620001d983620001fa565b9050620001f4565b81620001ee848262000405565b5060ff90505b92915050565b600080829050601f8151111562000228578260405163305a27a960e01b81526004016200009b9190620004d1565b8051620002358262000506565b179392505050565b634e487b7160e01b600052604160045260246000fd5b60005b838110156200027057818101518382015260200162000256565b50506000910152565b600082601f8301126200028b57600080fd5b81516001600160401b0380821115620002a857620002a86200023d565b604051601f8301601f19908116603f01168101908282118183101715620002d357620002d36200023d565b81604052838152866020858801011115620002ed57600080fd5b6200030084602083016020890162000253565b9695505050505050565b600080604083850312156200031e57600080fd5b82516001600160401b03808211156200033657600080fd5b620003448683870162000279565b935060208501519150808211156200035b57600080fd5b506200036a8582860162000279565b9150509250929050565b600181811c908216806200038957607f821691505b602082108103620003aa57634e487b7160e01b600052602260045260246000fd5b50919050565b601f82111562000400576000816000526020600020601f850160051c81016020861015620003db5750805b601f850160051c820191505b81811015620003fc57828155600101620003e7565b5050505b505050565b81516001600160401b038111156200042157620004216200023d565b620004398162000432845462000374565b84620003b0565b602080601f831160018114620004715760008415620004585750858301515b600019600386901b1c1916600185901b178555620003fc565b600085815260208120601f198616915b82811015620004a25788860151825594840194600190910190840162000481565b5085821015620004c15787850151600019600388901b60f8161c191681555b5050505050600190811b01905550565b6020815260008251806020840152620004f281604085016020870162000253565b601f01601f19169190910160400192915050565b80516020808301519190811015620003aa5760001960209190910360031b1b16919050565b60805160a05160c05160e0516101005161012051610140516110ee6200058660003960006108f1015260006108c4015260006107b70152600061078f015260006106ea015260006107140152600061073e01526110ee6000f3fe608060405234801561001057600080fd5b506004361061010b5760003560e01c8063715018a6116100a257806395d89b411161007157806395d89b411461021c578063a9059cbb14610224578063d505accf14610237578063dd62ed3e1461024a578063f2fde38b1461028357600080fd5b8063715018a6146101cb5780637ecebe00146101d357806384b0196e146101e65780638da5cb5b1461020157600080fd5b8063313ce567116100de578063313ce567146101765780633644e5151461018557806340c10f191461018d57806370a08231146101a257600080fd5b806306fdde0314610110578063095ea7b31461012e57806318160ddd1461015157806323b872dd14610163575b600080fd5b610118610296565b6040516101259190610e51565b60405180910390f35b61014161013c366004610e87565b610328565b6040519015158152602001610125565b6002545b604051908152602001610125565b610141610171366004610eb1565b610342565b60405160128152602001610125565b610155610366565b6101a061019b366004610e87565b610375565b005b6101556101b0366004610eed565b6001600160a01b031660009081526020819052604090205490565b6101a06103e1565b6101556101e1366004610eed565b6103f5565b6101ee610413565b6040516101259796959493929190610f08565b6005546040516001600160a01b039091168152602001610125565b610118610459565b610141610232366004610e87565b610468565b6101a0610245366004610fa1565b610476565b610155610258366004611014565b6001600160a01b03918216600090815260016020908152604080832093909416825291909152205490565b6101a0610291366004610eed565b6105b0565b6060600380546102a590611047565b80601f01602080910402602001604051908101604052809291908181526020018280546102d190611047565b801561031e5780601f106102f35761010080835404028352916020019161031e565b820191906000526020600020905b81548152906001019060200180831161030157829003601f168201915b5050505050905090565b6000336103368185856105ee565b60019150505b92915050565b600033610350858285610600565b61035b85858561067e565b506001949350505050565b60006103706106dd565b905090565b68056bc75e2d631000008111156103d35760405162461bcd60e51b815260206004820152601c60248201527f616d6f756e74206d757374206265206c657373207468616e203130300000000060448201526064015b60405180910390fd5b6103dd8282610808565b5050565b6103e961083e565b6103f3600061086b565b565b6001600160a01b03811660009081526008602052604081205461033c565b6000606080600080600060606104276108bd565b61042f6108ea565b60408051600080825260208201909252600f60f81b9b939a50919850469750309650945092509050565b6060600480546102a590611047565b60003361033681858561067e565b8342111561049a5760405163313c898160e11b8152600481018590526024016103ca565b60007f6e71edae12b1b97f4d1f60370fef10105fa2faae0126114a169c64845d6126c98888886104e78c6001600160a01b0316600090815260086020526040902080546001810190915590565b6040805160208101969096526001600160a01b0394851690860152929091166060840152608083015260a082015260c0810186905260e001604051602081830303815290604052805190602001209050600061054282610917565b9050600061055282878787610944565b9050896001600160a01b0316816001600160a01b031614610599576040516325c0072360e11b81526001600160a01b0380831660048301528b1660248201526044016103ca565b6105a48a8a8a6105ee565b50505050505050505050565b6105b861083e565b6001600160a01b0381166105e257604051631e4fbdf760e01b8152600060048201526024016103ca565b6105eb8161086b565b50565b6105fb8383836001610972565b505050565b6001600160a01b038381166000908152600160209081526040808320938616835292905220546000198114610678578181101561066957604051637dc7a0d960e11b81526001600160a01b038416600482015260248101829052604481018390526064016103ca565b61067884848484036000610972565b50505050565b6001600160a01b0383166106a857604051634b637e8f60e11b8152600060048201526024016103ca565b6001600160a01b0382166106d25760405163ec442f0560e01b8152600060048201526024016103ca565b6105fb838383610a47565b6000306001600160a01b037f00000000000000000000000000000000000000000000000000000000000000001614801561073657507f000000000000000000000000000000000000000000000000000000000000000046145b1561076057507f000000000000000000000000000000000000000000000000000000000000000090565b610370604080517f8b73c3c69bb8fe3d512ecc4cf759cc79239f7b179b0ffacaa9a75d522b39400f60208201527f0000000000000000000000000000000000000000000000000000000000000000918101919091527f000000000000000000000000000000000000000000000000000000000000000060608201524660808201523060a082015260009060c00160405160208183030381529060405280519060200120905090565b6001600160a01b0382166108325760405163ec442f0560e01b8152600060048201526024016103ca565b6103dd60008383610a47565b6005546001600160a01b031633146103f35760405163118cdaa760e01b81523360048201526024016103ca565b600580546001600160a01b038381166001600160a01b0319831681179093556040519116919082907f8be0079c531659141344cd1fd0a4f28419497f9722a3daafe3b4186f6b6457e090600090a35050565b60606103707f00000000000000000000000000000000000000000000000000000000000000006006610b71565b60606103707f00000000000000000000000000000000000000000000000000000000000000006007610b71565b600061033c6109246106dd565b8360405161190160f01b8152600281019290925260228201526042902090565b60008060008061095688888888610c1c565b9250925092506109668282610ceb565b50909695505050505050565b6001600160a01b03841661099c5760405163e602df0560e01b8152600060048201526024016103ca565b6001600160a01b0383166109c657604051634a1406b160e11b8152600060048201526024016103ca565b6001600160a01b038085166000908152600160209081526040808320938716835292905220829055801561067857826001600160a01b0316846001600160a01b03167f8c5be1e5ebec7d5bd14f71427d1e84f3dd0314c0f7b2291e5b200ac8c7c3b92584604051610a3991815260200190565b60405180910390a350505050565b6001600160a01b038316610a72578060026000828254610a679190611081565b90915550610ae49050565b6001600160a01b03831660009081526020819052604090205481811015610ac55760405163391434e360e21b81526001600160a01b038516600482015260248101829052604481018390526064016103ca565b6001600160a01b03841660009081526020819052604090209082900390555b6001600160a01b038216610b0057600280548290039055610b1f565b6001600160a01b03821660009081526020819052604090208054820190555b816001600160a01b0316836001600160a01b03167fddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef83604051610b6491815260200190565b60405180910390a3505050565b606060ff8314610b8b57610b8483610da4565b905061033c565b818054610b9790611047565b80601f0160208091040260200160405190810160405280929190818152602001828054610bc390611047565b8015610c105780601f10610be557610100808354040283529160200191610c10565b820191906000526020600020905b815481529060010190602001808311610bf357829003601f168201915b5050505050905061033c565b600080807f7fffffffffffffffffffffffffffffff5d576e7357a4501ddfe92f46681b20a0841115610c575750600091506003905082610ce1565b604080516000808252602082018084528a905260ff891692820192909252606081018790526080810186905260019060a0016020604051602081039080840390855afa158015610cab573d6000803e3d6000fd5b5050604051601f1901519150506001600160a01b038116610cd757506000925060019150829050610ce1565b9250600091508190505b9450945094915050565b6000826003811115610cff57610cff6110a2565b03610d08575050565b6001826003811115610d1c57610d1c6110a2565b03610d3a5760405163f645eedf60e01b815260040160405180910390fd5b6002826003811115610d4e57610d4e6110a2565b03610d6f5760405163fce698f760e01b8152600481018290526024016103ca565b6003826003811115610d8357610d836110a2565b036103dd576040516335e2f38360e21b8152600481018290526024016103ca565b60606000610db183610de3565b604080516020808252818301909252919250600091906020820181803683375050509182525060208101929092525090565b600060ff8216601f81111561033c57604051632cd44ac360e21b815260040160405180910390fd5b6000815180845260005b81811015610e3157602081850181015186830182015201610e15565b506000602082860101526020601f19601f83011685010191505092915050565b602081526000610e646020830184610e0b565b9392505050565b80356001600160a01b0381168114610e8257600080fd5b919050565b60008060408385031215610e9a57600080fd5b610ea383610e6b565b946020939093013593505050565b600080600060608486031215610ec657600080fd5b610ecf84610e6b565b9250610edd60208501610e6b565b9150604084013590509250925092565b600060208284031215610eff57600080fd5b610e6482610e6b565b60ff60f81b881681526000602060e06020840152610f2960e084018a610e0b565b8381036040850152610f3b818a610e0b565b606085018990526001600160a01b038816608086015260a0850187905284810360c08601528551808252602080880193509091019060005b81811015610f8f57835183529284019291840191600101610f73565b50909c9b505050505050505050505050565b600080600080600080600060e0888a031215610fbc57600080fd5b610fc588610e6b565b9650610fd360208901610e6b565b95506040880135945060608801359350608088013560ff81168114610ff757600080fd5b9699959850939692959460a0840135945060c09093013592915050565b6000806040838503121561102757600080fd5b61103083610e6b565b915061103e60208401610e6b565b90509250929050565b600181811c9082168061105b57607f821691505b60208210810361107b57634e487b7160e01b600052602260045260246000fd5b50919050565b8082018082111561033c57634e487b7160e01b600052601160045260246000fd5b634e487b7160e01b600052602160045260246000fdfea2646970667358221220c76c3d894040a933b0e7fa69e5a0f9e25228b0d3cfde796f6163abfc9f1aae1764736f6c63430008180033", "deployedBytecode": "0x608060405234801561001057600080fd5b506004361061010b5760003560e01c8063715018a6116100a257806395d89b411161007157806395d89b411461021c578063a9059cbb14610224578063d505accf14610237578063dd62ed3e1461024a578063f2fde38b1461028357600080fd5b8063715018a6146101cb5780637ecebe00146101d357806384b0196e146101e65780638da5cb5b1461020157600080fd5b8063313ce567116100de578063313ce567146101765780633644e5151461018557806340c10f191461018d57806370a08231146101a257600080fd5b806306fdde0314610110578063095ea7b31461012e57806318160ddd1461015157806323b872dd14610163575b600080fd5b610118610296565b6040516101259190610e51565b60405180910390f35b61014161013c366004610e87565b610328565b6040519015158152602001610125565b6002545b604051908152602001610125565b610141610171366004610eb1565b610342565b60405160128152602001610125565b610155610366565b6101a061019b366004610e87565b610375565b005b6101556101b0366004610eed565b6001600160a01b031660009081526020819052604090205490565b6101a06103e1565b6101556101e1366004610eed565b6103f5565b6101ee610413565b6040516101259796959493929190610f08565b6005546040516001600160a01b039091168152602001610125565b610118610459565b610141610232366004610e87565b610468565b6101a0610245366004610fa1565b610476565b610155610258366004611014565b6001600160a01b03918216600090815260016020908152604080832093909416825291909152205490565b6101a0610291366004610eed565b6105b0565b6060600380546102a590611047565b80601f01602080910402602001604051908101604052809291908181526020018280546102d190611047565b801561031e5780601f106102f35761010080835404028352916020019161031e565b820191906000526020600020905b81548152906001019060200180831161030157829003601f168201915b5050505050905090565b6000336103368185856105ee565b60019150505b92915050565b600033610350858285610600565b61035b85858561067e565b506001949350505050565b60006103706106dd565b905090565b68056bc75e2d631000008111156103d35760405162461bcd60e51b815260206004820152601c60248201527f616d6f756e74206d757374206265206c657373207468616e203130300000000060448201526064015b60405180910390fd5b6103dd8282610808565b5050565b6103e961083e565b6103f3600061086b565b565b6001600160a01b03811660009081526008602052604081205461033c565b6000606080600080600060606104276108bd565b61042f6108ea565b60408051600080825260208201909252600f60f81b9b939a50919850469750309650945092509050565b6060600480546102a590611047565b60003361033681858561067e565b8342111561049a5760405163313c898160e11b8152600481018590526024016103ca565b60007f6e71edae12b1b97f4d1f60370fef10105fa2faae0126114a169c64845d6126c98888886104e78c6001600160a01b0316600090815260086020526040902080546001810190915590565b6040805160208101969096526001600160a01b0394851690860152929091166060840152608083015260a082015260c0810186905260e001604051602081830303815290604052805190602001209050600061054282610917565b9050600061055282878787610944565b9050896001600160a01b0316816001600160a01b031614610599576040516325c0072360e11b81526001600160a01b0380831660048301528b1660248201526044016103ca565b6105a48a8a8a6105ee565b50505050505050505050565b6105b861083e565b6001600160a01b0381166105e257604051631e4fbdf760e01b8152600060048201526024016103ca565b6105eb8161086b565b50565b6105fb8383836001610972565b505050565b6001600160a01b038381166000908152600160209081526040808320938616835292905220546000198114610678578181101561066957604051637dc7a0d960e11b81526001600160a01b038416600482015260248101829052604481018390526064016103ca565b61067884848484036000610972565b50505050565b6001600160a01b0383166106a857604051634b637e8f60e11b8152600060048201526024016103ca565b6001600160a01b0382166106d25760405163ec442f0560e01b8152600060048201526024016103ca565b6105fb838383610a47565b6000306001600160a01b037f00000000000000000000000000000000000000000000000000000000000000001614801561073657507f000000000000000000000000000000000000000000000000000000000000000046145b1561076057507f000000000000000000000000000000000000000000000000000000000000000090565b610370604080517f8b73c3c69bb8fe3d512ecc4cf759cc79239f7b179b0ffacaa9a75d522b39400f60208201527f0000000000000000000000000000000000000000000000000000000000000000918101919091527f000000000000000000000000000000000000000000000000000000000000000060608201524660808201523060a082015260009060c00160405160208183030381529060405280519060200120905090565b6001600160a01b0382166108325760405163ec442f0560e01b8152600060048201526024016103ca565b6103dd60008383610a47565b6005546001600160a01b031633146103f35760405163118cdaa760e01b81523360048201526024016103ca565b600580546001600160a01b038381166001600160a01b0319831681179093556040519116919082907f8be0079c531659141344cd1fd0a4f28419497f9722a3daafe3b4186f6b6457e090600090a35050565b60606103707f00000000000000000000000000000000000000000000000000000000000000006006610b71565b60606103707f00000000000000000000000000000000000000000000000000000000000000006007610b71565b600061033c6109246106dd565b8360405161190160f01b8152600281019290925260228201526042902090565b60008060008061095688888888610c1c565b9250925092506109668282610ceb565b50909695505050505050565b6001600160a01b03841661099c5760405163e602df0560e01b8152600060048201526024016103ca565b6001600160a01b0383166109c657604051634a1406b160e11b8152600060048201526024016103ca565b6001600160a01b038085166000908152600160209081526040808320938716835292905220829055801561067857826001600160a01b0316846001600160a01b03167f8c5be1e5ebec7d5bd14f71427d1e84f3dd0314c0f7b2291e5b200ac8c7c3b92584604051610a3991815260200190565b60405180910390a350505050565b6001600160a01b038316610a72578060026000828254610a679190611081565b90915550610ae49050565b6001600160a01b03831660009081526020819052604090205481811015610ac55760405163391434e360e21b81526001600160a01b038516600482015260248101829052604481018390526064016103ca565b6001600160a01b03841660009081526020819052604090209082900390555b6001600160a01b038216610b0057600280548290039055610b1f565b6001600160a01b03821660009081526020819052604090208054820190555b816001600160a01b0316836001600160a01b03167fddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef83604051610b6491815260200190565b60405180910390a3505050565b606060ff8314610b8b57610b8483610da4565b905061033c565b818054610b9790611047565b80601f0160208091040260200160405190810160405280929190818152602001828054610bc390611047565b8015610c105780601f10610be557610100808354040283529160200191610c10565b820191906000526020600020905b815481529060010190602001808311610bf357829003601f168201915b5050505050905061033c565b600080807f7fffffffffffffffffffffffffffffff5d576e7357a4501ddfe92f46681b20a0841115610c575750600091506003905082610ce1565b604080516000808252602082018084528a905260ff891692820192909252606081018790526080810186905260019060a0016020604051602081039080840390855afa158015610cab573d6000803e3d6000fd5b5050604051601f1901519150506001600160a01b038116610cd757506000925060019150829050610ce1565b9250600091508190505b9450945094915050565b6000826003811115610cff57610cff6110a2565b03610d08575050565b6001826003811115610d1c57610d1c6110a2565b03610d3a5760405163f645eedf60e01b815260040160405180910390fd5b6002826003811115610d4e57610d4e6110a2565b03610d6f5760405163fce698f760e01b8152600481018290526024016103ca565b6003826003811115610d8357610d836110a2565b036103dd576040516335e2f38360e21b8152600481018290526024016103ca565b60606000610db183610de3565b604080516020808252818301909252919250600091906020820181803683375050509182525060208101929092525090565b600060ff8216601f81111561033c57604051632cd44ac360e21b815260040160405180910390fd5b6000815180845260005b81811015610e3157602081850181015186830182015201610e15565b506000602082860101526020601f19601f83011685010191505092915050565b602081526000610e646020830184610e0b565b9392505050565b80356001600160a01b0381168114610e8257600080fd5b919050565b60008060408385031215610e9a57600080fd5b610ea383610e6b565b946020939093013593505050565b600080600060608486031215610ec657600080fd5b610ecf84610e6b565b9250610edd60208501610e6b565b9150604084013590509250925092565b600060208284031215610eff57600080fd5b610e6482610e6b565b60ff60f81b881681526000602060e06020840152610f2960e084018a610e0b565b8381036040850152610f3b818a610e0b565b606085018990526001600160a01b038816608086015260a0850187905284810360c08601528551808252602080880193509091019060005b81811015610f8f57835183529284019291840191600101610f73565b50909c9b505050505050505050505050565b600080600080600080600060e0888a031215610fbc57600080fd5b610fc588610e6b565b9650610fd360208901610e6b565b95506040880135945060608801359350608088013560ff81168114610ff757600080fd5b9699959850939692959460a0840135945060c09093013592915050565b6000806040838503121561102757600080fd5b61103083610e6b565b915061103e60208401610e6b565b90509250929050565b600181811c9082168061105b57607f821691505b60208210810361107b57634e487b7160e01b600052602260045260246000fd5b50919050565b8082018082111561033c57634e487b7160e01b600052601160045260246000fd5b634e487b7160e01b600052602160045260246000fdfea2646970667358221220c76c3d894040a933b0e7fa69e5a0f9e25228b0d3cfde796f6163abfc9f1aae1764736f6c63430008180033", "linkReferences": {}, "deployedLinkReferences": {} } ================================================ FILE: 02-Basic Staking Full Stack Dapp/frontend/src/index.css ================================================ ================================================ FILE: 02-Basic Staking Full Stack Dapp/frontend/src/index.js ================================================ import React from 'react'; import ReactDOM from 'react-dom/client'; import './index.css'; import App from './App'; import reportWebVitals from './reportWebVitals'; const root = ReactDOM.createRoot(document.getElementById('root')); root.render( ); // If you want to start measuring performance in your app, pass a function // to log results (for example: reportWebVitals(console.log)) // or send to an analytics endpoint. Learn more: https://bit.ly/CRA-vitals reportWebVitals(); ================================================ FILE: 02-Basic Staking Full Stack Dapp/frontend/src/reportWebVitals.js ================================================ const reportWebVitals = onPerfEntry => { if (onPerfEntry && onPerfEntry instanceof Function) { import('web-vitals').then(({ getCLS, getFID, getFCP, getLCP, getTTFB }) => { getCLS(onPerfEntry); getFID(onPerfEntry); getFCP(onPerfEntry); getLCP(onPerfEntry); getTTFB(onPerfEntry); }); } }; export default reportWebVitals; ================================================ FILE: 02-Basic Staking Full Stack Dapp/frontend/src/setupTests.js ================================================ // jest-dom adds custom jest matchers for asserting on DOM nodes. // allows you to do things like: // expect(element).toHaveTextContent(/react/i) // learn more: https://github.com/testing-library/jest-dom import '@testing-library/jest-dom'; ================================================ FILE: 02-Basic Staking Full Stack Dapp/hardhat.config.js ================================================ /** * @type import('hardhat/config').HardhatUserConfig */ require('@nomiclabs/hardhat-ethers'); require("@nomiclabs/hardhat-waffle"); require("dotenv").config(); const PRIVATE_KEY = process.env.PRIVATE_KEY; module.exports = { defaultNetwork: 'core_testnet', networks: { hardhat: { }, core_testnet: { url: 'https://rpc.test2.btcs.network', accounts: [PRIVATE_KEY], chainId: 1114, } }, solidity: { compilers: [ { version: '0.8.24', settings: { evmVersion: 'shanghai', optimizer: { enabled: true, runs: 200, }, }, }, ], }, paths: { sources: './contracts', cache: './cache', artifacts: './artifacts', }, mocha: { timeout: 20000, }, }; ================================================ FILE: 02-Basic Staking Full Stack Dapp/ignition/modules/Lock.js ================================================ const { buildModule } = require("@nomicfoundation/hardhat-ignition/modules"); const JAN_1ST_2030 = 1893456000; const ONE_GWEI = 1_000_000_000n; module.exports = buildModule("LockModule", (m) => { const unlockTime = m.getParameter("unlockTime", JAN_1ST_2030); const lockedAmount = m.getParameter("lockedAmount", ONE_GWEI); const lock = m.contract("Lock", [unlockTime], { value: lockedAmount, }); return { lock }; }); ================================================ FILE: 02-Basic Staking Full Stack Dapp/package.json ================================================ { "name": "staking-dapp", "version": "1.0.0", "description": "", "main": "index.js", "scripts": { "test": "echo \"Error: no test specified\" && exit 1" }, "keywords": [], "author": "", "license": "ISC", "dependencies": { "@nomiclabs/hardhat-ethers": "^2.2.3", "@nomiclabs/hardhat-waffle": "^2.0.6", "@rainbow-me/rainbowkit": "^2.1.3", "@web3-react/core": "^8.2.3", "@web3-react/injected-connector": "^6.0.7", "chai": "^5.1.1", "dotenv": "^16.5.0", "ethereum-waffle": "^4.0.10", "ethers": "^5.7.2" }, "devDependencies": { "@openzeppelin/contracts": "^5.0.2", "hardhat": "^2.22.6" } } ================================================ FILE: 02-Basic Staking Full Stack Dapp/scripts/deploy.js ================================================ const { ethers } = require("hardhat"); async function main() { const [deployer] = await ethers.getSigners(); console.log("Deploying contracts with the account:", deployer.address); const StakingToken = await ethers.getContractFactory("StakingToken"); const stakingToken = await StakingToken.deploy("Staking Token", "STK"); const RewardToken = await ethers.getContractFactory("RewardToken"); const rewardToken = await RewardToken.deploy("Reward Token", "RTK"); const StakingDapp = await ethers.getContractFactory("StakingDapp"); const stakingDapp = await StakingDapp.deploy(stakingToken.address, rewardToken.address); console.log("Contracts deployed:"); console.log("Staking Token:", stakingToken.address); console.log("Reward Token:", rewardToken.address); console.log("Staking Dapp:", stakingDapp.address); } main() .then(() => process.exit(0)) .catch((error) => { console.error(error); process.exit(1); }); ================================================ FILE: 03-Decentralized Guestbook/.gitignore ================================================ # Node.js dependencies /node_modules # Hardhat artifacts /artifacts /cache # Environment and secret files .env .secret.json # Log files npm-debug.log* yarn-debug.log* yarn-error.log* # Ignore build output /build # Miscellaneous .DS_Store ================================================ FILE: 03-Decentralized Guestbook/README.md ================================================ # Guestbook dApp Tutorial / Boilerplate ## Overview This guide will walk you through creating a decentralized guestbook application using Hardhat for development, Solidity for smart contracts, and React for the frontend. This setup is tailored for the Core network. By following this tutorial, you'll learn how to: - Develop and deploy smart contracts on the Core Testnet. - Build a React frontend to interact with your smart contracts. - Integrate MetaMask for secure user interactions and transactions. ## Why Use This Boilerplate? - **Decentralization**: Store guestbook entries on the blockchain, ensuring data integrity and transparency. - **Security**: Immutable and tamper-proof records stored on the blockchain. - **Transparency**: All entries and transactions are publicly visible and verifiable. - **Real-World Applications**: Ideal for creating transparent feedback systems, community engagement tools, or personal guestbooks. ## Prerequisites Before getting started, ensure you have the following: - **Node.js**: Install Node.js from [nodejs.org](https://nodejs.org/). - **npm**: Node.js includes npm (Node Package Manager). - **MetaMask**: Install the MetaMask browser extension from [metamask.io](https://metamask.io/). - **Core Testnet Configuration**: Configure MetaMask to connect to the Core Testnet. - **Network Name**: Core Testnet - **New RPC URL**: `https://rpc.test.btcs.network` - **Chain ID**: `1115` - **Currency Symbol**: `CORE` - **Text Editor**: Use a text editor like Visual Studio Code. - **Core Faucet**: To get test CORE tokens for transactions, visit the [Core Faucet](https://scan.test.btcs.network/faucet) and refer to the [instructions for use](https://docs.coredao.org/docs/Dev-Guide/core-faucet). ## Project Setup ### 1. Initialize the Project Create a new directory for your project and navigate into it: ```sh mkdir guestbook-dapp cd guestbook-dapp npm init --yes ``` gdscreenshot1 ## 2. Install Dependencies Install Hardhat and other necessary dependencies: ``` npm install --save-dev hardhat @nomiclabs/hardhat-ethers ethers npm install --save-dev chai @nomiclabs/hardhat-waffle npm install react react-dom ``` gdscreenshot2 3. Set Up Hardhat Initialize a new Hardhat project: ``` npx hardhat ``` gdscreenshot3 Select "Create a Javascript Project" and "no" for installing the project's sample dependencies. We will now open up our newly created hardhat project in a code editor, for this guide, we will be using Visual Studio Code. navigate to the root of your directory in the terminal and type `code .` and hit enter ## 4. Create secret.json File Create a secret.json file in the root directory of your project to store your private key securely. Replace YOUR_PRIVATE_KEY with your actual private key. ``` { "PrivateKey": "YOUR_PRIVATE_KEY" } ``` gdscreenshot5 > [Refer to this guide](https://support.metamask.io/managing-my-wallet/secret-recovery-phrase-and-private-keys/how-to-export-an-accounts-private-key/) for instructions on how to export your account's private key via Metamask. ## 5. Update .gitignore File Update your .gitignore file to ensure that your secret.json file and other sensitive files are not committed to version control. Create or update the .gitignore file in your root directory with the following content: ``` # Node.js dependencies /node_modules # Hardhat artifacts /artifacts /cache # Environment and secret files .env .secret.json # Log files npm-debug.log* yarn-debug.log* yarn-error.log* # Ignore build output /build # Miscellaneous .DS_Store ``` ## 6. Update hardhat.config.js Replace the contents of hardhat.config.js with the following configuration: Ensure that the network settings are configured correctly for [Core Testnet](https://docs.coredao.org/docs/Dev-Guide/contract-verify#hardhat-verification) ``` /** * @type import('hardhat/config').HardhatUserConfig */ require('@nomiclabs/hardhat-ethers'); require("@nomiclabs/hardhat-waffle"); const { PrivateKey } = require('./secret.json'); module.exports = { defaultNetwork: 'testnet', networks: { hardhat: { }, testnet: { url: 'https://rpc.test2.btcs.network', accounts: [PRIVATE_KEY], chainId: 1115, // Ensure this matches the Core testnet chain ID } }, solidity: { compilers: [ { version: '0.8.21', // Update to at least 0.8.20 to support the 'paris' EVM settings: { evmVersion: 'paris', // Specify 'paris' EVM version optimizer: { enabled: true, runs: 200, }, }, }, ], }, paths: { sources: './contracts', cache: './cache', artifacts: './artifacts', }, mocha: { timeout: 20000, // You can adjust the timeout as needed }, }; ``` gdscreenshot5 1 ## Writing the Smart Contract 1. Create the Guestbook Smart Contract Delete the `lock.sol` file in `Contracts` Create a file `contracts/Guestbook.sol` with the following content: ``` // SPDX-License-Identifier: GPL-3.0 pragma solidity >=0.7.0 <0.9.0; /// @title Guestbook contract Guestbook { struct Entry { string name; string message; } Entry[] public entries; function signGuestbook(string memory _name, string memory _message) public { entries.push(Entry(_name, _message)); } function getEntries() public view returns (Entry[] memory) { return entries; } } ``` gdscreenshot6 ## Deploying the Smart Contract 1. Create Deployment Script Create a file scripts/deploy.js with the following content: ``` const hre = require("hardhat"); async function main() { await hre.run('compile'); // Ensure the contracts are compiled const Guestbook = await hre.ethers.getContractFactory("Guestbook"); const guestbook = await Guestbook.deploy(); await guestbook.deployed(); console.log("Guestbook contract deployed to:", guestbook.address); } main().catch((error) => { console.error(error); process.exitCode = 1; }); ``` gdscreenshot7 2. Deploy the Contract Deploy the contract to the Core network: ``` npx hardhat run scripts/deploy.js --network testnet ``` gdscreenshot8 ## Setting Up the React Frontend 1. Create the React App Create the basic structure for a React frontend: ``` npx create-react-app frontend cd frontend ``` gdscreenshot9 gdscreenshot10 3. Add GuestbookAbi.json Copy the Guestbook.json file from artifacts/contracts/Guestbook.sol/ to the frontend/src directory and rename it to GuestbookAbi.json. Ensure you replace placeholders like `YOUR_CONTRACT_ADDRESS` with actual values from your deployment. gdscreenshot11 gdscreenshot12 5. Update frontend/src/App.js Create or update the src/App.js file with the following content: ``` import React, { useState, useEffect } from 'react'; import { ethers } from 'ethers'; import GuestbookArtifact from './GuestbookAbi.json'; // Import the entire JSON artifact const contractAddress = 'YOUR_CONTRACT_ADDRESS'; // Replace with your deployed contract address const GuestbookAbi = GuestbookArtifact.abi; // Extract the ABI function App() { const [contract, setContract] = useState(null); const [entries, setEntries] = useState([]); const [name, setName] = useState(""); const [message, setMessage] = useState(""); const [loading, setLoading] = useState(true); const [error, setError] = useState(""); useEffect(() => { const init = async () => { if (window.ethereum) { try { console.log("Connecting to MetaMask..."); const provider = new ethers.providers.Web3Provider(window.ethereum); await provider.send("eth_requestAccounts", []); // Request account access if needed const network = await provider.getNetwork(); if (network.chainId !== 1115) { throw new Error("Please switch to the Core Testnet in MetaMask."); } const signer = provider.getSigner(); console.log("Signer obtained:", signer); const tempContract = new ethers.Contract(contractAddress, GuestbookAbi, signer); setContract(tempContract); console.log("Contract initialized:", tempContract); const entries = await tempContract.getEntries(); setEntries(entries); console.log("Entries loaded:", entries); } catch (error) { console.error("Error connecting to contract:", error); setError(error.message); } finally { setLoading(false); } } else { console.error("Please install MetaMask!"); setError("Please install MetaMask!"); setLoading(false); } }; init(); }, []); const signGuestbook = async () => { if (!contract) { console.error("Contract is not initialized!"); setError("Contract is not initialized!"); return; } try { console.log("Signing guestbook with:", name, message); const tx = await contract.signGuestbook(name, message, { gasLimit: 300000, // Adjust gas limit as necessary }); console.log("Transaction sent:", tx); await tx.wait(); // Wait for the transaction to be mined console.log("Transaction mined:", tx); const updatedEntries = await contract.getEntries(); setEntries(updatedEntries); console.log("Updated entries:", updatedEntries); } catch (error) { console.error("Error signing guestbook:", error); setError("Error signing guestbook. Please try again."); } }; return (

Guestbook DApp

{loading ? (

Loading contract...

) : ( <> {error &&

{error}

} setName(e.target.value)} /> setMessage(e.target.value)} />
    {entries.map((entry, index) => (
  • {entry.name}: {entry.message}
  • ))}
)}
); } export default App; ``` gdscreenshot13 Start the React app: >Ensure you are in /frontend within your repository (`cd frontend`) ``` npm start ``` You will be redirected to the development server gdscreenshot14 > In this example, we've already submitted our response, so we will navigate to the [Core Explorer](scan.coredao.org). Here you can see, the transaction has been submitted successfully. gdscreenshot16 The dapp webpage will update, and you will notice the feed on the UI has been updated with your your name and message. gdscreenshot15 ## Deploying the Frontend If you want your DApp to be accessible even when your local server is not running, consider deploying your frontend to a hosting service. Here are some common options: GitHub Pages: Free hosting for static sites directly from your GitHub repository. Netlify: A popular choice for deploying static sites with easy CI/CD integration. Vercel: Another popular choice, especially for React applications. AWS S3 + CloudFront: For more control over hosting and scaling. By deploying your frontend to one of these services, users can access your DApp from anywhere without needing your local development server to be running. ## Conclusion By following these steps, you should have a basic decentralized guestbook application deployed on the Core Test network with a React frontend to interact with it. You can clone this repository to use as a boilerplate, or an educational resource. ================================================ FILE: 03-Decentralized Guestbook/contracts/Guestbook.sol ================================================ // SPDX-License-Identifier: GPL-3.0 pragma solidity >=0.7.0 <0.9.0; /// @title Guestbook contract Guestbook { struct Entry { string name; string message; } Entry[] public entries; // Define an event to log new entries event EntrySigned(string name, string message); function signGuestbook(string memory _name, string memory _message) public { entries.push(Entry(_name, _message)); // Emit the event when a new entry is added emit EntrySigned(_name, _message); } function getEntries() public view returns (Entry[] memory) { return entries; } } ================================================ FILE: 03-Decentralized Guestbook/frontend/.gitignore ================================================ # See https://help.github.com/articles/ignoring-files/ for more about ignoring files. # dependencies /node_modules /.pnp .pnp.js # testing /coverage # production /build # misc .DS_Store .env.local .env.development.local .env.test.local .env.production.local npm-debug.log* yarn-debug.log* yarn-error.log* ================================================ FILE: 03-Decentralized Guestbook/frontend/README.md ================================================ # Getting Started with Create React App This project was bootstrapped with [Create React App](https://github.com/facebook/create-react-app). ## Available Scripts In the project directory, you can run: ### `npm start` Runs the app in the development mode.\ Open [http://localhost:3000](http://localhost:3000) to view it in your browser. The page will reload when you make changes.\ You may also see any lint errors in the console. ### `npm test` Launches the test runner in the interactive watch mode.\ See the section about [running tests](https://facebook.github.io/create-react-app/docs/running-tests) for more information. ### `npm run build` Builds the app for production to the `build` folder.\ It correctly bundles React in production mode and optimizes the build for the best performance. The build is minified and the filenames include the hashes.\ Your app is ready to be deployed! See the section about [deployment](https://facebook.github.io/create-react-app/docs/deployment) for more information. ### `npm run eject` **Note: this is a one-way operation. Once you `eject`, you can't go back!** If you aren't satisfied with the build tool and configuration choices, you can `eject` at any time. This command will remove the single build dependency from your project. Instead, it will copy all the configuration files and the transitive dependencies (webpack, Babel, ESLint, etc) right into your project so you have full control over them. All of the commands except `eject` will still work, but they will point to the copied scripts so you can tweak them. At this point you're on your own. You don't have to ever use `eject`. The curated feature set is suitable for small and middle deployments, and you shouldn't feel obligated to use this feature. However we understand that this tool wouldn't be useful if you couldn't customize it when you are ready for it. ## Learn More You can learn more in the [Create React App documentation](https://facebook.github.io/create-react-app/docs/getting-started). To learn React, check out the [React documentation](https://reactjs.org/). ### Code Splitting This section has moved here: [https://facebook.github.io/create-react-app/docs/code-splitting](https://facebook.github.io/create-react-app/docs/code-splitting) ### Analyzing the Bundle Size This section has moved here: [https://facebook.github.io/create-react-app/docs/analyzing-the-bundle-size](https://facebook.github.io/create-react-app/docs/analyzing-the-bundle-size) ### Making a Progressive Web App This section has moved here: [https://facebook.github.io/create-react-app/docs/making-a-progressive-web-app](https://facebook.github.io/create-react-app/docs/making-a-progressive-web-app) ### Advanced Configuration This section has moved here: [https://facebook.github.io/create-react-app/docs/advanced-configuration](https://facebook.github.io/create-react-app/docs/advanced-configuration) ### Deployment This section has moved here: [https://facebook.github.io/create-react-app/docs/deployment](https://facebook.github.io/create-react-app/docs/deployment) ### `npm run build` fails to minify This section has moved here: [https://facebook.github.io/create-react-app/docs/troubleshooting#npm-run-build-fails-to-minify](https://facebook.github.io/create-react-app/docs/troubleshooting#npm-run-build-fails-to-minify) ================================================ FILE: 03-Decentralized Guestbook/frontend/package.json ================================================ { "name": "frontend", "version": "0.1.0", "private": true, "dependencies": { "@testing-library/jest-dom": "5.17.0", "@testing-library/react": "13.4.0", "@testing-library/user-event": "13.5.0", "ethers": "5.6.9", "react": "18.3.1", "react-dom": "18.3.1", "react-scripts": "5.0.1", "web-vitals": "2.1.4" }, "scripts": { "start": "react-scripts start", "build": "react-scripts build", "test": "react-scripts test", "eject": "react-scripts eject" }, "eslintConfig": { "extends": [ "react-app", "react-app/jest" ] }, "browserslist": { "production": [ ">0.2%", "not dead", "not op_mini all" ], "development": [ "last 1 chrome version", "last 1 firefox version", "last 1 safari version" ] } } ================================================ FILE: 03-Decentralized Guestbook/frontend/public/index.html ================================================ React App
================================================ FILE: 03-Decentralized Guestbook/frontend/public/manifest.json ================================================ { "short_name": "React App", "name": "Create React App Sample", "icons": [ { "src": "favicon.ico", "sizes": "64x64 32x32 24x24 16x16", "type": "image/x-icon" }, { "src": "logo192.png", "type": "image/png", "sizes": "192x192" }, { "src": "logo512.png", "type": "image/png", "sizes": "512x512" } ], "start_url": ".", "display": "standalone", "theme_color": "#000000", "background_color": "#ffffff" } ================================================ FILE: 03-Decentralized Guestbook/frontend/public/robots.txt ================================================ # https://www.robotstxt.org/robotstxt.html User-agent: * Disallow: ================================================ FILE: 03-Decentralized Guestbook/frontend/src/App.css ================================================ .App { text-align: center; } .App-logo { height: 40vmin; pointer-events: none; } @media (prefers-reduced-motion: no-preference) { .App-logo { animation: App-logo-spin infinite 20s linear; } } .App-header { background-color: #282c34; min-height: 100vh; display: flex; flex-direction: column; align-items: center; justify-content: center; font-size: calc(10px + 2vmin); color: white; } .App-link { color: #61dafb; } @keyframes App-logo-spin { from { transform: rotate(0deg); } to { transform: rotate(360deg); } } ================================================ FILE: 03-Decentralized Guestbook/frontend/src/App.js ================================================ import React, { useState, useEffect } from 'react'; import { ethers } from 'ethers'; // Updated import for Web3Provider import { Contract } from 'ethers'; import GuestbookArtifact from './GuestbookAbi.json'; const contractAddress = '0x2e8EDe4E6A5Fd2d93072dBcF1BBe324Ff1677302'; const GuestbookAbi = GuestbookArtifact.abi; function App() { const [contract, setContract] = useState(null); const [entries, setEntries] = useState([]); const [name, setName] = useState(""); const [message, setMessage] = useState(""); const [loading, setLoading] = useState(true); const [error, setError] = useState(""); useEffect(() => { const init = async () => { if (window.ethereum) { try { console.log("Connecting to MetaMask..."); const provider = new ethers.providers.Web3Provider(window.ethereum); // Updated to Web3Provider await provider.send("eth_requestAccounts", []); const network = await provider.getNetwork(); if (network.chainId !== 1114) { throw new Error("Please switch to the Core Testnet in MetaMask."); } const signer = provider.getSigner(); console.log("Signer obtained:", signer); const tempContract = new Contract(contractAddress, GuestbookAbi, signer); setContract(tempContract); console.log("Contract initialized:", tempContract); const entries = await tempContract.getEntries(); setEntries(entries); console.log("Entries loaded:", entries); } catch (error) { console.error("Error connecting to contract:", error); setError(error.message); } finally { setLoading(false); } } else { console.error("Please install MetaMask!"); setError("Please install MetaMask!"); setLoading(false); } }; init(); }, []); const signGuestbook = async () => { if (!contract) { console.error("Contract is not initialized!"); setError("Contract is not initialized!"); return; } try { console.log("Signing guestbook with:", name, message); const tx = await contract.signGuestbook(name, message, { gasLimit: 300000, }); console.log("Transaction sent:", tx); await tx.wait(); const updatedEntries = await contract.getEntries(); setEntries(updatedEntries); console.log("Updated entries:", updatedEntries); } catch (error) { console.error("Error signing guestbook:", error); setError("Error signing guestbook. Please try again."); } }; return (

Guestbook DApp

{loading ? (

Loading contract...

) : ( <> {error &&

{error}

} setName(e.target.value)} /> setMessage(e.target.value)} />
    {entries.map((entry, index) => (
  • {entry.name}: {entry.message}
  • ))}
)}
); } export default App; ================================================ FILE: 03-Decentralized Guestbook/frontend/src/GuestbookAbi.json ================================================ { "_format": "hh-sol-artifact-1", "contractName": "Guestbook", "sourceName": "contracts/Guestbook.sol", "abi": [ { "anonymous": false, "inputs": [ { "indexed": false, "internalType": "string", "name": "name", "type": "string" }, { "indexed": false, "internalType": "string", "name": "message", "type": "string" } ], "name": "EntrySigned", "type": "event" }, { "inputs": [ { "internalType": "uint256", "name": "", "type": "uint256" } ], "name": "entries", "outputs": [ { "internalType": "string", "name": "name", "type": "string" }, { "internalType": "string", "name": "message", "type": "string" } ], "stateMutability": "view", "type": "function" }, { "inputs": [], "name": "getEntries", "outputs": [ { "components": [ { "internalType": "string", "name": "name", "type": "string" }, { "internalType": "string", "name": "message", "type": "string" } ], "internalType": "struct Guestbook.Entry[]", "name": "", "type": "tuple[]" } ], "stateMutability": "view", "type": "function" }, { "inputs": [ { "internalType": "string", "name": "_name", "type": "string" }, { "internalType": "string", "name": "_message", "type": "string" } ], "name": "signGuestbook", "outputs": [], "stateMutability": "nonpayable", "type": "function" } ], "bytecode": "0x608060405234801561001057600080fd5b50610741806100206000396000f3fe608060405234801561001057600080fd5b50600436106100415760003560e01c80630ffcb0701461004657806317be85c31461005b578063b30906d414610079575b600080fd5b610059610054366004610553565b61009a565b005b610063610150565b6040516100709190610604565b60405180910390f35b61008c610087366004610689565b6102d3565b6040516100709291906106a2565b604080518082019091528281526020808201839052600080546001810182559080528251805160029092027f290decd9548b62a8d60345a988386fc84ba6bc95484008f6362f93160ef3e56301926100f792849290910190610417565b5060208281015180516101109260018501920190610417565b5050507f0e8857b20aec2f13bb24d8ba5def534d3e73aa79fec2bcfd038c4d55e482deaa82826040516101449291906106a2565b60405180910390a15050565b60606000805480602002602001604051908101604052809291908181526020016000905b828210156102ca57838290600052602060002090600202016040518060400160405290816000820180546101a7906106d0565b80601f01602080910402602001604051908101604052809291908181526020018280546101d3906106d0565b80156102205780601f106101f557610100808354040283529160200191610220565b820191906000526020600020905b81548152906001019060200180831161020357829003601f168201915b50505050508152602001600182018054610239906106d0565b80601f0160208091040260200160405190810160405280929190818152602001828054610265906106d0565b80156102b25780601f10610287576101008083540402835291602001916102b2565b820191906000526020600020905b81548152906001019060200180831161029557829003601f168201915b50505050508152505081526020019060010190610174565b50505050905090565b600081815481106102e357600080fd5b9060005260206000209060020201600091509050806000018054610306906106d0565b80601f0160208091040260200160405190810160405280929190818152602001828054610332906106d0565b801561037f5780601f106103545761010080835404028352916020019161037f565b820191906000526020600020905b81548152906001019060200180831161036257829003601f168201915b505050505090806001018054610394906106d0565b80601f01602080910402602001604051908101604052809291908181526020018280546103c0906106d0565b801561040d5780601f106103e25761010080835404028352916020019161040d565b820191906000526020600020905b8154815290600101906020018083116103f057829003601f168201915b5050505050905082565b828054610423906106d0565b90600052602060002090601f016020900481019282610445576000855561048b565b82601f1061045e57805160ff191683800117855561048b565b8280016001018555821561048b579182015b8281111561048b578251825591602001919060010190610470565b5061049792915061049b565b5090565b5b80821115610497576000815560010161049c565b634e487b7160e01b600052604160045260246000fd5b600082601f8301126104d757600080fd5b813567ffffffffffffffff808211156104f2576104f26104b0565b604051601f8301601f19908116603f0116810190828211818310171561051a5761051a6104b0565b8160405283815286602085880101111561053357600080fd5b836020870160208301376000602085830101528094505050505092915050565b6000806040838503121561056657600080fd5b823567ffffffffffffffff8082111561057e57600080fd5b61058a868387016104c6565b935060208501359150808211156105a057600080fd5b506105ad858286016104c6565b9150509250929050565b6000815180845260005b818110156105dd576020818501810151868301820152016105c1565b818111156105ef576000602083870101525b50601f01601f19169290920160200192915050565b60006020808301818452808551808352604092508286019150828160051b87010184880160005b8381101561067b57888303603f190185528151805187855261064f888601826105b7565b91890151858303868b015291905061066781836105b7565b96890196945050509086019060010161062b565b509098975050505050505050565b60006020828403121561069b57600080fd5b5035919050565b6040815260006106b560408301856105b7565b82810360208401526106c781856105b7565b95945050505050565b600181811c908216806106e457607f821691505b6020821081141561070557634e487b7160e01b600052602260045260246000fd5b5091905056fea2646970667358221220de103d949600ba48036fe9ffaeb124297b28761f8942a55ba1c54f20c27d399964736f6c63430008090033", "deployedBytecode": "0x608060405234801561001057600080fd5b50600436106100415760003560e01c80630ffcb0701461004657806317be85c31461005b578063b30906d414610079575b600080fd5b610059610054366004610553565b61009a565b005b610063610150565b6040516100709190610604565b60405180910390f35b61008c610087366004610689565b6102d3565b6040516100709291906106a2565b604080518082019091528281526020808201839052600080546001810182559080528251805160029092027f290decd9548b62a8d60345a988386fc84ba6bc95484008f6362f93160ef3e56301926100f792849290910190610417565b5060208281015180516101109260018501920190610417565b5050507f0e8857b20aec2f13bb24d8ba5def534d3e73aa79fec2bcfd038c4d55e482deaa82826040516101449291906106a2565b60405180910390a15050565b60606000805480602002602001604051908101604052809291908181526020016000905b828210156102ca57838290600052602060002090600202016040518060400160405290816000820180546101a7906106d0565b80601f01602080910402602001604051908101604052809291908181526020018280546101d3906106d0565b80156102205780601f106101f557610100808354040283529160200191610220565b820191906000526020600020905b81548152906001019060200180831161020357829003601f168201915b50505050508152602001600182018054610239906106d0565b80601f0160208091040260200160405190810160405280929190818152602001828054610265906106d0565b80156102b25780601f10610287576101008083540402835291602001916102b2565b820191906000526020600020905b81548152906001019060200180831161029557829003601f168201915b50505050508152505081526020019060010190610174565b50505050905090565b600081815481106102e357600080fd5b9060005260206000209060020201600091509050806000018054610306906106d0565b80601f0160208091040260200160405190810160405280929190818152602001828054610332906106d0565b801561037f5780601f106103545761010080835404028352916020019161037f565b820191906000526020600020905b81548152906001019060200180831161036257829003601f168201915b505050505090806001018054610394906106d0565b80601f01602080910402602001604051908101604052809291908181526020018280546103c0906106d0565b801561040d5780601f106103e25761010080835404028352916020019161040d565b820191906000526020600020905b8154815290600101906020018083116103f057829003601f168201915b5050505050905082565b828054610423906106d0565b90600052602060002090601f016020900481019282610445576000855561048b565b82601f1061045e57805160ff191683800117855561048b565b8280016001018555821561048b579182015b8281111561048b578251825591602001919060010190610470565b5061049792915061049b565b5090565b5b80821115610497576000815560010161049c565b634e487b7160e01b600052604160045260246000fd5b600082601f8301126104d757600080fd5b813567ffffffffffffffff808211156104f2576104f26104b0565b604051601f8301601f19908116603f0116810190828211818310171561051a5761051a6104b0565b8160405283815286602085880101111561053357600080fd5b836020870160208301376000602085830101528094505050505092915050565b6000806040838503121561056657600080fd5b823567ffffffffffffffff8082111561057e57600080fd5b61058a868387016104c6565b935060208501359150808211156105a057600080fd5b506105ad858286016104c6565b9150509250929050565b6000815180845260005b818110156105dd576020818501810151868301820152016105c1565b818111156105ef576000602083870101525b50601f01601f19169290920160200192915050565b60006020808301818452808551808352604092508286019150828160051b87010184880160005b8381101561067b57888303603f190185528151805187855261064f888601826105b7565b91890151858303868b015291905061066781836105b7565b96890196945050509086019060010161062b565b509098975050505050505050565b60006020828403121561069b57600080fd5b5035919050565b6040815260006106b560408301856105b7565b82810360208401526106c781856105b7565b95945050505050565b600181811c908216806106e457607f821691505b6020821081141561070557634e487b7160e01b600052602260045260246000fd5b5091905056fea2646970667358221220de103d949600ba48036fe9ffaeb124297b28761f8942a55ba1c54f20c27d399964736f6c63430008090033", "linkReferences": {}, "deployedLinkReferences": {} } ================================================ FILE: 03-Decentralized Guestbook/frontend/src/index.css ================================================ body { margin: 0; font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'Roboto', 'Oxygen', 'Ubuntu', 'Cantarell', 'Fira Sans', 'Droid Sans', 'Helvetica Neue', sans-serif; -webkit-font-smoothing: antialiased; -moz-osx-font-smoothing: grayscale; } code { font-family: source-code-pro, Menlo, Monaco, Consolas, 'Courier New', monospace; } ================================================ FILE: 03-Decentralized Guestbook/frontend/src/index.js ================================================ import React from 'react'; import ReactDOM from 'react-dom/client'; import './index.css'; import App from './App'; import reportWebVitals from './reportWebVitals'; const root = ReactDOM.createRoot(document.getElementById('root')); root.render( ); // If you want to start measuring performance in your app, pass a function // to log results (for example: reportWebVitals(console.log)) // or send to an analytics endpoint. Learn more: https://bit.ly/CRA-vitals reportWebVitals(); ================================================ FILE: 03-Decentralized Guestbook/frontend/src/reportWebVitals.js ================================================ const reportWebVitals = onPerfEntry => { if (onPerfEntry && onPerfEntry instanceof Function) { import('web-vitals').then(({ getCLS, getFID, getFCP, getLCP, getTTFB }) => { getCLS(onPerfEntry); getFID(onPerfEntry); getFCP(onPerfEntry); getLCP(onPerfEntry); getTTFB(onPerfEntry); }); } }; export default reportWebVitals; ================================================ FILE: 03-Decentralized Guestbook/frontend/src/setupTests.js ================================================ // jest-dom adds custom jest matchers for asserting on DOM nodes. // allows you to do things like: // expect(element).toHaveTextContent(/react/i) // learn more: https://github.com/testing-library/jest-dom import '@testing-library/jest-dom'; ================================================ FILE: 03-Decentralized Guestbook/hardhat.config.js ================================================ require("@nomicfoundation/hardhat-toolbox"); require("dotenv").config(); /** @type import('hardhat/config').HardhatUserConfig */ const PRIVATE_KEY = process.env.PRIVATE_KEY; module.exports = { solidity: "0.8.28", networks: { localhost: { url: "http://127.0.0.1:8545/", // accounts: Thanks hardhat! chainId: 31337, allowUnlimitedContractSize: true, }, core: { url: 'https://rpc.test2.btcs.network', accounts: [PRIVATE_KEY], chainId: 1114, }, }, }; ================================================ FILE: 03-Decentralized Guestbook/package.json ================================================ { "name": "guestbook-dapp", "version": "1.0.0", "main": "index.js", "scripts": { "test": "echo \"Error: no test specified\" && exit 1" }, "keywords": [], "author": "", "license": "ISC", "description": "", "devDependencies": { "@nomicfoundation/hardhat-chai-matchers": "^2.0.8", "@nomicfoundation/hardhat-ethers": "^3.0.8", "@nomicfoundation/hardhat-ignition": "^0.15.11", "@nomicfoundation/hardhat-ignition-ethers": "^0.15.11", "@nomicfoundation/hardhat-network-helpers": "^1.0.12", "@nomicfoundation/hardhat-toolbox": "^5.0.0", "@nomicfoundation/hardhat-verify": "^2.0.14", "@nomiclabs/hardhat-ethers": "^2.2.3", "@nomiclabs/hardhat-waffle": "^2.0.6", "@typechain/ethers-v6": "^0.5.1", "@typechain/hardhat": "^9.1.0", "chai": "^4.5.0", "ethers": "^6.14.3", "hardhat": "^2.22.8", "hardhat-gas-reporter": "^1.0.10", "solidity-coverage": "^0.8.16", "typechain": "^8.3.2" }, "dependencies": { "dotenv": "^16.5.0", "react": "^18.3.1", "react-dom": "^18.3.1" } } ================================================ FILE: 03-Decentralized Guestbook/scripts/deploy.js ================================================ const hre = require("hardhat"); async function main() { const Guestbook = await hre.ethers.getContractFactory("Guestbook"); const guestbook = await Guestbook.deploy(); console.log("Guestbook contract deployed to:", guestbook.target); } main().catch((error) => { console.error(error); process.exitCode = 1; }); ================================================ FILE: 04-Pyth Pull Oracles/.gitignore ================================================ node_modules .env # Hardhat files /cache /artifacts # TypeChain files /typechain /typechain-types # solidity-coverage files /coverage /coverage.json # Hardhat Ignition default folder for deployments against a local node ignition/deployments/chain-31337 ================================================ FILE: 04-Pyth Pull Oracles/README.md ================================================ # Core Pyth Feed Boilerplate Pyth Feed Boilerplate is a React-based dApp for fetching and displaying real-time price feeds from the Pyth Network. This boilerplate provides a quickstart template for developers to quickly create similar applications on the Core blockchain. Purpose: The quickstart guide helps developers rapidly set up a functional dApp with essential setup instructions and code snippets. For detailed instructions and advanced configurations, refer to the full-length guide further down. ## Quickstart Project Setup: Clone the repository and install dependencies. Configuration: Set up the Pyth price feed smart contract and integrate it with the React app. Running the Application: Start the app and view real-time price feeds. ### Prerequisites Before setting up the project, ensure you have the following installed: - [Node.js and npm](https://nodejs.org/en/download/) - [MetaMask](https://metamask.io/download.html) browser extension - [Git](https://git-scm.com/downloads) ### Setup ### 1. Clone the Repository Clone the repository to your local machine using GitHub Desktop or Git: ```zsh gh repo clone Camnaz/Core-Pyth-Feed-Boiler cd Core-Pyth-Feed-Boiler ``` ### 2. Install Dependencies Navigate to the project directory and install the necessary dependencies: ``` npm install ``` Navigate to the frontend directory and install the dependencies: ```zsh cd frontend npm install cd .. ``` ### 3. Configure the Project - Add **Private Key**: Create a '**secret.json**' file in the project root and add your private key. ```json { "PrivateKey": "your-private-key-here" } ``` ### 3.1 Compile Hardhat ``` npx hardhat compile ``` >Once deployed, update Smart Contract Address: Open src/App.js and replace `0xYourContractAddress` with your deployed contract address on the Core blockchain. ### 4. Install Babel Plugin Install the Babel plugin to avoid dependency issues: ```zsh npm install --save-dev @babel/plugin-proposal-private-property-in-object ``` ### 4.1 Navigate to frontend of project ``` cd frontend ``` ### 5. Run the Application Start the React application: ```zsh npm start ``` ### 6. Access the Application Open your browser and navigate to if it has not already: ```arduino http://localhost:3000 ``` ### 7. Conclusion Congratulations, you now have a Pyth data feed for CORE/USD, and are able to view the Core price live which is updated every few seconds. You are able to use this boilerplate to imbed Pyth price feeds for Core into different Dapps, or as a learning resource. ### Troubleshooting Error: One of your dependencies, babel-preset-react-app, is importing the "@babel/plugin-proposal-private-property-in-object" package without declaring it in its dependencies. Solution: Install the Babel plugin manually: ```zsh npm install --save-dev @babel/plugin-proposal-private-property-in-object ``` **Error**: MetaMask - RPC Error: Request of type 'wallet_requestPermissions' already pending. **Solution**: Open MetaMask and approve or reject the pending permission request. **Error**: no matching function (argument="name", value="updatePrice", code=INVALID_ARGUMENT, version=abi/5.7.0) **Solution**: Ensure the ABI file is up-to-date and contains the correct function names. ================================================ FILE: 04-Pyth Pull Oracles/contracts/PythFeedBoilerplate.sol ================================================ // SPDX-License-Identifier: MIT pragma solidity ^0.8.9; import "@pythnetwork/pyth-sdk-solidity/IPyth.sol"; import "@pythnetwork/pyth-sdk-solidity/PythStructs.sol"; contract PythFeedBoilerplate { IPyth public pyth; constructor(address pythContract) { pyth = IPyth(pythContract); } function updatePrice(bytes[] calldata priceUpdate) public payable { uint fee = pyth.getUpdateFee(priceUpdate); pyth.updatePriceFeeds{ value: fee }(priceUpdate); } function getPrice(bytes32 priceFeedId) public view returns (PythStructs.Price memory) { return pyth.getPrice(priceFeedId); } function getPriceWithoutUpdate(bytes32 priceFeedId) public view returns (int64, int32) { PythStructs.Price memory price = pyth.getPrice(priceFeedId); return (price.price, price.expo); } } ================================================ FILE: 04-Pyth Pull Oracles/frontend/.gitignore ================================================ # See https://help.github.com/articles/ignoring-files/ for more about ignoring files. # dependencies /node_modules /.pnp .pnp.js # testing /coverage # production /build # misc .DS_Store .env.local .env.development.local .env.test.local .env.production.local npm-debug.log* yarn-debug.log* yarn-error.log* ================================================ FILE: 04-Pyth Pull Oracles/frontend/README.md ================================================ # Getting Started with Create React App This project was bootstrapped with [Create React App](https://github.com/facebook/create-react-app). ## Available Scripts In the project directory, you can run: ### `npm start` Runs the app in the development mode.\ Open [http://localhost:3000](http://localhost:3000) to view it in your browser. The page will reload when you make changes.\ You may also see any lint errors in the console. ### `npm test` Launches the test runner in the interactive watch mode.\ See the section about [running tests](https://facebook.github.io/create-react-app/docs/running-tests) for more information. ### `npm run build` Builds the app for production to the `build` folder.\ It correctly bundles React in production mode and optimizes the build for the best performance. The build is minified and the filenames include the hashes.\ Your app is ready to be deployed! See the section about [deployment](https://facebook.github.io/create-react-app/docs/deployment) for more information. ### `npm run eject` **Note: this is a one-way operation. Once you `eject`, you can't go back!** If you aren't satisfied with the build tool and configuration choices, you can `eject` at any time. This command will remove the single build dependency from your project. Instead, it will copy all the configuration files and the transitive dependencies (webpack, Babel, ESLint, etc) right into your project so you have full control over them. All of the commands except `eject` will still work, but they will point to the copied scripts so you can tweak them. At this point you're on your own. You don't have to ever use `eject`. The curated feature set is suitable for small and middle deployments, and you shouldn't feel obligated to use this feature. However we understand that this tool wouldn't be useful if you couldn't customize it when you are ready for it. ## Learn More You can learn more in the [Create React App documentation](https://facebook.github.io/create-react-app/docs/getting-started). To learn React, check out the [React documentation](https://reactjs.org/). ### Code Splitting This section has moved here: [https://facebook.github.io/create-react-app/docs/code-splitting](https://facebook.github.io/create-react-app/docs/code-splitting) ### Analyzing the Bundle Size This section has moved here: [https://facebook.github.io/create-react-app/docs/analyzing-the-bundle-size](https://facebook.github.io/create-react-app/docs/analyzing-the-bundle-size) ### Making a Progressive Web App This section has moved here: [https://facebook.github.io/create-react-app/docs/making-a-progressive-web-app](https://facebook.github.io/create-react-app/docs/making-a-progressive-web-app) ### Advanced Configuration This section has moved here: [https://facebook.github.io/create-react-app/docs/advanced-configuration](https://facebook.github.io/create-react-app/docs/advanced-configuration) ### Deployment This section has moved here: [https://facebook.github.io/create-react-app/docs/deployment](https://facebook.github.io/create-react-app/docs/deployment) ### `npm run build` fails to minify This section has moved here: [https://facebook.github.io/create-react-app/docs/troubleshooting#npm-run-build-fails-to-minify](https://facebook.github.io/create-react-app/docs/troubleshooting#npm-run-build-fails-to-minify) ================================================ FILE: 04-Pyth Pull Oracles/frontend/package.json ================================================ { "name": "frontend", "version": "0.1.0", "private": true, "dependencies": { "@pythnetwork/pyth-sdk-solidity": "^4.2.0", "@testing-library/jest-dom": "5.17.0", "@testing-library/react": "13.4.0", "@testing-library/user-event": "13.5.0", "ethers": "^6.15.0", "react": "18.3.1", "react-dom": "18.3.1", "react-scripts": "5.0.1", "web-vitals": "^2.1.4" }, "scripts": { "start": "react-scripts start", "build": "react-scripts build", "test": "react-scripts test", "eject": "react-scripts eject" }, "eslintConfig": { "extends": [ "react-app", "react-app/jest" ] }, "browserslist": { "production": [ ">0.2%", "not dead", "not op_mini all" ], "development": [ "last 1 chrome version", "last 1 firefox version", "last 1 safari version" ] } } ================================================ FILE: 04-Pyth Pull Oracles/frontend/public/index.html ================================================ React App
================================================ FILE: 04-Pyth Pull Oracles/frontend/public/manifest.json ================================================ { "short_name": "React App", "name": "Create React App Sample", "icons": [ { "src": "favicon.ico", "sizes": "64x64 32x32 24x24 16x16", "type": "image/x-icon" }, { "src": "logo192.png", "type": "image/png", "sizes": "192x192" }, { "src": "logo512.png", "type": "image/png", "sizes": "512x512" } ], "start_url": ".", "display": "standalone", "theme_color": "#000000", "background_color": "#ffffff" } ================================================ FILE: 04-Pyth Pull Oracles/frontend/public/robots.txt ================================================ # https://www.robotstxt.org/robotstxt.html User-agent: * Disallow: ================================================ FILE: 04-Pyth Pull Oracles/frontend/src/App.css ================================================ @import url('https://fonts.googleapis.com/css2?family=Lexend:wght@400;600&display=swap'); body { background-color: #121212; color: #292D32; font-family: 'Lexend', sans-serif; margin: 0; padding: 0; display: flex; justify-content: center; align-items: center; height: 100vh; } .App { text-align: center; } .App-header { background-color: #292D32; padding: 20px; border-radius: 10px; margin-bottom: 20px; color: #FBFCFC; } .App-title { margin: 0; text-align: left; color: #FFFFFF; } .price-container { background-color: #292D32; padding: 20px; border-radius: 10px; color: #FBFCFC; display: inline-block; margin-top: 20px; } .price { font-size: 1.5em; margin-top: 10px; color: #FFFFFF; } ================================================ FILE: 04-Pyth Pull Oracles/frontend/src/App.js ================================================ import React, { useEffect, useState } from 'react'; import { ethers } from 'ethers'; import './App.css'; // Import Pyth ABI - we'll use require for JSON files const PythAbi = require('@pythnetwork/pyth-sdk-solidity/abis/IPyth.json'); // Core Mainnet const contractAddress = '0xA2aa501b19aff244D90cc15a4Cf739D2725B5729'; const provider = new ethers.JsonRpcProvider('https://rpc.coredao.org'); const contract = new ethers.Contract(contractAddress, PythAbi, provider); const priceId = '0x9b4503710cc8c53f75c30e6e4fda1a7064680ef2e0ee97acd2e3a7c37b3c830c'; // CORE/USD const age = '60'; function App() { const [price, setPrice] = useState(null); useEffect(() => { let intervalId; const fetchPrice = async () => { try { console.log('Fetching price...'); // Use your new code to fetch price data const [price, conf, expo, timestamp] = await contract.getPriceNoOlderThan(priceId, age); console.log('Raw price data:', { price, conf, expo, timestamp }); // Convert BigInt to Number for calculation const expoNumber = Number(expo); console.log('Exponent:', expoNumber); // Adjust the price based on the exponent // The price comes with a specific decimal precision, we need to adjust it const adjustedPrice = parseFloat(ethers.formatUnits(price, -expoNumber)); setPrice(adjustedPrice.toFixed(5)); // Format to 5 decimal places console.log('Price fetched:', adjustedPrice); } catch (error) { console.error('Error fetching price:', error); } }; // Fetch the price immediately when the component mounts fetchPrice(); // Set up an interval to fetch the price every 2 minutes (120000 milliseconds) intervalId = setInterval(fetchPrice, 120000); // Clear the interval when the component unmounts return () => clearInterval(intervalId); }, []); return (

Pyth Feed Boilerplate

CORE / USD

Price: {price !== null ? `$${price}` : 'Loading...'}

); } export default App; ================================================ FILE: 04-Pyth Pull Oracles/frontend/src/App.test.js ================================================ import { render, screen } from '@testing-library/react'; import App from './App'; test('renders learn react link', () => { render(); const linkElement = screen.getByText(/learn react/i); expect(linkElement).toBeInTheDocument(); }); ================================================ FILE: 04-Pyth Pull Oracles/frontend/src/PythFeedBoilerplateAbi.json ================================================ { "_format": "hh-sol-artifact-1", "contractName": "PythFeedBoilerplate", "sourceName": "contracts/PythFeedBoilerplate.sol", "abi": [ { "inputs": [ { "internalType": "address", "name": "pythContract", "type": "address" } ], "stateMutability": "nonpayable", "type": "constructor" }, { "inputs": [ { "internalType": "bytes32", "name": "priceFeedId", "type": "bytes32" } ], "name": "getPrice", "outputs": [ { "components": [ { "internalType": "int64", "name": "price", "type": "int64" }, { "internalType": "uint64", "name": "conf", "type": "uint64" }, { "internalType": "int32", "name": "expo", "type": "int32" }, { "internalType": "uint256", "name": "publishTime", "type": "uint256" } ], "internalType": "struct PythStructs.Price", "name": "", "type": "tuple" } ], "stateMutability": "view", "type": "function" }, { "inputs": [ { "internalType": "bytes32", "name": "priceFeedId", "type": "bytes32" } ], "name": "getPriceWithoutUpdate", "outputs": [ { "internalType": "int64", "name": "", "type": "int64" }, { "internalType": "int32", "name": "", "type": "int32" } ], "stateMutability": "view", "type": "function" }, { "inputs": [], "name": "pyth", "outputs": [ { "internalType": "contract IPyth", "name": "", "type": "address" } ], "stateMutability": "view", "type": "function" }, { "inputs": [ { "internalType": "bytes[]", "name": "priceUpdate", "type": "bytes[]" } ], "name": "updatePrice", "outputs": [], "stateMutability": "payable", "type": "function" } ], "bytecode": "0x608060405234801561001057600080fd5b5060405161064e38038061064e83398101604081905261002f91610054565b600080546001600160a01b0319166001600160a01b0392909216919091179055610084565b60006020828403121561006657600080fd5b81516001600160a01b038116811461007d57600080fd5b9392505050565b6105bb806100936000396000f3fe60806040526004361061003f5760003560e01c8063083a816b146100445780632592c0bf1461008657806331d98b3f1461009b578063f98d06f0146100fe575b600080fd5b34801561005057600080fd5b5061006461005f36600461035b565b610136565b6040805160079390930b835260039190910b6020830152015b60405180910390f35b610099610094366004610374565b6101ca565b005b3480156100a757600080fd5b506100bb6100b636600461035b565b6102b9565b60405161007d9190815160070b815260208083015167ffffffffffffffff169082015260408083015160030b908201526060918201519181019190915260800190565b34801561010a57600080fd5b5060005461011e906001600160a01b031681565b6040516001600160a01b03909116815260200161007d565b600080546040516331d98b3f60e01b815260048101849052829182916001600160a01b03909116906331d98b3f9060240160806040518083038186803b15801561017f57600080fd5b505afa158015610193573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906101b79190610418565b8051604090910151909590945092505050565b6000805460405163d47eed4560e01b81526001600160a01b039091169063d47eed45906101fd90869086906004016104d1565b60206040518083038186803b15801561021557600080fd5b505afa158015610229573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061024d919061056c565b600054604051631df3cbc560e31b81529192506001600160a01b03169063ef9e5e2890839061028290879087906004016104d1565b6000604051808303818588803b15801561029b57600080fd5b505af11580156102af573d6000803e3d6000fd5b5050505050505050565b60408051608081018252600080825260208201819052818301819052606082018190525491516331d98b3f60e01b81526004810184905290916001600160a01b0316906331d98b3f9060240160806040518083038186803b15801561031d57600080fd5b505afa158015610331573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906103559190610418565b92915050565b60006020828403121561036d57600080fd5b5035919050565b6000806020838503121561038757600080fd5b823567ffffffffffffffff8082111561039f57600080fd5b818501915085601f8301126103b357600080fd5b8135818111156103c257600080fd5b8660208260051b85010111156103d757600080fd5b60209290920196919550909350505050565b805167ffffffffffffffff8116811461040157600080fd5b919050565b8051600381900b811461040157600080fd5b60006080828403121561042a57600080fd5b6040516080810181811067ffffffffffffffff8211171561045b57634e487b7160e01b600052604160045260246000fd5b6040528251600781900b811461047057600080fd5b815261047e602084016103e9565b602082015261048f60408401610406565b6040820152606083015160608201528091505092915050565b81835281816020850137506000828201602090810191909152601f909101601f19169091010190565b60208082528181018390526000906040600585901b8401810190840186845b8781101561055f57868403603f190183528135368a9003601e1901811261051657600080fd5b8901803567ffffffffffffffff81111561052f57600080fd5b8036038b131561053e57600080fd5b61054b86828985016104a8565b9550505091840191908401906001016104f0565b5091979650505050505050565b60006020828403121561057e57600080fd5b505191905056fea26469706673582212205d7a5e1856ba7a5ac5f0471280bd41bd8f274c6e9ad3dfe64a8057b660635c4564736f6c63430008090033", "deployedBytecode": "0x60806040526004361061003f5760003560e01c8063083a816b146100445780632592c0bf1461008657806331d98b3f1461009b578063f98d06f0146100fe575b600080fd5b34801561005057600080fd5b5061006461005f36600461035b565b610136565b6040805160079390930b835260039190910b6020830152015b60405180910390f35b610099610094366004610374565b6101ca565b005b3480156100a757600080fd5b506100bb6100b636600461035b565b6102b9565b60405161007d9190815160070b815260208083015167ffffffffffffffff169082015260408083015160030b908201526060918201519181019190915260800190565b34801561010a57600080fd5b5060005461011e906001600160a01b031681565b6040516001600160a01b03909116815260200161007d565b600080546040516331d98b3f60e01b815260048101849052829182916001600160a01b03909116906331d98b3f9060240160806040518083038186803b15801561017f57600080fd5b505afa158015610193573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906101b79190610418565b8051604090910151909590945092505050565b6000805460405163d47eed4560e01b81526001600160a01b039091169063d47eed45906101fd90869086906004016104d1565b60206040518083038186803b15801561021557600080fd5b505afa158015610229573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061024d919061056c565b600054604051631df3cbc560e31b81529192506001600160a01b03169063ef9e5e2890839061028290879087906004016104d1565b6000604051808303818588803b15801561029b57600080fd5b505af11580156102af573d6000803e3d6000fd5b5050505050505050565b60408051608081018252600080825260208201819052818301819052606082018190525491516331d98b3f60e01b81526004810184905290916001600160a01b0316906331d98b3f9060240160806040518083038186803b15801561031d57600080fd5b505afa158015610331573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906103559190610418565b92915050565b60006020828403121561036d57600080fd5b5035919050565b6000806020838503121561038757600080fd5b823567ffffffffffffffff8082111561039f57600080fd5b818501915085601f8301126103b357600080fd5b8135818111156103c257600080fd5b8660208260051b85010111156103d757600080fd5b60209290920196919550909350505050565b805167ffffffffffffffff8116811461040157600080fd5b919050565b8051600381900b811461040157600080fd5b60006080828403121561042a57600080fd5b6040516080810181811067ffffffffffffffff8211171561045b57634e487b7160e01b600052604160045260246000fd5b6040528251600781900b811461047057600080fd5b815261047e602084016103e9565b602082015261048f60408401610406565b6040820152606083015160608201528091505092915050565b81835281816020850137506000828201602090810191909152601f909101601f19169091010190565b60208082528181018390526000906040600585901b8401810190840186845b8781101561055f57868403603f190183528135368a9003601e1901811261051657600080fd5b8901803567ffffffffffffffff81111561052f57600080fd5b8036038b131561053e57600080fd5b61054b86828985016104a8565b9550505091840191908401906001016104f0565b5091979650505050505050565b60006020828403121561057e57600080fd5b505191905056fea26469706673582212205d7a5e1856ba7a5ac5f0471280bd41bd8f274c6e9ad3dfe64a8057b660635c4564736f6c63430008090033", "linkReferences": {}, "deployedLinkReferences": {} } ================================================ FILE: 04-Pyth Pull Oracles/frontend/src/index.css ================================================ body { margin: 0; font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'Roboto', 'Oxygen', 'Ubuntu', 'Cantarell', 'Fira Sans', 'Droid Sans', 'Helvetica Neue', sans-serif; -webkit-font-smoothing: antialiased; -moz-osx-font-smoothing: grayscale; } code { font-family: source-code-pro, Menlo, Monaco, Consolas, 'Courier New', monospace; } ================================================ FILE: 04-Pyth Pull Oracles/frontend/src/index.js ================================================ import React from 'react'; import ReactDOM from 'react-dom/client'; import './index.css'; import App from './App'; import reportWebVitals from './reportWebVitals'; const root = ReactDOM.createRoot(document.getElementById('root')); root.render( ); // If you want to start measuring performance in your app, pass a function // to log results (for example: reportWebVitals(console.log)) // or send to an analytics endpoint. Learn more: https://bit.ly/CRA-vitals reportWebVitals(); ================================================ FILE: 04-Pyth Pull Oracles/frontend/src/reportWebVitals.js ================================================ const reportWebVitals = onPerfEntry => { if (onPerfEntry && onPerfEntry instanceof Function) { import('web-vitals').then(({ getCLS, getFID, getFCP, getLCP, getTTFB }) => { getCLS(onPerfEntry); getFID(onPerfEntry); getFCP(onPerfEntry); getLCP(onPerfEntry); getTTFB(onPerfEntry); }); } }; export default reportWebVitals; ================================================ FILE: 04-Pyth Pull Oracles/frontend/src/setupTests.js ================================================ // jest-dom adds custom jest matchers for asserting on DOM nodes. // allows you to do things like: // expect(element).toHaveTextContent(/react/i) // learn more: https://github.com/testing-library/jest-dom import '@testing-library/jest-dom'; ================================================ FILE: 04-Pyth Pull Oracles/hardhat.config.js ================================================ require('@nomiclabs/hardhat-ethers'); require("@nomiclabs/hardhat-waffle"); require("dotenv").config(); /** @type import('hardhat/config').HardhatUserConfig */ const PRIVATE_KEY = process.env.PRIVATE_KEY; module.exports = { defaultNetwork: 'hardhat', networks: { hardhat: {}, core_testnet: { url: 'https://rpc.test2.btcs.network', accounts: [PRIVATE_KEY], chainId: 1114, }, }, solidity: { compilers: [ { version: '0.8.9', settings: { evmVersion: 'london', optimizer: { enabled: true, runs: 200, }, }, }, ], }, paths: { sources: './contracts', cache: './cache', artifacts: './artifacts', }, mocha: { timeout: 20000, }, }; ================================================ FILE: 04-Pyth Pull Oracles/package.json ================================================ { "name": "pyth-feed-boilerplate", "version": "1.0.0", "main": "index.js", "scripts": { "test": "echo \"Error: no test specified\" && exit 1" }, "keywords": [], "author": "", "license": "ISC", "description": "", "devDependencies": { "@babel/plugin-proposal-private-property-in-object": "^7.21.11", "hardhat": "^2.22.6" }, "dependencies": { "@nomiclabs/hardhat-ethers": "^2.2.3", "@nomiclabs/hardhat-waffle": "^2.0.6", "@pythnetwork/pyth-sdk-solidity": "^3.1.0", "dotenv": "^16.5.0", "ethers": "^5.7.2" } } ================================================ FILE: 04-Pyth Pull Oracles/scripts/deploy.js ================================================ async function main() { const [deployer] = await ethers.getSigners(); console.log("Deploying contracts with the account:", deployer.address); // Replace with the actual Pyth contract address for CoreDAO testnet const pythContractAddress = "0xA2aa501b19aff244D90cc15a4Cf739D2725B5729"; // Replace with actual address const PythFeedBoilerplate = await ethers.getContractFactory("PythFeedBoilerplate"); const pythFeedBoilerplate = await PythFeedBoilerplate.deploy(pythContractAddress); console.log("PythFeedBoilerplate deployed to:", pythFeedBoilerplate.address); } main() .then(() => process.exit(0)) .catch(error => { console.error(error); process.exit(1); }); ================================================ FILE: 05-Hello-World-Dapp/.gitignore ================================================ node_modules .env secret.json # Hardhat files /cache /artifacts # TypeChain files /typechain /typechain-types # solidity-coverage files /coverage /coverage.json # Hardhat Ignition default folder for deployments against a local node ignition/deployments/chain-31337 ================================================ FILE: 05-Hello-World-Dapp/README.md ================================================ # Simple Hello World dApp on Core In this tutorial, you'll learn how to build a simple decentralized application (dApp) using the Core blockchain TestNet. The focus will be on creating a "Hello World" dApp that interacts with a smart contract. This dApp will allow users to store, retrieve, and update a message on the blockchain. By following the steps in this guide, you will gain hands-on experience with MetaMask wallet integration, smart contract development, and front-end interaction using the Ethers.js library. ## What Are We Building In this tutorial, we'll develop a simple Hello World decentralized application (dApp) that stores a message in a smart contract deployed on the Core blockchain TestNet. The dApp also has the functionality to retrieve and display the stored message. ## Learning Takeaways This tutorial will help you gain knowledge on the following learning points: * MetaMask Wallet connectivity to Core Testnet; * Smart contract development and deployment on Core Testnet; * Front-end integration with the smart contract using Ethers.js library; * Read data from a smart contract; * Write data to a smart contract; ## Software Prerequisites * [Git](https://git-scm.com/) v2.44.0 * [Node.js](https://nodejs.org/en) v20.11.1 * [npm](https://docs.npmjs.com/downloading-and-installing-node-js-and-npm) v10.2.4 * [Hardhat](https://hardhat.org/hardhat-runner/docs/getting-started#installation) v2.22.7 * [MetaMask Web Wallet Extension](https://metamask.io/download/) ## Setting up the development environment 1. Create a new directory for the project and navigate into it ```bash mkdir hello-world-dapp cd hello-world-dapp ``` 2. Install Hardhat ```bash npm init --yes npm install --save-dev hardhat ``` 3. Initialize Hardhat project by running the following command ```bash npx hardhat init ``` ![dapp-tutorial-1](./assets/hardhat-init.png) 4. Once this project is initialized, you'll find the following project structure: ```bash dapp-tutorial. | .gitignore | hardhat-config.js | package-lock.json | package.json | README.md | +---contracts | Lock.sol | +---ignition | \---modules | Lock.js | +---node_modules | +---test | Lock.js | ``` 5. Install and configure MetaMask Chrome Extension to use with Core Testnet. Refer [here](https://docs.coredao.org/docs/Dev-Guide/core-testnet-wallet-config) for a detailed guide. 6. Create a secret.json file in the root folder and store the private key of your MetaMask wallet in it. Refer [here](https://metamask.zendesk.com/hc/en-us/articles/360015290032-How-to-reveal-your-Secret-Recovery-Phrase) for details on how to get MetaMask account's private key. ```json {"PrivateKey":"you private key, do not leak this file, do keep it absolutely safe"} ``` > Do not forget to add this file to the `.gitignore` file in the root folder of your project so that you don't accidentally check your private keys/secret phrases into a public repository. Make sure you keep this file in an absolutely safe place! 7. Copy the following into your `hardhat.config.js` file ```js require("@nomicfoundation/hardhat-toolbox"); require("dotenv").config(); /** @type import('hardhat/config').HardhatUserConfig */ const PRIVATE_KEY = process.env.PRIVATE_KEY; module.exports = { defaultNetwork: 'core_testnet', networks: { hardhat: { }, core_testnet: { url: 'https://rpc.test2.btcs.network', accounts: [PRIVATE_KEY], chainId: 1115, } }, solidity: { compilers: [ { version: '0.8.26', settings: { evmVersion: 'paris', optimizer: { enabled: true, runs: 200, }, }, }, ], }, paths: { sources: './contracts', cache: './cache', artifacts: './artifacts', }, mocha: { timeout: 60000, }, }; ``` ## Writing HelloWorld Smart Contract 1. Navigate to the `contracts` folder in the root directory of your project. 2. Delete the `Lock.sol` file; create a new file `HelloWorld.sol` and paste the following contents into it. ```javascript // SPDX-License-Identifier: MIT pragma solidity ^0.8.26; contract HelloWorld { string public message; constructor(string memory _message) { message = _message; } function setMessage(string memory _message) public { message = _message; } } ``` ### Explanation The `HelloWorld` Solidity contract stores a message in a public string variable. It initializes this message through the constructor when the contract is deployed. The `setMessage` function allows anyone to update the stored message. The `public` keyword makes the `message` variable readable by anyone. #### State Variable * `string public message`: Public string variable to store and read a message. #### Constructor * `constructor(string memory _message) { message = _message; }`: Initializes the message state variable with a value provided during deployment. #### Function * `function setMessage(string memory _message) public { message = _message; }`: Allows updating the message state variable. ## Compiling Smart Contract 1. To compile the `HelloWorld` smart contract defined in the `HelloWorld.sol`, from the root directory run the following command ```bash npx hardhat compile ``` ## Testing HelloWorld Smart Contracts 1. Before deploying your smart contract on the Core blockchain, it is best adviced to first run a series of tests making sure that the smart contract is working as desired. 2. Inside the `test` folder, delete the `Lock.js` file, create a new file `HelloWorld.js` and update it with the following: ```javascript const { expect } = require("chai"); describe("HelloWorld contract", function () { let HelloWorld; let helloWorld; let owner; beforeEach(async function () { HelloWorld = await ethers.getContractFactory("HelloWorld"); [owner] = await ethers.getSigners(); helloWorld = await HelloWorld.deploy("Hello, world!"); await helloWorld.waitForDeployment(); }); it("Should return the initial message", async function () { expect(await helloWorld.message()).to.equal("Hello, world!"); }); it("Should update the message", async function () { const tx =await helloWorld.setMessage("Hello, Hardhat!"); await tx.wait(); // Wait for the transaction to be mined expect(await helloWorld.message()).to.equal("Hello, Hardhat!"); }); }); ``` ### Explanation This test script is designed to validate the behavior of the HelloWorld smart contract. In the setup phase (beforeEach), it deploys a new instance of the contract with the initial message "Hello, world!" and waits for the deployment to complete. The first test, "Should return the initial message," checks that the contract correctly returns the initial message stored during deployment. It ensures that the message is set to "Hello, world!" as expected. The second test, "Should update the message," updates the message to "Hello, Hardhat!" and then verifies that the message has been updated successfully by checking its new value. This ensures that the setMessage function works correctly and the contract's state is updated as intended. This test script checks the functionality of the HelloWorld contract: * **Setup:** It deploys the HelloWorld contract with the initial message "Hello, world!" before each test. * **Test Initial Message:** It verifies that the contract's initial message is correctly set to "Hello, world!". * **Test Update Message:** It updates the message to "Hello, Hardhat!" and confirms that the change is successfully reflected. Overall, these tests confirm that the contract's functionality for setting and retrieving messages operates correctly. 3. Run the test scripts using the command `npx hardhat test` ![running-hardhat-test-scripts](./assets/hardhat-test.png) ## Deploying HelloWorld Smart Contract 1. Create a `scripts` folder in the root directory of your project. Inside this folder, create a file `deploy.js`; paste the following script into it. ```javascript const { ethers } = require("hardhat"); async function main() { const [deployer] = await ethers.getSigners(); console.log("Deploying contract with the account:", deployer.address); const HelloWorld = await ethers.getContractFactory("HelloWorld"); const helloWorld = await HelloWorld.deploy("Hello, World"); console.log("HelloWorld Contract Address:", await helloWorld.getAddress()); } main() .then(() => process.exit(0)) .catch((error) => { console.error(error); process.exit(1); }); ``` 3. Make sure your MetaMask wallet has tCORE test tokens for the Core Testnet. Refer [here](https://docs.coredao.org/docs/Dev-Guide/core-faucet) for details on how to get tCORE tokens from Core Faucet. 4. Run the following command from the root directory of your project, to deploy your smart contract on the Core Chain. ```bash npx hardhat run scripts/deploy.js ``` If succesfully deployed, you will get the following output ![hardhat-deploy-result](./assets/hardhat-deploy.png) 5. Make sure to save the Address of HelloWorld Contract at which is deployed, as obtained above, this will be used for interacting with smart contract from the dApp's frontend. 🎉 Congratulations! You have successfully learned how to create, compile, and deploy a smart contract on the Core Chain Testnet using the Hardhat. ## Interacting with Smart Contract through Frontend ⚡️ Let's create a frontend interface for interacting with the `HelloWorld` smart contract. ### Set Up React Project 1. Run the following commands to create a react project and install the required depencendy of `ethers.js` to communicate with the HelloWorld smart contract. ```bash npx create-react-app frontend cd frontend npm install ethers ``` ### Getting HelloWorld Contract ABI * Copy the `HelloWorld.json` file from `artifacts/contracts/HelloWorld.sol/` to the `frontend/src/Contract-ABI` directory. ### Create the React Components * Inside `src`, create a file named `HelloWorld.js`. Ensure you replace placeholders like `YOUR_CONTRACT_ADDRESS` with actual values from your deployment. ```javascript import React, { useState, useEffect } from 'react'; import { ethers } from 'ethers'; import { toast, ToastContainer } from 'react-toastify'; // Import ToastContainer and toast import 'react-toastify/dist/ReactToastify.css'; // Import the CSS for toast notifications import './HelloWorld.css'; // Import the CSS file // Import ABI from JSON file import HelloWorldABI from './Contract-ABI/HelloWorld.json'; // Import the logo image import logo from './core-dao-logo.png'; // Adjust the path as needed // Replace with your contract's address const contractAddress = "0xBF46BAA6210Ae6c9050F5453B996070209f69830"; function HelloWorld() { const [message, setMessage] = useState(''); const [newMessage, setNewMessage] = useState(''); const [provider, setProvider] = useState(null); const [contract, setContract] = useState(null); const [showMessage, setShowMessage] = useState(false); // State to control message visibility useEffect(() => { async function init() { if (!window.ethereum) { toast.error("No crypto wallet found. Please install MetaMask."); return; } try { // Prompt user to connect MetaMask await window.ethereum.request({ method: 'eth_requestAccounts' }); const provider = new ethers.BrowserProvider(window.ethereum); const signer = await provider.getSigner(); const contract = new ethers.Contract(contractAddress, HelloWorldABI.abi, signer); setProvider(provider); setContract(contract); } catch (error) { toast.error("Failed to connect to MetaMask. Please try again."); console.error("Error initializing MetaMask:", error); } } init(); }, []); const updateMessage = async () => { if (!contract) return; try { const tx = await contract.setMessage(newMessage); await tx.wait(); setNewMessage(''); // Clear the input field after updating toast.success("Message updated successfully!"); } catch (error) { toast.error("Failed to update message. Please try again."); console.error("Error updating message:", error); } }; const retrieveMessage = async () => { if (!contract) return; try { const currentMessage = await contract.message(); setMessage(currentMessage); setShowMessage(true); // Show the message after retrieval toast.success("Message retrieved successfully!"); } catch (error) { toast.error("Failed to retrieve message. Please try again."); console.error("Error retrieving message:", error); } }; return (
{/* Add ToastContainer to display notifications */} Core DAO Logo {showMessage && (
{message}
)}
setNewMessage(e.target.value)} className="input-field" placeholder="Enter new message" />
); } export default HelloWorld; ``` ### Create HelloWorld.css * Inside `src`, create a file named `HelloWorld.css` ```css .container { display: flex; flex-direction: column; align-items: center; justify-content: center; height: 100vh; width: 100vw; background-color: #2e2e2e; color: #e0e0e0; padding: 20px; box-sizing: border-box; } .logo { width: 200px; margin-bottom: 40px; border-radius: 10px; box-shadow: 0 4px 8px rgba(0, 0, 0, 0.5); } .retrieve-button, .update-button { background-color: #ff920f; color: white; border: none; padding: 14px 28px; margin: 10px; cursor: pointer; border-radius: 8px; font-size: 18px; transition: background-color 0.3s ease, transform 0.2s ease; } .retrieve-button:hover, .update-button:hover { background-color: #e67e22; transform: scale(1.05); } .message-display { font-size: 28px; margin-bottom: 20px; font-weight: bold; color: #ffd54f; } .input-field { padding: 14px; border: 1px solid #555; border-radius: 8px; width: 80%; max-width: 500px; margin-bottom: 20px; font-size: 18px; background-color: #424242; color: #fff; transition: background-color 0.3s ease, border-color 0.3s ease; } .retrieve-button { margin-top: 20px; } .input-field:focus { background-color: #616161; border-color: #ff920f; outline: none; } ``` ### Update App.js * Replace the contents of App.js with the following ```jsx import React from 'react'; import './App.css'; import HelloWorld from './HelloWorld'; function App() { return (
); } export default App; ``` ## Running Your Application * Start the React Development Server using the command `npm run start` ```bash npm start Your application should now be accessible at http://localhost:3000. ``` ## Interact with the dApp Open your React app in the browser. You should be able to retrieve and set messages using your deployed contract. ![frontend](./assets/frontend-ui.png) 🎉 Congratulations! You've just interacted with your newly-deployed contract using your dApp's front end! You can build on the codebase by deploying and interacting with different contracts, and by adding new UI components to the website for your users. ================================================ FILE: 05-Hello-World-Dapp/contracts/HelloWorld.sol ================================================ // SPDX-License-Identifier: MIT pragma solidity ^0.8.26; contract HelloWorld { string public message; constructor(string memory _message) { message = _message; } function setMessage(string memory _message) public { message = _message; } } ================================================ FILE: 05-Hello-World-Dapp/contracts/Lock.sol ================================================ // SPDX-License-Identifier: UNLICENSED pragma solidity ^0.8.24; // Uncomment this line to use console.log // import "hardhat/console.sol"; contract Lock { uint public unlockTime; address payable public owner; event Withdrawal(uint amount, uint when); constructor(uint _unlockTime) payable { require( block.timestamp < _unlockTime, "Unlock time should be in the future" ); unlockTime = _unlockTime; owner = payable(msg.sender); } function withdraw() public { // Uncomment this line, and the import of "hardhat/console.sol", to print a log in your terminal // console.log("Unlock time is %o and block timestamp is %o", unlockTime, block.timestamp); require(block.timestamp >= unlockTime, "You can't withdraw yet"); require(msg.sender == owner, "You aren't the owner"); emit Withdrawal(address(this).balance, block.timestamp); owner.transfer(address(this).balance); } } ================================================ FILE: 05-Hello-World-Dapp/frontend/.gitignore ================================================ # See https://help.github.com/articles/ignoring-files/ for more about ignoring files. # dependencies /node_modules /.pnp .pnp.js # testing /coverage # production /build # misc .DS_Store .env.local .env.development.local .env.test.local .env.production.local npm-debug.log* yarn-debug.log* yarn-error.log* ================================================ FILE: 05-Hello-World-Dapp/frontend/README.md ================================================ # Getting Started with Create React App This project was bootstrapped with [Create React App](https://github.com/facebook/create-react-app). ## Available Scripts In the project directory, you can run: ### `npm start` Runs the app in the development mode.\ Open [http://localhost:3000](http://localhost:3000) to view it in your browser. The page will reload when you make changes.\ You may also see any lint errors in the console. ### `npm test` Launches the test runner in the interactive watch mode.\ See the section about [running tests](https://facebook.github.io/create-react-app/docs/running-tests) for more information. ### `npm run build` Builds the app for production to the `build` folder.\ It correctly bundles React in production mode and optimizes the build for the best performance. The build is minified and the filenames include the hashes.\ Your app is ready to be deployed! See the section about [deployment](https://facebook.github.io/create-react-app/docs/deployment) for more information. ### `npm run eject` **Note: this is a one-way operation. Once you `eject`, you can't go back!** If you aren't satisfied with the build tool and configuration choices, you can `eject` at any time. This command will remove the single build dependency from your project. Instead, it will copy all the configuration files and the transitive dependencies (webpack, Babel, ESLint, etc) right into your project so you have full control over them. All of the commands except `eject` will still work, but they will point to the copied scripts so you can tweak them. At this point you're on your own. You don't have to ever use `eject`. The curated feature set is suitable for small and middle deployments, and you shouldn't feel obligated to use this feature. However we understand that this tool wouldn't be useful if you couldn't customize it when you are ready for it. ## Learn More You can learn more in the [Create React App documentation](https://facebook.github.io/create-react-app/docs/getting-started). To learn React, check out the [React documentation](https://reactjs.org/). ### Code Splitting This section has moved here: [https://facebook.github.io/create-react-app/docs/code-splitting](https://facebook.github.io/create-react-app/docs/code-splitting) ### Analyzing the Bundle Size This section has moved here: [https://facebook.github.io/create-react-app/docs/analyzing-the-bundle-size](https://facebook.github.io/create-react-app/docs/analyzing-the-bundle-size) ### Making a Progressive Web App This section has moved here: [https://facebook.github.io/create-react-app/docs/making-a-progressive-web-app](https://facebook.github.io/create-react-app/docs/making-a-progressive-web-app) ### Advanced Configuration This section has moved here: [https://facebook.github.io/create-react-app/docs/advanced-configuration](https://facebook.github.io/create-react-app/docs/advanced-configuration) ### Deployment This section has moved here: [https://facebook.github.io/create-react-app/docs/deployment](https://facebook.github.io/create-react-app/docs/deployment) ### `npm run build` fails to minify This section has moved here: [https://facebook.github.io/create-react-app/docs/troubleshooting#npm-run-build-fails-to-minify](https://facebook.github.io/create-react-app/docs/troubleshooting#npm-run-build-fails-to-minify) ================================================ FILE: 05-Hello-World-Dapp/frontend/package.json ================================================ { "name": "frontend", "version": "0.1.0", "private": true, "dependencies": { "@testing-library/jest-dom": "5.17.0", "@testing-library/react": "13.4.0", "@testing-library/user-event": "13.5.0", "ethers": "6.13.2", "react": "18.3.1", "react-dom": "18.3.1", "react-scripts": "5.0.1", "web-vitals": "^2.1.4" }, "scripts": { "start": "react-scripts start", "build": "react-scripts build", "test": "react-scripts test", "eject": "react-scripts eject" }, "eslintConfig": { "extends": [ "react-app", "react-app/jest" ] }, "browserslist": { "production": [ ">0.2%", "not dead", "not op_mini all" ], "development": [ "last 1 chrome version", "last 1 firefox version", "last 1 safari version" ] }, "devDependencies": { "react-toastify": "^10.0.5" } } ================================================ FILE: 05-Hello-World-Dapp/frontend/public/index.html ================================================ React App
================================================ FILE: 05-Hello-World-Dapp/frontend/public/manifest.json ================================================ { "short_name": "React App", "name": "Create React App Sample", "icons": [ { "src": "favicon.ico", "sizes": "64x64 32x32 24x24 16x16", "type": "image/x-icon" }, { "src": "logo192.png", "type": "image/png", "sizes": "192x192" }, { "src": "logo512.png", "type": "image/png", "sizes": "512x512" } ], "start_url": ".", "display": "standalone", "theme_color": "#000000", "background_color": "#ffffff" } ================================================ FILE: 05-Hello-World-Dapp/frontend/public/robots.txt ================================================ # https://www.robotstxt.org/robotstxt.html User-agent: * Disallow: ================================================ FILE: 05-Hello-World-Dapp/frontend/src/App.css ================================================ .App { text-align: center; } .App-logo { height: 40vmin; pointer-events: none; } @media (prefers-reduced-motion: no-preference) { .App-logo { animation: App-logo-spin infinite 20s linear; } } .App-header { background-color: #282c34; min-height: 100vh; display: flex; flex-direction: column; align-items: center; justify-content: center; font-size: calc(10px + 2vmin); color: white; } .App-link { color: #61dafb; } @keyframes App-logo-spin { from { transform: rotate(0deg); } to { transform: rotate(360deg); } } ================================================ FILE: 05-Hello-World-Dapp/frontend/src/App.js ================================================ import React from 'react'; import './App.css'; import HelloWorld from './HelloWorld'; function App() { return (
); } export default App; ================================================ FILE: 05-Hello-World-Dapp/frontend/src/App.test.js ================================================ import { render, screen } from '@testing-library/react'; import App from './App'; test('renders learn react link', () => { render(); const linkElement = screen.getByText(/learn react/i); expect(linkElement).toBeInTheDocument(); }); ================================================ FILE: 05-Hello-World-Dapp/frontend/src/Contract-ABI/HelloWorld.json ================================================ { "_format": "hh-sol-artifact-1", "contractName": "HelloWorld", "sourceName": "contracts/HelloWorld.sol", "abi": [ { "inputs": [ { "internalType": "string", "name": "_message", "type": "string" } ], "stateMutability": "nonpayable", "type": "constructor" }, { "inputs": [], "name": "message", "outputs": [ { "internalType": "string", "name": "", "type": "string" } ], "stateMutability": "view", "type": "function" }, { "inputs": [ { "internalType": "string", "name": "_message", "type": "string" } ], "name": "setMessage", "outputs": [], "stateMutability": "nonpayable", "type": "function" } ], "bytecode": "0x608060405234801561001057600080fd5b5060405161062138038061062183398101604081905261002f91610058565b600061003b82826101ad565b505061026b565b634e487b7160e01b600052604160045260246000fd5b60006020828403121561006a57600080fd5b81516001600160401b0381111561008057600080fd5b8201601f8101841361009157600080fd5b80516001600160401b038111156100aa576100aa610042565b604051601f8201601f19908116603f011681016001600160401b03811182821017156100d8576100d8610042565b6040528181528282016020018610156100f057600080fd5b60005b8281101561010f576020818501810151838301820152016100f3565b50600091810160200191909152949350505050565b600181811c9082168061013857607f821691505b60208210810361015857634e487b7160e01b600052602260045260246000fd5b50919050565b601f8211156101a857806000526020600020601f840160051c810160208510156101855750805b601f840160051c820191505b818110156101a55760008155600101610191565b50505b505050565b81516001600160401b038111156101c6576101c6610042565b6101da816101d48454610124565b8461015e565b6020601f82116001811461020e57600083156101f65750848201515b600019600385901b1c1916600184901b1784556101a5565b600084815260208120601f198516915b8281101561023e578785015182556020948501946001909201910161021e565b508482101561025c5786840151600019600387901b60f8161c191681555b50505050600190811b01905550565b6103a78061027a6000396000f3fe608060405234801561001057600080fd5b50600436106100365760003560e01c8063368b87721461003b578063e21f37ce14610050575b600080fd5b61004e610049366004610122565b61006e565b005b61005861007e565b60405161006591906101db565b60405180910390f35b600061007a82826102b2565b5050565b6000805461008b90610229565b80601f01602080910402602001604051908101604052809291908181526020018280546100b790610229565b80156101045780601f106100d957610100808354040283529160200191610104565b820191906000526020600020905b8154815290600101906020018083116100e757829003601f168201915b505050505081565b634e487b7160e01b600052604160045260246000fd5b60006020828403121561013457600080fd5b813567ffffffffffffffff81111561014b57600080fd5b8201601f8101841361015c57600080fd5b803567ffffffffffffffff8111156101765761017661010c565b604051601f8201601f19908116603f0116810167ffffffffffffffff811182821017156101a5576101a561010c565b6040528181528282016020018610156101bd57600080fd5b81602084016020830137600091810160200191909152949350505050565b602081526000825180602084015260005b8181101561020957602081860181015160408684010152016101ec565b506000604082850101526040601f19601f83011684010191505092915050565b600181811c9082168061023d57607f821691505b60208210810361025d57634e487b7160e01b600052602260045260246000fd5b50919050565b601f8211156102ad57806000526020600020601f840160051c8101602085101561028a5750805b601f840160051c820191505b818110156102aa5760008155600101610296565b50505b505050565b815167ffffffffffffffff8111156102cc576102cc61010c565b6102e0816102da8454610229565b84610263565b6020601f82116001811461031457600083156102fc5750848201515b600019600385901b1c1916600184901b1784556102aa565b600084815260208120601f198516915b828110156103445787850151825560209485019460019092019101610324565b50848210156103625786840151600019600387901b60f8161c191681555b50505050600190811b0190555056fea26469706673582212200901b2e271d38e15a461cb148f993399b3ccb61d788adadb0e62f7d9526a4ff764736f6c634300081a0033", "deployedBytecode": "0x608060405234801561001057600080fd5b50600436106100365760003560e01c8063368b87721461003b578063e21f37ce14610050575b600080fd5b61004e610049366004610122565b61006e565b005b61005861007e565b60405161006591906101db565b60405180910390f35b600061007a82826102b2565b5050565b6000805461008b90610229565b80601f01602080910402602001604051908101604052809291908181526020018280546100b790610229565b80156101045780601f106100d957610100808354040283529160200191610104565b820191906000526020600020905b8154815290600101906020018083116100e757829003601f168201915b505050505081565b634e487b7160e01b600052604160045260246000fd5b60006020828403121561013457600080fd5b813567ffffffffffffffff81111561014b57600080fd5b8201601f8101841361015c57600080fd5b803567ffffffffffffffff8111156101765761017661010c565b604051601f8201601f19908116603f0116810167ffffffffffffffff811182821017156101a5576101a561010c565b6040528181528282016020018610156101bd57600080fd5b81602084016020830137600091810160200191909152949350505050565b602081526000825180602084015260005b8181101561020957602081860181015160408684010152016101ec565b506000604082850101526040601f19601f83011684010191505092915050565b600181811c9082168061023d57607f821691505b60208210810361025d57634e487b7160e01b600052602260045260246000fd5b50919050565b601f8211156102ad57806000526020600020601f840160051c8101602085101561028a5750805b601f840160051c820191505b818110156102aa5760008155600101610296565b50505b505050565b815167ffffffffffffffff8111156102cc576102cc61010c565b6102e0816102da8454610229565b84610263565b6020601f82116001811461031457600083156102fc5750848201515b600019600385901b1c1916600184901b1784556102aa565b600084815260208120601f198516915b828110156103445787850151825560209485019460019092019101610324565b50848210156103625786840151600019600387901b60f8161c191681555b50505050600190811b0190555056fea26469706673582212200901b2e271d38e15a461cb148f993399b3ccb61d788adadb0e62f7d9526a4ff764736f6c634300081a0033", "linkReferences": {}, "deployedLinkReferences": {} } ================================================ FILE: 05-Hello-World-Dapp/frontend/src/HelloWorld.css ================================================ /* Container for the entire component */ .container { display: flex; flex-direction: column; align-items: center; justify-content: center; height: 100vh; /* Full viewport height */ width: 100vw; /* Full viewport width */ background-color: #2e2e2e; /* Darker gray background */ color: #e0e0e0; /* Light gray text for better readability */ padding: 20px; box-sizing: border-box; /* Ensure padding is included in height and width */ } /* Style for the logo */ .logo { width: 200px; /* Larger size for visibility */ margin-bottom: 40px; border-radius: 10px; /* Rounded corners for the logo */ box-shadow: 0 4px 8px rgba(0, 0, 0, 0.5); /* Shadow for depth */ } /* Style for the retrieve button and update button */ .retrieve-button, .update-button { background-color: #ff920f; /* Updated orange color */ color: white; border: none; padding: 14px 28px; /* Slightly larger padding */ margin: 10px; cursor: pointer; border-radius: 8px; font-size: 18px; transition: background-color 0.3s ease, transform 0.2s ease; } .retrieve-button:hover, .update-button:hover { background-color: #e67e22; /* Darker orange for hover effect */ transform: scale(1.05); /* Slightly enlarge button on hover */ } /* Style for the message display */ .message-display { font-size: 28px; /* Larger font size for better visibility */ margin-bottom: 20px; /* Space below the message */ font-weight: bold; color: #ffd54f; /* Bright yellow color for contrast */ } /* Style for the input field */ .input-field { padding: 14px; border: 1px solid #555; /* Darker border for visibility */ border-radius: 8px; width: 80%; max-width: 500px; /* Increased max-width for larger screens */ margin-bottom: 20px; /* Space below the input field */ font-size: 18px; background-color: #424242; /* Slightly lighter gray for input background */ color: #fff; /* White text color for the input field */ transition: background-color 0.3s ease, border-color 0.3s ease; } /* Adding gap specifically between input field and retrieve button */ .retrieve-button { margin-top: 20px; /* Adjust the gap as needed */ } .input-field:focus { background-color: #616161; /* Lighter gray on focus */ border-color: #ff920f; /* Orange border on focus */ outline: none; } ================================================ FILE: 05-Hello-World-Dapp/frontend/src/HelloWorld.js ================================================ import React, { useState, useEffect } from 'react'; import { ethers } from 'ethers'; import { toast, ToastContainer } from 'react-toastify'; // Import ToastContainer and toast import 'react-toastify/dist/ReactToastify.css'; // Import the CSS for toast notifications import './HelloWorld.css'; // Import the CSS file // Import ABI from JSON file import HelloWorldABI from './Contract-ABI/HelloWorld.json'; // Import the logo image import logo from './core-dao-logo.png'; // Adjust the path as needed // Replace with your contract's address const contractAddress = "0xf5d9Dd0f6EAa91802979707b91407d8448136DD0"; function HelloWorld() { const [message, setMessage] = useState(''); const [newMessage, setNewMessage] = useState(''); //const [provider, setProvider] = useState(null); const [contract, setContract] = useState(null); const [showMessage, setShowMessage] = useState(false); // State to control message visibility useEffect(() => { async function init() { if (!window.ethereum) { toast.error("No crypto wallet found. Please install MetaMask."); return; } try { // Prompt user to connect MetaMask await window.ethereum.request({ method: 'eth_requestAccounts' }); const provider = new ethers.BrowserProvider(window.ethereum); const signer = await provider.getSigner(); const contract = new ethers.Contract(contractAddress, HelloWorldABI.abi, signer); //setProvider(provider); setContract(contract); } catch (error) { toast.error("Failed to connect to MetaMask. Please try again."); console.error("Error initializing MetaMask:", error); } } init(); }, []); const updateMessage = async () => { if (!contract) return; try { const tx = await contract.setMessage(newMessage); await tx.wait(); setNewMessage(''); // Clear the input field after updating toast.success("Message updated successfully!"); } catch (error) { toast.error("Failed to update message. Please try again."); console.error("Error updating message:", error); } }; const retrieveMessage = async () => { if (!contract) return; try { const currentMessage = await contract.message(); setMessage(currentMessage); setShowMessage(true); // Show the message after retrieval toast.success("Message retrieved successfully!"); } catch (error) { toast.error("Failed to retrieve message. Please try again."); console.error("Error retrieving message:", error); } }; return (
{/* Add ToastContainer to display notifications */} Core DAO Logo {showMessage && (
{message}
)}
setNewMessage(e.target.value)} className="input-field" placeholder="Enter new message" />
); } export default HelloWorld; ================================================ FILE: 05-Hello-World-Dapp/frontend/src/index.css ================================================ body { margin: 0; font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'Roboto', 'Oxygen', 'Ubuntu', 'Cantarell', 'Fira Sans', 'Droid Sans', 'Helvetica Neue', sans-serif; -webkit-font-smoothing: antialiased; -moz-osx-font-smoothing: grayscale; } code { font-family: source-code-pro, Menlo, Monaco, Consolas, 'Courier New', monospace; } ================================================ FILE: 05-Hello-World-Dapp/frontend/src/index.js ================================================ import React from 'react'; import ReactDOM from 'react-dom/client'; import './index.css'; import App from './App'; import reportWebVitals from './reportWebVitals'; const root = ReactDOM.createRoot(document.getElementById('root')); root.render( ); // If you want to start measuring performance in your app, pass a function // to log results (for example: reportWebVitals(console.log)) // or send to an analytics endpoint. Learn more: https://bit.ly/CRA-vitals reportWebVitals(); ================================================ FILE: 05-Hello-World-Dapp/frontend/src/reportWebVitals.js ================================================ const reportWebVitals = onPerfEntry => { if (onPerfEntry && onPerfEntry instanceof Function) { import('web-vitals').then(({ getCLS, getFID, getFCP, getLCP, getTTFB }) => { getCLS(onPerfEntry); getFID(onPerfEntry); getFCP(onPerfEntry); getLCP(onPerfEntry); getTTFB(onPerfEntry); }); } }; export default reportWebVitals; ================================================ FILE: 05-Hello-World-Dapp/frontend/src/setupTests.js ================================================ // jest-dom adds custom jest matchers for asserting on DOM nodes. // allows you to do things like: // expect(element).toHaveTextContent(/react/i) // learn more: https://github.com/testing-library/jest-dom import '@testing-library/jest-dom'; ================================================ FILE: 05-Hello-World-Dapp/hardhat.config.js ================================================ require("@nomicfoundation/hardhat-toolbox"); require("dotenv").config(); /** @type import('hardhat/config').HardhatUserConfig */ const PRIVATE_KEY = process.env.PRIVATE_KEY; module.exports = { defaultNetwork: 'hardhat', networks: { hardhat: { }, core_testnet: { url: 'https://rpc.test2.btcs.network', accounts: [PRIVATE_KEY], chainId: 1114, } }, solidity: { compilers: [ { version: '0.8.26', settings: { evmVersion: 'shanghai', optimizer: { enabled: true, runs: 200, }, }, }, ], }, paths: { sources: './contracts', cache: './cache', artifacts: './artifacts', }, mocha: { timeout: 60000, }, }; ================================================ FILE: 05-Hello-World-Dapp/ignition/modules/Lock.js ================================================ const { buildModule } = require("@nomicfoundation/hardhat-ignition/modules"); const JAN_1ST_2030 = 1893456000; const ONE_GWEI = 1_000_000_000n; module.exports = buildModule("LockModule", (m) => { const unlockTime = m.getParameter("unlockTime", JAN_1ST_2030); const lockedAmount = m.getParameter("lockedAmount", ONE_GWEI); const lock = m.contract("Lock", [unlockTime], { value: lockedAmount, }); return { lock }; }); ================================================ FILE: 05-Hello-World-Dapp/npx ================================================ ================================================ FILE: 05-Hello-World-Dapp/package.json ================================================ { "name": "hardhat-project", "devDependencies": { "@nomicfoundation/hardhat-toolbox": "^5.0.0", "hardhat": "^2.22.7" }, "description": "This project demonstrates a basic Hardhat use case. It comes with a sample contract, a test for that contract, and a Hardhat Ignition module that deploys that contract.", "version": "1.0.0", "main": "hardhat.config.js", "directories": { "test": "test" }, "dependencies": { "dotenv": "^16.5.0" }, "scripts": { "test": "mocha" }, "keywords": [], "author": "", "license": "ISC" } ================================================ FILE: 05-Hello-World-Dapp/scripts/deploy.js ================================================ const { ethers } = require("hardhat"); async function main() { const [deployer] = await ethers.getSigners(); console.log("Deploying contract with the account:", deployer.address); const HelloWorld = await ethers.getContractFactory("HelloWorld"); const helloWorld = await HelloWorld.deploy("Hello, World"); console.log("HelloWorld Contract Address:", await helloWorld.getAddress()); } main() .then(() => process.exit(0)) .catch((error) => { console.error(error); process.exit(1); }); ================================================ FILE: 05-Hello-World-Dapp/test/HelloWorld.js ================================================ const { expect } = require("chai"); describe("HelloWorld contract", function () { let HelloWorld; let helloWorld; let owner; beforeEach(async function () { HelloWorld = await ethers.getContractFactory("HelloWorld"); [owner] = await ethers.getSigners(); helloWorld = await HelloWorld.deploy("Hello, world!"); await helloWorld.waitForDeployment(); }); it("Should return the initial message", async function () { expect(await helloWorld.message()).to.equal("Hello, world!"); }); it("Should update the message", async function () { const tx =await helloWorld.setMessage("Hello, Hardhat!"); await tx.wait(); // Wait for the transaction to be mined expect(await helloWorld.message()).to.equal("Hello, Hardhat!"); }); }); ================================================ FILE: 06-Subgraphs-on-Core/README.md ================================================ # Guestbook Subgraph This repository contains the subgraph for the Guestbook application on the Core Network. The subgraph indexes events and data from the Guestbook smart contract, allowing for easy querying using GraphQL. ## Table of Contents - [Prerequisites](#prerequisites) - [Clone the Repository](#clone-the-repository) - [Configuration](#configuration) - [Install Dependencies](#install-dependencies) - [Deploying with Docker](#deploying-with-docker) - [Deploying the Subgraph](#deploying-the-subgraph) - [Interacting with the Subgraph](#interacting-with-the-subgraph) - [Troubleshooting](#troubleshooting) ## Prerequisites Before you begin, ensure you have the following installed: - [Node.js](https://nodejs.org/en/) (v14 or later) - [npm](https://www.npmjs.com/) - [Docker](https://www.docker.com/) - [Git](https://git-scm.com/) ## Clone the Repository To clone the repository locally, run the following commands: ```bash git clone https://github.com/coredao-org/dapp-tutorial.git cd dapp-tutorial/06-Subgraphs-on-Core ``` ## Configuration ### Environment Variables You need to set up the following environment variables to configure deployment: Create a .env file in the root directory: ```bash touch.env ``` 2. Add the necessary environment variables to the .env file: ```env GRAPH_NODE=https://thegraph-node.test.btcs.network/ IPFS_NODE=https://thegraph-ipfs.test.btcs.network/ GRAPH_ACCESS_TOKEN=your_access_token_here ``` ### Subgraph Configuration Ensure your subgraph.yaml file is correctly set up with the necessary contract addresses and start blocks. ```zsh npm install ``` This will install all required packages including @graphprotocol/graph-cli and @graphprotocol/graph-ts. ## Deploying with Docker You can deploy your subgraph using Docker to simulate a local environment. 1. Build and Start Docker Containers: ```zsh docker-compose up -d ``` 2. Check Docker Containers: ```zsh docker ps ``` Ensure all necessary containers are running. ## Deploying the Subgraph ### Authenticate with Graph Node If not already authenticated, authenticate your deployment key: ```zsh export GRAPH_ACCESS_TOKEN=08e38ec0513b40fd9b6a4428923d06ac ``` ### Generate code and build the subgraph: ```bash graph codegen graph build ``` ### Create and Deploy Subgraph ``` graph create \ --node $GRAPH_NODE \ --access-token $GRAPH_ACCESS_TOKEN \ your-subgraph-name ``` ``` graph deploy \ --node $GRAPH_NODE \ --ipfs $IPFS_NODE \ --access-token $GRAPH_ACCESS_TOKEN \ your-subgraph-name ``` Replace your-subgraph-name with your deployment target. ### Query the Subgraph After deployment, your subgraph will be available at the query endpoint (e.g., https://thegraph.test2.btcs.network/subgraphs/name/guestbook-subgraph). Example query: ``` { entrySigneds(first: 10, orderBy: blockTimestamp, orderDirection: desc) { id name message blockNumber blockTimestamp transactionHash } } ``` You can use GraphQL, Apollo Client, or any GraphQL tool to query your data. ================================================ FILE: 06-Subgraphs-on-Core/abis/Guestbook.json ================================================ [ { "anonymous": false, "inputs": [ { "indexed": false, "internalType": "string", "name": "name", "type": "string" }, { "indexed": false, "internalType": "string", "name": "message", "type": "string" } ], "name": "EntrySigned", "type": "event" }, { "inputs": [{ "internalType": "uint256", "name": "", "type": "uint256" }], "name": "entries", "outputs": [ { "internalType": "string", "name": "name", "type": "string" }, { "internalType": "string", "name": "message", "type": "string" } ], "stateMutability": "view", "type": "function" }, { "inputs": [], "name": "getEntries", "outputs": [ { "components": [ { "internalType": "string", "name": "name", "type": "string" }, { "internalType": "string", "name": "message", "type": "string" } ], "internalType": "struct Guestbook.Entry[]", "name": "", "type": "tuple[]" } ], "stateMutability": "view", "type": "function" }, { "inputs": [ { "internalType": "string", "name": "_name", "type": "string" }, { "internalType": "string", "name": "_message", "type": "string" } ], "name": "signGuestbook", "outputs": [], "stateMutability": "nonpayable", "type": "function" } ] ================================================ FILE: 06-Subgraphs-on-Core/build/Guestbook/Guestbook.json ================================================ [ { "anonymous": false, "inputs": [ { "indexed": false, "internalType": "string", "name": "name", "type": "string" }, { "indexed": false, "internalType": "string", "name": "message", "type": "string" } ], "name": "EntrySigned", "type": "event" }, { "inputs": [ { "internalType": "uint256", "name": "", "type": "uint256" } ], "name": "entries", "outputs": [ { "internalType": "string", "name": "name", "type": "string" }, { "internalType": "string", "name": "message", "type": "string" } ], "stateMutability": "view", "type": "function" }, { "inputs": [], "name": "getEntries", "outputs": [ { "components": [ { "internalType": "string", "name": "name", "type": "string" }, { "internalType": "string", "name": "message", "type": "string" } ], "internalType": "struct Guestbook.Entry[]", "name": "", "type": "tuple[]" } ], "stateMutability": "view", "type": "function" }, { "inputs": [ { "internalType": "string", "name": "_name", "type": "string" }, { "internalType": "string", "name": "_message", "type": "string" } ], "name": "signGuestbook", "outputs": [], "stateMutability": "nonpayable", "type": "function" } ] ================================================ FILE: 06-Subgraphs-on-Core/build/schema.graphql ================================================ type EntrySigned @entity(immutable: true) { id: Bytes! name: String! # string message: String! # string blockNumber: BigInt! blockTimestamp: BigInt! transactionHash: Bytes! } ================================================ FILE: 06-Subgraphs-on-Core/build/subgraph.yaml ================================================ specVersion: 1.0.0 indexerHints: prune: auto schema: file: schema.graphql dataSources: - kind: ethereum name: Guestbook network: core source: address: "0x0D0b3bAc514d53AafC95c74294Bb1B613D1862c2" abi: Guestbook startBlock: 22122890 mapping: kind: ethereum/events apiVersion: 0.0.7 language: wasm/assemblyscript entities: - EntrySigned abis: - name: Guestbook file: Guestbook/Guestbook.json eventHandlers: - event: EntrySigned(string,string) handler: handleEntrySigned file: Guestbook/Guestbook.wasm ================================================ FILE: 06-Subgraphs-on-Core/docker-compose.yml ================================================ version: "3" services: graph-node: image: graphprotocol/graph-node ports: - "8000:8000" - "8001:8001" - "8020:8020" - "8030:8030" - "8040:8040" depends_on: - ipfs - postgres extra_hosts: - host.docker.internal:host-gateway environment: postgres_host: postgres postgres_user: graph-node postgres_pass: let-me-in postgres_db: graph-node ipfs: "ipfs:5001" ethereum: "core-testnet:https://rpc.test.btcs.network" GRAPH_LOG: info ipfs: image: ipfs/kubo:v0.17.0 ports: - "5001:5001" volumes: - ./data/ipfs:/data/ipfs postgres: image: postgres:14 ports: - "5432:5432" command: [ "postgres", "-cshared_preload_libraries=pg_stat_statements", "-cmax_connections=200", ] environment: POSTGRES_USER: graph-node POSTGRES_PASSWORD: let-me-in POSTGRES_DB: graph-node # FIXME: remove this env. var. which we shouldn't need. Introduced by # , maybe as a # workaround for https://github.com/docker/for-mac/issues/6270? PGDATA: "/var/lib/postgresql/data" POSTGRES_INITDB_ARGS: "-E UTF8 --locale=C" volumes: - ./data/postgres:/var/lib/postgresql/data ================================================ FILE: 06-Subgraphs-on-Core/generated/Guestbook/Guestbook.ts ================================================ // THIS IS AN AUTOGENERATED FILE. DO NOT EDIT THIS FILE DIRECTLY. import { ethereum, JSONValue, TypedMap, Entity, Bytes, Address, BigInt, } from "@graphprotocol/graph-ts"; export class EntrySigned extends ethereum.Event { get params(): EntrySigned__Params { return new EntrySigned__Params(this); } } export class EntrySigned__Params { _event: EntrySigned; constructor(event: EntrySigned) { this._event = event; } get name(): string { return this._event.parameters[0].value.toString(); } get message(): string { return this._event.parameters[1].value.toString(); } } export class Guestbook__entriesResult { value0: string; value1: string; constructor(value0: string, value1: string) { this.value0 = value0; this.value1 = value1; } toMap(): TypedMap { let map = new TypedMap(); map.set("value0", ethereum.Value.fromString(this.value0)); map.set("value1", ethereum.Value.fromString(this.value1)); return map; } getName(): string { return this.value0; } getMessage(): string { return this.value1; } } export class Guestbook__getEntriesResultValue0Struct extends ethereum.Tuple { get name(): string { return this[0].toString(); } get message(): string { return this[1].toString(); } } export class Guestbook extends ethereum.SmartContract { static bind(address: Address): Guestbook { return new Guestbook("Guestbook", address); } entries(param0: BigInt): Guestbook__entriesResult { let result = super.call("entries", "entries(uint256):(string,string)", [ ethereum.Value.fromUnsignedBigInt(param0), ]); return new Guestbook__entriesResult( result[0].toString(), result[1].toString(), ); } try_entries(param0: BigInt): ethereum.CallResult { let result = super.tryCall("entries", "entries(uint256):(string,string)", [ ethereum.Value.fromUnsignedBigInt(param0), ]); if (result.reverted) { return new ethereum.CallResult(); } let value = result.value; return ethereum.CallResult.fromValue( new Guestbook__entriesResult(value[0].toString(), value[1].toString()), ); } getEntries(): Array { let result = super.call( "getEntries", "getEntries():((string,string)[])", [], ); return result[0].toTupleArray(); } try_getEntries(): ethereum.CallResult< Array > { let result = super.tryCall( "getEntries", "getEntries():((string,string)[])", [], ); if (result.reverted) { return new ethereum.CallResult(); } let value = result.value; return ethereum.CallResult.fromValue( value[0].toTupleArray(), ); } } export class SignGuestbookCall extends ethereum.Call { get inputs(): SignGuestbookCall__Inputs { return new SignGuestbookCall__Inputs(this); } get outputs(): SignGuestbookCall__Outputs { return new SignGuestbookCall__Outputs(this); } } export class SignGuestbookCall__Inputs { _call: SignGuestbookCall; constructor(call: SignGuestbookCall) { this._call = call; } get _name(): string { return this._call.inputValues[0].value.toString(); } get _message(): string { return this._call.inputValues[1].value.toString(); } } export class SignGuestbookCall__Outputs { _call: SignGuestbookCall; constructor(call: SignGuestbookCall) { this._call = call; } } ================================================ FILE: 06-Subgraphs-on-Core/generated/schema.ts ================================================ // THIS IS AN AUTOGENERATED FILE. DO NOT EDIT THIS FILE DIRECTLY. import { TypedMap, Entity, Value, ValueKind, store, Bytes, BigInt, BigDecimal, } from "@graphprotocol/graph-ts"; export class EntrySigned extends Entity { constructor(id: Bytes) { super(); this.set("id", Value.fromBytes(id)); } save(): void { let id = this.get("id"); assert(id != null, "Cannot save EntrySigned entity without an ID"); if (id) { assert( id.kind == ValueKind.BYTES, `Entities of type EntrySigned must have an ID of type Bytes but the id '${id.displayData()}' is of type ${id.displayKind()}`, ); store.set("EntrySigned", id.toBytes().toHexString(), this); } } static loadInBlock(id: Bytes): EntrySigned | null { return changetype( store.get_in_block("EntrySigned", id.toHexString()), ); } static load(id: Bytes): EntrySigned | null { return changetype( store.get("EntrySigned", id.toHexString()), ); } get id(): Bytes { let value = this.get("id"); if (!value || value.kind == ValueKind.NULL) { throw new Error("Cannot return null for a required field."); } else { return value.toBytes(); } } set id(value: Bytes) { this.set("id", Value.fromBytes(value)); } get name(): string { let value = this.get("name"); if (!value || value.kind == ValueKind.NULL) { throw new Error("Cannot return null for a required field."); } else { return value.toString(); } } set name(value: string) { this.set("name", Value.fromString(value)); } get message(): string { let value = this.get("message"); if (!value || value.kind == ValueKind.NULL) { throw new Error("Cannot return null for a required field."); } else { return value.toString(); } } set message(value: string) { this.set("message", Value.fromString(value)); } get blockNumber(): BigInt { let value = this.get("blockNumber"); if (!value || value.kind == ValueKind.NULL) { throw new Error("Cannot return null for a required field."); } else { return value.toBigInt(); } } set blockNumber(value: BigInt) { this.set("blockNumber", Value.fromBigInt(value)); } get blockTimestamp(): BigInt { let value = this.get("blockTimestamp"); if (!value || value.kind == ValueKind.NULL) { throw new Error("Cannot return null for a required field."); } else { return value.toBigInt(); } } set blockTimestamp(value: BigInt) { this.set("blockTimestamp", Value.fromBigInt(value)); } get transactionHash(): Bytes { let value = this.get("transactionHash"); if (!value || value.kind == ValueKind.NULL) { throw new Error("Cannot return null for a required field."); } else { return value.toBytes(); } } set transactionHash(value: Bytes) { this.set("transactionHash", Value.fromBytes(value)); } } ================================================ FILE: 06-Subgraphs-on-Core/networks.json ================================================ { "core": { "Guestbook": { "address": "0x0D0b3bAc514d53AafC95c74294Bb1B613D1862c2", "startBlock": 22122890 } } } ================================================ FILE: 06-Subgraphs-on-Core/package.json ================================================ { "name": "guestbook-subgraph", "license": "UNLICENSED", "scripts": { "codegen": "graph codegen", "build": "graph build", "deploy": "graph deploy --node https://api.studio.thegraph.com/deploy/ guestbook-subgraph", "create-local": "graph create --node http://localhost:8020/ guestbook-subgraph", "remove-local": "graph remove --node http://localhost:8020/ guestbook-subgraph", "deploy-local": "graph deploy --node http://localhost:8020/ --ipfs http://localhost:5001 guestbook-subgraph", "test": "graph test" }, "dependencies": { "@graphprotocol/graph-cli": "0.80.0", "@graphprotocol/graph-ts": "0.32.0" }, "devDependencies": { "matchstick-as": "0.5.0" } } ================================================ FILE: 06-Subgraphs-on-Core/schema.graphql ================================================ type EntrySigned @entity(immutable: true) { id: Bytes! name: String! # string message: String! # string blockNumber: BigInt! blockTimestamp: BigInt! transactionHash: Bytes! } ================================================ FILE: 06-Subgraphs-on-Core/src/guestbook.ts ================================================ import { EntrySigned as EntrySignedEvent } from "../generated/Guestbook/Guestbook" import { EntrySigned } from "../generated/schema" export function handleEntrySigned(event: EntrySignedEvent): void { let entity = new EntrySigned( event.transaction.hash.concatI32(event.logIndex.toI32()) ) entity.name = event.params.name entity.message = event.params.message entity.blockNumber = event.block.number entity.blockTimestamp = event.block.timestamp entity.transactionHash = event.transaction.hash entity.save() } ================================================ FILE: 06-Subgraphs-on-Core/subgraph.yaml ================================================ specVersion: 1.0.0 indexerHints: prune: auto schema: file: ./schema.graphql dataSources: - kind: ethereum name: Guestbook network: core source: address: "0x0D0b3bAc514d53AafC95c74294Bb1B613D1862c2" abi: Guestbook startBlock: 22122890 mapping: kind: ethereum/events apiVersion: 0.0.7 language: wasm/assemblyscript entities: - EntrySigned abis: - name: Guestbook file: ./abis/Guestbook.json eventHandlers: - event: EntrySigned(string,string) handler: handleEntrySigned file: ./src/guestbook.ts ================================================ FILE: 06-Subgraphs-on-Core/tests/guestbook-utils.ts ================================================ import { newMockEvent } from "matchstick-as" import { ethereum } from "@graphprotocol/graph-ts" import { EntrySigned } from "../generated/Guestbook/Guestbook" export function createEntrySignedEvent( name: string, message: string ): EntrySigned { let entrySignedEvent = changetype(newMockEvent()) entrySignedEvent.parameters = new Array() entrySignedEvent.parameters.push( new ethereum.EventParam("name", ethereum.Value.fromString(name)) ) entrySignedEvent.parameters.push( new ethereum.EventParam("message", ethereum.Value.fromString(message)) ) return entrySignedEvent } ================================================ FILE: 06-Subgraphs-on-Core/tests/guestbook.test.ts ================================================ import { assert, describe, test, clearStore, beforeAll, afterAll } from "matchstick-as/assembly/index" import {} from "@graphprotocol/graph-ts" import { EntrySigned } from "../generated/schema" import { EntrySigned as EntrySignedEvent } from "../generated/Guestbook/Guestbook" import { handleEntrySigned } from "../src/guestbook" import { createEntrySignedEvent } from "./guestbook-utils" // Tests structure (matchstick-as >=0.5.0) // https://thegraph.com/docs/en/developer/matchstick/#tests-structure-0-5-0 describe("Describe entity assertions", () => { beforeAll(() => { let name = "Example string value" let message = "Example string value" let newEntrySignedEvent = createEntrySignedEvent(name, message) handleEntrySigned(newEntrySignedEvent) }) afterAll(() => { clearStore() }) // For more test scenarios, see: // https://thegraph.com/docs/en/developer/matchstick/#write-a-unit-test test("EntrySigned created and stored", () => { assert.entityCount("EntrySigned", 1) // 0xa16081f360e3847006db660bae1c6d1b2e17ec2a is the default address used in newMockEvent() function assert.fieldEquals( "EntrySigned", "0xa16081f360e3847006db660bae1c6d1b2e17ec2a-1", "name", "Example string value" ) assert.fieldEquals( "EntrySigned", "0xa16081f360e3847006db660bae1c6d1b2e17ec2a-1", "message", "Example string value" ) // More assert options: // https://thegraph.com/docs/en/developer/matchstick/#asserts }) }) ================================================ FILE: 06-Subgraphs-on-Core/tsconfig.json ================================================ { "extends": "@graphprotocol/graph-ts/types/tsconfig.base.json", "include": ["src", "tests"] } ================================================ FILE: 07-NFT Minitng dApp on Core/.gitignore ================================================ node_modules .env # Hardhat files /cache /artifacts # TypeChain files /typechain /typechain-types # solidity-coverage files /coverage /coverage.json # Hardhat Ignition default folder for deployments against a local node ignition/deployments/chain-31337 secret.json ================================================ FILE: 07-NFT Minitng dApp on Core/README.md ================================================ # Building NFT Minting DApp on Core Welcome to this tutorial where we will build a simple NFT Minting DApp on Core Blockchain from scratch. We will make a basic DApp where you will be able to mint NFTs from the frontend app. By the end of the tutorial, we will have a functional dapp that interacts with smart contracts on the Core Blockchain Testnet. Let’s start🙌 ## Learning Takeaways - Smart Contract Development in Solidity programming language - Building frontend using React.js - Using Ethers.js library for interaction of frontend with smart contracts - Integrating Metamask wallet for secure user transactions - Read and write data to/from smart contracts ## Software Prerequisites - [Git](https://git-scm.com/) - [Node.js](https://nodejs.org/en) v20.13.1 - [Yarn](https://yarnpkg.com/) v1.22.21 - [Hardhat](https://hardhat.org/) v2.20.1 - [Metamask Wallet](https://metamask.io/download/) - **Core Testnet Configuration**: Configure MetaMask to connect to the Core Testnet. Refer here for more details. - **Network Name**: Core Testnet - **New RPC URL**: [https://rpc.test2.btcs.network](https://rpc.test2.btcs.network) - **Chain ID**: 1114 - **Currency Symbol**: TCORE2 - **Core Faucet**: To get test CORE tokens for transactions, visit the Core Faucet, refer [here](https://docs.coredao.org/docs/Dev-Guide/core-faucet) for more details. ## Setting up Dev Environment ### 1. Initialize the project We will create a new director `NFT_Minting` and initialize our project using `yarn`. ```bash mkdir NFT_Minting cd NFT_Minting yarn init -y yarn add --dev hardhat yard hardhat init ``` ![img](./assets/pic1.png) Select the `Create a Javascript project` Select the default project root directory Select yes adding a `.gitignore` and installing additional packages ### 2. Install and Configure MetaMask - Install and configure MetaMask Chrome Extension to use with Core Testnet. - Refer [here](https://docs.coredao.org/docs/Dev-Guide/core-testnet-wallet-config) for a detailed guide. ### 3. Create a Secret File - Create a `.env` file in the root folder and store the private key of your MetaMask wallet in it. ```bash PRIVATE_KEY = ``` ### 4. Update .gitignore - Update your .gitignore file to ensure that your secret.json file and other sensitive files are not committed to version control. - Make sure to add `secret.json` to the `.gitignore` file. ### 5. Update the `hardhat.config.js` file Replace the contents of `hardhat.config.js` file with the following code. Make sure that the configuration for Core Testnet are set correctly. ```javascript require("@nomicfoundation/hardhat-toolbox"); require("dotenv").config(); /** @type import('hardhat/config').HardhatUserConfig */ const PRIVATE_KEY = process.env.PRIVATE_KEY; module.exports = { solidity: "0.8.24", defaultNetwork: "core_testnet", networks: { hardhat: {}, core_testnet: { url: "https://rpc.test.btcs.network", accounts: [PRIVATE_KEY], chainId: 1115, }, }, solidity: { compilers: [ { version: "0.8.24", settings: { evmVersion: "shanghai", optimizer: { enabled: true, runs: 200, }, }, }, ], }, paths: { sources: "./contracts", cache: "./cache", artifacts: "./artifacts", }, mocha: { timeout: 20000, }, }; ``` Your folder structure should look something like this. ![img](./assets/pic2.png) ## Writing smart contracts Awsome! Now lets jump in the exciting stuff and start writing our smart contracts. Go to the `contracts` folder and create a new file with the name `MyNFT.sol`. But before writing any code, we need to install the `@openzeppelin/contracts` library to implement our NFT smart contracts. Download it by running this command: ```bash yarn add @openzeppelin/contracts ``` After the download completes we can write our smart contract: ```js // SPDX-License-Identifier: UNLICENSED pragma solidity ^0.8.24; import "@openzeppelin/contracts/token/ERC721/ERC721.sol"; import "@openzeppelin/contracts/token/ERC721/extensions/ERC721URIStorage.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; contract Nft is ERC721, ERC721URIStorage, Ownable { uint256 private _nextTokenId; constructor() ERC721("MyNFT", "MYN") Ownable(msg.sender) {} function safeMint(address to, string memory uri) public { uint256 tokenId = _nextTokenId++; _safeMint(to, tokenId); _setTokenURI(tokenId, uri); } // The following functions are overrides required by Solidity. function tokenURI( uint256 tokenId ) public view override(ERC721, ERC721URIStorage) returns (string memory) { return super.tokenURI(tokenId); } function supportsInterface( bytes4 interfaceId ) public view override(ERC721, ERC721URIStorage) returns (bool) { return super.supportsInterface(interfaceId); } } ``` In this code, we - Import the `ERC721`, `ERC721URIStorage`, and `Ownable` classes from the openzeppelin/contracts library for creating a new NFT smart contract. - Initialize a private state variable `_nextTokenId` to store the ID of the NFT. - The constructor initializes the ERC721 contract with a name and symbol, and sets up the `Ownable` contract with the owner's address to restrict NFT minting to the owner. - The `safeMint` function mints a new NFT, taking the recipient's address and the NFT's URI as arguments. - The `tokenURI` and `supportsInterface` functions override required methods from `ERC721` and `ERC721URIStorage`. In the `safeMint` function, we - Increment the `_nextTokenId` variable to get the next token ID. - Mint the NFT to the user using the `_safeMint` function. - Set the URI of the NFT using the `_setTokenURI` function. The uri is the metadata of the NFT, which holds the image, name, and other details of the NFT. ## Compiling and Deploying the Smart Contract Great, Now run the following command to complie the contract ```bash yarn hardhat compile ``` If the compilation is successful, you should see something like this: ![img](./assets/image.png) Now let us deploy the smart contract to the Core Testnet. For this, create a new folder in your root directory and name it `scripts`. Inside the `scripts` folder, create a new file named `deploy.js` and write the following code: ```js const { ethers } = require("hardhat"); async function main() { const [deployer] = await ethers.getSigners(); console.log("Deploying contracts with the account:", deployer.address); const MyNFT = await ethers.getContractFactory("MyNFT"); const myNft = await MyNFT.deploy(); console.log("Token address:", await myNft.getAddress()); } main() .then(() => process.exit(0)) .catch((error) => { console.error(error); process.exit(1); }); ``` Make sure your metamask wallet has tCORE testnet tokens to deploy the contract. If not, visit the [Core Faucet](https://scan.test2.btcs.network/faucet) to get some testnet CORE tokens. Great! Now run the following command in the root directory of your project to deploy the smart contract: ```bash yarn hardhat run scripts/deploy.js ``` If the deployment is successful, you should see the address of the deployed contract in the console. ![img](./assets/pic3.png) Make sure to save this address as we will need it later to interact with the smart contract. ## Building the Frontend Awsome! We have deployed our smart contract to the Core Testnet. Now let's build the frontend of our DApp. We will use **Vite** and **React** to build our frontend. Go to the root directory of your project and run the following command: ```bash yarn create vite frontend ``` ![img](./assets/pic4.png) Select **React** from the `Select a framework` option and **Javascript** from `Select a variant` option. Now we will use the **Ethers.js** library to interact with our smart contracts. Install it in the frontend directory. ```bash yarn add ethers ``` To interact with the smart contract, we also need the ABI (Application Binary Interface) along with address of the deployed contract. We can get the ABI from the `artifacts` folder in the root directory of the project. Create a new directory in the `src` folder, name it `abis` and create a new file `MyNFTAbi.json` . Now copy the ABI of the `MyNFT` contract and paste it in the `MyNFTAbi.json` file. Excellent, now let's write code to connect our metamask wallet in the `App.jsx` file. ```javascript import { useEffect, useState } from "react"; import { ethers } from "ethers"; import MyNFTAbi from "./abis/MyNFTAbi.json"; import "./App.css"; function App() { const [walletAddress, setWalletAddress] = useState(); const [provider, setProvider] = useState(); const [signer, setSigner] = useState(); const contractAddress = "0x984eE96FE316006533c0BB78c97e3A02E41c7759"; // Replace contract address const abi = MyNFTAbi.abi; async function connectWallet() { const { ethereum } = window; if (!ethereum) { alert("Please install MetaMask!"); return; } try { const provider = new ethers.BrowserProvider(ethereum); const [account] = await ethereum.request({ method: "eth_requestAccounts", }); const signer = provider.getSigner(); setProvider(provider); setSigner(signer); setWalletAddress(account); } catch (error) { console.log("Error fetching network:", error); } } useEffect(() => { connectWallet(); }, []); return ( <>

NFT Minting Dapp

{walletAddress ? (

Connected Address: {walletAddress}

) : ( )} ); } export default App; ``` Now run `yarn dev` command in the frontend directory, open the app in your browser on `http://localhost:5173`. You should see your metamaks wallet prompt you to connect to the website. ![img](./assets/pic5.png) Make sure to connect that account only which you have used to deploy the contract. Since we have used the `Ownable` class in our contract, we will face errors if we try to mint the NFT in other accounts. By clicking `Next` and `Confirm`, our wallet will be connected to the website and we will see our address on the screen. ![img](./assets/pic6.png) Wonderful! Now we will write code to show the nft image and mint it in our wallet. We will also add code to show our NFT image and button to mint in our wallet ```javascript const nftImage = "https://raw.githubusercontent.com/GM-11/NFT_Minting_Tutorial_Core/main/assets/nft.png" const nftUri = "https://raw.githubusercontent.com/GM-11/NFT_Minting_Tutorial_Core/main/assets/metadata.json" ``` For this tutorial, you can copy these links as it is. ```javascript

NFT Minting Dapp

; { walletAddress ? (

Connected Address: {walletAddress}


) : ( ); } ``` Now our app will look something like this ![img](./assets/pic7.png) Now let's make a function to mint our NFT in our MetaMask wallet. ```javascript async function mintNFT() { try { const contract = new ethers.Contract(contractAddress, abi, signer); const tx = await contract.safeMint(walletAddress, nftUri); await tx.wait(); } catch (error) { console.log("Error minting NFT:", error); } } ``` In this function, we are - Creating a new instance of the contract using the contract address and ABI. - Calling the `safeMint` function of the contract to mint the NFT. The `safeMint` function takes two arguments, the address of the user to whom the NFT will be minted and the URI of the NFT. - Waiting for the transaction to be confirmed and then showing an alert that the NFT has been minted successfully. Now let's call this function when the user clicks the mint button. ```javascript ``` When we click the `**Mint this NFT** button, our wallet should prompt us to sign the transaction ![img](./assets/pic9.png) Click on **Confirm** to confirm the transaction. Awsome! We have minted our first NFT on the Core Blockchain!🥳 But wait, why can't we see it?🤔 ![img](./assets/pic10.png) Well since this NFT is on the testnet, metamask automatically does not detect them. We need to import our NFT into our wallet. Cick on `Import NFT` at the bottom. Add your contract address in the **Address** input field and 0 in the **Token Id** input field and click on **Import**. ![img](./assets/pic11.png) Wonderful, now we can see our nft in the wallet! ## Conclusion 🎉🙌Congratulations, you have created a basic NFT Minting DApp on the Core Testnet. ================================================ FILE: 07-NFT Minitng dApp on Core/assets/metadata.json ================================================ { "name": "Bored Ape", "image" : "https://raw.githubusercontent.com/GM-11/NFT_Minting_Tutorial_Core/master/assets/nft.png", "description": "A bored ape" } ================================================ FILE: 07-NFT Minitng dApp on Core/contracts/Lock.sol ================================================ // SPDX-License-Identifier: UNLICENSED pragma solidity ^0.8.24; // Uncomment this line to use console.log // import "hardhat/console.sol"; contract Lock { uint public unlockTime; address payable public owner; event Withdrawal(uint amount, uint when); constructor(uint _unlockTime) payable { require( block.timestamp < _unlockTime, "Unlock time should be in the future" ); unlockTime = _unlockTime; owner = payable(msg.sender); } function withdraw() public { // Uncomment this line, and the import of "hardhat/console.sol", to print a log in your terminal // console.log("Unlock time is %o and block timestamp is %o", unlockTime, block.timestamp); require(block.timestamp >= unlockTime, "You can't withdraw yet"); require(msg.sender == owner, "You aren't the owner"); emit Withdrawal(address(this).balance, block.timestamp); owner.transfer(address(this).balance); } } ================================================ FILE: 07-NFT Minitng dApp on Core/contracts/MyNFT.sol ================================================ // SPDX-License-Identifier: MIT pragma solidity ^0.8.24; import "@openzeppelin/contracts/token/ERC721/ERC721.sol"; import "@openzeppelin/contracts/token/ERC721/extensions/ERC721URIStorage.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; contract MyNFT is ERC721, ERC721URIStorage, Ownable { uint256 private _nextTokenId; constructor() ERC721("MyNFT", "MYN") Ownable(msg.sender) {} function safeMint(address to, string memory uri) public { uint256 tokenId = _nextTokenId++; _safeMint(to, tokenId); _setTokenURI(tokenId, uri); } // The following functions are overrides required by Solidity. function tokenURI( uint256 tokenId ) public view override(ERC721, ERC721URIStorage) returns (string memory) { return super.tokenURI(tokenId); } function supportsInterface( bytes4 interfaceId ) public view override(ERC721, ERC721URIStorage) returns (bool) { return super.supportsInterface(interfaceId); } } ================================================ FILE: 07-NFT Minitng dApp on Core/frontend/.gitignore ================================================ # Logs logs *.log npm-debug.log* yarn-debug.log* yarn-error.log* pnpm-debug.log* lerna-debug.log* node_modules dist dist-ssr *.local # Editor directories and files .vscode/* !.vscode/extensions.json .idea .DS_Store *.suo *.ntvs* *.njsproj *.sln *.sw? ================================================ FILE: 07-NFT Minitng dApp on Core/frontend/README.md ================================================ # React + Vite This template provides a minimal setup to get React working in Vite with HMR and some ESLint rules. Currently, two official plugins are available: - [@vitejs/plugin-react](https://github.com/vitejs/vite-plugin-react/blob/main/packages/plugin-react/README.md) uses [Babel](https://babeljs.io/) for Fast Refresh - [@vitejs/plugin-react-swc](https://github.com/vitejs/vite-plugin-react-swc) uses [SWC](https://swc.rs/) for Fast Refresh ================================================ FILE: 07-NFT Minitng dApp on Core/frontend/index.html ================================================ Vite + React
================================================ FILE: 07-NFT Minitng dApp on Core/frontend/package.json ================================================ { "name": "frontend", "private": true, "version": "0.0.0", "type": "module", "scripts": { "dev": "vite", "build": "vite build", "lint": "eslint . --ext js,jsx --report-unused-disable-directives --max-warnings 0", "preview": "vite preview" }, "dependencies": { "ethers": "6.13.2", "react": "18.3.1", "react-dom": "18.3.1" }, "devDependencies": { "@types/react": "18.3.3", "@types/react-dom": "18.3.0", "@vitejs/plugin-react": "4.3.1", "eslint": "8.57.0", "eslint-plugin-react": "7.34.3", "eslint-plugin-react-hooks": "4.6.2", "eslint-plugin-react-refresh": "0.4.7", "vite": "5.3.4" } } ================================================ FILE: 07-NFT Minitng dApp on Core/frontend/src/App.css ================================================ ================================================ FILE: 07-NFT Minitng dApp on Core/frontend/src/App.jsx ================================================ import { useEffect, useState } from "react"; import { ethers } from "ethers"; import MyNFTAbi from "./abis/MyNFTAbi.json"; import core_logo from "./assets/core-logo.png"; import "./App.css"; function App() { const [walletAddress, setWalletAddress] = useState(); const [provider, setProvider] = useState(); const [signer, setSigner] = useState(); const contractAddress = "0x8c546a571Ed23c32B7355E5C814589B6F627737D"; const abi = MyNFTAbi.abi; const nftImage = "https://raw.githubusercontent.com/GM-11/NFT_Minting_Tutorial/master/assets/nft.png"; const nftUri = "https://raw.githubusercontent.com/GM-11/NFT_Minting_Tutorial/master/assets/metadata.json"; async function connectWallet() { const { ethereum } = window; if (!ethereum) { alert("Please install MetaMask!"); return; } try { const provider = new ethers.BrowserProvider(ethereum); const [account] = await ethereum.request({ method: "eth_requestAccounts", }); const signer = await provider.getSigner(); setProvider(provider); setSigner(signer); setWalletAddress(account); } catch (error) { console.log("Error fetching network:", error); } } useEffect(() => { connectWallet(); }, []); async function mintNFT() { try { const contract = new ethers.Contract(contractAddress, abi, signer); const tx = await contract.safeMint(walletAddress, nftUri); await tx.wait(); alert("NFT has been minted successfully") } catch (error) { console.log("Error minting NFT:", error); } } return (
akldfj

NFT Minting Dapp

{walletAddress ? (

Connected Address: {walletAddress}


) : ( )}
); } export default App; ================================================ FILE: 07-NFT Minitng dApp on Core/frontend/src/abis/MyNFTAbi.json ================================================ { "_format": "hh-sol-artifact-1", "contractName": "Nft", "sourceName": "contracts/MyNFT.sol", "abi": [ { "inputs": [], "stateMutability": "nonpayable", "type": "constructor" }, { "inputs": [ { "internalType": "address", "name": "sender", "type": "address" }, { "internalType": "uint256", "name": "tokenId", "type": "uint256" }, { "internalType": "address", "name": "owner", "type": "address" } ], "name": "ERC721IncorrectOwner", "type": "error" }, { "inputs": [ { "internalType": "address", "name": "operator", "type": "address" }, { "internalType": "uint256", "name": "tokenId", "type": "uint256" } ], "name": "ERC721InsufficientApproval", "type": "error" }, { "inputs": [ { "internalType": "address", "name": "approver", "type": "address" } ], "name": "ERC721InvalidApprover", "type": "error" }, { "inputs": [ { "internalType": "address", "name": "operator", "type": "address" } ], "name": "ERC721InvalidOperator", "type": "error" }, { "inputs": [ { "internalType": "address", "name": "owner", "type": "address" } ], "name": "ERC721InvalidOwner", "type": "error" }, { "inputs": [ { "internalType": "address", "name": "receiver", "type": "address" } ], "name": "ERC721InvalidReceiver", "type": "error" }, { "inputs": [ { "internalType": "address", "name": "sender", "type": "address" } ], "name": "ERC721InvalidSender", "type": "error" }, { "inputs": [ { "internalType": "uint256", "name": "tokenId", "type": "uint256" } ], "name": "ERC721NonexistentToken", "type": "error" }, { "inputs": [ { "internalType": "address", "name": "owner", "type": "address" } ], "name": "OwnableInvalidOwner", "type": "error" }, { "inputs": [ { "internalType": "address", "name": "account", "type": "address" } ], "name": "OwnableUnauthorizedAccount", "type": "error" }, { "anonymous": false, "inputs": [ { "indexed": true, "internalType": "address", "name": "owner", "type": "address" }, { "indexed": true, "internalType": "address", "name": "approved", "type": "address" }, { "indexed": true, "internalType": "uint256", "name": "tokenId", "type": "uint256" } ], "name": "Approval", "type": "event" }, { "anonymous": false, "inputs": [ { "indexed": true, "internalType": "address", "name": "owner", "type": "address" }, { "indexed": true, "internalType": "address", "name": "operator", "type": "address" }, { "indexed": false, "internalType": "bool", "name": "approved", "type": "bool" } ], "name": "ApprovalForAll", "type": "event" }, { "anonymous": false, "inputs": [ { "indexed": false, "internalType": "uint256", "name": "_fromTokenId", "type": "uint256" }, { "indexed": false, "internalType": "uint256", "name": "_toTokenId", "type": "uint256" } ], "name": "BatchMetadataUpdate", "type": "event" }, { "anonymous": false, "inputs": [ { "indexed": false, "internalType": "uint256", "name": "_tokenId", "type": "uint256" } ], "name": "MetadataUpdate", "type": "event" }, { "anonymous": false, "inputs": [ { "indexed": true, "internalType": "address", "name": "previousOwner", "type": "address" }, { "indexed": true, "internalType": "address", "name": "newOwner", "type": "address" } ], "name": "OwnershipTransferred", "type": "event" }, { "anonymous": false, "inputs": [ { "indexed": true, "internalType": "address", "name": "from", "type": "address" }, { "indexed": true, "internalType": "address", "name": "to", "type": "address" }, { "indexed": true, "internalType": "uint256", "name": "tokenId", "type": "uint256" } ], "name": "Transfer", "type": "event" }, { "inputs": [ { "internalType": "address", "name": "to", "type": "address" }, { "internalType": "uint256", "name": "tokenId", "type": "uint256" } ], "name": "approve", "outputs": [], "stateMutability": "nonpayable", "type": "function" }, { "inputs": [ { "internalType": "address", "name": "owner", "type": "address" } ], "name": "balanceOf", "outputs": [ { "internalType": "uint256", "name": "", "type": "uint256" } ], "stateMutability": "view", "type": "function" }, { "inputs": [ { "internalType": "uint256", "name": "tokenId", "type": "uint256" } ], "name": "getApproved", "outputs": [ { "internalType": "address", "name": "", "type": "address" } ], "stateMutability": "view", "type": "function" }, { "inputs": [ { "internalType": "address", "name": "owner", "type": "address" }, { "internalType": "address", "name": "operator", "type": "address" } ], "name": "isApprovedForAll", "outputs": [ { "internalType": "bool", "name": "", "type": "bool" } ], "stateMutability": "view", "type": "function" }, { "inputs": [], "name": "name", "outputs": [ { "internalType": "string", "name": "", "type": "string" } ], "stateMutability": "view", "type": "function" }, { "inputs": [], "name": "owner", "outputs": [ { "internalType": "address", "name": "", "type": "address" } ], "stateMutability": "view", "type": "function" }, { "inputs": [ { "internalType": "uint256", "name": "tokenId", "type": "uint256" } ], "name": "ownerOf", "outputs": [ { "internalType": "address", "name": "", "type": "address" } ], "stateMutability": "view", "type": "function" }, { "inputs": [], "name": "renounceOwnership", "outputs": [], "stateMutability": "nonpayable", "type": "function" }, { "inputs": [ { "internalType": "address", "name": "to", "type": "address" }, { "internalType": "string", "name": "uri", "type": "string" } ], "name": "safeMint", "outputs": [], "stateMutability": "nonpayable", "type": "function" }, { "inputs": [ { "internalType": "address", "name": "from", "type": "address" }, { "internalType": "address", "name": "to", "type": "address" }, { "internalType": "uint256", "name": "tokenId", "type": "uint256" } ], "name": "safeTransferFrom", "outputs": [], "stateMutability": "nonpayable", "type": "function" }, { "inputs": [ { "internalType": "address", "name": "from", "type": "address" }, { "internalType": "address", "name": "to", "type": "address" }, { "internalType": "uint256", "name": "tokenId", "type": "uint256" }, { "internalType": "bytes", "name": "data", "type": "bytes" } ], "name": "safeTransferFrom", "outputs": [], "stateMutability": "nonpayable", "type": "function" }, { "inputs": [ { "internalType": "address", "name": "operator", "type": "address" }, { "internalType": "bool", "name": "approved", "type": "bool" } ], "name": "setApprovalForAll", "outputs": [], "stateMutability": "nonpayable", "type": "function" }, { "inputs": [ { "internalType": "bytes4", "name": "interfaceId", "type": "bytes4" } ], "name": "supportsInterface", "outputs": [ { "internalType": "bool", "name": "", "type": "bool" } ], "stateMutability": "view", "type": "function" }, { "inputs": [], "name": "symbol", "outputs": [ { "internalType": "string", "name": "", "type": "string" } ], "stateMutability": "view", "type": "function" }, { "inputs": [ { "internalType": "uint256", "name": "tokenId", "type": "uint256" } ], "name": "tokenURI", "outputs": [ { "internalType": "string", "name": "", "type": "string" } ], "stateMutability": "view", "type": "function" }, { "inputs": [ { "internalType": "address", "name": "from", "type": "address" }, { "internalType": "address", "name": "to", "type": "address" }, { "internalType": "uint256", "name": "tokenId", "type": "uint256" } ], "name": "transferFrom", "outputs": [], "stateMutability": "nonpayable", "type": "function" }, { "inputs": [ { "internalType": "address", "name": "newOwner", "type": "address" } ], "name": "transferOwnership", "outputs": [], "stateMutability": "nonpayable", "type": "function" } ], "bytecode": "0x60806040523480156200001157600080fd5b503360405180604001604052806005815260200164135e53919560da1b8152506040518060400160405280600381526020016226aca760e91b81525081600090816200005e9190620001aa565b5060016200006d8282620001aa565b5050506001600160a01b0381166200009f57604051631e4fbdf760e01b81526000600482015260240160405180910390fd5b620000aa81620000b1565b5062000276565b600780546001600160a01b038381166001600160a01b0319831681179093556040519116919082907f8be0079c531659141344cd1fd0a4f28419497f9722a3daafe3b4186f6b6457e090600090a35050565b634e487b7160e01b600052604160045260246000fd5b600181811c908216806200012e57607f821691505b6020821081036200014f57634e487b7160e01b600052602260045260246000fd5b50919050565b601f821115620001a5576000816000526020600020601f850160051c81016020861015620001805750805b601f850160051c820191505b81811015620001a1578281556001016200018c565b5050505b505050565b81516001600160401b03811115620001c657620001c662000103565b620001de81620001d7845462000119565b8462000155565b602080601f831160018114620002165760008415620001fd5750858301515b600019600386901b1c1916600185901b178555620001a1565b600085815260208120601f198616915b82811015620002475788860151825594840194600190910190840162000226565b5085821015620002665787850151600019600388901b60f8161c191681555b5050505050600190811b01905550565b61143b80620002866000396000f3fe608060405234801561001057600080fd5b506004361061010b5760003560e01c8063715018a6116100a2578063b88d4fde11610071578063b88d4fde1461021b578063c87b56dd1461022e578063d204c45e14610241578063e985e9c514610254578063f2fde38b1461026757600080fd5b8063715018a6146101e75780638da5cb5b146101ef57806395d89b4114610200578063a22cb4651461020857600080fd5b806323b872dd116100de57806323b872dd1461018d57806342842e0e146101a05780636352211e146101b357806370a08231146101c657600080fd5b806301ffc9a71461011057806306fdde0314610138578063081812fc1461014d578063095ea7b314610178575b600080fd5b61012361011e366004610efc565b61027a565b60405190151581526020015b60405180910390f35b61014061028b565b60405161012f9190610f69565b61016061015b366004610f7c565b61031d565b6040516001600160a01b03909116815260200161012f565b61018b610186366004610fb1565b610346565b005b61018b61019b366004610fdb565b610355565b61018b6101ae366004610fdb565b6103e5565b6101606101c1366004610f7c565b610405565b6101d96101d4366004611017565b610410565b60405190815260200161012f565b61018b610458565b6007546001600160a01b0316610160565b61014061046c565b61018b610216366004611032565b61047b565b61018b6102293660046110fa565b610486565b61014061023c366004610f7c565b61049d565b61018b61024f366004611176565b6104a8565b6101236102623660046111d8565b6104db565b61018b610275366004611017565b610509565b600061028582610547565b92915050565b60606000805461029a9061120b565b80601f01602080910402602001604051908101604052809291908181526020018280546102c69061120b565b80156103135780601f106102e857610100808354040283529160200191610313565b820191906000526020600020905b8154815290600101906020018083116102f657829003601f168201915b5050505050905090565b60006103288261056c565b506000828152600460205260409020546001600160a01b0316610285565b6103518282336105a5565b5050565b6001600160a01b03821661038457604051633250574960e11b8152600060048201526024015b60405180910390fd5b60006103918383336105b2565b9050836001600160a01b0316816001600160a01b0316146103df576040516364283d7b60e01b81526001600160a01b038086166004830152602482018490528216604482015260640161037b565b50505050565b61040083838360405180602001604052806000815250610486565b505050565b60006102858261056c565b60006001600160a01b03821661043c576040516322718ad960e21b81526000600482015260240161037b565b506001600160a01b031660009081526003602052604090205490565b6104606106ab565b61046a60006106d8565b565b60606001805461029a9061120b565b61035133838361072a565b610491848484610355565b6103df848484846107c9565b6060610285826108f2565b6104b06106ab565b60088054600091826104c183611245565b9190505590506104d18382610a03565b6104008183610a1d565b6001600160a01b03918216600090815260056020908152604080832093909416825291909152205460ff1690565b6105116106ab565b6001600160a01b03811661053b57604051631e4fbdf760e01b81526000600482015260240161037b565b610544816106d8565b50565b60006001600160e01b03198216632483248360e11b1480610285575061028582610a6d565b6000818152600260205260408120546001600160a01b03168061028557604051637e27328960e01b81526004810184905260240161037b565b6104008383836001610abd565b6000828152600260205260408120546001600160a01b03908116908316156105df576105df818486610bc3565b6001600160a01b0381161561061d576105fc600085600080610abd565b6001600160a01b038116600090815260036020526040902080546000190190555b6001600160a01b0385161561064c576001600160a01b0385166000908152600360205260409020805460010190555b60008481526002602052604080822080546001600160a01b0319166001600160a01b0389811691821790925591518793918516917fddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef91a4949350505050565b6007546001600160a01b0316331461046a5760405163118cdaa760e01b815233600482015260240161037b565b600780546001600160a01b038381166001600160a01b0319831681179093556040519116919082907f8be0079c531659141344cd1fd0a4f28419497f9722a3daafe3b4186f6b6457e090600090a35050565b6001600160a01b03821661075c57604051630b61174360e31b81526001600160a01b038316600482015260240161037b565b6001600160a01b03838116600081815260056020908152604080832094871680845294825291829020805460ff191686151590811790915591519182527f17307eab39ab6107e8899845ad3d59bd9653f200f220920489ca2b5937696c31910160405180910390a3505050565b6001600160a01b0383163b156103df57604051630a85bd0160e11b81526001600160a01b0384169063150b7a029061080b90339088908790879060040161126c565b6020604051808303816000875af1925050508015610846575060408051601f3d908101601f19168201909252610843918101906112a9565b60015b6108af573d808015610874576040519150601f19603f3d011682016040523d82523d6000602084013e610879565b606091505b5080516000036108a757604051633250574960e11b81526001600160a01b038516600482015260240161037b565b805181602001fd5b6001600160e01b03198116630a85bd0160e11b146108eb57604051633250574960e11b81526001600160a01b038516600482015260240161037b565b5050505050565b60606108fd8261056c565b50600082815260066020526040812080546109179061120b565b80601f01602080910402602001604051908101604052809291908181526020018280546109439061120b565b80156109905780601f1061096557610100808354040283529160200191610990565b820191906000526020600020905b81548152906001019060200180831161097357829003601f168201915b5050505050905060006109ae60408051602081019091526000815290565b905080516000036109c0575092915050565b8151156109f25780826040516020016109da9291906112c6565b60405160208183030381529060405292505050919050565b6109fb84610c27565b949350505050565b610351828260405180602001604052806000815250610c9c565b6000828152600660205260409020610a358282611345565b506040518281527ff8e1a15aba9398e019f0b49df1a4fde98ee17ae345cb5f6b5e2c27f5033e8ce79060200160405180910390a15050565b60006001600160e01b031982166380ac58cd60e01b1480610a9e57506001600160e01b03198216635b5e139f60e01b145b8061028557506301ffc9a760e01b6001600160e01b0319831614610285565b8080610ad157506001600160a01b03821615155b15610b93576000610ae18461056c565b90506001600160a01b03831615801590610b0d5750826001600160a01b0316816001600160a01b031614155b8015610b205750610b1e81846104db565b155b15610b495760405163a9fbf51f60e01b81526001600160a01b038416600482015260240161037b565b8115610b915783856001600160a01b0316826001600160a01b03167f8c5be1e5ebec7d5bd14f71427d1e84f3dd0314c0f7b2291e5b200ac8c7c3b92560405160405180910390a45b505b5050600090815260046020526040902080546001600160a01b0319166001600160a01b0392909216919091179055565b610bce838383610cb3565b610400576001600160a01b038316610bfc57604051637e27328960e01b81526004810182905260240161037b565b60405163177e802f60e01b81526001600160a01b03831660048201526024810182905260440161037b565b6060610c328261056c565b506000610c4a60408051602081019091526000815290565b90506000815111610c6a5760405180602001604052806000815250610c95565b80610c7484610d16565b604051602001610c859291906112c6565b6040516020818303038152906040525b9392505050565b610ca68383610da9565b61040060008484846107c9565b60006001600160a01b038316158015906109fb5750826001600160a01b0316846001600160a01b03161480610ced5750610ced84846104db565b806109fb5750506000908152600460205260409020546001600160a01b03908116911614919050565b60606000610d2383610e0e565b600101905060008167ffffffffffffffff811115610d4357610d4361106e565b6040519080825280601f01601f191660200182016040528015610d6d576020820181803683370190505b5090508181016020015b600019016f181899199a1a9b1b9c1cb0b131b232b360811b600a86061a8153600a8504945084610d7757509392505050565b6001600160a01b038216610dd357604051633250574960e11b81526000600482015260240161037b565b6000610de1838360006105b2565b90506001600160a01b03811615610400576040516339e3563760e11b81526000600482015260240161037b565b60008072184f03e93ff9f4daa797ed6e38ed64bf6a1f0160401b8310610e4d5772184f03e93ff9f4daa797ed6e38ed64bf6a1f0160401b830492506040015b6d04ee2d6d415b85acef81000000008310610e79576d04ee2d6d415b85acef8100000000830492506020015b662386f26fc100008310610e9757662386f26fc10000830492506010015b6305f5e1008310610eaf576305f5e100830492506008015b6127108310610ec357612710830492506004015b60648310610ed5576064830492506002015b600a83106102855760010192915050565b6001600160e01b03198116811461054457600080fd5b600060208284031215610f0e57600080fd5b8135610c9581610ee6565b60005b83811015610f34578181015183820152602001610f1c565b50506000910152565b60008151808452610f55816020860160208601610f19565b601f01601f19169290920160200192915050565b602081526000610c956020830184610f3d565b600060208284031215610f8e57600080fd5b5035919050565b80356001600160a01b0381168114610fac57600080fd5b919050565b60008060408385031215610fc457600080fd5b610fcd83610f95565b946020939093013593505050565b600080600060608486031215610ff057600080fd5b610ff984610f95565b925061100760208501610f95565b9150604084013590509250925092565b60006020828403121561102957600080fd5b610c9582610f95565b6000806040838503121561104557600080fd5b61104e83610f95565b91506020830135801515811461106357600080fd5b809150509250929050565b634e487b7160e01b600052604160045260246000fd5b600067ffffffffffffffff8084111561109f5761109f61106e565b604051601f8501601f19908116603f011681019082821181831017156110c7576110c761106e565b816040528093508581528686860111156110e057600080fd5b858560208301376000602087830101525050509392505050565b6000806000806080858703121561111057600080fd5b61111985610f95565b935061112760208601610f95565b925060408501359150606085013567ffffffffffffffff81111561114a57600080fd5b8501601f8101871361115b57600080fd5b61116a87823560208401611084565b91505092959194509250565b6000806040838503121561118957600080fd5b61119283610f95565b9150602083013567ffffffffffffffff8111156111ae57600080fd5b8301601f810185136111bf57600080fd5b6111ce85823560208401611084565b9150509250929050565b600080604083850312156111eb57600080fd5b6111f483610f95565b915061120260208401610f95565b90509250929050565b600181811c9082168061121f57607f821691505b60208210810361123f57634e487b7160e01b600052602260045260246000fd5b50919050565b60006001820161126557634e487b7160e01b600052601160045260246000fd5b5060010190565b6001600160a01b038581168252841660208201526040810183905260806060820181905260009061129f90830184610f3d565b9695505050505050565b6000602082840312156112bb57600080fd5b8151610c9581610ee6565b600083516112d8818460208801610f19565b8351908301906112ec818360208801610f19565b01949350505050565b601f821115610400576000816000526020600020601f850160051c8101602086101561131e5750805b601f850160051c820191505b8181101561133d5782815560010161132a565b505050505050565b815167ffffffffffffffff81111561135f5761135f61106e565b6113738161136d845461120b565b846112f5565b602080601f8311600181146113a857600084156113905750858301515b600019600386901b1c1916600185901b17855561133d565b600085815260208120601f198616915b828110156113d7578886015182559484019460019091019084016113b8565b50858210156113f55787850151600019600388901b60f8161c191681555b5050505050600190811b0190555056fea2646970667358221220c82add76c7b3647a1f7efd517f753c1d111704531523b024f30f22176bd20d2a64736f6c63430008180033", "deployedBytecode": "0x608060405234801561001057600080fd5b506004361061010b5760003560e01c8063715018a6116100a2578063b88d4fde11610071578063b88d4fde1461021b578063c87b56dd1461022e578063d204c45e14610241578063e985e9c514610254578063f2fde38b1461026757600080fd5b8063715018a6146101e75780638da5cb5b146101ef57806395d89b4114610200578063a22cb4651461020857600080fd5b806323b872dd116100de57806323b872dd1461018d57806342842e0e146101a05780636352211e146101b357806370a08231146101c657600080fd5b806301ffc9a71461011057806306fdde0314610138578063081812fc1461014d578063095ea7b314610178575b600080fd5b61012361011e366004610efc565b61027a565b60405190151581526020015b60405180910390f35b61014061028b565b60405161012f9190610f69565b61016061015b366004610f7c565b61031d565b6040516001600160a01b03909116815260200161012f565b61018b610186366004610fb1565b610346565b005b61018b61019b366004610fdb565b610355565b61018b6101ae366004610fdb565b6103e5565b6101606101c1366004610f7c565b610405565b6101d96101d4366004611017565b610410565b60405190815260200161012f565b61018b610458565b6007546001600160a01b0316610160565b61014061046c565b61018b610216366004611032565b61047b565b61018b6102293660046110fa565b610486565b61014061023c366004610f7c565b61049d565b61018b61024f366004611176565b6104a8565b6101236102623660046111d8565b6104db565b61018b610275366004611017565b610509565b600061028582610547565b92915050565b60606000805461029a9061120b565b80601f01602080910402602001604051908101604052809291908181526020018280546102c69061120b565b80156103135780601f106102e857610100808354040283529160200191610313565b820191906000526020600020905b8154815290600101906020018083116102f657829003601f168201915b5050505050905090565b60006103288261056c565b506000828152600460205260409020546001600160a01b0316610285565b6103518282336105a5565b5050565b6001600160a01b03821661038457604051633250574960e11b8152600060048201526024015b60405180910390fd5b60006103918383336105b2565b9050836001600160a01b0316816001600160a01b0316146103df576040516364283d7b60e01b81526001600160a01b038086166004830152602482018490528216604482015260640161037b565b50505050565b61040083838360405180602001604052806000815250610486565b505050565b60006102858261056c565b60006001600160a01b03821661043c576040516322718ad960e21b81526000600482015260240161037b565b506001600160a01b031660009081526003602052604090205490565b6104606106ab565b61046a60006106d8565b565b60606001805461029a9061120b565b61035133838361072a565b610491848484610355565b6103df848484846107c9565b6060610285826108f2565b6104b06106ab565b60088054600091826104c183611245565b9190505590506104d18382610a03565b6104008183610a1d565b6001600160a01b03918216600090815260056020908152604080832093909416825291909152205460ff1690565b6105116106ab565b6001600160a01b03811661053b57604051631e4fbdf760e01b81526000600482015260240161037b565b610544816106d8565b50565b60006001600160e01b03198216632483248360e11b1480610285575061028582610a6d565b6000818152600260205260408120546001600160a01b03168061028557604051637e27328960e01b81526004810184905260240161037b565b6104008383836001610abd565b6000828152600260205260408120546001600160a01b03908116908316156105df576105df818486610bc3565b6001600160a01b0381161561061d576105fc600085600080610abd565b6001600160a01b038116600090815260036020526040902080546000190190555b6001600160a01b0385161561064c576001600160a01b0385166000908152600360205260409020805460010190555b60008481526002602052604080822080546001600160a01b0319166001600160a01b0389811691821790925591518793918516917fddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef91a4949350505050565b6007546001600160a01b0316331461046a5760405163118cdaa760e01b815233600482015260240161037b565b600780546001600160a01b038381166001600160a01b0319831681179093556040519116919082907f8be0079c531659141344cd1fd0a4f28419497f9722a3daafe3b4186f6b6457e090600090a35050565b6001600160a01b03821661075c57604051630b61174360e31b81526001600160a01b038316600482015260240161037b565b6001600160a01b03838116600081815260056020908152604080832094871680845294825291829020805460ff191686151590811790915591519182527f17307eab39ab6107e8899845ad3d59bd9653f200f220920489ca2b5937696c31910160405180910390a3505050565b6001600160a01b0383163b156103df57604051630a85bd0160e11b81526001600160a01b0384169063150b7a029061080b90339088908790879060040161126c565b6020604051808303816000875af1925050508015610846575060408051601f3d908101601f19168201909252610843918101906112a9565b60015b6108af573d808015610874576040519150601f19603f3d011682016040523d82523d6000602084013e610879565b606091505b5080516000036108a757604051633250574960e11b81526001600160a01b038516600482015260240161037b565b805181602001fd5b6001600160e01b03198116630a85bd0160e11b146108eb57604051633250574960e11b81526001600160a01b038516600482015260240161037b565b5050505050565b60606108fd8261056c565b50600082815260066020526040812080546109179061120b565b80601f01602080910402602001604051908101604052809291908181526020018280546109439061120b565b80156109905780601f1061096557610100808354040283529160200191610990565b820191906000526020600020905b81548152906001019060200180831161097357829003601f168201915b5050505050905060006109ae60408051602081019091526000815290565b905080516000036109c0575092915050565b8151156109f25780826040516020016109da9291906112c6565b60405160208183030381529060405292505050919050565b6109fb84610c27565b949350505050565b610351828260405180602001604052806000815250610c9c565b6000828152600660205260409020610a358282611345565b506040518281527ff8e1a15aba9398e019f0b49df1a4fde98ee17ae345cb5f6b5e2c27f5033e8ce79060200160405180910390a15050565b60006001600160e01b031982166380ac58cd60e01b1480610a9e57506001600160e01b03198216635b5e139f60e01b145b8061028557506301ffc9a760e01b6001600160e01b0319831614610285565b8080610ad157506001600160a01b03821615155b15610b93576000610ae18461056c565b90506001600160a01b03831615801590610b0d5750826001600160a01b0316816001600160a01b031614155b8015610b205750610b1e81846104db565b155b15610b495760405163a9fbf51f60e01b81526001600160a01b038416600482015260240161037b565b8115610b915783856001600160a01b0316826001600160a01b03167f8c5be1e5ebec7d5bd14f71427d1e84f3dd0314c0f7b2291e5b200ac8c7c3b92560405160405180910390a45b505b5050600090815260046020526040902080546001600160a01b0319166001600160a01b0392909216919091179055565b610bce838383610cb3565b610400576001600160a01b038316610bfc57604051637e27328960e01b81526004810182905260240161037b565b60405163177e802f60e01b81526001600160a01b03831660048201526024810182905260440161037b565b6060610c328261056c565b506000610c4a60408051602081019091526000815290565b90506000815111610c6a5760405180602001604052806000815250610c95565b80610c7484610d16565b604051602001610c859291906112c6565b6040516020818303038152906040525b9392505050565b610ca68383610da9565b61040060008484846107c9565b60006001600160a01b038316158015906109fb5750826001600160a01b0316846001600160a01b03161480610ced5750610ced84846104db565b806109fb5750506000908152600460205260409020546001600160a01b03908116911614919050565b60606000610d2383610e0e565b600101905060008167ffffffffffffffff811115610d4357610d4361106e565b6040519080825280601f01601f191660200182016040528015610d6d576020820181803683370190505b5090508181016020015b600019016f181899199a1a9b1b9c1cb0b131b232b360811b600a86061a8153600a8504945084610d7757509392505050565b6001600160a01b038216610dd357604051633250574960e11b81526000600482015260240161037b565b6000610de1838360006105b2565b90506001600160a01b03811615610400576040516339e3563760e11b81526000600482015260240161037b565b60008072184f03e93ff9f4daa797ed6e38ed64bf6a1f0160401b8310610e4d5772184f03e93ff9f4daa797ed6e38ed64bf6a1f0160401b830492506040015b6d04ee2d6d415b85acef81000000008310610e79576d04ee2d6d415b85acef8100000000830492506020015b662386f26fc100008310610e9757662386f26fc10000830492506010015b6305f5e1008310610eaf576305f5e100830492506008015b6127108310610ec357612710830492506004015b60648310610ed5576064830492506002015b600a83106102855760010192915050565b6001600160e01b03198116811461054457600080fd5b600060208284031215610f0e57600080fd5b8135610c9581610ee6565b60005b83811015610f34578181015183820152602001610f1c565b50506000910152565b60008151808452610f55816020860160208601610f19565b601f01601f19169290920160200192915050565b602081526000610c956020830184610f3d565b600060208284031215610f8e57600080fd5b5035919050565b80356001600160a01b0381168114610fac57600080fd5b919050565b60008060408385031215610fc457600080fd5b610fcd83610f95565b946020939093013593505050565b600080600060608486031215610ff057600080fd5b610ff984610f95565b925061100760208501610f95565b9150604084013590509250925092565b60006020828403121561102957600080fd5b610c9582610f95565b6000806040838503121561104557600080fd5b61104e83610f95565b91506020830135801515811461106357600080fd5b809150509250929050565b634e487b7160e01b600052604160045260246000fd5b600067ffffffffffffffff8084111561109f5761109f61106e565b604051601f8501601f19908116603f011681019082821181831017156110c7576110c761106e565b816040528093508581528686860111156110e057600080fd5b858560208301376000602087830101525050509392505050565b6000806000806080858703121561111057600080fd5b61111985610f95565b935061112760208601610f95565b925060408501359150606085013567ffffffffffffffff81111561114a57600080fd5b8501601f8101871361115b57600080fd5b61116a87823560208401611084565b91505092959194509250565b6000806040838503121561118957600080fd5b61119283610f95565b9150602083013567ffffffffffffffff8111156111ae57600080fd5b8301601f810185136111bf57600080fd5b6111ce85823560208401611084565b9150509250929050565b600080604083850312156111eb57600080fd5b6111f483610f95565b915061120260208401610f95565b90509250929050565b600181811c9082168061121f57607f821691505b60208210810361123f57634e487b7160e01b600052602260045260246000fd5b50919050565b60006001820161126557634e487b7160e01b600052601160045260246000fd5b5060010190565b6001600160a01b038581168252841660208201526040810183905260806060820181905260009061129f90830184610f3d565b9695505050505050565b6000602082840312156112bb57600080fd5b8151610c9581610ee6565b600083516112d8818460208801610f19565b8351908301906112ec818360208801610f19565b01949350505050565b601f821115610400576000816000526020600020601f850160051c8101602086101561131e5750805b601f850160051c820191505b8181101561133d5782815560010161132a565b505050505050565b815167ffffffffffffffff81111561135f5761135f61106e565b6113738161136d845461120b565b846112f5565b602080601f8311600181146113a857600084156113905750858301515b600019600386901b1c1916600185901b17855561133d565b600085815260208120601f198616915b828110156113d7578886015182559484019460019091019084016113b8565b50858210156113f55787850151600019600388901b60f8161c191681555b5050505050600190811b0190555056fea2646970667358221220c82add76c7b3647a1f7efd517f753c1d111704531523b024f30f22176bd20d2a64736f6c63430008180033", "linkReferences": {}, "deployedLinkReferences": {} } ================================================ FILE: 07-NFT Minitng dApp on Core/frontend/src/index.css ================================================ :root { font-family: Inter, system-ui, Avenir, Helvetica, Arial, sans-serif; line-height: 1.5; font-weight: 400; color: #213547; background-color: #ffffff; font-synthesis: none; text-rendering: optimizeLegibility; -webkit-font-smoothing: antialiased; -moz-osx-font-smoothing: grayscale; } a { font-weight: 500; color: #646cff; text-decoration: inherit; } a:hover { color: #535bf2; } main { display: flex; flex-direction: column; align-items: center; justify-content: center; } .nft-section { display: flex; flex-direction: column; align-items: center; justify-content: center; } h1 { font-size: 3.2em; line-height: 1.1; } button { border-radius: 8px; border: 1px solid transparent; padding: 0.6em 1.2em; font-size: 1em; font-weight: 500; font-family: inherit; background-color: #d6d3d3; cursor: pointer; transition: border-color 0.25s; } button:hover { border-color: #646cff; } button:focus, button:focus-visible { outline: 4px auto -webkit-focus-ring-color; } ================================================ FILE: 07-NFT Minitng dApp on Core/frontend/src/main.jsx ================================================ import React from 'react' import ReactDOM from 'react-dom/client' import App from './App.jsx' import './index.css' ReactDOM.createRoot(document.getElementById('root')).render( , ) ================================================ FILE: 07-NFT Minitng dApp on Core/frontend/vite.config.js ================================================ import { defineConfig } from 'vite' import react from '@vitejs/plugin-react' // https://vitejs.dev/config/ export default defineConfig({ plugins: [react()], }) ================================================ FILE: 07-NFT Minitng dApp on Core/hardhat.config.js ================================================ require("@nomicfoundation/hardhat-toolbox"); require("dotenv").config(); /** @type import('hardhat/config').HardhatUserConfig */ const PRIVATE_KEY = process.env.PRIVATE_KEY; module.exports = { solidity: "0.8.24", defaultNetwork: "hardhat", networks: { hardhat: {}, core_testnet: { url: "https://rpc.test2.btcs.network", accounts: [PRIVATE_KEY], chainId: 1114, }, }, solidity: { compilers: [ { version: "0.8.24", settings: { evmVersion: "shanghai", optimizer: { enabled: true, runs: 200, }, }, }, ], }, paths: { sources: "./contracts", cache: "./cache", artifacts: "./artifacts", }, mocha: { timeout: 20000, }, }; ================================================ FILE: 07-NFT Minitng dApp on Core/ignition/modules/Lock.js ================================================ const { buildModule } = require("@nomicfoundation/hardhat-ignition/modules"); const JAN_1ST_2030 = 1893456000; const ONE_GWEI = 1_000_000_000n; module.exports = buildModule("LockModule", (m) => { const unlockTime = m.getParameter("unlockTime", JAN_1ST_2030); const lockedAmount = m.getParameter("lockedAmount", ONE_GWEI); const lock = m.contract("Lock", [unlockTime], { value: lockedAmount, }); return { lock }; }); ================================================ FILE: 07-NFT Minitng dApp on Core/package.json ================================================ { "name": "NFT_Collection_Tutorial", "version": "1.0.0", "main": "index.js", "license": "MIT", "devDependencies": { "@nomicfoundation/hardhat-chai-matchers": "^2.0.0", "@nomicfoundation/hardhat-ethers": "^3.0.0", "@nomicfoundation/hardhat-ignition": "^0.15.0", "@nomicfoundation/hardhat-ignition-ethers": "^0.15.0", "@nomicfoundation/hardhat-network-helpers": "^1.0.0", "@nomicfoundation/hardhat-toolbox": "^5.0.0", "@nomicfoundation/hardhat-verify": "^2.0.0", "@typechain/ethers-v6": "^0.5.0", "@typechain/hardhat": "^9.0.0", "chai": "^4.2.0", "ethers": "^6.4.0", "hardhat": "^2.22.6", "hardhat-gas-reporter": "^1.0.8", "solidity-coverage": "^0.8.0", "typechain": "^8.3.0" }, "dependencies": { "@openzeppelin/contracts": "^5.0.2", "dotenv": "^16.5.0" } } ================================================ FILE: 07-NFT Minitng dApp on Core/scripts/deploy.js ================================================ const { ethers } = require("hardhat"); async function main() { const [deployer] = await ethers.getSigners(); console.log("Deploying contract with the account:", deployer.address); const MyNFT = await ethers.getContractFactory("MyNFT"); const myNft = await MyNFT.deploy(); console.log("Contract address:", await myNft.getAddress()); } main() .then(() => process.exit(0)) .catch((error) => { console.error(error); process.exit(1); }); ================================================ FILE: 07-NFT Minitng dApp on Core/test/Lock.js ================================================ const { time, loadFixture, } = require("@nomicfoundation/hardhat-toolbox/network-helpers"); const { anyValue } = require("@nomicfoundation/hardhat-chai-matchers/withArgs"); const { expect } = require("chai"); describe("Lock", function () { // We define a fixture to reuse the same setup in every test. // We use loadFixture to run this setup once, snapshot that state, // and reset Hardhat Network to that snapshot in every test. async function deployOneYearLockFixture() { const ONE_YEAR_IN_SECS = 365 * 24 * 60 * 60; const ONE_GWEI = 1_000_000_000; const lockedAmount = ONE_GWEI; const unlockTime = (await time.latest()) + ONE_YEAR_IN_SECS; // Contracts are deployed using the first signer/account by default const [owner, otherAccount] = await ethers.getSigners(); const Lock = await ethers.getContractFactory("Lock"); const lock = await Lock.deploy(unlockTime, { value: lockedAmount }); return { lock, unlockTime, lockedAmount, owner, otherAccount }; } describe("Deployment", function () { it("Should set the right unlockTime", async function () { const { lock, unlockTime } = await loadFixture(deployOneYearLockFixture); expect(await lock.unlockTime()).to.equal(unlockTime); }); it("Should set the right owner", async function () { const { lock, owner } = await loadFixture(deployOneYearLockFixture); expect(await lock.owner()).to.equal(owner.address); }); it("Should receive and store the funds to lock", async function () { const { lock, lockedAmount } = await loadFixture( deployOneYearLockFixture ); expect(await ethers.provider.getBalance(lock.target)).to.equal( lockedAmount ); }); it("Should fail if the unlockTime is not in the future", async function () { // We don't use the fixture here because we want a different deployment const latestTime = await time.latest(); const Lock = await ethers.getContractFactory("Lock"); await expect(Lock.deploy(latestTime, { value: 1 })).to.be.revertedWith( "Unlock time should be in the future" ); }); }); describe("Withdrawals", function () { describe("Validations", function () { it("Should revert with the right error if called too soon", async function () { const { lock } = await loadFixture(deployOneYearLockFixture); await expect(lock.withdraw()).to.be.revertedWith( "You can't withdraw yet" ); }); it("Should revert with the right error if called from another account", async function () { const { lock, unlockTime, otherAccount } = await loadFixture( deployOneYearLockFixture ); // We can increase the time in Hardhat Network await time.increaseTo(unlockTime); // We use lock.connect() to send a transaction from another account await expect(lock.connect(otherAccount).withdraw()).to.be.revertedWith( "You aren't the owner" ); }); it("Shouldn't fail if the unlockTime has arrived and the owner calls it", async function () { const { lock, unlockTime } = await loadFixture( deployOneYearLockFixture ); // Transactions are sent using the first signer by default await time.increaseTo(unlockTime); await expect(lock.withdraw()).not.to.be.reverted; }); }); describe("Events", function () { it("Should emit an event on withdrawals", async function () { const { lock, unlockTime, lockedAmount } = await loadFixture( deployOneYearLockFixture ); await time.increaseTo(unlockTime); await expect(lock.withdraw()) .to.emit(lock, "Withdrawal") .withArgs(lockedAmount, anyValue); // We accept any value as `when` arg }); }); describe("Transfers", function () { it("Should transfer the funds to the owner", async function () { const { lock, unlockTime, lockedAmount, owner } = await loadFixture( deployOneYearLockFixture ); await time.increaseTo(unlockTime); await expect(lock.withdraw()).to.changeEtherBalances( [owner, lock], [lockedAmount, -lockedAmount] ); }); }); }); }); ================================================ FILE: 08-Guess-Game/.gitignore ================================================ node_modules .env # Hardhat files /cache /artifacts # TypeChain files /typechain /typechain-types # solidity-coverage files /coverage /coverage.json # Hardhat Ignition default folder for deployments against a local node ignition/deployments/chain-31337 ================================================ FILE: 08-Guess-Game/Frontend/.eslintrc.json ================================================ { "extends": ["next/core-web-vitals", "next/typescript"] } ================================================ FILE: 08-Guess-Game/Frontend/.gitignore ================================================ # See https://help.github.com/articles/ignoring-files/ for more about ignoring files. # dependencies /node_modules /.pnp .pnp.* .yarn/* !.yarn/patches !.yarn/plugins !.yarn/releases !.yarn/versions # testing /coverage # next.js /.next/ /out/ # production /build # misc .DS_Store *.pem # debug npm-debug.log* yarn-debug.log* yarn-error.log* # env files (can opt-in for commiting if needed) .env* # vercel .vercel # typescript *.tsbuildinfo next-env.d.ts ================================================ FILE: 08-Guess-Game/Frontend/README.md ================================================ This is a [Next.js](https://nextjs.org) project bootstrapped with [`create-next-app`](https://nextjs.org/docs/app/api-reference/cli/create-next-app). ## Getting Started First, run the development server: ```bash npm run dev # or yarn dev # or pnpm dev # or bun dev ``` Open [http://localhost:3000](http://localhost:3000) with your browser to see the result. You can start editing the page by modifying `app/page.tsx`. The page auto-updates as you edit the file. This project uses [`next/font`](https://nextjs.org/docs/app/building-your-application/optimizing/fonts) to automatically optimize and load [Geist](https://vercel.com/font), a new font family for Vercel. ## Learn More To learn more about Next.js, take a look at the following resources: - [Next.js Documentation](https://nextjs.org/docs) - learn about Next.js features and API. - [Learn Next.js](https://nextjs.org/learn) - an interactive Next.js tutorial. You can check out [the Next.js GitHub repository](https://github.com/vercel/next.js) - your feedback and contributions are welcome! ## Deploy on Vercel The easiest way to deploy your Next.js app is to use the [Vercel Platform](https://vercel.com/new?utm_medium=default-template&filter=next.js&utm_source=create-next-app&utm_campaign=create-next-app-readme) from the creators of Next.js. Check out our [Next.js deployment documentation](https://nextjs.org/docs/app/building-your-application/deploying) for more details. ================================================ FILE: 08-Guess-Game/Frontend/app/components/ui/button.tsx ================================================ import * as React from "react" import { Slot } from "@radix-ui/react-slot" import { cva, type VariantProps } from "class-variance-authority" import { cn } from "@/lib/utils" const buttonVariants = cva( "inline-flex items-center justify-center gap-2 whitespace-nowrap rounded-md text-sm font-medium transition-colors focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring disabled:pointer-events-none disabled:opacity-50 [&_svg]:pointer-events-none [&_svg]:size-4 [&_svg]:shrink-0", { variants: { variant: { default: "bg-primary text-primary-foreground shadow hover:bg-primary/90", destructive: "bg-destructive text-destructive-foreground shadow-sm hover:bg-destructive/90", outline: "border border-input bg-background shadow-sm hover:bg-accent hover:text-accent-foreground", secondary: "bg-secondary text-secondary-foreground shadow-sm hover:bg-secondary/80", ghost: "hover:bg-accent hover:text-accent-foreground", link: "text-primary underline-offset-4 hover:underline", }, size: { default: "h-9 px-4 py-2", sm: "h-8 rounded-md px-3 text-xs", lg: "h-10 rounded-md px-8", icon: "h-9 w-9", }, }, defaultVariants: { variant: "default", size: "default", }, } ) export interface ButtonProps extends React.ButtonHTMLAttributes, VariantProps { asChild?: boolean } const Button = React.forwardRef( ({ className, variant, size, asChild = false, ...props }, ref) => { const Comp = asChild ? Slot : "button" return ( ) } ) Button.displayName = "Button" export { Button, buttonVariants } ================================================ FILE: 08-Guess-Game/Frontend/app/components/ui/card.tsx ================================================ import * as React from "react" import { cn } from "@/lib/utils" const Card = React.forwardRef< HTMLDivElement, React.HTMLAttributes >(({ className, ...props }, ref) => (
)) Card.displayName = "Card" const CardHeader = React.forwardRef< HTMLDivElement, React.HTMLAttributes >(({ className, ...props }, ref) => (
)) CardHeader.displayName = "CardHeader" const CardTitle = React.forwardRef< HTMLDivElement, React.HTMLAttributes >(({ className, ...props }, ref) => (
)) CardTitle.displayName = "CardTitle" const CardDescription = React.forwardRef< HTMLDivElement, React.HTMLAttributes >(({ className, ...props }, ref) => (
)) CardDescription.displayName = "CardDescription" const CardContent = React.forwardRef< HTMLDivElement, React.HTMLAttributes >(({ className, ...props }, ref) => (
)) CardContent.displayName = "CardContent" const CardFooter = React.forwardRef< HTMLDivElement, React.HTMLAttributes >(({ className, ...props }, ref) => (
)) CardFooter.displayName = "CardFooter" export { Card, CardHeader, CardFooter, CardTitle, CardDescription, CardContent } ================================================ FILE: 08-Guess-Game/Frontend/app/components/ui/input.tsx ================================================ import * as React from "react" import { cn } from "@/lib/utils" const Input = React.forwardRef>( ({ className, type, ...props }, ref) => { return ( ) } ) Input.displayName = "Input" export { Input } ================================================ FILE: 08-Guess-Game/Frontend/app/constants/config.json ================================================ { "31337": { "guessGame": { "address": "0xe7f1725E7734CE288F8367e1Bb143E90bb3F0512" }, "guessToken": { "address": "0x5FbDB2315678afecb367f032d93F642f64180aa3" } }, "1114": { "guessGame": { "address": "0x10a7E98342529668665aC3B51d4125FD4498f119" }, "guessToken": { "address": "0xb4AadCf437b9EaD160D821E564ffc58EaDbDE642" } } } ================================================ FILE: 08-Guess-Game/Frontend/app/constants/solidityABI.json ================================================ [ { "inputs": [ { "internalType": "address", "name": "_rewardToken", "type": "address" }, { "internalType": "uint256", "name": "_rewardAmount", "type": "uint256" } ], "stateMutability": "nonpayable", "type": "constructor" }, { "inputs": [ { "internalType": "address", "name": "owner", "type": "address" } ], "name": "OwnableInvalidOwner", "type": "error" }, { "inputs": [ { "internalType": "address", "name": "account", "type": "address" } ], "name": "OwnableUnauthorizedAccount", "type": "error" }, { "anonymous": false, "inputs": [ { "indexed": false, "internalType": "uint256", "name": "blockNumber", "type": "uint256" } ], "name": "GameStarted", "type": "event" }, { "anonymous": false, "inputs": [ { "indexed": true, "internalType": "address", "name": "winner", "type": "address" }, { "indexed": false, "internalType": "uint256", "name": "attempts", "type": "uint256" }, { "indexed": false, "internalType": "uint256", "name": "reward", "type": "uint256" } ], "name": "GameWon", "type": "event" }, { "anonymous": false, "inputs": [ { "indexed": true, "internalType": "address", "name": "player", "type": "address" }, { "indexed": false, "internalType": "uint256", "name": "guess", "type": "uint256" }, { "indexed": false, "internalType": "string", "name": "message", "type": "string" } ], "name": "GuessMade", "type": "event" }, { "anonymous": false, "inputs": [ { "indexed": true, "internalType": "address", "name": "previousOwner", "type": "address" }, { "indexed": true, "internalType": "address", "name": "newOwner", "type": "address" } ], "name": "OwnershipTransferred", "type": "event" }, { "inputs": [ { "internalType": "address", "name": "", "type": "address" } ], "name": "attempts", "outputs": [ { "internalType": "uint256", "name": "", "type": "uint256" } ], "stateMutability": "view", "type": "function" }, { "inputs": [ { "internalType": "uint256", "name": "amount", "type": "uint256" } ], "name": "depositRewards", "outputs": [], "stateMutability": "nonpayable", "type": "function" }, { "inputs": [ { "internalType": "address", "name": "_playerAddress", "type": "address" } ], "name": "getAttempts", "outputs": [ { "internalType": "uint256", "name": "", "type": "uint256" } ], "stateMutability": "view", "type": "function" }, { "inputs": [], "name": "lastWinner", "outputs": [ { "internalType": "address", "name": "", "type": "address" } ], "stateMutability": "view", "type": "function" }, { "inputs": [ { "internalType": "uint256", "name": "_guess", "type": "uint256" } ], "name": "makeGuess", "outputs": [], "stateMutability": "nonpayable", "type": "function" }, { "inputs": [], "name": "owner", "outputs": [ { "internalType": "address", "name": "", "type": "address" } ], "stateMutability": "view", "type": "function" }, { "inputs": [], "name": "renounceOwnership", "outputs": [], "stateMutability": "nonpayable", "type": "function" }, { "inputs": [], "name": "resetGame", "outputs": [], "stateMutability": "nonpayable", "type": "function" }, { "inputs": [], "name": "rewardAmount", "outputs": [ { "internalType": "uint256", "name": "", "type": "uint256" } ], "stateMutability": "view", "type": "function" }, { "inputs": [], "name": "rewardToken", "outputs": [ { "internalType": "contract IERC20", "name": "", "type": "address" } ], "stateMutability": "view", "type": "function" }, { "inputs": [], "name": "secret", "outputs": [ { "internalType": "uint256", "name": "", "type": "uint256" } ], "stateMutability": "view", "type": "function" }, { "inputs": [], "name": "secretNumber", "outputs": [ { "internalType": "uint256", "name": "", "type": "uint256" } ], "stateMutability": "view", "type": "function" }, { "inputs": [ { "internalType": "uint256", "name": "_newAmount", "type": "uint256" } ], "name": "setReward", "outputs": [], "stateMutability": "nonpayable", "type": "function" }, { "inputs": [ { "internalType": "address", "name": "newOwner", "type": "address" } ], "name": "transferOwnership", "outputs": [], "stateMutability": "nonpayable", "type": "function" }, { "inputs": [ { "internalType": "uint256", "name": "amount", "type": "uint256" } ], "name": "withdrawTokens", "outputs": [], "stateMutability": "nonpayable", "type": "function" } ] ================================================ FILE: 08-Guess-Game/Frontend/app/globals.css ================================================ @tailwind base; @tailwind components; @tailwind utilities; body { font-family: Arial, Helvetica, sans-serif; } @layer base { :root { --background: 0 0% 100%; --foreground: 240 10% 3.9%; --card: 0 0% 100%; --card-foreground: 240 10% 3.9%; --popover: 0 0% 100%; --popover-foreground: 240 10% 3.9%; --primary: 240 5.9% 10%; --primary-foreground: 0 0% 98%; --secondary: 240 4.8% 95.9%; --secondary-foreground: 240 5.9% 10%; --muted: 240 4.8% 95.9%; --muted-foreground: 240 3.8% 46.1%; --accent: 240 4.8% 95.9%; --accent-foreground: 240 5.9% 10%; --destructive: 0 84.2% 60.2%; --destructive-foreground: 0 0% 98%; --border: 240 5.9% 90%; --input: 240 5.9% 90%; --ring: 240 10% 3.9%; --chart-1: 12 76% 61%; --chart-2: 173 58% 39%; --chart-3: 197 37% 24%; --chart-4: 43 74% 66%; --chart-5: 27 87% 67%; --radius: 0.5rem; } .dark { --background: 240 10% 3.9%; --foreground: 0 0% 98%; --card: 240 10% 3.9%; --card-foreground: 0 0% 98%; --popover: 240 10% 3.9%; --popover-foreground: 0 0% 98%; --primary: 0 0% 98%; --primary-foreground: 240 5.9% 10%; --secondary: 240 3.7% 15.9%; --secondary-foreground: 0 0% 98%; --muted: 240 3.7% 15.9%; --muted-foreground: 240 5% 64.9%; --accent: 240 3.7% 15.9%; --accent-foreground: 0 0% 98%; --destructive: 0 62.8% 30.6%; --destructive-foreground: 0 0% 98%; --border: 240 3.7% 15.9%; --input: 240 3.7% 15.9%; --ring: 240 4.9% 83.9%; --chart-1: 220 70% 50%; --chart-2: 160 60% 45%; --chart-3: 30 80% 55%; --chart-4: 280 65% 60%; --chart-5: 340 75% 55%; } } @layer base { * { @apply border-border; } body { @apply bg-background text-foreground; } } ================================================ FILE: 08-Guess-Game/Frontend/app/layout.tsx ================================================ import type { Metadata } from "next"; import localFont from "next/font/local"; import "./globals.css"; const geistSans = localFont({ src: "./fonts/GeistVF.woff", variable: "--font-geist-sans", weight: "100 900", }); const geistMono = localFont({ src: "./fonts/GeistMonoVF.woff", variable: "--font-geist-mono", weight: "100 900", }); export const metadata: Metadata = { title: "Create Next App", description: "Generated by create next app", }; export default function RootLayout({ children, }: Readonly<{ children: React.ReactNode; }>) { return ( {children} ); } ================================================ FILE: 08-Guess-Game/Frontend/app/page.tsx ================================================ "use client" import { useState, useEffect } from "react" import { Button } from "@/app/components/ui/button" import { Input } from "@/app/components/ui/input" import { Card, CardContent, CardHeader, CardTitle } from "@/app/components/ui/card" import { ethers } from "ethers" // ABIs & Configs import solidityABI from "./constants/solidityABI.json"; import config from "./constants/config.json"; export default function GuessTheNumber() { const [guess, setGuess] = useState("") const [message, setMessage] = useState("Connect your wallet to play!") const [attempts, setAttempts] = useState(0) const [isConnected, setIsConnected] = useState(false) const [account, setAccount] = useState("") const [factory, setFactory] = useState(undefined); const [provider, setProvider] = useState(undefined); const [targetNumber, setTargetNumber] = useState(0) const [isSupportedNetwork, setIsSupportedNetwork] = useState(true) useEffect(() => { loadBlockchainData() // Listen for network changes if (typeof (window as any).ethereum !== "undefined") { (window as any).ethereum.on('chainChanged', () => { window.location.reload(); // Reload the page when network changes }); (window as any).ethereum.on('accountsChanged', () => { window.location.reload(); // Reload the page when account changes }); } }, []) async function loadBlockchainData() { if (typeof (window as any).ethereum !== "undefined") { const provider = new ethers.BrowserProvider((window as any).ethereum); setProvider(provider); const network = await provider.getNetwork(); const chainId = network.chainId.toString(); console.log("Current chain ID:", chainId); console.log("Available config keys:", Object.keys(config)); // Check if the chainId exists in config if (!config[chainId as keyof typeof config]) { console.error(`Chain ID ${chainId} not found in config. Available chain IDs:`, Object.keys(config)); setMessage(`Unsupported network. Please switch to Core Testnet or localhost.`); setIsSupportedNetwork(false); return; } setIsSupportedNetwork(true); const address = config[chainId as keyof typeof config].guessGame.address as string; const contractFactory = new ethers.Contract(address, solidityABI, provider); setFactory(contractFactory); const target = await contractFactory.secret(); console.log(target); setTargetNumber(Number(target)); // Ensure it's stored as a number } else { console.error("Ethereum provider not found"); } } async function connectWallet() { if (typeof (window as any).ethereum !== "undefined") { try { const accounts = await (window as any).ethereum.request({ method: 'eth_requestAccounts' }); setAccount(accounts[0]); setIsConnected(true); setMessage("Guess a number between 1 and 100!"); // Reload blockchain data after connecting await loadBlockchainData(); } catch (error) { console.error("Failed to connect wallet:", error); } } else { setMessage("Please install MetaMask!"); } } async function switchToSupportedNetwork() { if (typeof (window as any).ethereum !== "undefined") { try { // Try to switch to Core testnet (chainId: 1114) await (window as any).ethereum.request({ method: 'wallet_switchEthereumChain', params: [{ chainId: '0x45A' }], // 1114 in hex }); // Reload blockchain data after switching await loadBlockchainData(); } catch (switchError: any) { // If the network doesn't exist, try to add it if (switchError.code === 4902) { try { await (window as any).ethereum.request({ method: 'wallet_addEthereumChain', params: [{ chainId: '0x45A', chainName: 'Core Testnet', rpcUrls: ['https://rpc.test2.btcs.network/'], nativeCurrency: { name: 'TCore2', symbol: 'TCORE2', decimals: 18, }, blockExplorerUrls: ['https://scan.test2.btcs.network/'], }], }); await loadBlockchainData(); } catch (addError) { console.error("Failed to add network:", addError); } } else { console.error("Failed to switch network:", switchError); } } } } async function handleGuess(providerr: any, factoryy: any) { try { const signer = await providerr.getSigner(); const userGuess = Number.parseInt(guess); const transaction = await factoryy.connect(signer).makeGuess(userGuess); await transaction.wait(); const tries = await factoryy.getAttempts(signer.address); setAttempts(Number(tries)); // Fetch secret number again to ensure it's the latest const updatedTarget = await factoryy.secret(); setTargetNumber(Number(updatedTarget)); if (userGuess === targetNumber) { setMessage(`🎉 Congratulations! You guessed the number in ${Number(tries)} attempts!`); } else if (userGuess < targetNumber) { setMessage("📉 Too low! Try a higher number."); } else { setMessage("📈 Too high! Try a lower number."); } setGuess(""); } catch (error) { alert("Guess should be between 1 - 100"); setMessage("⚠️ Error submitting guess, try again."); } } async function resetGame(providerr: any, factoryy: any) { try { const signer = await providerr.getSigner(); const transaction = await factoryy.connect(signer).resetGame(); await transaction.wait(); // Reset state setGuess(""); setMessage("Guess a number between 1 and 100!"); setAttempts(0); // Fetch new secret number const updatedTarget = await factoryy.secret(); setTargetNumber(Number(updatedTarget)); alert("Game Reset"); } catch (error) { console.error("Error resetting game:", error); setMessage("⚠️ Error resetting game."); } } return ( Guess the Number

{message}

{!isConnected ? ( ) : !isSupportedNetwork ? ( ) : ( <>

Connected: {account.slice(0, 6)}...{account.slice(-4)}

Attempts: {attempts}

setGuess(e.target.value)} placeholder="Enter your guess" className="flex-grow" />
)}
) } ================================================ FILE: 08-Guess-Game/Frontend/components.json ================================================ { "$schema": "https://ui.shadcn.com/schema.json", "style": "new-york", "rsc": true, "tsx": true, "tailwind": { "config": "tailwind.config.ts", "css": "app/globals.css", "baseColor": "zinc", "cssVariables": true, "prefix": "" }, "aliases": { "components": "@/components", "utils": "@/lib/utils", "ui": "@/components/ui", "lib": "@/lib", "hooks": "@/hooks" }, "iconLibrary": "lucide" } ================================================ FILE: 08-Guess-Game/Frontend/lib/utils.ts ================================================ import { clsx, type ClassValue } from "clsx" import { twMerge } from "tailwind-merge" export function cn(...inputs: ClassValue[]) { return twMerge(clsx(inputs)) } ================================================ FILE: 08-Guess-Game/Frontend/next.config.ts ================================================ import type { NextConfig } from "next"; const nextConfig: NextConfig = { /* config options here */ }; export default nextConfig; ================================================ FILE: 08-Guess-Game/Frontend/package.json ================================================ { "name": "reusable", "version": "0.1.0", "private": true, "scripts": { "dev": "next dev", "build": "next build", "start": "next start", "lint": "next lint" }, "dependencies": { "@radix-ui/react-slot": "1.1.2", "class-variance-authority": "0.7.0", "clsx": "2.1.1", "ethers": "6.13.5", "lucide-react": "0.454.0", "next": "15.0.2", "react": "18.3.1", "react-dom": "18.3.1", "tailwind-merge": "2.5.4", "tailwindcss-animate": "1.0.7" }, "devDependencies": { "@types/node": "^20", "@types/react": "18.3.3", "@types/react-dom": "18.3.0", "eslint": "8.57.0", "eslint-config-next": "15.0.2", "postcss": "^8", "tailwindcss": "^3.4.1", "typescript": "^5" } } ================================================ FILE: 08-Guess-Game/Frontend/postcss.config.mjs ================================================ /** @type {import('postcss-load-config').Config} */ const config = { plugins: { tailwindcss: {}, }, }; export default config; ================================================ FILE: 08-Guess-Game/Frontend/tailwind.config.ts ================================================ import type { Config } from "tailwindcss"; const config: Config = { darkMode: ["class"], content: [ "./pages/**/*.{js,ts,jsx,tsx,mdx}", "./components/**/*.{js,ts,jsx,tsx,mdx}", "./app/**/*.{js,ts,jsx,tsx,mdx}", ], theme: { extend: { colors: { background: 'hsl(var(--background))', foreground: 'hsl(var(--foreground))', card: { DEFAULT: 'hsl(var(--card))', foreground: 'hsl(var(--card-foreground))' }, popover: { DEFAULT: 'hsl(var(--popover))', foreground: 'hsl(var(--popover-foreground))' }, primary: { DEFAULT: 'hsl(var(--primary))', foreground: 'hsl(var(--primary-foreground))' }, secondary: { DEFAULT: 'hsl(var(--secondary))', foreground: 'hsl(var(--secondary-foreground))' }, muted: { DEFAULT: 'hsl(var(--muted))', foreground: 'hsl(var(--muted-foreground))' }, accent: { DEFAULT: 'hsl(var(--accent))', foreground: 'hsl(var(--accent-foreground))' }, destructive: { DEFAULT: 'hsl(var(--destructive))', foreground: 'hsl(var(--destructive-foreground))' }, border: 'hsl(var(--border))', input: 'hsl(var(--input))', ring: 'hsl(var(--ring))', chart: { '1': 'hsl(var(--chart-1))', '2': 'hsl(var(--chart-2))', '3': 'hsl(var(--chart-3))', '4': 'hsl(var(--chart-4))', '5': 'hsl(var(--chart-5))' } }, borderRadius: { lg: 'var(--radius)', md: 'calc(var(--radius) - 2px)', sm: 'calc(var(--radius) - 4px)' } } }, plugins: [require("tailwindcss-animate")], }; export default config; ================================================ FILE: 08-Guess-Game/Frontend/tsconfig.json ================================================ { "compilerOptions": { "target": "ES2017", "lib": ["dom", "dom.iterable", "esnext"], "allowJs": true, "skipLibCheck": true, "strict": true, "noEmit": true, "esModuleInterop": true, "module": "esnext", "moduleResolution": "bundler", "resolveJsonModule": true, "isolatedModules": true, "jsx": "preserve", "incremental": true, "plugins": [ { "name": "next" } ], "paths": { "@/*": ["./*"] } }, "include": ["next-env.d.ts", "**/*.ts", "**/*.tsx", ".next/types/**/*.ts"], "exclude": ["node_modules"] } ================================================ FILE: 08-Guess-Game/README.md ================================================ # Guess the Number Game on Core Blockchain Welcome to the "Guess the Number" game! This decentralized application (dApp) allows players to guess a secret number on the Core blockchain. The first player to guess the correct number is rewarded with tokens. ## Table of Contents - [Prerequisites](#prerequisites) - [Project Structure](#project-structure) - [Setup Instructions](#setup-instructions) - [Running the Application](#running-the-application) - [Interacting with the dApp](#interacting-with-the-dapp) - [Smart Contract Overview](#smart-contract-overview) - [Frontend Overview](#frontend-overview) - [Contributing](#contributing) - [License](#license) ## Prerequisites Before you begin, ensure you have the following installed: - [Node.js](https://nodejs.org/) (v14 or later) - [npm](https://www.npmjs.com/) or [Yarn](https://yarnpkg.com/) - [MetaMask](https://metamask.io/) browser extension - Basic understanding of Ethereum smart contracts and React ## Project Structure The repository is organized as follows: - `contracts/`: Contains the Solidity smart contract. - `scripts/`: Deployment scripts for the smart contract. - `test/`: Test scripts for the smart contract. - `frontend/`: React application for the game's frontend. - `hardhat.config.js`: Configuration file for Hardhat. ## Setup Instructions 1. **Clone the Repository** ```bash git clone https://github.com/coredao-org/dapp-tutorial.git cd dapp-tutorial/08-Guess-Game ``` 2. **Install Dependencies** Navigate to the root directory and install the necessary packages: ```bash npm install ``` Then, navigate to the `frontend` directory and install its dependencies: ```bash cd frontend npm install ``` ## Running the Application 1. **Compile the Smart Contract** Return to the root directory and compile the contract: ```bash cd .. npx hardhat compile ``` 2. **Deploy the Smart Contract** Deploy the contract to the Core blockchain testnet: ```bash npx hardhat run scripts/deploy.js --network coreTestnet ``` Ensure you have configured the `coreTestnet` network in your `hardhat.config.js` with the appropriate RPC URL and account details. 3. **Start the Frontend Application** Navigate back to the `frontend` directory and start the React application: ```bash cd frontend npm run dev ``` The application will be available at `http://localhost:3000`. ## Interacting with the dApp 1. **Connect Wallet** - Open the application in your browser. - Click on the "Connect Wallet" button. - Approve the connection in your MetaMask extension. 2. **Make a Guess** - Enter a number between 1 and 100 in the input field. - Click the "Guess" button. - The application will inform you if your guess is too high, too low, or correct. - Your number of attempts will be displayed. 3. **Reset the Game** - Click the "New Game" button to reset the game and start over. ## Smart Contract Overview The smart contract is written in Solidity and is located in the `contracts` directory. It manages the game's logic, including: - Storing the secret number. - Tracking the number of attempts by each player. - Rewarding the first player who guesses the correct number. ## Frontend Overview The frontend is built with React and is located in the `frontend` directory. It interacts with the smart contract using the ethers.js library and provides a user-friendly interface for players. ## Contributing Contributions are welcome! Please fork the repository and submit a pull request with your changes. ================================================ FILE: 08-Guess-Game/contracts/GuessTheNumber.sol ================================================ // SPDX-License-Identifier: MIT pragma solidity ^0.8.19; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; contract GuessTheNumber is Ownable { uint256 public secretNumber; address public lastWinner; mapping(address => uint256) public attempts; IERC20 public rewardToken; uint256 public rewardAmount; event GameStarted(uint256 blockNumber); event GuessMade(address indexed player, uint256 guess, string message); event GameWon(address indexed winner, uint256 attempts, uint256 reward); constructor(address _rewardToken, uint256 _rewardAmount) Ownable(msg.sender) { rewardToken = IERC20(_rewardToken); rewardAmount = _rewardAmount; resetGame(); } function resetGame() public { // Generate random number using blockhash and timestamp secretNumber = uint256(keccak256(abi.encodePacked(blockhash(block.number - 1), block.timestamp))) % 100 + 1; attempts[msg.sender] = 0; emit GameStarted(block.number); } function makeGuess(uint256 _guess) public { require(_guess >= 1 && _guess <= 100, "Guess must be between 1 and 100"); attempts[msg.sender]++; if (_guess == secretNumber) { lastWinner = msg.sender; // Reward the winner (if the contract has enough tokens) if (rewardToken.balanceOf(address(this)) >= rewardAmount) { rewardToken.transfer(msg.sender, rewardAmount); } emit GameWon(msg.sender, attempts[msg.sender], rewardAmount); resetGame(); } else if (_guess < secretNumber) { emit GuessMade(msg.sender, _guess, "Too low! Try a higher number."); } else { emit GuessMade(msg.sender, _guess, "Too high! Try a lower number."); } } // Owner can set new reward amount function setReward(uint256 _newAmount) external onlyOwner { rewardAmount = _newAmount; } // Deposit ERC-20 tokens to fund rewards function depositRewards(uint256 amount) external { require(rewardToken.transferFrom(msg.sender, address(this), amount), "Transfer failed"); } // Withdraw ERC-20 tokens (only owner) function withdrawTokens(uint256 amount) external onlyOwner { require(rewardToken.transfer(msg.sender, amount), "Transfer failed"); } function secret() public view returns (uint256) { return secretNumber; } function getAttempts(address _playerAddress) public view returns (uint256) { return attempts[_playerAddress]; } } ================================================ FILE: 08-Guess-Game/contracts/GuessToken.sol ================================================ // SPDX-License-Identifier: MIT // Compatible with OpenZeppelin Contracts ^5.0.0 pragma solidity ^0.8.22; import {ERC20} from "@openzeppelin/contracts/token/ERC20/ERC20.sol"; contract GuessToken is ERC20 { constructor() ERC20("GuessToken", "GTK") {} function mint(address gameAddress) public { _mint(gameAddress, 100000 * 10 ** 18); } } ================================================ FILE: 08-Guess-Game/hardhat.config.js ================================================ require("@nomicfoundation/hardhat-toolbox"); require("dotenv").config(); /** @type import('hardhat/config').HardhatUserConfig */ const PRIVATE_KEY = process.env.PRIVATE_KEY; module.exports = { solidity: "0.8.24", networks: { localhost: { url: "http://127.0.0.1:8545/", // accounts: Thanks hardhat! chainId: 31337, allowUnlimitedContractSize: true, }, coreTestnet: { url: 'https://rpc.test2.btcs.network/', accounts: [PRIVATE_KEY], chainId: 1114, }, }, }; ================================================ FILE: 08-Guess-Game/ignition/modules/Lock.js ================================================ // This setup uses Hardhat Ignition to manage smart contract deployments. // Learn more about it at https://hardhat.org/ignition const { buildModule } = require("@nomicfoundation/hardhat-ignition/modules"); const JAN_1ST_2030 = 1893456000; const ONE_GWEI = 1_000_000_000n; module.exports = buildModule("LockModule", (m) => { const unlockTime = m.getParameter("unlockTime", JAN_1ST_2030); const lockedAmount = m.getParameter("lockedAmount", ONE_GWEI); const lock = m.contract("Lock", [unlockTime], { value: lockedAmount, }); return { lock }; }); ================================================ FILE: 08-Guess-Game/package.json ================================================ { "name": "reuse", "version": "1.0.0", "main": "index.js", "scripts": { "test": "echo \"Error: no test specified\" && exit 1" }, "author": "", "license": "ISC", "description": "", "devDependencies": { "@nomicfoundation/hardhat-toolbox": "5.0.0", "hardhat": "2.22.15" }, "dependencies": { "@openzeppelin/contracts": "5.2.0", "dotenv": "16.4.7" } } ================================================ FILE: 08-Guess-Game/scripts/deploy-guess-game.js ================================================ const hre = require("hardhat"); async function main() { const GuessTokenContract = await hre.ethers.getContractFactory("GuessToken"); const guessTokenContract = await GuessTokenContract.deploy(); const GuessGameContract = await hre.ethers.getContractFactory("GuessTheNumber"); const guessGameContract = await GuessGameContract.deploy(guessTokenContract.target, ethers.parseEther("2")); await guessTokenContract.mint(guessGameContract.target) const balance = await guessTokenContract.balanceOf(guessGameContract.target); console.log(balance); console.log("Guess Token contract deployed to:", guessTokenContract.target); console.log("Guess game contract deployed to:", guessGameContract.target); } // We recommend this pattern to be able to use async/await everywhere // and properly handle errors. main().catch((error) => { console.error(error); process.exitCode = 1; }); // Telos: Support contract deployed to: 0x5Ac64F5DA22B25559C7D7522b4B2BB7e2012F382 ================================================ FILE: 08-Guess-Game/test/Lock.js ================================================ const { time, loadFixture, } = require("@nomicfoundation/hardhat-toolbox/network-helpers"); const { anyValue } = require("@nomicfoundation/hardhat-chai-matchers/withArgs"); const { expect } = require("chai"); describe("Lock", function () { // We define a fixture to reuse the same setup in every test. // We use loadFixture to run this setup once, snapshot that state, // and reset Hardhat Network to that snapshot in every test. async function deployOneYearLockFixture() { const ONE_YEAR_IN_SECS = 365 * 24 * 60 * 60; const ONE_GWEI = 1_000_000_000; const lockedAmount = ONE_GWEI; const unlockTime = (await time.latest()) + ONE_YEAR_IN_SECS; // Contracts are deployed using the first signer/account by default const [owner, otherAccount] = await ethers.getSigners(); const Lock = await ethers.getContractFactory("Lock"); const lock = await Lock.deploy(unlockTime, { value: lockedAmount }); return { lock, unlockTime, lockedAmount, owner, otherAccount }; } describe("Deployment", function () { it("Should set the right unlockTime", async function () { const { lock, unlockTime } = await loadFixture(deployOneYearLockFixture); expect(await lock.unlockTime()).to.equal(unlockTime); }); it("Should set the right owner", async function () { const { lock, owner } = await loadFixture(deployOneYearLockFixture); expect(await lock.owner()).to.equal(owner.address); }); it("Should receive and store the funds to lock", async function () { const { lock, lockedAmount } = await loadFixture( deployOneYearLockFixture ); expect(await ethers.provider.getBalance(lock.target)).to.equal( lockedAmount ); }); it("Should fail if the unlockTime is not in the future", async function () { // We don't use the fixture here because we want a different deployment const latestTime = await time.latest(); const Lock = await ethers.getContractFactory("Lock"); await expect(Lock.deploy(latestTime, { value: 1 })).to.be.revertedWith( "Unlock time should be in the future" ); }); }); describe("Withdrawals", function () { describe("Validations", function () { it("Should revert with the right error if called too soon", async function () { const { lock } = await loadFixture(deployOneYearLockFixture); await expect(lock.withdraw()).to.be.revertedWith( "You can't withdraw yet" ); }); it("Should revert with the right error if called from another account", async function () { const { lock, unlockTime, otherAccount } = await loadFixture( deployOneYearLockFixture ); // We can increase the time in Hardhat Network await time.increaseTo(unlockTime); // We use lock.connect() to send a transaction from another account await expect(lock.connect(otherAccount).withdraw()).to.be.revertedWith( "You aren't the owner" ); }); it("Shouldn't fail if the unlockTime has arrived and the owner calls it", async function () { const { lock, unlockTime } = await loadFixture( deployOneYearLockFixture ); // Transactions are sent using the first signer by default await time.increaseTo(unlockTime); await expect(lock.withdraw()).not.to.be.reverted; }); }); describe("Events", function () { it("Should emit an event on withdrawals", async function () { const { lock, unlockTime, lockedAmount } = await loadFixture( deployOneYearLockFixture ); await time.increaseTo(unlockTime); await expect(lock.withdraw()) .to.emit(lock, "Withdrawal") .withArgs(lockedAmount, anyValue); // We accept any value as `when` arg }); }); describe("Transfers", function () { it("Should transfer the funds to the owner", async function () { const { lock, unlockTime, lockedAmount, owner } = await loadFixture( deployOneYearLockFixture ); await time.increaseTo(unlockTime); await expect(lock.withdraw()).to.changeEtherBalances( [owner, lock], [lockedAmount, -lockedAmount] ); }); }); }); }); ================================================ FILE: 09-Token-swap-Dapp/.gitignore ================================================ node_modules .env # Hardhat files /cache /artifacts # TypeChain files /typechain /typechain-types # solidity-coverage files /coverage /coverage.json # Hardhat Ignition default folder for deployments against a local node ignition/modules/* ================================================ FILE: 09-Token-swap-Dapp/README.md ================================================ # Building a Token Swapping Dapp on Core ## What are we building In this tutorial, we will guide you through building a simple token swapping decentralized application (dApp) on the Core blockchain. By the end of this guide, you will have a fully functional dApp that allows users to seamlessly swap between native tokens and ERC20 tokens directly on the Core Testnet. This dApp will provide functionality for two types of swaps: ERC20-to-ERC20 swaps: Users will be able to exchange custom ERC20 tokens, such as `Token A (USDC)` for `Token B (USDT)` and vice versa. Native-to-ERC20 swaps: Users will also have the ability to swap `Core's native token (CORE)` with ERC20 tokens like `USDT` or `USDC`. ## Learning Takeaways - Smart Contract Development and deployment - Building a frontend for integration with smart contracts - Using Ethers.js library for communicating with smart contracts - Integrating Metamask for secure user transactions and interactions - Read and Write data to/from smart contracts ## Software Prerequisites - [Git](https://git-scm.com/) v2.44.0 - [Node.js](https://nodejs.org/en) v20.11.1 - [npm](https://docs.npmjs.com/downloading-and-installing-node-js-and-npm) v10.2.4 - [Hardhat](https://hardhat.org/hardhat-runner/docs/getting-started#installation) v2.22.6 - [MetaMask Web Wallet Extension](https://metamask.io/download/)Git v2.44.0 - **Core Testnet Configuration:** Configure MetaMask to connect to the Core Testnet. Refer [here](https://docs.coredao.org/docs/Dev-Guide/core-testnet-wallet-config#adding-core-testnet-to-metamask) for more details. - **Network Name:** Core Testnet - **New RPC URL:** https://rpc.test2.btcs.network - **Chain ID:** 1115 - **Currency Symbol:** CORE - **Core Faucet:** To get test CORE tokens for transactions, visit the [Core Faucet](https://scan.test2.btcs.network/faucet), refer [here] (https://docs.coredao.org/docs/Dev-Guide/core-faucet) for more details. ## Setting up Dev Environment ### 1. Initialize the Project ``` mkdir swap-token cd swap-token npm init -y npm install --save-dev hardhat npx hardhat init ``` ![img](./frontend/src/assets/hardhat-init.png) ### 2. Install and Configure MetaMask - Install and configure MetaMask Chrome Extension to use with Core Testnet. - Refer [here](https://docs.coredao.org/docs/Dev-Guide/core-testnet-wallet-config) for a detailed guide. ### 3. Create a Secret File - Create a `.env` file in the root folder and store the private key of your MetaMask wallet in it. ```bash PRIVATE_KEY = ``` > _Do not forget to add this file to the `.gitignore` file in the root folder of your project so that you don't accidentally check your private keys/secret phrases into a public repository. Make sure you keep this file in an absolutely safe place!_ ### 4. Update .gitignore - Update your .gitignore file to ensure that your secret.json file and other sensitive files are not committed to version control. - Make sure to add `secret.json` to the `.gitignore` file. ``` node_modules .env secret.json # Hardhat files /cache /artifacts # TypeChain files /typechain /typechain-types # solidity-coverage files /coverage /coverage.json # Hardhat Ignition default folder for deployments against a local node ignition/deployments/chain-31337 ``` ### 5. Update Hardhat.config Replace the contents of `hardhat.config.js` with the following configuration. Ensure that the network settings are configured correctly for Core Testnet. ``` require("@nomicfoundation/hardhat-toolbox"); require("dotenv").config(); /** @type import('hardhat/config').HardhatUserConfig */ const PRIVATE_KEY = process.env.PRIVATE_KEY; module.exports = { defaultNetwork: "hardhat", networks: { hardhat: {}, core_testnet: { url: "https://rpc.test2.btcs.network", accounts: [PRIVATE_KEY], chainId: 1114, }, }, solidity: { compilers: [ { version: '0.8.24', settings: { evmVersion: 'paris', optimizer: { enabled: true, runs: 200, }, }, }, ], }, paths: { sources: './contracts', cache: './cache', artifacts: './artifacts', }, mocha: { timeout: 20000, }, }; ``` ## Writing Smart Contracts In the `contracts` folder, create the following smart contracts. ### ERC20 Token Contract - For this dapp, we create a custom ERC20 Token contract - Create a `Token.sol` file in contracts folder and udpate its contents with the following. ```js // SPDX-License-Identifier: MIT pragma solidity ^0.8.24; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; contract Token is ERC20, Ownable { constructor(string memory _name, string memory _symbol) ERC20(_name, _symbol) Ownable(msg.sender) { _mint(msg.sender, 500 ether); } function mint(address to, uint256 amount) public onlyOwner { _mint(to, amount); } } ``` ### Swap Contract - Create a `Swap.sol` file in contracts folder and udpate its contents with the following. ```js // SPDX-License-Identifier: MIT pragma solidity ^0.8.24; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; contract Swap is Ownable { address public feeCollector; // Address to collect fees uint32 public feePercent; // Fee percentage (in basis points, e.g., 50 = 0.5%) event TokensSwapped( address indexed user, address indexed tokenA, address indexed tokenB, uint256 amountIn, uint256 amountOut, uint256 fee ); constructor(uint32 _feePercent) Ownable(msg.sender){ require(_feePercent <= 10000, "Fee too high"); feeCollector = msg.sender; feePercent = _feePercent; } // Swap ERC20 tokens function swapTokens( address tokenA, address tokenB, uint256 amountIn ) external { require(amountIn > 0, "AmountIn must be greater than 0"); // Calculate fee uint256 fee = (amountIn * feePercent) / 10000; uint256 amountOut = amountIn - fee; require(IERC20(tokenB).balanceOf(address(this)) >= amountOut, "Insufficient tokenB for swap"); // Transfer tokenA from sender to this contract IERC20(tokenA).transferFrom(msg.sender, address(this), amountIn); // Send fee to fee collector if (fee > 0) { IERC20(tokenA).transfer(feeCollector, fee); } // Transfer tokenB to the receiver IERC20(tokenB).transfer(msg.sender, amountOut); // Emit event for transparency emit TokensSwapped(msg.sender, tokenA, tokenB, amountIn, amountOut, fee); } // Swap native token (ETH) for ERC20 token function swapNativeForToken(address tokenB) external payable { require(msg.value > 0, "Amount must be greater than 0"); uint256 amountIn = msg.value; uint256 fee = (amountIn * feePercent) / 10000; uint256 amountOut = amountIn - fee; require(IERC20(tokenB).balanceOf(address(this)) >= amountOut, "Insufficient token for swap"); // Send fee to fee collector in native tokens if (fee > 0) { payable(feeCollector).transfer(fee); } // Transfer tokenB to the user IERC20(tokenB).transfer(msg.sender, amountOut); // Emit event for transparency emit TokensSwapped(msg.sender, address(0), tokenB, amountIn, amountOut, fee); } // Withdraw ERC20 tokens from the contract function withdrawTokens(address token, uint256 amount) external onlyOwner { require(IERC20(token).balanceOf(address(this)) >= amount, "Insufficient token balance"); IERC20(token).transfer(msg.sender, amount); } // Withdraw native tokens from the contract function withdrawNative(uint256 amount) external onlyOwner { require(address(this).balance >= amount, "Insufficient ETH balance"); payable(msg.sender).transfer(amount); } // Updates the fee percentage function updateFee(uint32 newFeePercent) public onlyOwner { require(newFeePercent <= 10000, "Fee too high"); feePercent = newFeePercent; } } ``` #### Explanation The Swap.sol contract handles the swapping of tokens between ERC20 tokens and the native token (CORE) on the Core blockchain. Here's how it works: ##### State Variables - **feeCollector:** This stores the address where the swap fees will be sent. - **feePercent:** This determines the percentage of the fee deducted during each swap (e.g., 50 = 0.5%). ##### Functions 1. **swapTokens(address tokenA, address tokenB, uint256 amountIn)**: - Allows users to swap one ERC20 token (tokenA) for another ERC20 token (tokenB). - Fee is deducted from amountIn, and the remaining amount is transferred to the user. - Emits the TokensSwapped event. 2. **swapNativeForToken(address tokenB)**: - Allows users to swap the native blockchain token (CORE) for an ERC20 token (tokenB). - Accepts a msg.value in native tokens, deducts a fee, and transfers the remaining tokenB to the user. - Emits a TokensSwapped event. 3. **withdrawTokens(address token, uint256 amount)**: Allows the contract owner to withdraw any ERC20 tokens stored in the contract. 4. **withdrawNative(uint256 amount)**: Allows the owner to withdraw native tokens stored in the contract. 5. **updateFee(uint32 newFeePercent)**: Updates the fee percentage for the swaps, limited to a maximum of 10000 basis points (i.e., 100%). ## How the Swap Works: 1. Users provide the input token (tokenA) they want to swap and specify the token they want to receive (tokenB). 2. The contract calculates the fee, deducts it from the input amount, and transfers the output token (tokenB) to the user. 3. The fee is transferred to the fee collector (the contract owner by default). ## Compile and Deploy Smart Contracts ### Compiling Smart Contracts To compile the smart contracts, run the command `npx hardhat compile` ### Deploying Smart Contracts - Create a `scritps` folder in the root of your project. - Create a file `deploy.js` in the `scripts` folder. - Update the contents of the `deploy.js` file with the following: ```js const { ethers } = require("hardhat"); async function main() { const [deployer] = await ethers.getSigners(); console.log("Deploying contracts with the account:", deployer.address); const ERC20 = await ethers.getContractFactory("Token"); const usdt = await ERC20.deploy("usdt", "USDT"); const usdc = await ERC20.deploy("usdc", "USDC"); const fee = 10; const Swap = await ethers.getContractFactory("Swap"); const swap = await Swap.deploy(fee); console.log("Contracts deployed:"); console.log("Swap Contract:", await swap.getAddress()); console.log("usdt Token:", await usdt.getAddress()); console.log("usdc Token:", await usdc.getAddress()); const swapContractAddr = await swap.getAddress(); await usdt.approve(swapContractAddr, ethers.parseEther("100")); await usdt.transfer(swapContractAddr, ethers.parseEther("100")); await usdc.approve(swapContractAddr, ethers.parseEther("100")); await usdc.transfer(swapContractAddr, ethers.parseEther("100")); } main() .then(() => process.exit(0)) .catch((error) => { console.error(error); process.exit(1); }); ``` - Make sure your MetaMask wallet has tCORE test tokens for the Core Testnet. Refer [here](https://docs.coredao.org/docs/Dev-Guide/core-faucet) for details on how to get tCORE tokens from Core Faucet. - Run the following command from the root directory of your project, to deploy smart contracts on the Core blockchain. ```bash npx hardhat run scripts/deploy.js ``` - If succesfully deployed, you will get the following output ![img](./frontend/src/assets/deploy.png) - Save the addresses for the deployed contracts for use with the frontend. ## Interacting with Smart Contract through Frontend ⚡️ Let's create a frontend interface for interacting with the smart contract. ### Setting up frontend - Create a simple react application using the following command ```bash npx create-react-app frontend cd frontend ``` - Install Dependencies, the Ethers.js library for communicating with the deployed smart contracts. ```bash npm install --save-dev ethers@5.7.2 ``` - Create a `contracts` folder inside the `frontend/src` folder. ```bash mkdir contracts ``` Copy the ABIs in the form of `.json` files, of your deployed smart contracts, from `artifacts/contracts/Token.sol` and `artifacts/contracts/Swap.sol` directories into the `frontend/src/contracts` directory. ### Adding Frontend Fuctionality - Update the `App.js` with the contents of the [App.js](./frontend/src/App.js) in the boilerplate repo. - Update the `App.css` with the contents of the [App.css](./frontend/src/App.css) in the boilerplate repo. ### Key Implementation The application's key blockchain logic is implemented in [App.js](./frontend/src/App.js) 1. **App.js (Connect Wallet)**: Line #41 onwards is the logic for connecting the application to the MetaMask wallet, allowing users to interact with the blockchain. 2. **App.js (Check Network)**: Line #28 is the logic for checking if the user is connected to the Core Testnet. It alerts the user if they are connected to the wrong network. 3. **App.js (Calculate Output Amount)** : Line #62 is the logic for calculating the output amount based on the input amount and the fee percentage applied during the token swap. 4. **App.js (Swap Tokens)**: Line #150 is the logic for executing the token swap. It handles both native token swaps and ERC-20 token swaps, including approval of tokens and transaction handling. ### Adding Smart Contract Details - Paste this into Lines 11, 12, and 15 the addresses of the deployed contracts of USDT, USDC and Swap Contract Address. ```js const tokenAddresses = { CORE: "0x0000000000000000000000000000000000000000", USDT: "0xdBb5e35236536d38239102596adcaA5626e27bE2", USDC: "0x82fa6E5EDCE48bA4EBcA82dCDdec08d124d7Eed3", }; const swapContractAddress = "0x8ac209ee5dfaC9c2D915f24edD34d4072059558b"; ``` ### Testing Locally - From the `frontend` directory, run the command `npm run start` - Make sure that your MetaMask wallet is correctly installed and switched to Core Testnet as described in our [Core Testnet user guide](https://docs.coredao.org/docs/Dev-Guide/core-testnet-wallet-config). You'll also need to connect your MetaMask wallet to the local site. - Navigate to `http://localhost:3000/` in your browser. ![dapp-ui](./frontend/src/assets/dapp_ui.png) #### Native to ERC-20 Token Transfer - Click on `CORE` Input token and choose the output token `USDT` or `USDC` - The Dapp automatically calculates the expected output amount based on the input amount, applying the defined fee percentage. ![dapp-ui](./frontend/src/assets/init_swap.png) - After reviwing the swap Details, click on Swap and you need to confirm the transaction ![dapp-ui](./frontend/src/assets/native_swap.png) - Once the transaction confirmed, you will see the swap successfull message and the balance has been updated ![dapp-ui](./frontend/src/assets/native_swap_success.png) #### ERC20 to ERC-20 Token Transfer - Click on `USDT` Input token and by default the output Amount will show `USDC` - The Dapp automatically calculates the expected output amount based on the input amount, applying the defined fee percentage. ![dapp-ui](./frontend/src/assets/usdt_usdc.png) - After reviwing the swap Details, click on Swap and First you need to Approve and then confirm the transaction ![dapp-ui](./frontend/src/assets/approve.png) ![dapp-ui](./frontend/src/assets/usdt_swap_confirm.png) - Once the transaction confirmed, you will see the swap successfull message ## 🎉 **Congratulations!** You've just interacted with your deployed contract using your dApp's front end! You can build on the codebase by adding new UI components or more functionality to the Token Swap dapp. ================================================ FILE: 09-Token-swap-Dapp/contracts/Swap.sol ================================================ // SPDX-License-Identifier: MIT pragma solidity ^0.8.24; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; contract Swap is Ownable { address public feeCollector; // Address to collect fees uint32 public feePercent; // Fee percentage (in basis points, e.g., 50 = 0.5%) event TokensSwapped( address indexed user, address indexed tokenA, address indexed tokenB, uint256 amountIn, uint256 amountOut, uint256 fee ); constructor(uint32 _feePercent) Ownable(msg.sender){ require(_feePercent <= 10000, "Fee too high"); feeCollector = msg.sender; feePercent = _feePercent; } // Swap ERC20 tokens function swapTokens( address tokenA, address tokenB, uint256 amountIn ) external { require(amountIn > 0, "AmountIn must be greater than 0"); // Calculate fee uint256 fee = (amountIn * feePercent) / 10000; uint256 amountOut = amountIn - fee; require(IERC20(tokenB).balanceOf(address(this)) >= amountOut, "Insufficient tokenB for swap"); // Transfer tokenA from sender to this contract IERC20(tokenA).transferFrom(msg.sender, address(this), amountIn); // Send fee to fee collector if (fee > 0) { IERC20(tokenA).transfer(feeCollector, fee); } // Transfer tokenB to the receiver IERC20(tokenB).transfer(msg.sender, amountOut); // Emit event for transparency emit TokensSwapped(msg.sender, tokenA, tokenB, amountIn, amountOut, fee); } // Swap native token (ETH) for ERC20 token function swapNativeForToken(address tokenB) external payable { require(msg.value > 0, "Amount must be greater than 0"); uint256 amountIn = msg.value; uint256 fee = (amountIn * feePercent) / 10000; uint256 amountOut = amountIn - fee; require(IERC20(tokenB).balanceOf(address(this)) >= amountOut, "Insufficient token for swap"); // Send fee to fee collector in native tokens if (fee > 0) { payable(feeCollector).transfer(fee); } // Transfer tokenB to the user IERC20(tokenB).transfer(msg.sender, amountOut); // Emit event for transparency emit TokensSwapped(msg.sender, address(0), tokenB, amountIn, amountOut, fee); } // Withdraw ERC20 tokens from the contract function withdrawTokens(address token, uint256 amount) external onlyOwner { require(IERC20(token).balanceOf(address(this)) >= amount, "Insufficient token balance"); IERC20(token).transfer(msg.sender, amount); } // Withdraw native tokens from the contract function withdrawNative(uint256 amount) external onlyOwner { require(address(this).balance >= amount, "Insufficient ETH balance"); payable(msg.sender).transfer(amount); } // Updates the fee percentage function updateFee(uint32 newFeePercent) public onlyOwner { require(newFeePercent <= 10000, "Fee too high"); feePercent = newFeePercent; } } ================================================ FILE: 09-Token-swap-Dapp/contracts/Token.sol ================================================ // SPDX-License-Identifier: MIT pragma solidity ^0.8.24; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; contract Token is ERC20, Ownable { constructor(string memory _name, string memory _symbol) ERC20(_name, _symbol) Ownable(msg.sender) { _mint(msg.sender, 500 ether); } function mint(address to, uint256 amount) public onlyOwner { _mint(to, amount); } } ================================================ FILE: 09-Token-swap-Dapp/frontend/.gitignore ================================================ # See https://help.github.com/articles/ignoring-files/ for more about ignoring files. # dependencies /node_modules /.pnp .pnp.js # testing /coverage # production /build # misc .DS_Store .env.local .env.development.local .env.test.local .env.production.local npm-debug.log* yarn-debug.log* yarn-error.log* ================================================ FILE: 09-Token-swap-Dapp/frontend/README.md ================================================ # Getting Started with Create React App This project was bootstrapped with [Create React App](https://github.com/facebook/create-react-app). ## Available Scripts In the project directory, you can run: ### `npm start` Runs the app in the development mode.\ Open [http://localhost:3000](http://localhost:3000) to view it in your browser. The page will reload when you make changes.\ You may also see any lint errors in the console. ### `npm test` Launches the test runner in the interactive watch mode.\ See the section about [running tests](https://facebook.github.io/create-react-app/docs/running-tests) for more information. ### `npm run build` Builds the app for production to the `build` folder.\ It correctly bundles React in production mode and optimizes the build for the best performance. The build is minified and the filenames include the hashes.\ Your app is ready to be deployed! See the section about [deployment](https://facebook.github.io/create-react-app/docs/deployment) for more information. ### `npm run eject` **Note: this is a one-way operation. Once you `eject`, you can't go back!** If you aren't satisfied with the build tool and configuration choices, you can `eject` at any time. This command will remove the single build dependency from your project. Instead, it will copy all the configuration files and the transitive dependencies (webpack, Babel, ESLint, etc) right into your project so you have full control over them. All of the commands except `eject` will still work, but they will point to the copied scripts so you can tweak them. At this point you're on your own. You don't have to ever use `eject`. The curated feature set is suitable for small and middle deployments, and you shouldn't feel obligated to use this feature. However we understand that this tool wouldn't be useful if you couldn't customize it when you are ready for it. ## Learn More You can learn more in the [Create React App documentation](https://facebook.github.io/create-react-app/docs/getting-started). To learn React, check out the [React documentation](https://reactjs.org/). ### Code Splitting This section has moved here: [https://facebook.github.io/create-react-app/docs/code-splitting](https://facebook.github.io/create-react-app/docs/code-splitting) ### Analyzing the Bundle Size This section has moved here: [https://facebook.github.io/create-react-app/docs/analyzing-the-bundle-size](https://facebook.github.io/create-react-app/docs/analyzing-the-bundle-size) ### Making a Progressive Web App This section has moved here: [https://facebook.github.io/create-react-app/docs/making-a-progressive-web-app](https://facebook.github.io/create-react-app/docs/making-a-progressive-web-app) ### Advanced Configuration This section has moved here: [https://facebook.github.io/create-react-app/docs/advanced-configuration](https://facebook.github.io/create-react-app/docs/advanced-configuration) ### Deployment This section has moved here: [https://facebook.github.io/create-react-app/docs/deployment](https://facebook.github.io/create-react-app/docs/deployment) ### `npm run build` fails to minify This section has moved here: [https://facebook.github.io/create-react-app/docs/troubleshooting#npm-run-build-fails-to-minify](https://facebook.github.io/create-react-app/docs/troubleshooting#npm-run-build-fails-to-minify) ================================================ FILE: 09-Token-swap-Dapp/frontend/package.json ================================================ { "name": "frontend", "version": "0.1.0", "private": true, "dependencies": { "@testing-library/jest-dom": "5.17.0", "@testing-library/react": "13.4.0", "@testing-library/user-event": "13.5.0", "ethers": "5.7.2", "lucide-react": "0.453.0", "react": "18.3.1", "react-dom": "18.3.1", "react-scripts": "5.0.1", "web-vitals": "2.1.4" }, "scripts": { "start": "react-scripts start", "build": "react-scripts build", "test": "react-scripts test", "eject": "react-scripts eject" }, "eslintConfig": { "extends": [ "react-app", "react-app/jest" ] }, "browserslist": { "production": [ ">0.2%", "not dead", "not op_mini all" ], "development": [ "last 1 chrome version", "last 1 firefox version", "last 1 safari version" ] } } ================================================ FILE: 09-Token-swap-Dapp/frontend/public/index.html ================================================ React App
================================================ FILE: 09-Token-swap-Dapp/frontend/public/manifest.json ================================================ { "short_name": "React App", "name": "Create React App Sample", "icons": [ { "src": "favicon.ico", "sizes": "64x64 32x32 24x24 16x16", "type": "image/x-icon" }, { "src": "logo192.png", "type": "image/png", "sizes": "192x192" }, { "src": "logo512.png", "type": "image/png", "sizes": "512x512" } ], "start_url": ".", "display": "standalone", "theme_color": "#000000", "background_color": "#ffffff" } ================================================ FILE: 09-Token-swap-Dapp/frontend/public/robots.txt ================================================ # https://www.robotstxt.org/robotstxt.html User-agent: * Disallow: ================================================ FILE: 09-Token-swap-Dapp/frontend/src/App.css ================================================ /* App.css */ body { margin: 0; font-family: Arial, sans-serif; background-color: #f4f4f9; color: #333; } .App { text-align: center; padding: 20px; position: relative; /* Ensure the App container is positioned relatively for absolute children */ } .logo-container { text-align: center; margin-bottom: 20px; } .logo { max-width: 150px; /* Adjust as needed for logo size */ } .App-header { background-color: #f8f9fa; padding: 20px; border-bottom: 2px solid #eaeaea; position: relative; /* To position elements inside it */ margin-bottom: 100px; /* Space between header and content */ } .App-header h1 { margin: 0; color: #ff6f00; /* Core Chain orange color */ } .btn-primary { background-color: #ff6f00; /* Core Chain orange color */ color: white; border: none; padding: 12px 20px; font-size: 16px; cursor: pointer; border-radius: 5px; width: 200px; /* Set a consistent width for all buttons */ height: 40px; /* Set a consistent height for all buttons */ display: inline-flex; align-items: center; justify-content: center; text-align: center; margin: 10px; /* Add margin to separate buttons */ } .btn-primary:hover { background-color: #e65c00; /* Darker orange for hover effect */ } .input-field { padding: 10px; font-size: 16px; border: 1px solid #ccc; border-radius: 5px; width: 200px; margin: 5px; } .input-field:focus { border-color: #ff6f00; outline: none; } .amount-ticker { display: flex; justify-content: space-between; align-items: center; margin-bottom: 20px; } .amount-ticker p { margin: 5px 20px; font-size: 18px; } .stake-container, .unstake-container { margin: 20px 0; } .stake-container input, .unstake-container input { width: 200px; } .modal-btns { display: flex; justify-content: center; gap: 10px; } .disconnect-btn { position: absolute; top: 20px; right: 20px; } .swap-container { display: flex; justify-content: center; align-items: center; padding: 20px; } .swap-box { width: 350px; padding: 20px; border-radius: 10px; border: 1px solid #ffa31a; } .swap-input { margin-bottom: 20px; } .swap-options { padding: 10px; font-size: 16px; border: 1px solid #ccc; border-radius: 5px; width: 100px; margin: 5px; } .input-row { display: flex; justify-content: space-between; align-items: center; } .input-row select { width: 40%; padding: 10px; margin-right: 10px; background: #333; color: white; border: none; border-radius: 5px; } .input-row input { width: 60%; padding: 10px; background: #333; color: white; border: none; border-radius: 5px; } .swap-arrow { width: 20%; padding: 10px; background: #333; color: white; border: none; border-radius: 5px; cursor: pointer; margin-bottom: 20px; } .swap-subtitle { text-align: left; color: #696868; padding-bottom: 20px; } @media (max-width: 768px) { .amount-ticker { flex-direction: column; align-items: flex-start; } .amount-ticker p { margin: 5px 0; } .disconnect-btn { position: relative; top: auto; right: auto; } } ================================================ FILE: 09-Token-swap-Dapp/frontend/src/App.js ================================================ import { useEffect, useState, useCallback } from "react"; import { ethers } from "ethers"; import "./App.css"; import TokenABI from "./contracts/Token.json"; import SwapABI from "./contracts/Swap.json"; import coreLogo from "./assets/core-logo.png"; // Replace these addresses with your actual token and swap contract addresses const tokenAddresses = { CORE: "0x0000000000000000000000000000000000000000", USDT: "0xdBb5e35236536d38239102596adcaA5626e27bE2", USDC: "0x82fa6E5EDCE48bA4EBcA82dCDdec08d124d7Eed3", }; const swapContractAddress = "0x8ac209ee5dfaC9c2D915f24edD34d4072059558b"; // Add your swap contract address here const tokens = ["CORE", "USDT", "USDC"]; const feePercentage = 0.5; function App() { const [inputToken, setInputToken] = useState("CORE"); const [outputToken, setOutputToken] = useState("USDT"); const [inputAmount, setInputAmount] = useState(""); const [outputAmount, setOutputAmount] = useState("0"); const [currentAccount, setCurrentAccount] = useState(null); const [network, setNetwork] = useState(""); const [isSwapping, setIsSwapping] = useState(false); // Check network const checkNetwork = async () => { const { ethereum } = window; if (!ethereum) { console.log("Ethereum object does not exist"); return; } try { const provider = new ethers.providers.Web3Provider(ethereum); const { chainId } = await provider.getNetwork(); if (chainId !== 1114) { alert("Please connect to the Core Testnet"); } else { setNetwork("Core Testnet"); } } catch (error) { console.error("Error fetching network:", error); } }; const connectWalletHandler = async () => { const { ethereum } = window; if (!ethereum) return alert("Please install MetaMask!"); const accounts = await ethereum.request({ method: "eth_requestAccounts" }); setCurrentAccount(accounts[0]); }; // Calculate the output amount based on the input and fee const calculateOutputAmount = useCallback(() => { if (!inputAmount) { setOutputAmount("0"); return; } const input = parseFloat(inputAmount); const fee = (input * feePercentage) / 100; const finalOutput = input - fee; setOutputAmount(finalOutput.toFixed(6)); }, [inputAmount]); const getOutputTokenOptions = () => { const tokenPairs = { USDT: ["USDC"], USDC: ["USDT"], }; return ( tokenPairs[inputToken] || tokens.filter((token) => token !== inputToken) ); }; useEffect(() => { checkNetwork(); calculateOutputAmount(); }, [inputToken, outputToken, inputAmount, calculateOutputAmount]); const handleInputChange = (value) => { if (/^\d*\.?\d*$/.test(value)) setInputAmount(value); }; const handleTokenSwap = async () => { if (!currentAccount) return alert("Please connect your wallet."); try { const { ethereum } = window; if (!ethereum) return alert("Ethereum object doesn't exist!"); setIsSwapping(true); const provider = new ethers.providers.Web3Provider(ethereum); const signer = provider.getSigner(); const parsedInputAmount = ethers.utils.parseUnits(inputAmount, 18); const swapContract = new ethers.Contract( swapContractAddress, SwapABI, signer ); if (inputToken === "CORE") { // If input token is CORE (native token swap) const txSwapNative = await swapContract.swapNativeForToken( tokenAddresses[outputToken], { value: parsedInputAmount } ); await txSwapNative.wait(); } else { // Approve tokens for swap contract const inputTokenAddress = tokenAddresses[inputToken]; const tokenContract = new ethers.Contract( inputTokenAddress, TokenABI, signer ); const txApprove = await tokenContract.approve( swapContractAddress, parsedInputAmount ); await txApprove.wait(); // Perform the swap const txSwap = await swapContract.swapTokens( inputTokenAddress, tokenAddresses[outputToken], parsedInputAmount ); await txSwap.wait(); } alert("Swap successful!"); } catch (error) { console.error("Swap failed:", error); alert("Swap failed, check the console for details."); } finally { setIsSwapping(false); setInputAmount(""); setOutputAmount("0"); } }; const switchTokens = () => { setInputToken(outputToken); setOutputToken(inputToken); setInputAmount(""); setOutputAmount("0"); }; return (
Core Logo

Swap Tokens

{currentAccount ? ( ) : ( )}
{currentAccount && (
handleInputChange(e.target.value)} placeholder="0.0" />

Exchange your tokens with a 0.5% fee

)}
); } export default App; ================================================ FILE: 09-Token-swap-Dapp/frontend/src/App.test.js ================================================ import { render, screen } from '@testing-library/react'; import App from './App'; test('renders learn react link', () => { render(); const linkElement = screen.getByText(/learn react/i); expect(linkElement).toBeInTheDocument(); }); ================================================ FILE: 09-Token-swap-Dapp/frontend/src/contracts/Swap.json ================================================ [ { "inputs": [ { "internalType": "uint32", "name": "_feePercent", "type": "uint32" } ], "stateMutability": "nonpayable", "type": "constructor" }, { "inputs": [ { "internalType": "address", "name": "owner", "type": "address" } ], "name": "OwnableInvalidOwner", "type": "error" }, { "inputs": [ { "internalType": "address", "name": "account", "type": "address" } ], "name": "OwnableUnauthorizedAccount", "type": "error" }, { "anonymous": false, "inputs": [ { "indexed": true, "internalType": "address", "name": "previousOwner", "type": "address" }, { "indexed": true, "internalType": "address", "name": "newOwner", "type": "address" } ], "name": "OwnershipTransferred", "type": "event" }, { "anonymous": false, "inputs": [ { "indexed": true, "internalType": "address", "name": "user", "type": "address" }, { "indexed": true, "internalType": "address", "name": "tokenA", "type": "address" }, { "indexed": true, "internalType": "address", "name": "tokenB", "type": "address" }, { "indexed": false, "internalType": "uint256", "name": "amountIn", "type": "uint256" }, { "indexed": false, "internalType": "uint256", "name": "amountOut", "type": "uint256" }, { "indexed": false, "internalType": "uint256", "name": "fee", "type": "uint256" } ], "name": "TokensSwapped", "type": "event" }, { "inputs": [], "name": "feeCollector", "outputs": [ { "internalType": "address", "name": "", "type": "address" } ], "stateMutability": "view", "type": "function" }, { "inputs": [], "name": "feePercent", "outputs": [ { "internalType": "uint32", "name": "", "type": "uint32" } ], "stateMutability": "view", "type": "function" }, { "inputs": [], "name": "owner", "outputs": [ { "internalType": "address", "name": "", "type": "address" } ], "stateMutability": "view", "type": "function" }, { "inputs": [], "name": "renounceOwnership", "outputs": [], "stateMutability": "nonpayable", "type": "function" }, { "inputs": [ { "internalType": "address", "name": "tokenB", "type": "address" } ], "name": "swapNativeForToken", "outputs": [], "stateMutability": "payable", "type": "function" }, { "inputs": [ { "internalType": "address", "name": "tokenA", "type": "address" }, { "internalType": "address", "name": "tokenB", "type": "address" }, { "internalType": "uint256", "name": "amountIn", "type": "uint256" } ], "name": "swapTokens", "outputs": [], "stateMutability": "nonpayable", "type": "function" }, { "inputs": [ { "internalType": "address", "name": "newOwner", "type": "address" } ], "name": "transferOwnership", "outputs": [], "stateMutability": "nonpayable", "type": "function" }, { "inputs": [ { "internalType": "uint32", "name": "newFeePercent", "type": "uint32" } ], "name": "updateFee", "outputs": [], "stateMutability": "nonpayable", "type": "function" }, { "inputs": [ { "internalType": "uint256", "name": "amount", "type": "uint256" } ], "name": "withdrawNative", "outputs": [], "stateMutability": "nonpayable", "type": "function" }, { "inputs": [ { "internalType": "address", "name": "token", "type": "address" }, { "internalType": "uint256", "name": "amount", "type": "uint256" } ], "name": "withdrawTokens", "outputs": [], "stateMutability": "nonpayable", "type": "function" } ] ================================================ FILE: 09-Token-swap-Dapp/frontend/src/contracts/Token.json ================================================ [ { "inputs": [ { "internalType": "string", "name": "_name", "type": "string" }, { "internalType": "string", "name": "_symbol", "type": "string" } ], "stateMutability": "nonpayable", "type": "constructor" }, { "inputs": [ { "internalType": "address", "name": "spender", "type": "address" }, { "internalType": "uint256", "name": "allowance", "type": "uint256" }, { "internalType": "uint256", "name": "needed", "type": "uint256" } ], "name": "ERC20InsufficientAllowance", "type": "error" }, { "inputs": [ { "internalType": "address", "name": "sender", "type": "address" }, { "internalType": "uint256", "name": "balance", "type": "uint256" }, { "internalType": "uint256", "name": "needed", "type": "uint256" } ], "name": "ERC20InsufficientBalance", "type": "error" }, { "inputs": [ { "internalType": "address", "name": "approver", "type": "address" } ], "name": "ERC20InvalidApprover", "type": "error" }, { "inputs": [ { "internalType": "address", "name": "receiver", "type": "address" } ], "name": "ERC20InvalidReceiver", "type": "error" }, { "inputs": [ { "internalType": "address", "name": "sender", "type": "address" } ], "name": "ERC20InvalidSender", "type": "error" }, { "inputs": [ { "internalType": "address", "name": "spender", "type": "address" } ], "name": "ERC20InvalidSpender", "type": "error" }, { "inputs": [ { "internalType": "address", "name": "owner", "type": "address" } ], "name": "OwnableInvalidOwner", "type": "error" }, { "inputs": [ { "internalType": "address", "name": "account", "type": "address" } ], "name": "OwnableUnauthorizedAccount", "type": "error" }, { "anonymous": false, "inputs": [ { "indexed": true, "internalType": "address", "name": "owner", "type": "address" }, { "indexed": true, "internalType": "address", "name": "spender", "type": "address" }, { "indexed": false, "internalType": "uint256", "name": "value", "type": "uint256" } ], "name": "Approval", "type": "event" }, { "anonymous": false, "inputs": [ { "indexed": true, "internalType": "address", "name": "previousOwner", "type": "address" }, { "indexed": true, "internalType": "address", "name": "newOwner", "type": "address" } ], "name": "OwnershipTransferred", "type": "event" }, { "anonymous": false, "inputs": [ { "indexed": true, "internalType": "address", "name": "from", "type": "address" }, { "indexed": true, "internalType": "address", "name": "to", "type": "address" }, { "indexed": false, "internalType": "uint256", "name": "value", "type": "uint256" } ], "name": "Transfer", "type": "event" }, { "inputs": [ { "internalType": "address", "name": "owner", "type": "address" }, { "internalType": "address", "name": "spender", "type": "address" } ], "name": "allowance", "outputs": [ { "internalType": "uint256", "name": "", "type": "uint256" } ], "stateMutability": "view", "type": "function" }, { "inputs": [ { "internalType": "address", "name": "spender", "type": "address" }, { "internalType": "uint256", "name": "value", "type": "uint256" } ], "name": "approve", "outputs": [ { "internalType": "bool", "name": "", "type": "bool" } ], "stateMutability": "nonpayable", "type": "function" }, { "inputs": [ { "internalType": "address", "name": "account", "type": "address" } ], "name": "balanceOf", "outputs": [ { "internalType": "uint256", "name": "", "type": "uint256" } ], "stateMutability": "view", "type": "function" }, { "inputs": [], "name": "decimals", "outputs": [ { "internalType": "uint8", "name": "", "type": "uint8" } ], "stateMutability": "view", "type": "function" }, { "inputs": [ { "internalType": "address", "name": "to", "type": "address" }, { "internalType": "uint256", "name": "amount", "type": "uint256" } ], "name": "mint", "outputs": [], "stateMutability": "nonpayable", "type": "function" }, { "inputs": [], "name": "name", "outputs": [ { "internalType": "string", "name": "", "type": "string" } ], "stateMutability": "view", "type": "function" }, { "inputs": [], "name": "owner", "outputs": [ { "internalType": "address", "name": "", "type": "address" } ], "stateMutability": "view", "type": "function" }, { "inputs": [], "name": "renounceOwnership", "outputs": [], "stateMutability": "nonpayable", "type": "function" }, { "inputs": [], "name": "symbol", "outputs": [ { "internalType": "string", "name": "", "type": "string" } ], "stateMutability": "view", "type": "function" }, { "inputs": [], "name": "totalSupply", "outputs": [ { "internalType": "uint256", "name": "", "type": "uint256" } ], "stateMutability": "view", "type": "function" }, { "inputs": [ { "internalType": "address", "name": "to", "type": "address" }, { "internalType": "uint256", "name": "value", "type": "uint256" } ], "name": "transfer", "outputs": [ { "internalType": "bool", "name": "", "type": "bool" } ], "stateMutability": "nonpayable", "type": "function" }, { "inputs": [ { "internalType": "address", "name": "from", "type": "address" }, { "internalType": "address", "name": "to", "type": "address" }, { "internalType": "uint256", "name": "value", "type": "uint256" } ], "name": "transferFrom", "outputs": [ { "internalType": "bool", "name": "", "type": "bool" } ], "stateMutability": "nonpayable", "type": "function" }, { "inputs": [ { "internalType": "address", "name": "newOwner", "type": "address" } ], "name": "transferOwnership", "outputs": [], "stateMutability": "nonpayable", "type": "function" } ] ================================================ FILE: 09-Token-swap-Dapp/frontend/src/index.css ================================================ body { margin: 0; font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'Roboto', 'Oxygen', 'Ubuntu', 'Cantarell', 'Fira Sans', 'Droid Sans', 'Helvetica Neue', sans-serif; -webkit-font-smoothing: antialiased; -moz-osx-font-smoothing: grayscale; } code { font-family: source-code-pro, Menlo, Monaco, Consolas, 'Courier New', monospace; } ================================================ FILE: 09-Token-swap-Dapp/frontend/src/index.js ================================================ import React from 'react'; import ReactDOM from 'react-dom/client'; import './index.css'; import App from './App'; import reportWebVitals from './reportWebVitals'; const root = ReactDOM.createRoot(document.getElementById('root')); root.render( ); // If you want to start measuring performance in your app, pass a function // to log results (for example: reportWebVitals(console.log)) // or send to an analytics endpoint. Learn more: https://bit.ly/CRA-vitals reportWebVitals(); ================================================ FILE: 09-Token-swap-Dapp/frontend/src/reportWebVitals.js ================================================ const reportWebVitals = onPerfEntry => { if (onPerfEntry && onPerfEntry instanceof Function) { import('web-vitals').then(({ getCLS, getFID, getFCP, getLCP, getTTFB }) => { getCLS(onPerfEntry); getFID(onPerfEntry); getFCP(onPerfEntry); getLCP(onPerfEntry); getTTFB(onPerfEntry); }); } }; export default reportWebVitals; ================================================ FILE: 09-Token-swap-Dapp/frontend/src/setupTests.js ================================================ // jest-dom adds custom jest matchers for asserting on DOM nodes. // allows you to do things like: // expect(element).toHaveTextContent(/react/i) // learn more: https://github.com/testing-library/jest-dom import '@testing-library/jest-dom'; ================================================ FILE: 09-Token-swap-Dapp/hardhat.config.js ================================================ require("@nomicfoundation/hardhat-toolbox"); require("dotenv").config(); /** @type import('hardhat/config').HardhatUserConfig */ const PRIVATE_KEY = process.env.PRIVATE_KEY; module.exports = { defaultNetwork: "hardhat", networks: { hardhat: {}, core_testnet: { url: "https://rpc.test2.btcs.network", accounts: [PRIVATE_KEY], chainId: 1114, }, }, solidity: { compilers: [ { version: "0.8.26", settings: { evmVersion: "shanghai", optimizer: { enabled: true, runs: 200, }, }, }, ], }, paths: { sources: "./contracts", cache: "./cache", artifacts: "./artifacts", }, mocha: { timeout: 60000, }, }; ================================================ FILE: 09-Token-swap-Dapp/package.json ================================================ { "name": "09-Token-swap-Dapp", "version": "1.0.0", "main": "index.js", "license": "MIT", "devDependencies": { "@nomicfoundation/hardhat-chai-matchers": "2.0.0", "@nomicfoundation/hardhat-ethers": "3.0.0", "@nomicfoundation/hardhat-ignition": "0.15.0", "@nomicfoundation/hardhat-ignition-ethers": "0.15.0", "@nomicfoundation/hardhat-network-helpers": "1.0.0", "@nomicfoundation/hardhat-toolbox": "5.0.0", "@nomicfoundation/hardhat-verify": "2.0.0", "@typechain/ethers-v6": "0.5.0", "@typechain/hardhat": "9.0.0", "chai": "4.2.0", "ethers": "6.4.0", "hardhat": "2.22.13", "hardhat-gas-reporter": "1.0.8", "solidity-coverage": "0.8.0", "typechain": "8.3.0" }, "dependencies": { "@openzeppelin/contracts": "5.1.0", "dotenv": "16.5.0" } } ================================================ FILE: 09-Token-swap-Dapp/scripts/deploy.js ================================================ const { ethers } = require("hardhat"); async function main() { const [deployer] = await ethers.getSigners(); console.log("Deploying contracts with the account:", deployer.address); const ERC20 = await ethers.getContractFactory("Token"); const usdt = await ERC20.deploy("usdt", "USDT"); const usdc = await ERC20.deploy("usdc", "USDC"); const fee = 10; const Swap = await ethers.getContractFactory("Swap"); const swap = await Swap.deploy(fee); console.log("Contracts deployed:"); console.log("Swap Contract:", await swap.getAddress()); console.log("usdt Token:", await usdt.getAddress()); console.log("usdc Token:", await usdc.getAddress()); const swapContractAddr = await swap.getAddress(); await usdt.approve(swapContractAddr, ethers.parseEther("100")); await usdt.transfer(swapContractAddr, ethers.parseEther("100")); await usdc.approve(swapContractAddr, ethers.parseEther("100")); await usdc.transfer(swapContractAddr, ethers.parseEther("100")); } main() .then(() => process.exit(0)) .catch((error) => { console.error(error); process.exit(1); }); ================================================ FILE: 09-Token-swap-Dapp/test/Swap.js ================================================ ================================================ FILE: 10-Advanced-Stake-Dapp/.gitignore ================================================ node_modules .env # Hardhat files /cache /artifacts # TypeChain files /typechain /typechain-types # solidity-coverage files /coverage /coverage.json # Hardhat Ignition default folder for deployments against a local node ignition/deployments/chain-31337 ================================================ FILE: 10-Advanced-Stake-Dapp/Frontend/.eslintrc.json ================================================ { "extends": ["next/core-web-vitals", "next/typescript"] } ================================================ FILE: 10-Advanced-Stake-Dapp/Frontend/.gitignore ================================================ # See https://help.github.com/articles/ignoring-files/ for more about ignoring files. # dependencies /node_modules /.pnp .pnp.* .yarn/* !.yarn/patches !.yarn/plugins !.yarn/releases !.yarn/versions # testing /coverage # next.js /.next/ /out/ # production /build # misc .DS_Store *.pem # debug npm-debug.log* yarn-debug.log* yarn-error.log* # env files (can opt-in for commiting if needed) .env* # vercel .vercel # typescript *.tsbuildinfo next-env.d.ts ================================================ FILE: 10-Advanced-Stake-Dapp/Frontend/README.md ================================================ This is a [Next.js](https://nextjs.org) project bootstrapped with [`create-next-app`](https://nextjs.org/docs/app/api-reference/cli/create-next-app). ## Getting Started First, run the development server: ```bash npm run dev # or yarn dev # or pnpm dev # or bun dev ``` Open [http://localhost:3000](http://localhost:3000) with your browser to see the result. You can start editing the page by modifying `app/page.tsx`. The page auto-updates as you edit the file. This project uses [`next/font`](https://nextjs.org/docs/app/building-your-application/optimizing/fonts) to automatically optimize and load [Geist](https://vercel.com/font), a new font family for Vercel. ## Learn More To learn more about Next.js, take a look at the following resources: - [Next.js Documentation](https://nextjs.org/docs) - learn about Next.js features and API. - [Learn Next.js](https://nextjs.org/learn) - an interactive Next.js tutorial. You can check out [the Next.js GitHub repository](https://github.com/vercel/next.js) - your feedback and contributions are welcome! ## Deploy on Vercel The easiest way to deploy your Next.js app is to use the [Vercel Platform](https://vercel.com/new?utm_medium=default-template&filter=next.js&utm_source=create-next-app&utm_campaign=create-next-app-readme) from the creators of Next.js. Check out our [Next.js deployment documentation](https://nextjs.org/docs/app/building-your-application/deploying) for more details. ================================================ FILE: 10-Advanced-Stake-Dapp/Frontend/app/globals.css ================================================ @tailwind base; @tailwind components; @tailwind utilities; @layer base { :root { /* Cream-based color palette for light mode */ --background: 48 33% 94%; /* Cream background #F5F2E3 */ --foreground: 240 10% 3.9%; --card: 48 30% 96%; /* Slightly lighter cream for cards #F8F6EA */ --card-foreground: 240 10% 3.9%; --popover: 48 30% 96%; --popover-foreground: 240 10% 3.9%; --primary: 240 5.9% 10%; --primary-foreground: 0 0% 98%; --secondary: 48 16% 90%; /* Muted cream for secondary elements #EBE7D9 */ --secondary-foreground: 240 5.9% 10%; --muted: 48 16% 90%; --muted-foreground: 240 3.8% 46.1%; --accent: 43 74% 49%; /* Gold accent #DAA520 */ --accent-foreground: 0 0% 98%; --destructive: 0 84.2% 60.2%; --destructive-foreground: 0 0% 98%; --border: 48 16% 85%; /* Cream border #E5E0CE */ --input: 48 16% 85%; --ring: 43 74% 49%; /* Gold ring */ --radius: 0.5rem; } .dark { --background: 240 10% 3.9%; /* Keep dark mode as is */ --foreground: 0 0% 98%; --card: 240 10% 3.9%; --card-foreground: 0 0% 98%; --popover: 240 10% 3.9%; --popover-foreground: 0 0% 98%; --primary: 0 0% 98%; --primary-foreground: 240 5.9% 10%; --secondary: 240 3.7% 15.9%; --secondary-foreground: 0 0% 98%; --muted: 240 3.7% 15.9%; --muted-foreground: 240 5% 64.9%; --accent: 43 74% 49%; /* Keep gold accent in dark mode */ --accent-foreground: 0 0% 98%; --destructive: 0 62.8% 30.6%; --destructive-foreground: 0 0% 98%; --border: 240 3.7% 15.9%; --input: 240 3.7% 15.9%; --ring: 240 4.9% 83.9%; } } @layer base { * { @apply border-border; } body { @apply bg-background text-foreground; } } ================================================ FILE: 10-Advanced-Stake-Dapp/Frontend/app/layout.tsx ================================================ import type React from "react" import type { Metadata } from "next" import { Inter } from "next/font/google" import "./globals.css" import { ThemeProvider } from "@/components/theme-provider" import { WalletProvider } from "@/components/wallet-provider" import { Toaster } from "@/components/ui/toaster" const inter = Inter({ subsets: ["latin"] }) export const metadata: Metadata = { title: "Staking dApp", description: "Stake your tokens and earn rewards", } export default function RootLayout({ children, }: Readonly<{ children: React.ReactNode }>) { return ( {children} ) } ================================================ FILE: 10-Advanced-Stake-Dapp/Frontend/app/page.tsx ================================================ import { StakingDashboard } from "@/components/staking-dashboard" export default function Home() { return (
) } ================================================ FILE: 10-Advanced-Stake-Dapp/Frontend/components/connect-wallet.tsx ================================================ "use client" import { useWallet } from "@/components/wallet-provider" import { Button } from "@/components/ui/button" import { Wallet, LogOut, Loader2 } from "lucide-react" export const ConnectWallet = () => { const { isConnected, isConnecting, connect, disconnect } = useWallet() return isConnected ? ( ) : ( ) } ================================================ FILE: 10-Advanced-Stake-Dapp/Frontend/components/global-overview.tsx ================================================ "use client" import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card" import { InfoTooltip } from "@/components/info-tooltip" import { TrendingUp, Users, Clock } from "lucide-react" export const GlobalOverview = () => { // In a real app, these would come from your contract or API const totalStaked = "1,245,678.45" const totalStakers = "3,721" const apy = "12.5" const lockupPeriod = "30 days" return (
Total Value Staked Platform-wide staking
{totalStaked} ETH
+5.2% from last week
Annual Percentage Yield Current reward rate
{apy}%
Rewards distributed daily
Platform Statistics Active stakers and lockup period
Total Stakers
{totalStakers}
Lockup Period
{lockupPeriod}
) } ================================================ FILE: 10-Advanced-Stake-Dapp/Frontend/components/header.tsx ================================================ "use client" import { useWallet } from "@/components/wallet-provider" import { ConnectWallet } from "@/components/connect-wallet" import { ModeToggle } from "@/components/mode-toggle" import { Coins } from "lucide-react" export const Header = () => { const { isConnected, address, balance } = useWallet() return (

Staking dApp

{isConnected && (
{address?.substring(0, 6)}...{address?.substring(38)} {Number.parseFloat(balance).toFixed(4)} ETH
)}
) } ================================================ FILE: 10-Advanced-Stake-Dapp/Frontend/components/info-tooltip.tsx ================================================ "use client" import { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger } from "@/components/ui/tooltip" import { Info } from "lucide-react" interface InfoTooltipProps { content: string } export const InfoTooltip = ({ content }: InfoTooltipProps) => { return ( {content} ) } ================================================ FILE: 10-Advanced-Stake-Dapp/Frontend/components/mode-toggle.tsx ================================================ "use client" import { Moon, Sun } from "lucide-react" import { useTheme } from "next-themes" import { Button } from "@/components/ui/button" import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuTrigger } from "@/components/ui/dropdown-menu" export function ModeToggle() { const { setTheme } = useTheme() return ( setTheme("light")}>Light setTheme("dark")}>Dark setTheme("system")}>System ) } ================================================ FILE: 10-Advanced-Stake-Dapp/Frontend/components/stake-form.tsx ================================================ "use client" import type React from "react" import { useState } from "react" import { useWallet } from "@/components/wallet-provider" import { Button } from "@/components/ui/button" import { Input } from "@/components/ui/input" import { Card, CardContent, CardDescription, CardFooter, CardHeader, CardTitle } from "@/components/ui/card" import { InfoTooltip } from "@/components/info-tooltip" import { useToast } from "@/hooks/use-toast" import { ArrowRight, Loader2 } from "lucide-react" import { useStakingContract } from "@/hooks/use-staking-contract" export const StakeForm = () => { const { balance } = useWallet() const { toast } = useToast() const [amount, setAmount] = useState("") const [isStaking, setIsStaking] = useState(false) const [error, setError] = useState("") const {stake} = useStakingContract(); const handleAmountChange = (e: React.ChangeEvent) => { const value = e.target.value // Allow only numbers and decimals if (value === "" || /^\d*\.?\d*$/.test(value)) { setAmount(value) // Validate amount if (value !== "") { const numValue = Number.parseFloat(value) const numBalance = Number.parseFloat(balance) if (numValue <= 0) { setError("Amount must be greater than 0") } else if (numValue > numBalance) { setError("Insufficient balance") } else { setError("") } } else { setError("") } } } const handleMaxClick = () => { // Set to 95% of balance to account for gas fees const maxAmount = (Number.parseFloat(balance) * 0.95).toFixed(6) setAmount(maxAmount) setError("") } const handleStake = async () => { if (!amount || Number.parseFloat(amount) <= 0) { setError("Please enter a valid amount") return } try { setIsStaking(true) // Simulate staking delay // await new Promise((resolve) => setTimeout(resolve, 2000)) await stake(amount); // In a real app, you would call your staking contract here toast({ title: "Tokens staked successfully", description: `You have staked ${amount} ETH`, }) setAmount("") } catch (error) { console.error("Staking error:", error) toast({ title: "Staking failed", description: "There was an error while staking your tokens. Please try again.", variant: "destructive", }) } finally { setIsStaking(false) } } return ( Stake Your Tokens Stake your ETH to earn rewards at 12.5% APY
Balance: {Number.parseFloat(balance).toFixed(4)} ETH
{error && (

{error}

)}

Staking Summary

You will stake: {amount || "0"} ETH
Lockup period: 30 days
Estimated APY: 12.5%
Estimated rewards (30 days): {amount ? ((Number.parseFloat(amount) * 0.125) / 12).toFixed(6) : "0"} ETH
) } ================================================ FILE: 10-Advanced-Stake-Dapp/Frontend/components/staker-directory.tsx ================================================ "use client" import { useState } from "react" import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card" import { Input } from "@/components/ui/input" import { Button } from "@/components/ui/button" import { InfoTooltip } from "@/components/info-tooltip" import { Search, ArrowUpDown, ExternalLink } from "lucide-react" // Mock data for stakers const MOCK_STAKERS = [ { address: "0x1234...5678", staked: "125.45", since: "30 days ago", rewards: "4.21" }, { address: "0xabcd...efgh", staked: "78.32", since: "25 days ago", rewards: "2.61" }, { address: "0x7890...1234", staked: "256.78", since: "45 days ago", rewards: "9.63" }, { address: "0xijkl...mnop", staked: "42.19", since: "15 days ago", rewards: "1.05" }, { address: "0x5678...9012", staked: "189.67", since: "60 days ago", rewards: "7.89" }, { address: "0xqrst...uvwx", staked: "63.41", since: "20 days ago", rewards: "1.58" }, { address: "0x3456...7890", staked: "95.23", since: "35 days ago", rewards: "3.47" }, { address: "0xyzab...cdef", staked: "112.87", since: "40 days ago", rewards: "4.71" }, ] type SortField = "staked" | "since" | "rewards" type SortDirection = "asc" | "desc" export const StakerDirectory = () => { const [searchTerm, setSearchTerm] = useState("") const [sortField, setSortField] = useState("staked") const [sortDirection, setSortDirection] = useState("desc") const handleSort = (field: SortField) => { if (sortField === field) { setSortDirection(sortDirection === "asc" ? "desc" : "asc") } else { setSortField(field) setSortDirection("desc") } } const filteredStakers = MOCK_STAKERS.filter((staker) => staker.address.toLowerCase().includes(searchTerm.toLowerCase()), ) const sortedStakers = [...filteredStakers].sort((a, b) => { let comparison = 0 if (sortField === "staked") { comparison = Number.parseFloat(a.staked) - Number.parseFloat(b.staked) } else if (sortField === "rewards") { comparison = Number.parseFloat(a.rewards) - Number.parseFloat(b.rewards) } else if (sortField === "since") { // Extract the number of days const daysA = Number.parseInt(a.since.split(" ")[0]) const daysB = Number.parseInt(b.since.split(" ")[0]) comparison = daysA - daysB } return sortDirection === "asc" ? comparison : -comparison }) return ( Staker Directory View all stakers and their contributions
setSearchTerm(e.target.value)} />
{sortedStakers.map((staker, index) => ( ))} {filteredStakers.length === 0 && ( )}
Address handleSort("staked")}>
Amount Staked
handleSort("since")}>
Staking Since
handleSort("rewards")}>
Rewards Earned
Actions
{staker.address} {staker.staked} ETH {staker.since} {staker.rewards} ETH
No stakers found matching your search.
) } ================================================ FILE: 10-Advanced-Stake-Dapp/Frontend/components/staking-dashboard.tsx ================================================ "use client" import { useState } from "react" import { Header } from "@/components/header" import { StakeForm } from "@/components/stake-form" import { UserDashboard } from "@/components/user-dashboard" import { GlobalOverview } from "@/components/global-overview" import { StakerDirectory } from "@/components/staker-directory" import { useWallet } from "@/components/wallet-provider" import { ConnectWallet } from "@/components/connect-wallet" export const StakingDashboard = () => { const { isConnected } = useWallet() const [activeTab, setActiveTab] = useState<"stake" | "dashboard" | "directory">("stake") return (
{!isConnected ? (

Connect Your Wallet to Start Staking

) : ( <>
{activeTab === "stake" && } {activeTab === "dashboard" && } {activeTab === "directory" && }
)}
) } ================================================ FILE: 10-Advanced-Stake-Dapp/Frontend/components/staking-form.tsx ================================================ "use client" import type React from "react" import { useState } from "react" import { useWallet } from "@/components/wallet-provider" import { Button } from "@/components/ui/button" import { Input } from "@/components/ui/input" import { Label } from "@/components/ui/label" import { Slider } from "@/components/ui/slider" import { useToast } from "@/components/ui/use-toast" import { InfoTooltip } from "@/components/info-tooltip" import { Loader2 } from "lucide-react" export function StakingForm() { const { address, balance } = useWallet() const [amount, setAmount] = useState("") const [isStaking, setIsStaking] = useState(false) const { toast } = useToast() const maxBalance = Number.parseFloat(balance || "0") const amountValue = Number.parseFloat(amount || "0") const isValidAmount = amountValue > 0 && amountValue <= maxBalance const handleSliderChange = (value: number[]) => { const percentage = value[0] const calculatedAmount = ((maxBalance * percentage) / 100).toFixed(6) setAmount(calculatedAmount) } const handleInputChange = (e: React.ChangeEvent) => { const value = e.target.value // Allow only numbers and decimals if (value === "" || /^\d*\.?\d*$/.test(value)) { setAmount(value) } } const handleMaxClick = () => { setAmount(maxBalance.toString()) } const handleStake = async () => { if (!isValidAmount) return setIsStaking(true) try { // In a real app, this would call the staking contract await new Promise((resolve) => setTimeout(resolve, 2000)) // Simulate transaction toast({ title: "Staking successful", description: `You have successfully staked ${amount} ETH`, }) setAmount("") } catch (error) { console.error("Staking error:", error) toast({ title: "Staking failed", description: "There was an error while staking your tokens. Please try again.", variant: "destructive", }) } finally { setIsStaking(false) } } return (
Balance: {maxBalance.toFixed(4)} ETH
{!isValidAmount && amount && (

{amountValue <= 0 ? "Amount must be greater than 0" : "Amount exceeds your balance"}

)}
0% 50% 100%
30 days
) } ================================================ FILE: 10-Advanced-Stake-Dapp/Frontend/components/theme-provider.tsx ================================================ "use client" import { ThemeProvider as NextThemesProvider } from "next-themes" import type { ThemeProviderProps } from "next-themes/dist/types" export function ThemeProvider({ children, ...props }: ThemeProviderProps) { return {children} } ================================================ FILE: 10-Advanced-Stake-Dapp/Frontend/components/theme-toggle.tsx ================================================ "use client" import { useTheme } from "next-themes" import { Button } from "@/components/ui/button" import { Moon, Sun } from "lucide-react" import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuTrigger } from "@/components/ui/dropdown-menu" import { useEffect, useState } from "react" export function ThemeToggle() { const { setTheme, theme } = useTheme() const [mounted, setMounted] = useState(false) // Prevent hydration mismatch useEffect(() => { setMounted(true) }, []) if (!mounted) { return ( ) } return ( setTheme("light")}> Light setTheme("dark")}> Dark setTheme("system")}> 💻 System ) } ================================================ FILE: 10-Advanced-Stake-Dapp/Frontend/components/ui/button.tsx ================================================ import * as React from "react" import { Slot } from "@radix-ui/react-slot" import { cva, type VariantProps } from "class-variance-authority" import { cn } from "@/lib/utils" const buttonVariants = cva( "inline-flex items-center justify-center gap-2 whitespace-nowrap rounded-md text-sm font-medium transition-colors focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring disabled:pointer-events-none disabled:opacity-50 [&_svg]:pointer-events-none [&_svg]:size-4 [&_svg]:shrink-0", { variants: { variant: { default: "bg-primary text-primary-foreground shadow hover:bg-primary/90", destructive: "bg-destructive text-destructive-foreground shadow-sm hover:bg-destructive/90", outline: "border border-input bg-background shadow-sm hover:bg-accent hover:text-accent-foreground", secondary: "bg-secondary text-secondary-foreground shadow-sm hover:bg-secondary/80", ghost: "hover:bg-accent hover:text-accent-foreground", link: "text-primary underline-offset-4 hover:underline", }, size: { default: "h-9 px-4 py-2", sm: "h-8 rounded-md px-3 text-xs", lg: "h-10 rounded-md px-8", icon: "h-9 w-9", }, }, defaultVariants: { variant: "default", size: "default", }, } ) export interface ButtonProps extends React.ButtonHTMLAttributes, VariantProps { asChild?: boolean } const Button = React.forwardRef( ({ className, variant, size, asChild = false, ...props }, ref) => { const Comp = asChild ? Slot : "button" return ( ) } ) Button.displayName = "Button" export { Button, buttonVariants } ================================================ FILE: 10-Advanced-Stake-Dapp/Frontend/components/ui/card.tsx ================================================ import * as React from "react" import { cn } from "@/lib/utils" const Card = React.forwardRef< HTMLDivElement, React.HTMLAttributes >(({ className, ...props }, ref) => (
)) Card.displayName = "Card" const CardHeader = React.forwardRef< HTMLDivElement, React.HTMLAttributes >(({ className, ...props }, ref) => (
)) CardHeader.displayName = "CardHeader" const CardTitle = React.forwardRef< HTMLDivElement, React.HTMLAttributes >(({ className, ...props }, ref) => (
)) CardTitle.displayName = "CardTitle" const CardDescription = React.forwardRef< HTMLDivElement, React.HTMLAttributes >(({ className, ...props }, ref) => (
)) CardDescription.displayName = "CardDescription" const CardContent = React.forwardRef< HTMLDivElement, React.HTMLAttributes >(({ className, ...props }, ref) => (
)) CardContent.displayName = "CardContent" const CardFooter = React.forwardRef< HTMLDivElement, React.HTMLAttributes >(({ className, ...props }, ref) => (
)) CardFooter.displayName = "CardFooter" export { Card, CardHeader, CardFooter, CardTitle, CardDescription, CardContent } ================================================ FILE: 10-Advanced-Stake-Dapp/Frontend/components/ui/dropdown-menu.tsx ================================================ "use client" import * as React from "react" import * as DropdownMenuPrimitive from "@radix-ui/react-dropdown-menu" import { Check, ChevronRight, Circle } from "lucide-react" import { cn } from "@/lib/utils" const DropdownMenu = DropdownMenuPrimitive.Root const DropdownMenuTrigger = DropdownMenuPrimitive.Trigger const DropdownMenuGroup = DropdownMenuPrimitive.Group const DropdownMenuPortal = DropdownMenuPrimitive.Portal const DropdownMenuSub = DropdownMenuPrimitive.Sub const DropdownMenuRadioGroup = DropdownMenuPrimitive.RadioGroup const DropdownMenuSubTrigger = React.forwardRef< React.ElementRef, React.ComponentPropsWithoutRef & { inset?: boolean } >(({ className, inset, children, ...props }, ref) => ( {children} )) DropdownMenuSubTrigger.displayName = DropdownMenuPrimitive.SubTrigger.displayName const DropdownMenuSubContent = React.forwardRef< React.ElementRef, React.ComponentPropsWithoutRef >(({ className, ...props }, ref) => ( )) DropdownMenuSubContent.displayName = DropdownMenuPrimitive.SubContent.displayName const DropdownMenuContent = React.forwardRef< React.ElementRef, React.ComponentPropsWithoutRef >(({ className, sideOffset = 4, ...props }, ref) => ( )) DropdownMenuContent.displayName = DropdownMenuPrimitive.Content.displayName const DropdownMenuItem = React.forwardRef< React.ElementRef, React.ComponentPropsWithoutRef & { inset?: boolean } >(({ className, inset, ...props }, ref) => ( svg]:size-4 [&>svg]:shrink-0", inset && "pl-8", className )} {...props} /> )) DropdownMenuItem.displayName = DropdownMenuPrimitive.Item.displayName const DropdownMenuCheckboxItem = React.forwardRef< React.ElementRef, React.ComponentPropsWithoutRef >(({ className, children, checked, ...props }, ref) => ( {children} )) DropdownMenuCheckboxItem.displayName = DropdownMenuPrimitive.CheckboxItem.displayName const DropdownMenuRadioItem = React.forwardRef< React.ElementRef, React.ComponentPropsWithoutRef >(({ className, children, ...props }, ref) => ( {children} )) DropdownMenuRadioItem.displayName = DropdownMenuPrimitive.RadioItem.displayName const DropdownMenuLabel = React.forwardRef< React.ElementRef, React.ComponentPropsWithoutRef & { inset?: boolean } >(({ className, inset, ...props }, ref) => ( )) DropdownMenuLabel.displayName = DropdownMenuPrimitive.Label.displayName const DropdownMenuSeparator = React.forwardRef< React.ElementRef, React.ComponentPropsWithoutRef >(({ className, ...props }, ref) => ( )) DropdownMenuSeparator.displayName = DropdownMenuPrimitive.Separator.displayName const DropdownMenuShortcut = ({ className, ...props }: React.HTMLAttributes) => { return ( ) } DropdownMenuShortcut.displayName = "DropdownMenuShortcut" export { DropdownMenu, DropdownMenuTrigger, DropdownMenuContent, DropdownMenuItem, DropdownMenuCheckboxItem, DropdownMenuRadioItem, DropdownMenuLabel, DropdownMenuSeparator, DropdownMenuShortcut, DropdownMenuGroup, DropdownMenuPortal, DropdownMenuSub, DropdownMenuSubContent, DropdownMenuSubTrigger, DropdownMenuRadioGroup, } ================================================ FILE: 10-Advanced-Stake-Dapp/Frontend/components/ui/input.tsx ================================================ import * as React from "react" import { cn } from "@/lib/utils" const Input = React.forwardRef>( ({ className, type, ...props }, ref) => { return ( ) } ) Input.displayName = "Input" export { Input } ================================================ FILE: 10-Advanced-Stake-Dapp/Frontend/components/ui/label.tsx ================================================ "use client" import * as React from "react" import * as LabelPrimitive from "@radix-ui/react-label" import { cva, type VariantProps } from "class-variance-authority" import { cn } from "@/lib/utils" const labelVariants = cva( "text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70" ) const Label = React.forwardRef< React.ElementRef, React.ComponentPropsWithoutRef & VariantProps >(({ className, ...props }, ref) => ( )) Label.displayName = LabelPrimitive.Root.displayName export { Label } ================================================ FILE: 10-Advanced-Stake-Dapp/Frontend/components/ui/progress.tsx ================================================ "use client" import * as React from "react" import * as ProgressPrimitive from "@radix-ui/react-progress" import { cn } from "@/lib/utils" const Progress = React.forwardRef< React.ElementRef, React.ComponentPropsWithoutRef >(({ className, value, ...props }, ref) => ( )) Progress.displayName = ProgressPrimitive.Root.displayName export { Progress } ================================================ FILE: 10-Advanced-Stake-Dapp/Frontend/components/ui/slider.tsx ================================================ "use client" import * as React from "react" import * as SliderPrimitive from "@radix-ui/react-slider" import { cn } from "@/lib/utils" const Slider = React.forwardRef< React.ElementRef, React.ComponentPropsWithoutRef >(({ className, ...props }, ref) => ( )) Slider.displayName = SliderPrimitive.Root.displayName export { Slider } ================================================ FILE: 10-Advanced-Stake-Dapp/Frontend/components/ui/tabs.tsx ================================================ "use client" import * as React from "react" import * as TabsPrimitive from "@radix-ui/react-tabs" import { cn } from "@/lib/utils" const Tabs = TabsPrimitive.Root const TabsList = React.forwardRef< React.ElementRef, React.ComponentPropsWithoutRef >(({ className, ...props }, ref) => ( )) TabsList.displayName = TabsPrimitive.List.displayName const TabsTrigger = React.forwardRef< React.ElementRef, React.ComponentPropsWithoutRef >(({ className, ...props }, ref) => ( )) TabsTrigger.displayName = TabsPrimitive.Trigger.displayName const TabsContent = React.forwardRef< React.ElementRef, React.ComponentPropsWithoutRef >(({ className, ...props }, ref) => ( )) TabsContent.displayName = TabsPrimitive.Content.displayName export { Tabs, TabsList, TabsTrigger, TabsContent } ================================================ FILE: 10-Advanced-Stake-Dapp/Frontend/components/ui/toast.tsx ================================================ "use client" import * as React from "react" import * as ToastPrimitives from "@radix-ui/react-toast" import { cva, type VariantProps } from "class-variance-authority" import { X } from "lucide-react" import { cn } from "@/lib/utils" const ToastProvider = ToastPrimitives.Provider const ToastViewport = React.forwardRef< React.ElementRef, React.ComponentPropsWithoutRef >(({ className, ...props }, ref) => ( )) ToastViewport.displayName = ToastPrimitives.Viewport.displayName const toastVariants = cva( "group pointer-events-auto relative flex w-full items-center justify-between space-x-2 overflow-hidden rounded-md border p-4 pr-6 shadow-lg transition-all data-[swipe=cancel]:translate-x-0 data-[swipe=end]:translate-x-[var(--radix-toast-swipe-end-x)] data-[swipe=move]:translate-x-[var(--radix-toast-swipe-move-x)] data-[swipe=move]:transition-none data-[state=open]:animate-in data-[state=closed]:animate-out data-[swipe=end]:animate-out data-[state=closed]:fade-out-80 data-[state=closed]:slide-out-to-right-full data-[state=open]:slide-in-from-top-full data-[state=open]:sm:slide-in-from-bottom-full", { variants: { variant: { default: "border bg-background text-foreground", destructive: "destructive group border-destructive bg-destructive text-destructive-foreground", }, }, defaultVariants: { variant: "default", }, } ) const Toast = React.forwardRef< React.ElementRef, React.ComponentPropsWithoutRef & VariantProps >(({ className, variant, ...props }, ref) => { return ( ) }) Toast.displayName = ToastPrimitives.Root.displayName const ToastAction = React.forwardRef< React.ElementRef, React.ComponentPropsWithoutRef >(({ className, ...props }, ref) => ( )) ToastAction.displayName = ToastPrimitives.Action.displayName const ToastClose = React.forwardRef< React.ElementRef, React.ComponentPropsWithoutRef >(({ className, ...props }, ref) => ( )) ToastClose.displayName = ToastPrimitives.Close.displayName const ToastTitle = React.forwardRef< React.ElementRef, React.ComponentPropsWithoutRef >(({ className, ...props }, ref) => ( )) ToastTitle.displayName = ToastPrimitives.Title.displayName const ToastDescription = React.forwardRef< React.ElementRef, React.ComponentPropsWithoutRef >(({ className, ...props }, ref) => ( )) ToastDescription.displayName = ToastPrimitives.Description.displayName type ToastProps = React.ComponentPropsWithoutRef type ToastActionElement = React.ReactElement export { type ToastProps, type ToastActionElement, ToastProvider, ToastViewport, Toast, ToastTitle, ToastDescription, ToastClose, ToastAction, } ================================================ FILE: 10-Advanced-Stake-Dapp/Frontend/components/ui/toaster.tsx ================================================ "use client" import { useToast } from "@/hooks/use-toast" import { Toast, ToastClose, ToastDescription, ToastProvider, ToastTitle, ToastViewport, } from "@/components/ui/toast" export function Toaster() { const { toasts } = useToast() return ( {toasts.map(function ({ id, title, description, action, ...props }) { return (
{title && {title}} {description && ( {description} )}
{action}
) })}
) } ================================================ FILE: 10-Advanced-Stake-Dapp/Frontend/components/ui/tooltip.tsx ================================================ "use client" import * as React from "react" import * as TooltipPrimitive from "@radix-ui/react-tooltip" import { cn } from "@/lib/utils" const TooltipProvider = TooltipPrimitive.Provider const Tooltip = TooltipPrimitive.Root const TooltipTrigger = TooltipPrimitive.Trigger const TooltipContent = React.forwardRef< React.ElementRef, React.ComponentPropsWithoutRef >(({ className, sideOffset = 4, ...props }, ref) => ( )) TooltipContent.displayName = TooltipPrimitive.Content.displayName export { Tooltip, TooltipTrigger, TooltipContent, TooltipProvider } ================================================ FILE: 10-Advanced-Stake-Dapp/Frontend/components/user-dashboard.tsx ================================================ "use client" import type React from "react" import { useState } from "react" import { Card, CardContent, CardDescription, CardFooter, CardHeader, CardTitle } from "@/components/ui/card" import { Button } from "@/components/ui/button" import { Input } from "@/components/ui/input" import { InfoTooltip } from "@/components/info-tooltip" import { useToast } from "@/hooks/use-toast" import { Loader2, TrendingUp, Clock, Award, ArrowDownToLine } from "lucide-react" import { Progress } from "@/components/ui/progress" import { useStakingContract } from "@/hooks/use-staking-contract" export const UserDashboard = () => { const { toast } = useToast() const [isWithdrawing, setIsWithdrawing] = useState(false) const [isClaiming, setIsClaiming] = useState(false) const [withdrawAmount, setWithdrawAmount] = useState("") const [withdrawError, setWithdrawError] = useState("") const {stakedBalance, rewards, withdraw, claimRewards} = useStakingContract() // In a real app, these would come from your contract // const stakedBalance = "42.5" // const rewards = "1.32" const stakingStartDate = "2023-12-15" const lockupEndDate = "2024-01-14" const daysRemaining = 5 const percentComplete = ((30 - daysRemaining) / 30) * 100 const handleWithdrawAmountChange = (e: React.ChangeEvent) => { const value = e.target.value // Allow only numbers and decimals if (value === "" || /^\d*\.?\d*$/.test(value)) { setWithdrawAmount(value) // Validate amount if (value !== "") { const numValue = Number.parseFloat(value) const numStaked = Number.parseFloat(stakedBalance) if (numValue <= 0) { setWithdrawError("Amount must be greater than 0") } else if (numValue > numStaked) { setWithdrawError("Cannot withdraw more than staked amount") } else { setWithdrawError("") } } else { setWithdrawError("") } } } const handleMaxWithdraw = () => { setWithdrawAmount(stakedBalance) setWithdrawError("") } const handleWithdraw = async () => { if (!withdrawAmount || Number.parseFloat(withdrawAmount) <= 0) { setWithdrawError("Please enter a valid amount") return } try { setIsWithdrawing(true) const withdrawValue = Number.parseFloat(withdrawAmount) // Check if early withdrawal (before lockup period ends) const isEarlyWithdrawal = daysRemaining > 0 if (isEarlyWithdrawal) { // Calculate penalty (10% for early withdrawal) const penalty = withdrawValue * 0.1 const amountAfterPenalty = withdrawValue - penalty // Simulate withdrawal delay // await new Promise((resolve) => setTimeout(resolve, 2000)) await withdraw(withdrawAmount) // In a real app, you would call your staking contract here toast({ title: "Early withdrawal processed", description: `You have withdrawn ${amountAfterPenalty.toFixed(2)} ETH (10% penalty applied)`, }) } else { toast({ title: "Withdrawal successful", description: `You have withdrawn ${withdrawAmount} ETH`, }) } window.dispatchEvent(new CustomEvent("withdraw", { detail: { withdrawAmount}, })); // Reset the withdrawal amount after successful withdrawal setWithdrawAmount("") } catch (error) { console.error("Withdrawal error:", error) toast({ title: "Withdrawal failed", description: "There was an error while withdrawing your tokens. Please try again.", variant: "destructive", }) } finally { setIsWithdrawing(false) } } const handleClaimRewards = async () => { try { setIsClaiming(true) // Simulate claiming delay // await new Promise((resolve) => setTimeout(resolve, 2000)) // In a real app, you would call your staking contract here claimRewards() toast({ title: "Rewards claimed successfully", description: `You have claimed ${rewards} ETH in rewards`, }) } catch (error) { console.error("Claiming error:", error) toast({ title: "Claiming failed", description: "There was an error while claiming your rewards. Please try again.", variant: "destructive", }) } finally { setIsClaiming(false) } } // Calculate the amount after penalty (if applicable) const calculateAmountAfterPenalty = () => { if (!withdrawAmount || Number.parseFloat(withdrawAmount) <= 0) return "0" const withdrawValue = Number.parseFloat(withdrawAmount) const isEarlyWithdrawal = daysRemaining > 0 if (isEarlyWithdrawal) { const penalty = withdrawValue * 0.1 return (withdrawValue - penalty).toFixed(6) } return withdrawValue.toFixed(6) } return (
My Staked Tokens Your active stake
{stakedBalance} ETH
Lockup Period {daysRemaining} days remaining
Staked on

{stakingStartDate}

Available on

{lockupEndDate}

Available: {stakedBalance} ETH
{withdrawError && (

{withdrawError}

)} {daysRemaining > 0 && withdrawAmount && !withdrawError && (
Withdrawal amount: {withdrawAmount} ETH
Early withdrawal penalty (10%): {(Number.parseFloat(withdrawAmount) * 0.1).toFixed(6)} ETH
You will receive: {calculateAmountAfterPenalty()} ETH
)}
{daysRemaining > 0 && (
Lockup period not complete. Early withdrawal will incur a 10% penalty.
)}
My Rewards Accumulated earnings
{rewards} ETH
+0.05 ETH earned today

Reward Statistics

Daily rate

0.05 ETH

Monthly estimate

1.5 ETH

APY

12.5%

Next reward

In 24 hours

) } ================================================ FILE: 10-Advanced-Stake-Dapp/Frontend/components/user-list.tsx ================================================ "use client" import type React from "react" import { useState, useEffect } from "react" import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card" import { Input } from "@/components/ui/input" import { Button } from "@/components/ui/button" import { Search, ArrowUpDown } from "lucide-react" type Staker = { address: string amount: number since: string } export function UserList() { const [stakers, setStakers] = useState([]) const [searchQuery, setSearchQuery] = useState("") const [sortOrder, setSortOrder] = useState<"asc" | "desc">("desc") // In a real app, this would fetch data from the blockchain useEffect(() => { // Mock data const mockStakers: Staker[] = [ { address: "0x1234...5678", amount: 245.5, since: "2 months ago" }, { address: "0xabcd...efgh", amount: 120.3, since: "1 month ago" }, { address: "0x9876...5432", amount: 89.7, since: "3 weeks ago" }, { address: "0xijkl...mnop", amount: 56.2, since: "2 weeks ago" }, { address: "0x2468...1357", amount: 34.8, since: "1 week ago" }, { address: "0xqrst...uvwx", amount: 23.5, since: "3 days ago" }, { address: "0x1357...2468", amount: 12.1, since: "1 day ago" }, ] setStakers(mockStakers) }, []) const handleSearch = (e: React.ChangeEvent) => { setSearchQuery(e.target.value) } const toggleSortOrder = () => { setSortOrder(sortOrder === "asc" ? "desc" : "asc") } const filteredStakers = stakers.filter((staker) => staker.address.toLowerCase().includes(searchQuery.toLowerCase())) const sortedStakers = [...filteredStakers].sort((a, b) => { return sortOrder === "asc" ? a.amount - b.amount : b.amount - a.amount }) return ( Top Stakers Users with the highest stakes
{sortedStakers.length > 0 ? ( sortedStakers.map((staker, index) => (
{staker.address} {staker.since}
{staker.amount.toFixed(2)} ETH
)) ) : (

No stakers found

)}
) } ================================================ FILE: 10-Advanced-Stake-Dapp/Frontend/components/user-stats.tsx ================================================ "use client" import { useEffect, useState } from "react" import { Progress } from "@/components/ui/progress" import { InfoTooltip } from "@/components/info-tooltip" export function UserStats() { // In a real app, these would come from the staking contract const [stakedAmount, setStakedAmount] = useState(1.5) const [rewards, setRewards] = useState(0.125) const [timeRemaining, setTimeRemaining] = useState(18) // days const totalLockupPeriod = 30 // days // Simulate rewards accruing in real-time useEffect(() => { const interval = setInterval(() => { setRewards((prev) => { const increase = 0.000001 * Math.random() return Number.parseFloat((prev + increase).toFixed(6)) }) }, 5000) return () => clearInterval(interval) }, []) const lockupProgress = Math.min(100, ((totalLockupPeriod - timeRemaining) / totalLockupPeriod) * 100) return (
Your Stake {stakedAmount.toFixed(4)} ETH
Earned Rewards {rewards.toFixed(6)} ETH
Lockup Period {timeRemaining} days left
0 days {totalLockupPeriod} days
Estimated APY: 12.5%
Projected Annual Earnings: {(stakedAmount * 0.125).toFixed(4)} ETH
) } ================================================ FILE: 10-Advanced-Stake-Dapp/Frontend/components/wallet-connect.tsx ================================================ "use client" import { useState } from "react" import { useWallet } from "@/components/wallet-provider" import { Button } from "@/components/ui/button" import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuTrigger } from "@/components/ui/dropdown-menu" import { Loader2, Wallet, LogOut, Copy, ExternalLink } from "lucide-react" import { useToast } from "@/components/ui/use-toast" export function WalletConnect() { const { address, balance, chainId, isConnected, isConnecting, connectWallet, disconnectWallet } = useWallet() const [isDropdownOpen, setIsDropdownOpen] = useState(false) const { toast } = useToast() const truncateAddress = (address: string) => { return `${address.slice(0, 6)}...${address.slice(-4)}` } const copyToClipboard = (text: string) => { navigator.clipboard.writeText(text) toast({ title: "Address copied", description: "Wallet address copied to clipboard", }) } const openExplorer = (address: string) => { // This would need to be updated based on the actual chain const explorerUrl = chainId === 1 ? `https://etherscan.io/address/${address}` : `https://testnet.etherscan.io/address/${address}` window.open(explorerUrl, "_blank") } if (isConnected && address) { return (

Connected Wallet

{address}

Balance: {Number.parseFloat(balance || "0").toFixed(4)} ETH

Network:{" "} {chainId === 1 ? "Ethereum" : chainId === 5 ? "Goerli" : `Chain ID: ${chainId}`}

copyToClipboard(address)}> Copy Address openExplorer(address)}> View on Explorer Disconnect
) } return ( connectWallet("metamask")}> MetaMask MetaMask connectWallet("walletconnect")}> WalletConnect WalletConnect ) } ================================================ FILE: 10-Advanced-Stake-Dapp/Frontend/components/wallet-provider.tsx ================================================ "use client" import type React from "react" import { createContext, useContext, useState, useEffect } from "react" import { ethers } from "ethers" import { useToast } from "@/hooks/use-toast" type WalletContextType = { address: string | null balance: string isConnected: boolean isConnecting: boolean connect: () => Promise disconnect: () => void } const WalletContext = createContext({ address: null, balance: "0", isConnected: false, isConnecting: false, connect: async () => {}, disconnect: () => {}, }) export const useWallet = () => useContext(WalletContext) export const WalletProvider = ({ children }: { children: React.ReactNode }) => { const [address, setAddress] = useState(null) const [balance, setBalance] = useState("0") const [isConnected, setIsConnected] = useState(false) const [isConnecting, setIsConnecting] = useState(false) const { toast } = useToast() const connect = async () => { if (typeof window.ethereum === "undefined") { toast({ title: "MetaMask not found", description: "Please install MetaMask to use this dApp", variant: "destructive", }) return } try { setIsConnecting(true) const provider = new ethers.BrowserProvider(window.ethereum) const accounts = await provider.send("eth_requestAccounts", []) if (accounts.length > 0) { const address = accounts[0] setAddress(address) setIsConnected(true) // Get balance const balance = await provider.getBalance(address) setBalance(ethers.formatEther(balance)) toast({ title: "Wallet connected", description: `Connected to ${address.substring(0, 6)}...${address.substring(38)}`, }) } } catch (error) { console.error("Error connecting wallet:", error) toast({ title: "Connection failed", description: "Failed to connect wallet. Please try again.", variant: "destructive", }) } finally { setIsConnecting(false) } } const disconnect = () => { setAddress(null) setBalance("0") setIsConnected(false) toast({ title: "Wallet disconnected", description: "Your wallet has been disconnected", }) } // Listen for account changes useEffect(() => { if (typeof window.ethereum !== "undefined") { const handleAccountsChanged = (accounts: string[]) => { if (accounts.length === 0) { // User disconnected their wallet disconnect() } else if (accounts[0] !== address) { // User switched accounts setAddress(accounts[0]) toast({ title: "Account changed", description: `Switched to ${accounts[0].substring(0, 6)}...${accounts[0].substring(38)}`, }) } } window.ethereum.on("accountsChanged", handleAccountsChanged) return () => { window.ethereum.removeListener("accountsChanged", handleAccountsChanged) } } }, [address]) return ( {children} ) } ================================================ FILE: 10-Advanced-Stake-Dapp/Frontend/components/withdraw-form.tsx ================================================ "use client" import type React from "react" import { useState } from "react" import { Button } from "@/components/ui/button" import { Input } from "@/components/ui/input" import { Label } from "@/components/ui/label" import { Slider } from "@/components/ui/slider" import { useToast } from "@/components/ui/use-toast" import { InfoTooltip } from "@/components/info-tooltip" import { Loader2 } from "lucide-react" export function WithdrawForm() { const [amount, setAmount] = useState("") const [isWithdrawing, setIsWithdrawing] = useState(false) const { toast } = useToast() // In a real app, this would come from the staking contract const stakedBalance = 1.5 const amountValue = Number.parseFloat(amount || "0") const isValidAmount = amountValue > 0 && amountValue <= stakedBalance const handleSliderChange = (value: number[]) => { const percentage = value[0] const calculatedAmount = ((stakedBalance * percentage) / 100).toFixed(6) setAmount(calculatedAmount) } const handleInputChange = (e: React.ChangeEvent) => { const value = e.target.value // Allow only numbers and decimals if (value === "" || /^\d*\.?\d*$/.test(value)) { setAmount(value) } } const handleMaxClick = () => { setAmount(stakedBalance.toString()) } const handleWithdraw = async () => { if (!isValidAmount) return setIsWithdrawing(true) try { // In a real app, this would call the staking contract await new Promise((resolve) => setTimeout(resolve, 2000)) // Simulate transaction toast({ title: "Withdrawal successful", description: `You have successfully withdrawn ${amount} ETH`, }) setAmount("") } catch (error) { console.error("Withdrawal error:", error) toast({ title: "Withdrawal failed", description: "There was an error while withdrawing your tokens. Please try again.", variant: "destructive", }) } finally { setIsWithdrawing(false) } } return (
Staked: {stakedBalance.toFixed(4)} ETH
{!isValidAmount && amount && (

{amountValue <= 0 ? "Amount must be greater than 0" : "Amount exceeds your staked balance"}

)}
0% 50% 100%
) } ================================================ FILE: 10-Advanced-Stake-Dapp/Frontend/components.json ================================================ { "$schema": "https://ui.shadcn.com/schema.json", "style": "new-york", "rsc": true, "tsx": true, "tailwind": { "config": "tailwind.config.ts", "css": "app/globals.css", "baseColor": "zinc", "cssVariables": true, "prefix": "" }, "aliases": { "components": "@/components", "utils": "@/lib/utils", "ui": "@/components/ui", "lib": "@/lib", "hooks": "@/hooks" }, "iconLibrary": "lucide" } ================================================ FILE: 10-Advanced-Stake-Dapp/Frontend/constants/constansts.tsx ================================================ const STAKING_CONTRACT_ADDRESS = "0x652Ca0319df1b8ebe9220B4894DC38Da5C9575d3" const STAKING_CONTRACT_ABI = [ { "inputs": [ { "internalType": "address", "name": "_rewardToken", "type": "address" }, { "internalType": "uint256", "name": "_rewardRatePerSecond", "type": "uint256" } ], "stateMutability": "nonpayable", "type": "constructor" }, { "anonymous": false, "inputs": [ { "indexed": true, "internalType": "address", "name": "user", "type": "address" }, { "indexed": false, "internalType": "uint256", "name": "reward", "type": "uint256" } ], "name": "RewardPaid", "type": "event" }, { "anonymous": false, "inputs": [ { "indexed": true, "internalType": "address", "name": "user", "type": "address" }, { "indexed": false, "internalType": "uint256", "name": "amount", "type": "uint256" } ], "name": "Staked", "type": "event" }, { "anonymous": false, "inputs": [ { "indexed": true, "internalType": "address", "name": "user", "type": "address" }, { "indexed": false, "internalType": "uint256", "name": "amount", "type": "uint256" } ], "name": "Withdrawn", "type": "event" }, { "inputs": [ { "internalType": "address", "name": "account", "type": "address" } ], "name": "balanceOf", "outputs": [ { "internalType": "uint256", "name": "", "type": "uint256" } ], "stateMutability": "view", "type": "function" }, { "inputs": [ { "internalType": "address", "name": "account", "type": "address" } ], "name": "currentEarned", "outputs": [ { "internalType": "uint256", "name": "", "type": "uint256" } ], "stateMutability": "view", "type": "function" }, { "inputs": [], "name": "dailyRewardRate", "outputs": [ { "internalType": "uint256", "name": "", "type": "uint256" } ], "stateMutability": "view", "type": "function" }, { "inputs": [ { "internalType": "uint256", "name": "stakeAmount", "type": "uint256" } ], "name": "estimateDailyEarningForStake", "outputs": [ { "internalType": "uint256", "name": "", "type": "uint256" } ], "stateMutability": "view", "type": "function" }, { "inputs": [], "name": "exit", "outputs": [], "stateMutability": "nonpayable", "type": "function" }, { "inputs": [], "name": "getReward", "outputs": [], "stateMutability": "nonpayable", "type": "function" }, { "inputs": [], "name": "lastUpdateTime", "outputs": [ { "internalType": "uint256", "name": "", "type": "uint256" } ], "stateMutability": "view", "type": "function" }, { "inputs": [], "name": "rewardPerToken", "outputs": [ { "internalType": "uint256", "name": "", "type": "uint256" } ], "stateMutability": "view", "type": "function" }, { "inputs": [], "name": "rewardPerTokenStored", "outputs": [ { "internalType": "uint256", "name": "", "type": "uint256" } ], "stateMutability": "view", "type": "function" }, { "inputs": [], "name": "rewardRatePerSecond", "outputs": [ { "internalType": "uint256", "name": "", "type": "uint256" } ], "stateMutability": "view", "type": "function" }, { "inputs": [], "name": "rewardToken", "outputs": [ { "internalType": "contract IERC20", "name": "", "type": "address" } ], "stateMutability": "view", "type": "function" }, { "inputs": [ { "internalType": "address", "name": "", "type": "address" } ], "name": "rewards", "outputs": [ { "internalType": "uint256", "name": "", "type": "uint256" } ], "stateMutability": "view", "type": "function" }, { "inputs": [], "name": "stake", "outputs": [], "stateMutability": "payable", "type": "function" }, { "inputs": [], "name": "totalStaked", "outputs": [ { "internalType": "uint256", "name": "", "type": "uint256" } ], "stateMutability": "view", "type": "function" }, { "inputs": [ { "internalType": "address", "name": "", "type": "address" } ], "name": "userRewardPerTokenPaid", "outputs": [ { "internalType": "uint256", "name": "", "type": "uint256" } ], "stateMutability": "view", "type": "function" }, { "inputs": [ { "internalType": "uint256", "name": "amount", "type": "uint256" } ], "name": "withdraw", "outputs": [], "stateMutability": "nonpayable", "type": "function" }, { "stateMutability": "payable", "type": "receive" } ] export {STAKING_CONTRACT_ADDRESS, STAKING_CONTRACT_ABI} ================================================ FILE: 10-Advanced-Stake-Dapp/Frontend/hooks/use-staking-contract.tsx ================================================ "use client" import { useState, useEffect } from "react" import { ethers } from "ethers" import { useWallet } from "@/components/wallet-provider" import { STAKING_CONTRACT_ABI, STAKING_CONTRACT_ADDRESS } from "@/constants/constansts" export const useStakingContract = () => { const { address, isConnected } = useWallet() const [contract, setContract] = useState(null) const [stakedBalance, setStakedBalance] = useState("0") const [rewards, setRewards] = useState("0") const [isLoading, setIsLoading] = useState(true) useEffect(() => { const initContract = async () => { if (typeof window.ethereum !== "undefined" && isConnected && address) { try { const provider = new ethers.BrowserProvider(window.ethereum) const signer = await provider.getSigner() const stakingContract = new ethers.Contract(STAKING_CONTRACT_ADDRESS, STAKING_CONTRACT_ABI, signer) setContract(stakingContract) console.log(stakingContract) // In a real app, you would fetch actual data from the contract const balance = await stakingContract.balanceOf(address) setStakedBalance(ethers.formatEther(balance)) const rewardsAmount = await stakingContract.currentEarned(address) setRewards(ethers.formatEther(rewardsAmount)) // For demo purposes, we're setting mock values // setStakedBalance("22.5") // setRewards("1.32") setIsLoading(false) } catch (error) { console.error("Error initializing contract:", error) setIsLoading(false) } } else { setContract(null) setStakedBalance("0") setRewards("0") setIsLoading(false) } } initContract() const onStake = () => { initContract() }; window.addEventListener("withdraw", onStake); return () => { window.removeEventListener("withdraw", onStake); }; }, [address, isConnected]) const stake = async (amount: string) => { if (!contract) return null try { console.log("Staking"); const tx = await contract.stake({ value: ethers.parseEther(amount), }) return await tx.wait() } catch (error) { console.error("Error staking:", error) throw error } } const withdraw = async (amount: string) => { if (!contract) return null try { console.log("Withdrawing....") const tx = await contract.withdraw(ethers.parseEther(amount)) return await tx.wait() } catch (error) { console.error("Error withdrawing:", error) throw error } } const claimRewards = async () => { if (!contract) return null try { const tx = await contract.getReward() return await tx.wait() } catch (error) { console.error("Error claiming rewards:", error) throw error } } return { contract, stakedBalance, rewards, isLoading, stake, withdraw, claimRewards, } } ================================================ FILE: 10-Advanced-Stake-Dapp/Frontend/hooks/use-toast.ts ================================================ "use client" // Inspired by react-hot-toast library import * as React from "react" import type { ToastActionElement, ToastProps, } from "@/components/ui/toast" const TOAST_LIMIT = 1 const TOAST_REMOVE_DELAY = 1000000 type ToasterToast = ToastProps & { id: string title?: React.ReactNode description?: React.ReactNode action?: ToastActionElement } const actionTypes = { ADD_TOAST: "ADD_TOAST", UPDATE_TOAST: "UPDATE_TOAST", DISMISS_TOAST: "DISMISS_TOAST", REMOVE_TOAST: "REMOVE_TOAST", } as const let count = 0 function genId() { count = (count + 1) % Number.MAX_SAFE_INTEGER return count.toString() } type ActionType = typeof actionTypes type Action = | { type: ActionType["ADD_TOAST"] toast: ToasterToast } | { type: ActionType["UPDATE_TOAST"] toast: Partial } | { type: ActionType["DISMISS_TOAST"] toastId?: ToasterToast["id"] } | { type: ActionType["REMOVE_TOAST"] toastId?: ToasterToast["id"] } interface State { toasts: ToasterToast[] } const toastTimeouts = new Map>() const addToRemoveQueue = (toastId: string) => { if (toastTimeouts.has(toastId)) { return } const timeout = setTimeout(() => { toastTimeouts.delete(toastId) dispatch({ type: "REMOVE_TOAST", toastId: toastId, }) }, TOAST_REMOVE_DELAY) toastTimeouts.set(toastId, timeout) } export const reducer = (state: State, action: Action): State => { switch (action.type) { case "ADD_TOAST": return { ...state, toasts: [action.toast, ...state.toasts].slice(0, TOAST_LIMIT), } case "UPDATE_TOAST": return { ...state, toasts: state.toasts.map((t) => t.id === action.toast.id ? { ...t, ...action.toast } : t ), } case "DISMISS_TOAST": { const { toastId } = action // ! Side effects ! - This could be extracted into a dismissToast() action, // but I'll keep it here for simplicity if (toastId) { addToRemoveQueue(toastId) } else { state.toasts.forEach((toast) => { addToRemoveQueue(toast.id) }) } return { ...state, toasts: state.toasts.map((t) => t.id === toastId || toastId === undefined ? { ...t, open: false, } : t ), } } case "REMOVE_TOAST": if (action.toastId === undefined) { return { ...state, toasts: [], } } return { ...state, toasts: state.toasts.filter((t) => t.id !== action.toastId), } } } const listeners: Array<(state: State) => void> = [] let memoryState: State = { toasts: [] } function dispatch(action: Action) { memoryState = reducer(memoryState, action) listeners.forEach((listener) => { listener(memoryState) }) } type Toast = Omit function toast({ ...props }: Toast) { const id = genId() const update = (props: ToasterToast) => dispatch({ type: "UPDATE_TOAST", toast: { ...props, id }, }) const dismiss = () => dispatch({ type: "DISMISS_TOAST", toastId: id }) dispatch({ type: "ADD_TOAST", toast: { ...props, id, open: true, onOpenChange: (open) => { if (!open) dismiss() }, }, }) return { id: id, dismiss, update, } } function useToast() { const [state, setState] = React.useState(memoryState) React.useEffect(() => { listeners.push(setState) return () => { const index = listeners.indexOf(setState) if (index > -1) { listeners.splice(index, 1) } } }, [state]) return { ...state, toast, dismiss: (toastId?: string) => dispatch({ type: "DISMISS_TOAST", toastId }), } } export { useToast, toast } ================================================ FILE: 10-Advanced-Stake-Dapp/Frontend/lib/utils.ts ================================================ import { type ClassValue, clsx } from "clsx" import { twMerge } from "tailwind-merge" export function cn(...inputs: ClassValue[]) { return twMerge(clsx(inputs)) } export function formatNumber(num: number): string { return new Intl.NumberFormat().format(num) } ================================================ FILE: 10-Advanced-Stake-Dapp/Frontend/next.config.ts ================================================ import type { NextConfig } from "next"; const nextConfig: NextConfig = { /* config options here */ }; export default nextConfig; ================================================ FILE: 10-Advanced-Stake-Dapp/Frontend/package.json ================================================ { "name": "Advanced-Stake-Dapp", "version": "0.1.0", "private": true, "scripts": { "dev": "next dev", "build": "next build", "start": "next start", "lint": "next lint" }, "dependencies": { "@radix-ui/react-dropdown-menu": "2.1.12", "@radix-ui/react-label": "2.1.4", "@radix-ui/react-progress": "1.1.4", "@radix-ui/react-slider": "1.3.2", "@radix-ui/react-slot": "1.2.0", "@radix-ui/react-tabs": "1.1.8", "@radix-ui/react-toast": "1.2.11", "@radix-ui/react-tooltip": "1.2.4", "class-variance-authority": "0.7.0", "clsx": "^2.1.1", "ethers": "^6.13.5", "lucide-react": "^0.454.0", "next": "15.0.2", "next-themes": "^0.4.6", "react": "19.0.0-rc-02c0e824-20241028", "react-dom": "19.0.0-rc-02c0e824-20241028", "tailwind-merge": "2.5.4", "tailwindcss-animate": "1.0.7" }, "devDependencies": { "@types/node": "^20", "@types/react": "^18", "@types/react-dom": "^18", "eslint": "^8", "eslint-config-next": "15.0.2", "postcss": "^8", "tailwindcss": "^3.4.17", "typescript": "^5" } } ================================================ FILE: 10-Advanced-Stake-Dapp/Frontend/postcss.config.mjs ================================================ /** @type {import('postcss-load-config').Config} */ const config = { plugins: { tailwindcss: {}, }, }; export default config; ================================================ FILE: 10-Advanced-Stake-Dapp/Frontend/tailwind.config.ts ================================================ import type { Config } from "tailwindcss" const config = { darkMode: ["class"], content: [ "./pages/**/*.{ts,tsx}", "./components/**/*.{ts,tsx}", "./app/**/*.{ts,tsx}", "./src/**/*.{ts,tsx}", "*.{js,ts,jsx,tsx,mdx}", ], prefix: "", theme: { container: { center: true, padding: "2rem", screens: { "2xl": "1400px", }, }, extend: { colors: { border: "hsl(var(--border))", input: "hsl(var(--input))", ring: "hsl(var(--ring))", background: "hsl(var(--background))", foreground: "hsl(var(--foreground))", primary: { DEFAULT: "hsl(var(--primary))", foreground: "hsl(var(--primary-foreground))", }, secondary: { DEFAULT: "hsl(var(--secondary))", foreground: "hsl(var(--secondary-foreground))", }, destructive: { DEFAULT: "hsl(var(--destructive))", foreground: "hsl(var(--destructive-foreground))", }, muted: { DEFAULT: "hsl(var(--muted))", foreground: "hsl(var(--muted-foreground))", }, accent: { DEFAULT: "hsl(var(--accent))", foreground: "hsl(var(--accent-foreground))", }, popover: { DEFAULT: "hsl(var(--popover))", foreground: "hsl(var(--popover-foreground))", }, card: { DEFAULT: "hsl(var(--card))", foreground: "hsl(var(--card-foreground))", }, gold: { DEFAULT: "#DAA520", hover: "#B8860B", }, cream: { DEFAULT: "#F5F2E3", light: "#F8F6EA", dark: "#EBE7D9", }, }, borderRadius: { lg: "var(--radius)", md: "calc(var(--radius) - 2px)", sm: "calc(var(--radius) - 4px)", }, keyframes: { "accordion-down": { from: { height: "0" }, to: { height: "var(--radix-accordion-content-height)" }, }, "accordion-up": { from: { height: "var(--radix-accordion-content-height)" }, to: { height: "0" }, }, }, animation: { "accordion-down": "accordion-down 0.2s ease-out", "accordion-up": "accordion-up 0.2s ease-out", }, }, }, plugins: [require("tailwindcss-animate")], } satisfies Config export default config ================================================ FILE: 10-Advanced-Stake-Dapp/Frontend/tsconfig.json ================================================ { "compilerOptions": { "target": "ES2017", "lib": ["dom", "dom.iterable", "esnext"], "allowJs": true, "skipLibCheck": true, "strict": true, "noEmit": true, "esModuleInterop": true, "module": "esnext", "moduleResolution": "bundler", "resolveJsonModule": true, "isolatedModules": true, "jsx": "preserve", "incremental": true, "plugins": [ { "name": "next" } ], "paths": { "@/*": ["./*"] } }, "include": ["next-env.d.ts", "**/*.ts", "**/*.tsx", ".next/types/**/*.ts"], "exclude": ["node_modules"] } ================================================ FILE: 10-Advanced-Stake-Dapp/Frontend/types/global.d.ts ================================================ interface Window { ethereum?: any } ================================================ FILE: 10-Advanced-Stake-Dapp/README.md ================================================ # 💰 Staking DApp – Reward-Based Token Staking A fast, responsive, and developer-friendly staking DApp that allows users to stake tokens, view real-time rewards, and interact with the smart contract using a clean UI. > 🧠 **GitHub Repository:** [https://github.com/coredao-org/dapp-tutorial](https://github.com/coredao-org/dapp-tutorial) --- ## ✨ Features - 🖥️ **Modern UI:** Sleek, clean, and intuitive interface built for seamless user interaction. - ⛏️ **Staking System:** Users can stake and withdraw tokens with clear feedback and updates. - 💹 **Real-Time Rewards:** Users see their rewards update instantly without needing to reload or resync. - 🔄 **Claim Rewards:** Reward tokens can be claimed any time, with sufficient pre-minted supply in the contract. - 🧪 **Test Tokens:** Built-in faucet mechanism to withdraw test tokens for quick experimentation by running a mint.js script. --- ## 🔧 Getting Started ### 1. Clone the Repository ```bash git clone https://github.com/coredao-org/dapp-tutorial.git cd dapp-tutorial/10-Adavanced-Stake-Dapp ``` ### 2. Setup Environment Create a `.env` file in the root directory and add your private key: ```bash PRIVATE_KEY=your_private_key_here ``` > **Note:** Never commit your `.env` file to version control. Keep your private key safe. ### 3. Install Dependencies Install smart contract dependencies: ```bash npm install ``` Then navigate to the frontend directory and install frontend dependencies: ```bash cd ./Frontend npm install ``` ### 4. Run the DApp Locally ```bash npm run dev ``` > The DApp will be available at `http://localhost:3000`. You can now: > > - Stake tokens > - View your staked balance > - Claim your real-time rewards > - Withdraw test tokens for tinkering --- ## 🪙 Reward Token Minting (Optional) If the **reward token balance** in the contract gets depleted and you can't claim rewards anymore, simply run the `mint.js` script to mint more tokens to the staking contract. ### 📜 Steps to Mint: 1. Open the `scripts/mint.js` file 2. Ensure the contract address and amount are correct 3. Run the script: ```bash npx hardhat run scripts/mint.js --network yourNetwork ``` Replace `yourNetwork` with the appropriate Hardhat network (e.g., `localhost`, `coreTestnet`). --- ## 👛 View Your Reward Tokens in Wallet To view your reward token balance in your wallet, you need to **import the token manually**: - **Token Contract Address:** `0xe11B22597Fbc161e2B8502D5D101C989a62dD288` - **Token Symbol:** `RTN` - **Decimals:** `18` > After importing, you will be able to see your claimed rewards directly in your wallet. --- ## 🗂️ Project Structure ```bash ├── contracts/ # Smart contracts (RewardToken, NativeStaking) ├── scripts/ │ └── mint.js # Script to mint additional reward tokens ├── Frontend # Frontend Next.js app ├── hardhat.config.js # Hardhat config for deployment ├── .env # Store your private key here └── README.md ``` --- ## 📘 Tech Stack - **Next.js** – Frontend framework - **Tailwind CSS** – Responsive design - **Hardhat** – Smart contract development - **Ethers.js** – Blockchain interaction - **Solidity** – Smart contract language - **OpenZeppelin** – Secure ERC20 implementation --- ## 🤝 Contributions Feel free to fork the repo, tweak the staking logic, improve the UI, or submit a PR! --- ================================================ FILE: 10-Advanced-Stake-Dapp/contracts/RewardToken.sol ================================================ // SPDX-License-Identifier: MIT pragma solidity ^0.8.22; import {ERC20} from "@openzeppelin/contracts/token/ERC20/ERC20.sol"; error RewardToken__NotOwner(); contract RewardToken is ERC20 { address public immutable i_owner; constructor() ERC20("RewardToken", "RTN") { i_owner = msg.sender; } modifier onlyOwner() { if(i_owner != msg.sender) revert RewardToken__NotOwner(); _; } function mint(address _receipient, uint256 _amount) public { _mint(_receipient, _amount); } } ================================================ FILE: 10-Advanced-Stake-Dapp/contracts/Stake.sol ================================================ // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; /** * @title SimpleStaking * @notice Stake native ETH, earn rewards in an ERC20 token */ contract NativeStaking { IERC20 public immutable rewardToken; uint256 public rewardRatePerSecond; uint256 public lastUpdateTime; uint256 public rewardPerTokenStored; uint256 private _totalStaked; mapping(address => uint256) private _balances; // reward accounting mapping(address => uint256) public userRewardPerTokenPaid; mapping(address => uint256) public rewards; event Staked(address indexed user, uint256 amount); event Withdrawn(address indexed user, uint256 amount); event RewardPaid(address indexed user, uint256 reward); constructor(address _rewardToken, uint256 _rewardRatePerSecond) { rewardToken = IERC20(_rewardToken); rewardRatePerSecond = _rewardRatePerSecond; lastUpdateTime = block.timestamp; } modifier updateReward(address account) { rewardPerTokenStored = rewardPerToken(); lastUpdateTime = block.timestamp; if (account != address(0)) { rewards[account] = earned(account); userRewardPerTokenPaid[account] = rewardPerTokenStored; } _; } // view total staked function totalStaked() external view returns (uint256) { return _totalStaked; } // view user staked balance function balanceOf(address account) external view returns (uint256) { return _balances[account]; } // view user current earned reward tokens function currentEarned(address account) external view returns (uint256) { return earned(account); } // calculate reward per token function rewardPerToken() public view returns (uint256) { if (_totalStaked == 0) { return rewardPerTokenStored; } return rewardPerTokenStored + (block.timestamp - lastUpdateTime) * rewardRatePerSecond * 1e18 / _totalStaked; } // calculate earned rewards function earned(address account) internal view returns (uint256) { return (_balances[account] * (rewardPerToken() - userRewardPerTokenPaid[account]) / 1e18) + rewards[account]; } // calculate daily reward rate per staked ETH function dailyRewardRate() external view returns (uint256) { return rewardRatePerSecond * 86400; // 86400 seconds in a day } // calculate total reward earned for a given stake amount function estimateDailyEarningForStake(uint256 stakeAmount) external view returns (uint256) { if (_totalStaked == 0) return 0; uint256 dailyRewardPerToken = (rewardRatePerSecond * 86400 * 1e18) / _totalStaked; return (stakeAmount * dailyRewardPerToken) / 1e18; } /** * @notice Stake native ETH */ function stake() public payable updateReward(msg.sender) { require(msg.value > 0, "Cannot stake 0"); _totalStaked += msg.value; _balances[msg.sender] += msg.value; emit Staked(msg.sender, msg.value); } /** * @notice Withdraw staked ETH * @param amount Amount of ETH to withdraw */ function withdraw(uint256 amount) public updateReward(msg.sender) { require(amount > 0, "Cannot withdraw 0"); require(_balances[msg.sender] >= amount, "Insufficient balance"); _totalStaked -= amount; _balances[msg.sender] -= amount; payable(msg.sender).transfer(amount); emit Withdrawn(msg.sender, amount); } /** * @notice Claim accumulated reward tokens */ function getReward() public updateReward(msg.sender) { uint256 reward = rewards[msg.sender]; if (reward > 0) { rewards[msg.sender] = 0; require(rewardToken.transfer(msg.sender, reward), "Reward transfer failed"); emit RewardPaid(msg.sender, reward); } } /** * @notice Exit staking: withdraw all and claim rewards */ function exit() external { withdraw(_balances[msg.sender]); getReward(); } // allow contract to receive ETH receive() external payable { stake(); } } ================================================ FILE: 10-Advanced-Stake-Dapp/hardhat.config.js ================================================ require("@nomicfoundation/hardhat-toolbox"); require("dotenv").config(); /** @type import('hardhat/config').HardhatUserConfig */ const PRIVATE_KEY = process.env.PRIVATE_KEY; module.exports = { solidity: "0.8.27", networks: { localhost: { url: "http://127.0.0.1:8545/", // accounts: Thanks hardhat! chainId: 31337, allowUnlimitedContractSize: true, }, coreTestnet: { url: "https://rpc.test2.btcs.network", accounts: [PRIVATE_KEY], chainId: 1114, } }, }; ================================================ FILE: 10-Advanced-Stake-Dapp/ignition/modules/Lock.js ================================================ // This setup uses Hardhat Ignition to manage smart contract deployments. // Learn more about it at https://hardhat.org/ignition const { buildModule } = require("@nomicfoundation/hardhat-ignition/modules"); const JAN_1ST_2030 = 1893456000; const ONE_GWEI = 1_000_000_000n; module.exports = buildModule("LockModule", (m) => { const unlockTime = m.getParameter("unlockTime", JAN_1ST_2030); const lockedAmount = m.getParameter("lockedAmount", ONE_GWEI); const lock = m.contract("Lock", [unlockTime], { value: lockedAmount, }); return { lock }; }); ================================================ FILE: 10-Advanced-Stake-Dapp/package.json ================================================ { "name": "reuse", "version": "1.0.0", "main": "index.js", "scripts": { "test": "echo \"Error: no test specified\" && exit 1" }, "author": "", "license": "ISC", "description": "", "devDependencies": { "@nomicfoundation/hardhat-toolbox": "^5.0.0", "hardhat": "^2.22.15" }, "dependencies": { "@openzeppelin/contracts": "^5.3.0", "dotenv": "^16.5.0" } } ================================================ FILE: 10-Advanced-Stake-Dapp/scripts/deploy-stake.js ================================================ const hre = require("hardhat"); async function main() { const rate = ethers.parseUnits("0.01", 18); const RewardToken = await hre.ethers.getContractFactory("RewardToken"); const rewardContract = await RewardToken.deploy(); console.log("Storage contract deployed to:", rewardContract.target); const NativeStaking = await hre.ethers.getContractFactory("NativeStaking"); const stakingContract = await NativeStaking.deploy(rewardContract.target, rate); console.log("Storage contract deployed to:", stakingContract.target); } // We recommend this pattern to be able to use async/await everywhere // and properly handle errors. main().catch((error) => { console.error(error); process.exitCode = 1; }); // Telos: Support contract deployed to: 0x5Ac64F5DA22B25559C7D7522b4B2BB7e2012F382 ================================================ FILE: 10-Advanced-Stake-Dapp/scripts/mint.js ================================================ const hre = require("hardhat"); async function main() { const rewardTokenAddress = "0xe11B22597Fbc161e2B8502D5D101C989a62dD288"; // deployed contract const recipient = "0x652Ca0319df1b8ebe9220B4894DC38Da5C9575d3"; // replace with actual recipient const amount = hre.ethers.parseUnits("9000000", 18); // mint 1000 tokens (adjust if needed) const RewardToken = await hre.ethers.getContractFactory("RewardToken"); const rewardToken = await RewardToken.attach(rewardTokenAddress); const tx = await rewardToken.mint(recipient, amount); await tx.wait(); const balance = await rewardToken.balanceOf(recipient); console.log(balance); console.log(`✅ Minted ${amount} RTN to ${recipient}`); } main().catch((error) => { console.error("❌ Error:", error); process.exitCode = 1; }); ================================================ FILE: 10-Advanced-Stake-Dapp/test/Lock.js ================================================ const { time, loadFixture, } = require("@nomicfoundation/hardhat-toolbox/network-helpers"); const { anyValue } = require("@nomicfoundation/hardhat-chai-matchers/withArgs"); const { expect } = require("chai"); describe("Lock", function () { // We define a fixture to reuse the same setup in every test. // We use loadFixture to run this setup once, snapshot that state, // and reset Hardhat Network to that snapshot in every test. async function deployOneYearLockFixture() { const ONE_YEAR_IN_SECS = 365 * 24 * 60 * 60; const ONE_GWEI = 1_000_000_000; const lockedAmount = ONE_GWEI; const unlockTime = (await time.latest()) + ONE_YEAR_IN_SECS; // Contracts are deployed using the first signer/account by default const [owner, otherAccount] = await ethers.getSigners(); const Lock = await ethers.getContractFactory("Lock"); const lock = await Lock.deploy(unlockTime, { value: lockedAmount }); return { lock, unlockTime, lockedAmount, owner, otherAccount }; } describe("Deployment", function () { it("Should set the right unlockTime", async function () { const { lock, unlockTime } = await loadFixture(deployOneYearLockFixture); expect(await lock.unlockTime()).to.equal(unlockTime); }); it("Should set the right owner", async function () { const { lock, owner } = await loadFixture(deployOneYearLockFixture); expect(await lock.owner()).to.equal(owner.address); }); it("Should receive and store the funds to lock", async function () { const { lock, lockedAmount } = await loadFixture( deployOneYearLockFixture ); expect(await ethers.provider.getBalance(lock.target)).to.equal( lockedAmount ); }); it("Should fail if the unlockTime is not in the future", async function () { // We don't use the fixture here because we want a different deployment const latestTime = await time.latest(); const Lock = await ethers.getContractFactory("Lock"); await expect(Lock.deploy(latestTime, { value: 1 })).to.be.revertedWith( "Unlock time should be in the future" ); }); }); describe("Withdrawals", function () { describe("Validations", function () { it("Should revert with the right error if called too soon", async function () { const { lock } = await loadFixture(deployOneYearLockFixture); await expect(lock.withdraw()).to.be.revertedWith( "You can't withdraw yet" ); }); it("Should revert with the right error if called from another account", async function () { const { lock, unlockTime, otherAccount } = await loadFixture( deployOneYearLockFixture ); // We can increase the time in Hardhat Network await time.increaseTo(unlockTime); // We use lock.connect() to send a transaction from another account await expect(lock.connect(otherAccount).withdraw()).to.be.revertedWith( "You aren't the owner" ); }); it("Shouldn't fail if the unlockTime has arrived and the owner calls it", async function () { const { lock, unlockTime } = await loadFixture( deployOneYearLockFixture ); // Transactions are sent using the first signer by default await time.increaseTo(unlockTime); await expect(lock.withdraw()).not.to.be.reverted; }); }); describe("Events", function () { it("Should emit an event on withdrawals", async function () { const { lock, unlockTime, lockedAmount } = await loadFixture( deployOneYearLockFixture ); await time.increaseTo(unlockTime); await expect(lock.withdraw()) .to.emit(lock, "Withdrawal") .withArgs(lockedAmount, anyValue); // We accept any value as `when` arg }); }); describe("Transfers", function () { it("Should transfer the funds to the owner", async function () { const { lock, unlockTime, lockedAmount, owner } = await loadFixture( deployOneYearLockFixture ); await time.increaseTo(unlockTime); await expect(lock.withdraw()).to.changeEtherBalances( [owner, lock], [lockedAmount, -lockedAmount] ); }); }); }); }); ================================================ FILE: 11-Bridge-Token-Using-Chainlink/License ================================================ MIT License Copyright (c) 2025 Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ================================================ FILE: 11-Bridge-Token-Using-Chainlink/README.md ================================================ # Crosschain Bridge Example This repository provides an example of a crosschain token bridge between **Core Testnet 2** and **Sepolia**. The project consists of two main components: 1. **Foundry (Smart Contracts)** – Contains the Solidity smart contracts for the crosschain bridge. 2. **Frontend (Next.js dApp)** – A frontend interface to interact with the bridge using Next.js, Viem, and Wagmi. The smart contract addresses are on Core Testnet2 Network ``` https://scan.test2.btcs.network/address/0xfa2Bf83Eb2b6e16a469abD3a514b6626206b0c9A ``` Ethereum Sepolia Network ``` https://sepolia.etherscan.io/address/0xa2024ba377ADc11388766d873406fd3C666f6d6A ``` ## Project Structure ``` ├── foundry/ # Contains the smart contracts │ ├── src | ├── CrosschainBridge.sol # Smart contract for crosschain bridging │ ├── USDC.sol # Example tUSDC token contract │ └── ... (other Foundry setup files) ├── frontend/ # Next.js dApp for interacting with the bridge │ ├── components/ # UI components │ ├── app/ # Next.js pages │ ├── lib/ # Utility functions │ ├── ... (other frontend setup files) └── README.md ``` ## Setup & Installation ### 1️⃣ **Clone the Repository** ```sh git clone https://github.com/coredao-org/dapp-tutorial.git cd dapp-tutorial/11-Bridge-Token-Using-Chainlink ``` ### 2️⃣ **Smart Contracts (Foundry)** Install Foundry if you haven’t already: ```sh curl -L https://foundry.paradigm.xyz | bash foundryup ``` Compile and test the contracts: ```sh cd foundry forge build forge test ``` ### 3️⃣ **Frontend (Next.js)** Navigate to the frontend directory and install dependencies: ```sh cd ../frontend npm install ``` Run the Next.js development server: ```sh npm run dev ``` ## How It Works 1. **User selects a token amount to bridge** from **Core Testnet 2 → Sepolia** (or vice versa). 2. **Approval transaction** is sent using **Viem**. 3. **Bridge transaction** is sent using **Wagmi**. 4. The contract **locks tUSDC on the source chain** and **mints an equivalent amount on the destination chain**. 5. The transaction is **finalized** when the tokens appear on the destination chain. ## ⚠️ Caution: This is an Example Project > **This project is for educational and demonstration purposes only.** > Do **NOT** use it in production or with real funds. The smart contracts are experimental and have not been audited. ## 📜 License This project is open-source under the [MIT License](LICENSE). ## ✉️ Contact For any questions or contributions, feel free to open an issue or reach out! --- ## Foundry (Smart Contracts) Deployment and Verification ### 📍 **Deploying on Core Testnet 2 and Sepolia** In this section, we’ll explain how to deploy the crosschain bridge contract on both **Core Testnet 2** and **Sepolia** using Foundry. The smart contract uses **LINK tokens** for bridging, and you'll need to mint **tUSDC** (a mintable token) to bridge between these networks. ### **1. Configure the Deployment Script** You will need to use a **Foundry script** to deploy the contract to the Core Testnet 2 and Sepolia. Here’s a breakdown of the deployment script you need to run: ```bash forge script script/CrosschainBridge.s.sol --rpc-url https://rpc.test2.btcs.network --private-key --broadcast ``` - **Core Testnet 2 RPC URL**: `https://rpc.test2.btcs.network` - **Private Key**: Replace `` with your private key. Be sure to keep your private key secure and **never expose it in your public repositories**. This script will deploy the `CrosschainBridge.sol` contract to Core Testnet 2. The same script can be used for Sepolia by updating the RPC URL accordingly: ```bash forge script script/CrosschainBridge.s.sol --rpc-url https://rpc.sepolia.eth.link --private-key --broadcast ``` ### **2. Smart Contract Details** The `CrosschainBridge.sol` contract facilitates bridging tokens between **Core Testnet 2** and **Sepolia**. Here’s a high-level overview of its functionality: - **Bridge Contract**: It locks `tUSDC` tokens on the source chain (either Core Testnet 2 or Sepolia) and mints an equivalent amount on the destination chain. - **LINK Token**: The contract utilizes **Chainlink’s oracles** and **automation services**, so you need to deposit a small amount of **LINK tokens** into the contract to allow it to use the Chainlink services for the bridging mechanism. ### **3. Minting tUSDC for Bridging** When you deploy the CrossChainBridge contract. It also deployes tUSDC token and sends the to the deployer 100 tUSDC. To perform a bridge transaction, you will need to mint `tUSDC` tokens (a mintable token contract). ### **4. Deposit LINK Token for Contract Usage** Since the contract uses Chainlink oracles for bridging, you will need to deposit a small amount of **LINK tokens** into the deployed contract. The LINK tokens are used for interacting with Chainlink’s services to finalize the bridge transactions. --- ### 🔧 **Verification via VS Code** After deploying the smart contract, it’s important to verify the contract on the respective blockchain explorers. To do this, you’ll use the verification script with the `--verifier custom` flag for verifying the contract manually. **Here’s the process to verify the contract via VS Code**: 1. **Run the Verification Script**: Use the following script to verify the contract: ```bash forge verify-contract --chain-id 1114 --num-of-optimizations 1000000 --watch --constructor-args $(cast abi-encode "constructor(address,address)" 0xded0EE188Fe8F1706D9049e29C82081A5ebEcb2F 0x6C475841d1D7871940E93579E5DBaE01634e17aA) --verifier custom --verifier-url https://api.test2.btcs.network/api --api-key --compiler-version v0.8.24 src/CrosschainBridge.sol:CrossChainBridge ``` - Replace `` with your API key for verification. - The contract address should match the address where the contract was deployed. 2. **Watch for Verification Confirmation**: After running the script, keep an eye on the output for verification confirmation. If successful, the contract will be marked as verified on the blockchain explorer. --- ### 📣 **Important Notes:** - **Use Only Testnet Tokens**: Ensure you are using testnet tokens (like tUSDC) for bridging and deploying on testnets. Never use real tokens or real funds. - **Contract Usage**: The contract locks tokens on the source chain and mints an equivalent amount on the destination chain. This feature is designed for demonstration purposes and is not suitable for production use. - **Chainlink Fees**: Make sure to deposit LINK tokens into the contract to use the Chainlink services for bridging. ================================================ FILE: 11-Bridge-Token-Using-Chainlink/foundry/.github/workflows/test.yml ================================================ name: CI on: push: pull_request: workflow_dispatch: env: FOUNDRY_PROFILE: ci jobs: check: strategy: fail-fast: true name: Foundry project runs-on: ubuntu-latest steps: - uses: actions/checkout@v4 with: submodules: recursive - name: Install Foundry uses: foundry-rs/foundry-toolchain@v1 - name: Show Forge version run: | forge --version - name: Run Forge fmt run: | forge fmt --check id: fmt - name: Run Forge build run: | forge build --sizes id: build - name: Run Forge tests run: | forge test -vvv id: test ================================================ FILE: 11-Bridge-Token-Using-Chainlink/foundry/.gitignore ================================================ # Compiler files cache/ out/ # Ignores development broadcast logs !/broadcast /broadcast/*/31337/ /broadcast/**/dry-run/ # Docs docs/ # Dotenv file .env lib/ dependencies/ ================================================ FILE: 11-Bridge-Token-Using-Chainlink/foundry/README.md ================================================ ## Foundry (Smart Contracts) Deployment and Verification ### 📍 **Deploying on Core Testnet 2 and Sepolia** In this section, we’ll explain how to deploy the crosschain bridge contract on both **Core Testnet 2** and **Sepolia** using Foundry. The smart contract uses **LINK tokens** for bridging, and you'll need to mint **tUSDC** (a mintable token) to bridge between these networks. ### **1. Configure the Deployment Script** You will need to use a **Foundry script** to deploy the contract to the Core Testnet 2 and Sepolia. Here’s a breakdown of the deployment script you need to run: ```bash forge script script/CrosschainBridge.s.sol --rpc-url https://rpc.test2.btcs.network --private-key --broadcast ``` - **Core Testnet 2 RPC URL**: `https://rpc.test2.btcs.network` - **Private Key**: Replace `` with your private key. Be sure to keep your private key secure and **never expose it in your public repositories**. This script will deploy the `CrosschainBridge.sol` contract to Core Testnet 2. The same script can be used for Sepolia by updating the RPC URL accordingly: ```bash forge script script/CrosschainBridge.s.sol --rpc-url https://rpc.sepolia.eth.link --private-key --broadcast ``` ### **2. Smart Contract Details** The `CrosschainBridge.sol` contract facilitates bridging tokens between **Core Testnet 2** and **Sepolia**. Here’s a high-level overview of its functionality: - **Bridge Contract**: It locks `tUSDC` tokens on the source chain (either Core Testnet 2 or Sepolia) and mints an equivalent amount on the destination chain. - **LINK Token**: The contract utilizes **Chainlink’s oracles** and **automation services**, so you need to deposit a small amount of **LINK tokens** into the contract to allow it to use the Chainlink services for the bridging mechanism. ### **3. Minting tUSDC for Bridging** When you deploy the CrossChainBridge contract. It also deployes tUSDC token and sends the to the deployer 100 tUSDC. To perform a bridge transaction, you will need to mint `tUSDC` tokens (a mintable token contract). ### **4. Deposit LINK Token for Contract Usage** Since the contract uses Chainlink oracles for bridging, you will need to deposit a small amount of **LINK tokens** into the deployed contract. The LINK tokens are used for interacting with Chainlink’s services to finalize the bridge transactions. --- ### 🔧 **Verification via VS Code** After deploying the smart contract, it’s important to verify the contract on the respective blockchain explorers. To do this, you’ll use the verification script with the `--verifier custom` flag for verifying the contract manually. **Here’s the process to verify the contract via VS Code**: 1. **Run the Verification Script**: Use the following script to verify the contract: ```bash forge verify-contract --chain-id 1114 --num-of-optimizations 1000000 --watch --constructor-args $(cast abi-encode "constructor(address,address)" 0xded0EE188Fe8F1706D9049e29C82081A5ebEcb2F 0x6C475841d1D7871940E93579E5DBaE01634e17aA) --verifier custom --verifier-url https://api.test2.btcs.network/api --api-key --compiler-version v0.8.24 src/CrosschainBridge.sol:CrossChainBridge ``` - Replace `` with your API key for verification. - The contract address should match the address where the contract was deployed. 2. **Watch for Verification Confirmation**: After running the script, keep an eye on the output for verification confirmation. If successful, the contract will be marked as verified on the blockchain explorer. --- ### 📣 **Important Notes:** - **Use Only Testnet Tokens**: Ensure you are using testnet tokens (like tUSDC) for bridging and deploying on testnets. Never use real tokens or real funds. - **Contract Usage**: The contract locks tokens on the source chain and mints an equivalent amount on the destination chain. This feature is designed for demonstration purposes and is not suitable for production use. - **Chainlink Fees**: Make sure to deposit LINK tokens into the contract to use the Chainlink services for bridging. ================================================ FILE: 11-Bridge-Token-Using-Chainlink/foundry/foundry.toml ================================================ [profile.default] src = "src" out = "out" libs = ["lib", "dependencies"] remappings = ["@chainlink/contracts/=dependencies/smartcontractkit-ccip-2.5.0-ccip1.1.0/contracts"] solidity_version = "0.8.24" evm_version = "shanghai" solc_version = "0.8.24" [dependencies] smartcontractkit-ccip = "2.5.0-ccip1.1.0" # See more config options https://github.com/foundry-rs/foundry/blob/master/crates/config/README.md#all-options ================================================ FILE: 11-Bridge-Token-Using-Chainlink/foundry/remappings.txt ================================================ smartcontractkit-ccip-2.5.0-ccip1.1.0/=dependencies/smartcontractkit-ccip-2.5.0-ccip1.1.0/ ================================================ FILE: 11-Bridge-Token-Using-Chainlink/foundry/script/CrosschainBridge.s.sol ================================================ // SPDX-License-Identifier: UNLICENSED pragma solidity ^0.8.13; import {Script, console} from "forge-std/Script.sol"; import {CrossChainBridge} from "../src/CrosschainBridge.sol"; import {HelperConfig} from "./HelperConfig.s.sol"; contract CrosschainBridgeScript is Script { function run() public { deployCrosschainBridge(); } function deployCrosschainBridge() public returns (HelperConfig, CrossChainBridge) { HelperConfig helperConfig = new HelperConfig(); HelperConfig.NetworkConfig memory config = helperConfig.getConfig(); vm.startBroadcast(); CrossChainBridge crosschainBridge = new CrossChainBridge( config.router, config.linkToken ); vm.stopBroadcast(); return (helperConfig, crosschainBridge); } } ================================================ FILE: 11-Bridge-Token-Using-Chainlink/foundry/script/HelperConfig.s.sol ================================================ // SPDX-License-Identifier: MIT pragma solidity ^0.8.24; import {Script, console2} from "forge-std/Script.sol"; contract HelperConfig is Script { /*////////////////////////////////////////////////////////////// ERRORS //////////////////////////////////////////////////////////////*/ error HelperConfig__InvalidChainId(); /*////////////////////////////////////////////////////////////// TYPES //////////////////////////////////////////////////////////////*/ struct NetworkConfig { address router; address linkToken; } /*////////////////////////////////////////////////////////////// STATE VARIABLES //////////////////////////////////////////////////////////////*/ uint256 constant ETH_SEPOLIA_CHAIN_ID = 11155111; uint256 constant CORE_TESTNET2_CHAIN_ID = 1114; mapping(uint256 chainId => NetworkConfig) public networkConfigs; /*////////////////////////////////////////////////////////////// FUNCTIONS //////////////////////////////////////////////////////////////*/ constructor() { networkConfigs[ETH_SEPOLIA_CHAIN_ID] = getEthSepoliaConfig(); networkConfigs[CORE_TESTNET2_CHAIN_ID] = getCoreTestnet2Config(); } function getConfig() public view returns (NetworkConfig memory) { return getConfigByChainId(block.chainid); } function getConfigByChainId( uint256 chainId ) public view returns (NetworkConfig memory) { return networkConfigs[chainId]; } /*////////////////////////////////////////////////////////////// CONFIGS //////////////////////////////////////////////////////////////*/ function getEthSepoliaConfig() public pure returns (NetworkConfig memory) { return NetworkConfig({ router: 0x0BF3dE8c5D3e8A2B34D2BEeB17ABfCeBaf363A59, linkToken: 0x779877A7B0D9E8603169DdbD7836e478b4624789 }); } function getCoreTestnet2Config() public pure returns (NetworkConfig memory) { return NetworkConfig({ router: 0xded0EE188Fe8F1706D9049e29C82081A5ebEcb2F, linkToken: 0x6C475841d1D7871940E93579E5DBaE01634e17aA }); } } ================================================ FILE: 11-Bridge-Token-Using-Chainlink/foundry/src/CrosschainBridge.sol ================================================ // SPDX-License-Identifier: MIT pragma solidity ^0.8.19; import {CCIPReceiver} from "@chainlink/contracts/src/v0.8/ccip/applications/CCIPReceiver.sol"; import {Client} from "@chainlink/contracts/src/v0.8/ccip/libraries/Client.sol"; import {IRouterClient} from "@chainlink/contracts/src/v0.8/ccip/interfaces/IRouterClient.sol"; import {OwnerIsCreator} from "@chainlink/contracts/src/v0.8/shared/access/OwnerIsCreator.sol"; import {IERC20} from "@chainlink/contracts/src/v0.8/vendor/openzeppelin-solidity/v4.8.0/contracts/token/ERC20/IERC20.sol"; import {LinkTokenInterface} from "./LinkTokenInterface.sol"; import {USDC} from "./USDC.sol"; /** * @title A simple cross-chain bridge contract * @author Fraol Bereket * @notice The smart contract is built to show a simple example of USDC token bridge between Core network and Eth Sepolia. Currently there is no bridgeable token between Core and Sepolia so in the example usdc token is created. */ contract CrossChainBridge is CCIPReceiver, OwnerIsCreator { event MessageSent( bytes32 indexed messageId, uint64 indexed destinationChainSelector, address sender, address receiver, uint256 amount ); event TokensReceived( bytes32 indexed messageId, uint64 indexed sourceChainSelector, address sender, address receiver, uint256 amount ); struct TransferData { address sender; uint256 amount; } USDC public usdcToken; LinkTokenInterface public linkToken; IRouterClient private s_router; constructor(address _router, address _linkToken) CCIPReceiver(_router) { s_router = IRouterClient(_router); linkToken = LinkTokenInterface(_linkToken); // Fix: Pass LINK token address usdcToken = new USDC(); usdcToken.mint(msg.sender, 100000000000000000000); } /// @notice Handles incoming CCIP messages function _ccipReceive( Client.Any2EVMMessage memory any2EvmMessage ) internal override { bytes32 messageId = any2EvmMessage.messageId; uint64 sourceChainSelector = any2EvmMessage.sourceChainSelector; address sender = abi.decode(any2EvmMessage.sender, (address)); // Decode the received data into TransferData struct TransferData memory transferData = abi.decode( any2EvmMessage.data, (TransferData) ); require(transferData.amount > 0, "Invalid transfer amount"); // Mint tokens to the sender (the original sender of the transaction) usdcToken.mint(transferData.sender, transferData.amount); emit TokensReceived( messageId, sourceChainSelector, sender, transferData.sender, // The original sender who should receive the tokens transferData.amount ); } /// @notice Bridges tokens to another chain function bridgeTokens( uint64 destinationChainSelector, address receiver, uint256 amount ) external { require( usdcToken.balanceOf(msg.sender) >= amount, "Insufficient balance" ); require( usdcToken.transferFrom(msg.sender, address(this), amount), "Transfer failed" ); sendMessage(destinationChainSelector, receiver, amount); } function sendMessage( uint64 destinationChainSelector, address receiver, uint256 transferAmount ) internal returns (bytes32 messageId) { address sender = msg.sender; TransferData memory transferData = TransferData({ sender: sender, amount: transferAmount }); // Encode the struct for transmission bytes memory encodedData = abi.encode(transferData); Client.EVM2AnyMessage memory evm2AnyMessage = Client.EVM2AnyMessage({ receiver: abi.encode(receiver), // ABI-encoded receiver address data: encodedData, // ABI-encoded string message tokenAmounts: new Client.EVMTokenAmount[](0), extraArgs: Client._argsToBytes( Client.EVMExtraArgsV1({ gasLimit: 200_000 // Gas limit for the callback on the destination chain }) ), feeToken: address(linkToken) // Setting feeToken to LinkToken address, indicating LINK will be used for fees }); // Get the fee required to send the message uint256 fees = s_router.getFee( destinationChainSelector, evm2AnyMessage ); // approve the Router to send LINK tokens on contract's behalf. I will spend the fees in LINK linkToken.approve(address(s_router), fees); require( IERC20(usdcToken).approve(address(s_router), transferAmount), "Failed to approve router" ); // Send the message through the router and store the returned message ID messageId = s_router.ccipSend(destinationChainSelector, evm2AnyMessage); // Emit an event with message details emit MessageSent( messageId, destinationChainSelector, sender, receiver, transferAmount ); // Return the message ID return messageId; } } ================================================ FILE: 11-Bridge-Token-Using-Chainlink/foundry/src/LinkTokenInterface.sol ================================================ // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; // solhint-disable-next-line interface-starts-with-i interface LinkTokenInterface { function allowance( address owner, address spender ) external view returns (uint256 remaining); function approve( address spender, uint256 value ) external returns (bool success); function balanceOf(address owner) external view returns (uint256 balance); function decimals() external view returns (uint8 decimalPlaces); function decreaseApproval( address spender, uint256 addedValue ) external returns (bool success); function increaseApproval( address spender, uint256 subtractedValue ) external; function name() external view returns (string memory tokenName); function symbol() external view returns (string memory tokenSymbol); function totalSupply() external view returns (uint256 totalTokensIssued); function transfer( address to, uint256 value ) external returns (bool success); function transferAndCall( address to, uint256 value, bytes calldata data ) external returns (bool success); function transferFrom( address from, address to, uint256 value ) external returns (bool success); } ================================================ FILE: 11-Bridge-Token-Using-Chainlink/foundry/src/USDC.sol ================================================ // SPDX-License-Identifier: MIT pragma solidity ^0.8.19; import {ERC20} from "@chainlink/contracts/src/v0.8/vendor/openzeppelin-solidity/v4.8.0/contracts/token/ERC20/ERC20.sol"; /** * @title Mock USDC for testing * @author Fraol Bereket * @notice This token is for testing purpose only. the token can be minted by anyone. */ contract USDC is ERC20 { constructor() ERC20("Test USDC", "tUSDC") { // Initial mint for deployer (optional) _mint(msg.sender, 1000000 * 10 ** decimals()); } /// @notice Allows anyone to mint test tokens (for testing only!) function mint(address to, uint256 amount) public { _mint(to, amount); } } ================================================ FILE: 11-Bridge-Token-Using-Chainlink/frontend/.gitignore ================================================ # See https://help.github.com/articles/ignoring-files/ for more about ignoring files. # dependencies /node_modules /.pnp .pnp.* .yarn/* !.yarn/patches !.yarn/plugins !.yarn/releases !.yarn/versions # testing /coverage # next.js /.next/ /out/ # production /build # misc .DS_Store *.pem # debug npm-debug.log* yarn-debug.log* yarn-error.log* .pnpm-debug.log* # env files (can opt-in for committing if needed) .env* # vercel .vercel # typescript *.tsbuildinfo next-env.d.ts ================================================ FILE: 11-Bridge-Token-Using-Chainlink/frontend/ABI/CrosschainBridge.json ================================================ [ { "inputs": [ { "internalType": "address", "name": "_router", "type": "address" }, { "internalType": "address", "name": "_linkToken", "type": "address" } ], "stateMutability": "nonpayable", "type": "constructor" }, { "inputs": [ { "internalType": "address", "name": "router", "type": "address" } ], "name": "InvalidRouter", "type": "error" }, { "anonymous": false, "inputs": [ { "indexed": true, "internalType": "bytes32", "name": "messageId", "type": "bytes32" }, { "indexed": true, "internalType": "uint64", "name": "destinationChainSelector", "type": "uint64" }, { "indexed": false, "internalType": "address", "name": "sender", "type": "address" }, { "indexed": false, "internalType": "address", "name": "receiver", "type": "address" }, { "indexed": false, "internalType": "uint256", "name": "amount", "type": "uint256" } ], "name": "MessageSent", "type": "event" }, { "anonymous": false, "inputs": [ { "indexed": true, "internalType": "address", "name": "from", "type": "address" }, { "indexed": true, "internalType": "address", "name": "to", "type": "address" } ], "name": "OwnershipTransferRequested", "type": "event" }, { "anonymous": false, "inputs": [ { "indexed": true, "internalType": "address", "name": "from", "type": "address" }, { "indexed": true, "internalType": "address", "name": "to", "type": "address" } ], "name": "OwnershipTransferred", "type": "event" }, { "anonymous": false, "inputs": [ { "indexed": true, "internalType": "bytes32", "name": "messageId", "type": "bytes32" }, { "indexed": true, "internalType": "uint64", "name": "sourceChainSelector", "type": "uint64" }, { "indexed": false, "internalType": "address", "name": "sender", "type": "address" }, { "indexed": false, "internalType": "address", "name": "receiver", "type": "address" }, { "indexed": false, "internalType": "uint256", "name": "amount", "type": "uint256" } ], "name": "TokensReceived", "type": "event" }, { "inputs": [], "name": "acceptOwnership", "outputs": [], "stateMutability": "nonpayable", "type": "function" }, { "inputs": [ { "internalType": "uint64", "name": "destinationChainSelector", "type": "uint64" }, { "internalType": "address", "name": "receiver", "type": "address" }, { "internalType": "uint256", "name": "amount", "type": "uint256" } ], "name": "bridgeTokens", "outputs": [ { "internalType": "bytes32", "name": "messageId", "type": "bytes32" } ], "stateMutability": "nonpayable", "type": "function" }, { "inputs": [ { "components": [ { "internalType": "bytes32", "name": "messageId", "type": "bytes32" }, { "internalType": "uint64", "name": "sourceChainSelector", "type": "uint64" }, { "internalType": "bytes", "name": "sender", "type": "bytes" }, { "internalType": "bytes", "name": "data", "type": "bytes" }, { "components": [ { "internalType": "address", "name": "token", "type": "address" }, { "internalType": "uint256", "name": "amount", "type": "uint256" } ], "internalType": "struct Client.EVMTokenAmount[]", "name": "destTokenAmounts", "type": "tuple[]" } ], "internalType": "struct Client.Any2EVMMessage", "name": "message", "type": "tuple" } ], "name": "ccipReceive", "outputs": [], "stateMutability": "nonpayable", "type": "function" }, { "inputs": [], "name": "getRouter", "outputs": [ { "internalType": "address", "name": "", "type": "address" } ], "stateMutability": "view", "type": "function" }, { "inputs": [], "name": "linkToken", "outputs": [ { "internalType": "contract LinkTokenInterface", "name": "", "type": "address" } ], "stateMutability": "view", "type": "function" }, { "inputs": [], "name": "owner", "outputs": [ { "internalType": "address", "name": "", "type": "address" } ], "stateMutability": "view", "type": "function" }, { "inputs": [ { "internalType": "bytes4", "name": "interfaceId", "type": "bytes4" } ], "name": "supportsInterface", "outputs": [ { "internalType": "bool", "name": "", "type": "bool" } ], "stateMutability": "view", "type": "function" }, { "inputs": [ { "internalType": "address", "name": "to", "type": "address" } ], "name": "transferOwnership", "outputs": [], "stateMutability": "nonpayable", "type": "function" }, { "inputs": [], "name": "usdcToken", "outputs": [ { "internalType": "contract USDC", "name": "", "type": "address" } ], "stateMutability": "view", "type": "function" } ] ================================================ FILE: 11-Bridge-Token-Using-Chainlink/frontend/ABI/USDC.json ================================================ [ { "inputs": [], "stateMutability": "nonpayable", "type": "constructor" }, { "inputs": [ { "internalType": "address", "name": "spender", "type": "address" }, { "internalType": "uint256", "name": "allowance", "type": "uint256" }, { "internalType": "uint256", "name": "needed", "type": "uint256" } ], "name": "ERC20InsufficientAllowance", "type": "error" }, { "inputs": [ { "internalType": "address", "name": "sender", "type": "address" }, { "internalType": "uint256", "name": "balance", "type": "uint256" }, { "internalType": "uint256", "name": "needed", "type": "uint256" } ], "name": "ERC20InsufficientBalance", "type": "error" }, { "inputs": [ { "internalType": "address", "name": "approver", "type": "address" } ], "name": "ERC20InvalidApprover", "type": "error" }, { "inputs": [ { "internalType": "address", "name": "receiver", "type": "address" } ], "name": "ERC20InvalidReceiver", "type": "error" }, { "inputs": [ { "internalType": "address", "name": "sender", "type": "address" } ], "name": "ERC20InvalidSender", "type": "error" }, { "inputs": [ { "internalType": "address", "name": "spender", "type": "address" } ], "name": "ERC20InvalidSpender", "type": "error" }, { "anonymous": false, "inputs": [ { "indexed": true, "internalType": "address", "name": "owner", "type": "address" }, { "indexed": true, "internalType": "address", "name": "spender", "type": "address" }, { "indexed": false, "internalType": "uint256", "name": "value", "type": "uint256" } ], "name": "Approval", "type": "event" }, { "anonymous": false, "inputs": [ { "indexed": true, "internalType": "address", "name": "from", "type": "address" }, { "indexed": true, "internalType": "address", "name": "to", "type": "address" }, { "indexed": false, "internalType": "uint256", "name": "value", "type": "uint256" } ], "name": "Transfer", "type": "event" }, { "inputs": [ { "internalType": "address", "name": "owner", "type": "address" }, { "internalType": "address", "name": "spender", "type": "address" } ], "name": "allowance", "outputs": [ { "internalType": "uint256", "name": "", "type": "uint256" } ], "stateMutability": "view", "type": "function" }, { "inputs": [ { "internalType": "address", "name": "spender", "type": "address" }, { "internalType": "uint256", "name": "value", "type": "uint256" } ], "name": "approve", "outputs": [ { "internalType": "bool", "name": "", "type": "bool" } ], "stateMutability": "nonpayable", "type": "function" }, { "inputs": [ { "internalType": "address", "name": "account", "type": "address" } ], "name": "balanceOf", "outputs": [ { "internalType": "uint256", "name": "", "type": "uint256" } ], "stateMutability": "view", "type": "function" }, { "inputs": [], "name": "decimals", "outputs": [ { "internalType": "uint8", "name": "", "type": "uint8" } ], "stateMutability": "view", "type": "function" }, { "inputs": [ { "internalType": "address", "name": "to", "type": "address" }, { "internalType": "uint256", "name": "amount", "type": "uint256" } ], "name": "mint", "outputs": [], "stateMutability": "nonpayable", "type": "function" }, { "inputs": [], "name": "name", "outputs": [ { "internalType": "string", "name": "", "type": "string" } ], "stateMutability": "view", "type": "function" }, { "inputs": [], "name": "symbol", "outputs": [ { "internalType": "string", "name": "", "type": "string" } ], "stateMutability": "view", "type": "function" }, { "inputs": [], "name": "totalSupply", "outputs": [ { "internalType": "uint256", "name": "", "type": "uint256" } ], "stateMutability": "view", "type": "function" }, { "inputs": [ { "internalType": "address", "name": "to", "type": "address" }, { "internalType": "uint256", "name": "value", "type": "uint256" } ], "name": "transfer", "outputs": [ { "internalType": "bool", "name": "", "type": "bool" } ], "stateMutability": "nonpayable", "type": "function" }, { "inputs": [ { "internalType": "address", "name": "from", "type": "address" }, { "internalType": "address", "name": "to", "type": "address" }, { "internalType": "uint256", "name": "value", "type": "uint256" } ], "name": "transferFrom", "outputs": [ { "internalType": "bool", "name": "", "type": "bool" } ], "stateMutability": "nonpayable", "type": "function" } ] ================================================ FILE: 11-Bridge-Token-Using-Chainlink/frontend/README.md ================================================ ## FRONTEND OF CROSSCHAIN BRIDGE This is the frontend of the Crosschain Bridge project built with Next.js. It interacts with the smart contracts on **Core Testnet 2** and **Sepolia**. The frontend allows users to bridge tokens between the two networks and view relevant information. ### Run the Development Server First, navigate to the `frontend` directory and install the required dependencies: ```bash npm install ``` Once the dependencies are installed, run the development server: ```bash npm run dev ``` This will start the Next.js development server. Open [http://localhost:3000](http://localhost:3000) with your browser to see the result. You can start editing the page by modifying `app/page.tsx`. The page auto-updates as you edit the file. ### Interacting with the Bridge On the frontend, users can: 1. Select the token and amount they want to bridge. 2. Interact with the smart contracts to perform token approval and bridging transactions. 3. View the status of their transactions on the selected network. ### Learn More To learn more about Next.js, take a look at the following resources: - [Next.js Documentation](https://nextjs.org/docs) - Learn about Next.js features and API. - [Learn Next.js](https://nextjs.org/learn) - An interactive Next.js tutorial. You can check out [the Next.js GitHub repository](https://github.com/vercel/next.js) - your feedback and contributions are welcome! ### Deploy on Vercel The easiest way to deploy your Next.js app is to use the [Vercel Platform](https://vercel.com/new?utm_medium=default-template&filter=next.js&utm_source=create-next-app&utm_campaign=create-next-app-readme) from the creators of Next.js. Check out our [Next.js deployment documentation](https://nextjs.org/docs/app/building-your-application/deploying) for more details. ================================================ FILE: 11-Bridge-Token-Using-Chainlink/frontend/WalletConfig.tsx ================================================ import "@rainbow-me/rainbowkit/styles.css"; import { getDefaultConfig } from "@rainbow-me/rainbowkit"; import { sepolia, type Chain } from "wagmi/chains"; import { Address } from "viem"; export const coreTestnet2: Chain = { id: 1114, name: "Core Testnet 2", iconUrl: "https://cryptologos.cc/logos/core-dao-core-logo.png?v=040", iconBackground: "#fff", nativeCurrency: { name: "CORE", symbol: "tCORE2", decimals: 18 }, rpcUrls: { default: { http: ["https://rpc.test2.btcs.network"] }, }, blockExplorers: { default: { name: "Core Explorer", url: "https://scan.test2.btcs.network/" }, }, testnet: true, }; export const walletConfig = getDefaultConfig({ appName: "Core DAO Token Bridge", projectId: process.env.NEXT_PUBLIC_WALLETCONNECT_PROJECT_ID, chains: [sepolia, coreTestnet2], ssr: true, // If your dApp uses server-side rendering (SSR) }); ================================================ FILE: 11-Bridge-Token-Using-Chainlink/frontend/app/Provider.tsx ================================================ "use client"; import React from "react"; import { WagmiProvider } from "wagmi"; import { QueryClient, QueryClientProvider } from "@tanstack/react-query"; import { walletConfig } from "@/WalletConfig"; import { RainbowKitProvider } from "@rainbow-me/rainbowkit"; const queryClient = new QueryClient(); export default function Provider({ children }: { children: React.ReactNode }) { return ( {children} ); } ================================================ FILE: 11-Bridge-Token-Using-Chainlink/frontend/app/globals.css ================================================ @import "tailwindcss"; @import "tw-animate-css"; @custom-variant dark (&:is(.dark *)); @theme inline { --color-background: var(--background); --color-foreground: var(--foreground); --font-sans: var(--font-geist-sans); --font-mono: var(--font-geist-mono); --color-sidebar-ring: var(--sidebar-ring); --color-sidebar-border: var(--sidebar-border); --color-sidebar-accent-foreground: var(--sidebar-accent-foreground); --color-sidebar-accent: var(--sidebar-accent); --color-sidebar-primary-foreground: var(--sidebar-primary-foreground); --color-sidebar-primary: var(--sidebar-primary); --color-sidebar-foreground: var(--sidebar-foreground); --color-sidebar: var(--sidebar); --color-chart-5: var(--chart-5); --color-chart-4: var(--chart-4); --color-chart-3: var(--chart-3); --color-chart-2: var(--chart-2); --color-chart-1: var(--chart-1); --color-ring: var(--ring); --color-input: var(--input); --color-border: var(--border); --color-destructive: var(--destructive); --color-accent-foreground: var(--accent-foreground); --color-accent: var(--accent); --color-muted-foreground: var(--muted-foreground); --color-muted: var(--muted); --color-secondary-foreground: var(--secondary-foreground); --color-secondary: var(--secondary); --color-primary-foreground: var(--primary-foreground); --color-primary: var(--primary); --color-popover-foreground: var(--popover-foreground); --color-popover: var(--popover); --color-card-foreground: var(--card-foreground); --color-card: var(--card); --radius-sm: calc(var(--radius) - 4px); --radius-md: calc(var(--radius) - 2px); --radius-lg: var(--radius); --radius-xl: calc(var(--radius) + 4px); } :root { --radius: 0.625rem; --background: oklch(1 0 0); --foreground: oklch(0.145 0 0); --card: oklch(1 0 0); --card-foreground: oklch(0.145 0 0); --popover: oklch(1 0 0); --popover-foreground: oklch(0.145 0 0); --primary: oklch(0.205 0 0); --primary-foreground: oklch(0.985 0 0); --secondary: oklch(0.97 0 0); --secondary-foreground: oklch(0.205 0 0); --muted: oklch(0.97 0 0); --muted-foreground: oklch(0.556 0 0); --accent: oklch(0.97 0 0); --accent-foreground: oklch(0.205 0 0); --destructive: oklch(0.577 0.245 27.325); --border: oklch(0.922 0 0); --input: oklch(0.922 0 0); --ring: oklch(0.708 0 0); --chart-1: oklch(0.646 0.222 41.116); --chart-2: oklch(0.6 0.118 184.704); --chart-3: oklch(0.398 0.07 227.392); --chart-4: oklch(0.828 0.189 84.429); --chart-5: oklch(0.769 0.188 70.08); --sidebar: oklch(0.985 0 0); --sidebar-foreground: oklch(0.145 0 0); --sidebar-primary: oklch(0.205 0 0); --sidebar-primary-foreground: oklch(0.985 0 0); --sidebar-accent: oklch(0.97 0 0); --sidebar-accent-foreground: oklch(0.205 0 0); --sidebar-border: oklch(0.922 0 0); --sidebar-ring: oklch(0.708 0 0); } .dark { --background: oklch(0.145 0 0); --foreground: oklch(0.985 0 0); --card: oklch(0.205 0 0); --card-foreground: oklch(0.985 0 0); --popover: oklch(0.205 0 0); --popover-foreground: oklch(0.985 0 0); --primary: oklch(0.922 0 0); --primary-foreground: oklch(0.205 0 0); --secondary: oklch(0.269 0 0); --secondary-foreground: oklch(0.985 0 0); --muted: oklch(0.269 0 0); --muted-foreground: oklch(0.708 0 0); --accent: oklch(0.269 0 0); --accent-foreground: oklch(0.985 0 0); --destructive: oklch(0.704 0.191 22.216); --border: oklch(1 0 0 / 10%); --input: oklch(1 0 0 / 15%); --ring: oklch(0.556 0 0); --chart-1: oklch(0.488 0.243 264.376); --chart-2: oklch(0.696 0.17 162.48); --chart-3: oklch(0.769 0.188 70.08); --chart-4: oklch(0.627 0.265 303.9); --chart-5: oklch(0.645 0.246 16.439); --sidebar: oklch(0.205 0 0); --sidebar-foreground: oklch(0.985 0 0); --sidebar-primary: oklch(0.488 0.243 264.376); --sidebar-primary-foreground: oklch(0.985 0 0); --sidebar-accent: oklch(0.269 0 0); --sidebar-accent-foreground: oklch(0.985 0 0); --sidebar-border: oklch(1 0 0 / 10%); --sidebar-ring: oklch(0.556 0 0); } @layer base { * { @apply border-border outline-ring/50; } body { @apply bg-background text-foreground; } } ================================================ FILE: 11-Bridge-Token-Using-Chainlink/frontend/app/layout.tsx ================================================ import type { Metadata } from "next"; import { Geist, Geist_Mono } from "next/font/google"; import "./globals.css"; import Provider from "./Provider"; const geistSans = Geist({ variable: "--font-geist-sans", subsets: ["latin"], }); const geistMono = Geist_Mono({ variable: "--font-geist-mono", subsets: ["latin"], }); export const metadata: Metadata = { title: "Bridge Token", description: "Bridge Token from Core to Sepolia and vice versa", }; export default function RootLayout({ children, }: Readonly<{ children: React.ReactNode; }>) { return ( {children} ); } ================================================ FILE: 11-Bridge-Token-Using-Chainlink/frontend/app/page.tsx ================================================ "use client"; import { useState, useEffect } from "react"; import Image from "next/image"; import { ConnectButton } from "@rainbow-me/rainbowkit"; import { Button } from "@/components/ui/button"; import { Card, CardContent, CardDescription, CardFooter, CardHeader, CardTitle, } from "@/components/ui/card"; import { Input } from "@/components/ui/input"; import { Label } from "@/components/ui/label"; import { useAccount, useBalance, useWriteContract } from "wagmi"; import { waitForTransactionReceipt } from "@wagmi/core"; import { parseEther } from "viem"; import CrosschainABI from "@/ABI/CrosschainBridge.json"; import UsdcABI from "@/ABI/USDC.json"; import { walletConfig } from "@/WalletConfig"; interface notificationInterfact { message: string; type: string; } export default function Home() { const BridgeToken_CORE = "0xfa2Bf83Eb2b6e16a469abD3a514b6626206b0c9A"; const BridgeToken_SEPOLIA = "0xa2024ba377ADc11388766d873406fd3C666f6d6A"; const tUSDC_ADDRESS_CORE = "0xb320c17e33cfb20d143db0f49e531c1762025d0f"; const tUSDC_ADDRESS_SEPOLIA = "0x58e5Daaa9af5849BB2f9F5C7679b84b9465fab0e"; const Core_Chain_Selector = "4264732132125536123"; const Sepolia_Chain_Selector = "16015286601757825753"; const [amount, setAmount] = useState("0"); const [loading, setLoading] = useState(false); const [notification, setNotification] = useState(); const { writeContract } = useWriteContract(); const { address, isConnected, chain } = useAccount(); const { data: balanceData, isLoading, isError, } = useBalance({ address, token: chain?.id == 11155111 ? tUSDC_ADDRESS_SEPOLIA : tUSDC_ADDRESS_CORE, }); const handleBridge = async (amount: string) => { console.log("handle bridge"); if (!chain) return; let chainSelector = chain.id === 11155111 ? Core_Chain_Selector : Sepolia_Chain_Selector; let Contract = chain.id === 11155111 ? BridgeToken_SEPOLIA : BridgeToken_CORE; let Receiver = chain.id === 11155111 ? BridgeToken_CORE : BridgeToken_SEPOLIA; let Token = chain.id === 11155111 ? tUSDC_ADDRESS_SEPOLIA : tUSDC_ADDRESS_CORE; try { setLoading(true); // Step 1: Approve the contract to spend the token const approveTx = await new Promise<`0x${string}`>((resolve, reject) => { writeContract( { abi: UsdcABI, address: Token as `0x${string}`, functionName: "approve", args: [Contract, parseEther(amount)], }, { onSuccess: (hash) => resolve(hash), onError: (error) => reject(error), } ); }); console.log("Approval transaction sent:", approveTx); // Step 2: Wait for confirmation const receipt = await waitForTransactionReceipt(walletConfig, { hash: approveTx, }); if (receipt.status !== "success") throw new Error("Approval failed"); // Step 3: Bridge the tokens using bridgeTokens const transferTx = await new Promise<`0x${string}`>((resolve, reject) => { writeContract( { abi: CrosschainABI, address: Contract as `0x${string}`, functionName: "bridgeTokens", args: [chainSelector, Receiver, parseEther(amount)], }, { onSuccess: (hash) => resolve(hash), onError: (error) => reject(error), } ); }); console.log("Transfer transaction sent:", transferTx); // Step 4: Wait for confirmation const receipt2 = await waitForTransactionReceipt(walletConfig, { hash: transferTx, }); if (receipt2.status !== "success") throw new Error("Approval failed"); setNotification({ message: "Bridge tUSDC successfully!", type: "success", }); setLoading(false); } catch (error) { console.error("Transaction failed:", error); setNotification({ message: "Error happened while bridging!", type: "error", }); setLoading(false); } setTimeout(() => setNotification(null), 5000); }; return (
{notification && (
{notification.message}
)}
Core Dao logo
Core Dao logo
Bridge Bridge tUSDC Token from{" "} {chain?.id == 11155111 ? "Sepolia to Core Testnet 2" : "Core Testnet2 to Sepolia"}
setAmount(e.target.value)} placeholder="Amount to bridge" />
tUSDC :{" "} {isConnected && isLoading ? "Loading..." : isError ? "Error fetching balance" : balanceData?.formatted}
); } ================================================ FILE: 11-Bridge-Token-Using-Chainlink/frontend/components/ui/alert.tsx ================================================ import * as React from "react" import { cva, type VariantProps } from "class-variance-authority" import { cn } from "@/lib/utils" const alertVariants = cva( "relative w-full rounded-lg border px-4 py-3 text-sm grid has-[>svg]:grid-cols-[calc(var(--spacing)*4)_1fr] grid-cols-[0_1fr] has-[>svg]:gap-x-3 gap-y-0.5 items-start [&>svg]:size-4 [&>svg]:translate-y-0.5 [&>svg]:text-current", { variants: { variant: { default: "bg-card text-card-foreground", destructive: "text-destructive bg-card [&>svg]:text-current *:data-[slot=alert-description]:text-destructive/90", }, }, defaultVariants: { variant: "default", }, } ) function Alert({ className, variant, ...props }: React.ComponentProps<"div"> & VariantProps) { return (
) } function AlertTitle({ className, ...props }: React.ComponentProps<"div">) { return (
) } function AlertDescription({ className, ...props }: React.ComponentProps<"div">) { return (
) } export { Alert, AlertTitle, AlertDescription } ================================================ FILE: 11-Bridge-Token-Using-Chainlink/frontend/components/ui/button.tsx ================================================ import * as React from "react" import { Slot } from "@radix-ui/react-slot" import { cva, type VariantProps } from "class-variance-authority" import { cn } from "@/lib/utils" const buttonVariants = cva( "inline-flex items-center justify-center gap-2 whitespace-nowrap rounded-md text-sm font-medium transition-all disabled:pointer-events-none disabled:opacity-50 [&_svg]:pointer-events-none [&_svg:not([class*='size-'])]:size-4 shrink-0 [&_svg]:shrink-0 outline-none focus-visible:border-ring focus-visible:ring-ring/50 focus-visible:ring-[3px] aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive", { variants: { variant: { default: "bg-primary text-primary-foreground shadow-xs hover:bg-primary/90", destructive: "bg-destructive text-white shadow-xs hover:bg-destructive/90 focus-visible:ring-destructive/20 dark:focus-visible:ring-destructive/40 dark:bg-destructive/60", outline: "border bg-background shadow-xs hover:bg-accent hover:text-accent-foreground dark:bg-input/30 dark:border-input dark:hover:bg-input/50", secondary: "bg-secondary text-secondary-foreground shadow-xs hover:bg-secondary/80", ghost: "hover:bg-accent hover:text-accent-foreground dark:hover:bg-accent/50", link: "text-primary underline-offset-4 hover:underline", }, size: { default: "h-9 px-4 py-2 has-[>svg]:px-3", sm: "h-8 rounded-md gap-1.5 px-3 has-[>svg]:px-2.5", lg: "h-10 rounded-md px-6 has-[>svg]:px-4", icon: "size-9", }, }, defaultVariants: { variant: "default", size: "default", }, } ) function Button({ className, variant, size, asChild = false, ...props }: React.ComponentProps<"button"> & VariantProps & { asChild?: boolean }) { const Comp = asChild ? Slot : "button" return ( ) } export { Button, buttonVariants } ================================================ FILE: 11-Bridge-Token-Using-Chainlink/frontend/components/ui/card.tsx ================================================ import * as React from "react" import { cn } from "@/lib/utils" function Card({ className, ...props }: React.ComponentProps<"div">) { return (
) } function CardHeader({ className, ...props }: React.ComponentProps<"div">) { return (
) } function CardTitle({ className, ...props }: React.ComponentProps<"div">) { return (
) } function CardDescription({ className, ...props }: React.ComponentProps<"div">) { return (
) } function CardAction({ className, ...props }: React.ComponentProps<"div">) { return (
) } function CardContent({ className, ...props }: React.ComponentProps<"div">) { return (
) } function CardFooter({ className, ...props }: React.ComponentProps<"div">) { return (
) } export { Card, CardHeader, CardFooter, CardTitle, CardAction, CardDescription, CardContent, } ================================================ FILE: 11-Bridge-Token-Using-Chainlink/frontend/components/ui/input.tsx ================================================ import * as React from "react" import { cn } from "@/lib/utils" function Input({ className, type, ...props }: React.ComponentProps<"input">) { return ( ) } export { Input } ================================================ FILE: 11-Bridge-Token-Using-Chainlink/frontend/components/ui/label.tsx ================================================ "use client" import * as React from "react" import * as LabelPrimitive from "@radix-ui/react-label" import { cn } from "@/lib/utils" function Label({ className, ...props }: React.ComponentProps) { return ( ) } export { Label } ================================================ FILE: 11-Bridge-Token-Using-Chainlink/frontend/components.json ================================================ { "$schema": "https://ui.shadcn.com/schema.json", "style": "new-york", "rsc": true, "tsx": true, "tailwind": { "config": "", "css": "app/globals.css", "baseColor": "neutral", "cssVariables": true, "prefix": "" }, "aliases": { "components": "@/components", "utils": "@/lib/utils", "ui": "@/components/ui", "lib": "@/lib", "hooks": "@/hooks" }, "iconLibrary": "lucide" } ================================================ FILE: 11-Bridge-Token-Using-Chainlink/frontend/eslint.config.mjs ================================================ import { dirname } from "path"; import { fileURLToPath } from "url"; import { FlatCompat } from "@eslint/eslintrc"; const __filename = fileURLToPath(import.meta.url); const __dirname = dirname(__filename); const compat = new FlatCompat({ baseDirectory: __dirname, }); const eslintConfig = [ ...compat.extends("next/core-web-vitals", "next/typescript"), ]; export default eslintConfig; ================================================ FILE: 11-Bridge-Token-Using-Chainlink/frontend/lib/utils.ts ================================================ import { clsx, type ClassValue } from "clsx" import { twMerge } from "tailwind-merge" export function cn(...inputs: ClassValue[]) { return twMerge(clsx(inputs)) } ================================================ FILE: 11-Bridge-Token-Using-Chainlink/frontend/next.config.ts ================================================ import type { NextConfig } from "next"; const nextConfig: NextConfig = { /* config options here */ }; export default nextConfig; ================================================ FILE: 11-Bridge-Token-Using-Chainlink/frontend/package.json ================================================ { "name": "frontend", "version": "0.1.0", "private": true, "scripts": { "dev": "next dev --turbopack", "build": "next build", "start": "next start", "lint": "next lint" }, "dependencies": { "@radix-ui/react-label": "2.1.2", "@radix-ui/react-slot": "1.1.2", "@rainbow-me/rainbowkit": "2.2.4", "@tanstack/react-query": "5.70.0", "class-variance-authority": "0.7.1", "clsx": "2.1.1", "lucide-react": "0.485.0", "next": "15.2.4", "react": "19.0.0", "react-dom": "19.0.0", "tailwind-merge": "3.0.2", "tw-animate-css": "1.2.5", "viem": "2.24.1", "wagmi": "2.14.15" }, "devDependencies": { "@eslint/eslintrc": "3.3.1", "@tailwindcss/postcss": "4.0.17", "@types/node": "20.17.28", "@types/react": "19.0.12", "@types/react-dom": "19.0.4", "eslint": "9.23.0", "eslint-config-next": "15.2.4", "tailwindcss": "4.0.17", "typescript": "5.8.2" } } ================================================ FILE: 11-Bridge-Token-Using-Chainlink/frontend/postcss.config.mjs ================================================ const config = { plugins: ["@tailwindcss/postcss"], }; export default config; ================================================ FILE: 11-Bridge-Token-Using-Chainlink/frontend/tsconfig.json ================================================ { "compilerOptions": { "target": "ES2017", "lib": ["dom", "dom.iterable", "esnext"], "allowJs": true, "skipLibCheck": true, "strict": true, "noEmit": true, "esModuleInterop": true, "module": "esnext", "moduleResolution": "bundler", "resolveJsonModule": true, "isolatedModules": true, "jsx": "preserve", "incremental": true, "plugins": [ { "name": "next" } ], "paths": { "@/*": ["./*"] } }, "include": ["next-env.d.ts", "**/*.ts", "**/*.tsx", ".next/types/**/*.ts"], "exclude": ["node_modules"] } ================================================ FILE: 12-Core-MultiSig/.gitignore ================================================ node_modules .env # Hardhat files /cache /artifacts # TypeChain files /typechain /typechain-types # solidity-coverage files /coverage /coverage.json # Hardhat Ignition default folder for deployments against a local node ignition/deployments/chain-31337 ================================================ FILE: 12-Core-MultiSig/Frontend/.eslintrc.json ================================================ { "extends": ["next/core-web-vitals", "next/typescript"], "rules": { "@typescript-eslint/no-explicit-any": "off", // Allow `any` type "@typescript-eslint/no-unused-vars": "off", // Disable unused variables check "@typescript-eslint/no-unused-expressions": "off", // Disable unused expressions check "react-hooks/exhaustive-deps": "off", // Suppress missing dependency warnings in useEffect "@next/next/no-img-element": "off" // Allow the use of instead of } } ================================================ FILE: 12-Core-MultiSig/Frontend/.gitignore ================================================ # See https://help.github.com/articles/ignoring-files/ for more about ignoring files. # dependencies /node_modules /.pnp .pnp.* .yarn/* !.yarn/patches !.yarn/plugins !.yarn/releases !.yarn/versions # testing /coverage # next.js /.next/ /out/ # production /build # misc .DS_Store *.pem # debug npm-debug.log* yarn-debug.log* yarn-error.log* # env files (can opt-in for commiting if needed) .env* # vercel .vercel # typescript *.tsbuildinfo next-env.d.ts ================================================ FILE: 12-Core-MultiSig/Frontend/README.md ================================================ This is a [Next.js](https://nextjs.org) project bootstrapped with [`create-next-app`](https://nextjs.org/docs/app/api-reference/cli/create-next-app). ## Getting Started First, run the development server: ```bash npm run dev # or yarn dev # or pnpm dev # or bun dev ``` Open [http://localhost:3000](http://localhost:3000) with your browser to see the result. You can start editing the page by modifying `app/page.tsx`. The page auto-updates as you edit the file. This project uses [`next/font`](https://nextjs.org/docs/app/building-your-application/optimizing/fonts) to automatically optimize and load [Geist](https://vercel.com/font), a new font family for Vercel. ## Learn More To learn more about Next.js, take a look at the following resources: - [Next.js Documentation](https://nextjs.org/docs) - learn about Next.js features and API. - [Learn Next.js](https://nextjs.org/learn) - an interactive Next.js tutorial. You can check out [the Next.js GitHub repository](https://github.com/vercel/next.js) - your feedback and contributions are welcome! ## Deploy on Vercel The easiest way to deploy your Next.js app is to use the [Vercel Platform](https://vercel.com/new?utm_medium=default-template&filter=next.js&utm_source=create-next-app&utm_campaign=create-next-app-readme) from the creators of Next.js. Check out our [Next.js deployment documentation](https://nextjs.org/docs/app/building-your-application/deploying) for more details. ================================================ FILE: 12-Core-MultiSig/Frontend/app/client.ts ================================================ // src/client.ts import { createThirdwebClient } from "thirdweb"; export const client = createThirdwebClient({ clientId: "abf285902676f10739931719171a6b4c", // For devs test }); ================================================ FILE: 12-Core-MultiSig/Frontend/app/constants/MultiSigFactory.json ================================================ [ { "inputs": [ { "internalType": "address", "name": "_feeReceiver", "type": "address" } ], "stateMutability": "nonpayable", "type": "constructor" }, { "anonymous": false, "inputs": [ { "indexed": false, "internalType": "address", "name": "multisigAddress", "type": "address" } ], "name": "MultiSigCreated", "type": "event" }, { "inputs": [ { "internalType": "address", "name": "multisigAddress", "type": "address" } ], "name": "Deposit", "outputs": [], "stateMutability": "nonpayable", "type": "function" }, { "inputs": [ { "internalType": "address", "name": "multisigAddress", "type": "address" }, { "internalType": "uint256", "name": "_proposalIndex", "type": "uint256" } ], "name": "confirmTransaction", "outputs": [ { "internalType": "bool", "name": "", "type": "bool" } ], "stateMutability": "nonpayable", "type": "function" }, { "inputs": [ { "internalType": "address[]", "name": "_owners", "type": "address[]" }, { "internalType": "uint256", "name": "_noOfConfirmations", "type": "uint256" } ], "name": "createMultiSig", "outputs": [ { "internalType": "address", "name": "multisigAddress", "type": "address" } ], "stateMutability": "payable", "type": "function" }, { "inputs": [ { "internalType": "address", "name": "multisigAddress", "type": "address" }, { "internalType": "uint256", "name": "_proposalIndex", "type": "uint256" } ], "name": "executeTransaction", "outputs": [ { "internalType": "bool", "name": "", "type": "bool" } ], "stateMutability": "nonpayable", "type": "function" }, { "inputs": [], "name": "getAllDeployedMultiSigs", "outputs": [ { "internalType": "address[]", "name": "", "type": "address[]" } ], "stateMutability": "view", "type": "function" }, { "inputs": [ { "internalType": "address", "name": "multisigAddress", "type": "address" } ], "name": "getAllProposals", "outputs": [ { "components": [ { "internalType": "address", "name": "proposer", "type": "address" }, { "internalType": "address", "name": "to", "type": "address" }, { "internalType": "uint256", "name": "value", "type": "uint256" }, { "internalType": "string", "name": "description", "type": "string" }, { "internalType": "uint256", "name": "noOfConfirmations", "type": "uint256" }, { "internalType": "bool", "name": "status", "type": "bool" } ], "internalType": "struct MultiSig.Transaction[]", "name": "", "type": "tuple[]" } ], "stateMutability": "view", "type": "function" }, { "inputs": [ { "internalType": "address", "name": "multisigAddress", "type": "address" } ], "name": "getDeployer", "outputs": [ { "internalType": "address", "name": "", "type": "address" } ], "stateMutability": "view", "type": "function" }, { "inputs": [ { "internalType": "address", "name": "deployer", "type": "address" } ], "name": "getDeployersWallets", "outputs": [ { "components": [ { "internalType": "address", "name": "walletAddress", "type": "address" }, { "internalType": "uint256", "name": "timeCreated", "type": "uint256" }, { "internalType": "uint256", "name": "balance", "type": "uint256" } ], "internalType": "struct MultiSigFactory.Wallets[]", "name": "", "type": "tuple[]" } ], "stateMutability": "view", "type": "function" }, { "inputs": [ { "internalType": "address", "name": "multisigAddress", "type": "address" } ], "name": "getOwners", "outputs": [ { "internalType": "address[]", "name": "", "type": "address[]" } ], "stateMutability": "view", "type": "function" }, { "inputs": [ { "internalType": "address", "name": "multisigAddress", "type": "address" } ], "name": "getTimeCreated", "outputs": [ { "internalType": "uint256", "name": "", "type": "uint256" } ], "stateMutability": "view", "type": "function" }, { "inputs": [ { "internalType": "address", "name": "multisigAddress", "type": "address" }, { "internalType": "uint256", "name": "_proposalIndex", "type": "uint256" } ], "name": "revokeConfirmedTransaction", "outputs": [ { "internalType": "bool", "name": "", "type": "bool" } ], "stateMutability": "nonpayable", "type": "function" }, { "inputs": [ { "internalType": "address", "name": "multisigAddress", "type": "address" }, { "internalType": "address", "name": "_to", "type": "address" }, { "internalType": "uint256", "name": "_value", "type": "uint256" }, { "internalType": "string", "name": "_description", "type": "string" } ], "name": "submitTransaction", "outputs": [ { "internalType": "bool", "name": "", "type": "bool" } ], "stateMutability": "nonpayable", "type": "function" } ] ================================================ FILE: 12-Core-MultiSig/Frontend/app/constants/config.json ================================================ { "31337": { "factory": { "address": "0x9A676e781A523b5d0C0e43731313A708CB607508" } }, "1114": { "factory": { "address": "0xAA4CA018D432b66c65c85467FEb08036B860362d" } } } ================================================ FILE: 12-Core-MultiSig/Frontend/app/create/createmultisig.tsx ================================================ "use client"; import { useState, useEffect } from "react"; import { Button } from "@/components/ui/button"; import { Input } from "@/components/ui/input"; import { Label } from "@/components/ui/label"; import { Card, CardContent, CardDescription, CardHeader, CardTitle, } from "@/components/ui/card"; import { Loader2 } from "lucide-react"; import { ethers } from "ethers"; // ABIs & Configs import MultiSigFactory from "../constants/MultiSigFactory.json"; import config from "../constants/config.json"; export default function CreateMultiSigWallet(provider: any, factory: any) { const [name, setName] = useState(""); const [owners, setOwners] = useState([""]); const [requiredConfirmations, setRequiredConfirmations] = useState(1); const [isCreating, setIsCreating] = useState(false); const handleAddOwner = () => setOwners([...owners, ""]); const handleOwnerChange = (index: number, value: string) => { const newOwners = [...owners]; newOwners[index] = value; setOwners(newOwners); }; const handleRemoveOwner = (index: number) => { const newOwners = owners.filter((_, i) => i !== index); setOwners(newOwners); }; async function createMultiSig(addresses: string[], amount: bigint) { try { if (typeof (window as any).ethereum !== "undefined") { const provider = new ethers.BrowserProvider((window as any).ethereum); console.log("Creating multisig...."); const signer = await provider.getSigner(); const network = await provider.getNetwork(); console.log("Network:", network); const chainId = network.chainId.toString(); const configData = config[`${network.chainId}` as keyof typeof config]; if (!configData) { console.error(`No configuration found for chain ID: ${chainId}`); return; } const address = configData.factory.address as string; if (!address || address === "") { console.error("Factory address is empty or undefined"); return; } const contractFactory = new ethers.Contract(address, MultiSigFactory, signer); console.log(contractFactory); const value = ethers.parseEther("0.01"); // Call the createMultiSig function const transaction = await contractFactory.createMultiSig(addresses, amount, { value }); await transaction.wait(); console.log("Done!"); } } catch (error) { console.error("Error creating multisig:", error); } } const handleSubmit = (e: React.FormEvent) => { e.preventDefault(); setIsCreating(true); setTimeout(() => { console.log("Wallet created:", { name, owners, requiredConfirmations }); setIsCreating(false); }, 2000); }; return (
Create Multi-Signature Wallet Set up a new multi-signature wallet by providing the required information
setName(e.target.value)} className="bg-blue-700 border-blue-600 text-white" required />
{owners.map((owner, index) => (
handleOwnerChange(index, e.target.value)} placeholder={`Owner ${index + 1} address`} className="bg-blue-700 border-blue-600 text-white flex-grow" required /> {index > 0 && ( )}
))}
setRequiredConfirmations(parseInt(e.target.value)) } className="bg-blue-700 border-blue-600 text-white" required />
); } ================================================ FILE: 12-Core-MultiSig/Frontend/app/create/multisigcreation.tsx ================================================ 'use client' import { useState } from 'react' import { Button } from '@/components/ui/button' import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogTrigger, } from '@/components/ui/dialog' import CreateMultiSigWallet from './createmultisig' import { Factory } from 'lucide-react' const MultiSigCreationModal = ({isOpen, setIsOpen, provider, factory} : {isOpen: any, setIsOpen: any, provider: any, factory: any}) => { return (
Create MultiSig
) } export default MultiSigCreationModal ================================================ FILE: 12-Core-MultiSig/Frontend/app/dashboard/page.tsx ================================================ "use client"; import { useState, useEffect } from "react"; import { Search } from "lucide-react"; import { Input } from "@/components/ui/input"; import { Button } from "@/components/ui/button"; import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card"; import { DashboardLayout } from "@/components/DashboardLayout"; import { client } from "../client"; import { useActiveAccount, ConnectButton} from "thirdweb/react"; import MultiSigCreationModal from "../create/multisigcreation"; import { ethers } from "ethers"; // ABIs & Configs import MultiSigFactory from "../constants/MultiSigFactory.json"; import config from "../constants/config.json"; export default function Dashboard() { const [search, setSearch] = useState(""); const [wallet, setWallet] = useState<{ walletAddress: string; timeCreated: bigint; balance: bigint; }[]>([]); const [isOpen, setIsOpen] = useState(false) const [factory, setFactory] = useState(undefined); const [provider, setProvider] = useState(undefined); const activeAccount = useActiveAccount(); async function loadBlockchainData() { try { if (typeof (window as any).ethereum !== "undefined") { const provider = new ethers.BrowserProvider((window as any).ethereum); setProvider(provider); console.log("Ethereum provider detected"); const signer = await provider.getSigner(); const network = await provider.getNetwork(); console.log("Network:", network); const chainId = network.chainId.toString(); const configData = config[`${network.chainId}` as keyof typeof config]; if (!configData) { console.error(`No configuration found for chain ID: ${chainId}`); return; } const address = configData.factory.address as string; if (!address || address === "") { console.error("Factory address is empty or undefined"); return; } const contractFactory = new ethers.Contract(address, MultiSigFactory, provider); console.log(contractFactory); setFactory(contractFactory); const smartWallet = await contractFactory.getDeployersWallets(signer.address); console.log(`Deployer's wallets: ${smartWallet}`); setWallet(smartWallet); } else { console.error("Ethereum provider not found!") } } catch (error) { console.error("Error loading blockchain data:", error); } } useEffect(() => { loadBlockchainData(); }, [isOpen]); return (

Wallet Dashboard

{/* */} {activeAccount?.address ? ( ) : ( )}

Connected Wallet:

{activeAccount?.address || "Not Connected"}

setSearch(e.target.value)} className="mr-4 bg-blue-800 border-blue-700 text-white placeholder-gray-400" />
{wallet.map((wallet, index) => ( {wallet.walletAddress}

Created on: {wallet.timeCreated}

Balance: {wallet.balance}

))}
); } ================================================ FILE: 12-Core-MultiSig/Frontend/app/globals.css ================================================ @tailwind base; @tailwind components; @tailwind utilities; @layer utilities { .border-border { } .bg-background { } .text-foreground{} } @layer base { :root { --background: 222.2 84% 4.9%; --foreground: 210 40% 98%; --card: 222.2 84% 4.9%; --card-foreground: 210 40% 98%; --popover: 222.2 84% 4.9%; --popover-foreground: 210 40% 98%; --primary: 217.2 91.2% 59.8%; --primary-foreground: 222.2 47.4% 11.2%; --secondary: 217.2 32.6% 17.5%; --secondary-foreground: 210 40% 98%; --muted: 217.2 32.6% 17.5%; --muted-foreground: 215 20.2% 65.1%; --accent: 217.2 32.6% 17.5%; --accent-foreground: 210 40% 98%; --destructive: 0 62.8% 30.6%; --destructive-foreground: 210 40% 98%; --border: 217.2 32.6% 17.5%; --input: 217.2 32.6% 17.5%; --ring: 224.3 76.3% 48%; --radius: 0.5rem; } } @layer base { * { @apply border-border; } body { @apply bg-background text-foreground; } } .animate-fade-in { animation: fadeIn 0.5s ease-out; } @keyframes fadeIn { from { opacity: 0; } to { opacity: 1; } } .animation-delay-200 { animation-delay: 200ms; } .animation-delay-400 { animation-delay: 400ms; } .animation-delay-600 { animation-delay: 600ms; } ================================================ FILE: 12-Core-MultiSig/Frontend/app/layout.tsx ================================================ import './globals.css' import type { Metadata } from 'next' import { Inter } from 'next/font/google' import Link from 'next/link' import { ThirdwebProvider } from 'thirdweb/react' const inter = Inter({ subsets: ['latin'] }) export const metadata: Metadata = { title: 'MultiSig Wallet', description: 'Secure your digital assets with multi-signature protection', } export default function RootLayout({ children, }: { children: React.ReactNode }) { return ( {children} ) } ================================================ FILE: 12-Core-MultiSig/Frontend/app/linkdash.tsx ================================================ 'use client' import React from 'react' import Link from 'next/link'; import { client } from "./client"; import {useActiveAccount } from "thirdweb/react"; const LinkDash = () => { const activeAccount = useActiveAccount(); return ( <>
Dashboard
) } export default LinkDash ================================================ FILE: 12-Core-MultiSig/Frontend/app/owners/page.tsx ================================================ 'use client' import { useState } from 'react' import { DashboardLayout } from '@/components/DashboardLayout' import { Button } from '@/components/ui/button' import { Input } from '@/components/ui/input' import { Label } from '@/components/ui/label' import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow, } from '@/components/ui/table' import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogTrigger, } from '@/components/ui/dialog' // Mock data for owners const initialOwners = [ { address: '0x1234...5678', name: 'Alice' }, { address: '0xabcd...efgh', name: 'Bob' }, { address: '0x9876...5432', name: 'Charlie' }, ] export default function OwnersPage() { const [owners, setOwners] = useState(initialOwners) const [isOpen, setIsOpen] = useState(false) const [newOwnerAddress, setNewOwnerAddress] = useState('') const [newOwnerName, setNewOwnerName] = useState('') const handleAddOwner = (e: React.FormEvent) => { e.preventDefault() if (newOwnerAddress && newOwnerName) { setOwners([...owners, { address: newOwnerAddress, name: newOwnerName }]) setNewOwnerAddress('') setNewOwnerName('') setIsOpen(false) } } return (

Manage Owners

Add New Owner
setNewOwnerAddress(e.target.value)} className="bg-blue-800 border-blue-700 text-white" />
setNewOwnerName(e.target.value)} className="bg-blue-800 border-blue-700 text-white" />
Owner Address Name Actions {owners.map((owner, index) => ( {owner.address} {owner.name} ))}
) } ================================================ FILE: 12-Core-MultiSig/Frontend/app/page.tsx ================================================ 'use cllient' import Image from "next/image"; import Link from "next/link"; import { Shield, FileText, Key } from "lucide-react"; import { client } from "./client"; import { ConnectButton } from "thirdweb/react"; import LinkDash from "./linkdash"; import { Button } from "@/components/ui/button"; export default function Home() { return (

Secure Your Digital Assets with Multi-Signature Protection

Collaborate and safeguard your funds with a decentralized multi-sig wallet.

Secure Digital Vault

Our Features

Create Multi-Sig Wallet

Secure your assets with multiple signatures for enhanced protection.

Manage Transactions

Easily submit, confirm, and track all your wallet transactions.

Connect Securely

Use your preferred wallet to connect and interact securely.

© 2025 MultiSig Wallet. All rights reserved.

); } ================================================ FILE: 12-Core-MultiSig/Frontend/app/wallet/DialogBoxes/Confirm.tsx ================================================ import React, {useState} from 'react'; import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogTrigger, } from '@/components/ui/dialog' import { Input } from '@/components/ui/input' import { Label } from '@/components/ui/label' import { Button } from '@/components/ui/button' import { ethers } from 'ethers'; const ConfirmTxn = ({factory, tempAddress} : {factory: ethers.Contract, tempAddress: string}) => { const [isOpen, setIsOpen] = useState(false); const [value, setValue] = useState(""); async function confirmTxn(addressSig: string, amount: bigint) { console.log("Confirming proposal....") // Call the submitTransaction function const transaction = await factory.confirmTransaction(addressSig, amount); await transaction.wait(); } return ( Confirm Transaction
setValue(e.target.value)}/>
) } export default ConfirmTxn ================================================ FILE: 12-Core-MultiSig/Frontend/app/wallet/DialogBoxes/Execute.tsx ================================================ import React, {useState} from 'react'; import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogTrigger, } from '@/components/ui/dialog' import { Input } from '@/components/ui/input' import { Label } from '@/components/ui/label' import { Button } from '@/components/ui/button' import { ethers } from 'ethers'; const ExecuteTxn = ({factory, tempAddress} : {factory: ethers.Contract, tempAddress: string}) => { const [isOpen, setIsOpen] = useState(false); const [value, setValue] = useState(""); async function executeTxn(addressSig: string, amount: bigint) { console.log("Executing proposal....") // Call the executeTransaction function const transaction = await factory.executeTransaction(addressSig, amount); await transaction.wait(); } return ( Execute Transaction
setValue(e.target.value)}/>
) } export default ExecuteTxn ================================================ FILE: 12-Core-MultiSig/Frontend/app/wallet/DialogBoxes/Revoke.tsx ================================================ import React, {useState} from 'react'; import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogTrigger, } from '@/components/ui/dialog' import { Input } from '@/components/ui/input' import { Label } from '@/components/ui/label' import { Button } from '@/components/ui/button' import { ethers } from 'ethers'; const RevokeTxn = ({factory, tempAddress} : {factory: ethers.Contract, tempAddress: string}) => { const [isOpen, setIsOpen] = useState(false); const [value, setValue] = useState(""); async function confirmTxn(addressSig: string, amount: bigint) { console.log("Revoking proposal....") // Call the submitTransaction function const transaction = await factory. revokeConfirmedTransaction(addressSig, amount); await transaction.wait(); } return ( Revoke Transaction
setValue(e.target.value)}/>
) } export default RevokeTxn ================================================ FILE: 12-Core-MultiSig/Frontend/app/wallet/DialogBoxes/Submit.tsx ================================================ import React, {useState} from 'react'; import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogTrigger, } from '@/components/ui/dialog' import { Input } from '@/components/ui/input' import { Label } from '@/components/ui/label' import { Button } from '@/components/ui/button' import { ethers } from 'ethers'; const SubmitTxn = ({factory, tempAddress} : {factory: ethers.Contract, tempAddress: string}) => { const [isOpen, setIsOpen] = useState(false); const [recipient, setRecipient] = useState(""); const [value, setValue] = useState(""); const [description, setDescription] = useState(""); async function submitTxn(addressSig: string, addressTo: string, amount: bigint, description: string) { try { console.log("Submitting proposals....") console.log("Wallet address (addressSig):", addressSig); console.log("Recipient address (addressTo):", addressTo); // Validate inputs if (!addressSig || addressSig === "" || addressSig.trim() === "") { console.error("Wallet address is empty or invalid:", addressSig); throw new Error("Invalid wallet address: Please add a MultiSig wallet address first"); } // Validate wallet address format if (!ethers.isAddress(addressSig)) { console.error("Wallet address format is invalid:", addressSig); throw new Error(`Invalid wallet address format: ${addressSig}`); } if (!addressTo || addressTo === "") { throw new Error("Recipient address is required"); } if (!ethers.isAddress(addressTo)) { throw new Error("Invalid recipient address format"); } if (amount <= 0n) { throw new Error("Amount must be greater than 0"); } if (!description || description === "") { throw new Error("Description is required"); } // Call the submitTransaction function const transaction = await factory.submitTransaction(addressSig, addressTo, amount, description); await transaction.wait(); console.log("Transaction submitted successfully!"); return true; } catch (error) { console.error("Error submitting transaction:", error); throw error; } } return ( Submit Transaction
setRecipient(e.target.value)}/>
setValue(e.target.value)}/>
setDescription(e.target.value)} />
) } export default SubmitTxn ================================================ FILE: 12-Core-MultiSig/Frontend/app/wallet/page.tsx ================================================ 'use client' import { useEffect, useState } from 'react' import { Button } from '@/components/ui/button' import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow, } from '@/components/ui/table' import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogTrigger, } from '@/components/ui/dialog' import { Input } from '@/components/ui/input' import { Label } from '@/components/ui/label' import { DashboardLayout } from '@/components/DashboardLayout' import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card' import { AlertCircle, CheckCircle, XCircle } from 'lucide-react' import { client } from "../client" import { useActiveAccount, ConnectButton } from "thirdweb/react"; import { ethers } from 'ethers'; import SubmitTxn from './DialogBoxes/Submit' // ABIs & Configs import MultiSigFactory from "../constants/MultiSigFactory.json"; import config from "../constants/config.json"; import ConfirmTxn from './DialogBoxes/Confirm' import RevokeTxn from './DialogBoxes/Revoke' import ExecuteTxn from './DialogBoxes/Execute' // Mock data for transactions const transactions = [ { id: '1', recipient: '0x1234...5678', value: '1.5', status: 'Pending', confirmations: 1 }, { id: '2', recipient: '0xabcd...efgh', value: '0.5', status: 'Executed', confirmations: 3 }, { id: '3', recipient: '0x9876...5432', value: '2.0', status: 'Rejected', confirmations: 2 }, ] export default function WalletPage() { const activeAccount = useActiveAccount(); const [isOpen, setIsOpen] = useState(false); const [isAdd, setIsAdd] = useState(false); const [isWallet, setIsWallet] = useState(""); const [tempAddress, setTempAddress] = useState(""); // Temporary variable for input const [factory, setFactory] = useState(); const [provider, setProvider] = useState(undefined); const [proposals, setProposals] = useState([]) async function loadBlockchainData() { try { if (typeof (window as any).ethereum !== "undefined") { const provider = new ethers.BrowserProvider((window as any).ethereum); console.log("Loading Blockchain data..."); const signer = await provider.getSigner(); const network = await provider.getNetwork(); console.log("Network:", network); const chainId = network.chainId.toString(); const configData = config[`${network.chainId}` as keyof typeof config]; if (!configData) { console.error(`No configuration found for chain ID: ${chainId}`); return; } const address = configData.factory.address as string; if (!address || address === "") { console.error("Factory address is empty or undefined"); return; } const contractFactory = new ethers.Contract(address, MultiSigFactory, signer); console.log(contractFactory); setFactory(contractFactory) console.log("Data loading done!"); } } catch (error) { console.error("Error loading blockchain data:", error); } } useEffect(() => { loadBlockchainData(); }, []); const handleSubmit = () => { // Validate address before setting if (!tempAddress || tempAddress.trim() === "") { alert("Please enter a MultiSig wallet address"); return; } if (!ethers.isAddress(tempAddress)) { alert(`Invalid wallet address format: ${tempAddress}`); return; } setIsWallet(tempAddress); // Update isWallet only after submitting console.log("Wallet Address Added:", tempAddress); setIsAdd(false); // Close the dialog after successful submission }; const getStatusIcon = (status: string) => { switch (status) { case 'Pending': return case 'Executed': return case 'Rejected': return default: return null } } return (

Wallet:

{activeAccount?.address || "Not connected"}

{activeAccount?.address ? ( <> Interact with MultiSig
setTempAddress(e.target.value)} className="bg-blue-800 border-blue-700 text-white" />

{isWallet}

) : ( )}
Balance

25.5 ETH

Owners

3/5

Confirmations

2

Transaction ID Recipient Address Value (ETH) Status Confirmations {transactions.map((tx) => ( {tx.id} {tx.recipient} {tx.value} {getStatusIcon(tx.status)} {tx.status} {tx.confirmations} ))}
) } ================================================ FILE: 12-Core-MultiSig/Frontend/components/DashboardLayout.tsx ================================================ import Link from 'next/link' import { Home, FileText, Users, Settings } from 'lucide-react' interface DashboardLayoutProps { children: React.ReactNode } export function DashboardLayout({ children }: DashboardLayoutProps) { return (
{children}
) } ================================================ FILE: 12-Core-MultiSig/Frontend/components/ui/button.tsx ================================================ import * as React from "react" import { Slot } from "@radix-ui/react-slot" import { cva, type VariantProps } from "class-variance-authority" import { cn } from "@/lib/utils" const buttonVariants = cva( "inline-flex items-center justify-center gap-2 whitespace-nowrap rounded-md text-sm font-medium transition-colors focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring disabled:pointer-events-none disabled:opacity-50 [&_svg]:pointer-events-none [&_svg]:size-4 [&_svg]:shrink-0", { variants: { variant: { default: "bg-primary text-primary-foreground shadow hover:bg-primary/90", destructive: "bg-destructive text-destructive-foreground shadow-sm hover:bg-destructive/90", outline: "border border-input bg-background shadow-sm hover:bg-accent hover:text-accent-foreground", secondary: "bg-secondary text-secondary-foreground shadow-sm hover:bg-secondary/80", ghost: "hover:bg-accent hover:text-accent-foreground", link: "text-primary underline-offset-4 hover:underline", }, size: { default: "h-9 px-4 py-2", sm: "h-8 rounded-md px-3 text-xs", lg: "h-10 rounded-md px-8", icon: "h-9 w-9", }, }, defaultVariants: { variant: "default", size: "default", }, } ) export interface ButtonProps extends React.ButtonHTMLAttributes, VariantProps { asChild?: boolean } const Button = React.forwardRef( ({ className, variant, size, asChild = false, ...props }, ref) => { const Comp = asChild ? Slot : "button" return ( ) } ) Button.displayName = "Button" export { Button, buttonVariants } ================================================ FILE: 12-Core-MultiSig/Frontend/components/ui/card.tsx ================================================ import * as React from "react" import { cn } from "@/lib/utils" const Card = React.forwardRef< HTMLDivElement, React.HTMLAttributes >(({ className, ...props }, ref) => (
)) Card.displayName = "Card" const CardHeader = React.forwardRef< HTMLDivElement, React.HTMLAttributes >(({ className, ...props }, ref) => (
)) CardHeader.displayName = "CardHeader" const CardTitle = React.forwardRef< HTMLDivElement, React.HTMLAttributes >(({ className, ...props }, ref) => (
)) CardTitle.displayName = "CardTitle" const CardDescription = React.forwardRef< HTMLDivElement, React.HTMLAttributes >(({ className, ...props }, ref) => (
)) CardDescription.displayName = "CardDescription" const CardContent = React.forwardRef< HTMLDivElement, React.HTMLAttributes >(({ className, ...props }, ref) => (
)) CardContent.displayName = "CardContent" const CardFooter = React.forwardRef< HTMLDivElement, React.HTMLAttributes >(({ className, ...props }, ref) => (
)) CardFooter.displayName = "CardFooter" export { Card, CardHeader, CardFooter, CardTitle, CardDescription, CardContent } ================================================ FILE: 12-Core-MultiSig/Frontend/components/ui/dialog.tsx ================================================ "use client" import * as React from "react" import * as DialogPrimitive from "@radix-ui/react-dialog" import { X } from "lucide-react" import { cn } from "@/lib/utils" const Dialog = DialogPrimitive.Root const DialogTrigger = DialogPrimitive.Trigger const DialogPortal = DialogPrimitive.Portal const DialogClose = DialogPrimitive.Close const DialogOverlay = React.forwardRef< React.ElementRef, React.ComponentPropsWithoutRef >(({ className, ...props }, ref) => ( )) DialogOverlay.displayName = DialogPrimitive.Overlay.displayName const DialogContent = React.forwardRef< React.ElementRef, React.ComponentPropsWithoutRef >(({ className, children, ...props }, ref) => ( {children} Close )) DialogContent.displayName = DialogPrimitive.Content.displayName const DialogHeader = ({ className, ...props }: React.HTMLAttributes) => (
) DialogHeader.displayName = "DialogHeader" const DialogFooter = ({ className, ...props }: React.HTMLAttributes) => (
) DialogFooter.displayName = "DialogFooter" const DialogTitle = React.forwardRef< React.ElementRef, React.ComponentPropsWithoutRef >(({ className, ...props }, ref) => ( )) DialogTitle.displayName = DialogPrimitive.Title.displayName const DialogDescription = React.forwardRef< React.ElementRef, React.ComponentPropsWithoutRef >(({ className, ...props }, ref) => ( )) DialogDescription.displayName = DialogPrimitive.Description.displayName export { Dialog, DialogPortal, DialogOverlay, DialogTrigger, DialogClose, DialogContent, DialogHeader, DialogFooter, DialogTitle, DialogDescription, } ================================================ FILE: 12-Core-MultiSig/Frontend/components/ui/input.tsx ================================================ import * as React from "react" import { cn } from "@/lib/utils" const Input = React.forwardRef>( ({ className, type, ...props }, ref) => { return ( ) } ) Input.displayName = "Input" export { Input } ================================================ FILE: 12-Core-MultiSig/Frontend/components/ui/label.tsx ================================================ "use client" import * as React from "react" import * as LabelPrimitive from "@radix-ui/react-label" import { cva, type VariantProps } from "class-variance-authority" import { cn } from "@/lib/utils" const labelVariants = cva( "text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70" ) const Label = React.forwardRef< React.ElementRef, React.ComponentPropsWithoutRef & VariantProps >(({ className, ...props }, ref) => ( )) Label.displayName = LabelPrimitive.Root.displayName export { Label } ================================================ FILE: 12-Core-MultiSig/Frontend/components/ui/table.tsx ================================================ import * as React from "react" import { cn } from "@/lib/utils" const Table = React.forwardRef< HTMLTableElement, React.HTMLAttributes >(({ className, ...props }, ref) => (
)) Table.displayName = "Table" const TableHeader = React.forwardRef< HTMLTableSectionElement, React.HTMLAttributes >(({ className, ...props }, ref) => ( )) TableHeader.displayName = "TableHeader" const TableBody = React.forwardRef< HTMLTableSectionElement, React.HTMLAttributes >(({ className, ...props }, ref) => ( )) TableBody.displayName = "TableBody" const TableFooter = React.forwardRef< HTMLTableSectionElement, React.HTMLAttributes >(({ className, ...props }, ref) => ( tr]:last:border-b-0", className )} {...props} /> )) TableFooter.displayName = "TableFooter" const TableRow = React.forwardRef< HTMLTableRowElement, React.HTMLAttributes >(({ className, ...props }, ref) => ( )) TableRow.displayName = "TableRow" const TableHead = React.forwardRef< HTMLTableCellElement, React.ThHTMLAttributes >(({ className, ...props }, ref) => (
[role=checkbox]]:translate-y-[2px]", className )} {...props} /> )) TableHead.displayName = "TableHead" const TableCell = React.forwardRef< HTMLTableCellElement, React.TdHTMLAttributes >(({ className, ...props }, ref) => ( [role=checkbox]]:translate-y-[2px]", className )} {...props} /> )) TableCell.displayName = "TableCell" const TableCaption = React.forwardRef< HTMLTableCaptionElement, React.HTMLAttributes >(({ className, ...props }, ref) => (
)) TableCaption.displayName = "TableCaption" export { Table, TableHeader, TableBody, TableFooter, TableHead, TableRow, TableCell, TableCaption, } ================================================ FILE: 12-Core-MultiSig/Frontend/components.json ================================================ { "$schema": "https://ui.shadcn.com/schema.json", "style": "new-york", "rsc": true, "tsx": true, "tailwind": { "config": "tailwind.config.ts", "css": "app/globals.css", "baseColor": "zinc", "cssVariables": true, "prefix": "" }, "aliases": { "components": "@/components", "utils": "@/lib/utils", "ui": "@/components/ui", "lib": "@/lib", "hooks": "@/hooks" }, "iconLibrary": "lucide" } ================================================ FILE: 12-Core-MultiSig/Frontend/lib/utils.ts ================================================ import { clsx, type ClassValue } from "clsx" import { twMerge } from "tailwind-merge" export function cn(...inputs: ClassValue[]) { return twMerge(clsx(inputs)) } ================================================ FILE: 12-Core-MultiSig/Frontend/next.config.ts ================================================ import type { NextConfig } from "next"; const nextConfig: NextConfig = { /* config options here */ }; export default nextConfig; ================================================ FILE: 12-Core-MultiSig/Frontend/package.json ================================================ { "name": "reusable", "version": "0.1.0", "private": true, "scripts": { "dev": "next dev", "build": "next build", "start": "next start", "lint": "next lint" }, "dependencies": { "@radix-ui/react-dialog": "1.1.4", "@radix-ui/react-label": "2.1.1", "@radix-ui/react-slot": "1.1.1", "class-variance-authority": "0.7.0", "clsx": "2.1.1", "dotenv": "16.4.7", "ethers": "6.13.5", "lucide-react": "0.454.0", "next": "15.0.2", "react": "19.2.0", "react-dom": "19.2.0", "tailwind-merge": "2.5.4", "tailwindcss-animate": "1.0.7", "thirdweb": "5.86.2" }, "devDependencies": { "@types/node": "^20", "@types/react": "^19", "@types/react-dom": "^19", "eslint": "^8", "eslint-config-next": "15.0.2", "postcss": "^8", "tailwindcss": "^3.4.1", "typescript": "^5" } } ================================================ FILE: 12-Core-MultiSig/Frontend/postcss.config.mjs ================================================ /** @type {import('postcss-load-config').Config} */ const config = { plugins: { tailwindcss: {}, }, }; export default config; ================================================ FILE: 12-Core-MultiSig/Frontend/tailwind.config.js ================================================ module.exports = { darkMode: ["class"], content: [ './pages/**/*.{ts,tsx}', './components/**/*.{ts,tsx}', './app/**/*.{ts,tsx}', './src/**/*.{ts,tsx}', ], theme: { container: { center: true, padding: "2rem", screens: { "2xl": "1400px", }, }, extend: { colors: { 'neon-green': '#39FF14', }, keyframes: { "accordion-down": { from: { height: 0 }, to: { height: "var(--radix-accordion-content-height)" }, }, "accordion-up": { from: { height: "var(--radix-accordion-content-height)" }, to: { height: 0 }, }, "fade-in": { "0%": { opacity: 0 }, "100%": { opacity: 1 }, }, }, animation: { "accordion-down": "accordion-down 0.2s ease-out", "accordion-up": "accordion-up 0.2s ease-out", "fade-in": "fade-in 1s ease-out", }, }, }, plugins: [require("tailwindcss-animate")], } ================================================ FILE: 12-Core-MultiSig/Frontend/tailwind.config.ts ================================================ import type { Config } from "tailwindcss"; const config: Config = { darkMode: ["class"], content: [ "./pages/**/*.{js,ts,jsx,tsx,mdx}", "./components/**/*.{js,ts,jsx,tsx,mdx}", "./app/**/*.{js,ts,jsx,tsx,mdx}", ], theme: { extend: { borderColor: { border: 'hsl(var(border-border))', // Explicitly add `border-border` as a utility }, colors: { background: 'hsl(var(--background))', foreground: 'hsl(var(--foreground))', card: { DEFAULT: 'hsl(var(--card))', foreground: 'hsl(var(--card-foreground))' }, popover: { DEFAULT: 'hsl(var(--popover))', foreground: 'hsl(var(--popover-foreground))' }, primary: { DEFAULT: 'hsl(var(--primary))', foreground: 'hsl(var(--primary-foreground))' }, secondary: { DEFAULT: 'hsl(var(--secondary))', foreground: 'hsl(var(--secondary-foreground))' }, muted: { DEFAULT: 'hsl(var(--muted))', foreground: 'hsl(var(--muted-foreground))' }, accent: { DEFAULT: 'hsl(var(--accent))', foreground: 'hsl(var(--accent-foreground))' }, destructive: { DEFAULT: 'hsl(var(--destructive))', foreground: 'hsl(var(--destructive-foreground))' }, border: 'hsl(var(--border))', input: 'hsl(var(--input))', ring: 'hsl(var(--ring))', chart: { '1': 'hsl(var(--chart-1))', '2': 'hsl(var(--chart-2))', '3': 'hsl(var(--chart-3))', '4': 'hsl(var(--chart-4))', '5': 'hsl(var(--chart-5))' } }, borderRadius: { lg: 'var(--radius)', md: 'calc(var(--radius) - 2px)', sm: 'calc(var(--radius) - 4px)' } } }, plugins: [require("tailwindcss-animate")], }; export default config; ================================================ FILE: 12-Core-MultiSig/Frontend/tsconfig.json ================================================ { "compilerOptions": { "target": "ES2017", "lib": ["dom", "dom.iterable", "esnext"], "allowJs": true, "skipLibCheck": true, "strict": true, "noEmit": true, "esModuleInterop": true, "module": "esnext", "moduleResolution": "bundler", "resolveJsonModule": true, "isolatedModules": true, "jsx": "preserve", "incremental": true, "plugins": [ { "name": "next" } ], "paths": { "@/*": ["./*"] } }, "include": ["next-env.d.ts", "**/*.ts", "**/*.tsx", ".next/types/**/*.ts"], "exclude": ["node_modules"] } ================================================ FILE: 12-Core-MultiSig/README.md ================================================ # MultiSig Wallet Factory Welcome to the MultiSig Wallet Factory project! This blockchain-based application enables users to easily deploy and manage multisignature (multisig) wallets for various use cases, enhancing security and collaborative control over assets. ## Features - **Easy Deployment**: Deploy multisig wallets with a user-friendly interface. - **Customizable Ownership**: Define multiple owners for each wallet, specifying the number of required confirmations for transactions. - **Secure Transactions**: Ensure that transactions are executed only after the necessary approvals, enhancing security. - **Wallet Monitoring**: Track and monitor deployed wallets and their activities. ## Getting Started Follow these instructions to set up and run the project locally. ### Prerequisites Ensure you have the following installed: - [Node.js](https://nodejs.org/) (v16 LTS) - [Yarn](https://yarnpkg.com/) - [Git](https://git-scm.com/) ### Installation 1. **Clone the Repository**: ```bash git clone https://github.com/coredao-org/dapp-tutorial.git cd dapp-tutorial/12-Core-MultiSig ``` 2. **Install Dependencies**: ```bash npm install ``` ### Running the Application 1. **Start the Local Blockchain**: ```bash npx hardhat node ``` This command starts a local Hardhat blockchain instance. 2. **Deploy Contracts**: ```bash npx hardhat run scripts/deploy-multisig.js --network localhost "For Local Blockchain" npx hardhat run scripts/deploy-multisig.js --network core "For Core Blockchain" ``` This command deploys the multisig wallet contracts to the local or core blockchain. 3. **Start the Frontend Application**: ```bash cd MultiSig-Wallet-Factory/Frontend npm start ``` This command starts the React frontend application. 4. **Access the Application**: Open your browser and navigate to `http://localhost:3000` to interact with the application. ## Usage - **Create a Multisig Wallet**: - Navigate to the "Create Wallet" section. - Enter the addresses of the owners and specify the number of required confirmations. - Click "Create" to deploy the wallet. - **Manage Wallets**: - View a list of deployed wallets in the "My Wallets" section. - Select a wallet to view details, propose transactions, and monitor activities. ## Project Structure - **Frontend**: Located in the `Frontend` directory, built with React. - **Contracts**: Solidity contracts are in the `contracts` directory. - **Deployment Scripts**: Found in the `scripts` directory, used for deploying contracts. - **Tests**: Located in the `test` directory, containing test cases for the contracts. ## Contributing Contributions are welcome! Please follow these steps: 1. Fork the repository. 2. Create a new branch (`git checkout -b feature/YourFeature`). 3. Commit your changes (`git commit -m 'Add YourFeature'`). 4. Push to the branch (`git push origin feature/YourFeature`). 5. Open a Pull Request. ================================================ FILE: 12-Core-MultiSig/contracts/MultiSig.sol ================================================ // SPDX-License-Identifier: MIT pragma solidity ^0.8.27; // import "hardhat/console.sol"; error MultiSig__OwnersRequired(); error MultiSig__InvalidAddress(); error MultiSig__NotConfirmed(); error MultiSig__AlreadyConfirmed(); error MultiSig__ProposalNotExists(); error MultiSig__AlreadyExecuted(); error MultiSig__NotEnoughConfirmations(); error MultiSig__NotOwner(); error MultiSig__TransferFailed(); contract MultiSig { uint256 private deployedTime; address private deployer; address[] private owners; uint private noOfConfirmationsNeeded; address private immutable sigFactory; uint256 public proposalIndex = 0; // Making it more complex by adding time periods for when proposals expires // enum Status { // success, // pending, // canceled // } // event Withdrawal(uint amount, uint when); struct Transaction { address proposer; address to; uint256 value; // bytes data; TODO: Complex functions string description; uint256 noOfConfirmations; bool status; } mapping(uint256 => Transaction) public proposalByIndex; mapping(address => bool) private isOwner; mapping(address => mapping(uint256 => bool)) private confirmedByIndex; Transaction[] public transactions; modifier onlyOwners() { if(!isOwner[msg.sender]) revert MultiSig__NotOwner(); _; } modifier proposalAvailable(uint256 _proposalIndex) { if(_proposalIndex >= transactions.length) revert MultiSig__ProposalNotExists(); _; } constructor() { sigFactory = msg.sender; } // Init function to be called only once by factory function init (address[] memory _owners, uint256 _noOfConfirmationsNeeded) external { if(sigFactory != msg.sender) revert MultiSig__NotOwner(); // Include your address if needed to perform the functions before deploying! if(_owners.length < 1) revert MultiSig__OwnersRequired(); deployedTime = block.timestamp; deployer = msg.sender; noOfConfirmationsNeeded = _noOfConfirmationsNeeded; for(uint i = 0; i < _owners.length; i++) { if(_owners[i] == address(0)) revert MultiSig__InvalidAddress(); owners.push(_owners[i]); isOwner[_owners[i]] = true; } } function submitProposal(address _to, uint256 _value, string memory _description) public returns (bool) { Transaction memory transaction = Transaction(msg.sender, _to, _value, _description, 0, false); transactions.push(transaction); proposalByIndex[proposalIndex] = transaction; proposalIndex += 1; return true; // emit ProposalSubmitted(); } function confirmProposal(uint256 _proposalIndex) public /**onlyOwners*/ proposalAvailable(_proposalIndex) returns (bool) { if(confirmedByIndex[msg.sender][_proposalIndex]) revert MultiSig__AlreadyConfirmed(); Transaction storage transaction = proposalByIndex[_proposalIndex]; if(transaction.status) revert MultiSig__AlreadyExecuted(); transaction.noOfConfirmations = transaction.noOfConfirmations + 1; transactions[_proposalIndex].noOfConfirmations += 1; confirmedByIndex[msg.sender][_proposalIndex] = true; // emit Confirmedproposal() } function revokeConfirmedProposal(uint256 _proposalIndex) public /**onlyOwners*/ proposalAvailable(_proposalIndex) returns (bool) { //TODO: Require incase the proposal is executed, it should revert if(!confirmedByIndex[msg.sender][_proposalIndex]) revert MultiSig__NotConfirmed(); Transaction storage transaction = proposalByIndex[_proposalIndex]; if(transaction.status) revert MultiSig__AlreadyExecuted(); transaction.noOfConfirmations = transaction.noOfConfirmations - 1; confirmedByIndex[msg.sender][_proposalIndex] = false; // emit RevokedProposal() } function executeProposal(uint _proposalIndex) public /**onlyOwners*/ proposalAvailable(_proposalIndex) returns (bool) { Transaction storage transaction = proposalByIndex[_proposalIndex]; if(transaction.noOfConfirmations < noOfConfirmationsNeeded) revert MultiSig__NotEnoughConfirmations(); if(transaction.status) revert MultiSig__AlreadyExecuted(); transaction.status = true; //TODO: execute the proposal (bool success, ) = transaction.to.call{value: transaction.value}(""/**transaction.data*/); if(!success) revert MultiSig__TransferFailed(); } function fundWallet() public payable {} ////// GETTER FUNCTIONS function getDeployer() public view returns (address) { return deployer; } function getOwners() public view returns (address[] memory) { return owners; } function getTimeCreated() public view returns (uint256) { return deployedTime; } function getAllProposals() public view returns (Transaction[] memory) { return transactions; } } ================================================ FILE: 12-Core-MultiSig/contracts/MultiSigFactory.sol ================================================ // SPDX-License-Identifier: MIT pragma solidity ^0.8.27; import "./MultiSig.sol"; import "./interfaces/IMultiSig.sol"; contract MultiSigFactory { address private feeReceiver; // TODO: implement token fee receivers for creating those smart wallets address[] private allWallets; struct Wallets { address walletAddress; uint256 timeCreated; uint256 balance; } mapping(address => Wallets[]) private wallets; event MultiSigCreated(address multisigAddress); constructor(address _feeReceiver) { feeReceiver = _feeReceiver; } function createMultiSig(address[] memory _owners, uint256 _noOfConfirmations) payable public returns (address multisigAddress) { bytes memory bytecode = type(MultiSig).creationCode; bytes32 salt = keccak256(abi.encodePacked(_owners, _noOfConfirmations)); //TODO: put the salt assembly { multisigAddress := create2(0, add(bytecode, 32), mload(bytecode), salt) } MultiSig(multisigAddress).init(_owners, _noOfConfirmations); allWallets.push(multisigAddress); Wallets memory wallet = Wallets(multisigAddress, block.timestamp, address(multisigAddress).balance); wallets[msg.sender].push(wallet); emit MultiSigCreated(multisigAddress); } //// ROUTING OR CONTROLLER SECTION function submitTransaction(address multisigAddress, address _to, uint256 _value, string memory _description) public returns (bool) { IMultiSig(multisigAddress).submitProposal(_to, _value, _description); return true; } function confirmTransaction(address multisigAddress, uint256 _proposalIndex) public returns (bool) { bool isConfirmed = IMultiSig(multisigAddress).confirmProposal(_proposalIndex); return isConfirmed; } function revokeConfirmedTransaction(address multisigAddress, uint256 _proposalIndex) public returns (bool) { bool isRevoked = IMultiSig(multisigAddress).revokeConfirmedProposal(_proposalIndex); return isRevoked; } function executeTransaction(address multisigAddress, uint _proposalIndex) public returns (bool) { bool isExecuted = IMultiSig(multisigAddress).executeProposal(_proposalIndex); return isExecuted; } function Deposit(address multisigAddress) public { IMultiSig(multisigAddress).fundWallet(); } // rOUTER TO GETTER FUNCIONS FROM THE MULTISIGS function getOwners(address multisigAddress) public view returns (address[] memory) { address[] memory owners = MultiSig(multisigAddress).getOwners(); return owners; } function getDeployer(address multisigAddress) public view returns (address) { return MultiSig(multisigAddress).getDeployer(); } function getAllProposals(address multisigAddress) public view returns (MultiSig.Transaction[] memory) { return MultiSig(multisigAddress).getAllProposals(); } function getTimeCreated(address multisigAddress) public view returns (uint256) { return MultiSig(multisigAddress).getTimeCreated(); } function getDeployersWallets(address deployer) public view returns (Wallets[] memory) { return wallets[deployer]; } // GETTER FUNCTIONS function getAllDeployedMultiSigs() public view returns (address[] memory) { return allWallets; } } ================================================ FILE: 12-Core-MultiSig/contracts/interfaces/IMultiSig.sol ================================================ // SPDX-License-Identifier: MIT pragma solidity ^0.8.27; // import "hardhat/console.sol"; interface IMultiSig { struct Transaction { address proposer; address to; uint256 value; // bytes data; TODO: Complex functions string description; uint256 noOfConfirmations; bool status; } function submitProposal(address _to, uint256 _value, string memory _description) external returns (bool); function confirmProposal(uint256 _proposalIndex) external returns (bool); function revokeConfirmedProposal(uint256 _proposalIndex) external returns (bool); function executeProposal(uint _proposalIndex) external returns (bool); function fundWallet() external payable; function getAllProposals() external returns (Transaction[] memory); function getOwners() external returns (address[] memory); function getTimeCreated() external returns (uint256); function getDeployer() external returns (address); } ================================================ FILE: 12-Core-MultiSig/hardhat.config.js ================================================ require("@nomicfoundation/hardhat-toolbox"); require("dotenv").config(); /** @type import('hardhat/config').HardhatUserConfig */ const PRIVATE_KEY = process.env.PRIVATE_KEY; module.exports = { solidity: "0.8.27", networks: { localhost: { url: "http://127.0.0.1:8545/", // accounts: Thanks hardhat! chainId: 31337, allowUnlimitedContractSize: true, }, core: { url: 'https://rpc.test2.btcs.network', accounts: [PRIVATE_KEY], chainId: 1114, }, }, }; ================================================ FILE: 12-Core-MultiSig/ignition/modules/Lock.js ================================================ // This setup uses Hardhat Ignition to manage smart contract deployments. // Learn more about it at https://hardhat.org/ignition const { buildModule } = require("@nomicfoundation/hardhat-ignition/modules"); const JAN_1ST_2030 = 1893456000; const ONE_GWEI = 1_000_000_000n; module.exports = buildModule("LockModule", (m) => { const unlockTime = m.getParameter("unlockTime", JAN_1ST_2030); const lockedAmount = m.getParameter("lockedAmount", ONE_GWEI); const lock = m.contract("Lock", [unlockTime], { value: lockedAmount, }); return { lock }; }); ================================================ FILE: 12-Core-MultiSig/package.json ================================================ { "name": "reuse", "version": "1.0.0", "main": "index.js", "scripts": { "test": "echo \"Error: no test specified\" && exit 1" }, "author": "", "license": "ISC", "description": "", "devDependencies": { "@nomicfoundation/hardhat-chai-matchers": "^2.0.8", "@nomicfoundation/hardhat-ethers": "^3.0.8", "@nomicfoundation/hardhat-ignition-ethers": "^0.15.9", "@nomicfoundation/hardhat-network-helpers": "^1.0.12", "@nomicfoundation/hardhat-toolbox": "^5.0.0", "@nomicfoundation/hardhat-verify": "^2.0.12", "@typechain/ethers-v6": "^0.5.1", "@typechain/hardhat": "^9.1.0", "@types/chai": "^4.3.20", "@types/mocha": "^10.0.10", "chai": "^4.5.0", "ethers": "^6.13.5", "hardhat": "^2.22.15", "hardhat-gas-reporter": "^1.0.10", "install": "^0.13.0", "npm": "^11.0.0", "solidity-coverage": "^0.8.14", "ts-node": "^10.9.2", "typechain": "^8.3.2", "typescript": "^5.7.3" }, "dependencies": { "dotenv": "^16.4.7" } } ================================================ FILE: 12-Core-MultiSig/scripts/deploy-multisig.js ================================================ const hre = require("hardhat"); const { loadFixture } = require("@nomicfoundation/hardhat-toolbox/network-helpers"); async function main() { const FactoryContract = await hre.ethers.getContractFactory("MultiSigFactory"); const factoryContract = await FactoryContract.deploy("0x650ADf6aA8b4e5764273E7f2001B2A3f792859a5"); console.log("Storage contract deployed to:", factoryContract.target); // const array = ["0xe7f1725E7734CE288F8367e1Bb143E90bb3F0512", "0xF5c87bFCE1999d3E48f0407E43F0Db10394A4B37", "0xF5c87bFCE1999d3E48f0407E43F0Db10394A4B37"] // const addresses = "0xF5c87bFCE1999d3E48f0407E43F0Db10394A4B37"; // const functionName = "transfer"; // console.log(factoryContract.target) // await factoryContract.createMultiSig(array, 1); // console.log("here"); // const getAddress = await factoryContract.getAllDeployedMultiSigs(); // console.log("here"); // const deployer = await factoryContract.getDeployer(getAddress[0]); // console.log(deployer); // // console.log(encodedData) // console.log(getAddress[0], array[1]); // // const value = await multiSigContract.connect(getAddress[0]).fundWallet({value: ethers.parseEther("3")}); // // console.log(value); // const address = await factoryContract.submitTransaction(getAddress[0], array[0], ethers.parseEther("2"), "Pay to Dave"); // const getProposals = await factoryContract.getAllProposals(getAddress[0]); // console.log(getProposals); // await factoryContract.confirmTransaction(getAddress[0], 0); // const wallets = await factoryContract.getDeployersWallets(); // console.log(wallets) // const proposalExecuted1 = await factoryContract.getAllProposals(getAddress[0]); // console.log(proposalExecuted1) // // await factoryContract.executeTransaction(getAddress[0], 0); // // const proposalExecuted = await factoryContract.getAllProposals(getAddress[0]); // // console.log(proposalExecuted) } // We recommend this pattern to be able to use async/await everywhere // and properly handle errors. main().catch((error) => { console.error(error); process.exitCode = 1; }); // CORE: PoolFactory contract deployed to: 0x5Ac64F5DA22B25559C7D7522b4B2BB7e2012F382 ================================================ FILE: 12-Core-MultiSig/test/Lock.js ================================================ const { time, loadFixture, } = require("@nomicfoundation/hardhat-toolbox/network-helpers"); const { anyValue } = require("@nomicfoundation/hardhat-chai-matchers/withArgs"); const { expect } = require("chai"); describe("Lock", function () { // We define a fixture to reuse the same setup in every test. // We use loadFixture to run this setup once, snapshot that state, // and reset Hardhat Network to that snapshot in every test. async function deployDefi() { // Contracts are deployed using the first signer/account by default const [owner, otherAccount] = await ethers.getSigners(); console.log("Heyyyyyyy"); // const Lock = await ethers.getContractFactory("Lock"); // const lock = await Lock.deploy(unlockTime, { value: lockedAmount }); const array = ["0xF5c87bFCE1999d3E48f0407E43F0Db10394A4B37", "0xF5c87bFCE1999d3E48f0407E43F0Db10394A4B37", "0xF5c87bFCE1999d3E48f0407E43F0Db10394A4B37"] // const multiSig = await ethers.getContractFactory("MultiSig"); // const multiSigContract = await multiSig.deploy(array, 2); const multiSigFactory = await ethers.getContractFactory("MultiSigFactory"); const factoryContract = await multiSigFactory.deploy("0xF5c87bFCE1999d3E48f0407E43F0Db10394A4B37"); return { factoryContract }; } describe("Deployment", function () { it("Checks if it creates pair", async function () { const { factoryContract } = await loadFixture(deployDefi); const array = ["0xF5c87bFCE1999d3E48f0407E43F0Db10394A4B37", "0xF5c87bFCE1999d3E48f0407E43F0Db10394A4B37", "0xF5c87bFCE1999d3E48f0407E43F0Db10394A4B37"] const pair = await factoryContract.createMultiSig(array, 2); const pairs = await factoryContract.createMultiSig(array, 2); const getAddress = await factoryContract.getAllDeployedMultiSigs(); const address = await factoryContract.getOwners(getAddress[0]); console.log(address); }); it("Checks if it creates pair", async function () { const { multiSigContract } = await loadFixture(deployDefi); // const getAddress = await multisigContract.getAllDeployedMultiSigs(); const address = await multiSigContract.submitProposal("0xF5c87bFCE1999d3E48f0407E43F0Db10394A4B37", 20000000," 0x736f6d6520737472696e67"); console.log(address); }); it.only("Checks if it creates pair", async function () { const { factoryContract, multiSigContract } = await loadFixture(deployDefi); const array = ["0xe7f1725E7734CE288F8367e1Bb143E90bb3F0512", "0xF5c87bFCE1999d3E48f0407E43F0Db10394A4B37", "0xF5c87bFCE1999d3E48f0407E43F0Db10394A4B37"] const addresses = "0xF5c87bFCE1999d3E48f0407E43F0Db10394A4B37"; const functionName = "transfer"; console.log(factoryContract.target) const pair = await factoryContract.createMultiSig(array, 1); const pairs = await factoryContract.createMultiSig( array, 1); const getAddress = await factoryContract.getAllDeployedMultiSigs(); const deployer = await factoryContract.getDeployer(getAddress[0]); console.log(deployer); // console.log(encodedData) console.log(getAddress[0], array[1]); // const value = await multiSigContract.connect(getAddress[0]).fundWallet({value: ethers.parseEther("3")}); // console.log(value); const address = await factoryContract.submitTransaction(getAddress[0], array[0], ethers.parseEther("2"), "Pay to Dave"); const getProposals = await factoryContract.getAllProposals(getAddress[0]); console.log(getProposals); await factoryContract.confirmTransaction(getAddress[0], 0); const wallets = await factoryContract.getDeployersWallets(); console.log(wallets) const proposalExecuted1 = await factoryContract.getAllProposals(getAddress[0]); console.log(proposalExecuted1) // await factoryContract.executeTransaction(getAddress[0], 0); // const proposalExecuted = await factoryContract.getAllProposals(getAddress[0]); // console.log(proposalExecuted) }); // it("checks if its adds liquidity", async function () { // const { factoryContract, cherryContract, appleContract, owner, liquidityContract} = await loadFixture(deployDefi); // console.log("heyy"); // await cherryContract.mint(owner.address, ethers.parseEther("10")); // await appleContract.mint(owner.address, ethers.parseEther("10")); // await cherryContract.approve(liquidityContract.target, ethers.parseEther("10")); // await appleContract.approve(liquidityContract.target, ethers.parseEther("10")); // console.log(await appleContract.balanceOf(owner.address)); // console.log(await cherryContract.balanceOf(owner.address)); // const pair = await liquidityContract.addLiquidity( // cherryContract.target, // appleContract.target, // ethers.parseEther("1.5"), // ethers.parseEther("1"), // ethers.parseEther(".9"), // ethers.parseEther("1.3") // ); // console.log(pair); // }); // it("Should receive and store the funds to lock", async function () { // const { lock, lockedAmount } = await loadFixture( // deployOneYearLockFixture // ); // expect(await ethers.provider.getBalance(lock.target)).to.equal( // lockedAmount // ); // }); }); }); ================================================ FILE: 13-Core-Test-Token-Faucet/.gitignore ================================================ node_modules .env # Hardhat files /cache /artifacts # TypeChain files /typechain /typechain-types # solidity-coverage files /coverage /coverage.json # Hardhat Ignition default folder for deployments against a local node ignition/deployments/chain-31337 ================================================ FILE: 13-Core-Test-Token-Faucet/Frontend/.eslintrc.json ================================================ { "extends": ["next/core-web-vitals", "next/typescript"], "rules": { "@typescript-eslint/no-explicit-any": "off", // Allow `any` type "@typescript-eslint/no-unused-vars": "off", // Disable unused variables check "@typescript-eslint/no-unused-expressions": "off", // Disable unused expressions check "react-hooks/exhaustive-deps": "off", // Suppress missing dependency warnings in useEffect "@next/next/no-img-element": "off", "react/no-unescaped-entities": "off" } } ================================================ FILE: 13-Core-Test-Token-Faucet/Frontend/.gitignore ================================================ # See https://help.github.com/articles/ignoring-files/ for more about ignoring files. # dependencies /node_modules /.pnp .pnp.* .yarn/* !.yarn/patches !.yarn/plugins !.yarn/releases !.yarn/versions # testing /coverage # next.js /.next/ /out/ # production /build # misc .DS_Store *.pem # debug npm-debug.log* yarn-debug.log* yarn-error.log* # env files (can opt-in for commiting if needed) .env* # vercel .vercel # typescript *.tsbuildinfo next-env.d.ts ================================================ FILE: 13-Core-Test-Token-Faucet/Frontend/README.md ================================================ This is a [Next.js](https://nextjs.org) project bootstrapped with [`create-next-app`](https://nextjs.org/docs/app/api-reference/cli/create-next-app). ## Getting Started First, run the development server: ```bash npm run dev # or yarn dev # or pnpm dev # or bun dev ``` Open [http://localhost:3000](http://localhost:3000) with your browser to see the result. You can start editing the page by modifying `app/page.tsx`. The page auto-updates as you edit the file. This project uses [`next/font`](https://nextjs.org/docs/app/building-your-application/optimizing/fonts) to automatically optimize and load [Geist](https://vercel.com/font), a new font family for Vercel. ## Learn More To learn more about Next.js, take a look at the following resources: - [Next.js Documentation](https://nextjs.org/docs) - learn about Next.js features and API. - [Learn Next.js](https://nextjs.org/learn) - an interactive Next.js tutorial. You can check out [the Next.js GitHub repository](https://github.com/vercel/next.js) - your feedback and contributions are welcome! ## Deploy on Vercel The easiest way to deploy your Next.js app is to use the [Vercel Platform](https://vercel.com/new?utm_medium=default-template&filter=next.js&utm_source=create-next-app&utm_campaign=create-next-app-readme) from the creators of Next.js. Check out our [Next.js deployment documentation](https://nextjs.org/docs/app/building-your-application/deploying) for more details. ================================================ FILE: 13-Core-Test-Token-Faucet/Frontend/app/globals.css ================================================ @tailwind base; @tailwind components; @tailwind utilities; body { font-family: Arial, Helvetica, sans-serif; } @layer base { :root { --background: 0 0% 100%; --foreground: 240 10% 3.9%; --card: 0 0% 100%; --card-foreground: 240 10% 3.9%; --popover: 0 0% 100%; --popover-foreground: 240 10% 3.9%; --primary: 240 5.9% 10%; --primary-foreground: 0 0% 98%; --secondary: 240 4.8% 95.9%; --secondary-foreground: 240 5.9% 10%; --muted: 240 4.8% 95.9%; --muted-foreground: 240 3.8% 46.1%; --accent: 240 4.8% 95.9%; --accent-foreground: 240 5.9% 10%; --destructive: 0 84.2% 60.2%; --destructive-foreground: 0 0% 98%; --border: 240 5.9% 90%; --input: 240 5.9% 90%; --ring: 240 10% 3.9%; --chart-1: 12 76% 61%; --chart-2: 173 58% 39%; --chart-3: 197 37% 24%; --chart-4: 43 74% 66%; --chart-5: 27 87% 67%; --radius: 0.5rem; } .dark { --background: 240 10% 3.9%; --foreground: 0 0% 98%; --card: 240 10% 3.9%; --card-foreground: 0 0% 98%; --popover: 240 10% 3.9%; --popover-foreground: 0 0% 98%; --primary: 0 0% 98%; --primary-foreground: 240 5.9% 10%; --secondary: 240 3.7% 15.9%; --secondary-foreground: 0 0% 98%; --muted: 240 3.7% 15.9%; --muted-foreground: 240 5% 64.9%; --accent: 240 3.7% 15.9%; --accent-foreground: 0 0% 98%; --destructive: 0 62.8% 30.6%; --destructive-foreground: 0 0% 98%; --border: 240 3.7% 15.9%; --input: 240 3.7% 15.9%; --ring: 240 4.9% 83.9%; --chart-1: 220 70% 50%; --chart-2: 160 60% 45%; --chart-3: 30 80% 55%; --chart-4: 280 65% 60%; --chart-5: 340 75% 55%; } } @layer base { * { @apply border-border; } body { @apply bg-background text-foreground; } } ================================================ FILE: 13-Core-Test-Token-Faucet/Frontend/app/layout.tsx ================================================ import type { Metadata } from "next"; import localFont from "next/font/local"; import "./globals.css"; const geistSans = localFont({ src: "./fonts/GeistVF.woff", variable: "--font-geist-sans", weight: "100 900", }); const geistMono = localFont({ src: "./fonts/GeistMonoVF.woff", variable: "--font-geist-mono", weight: "100 900", }); export const metadata: Metadata = { title: "Create Next App", description: "Generated by create next app", }; export default function RootLayout({ children, }: Readonly<{ children: React.ReactNode; }>) { return ( {children} ); } ================================================ FILE: 13-Core-Test-Token-Faucet/Frontend/app/page.tsx ================================================ "use client" import { useState } from "react" import { Navbar } from "@/components/navbar" import { NetworkModal } from "@/components/network-modal" import { TokenSelector } from "@/components/token-selector" import { Toaster } from "@/components/ui/toaster" import { toast } from "@/hooks/use-toast" import { ethers } from "ethers" export default function FaucetPage() { const [isConnected, setIsConnected] = useState(false) const [walletAddress, setWalletAddress] = useState("") const [signer, setSigner] = useState(null) const [provider, setProvider] = useState(null) const [isCorrectNetwork, setIsCorrectNetwork] = useState(true) const [showNetworkModal, setShowNetworkModal] = useState(false) const handleWalletConnect = async () => { try { // Placeholder wallet connection logic // In production, integrate with Wagmi or Ethers.js if (!(window as any).ethereum) { toast({ title: "Wallet not found", description: "Please install MetaMask or another Web3 wallet", variant: "destructive", }) return } const provider = new ethers.BrowserProvider((window as any).ethereum) const accounts = await provider.send("eth_requestAccounts", []) const network = await provider.getNetwork() const signee = await provider.getSigner(); setProvider(provider) // setAccount(accounts[0]) setSigner(signee) // setChainId(Number(network.chainId)) // const accounts = await window.ethereum.request({ method: 'eth_requestAccounts' }) setWalletAddress(accounts[0]) // setWalletAddress("0x1234567890123456789012345678901234567890") // Placeholder setIsConnected(true) // Simulate network check const isOnCoreTestnet = Number(network.chainId) == 1114 // Higher chance of correct network for demo setIsCorrectNetwork(isOnCoreTestnet) if (!isOnCoreTestnet) { setShowNetworkModal(true) } } catch (error) { console.error("Failed to connect wallet:", error) } } const handleWalletDisconnect = () => { setWalletAddress("") setIsConnected(false) setIsCorrectNetwork(true) } const handleNetworkSwitch = async () => { try { // Placeholder network switching logic // In production: call wallet_switchEthereumChain or wallet_addEthereumChain // await window.ethereum.request({ // method: 'wallet_switchEthereumChain', // params: [{ chainId: '0x45a' }], // Core Testnet // }) setIsCorrectNetwork(true) setShowNetworkModal(false) } catch (error) { console.error("Failed to switch network:", error) } } return (

Core Testnet Faucet

Connect your wallet and mint test tokens directly to your address on Core Testnet. Perfect for development and testing.

{!isConnected ? (

Connect Your Wallet

Connect your wallet to start minting test tokens directly to your address

) : !isCorrectNetwork ? (

Wrong Network

Please switch to Core Testnet to use the faucet

) : (
)} {/* Information section */}

How it works

1

Connect Wallet

Connect your wallet to Core Testnet

2

Select & Mint

Choose token and amount to mint

3

Receive Tokens

Tokens minted directly to your wallet

{/* Additional info */}

More Tokens Coming Soon

We're constantly adding new test tokens to support your development needs. Stay tuned for more ERC20 test tokens on Core Testnet.

setShowNetworkModal(false)} onSwitch={handleNetworkSwitch} />
) } ================================================ FILE: 13-Core-Test-Token-Faucet/Frontend/components/badge.tsx ================================================ import type * as React from "react" import { cva, type VariantProps } from "class-variance-authority" import { cn } from "@/lib/utils" const badgeVariants = cva( "inline-flex items-center rounded-full border px-2.5 py-0.5 text-xs font-semibold transition-colors focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2", { variants: { variant: { default: "border-transparent bg-primary text-primary-foreground hover:bg-primary/80", secondary: "border-transparent bg-secondary text-secondary-foreground hover:bg-secondary/80", destructive: "border-transparent bg-destructive text-destructive-foreground hover:bg-destructive/80", outline: "text-foreground", }, }, defaultVariants: { variant: "default", }, }, ) export interface BadgeProps extends React.HTMLAttributes, VariantProps {} function Badge({ className, variant, ...props }: BadgeProps) { return
} export { Badge, badgeVariants } ================================================ FILE: 13-Core-Test-Token-Faucet/Frontend/components/dialog.tsx ================================================ "use client" import * as React from "react" import * as DialogPrimitive from "@radix-ui/react-dialog" import { X } from "lucide-react" import { cn } from "@/lib/utils" const Dialog = DialogPrimitive.Root const DialogTrigger = DialogPrimitive.Trigger const DialogPortal = DialogPrimitive.Portal const DialogClose = DialogPrimitive.Close const DialogOverlay = React.forwardRef< React.ElementRef, React.ComponentPropsWithoutRef >(({ className, ...props }, ref) => ( )) DialogOverlay.displayName = DialogPrimitive.Overlay.displayName const DialogContent = React.forwardRef< React.ElementRef, React.ComponentPropsWithoutRef >(({ className, children, ...props }, ref) => ( {children} Close )) DialogContent.displayName = DialogPrimitive.Content.displayName const DialogHeader = ({ className, ...props }: React.HTMLAttributes) => (
) DialogHeader.displayName = "DialogHeader" const DialogFooter = ({ className, ...props }: React.HTMLAttributes) => (
) DialogFooter.displayName = "DialogFooter" const DialogTitle = React.forwardRef< React.ElementRef, React.ComponentPropsWithoutRef >(({ className, ...props }, ref) => ( )) DialogTitle.displayName = DialogPrimitive.Title.displayName const DialogDescription = React.forwardRef< React.ElementRef, React.ComponentPropsWithoutRef >(({ className, ...props }, ref) => ( )) DialogDescription.displayName = DialogPrimitive.Description.displayName export { Dialog, DialogPortal, DialogOverlay, DialogClose, DialogTrigger, DialogContent, DialogHeader, DialogFooter, DialogTitle, DialogDescription, } ================================================ FILE: 13-Core-Test-Token-Faucet/Frontend/components/dropdown-menu.tsx ================================================ "use client" import * as React from "react" import * as DropdownMenuPrimitive from "@radix-ui/react-dropdown-menu" import { Check, ChevronRight, Circle } from "lucide-react" import { cn } from "@/lib/utils" const DropdownMenu = DropdownMenuPrimitive.Root const DropdownMenuTrigger = DropdownMenuPrimitive.Trigger const DropdownMenuGroup = DropdownMenuPrimitive.Group const DropdownMenuPortal = DropdownMenuPrimitive.Portal const DropdownMenuSub = DropdownMenuPrimitive.Sub const DropdownMenuRadioGroup = DropdownMenuPrimitive.RadioGroup const DropdownMenuSubTrigger = React.forwardRef< React.ElementRef, React.ComponentPropsWithoutRef & { inset?: boolean } >(({ className, inset, children, ...props }, ref) => ( {children} )) DropdownMenuSubTrigger.displayName = DropdownMenuPrimitive.SubTrigger.displayName const DropdownMenuSubContent = React.forwardRef< React.ElementRef, React.ComponentPropsWithoutRef >(({ className, ...props }, ref) => ( )) DropdownMenuSubContent.displayName = DropdownMenuPrimitive.SubContent.displayName const DropdownMenuContent = React.forwardRef< React.ElementRef, React.ComponentPropsWithoutRef >(({ className, sideOffset = 4, ...props }, ref) => ( )) DropdownMenuContent.displayName = DropdownMenuPrimitive.Content.displayName const DropdownMenuItem = React.forwardRef< React.ElementRef, React.ComponentPropsWithoutRef & { inset?: boolean } >(({ className, inset, ...props }, ref) => ( )) DropdownMenuItem.displayName = DropdownMenuPrimitive.Item.displayName const DropdownMenuCheckboxItem = React.forwardRef< React.ElementRef, React.ComponentPropsWithoutRef >(({ className, children, checked, ...props }, ref) => ( {children} )) DropdownMenuCheckboxItem.displayName = DropdownMenuPrimitive.CheckboxItem.displayName const DropdownMenuRadioItem = React.forwardRef< React.ElementRef, React.ComponentPropsWithoutRef >(({ className, children, ...props }, ref) => ( {children} )) DropdownMenuRadioItem.displayName = DropdownMenuPrimitive.RadioItem.displayName const DropdownMenuLabel = React.forwardRef< React.ElementRef, React.ComponentPropsWithoutRef & { inset?: boolean } >(({ className, inset, ...props }, ref) => ( )) DropdownMenuLabel.displayName = DropdownMenuPrimitive.Label.displayName const DropdownMenuSeparator = React.forwardRef< React.ElementRef, React.ComponentPropsWithoutRef >(({ className, ...props }, ref) => ( )) DropdownMenuSeparator.displayName = DropdownMenuPrimitive.Separator.displayName const DropdownMenuShortcut = ({ className, ...props }: React.HTMLAttributes) => { return } DropdownMenuShortcut.displayName = "DropdownMenuShortcut" export { DropdownMenu, DropdownMenuTrigger, DropdownMenuContent, DropdownMenuItem, DropdownMenuCheckboxItem, DropdownMenuRadioItem, DropdownMenuLabel, DropdownMenuSeparator, DropdownMenuShortcut, DropdownMenuGroup, DropdownMenuPortal, DropdownMenuSub, DropdownMenuSubContent, DropdownMenuSubTrigger, DropdownMenuRadioGroup, } ================================================ FILE: 13-Core-Test-Token-Faucet/Frontend/components/navbar.tsx ================================================ "use client" import { Button } from "@/components/ui/button" import { Badge } from "@/components/ui/badge" import { ChevronDown, LogOut } from "lucide-react" import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuSeparator, DropdownMenuTrigger, } from "@/components/ui/dropdown-menu" interface NavbarProps { isConnected: boolean walletAddress: string onConnect: () => void onDisconnect: () => void isCorrectNetwork: boolean } export function Navbar({ isConnected, walletAddress, onConnect, onDisconnect, isCorrectNetwork }: NavbarProps) { const formatAddress = (address: string) => { if (!address || address.length < 10) return address return `${address.slice(0, 6)}...${address.slice(-4)}` } const copyAddress = async () => { try { await navigator.clipboard.writeText(walletAddress) } catch (error) { console.error("Failed to copy address:", error) } } return ( ) } ================================================ FILE: 13-Core-Test-Token-Faucet/Frontend/components/network-modal.tsx ================================================ "use client" import { Dialog, DialogContent, DialogDescription, DialogHeader, DialogTitle } from "@/components/ui/dialog" import { Button } from "@/components/ui/button" interface NetworkModalProps { isOpen: boolean onClose: () => void onSwitch: () => void } export function NetworkModal({ isOpen, onClose, onSwitch }: NetworkModalProps) { return ( Wrong Network Please switch to Core Testnet to use this faucet.
) } ================================================ FILE: 13-Core-Test-Token-Faucet/Frontend/components/select.tsx ================================================ "use client" import * as React from "react" import * as SelectPrimitive from "@radix-ui/react-select" import { Check, ChevronDown, ChevronUp } from "lucide-react" import { cn } from "@/lib/utils" const Select = SelectPrimitive.Root const SelectGroup = SelectPrimitive.Group const SelectValue = SelectPrimitive.Value const SelectTrigger = React.forwardRef< React.ElementRef, React.ComponentPropsWithoutRef >(({ className, children, ...props }, ref) => ( span]:line-clamp-1", className, )} {...props} > {children} )) SelectTrigger.displayName = SelectPrimitive.Trigger.displayName const SelectScrollUpButton = React.forwardRef< React.ElementRef, React.ComponentPropsWithoutRef >(({ className, ...props }, ref) => ( )) SelectScrollUpButton.displayName = SelectPrimitive.ScrollUpButton.displayName const SelectScrollDownButton = React.forwardRef< React.ElementRef, React.ComponentPropsWithoutRef >(({ className, ...props }, ref) => ( )) SelectScrollDownButton.displayName = SelectPrimitive.ScrollDownButton.displayName const SelectContent = React.forwardRef< React.ElementRef, React.ComponentPropsWithoutRef >(({ className, children, position = "popper", ...props }, ref) => ( {children} )) SelectContent.displayName = SelectPrimitive.Content.displayName const SelectLabel = React.forwardRef< React.ElementRef, React.ComponentPropsWithoutRef >(({ className, ...props }, ref) => ( )) SelectLabel.displayName = SelectPrimitive.Label.displayName const SelectItem = React.forwardRef< React.ElementRef, React.ComponentPropsWithoutRef >(({ className, children, ...props }, ref) => ( {children} )) SelectItem.displayName = SelectPrimitive.Item.displayName const SelectSeparator = React.forwardRef< React.ElementRef, React.ComponentPropsWithoutRef >(({ className, ...props }, ref) => ( )) SelectSeparator.displayName = SelectPrimitive.Separator.displayName export { Select, SelectGroup, SelectValue, SelectTrigger, SelectContent, SelectLabel, SelectItem, SelectSeparator, SelectScrollUpButton, SelectScrollDownButton, } ================================================ FILE: 13-Core-Test-Token-Faucet/Frontend/components/toast.tsx ================================================ "use client" import * as React from "react" import * as ToastPrimitives from "@radix-ui/react-toast" import { cva, type VariantProps } from "class-variance-authority" import { X } from "lucide-react" import { cn } from "@/lib/utils" const ToastProvider = ToastPrimitives.Provider const ToastViewport = React.forwardRef< React.ElementRef, React.ComponentPropsWithoutRef >(({ className, ...props }, ref) => ( )) ToastViewport.displayName = ToastPrimitives.Viewport.displayName const toastVariants = cva( "group pointer-events-auto relative flex w-full items-center justify-between space-x-4 overflow-hidden rounded-md border p-6 pr-8 shadow-lg transition-all data-[swipe=cancel]:translate-x-0 data-[swipe=end]:translate-x-[var(--radix-toast-swipe-end-x)] data-[swipe=move]:translate-x-[var(--radix-toast-swipe-move-x)] data-[swipe=move]:transition-none data-[state=open]:animate-in data-[state=closed]:animate-out data-[swipe=end]:animate-out data-[state=closed]:fade-out-80 data-[state=closed]:slide-out-to-right-full data-[state=open]:slide-in-from-top-full data-[state=open]:sm:slide-in-from-bottom-full", { variants: { variant: { default: "border bg-background text-foreground", destructive: "destructive border-destructive bg-destructive text-destructive-foreground", }, }, defaultVariants: { variant: "default", }, }, ) const Toast = React.forwardRef< React.ElementRef, React.ComponentPropsWithoutRef & VariantProps >(({ className, variant, ...props }, ref) => { return }) Toast.displayName = ToastPrimitives.Root.displayName const ToastAction = React.forwardRef< React.ElementRef, React.ComponentPropsWithoutRef >(({ className, ...props }, ref) => ( )) ToastAction.displayName = ToastPrimitives.Action.displayName const ToastClose = React.forwardRef< React.ElementRef, React.ComponentPropsWithoutRef >(({ className, ...props }, ref) => ( )) ToastClose.displayName = ToastPrimitives.Close.displayName const ToastTitle = React.forwardRef< React.ElementRef, React.ComponentPropsWithoutRef >(({ className, ...props }, ref) => ( )) ToastTitle.displayName = ToastPrimitives.Title.displayName const ToastDescription = React.forwardRef< React.ElementRef, React.ComponentPropsWithoutRef >(({ className, ...props }, ref) => ( )) ToastDescription.displayName = ToastPrimitives.Description.displayName type ToastProps = React.ComponentPropsWithoutRef type ToastActionElement = React.ReactElement export { type ToastProps, type ToastActionElement, ToastProvider, ToastViewport, Toast, ToastTitle, ToastDescription, ToastClose, ToastAction, } ================================================ FILE: 13-Core-Test-Token-Faucet/Frontend/components/toaster.tsx ================================================ "use client" import { useToast } from "@/hooks/use-toast" import { Toast, ToastClose, ToastDescription, ToastProvider, ToastTitle, ToastViewport } from "@/components/ui/toast" export function Toaster() { const { toasts } = useToast() return ( {toasts.map(({ id, title, description, action, ...props }) => (
{title && {title}} {description && {description}}
{action}
))}
) } ================================================ FILE: 13-Core-Test-Token-Faucet/Frontend/components/token-selector.tsx ================================================ "use client" import { useState } from "react" import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card" import { Button } from "@/components/ui/button" import { Input } from "@/components/ui/input" import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select" import { Badge } from "@/components/ui/badge" import { Copy, Check, ExternalLink, Wallet } from "lucide-react" import { useToast } from "@/hooks/use-toast" import { tokens, type Token } from "@/lib/tokens" import { CONTRACT_ABI } from "@/lib/constants" import {ethers} from "ethers" interface TokenSelectorProps { walletAddress: string signer: ethers.JsonRpcSigner | null } export function TokenSelector({ walletAddress, signer }: TokenSelectorProps) { const [selectedToken, setSelectedToken] = useState(null) const [amount, setAmount] = useState("1000") const [isMinting, setIsMinting] = useState(false) const [copied, setCopied] = useState(false) const { toast } = useToast() const handleTokenSelect = (tokenSymbol: string) => { const token = tokens.find((t) => t.symbol === tokenSymbol) if (token) { setSelectedToken(token) } } const handleCopyAddress = async () => { if (!selectedToken) return try { await navigator.clipboard.writeText(selectedToken.address) setCopied(true) toast({ title: "Address Copied! 📋", description: "Contract address copied to clipboard", duration: 2000, }) setTimeout(() => setCopied(false), 2000) } catch (error) { toast({ title: "Copy Failed", description: "Failed to copy address to clipboard", variant: "destructive", }) } } const handleMint = async () => { if (!selectedToken || !amount || !walletAddress) return setIsMinting(true) try { // Placeholder for smart contract interaction // In production: call the mint function on the token contract const contract = new ethers.Contract(selectedToken.address, CONTRACT_ABI, signer) const tx = await contract.mint(walletAddress, ethers.parseUnits(amount, 18)) await tx.wait() toast({ title: "Mint Successful! 🎉", description: `Successfully minted ${amount} ${selectedToken.symbol} to your wallet`, duration: 5000, }) // Reset amount to default setAmount("1000") } catch (error) { toast({ title: "Mint Failed", description: "Transaction failed. Please try again.", variant: "destructive", }) } finally { setIsMinting(false) } } const formatAddress = (address: string) => { return `${address.slice(0, 8)}...${address.slice(-8)}` } return ( Mint Test Tokens

Select a token and amount to mint directly to your connected wallet

{/* Connected Wallet Display */}

Connected Wallet

{walletAddress}

{/* Token Selector */}
{/* Selected Token Details */} {selectedToken && (
{selectedToken.symbol.charAt(0)}

{selectedToken.name}

{selectedToken.symbol} {selectedToken.decimals} decimals
{/* Contract Address */}
{selectedToken.address}
)} {/* Amount Input */} {selectedToken && (
setAmount(e.target.value)} placeholder="Enter amount" className="text-lg font-semibold h-14" min="1" max={selectedToken.maxMint.toString()} />
Minimum: 1 {selectedToken.symbol} Maximum: {selectedToken.maxMint.toLocaleString()} {selectedToken.symbol}
)} {/* Quick Amount Buttons */} {selectedToken && (
{[100, 1000, 5000, selectedToken.maxMint].map((quickAmount) => ( ))}
)} {/* Mint Button */} {selectedToken && ( )} {/* Transaction Info */} {selectedToken && (

Transaction Details

• Tokens will be minted directly to your connected wallet
• You'll need to confirm the transaction in your wallet
• Gas fees will be paid in tCORE (Core Testnet native token)
• Transaction will appear in your wallet after confirmation

)}
) } ================================================ FILE: 13-Core-Test-Token-Faucet/Frontend/components/ui/badge.tsx ================================================ import * as React from "react" import { cva, type VariantProps } from "class-variance-authority" import { cn } from "@/lib/utils" const badgeVariants = cva( "inline-flex items-center rounded-md border px-2.5 py-0.5 text-xs font-semibold transition-colors focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2", { variants: { variant: { default: "border-transparent bg-primary text-primary-foreground shadow hover:bg-primary/80", secondary: "border-transparent bg-secondary text-secondary-foreground hover:bg-secondary/80", destructive: "border-transparent bg-destructive text-destructive-foreground shadow hover:bg-destructive/80", outline: "text-foreground", }, }, defaultVariants: { variant: "default", }, } ) export interface BadgeProps extends React.HTMLAttributes, VariantProps {} function Badge({ className, variant, ...props }: BadgeProps) { return (
) } export { Badge, badgeVariants } ================================================ FILE: 13-Core-Test-Token-Faucet/Frontend/components/ui/button.tsx ================================================ import * as React from "react" import { Slot } from "@radix-ui/react-slot" import { cva, type VariantProps } from "class-variance-authority" import { cn } from "@/lib/utils" const buttonVariants = cva( "inline-flex items-center justify-center gap-2 whitespace-nowrap rounded-md text-sm font-medium transition-colors focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring disabled:pointer-events-none disabled:opacity-50 [&_svg]:pointer-events-none [&_svg]:size-4 [&_svg]:shrink-0", { variants: { variant: { default: "bg-primary text-primary-foreground shadow hover:bg-primary/90", destructive: "bg-destructive text-destructive-foreground shadow-sm hover:bg-destructive/90", outline: "border border-input bg-background shadow-sm hover:bg-accent hover:text-accent-foreground", secondary: "bg-secondary text-secondary-foreground shadow-sm hover:bg-secondary/80", ghost: "hover:bg-accent hover:text-accent-foreground", link: "text-primary underline-offset-4 hover:underline", }, size: { default: "h-9 px-4 py-2", sm: "h-8 rounded-md px-3 text-xs", lg: "h-10 rounded-md px-8", icon: "h-9 w-9", }, }, defaultVariants: { variant: "default", size: "default", }, } ) export interface ButtonProps extends React.ButtonHTMLAttributes, VariantProps { asChild?: boolean } const Button = React.forwardRef( ({ className, variant, size, asChild = false, ...props }, ref) => { const Comp = asChild ? Slot : "button" return ( ) } ) Button.displayName = "Button" export { Button, buttonVariants } ================================================ FILE: 13-Core-Test-Token-Faucet/Frontend/components/ui/card.tsx ================================================ import * as React from "react" import { cn } from "@/lib/utils" const Card = React.forwardRef< HTMLDivElement, React.HTMLAttributes >(({ className, ...props }, ref) => (
)) Card.displayName = "Card" const CardHeader = React.forwardRef< HTMLDivElement, React.HTMLAttributes >(({ className, ...props }, ref) => (
)) CardHeader.displayName = "CardHeader" const CardTitle = React.forwardRef< HTMLDivElement, React.HTMLAttributes >(({ className, ...props }, ref) => (
)) CardTitle.displayName = "CardTitle" const CardDescription = React.forwardRef< HTMLDivElement, React.HTMLAttributes >(({ className, ...props }, ref) => (
)) CardDescription.displayName = "CardDescription" const CardContent = React.forwardRef< HTMLDivElement, React.HTMLAttributes >(({ className, ...props }, ref) => (
)) CardContent.displayName = "CardContent" const CardFooter = React.forwardRef< HTMLDivElement, React.HTMLAttributes >(({ className, ...props }, ref) => (
)) CardFooter.displayName = "CardFooter" export { Card, CardHeader, CardFooter, CardTitle, CardDescription, CardContent } ================================================ FILE: 13-Core-Test-Token-Faucet/Frontend/components/ui/dialog.tsx ================================================ "use client" import * as React from "react" import * as DialogPrimitive from "@radix-ui/react-dialog" import { X } from "lucide-react" import { cn } from "@/lib/utils" const Dialog = DialogPrimitive.Root const DialogTrigger = DialogPrimitive.Trigger const DialogPortal = DialogPrimitive.Portal const DialogClose = DialogPrimitive.Close const DialogOverlay = React.forwardRef< React.ElementRef, React.ComponentPropsWithoutRef >(({ className, ...props }, ref) => ( )) DialogOverlay.displayName = DialogPrimitive.Overlay.displayName const DialogContent = React.forwardRef< React.ElementRef, React.ComponentPropsWithoutRef >(({ className, children, ...props }, ref) => ( {children} Close )) DialogContent.displayName = DialogPrimitive.Content.displayName const DialogHeader = ({ className, ...props }: React.HTMLAttributes) => (
) DialogHeader.displayName = "DialogHeader" const DialogFooter = ({ className, ...props }: React.HTMLAttributes) => (
) DialogFooter.displayName = "DialogFooter" const DialogTitle = React.forwardRef< React.ElementRef, React.ComponentPropsWithoutRef >(({ className, ...props }, ref) => ( )) DialogTitle.displayName = DialogPrimitive.Title.displayName const DialogDescription = React.forwardRef< React.ElementRef, React.ComponentPropsWithoutRef >(({ className, ...props }, ref) => ( )) DialogDescription.displayName = DialogPrimitive.Description.displayName export { Dialog, DialogPortal, DialogOverlay, DialogTrigger, DialogClose, DialogContent, DialogHeader, DialogFooter, DialogTitle, DialogDescription, } ================================================ FILE: 13-Core-Test-Token-Faucet/Frontend/components/ui/dropdown-menu.tsx ================================================ "use client" import * as React from "react" import * as DropdownMenuPrimitive from "@radix-ui/react-dropdown-menu" import { Check, ChevronRight, Circle } from "lucide-react" import { cn } from "@/lib/utils" const DropdownMenu = DropdownMenuPrimitive.Root const DropdownMenuTrigger = DropdownMenuPrimitive.Trigger const DropdownMenuGroup = DropdownMenuPrimitive.Group const DropdownMenuPortal = DropdownMenuPrimitive.Portal const DropdownMenuSub = DropdownMenuPrimitive.Sub const DropdownMenuRadioGroup = DropdownMenuPrimitive.RadioGroup const DropdownMenuSubTrigger = React.forwardRef< React.ElementRef, React.ComponentPropsWithoutRef & { inset?: boolean } >(({ className, inset, children, ...props }, ref) => ( {children} )) DropdownMenuSubTrigger.displayName = DropdownMenuPrimitive.SubTrigger.displayName const DropdownMenuSubContent = React.forwardRef< React.ElementRef, React.ComponentPropsWithoutRef >(({ className, ...props }, ref) => ( )) DropdownMenuSubContent.displayName = DropdownMenuPrimitive.SubContent.displayName const DropdownMenuContent = React.forwardRef< React.ElementRef, React.ComponentPropsWithoutRef >(({ className, sideOffset = 4, ...props }, ref) => ( )) DropdownMenuContent.displayName = DropdownMenuPrimitive.Content.displayName const DropdownMenuItem = React.forwardRef< React.ElementRef, React.ComponentPropsWithoutRef & { inset?: boolean } >(({ className, inset, ...props }, ref) => ( svg]:size-4 [&>svg]:shrink-0", inset && "pl-8", className )} {...props} /> )) DropdownMenuItem.displayName = DropdownMenuPrimitive.Item.displayName const DropdownMenuCheckboxItem = React.forwardRef< React.ElementRef, React.ComponentPropsWithoutRef >(({ className, children, checked, ...props }, ref) => ( {children} )) DropdownMenuCheckboxItem.displayName = DropdownMenuPrimitive.CheckboxItem.displayName const DropdownMenuRadioItem = React.forwardRef< React.ElementRef, React.ComponentPropsWithoutRef >(({ className, children, ...props }, ref) => ( {children} )) DropdownMenuRadioItem.displayName = DropdownMenuPrimitive.RadioItem.displayName const DropdownMenuLabel = React.forwardRef< React.ElementRef, React.ComponentPropsWithoutRef & { inset?: boolean } >(({ className, inset, ...props }, ref) => ( )) DropdownMenuLabel.displayName = DropdownMenuPrimitive.Label.displayName const DropdownMenuSeparator = React.forwardRef< React.ElementRef, React.ComponentPropsWithoutRef >(({ className, ...props }, ref) => ( )) DropdownMenuSeparator.displayName = DropdownMenuPrimitive.Separator.displayName const DropdownMenuShortcut = ({ className, ...props }: React.HTMLAttributes) => { return ( ) } DropdownMenuShortcut.displayName = "DropdownMenuShortcut" export { DropdownMenu, DropdownMenuTrigger, DropdownMenuContent, DropdownMenuItem, DropdownMenuCheckboxItem, DropdownMenuRadioItem, DropdownMenuLabel, DropdownMenuSeparator, DropdownMenuShortcut, DropdownMenuGroup, DropdownMenuPortal, DropdownMenuSub, DropdownMenuSubContent, DropdownMenuSubTrigger, DropdownMenuRadioGroup, } ================================================ FILE: 13-Core-Test-Token-Faucet/Frontend/components/ui/input.tsx ================================================ import * as React from "react" import { cn } from "@/lib/utils" const Input = React.forwardRef>( ({ className, type, ...props }, ref) => { return ( ) } ) Input.displayName = "Input" export { Input } ================================================ FILE: 13-Core-Test-Token-Faucet/Frontend/components/ui/select.tsx ================================================ "use client" import * as React from "react" import * as SelectPrimitive from "@radix-ui/react-select" import { Check, ChevronDown, ChevronUp } from "lucide-react" import { cn } from "@/lib/utils" const Select = SelectPrimitive.Root const SelectGroup = SelectPrimitive.Group const SelectValue = SelectPrimitive.Value const SelectTrigger = React.forwardRef< React.ElementRef, React.ComponentPropsWithoutRef >(({ className, children, ...props }, ref) => ( span]:line-clamp-1", className )} {...props} > {children} )) SelectTrigger.displayName = SelectPrimitive.Trigger.displayName const SelectScrollUpButton = React.forwardRef< React.ElementRef, React.ComponentPropsWithoutRef >(({ className, ...props }, ref) => ( )) SelectScrollUpButton.displayName = SelectPrimitive.ScrollUpButton.displayName const SelectScrollDownButton = React.forwardRef< React.ElementRef, React.ComponentPropsWithoutRef >(({ className, ...props }, ref) => ( )) SelectScrollDownButton.displayName = SelectPrimitive.ScrollDownButton.displayName const SelectContent = React.forwardRef< React.ElementRef, React.ComponentPropsWithoutRef >(({ className, children, position = "popper", ...props }, ref) => ( {children} )) SelectContent.displayName = SelectPrimitive.Content.displayName const SelectLabel = React.forwardRef< React.ElementRef, React.ComponentPropsWithoutRef >(({ className, ...props }, ref) => ( )) SelectLabel.displayName = SelectPrimitive.Label.displayName const SelectItem = React.forwardRef< React.ElementRef, React.ComponentPropsWithoutRef >(({ className, children, ...props }, ref) => ( {children} )) SelectItem.displayName = SelectPrimitive.Item.displayName const SelectSeparator = React.forwardRef< React.ElementRef, React.ComponentPropsWithoutRef >(({ className, ...props }, ref) => ( )) SelectSeparator.displayName = SelectPrimitive.Separator.displayName export { Select, SelectGroup, SelectValue, SelectTrigger, SelectContent, SelectLabel, SelectItem, SelectSeparator, SelectScrollUpButton, SelectScrollDownButton, } ================================================ FILE: 13-Core-Test-Token-Faucet/Frontend/components/ui/toast.tsx ================================================ "use client" import * as React from "react" import * as ToastPrimitives from "@radix-ui/react-toast" import { cva, type VariantProps } from "class-variance-authority" import { X } from "lucide-react" import { cn } from "@/lib/utils" const ToastProvider = ToastPrimitives.Provider const ToastViewport = React.forwardRef< React.ElementRef, React.ComponentPropsWithoutRef >(({ className, ...props }, ref) => ( )) ToastViewport.displayName = ToastPrimitives.Viewport.displayName const toastVariants = cva( "group pointer-events-auto relative flex w-full items-center justify-between space-x-2 overflow-hidden rounded-md border p-4 pr-6 shadow-lg transition-all data-[swipe=cancel]:translate-x-0 data-[swipe=end]:translate-x-[var(--radix-toast-swipe-end-x)] data-[swipe=move]:translate-x-[var(--radix-toast-swipe-move-x)] data-[swipe=move]:transition-none data-[state=open]:animate-in data-[state=closed]:animate-out data-[swipe=end]:animate-out data-[state=closed]:fade-out-80 data-[state=closed]:slide-out-to-right-full data-[state=open]:slide-in-from-top-full data-[state=open]:sm:slide-in-from-bottom-full", { variants: { variant: { default: "border bg-background text-foreground", destructive: "destructive group border-destructive bg-destructive text-destructive-foreground", }, }, defaultVariants: { variant: "default", }, } ) const Toast = React.forwardRef< React.ElementRef, React.ComponentPropsWithoutRef & VariantProps >(({ className, variant, ...props }, ref) => { return ( ) }) Toast.displayName = ToastPrimitives.Root.displayName const ToastAction = React.forwardRef< React.ElementRef, React.ComponentPropsWithoutRef >(({ className, ...props }, ref) => ( )) ToastAction.displayName = ToastPrimitives.Action.displayName const ToastClose = React.forwardRef< React.ElementRef, React.ComponentPropsWithoutRef >(({ className, ...props }, ref) => ( )) ToastClose.displayName = ToastPrimitives.Close.displayName const ToastTitle = React.forwardRef< React.ElementRef, React.ComponentPropsWithoutRef >(({ className, ...props }, ref) => ( )) ToastTitle.displayName = ToastPrimitives.Title.displayName const ToastDescription = React.forwardRef< React.ElementRef, React.ComponentPropsWithoutRef >(({ className, ...props }, ref) => ( )) ToastDescription.displayName = ToastPrimitives.Description.displayName type ToastProps = React.ComponentPropsWithoutRef type ToastActionElement = React.ReactElement export { type ToastProps, type ToastActionElement, ToastProvider, ToastViewport, Toast, ToastTitle, ToastDescription, ToastClose, ToastAction, } ================================================ FILE: 13-Core-Test-Token-Faucet/Frontend/components/ui/toaster.tsx ================================================ "use client" import { useToast } from "@/hooks/use-toast" import { Toast, ToastClose, ToastDescription, ToastProvider, ToastTitle, ToastViewport, } from "@/components/ui/toast" export function Toaster() { const { toasts } = useToast() return ( {toasts.map(function ({ id, title, description, action, ...props }) { return (
{title && {title}} {description && ( {description} )}
{action}
) })}
) } ================================================ FILE: 13-Core-Test-Token-Faucet/Frontend/components.json ================================================ { "$schema": "https://ui.shadcn.com/schema.json", "style": "new-york", "rsc": true, "tsx": true, "tailwind": { "config": "tailwind.config.ts", "css": "app/globals.css", "baseColor": "zinc", "cssVariables": true, "prefix": "" }, "aliases": { "components": "@/components", "utils": "@/lib/utils", "ui": "@/components/ui", "lib": "@/lib", "hooks": "@/hooks" }, "iconLibrary": "lucide" } ================================================ FILE: 13-Core-Test-Token-Faucet/Frontend/hooks/use-toast.ts ================================================ "use client" // Inspired by react-hot-toast library import * as React from "react" import type { ToastActionElement, ToastProps, } from "@/components/ui/toast" const TOAST_LIMIT = 1 const TOAST_REMOVE_DELAY = 1000000 type ToasterToast = ToastProps & { id: string title?: React.ReactNode description?: React.ReactNode action?: ToastActionElement } const actionTypes = { ADD_TOAST: "ADD_TOAST", UPDATE_TOAST: "UPDATE_TOAST", DISMISS_TOAST: "DISMISS_TOAST", REMOVE_TOAST: "REMOVE_TOAST", } as const let count = 0 function genId() { count = (count + 1) % Number.MAX_SAFE_INTEGER return count.toString() } type ActionType = typeof actionTypes type Action = | { type: ActionType["ADD_TOAST"] toast: ToasterToast } | { type: ActionType["UPDATE_TOAST"] toast: Partial } | { type: ActionType["DISMISS_TOAST"] toastId?: ToasterToast["id"] } | { type: ActionType["REMOVE_TOAST"] toastId?: ToasterToast["id"] } interface State { toasts: ToasterToast[] } const toastTimeouts = new Map>() const addToRemoveQueue = (toastId: string) => { if (toastTimeouts.has(toastId)) { return } const timeout = setTimeout(() => { toastTimeouts.delete(toastId) dispatch({ type: "REMOVE_TOAST", toastId: toastId, }) }, TOAST_REMOVE_DELAY) toastTimeouts.set(toastId, timeout) } export const reducer = (state: State, action: Action): State => { switch (action.type) { case "ADD_TOAST": return { ...state, toasts: [action.toast, ...state.toasts].slice(0, TOAST_LIMIT), } case "UPDATE_TOAST": return { ...state, toasts: state.toasts.map((t) => t.id === action.toast.id ? { ...t, ...action.toast } : t ), } case "DISMISS_TOAST": { const { toastId } = action // ! Side effects ! - This could be extracted into a dismissToast() action, // but I'll keep it here for simplicity if (toastId) { addToRemoveQueue(toastId) } else { state.toasts.forEach((toast) => { addToRemoveQueue(toast.id) }) } return { ...state, toasts: state.toasts.map((t) => t.id === toastId || toastId === undefined ? { ...t, open: false, } : t ), } } case "REMOVE_TOAST": if (action.toastId === undefined) { return { ...state, toasts: [], } } return { ...state, toasts: state.toasts.filter((t) => t.id !== action.toastId), } } } const listeners: Array<(state: State) => void> = [] let memoryState: State = { toasts: [] } function dispatch(action: Action) { memoryState = reducer(memoryState, action) listeners.forEach((listener) => { listener(memoryState) }) } type Toast = Omit function toast({ ...props }: Toast) { const id = genId() const update = (props: ToasterToast) => dispatch({ type: "UPDATE_TOAST", toast: { ...props, id }, }) const dismiss = () => dispatch({ type: "DISMISS_TOAST", toastId: id }) dispatch({ type: "ADD_TOAST", toast: { ...props, id, open: true, onOpenChange: (open) => { if (!open) dismiss() }, }, }) return { id: id, dismiss, update, } } function useToast() { const [state, setState] = React.useState(memoryState) React.useEffect(() => { listeners.push(setState) return () => { const index = listeners.indexOf(setState) if (index > -1) { listeners.splice(index, 1) } } }, [state]) return { ...state, toast, dismiss: (toastId?: string) => dispatch({ type: "DISMISS_TOAST", toastId }), } } export { useToast, toast } ================================================ FILE: 13-Core-Test-Token-Faucet/Frontend/lib/constants.ts ================================================ export const CORE_TESTNET = { chainId: "0x45a", // 1114 in hex chainIdDecimal: 1114, name: "Core Testnet", nativeCurrency: { name: "tCORE", symbol: "tCORE", decimals: 18, }, rpcUrls: ["https://rpc.test2.btcs.network"], blockExplorerUrls: ["https://scan.test2.btcs.network"], } export const SUPPORTED_CHAINS = [CORE_TESTNET.chainIdDecimal] export const CONTRACT_ABI = [ { "inputs": [], "stateMutability": "nonpayable", "type": "constructor" }, { "inputs": [ { "internalType": "address", "name": "spender", "type": "address" }, { "internalType": "uint256", "name": "allowance", "type": "uint256" }, { "internalType": "uint256", "name": "needed", "type": "uint256" } ], "name": "ERC20InsufficientAllowance", "type": "error" }, { "inputs": [ { "internalType": "address", "name": "sender", "type": "address" }, { "internalType": "uint256", "name": "balance", "type": "uint256" }, { "internalType": "uint256", "name": "needed", "type": "uint256" } ], "name": "ERC20InsufficientBalance", "type": "error" }, { "inputs": [ { "internalType": "address", "name": "approver", "type": "address" } ], "name": "ERC20InvalidApprover", "type": "error" }, { "inputs": [ { "internalType": "address", "name": "receiver", "type": "address" } ], "name": "ERC20InvalidReceiver", "type": "error" }, { "inputs": [ { "internalType": "address", "name": "sender", "type": "address" } ], "name": "ERC20InvalidSender", "type": "error" }, { "inputs": [ { "internalType": "address", "name": "spender", "type": "address" } ], "name": "ERC20InvalidSpender", "type": "error" }, { "anonymous": false, "inputs": [ { "indexed": true, "internalType": "address", "name": "owner", "type": "address" }, { "indexed": true, "internalType": "address", "name": "spender", "type": "address" }, { "indexed": false, "internalType": "uint256", "name": "value", "type": "uint256" } ], "name": "Approval", "type": "event" }, { "anonymous": false, "inputs": [ { "indexed": true, "internalType": "address", "name": "from", "type": "address" }, { "indexed": true, "internalType": "address", "name": "to", "type": "address" }, { "indexed": false, "internalType": "uint256", "name": "value", "type": "uint256" } ], "name": "Transfer", "type": "event" }, { "inputs": [ { "internalType": "address", "name": "owner", "type": "address" }, { "internalType": "address", "name": "spender", "type": "address" } ], "name": "allowance", "outputs": [ { "internalType": "uint256", "name": "", "type": "uint256" } ], "stateMutability": "view", "type": "function" }, { "inputs": [ { "internalType": "address", "name": "spender", "type": "address" }, { "internalType": "uint256", "name": "value", "type": "uint256" } ], "name": "approve", "outputs": [ { "internalType": "bool", "name": "", "type": "bool" } ], "stateMutability": "nonpayable", "type": "function" }, { "inputs": [ { "internalType": "address", "name": "account", "type": "address" } ], "name": "balanceOf", "outputs": [ { "internalType": "uint256", "name": "", "type": "uint256" } ], "stateMutability": "view", "type": "function" }, { "inputs": [], "name": "decimals", "outputs": [ { "internalType": "uint8", "name": "", "type": "uint8" } ], "stateMutability": "view", "type": "function" }, { "inputs": [], "name": "i_owner", "outputs": [ { "internalType": "address", "name": "", "type": "address" } ], "stateMutability": "view", "type": "function" }, { "inputs": [ { "internalType": "address", "name": "_receipient", "type": "address" }, { "internalType": "uint256", "name": "_amount", "type": "uint256" } ], "name": "mint", "outputs": [], "stateMutability": "nonpayable", "type": "function" }, { "inputs": [], "name": "name", "outputs": [ { "internalType": "string", "name": "", "type": "string" } ], "stateMutability": "view", "type": "function" }, { "inputs": [], "name": "symbol", "outputs": [ { "internalType": "string", "name": "", "type": "string" } ], "stateMutability": "view", "type": "function" }, { "inputs": [], "name": "totalSupply", "outputs": [ { "internalType": "uint256", "name": "", "type": "uint256" } ], "stateMutability": "view", "type": "function" }, { "inputs": [ { "internalType": "address", "name": "to", "type": "address" }, { "internalType": "uint256", "name": "value", "type": "uint256" } ], "name": "transfer", "outputs": [ { "internalType": "bool", "name": "", "type": "bool" } ], "stateMutability": "nonpayable", "type": "function" }, { "inputs": [ { "internalType": "address", "name": "from", "type": "address" }, { "internalType": "address", "name": "to", "type": "address" }, { "internalType": "uint256", "name": "value", "type": "uint256" } ], "name": "transferFrom", "outputs": [ { "internalType": "bool", "name": "", "type": "bool" } ], "stateMutability": "nonpayable", "type": "function" } ] ================================================ FILE: 13-Core-Test-Token-Faucet/Frontend/lib/tokens.ts ================================================ export interface Token { name: string symbol: string address: string decimals: number color: string maxMint: number } export const tokens: Token[] = [ { name: "Test DAI", symbol: "tDAI", address: "0x7a8eF80C8136862fc7402E8Cfb9Cd1ea9c3BFB4B", // Placeholder address decimals: 18, color: "#F5AC37", maxMint: 10000, }, { name: "Test USDC", symbol: "tUSDC", address: "0x2bE22845339D49E9b296AbA5462D78F2e929DB05", // Placeholder address decimals: 6, color: "#2775CA", maxMint: 10000, }, { name: "Test USDT", symbol: "tUSDT", address: "0x367a5a4C14214BfE67d3C00A97F19Cecd2cf9e87", // Placeholder address decimals: 6, color: "#26A17B", maxMint: 10000, }, ] // Easy to extend with more tokens: // { // name: "Test WETH", // symbol: "tWETH", // address: "0x4567890123456789012345678901234567890123", // decimals: 18, // color: "#627EEA", // maxMint: 100 // } ================================================ FILE: 13-Core-Test-Token-Faucet/Frontend/lib/utils.ts ================================================ import { clsx, type ClassValue } from "clsx" import { twMerge } from "tailwind-merge" export function cn(...inputs: ClassValue[]) { return twMerge(clsx(inputs)) } ================================================ FILE: 13-Core-Test-Token-Faucet/Frontend/next.config.js ================================================ /** @type {import('next').NextConfig} */ const nextConfig = { }; module.exports = nextConfig; ================================================ FILE: 13-Core-Test-Token-Faucet/Frontend/next.config.mjs ================================================ const nextConfig = { reactStrictMode: true, swcMinify: true, eslint: { ignoreDuringBuilds: true, }, typescript: { ignoreBuildErrors: true, }, images: { unoptimized: true, }, } export default nextConfig ================================================ FILE: 13-Core-Test-Token-Faucet/Frontend/package.json ================================================ { "name": "reusable", "version": "0.1.0", "private": true, "scripts": { "dev": "next dev", "build": "next build", "start": "next start", "lint": "next lint" }, "dependencies": { "@radix-ui/react-dialog": "1.1.14", "@radix-ui/react-dropdown-menu": "2.1.15", "@radix-ui/react-select": "2.2.5", "@radix-ui/react-slot": "1.2.3", "@radix-ui/react-toast": "1.2.14", "class-variance-authority": "0.7.0", "clsx": "2.1.1", "ethers": "6.15.0", "lucide-react": "0.454.0", "next": "15.0.2", "react": "19.0.0-rc-02c0e824-20241028", "react-dom": "19.0.0-rc-02c0e824-20241028", "tailwind-merge": "2.5.4", "tailwindcss-animate": "1.0.7" }, "devDependencies": { "@types/node": "^20", "@types/react": "^18", "@types/react-dom": "^18", "eslint": "^8", "eslint-config-next": "15.0.2", "postcss": "^8", "tailwindcss": "^3.4.1", "typescript": "^5" } } ================================================ FILE: 13-Core-Test-Token-Faucet/Frontend/postcss.config.js ================================================ // postcss.config.js module.exports = { plugins: { tailwindcss: {} } } ================================================ FILE: 13-Core-Test-Token-Faucet/Frontend/postcss.config.mjs ================================================ /** @type {import('postcss-load-config').Config} */ const config = { plugins: { tailwindcss: {}, }, }; export default config; ================================================ FILE: 13-Core-Test-Token-Faucet/Frontend/tailwind.config.ts ================================================ import type { Config } from "tailwindcss"; const config: Config = { darkMode: ["class"], content: [ "./pages/**/*.{js,ts,jsx,tsx,mdx}", "./components/**/*.{js,ts,jsx,tsx,mdx}", "./app/**/*.{js,ts,jsx,tsx,mdx}", ], theme: { extend: { colors: { background: 'hsl(var(--background))', foreground: 'hsl(var(--foreground))', card: { DEFAULT: 'hsl(var(--card))', foreground: 'hsl(var(--card-foreground))' }, popover: { DEFAULT: 'hsl(var(--popover))', foreground: 'hsl(var(--popover-foreground))' }, primary: { DEFAULT: 'hsl(var(--primary))', foreground: 'hsl(var(--primary-foreground))' }, secondary: { DEFAULT: 'hsl(var(--secondary))', foreground: 'hsl(var(--secondary-foreground))' }, muted: { DEFAULT: 'hsl(var(--muted))', foreground: 'hsl(var(--muted-foreground))' }, accent: { DEFAULT: 'hsl(var(--accent))', foreground: 'hsl(var(--accent-foreground))' }, destructive: { DEFAULT: 'hsl(var(--destructive))', foreground: 'hsl(var(--destructive-foreground))' }, border: 'hsl(var(--border))', input: 'hsl(var(--input))', ring: 'hsl(var(--ring))', chart: { '1': 'hsl(var(--chart-1))', '2': 'hsl(var(--chart-2))', '3': 'hsl(var(--chart-3))', '4': 'hsl(var(--chart-4))', '5': 'hsl(var(--chart-5))' } }, borderRadius: { lg: 'var(--radius)', md: 'calc(var(--radius) - 2px)', sm: 'calc(var(--radius) - 4px)' } } }, plugins: [require("tailwindcss-animate")], }; export default config; ================================================ FILE: 13-Core-Test-Token-Faucet/Frontend/tsconfig.json ================================================ { "compilerOptions": { "target": "ES2017", "lib": ["dom", "dom.iterable", "esnext"], "allowJs": true, "skipLibCheck": true, "strict": true, "noEmit": true, "esModuleInterop": true, "module": "esnext", "moduleResolution": "bundler", "resolveJsonModule": true, "isolatedModules": true, "jsx": "preserve", "incremental": true, "plugins": [ { "name": "next" } ], "paths": { "@/*": ["./*"] } }, "include": ["next-env.d.ts", "**/*.ts", "**/*.tsx", ".next/types/**/*.ts", "next.config.js"], "exclude": ["node_modules"] } ================================================ FILE: 13-Core-Test-Token-Faucet/README.md ================================================ # 🪙 Core Token Test Faucet This is a simple ERC-20 token faucet built to distribute testnet versions of tokens for various test dApps on the **Core Testnet**. ## 📌 Deployed Token Addresses | Token | Contract Address | | ---------------------- | -------------------------------------------- | | **Lending DAI Token** | `0x7a8eF80C8136862fc7402E8Cfb9Cd1ea9c3BFB4B` | | **Lending USDT Token** | `0x367a5a4C14214BfE67d3C00A97F19Cecd2cf9e87` | | **Lending USDC Token** | `0x2bE22845339D49E9b296AbA5462D78F2e929DB05` | > ⚠️ These tokens are for **Core Testnet** use only and have no real-world value. --- ## 💡 About the Project Tokens available for request: - ✅ Lending DAI - ✅ Lending USDT - ✅ Lending USDC --- ## 🔗 Live Faucet Interface 👉 [**https://token-faucet-sandy.vercel.app/**](https://token-faucet-sandy.vercel.app/) --- ## 🔧 How It Works 1. Connect your wallet to the **Core Testnet** 2. Visit the faucet interface 3. Choose the token you want to receive 4. Click **Request Tokens** and confirm the transaction Each wallet can request tokens based on optional rate limits (e.g., per hour/day) to prevent abuse. --- ## 🛠 Tech Stack - **Solidity** (`^0.8.x`) - **OpenZeppelin** ERC20 contracts - **Hardhat** for smart contract development - **Nextjs + Ethers.js** frontend _(optional)_ - **Core Blockchain Testnet** --- ## 📁 Local Development ### 1. Clone the repo ```bash git clone https://github.com/coredao-org/dapp-tutorial cd app-tutorial/13-Core-Test-Token-Faucet ``` ### 2. Install dependencies ```bash npm install ``` ### 3. Compile the contracts ```bash npx hardhat compile ``` ### 4. Deploy to Core Testnet ```bash npx hardhat run scripts/deploy.js --network core ``` ### 5. Launch the Frontend ```bash cd frontend npm install npm run dev ``` --- ### ✅ Requesting Test Tokens 1. Connect your wallet to the **Core Testnet** 2. Visit your localhost link. 3. Click on any token's **Request** button to receive test tokens directly to your wallet --- ## 🌐 Core Testnet Configuration You can manually add Core Testnet to MetaMask using: ``` Network Name: Core Testnet Chain ID: 1114 Currency Symbol: tCORE RPC URL: https://rpc.test2.btcs.network Block Explorer: https://scan.test2.btcs.network ``` --- ## 🤝 Contributing Feel free to fork the repo, suggest features, and open pull requests and add your test tokens to the faucet. Every contribution helps improve the faucet! --- ## 📢 Disclaimer This faucet is intended for **testing and development only**. Tokens dispensed have **no real monetary value** and should **not be used on mainnet**. ================================================ FILE: 13-Core-Test-Token-Faucet/contracts/tDai.sol ================================================ // SPDX-License-Identifier: MIT pragma solidity ^0.8.22; import {ERC20} from "@openzeppelin/contracts/token/ERC20/ERC20.sol"; error LendingDAIToken__NotOwner(); contract LendingDAIToken is ERC20 { address public immutable i_owner; constructor() ERC20("LendingDAIToken", "DAI") { i_owner = msg.sender; } modifier onlyOwner() { if(i_owner != msg.sender) revert LendingDAIToken__NotOwner(); _; } function mint(address _receipient, uint256 _amount) public { _mint(_receipient, _amount); } } ================================================ FILE: 13-Core-Test-Token-Faucet/contracts/tUSD.sol ================================================ // SPDX-License-Identifier: MIT pragma solidity ^0.8.22; import {ERC20} from "@openzeppelin/contracts/token/ERC20/ERC20.sol"; error LendingUSDToken__NotOwner(); contract LendingUSDToken is ERC20 { address public immutable i_owner; constructor() ERC20("LendingUSDToken", "USD") { i_owner = msg.sender; } modifier onlyOwner() { if(i_owner != msg.sender) revert LendingUSDToken__NotOwner(); _; } function mint(address _receipient, uint256 _amount) public { _mint(_receipient, _amount); } } ================================================ FILE: 13-Core-Test-Token-Faucet/contracts/tUSDC.sol ================================================ // SPDX-License-Identifier: MIT pragma solidity ^0.8.22; import {ERC20} from "@openzeppelin/contracts/token/ERC20/ERC20.sol"; error LendingUSDCToken__NotOwner(); contract LendingUSDCToken is ERC20 { address public immutable i_owner; constructor() ERC20("LendingUSDCToken", "USDC") { i_owner = msg.sender; } modifier onlyOwner() { if(i_owner != msg.sender) revert LendingUSDCToken__NotOwner(); _; } function mint(address _receipient, uint256 _amount) public { _mint(_receipient, _amount); } } ================================================ FILE: 13-Core-Test-Token-Faucet/hardhat.config.js ================================================ require("@nomicfoundation/hardhat-toolbox"); require("dotenv").config(); /** @type import('hardhat/config').HardhatUserConfig */ const PRIVATE_KEY = process.env.PRIVATE_KEY; module.exports = { solidity: "0.8.27", networks: { localhost: { url: "http://127.0.0.1:8545/", // accounts: Thanks hardhat! chainId: 31337, allowUnlimitedContractSize: true, }, core: { url: "https://rpc.test2.btcs.network", accounts: [PRIVATE_KEY], chainId: 1114, }, }, }; ================================================ FILE: 13-Core-Test-Token-Faucet/ignition/modules/Lock.js ================================================ // This setup uses Hardhat Ignition to manage smart contract deployments. // Learn more about it at https://hardhat.org/ignition const { buildModule } = require("@nomicfoundation/hardhat-ignition/modules"); const JAN_1ST_2030 = 1893456000; const ONE_GWEI = 1_000_000_000n; module.exports = buildModule("LockModule", (m) => { const unlockTime = m.getParameter("unlockTime", JAN_1ST_2030); const lockedAmount = m.getParameter("lockedAmount", ONE_GWEI); const lock = m.contract("Lock", [unlockTime], { value: lockedAmount, }); return { lock }; }); ================================================ FILE: 13-Core-Test-Token-Faucet/package.json ================================================ { "name": "reuse", "version": "1.0.0", "main": "index.js", "scripts": { "test": "echo \"Error: no test specified\" && exit 1" }, "author": "", "license": "ISC", "description": "", "devDependencies": { "@nomicfoundation/hardhat-toolbox": "^5.0.0", "hardhat": "^2.22.15" }, "dependencies": { "@openzeppelin/contracts": "^5.3.0", "dotenv": "^17.2.0" } } ================================================ FILE: 13-Core-Test-Token-Faucet/scripts/deploy.js ================================================ const hre = require("hardhat"); const { loadFixture } = require("@nomicfoundation/hardhat-toolbox/network-helpers"); async function main() { const FEE = ethers.parseUnits("0.01", 18); const LendingDAIToken = await hre.ethers.getContractFactory("LendingDAIToken"); const LendingDAI = await LendingDAIToken.deploy(); console.log("Lending Dai Token deployed to:", LendingDAI.target); const LendingUSDToken = await hre.ethers.getContractFactory("LendingUSDToken"); const LendingUSD = await LendingUSDToken.deploy(); console.log("Lending USDT oken deployed to:", LendingUSD.target); const LendingUSDCToken = await hre.ethers.getContractFactory("LendingUSDCToken"); const LendingUSDC = await LendingUSDCToken.deploy(); console.log("Lending USDC Token deployed to:", LendingUSDC.target); } // We recommend this pattern to be able to use async/await everywhere // and properly handle errors. main().catch((error) => { console.error(error); process.exitCode = 1; }); // CORE: CoreLend contract deployed to: 0x5Ac64F5DA22B25559C7D7522b4B2BB7e2012F382 ================================================ FILE: 13-Core-Test-Token-Faucet/test/Lock.js ================================================ const { time, loadFixture, } = require("@nomicfoundation/hardhat-toolbox/network-helpers"); const { anyValue } = require("@nomicfoundation/hardhat-chai-matchers/withArgs"); const { expect } = require("chai"); describe("Lock", function () { // We define a fixture to reuse the same setup in every test. // We use loadFixture to run this setup once, snapshot that state, // and reset Hardhat Network to that snapshot in every test. async function deployOneYearLockFixture() { const ONE_YEAR_IN_SECS = 365 * 24 * 60 * 60; const ONE_GWEI = 1_000_000_000; const lockedAmount = ONE_GWEI; const unlockTime = (await time.latest()) + ONE_YEAR_IN_SECS; // Contracts are deployed using the first signer/account by default const [owner, otherAccount] = await ethers.getSigners(); const Lock = await ethers.getContractFactory("Lock"); const lock = await Lock.deploy(unlockTime, { value: lockedAmount }); return { lock, unlockTime, lockedAmount, owner, otherAccount }; } describe("Deployment", function () { it("Should set the right unlockTime", async function () { const { lock, unlockTime } = await loadFixture(deployOneYearLockFixture); expect(await lock.unlockTime()).to.equal(unlockTime); }); it("Should set the right owner", async function () { const { lock, owner } = await loadFixture(deployOneYearLockFixture); expect(await lock.owner()).to.equal(owner.address); }); it("Should receive and store the funds to lock", async function () { const { lock, lockedAmount } = await loadFixture( deployOneYearLockFixture ); expect(await ethers.provider.getBalance(lock.target)).to.equal( lockedAmount ); }); it("Should fail if the unlockTime is not in the future", async function () { // We don't use the fixture here because we want a different deployment const latestTime = await time.latest(); const Lock = await ethers.getContractFactory("Lock"); await expect(Lock.deploy(latestTime, { value: 1 })).to.be.revertedWith( "Unlock time should be in the future" ); }); }); describe("Withdrawals", function () { describe("Validations", function () { it("Should revert with the right error if called too soon", async function () { const { lock } = await loadFixture(deployOneYearLockFixture); await expect(lock.withdraw()).to.be.revertedWith( "You can't withdraw yet" ); }); it("Should revert with the right error if called from another account", async function () { const { lock, unlockTime, otherAccount } = await loadFixture( deployOneYearLockFixture ); // We can increase the time in Hardhat Network await time.increaseTo(unlockTime); // We use lock.connect() to send a transaction from another account await expect(lock.connect(otherAccount).withdraw()).to.be.revertedWith( "You aren't the owner" ); }); it("Shouldn't fail if the unlockTime has arrived and the owner calls it", async function () { const { lock, unlockTime } = await loadFixture( deployOneYearLockFixture ); // Transactions are sent using the first signer by default await time.increaseTo(unlockTime); await expect(lock.withdraw()).not.to.be.reverted; }); }); describe("Events", function () { it("Should emit an event on withdrawals", async function () { const { lock, unlockTime, lockedAmount } = await loadFixture( deployOneYearLockFixture ); await time.increaseTo(unlockTime); await expect(lock.withdraw()) .to.emit(lock, "Withdrawal") .withArgs(lockedAmount, anyValue); // We accept any value as `when` arg }); }); describe("Transfers", function () { it("Should transfer the funds to the owner", async function () { const { lock, unlockTime, lockedAmount, owner } = await loadFixture( deployOneYearLockFixture ); await time.increaseTo(unlockTime); await expect(lock.withdraw()).to.changeEtherBalances( [owner, lock], [lockedAmount, -lockedAmount] ); }); }); }); }); ================================================ FILE: 14-Corelend/.gitignore ================================================ node_modules .env # Hardhat files /cache /artifacts # TypeChain files /typechain /typechain-types # solidity-coverage files /coverage /coverage.json # Hardhat Ignition default folder for deployments against a local node ignition/deployments/chain-31337 ================================================ FILE: 14-Corelend/Frontend/.eslintrc.json ================================================ { "extends": ["next/core-web-vitals", "next/typescript"] } ================================================ FILE: 14-Corelend/Frontend/.gitignore ================================================ # See https://help.github.com/articles/ignoring-files/ for more about ignoring files. # dependencies /node_modules /.pnp .pnp.* .yarn/* !.yarn/patches !.yarn/plugins !.yarn/releases !.yarn/versions # testing /coverage # next.js /.next/ /out/ # production /build # misc .DS_Store *.pem # debug npm-debug.log* yarn-debug.log* yarn-error.log* # env files (can opt-in for commiting if needed) .env* # vercel .vercel # typescript *.tsbuildinfo next-env.d.ts ================================================ FILE: 14-Corelend/Frontend/README.md ================================================ This is a [Next.js](https://nextjs.org) project bootstrapped with [`create-next-app`](https://nextjs.org/docs/app/api-reference/cli/create-next-app). ## Getting Started First, run the development server: ```bash npm run dev # or yarn dev # or pnpm dev # or bun dev ``` Open [http://localhost:3000](http://localhost:3000) with your browser to see the result. You can start editing the page by modifying `app/page.tsx`. The page auto-updates as you edit the file. This project uses [`next/font`](https://nextjs.org/docs/app/building-your-application/optimizing/fonts) to automatically optimize and load [Geist](https://vercel.com/font), a new font family for Vercel. ## Learn More To learn more about Next.js, take a look at the following resources: - [Next.js Documentation](https://nextjs.org/docs) - learn about Next.js features and API. - [Learn Next.js](https://nextjs.org/learn) - an interactive Next.js tutorial. You can check out [the Next.js GitHub repository](https://github.com/vercel/next.js) - your feedback and contributions are welcome! ## Deploy on Vercel The easiest way to deploy your Next.js app is to use the [Vercel Platform](https://vercel.com/new?utm_medium=default-template&filter=next.js&utm_source=create-next-app&utm_campaign=create-next-app-readme) from the creators of Next.js. Check out our [Next.js deployment documentation](https://nextjs.org/docs/app/building-your-application/deploying) for more details. ================================================ FILE: 14-Corelend/Frontend/app/borrow/page.tsx ================================================ "use client" import { useState } from "react" import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card" import { Button } from "@/components/ui/button" import { Input } from "@/components/ui/input" import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select" import { Badge } from "@/components/ui/badge" import { useWallet } from "@/components/wallet-provider" import { useToast } from "@/hooks/use-toast" import { AlertTriangle, Calculator, TrendingDown } from "lucide-react" import { CONTRACT_ABI, CONTRACT_ADDRESS, CONTRACT_TOKEN } from "../constants/constants" import { ethers } from "ethers" import { Value } from "@radix-ui/react-select" const tokens = [ { symbol: "USDT", name: "Tether USD", logo: "💵", address: "0x367a5a4C14214BfE67d3C00A97F19Cecd2cf9e87" }, { symbol: "DAI", name: "Dai Stablecoin", logo: "🟡", address: "0x7a8eF80C8136862fc7402E8Cfb9Cd1ea9c3BFB4B" }, { symbol: "USDC", name: "USD Coin", logo: "🔵", address: "0x2bE22845339D49E9b296AbA5462D78F2e929DB05" }, ] export default function BorrowPage() { const { isConnected, isCorrectNetwork, signer } = useWallet() const { toast } = useToast() const [collateralToken, setCollateralToken] = useState("") const [borrowToken, setBorrowToken] = useState("") const [borrowAmount, setBorrowAmount] = useState("") const collateralRequired = borrowAmount ? (Number.parseFloat(borrowAmount) * 1.5).toFixed(2) : "0.00" const liquidationPrice = borrowAmount ? (Number.parseFloat(borrowAmount) * 1.33).toFixed(2) : "0.00" const handleBorrow = async () => { if (!isConnected || !isCorrectNetwork) { toast({ title: "Wallet Not Connected", description: "Please connect your wallet and switch to Core Testnet", variant: "destructive", }) return } if (!collateralToken || !borrowToken || !borrowAmount) { toast({ title: "Missing Information", description: "Please fill in all required fields", variant: "destructive", }) return } if (Number.parseFloat(borrowAmount) <= 0) { toast({ title: "Invalid Amount", description: "Please enter a valid borrow amount", variant: "destructive", }) return } try { // TODO: Implement contract interaction const contract = new ethers.Contract(CONTRACT_ADDRESS, CONTRACT_ABI, signer) const token_contract = new ethers.Contract(collateralToken, CONTRACT_TOKEN, signer) console.log(collateralToken) console.log(borrowToken) const approval_tx = await token_contract.approve(CONTRACT_ADDRESS, ethers.parseUnits(collateralRequired, 18)) await approval_tx.wait(); const borrow_tx = await contract.borrow( collateralToken, borrowToken, ethers.parseUnits(borrowAmount, 18) ) await borrow_tx.wait() toast({ title: "Borrow Successful", description: `Successfully borrowed ${borrowAmount} ${borrowToken}`, }) // Reset form setCollateralToken("") setBorrowToken("") setBorrowAmount("") } catch (error) { console.log("Borrow failed:") toast({ title: "Borrow Failed", description: "Transaction failed. Please try again.", variant: "destructive", }) } } return (

Borrow Tokens

Borrow tokens by providing collateral. Maintain a healthy collateralization ratio to avoid liquidation.

Create Loan Select your collateral and borrow tokens, then specify the amount you want to borrow. {/* Collateral Token Selection */}
{/* Borrow Token Selection */}
{/* Borrow Amount */}
setBorrowAmount(e.target.value)} />
{/* Loan Details */} {borrowAmount && collateralToken && borrowToken && ( Loan Details
Collateral Required (150%) {collateralRequired} {tokens.find(t => t.address === collateralToken)?.symbol}
Liquidation Threshold {liquidationPrice} {tokens.find(t => t.address === collateralToken)?.symbol}
Interest Rate 12.5% APR
Loan-to-Value Ratio 66.67%
)} {/* Warning */}

Liquidation Risk Warning

If your collateral value falls below 133% of your borrowed amount, your position may be liquidated. Monitor your loan regularly.

{/* Borrow Button */}
{(!isConnected || !isCorrectNetwork) && (

{!isConnected ? "Connect your wallet to start borrowing" : "Switch to Core Testnet to continue"}

Make sure you're connected to the Core Testnet to interact with the protocol.

)}
) } ================================================ FILE: 14-Corelend/Frontend/app/constants/constants.tsx ================================================ const CONTRACT_ADDRESS = "0xd1022F7C4690458A3bB564710cE8f320aE940cB2"; const CONTRACT_ABI = [ { "inputs": [], "stateMutability": "nonpayable", "type": "constructor" }, { "inputs": [ { "internalType": "address", "name": "owner", "type": "address" } ], "name": "OwnableInvalidOwner", "type": "error" }, { "inputs": [ { "internalType": "address", "name": "account", "type": "address" } ], "name": "OwnableUnauthorizedAccount", "type": "error" }, { "anonymous": false, "inputs": [ { "indexed": true, "internalType": "address", "name": "previousOwner", "type": "address" }, { "indexed": true, "internalType": "address", "name": "newOwner", "type": "address" } ], "name": "OwnershipTransferred", "type": "event" }, { "inputs": [], "name": "SECONDS_IN_YEAR", "outputs": [ { "internalType": "uint256", "name": "", "type": "uint256" } ], "stateMutability": "view", "type": "function" }, { "inputs": [ { "internalType": "address", "name": "token", "type": "address" } ], "name": "addSupportedToken", "outputs": [], "stateMutability": "nonpayable", "type": "function" }, { "inputs": [ { "internalType": "address", "name": "collateralToken", "type": "address" }, { "internalType": "address", "name": "borrowToken", "type": "address" }, { "internalType": "uint256", "name": "borrowAmount", "type": "uint256" } ], "name": "borrow", "outputs": [], "stateMutability": "nonpayable", "type": "function" }, { "inputs": [], "name": "collateralFactor", "outputs": [ { "internalType": "uint256", "name": "", "type": "uint256" } ], "stateMutability": "view", "type": "function" }, { "inputs": [ { "internalType": "address", "name": "user", "type": "address" }, { "internalType": "address", "name": "borrowToken", "type": "address" } ], "name": "currentDebt", "outputs": [ { "internalType": "uint256", "name": "", "type": "uint256" } ], "stateMutability": "view", "type": "function" }, { "inputs": [ { "internalType": "address", "name": "token", "type": "address" }, { "internalType": "uint256", "name": "amount", "type": "uint256" } ], "name": "deposit", "outputs": [], "stateMutability": "nonpayable", "type": "function" }, { "inputs": [ { "internalType": "address", "name": "user", "type": "address" }, { "internalType": "address", "name": "tokenAddress", "type": "address" } ], "name": "getLendersBalance", "outputs": [ { "internalType": "uint256", "name": "", "type": "uint256" } ], "stateMutability": "view", "type": "function" }, { "inputs": [ { "internalType": "address", "name": "user", "type": "address" }, { "internalType": "address", "name": "borrowToken", "type": "address" } ], "name": "getLoanDetails", "outputs": [ { "components": [ { "internalType": "address", "name": "collateralToken", "type": "address" }, { "internalType": "address", "name": "borrowToken", "type": "address" }, { "internalType": "uint256", "name": "collateralAmount", "type": "uint256" }, { "internalType": "uint256", "name": "totalBorrowAmount", "type": "uint256" }, { "internalType": "uint256", "name": "timestamp", "type": "uint256" } ], "internalType": "struct CoreLend.LoanPosition", "name": "", "type": "tuple" } ], "stateMutability": "view", "type": "function" }, { "inputs": [], "name": "interestRatePerYear", "outputs": [ { "internalType": "uint256", "name": "", "type": "uint256" } ], "stateMutability": "view", "type": "function" }, { "inputs": [ { "internalType": "address", "name": "", "type": "address" } ], "name": "isSupportedToken", "outputs": [ { "internalType": "bool", "name": "", "type": "bool" } ], "stateMutability": "view", "type": "function" }, { "inputs": [ { "internalType": "address", "name": "", "type": "address" }, { "internalType": "address", "name": "", "type": "address" } ], "name": "lenderBalances", "outputs": [ { "internalType": "uint256", "name": "", "type": "uint256" } ], "stateMutability": "view", "type": "function" }, { "inputs": [ { "internalType": "address", "name": "user", "type": "address" }, { "internalType": "address", "name": "borrowToken", "type": "address" } ], "name": "liquidate", "outputs": [], "stateMutability": "nonpayable", "type": "function" }, { "inputs": [], "name": "owner", "outputs": [ { "internalType": "address", "name": "", "type": "address" } ], "stateMutability": "view", "type": "function" }, { "inputs": [], "name": "renounceOwnership", "outputs": [], "stateMutability": "nonpayable", "type": "function" }, { "inputs": [ { "internalType": "address", "name": "borrowToken", "type": "address" } ], "name": "repay", "outputs": [], "stateMutability": "nonpayable", "type": "function" }, { "inputs": [ { "internalType": "address", "name": "newOwner", "type": "address" } ], "name": "transferOwnership", "outputs": [], "stateMutability": "nonpayable", "type": "function" }, { "inputs": [ { "internalType": "address", "name": "", "type": "address" }, { "internalType": "address", "name": "", "type": "address" } ], "name": "userLoans", "outputs": [ { "internalType": "address", "name": "collateralToken", "type": "address" }, { "internalType": "address", "name": "borrowToken", "type": "address" }, { "internalType": "uint256", "name": "collateralAmount", "type": "uint256" }, { "internalType": "uint256", "name": "totalBorrowAmount", "type": "uint256" }, { "internalType": "uint256", "name": "timestamp", "type": "uint256" } ], "stateMutability": "view", "type": "function" }, { "inputs": [ { "internalType": "address", "name": "token", "type": "address" }, { "internalType": "uint256", "name": "amount", "type": "uint256" } ], "name": "withdraw", "outputs": [], "stateMutability": "nonpayable", "type": "function" } ] const CONTRACT_TOKEN = [ { "inputs": [], "stateMutability": "nonpayable", "type": "constructor" }, { "inputs": [ { "internalType": "address", "name": "spender", "type": "address" }, { "internalType": "uint256", "name": "allowance", "type": "uint256" }, { "internalType": "uint256", "name": "needed", "type": "uint256" } ], "name": "ERC20InsufficientAllowance", "type": "error" }, { "inputs": [ { "internalType": "address", "name": "sender", "type": "address" }, { "internalType": "uint256", "name": "balance", "type": "uint256" }, { "internalType": "uint256", "name": "needed", "type": "uint256" } ], "name": "ERC20InsufficientBalance", "type": "error" }, { "inputs": [ { "internalType": "address", "name": "approver", "type": "address" } ], "name": "ERC20InvalidApprover", "type": "error" }, { "inputs": [ { "internalType": "address", "name": "receiver", "type": "address" } ], "name": "ERC20InvalidReceiver", "type": "error" }, { "inputs": [ { "internalType": "address", "name": "sender", "type": "address" } ], "name": "ERC20InvalidSender", "type": "error" }, { "inputs": [ { "internalType": "address", "name": "spender", "type": "address" } ], "name": "ERC20InvalidSpender", "type": "error" }, { "anonymous": false, "inputs": [ { "indexed": true, "internalType": "address", "name": "owner", "type": "address" }, { "indexed": true, "internalType": "address", "name": "spender", "type": "address" }, { "indexed": false, "internalType": "uint256", "name": "value", "type": "uint256" } ], "name": "Approval", "type": "event" }, { "anonymous": false, "inputs": [ { "indexed": true, "internalType": "address", "name": "from", "type": "address" }, { "indexed": true, "internalType": "address", "name": "to", "type": "address" }, { "indexed": false, "internalType": "uint256", "name": "value", "type": "uint256" } ], "name": "Transfer", "type": "event" }, { "inputs": [ { "internalType": "address", "name": "owner", "type": "address" }, { "internalType": "address", "name": "spender", "type": "address" } ], "name": "allowance", "outputs": [ { "internalType": "uint256", "name": "", "type": "uint256" } ], "stateMutability": "view", "type": "function" }, { "inputs": [ { "internalType": "address", "name": "spender", "type": "address" }, { "internalType": "uint256", "name": "value", "type": "uint256" } ], "name": "approve", "outputs": [ { "internalType": "bool", "name": "", "type": "bool" } ], "stateMutability": "nonpayable", "type": "function" }, { "inputs": [ { "internalType": "address", "name": "account", "type": "address" } ], "name": "balanceOf", "outputs": [ { "internalType": "uint256", "name": "", "type": "uint256" } ], "stateMutability": "view", "type": "function" }, { "inputs": [], "name": "decimals", "outputs": [ { "internalType": "uint8", "name": "", "type": "uint8" } ], "stateMutability": "view", "type": "function" }, { "inputs": [], "name": "i_owner", "outputs": [ { "internalType": "address", "name": "", "type": "address" } ], "stateMutability": "view", "type": "function" }, { "inputs": [ { "internalType": "address", "name": "_receipient", "type": "address" }, { "internalType": "uint256", "name": "_amount", "type": "uint256" } ], "name": "mint", "outputs": [], "stateMutability": "nonpayable", "type": "function" }, { "inputs": [], "name": "name", "outputs": [ { "internalType": "string", "name": "", "type": "string" } ], "stateMutability": "view", "type": "function" }, { "inputs": [], "name": "symbol", "outputs": [ { "internalType": "string", "name": "", "type": "string" } ], "stateMutability": "view", "type": "function" }, { "inputs": [], "name": "totalSupply", "outputs": [ { "internalType": "uint256", "name": "", "type": "uint256" } ], "stateMutability": "view", "type": "function" }, { "inputs": [ { "internalType": "address", "name": "to", "type": "address" }, { "internalType": "uint256", "name": "value", "type": "uint256" } ], "name": "transfer", "outputs": [ { "internalType": "bool", "name": "", "type": "bool" } ], "stateMutability": "nonpayable", "type": "function" }, { "inputs": [ { "internalType": "address", "name": "from", "type": "address" }, { "internalType": "address", "name": "to", "type": "address" }, { "internalType": "uint256", "name": "value", "type": "uint256" } ], "name": "transferFrom", "outputs": [ { "internalType": "bool", "name": "", "type": "bool" } ], "stateMutability": "nonpayable", "type": "function" } ] export {CONTRACT_ABI, CONTRACT_ADDRESS, CONTRACT_TOKEN} ================================================ FILE: 14-Corelend/Frontend/app/globals.css ================================================ @tailwind base; @tailwind components; @tailwind utilities; @layer base { :root { --background: 0 0% 100%; --foreground: 222.2 84% 4.9%; --card: 0 0% 100%; --card-foreground: 222.2 84% 4.9%; --popover: 0 0% 100%; --popover-foreground: 222.2 84% 4.9%; --primary: 45 93% 47%; --primary-foreground: 222.2 84% 4.9%; --secondary: 210 40% 96%; --secondary-foreground: 222.2 84% 4.9%; --muted: 210 40% 96%; --muted-foreground: 215.4 16.3% 46.9%; --accent: 210 40% 96%; --accent-foreground: 222.2 84% 4.9%; --destructive: 0 84.2% 60.2%; --destructive-foreground: 210 40% 98%; --border: 214.3 31.8% 91.4%; --input: 214.3 31.8% 91.4%; --ring: 45 93% 47%; --radius: 0.5rem; } } @layer base { * { @apply border-border; } body { @apply bg-background text-foreground; } } ================================================ FILE: 14-Corelend/Frontend/app/layout.tsx ================================================ import type React from "react" import type { Metadata } from "next" import { Inter } from "next/font/google" import "./globals.css" import { Navbar } from "@/components/navbar" import { WalletProvider } from "@/components/wallet-provider" import { Toaster } from "@/components/ui/toaster" const inter = Inter({ subsets: ["latin"] }) export const metadata: Metadata = { title: "Core DeFi - Multi-Token Lending & Borrowing", description: "Decentralized lending and borrowing protocol on Core testnet", } export default function RootLayout({ children, }: { children: React.ReactNode }) { return (
{children}
) } ================================================ FILE: 14-Corelend/Frontend/app/lend/page.tsx ================================================ "use client" import { useState, useEffect } from "react" import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card" import { Button } from "@/components/ui/button" import { Input } from "@/components/ui/input" import { Badge } from "@/components/ui/badge" import { useWallet } from "@/components/wallet-provider" import { useToast } from "@/hooks/use-toast" import { Coins, TrendingUp, Wallet } from "lucide-react" import { CONTRACT_ABI, CONTRACT_ADDRESS, CONTRACT_TOKEN } from "../constants/constants" import { ethers } from "ethers" const supportedTokens = [ { symbol: "USDT", name: "Tether USD", logo: "💵", apy: "8.5%", address: "0x367a5a4C14214BfE67d3C00A97F19Cecd2cf9e87", }, { symbol: "DAI", name: "Dai Stablecoin", logo: "🟡", apy: "7.8%", address: "0x7a8eF80C8136862fc7402E8Cfb9Cd1ea9c3BFB4B", }, { symbol: "USDC", name: "USD Coin", logo: "🔵", apy: "8.2%", address: "0x2bE22845339D49E9b296AbA5462D78F2e929DB05", }, ] export default function LendPage() { const { isConnected, isCorrectNetwork, signer } = useWallet() const { toast } = useToast() const [depositAmounts, setDepositAmounts] = useState<{ [key: string]: string }>({}) const [withdrawAmounts, setWithdrawAmounts] = useState<{ [key: string]: string }>({}) const [balances, setBalances] = useState<{ [key: string]: string }>({}) const [deposits, setDeposits] = useState<{ [key: string]: string }>({}) const fetchBalances = async () => { if (!signer) return const updatedBalances: { [key: string]: string } = {}; const updatedDeposits: { [key: string]: string } = {}; for (const token of supportedTokens) { const tokenContract = new ethers.Contract(token.address, CONTRACT_TOKEN, signer) const mainContract = new ethers.Contract(CONTRACT_ADDRESS, CONTRACT_ABI, signer) const [balance, deposited] = await Promise.all([ tokenContract.balanceOf(signer), mainContract.getLendersBalance(signer, token.address), ]) updatedBalances[token.symbol] = ethers.formatUnits(balance, 18) updatedDeposits[token.symbol] = ethers.formatUnits(deposited, 18) } setBalances(updatedBalances) setDeposits(updatedDeposits) } useEffect(() => { if (isConnected && isCorrectNetwork) { fetchBalances() } }, [isConnected, isCorrectNetwork]) const handleDeposit = async (token: string, amount: string) => { if (!isConnected || !isCorrectNetwork) { toast({ title: "Wallet Not Connected", description: "Please connect your wallet and switch to Core Testnet", variant: "destructive", }) return } if (!amount || Number.parseFloat(amount) <= 0) { toast({ title: "Invalid Amount", description: "Please enter a valid deposit amount", variant: "destructive", }) return } try { // TODO: Implement contract interaction const contract = new ethers.Contract(CONTRACT_ADDRESS, CONTRACT_ABI, signer) const token_contract = new ethers.Contract(token, CONTRACT_TOKEN, signer) const approval_tx = await token_contract.approve(CONTRACT_ADDRESS, ethers.parseUnits(amount, 18)) await approval_tx.wait(); const deposit_tx = await contract.deposit(token, ethers.parseUnits(amount, 18)) await deposit_tx.wait(); toast({ title: "Deposit Successful", description: `Successfully deposited ${amount} ${token}`, }) setDepositAmounts((prev) => ({ ...prev, [token]: "" })) await fetchBalances() } catch (error) { console.log("Deposit failed:") toast({ title: "Deposit Failed", description: "Transaction failed. Please try again.", variant: "destructive", }) } } const handleWithdraw = async (token: string, amount: string) => { if (!isConnected || !isCorrectNetwork) { toast({ title: "Wallet Not Connected", description: "Please connect your wallet and switch to Core Testnet", variant: "destructive", }) return } if (!amount || Number.parseFloat(amount) <= 0) { toast({ title: "Invalid Amount", description: "Please enter a valid withdrawal amount", variant: "destructive", }) return } try { // TODO: Implement contract interaction console.log(token) const contract = new ethers.Contract(CONTRACT_ADDRESS, CONTRACT_ABI, signer) const withdraw_tx = await contract.withdraw(token, ethers.parseUnits(amount, 18)) await withdraw_tx.wait(); toast({ title: "Withdrawal Successful", description: `Successfully withdrew ${amount} ${token}`, }) setWithdrawAmounts((prev) => ({ ...prev, [token]: "" })) await fetchBalances() } catch (error) { console.log("Withdrawal failed:") toast({ title: "Withdrawal Failed", description: "Transaction failed. Please try again.", variant: "destructive", }) } } return (

Lend Tokens

Deposit your tokens to earn interest. Your deposits are secured by smart contracts and you can withdraw at any time.

{supportedTokens.map((token) => (
{token.logo}
{token.symbol} {token.name}
{token.apy} APY
{/* Balance Info */}
Wallet Balance {balances[token.symbol]} {token.symbol}
Deposited {deposits[token.symbol]} {token.symbol}
{/* Deposit Section */}

Deposit

setDepositAmounts((prev) => ({ ...prev, [token.symbol]: e.target.value, })) } className="flex-1" />
{/* Withdraw Section */}

Withdraw

setWithdrawAmounts((prev) => ({ ...prev, [token.symbol]: e.target.value, })) } className="flex-1" />
{/* Earnings Preview */}
Est. Annual Earnings {((Number.parseFloat(deposits[token.symbol]) * Number.parseFloat(token.apy)) / 100).toFixed(2)}{" "} {token.symbol}
))}
{(!isConnected || !isCorrectNetwork) && (

{!isConnected ? "Connect your wallet to start lending" : "Switch to Core Testnet to continue"}

Make sure you're connected to the Core Testnet to interact with the protocol.

)}
) } ================================================ FILE: 14-Corelend/Frontend/app/loans/page.tsx ================================================ "use client" import { useState, useEffect } from "react" import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card" import { Button } from "@/components/ui/button" import { Badge } from "@/components/ui/badge" import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table" import { useWallet } from "@/components/wallet-provider" import { useToast } from "@/hooks/use-toast" import { AlertTriangle, Clock, DollarSign, TrendingUp } from "lucide-react" import { CONTRACT_ABI, CONTRACT_ADDRESS, CONTRACT_TOKEN } from "../constants/constants" import { ethers } from "ethers" // Mock loan data - in real app, this would come from smart contract const mockLoans = [ { id: "1", collateralToken: "USDT", collateralAmount: "1500.00", borrowToken: "DAI", borrowAmount: "1000.00", interestAccrued: "45.67", totalRepayable: "1045.67", timeBorrowed: "2024-01-15", healthFactor: 1.85, status: "active", }, { id: "2", collateralToken: "USDC", collateralAmount: "750.00", borrowToken: "USDT", borrowAmount: "500.00", interestAccrued: "23.45", totalRepayable: "523.45", timeBorrowed: "2024-01-20", healthFactor: 1.43, status: "active", }, { id: "3", collateralToken: "DAI", collateralAmount: "2250.00", borrowToken: "USDC", borrowAmount: "1500.00", interestAccrued: "78.90", totalRepayable: "1578.90", timeBorrowed: "2024-01-10", healthFactor: 1.12, status: "at_risk", }, ] const tokenMap = { USDT: "0x367a5a4C14214BfE67d3C00A97F19Cecd2cf9e87", DAI: "0x7a8eF80C8136862fc7402E8Cfb9Cd1ea9c3BFB4B", USDC: "0x2bE22845339D49E9b296AbA5462D78F2e929DB05", } interface Loans { user: string borrowToken: string collateralToken: string borrowedAmount: number collateralAmount: number totalRepayable: number healthFactor: number } export default function LoansPage() { const { isConnected, isCorrectNetwork, provider, signer } = useWallet() const { toast } = useToast() const [loans, setLoans] = useState([]) const tokenMap = { USDT: "0x367a5a4C14214BfE67d3C00A97F19Cecd2cf9e87", DAI: "0x7a8eF80C8136862fc7402E8Cfb9Cd1ea9c3BFB4B", USDC: "0x2bE22845339D49E9b296AbA5462D78F2e929DB05", }; const symbolFromAddress = (address: string): string => { for (const [symbol, tokenAddr] of Object.entries(tokenMap)) { if (tokenAddr.toLowerCase() === address.toLowerCase()) { return symbol; } } return "UNKNOWN"; }; const fetchLoans = async () => { if (!provider || !signer) return; try { const userAddress = await signer.getAddress(); const contract = new ethers.Contract(CONTRACT_ADDRESS, CONTRACT_ABI, signer); const symbols = Object.keys(tokenMap); const allLoans: Loans[] = []; for (const borrowSymbol of symbols) { const borrowTokenAddress = tokenMap[borrowSymbol as keyof typeof tokenMap]; const loan = await contract.getLoanDetails(userAddress, borrowTokenAddress); // Only add if there's an actual loan if ( loan.collateralAmount > 0 && loan.totalBorrowAmount > 0 ) { const borrowAmount = Number(loan.totalBorrowAmount) / 1e18; const collateralAmount = Number(loan.collateralAmount) / 1e18; const collateralSymbol = symbolFromAddress(loan.collateralToken); const totalRepayable = borrowAmount * 1.1; // 10% interest const healthFactor = collateralAmount / totalRepayable; allLoans.push({ user: userAddress, borrowToken: borrowSymbol, collateralToken: collateralSymbol, borrowedAmount: borrowAmount, collateralAmount, totalRepayable, healthFactor, }); } } setLoans(allLoans); } catch (err) { console.log("Error fetching loans:"); } }; const handleRepay = async (borrowToken: string, collateralRequired: string, loanss: Loans) => { if (!isConnected || !isCorrectNetwork) { toast({ title: "Wallet Not Connected", description: "Please connect your wallet and switch to Core Testnet", variant: "destructive", }) return } try { // TODO: Implement contract interaction console.log("In here!") console.log(borrowToken) console.log(loanss) const contract = new ethers.Contract(CONTRACT_ADDRESS, CONTRACT_ABI, signer); const token_contract = new ethers.Contract(borrowToken, CONTRACT_TOKEN, signer) const approval_tx = await token_contract.approve(CONTRACT_ADDRESS, ethers.parseUnits(collateralRequired, 18)) await approval_tx.wait(); const repay_tx = await contract.repay(borrowToken) await repay_tx.wait(); toast({ title: "Repayment Successful", description: `Successfully repaid loan`, }) } catch (error) { console.log("Repayment failed:") toast({ title: "Repayment Failed", description: "Transaction failed. Please try again.", variant: "destructive", }) } } const handleLiquidate = async (loanId: any) => { if (!isConnected || !isCorrectNetwork) { toast({ title: "Wallet Not Connected", description: "Please connect your wallet and switch to Core Testnet", variant: "destructive", }) return } try { // TODO: Implement contract interaction // const contract = new ethers.Contract(contractAddress, abi, provider.getSigner()) // await contract.liquidate(loanId) toast({ title: "Liquidation Successful", description: `Successfully liquidated loan ${loanId}`, }) } catch (error) { console.log("Liquidation failed:") toast({ title: "Liquidation Failed", description: "Transaction failed. Please try again.", variant: "destructive", }) } } const getHealthFactorColor = (healthFactor: number) => { if (healthFactor >= 1.5) return "text-green-600" if (healthFactor >= 1.2) return "text-yellow-600" return "text-red-600" } const getHealthFactorBadge = (healthFactor: number) => { if (healthFactor >= 1.5) return Healthy if (healthFactor >= 1.2) return Warning return At Risk } const formatDate = (dateString: string) => { const date = new Date(dateString) const now = new Date() const diffTime = Math.abs(now.getTime() - date.getTime()) const diffDays = Math.ceil(diffTime / (1000 * 60 * 60 * 24)) return `${diffDays} days ago` } useEffect(() => { if (isConnected && isCorrectNetwork) fetchLoans() }, [isConnected]) const totalBorrowed = loans.reduce((sum, loan) => sum + loan.borrowedAmount, 0) const totalCollateral = loans.reduce((sum, loan) => sum + loan.collateralAmount, 0) const totalInterest = loans.reduce((sum, loan) => sum + (loan.totalRepayable - loan.borrowedAmount), 0) return (

My Loans

Monitor your active loans, track interest accrual, and manage repayments. Keep your health factor above 1.2 to avoid liquidation.

{/* Summary Cards */}
Total Borrowed
${totalBorrowed.toFixed(2)}

Across {loans.length} active loans

Total Collateral
${totalCollateral.toFixed(2)}

Locked as collateral

Total Interest
${totalInterest.toFixed(2)}

Accrued interest

{/* Loans Table */} Active Loans Manage your borrowing positions and monitor health factors {loans.length === 0 ? (

No active loans found

Visit the Borrow page to create your first loan

) : (
Collateral Borrowed Interest Total Repayable Health Factor Time Actions {loans.map((loan, i) => (
{loan.collateralAmount} {loan.collateralToken}
{loan.borrowedAmount} {loan.borrowToken}
+{loan.totalRepayable - loan.borrowedAmount} {loan.borrowToken}
{loan.totalRepayable} {loan.borrowToken}
{loan.healthFactor.toFixed(2)}
{getHealthFactorBadge(loan.healthFactor)}
{loan.borrowedAmount}
{loan.healthFactor < 1.2 && ( )}
))}
)}
{/* Risk Warning */}

Liquidation Risk Management

Monitor your health factors closely. Loans with health factors below 1.2 are at risk of liquidation. Consider adding more collateral or repaying part of your loan to maintain a healthy position.

{(!isConnected || !isCorrectNetwork) && (

{!isConnected ? "Connect your wallet to view your loans" : "Switch to Core Testnet to continue"}

Make sure you're connected to the Core Testnet to interact with the protocol.

)}
) } ================================================ FILE: 14-Corelend/Frontend/app/loans/store.tsx ================================================ "use client" import { useState } from "react" import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card" import { Button } from "@/components/ui/button" import { Badge } from "@/components/ui/badge" import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table" import { useWallet } from "@/components/wallet-provider" import { useToast } from "@/hooks/use-toast" import { AlertTriangle, Clock, DollarSign, TrendingUp } from "lucide-react" // Mock loan data - in real app, this would come from smart contract const mockLoans = [ { id: "1", collateralToken: "USDT", collateralAmount: "1500.00", borrowToken: "DAI", borrowAmount: "1000.00", interestAccrued: "45.67", totalRepayable: "1045.67", timeBorrowed: "2024-01-15", healthFactor: 1.85, status: "active", }, { id: "2", collateralToken: "USDC", collateralAmount: "750.00", borrowToken: "USDT", borrowAmount: "500.00", interestAccrued: "23.45", totalRepayable: "523.45", timeBorrowed: "2024-01-20", healthFactor: 1.43, status: "active", }, { id: "3", collateralToken: "DAI", collateralAmount: "2250.00", borrowToken: "USDC", borrowAmount: "1500.00", interestAccrued: "78.90", totalRepayable: "1578.90", timeBorrowed: "2024-01-10", healthFactor: 1.12, status: "at_risk", }, ] export default function LoansPage() { const { isConnected, isCorrectNetwork } = useWallet() const { toast } = useToast() const [loans] = useState(mockLoans) const handleRepay = async (loanId: string, amount: string) => { if (!isConnected || !isCorrectNetwork) { toast({ title: "Wallet Not Connected", description: "Please connect your wallet and switch to Core Testnet", variant: "destructive", }) return } try { // TODO: Implement contract interaction // const contract = new ethers.Contract(contractAddress, abi, provider.getSigner()) // await contract.repay(loanId, ethers.parseUnits(amount, 18)) toast({ title: "Repayment Successful", description: `Successfully repaid loan ${loanId}`, }) } catch (error) { console.error("Repayment failed:", error) toast({ title: "Repayment Failed", description: "Transaction failed. Please try again.", variant: "destructive", }) } } const handleLiquidate = async (loanId: string) => { if (!isConnected || !isCorrectNetwork) { toast({ title: "Wallet Not Connected", description: "Please connect your wallet and switch to Core Testnet", variant: "destructive", }) return } try { // TODO: Implement contract interaction // const contract = new ethers.Contract(contractAddress, abi, provider.getSigner()) // await contract.liquidate(loanId) toast({ title: "Liquidation Successful", description: `Successfully liquidated loan ${loanId}`, }) } catch (error) { console.error("Liquidation failed:", error) toast({ title: "Liquidation Failed", description: "Transaction failed. Please try again.", variant: "destructive", }) } } const getHealthFactorColor = (healthFactor: number) => { if (healthFactor >= 1.5) return "text-green-600" if (healthFactor >= 1.2) return "text-yellow-600" return "text-red-600" } const getHealthFactorBadge = (healthFactor: number) => { if (healthFactor >= 1.5) return Healthy if (healthFactor >= 1.2) return Warning return At Risk } const formatDate = (dateString: string) => { const date = new Date(dateString) const now = new Date() const diffTime = Math.abs(now.getTime() - date.getTime()) const diffDays = Math.ceil(diffTime / (1000 * 60 * 60 * 24)) return `${diffDays} days ago` } const totalBorrowed = loans.reduce((sum, loan) => sum + Number.parseFloat(loan.borrowAmount), 0) const totalCollateral = loans.reduce((sum, loan) => sum + Number.parseFloat(loan.collateralAmount), 0) const totalInterest = loans.reduce((sum, loan) => sum + Number.parseFloat(loan.interestAccrued), 0) return (

My Loans

Monitor your active loans, track interest accrual, and manage repayments. Keep your health factor above 1.2 to avoid liquidation.

{/* Summary Cards */}
Total Borrowed
${totalBorrowed.toFixed(2)}

Across {loans.length} active loans

Total Collateral
${totalCollateral.toFixed(2)}

Locked as collateral

Total Interest
${totalInterest.toFixed(2)}

Accrued interest

{/* Loans Table */} Active Loans Manage your borrowing positions and monitor health factors {loans.length === 0 ? (

No active loans found

Visit the Borrow page to create your first loan

) : (
Collateral Borrowed Interest Total Repayable Health Factor Time Actions {loans.map((loan) => (
{loan.collateralAmount} {loan.collateralToken}
{loan.borrowAmount} {loan.borrowToken}
+{loan.interestAccrued} {loan.borrowToken}
{loan.totalRepayable} {loan.borrowToken}
{loan.healthFactor.toFixed(2)}
{getHealthFactorBadge(loan.healthFactor)}
{formatDate(loan.timeBorrowed)}
{loan.healthFactor < 1.2 && ( )}
))}
)}
{/* Risk Warning */}

Liquidation Risk Management

Monitor your health factors closely. Loans with health factors below 1.2 are at risk of liquidation. Consider adding more collateral or repaying part of your loan to maintain a healthy position.

{(!isConnected || !isCorrectNetwork) && (

{!isConnected ? "Connect your wallet to view your loans" : "Switch to Core Testnet to continue"}

Make sure you're connected to the Core Testnet to interact with the protocol.

)}
) } ================================================ FILE: 14-Corelend/Frontend/app/loans/test.tsx ================================================ "use client" import { useState, useEffect } from "react" import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card" import { Button } from "@/components/ui/button" import { Badge } from "@/components/ui/badge" import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table" import { useWallet } from "@/components/wallet-provider" import { useToast } from "@/hooks/use-toast" import { AlertTriangle, Clock, DollarSign, TrendingUp } from "lucide-react" import { CONTRACT_ABI, CONTRACT_ADDRESS, CONTRACT_TOKEN } from "../constants/constants" import { ethers } from "ethers" // Mock loan data - in real app, this would come from smart contract const mockLoans = [ { id: "1", collateralToken: "USDT", collateralAmount: "1500.00", borrowToken: "DAI", borrowAmount: "1000.00", interestAccrued: "45.67", totalRepayable: "1045.67", timeBorrowed: "2024-01-15", healthFactor: 1.85, status: "active", }, { id: "2", collateralToken: "USDC", collateralAmount: "750.00", borrowToken: "USDT", borrowAmount: "500.00", interestAccrued: "23.45", totalRepayable: "523.45", timeBorrowed: "2024-01-20", healthFactor: 1.43, status: "active", }, { id: "3", collateralToken: "DAI", collateralAmount: "2250.00", borrowToken: "USDC", borrowAmount: "1500.00", interestAccrued: "78.90", totalRepayable: "1578.90", timeBorrowed: "2024-01-10", healthFactor: 1.12, status: "at_risk", }, ] const tokenMap = { USDT: "0x367a5a4C14214BfE67d3C00A97F19Cecd2cf9e87", DAI: "0x7a8eF80C8136862fc7402E8Cfb9Cd1ea9c3BFB4B", USDC: "0x2bE22845339D49E9b296AbA5462D78F2e929DB05", } interface Loans { user: string borrowToken: string collateralToken: string borrowedAmount: number collateralAmount: number totalRepayable: number healthFactor: number } export default function LoansPage() { const { isConnected, isCorrectNetwork, provider, signer } = useWallet() const { toast } = useToast() const [loans, setLoans] = useState([]) const fetchLoans = async () => { if (!provider || !signer) return try { console.log("Yup") const userAddress = await signer.getAddress() const contract = new ethers.Contract(CONTRACT_ADDRESS, CONTRACT_ABI, signer) const allLoans = [] for (const symbol of Object.keys(tokenMap)) { console.log("In here") const tokenAddress = tokenMap[symbol as keyof typeof tokenMap] const loanData = await contract.getLoanDetails(userAddress, tokenAddress) console.log(loanData) if (loanData.collateralAmount > 0 || loanData.totalBorrowAmount > 0) { const collateral = Number(loanData.collateralAmount) / 1e18 const borrowed = Number(loanData.totaltotalBorrowAmount) / 1e18 const totalRepayable = borrowed * 1.1 const healthFactor = collateral / totalRepayable allLoans.push({ user: userAddress, borrowToken: symbol, collateralToken: symbol, borrowedAmount: borrowed, collateralAmount: collateral, totalRepayable, healthFactor, }) } } setLoans(allLoans) } catch (err) { console.error("Loan fetch failed", err) } } const handleRepay = async (loanId: any, amount: any) => { if (!isConnected || !isCorrectNetwork) { toast({ title: "Wallet Not Connected", description: "Please connect your wallet and switch to Core Testnet", variant: "destructive", }) return } try { // TODO: Implement contract interaction // const contract = new ethers.Contract(contractAddress, abi, provider.getSigner()) // await contract.repay(loanId, ethers.parseUnits(amount, 18)) toast({ title: "Repayment Successful", description: `Successfully repaid loan ${loanId}`, }) } catch (error) { console.error("Repayment failed:", error) toast({ title: "Repayment Failed", description: "Transaction failed. Please try again.", variant: "destructive", }) } } const handleLiquidate = async (loanId: any) => { if (!isConnected || !isCorrectNetwork) { toast({ title: "Wallet Not Connected", description: "Please connect your wallet and switch to Core Testnet", variant: "destructive", }) return } try { // TODO: Implement contract interaction // const contract = new ethers.Contract(contractAddress, abi, provider.getSigner()) // await contract.liquidate(loanId) toast({ title: "Liquidation Successful", description: `Successfully liquidated loan ${loanId}`, }) } catch (error) { console.error("Liquidation failed:", error) toast({ title: "Liquidation Failed", description: "Transaction failed. Please try again.", variant: "destructive", }) } } const getHealthFactorColor = (healthFactor: number) => { if (healthFactor >= 1.5) return "text-green-600" if (healthFactor >= 1.2) return "text-yellow-600" return "text-red-600" } const getHealthFactorBadge = (healthFactor: number) => { if (healthFactor >= 1.5) return Healthy if (healthFactor >= 1.2) return Warning return At Risk } const formatDate = (dateString: string) => { const date = new Date(dateString) const now = new Date() const diffTime = Math.abs(now.getTime() - date.getTime()) const diffDays = Math.ceil(diffTime / (1000 * 60 * 60 * 24)) return `${diffDays} days ago` } useEffect(() => { if (isConnected && isCorrectNetwork) fetchLoans() }, [isConnected]) const totalBorrowed = loans.reduce((sum, loan) => sum + loan.borrowedAmount, 0) const totalCollateral = loans.reduce((sum, loan) => sum + loan.collateralAmount, 0) const totalInterest = loans.reduce((sum, loan) => sum + (loan.totalRepayable - loan.borrowedAmount), 0) return (

My Loans

Monitor your active loans, track interest accrual, and manage repayments. Keep your health factor above 1.2 to avoid liquidation.

{/* Summary Cards */}
Total Borrowed
${totalBorrowed.toFixed(2)}

Across {loans.length} active loans

Total Collateral
${totalCollateral.toFixed(2)}

Locked as collateral

Total Interest
${totalInterest.toFixed(2)}

Accrued interest

{/* Loans Table */} Active Loans Manage your borrowing positions and monitor health factors {loans.length === 0 ? (

No active loans found

Visit the Borrow page to create your first loan

) : (
Collateral Borrowed Interest Total Repayable Health Factor Time Actions {loans.map((loan, i) => (
{loan.collateralAmount} {loan.collateralToken}
{loan.borrowedAmount} {loan.borrowToken}
+{loan.totalRepayable - loan.borrowedAmount} {loan.borrowToken}
{loan.totalRepayable} {loan.borrowToken}
{loan.healthFactor.toFixed(2)}
{getHealthFactorBadge(loan.healthFactor)}
{loan.borrowedAmount}
{loan.healthFactor < 1.2 && ( )}
))}
)}
{/* Risk Warning */}

Liquidation Risk Management

Monitor your health factors closely. Loans with health factors below 1.2 are at risk of liquidation. Consider adding more collateral or repaying part of your loan to maintain a healthy position.

{(!isConnected || !isCorrectNetwork) && (

{!isConnected ? "Connect your wallet to view your loans" : "Switch to Core Testnet to continue"}

Make sure you're connected to the Core Testnet to interact with the protocol.

)}
) } ================================================ FILE: 14-Corelend/Frontend/app/page.tsx ================================================ import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card" import { Badge } from "@/components/ui/badge" import { TrendingUp, Users, DollarSign, Percent } from "lucide-react" export default function HomePage() { const stats = [ { title: "Total Value Locked", value: "$2.4M", change: "+12.5%", icon: DollarSign, color: "text-green-600", }, { title: "Average Interest Rate", value: "8.2%", change: "+0.3%", icon: Percent, color: "text-blue-600", }, { title: "Active Loans", value: "1,247", change: "+23", icon: TrendingUp, color: "text-purple-600", }, { title: "Total Users", value: "3,891", change: "+156", icon: Users, color: "text-orange-600", }, ] return (
{/* Hero Section */}
Built on Core Testnet

Multi-Token DeFi Lending & Borrowing

Secure, decentralized lending and borrowing protocol supporting multiple ERC20 tokens with competitive interest rates and flexible collateral options.

{/* Stats Grid */}
{stats.map((stat) => { const Icon = stat.icon return ( {stat.title}
{stat.value}

{stat.change} from last month

) })}
{/* Features Section */}
Multi-Token Support Lend and borrow multiple ERC20 tokens including USDT, DAI, and USDC
Competitive Rates Earn attractive yields on your deposits with dynamic interest rates
Flexible Collateral Use various tokens as collateral with 150% collateralization ratio
) } ================================================ FILE: 14-Corelend/Frontend/components/navbar.tsx ================================================ "use client" import Link from "next/link" import { usePathname } from "next/navigation" import { Button } from "@/components/ui/button" import { Badge } from "@/components/ui/badge" import { useWallet } from "@/components/wallet-provider" import { Coins, AlertTriangle } from "lucide-react" import { cn } from "@/lib/utils" const navigation = [ { name: "Dashboard", href: "/" }, { name: "Lend", href: "/lend" }, { name: "Borrow", href: "/borrow" }, { name: "My Loans", href: "/loans" }, ] export function Navbar() { const pathname = usePathname() const { account, isConnected, isCorrectNetwork, connectWallet, switchToCore } = useWallet() const truncateAddress = (address: string) => { return `${address.slice(0, 6)}...${address.slice(-4)}` } return ( ) } ================================================ FILE: 14-Corelend/Frontend/components/ui/badge.tsx ================================================ import * as React from "react" import { cva, type VariantProps } from "class-variance-authority" import { cn } from "@/lib/utils" const badgeVariants = cva( "inline-flex items-center rounded-md border px-2.5 py-0.5 text-xs font-semibold transition-colors focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2", { variants: { variant: { default: "border-transparent bg-primary text-primary-foreground shadow hover:bg-primary/80", secondary: "border-transparent bg-secondary text-secondary-foreground hover:bg-secondary/80", destructive: "border-transparent bg-destructive text-destructive-foreground shadow hover:bg-destructive/80", outline: "text-foreground", }, }, defaultVariants: { variant: "default", }, } ) export interface BadgeProps extends React.HTMLAttributes, VariantProps {} function Badge({ className, variant, ...props }: BadgeProps) { return (
) } export { Badge, badgeVariants } ================================================ FILE: 14-Corelend/Frontend/components/ui/button.tsx ================================================ import * as React from "react" import { Slot } from "@radix-ui/react-slot" import { cva, type VariantProps } from "class-variance-authority" import { cn } from "@/lib/utils" const buttonVariants = cva( "inline-flex items-center justify-center gap-2 whitespace-nowrap rounded-md text-sm font-medium transition-colors focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring disabled:pointer-events-none disabled:opacity-50 [&_svg]:pointer-events-none [&_svg]:size-4 [&_svg]:shrink-0", { variants: { variant: { default: "bg-primary text-primary-foreground shadow hover:bg-primary/90", destructive: "bg-destructive text-destructive-foreground shadow-sm hover:bg-destructive/90", outline: "border border-input bg-background shadow-sm hover:bg-accent hover:text-accent-foreground", secondary: "bg-secondary text-secondary-foreground shadow-sm hover:bg-secondary/80", ghost: "hover:bg-accent hover:text-accent-foreground", link: "text-primary underline-offset-4 hover:underline", }, size: { default: "h-9 px-4 py-2", sm: "h-8 rounded-md px-3 text-xs", lg: "h-10 rounded-md px-8", icon: "h-9 w-9", }, }, defaultVariants: { variant: "default", size: "default", }, } ) export interface ButtonProps extends React.ButtonHTMLAttributes, VariantProps { asChild?: boolean } const Button = React.forwardRef( ({ className, variant, size, asChild = false, ...props }, ref) => { const Comp = asChild ? Slot : "button" return ( ) } ) Button.displayName = "Button" export { Button, buttonVariants } ================================================ FILE: 14-Corelend/Frontend/components/ui/card.tsx ================================================ import * as React from "react" import { cn } from "@/lib/utils" const Card = React.forwardRef< HTMLDivElement, React.HTMLAttributes >(({ className, ...props }, ref) => (
)) Card.displayName = "Card" const CardHeader = React.forwardRef< HTMLDivElement, React.HTMLAttributes >(({ className, ...props }, ref) => (
)) CardHeader.displayName = "CardHeader" const CardTitle = React.forwardRef< HTMLDivElement, React.HTMLAttributes >(({ className, ...props }, ref) => (
)) CardTitle.displayName = "CardTitle" const CardDescription = React.forwardRef< HTMLDivElement, React.HTMLAttributes >(({ className, ...props }, ref) => (
)) CardDescription.displayName = "CardDescription" const CardContent = React.forwardRef< HTMLDivElement, React.HTMLAttributes >(({ className, ...props }, ref) => (
)) CardContent.displayName = "CardContent" const CardFooter = React.forwardRef< HTMLDivElement, React.HTMLAttributes >(({ className, ...props }, ref) => (
)) CardFooter.displayName = "CardFooter" export { Card, CardHeader, CardFooter, CardTitle, CardDescription, CardContent } ================================================ FILE: 14-Corelend/Frontend/components/ui/input.tsx ================================================ import * as React from "react" import { cn } from "@/lib/utils" const Input = React.forwardRef>( ({ className, type, ...props }, ref) => { return ( ) } ) Input.displayName = "Input" export { Input } ================================================ FILE: 14-Corelend/Frontend/components/ui/select.tsx ================================================ "use client" import * as React from "react" import * as SelectPrimitive from "@radix-ui/react-select" import { Check, ChevronDown, ChevronUp } from "lucide-react" import { cn } from "@/lib/utils" const Select = SelectPrimitive.Root const SelectGroup = SelectPrimitive.Group const SelectValue = SelectPrimitive.Value const SelectTrigger = React.forwardRef< React.ElementRef, React.ComponentPropsWithoutRef >(({ className, children, ...props }, ref) => ( span]:line-clamp-1", className )} {...props} > {children} )) SelectTrigger.displayName = SelectPrimitive.Trigger.displayName const SelectScrollUpButton = React.forwardRef< React.ElementRef, React.ComponentPropsWithoutRef >(({ className, ...props }, ref) => ( )) SelectScrollUpButton.displayName = SelectPrimitive.ScrollUpButton.displayName const SelectScrollDownButton = React.forwardRef< React.ElementRef, React.ComponentPropsWithoutRef >(({ className, ...props }, ref) => ( )) SelectScrollDownButton.displayName = SelectPrimitive.ScrollDownButton.displayName const SelectContent = React.forwardRef< React.ElementRef, React.ComponentPropsWithoutRef >(({ className, children, position = "popper", ...props }, ref) => ( {children} )) SelectContent.displayName = SelectPrimitive.Content.displayName const SelectLabel = React.forwardRef< React.ElementRef, React.ComponentPropsWithoutRef >(({ className, ...props }, ref) => ( )) SelectLabel.displayName = SelectPrimitive.Label.displayName const SelectItem = React.forwardRef< React.ElementRef, React.ComponentPropsWithoutRef >(({ className, children, ...props }, ref) => ( {children} )) SelectItem.displayName = SelectPrimitive.Item.displayName const SelectSeparator = React.forwardRef< React.ElementRef, React.ComponentPropsWithoutRef >(({ className, ...props }, ref) => ( )) SelectSeparator.displayName = SelectPrimitive.Separator.displayName export { Select, SelectGroup, SelectValue, SelectTrigger, SelectContent, SelectLabel, SelectItem, SelectSeparator, SelectScrollUpButton, SelectScrollDownButton, } ================================================ FILE: 14-Corelend/Frontend/components/ui/table.tsx ================================================ import * as React from "react" import { cn } from "@/lib/utils" const Table = React.forwardRef< HTMLTableElement, React.HTMLAttributes >(({ className, ...props }, ref) => (
)) Table.displayName = "Table" const TableHeader = React.forwardRef< HTMLTableSectionElement, React.HTMLAttributes >(({ className, ...props }, ref) => ( )) TableHeader.displayName = "TableHeader" const TableBody = React.forwardRef< HTMLTableSectionElement, React.HTMLAttributes >(({ className, ...props }, ref) => ( )) TableBody.displayName = "TableBody" const TableFooter = React.forwardRef< HTMLTableSectionElement, React.HTMLAttributes >(({ className, ...props }, ref) => ( tr]:last:border-b-0", className )} {...props} /> )) TableFooter.displayName = "TableFooter" const TableRow = React.forwardRef< HTMLTableRowElement, React.HTMLAttributes >(({ className, ...props }, ref) => ( )) TableRow.displayName = "TableRow" const TableHead = React.forwardRef< HTMLTableCellElement, React.ThHTMLAttributes >(({ className, ...props }, ref) => (
[role=checkbox]]:translate-y-[2px]", className )} {...props} /> )) TableHead.displayName = "TableHead" const TableCell = React.forwardRef< HTMLTableCellElement, React.TdHTMLAttributes >(({ className, ...props }, ref) => ( [role=checkbox]]:translate-y-[2px]", className )} {...props} /> )) TableCell.displayName = "TableCell" const TableCaption = React.forwardRef< HTMLTableCaptionElement, React.HTMLAttributes >(({ className, ...props }, ref) => (
)) TableCaption.displayName = "TableCaption" export { Table, TableHeader, TableBody, TableFooter, TableHead, TableRow, TableCell, TableCaption, } ================================================ FILE: 14-Corelend/Frontend/components/ui/toast.tsx ================================================ "use client" import * as React from "react" import * as ToastPrimitives from "@radix-ui/react-toast" import { cva, type VariantProps } from "class-variance-authority" import { X } from "lucide-react" import { cn } from "@/lib/utils" const ToastProvider = ToastPrimitives.Provider const ToastViewport = React.forwardRef< React.ElementRef, React.ComponentPropsWithoutRef >(({ className, ...props }, ref) => ( )) ToastViewport.displayName = ToastPrimitives.Viewport.displayName const toastVariants = cva( "group pointer-events-auto relative flex w-full items-center justify-between space-x-2 overflow-hidden rounded-md border p-4 pr-6 shadow-lg transition-all data-[swipe=cancel]:translate-x-0 data-[swipe=end]:translate-x-[var(--radix-toast-swipe-end-x)] data-[swipe=move]:translate-x-[var(--radix-toast-swipe-move-x)] data-[swipe=move]:transition-none data-[state=open]:animate-in data-[state=closed]:animate-out data-[swipe=end]:animate-out data-[state=closed]:fade-out-80 data-[state=closed]:slide-out-to-right-full data-[state=open]:slide-in-from-top-full data-[state=open]:sm:slide-in-from-bottom-full", { variants: { variant: { default: "border bg-background text-foreground", destructive: "destructive group border-destructive bg-destructive text-destructive-foreground", }, }, defaultVariants: { variant: "default", }, } ) const Toast = React.forwardRef< React.ElementRef, React.ComponentPropsWithoutRef & VariantProps >(({ className, variant, ...props }, ref) => { return ( ) }) Toast.displayName = ToastPrimitives.Root.displayName const ToastAction = React.forwardRef< React.ElementRef, React.ComponentPropsWithoutRef >(({ className, ...props }, ref) => ( )) ToastAction.displayName = ToastPrimitives.Action.displayName const ToastClose = React.forwardRef< React.ElementRef, React.ComponentPropsWithoutRef >(({ className, ...props }, ref) => ( )) ToastClose.displayName = ToastPrimitives.Close.displayName const ToastTitle = React.forwardRef< React.ElementRef, React.ComponentPropsWithoutRef >(({ className, ...props }, ref) => ( )) ToastTitle.displayName = ToastPrimitives.Title.displayName const ToastDescription = React.forwardRef< React.ElementRef, React.ComponentPropsWithoutRef >(({ className, ...props }, ref) => ( )) ToastDescription.displayName = ToastPrimitives.Description.displayName type ToastProps = React.ComponentPropsWithoutRef type ToastActionElement = React.ReactElement export { type ToastProps, type ToastActionElement, ToastProvider, ToastViewport, Toast, ToastTitle, ToastDescription, ToastClose, ToastAction, } ================================================ FILE: 14-Corelend/Frontend/components/ui/toaster.tsx ================================================ "use client" import { useToast } from "@/hooks/use-toast" import { Toast, ToastClose, ToastDescription, ToastProvider, ToastTitle, ToastViewport, } from "@/components/ui/toast" export function Toaster() { const { toasts } = useToast() return ( {toasts.map(function ({ id, title, description, action, ...props }) { return (
{title && {title}} {description && ( {description} )}
{action}
) })}
) } ================================================ FILE: 14-Corelend/Frontend/components/wallet-provider.tsx ================================================ "use client" import { createContext, useContext, useState, useEffect, type ReactNode } from "react" import { ethers } from "ethers" import { useToast } from "@/hooks/use-toast" interface WalletContextType { account: string | null provider: ethers.BrowserProvider | null signer: ethers.JsonRpcSigner | null chainId: number | null isConnected: boolean isCorrectNetwork: boolean connectWallet: () => Promise disconnectWallet: () => void switchToCore: () => Promise } const WalletContext = createContext(undefined) const CORE_TESTNET = { chainId: "0x45A", // 1114 in hex chainName: "Core Testnet", rpcUrls: ["https://rpc.test2.btcs.network"], nativeCurrency: { name: "tCORE", symbol: "tCORE", decimals: 18, }, blockExplorerUrls: ["https://scan.test2.btcs.network/"], } export function WalletProvider({ children }: { children: ReactNode }) { const [account, setAccount] = useState(null) const [provider, setProvider] = useState(null) const [signer, setSigner] = useState(null) const [chainId, setChainId] = useState(null) const { toast } = useToast() const isConnected = !!account const isCorrectNetwork = chainId === 1114 const connectWallet = async () => { try { if (!window.ethereum) { toast({ title: "Wallet not found", description: "Please install MetaMask or another Web3 wallet", variant: "destructive", }) return } const provider = new ethers.BrowserProvider(window.ethereum) const accounts = await provider.send("eth_requestAccounts", []) const network = await provider.getNetwork() const signer = await provider.getSigner() setProvider(provider) setAccount(accounts[0]) setChainId(Number(network.chainId)) setSigner(signer) if (Number(network.chainId) !== 1114) { toast({ title: "Wrong Network", description: "Please switch to Core Testnet", variant: "destructive", }) } else { toast({ title: "Wallet Connected", description: "Successfully connected to Core Testnet", }) } } catch (error) { console.error("Failed to connect wallet:", error) toast({ title: "Connection Failed", description: "Failed to connect wallet", variant: "destructive", }) } } const disconnectWallet = () => { setAccount(null) setProvider(null) setChainId(null) toast({ title: "Wallet Disconnected", description: "Your wallet has been disconnected", }) } const switchToCore = async () => { try { if (!window.ethereum) return await window.ethereum.request({ method: "wallet_switchEthereumChain", params: [{ chainId: CORE_TESTNET.chainId }], }) } catch (switchError: any) { // This error code indicates that the chain has not been added to MetaMask if (switchError.code === 4902) { try { await window.ethereum.request({ method: "wallet_addEthereumChain", params: [CORE_TESTNET], }) } catch (addError) { console.error("Failed to add Core Testnet:", addError) toast({ title: "Failed to Add Network", description: "Could not add Core Testnet to your wallet", variant: "destructive", }) } } else { console.error("Failed to switch to Core Testnet:", switchError) toast({ title: "Failed to Switch Network", description: "Could not switch to Core Testnet", variant: "destructive", }) } } } useEffect(() => { if (window.ethereum) { window.ethereum.on("accountsChanged", (accounts: string[]) => { if (accounts.length === 0) { disconnectWallet() } else { setAccount(accounts[0]) } }) window.ethereum.on("chainChanged", (chainId: string) => { setChainId(Number.parseInt(chainId, 16)) window.location.reload() }) } return () => { if (window.ethereum) { window.ethereum.removeAllListeners("accountsChanged") window.ethereum.removeAllListeners("chainChanged") } } }, []) return ( {children} ) } export function useWallet() { const context = useContext(WalletContext) if (context === undefined) { throw new Error("useWallet must be used within a WalletProvider") } return context } declare global { interface Window { ethereum?: any } } ================================================ FILE: 14-Corelend/Frontend/components.json ================================================ { "$schema": "https://ui.shadcn.com/schema.json", "style": "new-york", "rsc": true, "tsx": true, "tailwind": { "config": "tailwind.config.ts", "css": "app/globals.css", "baseColor": "zinc", "cssVariables": true, "prefix": "" }, "aliases": { "components": "@/components", "utils": "@/lib/utils", "ui": "@/components/ui", "lib": "@/lib", "hooks": "@/hooks" }, "iconLibrary": "lucide" } ================================================ FILE: 14-Corelend/Frontend/hooks/use-toast.ts ================================================ "use client" // Inspired by react-hot-toast library import * as React from "react" import type { ToastActionElement, ToastProps, } from "@/components/ui/toast" const TOAST_LIMIT = 1 const TOAST_REMOVE_DELAY = 1000000 type ToasterToast = ToastProps & { id: string title?: React.ReactNode description?: React.ReactNode action?: ToastActionElement } const actionTypes = { ADD_TOAST: "ADD_TOAST", UPDATE_TOAST: "UPDATE_TOAST", DISMISS_TOAST: "DISMISS_TOAST", REMOVE_TOAST: "REMOVE_TOAST", } as const let count = 0 function genId() { count = (count + 1) % Number.MAX_SAFE_INTEGER return count.toString() } type ActionType = typeof actionTypes type Action = | { type: ActionType["ADD_TOAST"] toast: ToasterToast } | { type: ActionType["UPDATE_TOAST"] toast: Partial } | { type: ActionType["DISMISS_TOAST"] toastId?: ToasterToast["id"] } | { type: ActionType["REMOVE_TOAST"] toastId?: ToasterToast["id"] } interface State { toasts: ToasterToast[] } const toastTimeouts = new Map>() const addToRemoveQueue = (toastId: string) => { if (toastTimeouts.has(toastId)) { return } const timeout = setTimeout(() => { toastTimeouts.delete(toastId) dispatch({ type: "REMOVE_TOAST", toastId: toastId, }) }, TOAST_REMOVE_DELAY) toastTimeouts.set(toastId, timeout) } export const reducer = (state: State, action: Action): State => { switch (action.type) { case "ADD_TOAST": return { ...state, toasts: [action.toast, ...state.toasts].slice(0, TOAST_LIMIT), } case "UPDATE_TOAST": return { ...state, toasts: state.toasts.map((t) => t.id === action.toast.id ? { ...t, ...action.toast } : t ), } case "DISMISS_TOAST": { const { toastId } = action // ! Side effects ! - This could be extracted into a dismissToast() action, // but I'll keep it here for simplicity if (toastId) { addToRemoveQueue(toastId) } else { state.toasts.forEach((toast) => { addToRemoveQueue(toast.id) }) } return { ...state, toasts: state.toasts.map((t) => t.id === toastId || toastId === undefined ? { ...t, open: false, } : t ), } } case "REMOVE_TOAST": if (action.toastId === undefined) { return { ...state, toasts: [], } } return { ...state, toasts: state.toasts.filter((t) => t.id !== action.toastId), } } } const listeners: Array<(state: State) => void> = [] let memoryState: State = { toasts: [] } function dispatch(action: Action) { memoryState = reducer(memoryState, action) listeners.forEach((listener) => { listener(memoryState) }) } type Toast = Omit function toast({ ...props }: Toast) { const id = genId() const update = (props: ToasterToast) => dispatch({ type: "UPDATE_TOAST", toast: { ...props, id }, }) const dismiss = () => dispatch({ type: "DISMISS_TOAST", toastId: id }) dispatch({ type: "ADD_TOAST", toast: { ...props, id, open: true, onOpenChange: (open) => { if (!open) dismiss() }, }, }) return { id: id, dismiss, update, } } function useToast() { const [state, setState] = React.useState(memoryState) React.useEffect(() => { listeners.push(setState) return () => { const index = listeners.indexOf(setState) if (index > -1) { listeners.splice(index, 1) } } }, [state]) return { ...state, toast, dismiss: (toastId?: string) => dispatch({ type: "DISMISS_TOAST", toastId }), } } export { useToast, toast } ================================================ FILE: 14-Corelend/Frontend/lib/utils.ts ================================================ import { clsx, type ClassValue } from "clsx" import { twMerge } from "tailwind-merge" export function cn(...inputs: ClassValue[]) { return twMerge(clsx(inputs)) } ================================================ FILE: 14-Corelend/Frontend/next.config.ts ================================================ import type { NextConfig } from "next"; const nextConfig: NextConfig = { /* config options here */ }; export default nextConfig; ================================================ FILE: 14-Corelend/Frontend/package.json ================================================ { "name": "reusable", "version": "0.1.0", "private": true, "scripts": { "dev": "next dev", "build": "next build", "start": "next start", "lint": "next lint" }, "dependencies": { "@radix-ui/react-select": "2.2.5", "@radix-ui/react-slot": "1.2.3", "@radix-ui/react-toast": "1.2.14", "class-variance-authority": "0.7.0", "clsx": "2.1.1", "ethers": "6.15.0", "lucide-react": "0.454.0", "next": "15.0.2", "react": "19.0.0-rc-02c0e824-20241028", "react-dom": "19.0.0-rc-02c0e824-20241028", "tailwind-merge": "2.5.4", "tailwindcss-animate": "1.0.7" }, "devDependencies": { "@types/node": "^20", "@types/react": "^18", "@types/react-dom": "^18", "eslint": "^8", "eslint-config-next": "15.0.2", "postcss": "^8", "tailwindcss": "3.4.17", "typescript": "^5" } } ================================================ FILE: 14-Corelend/Frontend/postcss.config.mjs ================================================ /** @type {import('postcss-load-config').Config} */ const config = { plugins: { tailwindcss: {}, }, }; export default config; ================================================ FILE: 14-Corelend/Frontend/tailwind.config.ts ================================================ import type { Config } from "tailwindcss" const config = { darkMode: ["class"], content: [ "./pages/**/*.{ts,tsx}", "./components/**/*.{ts,tsx}", "./app/**/*.{ts,tsx}", "./src/**/*.{ts,tsx}", "*.{js,ts,jsx,tsx,mdx}", ], prefix: "", theme: { container: { center: true, padding: "2rem", screens: { "2xl": "1400px", }, }, extend: { colors: { border: "hsl(var(--border))", input: "hsl(var(--input))", ring: "hsl(var(--ring))", background: "hsl(var(--background))", foreground: "hsl(var(--foreground))", primary: { DEFAULT: "#FFD700", foreground: "hsl(var(--primary-foreground))", }, secondary: { DEFAULT: "hsl(var(--secondary))", foreground: "hsl(var(--secondary-foreground))", }, destructive: { DEFAULT: "hsl(var(--destructive))", foreground: "hsl(var(--destructive-foreground))", }, muted: { DEFAULT: "hsl(var(--muted))", foreground: "hsl(var(--muted-foreground))", }, accent: { DEFAULT: "hsl(var(--accent))", foreground: "hsl(var(--accent-foreground))", }, popover: { DEFAULT: "hsl(var(--popover))", foreground: "hsl(var(--popover-foreground))", }, card: { DEFAULT: "hsl(var(--card))", foreground: "hsl(var(--card-foreground))", }, }, borderRadius: { lg: "var(--radius)", md: "calc(var(--radius) - 2px)", sm: "calc(var(--radius) - 4px)", }, keyframes: { "accordion-down": { from: { height: "0" }, to: { height: "var(--radix-accordion-content-height)" }, }, "accordion-up": { from: { height: "var(--radix-accordion-content-height)" }, to: { height: "0" }, }, }, animation: { "accordion-down": "accordion-down 0.2s ease-out", "accordion-up": "accordion-up 0.2s ease-out", }, }, }, plugins: [require("tailwindcss-animate")], } satisfies Config export default config ================================================ FILE: 14-Corelend/Frontend/tsconfig.json ================================================ { "compilerOptions": { "target": "ES2017", "lib": ["dom", "dom.iterable", "esnext"], "allowJs": true, "skipLibCheck": true, "strict": true, "noEmit": true, "esModuleInterop": true, "module": "esnext", "moduleResolution": "bundler", "resolveJsonModule": true, "isolatedModules": true, "jsx": "preserve", "incremental": true, "plugins": [ { "name": "next" } ], "paths": { "@/*": ["./*"] } }, "include": ["next-env.d.ts", "**/*.ts", "**/*.tsx", ".next/types/**/*.ts"], "exclude": ["node_modules"] } ================================================ FILE: 14-Corelend/README.md ================================================ # 💸 CoreLend – Multi-Token Lending & Borrowing Protocol A powerful, gas-efficient, and modular decentralized finance (DeFi) protocol enabling users to borrow against collateral and repay loans seamlessly using multiple supported tokens on **Core Testnet**. > 🧠 **GitHub Repository:** [https://github.com/coredao-org/dapp-tutorial](https://github.com/coredao-org/dapp-tutorial) --- ## ✨ Features - 🏦 **Lend & Borrow**: Supply collateral and borrow from a selection of supported tokens. - 🔄 **Repay System**: Easily repay borrowed tokens with calculated interest. - 🔍 **Loan Viewer**: See real-time loan data per token pair. - 🧠 **ERC-20 Support**: Currently supports USDT, USDC, and DAI. - ⚙️ **Smart Contract Factory Pattern**: Optimized to manage lending pools and loan data per user. --- ## 🔧 Getting Started ### 1. Clone the Repository ```bash git clone https://github.com/coredao-org/dapp-tutorial.git cd dapp-tutorial/14-CoreLend ``` --- ## 📦 Setup & Installation ### 2. Environment Setup Create a `.env` file in the root directory and add your private key: ```env PRIVATE_KEY=your_private_key_here ``` ### 3. Install Smart Contract Dependencies ```bash npm install ``` --- ## 🚀 Deployment on Core Testnet You can deploy the lending contract to **Core Testnet** using Hardhat. ### ⚙️ Compile Contracts ```bash npx hardhat compile ``` ### 🚀 Deploy to Core Testnet Update your `hardhat.config.ts` with Core Testnet RPC and run: ```bash npx hardhat run scripts/deploy.ts --network coreTestnet ``` > Make sure your `.env` contains a funded private key for the Core Testnet. --- ## 🧪 Test Tokens (Faucet) To interact with the protocol using tUSDT, tDAI, or tUSDC test tokens, visit: > 🧴 **Token Faucet**: [https://token-faucet-sandy.vercel.app](https://token-faucet-sandy.vercel.app) You’ll receive tokens compatible with CoreLend’s supported assets. --- ## 💻 Frontend Navigate into the frontend directory and run: ```bash cd frontend npm install npm run dev ``` > The dApp will be live at `http://localhost:3000` --- ## 🗂️ Project Structure ``` ├── contracts/ # Lending smart contracts (CoreLend.sol) ├── frontend/ # Frontend application (Next.js + Ethers.js) ├── scripts/ # Hardhat deployment scripts │ └── deploy.js # Deploys the CoreLend contract ├── hardhat.config.js # Network configuration ├── .env # Private key for deployment └── README.md ``` --- ## 🧠 Tech Stack - **Solidity** – Smart contract language - **Hardhat** – Smart contract dev environment - **Next.js** – React-based frontend framework - **Tailwind CSS** – Styling - **Ethers.js** – Web3 provider - **Core Blockchain** – Testnet deployment --- ## 🤝 Contributions Got an idea to improve the protocol? Feel free to: - Fork the repo - Submit issues - Propose pull requests We welcome community contributions! ================================================ FILE: 14-Corelend/contracts/CoreLend.sol ================================================ // SPDX-License-Identifier: MIT pragma solidity ^0.8.19; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; contract CoreLend is Ownable { uint256 public interestRatePerYear = 10; // 10% uint256 public constant SECONDS_IN_YEAR = 365 * 24 * 60 * 60; uint256 public collateralFactor = 150; // 150% (1.5x) struct LoanPosition { address collateralToken; address borrowToken; uint256 collateralAmount; uint256 totalBorrowAmount; uint256 timestamp; } mapping(address => bool) public isSupportedToken; mapping(address => mapping(address => uint256)) public lenderBalances; // lender => token => balance mapping(address => mapping(address => LoanPosition)) public userLoans; // user => borrowToken => LoanPosition modifier onlySupported(address token) { require(isSupportedToken[token], "Unsupported token"); _; } constructor() Ownable(msg.sender) {} function addSupportedToken(address token) external onlyOwner { isSupportedToken[token] = true; } function deposit(address token, uint256 amount) external /** onlySupported(token) */ { require(amount > 0, "Invalid amount"); IERC20(token).transferFrom(msg.sender, address(this), amount); lenderBalances[msg.sender][token] += amount; } function withdraw(address token, uint256 amount) external { require(lenderBalances[msg.sender][token] >= amount, "Insufficient balance"); lenderBalances[msg.sender][token] -= amount; IERC20(token).transfer(msg.sender, amount); } function borrow(address collateralToken, address borrowToken, uint256 borrowAmount) external /** onlySupported(collateralToken) onlySupported(borrowToken) */ { require(borrowAmount > 0, "Invalid borrow amount"); uint256 requiredCollateral = (borrowAmount * collateralFactor) / 100; IERC20(collateralToken).transferFrom(msg.sender, address(this), requiredCollateral); LoanPosition storage loan = userLoans[msg.sender][borrowToken]; if (loan.totalBorrowAmount == 0) { loan.collateralToken = collateralToken; loan.borrowToken = borrowToken; loan.timestamp = block.timestamp; } loan.collateralAmount += requiredCollateral; loan.totalBorrowAmount += borrowAmount; loan.timestamp = block.timestamp; IERC20(borrowToken).transfer(msg.sender, borrowAmount); } function repay(address borrowToken) external { LoanPosition storage loan = userLoans[msg.sender][borrowToken]; require(loan.totalBorrowAmount > 0, "No loan"); uint256 timeElapsed = block.timestamp - loan.timestamp; uint256 interest = (loan.totalBorrowAmount * interestRatePerYear * timeElapsed) / (100 * SECONDS_IN_YEAR); uint256 totalRepay = loan.totalBorrowAmount + interest; IERC20(loan.borrowToken).transferFrom(msg.sender, address(this), totalRepay); IERC20(loan.collateralToken).transfer(msg.sender, loan.collateralAmount); delete userLoans[msg.sender][borrowToken]; } function currentDebt(address user, address borrowToken) public view returns (uint256) { LoanPosition memory loan = userLoans[user][borrowToken]; if (loan.totalBorrowAmount == 0) return 0; uint256 timeElapsed = block.timestamp - loan.timestamp; uint256 interest = (loan.totalBorrowAmount * interestRatePerYear * timeElapsed) / (100 * SECONDS_IN_YEAR); return loan.totalBorrowAmount + interest; } function liquidate(address user, address borrowToken) external { LoanPosition memory loan = userLoans[user][borrowToken]; require(loan.totalBorrowAmount > 0, "No loan"); uint256 debt = currentDebt(user, borrowToken); require((loan.collateralAmount * 100) / debt < collateralFactor, "Healthy loan"); delete userLoans[user][borrowToken]; IERC20(loan.collateralToken).transfer(msg.sender, loan.collateralAmount); } function getLendersBalance(address user, address tokenAddress) external view returns (uint256) { return lenderBalances[user][tokenAddress]; } function getLoanDetails(address user, address borrowToken) external view returns (LoanPosition memory) { return userLoans[user][borrowToken]; } } ================================================ FILE: 14-Corelend/hardhat.config.js ================================================ require("@nomicfoundation/hardhat-toolbox"); require("dotenv").config(); /** @type import('hardhat/config').HardhatUserConfig */ const PRIVATE_KEY = process.env.PRIVATE_KEY; module.exports = { solidity: "0.8.27", networks: { localhost: { url: "http://127.0.0.1:8545/", // accounts: Thanks hardhat! chainId: 31337, allowUnlimitedContractSize: true, }, coreTestnet: { url: "https://rpc.test2.btcs.network", accounts: [PRIVATE_KEY], chainId: 1114, }, }, }; ================================================ FILE: 14-Corelend/ignition/modules/Lock.js ================================================ // This setup uses Hardhat Ignition to manage smart contract deployments. // Learn more about it at https://hardhat.org/ignition const { buildModule } = require("@nomicfoundation/hardhat-ignition/modules"); const JAN_1ST_2030 = 1893456000; const ONE_GWEI = 1_000_000_000n; module.exports = buildModule("LockModule", (m) => { const unlockTime = m.getParameter("unlockTime", JAN_1ST_2030); const lockedAmount = m.getParameter("lockedAmount", ONE_GWEI); const lock = m.contract("Lock", [unlockTime], { value: lockedAmount, }); return { lock }; }); ================================================ FILE: 14-Corelend/package.json ================================================ { "name": "reuse", "version": "1.0.0", "main": "index.js", "scripts": { "test": "echo \"Error: no test specified\" && exit 1" }, "author": "", "license": "ISC", "description": "", "devDependencies": { "@nomicfoundation/hardhat-toolbox": "^5.0.0", "hardhat": "^2.22.15" }, "dependencies": { "@openzeppelin/contracts": "^5.3.0", "dotenv": "^17.2.0" } } ================================================ FILE: 14-Corelend/scripts/deploy.js ================================================ const hre = require("hardhat"); const { loadFixture } = require("@nomicfoundation/hardhat-toolbox/network-helpers"); async function main() { const FEE = ethers.parseUnits("0.01", 18); const Corelend = await hre.ethers.getContractFactory("CoreLend"); const corelend = await Corelend.deploy(); console.log("CoreLend deployed to:", corelend.target); } // We recommend this pattern to be able to use async/await everywhere // and properly handle errors. main().catch((error) => { console.error(error); process.exitCode = 1; }); // CORE: CoreLend contract deployed to: 0x5Ac64F5DA22B25559C7D7522b4B2BB7e2012F382 ================================================ FILE: 14-Corelend/test/Lock.js ================================================ const { time, loadFixture, } = require("@nomicfoundation/hardhat-toolbox/network-helpers"); const { anyValue } = require("@nomicfoundation/hardhat-chai-matchers/withArgs"); const { expect } = require("chai"); describe("Lock", function () { // We define a fixture to reuse the same setup in every test. // We use loadFixture to run this setup once, snapshot that state, // and reset Hardhat Network to that snapshot in every test. async function deployOneYearLockFixture() { const ONE_YEAR_IN_SECS = 365 * 24 * 60 * 60; const ONE_GWEI = 1_000_000_000; const lockedAmount = ONE_GWEI; const unlockTime = (await time.latest()) + ONE_YEAR_IN_SECS; // Contracts are deployed using the first signer/account by default const [owner, otherAccount] = await ethers.getSigners(); const Lock = await ethers.getContractFactory("Lock"); const lock = await Lock.deploy(unlockTime, { value: lockedAmount }); return { lock, unlockTime, lockedAmount, owner, otherAccount }; } describe("Deployment", function () { it("Should set the right unlockTime", async function () { const { lock, unlockTime } = await loadFixture(deployOneYearLockFixture); expect(await lock.unlockTime()).to.equal(unlockTime); }); it("Should set the right owner", async function () { const { lock, owner } = await loadFixture(deployOneYearLockFixture); expect(await lock.owner()).to.equal(owner.address); }); it("Should receive and store the funds to lock", async function () { const { lock, lockedAmount } = await loadFixture( deployOneYearLockFixture ); expect(await ethers.provider.getBalance(lock.target)).to.equal( lockedAmount ); }); it("Should fail if the unlockTime is not in the future", async function () { // We don't use the fixture here because we want a different deployment const latestTime = await time.latest(); const Lock = await ethers.getContractFactory("Lock"); await expect(Lock.deploy(latestTime, { value: 1 })).to.be.revertedWith( "Unlock time should be in the future" ); }); }); describe("Withdrawals", function () { describe("Validations", function () { it("Should revert with the right error if called too soon", async function () { const { lock } = await loadFixture(deployOneYearLockFixture); await expect(lock.withdraw()).to.be.revertedWith( "You can't withdraw yet" ); }); it("Should revert with the right error if called from another account", async function () { const { lock, unlockTime, otherAccount } = await loadFixture( deployOneYearLockFixture ); // We can increase the time in Hardhat Network await time.increaseTo(unlockTime); // We use lock.connect() to send a transaction from another account await expect(lock.connect(otherAccount).withdraw()).to.be.revertedWith( "You aren't the owner" ); }); it("Shouldn't fail if the unlockTime has arrived and the owner calls it", async function () { const { lock, unlockTime } = await loadFixture( deployOneYearLockFixture ); // Transactions are sent using the first signer by default await time.increaseTo(unlockTime); await expect(lock.withdraw()).not.to.be.reverted; }); }); describe("Events", function () { it("Should emit an event on withdrawals", async function () { const { lock, unlockTime, lockedAmount } = await loadFixture( deployOneYearLockFixture ); await time.increaseTo(unlockTime); await expect(lock.withdraw()) .to.emit(lock, "Withdrawal") .withArgs(lockedAmount, anyValue); // We accept any value as `when` arg }); }); describe("Transfers", function () { it("Should transfer the funds to the owner", async function () { const { lock, unlockTime, lockedAmount, owner } = await loadFixture( deployOneYearLockFixture ); await time.increaseTo(unlockTime); await expect(lock.withdraw()).to.changeEtherBalances( [owner, lock], [lockedAmount, -lockedAmount] ); }); }); }); }); ================================================ FILE: 15-dns-protocol/.gitignore ================================================ node_modules .env # Hardhat files /cache /artifacts # TypeChain files /typechain /typechain-types # solidity-coverage files /coverage /coverage.json # Hardhat Ignition default folder for deployments against a local node ignition/deployments/chain-31337 ================================================ FILE: 15-dns-protocol/Frontend/.eslintrc.json ================================================ { "extends": ["next/core-web-vitals", "next/typescript"], "rules": { "@typescript-eslint/no-explicit-any": "off", // Allow `any` type "@typescript-eslint/no-unused-vars": "off", // Disable unused variables check "@typescript-eslint/no-unused-expressions": "off", // Disable unused expressions check "react-hooks/exhaustive-deps": "off", // Suppress missing dependency warnings in useEffect "@next/next/no-img-element": "off" // Allow the use of instead of } } ================================================ FILE: 15-dns-protocol/Frontend/.gitignore ================================================ # See https://help.github.com/articles/ignoring-files/ for more about ignoring files. # dependencies /node_modules /.pnp .pnp.* .yarn/* !.yarn/patches !.yarn/plugins !.yarn/releases !.yarn/versions # testing /coverage # next.js /.next/ /out/ # production /build # misc .DS_Store *.pem # debug npm-debug.log* yarn-debug.log* yarn-error.log* # env files (can opt-in for commiting if needed) .env* # vercel .vercel # typescript *.tsbuildinfo next-env.d.ts ================================================ FILE: 15-dns-protocol/Frontend/README.md ================================================ This is a [Next.js](https://nextjs.org) project bootstrapped with [`create-next-app`](https://nextjs.org/docs/app/api-reference/cli/create-next-app). ## Getting Started First, run the development server: ```bash npm run dev # or yarn dev # or pnpm dev # or bun dev ``` Open [http://localhost:3000](http://localhost:3000) with your browser to see the result. You can start editing the page by modifying `app/page.tsx`. The page auto-updates as you edit the file. This project uses [`next/font`](https://nextjs.org/docs/app/building-your-application/optimizing/fonts) to automatically optimize and load [Geist](https://vercel.com/font), a new font family for Vercel. ## Learn More To learn more about Next.js, take a look at the following resources: - [Next.js Documentation](https://nextjs.org/docs) - learn about Next.js features and API. - [Learn Next.js](https://nextjs.org/learn) - an interactive Next.js tutorial. You can check out [the Next.js GitHub repository](https://github.com/vercel/next.js) - your feedback and contributions are welcome! ## Deploy on Vercel The easiest way to deploy your Next.js app is to use the [Vercel Platform](https://vercel.com/new?utm_medium=default-template&filter=next.js&utm_source=create-next-app&utm_campaign=create-next-app-readme) from the creators of Next.js. Check out our [Next.js deployment documentation](https://nextjs.org/docs/app/building-your-application/deploying) for more details. ================================================ FILE: 15-dns-protocol/Frontend/app/dashboard/page.tsx ================================================ "use client" import { useEffect, useState } from "react" import { useWallet } from "@/hooks/use-wallet" import { DomainCard } from "@/components/domain-card" import { Button } from "@/components/ui/button" import { Skeleton } from "@/components/ui/skeleton" import { useRouter } from "next/navigation" import { Alert, AlertDescription, AlertTitle } from "@/components/ui/alert" import { AlertCircle } from "lucide-react" import { ethers } from "ethers" export default function Dashboard() { const { address, isConnected, getContractOne } = useWallet() const [domains, setDomains] = useState([]) const [loading, setLoading] = useState(true) const router = useRouter() useEffect(() => { if (!isConnected) { return } const fetchUserDomains = async () => { try { setLoading(true) // This would be replaced with actual contract call // Example: const userDomains = await coreContract.getUserDomains(address) const ensRegistry = getContractOne() if (!ensRegistry) throw new Error("ENS Registry contract is not loaded") // Call getSpecificRecord from the ENSRegistry contract const domainHashes = await ensRegistry.getDomainsByOwner(address) const domainNames = domainHashes.map((hash: any) => ethers.decodeBytes32String(hash)); // record: { owner, resolver, registration, expiration } console.log("heyy") console.log(domainHashes); console.log(domainNames) // Mock data for demonstration // const mockDomains = ["mydomain.core", "coredeveloper.core", "blockchain.core"] setDomains(domainNames) } catch (error) { console.error("Error fetching user domains:", error) } finally { setLoading(false) } } fetchUserDomains() }, [address, isConnected]) if (!isConnected) { return (

Connect Your Wallet

Please connect your wallet to view your domains.

) } return (

Your Domains

Manage your .core domains and their settings.

{loading ? (
{[1, 2, 3].map((i) => (
))}
) : domains.length > 0 ? (
{domains.map((domain) => ( ))}
) : ( No domains found You don't own any .core domains yet. Register your first domain now! )}
) } ================================================ FILE: 15-dns-protocol/Frontend/app/globals.css ================================================ @tailwind base; @tailwind components; @tailwind utilities; @layer base { :root { --background: 0 0% 100%; --foreground: 240 10% 3.9%; --card: 0 0% 100%; --card-foreground: 240 10% 3.9%; --popover: 0 0% 100%; --popover-foreground: 240 10% 3.9%; --primary: 24 95% 50%; --primary-foreground: 0 0% 98%; --secondary: 240 4.8% 95.9%; --secondary-foreground: 240 5.9% 10%; --muted: 240 4.8% 95.9%; --muted-foreground: 240 3.8% 46.1%; --accent: 240 4.8% 95.9%; --accent-foreground: 240 5.9% 10%; --destructive: 0 84.2% 60.2%; --destructive-foreground: 0 0% 98%; --border: 240 5.9% 90%; --input: 240 5.9% 90%; --ring: 24 95% 50%; --radius: 0.5rem; } .dark { --background: 20 14.3% 4.1%; --foreground: 0 0% 95%; --card: 24 9.8% 10%; --card-foreground: 0 0% 95%; --popover: 0 0% 9%; --popover-foreground: 0 0% 95%; --primary: 24 95% 50%; --primary-foreground: 0 0% 98%; --secondary: 240 3.7% 15.9%; --secondary-foreground: 0 0% 98%; --muted: 0 0% 15%; --muted-foreground: 240 5% 64.9%; --accent: 12 6.5% 15.1%; --accent-foreground: 0 0% 98%; --destructive: 0 62.8% 30.6%; --destructive-foreground: 0 85.7% 97.3%; --border: 240 3.7% 15.9%; --input: 240 3.7% 15.9%; --ring: 24 95% 50%; } } @layer base { * { @apply border-border; } body { @apply bg-background text-foreground; } } ================================================ FILE: 15-dns-protocol/Frontend/app/layout.tsx ================================================ import type React from "react" import type { Metadata } from "next" import { Inter } from "next/font/google" import "./globals.css" import { ThemeProvider } from "@/components/theme-provider" import { WalletProvider } from "@/components/wallet-provider" import { Header } from "@/components/header" const inter = Inter({ subsets: ["latin"] }) export const metadata: Metadata = { title: "CORE Domain Name Service", description: "Register and manage your .core domain names", } export default function RootLayout({ children, }: Readonly<{ children: React.ReactNode }>) { return (
{children}
) } ================================================ FILE: 15-dns-protocol/Frontend/app/page.tsx ================================================ import { DomainSearch } from "@/components/domain-search" import { Button } from "@/components/ui/button" import Link from "next/link" export default function Home() { return (

Own your digital identity
on the CORE blockchain

Register your .core domain name and take control of your web3 presence. Simple, secure, and decentralized.

Features

Everything you need to manage your digital identity on the CORE blockchain.

Secure Ownership

Your domains are secured by the CORE blockchain, giving you full control.

Easy Management

Manage all your domains from a simple, intuitive dashboard.

Public Registry

Browse all registered domains and find available names.

Ready to explore the registry?

) } ================================================ FILE: 15-dns-protocol/Frontend/app/registry/loading.tsx ================================================ export default function Loading() { return null } ================================================ FILE: 15-dns-protocol/Frontend/app/registry/page.tsx ================================================ "use client" import type React from "react" import { useState, useEffect } from "react" import { Input } from "@/components/ui/input" import { Button } from "@/components/ui/button" import { Skeleton } from "@/components/ui/skeleton" import { DomainDetails } from "@/components/domain-details" import { Search } from "lucide-react" interface Domain { name: string owner: string registrationDate: string } export default function Registry() { const [domains, setDomains] = useState([]) const [filteredDomains, setFilteredDomains] = useState([]) const [searchQuery, setSearchQuery] = useState("") const [loading, setLoading] = useState(true) const [selectedDomain, setSelectedDomain] = useState(null) useEffect(() => { const fetchAllDomains = async () => { try { setLoading(true) // This would be replaced with actual contract call // Example: const allDomains = await coreContract.getAllDomains() // Simulating API call with timeout await new Promise((resolve) => setTimeout(resolve, 1500)) // Mock data for demonstration const mockDomains: Domain[] = [ { name: "example.core", owner: "0x1234...5678", registrationDate: "2023-01-15", }, { name: "blockchain.core", owner: "0xabcd...ef01", registrationDate: "2023-02-20", }, { name: "defi.core", owner: "0x2468...1357", registrationDate: "2023-03-10", }, { name: "nft.core", owner: "0x9876...5432", registrationDate: "2023-04-05", }, { name: "metaverse.core", owner: "0xfedc...ba98", registrationDate: "2023-05-12", }, ] setDomains(mockDomains) setFilteredDomains(mockDomains) } catch (error) { console.error("Error fetching domains:", error) } finally { setLoading(false) } } fetchAllDomains() }, []) const handleSearch = () => { if (!searchQuery.trim()) { setFilteredDomains(domains) return } const query = searchQuery.toLowerCase() const filtered = domains.filter( (domain) => domain.name.toLowerCase().includes(query) || domain.owner.toLowerCase().includes(query), ) setFilteredDomains(filtered) } const handleKeyDown = (e: React.KeyboardEvent) => { if (e.key === "Enter") { handleSearch() } } return (

Public Domain Registry

Browse all registered .core domains and search for availability.

setSearchQuery(e.target.value)} onKeyDown={handleKeyDown} className="h-10" />
Registered Domains
{loading ? (
{[1, 2, 3, 4, 5].map((i) => ( ))}
) : filteredDomains.length > 0 ? (
    {filteredDomains.map((domain) => (
  • setSelectedDomain(domain)} >
    {domain.name}
    Owner: {domain.owner}
  • ))}
) : (
No domains found matching your search.
)}
Domain Details
{selectedDomain ? ( ) : (
Select a domain to view details
)}
) } ================================================ FILE: 15-dns-protocol/Frontend/components/alert.tsx ================================================ import * as React from "react" import { cva, type VariantProps } from "class-variance-authority" import { cn } from "@/lib/utils" const alertVariants = cva( "relative w-full rounded-lg border p-4 [&>svg~*]:pl-7 [&>svg+div]:translate-y-[-3px] [&>svg]:absolute [&>svg]:left-4 [&>svg]:top-4 [&>svg]:text-foreground", { variants: { variant: { default: "bg-background text-foreground", destructive: "border-destructive/50 text-destructive dark:border-destructive [&>svg]:text-destructive", warning: "border-yellow-500/50 text-yellow-700 dark:text-yellow-400 dark:border-yellow-400 [&>svg]:text-yellow-500", }, }, defaultVariants: { variant: "default", }, }, ) const Alert = React.forwardRef< HTMLDivElement, React.HTMLAttributes & VariantProps >(({ className, variant, ...props }, ref) => (
)) Alert.displayName = "Alert" const AlertTitle = React.forwardRef>( ({ className, ...props }, ref) => (
), ) AlertTitle.displayName = "AlertTitle" const AlertDescription = React.forwardRef>( ({ className, ...props }, ref) => (
), ) AlertDescription.displayName = "AlertDescription" export { Alert, AlertTitle, AlertDescription } ================================================ FILE: 15-dns-protocol/Frontend/components/domain-card.tsx ================================================ "use client" import { useEffect, useState } from "react" import { Card, CardContent, CardDescription, CardFooter, CardHeader, CardTitle } from "@/components/ui/card" import { Button } from "@/components/ui/button" import { Badge } from "@/components/ui/badge" import { Calendar, Globe } from "lucide-react" import { useWallet } from "@/hooks/use-wallet" import { ethers } from "ethers" interface DomainCardProps { domain: string } export function DomainCard({ domain }: DomainCardProps) { const { address, isConnected, getContractOne } = useWallet() const [expiryDate, setExpiryDate] = useState(""); // Mock data - in a real app, you would fetch this from the blockchain // const expiryDate = new Date() // expiryDate.setFullYear(expiryDate.getFullYear() + 1) useEffect(() => { if (!isConnected) { return } const fetchUserDomainDates = async () => { try { console.log("Hii") const ensRegistry = getContractOne() if (!ensRegistry) throw new Error("ENS Registry contract is not loaded") // Call getSpecificRecord from the ENSRegistry contract const domainHash = ethers.encodeBytes32String(domain) const datee = await ensRegistry.getSpecificRecord(domainHash) setExpiryDate(datee.expiration) } catch (error) { console.error("Error fetching user domains:", error) } } fetchUserDomainDates() }, [address, isConnected]) return (
{domain} Active
Expires: {expiryDate}
Primary Domain
) } ================================================ FILE: 15-dns-protocol/Frontend/components/domain-details.tsx ================================================ import { Badge } from "@/components/ui/badge" import { Calendar, User } from "lucide-react" interface Domain { name: string owner: string registrationDate: string } interface DomainDetailsProps { domain: Domain } export function DomainDetails({ domain }: DomainDetailsProps) { // Calculate expiry date (1 year from registration) const registrationDate = new Date(domain.registrationDate) const expiryDate = new Date(registrationDate) expiryDate.setFullYear(expiryDate.getFullYear() + 1) return (

{domain.name}

Registered

Owner

{domain.owner}

Registration Date

{new Date(domain.registrationDate).toLocaleDateString()}

Expiry Date

{expiryDate.toLocaleDateString()}

) } ================================================ FILE: 15-dns-protocol/Frontend/components/domain-search.tsx ================================================ "use client" import type React from "react" import { useState, useEffect } from "react" import { useRouter } from "next/navigation" import { useWallet } from "@/hooks/use-wallet" import { Input } from "@/components/ui/input" import { Button } from "@/components/ui/button" import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle, } from "@/components/ui/dialog" import { Alert, AlertDescription, AlertTitle } from "@/components/ui/alert" import { AlertCircle, Check, Loader2, Network } from "lucide-react" import { ethers } from "ethers" export function DomainSearch() { const [domainName, setDomainName] = useState("") const [isChecking, setIsChecking] = useState(false) const [isRegistering, setIsRegistering] = useState(false) const [isAvailable, setIsAvailable] = useState(null) const [owner, setOwner] = useState(null) const [showDialog, setShowDialog] = useState(false) const [registrationSuccess, setRegistrationSuccess] = useState(false) const [registrationError, setRegistrationError] = useState(null) const { isConnected, connect, networkStatus, switchNetwork, getContractOne, getContractTwo } = useWallet() const { isCorrectNetwork, isSwitchingNetwork } = networkStatus const router = useRouter() // Reset registration error when network status changes useEffect(() => { if (isCorrectNetwork) { setRegistrationError(null) } }, [isCorrectNetwork]) // Ensure domain name has .core suffix const formatDomainName = (name: string) => { if (!name) return "" const trimmed = name.trim().toLowerCase() if (trimmed.endsWith(".core")) return trimmed return `${trimmed}.core` } const handleInputChange = (e: React.ChangeEvent) => { setDomainName(e.target.value) // Reset states when input changes setIsAvailable(null) setOwner(null) setRegistrationError(null) } const checkAvailability = async () => { if (!domainName.trim()) return // Check if wallet is connected first if (!isConnected) { setRegistrationError("Please connect your wallet first.") return } const formattedName = formatDomainName(domainName) setIsChecking(true) setRegistrationError(null) try { console.log("Checking domain availability for:", formattedName) const domainHash = ethers.encodeBytes32String(formattedName) console.log("Domain hash:", domainHash) const ensRegistry = getContractOne() if (!ensRegistry) { throw new Error("ENS Registry contract is not loaded. Please ensure your wallet is connected and on the correct network.") } console.log("Contract loaded successfully:", ensRegistry) const record = await ensRegistry.getSpecificRecord(domainHash) console.log("Contract response:", record) const zeroAddress = "0x0000000000000000000000000000000000000000" // Check if domain is available (owner is zero address) if (record.owner === zeroAddress) { setIsAvailable(true) } else { setIsAvailable(false) setOwner(record.owner) } setShowDialog(true) } catch (error) { console.error("Error checking domain availability:", error) setRegistrationError(`Failed to check domain availability: ${error instanceof Error ? error.message : 'Unknown error'}`) } finally { setIsChecking(false) } } const handleConnectOrSwitch = async () => { if (!isConnected) { await connect() return false } if (!isCorrectNetwork) { await switchNetwork() return false } return true } const registerDomain = async () => { setRegistrationError(null) const readyToProceed = await handleConnectOrSwitch() if (!readyToProceed) return if (!isAvailable) return const formattedName = formatDomainName(domainName) setIsRegistering(true) try { const domainHash = ethers.encodeBytes32String(formattedName) const registrar = getContractTwo() if (!registrar) throw new Error("Registrar contract is not loaded") const tx = await registrar.register(domainHash, { value: ethers.parseEther("0.01"), }) await tx.wait() setRegistrationSuccess(true) setTimeout(() => { setShowDialog(false) router.push("/dashboard") }, 2000) } catch (error: any) { console.error("Error registering domain:", error) setRegistrationError(`Failed to register domain: ${error.message || "Unknown error"}`) } finally { setIsRegistering(false) } } return (
{domainName && !domainName.endsWith(".core") ? ".core" : ""}
Domain Registration {formatDomainName(domainName)}
{isAvailable === true && ( Available! This domain is available for registration. )} {isAvailable === false && ( Already Registered This domain has already been registered by {owner}. )} {registrationSuccess && ( Success! Domain successfully registered. Redirecting to your dashboard... )} {registrationError && ( Registration Failed {registrationError} )} {isConnected && !isCorrectNetwork && ( Wrong Network You need to switch to CoreTestnet2 to register domains. )}
{isAvailable && !registrationSuccess && ( )} {!isAvailable && ( )}
) } ================================================ FILE: 15-dns-protocol/Frontend/components/header.tsx ================================================ "use client" import Link from "next/link" import { useWallet } from "@/hooks/use-wallet" import { Button } from "@/components/ui/button" import { ModeToggle } from "@/components/mode-toggle" import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuTrigger } from "@/components/ui/dropdown-menu" import { AlertCircle, ChevronDown, Wallet } from "lucide-react" import { usePathname } from "next/navigation" import { Alert, AlertDescription } from "./ui/alert" import { useState, useEffect } from "react" import { NetworkSwitcher } from "./network-switcher" export function Header() { const { address, isConnected, networkStatus, connect, disconnect, switchNetwork } = useWallet() const { isCorrectNetwork, currentNetworkName, networkError } = networkStatus const pathname = usePathname() const [showNetworkError, setShowNetworkError] = useState(!!networkError) // Update network error visibility when error changes useEffect(() => { if (networkError) { setShowNetworkError(true) } }, [networkError]) const truncateAddress = (address: string) => { return `${address.slice(0, 6)}...${address.slice(-4)}` } return ( <>
CORE DNS
{isConnected ? ( My Domains Disconnect ) : ( )}
{isConnected && !isCorrectNetwork && (
You are on {currentNetworkName || "an unsupported network"}
)} {networkError && showNetworkError && (
{networkError}
)} ) } ================================================ FILE: 15-dns-protocol/Frontend/components/mode-toggle.tsx ================================================ "use client" import { useContext } from "react" import { Button } from "@/components/ui/button" import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuTrigger } from "@/components/ui/dropdown-menu" import { Moon, Sun } from "lucide-react" import { ThemeProviderContext } from "./theme-provider" export function ModeToggle() { const { theme, setTheme } = useContext(ThemeProviderContext) return ( setTheme("light")}>Light setTheme("dark")}>Dark setTheme("system")}>System ) } ================================================ FILE: 15-dns-protocol/Frontend/components/network-switcher.tsx ================================================ "use client" import { useWallet } from "@/hooks/use-wallet" import { Button } from "@/components/ui/button" import { Loader2, Check, AlertCircle } from "lucide-react" export function NetworkSwitcher() { const { isConnected, networkStatus, switchNetwork } = useWallet() const { isCorrectNetwork, currentNetworkName, isSwitchingNetwork } = networkStatus // If not connected, don't show anything if (!isConnected) { return null } // If on correct network, show a simple success indicator if (isCorrectNetwork) { return ( ) } // If switching network, show loading state if (isSwitchingNetwork) { return ( ) } // If on wrong network, show a simple switch button return ( ) } ================================================ FILE: 15-dns-protocol/Frontend/components/theme-provider.tsx ================================================ "use client" import type React from "react" import { createContext, useEffect, useState } from "react" type Theme = "dark" | "light" | "system" type ThemeProviderProps = { children: React.ReactNode defaultTheme?: Theme storageKey?: string } type ThemeProviderState = { theme: Theme setTheme: (theme: Theme) => void } const initialState: ThemeProviderState = { theme: "system", setTheme: () => null, } export const ThemeProviderContext = createContext(initialState) export function ThemeProvider({ children, defaultTheme = "system", storageKey = "theme", ...props }: ThemeProviderProps) { const [theme, setTheme] = useState(defaultTheme) useEffect(() => { const root = window.document.documentElement const savedTheme = localStorage.getItem(storageKey) if (savedTheme && ["dark", "light", "system"].includes(savedTheme)) { setTheme(savedTheme as Theme) } }, [storageKey]) useEffect(() => { const root = window.document.documentElement // Remove all theme classes root.classList.remove("light", "dark") if (theme === "system") { const systemTheme = window.matchMedia("(prefers-color-scheme: dark)").matches ? "dark" : "light" root.classList.add(systemTheme) return } root.classList.add(theme) localStorage.setItem(storageKey, theme) }, [theme, storageKey]) const value = { theme, setTheme: (theme: Theme) => { setTheme(theme) }, } return ( {children} ) } ================================================ FILE: 15-dns-protocol/Frontend/components/tooltip.tsx ================================================ "use client" import * as React from "react" import * as TooltipPrimitive from "@radix-ui/react-tooltip" import { cn } from "@/lib/utils" const TooltipProvider = TooltipPrimitive.Provider const Tooltip = TooltipPrimitive.Root const TooltipTrigger = TooltipPrimitive.Trigger const TooltipContent = React.forwardRef< React.ElementRef, React.ComponentPropsWithoutRef >(({ className, sideOffset = 4, ...props }, ref) => ( )) TooltipContent.displayName = TooltipPrimitive.Content.displayName export { Tooltip, TooltipTrigger, TooltipContent, TooltipProvider } ================================================ FILE: 15-dns-protocol/Frontend/components/ui/alert.tsx ================================================ "use client" import * as React from "react" import { cva, type VariantProps } from "class-variance-authority" import { cn } from "@/lib/utils" const alertVariants = cva( "relative w-full rounded-lg border px-4 py-3 text-sm [&>svg+div]:translate-y-[-3px] [&>svg]:absolute [&>svg]:left-4 [&>svg]:top-4 [&>svg]:text-foreground [&>svg~*]:pl-7", { variants: { variant: { default: "bg-background text-foreground", destructive: "border-destructive/50 text-destructive dark:border-destructive [&>svg]:text-destructive", }, }, defaultVariants: { variant: "default", }, } ) const Alert = React.forwardRef< HTMLDivElement, React.HTMLAttributes & VariantProps >(({ className, variant, ...props }, ref) => (
)) Alert.displayName = "Alert" const AlertTitle = React.forwardRef< HTMLParagraphElement, React.HTMLAttributes >(({ className, ...props }, ref) => (
)) AlertTitle.displayName = "AlertTitle" const AlertDescription = React.forwardRef< HTMLParagraphElement, React.HTMLAttributes >(({ className, ...props }, ref) => (
)) AlertDescription.displayName = "AlertDescription" export { Alert, AlertTitle, AlertDescription } ================================================ FILE: 15-dns-protocol/Frontend/components/ui/badge.tsx ================================================ import * as React from "react" import { cva, type VariantProps } from "class-variance-authority" import { cn } from "@/lib/utils" const badgeVariants = cva( "inline-flex items-center rounded-md border px-2.5 py-0.5 text-xs font-semibold transition-colors focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2", { variants: { variant: { default: "border-transparent bg-primary text-primary-foreground shadow hover:bg-primary/80", secondary: "border-transparent bg-secondary text-secondary-foreground hover:bg-secondary/80", destructive: "border-transparent bg-destructive text-destructive-foreground shadow hover:bg-destructive/80", outline: "text-foreground", }, }, defaultVariants: { variant: "default", }, } ) export interface BadgeProps extends React.HTMLAttributes, VariantProps {} function Badge({ className, variant, ...props }: BadgeProps) { return (
) } export { Badge, badgeVariants } ================================================ FILE: 15-dns-protocol/Frontend/components/ui/button.tsx ================================================ "use client" import * as React from "react" import { Slot } from "@radix-ui/react-slot" import { cva, type VariantProps } from "class-variance-authority" import { cn } from "@/lib/utils" const buttonVariants = cva( "inline-flex items-center justify-center gap-2 whitespace-nowrap rounded-md text-sm font-medium transition-colors focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring disabled:pointer-events-none disabled:opacity-50 [&_svg]:pointer-events-none [&_svg]:size-4 [&_svg]:shrink-0", { variants: { variant: { default: "bg-primary text-primary-foreground shadow hover:bg-primary/90", destructive: "bg-destructive text-destructive-foreground shadow-sm hover:bg-destructive/90", outline: "border border-input bg-background shadow-sm hover:bg-accent hover:text-accent-foreground", secondary: "bg-secondary text-secondary-foreground shadow-sm hover:bg-secondary/80", ghost: "hover:bg-accent hover:text-accent-foreground", link: "text-primary underline-offset-4 hover:underline", }, size: { default: "h-9 px-4 py-2", sm: "h-8 rounded-md px-3 text-xs", lg: "h-10 rounded-md px-8", icon: "h-9 w-9", }, }, defaultVariants: { variant: "default", size: "default", }, } ) export interface ButtonProps extends React.ButtonHTMLAttributes, VariantProps { asChild?: boolean } const Button = React.forwardRef( ({ className, variant, size, asChild = false, ...props }, ref) => { const Comp = asChild ? Slot : "button" return ( ) } ) Button.displayName = "Button" export { Button, buttonVariants } ================================================ FILE: 15-dns-protocol/Frontend/components/ui/card.tsx ================================================ "use client" import * as React from "react" import { cn } from "@/lib/utils" const Card = React.forwardRef< HTMLDivElement, React.HTMLAttributes >(({ className, ...props }, ref) => (
)) Card.displayName = "Card" const CardHeader = React.forwardRef< HTMLDivElement, React.HTMLAttributes >(({ className, ...props }, ref) => (
)) CardHeader.displayName = "CardHeader" const CardTitle = React.forwardRef< HTMLDivElement, React.HTMLAttributes >(({ className, ...props }, ref) => (
)) CardTitle.displayName = "CardTitle" const CardDescription = React.forwardRef< HTMLDivElement, React.HTMLAttributes >(({ className, ...props }, ref) => (
)) CardDescription.displayName = "CardDescription" const CardContent = React.forwardRef< HTMLDivElement, React.HTMLAttributes >(({ className, ...props }, ref) => (
)) CardContent.displayName = "CardContent" const CardFooter = React.forwardRef< HTMLDivElement, React.HTMLAttributes >(({ className, ...props }, ref) => (
)) CardFooter.displayName = "CardFooter" export { Card, CardHeader, CardFooter, CardTitle, CardDescription, CardContent } ================================================ FILE: 15-dns-protocol/Frontend/components/ui/dialog.tsx ================================================ "use client" "use client" import * as React from "react" import * as DialogPrimitive from "@radix-ui/react-dialog" import { X } from "lucide-react" import { cn } from "@/lib/utils" const Dialog = DialogPrimitive.Root const DialogTrigger = DialogPrimitive.Trigger const DialogPortal = DialogPrimitive.Portal const DialogClose = DialogPrimitive.Close const DialogOverlay = React.forwardRef< React.ElementRef, React.ComponentPropsWithoutRef >(({ className, ...props }, ref) => ( )) DialogOverlay.displayName = DialogPrimitive.Overlay.displayName const DialogContent = React.forwardRef< React.ElementRef, React.ComponentPropsWithoutRef >(({ className, children, ...props }, ref) => ( {children} Close )) DialogContent.displayName = DialogPrimitive.Content.displayName const DialogHeader = ({ className, ...props }: React.HTMLAttributes) => (
) DialogHeader.displayName = "DialogHeader" const DialogFooter = ({ className, ...props }: React.HTMLAttributes) => (
) DialogFooter.displayName = "DialogFooter" const DialogTitle = React.forwardRef< React.ElementRef, React.ComponentPropsWithoutRef >(({ className, ...props }, ref) => ( )) DialogTitle.displayName = DialogPrimitive.Title.displayName const DialogDescription = React.forwardRef< React.ElementRef, React.ComponentPropsWithoutRef >(({ className, ...props }, ref) => ( )) DialogDescription.displayName = DialogPrimitive.Description.displayName export { Dialog, DialogPortal, DialogOverlay, DialogTrigger, DialogClose, DialogContent, DialogHeader, DialogFooter, DialogTitle, DialogDescription, } ================================================ FILE: 15-dns-protocol/Frontend/components/ui/dropdown-menu.tsx ================================================ "use client" "use client" import * as React from "react" import * as DropdownMenuPrimitive from "@radix-ui/react-dropdown-menu" import { Check, ChevronRight, Circle } from "lucide-react" import { cn } from "@/lib/utils" const DropdownMenu = DropdownMenuPrimitive.Root const DropdownMenuTrigger = DropdownMenuPrimitive.Trigger const DropdownMenuGroup = DropdownMenuPrimitive.Group const DropdownMenuPortal = DropdownMenuPrimitive.Portal const DropdownMenuSub = DropdownMenuPrimitive.Sub const DropdownMenuRadioGroup = DropdownMenuPrimitive.RadioGroup const DropdownMenuSubTrigger = React.forwardRef< React.ElementRef, React.ComponentPropsWithoutRef & { inset?: boolean } >(({ className, inset, children, ...props }, ref) => ( {children} )) DropdownMenuSubTrigger.displayName = DropdownMenuPrimitive.SubTrigger.displayName const DropdownMenuSubContent = React.forwardRef< React.ElementRef, React.ComponentPropsWithoutRef >(({ className, ...props }, ref) => ( )) DropdownMenuSubContent.displayName = DropdownMenuPrimitive.SubContent.displayName const DropdownMenuContent = React.forwardRef< React.ElementRef, React.ComponentPropsWithoutRef >(({ className, sideOffset = 4, ...props }, ref) => ( )) DropdownMenuContent.displayName = DropdownMenuPrimitive.Content.displayName const DropdownMenuItem = React.forwardRef< React.ElementRef, React.ComponentPropsWithoutRef & { inset?: boolean } >(({ className, inset, ...props }, ref) => ( svg]:size-4 [&>svg]:shrink-0", inset && "pl-8", className )} {...props} /> )) DropdownMenuItem.displayName = DropdownMenuPrimitive.Item.displayName const DropdownMenuCheckboxItem = React.forwardRef< React.ElementRef, React.ComponentPropsWithoutRef >(({ className, children, checked, ...props }, ref) => ( {children} )) DropdownMenuCheckboxItem.displayName = DropdownMenuPrimitive.CheckboxItem.displayName const DropdownMenuRadioItem = React.forwardRef< React.ElementRef, React.ComponentPropsWithoutRef >(({ className, children, ...props }, ref) => ( {children} )) DropdownMenuRadioItem.displayName = DropdownMenuPrimitive.RadioItem.displayName const DropdownMenuLabel = React.forwardRef< React.ElementRef, React.ComponentPropsWithoutRef & { inset?: boolean } >(({ className, inset, ...props }, ref) => ( )) DropdownMenuLabel.displayName = DropdownMenuPrimitive.Label.displayName const DropdownMenuSeparator = React.forwardRef< React.ElementRef, React.ComponentPropsWithoutRef >(({ className, ...props }, ref) => ( )) DropdownMenuSeparator.displayName = DropdownMenuPrimitive.Separator.displayName const DropdownMenuShortcut = ({ className, ...props }: React.HTMLAttributes) => { return ( ) } DropdownMenuShortcut.displayName = "DropdownMenuShortcut" export { DropdownMenu, DropdownMenuTrigger, DropdownMenuContent, DropdownMenuItem, DropdownMenuCheckboxItem, DropdownMenuRadioItem, DropdownMenuLabel, DropdownMenuSeparator, DropdownMenuShortcut, DropdownMenuGroup, DropdownMenuPortal, DropdownMenuSub, DropdownMenuSubContent, DropdownMenuSubTrigger, DropdownMenuRadioGroup, } ================================================ FILE: 15-dns-protocol/Frontend/components/ui/input.tsx ================================================ "use client" import * as React from "react" import { cn } from "@/lib/utils" const Input = React.forwardRef>( ({ className, type, ...props }, ref) => { return ( ) } ) Input.displayName = "Input" export { Input } ================================================ FILE: 15-dns-protocol/Frontend/components/ui/skeleton.tsx ================================================ import { cn } from "@/lib/utils" function Skeleton({ className, ...props }: React.HTMLAttributes) { return (
) } export { Skeleton } ================================================ FILE: 15-dns-protocol/Frontend/components/wallet-provider.tsx ================================================ // WalletProvider.tsx "use client" import { createContext, useEffect, useState, useRef, ReactNode } from "react" import { ethers } from "ethers" import contractsData from "../constants/config.json" // CoreTestnet2 parameters const CORE_TESTNET2 = { chainId: "0x45a", // 1114 decimal chainName: "CoreTestnet2", nativeCurrency: { name: "tCORE2", symbol: "tCORE2", decimals: 18 }, rpcUrls: ["https://rpc.test2.btcs.network"], blockExplorerUrls: ["https://scan.test2.btcs.network"], } interface NetworkStatus { isCorrectNetwork: boolean currentChainId: string | null currentNetworkName: string | null isCheckingNetwork: boolean isSwitchingNetwork: boolean networkError: string | null } interface WalletContextType { address: string | null isConnected: boolean networkStatus: NetworkStatus connect: () => Promise disconnect: () => void switchNetwork: () => Promise provider: ethers.BrowserProvider | null signer: ethers.JsonRpcSigner | null getContractOne: () => ethers.Contract | null getContractTwo: () => ethers.Contract | null } const initialNetworkStatus: NetworkStatus = { isCorrectNetwork: false, currentChainId: null, currentNetworkName: null, isCheckingNetwork: false, isSwitchingNetwork: false, networkError: null, } export const WalletContext = createContext({ address: null, isConnected: false, networkStatus: initialNetworkStatus, connect: async () => {}, disconnect: () => {}, switchNetwork: async () => {}, provider: null, signer: null, getContractOne: () => null, getContractTwo: () => null }) // Helper to map chainId → name const getNetworkName = (chainId: string | null): string => { if (!chainId) return "Unknown Network" const id = chainId.startsWith("0x") ? parseInt(chainId, 16) : parseInt(chainId) const names: Record = { 1114: "CoreTestnet2", 1: "Ethereum Mainnet", 5: "Goerli" } return names[id] || `Chain ${id}` } export function WalletProvider({ children }: { children: ReactNode }) { const [address, setAddress] = useState(null) const [isConnected, setIsConnected] = useState(false) const [networkStatus, setNetworkStatus] = useState(initialNetworkStatus) const [provider, setProvider] = useState(null) const [signer, setSigner] = useState(null) const [contractData, setContractData] = useState(contractsData) const chainChangedRef = useRef<((chainId: string) => void)|null>(null) const accountsChangedRef = useRef<((accounts: string[]) => void)|null>(null) const disconnectRef = useRef<(() => void)|null>(null) const pollRef = useRef(null) // 1. Check network via RPC const checkNetwork = async (): Promise => { if (!window.ethereum) return false setNetworkStatus(ns => ({ ...ns, isCheckingNetwork: true })) try { const chainId: string = await window.ethereum.request({ method: "eth_chainId" }) const isCorrect = chainId === CORE_TESTNET2.chainId setNetworkStatus(ns => ({ ...ns, isCorrectNetwork: isCorrect, currentChainId: chainId, currentNetworkName: getNetworkName(chainId), isCheckingNetwork: false, networkError: isCorrect ? null : "Please switch back to CoreTestnet2.", })) return isCorrect } catch { setNetworkStatus(ns => ({ ...ns, isCheckingNetwork: false, networkError: "Network check failed" })) return false } } // 2. Setup chainChanged listener & polling const setupNetworkMonitoring = () => { if (!window.ethereum) return cleanupNetworkMonitoring() const onChainChanged = (chainId: string) => { const isCorrect = chainId === CORE_TESTNET2.chainId setNetworkStatus(ns => ({ ...ns, isCorrectNetwork: isCorrect, currentChainId: chainId, currentNetworkName: getNetworkName(chainId), isSwitchingNetwork: false, networkError: isCorrect ? null : "Please switch back to CoreTestnet2.", })) // update provider/signer after network flips if (isConnected) { const bp = new ethers.BrowserProvider((window as any).ethereum) setProvider(bp) bp.getSigner().then(setSigner).catch(console.error) } // MetaMask recommends reload on chain change :contentReference[oaicite:6]{index=6} window.location.reload() } chainChangedRef.current = onChainChanged window.ethereum.on("chainChanged", onChainChanged) pollRef.current = setInterval(checkNetwork, 5000) // fallback polling } const cleanupNetworkMonitoring = () => { if (window.ethereum && chainChangedRef.current) { window.ethereum.removeListener("chainChanged", chainChangedRef.current) } if (pollRef.current) clearInterval(pollRef.current) } // 3. switchNetwork with add fallback :contentReference[oaicite:7]{index=7} :contentReference[oaicite:8]{index=8} const switchNetwork = async () => { if (!window.ethereum) { setNetworkStatus(ns => ({ ...ns, networkError: "Please install MetaMask." })) return } setNetworkStatus(ns => ({ ...ns, isSwitchingNetwork: true, networkError: null })) try { await window.ethereum.request({ method: "wallet_switchEthereumChain", params: [{ chainId: CORE_TESTNET2.chainId }], }) } catch (err: any) { // if not added or silent‐fail, force add → switch :contentReference[oaicite:9]{index=9} await window.ethereum.request({ method: "wallet_addEthereumChain", params: [CORE_TESTNET2] }) await window.ethereum.request({ method: "wallet_switchEthereumChain", params: [{ chainId: CORE_TESTNET2.chainId }], }) } finally { setTimeout(async () => { setNetworkStatus(ns => ({ ...ns, isSwitchingNetwork: false })) await checkNetwork() }, 500) } } // 4. connect wallet const connect = async () => { if (!window.ethereum) { setNetworkStatus(ns => ({ ...ns, networkError: "Please install MetaMask." })) return } try { const accounts: string[] = await window.ethereum.request({ method: "eth_requestAccounts" }) if (accounts.length === 0) throw new Error("No accounts") const bp = new ethers.BrowserProvider(window.ethereum) const s = await bp.getSigner() setProvider(bp); setSigner(s); setAddress(await s.getAddress()); setIsConnected(true) localStorage.setItem("walletConnected", "true") await checkNetwork() setupNetworkMonitoring() // account/disconnect handlers const onAccountsChanged = (accs: string[]) => accs.length ? setAddress(accs[0]) : disconnect() const onDisconnect = () => disconnect() accountsChangedRef.current = onAccountsChanged disconnectRef.current = onDisconnect window.ethereum.on("accountsChanged", onAccountsChanged) window.ethereum.on("disconnect", onDisconnect) } catch (err: any) { setNetworkStatus(ns => ({ ...ns, networkError: `Connect failed: ${err.message}` })) } } // 5. disconnect const disconnect = () => { setAddress(null); setIsConnected(false); setNetworkStatus(initialNetworkStatus) setProvider(null); setSigner(null); localStorage.removeItem("walletConnected") if (window.ethereum) { if (accountsChangedRef.current) window.ethereum.removeListener("accountsChanged", accountsChangedRef.current) if (disconnectRef.current) window.ethereum.removeListener("disconnect", disconnectRef.current) } cleanupNetworkMonitoring() } // Helpers for creating contract instances using the signer const getContractOne = () => { if (signer) { return new ethers.Contract( contractData.ContractOne.address, contractData.ContractOne.abi, signer ) } return null } const getContractTwo = () => { if (signer) { return new ethers.Contract( contractData.ContractTwo.address, contractData.ContractTwo.abi, signer ) } return null } // Auto-reconnect if previously connected useEffect(() => { if (window.ethereum && localStorage.getItem("walletConnected") === "true") connect() return cleanupNetworkMonitoring // cleanup on unmount :contentReference[oaicite:10]{index=10} }, []) return ( {children} ) } ================================================ FILE: 15-dns-protocol/Frontend/components.json ================================================ { "$schema": "https://ui.shadcn.com/schema.json", "style": "new-york", "rsc": true, "tsx": true, "tailwind": { "config": "tailwind.config.ts", "css": "app/globals.css", "baseColor": "zinc", "cssVariables": true, "prefix": "" }, "aliases": { "components": "@/components", "utils": "@/lib/utils", "ui": "@/components/ui", "lib": "@/lib", "hooks": "@/hooks" }, "iconLibrary": "lucide" } ================================================ FILE: 15-dns-protocol/Frontend/constants/config.json ================================================ { "ContractOne": { "address": "0x529694c7174467B72195A8680Dd7E2BD10f81be5", "abi": [ { "anonymous": false, "inputs": [ { "indexed": true, "internalType": "bytes32", "name": "domain", "type": "bytes32" }, { "indexed": false, "internalType": "address", "name": "owner", "type": "address" } ], "name": "NewDomain", "type": "event" }, { "anonymous": false, "inputs": [ { "indexed": true, "internalType": "bytes32", "name": "domain", "type": "bytes32" }, { "indexed": false, "internalType": "uint256", "name": "expiration", "type": "uint256" } ], "name": "RenewDomain", "type": "event" }, { "anonymous": false, "inputs": [ { "indexed": true, "internalType": "bytes32", "name": "domain", "type": "bytes32" }, { "indexed": false, "internalType": "address", "name": "resolver", "type": "address" } ], "name": "SetResolver", "type": "event" }, { "anonymous": false, "inputs": [ { "indexed": true, "internalType": "bytes32", "name": "domain", "type": "bytes32" }, { "indexed": false, "internalType": "address", "name": "newOwner", "type": "address" } ], "name": "Transfer", "type": "event" }, { "inputs": [], "name": "getAllRecords", "outputs": [ { "components": [ { "internalType": "bytes32", "name": "domainName", "type": "bytes32" }, { "internalType": "address", "name": "owner", "type": "address" }, { "internalType": "address", "name": "resolver", "type": "address" }, { "internalType": "uint256", "name": "registration", "type": "uint256" }, { "internalType": "uint256", "name": "expiration", "type": "uint256" } ], "internalType": "struct ENSRegistry.Record[]", "name": "", "type": "tuple[]" } ], "stateMutability": "view", "type": "function" }, { "inputs": [ { "internalType": "address", "name": "ownerAddress", "type": "address" } ], "name": "getDomainsByOwner", "outputs": [ { "internalType": "bytes32[]", "name": "", "type": "bytes32[]" } ], "stateMutability": "view", "type": "function" }, { "inputs": [ { "internalType": "bytes32", "name": "domainHash", "type": "bytes32" } ], "name": "getSpecificRecord", "outputs": [ { "components": [ { "internalType": "bytes32", "name": "domainName", "type": "bytes32" }, { "internalType": "address", "name": "owner", "type": "address" }, { "internalType": "address", "name": "resolver", "type": "address" }, { "internalType": "uint256", "name": "registration", "type": "uint256" }, { "internalType": "uint256", "name": "expiration", "type": "uint256" } ], "internalType": "struct ENSRegistry.Record", "name": "", "type": "tuple" } ], "stateMutability": "view", "type": "function" }, { "inputs": [ { "internalType": "bytes32", "name": "", "type": "bytes32" } ], "name": "records", "outputs": [ { "internalType": "bytes32", "name": "domainName", "type": "bytes32" }, { "internalType": "address", "name": "owner", "type": "address" }, { "internalType": "address", "name": "resolver", "type": "address" }, { "internalType": "uint256", "name": "registration", "type": "uint256" }, { "internalType": "uint256", "name": "expiration", "type": "uint256" } ], "stateMutability": "view", "type": "function" }, { "inputs": [ { "internalType": "bytes32", "name": "domainHash", "type": "bytes32" }, { "internalType": "address", "name": "owner", "type": "address" }, { "internalType": "address", "name": "resolver", "type": "address" }, { "internalType": "uint256", "name": "registration", "type": "uint256" }, { "internalType": "uint256", "name": "expiration", "type": "uint256" } ], "name": "setRecord", "outputs": [], "stateMutability": "nonpayable", "type": "function" }, { "inputs": [ { "internalType": "bytes32", "name": "domainHash", "type": "bytes32" }, { "internalType": "address", "name": "resolver", "type": "address" } ], "name": "setResolver", "outputs": [], "stateMutability": "nonpayable", "type": "function" }, { "inputs": [ { "internalType": "bytes32", "name": "domainHash", "type": "bytes32" }, { "internalType": "address", "name": "newOwner", "type": "address" } ], "name": "transferOwnership", "outputs": [], "stateMutability": "nonpayable", "type": "function" } ] }, "ContractTwo": { "address": "0xd50E09199DB244cBA496857E4AC3E2300448cA50", "abi": [ { "inputs": [ { "internalType": "address", "name": "_registry", "type": "address" }, { "internalType": "uint256", "name": "_fee", "type": "uint256" } ], "stateMutability": "nonpayable", "type": "constructor" }, { "anonymous": false, "inputs": [ { "indexed": true, "internalType": "bytes32", "name": "domainHash", "type": "bytes32" }, { "indexed": false, "internalType": "address", "name": "owner", "type": "address" }, { "indexed": false, "internalType": "uint256", "name": "expiration", "type": "uint256" } ], "name": "DomainRegistered", "type": "event" }, { "inputs": [ { "internalType": "bytes32", "name": "domainHash", "type": "bytes32" } ], "name": "register", "outputs": [], "stateMutability": "payable", "type": "function" }, { "inputs": [], "name": "registrationFee", "outputs": [ { "internalType": "uint256", "name": "", "type": "uint256" } ], "stateMutability": "view", "type": "function" }, { "inputs": [], "name": "registrationPeriod", "outputs": [ { "internalType": "uint256", "name": "", "type": "uint256" } ], "stateMutability": "view", "type": "function" }, { "inputs": [], "name": "registry", "outputs": [ { "internalType": "contract ENSRegistry", "name": "", "type": "address" } ], "stateMutability": "view", "type": "function" }, { "inputs": [ { "internalType": "bytes32", "name": "domainHash", "type": "bytes32" } ], "name": "renew", "outputs": [], "stateMutability": "payable", "type": "function" } ] } } ================================================ FILE: 15-dns-protocol/Frontend/hooks/use-wallet.tsx ================================================ "use client" import { useContext } from "react" import { WalletContext } from "@/components/wallet-provider" export function useWallet() { const context = useContext(WalletContext) if (context === undefined) { throw new Error("useWallet must be used within a WalletProvider") } return context } ================================================ FILE: 15-dns-protocol/Frontend/lib/core-contract.ts ================================================ import { ethers } from "ethers" // This is a placeholder for the actual contract ABI // In a real application, you would import the actual ABI from a JSON file const CORE_DNS_ABI = [ // Example ABI entries "function registerDomain(string name) public", "function getOwner(string name) public view returns (address)", "function getUserDomains(address owner) public view returns (string[])", "function getAllDomains() public view returns (string[])", ] // Contract address - replace with actual contract address const CONTRACT_ADDRESS = "0x1234567890123456789012345678901234567890" export class CoreContract { private contract: ethers.Contract | null = null constructor(provider: ethers.BrowserProvider, signer: ethers.JsonRpcSigner) { this.contract = new ethers.Contract(CONTRACT_ADDRESS, CORE_DNS_ABI, signer) } async registerDomain(name: string): Promise { if (!this.contract) throw new Error("Contract not initialized") // Ensure domain has .core suffix const formattedName = this.formatDomainName(name) // Call the contract method return await this.contract.registerDomain(formattedName) } async getOwner(name: string): Promise { if (!this.contract) throw new Error("Contract not initialized") // Ensure domain has .core suffix const formattedName = this.formatDomainName(name) // Call the contract method return await this.contract.getOwner(formattedName) } async getUserDomains(owner: string): Promise { if (!this.contract) throw new Error("Contract not initialized") // Call the contract method return await this.contract.getUserDomains(owner) } async getAllDomains(): Promise { if (!this.contract) throw new Error("Contract not initialized") // Call the contract method return await this.contract.getAllDomains() } private formatDomainName(name: string): string { if (!name) return "" const trimmed = name.trim().toLowerCase() if (trimmed.endsWith(".core")) return trimmed return `${trimmed}.core` } } ================================================ FILE: 15-dns-protocol/Frontend/lib/utils.ts ================================================ import { clsx, type ClassValue } from "clsx" import { twMerge } from "tailwind-merge" export function cn(...inputs: ClassValue[]) { return twMerge(clsx(inputs)) } ================================================ FILE: 15-dns-protocol/Frontend/next.config.js ================================================ /** @type {import('next').NextConfig} */ const nextConfig = { /* config options here */ }; module.exports = nextConfig; ================================================ FILE: 15-dns-protocol/Frontend/package.json ================================================ { "name": "core-dns", "version": "0.1.0", "private": true, "scripts": { "dev": "next dev", "build": "next build", "start": "next start", "lint": "next lint" }, "dependencies": { "@radix-ui/react-dialog": "1.1.15", "@radix-ui/react-dropdown-menu": "2.0.0", "@radix-ui/react-slot": "1.0.0", "@radix-ui/react-tooltip": "1.0.0", "class-variance-authority": "0.7.0", "clsx": "2.0.0", "ethers": "6.8.0", "lucide-react": "0.292.0", "next": "15.0.2", "react": "^18", "react-dom": "^18", "tailwind-merge": "2.0.0", "tailwindcss-animate": "1.0.7" }, "devDependencies": { "@types/node": "^20", "@types/react": "^18", "@types/react-dom": "^18", "autoprefixer": "10.0.1", "eslint": "^8", "eslint-config-next": "14.0.3", "postcss": "^8", "tailwindcss": "3.3.0", "typescript": "^5" } } ================================================ FILE: 15-dns-protocol/Frontend/postcss.config.mjs ================================================ /** @type {import('postcss-load-config').Config} */ const config = { plugins: { tailwindcss: {}, }, }; export default config; ================================================ FILE: 15-dns-protocol/Frontend/tailwind.config.ts ================================================ import type { Config } from "tailwindcss"; const config: Config = { darkMode: ["class"], content: [ "./pages/**/*.{js,ts,jsx,tsx,mdx}", "./components/**/*.{js,ts,jsx,tsx,mdx}", "./app/**/*.{js,ts,jsx,tsx,mdx}", ], theme: { extend: { colors: { background: 'hsl(var(--background))', foreground: 'hsl(var(--foreground))', card: { DEFAULT: 'hsl(var(--card))', foreground: 'hsl(var(--card-foreground))' }, popover: { DEFAULT: 'hsl(var(--popover))', foreground: 'hsl(var(--popover-foreground))' }, primary: { DEFAULT: 'hsl(var(--primary))', foreground: 'hsl(var(--primary-foreground))' }, secondary: { DEFAULT: 'hsl(var(--secondary))', foreground: 'hsl(var(--secondary-foreground))' }, muted: { DEFAULT: 'hsl(var(--muted))', foreground: 'hsl(var(--muted-foreground))' }, accent: { DEFAULT: 'hsl(var(--accent))', foreground: 'hsl(var(--accent-foreground))' }, destructive: { DEFAULT: 'hsl(var(--destructive))', foreground: 'hsl(var(--destructive-foreground))' }, border: 'hsl(var(--border))', input: 'hsl(var(--input))', ring: 'hsl(var(--ring))', chart: { '1': 'hsl(var(--chart-1))', '2': 'hsl(var(--chart-2))', '3': 'hsl(var(--chart-3))', '4': 'hsl(var(--chart-4))', '5': 'hsl(var(--chart-5))' } }, borderRadius: { lg: 'var(--radius)', md: 'calc(var(--radius) - 2px)', sm: 'calc(var(--radius) - 4px)' } } }, plugins: [require("tailwindcss-animate")], }; export default config; ================================================ FILE: 15-dns-protocol/Frontend/tsconfig.json ================================================ { "compilerOptions": { "target": "ES2017", "lib": ["dom", "dom.iterable", "esnext"], "allowJs": true, "skipLibCheck": true, "strict": true, "noEmit": true, "esModuleInterop": true, "module": "esnext", "moduleResolution": "bundler", "resolveJsonModule": true, "isolatedModules": true, "jsx": "preserve", "incremental": true, "plugins": [ { "name": "next" } ], "paths": { "@/*": ["./*"] } }, "include": ["next-env.d.ts", "**/*.ts", "**/*.tsx", ".next/types/**/*.ts"], "exclude": ["node_modules"] } ================================================ FILE: 15-dns-protocol/Frontend/types/global.d.ts ================================================ declare global { interface Window { ethereum?: { isMetaMask?: boolean request: (request: { method: string; params?: any[] }) => Promise on: (event: string, listener: (...args: any[]) => void) => void removeListener: (event: string, listener: (...args: any[]) => void) => void } } } export {} ================================================ FILE: 15-dns-protocol/README.md ================================================ # CORE DNS-Protocol A decentralized naming service (DNS) protocol on the CORE blockchain, inspired by Ethereum Name Service (ENS). This project lets users register human-readable `.core` domains, map them to on-chain and off-chain resources, and manage ownership through smart contracts. 👉 Live App: [CoreDns](https://coredns.vercel.app/) ## 🚀 Features - **Domain Registry**: Store and manage ownership, registration, and expiration of `.core` domains. - **Resolver**: Associate domains with detailed records (wallet address, IPFS hash, email, social media link). - **Registrar**: Handle domain registration and renewal with a configurable fee and period. - **Front-end dApp**: Next.js application for users to connect wallets, register domains, view public registry, and manage personal domains. ## 📂 Project Structure ``` dns-protocol/ ├── contracts/ # Solidity smart contracts │ ├── ENS-Registry.sol # Core registry contract │ ├── ResolverContract.sol# Enhanced resolver for domain records │ └── RegistrationContract.sol # Registrar for registration logic ├── scripts/ # Deployment scripts │ └── deploy.js # Deploy registry & registrar ├── test/ # Hardhat tests (sample Lock contract) │ └── Lock.js ├── Frontend/ # Next.js front-end application ├── hardhat.config.js # Hardhat configuration (CORE testnet) ├── package.json └── README.md # This file ``` ## 🔧 Tech Stack - **Blockchain**: EVM-compatible CORE chain (testnet RPC at `https://rpc.test2.btcs.network`). - **Smart Contracts**: Solidity 0.8.x, Hardhat, Ethers.js. - **Front-end**: Next.js, TypeScript, Tailwind CSS, Ethers.js. ## 🛠 Prerequisites - [Node.js](https://nodejs.org/) (v16+) - [npm](https://www.npmjs.com/) or [Yarn](https://yarnpkg.com/) - [Hardhat CLI](https://hardhat.org/) - A CORE testnet wallet and a funded account private key ## 🚀 Getting Started ### 1. Clone the repository ```bash git clone https://github.com/coredao-org/dapp-tutorial.git cd dapp-tutorial/15-dns-protocol ``` ### 2. Install dependencies (root) ```bash npm install ``` ### 3. Configure environment Create a `.env` file in the root folder with: ```ini PRIVATE_KEY=your_core_testnet_private_key RPC_URL=https://rpc.test2.btcs.network ``` ### 4. Compile & Deploy Contracts Compile contracts: ```bash npx hardhat compile ``` Deploy to CORE testnet: ```bash npx hardhat run scripts/deploy.js --network core ``` > _Note the deployed addresses printed in console._ ### 5. Configure Front-end 1. Navigate to the `Frontend` folder: ```bash cd Frontend ``` 2. Install front-end dependencies: ```bash npm install ``` 3. Open the config.json file located in the constants folder within the Frontend directory: ```bash Frontend/constants/config.json ``` Update the contract addresses as follows: Contract One Address: Replace with the deployed address of the ENS Registry contract. Contract Two Address: Replace with the deployed address of the Registrar contract. Ensure that the addresses are correctly formatted as strings. For example: ```ini { "contractOneAddress": "0xYourENSRegistryAddress", "contractTwoAddress": "0xYourRegistrarAddress" } ``` ### 6. Run the Front-end ```bash npm run dev ``` Open your browser at `http://localhost:3000` to interact with the DNS dApp. ## 🧑‍💻 Usage Overview 1. **Public Registry Page**: View all registered `.core` domains and their owners. 2. **Search**: Filter domains by name to see owner details. 3. **Connect Wallet**: Use MetaMask or other EVM wallet to connect. 4. **Register Domain**: Type your desired name (without `.core`), the suffix is added automatically. If available, confirm transaction. If taken, an error displays the current owner. 5. **My Domains**: In your dashboard, view domains owned by your connected wallet. 6. **Resolver Management**: (Optional) Update domain records (wallet, IPFS, email, social) via the resolver interface. ## 📝 Testing > _The provided tests cover the sample Lock contract._ Run Hardhat tests: ```bash npx hardhat test ``` ## 🤝 Contributing Contributions are welcome! Please: 1. Fork the repo 2. Create a new branch (`git checkout -b feature/YourFeature`) 3. Commit your changes (`git commit -m "Add awesome feature"`) 4. Push to your branch (`git push origin feature/YourFeature`) 5. Open a Pull Request ================================================ FILE: 15-dns-protocol/contracts/ENS-Registry.sol ================================================ // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @title ENSRegistry * @notice This contract acts as the primary directory for domain names. * It stores ownership information, pointers to resolver contracts, and expiration times. */ contract ENSRegistry { // A record for each domain name struct Record { bytes32 domainName; address owner; // The wallet address that owns the domain address resolver; // Address of the resolver contract for this domain uint256 registration; // When the domain was registered uint256 expiration; // When the domain registration expires } // Mapping from a domain node (e.g., keccak256 hash of the domain name) to its record. mapping(bytes32 => Record) public records; // Array of all records for iteration purposes Record[] private allRecords; // Events to log changes in the registry. event NewDomain(bytes32 indexed domain, address owner); event Transfer(bytes32 indexed domain, address newOwner); event SetResolver(bytes32 indexed domain, address resolver); event RenewDomain(bytes32 indexed domain, uint256 expiration); /** * @notice Sets or updates the record for a domain. * @param domainHash The unique identifier for the domain. * @param owner The wallet address of the domain owner. * @param resolver The resolver contract address associated with this domain. * @param registration The timestamp when the domain was registered. * @param expiration The timestamp when the registration expires. */ function setRecord( bytes32 domainHash, address owner, address resolver, uint256 registration, uint256 expiration ) external { // Allow update if the caller is the current owner or if the domain is unregistered. require( msg.sender == records[domainHash].owner || records[domainHash].owner == address(0), "Not authorized" ); Record memory record = Record(domainHash, owner, resolver, registration, expiration); records[domainHash] = record; allRecords.push(record); emit NewDomain(domainHash, owner); } /** * @notice Transfers domain ownership to a new address. * @param domainHash The unique identifier for the domain. * @param newOwner The wallet address of the new owner. */ function transferOwnership(bytes32 domainHash, address newOwner) external { require(msg.sender == records[domainHash].owner, "Not authorized"); records[domainHash].owner = newOwner; emit Transfer(domainHash, newOwner); } /** * @notice Sets or updates the resolver for a domain. * @param domainHash The unique identifier for the domain. * @param resolver The new resolver contract address. */ function setResolver(bytes32 domainHash, address resolver) external { require(msg.sender == records[domainHash].owner, "Not authorized"); records[domainHash].resolver = resolver; emit SetResolver(domainHash, resolver); } /** * @notice Retrieve a specific record by domain hash. * @param domainHash The unique identifier for the domain. * @return The Record struct for the domain. */ function getSpecificRecord(bytes32 domainHash) external view returns (Record memory) { return records[domainHash]; } /** * @notice Retrieve all recorded domains. * @return An array of all Record structs. */ function getAllRecords() external view returns (Record[] memory) { return allRecords; } /** * @notice Retrieve all domain names owned by a particular address. * @param ownerAddress The address to query ownership for. * @return An array of domain hashes owned by the specified address. */ function getDomainsByOwner(address ownerAddress) external view returns (bytes32[] memory) { uint256 total = allRecords.length; uint256 count = 0; // First count how many domains belong to ownerAddress for (uint256 i = 0; i < total; i++) { if (allRecords[i].owner == ownerAddress) { count++; } } // Populate result array bytes32[] memory domains = new bytes32[](count); uint256 index = 0; for (uint256 i = 0; i < total; i++) { if (allRecords[i].owner == ownerAddress) { domains[index] = allRecords[i].domainName; index++; } } return domains; } } ================================================ FILE: 15-dns-protocol/contracts/RegistrationContract.sol ================================================ // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./ENS-Registry.sol"; import "./ResolverContract.sol"; /** * @title Registrar * @notice This contract handles domain registrations and renewals. * It interacts with the ENSRegistry to update domain records. */ contract Registrar { ENSRegistry public registry; // The registry contract that keeps domain records. uint256 public registrationPeriod = 365 days; // How long a domain remains registered. uint256 public registrationFee; // Fee required for registration or renewal. // Event to log domain registrations. event DomainRegistered(bytes32 indexed domainHash, address owner, uint256 expiration); /** * @notice Constructor sets the address of the ENSRegistry contract. * @param _registry The deployed ENSRegistry contract address. */ constructor(address _registry, uint256 _fee) { registry = ENSRegistry(_registry); registrationFee = _fee; } /** * @notice Registers a new domain. * @param domainHash The unique identifier for the domain. * Requirements: * - The domain must be unregistered or its registration must have expired. * - The sender must pay at least the registration fee. */ function register(bytes32 domainHash) external payable { require(msg.value >= registrationFee, "Insufficient fee"); ENSRegistry.Record memory rec = registry.getSpecificRecord(domainHash); // Check if the domain is either unregistered or its registration has expired. require(rec.owner == address(0) || rec.expiration < block.timestamp, "Domain already registered"); uint256 expiration = block.timestamp + registrationPeriod; registry.setRecord(domainHash, msg.sender, address(0), block.timestamp, expiration); emit DomainRegistered(domainHash, msg.sender, expiration); } /** * @notice Renews an existing domain registration. * @param domainHash The unique identifier for the domain. * Requirements: * - The sender must be the current owner. * - The sender must pay at least the registration fee. */ function renew(bytes32 domainHash) external payable { require(msg.value >= registrationFee, "Insufficient fee"); ENSRegistry.Record memory rec = registry.getSpecificRecord(domainHash); require(rec.owner == msg.sender, "Not the owner"); uint256 newExpiration; // If still active, extend from current expiration; otherwise, start from now. if (rec.expiration > block.timestamp) { newExpiration = rec.expiration + registrationPeriod; } else { newExpiration = block.timestamp + registrationPeriod; } registry.setRecord(domainHash, msg.sender, rec.resolver, block.timestamp, newExpiration); emit DomainRegistered(domainHash, msg.sender, newExpiration); } } ================================================ FILE: 15-dns-protocol/contracts/ResolverContract.sol ================================================ // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @title EnhancedResolver * @notice This contract stores multiple types of records for a domain. * It allows a domain owner to set details such as a wallet address, IPFS hash, email, and social media link. */ contract Resolver { // Structure that holds various details for a domain. struct Records { address wallet; // A wallet address (for payments or identification) string ipfsHash; // IPFS hash pointing to content (e.g., decentralized website) string email; // Contact email address string socialMedia; // Social media link or profile } // Mapping from the domain node to its set of records. mapping(bytes32 => Records) public records; // Event to notify when a domain's records are updated. event RecordsUpdated( bytes32 indexed node, address wallet, string ipfsHash, string email, string socialMedia ); /** * @notice Sets the records for a domain. * @param node The unique identifier for the domain. * @param wallet The wallet address to associate with the domain. * @param ipfsHash The IPFS hash for content related to the domain. * @param email The email address associated with the domain. * @param socialMedia The social media link related to the domain. * * Note: In a full implementation, access control should be enforced so that only the domain owner can update records. */ function setRecordsDetails( bytes32 node, address wallet, string memory ipfsHash, string memory email, string memory socialMedia ) public { // Access control should be added here (e.g., check with ENSRegistry for ownership) records[node] = Records(wallet, ipfsHash, email, socialMedia); emit RecordsUpdated(node, wallet, ipfsHash, email, socialMedia); } /** * @notice Retrieves all records associated with a domain. * @param node The unique identifier for the domain. * @return wallet The wallet address, ipfsHash The IPFS hash, * email The email address, socialMedia The social media link. */ function getRecordDetails(bytes32 node) public view returns ( address wallet, string memory ipfsHash, string memory email, string memory socialMedia ) { Records memory rec = records[node]; return (rec.wallet, rec.ipfsHash, rec.email, rec.socialMedia); } } ================================================ FILE: 15-dns-protocol/hardhat.config.js ================================================ require("@nomicfoundation/hardhat-toolbox"); require("dotenv").config(); /** @type import('hardhat/config').HardhatUserConfig */ const PRIVATE_KEY = process.env.PRIVATE_KEY; module.exports = { solidity: "0.8.24", networks: { localhost: { url: "http://127.0.0.1:8545/", // accounts: Thanks hardhat! chainId: 31337, allowUnlimitedContractSize: true, }, core: { url: "https://rpc.test2.btcs.network", accounts: [PRIVATE_KEY], chainId: 1114, }, }, }; ================================================ FILE: 15-dns-protocol/ignition/modules/Lock.js ================================================ // This setup uses Hardhat Ignition to manage smart contract deployments. // Learn more about it at https://hardhat.org/ignition const { buildModule } = require("@nomicfoundation/hardhat-ignition/modules"); const JAN_1ST_2030 = 1893456000; const ONE_GWEI = 1_000_000_000n; module.exports = buildModule("LockModule", (m) => { const unlockTime = m.getParameter("unlockTime", JAN_1ST_2030); const lockedAmount = m.getParameter("lockedAmount", ONE_GWEI); const lock = m.contract("Lock", [unlockTime], { value: lockedAmount, }); return { lock }; }); ================================================ FILE: 15-dns-protocol/package.json ================================================ { "name": "reuse", "version": "1.0.0", "main": "index.js", "scripts": { "test": "echo \"Error: no test specified\" && exit 1" }, "author": "", "license": "ISC", "description": "", "devDependencies": { "@nomicfoundation/hardhat-toolbox": "5.0.0", "hardhat": "2.22.15" }, "dependencies": { "dotenv": "16.5.0" } } ================================================ FILE: 15-dns-protocol/scripts/deploy.js ================================================ const hre = require("hardhat"); async function main() { const fee = ethers.parseUnits("0.01", 18); const ENSRegistry = await hre.ethers.getContractFactory("ENSRegistry"); const ensContract = await ENSRegistry.deploy(); console.log("Storage contract deployed to:", ensContract.target); const RegistrarContract = await hre.ethers.getContractFactory("Registrar"); const registrarContract = await RegistrarContract.deploy(ensContract.target, fee); console.log("Storage contract deployed to:", registrarContract.target); // const bytes322 = ethers.encodeBytes32String("David.core"); // const bytes3 = ethers.encodeBytes32String("alice.core"); // const decode = ethers.decodeBytes32String(bytes322); // console.log(bytes3) // console.log(decode) // await registrarContract.register(bytes322); // await registrarContract.register(bytes3); // const specificRecord = await ensContract.getSpecificRecord(bytes322); // console.log(specificRecord); // const allRecords = await ensContract.getAllRecords(); // console.log(allRecords); } // We recommend this pattern to be able to use async/await everywhere // and properly handle errors. main().catch((error) => { console.error(error); process.exitCode = 1; }); // Telos: Support contract deployed to: 0x5Ac64F5DA22B25559C7D7522b4B2BB7e2012F382 ================================================ FILE: 15-dns-protocol/test/Lock.js ================================================ const { time, loadFixture, } = require("@nomicfoundation/hardhat-toolbox/network-helpers"); const { anyValue } = require("@nomicfoundation/hardhat-chai-matchers/withArgs"); const { expect } = require("chai"); describe("Lock", function () { // We define a fixture to reuse the same setup in every test. // We use loadFixture to run this setup once, snapshot that state, // and reset Hardhat Network to that snapshot in every test. async function deployOneYearLockFixture() { const ONE_YEAR_IN_SECS = 365 * 24 * 60 * 60; const ONE_GWEI = 1_000_000_000; const lockedAmount = ONE_GWEI; const unlockTime = (await time.latest()) + ONE_YEAR_IN_SECS; // Contracts are deployed using the first signer/account by default const [owner, otherAccount] = await ethers.getSigners(); const Lock = await ethers.getContractFactory("Lock"); const lock = await Lock.deploy(unlockTime, { value: lockedAmount }); return { lock, unlockTime, lockedAmount, owner, otherAccount }; } describe("Deployment", function () { it("Should set the right unlockTime", async function () { const { lock, unlockTime } = await loadFixture(deployOneYearLockFixture); expect(await lock.unlockTime()).to.equal(unlockTime); }); it("Should set the right owner", async function () { const { lock, owner } = await loadFixture(deployOneYearLockFixture); expect(await lock.owner()).to.equal(owner.address); }); it("Should receive and store the funds to lock", async function () { const { lock, lockedAmount } = await loadFixture( deployOneYearLockFixture ); expect(await ethers.provider.getBalance(lock.target)).to.equal( lockedAmount ); }); it("Should fail if the unlockTime is not in the future", async function () { // We don't use the fixture here because we want a different deployment const latestTime = await time.latest(); const Lock = await ethers.getContractFactory("Lock"); await expect(Lock.deploy(latestTime, { value: 1 })).to.be.revertedWith( "Unlock time should be in the future" ); }); }); describe("Withdrawals", function () { describe("Validations", function () { it("Should revert with the right error if called too soon", async function () { const { lock } = await loadFixture(deployOneYearLockFixture); await expect(lock.withdraw()).to.be.revertedWith( "You can't withdraw yet" ); }); it("Should revert with the right error if called from another account", async function () { const { lock, unlockTime, otherAccount } = await loadFixture( deployOneYearLockFixture ); // We can increase the time in Hardhat Network await time.increaseTo(unlockTime); // We use lock.connect() to send a transaction from another account await expect(lock.connect(otherAccount).withdraw()).to.be.revertedWith( "You aren't the owner" ); }); it("Shouldn't fail if the unlockTime has arrived and the owner calls it", async function () { const { lock, unlockTime } = await loadFixture( deployOneYearLockFixture ); // Transactions are sent using the first signer by default await time.increaseTo(unlockTime); await expect(lock.withdraw()).not.to.be.reverted; }); }); describe("Events", function () { it("Should emit an event on withdrawals", async function () { const { lock, unlockTime, lockedAmount } = await loadFixture( deployOneYearLockFixture ); await time.increaseTo(unlockTime); await expect(lock.withdraw()) .to.emit(lock, "Withdrawal") .withArgs(lockedAmount, anyValue); // We accept any value as `when` arg }); }); describe("Transfers", function () { it("Should transfer the funds to the owner", async function () { const { lock, unlockTime, lockedAmount, owner } = await loadFixture( deployOneYearLockFixture ); await time.increaseTo(unlockTime); await expect(lock.withdraw()).to.changeEtherBalances( [owner, lock], [lockedAmount, -lockedAmount] ); }); }); }); }); ================================================ FILE: 16-Pump.Core/.gitignore ================================================ node_modules .env # Hardhat files /cache /artifacts # TypeChain files /typechain /typechain-types # solidity-coverage files /coverage /coverage.json # Hardhat Ignition default folder for deployments against a local node ignition/deployments/chain-31337 ================================================ FILE: 16-Pump.Core/Frontend/.eslintrc.json ================================================ { "extends": ["next/core-web-vitals", "next/typescript"] } ================================================ FILE: 16-Pump.Core/Frontend/.gitignore ================================================ # See https://help.github.com/articles/ignoring-files/ for more about ignoring files. # dependencies /node_modules /.pnp .pnp.* .yarn/* !.yarn/patches !.yarn/plugins !.yarn/releases !.yarn/versions # testing /coverage # next.js /.next/ /out/ # production /build # misc .DS_Store *.pem # debug npm-debug.log* yarn-debug.log* yarn-error.log* # env files (can opt-in for commiting if needed) .env* # vercel .vercel # typescript *.tsbuildinfo next-env.d.ts ================================================ FILE: 16-Pump.Core/Frontend/README.md ================================================ This is a [Next.js](https://nextjs.org) project bootstrapped with [`create-next-app`](https://nextjs.org/docs/app/api-reference/cli/create-next-app). ## Getting Started First, run the development server: ```bash npm run dev # or yarn dev # or pnpm dev # or bun dev ``` Open [http://localhost:3000](http://localhost:3000) with your browser to see the result. You can start editing the page by modifying `app/page.tsx`. The page auto-updates as you edit the file. This project uses [`next/font`](https://nextjs.org/docs/app/building-your-application/optimizing/fonts) to automatically optimize and load [Geist](https://vercel.com/font), a new font family for Vercel. ## Learn More To learn more about Next.js, take a look at the following resources: - [Next.js Documentation](https://nextjs.org/docs) - learn about Next.js features and API. - [Learn Next.js](https://nextjs.org/learn) - an interactive Next.js tutorial. You can check out [the Next.js GitHub repository](https://github.com/vercel/next.js) - your feedback and contributions are welcome! ## Deploy on Vercel The easiest way to deploy your Next.js app is to use the [Vercel Platform](https://vercel.com/new?utm_medium=default-template&filter=next.js&utm_source=create-next-app&utm_campaign=create-next-app-readme) from the creators of Next.js. Check out our [Next.js deployment documentation](https://nextjs.org/docs/app/building-your-application/deploying) for more details. ================================================ FILE: 16-Pump.Core/Frontend/app/dashboard/page.tsx ================================================ "use client" import { useState, useEffect } from "react" import { Navbar } from "@/components/navbar" import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs" import { CreatorDashboard } from "@/components/creator-dashboard" import { OwnerDashboard } from "@/components/owner-dashboard" import { useWeb3 } from "@/hooks/use-web3" import { Loader2 } from "lucide-react" export default function Dashboard() { const { account, contract } = useWeb3() const [isOwner, setIsOwner] = useState(false) const [loading, setLoading] = useState(true) useEffect(() => { const checkOwner = async () => { if (contract && account) { try { // In a real implementation, this would check if the current account is the contract owner // const owner = await contract.owner() // setIsOwner(owner.toLowerCase() === account.toLowerCase()) // For demo purposes, we'll randomly set isOwner setIsOwner(Math.random() > 0.7) } catch (error) { console.error("Error checking owner:", error) setIsOwner(false) } finally { setLoading(false) } } else { setLoading(false) } } checkOwner() }, [contract, account]) if (!account) { return (

Dashboard

Please connect your wallet to view your dashboard.

) } if (loading) { return (
) } return (

Dashboard

Creator Dashboard {isOwner && Owner Dashboard} {isOwner && ( )}
) } ================================================ FILE: 16-Pump.Core/Frontend/app/globals.css ================================================ @tailwind base; @tailwind components; @tailwind utilities; @layer base { :root { --background: 0 0% 100%; --foreground: 240 10% 3.9%; --card: 0 0% 100%; --card-foreground: 240 10% 3.9%; --popover: 0 0% 100%; --popover-foreground: 240 10% 3.9%; --primary: 24 100% 50%; --primary-foreground: 0 0% 98%; --secondary: 240 4.8% 95.9%; --secondary-foreground: 240 5.9% 10%; --muted: 240 4.8% 95.9%; --muted-foreground: 240 3.8% 46.1%; --accent: 240 4.8% 95.9%; --accent-foreground: 240 5.9% 10%; --destructive: 0 84.2% 60.2%; --destructive-foreground: 0 0% 98%; --border: 240 5.9% 90%; --input: 240 5.9% 90%; --ring: 24 100% 50%; --radius: 0.5rem; } .dark { --background: 240 10% 3.9%; --foreground: 0 0% 98%; --card: 240 10% 3.9%; --card-foreground: 0 0% 98%; --popover: 240 10% 3.9%; --popover-foreground: 0 0% 98%; --primary: 24 100% 50%; --primary-foreground: 0 0% 98%; --secondary: 240 3.7% 15.9%; --secondary-foreground: 0 0% 98%; --muted: 240 3.7% 15.9%; --muted-foreground: 240 5% 64.9%; --accent: 240 3.7% 15.9%; --accent-foreground: 0 0% 98%; --destructive: 0 62.8% 30.6%; --destructive-foreground: 0 0% 98%; --border: 240 3.7% 15.9%; --input: 240 3.7% 15.9%; --ring: 24 100% 50%; } } @layer base { * { @apply border-border; } body { @apply bg-background text-foreground; } } ================================================ FILE: 16-Pump.Core/Frontend/app/layout.tsx ================================================ import type React from "react" import type { Metadata } from "next" import { Inter } from "next/font/google" import "./globals.css" import { Web3Provider } from "@/providers/web3-provider" import { Toaster } from "@/components/ui/toaster" // import { ThemeProvider } from "@/components/theme-provider" const inter = Inter({ subsets: ["latin"] }) export const metadata: Metadata = { title: "MemeFactory UI", description: "Create and trade meme tokens on Ethereum", } export default function RootLayout({ children, }: Readonly<{ children: React.ReactNode }>) { return ( {children} ) } ================================================ FILE: 16-Pump.Core/Frontend/app/page.tsx ================================================ import { Navbar } from "@/components/navbar" import { TokenListing } from "@/components/token-listing" import { LaunchTokenButton } from "@/components/launch-token-button" export default function Home() { return (

MemeFactory

Create and trade meme tokens on Ethereum. Launch your own token in minutes.

) } ================================================ FILE: 16-Pump.Core/Frontend/app/scss/_layout.scss ================================================ .container { width: 100%; max-width: 1400px; margin: 0 auto; padding: 0 $spacing-4; @include md { padding: 0 $spacing-6; } } .main { min-height: 100vh; background-color: $color-zinc-50; } .home-content { display: flex; flex-direction: column; gap: $spacing-6; padding: $spacing-8 0; } .hero-section { display: flex; flex-direction: column; justify-content: space-between; align-items: center; gap: $spacing-4; background-color: $color-white; padding: $spacing-6; border-radius: $radius-xl; box-shadow: 0 1px 3px rgba(0, 0, 0, 0.05); border: 1px solid $color-zinc-100; @include md { flex-direction: row; } } .hero-content { display: flex; flex-direction: column; gap: $spacing-2; max-width: 100%; @include md { max-width: 60%; } } .hero-title { font-size: $font-size-2xl; font-weight: $font-weight-bold; margin-bottom: $spacing-2; @include md { font-size: $font-size-3xl; } } .hero-description { color: $color-zinc-500; max-width: 32rem; } .sr-only { position: absolute; width: 1px; height: 1px; padding: 0; margin: -1px; overflow: hidden; clip: rect(0, 0, 0, 0); white-space: nowrap; border-width: 0; } ================================================ FILE: 16-Pump.Core/Frontend/app/scss/_mixins.scss ================================================ @mixin sm { @media (min-width: $breakpoint-sm) { @content; } } @mixin md { @media (min-width: $breakpoint-md) { @content; } } @mixin lg { @media (min-width: $breakpoint-lg) { @content; } } @mixin xl { @media (min-width: $breakpoint-xl) { @content; } } @mixin xxl { @media (min-width: $breakpoint-2xl) { @content; } } // Flexbox helpers @mixin flex($direction: row, $justify: flex-start, $align: stretch, $wrap: nowrap) { display: flex; flex-direction: $direction; justify-content: $justify; align-items: $align; flex-wrap: $wrap; } // Grid helpers @mixin grid($columns: 1, $gap: $spacing-4) { display: grid; grid-template-columns: repeat($columns, 1fr); gap: $gap; } // Typography @mixin text-truncate { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } // Buttons @mixin button-base { display: inline-flex; align-items: center; justify-content: center; font-weight: $font-weight-medium; border-radius: $radius-md; transition: $transition-base; cursor: pointer; &:disabled { opacity: 0.5; cursor: not-allowed; } } // Focus styles @mixin focus-ring { outline: none; box-shadow: 0 0 0 2px rgba($color-primary, 0.5); } // Card styles @mixin card { background-color: $color-background; border-radius: $radius-lg; border: 1px solid $color-border; overflow: hidden; } ================================================ FILE: 16-Pump.Core/Frontend/app/scss/_reset.scss ================================================ *, *::before, *::after { box-sizing: border-box; } /* Remove default margin */ body, h1, h2, h3, h4, p, figure, blockquote, dl, dd { margin: 0; } /* Remove list styles on ul, ol elements */ ul, ol { list-style: none; padding: 0; margin: 0; } /* Set core root defaults */ html:focus-within { scroll-behavior: smooth; } /* Set core body defaults */ body { min-height: 100vh; text-rendering: optimizeSpeed; line-height: 1.5; font-family: $font-family-sans; } /* A elements that don't have a class get default styles */ a:not([class]) { text-decoration-skip-ink: auto; } /* Make images easier to work with */ img, picture { max-width: 100%; display: block; } /* Inherit fonts for inputs and buttons */ input, button, textarea, select { font: inherit; } /* Remove all animations, transitions and smooth scroll for people that prefer not to see them */ @media (prefers-reduced-motion: reduce) { html:focus-within { scroll-behavior: auto; } *, *::before, *::after { animation-duration: 0.01ms !important; animation-iteration-count: 1 !important; transition-duration: 0.01ms !important; scroll-behavior: auto !important; } } ================================================ FILE: 16-Pump.Core/Frontend/app/scss/_typography.scss ================================================ body { font-family: $font-family-sans; font-size: $font-size-base; line-height: 1.5; color: $color-foreground; } h1, h2, h3, h4, h5, h6 { font-weight: $font-weight-bold; line-height: 1.2; margin-bottom: $spacing-4; } h1 { font-size: $font-size-3xl; @include md { font-size: $font-size-4xl; } } h2 { font-size: $font-size-2xl; @include md { font-size: $font-size-3xl; } } h3 { font-size: $font-size-xl; @include md { font-size: $font-size-2xl; } } h4 { font-size: $font-size-lg; } p { margin-bottom: $spacing-4; } a { color: $color-primary; text-decoration: none; transition: $transition-base; &:hover { color: $color-primary-hover; } } .text-xs { font-size: $font-size-xs; } .text-sm { font-size: $font-size-sm; } .text-base { font-size: $font-size-base; } .text-lg { font-size: $font-size-lg; } .text-xl { font-size: $font-size-xl; } .text-2xl { font-size: $font-size-2xl; } .font-normal { font-weight: $font-weight-normal; } .font-medium { font-weight: $font-weight-medium; } .font-semibold { font-weight: $font-weight-semibold; } .font-bold { font-weight: $font-weight-bold; } ================================================ FILE: 16-Pump.Core/Frontend/app/scss/_utilities.scss ================================================ .block { display: block; } .inline-block { display: inline-block; } .inline { display: inline; } .flex { display: flex; } .inline-flex { display: inline-flex; } .grid { display: grid; } .hidden { display: none; } // Flex utilities .flex-row { flex-direction: row; } .flex-col { flex-direction: column; } .flex-wrap { flex-wrap: wrap; } .flex-nowrap { flex-wrap: nowrap; } .items-start { align-items: flex-start; } .items-center { align-items: center; } .items-end { align-items: flex-end; } .justify-start { justify-content: flex-start; } .justify-center { justify-content: center; } .justify-end { justify-content: flex-end; } .justify-between { justify-content: space-between; } // Spacing .m-0 { margin: $spacing-0; } .m-1 { margin: $spacing-1; } .m-2 { margin: $spacing-2; } .m-4 { margin: $spacing-4; } .m-6 { margin: $spacing-6; } .m-8 { margin: $spacing-8; } .mx-auto { margin-left: auto; margin-right: auto; } .mt-1 { margin-top: $spacing-1; } .mt-2 { margin-top: $spacing-2; } .mt-4 { margin-top: $spacing-4; } .mt-6 { margin-top: $spacing-6; } .mt-8 { margin-top: $spacing-8; } .mb-1 { margin-bottom: $spacing-1; } .mb-2 { margin-bottom: $spacing-2; } .mb-4 { margin-bottom: $spacing-4; } .mb-6 { margin-bottom: $spacing-6; } .mb-8 { margin-bottom: $spacing-8; } .ml-auto { margin-left: auto; } .mr-auto { margin-right: auto; } .p-0 { padding: $spacing-0; } .p-1 { padding: $spacing-1; } .p-2 { padding: $spacing-2; } .p-4 { padding: $spacing-4; } .p-6 { padding: $spacing-6; } .p-8 { padding: $spacing-8; } .py-1 { padding-top: $spacing-1; padding-bottom: $spacing-1; } .py-2 { padding-top: $spacing-2; padding-bottom: $spacing-2; } .py-4 { padding-top: $spacing-4; padding-bottom: $spacing-4; } .py-6 { padding-top: $spacing-6; padding-bottom: $spacing-6; } .py-8 { padding-top: $spacing-8; padding-bottom: $spacing-8; } .px-1 { padding-left: $spacing-1; padding-right: $spacing-1; } .px-2 { padding-left: $spacing-2; padding-right: $spacing-2; } .px-4 { padding-left: $spacing-4; padding-right: $spacing-4; } .px-6 { padding-left: $spacing-6; padding-right: $spacing-6; } .px-8 { padding-left: $spacing-8; padding-right: $spacing-8; } // Text alignment .text-left { text-align: left; } .text-center { text-align: center; } .text-right { text-align: right; } // Text colors .text-primary { color: $color-primary; } .text-muted { color: $color-muted-foreground; } .text-white { color: $color-white; } .text-danger { color: $color-red-500; } .text-success { color: $color-green-500; } // Background colors .bg-white { background-color: $color-white; } .bg-muted { background-color: $color-muted; } .bg-primary { background-color: $color-primary; } .bg-danger { background-color: $color-red-500; } .bg-success { background-color: $color-green-500; } // Width and height .w-full { width: 100%; } .h-full { height: 100%; } .min-h-screen { min-height: 100vh; } // Borders .rounded-sm { border-radius: $radius-sm; } .rounded-md { border-radius: $radius-md; } .rounded-lg { border-radius: $radius-lg; } .rounded-xl { border-radius: $radius-xl; } .rounded-full { border-radius: $radius-full; } .border { border: 1px solid $color-border; } .border-t { border-top: 1px solid $color-border; } .border-r { border-right: 1px solid $color-border; } .border-b { border-bottom: 1px solid $color-border; } .border-l { border-left: 1px solid $color-border; } // Shadows .shadow-sm { box-shadow: $shadow-sm; } .shadow-md { box-shadow: $shadow-md; } .shadow-lg { box-shadow: $shadow-lg; } // Position .relative { position: relative; } .absolute { position: absolute; } .fixed { position: fixed; } .sticky { position: sticky; } .inset-0 { top: 0; right: 0; bottom: 0; left: 0; } .z-10 { z-index: 10; } .z-20 { z-index: 20; } .z-30 { z-index: 30; } .z-40 { z-index: 40; } .z-50 { z-index: 50; } // Overflow .overflow-hidden { overflow: hidden; } .overflow-auto { overflow: auto; } .overflow-scroll { overflow: scroll; } .overflow-x-auto { overflow-x: auto; } .overflow-y-auto { overflow-y: auto; } // Cursor .cursor-pointer { cursor: pointer; } .cursor-not-allowed { cursor: not-allowed; } ================================================ FILE: 16-Pump.Core/Frontend/app/scss/_variables.scss ================================================ $color-orange-50: #fff8eb; $color-orange-100: #ffebc8; $color-orange-200: #ffd685; $color-orange-300: #ffbe42; $color-orange-400: #ffa50f; $color-orange-500: #ff9500; // Primary brand color $color-orange-600: #e66a00; $color-orange-700: #c04e00; $color-orange-800: #9a3d06; $color-orange-900: #7e340b; $color-white: #ffffff; $color-black: #000000; $color-zinc-50: #fafafa; $color-zinc-100: #f4f4f5; $color-zinc-200: #e4e4e7; $color-zinc-300: #d4d4d8; $color-zinc-400: #a1a1aa; $color-zinc-500: #71717a; $color-zinc-600: #52525b; $color-zinc-700: #3f3f46; $color-zinc-800: #27272a; $color-zinc-900: #18181b; $color-green-500: #22c55e; $color-red-500: #ef4444; // Theme colors $color-primary: $color-orange-500; $color-primary-hover: $color-orange-600; $color-primary-foreground: $color-white; $color-background: $color-white; $color-foreground: $color-zinc-900; $color-muted: $color-zinc-50; $color-muted-foreground: $color-zinc-500; $color-border: $color-zinc-200; $color-input: $color-zinc-200; // Typography $font-family-sans: 'Inter', -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu, Cantarell, 'Open Sans', 'Helvetica Neue', sans-serif; $font-size-xs: 0.75rem; // 12px $font-size-sm: 0.875rem; // 14px $font-size-base: 1rem; // 16px $font-size-lg: 1.125rem; // 18px $font-size-xl: 1.25rem; // 20px $font-size-2xl: 1.5rem; // 24px $font-size-3xl: 1.875rem; // 30px $font-size-4xl: 2.25rem; // 36px $font-weight-normal: 400; $font-weight-medium: 500; $font-weight-semibold: 600; $font-weight-bold: 700; // Spacing $spacing-0: 0; $spacing-1: 0.25rem; // 4px $spacing-2: 0.5rem; // 8px $spacing-3: 0.75rem; // 12px $spacing-4: 1rem; // 16px $spacing-5: 1.25rem; // 20px $spacing-6: 1.5rem; // 24px $spacing-8: 2rem; // 32px $spacing-10: 2.5rem; // 40px $spacing-12: 3rem; // 48px $spacing-16: 4rem; // 64px $spacing-20: 5rem; // 80px $spacing-24: 6rem; // 96px $spacing-32: 8rem; // 128px // Breakpoints $breakpoint-sm: 640px; $breakpoint-md: 768px; $breakpoint-lg: 1024px; $breakpoint-xl: 1280px; $breakpoint-2xl: 1536px; // Border radius $radius-sm: 0.125rem; // 2px $radius-md: 0.25rem; // 4px $radius-lg: 0.5rem; // 8px $radius-xl: 0.75rem; // 12px $radius-2xl: 1rem; // 16px $radius-full: 9999px; // Shadows $shadow-sm: 0 1px 2px 0 rgba(0, 0, 0, 0.05); $shadow-md: 0 4px 6px -1px rgba(0, 0, 0, 0.1), 0 2px 4px -1px rgba(0, 0, 0, 0.06); $shadow-lg: 0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -2px rgba(0, 0, 0, 0.05); // Z-index $z-index-dropdown: 1000; $z-index-sticky: 1020; $z-index-fixed: 1030; $z-index-modal-backdrop: 1040; $z-index-modal: 1050; $z-index-popover: 1060; $z-index-tooltip: 1070; // Transitions $transition-base: all 0.2s ease-in-out; $transition-slow: all 0.3s ease-in-out; $transition-fast: all 0.1s ease-in-out; ================================================ FILE: 16-Pump.Core/Frontend/app/scss/components/_badges.scss ================================================ .badge { display: inline-flex; align-items: center; justify-content: center; font-size: $font-size-xs; font-weight: $font-weight-medium; height: 1.25rem; padding: 0 $spacing-2; border-radius: $radius-full; color: $color-white; &--green { background-color: $color-green-500; } &--red { background-color: $color-red-500; } } ================================================ FILE: 16-Pump.Core/Frontend/app/scss/components/_buttons.scss ================================================ .button { @include button-base; height: 2.5rem; padding: 0 $spacing-4; font-size: $font-size-sm; background-color: $color-background; border: 1px solid $color-border; color: $color-foreground; &:hover:not(:disabled) { background-color: $color-zinc-50; } &:focus { @include focus-ring; } &--connect, &--connecting { background-color: $color-primary; border-color: $color-primary; color: $color-white; &:hover:not(:disabled) { background-color: $color-primary-hover; border-color: $color-primary-hover; } } &--connected { border-color: $color-primary; color: $color-primary; &:hover:not(:disabled) { background-color: rgba($color-primary, 0.05); } } &__icon { margin-right: $spacing-2; height: 1rem; width: 1rem; &--spinner { animation: spin 1s linear infinite; } } } .launch-button { @include button-base; height: 2.5rem; padding: 0 $spacing-4; font-size: $font-size-sm; background-color: $color-primary; border: 1px solid $color-primary; color: $color-white; &:hover:not(:disabled) { background-color: $color-primary-hover; border-color: $color-primary-hover; } &:focus { @include focus-ring; } &__icon { margin-right: $spacing-2; height: 1rem; width: 1rem; } } @keyframes spin { from { transform: rotate(0deg); } to { transform: rotate(360deg); } } ================================================ FILE: 16-Pump.Core/Frontend/app/scss/components/_cards.scss ================================================ .token-card { @include card; display: flex; flex-direction: column; &__header { padding: 0; } &__image-container { position: relative; height: 12rem; width: 100%; background-color: $color-zinc-100; } &__image { object-fit: cover; } &__badge { position: absolute; top: $spacing-3; right: $spacing-3; &--open { background-color: $color-green-500; } &--closed { background-color: $color-red-500; } } &__content { padding: $spacing-6; } &__title-row { @include flex(row, space-between, flex-start); margin-bottom: $spacing-4; } &__name { font-weight: $font-weight-bold; font-size: $font-size-lg; margin-bottom: 0; } &__symbol { font-size: $font-size-sm; color: $color-zinc-500; } &__stats { display: flex; flex-direction: column; gap: $spacing-4; } &__stat { &-header { @include flex(row, space-between); font-size: $font-size-sm; margin-bottom: $spacing-1; } &-value { font-weight: $font-weight-medium; } } &__progress { height: 0.5rem; } &__footer { padding: $spacing-6; padding-top: 0; } &__button { @include button-base; width: 100%; height: 2.5rem; background-color: $color-primary; border: 1px solid $color-primary; color: $color-white; &:hover:not(:disabled) { background-color: $color-primary-hover; border-color: $color-primary-hover; } &--disabled { opacity: 0.5; cursor: not-allowed; } } } ================================================ FILE: 16-Pump.Core/Frontend/app/scss/components/_dialogs.scss ================================================ .dialog { &__overlay { position: fixed; inset: 0; z-index: $z-index-modal-backdrop; background-color: rgba($color-black, 0.8); animation: fadeIn 0.2s ease; } &__content { position: fixed; left: 50%; top: 50%; z-index: $z-index-modal; transform: translate(-50%, -50%); width: 100%; max-width: 32rem; background-color: $color-background; border-radius: $radius-lg; border: 1px solid $color-border; box-shadow: $shadow-lg; padding: $spacing-6; animation: zoomIn 0.2s ease; @include sm { width: 90%; } } &__close { position: absolute; top: $spacing-4; right: $spacing-4; height: 1.5rem; width: 1.5rem; display: flex; align-items: center; justify-content: center; border-radius: $radius-sm; opacity: 0.7; transition: $transition-base; &:hover { opacity: 1; background-color: $color-zinc-100; } } &__header { display: flex; flex-direction: column; gap: $spacing-1; text-align: center; margin-bottom: $spacing-4; @include sm { text-align: left; } } &__title { font-size: $font-size-lg; font-weight: $font-weight-semibold; line-height: 1.2; } &__description { font-size: $font-size-sm; color: $color-muted-foreground; } &__footer { display: flex; flex-direction: column-reverse; gap: $spacing-2; margin-top: $spacing-4; @include sm { flex-direction: row; justify-content: flex-end; } } } @keyframes fadeIn { from { opacity: 0; } to { opacity: 1; } } @keyframes zoomIn { from { opacity: 0; transform: translate(-50%, -48%) scale(0.95); } to { opacity: 1; transform: translate(-50%, -50%) scale(1); } } ================================================ FILE: 16-Pump.Core/Frontend/app/scss/components/_dropdown.scss ================================================ .dropdown { position: relative; &__content { position: absolute; z-index: $z-index-dropdown; min-width: 12rem; background-color: $color-background; border-radius: $radius-md; border: 1px solid $color-border; box-shadow: $shadow-md; padding: $spacing-1; margin-top: $spacing-1; &--right { right: 0; } } &__label { padding: $spacing-2 $spacing-3; font-size: $font-size-sm; font-weight: $font-weight-medium; } &__separator { height: 1px; background-color: $color-border; margin: $spacing-1 0; } &__item { display: flex; align-items: center; width: 100%; padding: $spacing-2 $spacing-3; font-size: $font-size-sm; border-radius: $radius-sm; cursor: pointer; &:hover { background-color: $color-zinc-50; } &--danger { color: $color-red-500; &:hover { background-color: rgba($color-red-500, 0.1); } } } &__link { display: flex; align-items: center; width: 100%; padding: $spacing-2 $spacing-3; font-size: $font-size-sm; border-radius: $radius-sm; cursor: pointer; color: $color-foreground; text-decoration: none; &:hover { background-color: $color-zinc-50; } } &__icon { margin-left: $spacing-2; height: 1rem; width: 1rem; } } ================================================ FILE: 16-Pump.Core/Frontend/app/scss/components/_forms.scss ================================================ .form-label { display: block; font-size: $font-size-sm; font-weight: $font-weight-medium; margin-bottom: $spacing-2; } .form-input { width: 100%; height: 2.5rem; padding: 0 $spacing-3; font-size: $font-size-sm; background-color: $color-background; border: 1px solid $color-input; border-radius: $radius-md; transition: $transition-base; &:focus { outline: none; border-color: $color-primary; box-shadow: 0 0 0 2px rgba($color-primary, 0.2); } &::placeholder { color: $color-zinc-400; } &:disabled { opacity: 0.5; cursor: not-allowed; } } .form-select { width: 100%; height: 2.5rem; padding: 0 $spacing-3; font-size: $font-size-sm; background-color: $color-background; border: 1px solid $color-input; border-radius: $radius-md; transition: $transition-base; &:focus { outline: none; border-color: $color-primary; box-shadow: 0 0 0 2px rgba($color-primary, 0.2); } &:disabled { opacity: 0.5; cursor: not-allowed; } } .form-textarea { width: 100%; min-height: 6rem; padding: $spacing-2 $spacing-3; font-size: $font-size-sm; background-color: $color-background; border: 1px solid $color-input; border-radius: $radius-md; transition: $transition-base; resize: vertical; &:focus { outline: none; border-color: $color-primary; box-shadow: 0 0 0 2px rgba($color-primary, 0.2); } &::placeholder { color: $color-zinc-400; } &:disabled { opacity: 0.5; cursor: not-allowed; } } .form-checkbox { display: flex; align-items: center; input[type="checkbox"] { height: 1rem; width: 1rem; margin-right: $spacing-2; accent-color: $color-primary; } label { font-size: $font-size-sm; } } .form-group { margin-bottom: $spacing-4; } ================================================ FILE: 16-Pump.Core/Frontend/app/scss/components/_launch-dialog.scss ================================================ .launch-dialog { max-width: 500px; max-height: 90vh; overflow-y: auto; &__step { display: grid; gap: $spacing-6; padding: $spacing-4 0; } &__field { display: grid; gap: $spacing-3; } &__hint { font-size: $font-size-xs; color: $color-zinc-500; } &__fee-notice { background-color: rgba($color-primary, 0.05); padding: $spacing-4; border-radius: $radius-lg; border: 1px solid rgba($color-primary, 0.2); &-title { font-size: $font-size-sm; font-weight: $font-weight-medium; color: darken($color-primary, 20%); } &-description { font-size: $font-size-xs; color: darken($color-primary, 10%); margin-top: $spacing-1; } } &__pfp-selector { text-align: center; } &__section-title { font-weight: $font-weight-medium; margin-bottom: $spacing-2; } &__section-description { font-size: $font-size-sm; color: $color-zinc-500; margin-bottom: $spacing-4; } &__pfp-preview { position: relative; width: 12rem; height: 12rem; margin: 0 auto; background-color: $color-zinc-100; border-radius: $radius-lg; overflow: hidden; @include sm { width: 10rem; height: 10rem; } @include md { width: 12rem; height: 12rem; } } &__pfp-image { object-fit: cover; } &__pfp-nav { position: absolute; top: 50%; transform: translateY(-50%); background-color: rgba($color-white, 0.8); border: none; width: 2rem; height: 2rem; display: flex; align-items: center; justify-content: center; border-radius: $radius-full; cursor: pointer; &:hover { background-color: $color-white; } &--prev { left: $spacing-2; } &--next { right: $spacing-2; } &-icon { height: 1rem; width: 1rem; } } &__pfp-counter { margin-top: $spacing-4; font-size: $font-size-sm; &-current { font-weight: $font-weight-medium; } } &__summary { background-color: $color-zinc-50; padding: $spacing-4; border-radius: $radius-lg; } &__summary-grid { display: grid; grid-template-columns: repeat(2, 1fr); gap: $spacing-2; font-size: $font-size-sm; } &__summary-label { color: $color-zinc-500; } &__summary-value { font-weight: $font-weight-medium; } &__footer { display: flex; flex-direction: column; gap: $spacing-2; margin-top: $spacing-2; @include sm { flex-direction: row; } } &__back-button { @include button-base; height: 2.5rem; padding: 0 $spacing-4; background-color: transparent; border: 1px solid $color-border; @include sm { margin-right: auto; } } &__next-button, &__launch-button { @include button-base; height: 2.5rem; padding: 0 $spacing-4; background-color: $color-primary; border: 1px solid $color-primary; color: $color-white; &:hover:not(:disabled) { background-color: $color-primary-hover; border-color: $color-primary-hover; } } &__spinner { margin-right: $spacing-2; height: 1rem; width: 1rem; animation: spin 1s linear infinite; } } ================================================ FILE: 16-Pump.Core/Frontend/app/scss/components/_navbar.scss ================================================ .navbar { position: sticky; top: 0; z-index: $z-index-sticky; width: 100%; background-color: $color-white; transition: $transition-base; &--scrolled { background-color: rgba($color-white, 0.8); backdrop-filter: blur(8px); box-shadow: 0 1px 3px rgba(0, 0, 0, 0.05); } &__content { @include flex(row, space-between, center); height: 4rem; } &__left { @include flex(row, flex-start, center); gap: $spacing-6; } &__logo { @include flex(row, center, center); gap: $spacing-2; &-icon { @include flex(row, center, center); height: 2rem; width: 2rem; border-radius: $radius-full; background-color: $color-primary; color: $color-white; font-weight: $font-weight-bold; } &-text { font-weight: $font-weight-bold; font-size: $font-size-lg; display: none; @include md { display: inline-block; } } } &__nav { display: none; @include md { @include flex(row, flex-start, center); gap: $spacing-6; } } &__nav-link { font-size: $font-size-sm; font-weight: $font-weight-medium; color: $color-foreground; transition: $transition-base; &:hover { color: $color-primary; } } &__right { @include flex(row, flex-end, center); gap: $spacing-4; } &__balance { @include flex(row, flex-start, center); gap: $spacing-2; font-size: $font-size-sm; background-color: $color-zinc-100; padding: $spacing-1 $spacing-3; border-radius: $radius-full; display: none; @include md { display: flex; } &-indicator { width: 0.5rem; height: 0.5rem; border-radius: $radius-full; background-color: $color-green-500; } &-text { font-weight: $font-weight-medium; } } &__menu-button { @include md { display: none; } } &__menu-icon { height: 1.25rem; width: 1.25rem; } &__mobile-nav { @include flex(column); gap: $spacing-4; margin-top: $spacing-8; } &__mobile-link { font-size: $font-size-lg; font-weight: $font-weight-medium; color: $color-foreground; transition: $transition-base; &:hover { color: $color-primary; } } } ================================================ FILE: 16-Pump.Core/Frontend/app/scss/components/_progress.scss ================================================ .progress { width: 100%; height: 0.5rem; background-color: $color-zinc-200; border-radius: $radius-full; overflow: hidden; &__bar { height: 100%; background-color: $color-primary; transition: width 0.3s ease; } } ================================================ FILE: 16-Pump.Core/Frontend/app/scss/components/_toast.scss ================================================ .toast { position: fixed; bottom: $spacing-4; right: $spacing-4; z-index: $z-index-toast; max-width: 350px; background-color: $color-background; border: 1px solid $color-border; border-radius: $radius-md; box-shadow: $shadow-lg; padding: $spacing-4; animation: slideIn 0.2s ease; &__header { display: flex; align-items: flex-start; justify-content: space-between; margin-bottom: $spacing-2; } &__title { font-weight: $font-weight-semibold; font-size: $font-size-sm; } &__close { height: 1.25rem; width: 1.25rem; display: flex; align-items: center; justify-content: center; opacity: 0.5; transition: $transition-base; &:hover { opacity: 1; } } &__description { font-size: $font-size-sm; color: $color-muted-foreground; } &--success { border-left: 4px solid $color-green-500; } &--error { border-left: 4px solid $color-red-500; } } @keyframes slideIn { from { transform: translateX(100%); opacity: 0; } to { transform: translateX(0); opacity: 1; } } ================================================ FILE: 16-Pump.Core/Frontend/app/scss/components/_token-listing.scss ================================================ .token-listing { display: flex; flex-direction: column; gap: $spacing-6; &__header { @include flex(row, space-between, center); } &__title { font-size: $font-size-2xl; font-weight: $font-weight-bold; } &__grid { display: grid; grid-template-columns: 1fr; gap: $spacing-6; @include sm { grid-template-columns: repeat(2, 1fr); } @include lg { grid-template-columns: repeat(3, 1fr); } } &__loading { @include flex(row, center, center); padding: $spacing-12; } &__spinner { height: 2rem; width: 2rem; animation: spin 1s linear infinite; color: $color-primary; } &__empty { text-align: center; padding: $spacing-12; &-title { font-size: $font-size-lg; font-weight: $font-weight-medium; margin-bottom: $spacing-2; } &-text { color: $color-zinc-500; } } } ================================================ FILE: 16-Pump.Core/Frontend/app/scss/main.scss ================================================ @import 'variables'; @import 'mixins'; @import 'reset'; @import 'typography'; @import 'layout'; @import 'components/navbar'; @import 'components/buttons'; @import 'components/cards'; @import 'components/forms'; @import 'components/dialogs'; @import 'components/token-listing'; @import 'components/launch-dialog'; @import 'components/progress'; @import 'components/badges'; @import 'components/dropdown'; @import 'components/toast'; @import 'utilities'; ================================================ FILE: 16-Pump.Core/Frontend/components/buy-token-dialog.tsx ================================================ "use client" import type React from "react" import { useState, useEffect } from "react" import { useWeb3 } from "@/hooks/use-web3" import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle, } from "@/components/ui/dialog" import { Button } from "@/components/ui/button" import { Slider } from "@/components/ui/slider" import { Input } from "@/components/ui/input" import { Loader2 } from "lucide-react" import { parseEther } from "ethers" import { useToast } from "@/hooks/use-toast" import { NetworkSwitcher } from "@/components/network-switcher" import Image from "next/image" import { ethers } from "ethers" type TokenSale = { id: number address: string name: string symbol: string creator: string sold: bigint target: bigint raised: bigint pfpUrl: string isOpen: boolean } interface BuyTokenDialogProps { token: TokenSale open: boolean onOpenChange: (open: boolean) => void } export function BuyTokenDialog({ token, open, onOpenChange }: BuyTokenDialogProps) { const { contract, account, isCorrectNetwork } = useWeb3() const { toast } = useToast() const [amount, setAmount] = useState(1) const [isLoading, setIsLoading] = useState(false) const [pricePerToken, setPricePerToken] = useState(0n); // cost of ONE token const [totalPrice, setTotalPrice] = useState(0n); const forMath = 10**18; const calculatePrice = async (qty: number) => { if (!contract) return 0n; // 1. cost of ONE token (wei) const costPerToken: bigint = await contract.getCost(token.sold); // returns bigint // 2. qty in token-wei (18 decimals) const qtyWei = ethers.parseEther(qty.toString()); // bigint // 3. total cost (wei) — multiply *before* dividing to avoid rounding const totalCostWei = costPerToken * qtyWei / ethers.parseEther("1"); // update UI setPricePerToken(costPerToken); setTotalPrice(totalCostWei); return totalCostWei; // bigint }; useEffect(() => { calculatePrice(amount); }, [amount, contract]); const handleAmountChange = (value: number[]) => { setAmount(value[0]) } const handleInputChange = (e: React.ChangeEvent) => { const value = Number.parseInt(e.target.value) if (!isNaN(value) && value >= 1 && value <= 1000) { setAmount(value) } } const handleBuy = async () => { if (!contract || !account || !isCorrectNetwork) return try { setIsLoading(true) // Calculate the cost in wei console.log("hii") // make sure we have the latest price const costInWei = await calculatePrice(amount); // bigint console.log(costInWei) const amountWei = ethers.parseEther(amount.toString()); // qty in 18 decimals const tx = await contract.buyToken( token.address, amountWei, // _amount (uint256) { value: costInWei } // msg.value ); await tx.wait(); toast({ title: "Tokens purchased!", description: `You have successfully purchased ${amount} ${token.symbol} tokens.`, }) const name = token.name; const symbol = token.symbol window.dispatchEvent(new CustomEvent("tokenLaunched", { detail: { name, symbol}, })); onOpenChange(false) } catch (error) { console.log("Error buying tokens") toast({ title: "Transaction failed", description: "There was an error processing your transaction.", variant: "destructive", }) } finally { setIsLoading(false) } } if (!isCorrectNetwork && account) { return ( Network Switch Required Please switch to Core Testnet 2 to buy tokens.
) } return (
{token.name}
Buy {token.name} Tokens
Select the amount of ${token.symbol} tokens you want to purchase.
1 500 1000
Price per token {ethers.formatEther(pricePerToken)} tCORE2
Total price {ethers.formatEther(totalPrice)} tCORE2
) } ================================================ FILE: 16-Pump.Core/Frontend/components/connect-wallet.tsx ================================================ "use client" import { Button } from "@/components/ui/button" import { useWeb3 } from "@/hooks/use-web3" import { Loader2, ExternalLink } from "lucide-react" import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuLabel, DropdownMenuSeparator, DropdownMenuTrigger, } from "@/components/ui/dropdown-menu" import { shortenAddress } from "@/lib/utils" export function ConnectWallet() { const { account, isConnecting, connect, disconnect, isCorrectNetwork } = useWeb3() if (isConnecting) { return ( ) } if (account) { return ( My Account View on {isCorrectNetwork ? "Block Explorer" : "Etherscan"} Disconnect ) } return ( ) } ================================================ FILE: 16-Pump.Core/Frontend/components/creator-dashboard.tsx ================================================ "use client" import { useState, useEffect } from "react" import { useWeb3 } from "@/hooks/use-web3" import { Card, CardContent, CardDescription, CardFooter, CardHeader, CardTitle } from "@/components/ui/card" import { Button } from "@/components/ui/button" import { Loader2 } from "lucide-react" import { formatEther } from "ethers" import { useToast } from "@/hooks/use-toast" import Image from "next/image" type CreatorToken = { id: number address: string name: string symbol: string sold: bigint remaining: bigint raised: bigint pfpUrl: string } export function CreatorDashboard() { const { contract, account } = useWeb3() const { toast } = useToast() const [tokens, setTokens] = useState([]) const [loading, setLoading] = useState(true) const [depositLoading, setDepositLoading] = useState(null) // IPFS PFP URLs - in a real app, these would be associated with each token const pfpUrls = [ "https://pump.mypinata.cloud/ipfs/QmZ4ea3wmwzwYwyWnhzs35hyxw4YryWB82TknGY3L5Wbxn", "https://pump.mypinata.cloud/ipfs/QmfFEKp9zFzTmcDjHLXi5H6E5dnKn8NjeaT5ZN2yenFfUR", "https://pump.mypinata.cloud/ipfs/QmdwMz7LDs42JoUxz1E9fyWjRwi9dLE1R8HEGDc4EdTvty", "https://pump.mypinata.cloud/ipfs/QmQEhM1g9THLbi8WFdTSgVhUtXuBua26moQx29qUVFAomh", "https://pump.mypinata.cloud/ipfs/QmP3QrGTLWU3ovUSh3hhEZAkkmz4wQUytGFB8T6FYCNbmB", "https://pump.mypinata.cloud/ipfs/QmPPhPbe9t5AKkBgBP4uon7aBdwLzukdS5PJoujC4YjJBj", ] useEffect(() => { if (contract && account) { fetchCreatorTokens() } }, [contract, account]) const fetchCreatorTokens = async () => { try { setLoading(true) // In a real implementation, we would fetch tokens where the creator is the current account // For demo purposes, we'll create mock data const mockTokens: CreatorToken[] = Array(3) .fill(null) .map((_, i) => ({ id: i, address: `0x${Array(40) .fill(0) .map(() => Math.floor(Math.random() * 16).toString(16)) .join("")}`, name: ["CreatorCoin", "MyToken", "AwesomeCoin"][i % 3], symbol: ["CRCN", "MYTK", "AWSM"][i % 3], sold: BigInt(Math.floor(Math.random() * 800)), remaining: BigInt(Math.floor(Math.random() * 200)), raised: BigInt(Math.floor(Math.random() * 5 * 1e18)), pfpUrl: pfpUrls[i % pfpUrls.length], })) setTokens(mockTokens) } catch (error) { console.error("Error fetching creator tokens:", error) } finally { setLoading(false) } } const handleDeposit = async (token: CreatorToken) => { if (!contract || !account) return try { setDepositLoading(token.address) // In a real implementation, this would call the contract's deposit function // await contract.deposit(token.address) // Simulate a transaction delay await new Promise((resolve) => setTimeout(resolve, 2000)) toast({ title: "Deposit successful!", description: `You have successfully deposited to ${token.name}.`, }) // Refresh the token list await fetchCreatorTokens() } catch (error) { console.error("Error depositing:", error) toast({ title: "Transaction failed", description: "There was an error processing your deposit.", variant: "destructive", }) } finally { setDepositLoading(null) } } if (loading) { return (
) } if (tokens.length === 0) { return (

No tokens created yet

You haven't created any tokens yet. Launch your first token to get started!

) } return (
{tokens.map((token) => (
{token.name}
{token.name} ${token.symbol}
Tokens Sold: {token.sold.toString()}
Tokens Remaining: {token.remaining.toString()}
ETH Raised: {Number.parseFloat(formatEther(token.raised)).toFixed(4)} ETH
))}
Transaction History Recent transactions for your tokens
{Array(5) .fill(null) .map((_, i) => (
{["Buy", "Deposit", "Create"][i % 3]} {tokens[i % tokens.length]?.name}
{new Date(Date.now() - i * 86400000).toLocaleDateString()}
{Number.parseFloat((Math.random() * 0.1).toFixed(4))} ETH
{["Completed", "Pending"][i % 2]}
))}
) } ================================================ FILE: 16-Pump.Core/Frontend/components/dialog.tsx ================================================ "use client" import * as React from "react" import * as DialogPrimitive from "@radix-ui/react-dialog" import { X } from "lucide-react" import { cn } from "@/lib/utils" const Dialog = DialogPrimitive.Root const DialogTrigger = DialogPrimitive.Trigger const DialogPortal = DialogPrimitive.Portal const DialogClose = DialogPrimitive.Close const DialogOverlay = React.forwardRef< React.ElementRef, React.ComponentPropsWithoutRef >(({ className, ...props }, ref) => ( )) DialogOverlay.displayName = DialogPrimitive.Overlay.displayName const DialogContent = React.forwardRef< React.ElementRef, React.ComponentPropsWithoutRef >(({ className, children, ...props }, ref) => ( {children} Close )) DialogContent.displayName = DialogPrimitive.Content.displayName const DialogHeader = ({ className, ...props }: React.HTMLAttributes) => (
) DialogHeader.displayName = "DialogHeader" const DialogFooter = ({ className, ...props }: React.HTMLAttributes) => (
) DialogFooter.displayName = "DialogFooter" const DialogTitle = React.forwardRef< React.ElementRef, React.ComponentPropsWithoutRef >(({ className, ...props }, ref) => ( )) DialogTitle.displayName = DialogPrimitive.Title.displayName const DialogDescription = React.forwardRef< React.ElementRef, React.ComponentPropsWithoutRef >(({ className, ...props }, ref) => ( )) DialogDescription.displayName = DialogPrimitive.Description.displayName export { Dialog, DialogPortal, DialogOverlay, DialogClose, DialogTrigger, DialogContent, DialogHeader, DialogFooter, DialogTitle, DialogDescription, } ================================================ FILE: 16-Pump.Core/Frontend/components/launch-token-button.tsx ================================================ "use client" import { useState } from "react" import { Button } from "@/components/ui/button" import { PlusCircle } from "lucide-react" import { LaunchTokenDialog } from "@/components/launch-token-dialog" import { useWeb3 } from "@/hooks/use-web3" export function LaunchTokenButton() { const { account, isCorrectNetwork } = useWeb3() const [dialogOpen, setDialogOpen] = useState(false) // If user is not connected, show disabled button if (!account) { return ( ) } // Always show the launch button, network check happens in the dialog return ( <> ) } ================================================ FILE: 16-Pump.Core/Frontend/components/launch-token-dialog.tsx ================================================ "use client" import { useState } from "react" import { useWeb3 } from "@/hooks/use-web3" import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle, } from "@/components/ui/dialog" import { Button } from "@/components/ui/button" import { Input } from "@/components/ui/input" import { Label } from "@/components/ui/label" import { Loader2, ChevronLeft, ChevronRight } from "lucide-react" import { useToast } from "@/hooks/use-toast" import { NetworkSwitcher } from "@/components/network-switcher" import Image from "next/image" import { ethers } from "ethers" interface LaunchTokenDialogProps { open: boolean onOpenChange: (open: boolean) => void } export function LaunchTokenDialog({ open, onOpenChange }: LaunchTokenDialogProps) { const { contract, account, isCorrectNetwork } = useWeb3() const { toast } = useToast() const [name, setName] = useState("") const [symbol, setSymbol] = useState("") const [isLoading, setIsLoading] = useState(false) const [currentStep, setCurrentStep] = useState(0) const [selectedPfpIndex, setSelectedPfpIndex] = useState(0) // IPFS PFP URLs const pfpUrls = [ "https://pump.mypinata.cloud/ipfs/QmZ4ea3wmwzwYwyWnhzs35hyxw4YryWB82TknGY3L5Wbxn", "https://pump.mypinata.cloud/ipfs/QmfFEKp9zFzTmcDjHLXi5H6E5dnKn8NjeaT5ZN2yenFfUR", "https://pump.mypinata.cloud/ipfs/QmdwMz7LDs42JoUxz1E9fyWjRwi9dLE1R8HEGDc4EdTvty", "https://pump.mypinata.cloud/ipfs/QmQEhM1g9THLbi8WFdTSgVhUtXuBua26moQx29qUVFAomh", "https://pump.mypinata.cloud/ipfs/QmP3QrGTLWU3ovUSh3hhEZAkkmz4wQUytGFB8T6FYCNbmB", "https://pump.mypinata.cloud/ipfs/QmPPhPbe9t5AKkBgBP4uon7aBdwLzukdS5PJoujC4YjJBj", ] // Mock factory fee - in a real implementation, this would be fetched from the contract const factoryFee = ethers.parseEther("0.01" )// tCORE2 // Reset state when dialog is opened or closed const handleOpenChange = (newOpen: boolean) => { if (!newOpen) { // Reset state when dialog is closed setCurrentStep(0) setName("") setSymbol("") setSelectedPfpIndex(0) } onOpenChange(newOpen) } const handleNextStep = () => { if (currentStep === 0) { if (!name || !symbol) { toast({ title: "Missing information", description: "Please provide both a token name and symbol.", variant: "destructive", }) return } if (symbol.length > 5) { toast({ title: "Symbol too long", description: "Token symbol should be 5 characters or less.", variant: "destructive", }) return } } setCurrentStep(currentStep + 1) } const handlePrevStep = () => { setCurrentStep(currentStep - 1) } const handlePrevPfp = () => { setSelectedPfpIndex((selectedPfpIndex - 1 + pfpUrls.length) % pfpUrls.length) } const handleNextPfp = () => { setSelectedPfpIndex((selectedPfpIndex + 1) % pfpUrls.length) } const handleLaunch = async () => { if (!contract || !account || !isCorrectNetwork) return try { setIsLoading(true) // In a real implementation, this would call the contract's create function const tx = await contract.create(name, symbol, { value: factoryFee }) await tx.wait(); // Simulate a transaction delay // await new Promise((resolve) => setTimeout(resolve, 2000)) toast({ title: "Token launched!", description: `Your token ${name} (${symbol}) has been successfully created.`, }) // 🔔 dispatch a global event so others can know “a token was just created” window.dispatchEvent(new CustomEvent("tokenLaunched", { detail: { name, symbol}, })); onOpenChange(false) setName("") setSymbol("") setCurrentStep(0) } catch (error) { console.log("Error launching token") toast({ title: "Transaction failed", description: "There was an error processing your transaction.", variant: "destructive", }) } finally { setIsLoading(false) } } // If not on correct network, show network switcher if (!isCorrectNetwork && account) { return ( Network Switch Required Please switch to Core Testnet 2 to launch a token.
) } return ( Launch New Token Create your own meme token on Core Testnet 2 in just a few steps. {currentStep === 0 && (
setName(e.target.value)} placeholder="e.g. Moon Coin" />
setSymbol(e.target.value.toUpperCase())} placeholder="e.g. MOON" maxLength={5} />

Maximum 5 characters recommended for token symbols.

Factory Fee: {factoryFee} tCORE2

This fee is required to create a new token and is paid to the contract owner.

)} {currentStep === 1 && (

Select Token Image

Choose a profile picture for your token from our collection.

Token PFP
{selectedPfpIndex + 1} of {pfpUrls.length}

Token Summary

Name:
{name}
Symbol:
${symbol}
Fee:
{factoryFee} tCORE2
)} {currentStep > 0 && ( )} {currentStep === 0 && ( )} {currentStep === 1 && ( )}
) } ================================================ FILE: 16-Pump.Core/Frontend/components/navbar.tsx ================================================ "use client" import { useState, useEffect } from "react" import { ConnectWallet } from "@/components/connect-wallet" import { useWeb3 } from "@/hooks/use-web3" import { formatEther } from "ethers" import Link from "next/link" import { Menu } from "lucide-react" import { Button } from "@/components/ui/button" import { Sheet, SheetContent, SheetTrigger } from "@/components/ui/sheet" import { NetworkSwitcher } from "@/components/network-switcher" export function Navbar() { const { account, balance, isCorrectNetwork } = useWeb3() const [isScrolled, setIsScrolled] = useState(false) useEffect(() => { const handleScroll = () => { setIsScrolled(window.scrollY > 10) } window.addEventListener("scroll", handleScroll) return () => window.removeEventListener("scroll", handleScroll) }, []) return (
M MemeFactory
{!isCorrectNetwork && account && } {account && balance && isCorrectNetwork && (
{balance ? Number.parseFloat(formatEther(balance)).toFixed(4) : "0.0"} tCORE2
)}
) } ================================================ FILE: 16-Pump.Core/Frontend/components/network-switcher.tsx ================================================ "use client" import { Button } from "@/components/ui/button" import { useWeb3 } from "@/hooks/use-web3" import { AlertTriangle } from "lucide-react" import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle, } from "@/components/ui/dialog" import { useState } from "react" import { useToast } from "@/hooks/use-toast" export function NetworkSwitcher() { const { switchToCorrectNetwork, addCoreTestnet2, isCorrectNetwork } = useWeb3() const [showDialog, setShowDialog] = useState(false) const [isLoading, setIsLoading] = useState(false) const { toast } = useToast() const handleSwitchNetwork = async () => { try { setIsLoading(true) await switchToCorrectNetwork() // If we get here, the switch was successful toast({ title: "Network Switched", description: "Successfully connected to Core Testnet 2.", }) setShowDialog(false) } catch (error: any) { console.error("Error switching network:", error) // If the network is not added, show the dialog to add it if (error.code === 4902) { setShowDialog(true) } else { toast({ title: "Network Switch Failed", description: "There was an error switching networks. Please try again.", variant: "destructive", }) } } finally { setIsLoading(false) } } const handleAddNetwork = async () => { try { setIsLoading(true) await addCoreTestnet2() toast({ title: "Network Added", description: "Core Testnet 2 has been added to your wallet.", }) setShowDialog(false) } catch (error) { console.error("Error adding network:", error) toast({ title: "Failed to Add Network", description: "There was an error adding Core Testnet 2 to your wallet.", variant: "destructive", }) } finally { setIsLoading(false) } } if (isCorrectNetwork) { return null } return ( <> Network Configuration Required Core Testnet 2 needs to be added to your wallet to use this application.
Network Name:
Core Testnet 2
RPC URL:
https://rpc.test2.btcs.network
Chain ID:
1114 (0x45a)
Currency Symbol:
tCORE2
Block Explorer:
https://scan.test2.btcs.network
) } ================================================ FILE: 16-Pump.Core/Frontend/components/owner-dashboard.tsx ================================================ "use client" import { useState } from "react" import { useWeb3 } from "@/hooks/use-web3" import { Card, CardContent, CardDescription, CardFooter, CardHeader, CardTitle } from "@/components/ui/card" import { Button } from "@/components/ui/button" import { Input } from "@/components/ui/input" import { Label } from "@/components/ui/label" import { Loader2 } from "lucide-react" import { useToast } from "@/hooks/use-toast" export function OwnerDashboard() { const { contract, account } = useWeb3() const { toast } = useToast() const [withdrawAmount, setWithdrawAmount] = useState("") const [isWithdrawing, setIsWithdrawing] = useState(false) // Mock factory fee collected - in a real implementation, this would be fetched from the contract const feeCollected = "0.25" // ETH const handleWithdraw = async () => { if (!contract || !account || !withdrawAmount) return try { setIsWithdrawing(true) // Validate the amount const amount = Number.parseFloat(withdrawAmount) if (isNaN(amount) || amount <= 0 || amount > Number.parseFloat(feeCollected)) { toast({ title: "Invalid amount", description: "Please enter a valid amount to withdraw.", variant: "destructive", }) setIsWithdrawing(false) return } // In a real implementation, this would call the contract's withdraw function // await contract.withdraw(parseEther(withdrawAmount)) // Simulate a transaction delay await new Promise((resolve) => setTimeout(resolve, 2000)) toast({ title: "Withdrawal successful!", description: `You have successfully withdrawn ${withdrawAmount} ETH.`, }) setWithdrawAmount("") } catch (error) { console.error("Error withdrawing:", error) toast({ title: "Transaction failed", description: "There was an error processing your withdrawal.", variant: "destructive", }) } finally { setIsWithdrawing(false) } } return (
Owner Dashboard Manage your MemeFactory contract

Factory Fee Collected

Total fees collected from token creation

{feeCollected} ETH
setWithdrawAmount(e.target.value)} min="0" max={feeCollected} step="0.01" />

You can withdraw up to {feeCollected} ETH.

Factory Settings Configure your MemeFactory contract

Fee required to create a new token.

Maximum number of tokens that can be sold per token.

) } ================================================ FILE: 16-Pump.Core/Frontend/components/token-listing.tsx ================================================ "use client" import { useEffect, useState } from "react" import { useWeb3 } from "@/hooks/use-web3" import { Card, CardContent, CardFooter, CardHeader } from "@/components/ui/card" import { Badge } from "@/components/ui/badge" import { Button } from "@/components/ui/button" import { Progress } from "@/components/ui/progress" import { Loader2, Check, Copy } from "lucide-react" import { formatEther } from "ethers" import { BuyTokenDialog } from "@/components/buy-token-dialog" import { NetworkSwitcher } from "@/components/network-switcher" import Image from "next/image" import { ethers } from "ethers" type TokenSale = { id: number address: string name: string symbol: string creator: string sold: bigint target: bigint raised: bigint pfpUrl: string isOpen: boolean } const TOKEN_LIMIT = 1000n // This should match the contract's TOKEN_LIMIT export function TokenListing() { const { contract, account, isCorrectNetwork } = useWeb3() const [tokens, setTokens] = useState([]) const [loading, setLoading] = useState(true) const [selectedToken, setSelectedToken] = useState(null) const [buyDialogOpen, setBuyDialogOpen] = useState(false) const [copiedTokenId, setCopiedTokenId] = useState(null) const pfpUrls = [ "https://pump.mypinata.cloud/ipfs/QmZ4ea3wmwzwYwyWnhzs35hyxw4YryWB82TknGY3L5Wbxn", "https://pump.mypinata.cloud/ipfs/QmfFEKp9zFzTmcDjHLXi5H6E5dnKn8NjeaT5ZN2yenFfUR", "https://pump.mypinata.cloud/ipfs/QmdwMz7LDs42JoUxz1E9fyWjRwi9dLE1R8HEGDc4EdTvty", "https://pump.mypinata.cloud/ipfs/QmQEhM1g9THLbi8WFdTSgVhUtXuBua26moQx29qUVFAomh", "https://pump.mypinata.cloud/ipfs/QmP3QrGTLWU3ovUSh3hhEZAkkmz4wQUytGFB8T6FYCNbmB", "https://pump.mypinata.cloud/ipfs/QmPPhPbe9t5AKkBgBP4uon7aBdwLzukdS5PJoujC4YjJBj", ] useEffect(() => { if (contract && isCorrectNetwork) { fetchTokens() } else { const timer = setTimeout(() => { setLoading(false) }, 1000) return () => clearTimeout(timer) } }, [contract, isCorrectNetwork]) const fetchTokens = async () => { try { setLoading(true) const tokenCount = await contract.totalTokens() const fetchedTokens: TokenSale[] = [] for (let i = 0; i < Number(tokenCount); i++) { try { const tokenSale = await contract.getTokenSale(i) const tokenData: TokenSale = { id: i, address: tokenSale.token, name: tokenSale.name, symbol: tokenSale.symbol, creator: tokenSale.creator, sold: BigInt(tokenSale.sold), target: 3000000000000000000n, // 3 ether target raised: BigInt(tokenSale.raised), pfpUrl: pfpUrls[i % pfpUrls.length], isOpen: tokenSale.isOpen, } fetchedTokens.push(tokenData) } catch (error) { console.error(`Error fetching token at index ${i}:`, error) break } } setTokens(fetchedTokens) } catch (error) { console.error("Error fetching tokens:", error) } finally { setTimeout(() => { setLoading(false) }, 500) } } useEffect(() => { const onLaunched = () => { fetchTokens(); }; window.addEventListener("tokenLaunched", onLaunched); return () => { window.removeEventListener("tokenLaunched", onLaunched); }; }, [fetchTokens]); const handleBuyClick = (token: TokenSale) => { if (!isCorrectNetwork) return setSelectedToken(token) setBuyDialogOpen(true) } if (loading) { return (
) } if (!isCorrectNetwork && account) { return (

Network Switch Required

Please switch to Core Testnet 2 to view and interact with tokens.

) } if (tokens.length === 0) { return (

No tokens available yet

Be the first to launch a token!

) } return (

Available Tokens

{tokens.map((token) => (
{token.name} {token.isOpen ? "Open" : "Closed"}

{token.name}

${token.symbol}

Sold {ethers.formatEther(token.sold.toString())} / {TOKEN_LIMIT.toString()}
Raised {Number.parseFloat(formatEther(token.raised)).toFixed(4)} tCORE2
{token.address}
))}
{selectedToken && ( )}
) } ================================================ FILE: 16-Pump.Core/Frontend/components/ui/badge.tsx ================================================ import * as React from "react" import { cva, type VariantProps } from "class-variance-authority" import { cn } from "@/lib/utils" const badgeVariants = cva( "inline-flex items-center rounded-md border px-2.5 py-0.5 text-xs font-semibold transition-colors focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2", { variants: { variant: { default: "border-transparent bg-primary text-primary-foreground shadow hover:bg-primary/80", secondary: "border-transparent bg-secondary text-secondary-foreground hover:bg-secondary/80", destructive: "border-transparent bg-destructive text-destructive-foreground shadow hover:bg-destructive/80", outline: "text-foreground", }, }, defaultVariants: { variant: "default", }, } ) export interface BadgeProps extends React.HTMLAttributes, VariantProps {} function Badge({ className, variant, ...props }: BadgeProps) { return (
) } export { Badge, badgeVariants } ================================================ FILE: 16-Pump.Core/Frontend/components/ui/button.tsx ================================================ import * as React from "react" import { Slot } from "@radix-ui/react-slot" import { cva, type VariantProps } from "class-variance-authority" import { cn } from "@/lib/utils" const buttonVariants = cva( "inline-flex items-center justify-center gap-2 whitespace-nowrap rounded-md text-sm font-medium transition-colors focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring disabled:pointer-events-none disabled:opacity-50 [&_svg]:pointer-events-none [&_svg]:size-4 [&_svg]:shrink-0", { variants: { variant: { default: "bg-primary text-primary-foreground shadow hover:bg-primary/90", destructive: "bg-destructive text-destructive-foreground shadow-sm hover:bg-destructive/90", outline: "border border-input bg-background shadow-sm hover:bg-accent hover:text-accent-foreground", secondary: "bg-secondary text-secondary-foreground shadow-sm hover:bg-secondary/80", ghost: "hover:bg-accent hover:text-accent-foreground", link: "text-primary underline-offset-4 hover:underline", }, size: { default: "h-9 px-4 py-2", sm: "h-8 rounded-md px-3 text-xs", lg: "h-10 rounded-md px-8", icon: "h-9 w-9", }, }, defaultVariants: { variant: "default", size: "default", }, } ) export interface ButtonProps extends React.ButtonHTMLAttributes, VariantProps { asChild?: boolean } const Button = React.forwardRef( ({ className, variant, size, asChild = false, ...props }, ref) => { const Comp = asChild ? Slot : "button" return ( ) } ) Button.displayName = "Button" export { Button, buttonVariants } ================================================ FILE: 16-Pump.Core/Frontend/components/ui/card.tsx ================================================ import * as React from "react" import { cn } from "@/lib/utils" const Card = React.forwardRef< HTMLDivElement, React.HTMLAttributes >(({ className, ...props }, ref) => (
)) Card.displayName = "Card" const CardHeader = React.forwardRef< HTMLDivElement, React.HTMLAttributes >(({ className, ...props }, ref) => (
)) CardHeader.displayName = "CardHeader" const CardTitle = React.forwardRef< HTMLDivElement, React.HTMLAttributes >(({ className, ...props }, ref) => (
)) CardTitle.displayName = "CardTitle" const CardDescription = React.forwardRef< HTMLDivElement, React.HTMLAttributes >(({ className, ...props }, ref) => (
)) CardDescription.displayName = "CardDescription" const CardContent = React.forwardRef< HTMLDivElement, React.HTMLAttributes >(({ className, ...props }, ref) => (
)) CardContent.displayName = "CardContent" const CardFooter = React.forwardRef< HTMLDivElement, React.HTMLAttributes >(({ className, ...props }, ref) => (
)) CardFooter.displayName = "CardFooter" export { Card, CardHeader, CardFooter, CardTitle, CardDescription, CardContent } ================================================ FILE: 16-Pump.Core/Frontend/components/ui/dialog.tsx ================================================ "use client" import * as React from "react" import * as DialogPrimitive from "@radix-ui/react-dialog" import { X } from "lucide-react" import { cn } from "@/lib/utils" const Dialog = DialogPrimitive.Root const DialogTrigger = DialogPrimitive.Trigger const DialogPortal = DialogPrimitive.Portal const DialogClose = DialogPrimitive.Close const DialogOverlay = React.forwardRef< React.ElementRef, React.ComponentPropsWithoutRef >(({ className, ...props }, ref) => ( )) DialogOverlay.displayName = DialogPrimitive.Overlay.displayName const DialogContent = React.forwardRef< React.ElementRef, React.ComponentPropsWithoutRef >(({ className, children, ...props }, ref) => ( {children} Close )) DialogContent.displayName = DialogPrimitive.Content.displayName const DialogHeader = ({ className, ...props }: React.HTMLAttributes) => (
) DialogHeader.displayName = "DialogHeader" const DialogFooter = ({ className, ...props }: React.HTMLAttributes) => (
) DialogFooter.displayName = "DialogFooter" const DialogTitle = React.forwardRef< React.ElementRef, React.ComponentPropsWithoutRef >(({ className, ...props }, ref) => ( )) DialogTitle.displayName = DialogPrimitive.Title.displayName const DialogDescription = React.forwardRef< React.ElementRef, React.ComponentPropsWithoutRef >(({ className, ...props }, ref) => ( )) DialogDescription.displayName = DialogPrimitive.Description.displayName export { Dialog, DialogPortal, DialogOverlay, DialogTrigger, DialogClose, DialogContent, DialogHeader, DialogFooter, DialogTitle, DialogDescription, } ================================================ FILE: 16-Pump.Core/Frontend/components/ui/dropdown-menu.tsx ================================================ "use client" import * as React from "react" import * as DropdownMenuPrimitive from "@radix-ui/react-dropdown-menu" import { Check, ChevronRight, Circle } from "lucide-react" import { cn } from "@/lib/utils" const DropdownMenu = DropdownMenuPrimitive.Root const DropdownMenuTrigger = DropdownMenuPrimitive.Trigger const DropdownMenuGroup = DropdownMenuPrimitive.Group const DropdownMenuPortal = DropdownMenuPrimitive.Portal const DropdownMenuSub = DropdownMenuPrimitive.Sub const DropdownMenuRadioGroup = DropdownMenuPrimitive.RadioGroup const DropdownMenuSubTrigger = React.forwardRef< React.ElementRef, React.ComponentPropsWithoutRef & { inset?: boolean } >(({ className, inset, children, ...props }, ref) => ( {children} )) DropdownMenuSubTrigger.displayName = DropdownMenuPrimitive.SubTrigger.displayName const DropdownMenuSubContent = React.forwardRef< React.ElementRef, React.ComponentPropsWithoutRef >(({ className, ...props }, ref) => ( )) DropdownMenuSubContent.displayName = DropdownMenuPrimitive.SubContent.displayName const DropdownMenuContent = React.forwardRef< React.ElementRef, React.ComponentPropsWithoutRef >(({ className, sideOffset = 4, ...props }, ref) => ( )) DropdownMenuContent.displayName = DropdownMenuPrimitive.Content.displayName const DropdownMenuItem = React.forwardRef< React.ElementRef, React.ComponentPropsWithoutRef & { inset?: boolean } >(({ className, inset, ...props }, ref) => ( svg]:size-4 [&>svg]:shrink-0", inset && "pl-8", className )} {...props} /> )) DropdownMenuItem.displayName = DropdownMenuPrimitive.Item.displayName const DropdownMenuCheckboxItem = React.forwardRef< React.ElementRef, React.ComponentPropsWithoutRef >(({ className, children, checked, ...props }, ref) => ( {children} )) DropdownMenuCheckboxItem.displayName = DropdownMenuPrimitive.CheckboxItem.displayName const DropdownMenuRadioItem = React.forwardRef< React.ElementRef, React.ComponentPropsWithoutRef >(({ className, children, ...props }, ref) => ( {children} )) DropdownMenuRadioItem.displayName = DropdownMenuPrimitive.RadioItem.displayName const DropdownMenuLabel = React.forwardRef< React.ElementRef, React.ComponentPropsWithoutRef & { inset?: boolean } >(({ className, inset, ...props }, ref) => ( )) DropdownMenuLabel.displayName = DropdownMenuPrimitive.Label.displayName const DropdownMenuSeparator = React.forwardRef< React.ElementRef, React.ComponentPropsWithoutRef >(({ className, ...props }, ref) => ( )) DropdownMenuSeparator.displayName = DropdownMenuPrimitive.Separator.displayName const DropdownMenuShortcut = ({ className, ...props }: React.HTMLAttributes) => { return ( ) } DropdownMenuShortcut.displayName = "DropdownMenuShortcut" export { DropdownMenu, DropdownMenuTrigger, DropdownMenuContent, DropdownMenuItem, DropdownMenuCheckboxItem, DropdownMenuRadioItem, DropdownMenuLabel, DropdownMenuSeparator, DropdownMenuShortcut, DropdownMenuGroup, DropdownMenuPortal, DropdownMenuSub, DropdownMenuSubContent, DropdownMenuSubTrigger, DropdownMenuRadioGroup, } ================================================ FILE: 16-Pump.Core/Frontend/components/ui/input.tsx ================================================ import * as React from "react" import { cn } from "@/lib/utils" const Input = React.forwardRef>( ({ className, type, ...props }, ref) => { return ( ) } ) Input.displayName = "Input" export { Input } ================================================ FILE: 16-Pump.Core/Frontend/components/ui/label.tsx ================================================ "use client" import * as React from "react" import * as LabelPrimitive from "@radix-ui/react-label" import { cva, type VariantProps } from "class-variance-authority" import { cn } from "@/lib/utils" const labelVariants = cva( "text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70" ) const Label = React.forwardRef< React.ElementRef, React.ComponentPropsWithoutRef & VariantProps >(({ className, ...props }, ref) => ( )) Label.displayName = LabelPrimitive.Root.displayName export { Label } ================================================ FILE: 16-Pump.Core/Frontend/components/ui/progress.tsx ================================================ "use client" import * as React from "react" import * as ProgressPrimitive from "@radix-ui/react-progress" import { cn } from "@/lib/utils" const Progress = React.forwardRef< React.ElementRef, React.ComponentPropsWithoutRef >(({ className, value, ...props }, ref) => ( )) Progress.displayName = ProgressPrimitive.Root.displayName export { Progress } ================================================ FILE: 16-Pump.Core/Frontend/components/ui/sheet.tsx ================================================ "use client" import * as React from "react" import * as SheetPrimitive from "@radix-ui/react-dialog" import { cva, type VariantProps } from "class-variance-authority" import { X } from "lucide-react" import { cn } from "@/lib/utils" const Sheet = SheetPrimitive.Root const SheetTrigger = SheetPrimitive.Trigger const SheetClose = SheetPrimitive.Close const SheetPortal = SheetPrimitive.Portal const SheetOverlay = React.forwardRef< React.ElementRef, React.ComponentPropsWithoutRef >(({ className, ...props }, ref) => ( )) SheetOverlay.displayName = SheetPrimitive.Overlay.displayName const sheetVariants = cva( "fixed z-50 gap-4 bg-background p-6 shadow-lg transition ease-in-out data-[state=closed]:duration-300 data-[state=open]:duration-500 data-[state=open]:animate-in data-[state=closed]:animate-out", { variants: { side: { top: "inset-x-0 top-0 border-b data-[state=closed]:slide-out-to-top data-[state=open]:slide-in-from-top", bottom: "inset-x-0 bottom-0 border-t data-[state=closed]:slide-out-to-bottom data-[state=open]:slide-in-from-bottom", left: "inset-y-0 left-0 h-full w-3/4 border-r data-[state=closed]:slide-out-to-left data-[state=open]:slide-in-from-left sm:max-w-sm", right: "inset-y-0 right-0 h-full w-3/4 border-l data-[state=closed]:slide-out-to-right data-[state=open]:slide-in-from-right sm:max-w-sm", }, }, defaultVariants: { side: "right", }, } ) interface SheetContentProps extends React.ComponentPropsWithoutRef, VariantProps {} const SheetContent = React.forwardRef< React.ElementRef, SheetContentProps >(({ side = "right", className, children, ...props }, ref) => ( Close {children} )) SheetContent.displayName = SheetPrimitive.Content.displayName const SheetHeader = ({ className, ...props }: React.HTMLAttributes) => (
) SheetHeader.displayName = "SheetHeader" const SheetFooter = ({ className, ...props }: React.HTMLAttributes) => (
) SheetFooter.displayName = "SheetFooter" const SheetTitle = React.forwardRef< React.ElementRef, React.ComponentPropsWithoutRef >(({ className, ...props }, ref) => ( )) SheetTitle.displayName = SheetPrimitive.Title.displayName const SheetDescription = React.forwardRef< React.ElementRef, React.ComponentPropsWithoutRef >(({ className, ...props }, ref) => ( )) SheetDescription.displayName = SheetPrimitive.Description.displayName export { Sheet, SheetPortal, SheetOverlay, SheetTrigger, SheetClose, SheetContent, SheetHeader, SheetFooter, SheetTitle, SheetDescription, } ================================================ FILE: 16-Pump.Core/Frontend/components/ui/slider.tsx ================================================ "use client" import * as React from "react" import * as SliderPrimitive from "@radix-ui/react-slider" import { cn } from "@/lib/utils" const Slider = React.forwardRef< React.ElementRef, React.ComponentPropsWithoutRef >(({ className, ...props }, ref) => ( )) Slider.displayName = SliderPrimitive.Root.displayName export { Slider } ================================================ FILE: 16-Pump.Core/Frontend/components/ui/tabs.tsx ================================================ "use client" import * as React from "react" import * as TabsPrimitive from "@radix-ui/react-tabs" import { cn } from "@/lib/utils" const Tabs = TabsPrimitive.Root const TabsList = React.forwardRef< React.ElementRef, React.ComponentPropsWithoutRef >(({ className, ...props }, ref) => ( )) TabsList.displayName = TabsPrimitive.List.displayName const TabsTrigger = React.forwardRef< React.ElementRef, React.ComponentPropsWithoutRef >(({ className, ...props }, ref) => ( )) TabsTrigger.displayName = TabsPrimitive.Trigger.displayName const TabsContent = React.forwardRef< React.ElementRef, React.ComponentPropsWithoutRef >(({ className, ...props }, ref) => ( )) TabsContent.displayName = TabsPrimitive.Content.displayName export { Tabs, TabsList, TabsTrigger, TabsContent } ================================================ FILE: 16-Pump.Core/Frontend/components/ui/toast.tsx ================================================ "use client" import * as React from "react" import * as ToastPrimitives from "@radix-ui/react-toast" import { cva, type VariantProps } from "class-variance-authority" import { X } from "lucide-react" import { cn } from "@/lib/utils" const ToastProvider = ToastPrimitives.Provider const ToastViewport = React.forwardRef< React.ElementRef, React.ComponentPropsWithoutRef >(({ className, ...props }, ref) => ( )) ToastViewport.displayName = ToastPrimitives.Viewport.displayName const toastVariants = cva( "group pointer-events-auto relative flex w-full items-center justify-between space-x-2 overflow-hidden rounded-md border p-4 pr-6 shadow-lg transition-all data-[swipe=cancel]:translate-x-0 data-[swipe=end]:translate-x-[var(--radix-toast-swipe-end-x)] data-[swipe=move]:translate-x-[var(--radix-toast-swipe-move-x)] data-[swipe=move]:transition-none data-[state=open]:animate-in data-[state=closed]:animate-out data-[swipe=end]:animate-out data-[state=closed]:fade-out-80 data-[state=closed]:slide-out-to-right-full data-[state=open]:slide-in-from-top-full data-[state=open]:sm:slide-in-from-bottom-full", { variants: { variant: { default: "border bg-background text-foreground", destructive: "destructive group border-destructive bg-destructive text-destructive-foreground", }, }, defaultVariants: { variant: "default", }, } ) const Toast = React.forwardRef< React.ElementRef, React.ComponentPropsWithoutRef & VariantProps >(({ className, variant, ...props }, ref) => { return ( ) }) Toast.displayName = ToastPrimitives.Root.displayName const ToastAction = React.forwardRef< React.ElementRef, React.ComponentPropsWithoutRef >(({ className, ...props }, ref) => ( )) ToastAction.displayName = ToastPrimitives.Action.displayName const ToastClose = React.forwardRef< React.ElementRef, React.ComponentPropsWithoutRef >(({ className, ...props }, ref) => ( )) ToastClose.displayName = ToastPrimitives.Close.displayName const ToastTitle = React.forwardRef< React.ElementRef, React.ComponentPropsWithoutRef >(({ className, ...props }, ref) => ( )) ToastTitle.displayName = ToastPrimitives.Title.displayName const ToastDescription = React.forwardRef< React.ElementRef, React.ComponentPropsWithoutRef >(({ className, ...props }, ref) => ( )) ToastDescription.displayName = ToastPrimitives.Description.displayName type ToastProps = React.ComponentPropsWithoutRef type ToastActionElement = React.ReactElement export { type ToastProps, type ToastActionElement, ToastProvider, ToastViewport, Toast, ToastTitle, ToastDescription, ToastClose, ToastAction, } ================================================ FILE: 16-Pump.Core/Frontend/components/ui/toaster.tsx ================================================ "use client" import { useToast } from "@/hooks/use-toast" import { Toast, ToastClose, ToastDescription, ToastProvider, ToastTitle, ToastViewport, } from "@/components/ui/toast" export function Toaster() { const { toasts } = useToast() return ( {toasts.map(function ({ id, title, description, action, ...props }) { return (
{title && {title}} {description && ( {description} )}
{action}
) })}
) } ================================================ FILE: 16-Pump.Core/Frontend/components.json ================================================ { "$schema": "https://ui.shadcn.com/schema.json", "style": "new-york", "rsc": true, "tsx": true, "tailwind": { "config": "tailwind.config.ts", "css": "app/globals.css", "baseColor": "zinc", "cssVariables": true, "prefix": "" }, "aliases": { "components": "@/components", "utils": "@/lib/utils", "ui": "@/components/ui", "lib": "@/lib", "hooks": "@/hooks" }, "iconLibrary": "lucide" } ================================================ FILE: 16-Pump.Core/Frontend/constants/constansts.tsx ================================================ const CONTRACT_ADDRESS = "0x698bbc18d5aC177154fcA7Ba47Bf91D85c41df59" const CONTRACT_ABI = [ { "inputs": [ { "internalType": "uint256", "name": "_fee", "type": "uint256" } ], "stateMutability": "nonpayable", "type": "constructor" }, { "inputs": [], "name": "MemeFactory__AmountExceeded", "type": "error" }, { "inputs": [], "name": "MemeFactory__InsufficientETH", "type": "error" }, { "inputs": [], "name": "MemeFactory__InsufficientFee", "type": "error" }, { "inputs": [], "name": "MemeFactory__NotOwner", "type": "error" }, { "inputs": [], "name": "MemeFactory__SaleClosed", "type": "error" }, { "inputs": [], "name": "MemeFactory__TokenAmountTooLow", "type": "error" }, { "inputs": [], "name": "MemeFactory__TransferFailed", "type": "error" }, { "anonymous": false, "inputs": [ { "indexed": true, "internalType": "address", "name": "token", "type": "address" }, { "indexed": false, "internalType": "uint256", "name": "amount", "type": "uint256" } ], "name": "BoughtToken", "type": "event" }, { "anonymous": false, "inputs": [ { "indexed": true, "internalType": "address", "name": "token", "type": "address" } ], "name": "Created", "type": "event" }, { "inputs": [], "name": "TARGET", "outputs": [ { "internalType": "uint256", "name": "", "type": "uint256" } ], "stateMutability": "view", "type": "function" }, { "inputs": [], "name": "TOKEN_LIMIT", "outputs": [ { "internalType": "uint256", "name": "", "type": "uint256" } ], "stateMutability": "view", "type": "function" }, { "inputs": [ { "internalType": "address", "name": "_token", "type": "address" }, { "internalType": "uint256", "name": "_amount", "type": "uint256" } ], "name": "buyToken", "outputs": [], "stateMutability": "payable", "type": "function" }, { "inputs": [ { "internalType": "string", "name": "_name", "type": "string" }, { "internalType": "string", "name": "_symbol", "type": "string" } ], "name": "create", "outputs": [], "stateMutability": "payable", "type": "function" }, { "inputs": [ { "internalType": "address", "name": "_token", "type": "address" } ], "name": "deposit", "outputs": [], "stateMutability": "nonpayable", "type": "function" }, { "inputs": [], "name": "fee", "outputs": [ { "internalType": "uint256", "name": "", "type": "uint256" } ], "stateMutability": "view", "type": "function" }, { "inputs": [ { "internalType": "uint256", "name": "_sold", "type": "uint256" } ], "name": "getCost", "outputs": [ { "internalType": "uint256", "name": "", "type": "uint256" } ], "stateMutability": "pure", "type": "function" }, { "inputs": [ { "internalType": "uint256", "name": "_index", "type": "uint256" } ], "name": "getTokenSale", "outputs": [ { "components": [ { "internalType": "address", "name": "token", "type": "address" }, { "internalType": "string", "name": "name", "type": "string" }, { "internalType": "string", "name": "symbol", "type": "string" }, { "internalType": "address", "name": "creator", "type": "address" }, { "internalType": "uint256", "name": "sold", "type": "uint256" }, { "internalType": "uint256", "name": "raised", "type": "uint256" }, { "internalType": "bool", "name": "isOpen", "type": "bool" } ], "internalType": "struct MemeFactory.TokenSale", "name": "", "type": "tuple" } ], "stateMutability": "view", "type": "function" }, { "inputs": [], "name": "owner", "outputs": [ { "internalType": "address", "name": "", "type": "address" } ], "stateMutability": "view", "type": "function" }, { "inputs": [ { "internalType": "address", "name": "", "type": "address" } ], "name": "tokenToSale", "outputs": [ { "internalType": "address", "name": "token", "type": "address" }, { "internalType": "string", "name": "name", "type": "string" }, { "internalType": "string", "name": "symbol", "type": "string" }, { "internalType": "address", "name": "creator", "type": "address" }, { "internalType": "uint256", "name": "sold", "type": "uint256" }, { "internalType": "uint256", "name": "raised", "type": "uint256" }, { "internalType": "bool", "name": "isOpen", "type": "bool" } ], "stateMutability": "view", "type": "function" }, { "inputs": [ { "internalType": "uint256", "name": "", "type": "uint256" } ], "name": "tokens", "outputs": [ { "internalType": "address", "name": "", "type": "address" } ], "stateMutability": "view", "type": "function" }, { "inputs": [], "name": "totalTokens", "outputs": [ { "internalType": "uint256", "name": "", "type": "uint256" } ], "stateMutability": "view", "type": "function" }, { "inputs": [ { "internalType": "uint256", "name": "_amount", "type": "uint256" } ], "name": "withdraw", "outputs": [], "stateMutability": "nonpayable", "type": "function" } ] export {CONTRACT_ADDRESS, CONTRACT_ABI} ================================================ FILE: 16-Pump.Core/Frontend/hooks/use-toast.ts ================================================ "use client" // Inspired by react-hot-toast library import * as React from "react" import type { ToastActionElement, ToastProps, } from "@/components/ui/toast" const TOAST_LIMIT = 1 const TOAST_REMOVE_DELAY = 1000000 type ToasterToast = ToastProps & { id: string title?: React.ReactNode description?: React.ReactNode action?: ToastActionElement } const actionTypes = { ADD_TOAST: "ADD_TOAST", UPDATE_TOAST: "UPDATE_TOAST", DISMISS_TOAST: "DISMISS_TOAST", REMOVE_TOAST: "REMOVE_TOAST", } as const let count = 0 function genId() { count = (count + 1) % Number.MAX_SAFE_INTEGER return count.toString() } type ActionType = typeof actionTypes type Action = | { type: ActionType["ADD_TOAST"] toast: ToasterToast } | { type: ActionType["UPDATE_TOAST"] toast: Partial } | { type: ActionType["DISMISS_TOAST"] toastId?: ToasterToast["id"] } | { type: ActionType["REMOVE_TOAST"] toastId?: ToasterToast["id"] } interface State { toasts: ToasterToast[] } const toastTimeouts = new Map>() const addToRemoveQueue = (toastId: string) => { if (toastTimeouts.has(toastId)) { return } const timeout = setTimeout(() => { toastTimeouts.delete(toastId) dispatch({ type: "REMOVE_TOAST", toastId: toastId, }) }, TOAST_REMOVE_DELAY) toastTimeouts.set(toastId, timeout) } export const reducer = (state: State, action: Action): State => { switch (action.type) { case "ADD_TOAST": return { ...state, toasts: [action.toast, ...state.toasts].slice(0, TOAST_LIMIT), } case "UPDATE_TOAST": return { ...state, toasts: state.toasts.map((t) => t.id === action.toast.id ? { ...t, ...action.toast } : t ), } case "DISMISS_TOAST": { const { toastId } = action // ! Side effects ! - This could be extracted into a dismissToast() action, // but I'll keep it here for simplicity if (toastId) { addToRemoveQueue(toastId) } else { state.toasts.forEach((toast) => { addToRemoveQueue(toast.id) }) } return { ...state, toasts: state.toasts.map((t) => t.id === toastId || toastId === undefined ? { ...t, open: false, } : t ), } } case "REMOVE_TOAST": if (action.toastId === undefined) { return { ...state, toasts: [], } } return { ...state, toasts: state.toasts.filter((t) => t.id !== action.toastId), } } } const listeners: Array<(state: State) => void> = [] let memoryState: State = { toasts: [] } function dispatch(action: Action) { memoryState = reducer(memoryState, action) listeners.forEach((listener) => { listener(memoryState) }) } type Toast = Omit function toast({ ...props }: Toast) { const id = genId() const update = (props: ToasterToast) => dispatch({ type: "UPDATE_TOAST", toast: { ...props, id }, }) const dismiss = () => dispatch({ type: "DISMISS_TOAST", toastId: id }) dispatch({ type: "ADD_TOAST", toast: { ...props, id, open: true, onOpenChange: (open) => { if (!open) dismiss() }, }, }) return { id: id, dismiss, update, } } function useToast() { const [state, setState] = React.useState(memoryState) React.useEffect(() => { listeners.push(setState) return () => { const index = listeners.indexOf(setState) if (index > -1) { listeners.splice(index, 1) } } }, [state]) return { ...state, toast, dismiss: (toastId?: string) => dispatch({ type: "DISMISS_TOAST", toastId }), } } export { useToast, toast } ================================================ FILE: 16-Pump.Core/Frontend/hooks/use-web3.tsx ================================================ "use client" import { useContext } from "react" import { Web3Context } from "@/providers/web3-provider" export function useWeb3() { const context = useContext(Web3Context) if (context === undefined) { throw new Error("useWeb3 must be used within a Web3Provider") } return context } ================================================ FILE: 16-Pump.Core/Frontend/lib/utils.ts ================================================ import { type ClassValue, clsx } from "clsx" import { twMerge } from "tailwind-merge" export function cn(...inputs: ClassValue[]) { return twMerge(clsx(inputs)) } export function shortenAddress(address: string, chars = 4): string { if (!address) return "" return `${address.substring(0, chars + 2)}...${address.substring(address.length - chars)}` } ================================================ FILE: 16-Pump.Core/Frontend/next.config.ts ================================================ import type { NextConfig } from "next"; const nextConfig: NextConfig = { /* config options here */ // ✅ Recommended (Next.js 13+) images: { remotePatterns: [ { protocol: 'https', hostname: 'pump.mypinata.cloud', port: '', pathname: '/**', }, ], } }; export default nextConfig; ================================================ FILE: 16-Pump.Core/Frontend/package.json ================================================ { "name": "reusable", "version": "0.1.0", "private": true, "scripts": { "dev": "next dev", "build": "next build", "start": "next start", "lint": "next lint" }, "dependencies": { "@radix-ui/react-dialog": "1.1.13", "@radix-ui/react-dropdown-menu": "2.1.14", "@radix-ui/react-label": "2.1.6", "@radix-ui/react-progress": "1.1.6", "@radix-ui/react-slider": "1.3.4", "@radix-ui/react-slot": "1.2.2", "@radix-ui/react-tabs": "1.1.11", "@radix-ui/react-toast": "1.2.13", "class-variance-authority": "0.7.0", "clsx": "2.1.1", "components": "0.1.0", "ethers": "6.14.0", "layout": "2.2.0", "lucide-react": "0.454.0", "mixins": "0.0.1", "next": "15.0.2", "react": "19.0.0-rc-02c0e824-20241028", "react-dom": "19.0.0-rc-02c0e824-20241028", "reset": "0.1.0", "tailwind-merge": "2.5.4", "tailwindcss-animate": "1.0.7", "typography": "0.16.24", "utilities": "1.0.6", "variables": "1.0.1" }, "devDependencies": { "@types/node": "^20", "@types/react": "^18", "@types/react-dom": "^18", "eslint": "^8", "eslint-config-next": "15.0.2", "postcss": "^8", "tailwindcss": "^3.4.17", "typescript": "^5" } } ================================================ FILE: 16-Pump.Core/Frontend/postcss.config.mjs ================================================ /** @type {import('postcss-load-config').Config} */ const config = { plugins: { tailwindcss: {}, }, }; export default config; ================================================ FILE: 16-Pump.Core/Frontend/providers/web3-provider.tsx ================================================ "use client" import { createContext, useEffect, useState, type ReactNode } from "react" import { BrowserProvider, Contract, type JsonRpcSigner } from "ethers" import { useToast } from "@/hooks/use-toast" import { CONTRACT_ABI, CONTRACT_ADDRESS } from "@/constants/constansts" // // This would be your actual contract ABI // const CONTRACT_ABI = [ // // Add your contract ABI here // // Example: // // { // // "inputs": [ // // { // // "internalType": "string", // // "name": "name", // // "type": "string" // // }, // // { // // "internalType": "string", // // "name": "symbol", // // "type": "string" // // } // // ], // // "name": "create", // // "outputs": [], // // "stateMutability": "payable", // // "type": "function" // // }, // // ... // ] // // This would be your actual contract address // const CONTRACT_ADDRESS = "0x0000000000000000000000000000000000000000" // Core Testnet 2 Chain ID const CORE_TESTNET_2_CHAIN_ID = "0x45a" // 1114 in decimal const CORE_TESTNET_2_DETAILS = { chainId: CORE_TESTNET_2_CHAIN_ID, chainName: "Core Testnet 2", nativeCurrency: { name: "Core Testnet 2", symbol: "tCORE2", decimals: 18, }, rpcUrls: ["https://rpc.test2.btcs.network"], blockExplorerUrls: ["https://scan.test2.btcs.network"], } interface Web3ContextType { account: string | null balance: bigint | null provider: BrowserProvider | null signer: JsonRpcSigner | null contract: Contract | any isConnecting: boolean isCorrectNetwork: boolean connect: () => Promise disconnect: () => void switchToCorrectNetwork: () => Promise addCoreTestnet2: () => Promise } export const Web3Context = createContext({ account: null, balance: null, provider: null, signer: null, contract: null, isConnecting: false, isCorrectNetwork: false, connect: async () => {}, disconnect: () => {}, switchToCorrectNetwork: async () => {}, addCoreTestnet2: async () => {}, }) export function Web3Provider({ children }: { children: ReactNode }) { const [account, setAccount] = useState(null) const [balance, setBalance] = useState(null) const [provider, setProvider] = useState(null) const [signer, setSigner] = useState(null) const [contract, setContract] = useState(null) const [isConnecting, setIsConnecting] = useState(false) const [isCorrectNetwork, setIsCorrectNetwork] = useState(false) const [chainId, setChainId] = useState(null) const { toast } = useToast() // Check if MetaMask is installed const isMetaMaskInstalled = () => { return typeof window !== "undefined" && window.ethereum !== undefined } // Check if the current network is Core Testnet 2 const checkNetwork = async () => { if (!provider) return false try { const network = await provider.getNetwork() const currentChainId = "0x" + network.chainId.toString(16) setChainId(currentChainId) const isCorrect = currentChainId === CORE_TESTNET_2_CHAIN_ID setIsCorrectNetwork(isCorrect) return isCorrect } catch (error) { console.error("Error checking network:", error) setIsCorrectNetwork(false) return false } } // Switch to Core Testnet 2 const switchToCorrectNetwork = async () => { if (!window.ethereum) throw new Error("No crypto wallet found") try { await window.ethereum.request({ method: "wallet_switchEthereumChain", params: [{ chainId: CORE_TESTNET_2_CHAIN_ID }], }) // Check network after switching const provider = new BrowserProvider(window.ethereum) setProvider(provider) await checkNetwork() return true } catch (error: any) { // This error code indicates that the chain has not been added to MetaMask if (error.code === 4902) { return addCoreTestnet2() } throw error } } // Add Core Testnet 2 to MetaMask const addCoreTestnet2 = async () => { if (!window.ethereum) throw new Error("No crypto wallet found") try { await window.ethereum.request({ method: "wallet_addEthereumChain", params: [CORE_TESTNET_2_DETAILS], }) // Check network after adding const provider = new BrowserProvider(window.ethereum) setProvider(provider) await checkNetwork() return true } catch (error) { console.error("Error adding network:", error) throw error } } // Initialize provider and listen for account changes useEffect(() => { if (isMetaMaskInstalled()) { const ethereum = window.ethereum // Create provider const provider = new BrowserProvider(ethereum) setProvider(provider) // Check if already connected const checkConnection = async () => { try { const accounts = await provider.listAccounts() if (accounts.length > 0) { const account = accounts[0].address const signer = await provider.getSigner() const balance = await provider.getBalance(account) setAccount(account) setBalance(balance) setSigner(signer) // Check if on correct network await checkNetwork() // Initialize contract // Even if CONTRACT_ABI is empty, create a minimal contract to prevent loading issues const contract = new Contract(CONTRACT_ADDRESS, CONTRACT_ABI.length ? CONTRACT_ABI : [], signer) setContract(contract) } } catch (error) { console.error("Error checking connection:", error) } } checkConnection() // Listen for account changes const handleAccountsChanged = (accounts: string[]) => { if (accounts.length === 0) { // User disconnected disconnect() } else { // Account changed const newAccount = accounts[0] setAccount(newAccount) // Update balance and signer provider.getBalance(newAccount).then(setBalance) provider.getSigner().then(setSigner) // Check network again checkNetwork() } } // Listen for chain changes const handleChainChanged = () => { // Instead of reloading the page, update the chain ID and check if it's the correct network checkNetwork().then((isCorrect) => { if (isCorrect) { toast({ title: "Network Changed", description: "Successfully connected to Core Testnet 2.", }) } }) } ethereum.on("accountsChanged", handleAccountsChanged) ethereum.on("chainChanged", handleChainChanged) return () => { ethereum.removeListener("accountsChanged", handleAccountsChanged) ethereum.removeListener("chainChanged", handleChainChanged) } } }, []) // Update contract when signer changes useEffect(() => { if (signer && CONTRACT_ABI && CONTRACT_ADDRESS) { const contract = new Contract(CONTRACT_ADDRESS, CONTRACT_ABI, signer) setContract(contract) } }, [signer]) // Connect wallet const connect = async () => { if (!isMetaMaskInstalled()) { toast({ title: "MetaMask not installed", description: "Please install MetaMask to use this application.", variant: "destructive", }) return } try { setIsConnecting(true) // Request accounts const accounts = await window.ethereum.request({ method: "eth_requestAccounts" }) const account = accounts[0] // Get provider and signer const provider = new BrowserProvider(window.ethereum) const signer = await provider.getSigner() const balance = await provider.getBalance(account) setAccount(account) setProvider(provider) setSigner(signer) setBalance(balance) // Check if on correct network const isCorrect = await checkNetwork() // Initialize contract const contract = new Contract(CONTRACT_ADDRESS, CONTRACT_ABI.length ? CONTRACT_ABI : [], signer) setContract(contract) toast({ title: "Wallet connected", description: "Your wallet has been successfully connected.", }) // If not on correct network, show a toast but don't force switch if (!isCorrect) { toast({ title: "Wrong Network", description: "Please switch to Core Testnet 2 for full functionality.", variant: "destructive", }) } } catch (error) { console.error("Error connecting wallet:", error) toast({ title: "Connection failed", description: "There was an error connecting your wallet.", variant: "destructive", }) } finally { setIsConnecting(false) } } // Disconnect wallet const disconnect = () => { setAccount(null) setBalance(null) setSigner(null) setContract(null) setIsCorrectNetwork(false) toast({ title: "Wallet disconnected", description: "Your wallet has been disconnected.", }) } return ( {children} ) } ================================================ FILE: 16-Pump.Core/Frontend/tailwind.config.ts ================================================ import type { Config } from "tailwindcss" const config = { darkMode: ["class"], content: [ "./pages/**/*.{ts,tsx}", "./components/**/*.{ts,tsx}", "./app/**/*.{ts,tsx}", "./src/**/*.{ts,tsx}", "*.{js,ts,jsx,tsx,mdx}", ], prefix: "", theme: { container: { center: true, padding: "2rem", screens: { "2xl": "1400px", }, }, extend: { colors: { border: "hsl(var(--border))", input: "hsl(var(--input))", ring: "hsl(var(--ring))", background: "hsl(var(--background))", foreground: "hsl(var(--foreground))", primary: { DEFAULT: "hsl(var(--primary))", foreground: "hsl(var(--primary-foreground))", }, secondary: { DEFAULT: "hsl(var(--secondary))", foreground: "hsl(var(--secondary-foreground))", }, destructive: { DEFAULT: "hsl(var(--destructive))", foreground: "hsl(var(--destructive-foreground))", }, muted: { DEFAULT: "hsl(var(--muted))", foreground: "hsl(var(--muted-foreground))", }, accent: { DEFAULT: "hsl(var(--accent))", foreground: "hsl(var(--accent-foreground))", }, popover: { DEFAULT: "hsl(var(--popover))", foreground: "hsl(var(--popover-foreground))", }, card: { DEFAULT: "hsl(var(--card))", foreground: "hsl(var(--card-foreground))", }, orange: { "50": "#fff8eb", "100": "#ffebc8", "200": "#ffd685", "300": "#ffbe42", "400": "#ffa50f", "500": "#ff9500", "600": "#e66a00", "700": "#c04e00", "800": "#9a3d06", "900": "#7e340b", }, }, borderRadius: { lg: "var(--radius)", md: "calc(var(--radius) - 2px)", sm: "calc(var(--radius) - 4px)", }, keyframes: { "accordion-down": { from: { height: "0" }, to: { height: "var(--radix-accordion-content-height)" }, }, "accordion-up": { from: { height: "var(--radix-accordion-content-height)" }, to: { height: "0" }, }, }, animation: { "accordion-down": "accordion-down 0.2s ease-out", "accordion-up": "accordion-up 0.2s ease-out", }, }, }, plugins: [require("tailwindcss-animate")], } satisfies Config export default config ================================================ FILE: 16-Pump.Core/Frontend/tsconfig.json ================================================ { "compilerOptions": { "target": "ES2020", "lib": ["ES2020", "dom"], "allowJs": true, "skipLibCheck": true, "strict": true, "noEmit": true, "esModuleInterop": true, "module": "esnext", "moduleResolution": "bundler", "resolveJsonModule": true, "isolatedModules": true, "jsx": "preserve", "incremental": true, "plugins": [ { "name": "next" } ], "paths": { "@/*": ["./*"] } }, "include": ["next-env.d.ts", "**/*.ts", "**/*.tsx", ".next/types/**/*.ts"], "exclude": ["node_modules"] } ================================================ FILE: 16-Pump.Core/Frontend/types/global.d.ts ================================================ interface Window { ethereum: any } ================================================ FILE: 16-Pump.Core/README.md ================================================ # 🚀 MemeLaunch – Token Launchpad on Core Blockchain MemeLaunch is a dynamic, pump.fun-inspired DApp built on the Core Blockchain, enabling users to **easily launch tokens**, **view all launched tokens**, **buy any token**, and **track token balances** in their wallets. It is **modular**, **extensible**, and ready for builders who want to expand functionality like adding a **creator dashboard**, **liquidity tools**, and more. > 🧠 **GitHub Repository:** [https://github.com/coredao-org/dapp-tutorial](https://github.com/coredao-org/dapp-tutorial) --- ## ✨ Features - 🧱 **Token Factory:** Instantly deploy custom tokens with ease. - 🔍 **Token Explorer:** See a list of all launched tokens, including names, prices, and contract details. - 💰 **Buy Tokens:** Instantly buy any launched token using native Core currency. - 👛 **Wallet Integration:** View token balances directly in your wallet. - 🧪 **Test Mode Support:** Quickly test all features using test tokens on Core testnet. - 🧩 **Extensible Architecture:** Includes space to build out your **Creator Dashboard**, **liquidity manager**, and other tools. - 🌍 **Core Blockchain Ready:** Fully integrated with Core Blockchain for fast, low-cost transactions. --- ## 🔧 Getting Started ### 1. Clone the Repository ```bash git clone https://github.com/coredao-org/dapp-tutorial.git cd dapp-tutorial/16-Pump.Core ``` ### 2. Setup Environment Create a `.env` file in the root directory and add your private key: ```env PRIVATE_KEY=your_private_key_here ``` > ⚠️ **Warning:** Never expose or commit your `.env` file. Keep your private key safe. ### 3. Install Dependencies Install smart contract dependencies: ```bash npm install ``` Then navigate to the frontend directory and install frontend dependencies: ```bash cd ./Frontend npm install ``` ### 4. Run the DApp Locally ```bash npm run dev ``` > Open your browser at `http://localhost:3000` to: > > - Launch new tokens in seconds > - Buy and track trending tokens > - View token balances in your wallet > - Start customizing the creator dashboard --- ## 🚀 Deploy to Core Testnet To deploy your contracts on **Core Testnet**, follow these steps: ### 1. Set Up `.env` Make sure your `.env` file in the root directory includes: ```env PRIVATE_KEY=your_private_key CORE_TESTNET_RPC=https://rpc.test2.btcs.network ``` ### 2. Update Hardhat Config Ensure your `hardhat.config.js` includes the Core Testnet configuration: ```js require("@nomiclabs/hardhat-ethers"); require("dotenv").config(); module.exports = { solidity: "0.8.19", networks: { coreTestnet: { url: process.env.CORE_TESTNET_RPC, accounts: [process.env.PRIVATE_KEY], chainId: 1115, }, }, }; ``` ### 3. Compile & Deploy Compile contracts: ```bash npx hardhat compile ``` Deploy: ```bash npx hardhat run scripts/deploy.js --network coreTestnet ``` > 🧠 After deploying, copy the deployed contract addresses and paste them into your frontend’s environment config or contract interaction hooks. --- ## 🛠️ Creator Dashboard Starter The project includes a placeholder structure where developers can build their own **Creator Dashboard** to manage token performance, community, and liquidity. 📍 Located in the frontend: ```bash Frontend/app/dashboard ``` 💡 Ideas to Extend: - Add liquidity to token pools - Enable burn/mint features - Show real-time charts for tokens - Add community governance options > Fork this repo and start building your own meme economy on Core! --- ## 👛 View Token in Wallet After buying a token, you can add it manually to your wallet: 1. Copy the token contract address shown in the UI. 2. Open your wallet (e.g. MetaMask). 3. Click **Import Token** and paste the contract address. 4. View your token balance. --- ## 🗂️ Project Structure ```bash ├── contracts/ # Smart contracts (TokenFactory, LaunchToken) ├── scripts/ # Deployment and helper scripts ├── Frontend # Frontend Next.js app ├── hardhat.config.js # Hardhat configuration ├── .env # Store your private key securely └── README.md ``` --- ## 📘 Tech Stack - **Next.js** – Frontend framework - **Tailwind CSS** – Beautiful, responsive UI - **Hardhat** – Smart contract development and deployment - **Ethers.js** – Blockchain connection - **Solidity** – Smart contract language - **OpenZeppelin** – Secure contract standards - **Core Blockchain** – High-speed, EVM-compatible blockchain --- ## 🤝 Contribute & Build Fork this repo to kickstart your **token economy** or **meme coin launchpad**. Add: - Liquidity tools - A creator analytics dashboard - Voting & DAO integrations ================================================ FILE: 16-Pump.Core/contracts/MemeFactory.sol ================================================ // SPDX-License-Identifier: UNLICENSED pragma solidity ^0.8.27; // Uncomment this line to use console.log // import "hardhat/console.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import {MemeToken} from "./MemeToken.sol"; error MemeFactory__InsufficientFee(); error MemeFactory__InsufficientETH(); error MemeFactory__SaleClosed(); error MemeFactory__TokenAmountTooLow(); error MemeFactory__AmountExceeded(); error MemeFactory__TransferFailed(); error MemeFactory__NotOwner(); contract MemeFactory { uint256 public constant TOKEN_LIMIT = 500_000 ether; uint256 public constant TARGET = 3 ether; uint256 public immutable fee; address public owner; uint256 public totalTokens; struct TokenSale { address token; string name; string symbol; address creator; uint256 sold; uint256 raised; bool isOpen; } mapping(address => TokenSale) public tokenToSale; address[] public tokens; event Created(address indexed token); event BoughtToken(address indexed token, uint256 amount); constructor(uint256 _fee) { fee = _fee; owner = msg.sender; } // CREATE FUNCTION // 1. create new token 2. save token for later use // 3. list token for sale 4. tell people it is live function create(string memory _name, string memory _symbol) public payable { if(msg.value < fee) revert MemeFactory__InsufficientFee(); // Create a new Token MemeToken token = new MemeToken(msg.sender, _name, _symbol, 1_000_000 ether); tokens.push(address(token)); totalTokens += 1; // List Token TokenSale memory sale = TokenSale(address(token), _name, _symbol, msg.sender, 0, 0, true); tokenToSale[address(token)] = sale; // Tell people it is live emit Created(address(token)); } // Buy Token function buyToken(address _token, uint256 _amount) external payable { TokenSale storage sale = tokenToSale[_token]; if(sale.isOpen == false) revert MemeFactory__SaleClosed(); if(_amount < 0.001 ether) revert MemeFactory__TokenAmountTooLow(); if(_amount >= 1000 ether) revert MemeFactory__AmountExceeded(); // calculate the price of one token based on total bought uint256 cost = getCost(sale.sold); uint256 price = cost * (_amount / 10 ** 18); if(msg.value < price) revert MemeFactory__InsufficientETH(); sale.sold += _amount; sale.raised += price; // When it reaches this threshold then the token can be successsfully launched and deposited on a dex if(sale.sold >= TOKEN_LIMIT || sale.raised >= TARGET) sale.isOpen = false; MemeToken(_token).transfer(msg.sender, _amount); emit BoughtToken(_token, _amount); } function deposit(address _token) external { // The remaining token balance and the ETH raised would // go into a liquidity pool like uniswapV3. // For simplicity, we just transfer remaining tokens and ETH raised to the creator TokenSale memory sale = tokenToSale[_token]; // Transfer tokens MemeToken token = MemeToken(_token); token.transfer(sale.creator, token.balanceOf(address(this))); // Transfer ETH raised (bool success, ) = payable(sale.creator).call{value: sale.raised}(""); if(!success) revert MemeFactory__TransferFailed(); } function withdraw(uint256 _amount) external { if(msg.sender != owner) revert MemeFactory__NotOwner(); (bool success, ) = payable(owner).call{value: _amount}(""); if(!success) revert MemeFactory__TransferFailed(); } //// INTERNAL FUNCTIONS function getCost(uint256 _sold) public pure returns (uint256) { uint256 floor = 0.0001 ether; uint256 step = 0.0001 ether; uint256 increment = 10000 ether; uint256 cost = (step * (_sold / increment)) + floor; return cost; } //// GETTER FUNCTIONS function getTokenSale(uint256 _index) public view returns (TokenSale memory) { return tokenToSale[tokens[_index]]; } } ================================================ FILE: 16-Pump.Core/contracts/MemeToken.sol ================================================ // SPDX-License-Identifier: UNLICENSED pragma solidity ^0.8.27; // Uncomment this line to use console.log // import "hardhat/console.sol"; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; contract MemeToken is ERC20 { address payable public owner; address public creator; // event Withdrawal(uint amount, uint when); constructor(address _creator, string memory _name, string memory _symbol, uint256 _totalSupply) ERC20(_name, _symbol) { owner = payable(msg.sender); creator = _creator; _mint(msg.sender, _totalSupply); } // function withdraw() public { // // Uncomment this line, and the import of "hardhat/console.sol", to print a log in your terminal // // console.log("Unlock time is %o and block timestamp is %o", unlockTime, block.timestamp); // require(block.timestamp >= unlockTime, "You can't withdraw yet"); // require(msg.sender == owner, "You aren't the owner"); // emit Withdrawal(address(this).balance, block.timestamp); // owner.transfer(address(this).balance); // } } ================================================ FILE: 16-Pump.Core/hardhat.config.js ================================================ require("@nomicfoundation/hardhat-toolbox"); require("dotenv").config(); /** @type import('hardhat/config').HardhatUserConfig */ const PRIVATE_KEY = process.env.PRIVATE_KEY; module.exports = { solidity: "0.8.27", networks: { localhost: { url: "http://127.0.0.1:8545/", // accounts: Thanks hardhat! chainId: 31337, allowUnlimitedContractSize: true, }, core: { url: 'https://rpc.test2.btcs.network', accounts: [PRIVATE_KEY], chainId: 1114, }, }, }; ================================================ FILE: 16-Pump.Core/ignition/modules/Lock.js ================================================ // This setup uses Hardhat Ignition to manage smart contract deployments. // Learn more about it at https://hardhat.org/ignition const { buildModule } = require("@nomicfoundation/hardhat-ignition/modules"); const JAN_1ST_2030 = 1893456000; const ONE_GWEI = 1_000_000_000n; module.exports = buildModule("LockModule", (m) => { const unlockTime = m.getParameter("unlockTime", JAN_1ST_2030); const lockedAmount = m.getParameter("lockedAmount", ONE_GWEI); const lock = m.contract("Lock", [unlockTime], { value: lockedAmount, }); return { lock }; }); ================================================ FILE: 16-Pump.Core/package.json ================================================ { "name": "reuse", "version": "1.0.0", "main": "index.js", "scripts": { "test": "echo \"Error: no test specified\" && exit 1" }, "author": "", "license": "ISC", "description": "", "devDependencies": { "@nomicfoundation/hardhat-toolbox": "5.0.0", "hardhat": "2.22.15" }, "dependencies": { "@openzeppelin/contracts": "5.3.0", "dotenv": "16.5.0" } } ================================================ FILE: 16-Pump.Core/scripts/deploy.js ================================================ const hre = require("hardhat"); const { loadFixture } = require("@nomicfoundation/hardhat-toolbox/network-helpers"); async function main() { const FEE = ethers.parseUnits("0.01", 18); const FactoryMeme = await hre.ethers.getContractFactory("MemeFactory"); const factoryMeme = await FactoryMeme.deploy(FEE); console.log("MemeFactory deployed to:", factoryMeme.target); } // We recommend this pattern to be able to use async/await everywhere // and properly handle errors. main().catch((error) => { console.error(error); process.exitCode = 1; }); // CORE: PoolFactory contract deployed to: 0x5Ac64F5DA22B25559C7D7522b4B2BB7e2012F382 ================================================ FILE: 16-Pump.Core/test/Lock.js ================================================ const { time, loadFixture, } = require("@nomicfoundation/hardhat-toolbox/network-helpers"); const { anyValue } = require("@nomicfoundation/hardhat-chai-matchers/withArgs"); const { expect } = require("chai"); describe("Lock", function () { // We define a fixture to reuse the same setup in every test. // We use loadFixture to run this setup once, snapshot that state, // and reset Hardhat Network to that snapshot in every test. async function deployOneYearLockFixture() { const ONE_YEAR_IN_SECS = 365 * 24 * 60 * 60; const ONE_GWEI = 1_000_000_000; const lockedAmount = ONE_GWEI; const unlockTime = (await time.latest()) + ONE_YEAR_IN_SECS; // Contracts are deployed using the first signer/account by default const [owner, otherAccount] = await ethers.getSigners(); const Lock = await ethers.getContractFactory("Lock"); const lock = await Lock.deploy(unlockTime, { value: lockedAmount }); return { lock, unlockTime, lockedAmount, owner, otherAccount }; } describe("Deployment", function () { it("Should set the right unlockTime", async function () { const { lock, unlockTime } = await loadFixture(deployOneYearLockFixture); expect(await lock.unlockTime()).to.equal(unlockTime); }); it("Should set the right owner", async function () { const { lock, owner } = await loadFixture(deployOneYearLockFixture); expect(await lock.owner()).to.equal(owner.address); }); it("Should receive and store the funds to lock", async function () { const { lock, lockedAmount } = await loadFixture( deployOneYearLockFixture ); expect(await ethers.provider.getBalance(lock.target)).to.equal( lockedAmount ); }); it("Should fail if the unlockTime is not in the future", async function () { // We don't use the fixture here because we want a different deployment const latestTime = await time.latest(); const Lock = await ethers.getContractFactory("Lock"); await expect(Lock.deploy(latestTime, { value: 1 })).to.be.revertedWith( "Unlock time should be in the future" ); }); }); describe("Withdrawals", function () { describe("Validations", function () { it("Should revert with the right error if called too soon", async function () { const { lock } = await loadFixture(deployOneYearLockFixture); await expect(lock.withdraw()).to.be.revertedWith( "You can't withdraw yet" ); }); it("Should revert with the right error if called from another account", async function () { const { lock, unlockTime, otherAccount } = await loadFixture( deployOneYearLockFixture ); // We can increase the time in Hardhat Network await time.increaseTo(unlockTime); // We use lock.connect() to send a transaction from another account await expect(lock.connect(otherAccount).withdraw()).to.be.revertedWith( "You aren't the owner" ); }); it("Shouldn't fail if the unlockTime has arrived and the owner calls it", async function () { const { lock, unlockTime } = await loadFixture( deployOneYearLockFixture ); // Transactions are sent using the first signer by default await time.increaseTo(unlockTime); await expect(lock.withdraw()).not.to.be.reverted; }); }); describe("Events", function () { it("Should emit an event on withdrawals", async function () { const { lock, unlockTime, lockedAmount } = await loadFixture( deployOneYearLockFixture ); await time.increaseTo(unlockTime); await expect(lock.withdraw()) .to.emit(lock, "Withdrawal") .withArgs(lockedAmount, anyValue); // We accept any value as `when` arg }); }); describe("Transfers", function () { it("Should transfer the funds to the owner", async function () { const { lock, unlockTime, lockedAmount, owner } = await loadFixture( deployOneYearLockFixture ); await time.increaseTo(unlockTime); await expect(lock.withdraw()).to.changeEtherBalances( [owner, lock], [lockedAmount, -lockedAmount] ); }); }); }); }); ================================================ FILE: 17-Crowd-Funding-Dapp/Contract/.gitignore ================================================ node_modules .env coverage coverage.json typechain typechain-types #Hardhat files cache* artifacts* ================================================ FILE: 17-Crowd-Funding-Dapp/Contract/README.md ================================================ ## Getting Started Create a project using this example: ```bash npx thirdweb create --contract --template hardhat-javascript-starter ``` You can start editing the page by modifying `contracts/Contract.sol`. To add functionality to your contracts, you can use the `@thirdweb-dev/contracts` package which provides base contracts and extensions to inherit. The package is already installed with this project. Head to our [Contracts Extensions Docs](https://portal.thirdweb.com/contractkit) to learn more. ## Building the project After any changes to the contract, run: ```bash npm run build # or yarn build ``` to compile your contracts. This will also detect the [Contracts Extensions Docs](https://portal.thirdweb.com/contractkit) detected on your contract. ## Deploying Contracts When you're ready to deploy your contracts, just run one of the following command to deploy you're contracts: ```bash npm run deploy # or yarn deploy ``` > [!IMPORTANT] > This requires a secret key to make it work. Get your secret key [here](https://thirdweb.com/dashboard/settings/api-keys). > Pass your secret key as a value after `-k` flag. > ```bash > npm run deploy -- -k > # or > yarn deploy -k ## Releasing Contracts If you want to release a version of your contracts publicly, you can use one of the followings command: ```bash npm run release # or yarn release ``` ## Join our Discord! For any questions, suggestions, join our discord at [https://discord.gg/thirdweb](https://discord.gg/thirdweb). ================================================ FILE: 17-Crowd-Funding-Dapp/Contract/contracts/CrowdFunding.sol ================================================ // SPDX-License-Identifier: UNLICENSED pragma solidity ^0.8.13; contract CrowdFunding{ string public name; string public description; uint256 public goal; uint256 public deadLine; address public owner; bool public paused; enum CampaignState {Active , Successful , Failed} CampaignState public state; struct Tier{ string name; uint256 amount; uint256 backers; } struct Backer{ uint256 totalcontribution; mapping (uint256 =>bool) fundedTires; } Tier[] public tiers; mapping (address =>Backer) public backers; modifier onlyOwner(){ require(msg.sender==owner,"Not Owner"); _; } modifier campaingOpen(){ require(state==CampaignState.Active,"Campain is not Active"); _; } modifier notpuased(){ require(!paused,"Contract is Paused"); _; } constructor(address _owner,string memory _name,string memory _description,uint256 _goal , uint256 _duration ){ name=_name; description=_description; goal=_goal; deadLine=block.timestamp+(_duration * 1 days); owner=_owner; state=CampaignState.Active; } function checkAndUpdateCampaignState() internal{ if(state== CampaignState.Active){ if(block.timestamp>=deadLine){ state=address(this).balance >= goal ? CampaignState.Successful: CampaignState.Failed; } else{ state=address(this).balance >= goal ? CampaignState.Successful: CampaignState.Active; } } } function fund(uint256 _tierIndex)public payable campaingOpen notpuased{ require(_tierIndex0,"Please Enter Valid Tier"); tiers.push(Tier(_name,_amount,0)); } function removeTier(uint256 _index) public onlyOwner{ require(_index0,"no Balance"); payable(owner).transfer(balance); } function getcontractBalance() public view returns (uint256){ return address(this).balance; } function refund() public { checkAndUpdateCampaignState(); uint256 amount =backers[msg.sender].totalcontribution; require(amount>0,"No contribution to refund"); backers[msg.sender].totalcontribution=0; payable(msg.sender).transfer(amount); } function hasfundedtier(address _backer , uint256 _tierIndex) public view returns (bool){ return backers[_backer].fundedTires[_tierIndex]; } function getTiers() public view returns (Tier[] memory){ return tiers; } function tooglepause () public onlyOwner{ paused = !paused; } function getCampaignStatus() public view returns (CampaignState){ if(state== CampaignState.Active && block.timestamp>deadLine){ return address(this).balance >= goal ? CampaignState.Successful : CampaignState.Failed; } return state; } function extendDeadLine(uint256 _daysAdded) public onlyOwner campaingOpen{ deadLine+=_daysAdded*1 days; } } ================================================ FILE: 17-Crowd-Funding-Dapp/Contract/contracts/CrowdFundingFactory.sol ================================================ // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; // import {CrowdFunding} from "./CrowdFunding.sol"; import {CrowdFunding} from "./CrowdFunding.sol"; contract CrowdFundingFactory { address public owner; bool public paused; struct Campaign { address campaignAddress; address owner; string name; uint256 creationTime; } Campaign[] public campaigns; mapping(address => Campaign[]) public userCampaigns; modifier onlyOwner() { require(msg.sender == owner, "Only the owner can perform this action"); _; } modifier notPaused() { require(!paused, "Factory paused"); _; } constructor() { owner = msg.sender; } function createCampaign( string memory _name, string memory _description, uint256 _goal, uint256 _duration ) external notPaused { CrowdFunding newCampaign = new CrowdFunding(msg.sender, _name, _description, _goal, _duration); address campaignAddress = address(newCampaign); Campaign memory campaign = Campaign({ campaignAddress: campaignAddress, owner: msg.sender, name: _name, creationTime: block.timestamp }); campaigns.push(campaign); userCampaigns[msg.sender].push(campaign); } function getUserCampaigns(address _user) external view returns (Campaign[] memory) { return userCampaigns[_user]; } function getAllCampaigns() external view returns (Campaign[] memory) { return campaigns; } function togglePause() external onlyOwner { paused = !paused; } } ================================================ FILE: 17-Crowd-Funding-Dapp/Contract/hardhat.config.js ================================================ require("@matterlabs/hardhat-zksync-solc"); require("@matterlabs/hardhat-zksync-verify"); /** @type import('hardhat/config').HardhatUserConfig */ module.exports = { zksolc: { version: "1.4.1", compilerSource: "binary", settings: { optimizer: { enabled: true, }, }, }, networks: { zkSyncSepoliaTestnet: { url: "https://sepolia.era.zksync.dev", ethNetwork: "sepolia", zksync: true, chainId: 300, verifyURL: "https://explorer.sepolia.era.zksync.dev/contract_verification", }, zkSyncMainnet: { url: "https://mainnet.era.zksync.io", ethNetwork: "mainnet", zksync: true, chainId: 324, verifyURL: "https://zksync2-mainnet-explorer.zksync.io/contract_verification", }, }, paths: { artifacts: "./artifacts-zk", cache: "./cache-zk", sources: "./contracts", tests: "./test", }, solidity: { version: "0.8.23", settings: { optimizer: { enabled: true, runs: 200, }, }, }, }; ================================================ FILE: 17-Crowd-Funding-Dapp/Contract/package.json ================================================ { "name": "hardhat-javascript-starter", "scripts": { "build": "npx thirdweb@latest detect", "deploy": "npx thirdweb@latest deploy", "publish": "npx thirdweb@latest publish" }, "devDependencies": { "@matterlabs/hardhat-zksync-solc": "^1.1.14", "@matterlabs/hardhat-zksync-verify": "^1.7.1", "hardhat": "^2.19.1" }, "dependencies": { "@thirdweb-dev/contracts": "^3.8.0", "zksync-ethers": "^5.7.0" } } ================================================ FILE: 17-Crowd-Funding-Dapp/Contract/scripts/verify/my-contract.js ================================================ const hre = require("hardhat"); // to run the script: // npx hardhat run scripts/verify/my-contract.js --network zkSyncSepoliaTestnet async function main() { const contractAddress = ""; // TODO: contract address const constructorArgs = []; // TODO: add constructor params here, if any console.log("Verifying contract."); await verify( contractAddress, "contracts/Contract.sol:MyContract", constructorArgs ); } async function verify(address, contract, args) { try { return await hre.run("verify:verify", { address: address, contract: contract, constructorArguments: args, }); } catch (e) { console.log(address, args, e); } } main() .then(() => process.exit(0)) .catch((e) => { console.error(e); process.exit(1); }); ================================================ FILE: 17-Crowd-Funding-Dapp/Frontend/.gitignore ================================================ # Logs logs *.log npm-debug.log* yarn-debug.log* yarn-error.log* pnpm-debug.log* lerna-debug.log* node_modules dist dist-ssr *.local # Editor directories and files .vscode/* !.vscode/extensions.json .idea .DS_Store *.suo *.ntvs* *.njsproj *.sln *.sw? # secrets .env ================================================ FILE: 17-Crowd-Funding-Dapp/Frontend/.prettierrc ================================================ { "singleQuote": false, "semi": true } ================================================ FILE: 17-Crowd-Funding-Dapp/Frontend/.vite/deps_temp_6cf5ba4c/AllWalletsUI-27PR6NO2.js ================================================ "use client"; import { AllWalletsUI_default } from "./chunk-HO57TQQM.js"; import "./chunk-AARWH2GQ.js"; import "./chunk-HI6IFF64.js"; import "./chunk-U3QNWT4A.js"; import "./chunk-XC5J5ANL.js"; import "./chunk-NOA36MVL.js"; import "./chunk-FXBAO7K3.js"; import "./chunk-PWFRCBEK.js"; import "./chunk-2HYPHUAF.js"; import "./chunk-FNI7M3UI.js"; import "./chunk-Q3TN3POE.js"; import "./chunk-ZLJ6VYSG.js"; import "./chunk-6WNCTW75.js"; import "./chunk-QLJVAXYD.js"; import "./chunk-CLN3QXW2.js"; import "./chunk-R76ND7QY.js"; import "./chunk-G26WKBGM.js"; import "./chunk-7AY3QZZV.js"; import "./chunk-BZXRHH4X.js"; import "./chunk-QIUEWTOP.js"; import "./chunk-2RRVHQYX.js"; import "./chunk-I2GEMA2B.js"; import "./chunk-SWMZXE3E.js"; import "./chunk-N24CESYN.js"; import "./chunk-VIBS7Y3M.js"; import "./chunk-PB7CMXGP.js"; import "./chunk-2MTJELC7.js"; import "./chunk-4PEUWIWY.js"; import "./chunk-7ZCK2FX5.js"; import "./chunk-UY2SRO54.js"; import "./chunk-ZNEQLT5Q.js"; import "./chunk-NPXNISXJ.js"; import "./chunk-PK5NRJAC.js"; import "./chunk-7VZHRFCE.js"; import "./chunk-AG4NO6K6.js"; import "./chunk-NPJBMLFY.js"; import "./chunk-YPFLLHK6.js"; import "./chunk-7EY5MWB2.js"; import "./chunk-U7TO6S3N.js"; import "./chunk-LO5SQBMX.js"; import "./chunk-EIVAOYE5.js"; import "./chunk-67BSOYLQ.js"; import "./chunk-B7XHB4Z2.js"; import "./chunk-O6UZ65WN.js"; import "./chunk-GINVHONX.js"; import "./chunk-O6LGEXJ4.js"; import "./chunk-ME5GAE4N.js"; import "./chunk-I5DK3TWY.js"; import "./chunk-NJUWOGZE.js"; import "./chunk-TFBEDS4S.js"; import "./chunk-GOA7IGSB.js"; import "./chunk-QHKZ43P6.js"; import "./chunk-3GSJ2FQJ.js"; import "./chunk-P7ZDTV2E.js"; import "./chunk-SNQ54XRM.js"; import "./chunk-BBNNHC5G.js"; import "./chunk-Y3WKETHV.js"; import "./chunk-SPELR2RL.js"; import "./chunk-SEVZ5PBP.js"; export { AllWalletsUI_default as default }; //# sourceMappingURL=AllWalletsUI-27PR6NO2.js.map ================================================ FILE: 17-Crowd-Funding-Dapp/Frontend/.vite/deps_temp_6cf5ba4c/BuyScreen-N3MCCV33.js ================================================ import { BuyScreen } from "./chunk-FHZU65JA.js"; import "./chunk-QLCPWJYR.js"; import "./chunk-EGJT3UEX.js"; import "./chunk-YG7T4W43.js"; import "./chunk-R554PO5S.js"; import "./chunk-5THTWD2M.js"; import "./chunk-7ZNEOXS2.js"; import "./chunk-KWA5PGSC.js"; import "./chunk-MGEBXLXC.js"; import "./chunk-65EUCVOP.js"; import "./chunk-HO57TQQM.js"; import "./chunk-AARWH2GQ.js"; import "./chunk-HI6IFF64.js"; import "./chunk-U3QNWT4A.js"; import "./chunk-GGVPULQZ.js"; import "./chunk-6RU56BH7.js"; import "./chunk-EHYTL2NA.js"; import "./chunk-YGRUPXVB.js"; import "./chunk-XB34LHR5.js"; import "./chunk-5U5XBS6S.js"; import "./chunk-XC5J5ANL.js"; import "./chunk-36FW3ZLE.js"; import "./chunk-7ETS5GH6.js"; import "./chunk-4U2YWK76.js"; import "./chunk-VJFQPB47.js"; import "./chunk-NOA36MVL.js"; import "./chunk-FXBAO7K3.js"; import "./chunk-PWFRCBEK.js"; import "./chunk-2HYPHUAF.js"; import "./chunk-FNI7M3UI.js"; import "./chunk-Q3TN3POE.js"; import "./chunk-O6KA6WKL.js"; import "./chunk-ZLJ6VYSG.js"; import "./chunk-6WNCTW75.js"; import "./chunk-QLJVAXYD.js"; import "./chunk-CLN3QXW2.js"; import "./chunk-4RRAU5V7.js"; import "./chunk-QVNJVROL.js"; import "./chunk-R76ND7QY.js"; import "./chunk-G26WKBGM.js"; import "./chunk-7AY3QZZV.js"; import "./chunk-BZXRHH4X.js"; import "./chunk-QIUEWTOP.js"; import "./chunk-2RRVHQYX.js"; import "./chunk-XTOEMUZK.js"; import "./chunk-J7FYPWA5.js"; import "./chunk-EIBOABXT.js"; import "./chunk-I2GEMA2B.js"; import "./chunk-SWMZXE3E.js"; import "./chunk-N24CESYN.js"; import "./chunk-CYVKJMZE.js"; import "./chunk-VIBS7Y3M.js"; import "./chunk-VJOHABJ4.js"; import "./chunk-6FLJU7W7.js"; import "./chunk-PB7CMXGP.js"; import "./chunk-SJKAB62J.js"; import "./chunk-2MTJELC7.js"; import "./chunk-PHVX3XOV.js"; import "./chunk-ADIC4TC2.js"; import "./chunk-4PEUWIWY.js"; import "./chunk-TTOANXGP.js"; import "./chunk-AWMNEQRO.js"; import "./chunk-6XF6HOWC.js"; import "./chunk-JTR2PIFP.js"; import "./chunk-JZC47WAY.js"; import "./chunk-CXAZLQ2Z.js"; import "./chunk-QC3K2OKT.js"; import "./chunk-7ZCK2FX5.js"; import "./chunk-7QDK5KLB.js"; import "./chunk-UY2SRO54.js"; import "./chunk-673YCYST.js"; import "./chunk-JBQP4JIV.js"; import "./chunk-4OCU6WGG.js"; import "./chunk-3DBHE3NE.js"; import "./chunk-5CO5G7XZ.js"; import "./chunk-ZNEQLT5Q.js"; import "./chunk-NPXNISXJ.js"; import "./chunk-PK5NRJAC.js"; import "./chunk-7VZHRFCE.js"; import "./chunk-CNLOA7AS.js"; import "./chunk-AG4NO6K6.js"; import "./chunk-NPJBMLFY.js"; import "./chunk-YPFLLHK6.js"; import "./chunk-7EY5MWB2.js"; import "./chunk-U7TO6S3N.js"; import "./chunk-LO5SQBMX.js"; import "./chunk-EIVAOYE5.js"; import "./chunk-67BSOYLQ.js"; import "./chunk-B7XHB4Z2.js"; import "./chunk-O6UZ65WN.js"; import "./chunk-GINVHONX.js"; import "./chunk-O6LGEXJ4.js"; import "./chunk-ME5GAE4N.js"; import "./chunk-I5DK3TWY.js"; import "./chunk-NJUWOGZE.js"; import "./chunk-TFBEDS4S.js"; import "./chunk-GOA7IGSB.js"; import "./chunk-QHKZ43P6.js"; import "./chunk-3GSJ2FQJ.js"; import "./chunk-P7ZDTV2E.js"; import "./chunk-SNQ54XRM.js"; import "./chunk-BBNNHC5G.js"; import "./chunk-Y3WKETHV.js"; import "./chunk-SPELR2RL.js"; import "./chunk-SEVZ5PBP.js"; export { BuyScreen as default }; //# sourceMappingURL=BuyScreen-N3MCCV33.js.map ================================================ FILE: 17-Crowd-Funding-Dapp/Frontend/.vite/deps_temp_6cf5ba4c/CoinbaseSDKConnection-PPK2JHPJ.js ================================================ import { ConnectingScreen } from "./chunk-MGEBXLXC.js"; import "./chunk-HI6IFF64.js"; import { require_jsx_runtime } from "./chunk-U3QNWT4A.js"; import "./chunk-XC5J5ANL.js"; import "./chunk-NOA36MVL.js"; import "./chunk-PWFRCBEK.js"; import "./chunk-ZLJ6VYSG.js"; import "./chunk-BZXRHH4X.js"; import "./chunk-QIUEWTOP.js"; import "./chunk-VIBS7Y3M.js"; import { require_react } from "./chunk-2MTJELC7.js"; import "./chunk-4PEUWIWY.js"; import "./chunk-UY2SRO54.js"; import "./chunk-ZNEQLT5Q.js"; import "./chunk-PK5NRJAC.js"; import "./chunk-7VZHRFCE.js"; import "./chunk-AG4NO6K6.js"; import "./chunk-NPJBMLFY.js"; import "./chunk-YPFLLHK6.js"; import "./chunk-7EY5MWB2.js"; import "./chunk-U7TO6S3N.js"; import "./chunk-LO5SQBMX.js"; import "./chunk-EIVAOYE5.js"; import "./chunk-67BSOYLQ.js"; import "./chunk-B7XHB4Z2.js"; import "./chunk-O6UZ65WN.js"; import "./chunk-GINVHONX.js"; import "./chunk-O6LGEXJ4.js"; import "./chunk-ME5GAE4N.js"; import "./chunk-I5DK3TWY.js"; import "./chunk-NJUWOGZE.js"; import "./chunk-TFBEDS4S.js"; import "./chunk-GOA7IGSB.js"; import "./chunk-QHKZ43P6.js"; import "./chunk-3GSJ2FQJ.js"; import "./chunk-P7ZDTV2E.js"; import "./chunk-SNQ54XRM.js"; import "./chunk-BBNNHC5G.js"; import "./chunk-Y3WKETHV.js"; import "./chunk-SPELR2RL.js"; import { __toESM } from "./chunk-SEVZ5PBP.js"; // node_modules/thirdweb/dist/esm/react/web/wallets/shared/CoinbaseSDKConnection.js var import_jsx_runtime = __toESM(require_jsx_runtime(), 1); var import_react = __toESM(require_react(), 1); function ExternalWalletConnectUI(props) { const { onBack, done, wallet, walletInfo, onGetStarted, locale } = props; const [errorConnecting, setErrorConnecting] = (0, import_react.useState)(false); const connect = (0, import_react.useCallback)(() => { setErrorConnecting(false); wallet.connect({ client: props.client, chain: props.chain }).then(() => { done(); }).catch((e) => { console.error(e); setErrorConnecting(true); }); }, [props.client, wallet, props.chain, done]); const scanStarted = (0, import_react.useRef)(false); (0, import_react.useEffect)(() => { if (scanStarted.current) { return; } scanStarted.current = true; connect(); }, [connect]); return (0, import_jsx_runtime.jsx)(ConnectingScreen, { locale: { getStartedLink: locale.getStartedLink, instruction: locale.connectionScreen.instruction, tryAgain: locale.connectionScreen.retry, inProgress: locale.connectionScreen.inProgress, failed: locale.connectionScreen.failed }, onBack, walletName: walletInfo.name, walletId: wallet.id, errorConnecting, onRetry: connect, onGetStarted, client: props.client, size: props.size }); } var CoinbaseSDKConnection_default = ExternalWalletConnectUI; export { CoinbaseSDKConnection_default as default }; //# sourceMappingURL=CoinbaseSDKConnection-PPK2JHPJ.js.map ================================================ FILE: 17-Crowd-Funding-Dapp/Frontend/.vite/deps_temp_6cf5ba4c/EcosystemWalletConnectUI-ANAXYA53.js ================================================ "use client"; import { EcosystemWalletConnectUI_default } from "./chunk-EGJT3UEX.js"; import "./chunk-7ZNEOXS2.js"; import "./chunk-KWA5PGSC.js"; import "./chunk-MGEBXLXC.js"; import "./chunk-65EUCVOP.js"; import "./chunk-HO57TQQM.js"; import "./chunk-AARWH2GQ.js"; import "./chunk-HI6IFF64.js"; import "./chunk-U3QNWT4A.js"; import "./chunk-5U5XBS6S.js"; import "./chunk-XC5J5ANL.js"; import "./chunk-NOA36MVL.js"; import "./chunk-FXBAO7K3.js"; import "./chunk-PWFRCBEK.js"; import "./chunk-2HYPHUAF.js"; import "./chunk-FNI7M3UI.js"; import "./chunk-Q3TN3POE.js"; import "./chunk-ZLJ6VYSG.js"; import "./chunk-6WNCTW75.js"; import "./chunk-QLJVAXYD.js"; import "./chunk-CLN3QXW2.js"; import "./chunk-R76ND7QY.js"; import "./chunk-G26WKBGM.js"; import "./chunk-7AY3QZZV.js"; import "./chunk-BZXRHH4X.js"; import "./chunk-QIUEWTOP.js"; import "./chunk-2RRVHQYX.js"; import "./chunk-XTOEMUZK.js"; import "./chunk-J7FYPWA5.js"; import "./chunk-EIBOABXT.js"; import "./chunk-I2GEMA2B.js"; import "./chunk-SWMZXE3E.js"; import "./chunk-N24CESYN.js"; import "./chunk-CYVKJMZE.js"; import "./chunk-VIBS7Y3M.js"; import "./chunk-VJOHABJ4.js"; import "./chunk-PB7CMXGP.js"; import "./chunk-2MTJELC7.js"; import "./chunk-4PEUWIWY.js"; import "./chunk-7ZCK2FX5.js"; import "./chunk-UY2SRO54.js"; import "./chunk-ZNEQLT5Q.js"; import "./chunk-NPXNISXJ.js"; import "./chunk-PK5NRJAC.js"; import "./chunk-7VZHRFCE.js"; import "./chunk-AG4NO6K6.js"; import "./chunk-NPJBMLFY.js"; import "./chunk-YPFLLHK6.js"; import "./chunk-7EY5MWB2.js"; import "./chunk-U7TO6S3N.js"; import "./chunk-LO5SQBMX.js"; import "./chunk-EIVAOYE5.js"; import "./chunk-67BSOYLQ.js"; import "./chunk-B7XHB4Z2.js"; import "./chunk-O6UZ65WN.js"; import "./chunk-GINVHONX.js"; import "./chunk-O6LGEXJ4.js"; import "./chunk-ME5GAE4N.js"; import "./chunk-I5DK3TWY.js"; import "./chunk-NJUWOGZE.js"; import "./chunk-TFBEDS4S.js"; import "./chunk-GOA7IGSB.js"; import "./chunk-QHKZ43P6.js"; import "./chunk-3GSJ2FQJ.js"; import "./chunk-P7ZDTV2E.js"; import "./chunk-SNQ54XRM.js"; import "./chunk-BBNNHC5G.js"; import "./chunk-Y3WKETHV.js"; import "./chunk-SPELR2RL.js"; import "./chunk-SEVZ5PBP.js"; export { EcosystemWalletConnectUI_default as default }; //# sourceMappingURL=EcosystemWalletConnectUI-ANAXYA53.js.map ================================================ FILE: 17-Crowd-Funding-Dapp/Frontend/.vite/deps_temp_6cf5ba4c/InAppWalletConnectUI-IYEPIHHJ.js ================================================ "use client"; import { GuestLogin, OTPLoginUI, PassKeyLogin, PoweredByThirdweb, SocialLogin, TOS, WalletAuth } from "./chunk-7ZNEOXS2.js"; import { ConnectWalletSocialOptions, LoadingScreen, useInAppWalletLocale, useScreenContext } from "./chunk-KWA5PGSC.js"; import "./chunk-MGEBXLXC.js"; import "./chunk-65EUCVOP.js"; import "./chunk-HO57TQQM.js"; import { useSelectionData, useSetSelectionData } from "./chunk-AARWH2GQ.js"; import { Container, Img, ModalHeader, ModalTitle, Spacer, iconSize } from "./chunk-HI6IFF64.js"; import { require_jsx_runtime } from "./chunk-U3QNWT4A.js"; import "./chunk-5U5XBS6S.js"; import "./chunk-XC5J5ANL.js"; import "./chunk-NOA36MVL.js"; import "./chunk-FXBAO7K3.js"; import "./chunk-PWFRCBEK.js"; import "./chunk-2HYPHUAF.js"; import "./chunk-FNI7M3UI.js"; import "./chunk-Q3TN3POE.js"; import "./chunk-ZLJ6VYSG.js"; import "./chunk-6WNCTW75.js"; import "./chunk-QLJVAXYD.js"; import "./chunk-CLN3QXW2.js"; import "./chunk-R76ND7QY.js"; import "./chunk-G26WKBGM.js"; import "./chunk-7AY3QZZV.js"; import "./chunk-BZXRHH4X.js"; import "./chunk-QIUEWTOP.js"; import "./chunk-2RRVHQYX.js"; import "./chunk-XTOEMUZK.js"; import "./chunk-J7FYPWA5.js"; import "./chunk-EIBOABXT.js"; import "./chunk-I2GEMA2B.js"; import "./chunk-SWMZXE3E.js"; import "./chunk-N24CESYN.js"; import "./chunk-CYVKJMZE.js"; import "./chunk-VIBS7Y3M.js"; import "./chunk-VJOHABJ4.js"; import "./chunk-PB7CMXGP.js"; import { require_react } from "./chunk-2MTJELC7.js"; import "./chunk-4PEUWIWY.js"; import "./chunk-7ZCK2FX5.js"; import "./chunk-UY2SRO54.js"; import "./chunk-ZNEQLT5Q.js"; import "./chunk-NPXNISXJ.js"; import "./chunk-PK5NRJAC.js"; import "./chunk-7VZHRFCE.js"; import "./chunk-AG4NO6K6.js"; import "./chunk-NPJBMLFY.js"; import "./chunk-YPFLLHK6.js"; import "./chunk-7EY5MWB2.js"; import "./chunk-U7TO6S3N.js"; import "./chunk-LO5SQBMX.js"; import "./chunk-EIVAOYE5.js"; import "./chunk-67BSOYLQ.js"; import "./chunk-B7XHB4Z2.js"; import "./chunk-O6UZ65WN.js"; import "./chunk-GINVHONX.js"; import "./chunk-O6LGEXJ4.js"; import "./chunk-ME5GAE4N.js"; import "./chunk-I5DK3TWY.js"; import "./chunk-NJUWOGZE.js"; import "./chunk-TFBEDS4S.js"; import "./chunk-GOA7IGSB.js"; import "./chunk-QHKZ43P6.js"; import "./chunk-3GSJ2FQJ.js"; import "./chunk-P7ZDTV2E.js"; import "./chunk-SNQ54XRM.js"; import "./chunk-BBNNHC5G.js"; import "./chunk-Y3WKETHV.js"; import "./chunk-SPELR2RL.js"; import { __toESM } from "./chunk-SEVZ5PBP.js"; // node_modules/thirdweb/dist/esm/react/web/wallets/in-app/InAppWalletConnectUI.js var import_jsx_runtime2 = __toESM(require_jsx_runtime(), 1); // node_modules/thirdweb/dist/esm/react/web/wallets/in-app/InAppWalletFormUI.js var import_jsx_runtime = __toESM(require_jsx_runtime(), 1); var import_react = __toESM(require_react(), 1); function InAppWalletFormUIScreen(props) { var _a, _b, _c, _d, _e, _f, _g, _h, _i, _j, _k; const isCompact = props.size === "compact"; const { initialScreen, screen } = useScreenContext(); const [isApproved, setIsApproved] = (0, import_react.useState)(false); const isInitialScreen = screen === props.wallet && initialScreen === props.wallet; const onBack = isInitialScreen && !props.isLinking ? void 0 : props.goBack; return (0, import_jsx_runtime.jsxs)(Container, { fullHeight: true, flex: "column", p: "lg", animate: "fadein", style: { minHeight: "250px" }, children: [isCompact && (isInitialScreen ? (0, import_jsx_runtime.jsxs)(import_jsx_runtime.Fragment, { children: [(0, import_jsx_runtime.jsx)(ModalHeader, { onBack, leftAligned: !props.isLinking, title: (0, import_jsx_runtime.jsxs)(import_jsx_runtime.Fragment, { children: [!((_a = props.meta) == null ? void 0 : _a.titleIconUrl) ? null : (0, import_jsx_runtime.jsx)(Img, { src: (_b = props.meta) == null ? void 0 : _b.titleIconUrl, width: iconSize.md, height: iconSize.md, client: props.client }), (0, import_jsx_runtime.jsx)(ModalTitle, { children: ((_c = props.meta) == null ? void 0 : _c.title) ?? props.inAppWalletLocale.emailLoginScreen.title })] }) }), (0, import_jsx_runtime.jsx)(Spacer, { y: "lg" })] }) : (0, import_jsx_runtime.jsx)(ModalHeader, { onBack, title: props.inAppWalletLocale.signIn })), (0, import_jsx_runtime.jsx)(Container, { expand: true, flex: "column", center: "y", p: isCompact ? void 0 : "lg", children: (0, import_jsx_runtime.jsx)(ConnectWalletSocialOptions, { ...props, locale: props.inAppWalletLocale, disabled: ((_d = props.meta) == null ? void 0 : _d.requireApproval) && !isApproved }) }), isCompact && (((_e = props.meta) == null ? void 0 : _e.showThirdwebBranding) !== false || ((_f = props.meta) == null ? void 0 : _f.termsOfServiceUrl) || ((_g = props.meta) == null ? void 0 : _g.privacyPolicyUrl)) && (0, import_jsx_runtime.jsx)(Spacer, { y: "xl" }), (0, import_jsx_runtime.jsxs)(Container, { flex: "column", gap: "lg", children: [(0, import_jsx_runtime.jsx)(TOS, { termsOfServiceUrl: (_h = props.meta) == null ? void 0 : _h.termsOfServiceUrl, privacyPolicyUrl: (_i = props.meta) == null ? void 0 : _i.privacyPolicyUrl, locale: props.connectLocale.agreement, requireApproval: (_j = props.meta) == null ? void 0 : _j.requireApproval, onApprove: () => { setIsApproved(!isApproved); }, isApproved }), ((_k = props.meta) == null ? void 0 : _k.showThirdwebBranding) !== false && (0, import_jsx_runtime.jsx)(PoweredByThirdweb, {})] })] }); } // node_modules/thirdweb/dist/esm/react/web/wallets/in-app/InAppWalletConnectUI.js function InAppWalletConnectUI(props) { const data = useSelectionData(); const setSelectionData = useSetSelectionData(); const state = data; const localeId = props.connectLocale.id; const locale = useInAppWalletLocale(localeId); const { initialScreen } = useScreenContext(); if (!locale) { return (0, import_jsx_runtime2.jsx)(LoadingScreen, {}); } const goBackToMain = () => { var _a; if (initialScreen === props.wallet) { setSelectionData({}); } else { (_a = props.goBack) == null ? void 0 : _a.call(props); setSelectionData({}); } }; const done = () => { props.done(); setSelectionData({}); }; const otpUserInfo = (state == null ? void 0 : state.emailLogin) ? { email: state.emailLogin } : (state == null ? void 0 : state.phoneLogin) ? { phone: state.phoneLogin } : void 0; if (otpUserInfo) { return (0, import_jsx_runtime2.jsx)(OTPLoginUI, { userInfo: otpUserInfo, locale, done, goBack: goBackToMain, wallet: props.wallet, chain: props.chain, client: props.client, size: props.size, isLinking: props.isLinking }); } if (state == null ? void 0 : state.passkeyLogin) { return (0, import_jsx_runtime2.jsx)(PassKeyLogin, { locale: props.connectLocale, wallet: props.wallet, done, onBack: goBackToMain, chain: props.chain, client: props.client, size: props.size, isLinking: props.isLinking }); } if (state == null ? void 0 : state.walletLogin) { return (0, import_jsx_runtime2.jsx)(WalletAuth, { meta: props.meta, inAppLocale: locale, walletConnect: props.walletConnect, wallet: props.wallet, client: props.client, size: props.size, done, onBack: goBackToMain || (() => setSelectionData({})), locale: props.connectLocale, isLinking: state.walletLogin.linking }); } if (state == null ? void 0 : state.socialLogin) { return (0, import_jsx_runtime2.jsx)(SocialLogin, { socialAuth: state.socialLogin.type, locale, done, goBack: goBackToMain, wallet: props.wallet, state, chain: props.chain, client: props.client, size: props.size, connectLocale: props.connectLocale, isLinking: props.isLinking }); } if (state == null ? void 0 : state.guestLogin) { return (0, import_jsx_runtime2.jsx)(GuestLogin, { locale, done, goBack: goBackToMain, wallet: props.wallet, state, client: props.client, size: props.size, connectLocale: props.connectLocale }); } return (0, import_jsx_runtime2.jsx)(InAppWalletFormUIScreen, { select: () => { }, connectLocale: props.connectLocale, inAppWalletLocale: locale, done, goBack: props.goBack, wallet: props.wallet, client: props.client, meta: props.meta, size: props.size, chain: props.chain, isLinking: props.isLinking }); } var InAppWalletConnectUI_default = InAppWalletConnectUI; export { InAppWalletConnectUI_default as default }; //# sourceMappingURL=InAppWalletConnectUI-IYEPIHHJ.js.map ================================================ FILE: 17-Crowd-Funding-Dapp/Frontend/.vite/deps_temp_6cf5ba4c/InAppWalletSelectionUI-QJ7CQPJG.js ================================================ "use client"; import { ConnectWalletSocialOptions, LoadingScreen, reservedScreens, useInAppWalletLocale, useScreenContext } from "./chunk-KWA5PGSC.js"; import "./chunk-65EUCVOP.js"; import { WalletEntryButton, useSetSelectionData } from "./chunk-AARWH2GQ.js"; import "./chunk-HI6IFF64.js"; import { require_jsx_runtime } from "./chunk-U3QNWT4A.js"; import "./chunk-XC5J5ANL.js"; import "./chunk-NOA36MVL.js"; import "./chunk-PWFRCBEK.js"; import "./chunk-ZLJ6VYSG.js"; import "./chunk-6WNCTW75.js"; import "./chunk-QLJVAXYD.js"; import "./chunk-CLN3QXW2.js"; import "./chunk-BZXRHH4X.js"; import "./chunk-QIUEWTOP.js"; import "./chunk-J7FYPWA5.js"; import "./chunk-EIBOABXT.js"; import "./chunk-N24CESYN.js"; import "./chunk-VIBS7Y3M.js"; import "./chunk-2MTJELC7.js"; import "./chunk-4PEUWIWY.js"; import "./chunk-UY2SRO54.js"; import "./chunk-ZNEQLT5Q.js"; import "./chunk-PK5NRJAC.js"; import "./chunk-7VZHRFCE.js"; import "./chunk-AG4NO6K6.js"; import "./chunk-NPJBMLFY.js"; import "./chunk-YPFLLHK6.js"; import "./chunk-7EY5MWB2.js"; import "./chunk-U7TO6S3N.js"; import "./chunk-LO5SQBMX.js"; import "./chunk-EIVAOYE5.js"; import "./chunk-67BSOYLQ.js"; import "./chunk-B7XHB4Z2.js"; import "./chunk-O6UZ65WN.js"; import "./chunk-GINVHONX.js"; import "./chunk-O6LGEXJ4.js"; import "./chunk-ME5GAE4N.js"; import "./chunk-I5DK3TWY.js"; import "./chunk-NJUWOGZE.js"; import "./chunk-TFBEDS4S.js"; import "./chunk-GOA7IGSB.js"; import "./chunk-QHKZ43P6.js"; import "./chunk-3GSJ2FQJ.js"; import "./chunk-P7ZDTV2E.js"; import "./chunk-SNQ54XRM.js"; import "./chunk-BBNNHC5G.js"; import "./chunk-Y3WKETHV.js"; import "./chunk-SPELR2RL.js"; import { __toESM } from "./chunk-SEVZ5PBP.js"; // node_modules/thirdweb/dist/esm/react/web/wallets/in-app/InAppWalletSelectionUI.js var import_jsx_runtime = __toESM(require_jsx_runtime(), 1); function InAppWalletSelectionUI(props) { const { screen } = useScreenContext(); const setData = useSetSelectionData(); const locale = useInAppWalletLocale(props.connectLocale.id); if (props.size === "wide" || screen !== reservedScreens.main && props.size === "compact") { return (0, import_jsx_runtime.jsx)(WalletEntryButton, { walletId: props.wallet.id, selectWallet: () => { setData({}); props.select(); }, client: props.client, connectLocale: props.connectLocale, recommendedWallets: props.recommendedWallets, isActive: screen === props.wallet, badge: void 0 }); } if (!locale) { return (0, import_jsx_runtime.jsx)(LoadingScreen, { height: "195px" }); } return (0, import_jsx_runtime.jsx)(ConnectWalletSocialOptions, { disabled: props.disabled, locale, wallet: props.wallet, done: props.done, select: props.select, goBack: props.goBack, chain: props.chain, client: props.client, size: props.size }); } var InAppWalletSelectionUI_default = InAppWalletSelectionUI; export { InAppWalletSelectionUI_default as default }; //# sourceMappingURL=InAppWalletSelectionUI-QJ7CQPJG.js.map ================================================ FILE: 17-Crowd-Funding-Dapp/Frontend/.vite/deps_temp_6cf5ba4c/ModelViewer-GZZWO7FG.js ================================================ import { ReactiveElement, html, property, render } from "./chunk-6LAJV43E.js"; import { require_jsx_runtime } from "./chunk-U3QNWT4A.js"; import { require_react } from "./chunk-2MTJELC7.js"; import { __toESM } from "./chunk-SEVZ5PBP.js"; // node_modules/thirdweb/dist/esm/react/web/ui/MediaRenderer/ModelViewer.js var import_jsx_runtime = __toESM(require_jsx_runtime(), 1); // node_modules/three/build/three.module.js var REVISION = "146"; var CullFaceNone = 0; var CullFaceBack = 1; var CullFaceFront = 2; var PCFShadowMap = 1; var PCFSoftShadowMap = 2; var VSMShadowMap = 3; var FrontSide = 0; var BackSide = 1; var DoubleSide = 2; var NoBlending = 0; var NormalBlending = 1; var AdditiveBlending = 2; var SubtractiveBlending = 3; var MultiplyBlending = 4; var CustomBlending = 5; var AddEquation = 100; var SubtractEquation = 101; var ReverseSubtractEquation = 102; var MinEquation = 103; var MaxEquation = 104; var ZeroFactor = 200; var OneFactor = 201; var SrcColorFactor = 202; var OneMinusSrcColorFactor = 203; var SrcAlphaFactor = 204; var OneMinusSrcAlphaFactor = 205; var DstAlphaFactor = 206; var OneMinusDstAlphaFactor = 207; var DstColorFactor = 208; var OneMinusDstColorFactor = 209; var SrcAlphaSaturateFactor = 210; var NeverDepth = 0; var AlwaysDepth = 1; var LessDepth = 2; var LessEqualDepth = 3; var EqualDepth = 4; var GreaterEqualDepth = 5; var GreaterDepth = 6; var NotEqualDepth = 7; var MultiplyOperation = 0; var MixOperation = 1; var AddOperation = 2; var NoToneMapping = 0; var LinearToneMapping = 1; var ReinhardToneMapping = 2; var CineonToneMapping = 3; var ACESFilmicToneMapping = 4; var CustomToneMapping = 5; var UVMapping = 300; var CubeReflectionMapping = 301; var CubeRefractionMapping = 302; var EquirectangularReflectionMapping = 303; var EquirectangularRefractionMapping = 304; var CubeUVReflectionMapping = 306; var RepeatWrapping = 1e3; var ClampToEdgeWrapping = 1001; var MirroredRepeatWrapping = 1002; var NearestFilter = 1003; var NearestMipmapNearestFilter = 1004; var NearestMipmapLinearFilter = 1005; var LinearFilter = 1006; var LinearMipmapNearestFilter = 1007; var LinearMipmapLinearFilter = 1008; var UnsignedByteType = 1009; var ByteType = 1010; var ShortType = 1011; var UnsignedShortType = 1012; var IntType = 1013; var UnsignedIntType = 1014; var FloatType = 1015; var HalfFloatType = 1016; var UnsignedShort4444Type = 1017; var UnsignedShort5551Type = 1018; var UnsignedInt248Type = 1020; var AlphaFormat = 1021; var RGBFormat = 1022; var RGBAFormat = 1023; var LuminanceFormat = 1024; var LuminanceAlphaFormat = 1025; var DepthFormat = 1026; var DepthStencilFormat = 1027; var RedFormat = 1028; var RedIntegerFormat = 1029; var RGFormat = 1030; var RGIntegerFormat = 1031; var RGBAIntegerFormat = 1033; var RGB_S3TC_DXT1_Format = 33776; var RGBA_S3TC_DXT1_Format = 33777; var RGBA_S3TC_DXT3_Format = 33778; var RGBA_S3TC_DXT5_Format = 33779; var RGB_PVRTC_4BPPV1_Format = 35840; var RGB_PVRTC_2BPPV1_Format = 35841; var RGBA_PVRTC_4BPPV1_Format = 35842; var RGBA_PVRTC_2BPPV1_Format = 35843; var RGB_ETC1_Format = 36196; var RGB_ETC2_Format = 37492; var RGBA_ETC2_EAC_Format = 37496; var RGBA_ASTC_4x4_Format = 37808; var RGBA_ASTC_5x4_Format = 37809; var RGBA_ASTC_5x5_Format = 37810; var RGBA_ASTC_6x5_Format = 37811; var RGBA_ASTC_6x6_Format = 37812; var RGBA_ASTC_8x5_Format = 37813; var RGBA_ASTC_8x6_Format = 37814; var RGBA_ASTC_8x8_Format = 37815; var RGBA_ASTC_10x5_Format = 37816; var RGBA_ASTC_10x6_Format = 37817; var RGBA_ASTC_10x8_Format = 37818; var RGBA_ASTC_10x10_Format = 37819; var RGBA_ASTC_12x10_Format = 37820; var RGBA_ASTC_12x12_Format = 37821; var RGBA_BPTC_Format = 36492; var LoopOnce = 2200; var LoopRepeat = 2201; var LoopPingPong = 2202; var InterpolateDiscrete = 2300; var InterpolateLinear = 2301; var InterpolateSmooth = 2302; var ZeroCurvatureEnding = 2400; var ZeroSlopeEnding = 2401; var WrapAroundEnding = 2402; var NormalAnimationBlendMode = 2500; var AdditiveAnimationBlendMode = 2501; var TriangleStripDrawMode = 1; var TriangleFanDrawMode = 2; var LinearEncoding = 3e3; var sRGBEncoding = 3001; var BasicDepthPacking = 3200; var RGBADepthPacking = 3201; var TangentSpaceNormalMap = 0; var ObjectSpaceNormalMap = 1; var SRGBColorSpace = "srgb"; var LinearSRGBColorSpace = "srgb-linear"; var KeepStencilOp = 7680; var AlwaysStencilFunc = 519; var StaticDrawUsage = 35044; var GLSL3 = "300 es"; var _SRGBAFormat = 1035; var EventDispatcher = class { addEventListener(type, listener) { if (this._listeners === void 0) this._listeners = {}; const listeners = this._listeners; if (listeners[type] === void 0) { listeners[type] = []; } if (listeners[type].indexOf(listener) === -1) { listeners[type].push(listener); } } hasEventListener(type, listener) { if (this._listeners === void 0) return false; const listeners = this._listeners; return listeners[type] !== void 0 && listeners[type].indexOf(listener) !== -1; } removeEventListener(type, listener) { if (this._listeners === void 0) return; const listeners = this._listeners; const listenerArray = listeners[type]; if (listenerArray !== void 0) { const index = listenerArray.indexOf(listener); if (index !== -1) { listenerArray.splice(index, 1); } } } dispatchEvent(event) { if (this._listeners === void 0) return; const listeners = this._listeners; const listenerArray = listeners[event.type]; if (listenerArray !== void 0) { event.target = this; const array = listenerArray.slice(0); for (let i = 0, l = array.length; i < l; i++) { array[i].call(this, event); } event.target = null; } } }; var _lut = ["00", "01", "02", "03", "04", "05", "06", "07", "08", "09", "0a", "0b", "0c", "0d", "0e", "0f", "10", "11", "12", "13", "14", "15", "16", "17", "18", "19", "1a", "1b", "1c", "1d", "1e", "1f", "20", "21", "22", "23", "24", "25", "26", "27", "28", "29", "2a", "2b", "2c", "2d", "2e", "2f", "30", "31", "32", "33", "34", "35", "36", "37", "38", "39", "3a", "3b", "3c", "3d", "3e", "3f", "40", "41", "42", "43", "44", "45", "46", "47", "48", "49", "4a", "4b", "4c", "4d", "4e", "4f", "50", "51", "52", "53", "54", "55", "56", "57", "58", "59", "5a", "5b", "5c", "5d", "5e", "5f", "60", "61", "62", "63", "64", "65", "66", "67", "68", "69", "6a", "6b", "6c", "6d", "6e", "6f", "70", "71", "72", "73", "74", "75", "76", "77", "78", "79", "7a", "7b", "7c", "7d", "7e", "7f", "80", "81", "82", "83", "84", "85", "86", "87", "88", "89", "8a", "8b", "8c", "8d", "8e", "8f", "90", "91", "92", "93", "94", "95", "96", "97", "98", "99", "9a", "9b", "9c", "9d", "9e", "9f", "a0", "a1", "a2", "a3", "a4", "a5", "a6", "a7", "a8", "a9", "aa", "ab", "ac", "ad", "ae", "af", "b0", "b1", "b2", "b3", "b4", "b5", "b6", "b7", "b8", "b9", "ba", "bb", "bc", "bd", "be", "bf", "c0", "c1", "c2", "c3", "c4", "c5", "c6", "c7", "c8", "c9", "ca", "cb", "cc", "cd", "ce", "cf", "d0", "d1", "d2", "d3", "d4", "d5", "d6", "d7", "d8", "d9", "da", "db", "dc", "dd", "de", "df", "e0", "e1", "e2", "e3", "e4", "e5", "e6", "e7", "e8", "e9", "ea", "eb", "ec", "ed", "ee", "ef", "f0", "f1", "f2", "f3", "f4", "f5", "f6", "f7", "f8", "f9", "fa", "fb", "fc", "fd", "fe", "ff"]; var _seed = 1234567; var DEG2RAD = Math.PI / 180; var RAD2DEG = 180 / Math.PI; function generateUUID() { const d0 = Math.random() * 4294967295 | 0; const d1 = Math.random() * 4294967295 | 0; const d2 = Math.random() * 4294967295 | 0; const d3 = Math.random() * 4294967295 | 0; const uuid = _lut[d0 & 255] + _lut[d0 >> 8 & 255] + _lut[d0 >> 16 & 255] + _lut[d0 >> 24 & 255] + "-" + _lut[d1 & 255] + _lut[d1 >> 8 & 255] + "-" + _lut[d1 >> 16 & 15 | 64] + _lut[d1 >> 24 & 255] + "-" + _lut[d2 & 63 | 128] + _lut[d2 >> 8 & 255] + "-" + _lut[d2 >> 16 & 255] + _lut[d2 >> 24 & 255] + _lut[d3 & 255] + _lut[d3 >> 8 & 255] + _lut[d3 >> 16 & 255] + _lut[d3 >> 24 & 255]; return uuid.toLowerCase(); } function clamp(value, min, max2) { return Math.max(min, Math.min(max2, value)); } function euclideanModulo(n2, m) { return (n2 % m + m) % m; } function mapLinear(x2, a1, a2, b1, b22) { return b1 + (x2 - a1) * (b22 - b1) / (a2 - a1); } function inverseLerp(x2, y, value) { if (x2 !== y) { return (value - x2) / (y - x2); } else { return 0; } } function lerp(x2, y, t2) { return (1 - t2) * x2 + t2 * y; } function damp(x2, y, lambda, dt2) { return lerp(x2, y, 1 - Math.exp(-lambda * dt2)); } function pingpong(x2, length = 1) { return length - Math.abs(euclideanModulo(x2, length * 2) - length); } function smoothstep(x2, min, max2) { if (x2 <= min) return 0; if (x2 >= max2) return 1; x2 = (x2 - min) / (max2 - min); return x2 * x2 * (3 - 2 * x2); } function smootherstep(x2, min, max2) { if (x2 <= min) return 0; if (x2 >= max2) return 1; x2 = (x2 - min) / (max2 - min); return x2 * x2 * x2 * (x2 * (x2 * 6 - 15) + 10); } function randInt(low, high) { return low + Math.floor(Math.random() * (high - low + 1)); } function randFloat(low, high) { return low + Math.random() * (high - low); } function randFloatSpread(range) { return range * (0.5 - Math.random()); } function seededRandom(s) { if (s !== void 0) _seed = s; let t2 = _seed += 1831565813; t2 = Math.imul(t2 ^ t2 >>> 15, t2 | 1); t2 ^= t2 + Math.imul(t2 ^ t2 >>> 7, t2 | 61); return ((t2 ^ t2 >>> 14) >>> 0) / 4294967296; } function degToRad(degrees) { return degrees * DEG2RAD; } function radToDeg(radians) { return radians * RAD2DEG; } function isPowerOfTwo(value) { return (value & value - 1) === 0 && value !== 0; } function ceilPowerOfTwo(value) { return Math.pow(2, Math.ceil(Math.log(value) / Math.LN2)); } function floorPowerOfTwo(value) { return Math.pow(2, Math.floor(Math.log(value) / Math.LN2)); } function setQuaternionFromProperEuler(q, a, b, c, order) { const cos = Math.cos; const sin = Math.sin; const c2 = cos(b / 2); const s2 = sin(b / 2); const c13 = cos((a + c) / 2); const s13 = sin((a + c) / 2); const c1_3 = cos((a - c) / 2); const s1_3 = sin((a - c) / 2); const c3_1 = cos((c - a) / 2); const s3_1 = sin((c - a) / 2); switch (order) { case "XYX": q.set(c2 * s13, s2 * c1_3, s2 * s1_3, c2 * c13); break; case "YZY": q.set(s2 * s1_3, c2 * s13, s2 * c1_3, c2 * c13); break; case "ZXZ": q.set(s2 * c1_3, s2 * s1_3, c2 * s13, c2 * c13); break; case "XZX": q.set(c2 * s13, s2 * s3_1, s2 * c3_1, c2 * c13); break; case "YXY": q.set(s2 * c3_1, c2 * s13, s2 * s3_1, c2 * c13); break; case "ZYZ": q.set(s2 * s3_1, s2 * c3_1, c2 * s13, c2 * c13); break; default: console.warn("THREE.MathUtils: .setQuaternionFromProperEuler() encountered an unknown order: " + order); } } function denormalize(value, array) { switch (array.constructor) { case Float32Array: return value; case Uint16Array: return value / 65535; case Uint8Array: return value / 255; case Int16Array: return Math.max(value / 32767, -1); case Int8Array: return Math.max(value / 127, -1); default: throw new Error("Invalid component type."); } } function normalize(value, array) { switch (array.constructor) { case Float32Array: return value; case Uint16Array: return Math.round(value * 65535); case Uint8Array: return Math.round(value * 255); case Int16Array: return Math.round(value * 32767); case Int8Array: return Math.round(value * 127); default: throw new Error("Invalid component type."); } } var MathUtils = Object.freeze({ __proto__: null, DEG2RAD, RAD2DEG, generateUUID, clamp, euclideanModulo, mapLinear, inverseLerp, lerp, damp, pingpong, smoothstep, smootherstep, randInt, randFloat, randFloatSpread, seededRandom, degToRad, radToDeg, isPowerOfTwo, ceilPowerOfTwo, floorPowerOfTwo, setQuaternionFromProperEuler, normalize, denormalize }); var Vector2 = class _Vector2 { constructor(x2 = 0, y = 0) { _Vector2.prototype.isVector2 = true; this.x = x2; this.y = y; } get width() { return this.x; } set width(value) { this.x = value; } get height() { return this.y; } set height(value) { this.y = value; } set(x2, y) { this.x = x2; this.y = y; return this; } setScalar(scalar) { this.x = scalar; this.y = scalar; return this; } setX(x2) { this.x = x2; return this; } setY(y) { this.y = y; return this; } setComponent(index, value) { switch (index) { case 0: this.x = value; break; case 1: this.y = value; break; default: throw new Error("index is out of range: " + index); } return this; } getComponent(index) { switch (index) { case 0: return this.x; case 1: return this.y; default: throw new Error("index is out of range: " + index); } } clone() { return new this.constructor(this.x, this.y); } copy(v) { this.x = v.x; this.y = v.y; return this; } add(v) { this.x += v.x; this.y += v.y; return this; } addScalar(s) { this.x += s; this.y += s; return this; } addVectors(a, b) { this.x = a.x + b.x; this.y = a.y + b.y; return this; } addScaledVector(v, s) { this.x += v.x * s; this.y += v.y * s; return this; } sub(v) { this.x -= v.x; this.y -= v.y; return this; } subScalar(s) { this.x -= s; this.y -= s; return this; } subVectors(a, b) { this.x = a.x - b.x; this.y = a.y - b.y; return this; } multiply(v) { this.x *= v.x; this.y *= v.y; return this; } multiplyScalar(scalar) { this.x *= scalar; this.y *= scalar; return this; } divide(v) { this.x /= v.x; this.y /= v.y; return this; } divideScalar(scalar) { return this.multiplyScalar(1 / scalar); } applyMatrix3(m) { const x2 = this.x, y = this.y; const e = m.elements; this.x = e[0] * x2 + e[3] * y + e[6]; this.y = e[1] * x2 + e[4] * y + e[7]; return this; } min(v) { this.x = Math.min(this.x, v.x); this.y = Math.min(this.y, v.y); return this; } max(v) { this.x = Math.max(this.x, v.x); this.y = Math.max(this.y, v.y); return this; } clamp(min, max2) { this.x = Math.max(min.x, Math.min(max2.x, this.x)); this.y = Math.max(min.y, Math.min(max2.y, this.y)); return this; } clampScalar(minVal, maxVal) { this.x = Math.max(minVal, Math.min(maxVal, this.x)); this.y = Math.max(minVal, Math.min(maxVal, this.y)); return this; } clampLength(min, max2) { const length = this.length(); return this.divideScalar(length || 1).multiplyScalar(Math.max(min, Math.min(max2, length))); } floor() { this.x = Math.floor(this.x); this.y = Math.floor(this.y); return this; } ceil() { this.x = Math.ceil(this.x); this.y = Math.ceil(this.y); return this; } round() { this.x = Math.round(this.x); this.y = Math.round(this.y); return this; } roundToZero() { this.x = this.x < 0 ? Math.ceil(this.x) : Math.floor(this.x); this.y = this.y < 0 ? Math.ceil(this.y) : Math.floor(this.y); return this; } negate() { this.x = -this.x; this.y = -this.y; return this; } dot(v) { return this.x * v.x + this.y * v.y; } cross(v) { return this.x * v.y - this.y * v.x; } lengthSq() { return this.x * this.x + this.y * this.y; } length() { return Math.sqrt(this.x * this.x + this.y * this.y); } manhattanLength() { return Math.abs(this.x) + Math.abs(this.y); } normalize() { return this.divideScalar(this.length() || 1); } angle() { const angle = Math.atan2(-this.y, -this.x) + Math.PI; return angle; } distanceTo(v) { return Math.sqrt(this.distanceToSquared(v)); } distanceToSquared(v) { const dx = this.x - v.x, dy = this.y - v.y; return dx * dx + dy * dy; } manhattanDistanceTo(v) { return Math.abs(this.x - v.x) + Math.abs(this.y - v.y); } setLength(length) { return this.normalize().multiplyScalar(length); } lerp(v, alpha) { this.x += (v.x - this.x) * alpha; this.y += (v.y - this.y) * alpha; return this; } lerpVectors(v1, v2, alpha) { this.x = v1.x + (v2.x - v1.x) * alpha; this.y = v1.y + (v2.y - v1.y) * alpha; return this; } equals(v) { return v.x === this.x && v.y === this.y; } fromArray(array, offset = 0) { this.x = array[offset]; this.y = array[offset + 1]; return this; } toArray(array = [], offset = 0) { array[offset] = this.x; array[offset + 1] = this.y; return array; } fromBufferAttribute(attribute, index) { this.x = attribute.getX(index); this.y = attribute.getY(index); return this; } rotateAround(center, angle) { const c = Math.cos(angle), s = Math.sin(angle); const x2 = this.x - center.x; const y = this.y - center.y; this.x = x2 * c - y * s + center.x; this.y = x2 * s + y * c + center.y; return this; } random() { this.x = Math.random(); this.y = Math.random(); return this; } *[Symbol.iterator]() { yield this.x; yield this.y; } }; var Matrix3 = class _Matrix3 { constructor() { _Matrix3.prototype.isMatrix3 = true; this.elements = [ 1, 0, 0, 0, 1, 0, 0, 0, 1 ]; } set(n11, n12, n13, n21, n22, n23, n31, n32, n33) { const te2 = this.elements; te2[0] = n11; te2[1] = n21; te2[2] = n31; te2[3] = n12; te2[4] = n22; te2[5] = n32; te2[6] = n13; te2[7] = n23; te2[8] = n33; return this; } identity() { this.set( 1, 0, 0, 0, 1, 0, 0, 0, 1 ); return this; } copy(m) { const te2 = this.elements; const me = m.elements; te2[0] = me[0]; te2[1] = me[1]; te2[2] = me[2]; te2[3] = me[3]; te2[4] = me[4]; te2[5] = me[5]; te2[6] = me[6]; te2[7] = me[7]; te2[8] = me[8]; return this; } extractBasis(xAxis, yAxis, zAxis) { xAxis.setFromMatrix3Column(this, 0); yAxis.setFromMatrix3Column(this, 1); zAxis.setFromMatrix3Column(this, 2); return this; } setFromMatrix4(m) { const me = m.elements; this.set( me[0], me[4], me[8], me[1], me[5], me[9], me[2], me[6], me[10] ); return this; } multiply(m) { return this.multiplyMatrices(this, m); } premultiply(m) { return this.multiplyMatrices(m, this); } multiplyMatrices(a, b) { const ae = a.elements; const be = b.elements; const te2 = this.elements; const a11 = ae[0], a12 = ae[3], a13 = ae[6]; const a21 = ae[1], a22 = ae[4], a23 = ae[7]; const a31 = ae[2], a32 = ae[5], a33 = ae[8]; const b11 = be[0], b12 = be[3], b13 = be[6]; const b21 = be[1], b22 = be[4], b23 = be[7]; const b31 = be[2], b32 = be[5], b33 = be[8]; te2[0] = a11 * b11 + a12 * b21 + a13 * b31; te2[3] = a11 * b12 + a12 * b22 + a13 * b32; te2[6] = a11 * b13 + a12 * b23 + a13 * b33; te2[1] = a21 * b11 + a22 * b21 + a23 * b31; te2[4] = a21 * b12 + a22 * b22 + a23 * b32; te2[7] = a21 * b13 + a22 * b23 + a23 * b33; te2[2] = a31 * b11 + a32 * b21 + a33 * b31; te2[5] = a31 * b12 + a32 * b22 + a33 * b32; te2[8] = a31 * b13 + a32 * b23 + a33 * b33; return this; } multiplyScalar(s) { const te2 = this.elements; te2[0] *= s; te2[3] *= s; te2[6] *= s; te2[1] *= s; te2[4] *= s; te2[7] *= s; te2[2] *= s; te2[5] *= s; te2[8] *= s; return this; } determinant() { const te2 = this.elements; const a = te2[0], b = te2[1], c = te2[2], d = te2[3], e = te2[4], f = te2[5], g2 = te2[6], h = te2[7], i = te2[8]; return a * e * i - a * f * h - b * d * i + b * f * g2 + c * d * h - c * e * g2; } invert() { const te2 = this.elements, n11 = te2[0], n21 = te2[1], n31 = te2[2], n12 = te2[3], n22 = te2[4], n32 = te2[5], n13 = te2[6], n23 = te2[7], n33 = te2[8], t11 = n33 * n22 - n32 * n23, t12 = n32 * n13 - n33 * n12, t13 = n23 * n12 - n22 * n13, det = n11 * t11 + n21 * t12 + n31 * t13; if (det === 0) return this.set(0, 0, 0, 0, 0, 0, 0, 0, 0); const detInv = 1 / det; te2[0] = t11 * detInv; te2[1] = (n31 * n23 - n33 * n21) * detInv; te2[2] = (n32 * n21 - n31 * n22) * detInv; te2[3] = t12 * detInv; te2[4] = (n33 * n11 - n31 * n13) * detInv; te2[5] = (n31 * n12 - n32 * n11) * detInv; te2[6] = t13 * detInv; te2[7] = (n21 * n13 - n23 * n11) * detInv; te2[8] = (n22 * n11 - n21 * n12) * detInv; return this; } transpose() { let tmp2; const m = this.elements; tmp2 = m[1]; m[1] = m[3]; m[3] = tmp2; tmp2 = m[2]; m[2] = m[6]; m[6] = tmp2; tmp2 = m[5]; m[5] = m[7]; m[7] = tmp2; return this; } getNormalMatrix(matrix42) { return this.setFromMatrix4(matrix42).invert().transpose(); } transposeIntoArray(r) { const m = this.elements; r[0] = m[0]; r[1] = m[3]; r[2] = m[6]; r[3] = m[1]; r[4] = m[4]; r[5] = m[7]; r[6] = m[2]; r[7] = m[5]; r[8] = m[8]; return this; } setUvTransform(tx, ty, sx, sy, rotation, cx, cy) { const c = Math.cos(rotation); const s = Math.sin(rotation); this.set( sx * c, sx * s, -sx * (c * cx + s * cy) + cx + tx, -sy * s, sy * c, -sy * (-s * cx + c * cy) + cy + ty, 0, 0, 1 ); return this; } scale(sx, sy) { const te2 = this.elements; te2[0] *= sx; te2[3] *= sx; te2[6] *= sx; te2[1] *= sy; te2[4] *= sy; te2[7] *= sy; return this; } rotate(theta) { const c = Math.cos(theta); const s = Math.sin(theta); const te2 = this.elements; const a11 = te2[0], a12 = te2[3], a13 = te2[6]; const a21 = te2[1], a22 = te2[4], a23 = te2[7]; te2[0] = c * a11 + s * a21; te2[3] = c * a12 + s * a22; te2[6] = c * a13 + s * a23; te2[1] = -s * a11 + c * a21; te2[4] = -s * a12 + c * a22; te2[7] = -s * a13 + c * a23; return this; } translate(tx, ty) { const te2 = this.elements; te2[0] += tx * te2[2]; te2[3] += tx * te2[5]; te2[6] += tx * te2[8]; te2[1] += ty * te2[2]; te2[4] += ty * te2[5]; te2[7] += ty * te2[8]; return this; } equals(matrix) { const te2 = this.elements; const me = matrix.elements; for (let i = 0; i < 9; i++) { if (te2[i] !== me[i]) return false; } return true; } fromArray(array, offset = 0) { for (let i = 0; i < 9; i++) { this.elements[i] = array[i + offset]; } return this; } toArray(array = [], offset = 0) { const te2 = this.elements; array[offset] = te2[0]; array[offset + 1] = te2[1]; array[offset + 2] = te2[2]; array[offset + 3] = te2[3]; array[offset + 4] = te2[4]; array[offset + 5] = te2[5]; array[offset + 6] = te2[6]; array[offset + 7] = te2[7]; array[offset + 8] = te2[8]; return array; } clone() { return new this.constructor().fromArray(this.elements); } }; function arrayNeedsUint32(array) { for (let i = array.length - 1; i >= 0; --i) { if (array[i] >= 65535) return true; } return false; } function createElementNS(name) { return document.createElementNS("http://www.w3.org/1999/xhtml", name); } function SRGBToLinear(c) { return c < 0.04045 ? c * 0.0773993808 : Math.pow(c * 0.9478672986 + 0.0521327014, 2.4); } function LinearToSRGB(c) { return c < 31308e-7 ? c * 12.92 : 1.055 * Math.pow(c, 0.41666) - 0.055; } var FN = { [SRGBColorSpace]: { [LinearSRGBColorSpace]: SRGBToLinear }, [LinearSRGBColorSpace]: { [SRGBColorSpace]: LinearToSRGB } }; var ColorManagement = { legacyMode: true, get workingColorSpace() { return LinearSRGBColorSpace; }, set workingColorSpace(colorSpace) { console.warn("THREE.ColorManagement: .workingColorSpace is readonly."); }, convert: function(color, sourceColorSpace, targetColorSpace) { if (this.legacyMode || sourceColorSpace === targetColorSpace || !sourceColorSpace || !targetColorSpace) { return color; } if (FN[sourceColorSpace] && FN[sourceColorSpace][targetColorSpace] !== void 0) { const fn = FN[sourceColorSpace][targetColorSpace]; color.r = fn(color.r); color.g = fn(color.g); color.b = fn(color.b); return color; } throw new Error("Unsupported color space conversion."); }, fromWorkingColorSpace: function(color, targetColorSpace) { return this.convert(color, this.workingColorSpace, targetColorSpace); }, toWorkingColorSpace: function(color, sourceColorSpace) { return this.convert(color, sourceColorSpace, this.workingColorSpace); } }; var _colorKeywords = { "aliceblue": 15792383, "antiquewhite": 16444375, "aqua": 65535, "aquamarine": 8388564, "azure": 15794175, "beige": 16119260, "bisque": 16770244, "black": 0, "blanchedalmond": 16772045, "blue": 255, "blueviolet": 9055202, "brown": 10824234, "burlywood": 14596231, "cadetblue": 6266528, "chartreuse": 8388352, "chocolate": 13789470, "coral": 16744272, "cornflowerblue": 6591981, "cornsilk": 16775388, "crimson": 14423100, "cyan": 65535, "darkblue": 139, "darkcyan": 35723, "darkgoldenrod": 12092939, "darkgray": 11119017, "darkgreen": 25600, "darkgrey": 11119017, "darkkhaki": 12433259, "darkmagenta": 9109643, "darkolivegreen": 5597999, "darkorange": 16747520, "darkorchid": 10040012, "darkred": 9109504, "darksalmon": 15308410, "darkseagreen": 9419919, "darkslateblue": 4734347, "darkslategray": 3100495, "darkslategrey": 3100495, "darkturquoise": 52945, "darkviolet": 9699539, "deeppink": 16716947, "deepskyblue": 49151, "dimgray": 6908265, "dimgrey": 6908265, "dodgerblue": 2003199, "firebrick": 11674146, "floralwhite": 16775920, "forestgreen": 2263842, "fuchsia": 16711935, "gainsboro": 14474460, "ghostwhite": 16316671, "gold": 16766720, "goldenrod": 14329120, "gray": 8421504, "green": 32768, "greenyellow": 11403055, "grey": 8421504, "honeydew": 15794160, "hotpink": 16738740, "indianred": 13458524, "indigo": 4915330, "ivory": 16777200, "khaki": 15787660, "lavender": 15132410, "lavenderblush": 16773365, "lawngreen": 8190976, "lemonchiffon": 16775885, "lightblue": 11393254, "lightcoral": 15761536, "lightcyan": 14745599, "lightgoldenrodyellow": 16448210, "lightgray": 13882323, "lightgreen": 9498256, "lightgrey": 13882323, "lightpink": 16758465, "lightsalmon": 16752762, "lightseagreen": 2142890, "lightskyblue": 8900346, "lightslategray": 7833753, "lightslategrey": 7833753, "lightsteelblue": 11584734, "lightyellow": 16777184, "lime": 65280, "limegreen": 3329330, "linen": 16445670, "magenta": 16711935, "maroon": 8388608, "mediumaquamarine": 6737322, "mediumblue": 205, "mediumorchid": 12211667, "mediumpurple": 9662683, "mediumseagreen": 3978097, "mediumslateblue": 8087790, "mediumspringgreen": 64154, "mediumturquoise": 4772300, "mediumvioletred": 13047173, "midnightblue": 1644912, "mintcream": 16121850, "mistyrose": 16770273, "moccasin": 16770229, "navajowhite": 16768685, "navy": 128, "oldlace": 16643558, "olive": 8421376, "olivedrab": 7048739, "orange": 16753920, "orangered": 16729344, "orchid": 14315734, "palegoldenrod": 15657130, "palegreen": 10025880, "paleturquoise": 11529966, "palevioletred": 14381203, "papayawhip": 16773077, "peachpuff": 16767673, "peru": 13468991, "pink": 16761035, "plum": 14524637, "powderblue": 11591910, "purple": 8388736, "rebeccapurple": 6697881, "red": 16711680, "rosybrown": 12357519, "royalblue": 4286945, "saddlebrown": 9127187, "salmon": 16416882, "sandybrown": 16032864, "seagreen": 3050327, "seashell": 16774638, "sienna": 10506797, "silver": 12632256, "skyblue": 8900331, "slateblue": 6970061, "slategray": 7372944, "slategrey": 7372944, "snow": 16775930, "springgreen": 65407, "steelblue": 4620980, "tan": 13808780, "teal": 32896, "thistle": 14204888, "tomato": 16737095, "turquoise": 4251856, "violet": 15631086, "wheat": 16113331, "white": 16777215, "whitesmoke": 16119285, "yellow": 16776960, "yellowgreen": 10145074 }; var _rgb = { r: 0, g: 0, b: 0 }; var _hslA = { h: 0, s: 0, l: 0 }; var _hslB = { h: 0, s: 0, l: 0 }; function hue2rgb(p2, q, t2) { if (t2 < 0) t2 += 1; if (t2 > 1) t2 -= 1; if (t2 < 1 / 6) return p2 + (q - p2) * 6 * t2; if (t2 < 1 / 2) return q; if (t2 < 2 / 3) return p2 + (q - p2) * 6 * (2 / 3 - t2); return p2; } function toComponents(source, target2) { target2.r = source.r; target2.g = source.g; target2.b = source.b; return target2; } var Color = class { constructor(r, g2, b) { this.isColor = true; this.r = 1; this.g = 1; this.b = 1; if (g2 === void 0 && b === void 0) { return this.set(r); } return this.setRGB(r, g2, b); } set(value) { if (value && value.isColor) { this.copy(value); } else if (typeof value === "number") { this.setHex(value); } else if (typeof value === "string") { this.setStyle(value); } return this; } setScalar(scalar) { this.r = scalar; this.g = scalar; this.b = scalar; return this; } setHex(hex, colorSpace = SRGBColorSpace) { hex = Math.floor(hex); this.r = (hex >> 16 & 255) / 255; this.g = (hex >> 8 & 255) / 255; this.b = (hex & 255) / 255; ColorManagement.toWorkingColorSpace(this, colorSpace); return this; } setRGB(r, g2, b, colorSpace = LinearSRGBColorSpace) { this.r = r; this.g = g2; this.b = b; ColorManagement.toWorkingColorSpace(this, colorSpace); return this; } setHSL(h, s, l, colorSpace = LinearSRGBColorSpace) { h = euclideanModulo(h, 1); s = clamp(s, 0, 1); l = clamp(l, 0, 1); if (s === 0) { this.r = this.g = this.b = l; } else { const p2 = l <= 0.5 ? l * (1 + s) : l + s - l * s; const q = 2 * l - p2; this.r = hue2rgb(q, p2, h + 1 / 3); this.g = hue2rgb(q, p2, h); this.b = hue2rgb(q, p2, h - 1 / 3); } ColorManagement.toWorkingColorSpace(this, colorSpace); return this; } setStyle(style2, colorSpace = SRGBColorSpace) { function handleAlpha(string) { if (string === void 0) return; if (parseFloat(string) < 1) { console.warn("THREE.Color: Alpha component of " + style2 + " will be ignored."); } } let m; if (m = /^((?:rgb|hsl)a?)\(([^\)]*)\)/.exec(style2)) { let color; const name = m[1]; const components = m[2]; switch (name) { case "rgb": case "rgba": if (color = /^\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec(components)) { this.r = Math.min(255, parseInt(color[1], 10)) / 255; this.g = Math.min(255, parseInt(color[2], 10)) / 255; this.b = Math.min(255, parseInt(color[3], 10)) / 255; ColorManagement.toWorkingColorSpace(this, colorSpace); handleAlpha(color[4]); return this; } if (color = /^\s*(\d+)\%\s*,\s*(\d+)\%\s*,\s*(\d+)\%\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec(components)) { this.r = Math.min(100, parseInt(color[1], 10)) / 100; this.g = Math.min(100, parseInt(color[2], 10)) / 100; this.b = Math.min(100, parseInt(color[3], 10)) / 100; ColorManagement.toWorkingColorSpace(this, colorSpace); handleAlpha(color[4]); return this; } break; case "hsl": case "hsla": if (color = /^\s*(\d*\.?\d+)\s*,\s*(\d*\.?\d+)\%\s*,\s*(\d*\.?\d+)\%\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec(components)) { const h = parseFloat(color[1]) / 360; const s = parseFloat(color[2]) / 100; const l = parseFloat(color[3]) / 100; handleAlpha(color[4]); return this.setHSL(h, s, l, colorSpace); } break; } } else if (m = /^\#([A-Fa-f\d]+)$/.exec(style2)) { const hex = m[1]; const size = hex.length; if (size === 3) { this.r = parseInt(hex.charAt(0) + hex.charAt(0), 16) / 255; this.g = parseInt(hex.charAt(1) + hex.charAt(1), 16) / 255; this.b = parseInt(hex.charAt(2) + hex.charAt(2), 16) / 255; ColorManagement.toWorkingColorSpace(this, colorSpace); return this; } else if (size === 6) { this.r = parseInt(hex.charAt(0) + hex.charAt(1), 16) / 255; this.g = parseInt(hex.charAt(2) + hex.charAt(3), 16) / 255; this.b = parseInt(hex.charAt(4) + hex.charAt(5), 16) / 255; ColorManagement.toWorkingColorSpace(this, colorSpace); return this; } } if (style2 && style2.length > 0) { return this.setColorName(style2, colorSpace); } return this; } setColorName(style2, colorSpace = SRGBColorSpace) { const hex = _colorKeywords[style2.toLowerCase()]; if (hex !== void 0) { this.setHex(hex, colorSpace); } else { console.warn("THREE.Color: Unknown color " + style2); } return this; } clone() { return new this.constructor(this.r, this.g, this.b); } copy(color) { this.r = color.r; this.g = color.g; this.b = color.b; return this; } copySRGBToLinear(color) { this.r = SRGBToLinear(color.r); this.g = SRGBToLinear(color.g); this.b = SRGBToLinear(color.b); return this; } copyLinearToSRGB(color) { this.r = LinearToSRGB(color.r); this.g = LinearToSRGB(color.g); this.b = LinearToSRGB(color.b); return this; } convertSRGBToLinear() { this.copySRGBToLinear(this); return this; } convertLinearToSRGB() { this.copyLinearToSRGB(this); return this; } getHex(colorSpace = SRGBColorSpace) { ColorManagement.fromWorkingColorSpace(toComponents(this, _rgb), colorSpace); return clamp(_rgb.r * 255, 0, 255) << 16 ^ clamp(_rgb.g * 255, 0, 255) << 8 ^ clamp(_rgb.b * 255, 0, 255) << 0; } getHexString(colorSpace = SRGBColorSpace) { return ("000000" + this.getHex(colorSpace).toString(16)).slice(-6); } getHSL(target2, colorSpace = LinearSRGBColorSpace) { ColorManagement.fromWorkingColorSpace(toComponents(this, _rgb), colorSpace); const r = _rgb.r, g2 = _rgb.g, b = _rgb.b; const max2 = Math.max(r, g2, b); const min = Math.min(r, g2, b); let hue, saturation; const lightness = (min + max2) / 2; if (min === max2) { hue = 0; saturation = 0; } else { const delta = max2 - min; saturation = lightness <= 0.5 ? delta / (max2 + min) : delta / (2 - max2 - min); switch (max2) { case r: hue = (g2 - b) / delta + (g2 < b ? 6 : 0); break; case g2: hue = (b - r) / delta + 2; break; case b: hue = (r - g2) / delta + 4; break; } hue /= 6; } target2.h = hue; target2.s = saturation; target2.l = lightness; return target2; } getRGB(target2, colorSpace = LinearSRGBColorSpace) { ColorManagement.fromWorkingColorSpace(toComponents(this, _rgb), colorSpace); target2.r = _rgb.r; target2.g = _rgb.g; target2.b = _rgb.b; return target2; } getStyle(colorSpace = SRGBColorSpace) { ColorManagement.fromWorkingColorSpace(toComponents(this, _rgb), colorSpace); if (colorSpace !== SRGBColorSpace) { return `color(${colorSpace} ${_rgb.r} ${_rgb.g} ${_rgb.b})`; } return `rgb(${_rgb.r * 255 | 0},${_rgb.g * 255 | 0},${_rgb.b * 255 | 0})`; } offsetHSL(h, s, l) { this.getHSL(_hslA); _hslA.h += h; _hslA.s += s; _hslA.l += l; this.setHSL(_hslA.h, _hslA.s, _hslA.l); return this; } add(color) { this.r += color.r; this.g += color.g; this.b += color.b; return this; } addColors(color1, color2) { this.r = color1.r + color2.r; this.g = color1.g + color2.g; this.b = color1.b + color2.b; return this; } addScalar(s) { this.r += s; this.g += s; this.b += s; return this; } sub(color) { this.r = Math.max(0, this.r - color.r); this.g = Math.max(0, this.g - color.g); this.b = Math.max(0, this.b - color.b); return this; } multiply(color) { this.r *= color.r; this.g *= color.g; this.b *= color.b; return this; } multiplyScalar(s) { this.r *= s; this.g *= s; this.b *= s; return this; } lerp(color, alpha) { this.r += (color.r - this.r) * alpha; this.g += (color.g - this.g) * alpha; this.b += (color.b - this.b) * alpha; return this; } lerpColors(color1, color2, alpha) { this.r = color1.r + (color2.r - color1.r) * alpha; this.g = color1.g + (color2.g - color1.g) * alpha; this.b = color1.b + (color2.b - color1.b) * alpha; return this; } lerpHSL(color, alpha) { this.getHSL(_hslA); color.getHSL(_hslB); const h = lerp(_hslA.h, _hslB.h, alpha); const s = lerp(_hslA.s, _hslB.s, alpha); const l = lerp(_hslA.l, _hslB.l, alpha); this.setHSL(h, s, l); return this; } equals(c) { return c.r === this.r && c.g === this.g && c.b === this.b; } fromArray(array, offset = 0) { this.r = array[offset]; this.g = array[offset + 1]; this.b = array[offset + 2]; return this; } toArray(array = [], offset = 0) { array[offset] = this.r; array[offset + 1] = this.g; array[offset + 2] = this.b; return array; } fromBufferAttribute(attribute, index) { this.r = attribute.getX(index); this.g = attribute.getY(index); this.b = attribute.getZ(index); return this; } toJSON() { return this.getHex(); } *[Symbol.iterator]() { yield this.r; yield this.g; yield this.b; } }; Color.NAMES = _colorKeywords; var _canvas; var ImageUtils = class { static getDataURL(image) { if (/^data:/i.test(image.src)) { return image.src; } if (typeof HTMLCanvasElement == "undefined") { return image.src; } let canvas; if (image instanceof HTMLCanvasElement) { canvas = image; } else { if (_canvas === void 0) _canvas = createElementNS("canvas"); _canvas.width = image.width; _canvas.height = image.height; const context = _canvas.getContext("2d"); if (image instanceof ImageData) { context.putImageData(image, 0, 0); } else { context.drawImage(image, 0, 0, image.width, image.height); } canvas = _canvas; } if (canvas.width > 2048 || canvas.height > 2048) { console.warn("THREE.ImageUtils.getDataURL: Image converted to jpg for performance reasons", image); return canvas.toDataURL("image/jpeg", 0.6); } else { return canvas.toDataURL("image/png"); } } static sRGBToLinear(image) { if (typeof HTMLImageElement !== "undefined" && image instanceof HTMLImageElement || typeof HTMLCanvasElement !== "undefined" && image instanceof HTMLCanvasElement || typeof ImageBitmap !== "undefined" && image instanceof ImageBitmap) { const canvas = createElementNS("canvas"); canvas.width = image.width; canvas.height = image.height; const context = canvas.getContext("2d"); context.drawImage(image, 0, 0, image.width, image.height); const imageData = context.getImageData(0, 0, image.width, image.height); const data = imageData.data; for (let i = 0; i < data.length; i++) { data[i] = SRGBToLinear(data[i] / 255) * 255; } context.putImageData(imageData, 0, 0); return canvas; } else if (image.data) { const data = image.data.slice(0); for (let i = 0; i < data.length; i++) { if (data instanceof Uint8Array || data instanceof Uint8ClampedArray) { data[i] = Math.floor(SRGBToLinear(data[i] / 255) * 255); } else { data[i] = SRGBToLinear(data[i]); } } return { data, width: image.width, height: image.height }; } else { console.warn("THREE.ImageUtils.sRGBToLinear(): Unsupported image type. No color space conversion applied."); return image; } } }; var Source = class { constructor(data = null) { this.isSource = true; this.uuid = generateUUID(); this.data = data; this.version = 0; } set needsUpdate(value) { if (value === true) this.version++; } toJSON(meta) { const isRootObject = meta === void 0 || typeof meta === "string"; if (!isRootObject && meta.images[this.uuid] !== void 0) { return meta.images[this.uuid]; } const output = { uuid: this.uuid, url: "" }; const data = this.data; if (data !== null) { let url; if (Array.isArray(data)) { url = []; for (let i = 0, l = data.length; i < l; i++) { if (data[i].isDataTexture) { url.push(serializeImage(data[i].image)); } else { url.push(serializeImage(data[i])); } } } else { url = serializeImage(data); } output.url = url; } if (!isRootObject) { meta.images[this.uuid] = output; } return output; } }; function serializeImage(image) { if (typeof HTMLImageElement !== "undefined" && image instanceof HTMLImageElement || typeof HTMLCanvasElement !== "undefined" && image instanceof HTMLCanvasElement || typeof ImageBitmap !== "undefined" && image instanceof ImageBitmap) { return ImageUtils.getDataURL(image); } else { if (image.data) { return { data: Array.from(image.data), width: image.width, height: image.height, type: image.data.constructor.name }; } else { console.warn("THREE.Texture: Unable to serialize Texture."); return {}; } } } var textureId = 0; var Texture = class _Texture extends EventDispatcher { constructor(image = _Texture.DEFAULT_IMAGE, mapping = _Texture.DEFAULT_MAPPING, wrapS = ClampToEdgeWrapping, wrapT = ClampToEdgeWrapping, magFilter = LinearFilter, minFilter = LinearMipmapLinearFilter, format = RGBAFormat, type = UnsignedByteType, anisotropy = 1, encoding = LinearEncoding) { super(); this.isTexture = true; Object.defineProperty(this, "id", { value: textureId++ }); this.uuid = generateUUID(); this.name = ""; this.source = new Source(image); this.mipmaps = []; this.mapping = mapping; this.wrapS = wrapS; this.wrapT = wrapT; this.magFilter = magFilter; this.minFilter = minFilter; this.anisotropy = anisotropy; this.format = format; this.internalFormat = null; this.type = type; this.offset = new Vector2(0, 0); this.repeat = new Vector2(1, 1); this.center = new Vector2(0, 0); this.rotation = 0; this.matrixAutoUpdate = true; this.matrix = new Matrix3(); this.generateMipmaps = true; this.premultiplyAlpha = false; this.flipY = true; this.unpackAlignment = 4; this.encoding = encoding; this.userData = {}; this.version = 0; this.onUpdate = null; this.isRenderTargetTexture = false; this.needsPMREMUpdate = false; } get image() { return this.source.data; } set image(value) { this.source.data = value; } updateMatrix() { this.matrix.setUvTransform(this.offset.x, this.offset.y, this.repeat.x, this.repeat.y, this.rotation, this.center.x, this.center.y); } clone() { return new this.constructor().copy(this); } copy(source) { this.name = source.name; this.source = source.source; this.mipmaps = source.mipmaps.slice(0); this.mapping = source.mapping; this.wrapS = source.wrapS; this.wrapT = source.wrapT; this.magFilter = source.magFilter; this.minFilter = source.minFilter; this.anisotropy = source.anisotropy; this.format = source.format; this.internalFormat = source.internalFormat; this.type = source.type; this.offset.copy(source.offset); this.repeat.copy(source.repeat); this.center.copy(source.center); this.rotation = source.rotation; this.matrixAutoUpdate = source.matrixAutoUpdate; this.matrix.copy(source.matrix); this.generateMipmaps = source.generateMipmaps; this.premultiplyAlpha = source.premultiplyAlpha; this.flipY = source.flipY; this.unpackAlignment = source.unpackAlignment; this.encoding = source.encoding; this.userData = JSON.parse(JSON.stringify(source.userData)); this.needsUpdate = true; return this; } toJSON(meta) { const isRootObject = meta === void 0 || typeof meta === "string"; if (!isRootObject && meta.textures[this.uuid] !== void 0) { return meta.textures[this.uuid]; } const output = { metadata: { version: 4.5, type: "Texture", generator: "Texture.toJSON" }, uuid: this.uuid, name: this.name, image: this.source.toJSON(meta).uuid, mapping: this.mapping, repeat: [this.repeat.x, this.repeat.y], offset: [this.offset.x, this.offset.y], center: [this.center.x, this.center.y], rotation: this.rotation, wrap: [this.wrapS, this.wrapT], format: this.format, type: this.type, encoding: this.encoding, minFilter: this.minFilter, magFilter: this.magFilter, anisotropy: this.anisotropy, flipY: this.flipY, premultiplyAlpha: this.premultiplyAlpha, unpackAlignment: this.unpackAlignment }; if (JSON.stringify(this.userData) !== "{}") output.userData = this.userData; if (!isRootObject) { meta.textures[this.uuid] = output; } return output; } dispose() { this.dispatchEvent({ type: "dispose" }); } transformUv(uv) { if (this.mapping !== UVMapping) return uv; uv.applyMatrix3(this.matrix); if (uv.x < 0 || uv.x > 1) { switch (this.wrapS) { case RepeatWrapping: uv.x = uv.x - Math.floor(uv.x); break; case ClampToEdgeWrapping: uv.x = uv.x < 0 ? 0 : 1; break; case MirroredRepeatWrapping: if (Math.abs(Math.floor(uv.x) % 2) === 1) { uv.x = Math.ceil(uv.x) - uv.x; } else { uv.x = uv.x - Math.floor(uv.x); } break; } } if (uv.y < 0 || uv.y > 1) { switch (this.wrapT) { case RepeatWrapping: uv.y = uv.y - Math.floor(uv.y); break; case ClampToEdgeWrapping: uv.y = uv.y < 0 ? 0 : 1; break; case MirroredRepeatWrapping: if (Math.abs(Math.floor(uv.y) % 2) === 1) { uv.y = Math.ceil(uv.y) - uv.y; } else { uv.y = uv.y - Math.floor(uv.y); } break; } } if (this.flipY) { uv.y = 1 - uv.y; } return uv; } set needsUpdate(value) { if (value === true) { this.version++; this.source.needsUpdate = true; } } }; Texture.DEFAULT_IMAGE = null; Texture.DEFAULT_MAPPING = UVMapping; var Vector4 = class _Vector4 { constructor(x2 = 0, y = 0, z = 0, w = 1) { _Vector4.prototype.isVector4 = true; this.x = x2; this.y = y; this.z = z; this.w = w; } get width() { return this.z; } set width(value) { this.z = value; } get height() { return this.w; } set height(value) { this.w = value; } set(x2, y, z, w) { this.x = x2; this.y = y; this.z = z; this.w = w; return this; } setScalar(scalar) { this.x = scalar; this.y = scalar; this.z = scalar; this.w = scalar; return this; } setX(x2) { this.x = x2; return this; } setY(y) { this.y = y; return this; } setZ(z) { this.z = z; return this; } setW(w) { this.w = w; return this; } setComponent(index, value) { switch (index) { case 0: this.x = value; break; case 1: this.y = value; break; case 2: this.z = value; break; case 3: this.w = value; break; default: throw new Error("index is out of range: " + index); } return this; } getComponent(index) { switch (index) { case 0: return this.x; case 1: return this.y; case 2: return this.z; case 3: return this.w; default: throw new Error("index is out of range: " + index); } } clone() { return new this.constructor(this.x, this.y, this.z, this.w); } copy(v) { this.x = v.x; this.y = v.y; this.z = v.z; this.w = v.w !== void 0 ? v.w : 1; return this; } add(v) { this.x += v.x; this.y += v.y; this.z += v.z; this.w += v.w; return this; } addScalar(s) { this.x += s; this.y += s; this.z += s; this.w += s; return this; } addVectors(a, b) { this.x = a.x + b.x; this.y = a.y + b.y; this.z = a.z + b.z; this.w = a.w + b.w; return this; } addScaledVector(v, s) { this.x += v.x * s; this.y += v.y * s; this.z += v.z * s; this.w += v.w * s; return this; } sub(v) { this.x -= v.x; this.y -= v.y; this.z -= v.z; this.w -= v.w; return this; } subScalar(s) { this.x -= s; this.y -= s; this.z -= s; this.w -= s; return this; } subVectors(a, b) { this.x = a.x - b.x; this.y = a.y - b.y; this.z = a.z - b.z; this.w = a.w - b.w; return this; } multiply(v) { this.x *= v.x; this.y *= v.y; this.z *= v.z; this.w *= v.w; return this; } multiplyScalar(scalar) { this.x *= scalar; this.y *= scalar; this.z *= scalar; this.w *= scalar; return this; } applyMatrix4(m) { const x2 = this.x, y = this.y, z = this.z, w = this.w; const e = m.elements; this.x = e[0] * x2 + e[4] * y + e[8] * z + e[12] * w; this.y = e[1] * x2 + e[5] * y + e[9] * z + e[13] * w; this.z = e[2] * x2 + e[6] * y + e[10] * z + e[14] * w; this.w = e[3] * x2 + e[7] * y + e[11] * z + e[15] * w; return this; } divideScalar(scalar) { return this.multiplyScalar(1 / scalar); } setAxisAngleFromQuaternion(q) { this.w = 2 * Math.acos(q.w); const s = Math.sqrt(1 - q.w * q.w); if (s < 1e-4) { this.x = 1; this.y = 0; this.z = 0; } else { this.x = q.x / s; this.y = q.y / s; this.z = q.z / s; } return this; } setAxisAngleFromRotationMatrix(m) { let angle, x2, y, z; const epsilon = 0.01, epsilon2 = 0.1, te2 = m.elements, m11 = te2[0], m12 = te2[4], m13 = te2[8], m21 = te2[1], m22 = te2[5], m23 = te2[9], m31 = te2[2], m32 = te2[6], m33 = te2[10]; if (Math.abs(m12 - m21) < epsilon && Math.abs(m13 - m31) < epsilon && Math.abs(m23 - m32) < epsilon) { if (Math.abs(m12 + m21) < epsilon2 && Math.abs(m13 + m31) < epsilon2 && Math.abs(m23 + m32) < epsilon2 && Math.abs(m11 + m22 + m33 - 3) < epsilon2) { this.set(1, 0, 0, 0); return this; } angle = Math.PI; const xx = (m11 + 1) / 2; const yy = (m22 + 1) / 2; const zz = (m33 + 1) / 2; const xy = (m12 + m21) / 4; const xz = (m13 + m31) / 4; const yz = (m23 + m32) / 4; if (xx > yy && xx > zz) { if (xx < epsilon) { x2 = 0; y = 0.707106781; z = 0.707106781; } else { x2 = Math.sqrt(xx); y = xy / x2; z = xz / x2; } } else if (yy > zz) { if (yy < epsilon) { x2 = 0.707106781; y = 0; z = 0.707106781; } else { y = Math.sqrt(yy); x2 = xy / y; z = yz / y; } } else { if (zz < epsilon) { x2 = 0.707106781; y = 0.707106781; z = 0; } else { z = Math.sqrt(zz); x2 = xz / z; y = yz / z; } } this.set(x2, y, z, angle); return this; } let s = Math.sqrt((m32 - m23) * (m32 - m23) + (m13 - m31) * (m13 - m31) + (m21 - m12) * (m21 - m12)); if (Math.abs(s) < 1e-3) s = 1; this.x = (m32 - m23) / s; this.y = (m13 - m31) / s; this.z = (m21 - m12) / s; this.w = Math.acos((m11 + m22 + m33 - 1) / 2); return this; } min(v) { this.x = Math.min(this.x, v.x); this.y = Math.min(this.y, v.y); this.z = Math.min(this.z, v.z); this.w = Math.min(this.w, v.w); return this; } max(v) { this.x = Math.max(this.x, v.x); this.y = Math.max(this.y, v.y); this.z = Math.max(this.z, v.z); this.w = Math.max(this.w, v.w); return this; } clamp(min, max2) { this.x = Math.max(min.x, Math.min(max2.x, this.x)); this.y = Math.max(min.y, Math.min(max2.y, this.y)); this.z = Math.max(min.z, Math.min(max2.z, this.z)); this.w = Math.max(min.w, Math.min(max2.w, this.w)); return this; } clampScalar(minVal, maxVal) { this.x = Math.max(minVal, Math.min(maxVal, this.x)); this.y = Math.max(minVal, Math.min(maxVal, this.y)); this.z = Math.max(minVal, Math.min(maxVal, this.z)); this.w = Math.max(minVal, Math.min(maxVal, this.w)); return this; } clampLength(min, max2) { const length = this.length(); return this.divideScalar(length || 1).multiplyScalar(Math.max(min, Math.min(max2, length))); } floor() { this.x = Math.floor(this.x); this.y = Math.floor(this.y); this.z = Math.floor(this.z); this.w = Math.floor(this.w); return this; } ceil() { this.x = Math.ceil(this.x); this.y = Math.ceil(this.y); this.z = Math.ceil(this.z); this.w = Math.ceil(this.w); return this; } round() { this.x = Math.round(this.x); this.y = Math.round(this.y); this.z = Math.round(this.z); this.w = Math.round(this.w); return this; } roundToZero() { this.x = this.x < 0 ? Math.ceil(this.x) : Math.floor(this.x); this.y = this.y < 0 ? Math.ceil(this.y) : Math.floor(this.y); this.z = this.z < 0 ? Math.ceil(this.z) : Math.floor(this.z); this.w = this.w < 0 ? Math.ceil(this.w) : Math.floor(this.w); return this; } negate() { this.x = -this.x; this.y = -this.y; this.z = -this.z; this.w = -this.w; return this; } dot(v) { return this.x * v.x + this.y * v.y + this.z * v.z + this.w * v.w; } lengthSq() { return this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w; } length() { return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w); } manhattanLength() { return Math.abs(this.x) + Math.abs(this.y) + Math.abs(this.z) + Math.abs(this.w); } normalize() { return this.divideScalar(this.length() || 1); } setLength(length) { return this.normalize().multiplyScalar(length); } lerp(v, alpha) { this.x += (v.x - this.x) * alpha; this.y += (v.y - this.y) * alpha; this.z += (v.z - this.z) * alpha; this.w += (v.w - this.w) * alpha; return this; } lerpVectors(v1, v2, alpha) { this.x = v1.x + (v2.x - v1.x) * alpha; this.y = v1.y + (v2.y - v1.y) * alpha; this.z = v1.z + (v2.z - v1.z) * alpha; this.w = v1.w + (v2.w - v1.w) * alpha; return this; } equals(v) { return v.x === this.x && v.y === this.y && v.z === this.z && v.w === this.w; } fromArray(array, offset = 0) { this.x = array[offset]; this.y = array[offset + 1]; this.z = array[offset + 2]; this.w = array[offset + 3]; return this; } toArray(array = [], offset = 0) { array[offset] = this.x; array[offset + 1] = this.y; array[offset + 2] = this.z; array[offset + 3] = this.w; return array; } fromBufferAttribute(attribute, index) { this.x = attribute.getX(index); this.y = attribute.getY(index); this.z = attribute.getZ(index); this.w = attribute.getW(index); return this; } random() { this.x = Math.random(); this.y = Math.random(); this.z = Math.random(); this.w = Math.random(); return this; } *[Symbol.iterator]() { yield this.x; yield this.y; yield this.z; yield this.w; } }; var WebGLRenderTarget = class extends EventDispatcher { constructor(width = 1, height = 1, options = {}) { super(); this.isWebGLRenderTarget = true; this.width = width; this.height = height; this.depth = 1; this.scissor = new Vector4(0, 0, width, height); this.scissorTest = false; this.viewport = new Vector4(0, 0, width, height); const image = { width, height, depth: 1 }; this.texture = new Texture(image, options.mapping, options.wrapS, options.wrapT, options.magFilter, options.minFilter, options.format, options.type, options.anisotropy, options.encoding); this.texture.isRenderTargetTexture = true; this.texture.flipY = false; this.texture.generateMipmaps = options.generateMipmaps !== void 0 ? options.generateMipmaps : false; this.texture.internalFormat = options.internalFormat !== void 0 ? options.internalFormat : null; this.texture.minFilter = options.minFilter !== void 0 ? options.minFilter : LinearFilter; this.depthBuffer = options.depthBuffer !== void 0 ? options.depthBuffer : true; this.stencilBuffer = options.stencilBuffer !== void 0 ? options.stencilBuffer : false; this.depthTexture = options.depthTexture !== void 0 ? options.depthTexture : null; this.samples = options.samples !== void 0 ? options.samples : 0; } setSize(width, height, depth = 1) { if (this.width !== width || this.height !== height || this.depth !== depth) { this.width = width; this.height = height; this.depth = depth; this.texture.image.width = width; this.texture.image.height = height; this.texture.image.depth = depth; this.dispose(); } this.viewport.set(0, 0, width, height); this.scissor.set(0, 0, width, height); } clone() { return new this.constructor().copy(this); } copy(source) { this.width = source.width; this.height = source.height; this.depth = source.depth; this.viewport.copy(source.viewport); this.texture = source.texture.clone(); this.texture.isRenderTargetTexture = true; const image = Object.assign({}, source.texture.image); this.texture.source = new Source(image); this.depthBuffer = source.depthBuffer; this.stencilBuffer = source.stencilBuffer; if (source.depthTexture !== null) this.depthTexture = source.depthTexture.clone(); this.samples = source.samples; return this; } dispose() { this.dispatchEvent({ type: "dispose" }); } }; var DataArrayTexture = class extends Texture { constructor(data = null, width = 1, height = 1, depth = 1) { super(null); this.isDataArrayTexture = true; this.image = { data, width, height, depth }; this.magFilter = NearestFilter; this.minFilter = NearestFilter; this.wrapR = ClampToEdgeWrapping; this.generateMipmaps = false; this.flipY = false; this.unpackAlignment = 1; } }; var Data3DTexture = class extends Texture { constructor(data = null, width = 1, height = 1, depth = 1) { super(null); this.isData3DTexture = true; this.image = { data, width, height, depth }; this.magFilter = NearestFilter; this.minFilter = NearestFilter; this.wrapR = ClampToEdgeWrapping; this.generateMipmaps = false; this.flipY = false; this.unpackAlignment = 1; } }; var Quaternion = class { constructor(x2 = 0, y = 0, z = 0, w = 1) { this.isQuaternion = true; this._x = x2; this._y = y; this._z = z; this._w = w; } static slerpFlat(dst, dstOffset, src0, srcOffset0, src1, srcOffset1, t2) { let x0 = src0[srcOffset0 + 0], y0 = src0[srcOffset0 + 1], z0 = src0[srcOffset0 + 2], w0 = src0[srcOffset0 + 3]; const x1 = src1[srcOffset1 + 0], y1 = src1[srcOffset1 + 1], z1 = src1[srcOffset1 + 2], w1 = src1[srcOffset1 + 3]; if (t2 === 0) { dst[dstOffset + 0] = x0; dst[dstOffset + 1] = y0; dst[dstOffset + 2] = z0; dst[dstOffset + 3] = w0; return; } if (t2 === 1) { dst[dstOffset + 0] = x1; dst[dstOffset + 1] = y1; dst[dstOffset + 2] = z1; dst[dstOffset + 3] = w1; return; } if (w0 !== w1 || x0 !== x1 || y0 !== y1 || z0 !== z1) { let s = 1 - t2; const cos = x0 * x1 + y0 * y1 + z0 * z1 + w0 * w1, dir = cos >= 0 ? 1 : -1, sqrSin = 1 - cos * cos; if (sqrSin > Number.EPSILON) { const sin = Math.sqrt(sqrSin), len = Math.atan2(sin, cos * dir); s = Math.sin(s * len) / sin; t2 = Math.sin(t2 * len) / sin; } const tDir = t2 * dir; x0 = x0 * s + x1 * tDir; y0 = y0 * s + y1 * tDir; z0 = z0 * s + z1 * tDir; w0 = w0 * s + w1 * tDir; if (s === 1 - t2) { const f = 1 / Math.sqrt(x0 * x0 + y0 * y0 + z0 * z0 + w0 * w0); x0 *= f; y0 *= f; z0 *= f; w0 *= f; } } dst[dstOffset] = x0; dst[dstOffset + 1] = y0; dst[dstOffset + 2] = z0; dst[dstOffset + 3] = w0; } static multiplyQuaternionsFlat(dst, dstOffset, src0, srcOffset0, src1, srcOffset1) { const x0 = src0[srcOffset0]; const y0 = src0[srcOffset0 + 1]; const z0 = src0[srcOffset0 + 2]; const w0 = src0[srcOffset0 + 3]; const x1 = src1[srcOffset1]; const y1 = src1[srcOffset1 + 1]; const z1 = src1[srcOffset1 + 2]; const w1 = src1[srcOffset1 + 3]; dst[dstOffset] = x0 * w1 + w0 * x1 + y0 * z1 - z0 * y1; dst[dstOffset + 1] = y0 * w1 + w0 * y1 + z0 * x1 - x0 * z1; dst[dstOffset + 2] = z0 * w1 + w0 * z1 + x0 * y1 - y0 * x1; dst[dstOffset + 3] = w0 * w1 - x0 * x1 - y0 * y1 - z0 * z1; return dst; } get x() { return this._x; } set x(value) { this._x = value; this._onChangeCallback(); } get y() { return this._y; } set y(value) { this._y = value; this._onChangeCallback(); } get z() { return this._z; } set z(value) { this._z = value; this._onChangeCallback(); } get w() { return this._w; } set w(value) { this._w = value; this._onChangeCallback(); } set(x2, y, z, w) { this._x = x2; this._y = y; this._z = z; this._w = w; this._onChangeCallback(); return this; } clone() { return new this.constructor(this._x, this._y, this._z, this._w); } copy(quaternion) { this._x = quaternion.x; this._y = quaternion.y; this._z = quaternion.z; this._w = quaternion.w; this._onChangeCallback(); return this; } setFromEuler(euler, update) { const x2 = euler._x, y = euler._y, z = euler._z, order = euler._order; const cos = Math.cos; const sin = Math.sin; const c1 = cos(x2 / 2); const c2 = cos(y / 2); const c3 = cos(z / 2); const s1 = sin(x2 / 2); const s2 = sin(y / 2); const s3 = sin(z / 2); switch (order) { case "XYZ": this._x = s1 * c2 * c3 + c1 * s2 * s3; this._y = c1 * s2 * c3 - s1 * c2 * s3; this._z = c1 * c2 * s3 + s1 * s2 * c3; this._w = c1 * c2 * c3 - s1 * s2 * s3; break; case "YXZ": this._x = s1 * c2 * c3 + c1 * s2 * s3; this._y = c1 * s2 * c3 - s1 * c2 * s3; this._z = c1 * c2 * s3 - s1 * s2 * c3; this._w = c1 * c2 * c3 + s1 * s2 * s3; break; case "ZXY": this._x = s1 * c2 * c3 - c1 * s2 * s3; this._y = c1 * s2 * c3 + s1 * c2 * s3; this._z = c1 * c2 * s3 + s1 * s2 * c3; this._w = c1 * c2 * c3 - s1 * s2 * s3; break; case "ZYX": this._x = s1 * c2 * c3 - c1 * s2 * s3; this._y = c1 * s2 * c3 + s1 * c2 * s3; this._z = c1 * c2 * s3 - s1 * s2 * c3; this._w = c1 * c2 * c3 + s1 * s2 * s3; break; case "YZX": this._x = s1 * c2 * c3 + c1 * s2 * s3; this._y = c1 * s2 * c3 + s1 * c2 * s3; this._z = c1 * c2 * s3 - s1 * s2 * c3; this._w = c1 * c2 * c3 - s1 * s2 * s3; break; case "XZY": this._x = s1 * c2 * c3 - c1 * s2 * s3; this._y = c1 * s2 * c3 - s1 * c2 * s3; this._z = c1 * c2 * s3 + s1 * s2 * c3; this._w = c1 * c2 * c3 + s1 * s2 * s3; break; default: console.warn("THREE.Quaternion: .setFromEuler() encountered an unknown order: " + order); } if (update !== false) this._onChangeCallback(); return this; } setFromAxisAngle(axis, angle) { const halfAngle = angle / 2, s = Math.sin(halfAngle); this._x = axis.x * s; this._y = axis.y * s; this._z = axis.z * s; this._w = Math.cos(halfAngle); this._onChangeCallback(); return this; } setFromRotationMatrix(m) { const te2 = m.elements, m11 = te2[0], m12 = te2[4], m13 = te2[8], m21 = te2[1], m22 = te2[5], m23 = te2[9], m31 = te2[2], m32 = te2[6], m33 = te2[10], trace = m11 + m22 + m33; if (trace > 0) { const s = 0.5 / Math.sqrt(trace + 1); this._w = 0.25 / s; this._x = (m32 - m23) * s; this._y = (m13 - m31) * s; this._z = (m21 - m12) * s; } else if (m11 > m22 && m11 > m33) { const s = 2 * Math.sqrt(1 + m11 - m22 - m33); this._w = (m32 - m23) / s; this._x = 0.25 * s; this._y = (m12 + m21) / s; this._z = (m13 + m31) / s; } else if (m22 > m33) { const s = 2 * Math.sqrt(1 + m22 - m11 - m33); this._w = (m13 - m31) / s; this._x = (m12 + m21) / s; this._y = 0.25 * s; this._z = (m23 + m32) / s; } else { const s = 2 * Math.sqrt(1 + m33 - m11 - m22); this._w = (m21 - m12) / s; this._x = (m13 + m31) / s; this._y = (m23 + m32) / s; this._z = 0.25 * s; } this._onChangeCallback(); return this; } setFromUnitVectors(vFrom, vTo) { let r = vFrom.dot(vTo) + 1; if (r < Number.EPSILON) { r = 0; if (Math.abs(vFrom.x) > Math.abs(vFrom.z)) { this._x = -vFrom.y; this._y = vFrom.x; this._z = 0; this._w = r; } else { this._x = 0; this._y = -vFrom.z; this._z = vFrom.y; this._w = r; } } else { this._x = vFrom.y * vTo.z - vFrom.z * vTo.y; this._y = vFrom.z * vTo.x - vFrom.x * vTo.z; this._z = vFrom.x * vTo.y - vFrom.y * vTo.x; this._w = r; } return this.normalize(); } angleTo(q) { return 2 * Math.acos(Math.abs(clamp(this.dot(q), -1, 1))); } rotateTowards(q, step) { const angle = this.angleTo(q); if (angle === 0) return this; const t2 = Math.min(1, step / angle); this.slerp(q, t2); return this; } identity() { return this.set(0, 0, 0, 1); } invert() { return this.conjugate(); } conjugate() { this._x *= -1; this._y *= -1; this._z *= -1; this._onChangeCallback(); return this; } dot(v) { return this._x * v._x + this._y * v._y + this._z * v._z + this._w * v._w; } lengthSq() { return this._x * this._x + this._y * this._y + this._z * this._z + this._w * this._w; } length() { return Math.sqrt(this._x * this._x + this._y * this._y + this._z * this._z + this._w * this._w); } normalize() { let l = this.length(); if (l === 0) { this._x = 0; this._y = 0; this._z = 0; this._w = 1; } else { l = 1 / l; this._x = this._x * l; this._y = this._y * l; this._z = this._z * l; this._w = this._w * l; } this._onChangeCallback(); return this; } multiply(q) { return this.multiplyQuaternions(this, q); } premultiply(q) { return this.multiplyQuaternions(q, this); } multiplyQuaternions(a, b) { const qax = a._x, qay = a._y, qaz = a._z, qaw = a._w; const qbx = b._x, qby = b._y, qbz = b._z, qbw = b._w; this._x = qax * qbw + qaw * qbx + qay * qbz - qaz * qby; this._y = qay * qbw + qaw * qby + qaz * qbx - qax * qbz; this._z = qaz * qbw + qaw * qbz + qax * qby - qay * qbx; this._w = qaw * qbw - qax * qbx - qay * qby - qaz * qbz; this._onChangeCallback(); return this; } slerp(qb, t2) { if (t2 === 0) return this; if (t2 === 1) return this.copy(qb); const x2 = this._x, y = this._y, z = this._z, w = this._w; let cosHalfTheta = w * qb._w + x2 * qb._x + y * qb._y + z * qb._z; if (cosHalfTheta < 0) { this._w = -qb._w; this._x = -qb._x; this._y = -qb._y; this._z = -qb._z; cosHalfTheta = -cosHalfTheta; } else { this.copy(qb); } if (cosHalfTheta >= 1) { this._w = w; this._x = x2; this._y = y; this._z = z; return this; } const sqrSinHalfTheta = 1 - cosHalfTheta * cosHalfTheta; if (sqrSinHalfTheta <= Number.EPSILON) { const s = 1 - t2; this._w = s * w + t2 * this._w; this._x = s * x2 + t2 * this._x; this._y = s * y + t2 * this._y; this._z = s * z + t2 * this._z; this.normalize(); this._onChangeCallback(); return this; } const sinHalfTheta = Math.sqrt(sqrSinHalfTheta); const halfTheta = Math.atan2(sinHalfTheta, cosHalfTheta); const ratioA = Math.sin((1 - t2) * halfTheta) / sinHalfTheta, ratioB = Math.sin(t2 * halfTheta) / sinHalfTheta; this._w = w * ratioA + this._w * ratioB; this._x = x2 * ratioA + this._x * ratioB; this._y = y * ratioA + this._y * ratioB; this._z = z * ratioA + this._z * ratioB; this._onChangeCallback(); return this; } slerpQuaternions(qa, qb, t2) { return this.copy(qa).slerp(qb, t2); } random() { const u1 = Math.random(); const sqrt1u1 = Math.sqrt(1 - u1); const sqrtu1 = Math.sqrt(u1); const u2 = 2 * Math.PI * Math.random(); const u3 = 2 * Math.PI * Math.random(); return this.set( sqrt1u1 * Math.cos(u2), sqrtu1 * Math.sin(u3), sqrtu1 * Math.cos(u3), sqrt1u1 * Math.sin(u2) ); } equals(quaternion) { return quaternion._x === this._x && quaternion._y === this._y && quaternion._z === this._z && quaternion._w === this._w; } fromArray(array, offset = 0) { this._x = array[offset]; this._y = array[offset + 1]; this._z = array[offset + 2]; this._w = array[offset + 3]; this._onChangeCallback(); return this; } toArray(array = [], offset = 0) { array[offset] = this._x; array[offset + 1] = this._y; array[offset + 2] = this._z; array[offset + 3] = this._w; return array; } fromBufferAttribute(attribute, index) { this._x = attribute.getX(index); this._y = attribute.getY(index); this._z = attribute.getZ(index); this._w = attribute.getW(index); return this; } _onChange(callback) { this._onChangeCallback = callback; return this; } _onChangeCallback() { } *[Symbol.iterator]() { yield this._x; yield this._y; yield this._z; yield this._w; } }; var Vector3 = class _Vector3 { constructor(x2 = 0, y = 0, z = 0) { _Vector3.prototype.isVector3 = true; this.x = x2; this.y = y; this.z = z; } set(x2, y, z) { if (z === void 0) z = this.z; this.x = x2; this.y = y; this.z = z; return this; } setScalar(scalar) { this.x = scalar; this.y = scalar; this.z = scalar; return this; } setX(x2) { this.x = x2; return this; } setY(y) { this.y = y; return this; } setZ(z) { this.z = z; return this; } setComponent(index, value) { switch (index) { case 0: this.x = value; break; case 1: this.y = value; break; case 2: this.z = value; break; default: throw new Error("index is out of range: " + index); } return this; } getComponent(index) { switch (index) { case 0: return this.x; case 1: return this.y; case 2: return this.z; default: throw new Error("index is out of range: " + index); } } clone() { return new this.constructor(this.x, this.y, this.z); } copy(v) { this.x = v.x; this.y = v.y; this.z = v.z; return this; } add(v) { this.x += v.x; this.y += v.y; this.z += v.z; return this; } addScalar(s) { this.x += s; this.y += s; this.z += s; return this; } addVectors(a, b) { this.x = a.x + b.x; this.y = a.y + b.y; this.z = a.z + b.z; return this; } addScaledVector(v, s) { this.x += v.x * s; this.y += v.y * s; this.z += v.z * s; return this; } sub(v) { this.x -= v.x; this.y -= v.y; this.z -= v.z; return this; } subScalar(s) { this.x -= s; this.y -= s; this.z -= s; return this; } subVectors(a, b) { this.x = a.x - b.x; this.y = a.y - b.y; this.z = a.z - b.z; return this; } multiply(v) { this.x *= v.x; this.y *= v.y; this.z *= v.z; return this; } multiplyScalar(scalar) { this.x *= scalar; this.y *= scalar; this.z *= scalar; return this; } multiplyVectors(a, b) { this.x = a.x * b.x; this.y = a.y * b.y; this.z = a.z * b.z; return this; } applyEuler(euler) { return this.applyQuaternion(_quaternion$4.setFromEuler(euler)); } applyAxisAngle(axis, angle) { return this.applyQuaternion(_quaternion$4.setFromAxisAngle(axis, angle)); } applyMatrix3(m) { const x2 = this.x, y = this.y, z = this.z; const e = m.elements; this.x = e[0] * x2 + e[3] * y + e[6] * z; this.y = e[1] * x2 + e[4] * y + e[7] * z; this.z = e[2] * x2 + e[5] * y + e[8] * z; return this; } applyNormalMatrix(m) { return this.applyMatrix3(m).normalize(); } applyMatrix4(m) { const x2 = this.x, y = this.y, z = this.z; const e = m.elements; const w = 1 / (e[3] * x2 + e[7] * y + e[11] * z + e[15]); this.x = (e[0] * x2 + e[4] * y + e[8] * z + e[12]) * w; this.y = (e[1] * x2 + e[5] * y + e[9] * z + e[13]) * w; this.z = (e[2] * x2 + e[6] * y + e[10] * z + e[14]) * w; return this; } applyQuaternion(q) { const x2 = this.x, y = this.y, z = this.z; const qx = q.x, qy = q.y, qz = q.z, qw = q.w; const ix = qw * x2 + qy * z - qz * y; const iy = qw * y + qz * x2 - qx * z; const iz = qw * z + qx * y - qy * x2; const iw = -qx * x2 - qy * y - qz * z; this.x = ix * qw + iw * -qx + iy * -qz - iz * -qy; this.y = iy * qw + iw * -qy + iz * -qx - ix * -qz; this.z = iz * qw + iw * -qz + ix * -qy - iy * -qx; return this; } project(camera2) { return this.applyMatrix4(camera2.matrixWorldInverse).applyMatrix4(camera2.projectionMatrix); } unproject(camera2) { return this.applyMatrix4(camera2.projectionMatrixInverse).applyMatrix4(camera2.matrixWorld); } transformDirection(m) { const x2 = this.x, y = this.y, z = this.z; const e = m.elements; this.x = e[0] * x2 + e[4] * y + e[8] * z; this.y = e[1] * x2 + e[5] * y + e[9] * z; this.z = e[2] * x2 + e[6] * y + e[10] * z; return this.normalize(); } divide(v) { this.x /= v.x; this.y /= v.y; this.z /= v.z; return this; } divideScalar(scalar) { return this.multiplyScalar(1 / scalar); } min(v) { this.x = Math.min(this.x, v.x); this.y = Math.min(this.y, v.y); this.z = Math.min(this.z, v.z); return this; } max(v) { this.x = Math.max(this.x, v.x); this.y = Math.max(this.y, v.y); this.z = Math.max(this.z, v.z); return this; } clamp(min, max2) { this.x = Math.max(min.x, Math.min(max2.x, this.x)); this.y = Math.max(min.y, Math.min(max2.y, this.y)); this.z = Math.max(min.z, Math.min(max2.z, this.z)); return this; } clampScalar(minVal, maxVal) { this.x = Math.max(minVal, Math.min(maxVal, this.x)); this.y = Math.max(minVal, Math.min(maxVal, this.y)); this.z = Math.max(minVal, Math.min(maxVal, this.z)); return this; } clampLength(min, max2) { const length = this.length(); return this.divideScalar(length || 1).multiplyScalar(Math.max(min, Math.min(max2, length))); } floor() { this.x = Math.floor(this.x); this.y = Math.floor(this.y); this.z = Math.floor(this.z); return this; } ceil() { this.x = Math.ceil(this.x); this.y = Math.ceil(this.y); this.z = Math.ceil(this.z); return this; } round() { this.x = Math.round(this.x); this.y = Math.round(this.y); this.z = Math.round(this.z); return this; } roundToZero() { this.x = this.x < 0 ? Math.ceil(this.x) : Math.floor(this.x); this.y = this.y < 0 ? Math.ceil(this.y) : Math.floor(this.y); this.z = this.z < 0 ? Math.ceil(this.z) : Math.floor(this.z); return this; } negate() { this.x = -this.x; this.y = -this.y; this.z = -this.z; return this; } dot(v) { return this.x * v.x + this.y * v.y + this.z * v.z; } // TODO lengthSquared? lengthSq() { return this.x * this.x + this.y * this.y + this.z * this.z; } length() { return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z); } manhattanLength() { return Math.abs(this.x) + Math.abs(this.y) + Math.abs(this.z); } normalize() { return this.divideScalar(this.length() || 1); } setLength(length) { return this.normalize().multiplyScalar(length); } lerp(v, alpha) { this.x += (v.x - this.x) * alpha; this.y += (v.y - this.y) * alpha; this.z += (v.z - this.z) * alpha; return this; } lerpVectors(v1, v2, alpha) { this.x = v1.x + (v2.x - v1.x) * alpha; this.y = v1.y + (v2.y - v1.y) * alpha; this.z = v1.z + (v2.z - v1.z) * alpha; return this; } cross(v) { return this.crossVectors(this, v); } crossVectors(a, b) { const ax = a.x, ay = a.y, az = a.z; const bx = b.x, by = b.y, bz = b.z; this.x = ay * bz - az * by; this.y = az * bx - ax * bz; this.z = ax * by - ay * bx; return this; } projectOnVector(v) { const denominator = v.lengthSq(); if (denominator === 0) return this.set(0, 0, 0); const scalar = v.dot(this) / denominator; return this.copy(v).multiplyScalar(scalar); } projectOnPlane(planeNormal) { _vector$c.copy(this).projectOnVector(planeNormal); return this.sub(_vector$c); } reflect(normal) { return this.sub(_vector$c.copy(normal).multiplyScalar(2 * this.dot(normal))); } angleTo(v) { const denominator = Math.sqrt(this.lengthSq() * v.lengthSq()); if (denominator === 0) return Math.PI / 2; const theta = this.dot(v) / denominator; return Math.acos(clamp(theta, -1, 1)); } distanceTo(v) { return Math.sqrt(this.distanceToSquared(v)); } distanceToSquared(v) { const dx = this.x - v.x, dy = this.y - v.y, dz = this.z - v.z; return dx * dx + dy * dy + dz * dz; } manhattanDistanceTo(v) { return Math.abs(this.x - v.x) + Math.abs(this.y - v.y) + Math.abs(this.z - v.z); } setFromSpherical(s) { return this.setFromSphericalCoords(s.radius, s.phi, s.theta); } setFromSphericalCoords(radius, phi, theta) { const sinPhiRadius = Math.sin(phi) * radius; this.x = sinPhiRadius * Math.sin(theta); this.y = Math.cos(phi) * radius; this.z = sinPhiRadius * Math.cos(theta); return this; } setFromCylindrical(c) { return this.setFromCylindricalCoords(c.radius, c.theta, c.y); } setFromCylindricalCoords(radius, theta, y) { this.x = radius * Math.sin(theta); this.y = y; this.z = radius * Math.cos(theta); return this; } setFromMatrixPosition(m) { const e = m.elements; this.x = e[12]; this.y = e[13]; this.z = e[14]; return this; } setFromMatrixScale(m) { const sx = this.setFromMatrixColumn(m, 0).length(); const sy = this.setFromMatrixColumn(m, 1).length(); const sz = this.setFromMatrixColumn(m, 2).length(); this.x = sx; this.y = sy; this.z = sz; return this; } setFromMatrixColumn(m, index) { return this.fromArray(m.elements, index * 4); } setFromMatrix3Column(m, index) { return this.fromArray(m.elements, index * 3); } setFromEuler(e) { this.x = e._x; this.y = e._y; this.z = e._z; return this; } equals(v) { return v.x === this.x && v.y === this.y && v.z === this.z; } fromArray(array, offset = 0) { this.x = array[offset]; this.y = array[offset + 1]; this.z = array[offset + 2]; return this; } toArray(array = [], offset = 0) { array[offset] = this.x; array[offset + 1] = this.y; array[offset + 2] = this.z; return array; } fromBufferAttribute(attribute, index) { this.x = attribute.getX(index); this.y = attribute.getY(index); this.z = attribute.getZ(index); return this; } random() { this.x = Math.random(); this.y = Math.random(); this.z = Math.random(); return this; } randomDirection() { const u = (Math.random() - 0.5) * 2; const t2 = Math.random() * Math.PI * 2; const f = Math.sqrt(1 - u ** 2); this.x = f * Math.cos(t2); this.y = f * Math.sin(t2); this.z = u; return this; } *[Symbol.iterator]() { yield this.x; yield this.y; yield this.z; } }; var _vector$c = new Vector3(); var _quaternion$4 = new Quaternion(); var Box3 = class { constructor(min = new Vector3(Infinity, Infinity, Infinity), max2 = new Vector3(-Infinity, -Infinity, -Infinity)) { this.isBox3 = true; this.min = min; this.max = max2; } set(min, max2) { this.min.copy(min); this.max.copy(max2); return this; } setFromArray(array) { let minX = Infinity; let minY = Infinity; let minZ = Infinity; let maxX = -Infinity; let maxY = -Infinity; let maxZ = -Infinity; for (let i = 0, l = array.length; i < l; i += 3) { const x2 = array[i]; const y = array[i + 1]; const z = array[i + 2]; if (x2 < minX) minX = x2; if (y < minY) minY = y; if (z < minZ) minZ = z; if (x2 > maxX) maxX = x2; if (y > maxY) maxY = y; if (z > maxZ) maxZ = z; } this.min.set(minX, minY, minZ); this.max.set(maxX, maxY, maxZ); return this; } setFromBufferAttribute(attribute) { let minX = Infinity; let minY = Infinity; let minZ = Infinity; let maxX = -Infinity; let maxY = -Infinity; let maxZ = -Infinity; for (let i = 0, l = attribute.count; i < l; i++) { const x2 = attribute.getX(i); const y = attribute.getY(i); const z = attribute.getZ(i); if (x2 < minX) minX = x2; if (y < minY) minY = y; if (z < minZ) minZ = z; if (x2 > maxX) maxX = x2; if (y > maxY) maxY = y; if (z > maxZ) maxZ = z; } this.min.set(minX, minY, minZ); this.max.set(maxX, maxY, maxZ); return this; } setFromPoints(points) { this.makeEmpty(); for (let i = 0, il = points.length; i < il; i++) { this.expandByPoint(points[i]); } return this; } setFromCenterAndSize(center, size) { const halfSize = _vector$b.copy(size).multiplyScalar(0.5); this.min.copy(center).sub(halfSize); this.max.copy(center).add(halfSize); return this; } setFromObject(object, precise = false) { this.makeEmpty(); return this.expandByObject(object, precise); } clone() { return new this.constructor().copy(this); } copy(box) { this.min.copy(box.min); this.max.copy(box.max); return this; } makeEmpty() { this.min.x = this.min.y = this.min.z = Infinity; this.max.x = this.max.y = this.max.z = -Infinity; return this; } isEmpty() { return this.max.x < this.min.x || this.max.y < this.min.y || this.max.z < this.min.z; } getCenter(target2) { return this.isEmpty() ? target2.set(0, 0, 0) : target2.addVectors(this.min, this.max).multiplyScalar(0.5); } getSize(target2) { return this.isEmpty() ? target2.set(0, 0, 0) : target2.subVectors(this.max, this.min); } expandByPoint(point) { this.min.min(point); this.max.max(point); return this; } expandByVector(vector) { this.min.sub(vector); this.max.add(vector); return this; } expandByScalar(scalar) { this.min.addScalar(-scalar); this.max.addScalar(scalar); return this; } expandByObject(object, precise = false) { object.updateWorldMatrix(false, false); const geometry = object.geometry; if (geometry !== void 0) { if (precise && geometry.attributes != void 0 && geometry.attributes.position !== void 0) { const position = geometry.attributes.position; for (let i = 0, l = position.count; i < l; i++) { _vector$b.fromBufferAttribute(position, i).applyMatrix4(object.matrixWorld); this.expandByPoint(_vector$b); } } else { if (geometry.boundingBox === null) { geometry.computeBoundingBox(); } _box$3.copy(geometry.boundingBox); _box$3.applyMatrix4(object.matrixWorld); this.union(_box$3); } } const children = object.children; for (let i = 0, l = children.length; i < l; i++) { this.expandByObject(children[i], precise); } return this; } containsPoint(point) { return point.x < this.min.x || point.x > this.max.x || point.y < this.min.y || point.y > this.max.y || point.z < this.min.z || point.z > this.max.z ? false : true; } containsBox(box) { return this.min.x <= box.min.x && box.max.x <= this.max.x && this.min.y <= box.min.y && box.max.y <= this.max.y && this.min.z <= box.min.z && box.max.z <= this.max.z; } getParameter(point, target2) { return target2.set( (point.x - this.min.x) / (this.max.x - this.min.x), (point.y - this.min.y) / (this.max.y - this.min.y), (point.z - this.min.z) / (this.max.z - this.min.z) ); } intersectsBox(box) { return box.max.x < this.min.x || box.min.x > this.max.x || box.max.y < this.min.y || box.min.y > this.max.y || box.max.z < this.min.z || box.min.z > this.max.z ? false : true; } intersectsSphere(sphere) { this.clampPoint(sphere.center, _vector$b); return _vector$b.distanceToSquared(sphere.center) <= sphere.radius * sphere.radius; } intersectsPlane(plane) { let min, max2; if (plane.normal.x > 0) { min = plane.normal.x * this.min.x; max2 = plane.normal.x * this.max.x; } else { min = plane.normal.x * this.max.x; max2 = plane.normal.x * this.min.x; } if (plane.normal.y > 0) { min += plane.normal.y * this.min.y; max2 += plane.normal.y * this.max.y; } else { min += plane.normal.y * this.max.y; max2 += plane.normal.y * this.min.y; } if (plane.normal.z > 0) { min += plane.normal.z * this.min.z; max2 += plane.normal.z * this.max.z; } else { min += plane.normal.z * this.max.z; max2 += plane.normal.z * this.min.z; } return min <= -plane.constant && max2 >= -plane.constant; } intersectsTriangle(triangle) { if (this.isEmpty()) { return false; } this.getCenter(_center); _extents.subVectors(this.max, _center); _v0$2.subVectors(triangle.a, _center); _v1$7.subVectors(triangle.b, _center); _v2$4.subVectors(triangle.c, _center); _f0.subVectors(_v1$7, _v0$2); _f1.subVectors(_v2$4, _v1$7); _f2.subVectors(_v0$2, _v2$4); let axes = [ 0, -_f0.z, _f0.y, 0, -_f1.z, _f1.y, 0, -_f2.z, _f2.y, _f0.z, 0, -_f0.x, _f1.z, 0, -_f1.x, _f2.z, 0, -_f2.x, -_f0.y, _f0.x, 0, -_f1.y, _f1.x, 0, -_f2.y, _f2.x, 0 ]; if (!satForAxes(axes, _v0$2, _v1$7, _v2$4, _extents)) { return false; } axes = [1, 0, 0, 0, 1, 0, 0, 0, 1]; if (!satForAxes(axes, _v0$2, _v1$7, _v2$4, _extents)) { return false; } _triangleNormal.crossVectors(_f0, _f1); axes = [_triangleNormal.x, _triangleNormal.y, _triangleNormal.z]; return satForAxes(axes, _v0$2, _v1$7, _v2$4, _extents); } clampPoint(point, target2) { return target2.copy(point).clamp(this.min, this.max); } distanceToPoint(point) { const clampedPoint = _vector$b.copy(point).clamp(this.min, this.max); return clampedPoint.sub(point).length(); } getBoundingSphere(target2) { this.getCenter(target2.center); target2.radius = this.getSize(_vector$b).length() * 0.5; return target2; } intersect(box) { this.min.max(box.min); this.max.min(box.max); if (this.isEmpty()) this.makeEmpty(); return this; } union(box) { this.min.min(box.min); this.max.max(box.max); return this; } applyMatrix4(matrix) { if (this.isEmpty()) return this; _points[0].set(this.min.x, this.min.y, this.min.z).applyMatrix4(matrix); _points[1].set(this.min.x, this.min.y, this.max.z).applyMatrix4(matrix); _points[2].set(this.min.x, this.max.y, this.min.z).applyMatrix4(matrix); _points[3].set(this.min.x, this.max.y, this.max.z).applyMatrix4(matrix); _points[4].set(this.max.x, this.min.y, this.min.z).applyMatrix4(matrix); _points[5].set(this.max.x, this.min.y, this.max.z).applyMatrix4(matrix); _points[6].set(this.max.x, this.max.y, this.min.z).applyMatrix4(matrix); _points[7].set(this.max.x, this.max.y, this.max.z).applyMatrix4(matrix); this.setFromPoints(_points); return this; } translate(offset) { this.min.add(offset); this.max.add(offset); return this; } equals(box) { return box.min.equals(this.min) && box.max.equals(this.max); } }; var _points = [ new Vector3(), new Vector3(), new Vector3(), new Vector3(), new Vector3(), new Vector3(), new Vector3(), new Vector3() ]; var _vector$b = new Vector3(); var _box$3 = new Box3(); var _v0$2 = new Vector3(); var _v1$7 = new Vector3(); var _v2$4 = new Vector3(); var _f0 = new Vector3(); var _f1 = new Vector3(); var _f2 = new Vector3(); var _center = new Vector3(); var _extents = new Vector3(); var _triangleNormal = new Vector3(); var _testAxis = new Vector3(); function satForAxes(axes, v0, v1, v2, extents) { for (let i = 0, j = axes.length - 3; i <= j; i += 3) { _testAxis.fromArray(axes, i); const r = extents.x * Math.abs(_testAxis.x) + extents.y * Math.abs(_testAxis.y) + extents.z * Math.abs(_testAxis.z); const p0 = v0.dot(_testAxis); const p1 = v1.dot(_testAxis); const p2 = v2.dot(_testAxis); if (Math.max(-Math.max(p0, p1, p2), Math.min(p0, p1, p2)) > r) { return false; } } return true; } var _box$2 = new Box3(); var _v1$6 = new Vector3(); var _v2$3 = new Vector3(); var Sphere = class { constructor(center = new Vector3(), radius = -1) { this.center = center; this.radius = radius; } set(center, radius) { this.center.copy(center); this.radius = radius; return this; } setFromPoints(points, optionalCenter) { const center = this.center; if (optionalCenter !== void 0) { center.copy(optionalCenter); } else { _box$2.setFromPoints(points).getCenter(center); } let maxRadiusSq = 0; for (let i = 0, il = points.length; i < il; i++) { maxRadiusSq = Math.max(maxRadiusSq, center.distanceToSquared(points[i])); } this.radius = Math.sqrt(maxRadiusSq); return this; } copy(sphere) { this.center.copy(sphere.center); this.radius = sphere.radius; return this; } isEmpty() { return this.radius < 0; } makeEmpty() { this.center.set(0, 0, 0); this.radius = -1; return this; } containsPoint(point) { return point.distanceToSquared(this.center) <= this.radius * this.radius; } distanceToPoint(point) { return point.distanceTo(this.center) - this.radius; } intersectsSphere(sphere) { const radiusSum = this.radius + sphere.radius; return sphere.center.distanceToSquared(this.center) <= radiusSum * radiusSum; } intersectsBox(box) { return box.intersectsSphere(this); } intersectsPlane(plane) { return Math.abs(plane.distanceToPoint(this.center)) <= this.radius; } clampPoint(point, target2) { const deltaLengthSq = this.center.distanceToSquared(point); target2.copy(point); if (deltaLengthSq > this.radius * this.radius) { target2.sub(this.center).normalize(); target2.multiplyScalar(this.radius).add(this.center); } return target2; } getBoundingBox(target2) { if (this.isEmpty()) { target2.makeEmpty(); return target2; } target2.set(this.center, this.center); target2.expandByScalar(this.radius); return target2; } applyMatrix4(matrix) { this.center.applyMatrix4(matrix); this.radius = this.radius * matrix.getMaxScaleOnAxis(); return this; } translate(offset) { this.center.add(offset); return this; } expandByPoint(point) { if (this.isEmpty()) { this.center.copy(point); this.radius = 0; return this; } _v1$6.subVectors(point, this.center); const lengthSq = _v1$6.lengthSq(); if (lengthSq > this.radius * this.radius) { const length = Math.sqrt(lengthSq); const delta = (length - this.radius) * 0.5; this.center.addScaledVector(_v1$6, delta / length); this.radius += delta; } return this; } union(sphere) { if (sphere.isEmpty()) { return this; } if (this.isEmpty()) { this.copy(sphere); return this; } if (this.center.equals(sphere.center) === true) { this.radius = Math.max(this.radius, sphere.radius); } else { _v2$3.subVectors(sphere.center, this.center).setLength(sphere.radius); this.expandByPoint(_v1$6.copy(sphere.center).add(_v2$3)); this.expandByPoint(_v1$6.copy(sphere.center).sub(_v2$3)); } return this; } equals(sphere) { return sphere.center.equals(this.center) && sphere.radius === this.radius; } clone() { return new this.constructor().copy(this); } }; var _vector$a = new Vector3(); var _segCenter = new Vector3(); var _segDir = new Vector3(); var _diff = new Vector3(); var _edge1 = new Vector3(); var _edge2 = new Vector3(); var _normal$1 = new Vector3(); var Ray = class { constructor(origin = new Vector3(), direction = new Vector3(0, 0, -1)) { this.origin = origin; this.direction = direction; } set(origin, direction) { this.origin.copy(origin); this.direction.copy(direction); return this; } copy(ray) { this.origin.copy(ray.origin); this.direction.copy(ray.direction); return this; } at(t2, target2) { return target2.copy(this.direction).multiplyScalar(t2).add(this.origin); } lookAt(v) { this.direction.copy(v).sub(this.origin).normalize(); return this; } recast(t2) { this.origin.copy(this.at(t2, _vector$a)); return this; } closestPointToPoint(point, target2) { target2.subVectors(point, this.origin); const directionDistance = target2.dot(this.direction); if (directionDistance < 0) { return target2.copy(this.origin); } return target2.copy(this.direction).multiplyScalar(directionDistance).add(this.origin); } distanceToPoint(point) { return Math.sqrt(this.distanceSqToPoint(point)); } distanceSqToPoint(point) { const directionDistance = _vector$a.subVectors(point, this.origin).dot(this.direction); if (directionDistance < 0) { return this.origin.distanceToSquared(point); } _vector$a.copy(this.direction).multiplyScalar(directionDistance).add(this.origin); return _vector$a.distanceToSquared(point); } distanceSqToSegment(v0, v1, optionalPointOnRay, optionalPointOnSegment) { _segCenter.copy(v0).add(v1).multiplyScalar(0.5); _segDir.copy(v1).sub(v0).normalize(); _diff.copy(this.origin).sub(_segCenter); const segExtent = v0.distanceTo(v1) * 0.5; const a01 = -this.direction.dot(_segDir); const b0 = _diff.dot(this.direction); const b1 = -_diff.dot(_segDir); const c = _diff.lengthSq(); const det = Math.abs(1 - a01 * a01); let s0, s1, sqrDist, extDet; if (det > 0) { s0 = a01 * b1 - b0; s1 = a01 * b0 - b1; extDet = segExtent * det; if (s0 >= 0) { if (s1 >= -extDet) { if (s1 <= extDet) { const invDet = 1 / det; s0 *= invDet; s1 *= invDet; sqrDist = s0 * (s0 + a01 * s1 + 2 * b0) + s1 * (a01 * s0 + s1 + 2 * b1) + c; } else { s1 = segExtent; s0 = Math.max(0, -(a01 * s1 + b0)); sqrDist = -s0 * s0 + s1 * (s1 + 2 * b1) + c; } } else { s1 = -segExtent; s0 = Math.max(0, -(a01 * s1 + b0)); sqrDist = -s0 * s0 + s1 * (s1 + 2 * b1) + c; } } else { if (s1 <= -extDet) { s0 = Math.max(0, -(-a01 * segExtent + b0)); s1 = s0 > 0 ? -segExtent : Math.min(Math.max(-segExtent, -b1), segExtent); sqrDist = -s0 * s0 + s1 * (s1 + 2 * b1) + c; } else if (s1 <= extDet) { s0 = 0; s1 = Math.min(Math.max(-segExtent, -b1), segExtent); sqrDist = s1 * (s1 + 2 * b1) + c; } else { s0 = Math.max(0, -(a01 * segExtent + b0)); s1 = s0 > 0 ? segExtent : Math.min(Math.max(-segExtent, -b1), segExtent); sqrDist = -s0 * s0 + s1 * (s1 + 2 * b1) + c; } } } else { s1 = a01 > 0 ? -segExtent : segExtent; s0 = Math.max(0, -(a01 * s1 + b0)); sqrDist = -s0 * s0 + s1 * (s1 + 2 * b1) + c; } if (optionalPointOnRay) { optionalPointOnRay.copy(this.direction).multiplyScalar(s0).add(this.origin); } if (optionalPointOnSegment) { optionalPointOnSegment.copy(_segDir).multiplyScalar(s1).add(_segCenter); } return sqrDist; } intersectSphere(sphere, target2) { _vector$a.subVectors(sphere.center, this.origin); const tca = _vector$a.dot(this.direction); const d2 = _vector$a.dot(_vector$a) - tca * tca; const radius2 = sphere.radius * sphere.radius; if (d2 > radius2) return null; const thc = Math.sqrt(radius2 - d2); const t0 = tca - thc; const t1 = tca + thc; if (t0 < 0 && t1 < 0) return null; if (t0 < 0) return this.at(t1, target2); return this.at(t0, target2); } intersectsSphere(sphere) { return this.distanceSqToPoint(sphere.center) <= sphere.radius * sphere.radius; } distanceToPlane(plane) { const denominator = plane.normal.dot(this.direction); if (denominator === 0) { if (plane.distanceToPoint(this.origin) === 0) { return 0; } return null; } const t2 = -(this.origin.dot(plane.normal) + plane.constant) / denominator; return t2 >= 0 ? t2 : null; } intersectPlane(plane, target2) { const t2 = this.distanceToPlane(plane); if (t2 === null) { return null; } return this.at(t2, target2); } intersectsPlane(plane) { const distToPoint = plane.distanceToPoint(this.origin); if (distToPoint === 0) { return true; } const denominator = plane.normal.dot(this.direction); if (denominator * distToPoint < 0) { return true; } return false; } intersectBox(box, target2) { let tmin, tmax, tymin, tymax, tzmin, tzmax; const invdirx = 1 / this.direction.x, invdiry = 1 / this.direction.y, invdirz = 1 / this.direction.z; const origin = this.origin; if (invdirx >= 0) { tmin = (box.min.x - origin.x) * invdirx; tmax = (box.max.x - origin.x) * invdirx; } else { tmin = (box.max.x - origin.x) * invdirx; tmax = (box.min.x - origin.x) * invdirx; } if (invdiry >= 0) { tymin = (box.min.y - origin.y) * invdiry; tymax = (box.max.y - origin.y) * invdiry; } else { tymin = (box.max.y - origin.y) * invdiry; tymax = (box.min.y - origin.y) * invdiry; } if (tmin > tymax || tymin > tmax) return null; if (tymin > tmin || isNaN(tmin)) tmin = tymin; if (tymax < tmax || isNaN(tmax)) tmax = tymax; if (invdirz >= 0) { tzmin = (box.min.z - origin.z) * invdirz; tzmax = (box.max.z - origin.z) * invdirz; } else { tzmin = (box.max.z - origin.z) * invdirz; tzmax = (box.min.z - origin.z) * invdirz; } if (tmin > tzmax || tzmin > tmax) return null; if (tzmin > tmin || tmin !== tmin) tmin = tzmin; if (tzmax < tmax || tmax !== tmax) tmax = tzmax; if (tmax < 0) return null; return this.at(tmin >= 0 ? tmin : tmax, target2); } intersectsBox(box) { return this.intersectBox(box, _vector$a) !== null; } intersectTriangle(a, b, c, backfaceCulling, target2) { _edge1.subVectors(b, a); _edge2.subVectors(c, a); _normal$1.crossVectors(_edge1, _edge2); let DdN = this.direction.dot(_normal$1); let sign2; if (DdN > 0) { if (backfaceCulling) return null; sign2 = 1; } else if (DdN < 0) { sign2 = -1; DdN = -DdN; } else { return null; } _diff.subVectors(this.origin, a); const DdQxE2 = sign2 * this.direction.dot(_edge2.crossVectors(_diff, _edge2)); if (DdQxE2 < 0) { return null; } const DdE1xQ = sign2 * this.direction.dot(_edge1.cross(_diff)); if (DdE1xQ < 0) { return null; } if (DdQxE2 + DdE1xQ > DdN) { return null; } const QdN = -sign2 * _diff.dot(_normal$1); if (QdN < 0) { return null; } return this.at(QdN / DdN, target2); } applyMatrix4(matrix42) { this.origin.applyMatrix4(matrix42); this.direction.transformDirection(matrix42); return this; } equals(ray) { return ray.origin.equals(this.origin) && ray.direction.equals(this.direction); } clone() { return new this.constructor().copy(this); } }; var Matrix4 = class _Matrix4 { constructor() { _Matrix4.prototype.isMatrix4 = true; this.elements = [ 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1 ]; } set(n11, n12, n13, n14, n21, n22, n23, n24, n31, n32, n33, n34, n41, n42, n43, n44) { const te2 = this.elements; te2[0] = n11; te2[4] = n12; te2[8] = n13; te2[12] = n14; te2[1] = n21; te2[5] = n22; te2[9] = n23; te2[13] = n24; te2[2] = n31; te2[6] = n32; te2[10] = n33; te2[14] = n34; te2[3] = n41; te2[7] = n42; te2[11] = n43; te2[15] = n44; return this; } identity() { this.set( 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1 ); return this; } clone() { return new _Matrix4().fromArray(this.elements); } copy(m) { const te2 = this.elements; const me = m.elements; te2[0] = me[0]; te2[1] = me[1]; te2[2] = me[2]; te2[3] = me[3]; te2[4] = me[4]; te2[5] = me[5]; te2[6] = me[6]; te2[7] = me[7]; te2[8] = me[8]; te2[9] = me[9]; te2[10] = me[10]; te2[11] = me[11]; te2[12] = me[12]; te2[13] = me[13]; te2[14] = me[14]; te2[15] = me[15]; return this; } copyPosition(m) { const te2 = this.elements, me = m.elements; te2[12] = me[12]; te2[13] = me[13]; te2[14] = me[14]; return this; } setFromMatrix3(m) { const me = m.elements; this.set( me[0], me[3], me[6], 0, me[1], me[4], me[7], 0, me[2], me[5], me[8], 0, 0, 0, 0, 1 ); return this; } extractBasis(xAxis, yAxis, zAxis) { xAxis.setFromMatrixColumn(this, 0); yAxis.setFromMatrixColumn(this, 1); zAxis.setFromMatrixColumn(this, 2); return this; } makeBasis(xAxis, yAxis, zAxis) { this.set( xAxis.x, yAxis.x, zAxis.x, 0, xAxis.y, yAxis.y, zAxis.y, 0, xAxis.z, yAxis.z, zAxis.z, 0, 0, 0, 0, 1 ); return this; } extractRotation(m) { const te2 = this.elements; const me = m.elements; const scaleX = 1 / _v1$5.setFromMatrixColumn(m, 0).length(); const scaleY = 1 / _v1$5.setFromMatrixColumn(m, 1).length(); const scaleZ = 1 / _v1$5.setFromMatrixColumn(m, 2).length(); te2[0] = me[0] * scaleX; te2[1] = me[1] * scaleX; te2[2] = me[2] * scaleX; te2[3] = 0; te2[4] = me[4] * scaleY; te2[5] = me[5] * scaleY; te2[6] = me[6] * scaleY; te2[7] = 0; te2[8] = me[8] * scaleZ; te2[9] = me[9] * scaleZ; te2[10] = me[10] * scaleZ; te2[11] = 0; te2[12] = 0; te2[13] = 0; te2[14] = 0; te2[15] = 1; return this; } makeRotationFromEuler(euler) { const te2 = this.elements; const x2 = euler.x, y = euler.y, z = euler.z; const a = Math.cos(x2), b = Math.sin(x2); const c = Math.cos(y), d = Math.sin(y); const e = Math.cos(z), f = Math.sin(z); if (euler.order === "XYZ") { const ae = a * e, af = a * f, be = b * e, bf = b * f; te2[0] = c * e; te2[4] = -c * f; te2[8] = d; te2[1] = af + be * d; te2[5] = ae - bf * d; te2[9] = -b * c; te2[2] = bf - ae * d; te2[6] = be + af * d; te2[10] = a * c; } else if (euler.order === "YXZ") { const ce = c * e, cf = c * f, de2 = d * e, df = d * f; te2[0] = ce + df * b; te2[4] = de2 * b - cf; te2[8] = a * d; te2[1] = a * f; te2[5] = a * e; te2[9] = -b; te2[2] = cf * b - de2; te2[6] = df + ce * b; te2[10] = a * c; } else if (euler.order === "ZXY") { const ce = c * e, cf = c * f, de2 = d * e, df = d * f; te2[0] = ce - df * b; te2[4] = -a * f; te2[8] = de2 + cf * b; te2[1] = cf + de2 * b; te2[5] = a * e; te2[9] = df - ce * b; te2[2] = -a * d; te2[6] = b; te2[10] = a * c; } else if (euler.order === "ZYX") { const ae = a * e, af = a * f, be = b * e, bf = b * f; te2[0] = c * e; te2[4] = be * d - af; te2[8] = ae * d + bf; te2[1] = c * f; te2[5] = bf * d + ae; te2[9] = af * d - be; te2[2] = -d; te2[6] = b * c; te2[10] = a * c; } else if (euler.order === "YZX") { const ac = a * c, ad = a * d, bc = b * c, bd = b * d; te2[0] = c * e; te2[4] = bd - ac * f; te2[8] = bc * f + ad; te2[1] = f; te2[5] = a * e; te2[9] = -b * e; te2[2] = -d * e; te2[6] = ad * f + bc; te2[10] = ac - bd * f; } else if (euler.order === "XZY") { const ac = a * c, ad = a * d, bc = b * c, bd = b * d; te2[0] = c * e; te2[4] = -f; te2[8] = d * e; te2[1] = ac * f + bd; te2[5] = a * e; te2[9] = ad * f - bc; te2[2] = bc * f - ad; te2[6] = b * e; te2[10] = bd * f + ac; } te2[3] = 0; te2[7] = 0; te2[11] = 0; te2[12] = 0; te2[13] = 0; te2[14] = 0; te2[15] = 1; return this; } makeRotationFromQuaternion(q) { return this.compose(_zero, q, _one); } lookAt(eye, target2, up) { const te2 = this.elements; _z.subVectors(eye, target2); if (_z.lengthSq() === 0) { _z.z = 1; } _z.normalize(); _x.crossVectors(up, _z); if (_x.lengthSq() === 0) { if (Math.abs(up.z) === 1) { _z.x += 1e-4; } else { _z.z += 1e-4; } _z.normalize(); _x.crossVectors(up, _z); } _x.normalize(); _y.crossVectors(_z, _x); te2[0] = _x.x; te2[4] = _y.x; te2[8] = _z.x; te2[1] = _x.y; te2[5] = _y.y; te2[9] = _z.y; te2[2] = _x.z; te2[6] = _y.z; te2[10] = _z.z; return this; } multiply(m) { return this.multiplyMatrices(this, m); } premultiply(m) { return this.multiplyMatrices(m, this); } multiplyMatrices(a, b) { const ae = a.elements; const be = b.elements; const te2 = this.elements; const a11 = ae[0], a12 = ae[4], a13 = ae[8], a14 = ae[12]; const a21 = ae[1], a22 = ae[5], a23 = ae[9], a24 = ae[13]; const a31 = ae[2], a32 = ae[6], a33 = ae[10], a34 = ae[14]; const a41 = ae[3], a42 = ae[7], a43 = ae[11], a44 = ae[15]; const b11 = be[0], b12 = be[4], b13 = be[8], b14 = be[12]; const b21 = be[1], b22 = be[5], b23 = be[9], b24 = be[13]; const b31 = be[2], b32 = be[6], b33 = be[10], b34 = be[14]; const b41 = be[3], b42 = be[7], b43 = be[11], b44 = be[15]; te2[0] = a11 * b11 + a12 * b21 + a13 * b31 + a14 * b41; te2[4] = a11 * b12 + a12 * b22 + a13 * b32 + a14 * b42; te2[8] = a11 * b13 + a12 * b23 + a13 * b33 + a14 * b43; te2[12] = a11 * b14 + a12 * b24 + a13 * b34 + a14 * b44; te2[1] = a21 * b11 + a22 * b21 + a23 * b31 + a24 * b41; te2[5] = a21 * b12 + a22 * b22 + a23 * b32 + a24 * b42; te2[9] = a21 * b13 + a22 * b23 + a23 * b33 + a24 * b43; te2[13] = a21 * b14 + a22 * b24 + a23 * b34 + a24 * b44; te2[2] = a31 * b11 + a32 * b21 + a33 * b31 + a34 * b41; te2[6] = a31 * b12 + a32 * b22 + a33 * b32 + a34 * b42; te2[10] = a31 * b13 + a32 * b23 + a33 * b33 + a34 * b43; te2[14] = a31 * b14 + a32 * b24 + a33 * b34 + a34 * b44; te2[3] = a41 * b11 + a42 * b21 + a43 * b31 + a44 * b41; te2[7] = a41 * b12 + a42 * b22 + a43 * b32 + a44 * b42; te2[11] = a41 * b13 + a42 * b23 + a43 * b33 + a44 * b43; te2[15] = a41 * b14 + a42 * b24 + a43 * b34 + a44 * b44; return this; } multiplyScalar(s) { const te2 = this.elements; te2[0] *= s; te2[4] *= s; te2[8] *= s; te2[12] *= s; te2[1] *= s; te2[5] *= s; te2[9] *= s; te2[13] *= s; te2[2] *= s; te2[6] *= s; te2[10] *= s; te2[14] *= s; te2[3] *= s; te2[7] *= s; te2[11] *= s; te2[15] *= s; return this; } determinant() { const te2 = this.elements; const n11 = te2[0], n12 = te2[4], n13 = te2[8], n14 = te2[12]; const n21 = te2[1], n22 = te2[5], n23 = te2[9], n24 = te2[13]; const n31 = te2[2], n32 = te2[6], n33 = te2[10], n34 = te2[14]; const n41 = te2[3], n42 = te2[7], n43 = te2[11], n44 = te2[15]; return n41 * (+n14 * n23 * n32 - n13 * n24 * n32 - n14 * n22 * n33 + n12 * n24 * n33 + n13 * n22 * n34 - n12 * n23 * n34) + n42 * (+n11 * n23 * n34 - n11 * n24 * n33 + n14 * n21 * n33 - n13 * n21 * n34 + n13 * n24 * n31 - n14 * n23 * n31) + n43 * (+n11 * n24 * n32 - n11 * n22 * n34 - n14 * n21 * n32 + n12 * n21 * n34 + n14 * n22 * n31 - n12 * n24 * n31) + n44 * (-n13 * n22 * n31 - n11 * n23 * n32 + n11 * n22 * n33 + n13 * n21 * n32 - n12 * n21 * n33 + n12 * n23 * n31); } transpose() { const te2 = this.elements; let tmp2; tmp2 = te2[1]; te2[1] = te2[4]; te2[4] = tmp2; tmp2 = te2[2]; te2[2] = te2[8]; te2[8] = tmp2; tmp2 = te2[6]; te2[6] = te2[9]; te2[9] = tmp2; tmp2 = te2[3]; te2[3] = te2[12]; te2[12] = tmp2; tmp2 = te2[7]; te2[7] = te2[13]; te2[13] = tmp2; tmp2 = te2[11]; te2[11] = te2[14]; te2[14] = tmp2; return this; } setPosition(x2, y, z) { const te2 = this.elements; if (x2.isVector3) { te2[12] = x2.x; te2[13] = x2.y; te2[14] = x2.z; } else { te2[12] = x2; te2[13] = y; te2[14] = z; } return this; } invert() { const te2 = this.elements, n11 = te2[0], n21 = te2[1], n31 = te2[2], n41 = te2[3], n12 = te2[4], n22 = te2[5], n32 = te2[6], n42 = te2[7], n13 = te2[8], n23 = te2[9], n33 = te2[10], n43 = te2[11], n14 = te2[12], n24 = te2[13], n34 = te2[14], n44 = te2[15], t11 = n23 * n34 * n42 - n24 * n33 * n42 + n24 * n32 * n43 - n22 * n34 * n43 - n23 * n32 * n44 + n22 * n33 * n44, t12 = n14 * n33 * n42 - n13 * n34 * n42 - n14 * n32 * n43 + n12 * n34 * n43 + n13 * n32 * n44 - n12 * n33 * n44, t13 = n13 * n24 * n42 - n14 * n23 * n42 + n14 * n22 * n43 - n12 * n24 * n43 - n13 * n22 * n44 + n12 * n23 * n44, t14 = n14 * n23 * n32 - n13 * n24 * n32 - n14 * n22 * n33 + n12 * n24 * n33 + n13 * n22 * n34 - n12 * n23 * n34; const det = n11 * t11 + n21 * t12 + n31 * t13 + n41 * t14; if (det === 0) return this.set(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0); const detInv = 1 / det; te2[0] = t11 * detInv; te2[1] = (n24 * n33 * n41 - n23 * n34 * n41 - n24 * n31 * n43 + n21 * n34 * n43 + n23 * n31 * n44 - n21 * n33 * n44) * detInv; te2[2] = (n22 * n34 * n41 - n24 * n32 * n41 + n24 * n31 * n42 - n21 * n34 * n42 - n22 * n31 * n44 + n21 * n32 * n44) * detInv; te2[3] = (n23 * n32 * n41 - n22 * n33 * n41 - n23 * n31 * n42 + n21 * n33 * n42 + n22 * n31 * n43 - n21 * n32 * n43) * detInv; te2[4] = t12 * detInv; te2[5] = (n13 * n34 * n41 - n14 * n33 * n41 + n14 * n31 * n43 - n11 * n34 * n43 - n13 * n31 * n44 + n11 * n33 * n44) * detInv; te2[6] = (n14 * n32 * n41 - n12 * n34 * n41 - n14 * n31 * n42 + n11 * n34 * n42 + n12 * n31 * n44 - n11 * n32 * n44) * detInv; te2[7] = (n12 * n33 * n41 - n13 * n32 * n41 + n13 * n31 * n42 - n11 * n33 * n42 - n12 * n31 * n43 + n11 * n32 * n43) * detInv; te2[8] = t13 * detInv; te2[9] = (n14 * n23 * n41 - n13 * n24 * n41 - n14 * n21 * n43 + n11 * n24 * n43 + n13 * n21 * n44 - n11 * n23 * n44) * detInv; te2[10] = (n12 * n24 * n41 - n14 * n22 * n41 + n14 * n21 * n42 - n11 * n24 * n42 - n12 * n21 * n44 + n11 * n22 * n44) * detInv; te2[11] = (n13 * n22 * n41 - n12 * n23 * n41 - n13 * n21 * n42 + n11 * n23 * n42 + n12 * n21 * n43 - n11 * n22 * n43) * detInv; te2[12] = t14 * detInv; te2[13] = (n13 * n24 * n31 - n14 * n23 * n31 + n14 * n21 * n33 - n11 * n24 * n33 - n13 * n21 * n34 + n11 * n23 * n34) * detInv; te2[14] = (n14 * n22 * n31 - n12 * n24 * n31 - n14 * n21 * n32 + n11 * n24 * n32 + n12 * n21 * n34 - n11 * n22 * n34) * detInv; te2[15] = (n12 * n23 * n31 - n13 * n22 * n31 + n13 * n21 * n32 - n11 * n23 * n32 - n12 * n21 * n33 + n11 * n22 * n33) * detInv; return this; } scale(v) { const te2 = this.elements; const x2 = v.x, y = v.y, z = v.z; te2[0] *= x2; te2[4] *= y; te2[8] *= z; te2[1] *= x2; te2[5] *= y; te2[9] *= z; te2[2] *= x2; te2[6] *= y; te2[10] *= z; te2[3] *= x2; te2[7] *= y; te2[11] *= z; return this; } getMaxScaleOnAxis() { const te2 = this.elements; const scaleXSq = te2[0] * te2[0] + te2[1] * te2[1] + te2[2] * te2[2]; const scaleYSq = te2[4] * te2[4] + te2[5] * te2[5] + te2[6] * te2[6]; const scaleZSq = te2[8] * te2[8] + te2[9] * te2[9] + te2[10] * te2[10]; return Math.sqrt(Math.max(scaleXSq, scaleYSq, scaleZSq)); } makeTranslation(x2, y, z) { this.set( 1, 0, 0, x2, 0, 1, 0, y, 0, 0, 1, z, 0, 0, 0, 1 ); return this; } makeRotationX(theta) { const c = Math.cos(theta), s = Math.sin(theta); this.set( 1, 0, 0, 0, 0, c, -s, 0, 0, s, c, 0, 0, 0, 0, 1 ); return this; } makeRotationY(theta) { const c = Math.cos(theta), s = Math.sin(theta); this.set( c, 0, s, 0, 0, 1, 0, 0, -s, 0, c, 0, 0, 0, 0, 1 ); return this; } makeRotationZ(theta) { const c = Math.cos(theta), s = Math.sin(theta); this.set( c, -s, 0, 0, s, c, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1 ); return this; } makeRotationAxis(axis, angle) { const c = Math.cos(angle); const s = Math.sin(angle); const t2 = 1 - c; const x2 = axis.x, y = axis.y, z = axis.z; const tx = t2 * x2, ty = t2 * y; this.set( tx * x2 + c, tx * y - s * z, tx * z + s * y, 0, tx * y + s * z, ty * y + c, ty * z - s * x2, 0, tx * z - s * y, ty * z + s * x2, t2 * z * z + c, 0, 0, 0, 0, 1 ); return this; } makeScale(x2, y, z) { this.set( x2, 0, 0, 0, 0, y, 0, 0, 0, 0, z, 0, 0, 0, 0, 1 ); return this; } makeShear(xy, xz, yx, yz, zx, zy) { this.set( 1, yx, zx, 0, xy, 1, zy, 0, xz, yz, 1, 0, 0, 0, 0, 1 ); return this; } compose(position, quaternion, scale) { const te2 = this.elements; const x2 = quaternion._x, y = quaternion._y, z = quaternion._z, w = quaternion._w; const x22 = x2 + x2, y2 = y + y, z2 = z + z; const xx = x2 * x22, xy = x2 * y2, xz = x2 * z2; const yy = y * y2, yz = y * z2, zz = z * z2; const wx = w * x22, wy = w * y2, wz = w * z2; const sx = scale.x, sy = scale.y, sz = scale.z; te2[0] = (1 - (yy + zz)) * sx; te2[1] = (xy + wz) * sx; te2[2] = (xz - wy) * sx; te2[3] = 0; te2[4] = (xy - wz) * sy; te2[5] = (1 - (xx + zz)) * sy; te2[6] = (yz + wx) * sy; te2[7] = 0; te2[8] = (xz + wy) * sz; te2[9] = (yz - wx) * sz; te2[10] = (1 - (xx + yy)) * sz; te2[11] = 0; te2[12] = position.x; te2[13] = position.y; te2[14] = position.z; te2[15] = 1; return this; } decompose(position, quaternion, scale) { const te2 = this.elements; let sx = _v1$5.set(te2[0], te2[1], te2[2]).length(); const sy = _v1$5.set(te2[4], te2[5], te2[6]).length(); const sz = _v1$5.set(te2[8], te2[9], te2[10]).length(); const det = this.determinant(); if (det < 0) sx = -sx; position.x = te2[12]; position.y = te2[13]; position.z = te2[14]; _m1$2.copy(this); const invSX = 1 / sx; const invSY = 1 / sy; const invSZ = 1 / sz; _m1$2.elements[0] *= invSX; _m1$2.elements[1] *= invSX; _m1$2.elements[2] *= invSX; _m1$2.elements[4] *= invSY; _m1$2.elements[5] *= invSY; _m1$2.elements[6] *= invSY; _m1$2.elements[8] *= invSZ; _m1$2.elements[9] *= invSZ; _m1$2.elements[10] *= invSZ; quaternion.setFromRotationMatrix(_m1$2); scale.x = sx; scale.y = sy; scale.z = sz; return this; } makePerspective(left, right, top, bottom, near, far) { const te2 = this.elements; const x2 = 2 * near / (right - left); const y = 2 * near / (top - bottom); const a = (right + left) / (right - left); const b = (top + bottom) / (top - bottom); const c = -(far + near) / (far - near); const d = -2 * far * near / (far - near); te2[0] = x2; te2[4] = 0; te2[8] = a; te2[12] = 0; te2[1] = 0; te2[5] = y; te2[9] = b; te2[13] = 0; te2[2] = 0; te2[6] = 0; te2[10] = c; te2[14] = d; te2[3] = 0; te2[7] = 0; te2[11] = -1; te2[15] = 0; return this; } makeOrthographic(left, right, top, bottom, near, far) { const te2 = this.elements; const w = 1 / (right - left); const h = 1 / (top - bottom); const p2 = 1 / (far - near); const x2 = (right + left) * w; const y = (top + bottom) * h; const z = (far + near) * p2; te2[0] = 2 * w; te2[4] = 0; te2[8] = 0; te2[12] = -x2; te2[1] = 0; te2[5] = 2 * h; te2[9] = 0; te2[13] = -y; te2[2] = 0; te2[6] = 0; te2[10] = -2 * p2; te2[14] = -z; te2[3] = 0; te2[7] = 0; te2[11] = 0; te2[15] = 1; return this; } equals(matrix) { const te2 = this.elements; const me = matrix.elements; for (let i = 0; i < 16; i++) { if (te2[i] !== me[i]) return false; } return true; } fromArray(array, offset = 0) { for (let i = 0; i < 16; i++) { this.elements[i] = array[i + offset]; } return this; } toArray(array = [], offset = 0) { const te2 = this.elements; array[offset] = te2[0]; array[offset + 1] = te2[1]; array[offset + 2] = te2[2]; array[offset + 3] = te2[3]; array[offset + 4] = te2[4]; array[offset + 5] = te2[5]; array[offset + 6] = te2[6]; array[offset + 7] = te2[7]; array[offset + 8] = te2[8]; array[offset + 9] = te2[9]; array[offset + 10] = te2[10]; array[offset + 11] = te2[11]; array[offset + 12] = te2[12]; array[offset + 13] = te2[13]; array[offset + 14] = te2[14]; array[offset + 15] = te2[15]; return array; } }; var _v1$5 = new Vector3(); var _m1$2 = new Matrix4(); var _zero = new Vector3(0, 0, 0); var _one = new Vector3(1, 1, 1); var _x = new Vector3(); var _y = new Vector3(); var _z = new Vector3(); var _matrix$1 = new Matrix4(); var _quaternion$3 = new Quaternion(); var Euler = class _Euler { constructor(x2 = 0, y = 0, z = 0, order = _Euler.DefaultOrder) { this.isEuler = true; this._x = x2; this._y = y; this._z = z; this._order = order; } get x() { return this._x; } set x(value) { this._x = value; this._onChangeCallback(); } get y() { return this._y; } set y(value) { this._y = value; this._onChangeCallback(); } get z() { return this._z; } set z(value) { this._z = value; this._onChangeCallback(); } get order() { return this._order; } set order(value) { this._order = value; this._onChangeCallback(); } set(x2, y, z, order = this._order) { this._x = x2; this._y = y; this._z = z; this._order = order; this._onChangeCallback(); return this; } clone() { return new this.constructor(this._x, this._y, this._z, this._order); } copy(euler) { this._x = euler._x; this._y = euler._y; this._z = euler._z; this._order = euler._order; this._onChangeCallback(); return this; } setFromRotationMatrix(m, order = this._order, update = true) { const te2 = m.elements; const m11 = te2[0], m12 = te2[4], m13 = te2[8]; const m21 = te2[1], m22 = te2[5], m23 = te2[9]; const m31 = te2[2], m32 = te2[6], m33 = te2[10]; switch (order) { case "XYZ": this._y = Math.asin(clamp(m13, -1, 1)); if (Math.abs(m13) < 0.9999999) { this._x = Math.atan2(-m23, m33); this._z = Math.atan2(-m12, m11); } else { this._x = Math.atan2(m32, m22); this._z = 0; } break; case "YXZ": this._x = Math.asin(-clamp(m23, -1, 1)); if (Math.abs(m23) < 0.9999999) { this._y = Math.atan2(m13, m33); this._z = Math.atan2(m21, m22); } else { this._y = Math.atan2(-m31, m11); this._z = 0; } break; case "ZXY": this._x = Math.asin(clamp(m32, -1, 1)); if (Math.abs(m32) < 0.9999999) { this._y = Math.atan2(-m31, m33); this._z = Math.atan2(-m12, m22); } else { this._y = 0; this._z = Math.atan2(m21, m11); } break; case "ZYX": this._y = Math.asin(-clamp(m31, -1, 1)); if (Math.abs(m31) < 0.9999999) { this._x = Math.atan2(m32, m33); this._z = Math.atan2(m21, m11); } else { this._x = 0; this._z = Math.atan2(-m12, m22); } break; case "YZX": this._z = Math.asin(clamp(m21, -1, 1)); if (Math.abs(m21) < 0.9999999) { this._x = Math.atan2(-m23, m22); this._y = Math.atan2(-m31, m11); } else { this._x = 0; this._y = Math.atan2(m13, m33); } break; case "XZY": this._z = Math.asin(-clamp(m12, -1, 1)); if (Math.abs(m12) < 0.9999999) { this._x = Math.atan2(m32, m22); this._y = Math.atan2(m13, m11); } else { this._x = Math.atan2(-m23, m33); this._y = 0; } break; default: console.warn("THREE.Euler: .setFromRotationMatrix() encountered an unknown order: " + order); } this._order = order; if (update === true) this._onChangeCallback(); return this; } setFromQuaternion(q, order, update) { _matrix$1.makeRotationFromQuaternion(q); return this.setFromRotationMatrix(_matrix$1, order, update); } setFromVector3(v, order = this._order) { return this.set(v.x, v.y, v.z, order); } reorder(newOrder) { _quaternion$3.setFromEuler(this); return this.setFromQuaternion(_quaternion$3, newOrder); } equals(euler) { return euler._x === this._x && euler._y === this._y && euler._z === this._z && euler._order === this._order; } fromArray(array) { this._x = array[0]; this._y = array[1]; this._z = array[2]; if (array[3] !== void 0) this._order = array[3]; this._onChangeCallback(); return this; } toArray(array = [], offset = 0) { array[offset] = this._x; array[offset + 1] = this._y; array[offset + 2] = this._z; array[offset + 3] = this._order; return array; } _onChange(callback) { this._onChangeCallback = callback; return this; } _onChangeCallback() { } *[Symbol.iterator]() { yield this._x; yield this._y; yield this._z; yield this._order; } // @deprecated since r138, 02cf0df1cb4575d5842fef9c85bb5a89fe020d53 toVector3() { console.error("THREE.Euler: .toVector3() has been removed. Use Vector3.setFromEuler() instead"); } }; Euler.DefaultOrder = "XYZ"; Euler.RotationOrders = ["XYZ", "YZX", "ZXY", "XZY", "YXZ", "ZYX"]; var Layers = class { constructor() { this.mask = 1 | 0; } set(channel) { this.mask = (1 << channel | 0) >>> 0; } enable(channel) { this.mask |= 1 << channel | 0; } enableAll() { this.mask = 4294967295 | 0; } toggle(channel) { this.mask ^= 1 << channel | 0; } disable(channel) { this.mask &= ~(1 << channel | 0); } disableAll() { this.mask = 0; } test(layers) { return (this.mask & layers.mask) !== 0; } isEnabled(channel) { return (this.mask & (1 << channel | 0)) !== 0; } }; var _object3DId = 0; var _v1$4 = new Vector3(); var _q1 = new Quaternion(); var _m1$1 = new Matrix4(); var _target = new Vector3(); var _position$3 = new Vector3(); var _scale$2 = new Vector3(); var _quaternion$2 = new Quaternion(); var _xAxis = new Vector3(1, 0, 0); var _yAxis = new Vector3(0, 1, 0); var _zAxis = new Vector3(0, 0, 1); var _addedEvent = { type: "added" }; var _removedEvent = { type: "removed" }; var Object3D = class _Object3D extends EventDispatcher { constructor() { super(); this.isObject3D = true; Object.defineProperty(this, "id", { value: _object3DId++ }); this.uuid = generateUUID(); this.name = ""; this.type = "Object3D"; this.parent = null; this.children = []; this.up = _Object3D.DefaultUp.clone(); const position = new Vector3(); const rotation = new Euler(); const quaternion = new Quaternion(); const scale = new Vector3(1, 1, 1); function onRotationChange() { quaternion.setFromEuler(rotation, false); } function onQuaternionChange() { rotation.setFromQuaternion(quaternion, void 0, false); } rotation._onChange(onRotationChange); quaternion._onChange(onQuaternionChange); Object.defineProperties(this, { position: { configurable: true, enumerable: true, value: position }, rotation: { configurable: true, enumerable: true, value: rotation }, quaternion: { configurable: true, enumerable: true, value: quaternion }, scale: { configurable: true, enumerable: true, value: scale }, modelViewMatrix: { value: new Matrix4() }, normalMatrix: { value: new Matrix3() } }); this.matrix = new Matrix4(); this.matrixWorld = new Matrix4(); this.matrixAutoUpdate = _Object3D.DefaultMatrixAutoUpdate; this.matrixWorldNeedsUpdate = false; this.matrixWorldAutoUpdate = _Object3D.DefaultMatrixWorldAutoUpdate; this.layers = new Layers(); this.visible = true; this.castShadow = false; this.receiveShadow = false; this.frustumCulled = true; this.renderOrder = 0; this.animations = []; this.userData = {}; } onBeforeRender() { } onAfterRender() { } applyMatrix4(matrix) { if (this.matrixAutoUpdate) this.updateMatrix(); this.matrix.premultiply(matrix); this.matrix.decompose(this.position, this.quaternion, this.scale); } applyQuaternion(q) { this.quaternion.premultiply(q); return this; } setRotationFromAxisAngle(axis, angle) { this.quaternion.setFromAxisAngle(axis, angle); } setRotationFromEuler(euler) { this.quaternion.setFromEuler(euler, true); } setRotationFromMatrix(m) { this.quaternion.setFromRotationMatrix(m); } setRotationFromQuaternion(q) { this.quaternion.copy(q); } rotateOnAxis(axis, angle) { _q1.setFromAxisAngle(axis, angle); this.quaternion.multiply(_q1); return this; } rotateOnWorldAxis(axis, angle) { _q1.setFromAxisAngle(axis, angle); this.quaternion.premultiply(_q1); return this; } rotateX(angle) { return this.rotateOnAxis(_xAxis, angle); } rotateY(angle) { return this.rotateOnAxis(_yAxis, angle); } rotateZ(angle) { return this.rotateOnAxis(_zAxis, angle); } translateOnAxis(axis, distance) { _v1$4.copy(axis).applyQuaternion(this.quaternion); this.position.add(_v1$4.multiplyScalar(distance)); return this; } translateX(distance) { return this.translateOnAxis(_xAxis, distance); } translateY(distance) { return this.translateOnAxis(_yAxis, distance); } translateZ(distance) { return this.translateOnAxis(_zAxis, distance); } localToWorld(vector) { return vector.applyMatrix4(this.matrixWorld); } worldToLocal(vector) { return vector.applyMatrix4(_m1$1.copy(this.matrixWorld).invert()); } lookAt(x2, y, z) { if (x2.isVector3) { _target.copy(x2); } else { _target.set(x2, y, z); } const parent = this.parent; this.updateWorldMatrix(true, false); _position$3.setFromMatrixPosition(this.matrixWorld); if (this.isCamera || this.isLight) { _m1$1.lookAt(_position$3, _target, this.up); } else { _m1$1.lookAt(_target, _position$3, this.up); } this.quaternion.setFromRotationMatrix(_m1$1); if (parent) { _m1$1.extractRotation(parent.matrixWorld); _q1.setFromRotationMatrix(_m1$1); this.quaternion.premultiply(_q1.invert()); } } add(object) { if (arguments.length > 1) { for (let i = 0; i < arguments.length; i++) { this.add(arguments[i]); } return this; } if (object === this) { console.error("THREE.Object3D.add: object can't be added as a child of itself.", object); return this; } if (object && object.isObject3D) { if (object.parent !== null) { object.parent.remove(object); } object.parent = this; this.children.push(object); object.dispatchEvent(_addedEvent); } else { console.error("THREE.Object3D.add: object not an instance of THREE.Object3D.", object); } return this; } remove(object) { if (arguments.length > 1) { for (let i = 0; i < arguments.length; i++) { this.remove(arguments[i]); } return this; } const index = this.children.indexOf(object); if (index !== -1) { object.parent = null; this.children.splice(index, 1); object.dispatchEvent(_removedEvent); } return this; } removeFromParent() { const parent = this.parent; if (parent !== null) { parent.remove(this); } return this; } clear() { for (let i = 0; i < this.children.length; i++) { const object = this.children[i]; object.parent = null; object.dispatchEvent(_removedEvent); } this.children.length = 0; return this; } attach(object) { this.updateWorldMatrix(true, false); _m1$1.copy(this.matrixWorld).invert(); if (object.parent !== null) { object.parent.updateWorldMatrix(true, false); _m1$1.multiply(object.parent.matrixWorld); } object.applyMatrix4(_m1$1); this.add(object); object.updateWorldMatrix(false, true); return this; } getObjectById(id) { return this.getObjectByProperty("id", id); } getObjectByName(name) { return this.getObjectByProperty("name", name); } getObjectByProperty(name, value) { if (this[name] === value) return this; for (let i = 0, l = this.children.length; i < l; i++) { const child = this.children[i]; const object = child.getObjectByProperty(name, value); if (object !== void 0) { return object; } } return void 0; } getWorldPosition(target2) { this.updateWorldMatrix(true, false); return target2.setFromMatrixPosition(this.matrixWorld); } getWorldQuaternion(target2) { this.updateWorldMatrix(true, false); this.matrixWorld.decompose(_position$3, target2, _scale$2); return target2; } getWorldScale(target2) { this.updateWorldMatrix(true, false); this.matrixWorld.decompose(_position$3, _quaternion$2, target2); return target2; } getWorldDirection(target2) { this.updateWorldMatrix(true, false); const e = this.matrixWorld.elements; return target2.set(e[8], e[9], e[10]).normalize(); } raycast() { } traverse(callback) { callback(this); const children = this.children; for (let i = 0, l = children.length; i < l; i++) { children[i].traverse(callback); } } traverseVisible(callback) { if (this.visible === false) return; callback(this); const children = this.children; for (let i = 0, l = children.length; i < l; i++) { children[i].traverseVisible(callback); } } traverseAncestors(callback) { const parent = this.parent; if (parent !== null) { callback(parent); parent.traverseAncestors(callback); } } updateMatrix() { this.matrix.compose(this.position, this.quaternion, this.scale); this.matrixWorldNeedsUpdate = true; } updateMatrixWorld(force) { if (this.matrixAutoUpdate) this.updateMatrix(); if (this.matrixWorldNeedsUpdate || force) { if (this.parent === null) { this.matrixWorld.copy(this.matrix); } else { this.matrixWorld.multiplyMatrices(this.parent.matrixWorld, this.matrix); } this.matrixWorldNeedsUpdate = false; force = true; } const children = this.children; for (let i = 0, l = children.length; i < l; i++) { const child = children[i]; if (child.matrixWorldAutoUpdate === true || force === true) { child.updateMatrixWorld(force); } } } updateWorldMatrix(updateParents, updateChildren) { const parent = this.parent; if (updateParents === true && parent !== null && parent.matrixWorldAutoUpdate === true) { parent.updateWorldMatrix(true, false); } if (this.matrixAutoUpdate) this.updateMatrix(); if (this.parent === null) { this.matrixWorld.copy(this.matrix); } else { this.matrixWorld.multiplyMatrices(this.parent.matrixWorld, this.matrix); } if (updateChildren === true) { const children = this.children; for (let i = 0, l = children.length; i < l; i++) { const child = children[i]; if (child.matrixWorldAutoUpdate === true) { child.updateWorldMatrix(false, true); } } } } toJSON(meta) { const isRootObject = meta === void 0 || typeof meta === "string"; const output = {}; if (isRootObject) { meta = { geometries: {}, materials: {}, textures: {}, images: {}, shapes: {}, skeletons: {}, animations: {}, nodes: {} }; output.metadata = { version: 4.5, type: "Object", generator: "Object3D.toJSON" }; } const object = {}; object.uuid = this.uuid; object.type = this.type; if (this.name !== "") object.name = this.name; if (this.castShadow === true) object.castShadow = true; if (this.receiveShadow === true) object.receiveShadow = true; if (this.visible === false) object.visible = false; if (this.frustumCulled === false) object.frustumCulled = false; if (this.renderOrder !== 0) object.renderOrder = this.renderOrder; if (JSON.stringify(this.userData) !== "{}") object.userData = this.userData; object.layers = this.layers.mask; object.matrix = this.matrix.toArray(); if (this.matrixAutoUpdate === false) object.matrixAutoUpdate = false; if (this.isInstancedMesh) { object.type = "InstancedMesh"; object.count = this.count; object.instanceMatrix = this.instanceMatrix.toJSON(); if (this.instanceColor !== null) object.instanceColor = this.instanceColor.toJSON(); } function serialize(library, element) { if (library[element.uuid] === void 0) { library[element.uuid] = element.toJSON(meta); } return element.uuid; } if (this.isScene) { if (this.background) { if (this.background.isColor) { object.background = this.background.toJSON(); } else if (this.background.isTexture) { object.background = this.background.toJSON(meta).uuid; } } if (this.environment && this.environment.isTexture && this.environment.isRenderTargetTexture !== true) { object.environment = this.environment.toJSON(meta).uuid; } } else if (this.isMesh || this.isLine || this.isPoints) { object.geometry = serialize(meta.geometries, this.geometry); const parameters = this.geometry.parameters; if (parameters !== void 0 && parameters.shapes !== void 0) { const shapes = parameters.shapes; if (Array.isArray(shapes)) { for (let i = 0, l = shapes.length; i < l; i++) { const shape = shapes[i]; serialize(meta.shapes, shape); } } else { serialize(meta.shapes, shapes); } } } if (this.isSkinnedMesh) { object.bindMode = this.bindMode; object.bindMatrix = this.bindMatrix.toArray(); if (this.skeleton !== void 0) { serialize(meta.skeletons, this.skeleton); object.skeleton = this.skeleton.uuid; } } if (this.material !== void 0) { if (Array.isArray(this.material)) { const uuids = []; for (let i = 0, l = this.material.length; i < l; i++) { uuids.push(serialize(meta.materials, this.material[i])); } object.material = uuids; } else { object.material = serialize(meta.materials, this.material); } } if (this.children.length > 0) { object.children = []; for (let i = 0; i < this.children.length; i++) { object.children.push(this.children[i].toJSON(meta).object); } } if (this.animations.length > 0) { object.animations = []; for (let i = 0; i < this.animations.length; i++) { const animation = this.animations[i]; object.animations.push(serialize(meta.animations, animation)); } } if (isRootObject) { const geometries = extractFromCache(meta.geometries); const materials = extractFromCache(meta.materials); const textures = extractFromCache(meta.textures); const images = extractFromCache(meta.images); const shapes = extractFromCache(meta.shapes); const skeletons = extractFromCache(meta.skeletons); const animations = extractFromCache(meta.animations); const nodes = extractFromCache(meta.nodes); if (geometries.length > 0) output.geometries = geometries; if (materials.length > 0) output.materials = materials; if (textures.length > 0) output.textures = textures; if (images.length > 0) output.images = images; if (shapes.length > 0) output.shapes = shapes; if (skeletons.length > 0) output.skeletons = skeletons; if (animations.length > 0) output.animations = animations; if (nodes.length > 0) output.nodes = nodes; } output.object = object; return output; function extractFromCache(cache2) { const values = []; for (const key in cache2) { const data = cache2[key]; delete data.metadata; values.push(data); } return values; } } clone(recursive) { return new this.constructor().copy(this, recursive); } copy(source, recursive = true) { this.name = source.name; this.up.copy(source.up); this.position.copy(source.position); this.rotation.order = source.rotation.order; this.quaternion.copy(source.quaternion); this.scale.copy(source.scale); this.matrix.copy(source.matrix); this.matrixWorld.copy(source.matrixWorld); this.matrixAutoUpdate = source.matrixAutoUpdate; this.matrixWorldNeedsUpdate = source.matrixWorldNeedsUpdate; this.matrixWorldAutoUpdate = source.matrixWorldAutoUpdate; this.layers.mask = source.layers.mask; this.visible = source.visible; this.castShadow = source.castShadow; this.receiveShadow = source.receiveShadow; this.frustumCulled = source.frustumCulled; this.renderOrder = source.renderOrder; this.userData = JSON.parse(JSON.stringify(source.userData)); if (recursive === true) { for (let i = 0; i < source.children.length; i++) { const child = source.children[i]; this.add(child.clone()); } } return this; } }; Object3D.DefaultUp = new Vector3(0, 1, 0); Object3D.DefaultMatrixAutoUpdate = true; Object3D.DefaultMatrixWorldAutoUpdate = true; var _v0$1 = new Vector3(); var _v1$3 = new Vector3(); var _v2$2 = new Vector3(); var _v3$1 = new Vector3(); var _vab = new Vector3(); var _vac = new Vector3(); var _vbc = new Vector3(); var _vap = new Vector3(); var _vbp = new Vector3(); var _vcp = new Vector3(); var Triangle = class _Triangle { constructor(a = new Vector3(), b = new Vector3(), c = new Vector3()) { this.a = a; this.b = b; this.c = c; } static getNormal(a, b, c, target2) { target2.subVectors(c, b); _v0$1.subVectors(a, b); target2.cross(_v0$1); const targetLengthSq = target2.lengthSq(); if (targetLengthSq > 0) { return target2.multiplyScalar(1 / Math.sqrt(targetLengthSq)); } return target2.set(0, 0, 0); } // static/instance method to calculate barycentric coordinates // based on: http://www.blackpawn.com/texts/pointinpoly/default.html static getBarycoord(point, a, b, c, target2) { _v0$1.subVectors(c, a); _v1$3.subVectors(b, a); _v2$2.subVectors(point, a); const dot00 = _v0$1.dot(_v0$1); const dot01 = _v0$1.dot(_v1$3); const dot02 = _v0$1.dot(_v2$2); const dot11 = _v1$3.dot(_v1$3); const dot12 = _v1$3.dot(_v2$2); const denom = dot00 * dot11 - dot01 * dot01; if (denom === 0) { return target2.set(-2, -1, -1); } const invDenom = 1 / denom; const u = (dot11 * dot02 - dot01 * dot12) * invDenom; const v = (dot00 * dot12 - dot01 * dot02) * invDenom; return target2.set(1 - u - v, v, u); } static containsPoint(point, a, b, c) { this.getBarycoord(point, a, b, c, _v3$1); return _v3$1.x >= 0 && _v3$1.y >= 0 && _v3$1.x + _v3$1.y <= 1; } static getUV(point, p1, p2, p3, uv1, uv2, uv3, target2) { this.getBarycoord(point, p1, p2, p3, _v3$1); target2.set(0, 0); target2.addScaledVector(uv1, _v3$1.x); target2.addScaledVector(uv2, _v3$1.y); target2.addScaledVector(uv3, _v3$1.z); return target2; } static isFrontFacing(a, b, c, direction) { _v0$1.subVectors(c, b); _v1$3.subVectors(a, b); return _v0$1.cross(_v1$3).dot(direction) < 0 ? true : false; } set(a, b, c) { this.a.copy(a); this.b.copy(b); this.c.copy(c); return this; } setFromPointsAndIndices(points, i0, i1, i2) { this.a.copy(points[i0]); this.b.copy(points[i1]); this.c.copy(points[i2]); return this; } setFromAttributeAndIndices(attribute, i0, i1, i2) { this.a.fromBufferAttribute(attribute, i0); this.b.fromBufferAttribute(attribute, i1); this.c.fromBufferAttribute(attribute, i2); return this; } clone() { return new this.constructor().copy(this); } copy(triangle) { this.a.copy(triangle.a); this.b.copy(triangle.b); this.c.copy(triangle.c); return this; } getArea() { _v0$1.subVectors(this.c, this.b); _v1$3.subVectors(this.a, this.b); return _v0$1.cross(_v1$3).length() * 0.5; } getMidpoint(target2) { return target2.addVectors(this.a, this.b).add(this.c).multiplyScalar(1 / 3); } getNormal(target2) { return _Triangle.getNormal(this.a, this.b, this.c, target2); } getPlane(target2) { return target2.setFromCoplanarPoints(this.a, this.b, this.c); } getBarycoord(point, target2) { return _Triangle.getBarycoord(point, this.a, this.b, this.c, target2); } getUV(point, uv1, uv2, uv3, target2) { return _Triangle.getUV(point, this.a, this.b, this.c, uv1, uv2, uv3, target2); } containsPoint(point) { return _Triangle.containsPoint(point, this.a, this.b, this.c); } isFrontFacing(direction) { return _Triangle.isFrontFacing(this.a, this.b, this.c, direction); } intersectsBox(box) { return box.intersectsTriangle(this); } closestPointToPoint(p2, target2) { const a = this.a, b = this.b, c = this.c; let v, w; _vab.subVectors(b, a); _vac.subVectors(c, a); _vap.subVectors(p2, a); const d1 = _vab.dot(_vap); const d2 = _vac.dot(_vap); if (d1 <= 0 && d2 <= 0) { return target2.copy(a); } _vbp.subVectors(p2, b); const d3 = _vab.dot(_vbp); const d4 = _vac.dot(_vbp); if (d3 >= 0 && d4 <= d3) { return target2.copy(b); } const vc = d1 * d4 - d3 * d2; if (vc <= 0 && d1 >= 0 && d3 <= 0) { v = d1 / (d1 - d3); return target2.copy(a).addScaledVector(_vab, v); } _vcp.subVectors(p2, c); const d5 = _vab.dot(_vcp); const d6 = _vac.dot(_vcp); if (d6 >= 0 && d5 <= d6) { return target2.copy(c); } const vb = d5 * d2 - d1 * d6; if (vb <= 0 && d2 >= 0 && d6 <= 0) { w = d2 / (d2 - d6); return target2.copy(a).addScaledVector(_vac, w); } const va = d3 * d6 - d5 * d4; if (va <= 0 && d4 - d3 >= 0 && d5 - d6 >= 0) { _vbc.subVectors(c, b); w = (d4 - d3) / (d4 - d3 + (d5 - d6)); return target2.copy(b).addScaledVector(_vbc, w); } const denom = 1 / (va + vb + vc); v = vb * denom; w = vc * denom; return target2.copy(a).addScaledVector(_vab, v).addScaledVector(_vac, w); } equals(triangle) { return triangle.a.equals(this.a) && triangle.b.equals(this.b) && triangle.c.equals(this.c); } }; var materialId = 0; var Material = class extends EventDispatcher { constructor() { super(); this.isMaterial = true; Object.defineProperty(this, "id", { value: materialId++ }); this.uuid = generateUUID(); this.name = ""; this.type = "Material"; this.blending = NormalBlending; this.side = FrontSide; this.vertexColors = false; this.opacity = 1; this.transparent = false; this.blendSrc = SrcAlphaFactor; this.blendDst = OneMinusSrcAlphaFactor; this.blendEquation = AddEquation; this.blendSrcAlpha = null; this.blendDstAlpha = null; this.blendEquationAlpha = null; this.depthFunc = LessEqualDepth; this.depthTest = true; this.depthWrite = true; this.stencilWriteMask = 255; this.stencilFunc = AlwaysStencilFunc; this.stencilRef = 0; this.stencilFuncMask = 255; this.stencilFail = KeepStencilOp; this.stencilZFail = KeepStencilOp; this.stencilZPass = KeepStencilOp; this.stencilWrite = false; this.clippingPlanes = null; this.clipIntersection = false; this.clipShadows = false; this.shadowSide = null; this.colorWrite = true; this.precision = null; this.polygonOffset = false; this.polygonOffsetFactor = 0; this.polygonOffsetUnits = 0; this.dithering = false; this.alphaToCoverage = false; this.premultipliedAlpha = false; this.visible = true; this.toneMapped = true; this.userData = {}; this.version = 0; this._alphaTest = 0; } get alphaTest() { return this._alphaTest; } set alphaTest(value) { if (this._alphaTest > 0 !== value > 0) { this.version++; } this._alphaTest = value; } onBuild() { } onBeforeRender() { } onBeforeCompile() { } customProgramCacheKey() { return this.onBeforeCompile.toString(); } setValues(values) { if (values === void 0) return; for (const key in values) { const newValue = values[key]; if (newValue === void 0) { console.warn("THREE.Material: '" + key + "' parameter is undefined."); continue; } const currentValue = this[key]; if (currentValue === void 0) { console.warn("THREE." + this.type + ": '" + key + "' is not a property of this material."); continue; } if (currentValue && currentValue.isColor) { currentValue.set(newValue); } else if (currentValue && currentValue.isVector3 && (newValue && newValue.isVector3)) { currentValue.copy(newValue); } else { this[key] = newValue; } } } toJSON(meta) { const isRootObject = meta === void 0 || typeof meta === "string"; if (isRootObject) { meta = { textures: {}, images: {} }; } const data = { metadata: { version: 4.5, type: "Material", generator: "Material.toJSON" } }; data.uuid = this.uuid; data.type = this.type; if (this.name !== "") data.name = this.name; if (this.color && this.color.isColor) data.color = this.color.getHex(); if (this.roughness !== void 0) data.roughness = this.roughness; if (this.metalness !== void 0) data.metalness = this.metalness; if (this.sheen !== void 0) data.sheen = this.sheen; if (this.sheenColor && this.sheenColor.isColor) data.sheenColor = this.sheenColor.getHex(); if (this.sheenRoughness !== void 0) data.sheenRoughness = this.sheenRoughness; if (this.emissive && this.emissive.isColor) data.emissive = this.emissive.getHex(); if (this.emissiveIntensity && this.emissiveIntensity !== 1) data.emissiveIntensity = this.emissiveIntensity; if (this.specular && this.specular.isColor) data.specular = this.specular.getHex(); if (this.specularIntensity !== void 0) data.specularIntensity = this.specularIntensity; if (this.specularColor && this.specularColor.isColor) data.specularColor = this.specularColor.getHex(); if (this.shininess !== void 0) data.shininess = this.shininess; if (this.clearcoat !== void 0) data.clearcoat = this.clearcoat; if (this.clearcoatRoughness !== void 0) data.clearcoatRoughness = this.clearcoatRoughness; if (this.clearcoatMap && this.clearcoatMap.isTexture) { data.clearcoatMap = this.clearcoatMap.toJSON(meta).uuid; } if (this.clearcoatRoughnessMap && this.clearcoatRoughnessMap.isTexture) { data.clearcoatRoughnessMap = this.clearcoatRoughnessMap.toJSON(meta).uuid; } if (this.clearcoatNormalMap && this.clearcoatNormalMap.isTexture) { data.clearcoatNormalMap = this.clearcoatNormalMap.toJSON(meta).uuid; data.clearcoatNormalScale = this.clearcoatNormalScale.toArray(); } if (this.iridescence !== void 0) data.iridescence = this.iridescence; if (this.iridescenceIOR !== void 0) data.iridescenceIOR = this.iridescenceIOR; if (this.iridescenceThicknessRange !== void 0) data.iridescenceThicknessRange = this.iridescenceThicknessRange; if (this.iridescenceMap && this.iridescenceMap.isTexture) { data.iridescenceMap = this.iridescenceMap.toJSON(meta).uuid; } if (this.iridescenceThicknessMap && this.iridescenceThicknessMap.isTexture) { data.iridescenceThicknessMap = this.iridescenceThicknessMap.toJSON(meta).uuid; } if (this.map && this.map.isTexture) data.map = this.map.toJSON(meta).uuid; if (this.matcap && this.matcap.isTexture) data.matcap = this.matcap.toJSON(meta).uuid; if (this.alphaMap && this.alphaMap.isTexture) data.alphaMap = this.alphaMap.toJSON(meta).uuid; if (this.lightMap && this.lightMap.isTexture) { data.lightMap = this.lightMap.toJSON(meta).uuid; data.lightMapIntensity = this.lightMapIntensity; } if (this.aoMap && this.aoMap.isTexture) { data.aoMap = this.aoMap.toJSON(meta).uuid; data.aoMapIntensity = this.aoMapIntensity; } if (this.bumpMap && this.bumpMap.isTexture) { data.bumpMap = this.bumpMap.toJSON(meta).uuid; data.bumpScale = this.bumpScale; } if (this.normalMap && this.normalMap.isTexture) { data.normalMap = this.normalMap.toJSON(meta).uuid; data.normalMapType = this.normalMapType; data.normalScale = this.normalScale.toArray(); } if (this.displacementMap && this.displacementMap.isTexture) { data.displacementMap = this.displacementMap.toJSON(meta).uuid; data.displacementScale = this.displacementScale; data.displacementBias = this.displacementBias; } if (this.roughnessMap && this.roughnessMap.isTexture) data.roughnessMap = this.roughnessMap.toJSON(meta).uuid; if (this.metalnessMap && this.metalnessMap.isTexture) data.metalnessMap = this.metalnessMap.toJSON(meta).uuid; if (this.emissiveMap && this.emissiveMap.isTexture) data.emissiveMap = this.emissiveMap.toJSON(meta).uuid; if (this.specularMap && this.specularMap.isTexture) data.specularMap = this.specularMap.toJSON(meta).uuid; if (this.specularIntensityMap && this.specularIntensityMap.isTexture) data.specularIntensityMap = this.specularIntensityMap.toJSON(meta).uuid; if (this.specularColorMap && this.specularColorMap.isTexture) data.specularColorMap = this.specularColorMap.toJSON(meta).uuid; if (this.envMap && this.envMap.isTexture) { data.envMap = this.envMap.toJSON(meta).uuid; if (this.combine !== void 0) data.combine = this.combine; } if (this.envMapIntensity !== void 0) data.envMapIntensity = this.envMapIntensity; if (this.reflectivity !== void 0) data.reflectivity = this.reflectivity; if (this.refractionRatio !== void 0) data.refractionRatio = this.refractionRatio; if (this.gradientMap && this.gradientMap.isTexture) { data.gradientMap = this.gradientMap.toJSON(meta).uuid; } if (this.transmission !== void 0) data.transmission = this.transmission; if (this.transmissionMap && this.transmissionMap.isTexture) data.transmissionMap = this.transmissionMap.toJSON(meta).uuid; if (this.thickness !== void 0) data.thickness = this.thickness; if (this.thicknessMap && this.thicknessMap.isTexture) data.thicknessMap = this.thicknessMap.toJSON(meta).uuid; if (this.attenuationDistance !== void 0 && this.attenuationDistance !== Infinity) data.attenuationDistance = this.attenuationDistance; if (this.attenuationColor !== void 0) data.attenuationColor = this.attenuationColor.getHex(); if (this.size !== void 0) data.size = this.size; if (this.shadowSide !== null) data.shadowSide = this.shadowSide; if (this.sizeAttenuation !== void 0) data.sizeAttenuation = this.sizeAttenuation; if (this.blending !== NormalBlending) data.blending = this.blending; if (this.side !== FrontSide) data.side = this.side; if (this.vertexColors) data.vertexColors = true; if (this.opacity < 1) data.opacity = this.opacity; if (this.transparent === true) data.transparent = this.transparent; data.depthFunc = this.depthFunc; data.depthTest = this.depthTest; data.depthWrite = this.depthWrite; data.colorWrite = this.colorWrite; data.stencilWrite = this.stencilWrite; data.stencilWriteMask = this.stencilWriteMask; data.stencilFunc = this.stencilFunc; data.stencilRef = this.stencilRef; data.stencilFuncMask = this.stencilFuncMask; data.stencilFail = this.stencilFail; data.stencilZFail = this.stencilZFail; data.stencilZPass = this.stencilZPass; if (this.rotation !== void 0 && this.rotation !== 0) data.rotation = this.rotation; if (this.polygonOffset === true) data.polygonOffset = true; if (this.polygonOffsetFactor !== 0) data.polygonOffsetFactor = this.polygonOffsetFactor; if (this.polygonOffsetUnits !== 0) data.polygonOffsetUnits = this.polygonOffsetUnits; if (this.linewidth !== void 0 && this.linewidth !== 1) data.linewidth = this.linewidth; if (this.dashSize !== void 0) data.dashSize = this.dashSize; if (this.gapSize !== void 0) data.gapSize = this.gapSize; if (this.scale !== void 0) data.scale = this.scale; if (this.dithering === true) data.dithering = true; if (this.alphaTest > 0) data.alphaTest = this.alphaTest; if (this.alphaToCoverage === true) data.alphaToCoverage = this.alphaToCoverage; if (this.premultipliedAlpha === true) data.premultipliedAlpha = this.premultipliedAlpha; if (this.wireframe === true) data.wireframe = this.wireframe; if (this.wireframeLinewidth > 1) data.wireframeLinewidth = this.wireframeLinewidth; if (this.wireframeLinecap !== "round") data.wireframeLinecap = this.wireframeLinecap; if (this.wireframeLinejoin !== "round") data.wireframeLinejoin = this.wireframeLinejoin; if (this.flatShading === true) data.flatShading = this.flatShading; if (this.visible === false) data.visible = false; if (this.toneMapped === false) data.toneMapped = false; if (this.fog === false) data.fog = false; if (JSON.stringify(this.userData) !== "{}") data.userData = this.userData; function extractFromCache(cache2) { const values = []; for (const key in cache2) { const data2 = cache2[key]; delete data2.metadata; values.push(data2); } return values; } if (isRootObject) { const textures = extractFromCache(meta.textures); const images = extractFromCache(meta.images); if (textures.length > 0) data.textures = textures; if (images.length > 0) data.images = images; } return data; } clone() { return new this.constructor().copy(this); } copy(source) { this.name = source.name; this.blending = source.blending; this.side = source.side; this.vertexColors = source.vertexColors; this.opacity = source.opacity; this.transparent = source.transparent; this.blendSrc = source.blendSrc; this.blendDst = source.blendDst; this.blendEquation = source.blendEquation; this.blendSrcAlpha = source.blendSrcAlpha; this.blendDstAlpha = source.blendDstAlpha; this.blendEquationAlpha = source.blendEquationAlpha; this.depthFunc = source.depthFunc; this.depthTest = source.depthTest; this.depthWrite = source.depthWrite; this.stencilWriteMask = source.stencilWriteMask; this.stencilFunc = source.stencilFunc; this.stencilRef = source.stencilRef; this.stencilFuncMask = source.stencilFuncMask; this.stencilFail = source.stencilFail; this.stencilZFail = source.stencilZFail; this.stencilZPass = source.stencilZPass; this.stencilWrite = source.stencilWrite; const srcPlanes = source.clippingPlanes; let dstPlanes = null; if (srcPlanes !== null) { const n2 = srcPlanes.length; dstPlanes = new Array(n2); for (let i = 0; i !== n2; ++i) { dstPlanes[i] = srcPlanes[i].clone(); } } this.clippingPlanes = dstPlanes; this.clipIntersection = source.clipIntersection; this.clipShadows = source.clipShadows; this.shadowSide = source.shadowSide; this.colorWrite = source.colorWrite; this.precision = source.precision; this.polygonOffset = source.polygonOffset; this.polygonOffsetFactor = source.polygonOffsetFactor; this.polygonOffsetUnits = source.polygonOffsetUnits; this.dithering = source.dithering; this.alphaTest = source.alphaTest; this.alphaToCoverage = source.alphaToCoverage; this.premultipliedAlpha = source.premultipliedAlpha; this.visible = source.visible; this.toneMapped = source.toneMapped; this.userData = JSON.parse(JSON.stringify(source.userData)); return this; } dispose() { this.dispatchEvent({ type: "dispose" }); } set needsUpdate(value) { if (value === true) this.version++; } }; var MeshBasicMaterial = class extends Material { constructor(parameters) { super(); this.isMeshBasicMaterial = true; this.type = "MeshBasicMaterial"; this.color = new Color(16777215); this.map = null; this.lightMap = null; this.lightMapIntensity = 1; this.aoMap = null; this.aoMapIntensity = 1; this.specularMap = null; this.alphaMap = null; this.envMap = null; this.combine = MultiplyOperation; this.reflectivity = 1; this.refractionRatio = 0.98; this.wireframe = false; this.wireframeLinewidth = 1; this.wireframeLinecap = "round"; this.wireframeLinejoin = "round"; this.fog = true; this.setValues(parameters); } copy(source) { super.copy(source); this.color.copy(source.color); this.map = source.map; this.lightMap = source.lightMap; this.lightMapIntensity = source.lightMapIntensity; this.aoMap = source.aoMap; this.aoMapIntensity = source.aoMapIntensity; this.specularMap = source.specularMap; this.alphaMap = source.alphaMap; this.envMap = source.envMap; this.combine = source.combine; this.reflectivity = source.reflectivity; this.refractionRatio = source.refractionRatio; this.wireframe = source.wireframe; this.wireframeLinewidth = source.wireframeLinewidth; this.wireframeLinecap = source.wireframeLinecap; this.wireframeLinejoin = source.wireframeLinejoin; this.fog = source.fog; return this; } }; var _vector$9 = new Vector3(); var _vector2$1 = new Vector2(); var BufferAttribute = class { constructor(array, itemSize, normalized) { if (Array.isArray(array)) { throw new TypeError("THREE.BufferAttribute: array should be a Typed Array."); } this.isBufferAttribute = true; this.name = ""; this.array = array; this.itemSize = itemSize; this.count = array !== void 0 ? array.length / itemSize : 0; this.normalized = normalized === true; this.usage = StaticDrawUsage; this.updateRange = { offset: 0, count: -1 }; this.version = 0; } onUploadCallback() { } set needsUpdate(value) { if (value === true) this.version++; } setUsage(value) { this.usage = value; return this; } copy(source) { this.name = source.name; this.array = new source.array.constructor(source.array); this.itemSize = source.itemSize; this.count = source.count; this.normalized = source.normalized; this.usage = source.usage; return this; } copyAt(index1, attribute, index2) { index1 *= this.itemSize; index2 *= attribute.itemSize; for (let i = 0, l = this.itemSize; i < l; i++) { this.array[index1 + i] = attribute.array[index2 + i]; } return this; } copyArray(array) { this.array.set(array); return this; } applyMatrix3(m) { if (this.itemSize === 2) { for (let i = 0, l = this.count; i < l; i++) { _vector2$1.fromBufferAttribute(this, i); _vector2$1.applyMatrix3(m); this.setXY(i, _vector2$1.x, _vector2$1.y); } } else if (this.itemSize === 3) { for (let i = 0, l = this.count; i < l; i++) { _vector$9.fromBufferAttribute(this, i); _vector$9.applyMatrix3(m); this.setXYZ(i, _vector$9.x, _vector$9.y, _vector$9.z); } } return this; } applyMatrix4(m) { for (let i = 0, l = this.count; i < l; i++) { _vector$9.fromBufferAttribute(this, i); _vector$9.applyMatrix4(m); this.setXYZ(i, _vector$9.x, _vector$9.y, _vector$9.z); } return this; } applyNormalMatrix(m) { for (let i = 0, l = this.count; i < l; i++) { _vector$9.fromBufferAttribute(this, i); _vector$9.applyNormalMatrix(m); this.setXYZ(i, _vector$9.x, _vector$9.y, _vector$9.z); } return this; } transformDirection(m) { for (let i = 0, l = this.count; i < l; i++) { _vector$9.fromBufferAttribute(this, i); _vector$9.transformDirection(m); this.setXYZ(i, _vector$9.x, _vector$9.y, _vector$9.z); } return this; } set(value, offset = 0) { this.array.set(value, offset); return this; } getX(index) { let x2 = this.array[index * this.itemSize]; if (this.normalized) x2 = denormalize(x2, this.array); return x2; } setX(index, x2) { if (this.normalized) x2 = normalize(x2, this.array); this.array[index * this.itemSize] = x2; return this; } getY(index) { let y = this.array[index * this.itemSize + 1]; if (this.normalized) y = denormalize(y, this.array); return y; } setY(index, y) { if (this.normalized) y = normalize(y, this.array); this.array[index * this.itemSize + 1] = y; return this; } getZ(index) { let z = this.array[index * this.itemSize + 2]; if (this.normalized) z = denormalize(z, this.array); return z; } setZ(index, z) { if (this.normalized) z = normalize(z, this.array); this.array[index * this.itemSize + 2] = z; return this; } getW(index) { let w = this.array[index * this.itemSize + 3]; if (this.normalized) w = denormalize(w, this.array); return w; } setW(index, w) { if (this.normalized) w = normalize(w, this.array); this.array[index * this.itemSize + 3] = w; return this; } setXY(index, x2, y) { index *= this.itemSize; if (this.normalized) { x2 = normalize(x2, this.array); y = normalize(y, this.array); } this.array[index + 0] = x2; this.array[index + 1] = y; return this; } setXYZ(index, x2, y, z) { index *= this.itemSize; if (this.normalized) { x2 = normalize(x2, this.array); y = normalize(y, this.array); z = normalize(z, this.array); } this.array[index + 0] = x2; this.array[index + 1] = y; this.array[index + 2] = z; return this; } setXYZW(index, x2, y, z, w) { index *= this.itemSize; if (this.normalized) { x2 = normalize(x2, this.array); y = normalize(y, this.array); z = normalize(z, this.array); w = normalize(w, this.array); } this.array[index + 0] = x2; this.array[index + 1] = y; this.array[index + 2] = z; this.array[index + 3] = w; return this; } onUpload(callback) { this.onUploadCallback = callback; return this; } clone() { return new this.constructor(this.array, this.itemSize).copy(this); } toJSON() { const data = { itemSize: this.itemSize, type: this.array.constructor.name, array: Array.from(this.array), normalized: this.normalized }; if (this.name !== "") data.name = this.name; if (this.usage !== StaticDrawUsage) data.usage = this.usage; if (this.updateRange.offset !== 0 || this.updateRange.count !== -1) data.updateRange = this.updateRange; return data; } // @deprecated copyColorsArray() { console.error("THREE.BufferAttribute: copyColorsArray() was removed in r144."); } copyVector2sArray() { console.error("THREE.BufferAttribute: copyVector2sArray() was removed in r144."); } copyVector3sArray() { console.error("THREE.BufferAttribute: copyVector3sArray() was removed in r144."); } copyVector4sArray() { console.error("THREE.BufferAttribute: copyVector4sArray() was removed in r144."); } }; var Uint16BufferAttribute = class extends BufferAttribute { constructor(array, itemSize, normalized) { super(new Uint16Array(array), itemSize, normalized); } }; var Uint32BufferAttribute = class extends BufferAttribute { constructor(array, itemSize, normalized) { super(new Uint32Array(array), itemSize, normalized); } }; var Float32BufferAttribute = class extends BufferAttribute { constructor(array, itemSize, normalized) { super(new Float32Array(array), itemSize, normalized); } }; var _id$1 = 0; var _m1 = new Matrix4(); var _obj = new Object3D(); var _offset = new Vector3(); var _box$1 = new Box3(); var _boxMorphTargets = new Box3(); var _vector$8 = new Vector3(); var BufferGeometry = class _BufferGeometry extends EventDispatcher { constructor() { super(); this.isBufferGeometry = true; Object.defineProperty(this, "id", { value: _id$1++ }); this.uuid = generateUUID(); this.name = ""; this.type = "BufferGeometry"; this.index = null; this.attributes = {}; this.morphAttributes = {}; this.morphTargetsRelative = false; this.groups = []; this.boundingBox = null; this.boundingSphere = null; this.drawRange = { start: 0, count: Infinity }; this.userData = {}; } getIndex() { return this.index; } setIndex(index) { if (Array.isArray(index)) { this.index = new (arrayNeedsUint32(index) ? Uint32BufferAttribute : Uint16BufferAttribute)(index, 1); } else { this.index = index; } return this; } getAttribute(name) { return this.attributes[name]; } setAttribute(name, attribute) { this.attributes[name] = attribute; return this; } deleteAttribute(name) { delete this.attributes[name]; return this; } hasAttribute(name) { return this.attributes[name] !== void 0; } addGroup(start, count, materialIndex = 0) { this.groups.push({ start, count, materialIndex }); } clearGroups() { this.groups = []; } setDrawRange(start, count) { this.drawRange.start = start; this.drawRange.count = count; } applyMatrix4(matrix) { const position = this.attributes.position; if (position !== void 0) { position.applyMatrix4(matrix); position.needsUpdate = true; } const normal = this.attributes.normal; if (normal !== void 0) { const normalMatrix = new Matrix3().getNormalMatrix(matrix); normal.applyNormalMatrix(normalMatrix); normal.needsUpdate = true; } const tangent = this.attributes.tangent; if (tangent !== void 0) { tangent.transformDirection(matrix); tangent.needsUpdate = true; } if (this.boundingBox !== null) { this.computeBoundingBox(); } if (this.boundingSphere !== null) { this.computeBoundingSphere(); } return this; } applyQuaternion(q) { _m1.makeRotationFromQuaternion(q); this.applyMatrix4(_m1); return this; } rotateX(angle) { _m1.makeRotationX(angle); this.applyMatrix4(_m1); return this; } rotateY(angle) { _m1.makeRotationY(angle); this.applyMatrix4(_m1); return this; } rotateZ(angle) { _m1.makeRotationZ(angle); this.applyMatrix4(_m1); return this; } translate(x2, y, z) { _m1.makeTranslation(x2, y, z); this.applyMatrix4(_m1); return this; } scale(x2, y, z) { _m1.makeScale(x2, y, z); this.applyMatrix4(_m1); return this; } lookAt(vector) { _obj.lookAt(vector); _obj.updateMatrix(); this.applyMatrix4(_obj.matrix); return this; } center() { this.computeBoundingBox(); this.boundingBox.getCenter(_offset).negate(); this.translate(_offset.x, _offset.y, _offset.z); return this; } setFromPoints(points) { const position = []; for (let i = 0, l = points.length; i < l; i++) { const point = points[i]; position.push(point.x, point.y, point.z || 0); } this.setAttribute("position", new Float32BufferAttribute(position, 3)); return this; } computeBoundingBox() { if (this.boundingBox === null) { this.boundingBox = new Box3(); } const position = this.attributes.position; const morphAttributesPosition = this.morphAttributes.position; if (position && position.isGLBufferAttribute) { console.error('THREE.BufferGeometry.computeBoundingBox(): GLBufferAttribute requires a manual bounding box. Alternatively set "mesh.frustumCulled" to "false".', this); this.boundingBox.set( new Vector3(-Infinity, -Infinity, -Infinity), new Vector3(Infinity, Infinity, Infinity) ); return; } if (position !== void 0) { this.boundingBox.setFromBufferAttribute(position); if (morphAttributesPosition) { for (let i = 0, il = morphAttributesPosition.length; i < il; i++) { const morphAttribute = morphAttributesPosition[i]; _box$1.setFromBufferAttribute(morphAttribute); if (this.morphTargetsRelative) { _vector$8.addVectors(this.boundingBox.min, _box$1.min); this.boundingBox.expandByPoint(_vector$8); _vector$8.addVectors(this.boundingBox.max, _box$1.max); this.boundingBox.expandByPoint(_vector$8); } else { this.boundingBox.expandByPoint(_box$1.min); this.boundingBox.expandByPoint(_box$1.max); } } } } else { this.boundingBox.makeEmpty(); } if (isNaN(this.boundingBox.min.x) || isNaN(this.boundingBox.min.y) || isNaN(this.boundingBox.min.z)) { console.error('THREE.BufferGeometry.computeBoundingBox(): Computed min/max have NaN values. The "position" attribute is likely to have NaN values.', this); } } computeBoundingSphere() { if (this.boundingSphere === null) { this.boundingSphere = new Sphere(); } const position = this.attributes.position; const morphAttributesPosition = this.morphAttributes.position; if (position && position.isGLBufferAttribute) { console.error('THREE.BufferGeometry.computeBoundingSphere(): GLBufferAttribute requires a manual bounding sphere. Alternatively set "mesh.frustumCulled" to "false".', this); this.boundingSphere.set(new Vector3(), Infinity); return; } if (position) { const center = this.boundingSphere.center; _box$1.setFromBufferAttribute(position); if (morphAttributesPosition) { for (let i = 0, il = morphAttributesPosition.length; i < il; i++) { const morphAttribute = morphAttributesPosition[i]; _boxMorphTargets.setFromBufferAttribute(morphAttribute); if (this.morphTargetsRelative) { _vector$8.addVectors(_box$1.min, _boxMorphTargets.min); _box$1.expandByPoint(_vector$8); _vector$8.addVectors(_box$1.max, _boxMorphTargets.max); _box$1.expandByPoint(_vector$8); } else { _box$1.expandByPoint(_boxMorphTargets.min); _box$1.expandByPoint(_boxMorphTargets.max); } } } _box$1.getCenter(center); let maxRadiusSq = 0; for (let i = 0, il = position.count; i < il; i++) { _vector$8.fromBufferAttribute(position, i); maxRadiusSq = Math.max(maxRadiusSq, center.distanceToSquared(_vector$8)); } if (morphAttributesPosition) { for (let i = 0, il = morphAttributesPosition.length; i < il; i++) { const morphAttribute = morphAttributesPosition[i]; const morphTargetsRelative = this.morphTargetsRelative; for (let j = 0, jl = morphAttribute.count; j < jl; j++) { _vector$8.fromBufferAttribute(morphAttribute, j); if (morphTargetsRelative) { _offset.fromBufferAttribute(position, j); _vector$8.add(_offset); } maxRadiusSq = Math.max(maxRadiusSq, center.distanceToSquared(_vector$8)); } } } this.boundingSphere.radius = Math.sqrt(maxRadiusSq); if (isNaN(this.boundingSphere.radius)) { console.error('THREE.BufferGeometry.computeBoundingSphere(): Computed radius is NaN. The "position" attribute is likely to have NaN values.', this); } } } computeTangents() { const index = this.index; const attributes = this.attributes; if (index === null || attributes.position === void 0 || attributes.normal === void 0 || attributes.uv === void 0) { console.error("THREE.BufferGeometry: .computeTangents() failed. Missing required attributes (index, position, normal or uv)"); return; } const indices = index.array; const positions = attributes.position.array; const normals = attributes.normal.array; const uvs = attributes.uv.array; const nVertices = positions.length / 3; if (this.hasAttribute("tangent") === false) { this.setAttribute("tangent", new BufferAttribute(new Float32Array(4 * nVertices), 4)); } const tangents = this.getAttribute("tangent").array; const tan1 = [], tan2 = []; for (let i = 0; i < nVertices; i++) { tan1[i] = new Vector3(); tan2[i] = new Vector3(); } const vA = new Vector3(), vB = new Vector3(), vC = new Vector3(), uvA = new Vector2(), uvB = new Vector2(), uvC = new Vector2(), sdir = new Vector3(), tdir = new Vector3(); function handleTriangle(a, b, c) { vA.fromArray(positions, a * 3); vB.fromArray(positions, b * 3); vC.fromArray(positions, c * 3); uvA.fromArray(uvs, a * 2); uvB.fromArray(uvs, b * 2); uvC.fromArray(uvs, c * 2); vB.sub(vA); vC.sub(vA); uvB.sub(uvA); uvC.sub(uvA); const r = 1 / (uvB.x * uvC.y - uvC.x * uvB.y); if (!isFinite(r)) return; sdir.copy(vB).multiplyScalar(uvC.y).addScaledVector(vC, -uvB.y).multiplyScalar(r); tdir.copy(vC).multiplyScalar(uvB.x).addScaledVector(vB, -uvC.x).multiplyScalar(r); tan1[a].add(sdir); tan1[b].add(sdir); tan1[c].add(sdir); tan2[a].add(tdir); tan2[b].add(tdir); tan2[c].add(tdir); } let groups = this.groups; if (groups.length === 0) { groups = [{ start: 0, count: indices.length }]; } for (let i = 0, il = groups.length; i < il; ++i) { const group = groups[i]; const start = group.start; const count = group.count; for (let j = start, jl = start + count; j < jl; j += 3) { handleTriangle( indices[j + 0], indices[j + 1], indices[j + 2] ); } } const tmp2 = new Vector3(), tmp22 = new Vector3(); const n2 = new Vector3(), n22 = new Vector3(); function handleVertex(v) { n2.fromArray(normals, v * 3); n22.copy(n2); const t2 = tan1[v]; tmp2.copy(t2); tmp2.sub(n2.multiplyScalar(n2.dot(t2))).normalize(); tmp22.crossVectors(n22, t2); const test = tmp22.dot(tan2[v]); const w = test < 0 ? -1 : 1; tangents[v * 4] = tmp2.x; tangents[v * 4 + 1] = tmp2.y; tangents[v * 4 + 2] = tmp2.z; tangents[v * 4 + 3] = w; } for (let i = 0, il = groups.length; i < il; ++i) { const group = groups[i]; const start = group.start; const count = group.count; for (let j = start, jl = start + count; j < jl; j += 3) { handleVertex(indices[j + 0]); handleVertex(indices[j + 1]); handleVertex(indices[j + 2]); } } } computeVertexNormals() { const index = this.index; const positionAttribute = this.getAttribute("position"); if (positionAttribute !== void 0) { let normalAttribute = this.getAttribute("normal"); if (normalAttribute === void 0) { normalAttribute = new BufferAttribute(new Float32Array(positionAttribute.count * 3), 3); this.setAttribute("normal", normalAttribute); } else { for (let i = 0, il = normalAttribute.count; i < il; i++) { normalAttribute.setXYZ(i, 0, 0, 0); } } const pA = new Vector3(), pB = new Vector3(), pC = new Vector3(); const nA = new Vector3(), nB = new Vector3(), nC = new Vector3(); const cb = new Vector3(), ab = new Vector3(); if (index) { for (let i = 0, il = index.count; i < il; i += 3) { const vA = index.getX(i + 0); const vB = index.getX(i + 1); const vC = index.getX(i + 2); pA.fromBufferAttribute(positionAttribute, vA); pB.fromBufferAttribute(positionAttribute, vB); pC.fromBufferAttribute(positionAttribute, vC); cb.subVectors(pC, pB); ab.subVectors(pA, pB); cb.cross(ab); nA.fromBufferAttribute(normalAttribute, vA); nB.fromBufferAttribute(normalAttribute, vB); nC.fromBufferAttribute(normalAttribute, vC); nA.add(cb); nB.add(cb); nC.add(cb); normalAttribute.setXYZ(vA, nA.x, nA.y, nA.z); normalAttribute.setXYZ(vB, nB.x, nB.y, nB.z); normalAttribute.setXYZ(vC, nC.x, nC.y, nC.z); } } else { for (let i = 0, il = positionAttribute.count; i < il; i += 3) { pA.fromBufferAttribute(positionAttribute, i + 0); pB.fromBufferAttribute(positionAttribute, i + 1); pC.fromBufferAttribute(positionAttribute, i + 2); cb.subVectors(pC, pB); ab.subVectors(pA, pB); cb.cross(ab); normalAttribute.setXYZ(i + 0, cb.x, cb.y, cb.z); normalAttribute.setXYZ(i + 1, cb.x, cb.y, cb.z); normalAttribute.setXYZ(i + 2, cb.x, cb.y, cb.z); } } this.normalizeNormals(); normalAttribute.needsUpdate = true; } } // @deprecated since r144 merge() { console.error("THREE.BufferGeometry.merge() has been removed. Use THREE.BufferGeometryUtils.mergeBufferGeometries() instead."); return this; } normalizeNormals() { const normals = this.attributes.normal; for (let i = 0, il = normals.count; i < il; i++) { _vector$8.fromBufferAttribute(normals, i); _vector$8.normalize(); normals.setXYZ(i, _vector$8.x, _vector$8.y, _vector$8.z); } } toNonIndexed() { function convertBufferAttribute(attribute, indices2) { const array = attribute.array; const itemSize = attribute.itemSize; const normalized = attribute.normalized; const array2 = new array.constructor(indices2.length * itemSize); let index = 0, index2 = 0; for (let i = 0, l = indices2.length; i < l; i++) { if (attribute.isInterleavedBufferAttribute) { index = indices2[i] * attribute.data.stride + attribute.offset; } else { index = indices2[i] * itemSize; } for (let j = 0; j < itemSize; j++) { array2[index2++] = array[index++]; } } return new BufferAttribute(array2, itemSize, normalized); } if (this.index === null) { console.warn("THREE.BufferGeometry.toNonIndexed(): BufferGeometry is already non-indexed."); return this; } const geometry2 = new _BufferGeometry(); const indices = this.index.array; const attributes = this.attributes; for (const name in attributes) { const attribute = attributes[name]; const newAttribute = convertBufferAttribute(attribute, indices); geometry2.setAttribute(name, newAttribute); } const morphAttributes = this.morphAttributes; for (const name in morphAttributes) { const morphArray = []; const morphAttribute = morphAttributes[name]; for (let i = 0, il = morphAttribute.length; i < il; i++) { const attribute = morphAttribute[i]; const newAttribute = convertBufferAttribute(attribute, indices); morphArray.push(newAttribute); } geometry2.morphAttributes[name] = morphArray; } geometry2.morphTargetsRelative = this.morphTargetsRelative; const groups = this.groups; for (let i = 0, l = groups.length; i < l; i++) { const group = groups[i]; geometry2.addGroup(group.start, group.count, group.materialIndex); } return geometry2; } toJSON() { const data = { metadata: { version: 4.5, type: "BufferGeometry", generator: "BufferGeometry.toJSON" } }; data.uuid = this.uuid; data.type = this.type; if (this.name !== "") data.name = this.name; if (Object.keys(this.userData).length > 0) data.userData = this.userData; if (this.parameters !== void 0) { const parameters = this.parameters; for (const key in parameters) { if (parameters[key] !== void 0) data[key] = parameters[key]; } return data; } data.data = { attributes: {} }; const index = this.index; if (index !== null) { data.data.index = { type: index.array.constructor.name, array: Array.prototype.slice.call(index.array) }; } const attributes = this.attributes; for (const key in attributes) { const attribute = attributes[key]; data.data.attributes[key] = attribute.toJSON(data.data); } const morphAttributes = {}; let hasMorphAttributes = false; for (const key in this.morphAttributes) { const attributeArray = this.morphAttributes[key]; const array = []; for (let i = 0, il = attributeArray.length; i < il; i++) { const attribute = attributeArray[i]; array.push(attribute.toJSON(data.data)); } if (array.length > 0) { morphAttributes[key] = array; hasMorphAttributes = true; } } if (hasMorphAttributes) { data.data.morphAttributes = morphAttributes; data.data.morphTargetsRelative = this.morphTargetsRelative; } const groups = this.groups; if (groups.length > 0) { data.data.groups = JSON.parse(JSON.stringify(groups)); } const boundingSphere = this.boundingSphere; if (boundingSphere !== null) { data.data.boundingSphere = { center: boundingSphere.center.toArray(), radius: boundingSphere.radius }; } return data; } clone() { return new this.constructor().copy(this); } copy(source) { this.index = null; this.attributes = {}; this.morphAttributes = {}; this.groups = []; this.boundingBox = null; this.boundingSphere = null; const data = {}; this.name = source.name; const index = source.index; if (index !== null) { this.setIndex(index.clone(data)); } const attributes = source.attributes; for (const name in attributes) { const attribute = attributes[name]; this.setAttribute(name, attribute.clone(data)); } const morphAttributes = source.morphAttributes; for (const name in morphAttributes) { const array = []; const morphAttribute = morphAttributes[name]; for (let i = 0, l = morphAttribute.length; i < l; i++) { array.push(morphAttribute[i].clone(data)); } this.morphAttributes[name] = array; } this.morphTargetsRelative = source.morphTargetsRelative; const groups = source.groups; for (let i = 0, l = groups.length; i < l; i++) { const group = groups[i]; this.addGroup(group.start, group.count, group.materialIndex); } const boundingBox = source.boundingBox; if (boundingBox !== null) { this.boundingBox = boundingBox.clone(); } const boundingSphere = source.boundingSphere; if (boundingSphere !== null) { this.boundingSphere = boundingSphere.clone(); } this.drawRange.start = source.drawRange.start; this.drawRange.count = source.drawRange.count; this.userData = source.userData; if (source.parameters !== void 0) this.parameters = Object.assign({}, source.parameters); return this; } dispose() { this.dispatchEvent({ type: "dispose" }); } }; var _inverseMatrix$2 = new Matrix4(); var _ray$2 = new Ray(); var _sphere$3 = new Sphere(); var _vA$1 = new Vector3(); var _vB$1 = new Vector3(); var _vC$1 = new Vector3(); var _tempA = new Vector3(); var _tempB = new Vector3(); var _tempC = new Vector3(); var _morphA = new Vector3(); var _morphB = new Vector3(); var _morphC = new Vector3(); var _uvA$1 = new Vector2(); var _uvB$1 = new Vector2(); var _uvC$1 = new Vector2(); var _intersectionPoint = new Vector3(); var _intersectionPointWorld = new Vector3(); var Mesh = class extends Object3D { constructor(geometry = new BufferGeometry(), material = new MeshBasicMaterial()) { super(); this.isMesh = true; this.type = "Mesh"; this.geometry = geometry; this.material = material; this.updateMorphTargets(); } copy(source, recursive) { super.copy(source, recursive); if (source.morphTargetInfluences !== void 0) { this.morphTargetInfluences = source.morphTargetInfluences.slice(); } if (source.morphTargetDictionary !== void 0) { this.morphTargetDictionary = Object.assign({}, source.morphTargetDictionary); } this.material = source.material; this.geometry = source.geometry; return this; } updateMorphTargets() { const geometry = this.geometry; const morphAttributes = geometry.morphAttributes; const keys = Object.keys(morphAttributes); if (keys.length > 0) { const morphAttribute = morphAttributes[keys[0]]; if (morphAttribute !== void 0) { this.morphTargetInfluences = []; this.morphTargetDictionary = {}; for (let m = 0, ml = morphAttribute.length; m < ml; m++) { const name = morphAttribute[m].name || String(m); this.morphTargetInfluences.push(0); this.morphTargetDictionary[name] = m; } } } } raycast(raycaster2, intersects2) { const geometry = this.geometry; const material = this.material; const matrixWorld = this.matrixWorld; if (material === void 0) return; if (geometry.boundingSphere === null) geometry.computeBoundingSphere(); _sphere$3.copy(geometry.boundingSphere); _sphere$3.applyMatrix4(matrixWorld); if (raycaster2.ray.intersectsSphere(_sphere$3) === false) return; _inverseMatrix$2.copy(matrixWorld).invert(); _ray$2.copy(raycaster2.ray).applyMatrix4(_inverseMatrix$2); if (geometry.boundingBox !== null) { if (_ray$2.intersectsBox(geometry.boundingBox) === false) return; } let intersection; const index = geometry.index; const position = geometry.attributes.position; const morphPosition = geometry.morphAttributes.position; const morphTargetsRelative = geometry.morphTargetsRelative; const uv = geometry.attributes.uv; const uv2 = geometry.attributes.uv2; const groups = geometry.groups; const drawRange = geometry.drawRange; if (index !== null) { if (Array.isArray(material)) { for (let i = 0, il = groups.length; i < il; i++) { const group = groups[i]; const groupMaterial = material[group.materialIndex]; const start = Math.max(group.start, drawRange.start); const end = Math.min(index.count, Math.min(group.start + group.count, drawRange.start + drawRange.count)); for (let j = start, jl = end; j < jl; j += 3) { const a = index.getX(j); const b = index.getX(j + 1); const c = index.getX(j + 2); intersection = checkBufferGeometryIntersection(this, groupMaterial, raycaster2, _ray$2, position, morphPosition, morphTargetsRelative, uv, uv2, a, b, c); if (intersection) { intersection.faceIndex = Math.floor(j / 3); intersection.face.materialIndex = group.materialIndex; intersects2.push(intersection); } } } } else { const start = Math.max(0, drawRange.start); const end = Math.min(index.count, drawRange.start + drawRange.count); for (let i = start, il = end; i < il; i += 3) { const a = index.getX(i); const b = index.getX(i + 1); const c = index.getX(i + 2); intersection = checkBufferGeometryIntersection(this, material, raycaster2, _ray$2, position, morphPosition, morphTargetsRelative, uv, uv2, a, b, c); if (intersection) { intersection.faceIndex = Math.floor(i / 3); intersects2.push(intersection); } } } } else if (position !== void 0) { if (Array.isArray(material)) { for (let i = 0, il = groups.length; i < il; i++) { const group = groups[i]; const groupMaterial = material[group.materialIndex]; const start = Math.max(group.start, drawRange.start); const end = Math.min(position.count, Math.min(group.start + group.count, drawRange.start + drawRange.count)); for (let j = start, jl = end; j < jl; j += 3) { const a = j; const b = j + 1; const c = j + 2; intersection = checkBufferGeometryIntersection(this, groupMaterial, raycaster2, _ray$2, position, morphPosition, morphTargetsRelative, uv, uv2, a, b, c); if (intersection) { intersection.faceIndex = Math.floor(j / 3); intersection.face.materialIndex = group.materialIndex; intersects2.push(intersection); } } } } else { const start = Math.max(0, drawRange.start); const end = Math.min(position.count, drawRange.start + drawRange.count); for (let i = start, il = end; i < il; i += 3) { const a = i; const b = i + 1; const c = i + 2; intersection = checkBufferGeometryIntersection(this, material, raycaster2, _ray$2, position, morphPosition, morphTargetsRelative, uv, uv2, a, b, c); if (intersection) { intersection.faceIndex = Math.floor(i / 3); intersects2.push(intersection); } } } } } }; function checkIntersection(object, material, raycaster2, ray, pA, pB, pC, point) { let intersect; if (material.side === BackSide) { intersect = ray.intersectTriangle(pC, pB, pA, true, point); } else { intersect = ray.intersectTriangle(pA, pB, pC, material.side !== DoubleSide, point); } if (intersect === null) return null; _intersectionPointWorld.copy(point); _intersectionPointWorld.applyMatrix4(object.matrixWorld); const distance = raycaster2.ray.origin.distanceTo(_intersectionPointWorld); if (distance < raycaster2.near || distance > raycaster2.far) return null; return { distance, point: _intersectionPointWorld.clone(), object }; } function checkBufferGeometryIntersection(object, material, raycaster2, ray, position, morphPosition, morphTargetsRelative, uv, uv2, a, b, c) { _vA$1.fromBufferAttribute(position, a); _vB$1.fromBufferAttribute(position, b); _vC$1.fromBufferAttribute(position, c); const morphInfluences = object.morphTargetInfluences; if (morphPosition && morphInfluences) { _morphA.set(0, 0, 0); _morphB.set(0, 0, 0); _morphC.set(0, 0, 0); for (let i = 0, il = morphPosition.length; i < il; i++) { const influence = morphInfluences[i]; const morphAttribute = morphPosition[i]; if (influence === 0) continue; _tempA.fromBufferAttribute(morphAttribute, a); _tempB.fromBufferAttribute(morphAttribute, b); _tempC.fromBufferAttribute(morphAttribute, c); if (morphTargetsRelative) { _morphA.addScaledVector(_tempA, influence); _morphB.addScaledVector(_tempB, influence); _morphC.addScaledVector(_tempC, influence); } else { _morphA.addScaledVector(_tempA.sub(_vA$1), influence); _morphB.addScaledVector(_tempB.sub(_vB$1), influence); _morphC.addScaledVector(_tempC.sub(_vC$1), influence); } } _vA$1.add(_morphA); _vB$1.add(_morphB); _vC$1.add(_morphC); } if (object.isSkinnedMesh) { object.boneTransform(a, _vA$1); object.boneTransform(b, _vB$1); object.boneTransform(c, _vC$1); } const intersection = checkIntersection(object, material, raycaster2, ray, _vA$1, _vB$1, _vC$1, _intersectionPoint); if (intersection) { if (uv) { _uvA$1.fromBufferAttribute(uv, a); _uvB$1.fromBufferAttribute(uv, b); _uvC$1.fromBufferAttribute(uv, c); intersection.uv = Triangle.getUV(_intersectionPoint, _vA$1, _vB$1, _vC$1, _uvA$1, _uvB$1, _uvC$1, new Vector2()); } if (uv2) { _uvA$1.fromBufferAttribute(uv2, a); _uvB$1.fromBufferAttribute(uv2, b); _uvC$1.fromBufferAttribute(uv2, c); intersection.uv2 = Triangle.getUV(_intersectionPoint, _vA$1, _vB$1, _vC$1, _uvA$1, _uvB$1, _uvC$1, new Vector2()); } const face = { a, b, c, normal: new Vector3(), materialIndex: 0 }; Triangle.getNormal(_vA$1, _vB$1, _vC$1, face.normal); intersection.face = face; } return intersection; } var BoxGeometry = class _BoxGeometry extends BufferGeometry { constructor(width = 1, height = 1, depth = 1, widthSegments = 1, heightSegments = 1, depthSegments = 1) { super(); this.type = "BoxGeometry"; this.parameters = { width, height, depth, widthSegments, heightSegments, depthSegments }; const scope = this; widthSegments = Math.floor(widthSegments); heightSegments = Math.floor(heightSegments); depthSegments = Math.floor(depthSegments); const indices = []; const vertices = []; const normals = []; const uvs = []; let numberOfVertices = 0; let groupStart = 0; buildPlane("z", "y", "x", -1, -1, depth, height, width, depthSegments, heightSegments, 0); buildPlane("z", "y", "x", 1, -1, depth, height, -width, depthSegments, heightSegments, 1); buildPlane("x", "z", "y", 1, 1, width, depth, height, widthSegments, depthSegments, 2); buildPlane("x", "z", "y", 1, -1, width, depth, -height, widthSegments, depthSegments, 3); buildPlane("x", "y", "z", 1, -1, width, height, depth, widthSegments, heightSegments, 4); buildPlane("x", "y", "z", -1, -1, width, height, -depth, widthSegments, heightSegments, 5); this.setIndex(indices); this.setAttribute("position", new Float32BufferAttribute(vertices, 3)); this.setAttribute("normal", new Float32BufferAttribute(normals, 3)); this.setAttribute("uv", new Float32BufferAttribute(uvs, 2)); function buildPlane(u, v, w, udir, vdir, width2, height2, depth2, gridX, gridY, materialIndex) { const segmentWidth = width2 / gridX; const segmentHeight = height2 / gridY; const widthHalf = width2 / 2; const heightHalf = height2 / 2; const depthHalf = depth2 / 2; const gridX1 = gridX + 1; const gridY1 = gridY + 1; let vertexCounter = 0; let groupCount = 0; const vector = new Vector3(); for (let iy = 0; iy < gridY1; iy++) { const y = iy * segmentHeight - heightHalf; for (let ix = 0; ix < gridX1; ix++) { const x2 = ix * segmentWidth - widthHalf; vector[u] = x2 * udir; vector[v] = y * vdir; vector[w] = depthHalf; vertices.push(vector.x, vector.y, vector.z); vector[u] = 0; vector[v] = 0; vector[w] = depth2 > 0 ? 1 : -1; normals.push(vector.x, vector.y, vector.z); uvs.push(ix / gridX); uvs.push(1 - iy / gridY); vertexCounter += 1; } } for (let iy = 0; iy < gridY; iy++) { for (let ix = 0; ix < gridX; ix++) { const a = numberOfVertices + ix + gridX1 * iy; const b = numberOfVertices + ix + gridX1 * (iy + 1); const c = numberOfVertices + (ix + 1) + gridX1 * (iy + 1); const d = numberOfVertices + (ix + 1) + gridX1 * iy; indices.push(a, b, d); indices.push(b, c, d); groupCount += 6; } } scope.addGroup(groupStart, groupCount, materialIndex); groupStart += groupCount; numberOfVertices += vertexCounter; } } static fromJSON(data) { return new _BoxGeometry(data.width, data.height, data.depth, data.widthSegments, data.heightSegments, data.depthSegments); } }; function cloneUniforms(src) { const dst = {}; for (const u in src) { dst[u] = {}; for (const p2 in src[u]) { const property2 = src[u][p2]; if (property2 && (property2.isColor || property2.isMatrix3 || property2.isMatrix4 || property2.isVector2 || property2.isVector3 || property2.isVector4 || property2.isTexture || property2.isQuaternion)) { dst[u][p2] = property2.clone(); } else if (Array.isArray(property2)) { dst[u][p2] = property2.slice(); } else { dst[u][p2] = property2; } } } return dst; } function mergeUniforms(uniforms) { const merged = {}; for (let u = 0; u < uniforms.length; u++) { const tmp2 = cloneUniforms(uniforms[u]); for (const p2 in tmp2) { merged[p2] = tmp2[p2]; } } return merged; } function cloneUniformsGroups(src) { const dst = []; for (let u = 0; u < src.length; u++) { dst.push(src[u].clone()); } return dst; } var UniformsUtils = { clone: cloneUniforms, merge: mergeUniforms }; var default_vertex = "void main() {\n gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );\n}"; var default_fragment = "void main() {\n gl_FragColor = vec4( 1.0, 0.0, 0.0, 1.0 );\n}"; var ShaderMaterial = class extends Material { constructor(parameters) { super(); this.isShaderMaterial = true; this.type = "ShaderMaterial"; this.defines = {}; this.uniforms = {}; this.uniformsGroups = []; this.vertexShader = default_vertex; this.fragmentShader = default_fragment; this.linewidth = 1; this.wireframe = false; this.wireframeLinewidth = 1; this.fog = false; this.lights = false; this.clipping = false; this.extensions = { derivatives: false, // set to use derivatives fragDepth: false, // set to use fragment depth values drawBuffers: false, // set to use draw buffers shaderTextureLOD: false // set to use shader texture LOD }; this.defaultAttributeValues = { "color": [1, 1, 1], "uv": [0, 0], "uv2": [0, 0] }; this.index0AttributeName = void 0; this.uniformsNeedUpdate = false; this.glslVersion = null; if (parameters !== void 0) { this.setValues(parameters); } } copy(source) { super.copy(source); this.fragmentShader = source.fragmentShader; this.vertexShader = source.vertexShader; this.uniforms = cloneUniforms(source.uniforms); this.uniformsGroups = cloneUniformsGroups(source.uniformsGroups); this.defines = Object.assign({}, source.defines); this.wireframe = source.wireframe; this.wireframeLinewidth = source.wireframeLinewidth; this.fog = source.fog; this.lights = source.lights; this.clipping = source.clipping; this.extensions = Object.assign({}, source.extensions); this.glslVersion = source.glslVersion; return this; } toJSON(meta) { const data = super.toJSON(meta); data.glslVersion = this.glslVersion; data.uniforms = {}; for (const name in this.uniforms) { const uniform = this.uniforms[name]; const value = uniform.value; if (value && value.isTexture) { data.uniforms[name] = { type: "t", value: value.toJSON(meta).uuid }; } else if (value && value.isColor) { data.uniforms[name] = { type: "c", value: value.getHex() }; } else if (value && value.isVector2) { data.uniforms[name] = { type: "v2", value: value.toArray() }; } else if (value && value.isVector3) { data.uniforms[name] = { type: "v3", value: value.toArray() }; } else if (value && value.isVector4) { data.uniforms[name] = { type: "v4", value: value.toArray() }; } else if (value && value.isMatrix3) { data.uniforms[name] = { type: "m3", value: value.toArray() }; } else if (value && value.isMatrix4) { data.uniforms[name] = { type: "m4", value: value.toArray() }; } else { data.uniforms[name] = { value }; } } if (Object.keys(this.defines).length > 0) data.defines = this.defines; data.vertexShader = this.vertexShader; data.fragmentShader = this.fragmentShader; const extensions = {}; for (const key in this.extensions) { if (this.extensions[key] === true) extensions[key] = true; } if (Object.keys(extensions).length > 0) data.extensions = extensions; return data; } }; var Camera = class extends Object3D { constructor() { super(); this.isCamera = true; this.type = "Camera"; this.matrixWorldInverse = new Matrix4(); this.projectionMatrix = new Matrix4(); this.projectionMatrixInverse = new Matrix4(); } copy(source, recursive) { super.copy(source, recursive); this.matrixWorldInverse.copy(source.matrixWorldInverse); this.projectionMatrix.copy(source.projectionMatrix); this.projectionMatrixInverse.copy(source.projectionMatrixInverse); return this; } getWorldDirection(target2) { this.updateWorldMatrix(true, false); const e = this.matrixWorld.elements; return target2.set(-e[8], -e[9], -e[10]).normalize(); } updateMatrixWorld(force) { super.updateMatrixWorld(force); this.matrixWorldInverse.copy(this.matrixWorld).invert(); } updateWorldMatrix(updateParents, updateChildren) { super.updateWorldMatrix(updateParents, updateChildren); this.matrixWorldInverse.copy(this.matrixWorld).invert(); } clone() { return new this.constructor().copy(this); } }; var PerspectiveCamera = class extends Camera { constructor(fov2 = 50, aspect2 = 1, near = 0.1, far = 2e3) { super(); this.isPerspectiveCamera = true; this.type = "PerspectiveCamera"; this.fov = fov2; this.zoom = 1; this.near = near; this.far = far; this.focus = 10; this.aspect = aspect2; this.view = null; this.filmGauge = 35; this.filmOffset = 0; this.updateProjectionMatrix(); } copy(source, recursive) { super.copy(source, recursive); this.fov = source.fov; this.zoom = source.zoom; this.near = source.near; this.far = source.far; this.focus = source.focus; this.aspect = source.aspect; this.view = source.view === null ? null : Object.assign({}, source.view); this.filmGauge = source.filmGauge; this.filmOffset = source.filmOffset; return this; } /** * Sets the FOV by focal length in respect to the current .filmGauge. * * The default film gauge is 35, so that the focal length can be specified for * a 35mm (full frame) camera. * * Values for focal length and film gauge must have the same unit. */ setFocalLength(focalLength) { const vExtentSlope = 0.5 * this.getFilmHeight() / focalLength; this.fov = RAD2DEG * 2 * Math.atan(vExtentSlope); this.updateProjectionMatrix(); } /** * Calculates the focal length from the current .fov and .filmGauge. */ getFocalLength() { const vExtentSlope = Math.tan(DEG2RAD * 0.5 * this.fov); return 0.5 * this.getFilmHeight() / vExtentSlope; } getEffectiveFOV() { return RAD2DEG * 2 * Math.atan( Math.tan(DEG2RAD * 0.5 * this.fov) / this.zoom ); } getFilmWidth() { return this.filmGauge * Math.min(this.aspect, 1); } getFilmHeight() { return this.filmGauge / Math.max(this.aspect, 1); } /** * Sets an offset in a larger frustum. This is useful for multi-window or * multi-monitor/multi-machine setups. * * For example, if you have 3x2 monitors and each monitor is 1920x1080 and * the monitors are in grid like this * * +---+---+---+ * | A | B | C | * +---+---+---+ * | D | E | F | * +---+---+---+ * * then for each monitor you would call it like this * * const w = 1920; * const h = 1080; * const fullWidth = w * 3; * const fullHeight = h * 2; * * --A-- * camera.setViewOffset( fullWidth, fullHeight, w * 0, h * 0, w, h ); * --B-- * camera.setViewOffset( fullWidth, fullHeight, w * 1, h * 0, w, h ); * --C-- * camera.setViewOffset( fullWidth, fullHeight, w * 2, h * 0, w, h ); * --D-- * camera.setViewOffset( fullWidth, fullHeight, w * 0, h * 1, w, h ); * --E-- * camera.setViewOffset( fullWidth, fullHeight, w * 1, h * 1, w, h ); * --F-- * camera.setViewOffset( fullWidth, fullHeight, w * 2, h * 1, w, h ); * * Note there is no reason monitors have to be the same size or in a grid. */ setViewOffset(fullWidth, fullHeight, x2, y, width, height) { this.aspect = fullWidth / fullHeight; if (this.view === null) { this.view = { enabled: true, fullWidth: 1, fullHeight: 1, offsetX: 0, offsetY: 0, width: 1, height: 1 }; } this.view.enabled = true; this.view.fullWidth = fullWidth; this.view.fullHeight = fullHeight; this.view.offsetX = x2; this.view.offsetY = y; this.view.width = width; this.view.height = height; this.updateProjectionMatrix(); } clearViewOffset() { if (this.view !== null) { this.view.enabled = false; } this.updateProjectionMatrix(); } updateProjectionMatrix() { const near = this.near; let top = near * Math.tan(DEG2RAD * 0.5 * this.fov) / this.zoom; let height = 2 * top; let width = this.aspect * height; let left = -0.5 * width; const view2 = this.view; if (this.view !== null && this.view.enabled) { const fullWidth = view2.fullWidth, fullHeight = view2.fullHeight; left += view2.offsetX * width / fullWidth; top -= view2.offsetY * height / fullHeight; width *= view2.width / fullWidth; height *= view2.height / fullHeight; } const skew = this.filmOffset; if (skew !== 0) left += near * skew / this.getFilmWidth(); this.projectionMatrix.makePerspective(left, left + width, top, top - height, near, this.far); this.projectionMatrixInverse.copy(this.projectionMatrix).invert(); } toJSON(meta) { const data = super.toJSON(meta); data.object.fov = this.fov; data.object.zoom = this.zoom; data.object.near = this.near; data.object.far = this.far; data.object.focus = this.focus; data.object.aspect = this.aspect; if (this.view !== null) data.object.view = Object.assign({}, this.view); data.object.filmGauge = this.filmGauge; data.object.filmOffset = this.filmOffset; return data; } }; var fov = 90; var aspect = 1; var CubeCamera = class extends Object3D { constructor(near, far, renderTarget) { super(); this.type = "CubeCamera"; this.renderTarget = renderTarget; const cameraPX = new PerspectiveCamera(fov, aspect, near, far); cameraPX.layers = this.layers; cameraPX.up.set(0, -1, 0); cameraPX.lookAt(new Vector3(1, 0, 0)); this.add(cameraPX); const cameraNX = new PerspectiveCamera(fov, aspect, near, far); cameraNX.layers = this.layers; cameraNX.up.set(0, -1, 0); cameraNX.lookAt(new Vector3(-1, 0, 0)); this.add(cameraNX); const cameraPY = new PerspectiveCamera(fov, aspect, near, far); cameraPY.layers = this.layers; cameraPY.up.set(0, 0, 1); cameraPY.lookAt(new Vector3(0, 1, 0)); this.add(cameraPY); const cameraNY = new PerspectiveCamera(fov, aspect, near, far); cameraNY.layers = this.layers; cameraNY.up.set(0, 0, -1); cameraNY.lookAt(new Vector3(0, -1, 0)); this.add(cameraNY); const cameraPZ = new PerspectiveCamera(fov, aspect, near, far); cameraPZ.layers = this.layers; cameraPZ.up.set(0, -1, 0); cameraPZ.lookAt(new Vector3(0, 0, 1)); this.add(cameraPZ); const cameraNZ = new PerspectiveCamera(fov, aspect, near, far); cameraNZ.layers = this.layers; cameraNZ.up.set(0, -1, 0); cameraNZ.lookAt(new Vector3(0, 0, -1)); this.add(cameraNZ); } update(renderer, scene) { if (this.parent === null) this.updateMatrixWorld(); const renderTarget = this.renderTarget; const [cameraPX, cameraNX, cameraPY, cameraNY, cameraPZ, cameraNZ] = this.children; const currentRenderTarget = renderer.getRenderTarget(); const currentToneMapping = renderer.toneMapping; const currentXrEnabled = renderer.xr.enabled; renderer.toneMapping = NoToneMapping; renderer.xr.enabled = false; const generateMipmaps = renderTarget.texture.generateMipmaps; renderTarget.texture.generateMipmaps = false; renderer.setRenderTarget(renderTarget, 0); renderer.render(scene, cameraPX); renderer.setRenderTarget(renderTarget, 1); renderer.render(scene, cameraNX); renderer.setRenderTarget(renderTarget, 2); renderer.render(scene, cameraPY); renderer.setRenderTarget(renderTarget, 3); renderer.render(scene, cameraNY); renderer.setRenderTarget(renderTarget, 4); renderer.render(scene, cameraPZ); renderTarget.texture.generateMipmaps = generateMipmaps; renderer.setRenderTarget(renderTarget, 5); renderer.render(scene, cameraNZ); renderer.setRenderTarget(currentRenderTarget); renderer.toneMapping = currentToneMapping; renderer.xr.enabled = currentXrEnabled; renderTarget.texture.needsPMREMUpdate = true; } }; var CubeTexture = class extends Texture { constructor(images, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, encoding) { images = images !== void 0 ? images : []; mapping = mapping !== void 0 ? mapping : CubeReflectionMapping; super(images, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, encoding); this.isCubeTexture = true; this.flipY = false; } get images() { return this.image; } set images(value) { this.image = value; } }; var WebGLCubeRenderTarget = class extends WebGLRenderTarget { constructor(size = 1, options = {}) { super(size, size, options); this.isWebGLCubeRenderTarget = true; const image = { width: size, height: size, depth: 1 }; const images = [image, image, image, image, image, image]; this.texture = new CubeTexture(images, options.mapping, options.wrapS, options.wrapT, options.magFilter, options.minFilter, options.format, options.type, options.anisotropy, options.encoding); this.texture.isRenderTargetTexture = true; this.texture.generateMipmaps = options.generateMipmaps !== void 0 ? options.generateMipmaps : false; this.texture.minFilter = options.minFilter !== void 0 ? options.minFilter : LinearFilter; } fromEquirectangularTexture(renderer, texture) { this.texture.type = texture.type; this.texture.encoding = texture.encoding; this.texture.generateMipmaps = texture.generateMipmaps; this.texture.minFilter = texture.minFilter; this.texture.magFilter = texture.magFilter; const shader = { uniforms: { tEquirect: { value: null } }, vertexShader: ( /* glsl */ ` varying vec3 vWorldDirection; vec3 transformDirection( in vec3 dir, in mat4 matrix ) { return normalize( ( matrix * vec4( dir, 0.0 ) ).xyz ); } void main() { vWorldDirection = transformDirection( position, modelMatrix ); #include #include } ` ), fragmentShader: ( /* glsl */ ` uniform sampler2D tEquirect; varying vec3 vWorldDirection; #include void main() { vec3 direction = normalize( vWorldDirection ); vec2 sampleUV = equirectUv( direction ); gl_FragColor = texture2D( tEquirect, sampleUV ); } ` ) }; const geometry = new BoxGeometry(5, 5, 5); const material = new ShaderMaterial({ name: "CubemapFromEquirect", uniforms: cloneUniforms(shader.uniforms), vertexShader: shader.vertexShader, fragmentShader: shader.fragmentShader, side: BackSide, blending: NoBlending }); material.uniforms.tEquirect.value = texture; const mesh = new Mesh(geometry, material); const currentMinFilter = texture.minFilter; if (texture.minFilter === LinearMipmapLinearFilter) texture.minFilter = LinearFilter; const camera2 = new CubeCamera(1, 10, this); camera2.update(renderer, mesh); texture.minFilter = currentMinFilter; mesh.geometry.dispose(); mesh.material.dispose(); return this; } clear(renderer, color, depth, stencil) { const currentRenderTarget = renderer.getRenderTarget(); for (let i = 0; i < 6; i++) { renderer.setRenderTarget(this, i); renderer.clear(color, depth, stencil); } renderer.setRenderTarget(currentRenderTarget); } }; var _vector1 = new Vector3(); var _vector2 = new Vector3(); var _normalMatrix = new Matrix3(); var Plane = class { constructor(normal = new Vector3(1, 0, 0), constant = 0) { this.isPlane = true; this.normal = normal; this.constant = constant; } set(normal, constant) { this.normal.copy(normal); this.constant = constant; return this; } setComponents(x2, y, z, w) { this.normal.set(x2, y, z); this.constant = w; return this; } setFromNormalAndCoplanarPoint(normal, point) { this.normal.copy(normal); this.constant = -point.dot(this.normal); return this; } setFromCoplanarPoints(a, b, c) { const normal = _vector1.subVectors(c, b).cross(_vector2.subVectors(a, b)).normalize(); this.setFromNormalAndCoplanarPoint(normal, a); return this; } copy(plane) { this.normal.copy(plane.normal); this.constant = plane.constant; return this; } normalize() { const inverseNormalLength = 1 / this.normal.length(); this.normal.multiplyScalar(inverseNormalLength); this.constant *= inverseNormalLength; return this; } negate() { this.constant *= -1; this.normal.negate(); return this; } distanceToPoint(point) { return this.normal.dot(point) + this.constant; } distanceToSphere(sphere) { return this.distanceToPoint(sphere.center) - sphere.radius; } projectPoint(point, target2) { return target2.copy(this.normal).multiplyScalar(-this.distanceToPoint(point)).add(point); } intersectLine(line, target2) { const direction = line.delta(_vector1); const denominator = this.normal.dot(direction); if (denominator === 0) { if (this.distanceToPoint(line.start) === 0) { return target2.copy(line.start); } return null; } const t2 = -(line.start.dot(this.normal) + this.constant) / denominator; if (t2 < 0 || t2 > 1) { return null; } return target2.copy(direction).multiplyScalar(t2).add(line.start); } intersectsLine(line) { const startSign = this.distanceToPoint(line.start); const endSign = this.distanceToPoint(line.end); return startSign < 0 && endSign > 0 || endSign < 0 && startSign > 0; } intersectsBox(box) { return box.intersectsPlane(this); } intersectsSphere(sphere) { return sphere.intersectsPlane(this); } coplanarPoint(target2) { return target2.copy(this.normal).multiplyScalar(-this.constant); } applyMatrix4(matrix, optionalNormalMatrix) { const normalMatrix = optionalNormalMatrix || _normalMatrix.getNormalMatrix(matrix); const referencePoint = this.coplanarPoint(_vector1).applyMatrix4(matrix); const normal = this.normal.applyMatrix3(normalMatrix).normalize(); this.constant = -referencePoint.dot(normal); return this; } translate(offset) { this.constant -= offset.dot(this.normal); return this; } equals(plane) { return plane.normal.equals(this.normal) && plane.constant === this.constant; } clone() { return new this.constructor().copy(this); } }; var _sphere$2 = new Sphere(); var _vector$7 = new Vector3(); var Frustum = class { constructor(p0 = new Plane(), p1 = new Plane(), p2 = new Plane(), p3 = new Plane(), p4 = new Plane(), p5 = new Plane()) { this.planes = [p0, p1, p2, p3, p4, p5]; } set(p0, p1, p2, p3, p4, p5) { const planes = this.planes; planes[0].copy(p0); planes[1].copy(p1); planes[2].copy(p2); planes[3].copy(p3); planes[4].copy(p4); planes[5].copy(p5); return this; } copy(frustum) { const planes = this.planes; for (let i = 0; i < 6; i++) { planes[i].copy(frustum.planes[i]); } return this; } setFromProjectionMatrix(m) { const planes = this.planes; const me = m.elements; const me0 = me[0], me1 = me[1], me2 = me[2], me3 = me[3]; const me4 = me[4], me5 = me[5], me6 = me[6], me7 = me[7]; const me8 = me[8], me9 = me[9], me10 = me[10], me11 = me[11]; const me12 = me[12], me13 = me[13], me14 = me[14], me15 = me[15]; planes[0].setComponents(me3 - me0, me7 - me4, me11 - me8, me15 - me12).normalize(); planes[1].setComponents(me3 + me0, me7 + me4, me11 + me8, me15 + me12).normalize(); planes[2].setComponents(me3 + me1, me7 + me5, me11 + me9, me15 + me13).normalize(); planes[3].setComponents(me3 - me1, me7 - me5, me11 - me9, me15 - me13).normalize(); planes[4].setComponents(me3 - me2, me7 - me6, me11 - me10, me15 - me14).normalize(); planes[5].setComponents(me3 + me2, me7 + me6, me11 + me10, me15 + me14).normalize(); return this; } intersectsObject(object) { const geometry = object.geometry; if (geometry.boundingSphere === null) geometry.computeBoundingSphere(); _sphere$2.copy(geometry.boundingSphere).applyMatrix4(object.matrixWorld); return this.intersectsSphere(_sphere$2); } intersectsSprite(sprite) { _sphere$2.center.set(0, 0, 0); _sphere$2.radius = 0.7071067811865476; _sphere$2.applyMatrix4(sprite.matrixWorld); return this.intersectsSphere(_sphere$2); } intersectsSphere(sphere) { const planes = this.planes; const center = sphere.center; const negRadius = -sphere.radius; for (let i = 0; i < 6; i++) { const distance = planes[i].distanceToPoint(center); if (distance < negRadius) { return false; } } return true; } intersectsBox(box) { const planes = this.planes; for (let i = 0; i < 6; i++) { const plane = planes[i]; _vector$7.x = plane.normal.x > 0 ? box.max.x : box.min.x; _vector$7.y = plane.normal.y > 0 ? box.max.y : box.min.y; _vector$7.z = plane.normal.z > 0 ? box.max.z : box.min.z; if (plane.distanceToPoint(_vector$7) < 0) { return false; } } return true; } containsPoint(point) { const planes = this.planes; for (let i = 0; i < 6; i++) { if (planes[i].distanceToPoint(point) < 0) { return false; } } return true; } clone() { return new this.constructor().copy(this); } }; function WebGLAnimation() { let context = null; let isAnimating = false; let animationLoop = null; let requestId = null; function onAnimationFrame(time, frame) { animationLoop(time, frame); requestId = context.requestAnimationFrame(onAnimationFrame); } return { start: function() { if (isAnimating === true) return; if (animationLoop === null) return; requestId = context.requestAnimationFrame(onAnimationFrame); isAnimating = true; }, stop: function() { context.cancelAnimationFrame(requestId); isAnimating = false; }, setAnimationLoop: function(callback) { animationLoop = callback; }, setContext: function(value) { context = value; } }; } function WebGLAttributes(gl, capabilities) { const isWebGL2 = capabilities.isWebGL2; const buffers = /* @__PURE__ */ new WeakMap(); function createBuffer(attribute, bufferType) { const array = attribute.array; const usage = attribute.usage; const buffer = gl.createBuffer(); gl.bindBuffer(bufferType, buffer); gl.bufferData(bufferType, array, usage); attribute.onUploadCallback(); let type; if (array instanceof Float32Array) { type = 5126; } else if (array instanceof Uint16Array) { if (attribute.isFloat16BufferAttribute) { if (isWebGL2) { type = 5131; } else { throw new Error("THREE.WebGLAttributes: Usage of Float16BufferAttribute requires WebGL2."); } } else { type = 5123; } } else if (array instanceof Int16Array) { type = 5122; } else if (array instanceof Uint32Array) { type = 5125; } else if (array instanceof Int32Array) { type = 5124; } else if (array instanceof Int8Array) { type = 5120; } else if (array instanceof Uint8Array) { type = 5121; } else if (array instanceof Uint8ClampedArray) { type = 5121; } else { throw new Error("THREE.WebGLAttributes: Unsupported buffer data format: " + array); } return { buffer, type, bytesPerElement: array.BYTES_PER_ELEMENT, version: attribute.version }; } function updateBuffer(buffer, attribute, bufferType) { const array = attribute.array; const updateRange = attribute.updateRange; gl.bindBuffer(bufferType, buffer); if (updateRange.count === -1) { gl.bufferSubData(bufferType, 0, array); } else { if (isWebGL2) { gl.bufferSubData( bufferType, updateRange.offset * array.BYTES_PER_ELEMENT, array, updateRange.offset, updateRange.count ); } else { gl.bufferSubData( bufferType, updateRange.offset * array.BYTES_PER_ELEMENT, array.subarray(updateRange.offset, updateRange.offset + updateRange.count) ); } updateRange.count = -1; } } function get(attribute) { if (attribute.isInterleavedBufferAttribute) attribute = attribute.data; return buffers.get(attribute); } function remove(attribute) { if (attribute.isInterleavedBufferAttribute) attribute = attribute.data; const data = buffers.get(attribute); if (data) { gl.deleteBuffer(data.buffer); buffers.delete(attribute); } } function update(attribute, bufferType) { if (attribute.isGLBufferAttribute) { const cached = buffers.get(attribute); if (!cached || cached.version < attribute.version) { buffers.set(attribute, { buffer: attribute.buffer, type: attribute.type, bytesPerElement: attribute.elementSize, version: attribute.version }); } return; } if (attribute.isInterleavedBufferAttribute) attribute = attribute.data; const data = buffers.get(attribute); if (data === void 0) { buffers.set(attribute, createBuffer(attribute, bufferType)); } else if (data.version < attribute.version) { updateBuffer(data.buffer, attribute, bufferType); data.version = attribute.version; } } return { get, remove, update }; } var PlaneGeometry = class _PlaneGeometry extends BufferGeometry { constructor(width = 1, height = 1, widthSegments = 1, heightSegments = 1) { super(); this.type = "PlaneGeometry"; this.parameters = { width, height, widthSegments, heightSegments }; const width_half = width / 2; const height_half = height / 2; const gridX = Math.floor(widthSegments); const gridY = Math.floor(heightSegments); const gridX1 = gridX + 1; const gridY1 = gridY + 1; const segment_width = width / gridX; const segment_height = height / gridY; const indices = []; const vertices = []; const normals = []; const uvs = []; for (let iy = 0; iy < gridY1; iy++) { const y = iy * segment_height - height_half; for (let ix = 0; ix < gridX1; ix++) { const x2 = ix * segment_width - width_half; vertices.push(x2, -y, 0); normals.push(0, 0, 1); uvs.push(ix / gridX); uvs.push(1 - iy / gridY); } } for (let iy = 0; iy < gridY; iy++) { for (let ix = 0; ix < gridX; ix++) { const a = ix + gridX1 * iy; const b = ix + gridX1 * (iy + 1); const c = ix + 1 + gridX1 * (iy + 1); const d = ix + 1 + gridX1 * iy; indices.push(a, b, d); indices.push(b, c, d); } } this.setIndex(indices); this.setAttribute("position", new Float32BufferAttribute(vertices, 3)); this.setAttribute("normal", new Float32BufferAttribute(normals, 3)); this.setAttribute("uv", new Float32BufferAttribute(uvs, 2)); } static fromJSON(data) { return new _PlaneGeometry(data.width, data.height, data.widthSegments, data.heightSegments); } }; var alphamap_fragment = "#ifdef USE_ALPHAMAP\n diffuseColor.a *= texture2D( alphaMap, vUv ).g;\n#endif"; var alphamap_pars_fragment = "#ifdef USE_ALPHAMAP\n uniform sampler2D alphaMap;\n#endif"; var alphatest_fragment = "#ifdef USE_ALPHATEST\n if ( diffuseColor.a < alphaTest ) discard;\n#endif"; var alphatest_pars_fragment = "#ifdef USE_ALPHATEST\n uniform float alphaTest;\n#endif"; var aomap_fragment = "#ifdef USE_AOMAP\n float ambientOcclusion = ( texture2D( aoMap, vUv2 ).r - 1.0 ) * aoMapIntensity + 1.0;\n reflectedLight.indirectDiffuse *= ambientOcclusion;\n #if defined( USE_ENVMAP ) && defined( STANDARD )\n float dotNV = saturate( dot( geometry.normal, geometry.viewDir ) );\n reflectedLight.indirectSpecular *= computeSpecularOcclusion( dotNV, ambientOcclusion, material.roughness );\n #endif\n#endif"; var aomap_pars_fragment = "#ifdef USE_AOMAP\n uniform sampler2D aoMap;\n uniform float aoMapIntensity;\n#endif"; var begin_vertex = "vec3 transformed = vec3( position );"; var beginnormal_vertex = "vec3 objectNormal = vec3( normal );\n#ifdef USE_TANGENT\n vec3 objectTangent = vec3( tangent.xyz );\n#endif"; var bsdfs = "vec3 BRDF_Lambert( const in vec3 diffuseColor ) {\n return RECIPROCAL_PI * diffuseColor;\n}\nvec3 F_Schlick( const in vec3 f0, const in float f90, const in float dotVH ) {\n float fresnel = exp2( ( - 5.55473 * dotVH - 6.98316 ) * dotVH );\n return f0 * ( 1.0 - fresnel ) + ( f90 * fresnel );\n}\nfloat F_Schlick( const in float f0, const in float f90, const in float dotVH ) {\n float fresnel = exp2( ( - 5.55473 * dotVH - 6.98316 ) * dotVH );\n return f0 * ( 1.0 - fresnel ) + ( f90 * fresnel );\n}\nvec3 Schlick_to_F0( const in vec3 f, const in float f90, const in float dotVH ) {\n float x = clamp( 1.0 - dotVH, 0.0, 1.0 );\n float x2 = x * x;\n float x5 = clamp( x * x2 * x2, 0.0, 0.9999 );\n return ( f - vec3( f90 ) * x5 ) / ( 1.0 - x5 );\n}\nfloat V_GGX_SmithCorrelated( const in float alpha, const in float dotNL, const in float dotNV ) {\n float a2 = pow2( alpha );\n float gv = dotNL * sqrt( a2 + ( 1.0 - a2 ) * pow2( dotNV ) );\n float gl = dotNV * sqrt( a2 + ( 1.0 - a2 ) * pow2( dotNL ) );\n return 0.5 / max( gv + gl, EPSILON );\n}\nfloat D_GGX( const in float alpha, const in float dotNH ) {\n float a2 = pow2( alpha );\n float denom = pow2( dotNH ) * ( a2 - 1.0 ) + 1.0;\n return RECIPROCAL_PI * a2 / pow2( denom );\n}\nvec3 BRDF_GGX( const in vec3 lightDir, const in vec3 viewDir, const in vec3 normal, const in vec3 f0, const in float f90, const in float roughness ) {\n float alpha = pow2( roughness );\n vec3 halfDir = normalize( lightDir + viewDir );\n float dotNL = saturate( dot( normal, lightDir ) );\n float dotNV = saturate( dot( normal, viewDir ) );\n float dotNH = saturate( dot( normal, halfDir ) );\n float dotVH = saturate( dot( viewDir, halfDir ) );\n vec3 F = F_Schlick( f0, f90, dotVH );\n float V = V_GGX_SmithCorrelated( alpha, dotNL, dotNV );\n float D = D_GGX( alpha, dotNH );\n return F * ( V * D );\n}\n#ifdef USE_IRIDESCENCE\n vec3 BRDF_GGX_Iridescence( const in vec3 lightDir, const in vec3 viewDir, const in vec3 normal, const in vec3 f0, const in float f90, const in float iridescence, const in vec3 iridescenceFresnel, const in float roughness ) {\n float alpha = pow2( roughness );\n vec3 halfDir = normalize( lightDir + viewDir );\n float dotNL = saturate( dot( normal, lightDir ) );\n float dotNV = saturate( dot( normal, viewDir ) );\n float dotNH = saturate( dot( normal, halfDir ) );\n float dotVH = saturate( dot( viewDir, halfDir ) );\n vec3 F = mix( F_Schlick( f0, f90, dotVH ), iridescenceFresnel, iridescence );\n float V = V_GGX_SmithCorrelated( alpha, dotNL, dotNV );\n float D = D_GGX( alpha, dotNH );\n return F * ( V * D );\n }\n#endif\nvec2 LTC_Uv( const in vec3 N, const in vec3 V, const in float roughness ) {\n const float LUT_SIZE = 64.0;\n const float LUT_SCALE = ( LUT_SIZE - 1.0 ) / LUT_SIZE;\n const float LUT_BIAS = 0.5 / LUT_SIZE;\n float dotNV = saturate( dot( N, V ) );\n vec2 uv = vec2( roughness, sqrt( 1.0 - dotNV ) );\n uv = uv * LUT_SCALE + LUT_BIAS;\n return uv;\n}\nfloat LTC_ClippedSphereFormFactor( const in vec3 f ) {\n float l = length( f );\n return max( ( l * l + f.z ) / ( l + 1.0 ), 0.0 );\n}\nvec3 LTC_EdgeVectorFormFactor( const in vec3 v1, const in vec3 v2 ) {\n float x = dot( v1, v2 );\n float y = abs( x );\n float a = 0.8543985 + ( 0.4965155 + 0.0145206 * y ) * y;\n float b = 3.4175940 + ( 4.1616724 + y ) * y;\n float v = a / b;\n float theta_sintheta = ( x > 0.0 ) ? v : 0.5 * inversesqrt( max( 1.0 - x * x, 1e-7 ) ) - v;\n return cross( v1, v2 ) * theta_sintheta;\n}\nvec3 LTC_Evaluate( const in vec3 N, const in vec3 V, const in vec3 P, const in mat3 mInv, const in vec3 rectCoords[ 4 ] ) {\n vec3 v1 = rectCoords[ 1 ] - rectCoords[ 0 ];\n vec3 v2 = rectCoords[ 3 ] - rectCoords[ 0 ];\n vec3 lightNormal = cross( v1, v2 );\n if( dot( lightNormal, P - rectCoords[ 0 ] ) < 0.0 ) return vec3( 0.0 );\n vec3 T1, T2;\n T1 = normalize( V - N * dot( V, N ) );\n T2 = - cross( N, T1 );\n mat3 mat = mInv * transposeMat3( mat3( T1, T2, N ) );\n vec3 coords[ 4 ];\n coords[ 0 ] = mat * ( rectCoords[ 0 ] - P );\n coords[ 1 ] = mat * ( rectCoords[ 1 ] - P );\n coords[ 2 ] = mat * ( rectCoords[ 2 ] - P );\n coords[ 3 ] = mat * ( rectCoords[ 3 ] - P );\n coords[ 0 ] = normalize( coords[ 0 ] );\n coords[ 1 ] = normalize( coords[ 1 ] );\n coords[ 2 ] = normalize( coords[ 2 ] );\n coords[ 3 ] = normalize( coords[ 3 ] );\n vec3 vectorFormFactor = vec3( 0.0 );\n vectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 0 ], coords[ 1 ] );\n vectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 1 ], coords[ 2 ] );\n vectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 2 ], coords[ 3 ] );\n vectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 3 ], coords[ 0 ] );\n float result = LTC_ClippedSphereFormFactor( vectorFormFactor );\n return vec3( result );\n}\nfloat G_BlinnPhong_Implicit( ) {\n return 0.25;\n}\nfloat D_BlinnPhong( const in float shininess, const in float dotNH ) {\n return RECIPROCAL_PI * ( shininess * 0.5 + 1.0 ) * pow( dotNH, shininess );\n}\nvec3 BRDF_BlinnPhong( const in vec3 lightDir, const in vec3 viewDir, const in vec3 normal, const in vec3 specularColor, const in float shininess ) {\n vec3 halfDir = normalize( lightDir + viewDir );\n float dotNH = saturate( dot( normal, halfDir ) );\n float dotVH = saturate( dot( viewDir, halfDir ) );\n vec3 F = F_Schlick( specularColor, 1.0, dotVH );\n float G = G_BlinnPhong_Implicit( );\n float D = D_BlinnPhong( shininess, dotNH );\n return F * ( G * D );\n}\n#if defined( USE_SHEEN )\nfloat D_Charlie( float roughness, float dotNH ) {\n float alpha = pow2( roughness );\n float invAlpha = 1.0 / alpha;\n float cos2h = dotNH * dotNH;\n float sin2h = max( 1.0 - cos2h, 0.0078125 );\n return ( 2.0 + invAlpha ) * pow( sin2h, invAlpha * 0.5 ) / ( 2.0 * PI );\n}\nfloat V_Neubelt( float dotNV, float dotNL ) {\n return saturate( 1.0 / ( 4.0 * ( dotNL + dotNV - dotNL * dotNV ) ) );\n}\nvec3 BRDF_Sheen( const in vec3 lightDir, const in vec3 viewDir, const in vec3 normal, vec3 sheenColor, const in float sheenRoughness ) {\n vec3 halfDir = normalize( lightDir + viewDir );\n float dotNL = saturate( dot( normal, lightDir ) );\n float dotNV = saturate( dot( normal, viewDir ) );\n float dotNH = saturate( dot( normal, halfDir ) );\n float D = D_Charlie( sheenRoughness, dotNH );\n float V = V_Neubelt( dotNV, dotNL );\n return sheenColor * ( D * V );\n}\n#endif"; var iridescence_fragment = "#ifdef USE_IRIDESCENCE\n const mat3 XYZ_TO_REC709 = mat3(\n 3.2404542, -0.9692660, 0.0556434,\n -1.5371385, 1.8760108, -0.2040259,\n -0.4985314, 0.0415560, 1.0572252\n );\n vec3 Fresnel0ToIor( vec3 fresnel0 ) {\n vec3 sqrtF0 = sqrt( fresnel0 );\n return ( vec3( 1.0 ) + sqrtF0 ) / ( vec3( 1.0 ) - sqrtF0 );\n }\n vec3 IorToFresnel0( vec3 transmittedIor, float incidentIor ) {\n return pow2( ( transmittedIor - vec3( incidentIor ) ) / ( transmittedIor + vec3( incidentIor ) ) );\n }\n float IorToFresnel0( float transmittedIor, float incidentIor ) {\n return pow2( ( transmittedIor - incidentIor ) / ( transmittedIor + incidentIor ));\n }\n vec3 evalSensitivity( float OPD, vec3 shift ) {\n float phase = 2.0 * PI * OPD * 1.0e-9;\n vec3 val = vec3( 5.4856e-13, 4.4201e-13, 5.2481e-13 );\n vec3 pos = vec3( 1.6810e+06, 1.7953e+06, 2.2084e+06 );\n vec3 var = vec3( 4.3278e+09, 9.3046e+09, 6.6121e+09 );\n vec3 xyz = val * sqrt( 2.0 * PI * var ) * cos( pos * phase + shift ) * exp( - pow2( phase ) * var );\n xyz.x += 9.7470e-14 * sqrt( 2.0 * PI * 4.5282e+09 ) * cos( 2.2399e+06 * phase + shift[ 0 ] ) * exp( - 4.5282e+09 * pow2( phase ) );\n xyz /= 1.0685e-7;\n vec3 rgb = XYZ_TO_REC709 * xyz;\n return rgb;\n }\n vec3 evalIridescence( float outsideIOR, float eta2, float cosTheta1, float thinFilmThickness, vec3 baseF0 ) {\n vec3 I;\n float iridescenceIOR = mix( outsideIOR, eta2, smoothstep( 0.0, 0.03, thinFilmThickness ) );\n float sinTheta2Sq = pow2( outsideIOR / iridescenceIOR ) * ( 1.0 - pow2( cosTheta1 ) );\n float cosTheta2Sq = 1.0 - sinTheta2Sq;\n if ( cosTheta2Sq < 0.0 ) {\n return vec3( 1.0 );\n }\n float cosTheta2 = sqrt( cosTheta2Sq );\n float R0 = IorToFresnel0( iridescenceIOR, outsideIOR );\n float R12 = F_Schlick( R0, 1.0, cosTheta1 );\n float R21 = R12;\n float T121 = 1.0 - R12;\n float phi12 = 0.0;\n if ( iridescenceIOR < outsideIOR ) phi12 = PI;\n float phi21 = PI - phi12;\n vec3 baseIOR = Fresnel0ToIor( clamp( baseF0, 0.0, 0.9999 ) ); vec3 R1 = IorToFresnel0( baseIOR, iridescenceIOR );\n vec3 R23 = F_Schlick( R1, 1.0, cosTheta2 );\n vec3 phi23 = vec3( 0.0 );\n if ( baseIOR[ 0 ] < iridescenceIOR ) phi23[ 0 ] = PI;\n if ( baseIOR[ 1 ] < iridescenceIOR ) phi23[ 1 ] = PI;\n if ( baseIOR[ 2 ] < iridescenceIOR ) phi23[ 2 ] = PI;\n float OPD = 2.0 * iridescenceIOR * thinFilmThickness * cosTheta2;\n vec3 phi = vec3( phi21 ) + phi23;\n vec3 R123 = clamp( R12 * R23, 1e-5, 0.9999 );\n vec3 r123 = sqrt( R123 );\n vec3 Rs = pow2( T121 ) * R23 / ( vec3( 1.0 ) - R123 );\n vec3 C0 = R12 + Rs;\n I = C0;\n vec3 Cm = Rs - T121;\n for ( int m = 1; m <= 2; ++ m ) {\n Cm *= r123;\n vec3 Sm = 2.0 * evalSensitivity( float( m ) * OPD, float( m ) * phi );\n I += Cm * Sm;\n }\n return max( I, vec3( 0.0 ) );\n }\n#endif"; var bumpmap_pars_fragment = "#ifdef USE_BUMPMAP\n uniform sampler2D bumpMap;\n uniform float bumpScale;\n vec2 dHdxy_fwd() {\n vec2 dSTdx = dFdx( vUv );\n vec2 dSTdy = dFdy( vUv );\n float Hll = bumpScale * texture2D( bumpMap, vUv ).x;\n float dBx = bumpScale * texture2D( bumpMap, vUv + dSTdx ).x - Hll;\n float dBy = bumpScale * texture2D( bumpMap, vUv + dSTdy ).x - Hll;\n return vec2( dBx, dBy );\n }\n vec3 perturbNormalArb( vec3 surf_pos, vec3 surf_norm, vec2 dHdxy, float faceDirection ) {\n vec3 vSigmaX = dFdx( surf_pos.xyz );\n vec3 vSigmaY = dFdy( surf_pos.xyz );\n vec3 vN = surf_norm;\n vec3 R1 = cross( vSigmaY, vN );\n vec3 R2 = cross( vN, vSigmaX );\n float fDet = dot( vSigmaX, R1 ) * faceDirection;\n vec3 vGrad = sign( fDet ) * ( dHdxy.x * R1 + dHdxy.y * R2 );\n return normalize( abs( fDet ) * surf_norm - vGrad );\n }\n#endif"; var clipping_planes_fragment = "#if NUM_CLIPPING_PLANES > 0\n vec4 plane;\n #pragma unroll_loop_start\n for ( int i = 0; i < UNION_CLIPPING_PLANES; i ++ ) {\n plane = clippingPlanes[ i ];\n if ( dot( vClipPosition, plane.xyz ) > plane.w ) discard;\n }\n #pragma unroll_loop_end\n #if UNION_CLIPPING_PLANES < NUM_CLIPPING_PLANES\n bool clipped = true;\n #pragma unroll_loop_start\n for ( int i = UNION_CLIPPING_PLANES; i < NUM_CLIPPING_PLANES; i ++ ) {\n plane = clippingPlanes[ i ];\n clipped = ( dot( vClipPosition, plane.xyz ) > plane.w ) && clipped;\n }\n #pragma unroll_loop_end\n if ( clipped ) discard;\n #endif\n#endif"; var clipping_planes_pars_fragment = "#if NUM_CLIPPING_PLANES > 0\n varying vec3 vClipPosition;\n uniform vec4 clippingPlanes[ NUM_CLIPPING_PLANES ];\n#endif"; var clipping_planes_pars_vertex = "#if NUM_CLIPPING_PLANES > 0\n varying vec3 vClipPosition;\n#endif"; var clipping_planes_vertex = "#if NUM_CLIPPING_PLANES > 0\n vClipPosition = - mvPosition.xyz;\n#endif"; var color_fragment = "#if defined( USE_COLOR_ALPHA )\n diffuseColor *= vColor;\n#elif defined( USE_COLOR )\n diffuseColor.rgb *= vColor;\n#endif"; var color_pars_fragment = "#if defined( USE_COLOR_ALPHA )\n varying vec4 vColor;\n#elif defined( USE_COLOR )\n varying vec3 vColor;\n#endif"; var color_pars_vertex = "#if defined( USE_COLOR_ALPHA )\n varying vec4 vColor;\n#elif defined( USE_COLOR ) || defined( USE_INSTANCING_COLOR )\n varying vec3 vColor;\n#endif"; var color_vertex = "#if defined( USE_COLOR_ALPHA )\n vColor = vec4( 1.0 );\n#elif defined( USE_COLOR ) || defined( USE_INSTANCING_COLOR )\n vColor = vec3( 1.0 );\n#endif\n#ifdef USE_COLOR\n vColor *= color;\n#endif\n#ifdef USE_INSTANCING_COLOR\n vColor.xyz *= instanceColor.xyz;\n#endif"; var common = "#define PI 3.141592653589793\n#define PI2 6.283185307179586\n#define PI_HALF 1.5707963267948966\n#define RECIPROCAL_PI 0.3183098861837907\n#define RECIPROCAL_PI2 0.15915494309189535\n#define EPSILON 1e-6\n#ifndef saturate\n#define saturate( a ) clamp( a, 0.0, 1.0 )\n#endif\n#define whiteComplement( a ) ( 1.0 - saturate( a ) )\nfloat pow2( const in float x ) { return x*x; }\nvec3 pow2( const in vec3 x ) { return x*x; }\nfloat pow3( const in float x ) { return x*x*x; }\nfloat pow4( const in float x ) { float x2 = x*x; return x2*x2; }\nfloat max3( const in vec3 v ) { return max( max( v.x, v.y ), v.z ); }\nfloat average( const in vec3 v ) { return dot( v, vec3( 0.3333333 ) ); }\nhighp float rand( const in vec2 uv ) {\n const highp float a = 12.9898, b = 78.233, c = 43758.5453;\n highp float dt = dot( uv.xy, vec2( a,b ) ), sn = mod( dt, PI );\n return fract( sin( sn ) * c );\n}\n#ifdef HIGH_PRECISION\n float precisionSafeLength( vec3 v ) { return length( v ); }\n#else\n float precisionSafeLength( vec3 v ) {\n float maxComponent = max3( abs( v ) );\n return length( v / maxComponent ) * maxComponent;\n }\n#endif\nstruct IncidentLight {\n vec3 color;\n vec3 direction;\n bool visible;\n};\nstruct ReflectedLight {\n vec3 directDiffuse;\n vec3 directSpecular;\n vec3 indirectDiffuse;\n vec3 indirectSpecular;\n};\nstruct GeometricContext {\n vec3 position;\n vec3 normal;\n vec3 viewDir;\n#ifdef USE_CLEARCOAT\n vec3 clearcoatNormal;\n#endif\n};\nvec3 transformDirection( in vec3 dir, in mat4 matrix ) {\n return normalize( ( matrix * vec4( dir, 0.0 ) ).xyz );\n}\nvec3 inverseTransformDirection( in vec3 dir, in mat4 matrix ) {\n return normalize( ( vec4( dir, 0.0 ) * matrix ).xyz );\n}\nmat3 transposeMat3( const in mat3 m ) {\n mat3 tmp;\n tmp[ 0 ] = vec3( m[ 0 ].x, m[ 1 ].x, m[ 2 ].x );\n tmp[ 1 ] = vec3( m[ 0 ].y, m[ 1 ].y, m[ 2 ].y );\n tmp[ 2 ] = vec3( m[ 0 ].z, m[ 1 ].z, m[ 2 ].z );\n return tmp;\n}\nfloat luminance( const in vec3 rgb ) {\n const vec3 weights = vec3( 0.2126729, 0.7151522, 0.0721750 );\n return dot( weights, rgb );\n}\nbool isPerspectiveMatrix( mat4 m ) {\n return m[ 2 ][ 3 ] == - 1.0;\n}\nvec2 equirectUv( in vec3 dir ) {\n float u = atan( dir.z, dir.x ) * RECIPROCAL_PI2 + 0.5;\n float v = asin( clamp( dir.y, - 1.0, 1.0 ) ) * RECIPROCAL_PI + 0.5;\n return vec2( u, v );\n}"; var cube_uv_reflection_fragment = "#ifdef ENVMAP_TYPE_CUBE_UV\n #define cubeUV_minMipLevel 4.0\n #define cubeUV_minTileSize 16.0\n float getFace( vec3 direction ) {\n vec3 absDirection = abs( direction );\n float face = - 1.0;\n if ( absDirection.x > absDirection.z ) {\n if ( absDirection.x > absDirection.y )\n face = direction.x > 0.0 ? 0.0 : 3.0;\n else\n face = direction.y > 0.0 ? 1.0 : 4.0;\n } else {\n if ( absDirection.z > absDirection.y )\n face = direction.z > 0.0 ? 2.0 : 5.0;\n else\n face = direction.y > 0.0 ? 1.0 : 4.0;\n }\n return face;\n }\n vec2 getUV( vec3 direction, float face ) {\n vec2 uv;\n if ( face == 0.0 ) {\n uv = vec2( direction.z, direction.y ) / abs( direction.x );\n } else if ( face == 1.0 ) {\n uv = vec2( - direction.x, - direction.z ) / abs( direction.y );\n } else if ( face == 2.0 ) {\n uv = vec2( - direction.x, direction.y ) / abs( direction.z );\n } else if ( face == 3.0 ) {\n uv = vec2( - direction.z, direction.y ) / abs( direction.x );\n } else if ( face == 4.0 ) {\n uv = vec2( - direction.x, direction.z ) / abs( direction.y );\n } else {\n uv = vec2( direction.x, direction.y ) / abs( direction.z );\n }\n return 0.5 * ( uv + 1.0 );\n }\n vec3 bilinearCubeUV( sampler2D envMap, vec3 direction, float mipInt ) {\n float face = getFace( direction );\n float filterInt = max( cubeUV_minMipLevel - mipInt, 0.0 );\n mipInt = max( mipInt, cubeUV_minMipLevel );\n float faceSize = exp2( mipInt );\n vec2 uv = getUV( direction, face ) * ( faceSize - 2.0 ) + 1.0;\n if ( face > 2.0 ) {\n uv.y += faceSize;\n face -= 3.0;\n }\n uv.x += face * faceSize;\n uv.x += filterInt * 3.0 * cubeUV_minTileSize;\n uv.y += 4.0 * ( exp2( CUBEUV_MAX_MIP ) - faceSize );\n uv.x *= CUBEUV_TEXEL_WIDTH;\n uv.y *= CUBEUV_TEXEL_HEIGHT;\n #ifdef texture2DGradEXT\n return texture2DGradEXT( envMap, uv, vec2( 0.0 ), vec2( 0.0 ) ).rgb;\n #else\n return texture2D( envMap, uv ).rgb;\n #endif\n }\n #define cubeUV_r0 1.0\n #define cubeUV_v0 0.339\n #define cubeUV_m0 - 2.0\n #define cubeUV_r1 0.8\n #define cubeUV_v1 0.276\n #define cubeUV_m1 - 1.0\n #define cubeUV_r4 0.4\n #define cubeUV_v4 0.046\n #define cubeUV_m4 2.0\n #define cubeUV_r5 0.305\n #define cubeUV_v5 0.016\n #define cubeUV_m5 3.0\n #define cubeUV_r6 0.21\n #define cubeUV_v6 0.0038\n #define cubeUV_m6 4.0\n float roughnessToMip( float roughness ) {\n float mip = 0.0;\n if ( roughness >= cubeUV_r1 ) {\n mip = ( cubeUV_r0 - roughness ) * ( cubeUV_m1 - cubeUV_m0 ) / ( cubeUV_r0 - cubeUV_r1 ) + cubeUV_m0;\n } else if ( roughness >= cubeUV_r4 ) {\n mip = ( cubeUV_r1 - roughness ) * ( cubeUV_m4 - cubeUV_m1 ) / ( cubeUV_r1 - cubeUV_r4 ) + cubeUV_m1;\n } else if ( roughness >= cubeUV_r5 ) {\n mip = ( cubeUV_r4 - roughness ) * ( cubeUV_m5 - cubeUV_m4 ) / ( cubeUV_r4 - cubeUV_r5 ) + cubeUV_m4;\n } else if ( roughness >= cubeUV_r6 ) {\n mip = ( cubeUV_r5 - roughness ) * ( cubeUV_m6 - cubeUV_m5 ) / ( cubeUV_r5 - cubeUV_r6 ) + cubeUV_m5;\n } else {\n mip = - 2.0 * log2( 1.16 * roughness ); }\n return mip;\n }\n vec4 textureCubeUV( sampler2D envMap, vec3 sampleDir, float roughness ) {\n float mip = clamp( roughnessToMip( roughness ), cubeUV_m0, CUBEUV_MAX_MIP );\n float mipF = fract( mip );\n float mipInt = floor( mip );\n vec3 color0 = bilinearCubeUV( envMap, sampleDir, mipInt );\n if ( mipF == 0.0 ) {\n return vec4( color0, 1.0 );\n } else {\n vec3 color1 = bilinearCubeUV( envMap, sampleDir, mipInt + 1.0 );\n return vec4( mix( color0, color1, mipF ), 1.0 );\n }\n }\n#endif"; var defaultnormal_vertex = "vec3 transformedNormal = objectNormal;\n#ifdef USE_INSTANCING\n mat3 m = mat3( instanceMatrix );\n transformedNormal /= vec3( dot( m[ 0 ], m[ 0 ] ), dot( m[ 1 ], m[ 1 ] ), dot( m[ 2 ], m[ 2 ] ) );\n transformedNormal = m * transformedNormal;\n#endif\ntransformedNormal = normalMatrix * transformedNormal;\n#ifdef FLIP_SIDED\n transformedNormal = - transformedNormal;\n#endif\n#ifdef USE_TANGENT\n vec3 transformedTangent = ( modelViewMatrix * vec4( objectTangent, 0.0 ) ).xyz;\n #ifdef FLIP_SIDED\n transformedTangent = - transformedTangent;\n #endif\n#endif"; var displacementmap_pars_vertex = "#ifdef USE_DISPLACEMENTMAP\n uniform sampler2D displacementMap;\n uniform float displacementScale;\n uniform float displacementBias;\n#endif"; var displacementmap_vertex = "#ifdef USE_DISPLACEMENTMAP\n transformed += normalize( objectNormal ) * ( texture2D( displacementMap, vUv ).x * displacementScale + displacementBias );\n#endif"; var emissivemap_fragment = "#ifdef USE_EMISSIVEMAP\n vec4 emissiveColor = texture2D( emissiveMap, vUv );\n totalEmissiveRadiance *= emissiveColor.rgb;\n#endif"; var emissivemap_pars_fragment = "#ifdef USE_EMISSIVEMAP\n uniform sampler2D emissiveMap;\n#endif"; var encodings_fragment = "gl_FragColor = linearToOutputTexel( gl_FragColor );"; var encodings_pars_fragment = "vec4 LinearToLinear( in vec4 value ) {\n return value;\n}\nvec4 LinearTosRGB( in vec4 value ) {\n return vec4( mix( pow( value.rgb, vec3( 0.41666 ) ) * 1.055 - vec3( 0.055 ), value.rgb * 12.92, vec3( lessThanEqual( value.rgb, vec3( 0.0031308 ) ) ) ), value.a );\n}"; var envmap_fragment = "#ifdef USE_ENVMAP\n #ifdef ENV_WORLDPOS\n vec3 cameraToFrag;\n if ( isOrthographic ) {\n cameraToFrag = normalize( vec3( - viewMatrix[ 0 ][ 2 ], - viewMatrix[ 1 ][ 2 ], - viewMatrix[ 2 ][ 2 ] ) );\n } else {\n cameraToFrag = normalize( vWorldPosition - cameraPosition );\n }\n vec3 worldNormal = inverseTransformDirection( normal, viewMatrix );\n #ifdef ENVMAP_MODE_REFLECTION\n vec3 reflectVec = reflect( cameraToFrag, worldNormal );\n #else\n vec3 reflectVec = refract( cameraToFrag, worldNormal, refractionRatio );\n #endif\n #else\n vec3 reflectVec = vReflect;\n #endif\n #ifdef ENVMAP_TYPE_CUBE\n vec4 envColor = textureCube( envMap, vec3( flipEnvMap * reflectVec.x, reflectVec.yz ) );\n #else\n vec4 envColor = vec4( 0.0 );\n #endif\n #ifdef ENVMAP_BLENDING_MULTIPLY\n outgoingLight = mix( outgoingLight, outgoingLight * envColor.xyz, specularStrength * reflectivity );\n #elif defined( ENVMAP_BLENDING_MIX )\n outgoingLight = mix( outgoingLight, envColor.xyz, specularStrength * reflectivity );\n #elif defined( ENVMAP_BLENDING_ADD )\n outgoingLight += envColor.xyz * specularStrength * reflectivity;\n #endif\n#endif"; var envmap_common_pars_fragment = "#ifdef USE_ENVMAP\n uniform float envMapIntensity;\n uniform float flipEnvMap;\n #ifdef ENVMAP_TYPE_CUBE\n uniform samplerCube envMap;\n #else\n uniform sampler2D envMap;\n #endif\n \n#endif"; var envmap_pars_fragment = "#ifdef USE_ENVMAP\n uniform float reflectivity;\n #if defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( PHONG ) || defined( LAMBERT )\n #define ENV_WORLDPOS\n #endif\n #ifdef ENV_WORLDPOS\n varying vec3 vWorldPosition;\n uniform float refractionRatio;\n #else\n varying vec3 vReflect;\n #endif\n#endif"; var envmap_pars_vertex = "#ifdef USE_ENVMAP\n #if defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( PHONG ) || defined( LAMBERT )\n #define ENV_WORLDPOS\n #endif\n #ifdef ENV_WORLDPOS\n \n varying vec3 vWorldPosition;\n #else\n varying vec3 vReflect;\n uniform float refractionRatio;\n #endif\n#endif"; var envmap_vertex = "#ifdef USE_ENVMAP\n #ifdef ENV_WORLDPOS\n vWorldPosition = worldPosition.xyz;\n #else\n vec3 cameraToVertex;\n if ( isOrthographic ) {\n cameraToVertex = normalize( vec3( - viewMatrix[ 0 ][ 2 ], - viewMatrix[ 1 ][ 2 ], - viewMatrix[ 2 ][ 2 ] ) );\n } else {\n cameraToVertex = normalize( worldPosition.xyz - cameraPosition );\n }\n vec3 worldNormal = inverseTransformDirection( transformedNormal, viewMatrix );\n #ifdef ENVMAP_MODE_REFLECTION\n vReflect = reflect( cameraToVertex, worldNormal );\n #else\n vReflect = refract( cameraToVertex, worldNormal, refractionRatio );\n #endif\n #endif\n#endif"; var fog_vertex = "#ifdef USE_FOG\n vFogDepth = - mvPosition.z;\n#endif"; var fog_pars_vertex = "#ifdef USE_FOG\n varying float vFogDepth;\n#endif"; var fog_fragment = "#ifdef USE_FOG\n #ifdef FOG_EXP2\n float fogFactor = 1.0 - exp( - fogDensity * fogDensity * vFogDepth * vFogDepth );\n #else\n float fogFactor = smoothstep( fogNear, fogFar, vFogDepth );\n #endif\n gl_FragColor.rgb = mix( gl_FragColor.rgb, fogColor, fogFactor );\n#endif"; var fog_pars_fragment = "#ifdef USE_FOG\n uniform vec3 fogColor;\n varying float vFogDepth;\n #ifdef FOG_EXP2\n uniform float fogDensity;\n #else\n uniform float fogNear;\n uniform float fogFar;\n #endif\n#endif"; var gradientmap_pars_fragment = "#ifdef USE_GRADIENTMAP\n uniform sampler2D gradientMap;\n#endif\nvec3 getGradientIrradiance( vec3 normal, vec3 lightDirection ) {\n float dotNL = dot( normal, lightDirection );\n vec2 coord = vec2( dotNL * 0.5 + 0.5, 0.0 );\n #ifdef USE_GRADIENTMAP\n return vec3( texture2D( gradientMap, coord ).r );\n #else\n vec2 fw = fwidth( coord ) * 0.5;\n return mix( vec3( 0.7 ), vec3( 1.0 ), smoothstep( 0.7 - fw.x, 0.7 + fw.x, coord.x ) );\n #endif\n}"; var lightmap_fragment = "#ifdef USE_LIGHTMAP\n vec4 lightMapTexel = texture2D( lightMap, vUv2 );\n vec3 lightMapIrradiance = lightMapTexel.rgb * lightMapIntensity;\n reflectedLight.indirectDiffuse += lightMapIrradiance;\n#endif"; var lightmap_pars_fragment = "#ifdef USE_LIGHTMAP\n uniform sampler2D lightMap;\n uniform float lightMapIntensity;\n#endif"; var lights_lambert_fragment = "LambertMaterial material;\nmaterial.diffuseColor = diffuseColor.rgb;\nmaterial.specularStrength = specularStrength;"; var lights_lambert_pars_fragment = "varying vec3 vViewPosition;\nstruct LambertMaterial {\n vec3 diffuseColor;\n float specularStrength;\n};\nvoid RE_Direct_Lambert( const in IncidentLight directLight, const in GeometricContext geometry, const in LambertMaterial material, inout ReflectedLight reflectedLight ) {\n float dotNL = saturate( dot( geometry.normal, directLight.direction ) );\n vec3 irradiance = dotNL * directLight.color;\n reflectedLight.directDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );\n}\nvoid RE_IndirectDiffuse_Lambert( const in vec3 irradiance, const in GeometricContext geometry, const in LambertMaterial material, inout ReflectedLight reflectedLight ) {\n reflectedLight.indirectDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );\n}\n#define RE_Direct RE_Direct_Lambert\n#define RE_IndirectDiffuse RE_IndirectDiffuse_Lambert\n#define Material_LightProbeLOD( material ) (0)"; var lights_pars_begin = "uniform bool receiveShadow;\nuniform vec3 ambientLightColor;\nuniform vec3 lightProbe[ 9 ];\nvec3 shGetIrradianceAt( in vec3 normal, in vec3 shCoefficients[ 9 ] ) {\n float x = normal.x, y = normal.y, z = normal.z;\n vec3 result = shCoefficients[ 0 ] * 0.886227;\n result += shCoefficients[ 1 ] * 2.0 * 0.511664 * y;\n result += shCoefficients[ 2 ] * 2.0 * 0.511664 * z;\n result += shCoefficients[ 3 ] * 2.0 * 0.511664 * x;\n result += shCoefficients[ 4 ] * 2.0 * 0.429043 * x * y;\n result += shCoefficients[ 5 ] * 2.0 * 0.429043 * y * z;\n result += shCoefficients[ 6 ] * ( 0.743125 * z * z - 0.247708 );\n result += shCoefficients[ 7 ] * 2.0 * 0.429043 * x * z;\n result += shCoefficients[ 8 ] * 0.429043 * ( x * x - y * y );\n return result;\n}\nvec3 getLightProbeIrradiance( const in vec3 lightProbe[ 9 ], const in vec3 normal ) {\n vec3 worldNormal = inverseTransformDirection( normal, viewMatrix );\n vec3 irradiance = shGetIrradianceAt( worldNormal, lightProbe );\n return irradiance;\n}\nvec3 getAmbientLightIrradiance( const in vec3 ambientLightColor ) {\n vec3 irradiance = ambientLightColor;\n return irradiance;\n}\nfloat getDistanceAttenuation( const in float lightDistance, const in float cutoffDistance, const in float decayExponent ) {\n #if defined ( PHYSICALLY_CORRECT_LIGHTS )\n float distanceFalloff = 1.0 / max( pow( lightDistance, decayExponent ), 0.01 );\n if ( cutoffDistance > 0.0 ) {\n distanceFalloff *= pow2( saturate( 1.0 - pow4( lightDistance / cutoffDistance ) ) );\n }\n return distanceFalloff;\n #else\n if ( cutoffDistance > 0.0 && decayExponent > 0.0 ) {\n return pow( saturate( - lightDistance / cutoffDistance + 1.0 ), decayExponent );\n }\n return 1.0;\n #endif\n}\nfloat getSpotAttenuation( const in float coneCosine, const in float penumbraCosine, const in float angleCosine ) {\n return smoothstep( coneCosine, penumbraCosine, angleCosine );\n}\n#if NUM_DIR_LIGHTS > 0\n struct DirectionalLight {\n vec3 direction;\n vec3 color;\n };\n uniform DirectionalLight directionalLights[ NUM_DIR_LIGHTS ];\n void getDirectionalLightInfo( const in DirectionalLight directionalLight, const in GeometricContext geometry, out IncidentLight light ) {\n light.color = directionalLight.color;\n light.direction = directionalLight.direction;\n light.visible = true;\n }\n#endif\n#if NUM_POINT_LIGHTS > 0\n struct PointLight {\n vec3 position;\n vec3 color;\n float distance;\n float decay;\n };\n uniform PointLight pointLights[ NUM_POINT_LIGHTS ];\n void getPointLightInfo( const in PointLight pointLight, const in GeometricContext geometry, out IncidentLight light ) {\n vec3 lVector = pointLight.position - geometry.position;\n light.direction = normalize( lVector );\n float lightDistance = length( lVector );\n light.color = pointLight.color;\n light.color *= getDistanceAttenuation( lightDistance, pointLight.distance, pointLight.decay );\n light.visible = ( light.color != vec3( 0.0 ) );\n }\n#endif\n#if NUM_SPOT_LIGHTS > 0\n struct SpotLight {\n vec3 position;\n vec3 direction;\n vec3 color;\n float distance;\n float decay;\n float coneCos;\n float penumbraCos;\n };\n uniform SpotLight spotLights[ NUM_SPOT_LIGHTS ];\n void getSpotLightInfo( const in SpotLight spotLight, const in GeometricContext geometry, out IncidentLight light ) {\n vec3 lVector = spotLight.position - geometry.position;\n light.direction = normalize( lVector );\n float angleCos = dot( light.direction, spotLight.direction );\n float spotAttenuation = getSpotAttenuation( spotLight.coneCos, spotLight.penumbraCos, angleCos );\n if ( spotAttenuation > 0.0 ) {\n float lightDistance = length( lVector );\n light.color = spotLight.color * spotAttenuation;\n light.color *= getDistanceAttenuation( lightDistance, spotLight.distance, spotLight.decay );\n light.visible = ( light.color != vec3( 0.0 ) );\n } else {\n light.color = vec3( 0.0 );\n light.visible = false;\n }\n }\n#endif\n#if NUM_RECT_AREA_LIGHTS > 0\n struct RectAreaLight {\n vec3 color;\n vec3 position;\n vec3 halfWidth;\n vec3 halfHeight;\n };\n uniform sampler2D ltc_1; uniform sampler2D ltc_2;\n uniform RectAreaLight rectAreaLights[ NUM_RECT_AREA_LIGHTS ];\n#endif\n#if NUM_HEMI_LIGHTS > 0\n struct HemisphereLight {\n vec3 direction;\n vec3 skyColor;\n vec3 groundColor;\n };\n uniform HemisphereLight hemisphereLights[ NUM_HEMI_LIGHTS ];\n vec3 getHemisphereLightIrradiance( const in HemisphereLight hemiLight, const in vec3 normal ) {\n float dotNL = dot( normal, hemiLight.direction );\n float hemiDiffuseWeight = 0.5 * dotNL + 0.5;\n vec3 irradiance = mix( hemiLight.groundColor, hemiLight.skyColor, hemiDiffuseWeight );\n return irradiance;\n }\n#endif"; var envmap_physical_pars_fragment = "#if defined( USE_ENVMAP )\n vec3 getIBLIrradiance( const in vec3 normal ) {\n #if defined( ENVMAP_TYPE_CUBE_UV )\n vec3 worldNormal = inverseTransformDirection( normal, viewMatrix );\n vec4 envMapColor = textureCubeUV( envMap, worldNormal, 1.0 );\n return PI * envMapColor.rgb * envMapIntensity;\n #else\n return vec3( 0.0 );\n #endif\n }\n vec3 getIBLRadiance( const in vec3 viewDir, const in vec3 normal, const in float roughness ) {\n #if defined( ENVMAP_TYPE_CUBE_UV )\n vec3 reflectVec = reflect( - viewDir, normal );\n reflectVec = normalize( mix( reflectVec, normal, roughness * roughness) );\n reflectVec = inverseTransformDirection( reflectVec, viewMatrix );\n vec4 envMapColor = textureCubeUV( envMap, reflectVec, roughness );\n return envMapColor.rgb * envMapIntensity;\n #else\n return vec3( 0.0 );\n #endif\n }\n#endif"; var lights_toon_fragment = "ToonMaterial material;\nmaterial.diffuseColor = diffuseColor.rgb;"; var lights_toon_pars_fragment = "varying vec3 vViewPosition;\nstruct ToonMaterial {\n vec3 diffuseColor;\n};\nvoid RE_Direct_Toon( const in IncidentLight directLight, const in GeometricContext geometry, const in ToonMaterial material, inout ReflectedLight reflectedLight ) {\n vec3 irradiance = getGradientIrradiance( geometry.normal, directLight.direction ) * directLight.color;\n reflectedLight.directDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );\n}\nvoid RE_IndirectDiffuse_Toon( const in vec3 irradiance, const in GeometricContext geometry, const in ToonMaterial material, inout ReflectedLight reflectedLight ) {\n reflectedLight.indirectDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );\n}\n#define RE_Direct RE_Direct_Toon\n#define RE_IndirectDiffuse RE_IndirectDiffuse_Toon\n#define Material_LightProbeLOD( material ) (0)"; var lights_phong_fragment = "BlinnPhongMaterial material;\nmaterial.diffuseColor = diffuseColor.rgb;\nmaterial.specularColor = specular;\nmaterial.specularShininess = shininess;\nmaterial.specularStrength = specularStrength;"; var lights_phong_pars_fragment = "varying vec3 vViewPosition;\nstruct BlinnPhongMaterial {\n vec3 diffuseColor;\n vec3 specularColor;\n float specularShininess;\n float specularStrength;\n};\nvoid RE_Direct_BlinnPhong( const in IncidentLight directLight, const in GeometricContext geometry, const in BlinnPhongMaterial material, inout ReflectedLight reflectedLight ) {\n float dotNL = saturate( dot( geometry.normal, directLight.direction ) );\n vec3 irradiance = dotNL * directLight.color;\n reflectedLight.directDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );\n reflectedLight.directSpecular += irradiance * BRDF_BlinnPhong( directLight.direction, geometry.viewDir, geometry.normal, material.specularColor, material.specularShininess ) * material.specularStrength;\n}\nvoid RE_IndirectDiffuse_BlinnPhong( const in vec3 irradiance, const in GeometricContext geometry, const in BlinnPhongMaterial material, inout ReflectedLight reflectedLight ) {\n reflectedLight.indirectDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );\n}\n#define RE_Direct RE_Direct_BlinnPhong\n#define RE_IndirectDiffuse RE_IndirectDiffuse_BlinnPhong\n#define Material_LightProbeLOD( material ) (0)"; var lights_physical_fragment = "PhysicalMaterial material;\nmaterial.diffuseColor = diffuseColor.rgb * ( 1.0 - metalnessFactor );\nvec3 dxy = max( abs( dFdx( geometryNormal ) ), abs( dFdy( geometryNormal ) ) );\nfloat geometryRoughness = max( max( dxy.x, dxy.y ), dxy.z );\nmaterial.roughness = max( roughnessFactor, 0.0525 );material.roughness += geometryRoughness;\nmaterial.roughness = min( material.roughness, 1.0 );\n#ifdef IOR\n material.ior = ior;\n #ifdef SPECULAR\n float specularIntensityFactor = specularIntensity;\n vec3 specularColorFactor = specularColor;\n #ifdef USE_SPECULARINTENSITYMAP\n specularIntensityFactor *= texture2D( specularIntensityMap, vUv ).a;\n #endif\n #ifdef USE_SPECULARCOLORMAP\n specularColorFactor *= texture2D( specularColorMap, vUv ).rgb;\n #endif\n material.specularF90 = mix( specularIntensityFactor, 1.0, metalnessFactor );\n #else\n float specularIntensityFactor = 1.0;\n vec3 specularColorFactor = vec3( 1.0 );\n material.specularF90 = 1.0;\n #endif\n material.specularColor = mix( min( pow2( ( material.ior - 1.0 ) / ( material.ior + 1.0 ) ) * specularColorFactor, vec3( 1.0 ) ) * specularIntensityFactor, diffuseColor.rgb, metalnessFactor );\n#else\n material.specularColor = mix( vec3( 0.04 ), diffuseColor.rgb, metalnessFactor );\n material.specularF90 = 1.0;\n#endif\n#ifdef USE_CLEARCOAT\n material.clearcoat = clearcoat;\n material.clearcoatRoughness = clearcoatRoughness;\n material.clearcoatF0 = vec3( 0.04 );\n material.clearcoatF90 = 1.0;\n #ifdef USE_CLEARCOATMAP\n material.clearcoat *= texture2D( clearcoatMap, vUv ).x;\n #endif\n #ifdef USE_CLEARCOAT_ROUGHNESSMAP\n material.clearcoatRoughness *= texture2D( clearcoatRoughnessMap, vUv ).y;\n #endif\n material.clearcoat = saturate( material.clearcoat ); material.clearcoatRoughness = max( material.clearcoatRoughness, 0.0525 );\n material.clearcoatRoughness += geometryRoughness;\n material.clearcoatRoughness = min( material.clearcoatRoughness, 1.0 );\n#endif\n#ifdef USE_IRIDESCENCE\n material.iridescence = iridescence;\n material.iridescenceIOR = iridescenceIOR;\n #ifdef USE_IRIDESCENCEMAP\n material.iridescence *= texture2D( iridescenceMap, vUv ).r;\n #endif\n #ifdef USE_IRIDESCENCE_THICKNESSMAP\n material.iridescenceThickness = (iridescenceThicknessMaximum - iridescenceThicknessMinimum) * texture2D( iridescenceThicknessMap, vUv ).g + iridescenceThicknessMinimum;\n #else\n material.iridescenceThickness = iridescenceThicknessMaximum;\n #endif\n#endif\n#ifdef USE_SHEEN\n material.sheenColor = sheenColor;\n #ifdef USE_SHEENCOLORMAP\n material.sheenColor *= texture2D( sheenColorMap, vUv ).rgb;\n #endif\n material.sheenRoughness = clamp( sheenRoughness, 0.07, 1.0 );\n #ifdef USE_SHEENROUGHNESSMAP\n material.sheenRoughness *= texture2D( sheenRoughnessMap, vUv ).a;\n #endif\n#endif"; var lights_physical_pars_fragment = "struct PhysicalMaterial {\n vec3 diffuseColor;\n float roughness;\n vec3 specularColor;\n float specularF90;\n #ifdef USE_CLEARCOAT\n float clearcoat;\n float clearcoatRoughness;\n vec3 clearcoatF0;\n float clearcoatF90;\n #endif\n #ifdef USE_IRIDESCENCE\n float iridescence;\n float iridescenceIOR;\n float iridescenceThickness;\n vec3 iridescenceFresnel;\n vec3 iridescenceF0;\n #endif\n #ifdef USE_SHEEN\n vec3 sheenColor;\n float sheenRoughness;\n #endif\n #ifdef IOR\n float ior;\n #endif\n #ifdef USE_TRANSMISSION\n float transmission;\n float transmissionAlpha;\n float thickness;\n float attenuationDistance;\n vec3 attenuationColor;\n #endif\n};\nvec3 clearcoatSpecular = vec3( 0.0 );\nvec3 sheenSpecular = vec3( 0.0 );\nfloat IBLSheenBRDF( const in vec3 normal, const in vec3 viewDir, const in float roughness ) {\n float dotNV = saturate( dot( normal, viewDir ) );\n float r2 = roughness * roughness;\n float a = roughness < 0.25 ? -339.2 * r2 + 161.4 * roughness - 25.9 : -8.48 * r2 + 14.3 * roughness - 9.95;\n float b = roughness < 0.25 ? 44.0 * r2 - 23.7 * roughness + 3.26 : 1.97 * r2 - 3.27 * roughness + 0.72;\n float DG = exp( a * dotNV + b ) + ( roughness < 0.25 ? 0.0 : 0.1 * ( roughness - 0.25 ) );\n return saturate( DG * RECIPROCAL_PI );\n}\nvec2 DFGApprox( const in vec3 normal, const in vec3 viewDir, const in float roughness ) {\n float dotNV = saturate( dot( normal, viewDir ) );\n const vec4 c0 = vec4( - 1, - 0.0275, - 0.572, 0.022 );\n const vec4 c1 = vec4( 1, 0.0425, 1.04, - 0.04 );\n vec4 r = roughness * c0 + c1;\n float a004 = min( r.x * r.x, exp2( - 9.28 * dotNV ) ) * r.x + r.y;\n vec2 fab = vec2( - 1.04, 1.04 ) * a004 + r.zw;\n return fab;\n}\nvec3 EnvironmentBRDF( const in vec3 normal, const in vec3 viewDir, const in vec3 specularColor, const in float specularF90, const in float roughness ) {\n vec2 fab = DFGApprox( normal, viewDir, roughness );\n return specularColor * fab.x + specularF90 * fab.y;\n}\n#ifdef USE_IRIDESCENCE\nvoid computeMultiscatteringIridescence( const in vec3 normal, const in vec3 viewDir, const in vec3 specularColor, const in float specularF90, const in float iridescence, const in vec3 iridescenceF0, const in float roughness, inout vec3 singleScatter, inout vec3 multiScatter ) {\n#else\nvoid computeMultiscattering( const in vec3 normal, const in vec3 viewDir, const in vec3 specularColor, const in float specularF90, const in float roughness, inout vec3 singleScatter, inout vec3 multiScatter ) {\n#endif\n vec2 fab = DFGApprox( normal, viewDir, roughness );\n #ifdef USE_IRIDESCENCE\n vec3 Fr = mix( specularColor, iridescenceF0, iridescence );\n #else\n vec3 Fr = specularColor;\n #endif\n vec3 FssEss = Fr * fab.x + specularF90 * fab.y;\n float Ess = fab.x + fab.y;\n float Ems = 1.0 - Ess;\n vec3 Favg = Fr + ( 1.0 - Fr ) * 0.047619; vec3 Fms = FssEss * Favg / ( 1.0 - Ems * Favg );\n singleScatter += FssEss;\n multiScatter += Fms * Ems;\n}\n#if NUM_RECT_AREA_LIGHTS > 0\n void RE_Direct_RectArea_Physical( const in RectAreaLight rectAreaLight, const in GeometricContext geometry, const in PhysicalMaterial material, inout ReflectedLight reflectedLight ) {\n vec3 normal = geometry.normal;\n vec3 viewDir = geometry.viewDir;\n vec3 position = geometry.position;\n vec3 lightPos = rectAreaLight.position;\n vec3 halfWidth = rectAreaLight.halfWidth;\n vec3 halfHeight = rectAreaLight.halfHeight;\n vec3 lightColor = rectAreaLight.color;\n float roughness = material.roughness;\n vec3 rectCoords[ 4 ];\n rectCoords[ 0 ] = lightPos + halfWidth - halfHeight; rectCoords[ 1 ] = lightPos - halfWidth - halfHeight;\n rectCoords[ 2 ] = lightPos - halfWidth + halfHeight;\n rectCoords[ 3 ] = lightPos + halfWidth + halfHeight;\n vec2 uv = LTC_Uv( normal, viewDir, roughness );\n vec4 t1 = texture2D( ltc_1, uv );\n vec4 t2 = texture2D( ltc_2, uv );\n mat3 mInv = mat3(\n vec3( t1.x, 0, t1.y ),\n vec3( 0, 1, 0 ),\n vec3( t1.z, 0, t1.w )\n );\n vec3 fresnel = ( material.specularColor * t2.x + ( vec3( 1.0 ) - material.specularColor ) * t2.y );\n reflectedLight.directSpecular += lightColor * fresnel * LTC_Evaluate( normal, viewDir, position, mInv, rectCoords );\n reflectedLight.directDiffuse += lightColor * material.diffuseColor * LTC_Evaluate( normal, viewDir, position, mat3( 1.0 ), rectCoords );\n }\n#endif\nvoid RE_Direct_Physical( const in IncidentLight directLight, const in GeometricContext geometry, const in PhysicalMaterial material, inout ReflectedLight reflectedLight ) {\n float dotNL = saturate( dot( geometry.normal, directLight.direction ) );\n vec3 irradiance = dotNL * directLight.color;\n #ifdef USE_CLEARCOAT\n float dotNLcc = saturate( dot( geometry.clearcoatNormal, directLight.direction ) );\n vec3 ccIrradiance = dotNLcc * directLight.color;\n clearcoatSpecular += ccIrradiance * BRDF_GGX( directLight.direction, geometry.viewDir, geometry.clearcoatNormal, material.clearcoatF0, material.clearcoatF90, material.clearcoatRoughness );\n #endif\n #ifdef USE_SHEEN\n sheenSpecular += irradiance * BRDF_Sheen( directLight.direction, geometry.viewDir, geometry.normal, material.sheenColor, material.sheenRoughness );\n #endif\n #ifdef USE_IRIDESCENCE\n reflectedLight.directSpecular += irradiance * BRDF_GGX_Iridescence( directLight.direction, geometry.viewDir, geometry.normal, material.specularColor, material.specularF90, material.iridescence, material.iridescenceFresnel, material.roughness );\n #else\n reflectedLight.directSpecular += irradiance * BRDF_GGX( directLight.direction, geometry.viewDir, geometry.normal, material.specularColor, material.specularF90, material.roughness );\n #endif\n reflectedLight.directDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );\n}\nvoid RE_IndirectDiffuse_Physical( const in vec3 irradiance, const in GeometricContext geometry, const in PhysicalMaterial material, inout ReflectedLight reflectedLight ) {\n reflectedLight.indirectDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );\n}\nvoid RE_IndirectSpecular_Physical( const in vec3 radiance, const in vec3 irradiance, const in vec3 clearcoatRadiance, const in GeometricContext geometry, const in PhysicalMaterial material, inout ReflectedLight reflectedLight) {\n #ifdef USE_CLEARCOAT\n clearcoatSpecular += clearcoatRadiance * EnvironmentBRDF( geometry.clearcoatNormal, geometry.viewDir, material.clearcoatF0, material.clearcoatF90, material.clearcoatRoughness );\n #endif\n #ifdef USE_SHEEN\n sheenSpecular += irradiance * material.sheenColor * IBLSheenBRDF( geometry.normal, geometry.viewDir, material.sheenRoughness );\n #endif\n vec3 singleScattering = vec3( 0.0 );\n vec3 multiScattering = vec3( 0.0 );\n vec3 cosineWeightedIrradiance = irradiance * RECIPROCAL_PI;\n #ifdef USE_IRIDESCENCE\n computeMultiscatteringIridescence( geometry.normal, geometry.viewDir, material.specularColor, material.specularF90, material.iridescence, material.iridescenceFresnel, material.roughness, singleScattering, multiScattering );\n #else\n computeMultiscattering( geometry.normal, geometry.viewDir, material.specularColor, material.specularF90, material.roughness, singleScattering, multiScattering );\n #endif\n vec3 totalScattering = singleScattering + multiScattering;\n vec3 diffuse = material.diffuseColor * ( 1.0 - max( max( totalScattering.r, totalScattering.g ), totalScattering.b ) );\n reflectedLight.indirectSpecular += radiance * singleScattering;\n reflectedLight.indirectSpecular += multiScattering * cosineWeightedIrradiance;\n reflectedLight.indirectDiffuse += diffuse * cosineWeightedIrradiance;\n}\n#define RE_Direct RE_Direct_Physical\n#define RE_Direct_RectArea RE_Direct_RectArea_Physical\n#define RE_IndirectDiffuse RE_IndirectDiffuse_Physical\n#define RE_IndirectSpecular RE_IndirectSpecular_Physical\nfloat computeSpecularOcclusion( const in float dotNV, const in float ambientOcclusion, const in float roughness ) {\n return saturate( pow( dotNV + ambientOcclusion, exp2( - 16.0 * roughness - 1.0 ) ) - 1.0 + ambientOcclusion );\n}"; var lights_fragment_begin = "\nGeometricContext geometry;\ngeometry.position = - vViewPosition;\ngeometry.normal = normal;\ngeometry.viewDir = ( isOrthographic ) ? vec3( 0, 0, 1 ) : normalize( vViewPosition );\n#ifdef USE_CLEARCOAT\n geometry.clearcoatNormal = clearcoatNormal;\n#endif\n#ifdef USE_IRIDESCENCE\n float dotNVi = saturate( dot( normal, geometry.viewDir ) );\n if ( material.iridescenceThickness == 0.0 ) {\n material.iridescence = 0.0;\n } else {\n material.iridescence = saturate( material.iridescence );\n }\n if ( material.iridescence > 0.0 ) {\n material.iridescenceFresnel = evalIridescence( 1.0, material.iridescenceIOR, dotNVi, material.iridescenceThickness, material.specularColor );\n material.iridescenceF0 = Schlick_to_F0( material.iridescenceFresnel, 1.0, dotNVi );\n }\n#endif\nIncidentLight directLight;\n#if ( NUM_POINT_LIGHTS > 0 ) && defined( RE_Direct )\n PointLight pointLight;\n #if defined( USE_SHADOWMAP ) && NUM_POINT_LIGHT_SHADOWS > 0\n PointLightShadow pointLightShadow;\n #endif\n #pragma unroll_loop_start\n for ( int i = 0; i < NUM_POINT_LIGHTS; i ++ ) {\n pointLight = pointLights[ i ];\n getPointLightInfo( pointLight, geometry, directLight );\n #if defined( USE_SHADOWMAP ) && ( UNROLLED_LOOP_INDEX < NUM_POINT_LIGHT_SHADOWS )\n pointLightShadow = pointLightShadows[ i ];\n directLight.color *= all( bvec2( directLight.visible, receiveShadow ) ) ? getPointShadow( pointShadowMap[ i ], pointLightShadow.shadowMapSize, pointLightShadow.shadowBias, pointLightShadow.shadowRadius, vPointShadowCoord[ i ], pointLightShadow.shadowCameraNear, pointLightShadow.shadowCameraFar ) : 1.0;\n #endif\n RE_Direct( directLight, geometry, material, reflectedLight );\n }\n #pragma unroll_loop_end\n#endif\n#if ( NUM_SPOT_LIGHTS > 0 ) && defined( RE_Direct )\n SpotLight spotLight;\n vec4 spotColor;\n vec3 spotLightCoord;\n bool inSpotLightMap;\n #if defined( USE_SHADOWMAP ) && NUM_SPOT_LIGHT_SHADOWS > 0\n SpotLightShadow spotLightShadow;\n #endif\n #pragma unroll_loop_start\n for ( int i = 0; i < NUM_SPOT_LIGHTS; i ++ ) {\n spotLight = spotLights[ i ];\n getSpotLightInfo( spotLight, geometry, directLight );\n #if ( UNROLLED_LOOP_INDEX < NUM_SPOT_LIGHT_SHADOWS_WITH_MAPS )\n #define SPOT_LIGHT_MAP_INDEX UNROLLED_LOOP_INDEX\n #elif ( UNROLLED_LOOP_INDEX < NUM_SPOT_LIGHT_SHADOWS )\n #define SPOT_LIGHT_MAP_INDEX NUM_SPOT_LIGHT_MAPS\n #else\n #define SPOT_LIGHT_MAP_INDEX ( UNROLLED_LOOP_INDEX - NUM_SPOT_LIGHT_SHADOWS + NUM_SPOT_LIGHT_SHADOWS_WITH_MAPS )\n #endif\n #if ( SPOT_LIGHT_MAP_INDEX < NUM_SPOT_LIGHT_MAPS )\n spotLightCoord = vSpotLightCoord[ i ].xyz / vSpotLightCoord[ i ].w;\n inSpotLightMap = all( lessThan( abs( spotLightCoord * 2. - 1. ), vec3( 1.0 ) ) );\n spotColor = texture2D( spotLightMap[ SPOT_LIGHT_MAP_INDEX ], spotLightCoord.xy );\n directLight.color = inSpotLightMap ? directLight.color * spotColor.rgb : directLight.color;\n #endif\n #undef SPOT_LIGHT_MAP_INDEX\n #if defined( USE_SHADOWMAP ) && ( UNROLLED_LOOP_INDEX < NUM_SPOT_LIGHT_SHADOWS )\n spotLightShadow = spotLightShadows[ i ];\n directLight.color *= all( bvec2( directLight.visible, receiveShadow ) ) ? getShadow( spotShadowMap[ i ], spotLightShadow.shadowMapSize, spotLightShadow.shadowBias, spotLightShadow.shadowRadius, vSpotLightCoord[ i ] ) : 1.0;\n #endif\n RE_Direct( directLight, geometry, material, reflectedLight );\n }\n #pragma unroll_loop_end\n#endif\n#if ( NUM_DIR_LIGHTS > 0 ) && defined( RE_Direct )\n DirectionalLight directionalLight;\n #if defined( USE_SHADOWMAP ) && NUM_DIR_LIGHT_SHADOWS > 0\n DirectionalLightShadow directionalLightShadow;\n #endif\n #pragma unroll_loop_start\n for ( int i = 0; i < NUM_DIR_LIGHTS; i ++ ) {\n directionalLight = directionalLights[ i ];\n getDirectionalLightInfo( directionalLight, geometry, directLight );\n #if defined( USE_SHADOWMAP ) && ( UNROLLED_LOOP_INDEX < NUM_DIR_LIGHT_SHADOWS )\n directionalLightShadow = directionalLightShadows[ i ];\n directLight.color *= all( bvec2( directLight.visible, receiveShadow ) ) ? getShadow( directionalShadowMap[ i ], directionalLightShadow.shadowMapSize, directionalLightShadow.shadowBias, directionalLightShadow.shadowRadius, vDirectionalShadowCoord[ i ] ) : 1.0;\n #endif\n RE_Direct( directLight, geometry, material, reflectedLight );\n }\n #pragma unroll_loop_end\n#endif\n#if ( NUM_RECT_AREA_LIGHTS > 0 ) && defined( RE_Direct_RectArea )\n RectAreaLight rectAreaLight;\n #pragma unroll_loop_start\n for ( int i = 0; i < NUM_RECT_AREA_LIGHTS; i ++ ) {\n rectAreaLight = rectAreaLights[ i ];\n RE_Direct_RectArea( rectAreaLight, geometry, material, reflectedLight );\n }\n #pragma unroll_loop_end\n#endif\n#if defined( RE_IndirectDiffuse )\n vec3 iblIrradiance = vec3( 0.0 );\n vec3 irradiance = getAmbientLightIrradiance( ambientLightColor );\n irradiance += getLightProbeIrradiance( lightProbe, geometry.normal );\n #if ( NUM_HEMI_LIGHTS > 0 )\n #pragma unroll_loop_start\n for ( int i = 0; i < NUM_HEMI_LIGHTS; i ++ ) {\n irradiance += getHemisphereLightIrradiance( hemisphereLights[ i ], geometry.normal );\n }\n #pragma unroll_loop_end\n #endif\n#endif\n#if defined( RE_IndirectSpecular )\n vec3 radiance = vec3( 0.0 );\n vec3 clearcoatRadiance = vec3( 0.0 );\n#endif"; var lights_fragment_maps = "#if defined( RE_IndirectDiffuse )\n #ifdef USE_LIGHTMAP\n vec4 lightMapTexel = texture2D( lightMap, vUv2 );\n vec3 lightMapIrradiance = lightMapTexel.rgb * lightMapIntensity;\n irradiance += lightMapIrradiance;\n #endif\n #if defined( USE_ENVMAP ) && defined( STANDARD ) && defined( ENVMAP_TYPE_CUBE_UV )\n iblIrradiance += getIBLIrradiance( geometry.normal );\n #endif\n#endif\n#if defined( USE_ENVMAP ) && defined( RE_IndirectSpecular )\n radiance += getIBLRadiance( geometry.viewDir, geometry.normal, material.roughness );\n #ifdef USE_CLEARCOAT\n clearcoatRadiance += getIBLRadiance( geometry.viewDir, geometry.clearcoatNormal, material.clearcoatRoughness );\n #endif\n#endif"; var lights_fragment_end = "#if defined( RE_IndirectDiffuse )\n RE_IndirectDiffuse( irradiance, geometry, material, reflectedLight );\n#endif\n#if defined( RE_IndirectSpecular )\n RE_IndirectSpecular( radiance, iblIrradiance, clearcoatRadiance, geometry, material, reflectedLight );\n#endif"; var logdepthbuf_fragment = "#if defined( USE_LOGDEPTHBUF ) && defined( USE_LOGDEPTHBUF_EXT )\n gl_FragDepthEXT = vIsPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;\n#endif"; var logdepthbuf_pars_fragment = "#if defined( USE_LOGDEPTHBUF ) && defined( USE_LOGDEPTHBUF_EXT )\n uniform float logDepthBufFC;\n varying float vFragDepth;\n varying float vIsPerspective;\n#endif"; var logdepthbuf_pars_vertex = "#ifdef USE_LOGDEPTHBUF\n #ifdef USE_LOGDEPTHBUF_EXT\n varying float vFragDepth;\n varying float vIsPerspective;\n #else\n uniform float logDepthBufFC;\n #endif\n#endif"; var logdepthbuf_vertex = "#ifdef USE_LOGDEPTHBUF\n #ifdef USE_LOGDEPTHBUF_EXT\n vFragDepth = 1.0 + gl_Position.w;\n vIsPerspective = float( isPerspectiveMatrix( projectionMatrix ) );\n #else\n if ( isPerspectiveMatrix( projectionMatrix ) ) {\n gl_Position.z = log2( max( EPSILON, gl_Position.w + 1.0 ) ) * logDepthBufFC - 1.0;\n gl_Position.z *= gl_Position.w;\n }\n #endif\n#endif"; var map_fragment = "#ifdef USE_MAP\n vec4 sampledDiffuseColor = texture2D( map, vUv );\n #ifdef DECODE_VIDEO_TEXTURE\n sampledDiffuseColor = vec4( mix( pow( sampledDiffuseColor.rgb * 0.9478672986 + vec3( 0.0521327014 ), vec3( 2.4 ) ), sampledDiffuseColor.rgb * 0.0773993808, vec3( lessThanEqual( sampledDiffuseColor.rgb, vec3( 0.04045 ) ) ) ), sampledDiffuseColor.w );\n #endif\n diffuseColor *= sampledDiffuseColor;\n#endif"; var map_pars_fragment = "#ifdef USE_MAP\n uniform sampler2D map;\n#endif"; var map_particle_fragment = "#if defined( USE_MAP ) || defined( USE_ALPHAMAP )\n vec2 uv = ( uvTransform * vec3( gl_PointCoord.x, 1.0 - gl_PointCoord.y, 1 ) ).xy;\n#endif\n#ifdef USE_MAP\n diffuseColor *= texture2D( map, uv );\n#endif\n#ifdef USE_ALPHAMAP\n diffuseColor.a *= texture2D( alphaMap, uv ).g;\n#endif"; var map_particle_pars_fragment = "#if defined( USE_MAP ) || defined( USE_ALPHAMAP )\n uniform mat3 uvTransform;\n#endif\n#ifdef USE_MAP\n uniform sampler2D map;\n#endif\n#ifdef USE_ALPHAMAP\n uniform sampler2D alphaMap;\n#endif"; var metalnessmap_fragment = "float metalnessFactor = metalness;\n#ifdef USE_METALNESSMAP\n vec4 texelMetalness = texture2D( metalnessMap, vUv );\n metalnessFactor *= texelMetalness.b;\n#endif"; var metalnessmap_pars_fragment = "#ifdef USE_METALNESSMAP\n uniform sampler2D metalnessMap;\n#endif"; var morphcolor_vertex = "#if defined( USE_MORPHCOLORS ) && defined( MORPHTARGETS_TEXTURE )\n vColor *= morphTargetBaseInfluence;\n for ( int i = 0; i < MORPHTARGETS_COUNT; i ++ ) {\n #if defined( USE_COLOR_ALPHA )\n if ( morphTargetInfluences[ i ] != 0.0 ) vColor += getMorph( gl_VertexID, i, 2 ) * morphTargetInfluences[ i ];\n #elif defined( USE_COLOR )\n if ( morphTargetInfluences[ i ] != 0.0 ) vColor += getMorph( gl_VertexID, i, 2 ).rgb * morphTargetInfluences[ i ];\n #endif\n }\n#endif"; var morphnormal_vertex = "#ifdef USE_MORPHNORMALS\n objectNormal *= morphTargetBaseInfluence;\n #ifdef MORPHTARGETS_TEXTURE\n for ( int i = 0; i < MORPHTARGETS_COUNT; i ++ ) {\n if ( morphTargetInfluences[ i ] != 0.0 ) objectNormal += getMorph( gl_VertexID, i, 1 ).xyz * morphTargetInfluences[ i ];\n }\n #else\n objectNormal += morphNormal0 * morphTargetInfluences[ 0 ];\n objectNormal += morphNormal1 * morphTargetInfluences[ 1 ];\n objectNormal += morphNormal2 * morphTargetInfluences[ 2 ];\n objectNormal += morphNormal3 * morphTargetInfluences[ 3 ];\n #endif\n#endif"; var morphtarget_pars_vertex = "#ifdef USE_MORPHTARGETS\n uniform float morphTargetBaseInfluence;\n #ifdef MORPHTARGETS_TEXTURE\n uniform float morphTargetInfluences[ MORPHTARGETS_COUNT ];\n uniform sampler2DArray morphTargetsTexture;\n uniform ivec2 morphTargetsTextureSize;\n vec4 getMorph( const in int vertexIndex, const in int morphTargetIndex, const in int offset ) {\n int texelIndex = vertexIndex * MORPHTARGETS_TEXTURE_STRIDE + offset;\n int y = texelIndex / morphTargetsTextureSize.x;\n int x = texelIndex - y * morphTargetsTextureSize.x;\n ivec3 morphUV = ivec3( x, y, morphTargetIndex );\n return texelFetch( morphTargetsTexture, morphUV, 0 );\n }\n #else\n #ifndef USE_MORPHNORMALS\n uniform float morphTargetInfluences[ 8 ];\n #else\n uniform float morphTargetInfluences[ 4 ];\n #endif\n #endif\n#endif"; var morphtarget_vertex = "#ifdef USE_MORPHTARGETS\n transformed *= morphTargetBaseInfluence;\n #ifdef MORPHTARGETS_TEXTURE\n for ( int i = 0; i < MORPHTARGETS_COUNT; i ++ ) {\n if ( morphTargetInfluences[ i ] != 0.0 ) transformed += getMorph( gl_VertexID, i, 0 ).xyz * morphTargetInfluences[ i ];\n }\n #else\n transformed += morphTarget0 * morphTargetInfluences[ 0 ];\n transformed += morphTarget1 * morphTargetInfluences[ 1 ];\n transformed += morphTarget2 * morphTargetInfluences[ 2 ];\n transformed += morphTarget3 * morphTargetInfluences[ 3 ];\n #ifndef USE_MORPHNORMALS\n transformed += morphTarget4 * morphTargetInfluences[ 4 ];\n transformed += morphTarget5 * morphTargetInfluences[ 5 ];\n transformed += morphTarget6 * morphTargetInfluences[ 6 ];\n transformed += morphTarget7 * morphTargetInfluences[ 7 ];\n #endif\n #endif\n#endif"; var normal_fragment_begin = "float faceDirection = gl_FrontFacing ? 1.0 : - 1.0;\n#ifdef FLAT_SHADED\n vec3 fdx = dFdx( vViewPosition );\n vec3 fdy = dFdy( vViewPosition );\n vec3 normal = normalize( cross( fdx, fdy ) );\n#else\n vec3 normal = normalize( vNormal );\n #ifdef DOUBLE_SIDED\n normal = normal * faceDirection;\n #endif\n #ifdef USE_TANGENT\n vec3 tangent = normalize( vTangent );\n vec3 bitangent = normalize( vBitangent );\n #ifdef DOUBLE_SIDED\n tangent = tangent * faceDirection;\n bitangent = bitangent * faceDirection;\n #endif\n #if defined( TANGENTSPACE_NORMALMAP ) || defined( USE_CLEARCOAT_NORMALMAP )\n mat3 vTBN = mat3( tangent, bitangent, normal );\n #endif\n #endif\n#endif\nvec3 geometryNormal = normal;"; var normal_fragment_maps = "#ifdef OBJECTSPACE_NORMALMAP\n normal = texture2D( normalMap, vUv ).xyz * 2.0 - 1.0;\n #ifdef FLIP_SIDED\n normal = - normal;\n #endif\n #ifdef DOUBLE_SIDED\n normal = normal * faceDirection;\n #endif\n normal = normalize( normalMatrix * normal );\n#elif defined( TANGENTSPACE_NORMALMAP )\n vec3 mapN = texture2D( normalMap, vUv ).xyz * 2.0 - 1.0;\n mapN.xy *= normalScale;\n #ifdef USE_TANGENT\n normal = normalize( vTBN * mapN );\n #else\n normal = perturbNormal2Arb( - vViewPosition, normal, mapN, faceDirection );\n #endif\n#elif defined( USE_BUMPMAP )\n normal = perturbNormalArb( - vViewPosition, normal, dHdxy_fwd(), faceDirection );\n#endif"; var normal_pars_fragment = "#ifndef FLAT_SHADED\n varying vec3 vNormal;\n #ifdef USE_TANGENT\n varying vec3 vTangent;\n varying vec3 vBitangent;\n #endif\n#endif"; var normal_pars_vertex = "#ifndef FLAT_SHADED\n varying vec3 vNormal;\n #ifdef USE_TANGENT\n varying vec3 vTangent;\n varying vec3 vBitangent;\n #endif\n#endif"; var normal_vertex = "#ifndef FLAT_SHADED\n vNormal = normalize( transformedNormal );\n #ifdef USE_TANGENT\n vTangent = normalize( transformedTangent );\n vBitangent = normalize( cross( vNormal, vTangent ) * tangent.w );\n #endif\n#endif"; var normalmap_pars_fragment = "#ifdef USE_NORMALMAP\n uniform sampler2D normalMap;\n uniform vec2 normalScale;\n#endif\n#ifdef OBJECTSPACE_NORMALMAP\n uniform mat3 normalMatrix;\n#endif\n#if ! defined ( USE_TANGENT ) && ( defined ( TANGENTSPACE_NORMALMAP ) || defined ( USE_CLEARCOAT_NORMALMAP ) )\n vec3 perturbNormal2Arb( vec3 eye_pos, vec3 surf_norm, vec3 mapN, float faceDirection ) {\n vec3 q0 = dFdx( eye_pos.xyz );\n vec3 q1 = dFdy( eye_pos.xyz );\n vec2 st0 = dFdx( vUv.st );\n vec2 st1 = dFdy( vUv.st );\n vec3 N = surf_norm;\n vec3 q1perp = cross( q1, N );\n vec3 q0perp = cross( N, q0 );\n vec3 T = q1perp * st0.x + q0perp * st1.x;\n vec3 B = q1perp * st0.y + q0perp * st1.y;\n float det = max( dot( T, T ), dot( B, B ) );\n float scale = ( det == 0.0 ) ? 0.0 : faceDirection * inversesqrt( det );\n return normalize( T * ( mapN.x * scale ) + B * ( mapN.y * scale ) + N * mapN.z );\n }\n#endif"; var clearcoat_normal_fragment_begin = "#ifdef USE_CLEARCOAT\n vec3 clearcoatNormal = geometryNormal;\n#endif"; var clearcoat_normal_fragment_maps = "#ifdef USE_CLEARCOAT_NORMALMAP\n vec3 clearcoatMapN = texture2D( clearcoatNormalMap, vUv ).xyz * 2.0 - 1.0;\n clearcoatMapN.xy *= clearcoatNormalScale;\n #ifdef USE_TANGENT\n clearcoatNormal = normalize( vTBN * clearcoatMapN );\n #else\n clearcoatNormal = perturbNormal2Arb( - vViewPosition, clearcoatNormal, clearcoatMapN, faceDirection );\n #endif\n#endif"; var clearcoat_pars_fragment = "#ifdef USE_CLEARCOATMAP\n uniform sampler2D clearcoatMap;\n#endif\n#ifdef USE_CLEARCOAT_ROUGHNESSMAP\n uniform sampler2D clearcoatRoughnessMap;\n#endif\n#ifdef USE_CLEARCOAT_NORMALMAP\n uniform sampler2D clearcoatNormalMap;\n uniform vec2 clearcoatNormalScale;\n#endif"; var iridescence_pars_fragment = "#ifdef USE_IRIDESCENCEMAP\n uniform sampler2D iridescenceMap;\n#endif\n#ifdef USE_IRIDESCENCE_THICKNESSMAP\n uniform sampler2D iridescenceThicknessMap;\n#endif"; var output_fragment = "#ifdef OPAQUE\ndiffuseColor.a = 1.0;\n#endif\n#ifdef USE_TRANSMISSION\ndiffuseColor.a *= material.transmissionAlpha + 0.1;\n#endif\ngl_FragColor = vec4( outgoingLight, diffuseColor.a );"; var packing = "vec3 packNormalToRGB( const in vec3 normal ) {\n return normalize( normal ) * 0.5 + 0.5;\n}\nvec3 unpackRGBToNormal( const in vec3 rgb ) {\n return 2.0 * rgb.xyz - 1.0;\n}\nconst float PackUpscale = 256. / 255.;const float UnpackDownscale = 255. / 256.;\nconst vec3 PackFactors = vec3( 256. * 256. * 256., 256. * 256., 256. );\nconst vec4 UnpackFactors = UnpackDownscale / vec4( PackFactors, 1. );\nconst float ShiftRight8 = 1. / 256.;\nvec4 packDepthToRGBA( const in float v ) {\n vec4 r = vec4( fract( v * PackFactors ), v );\n r.yzw -= r.xyz * ShiftRight8; return r * PackUpscale;\n}\nfloat unpackRGBAToDepth( const in vec4 v ) {\n return dot( v, UnpackFactors );\n}\nvec2 packDepthToRG( in highp float v ) {\n return packDepthToRGBA( v ).yx;\n}\nfloat unpackRGToDepth( const in highp vec2 v ) {\n return unpackRGBAToDepth( vec4( v.xy, 0.0, 0.0 ) );\n}\nvec4 pack2HalfToRGBA( vec2 v ) {\n vec4 r = vec4( v.x, fract( v.x * 255.0 ), v.y, fract( v.y * 255.0 ) );\n return vec4( r.x - r.y / 255.0, r.y, r.z - r.w / 255.0, r.w );\n}\nvec2 unpackRGBATo2Half( vec4 v ) {\n return vec2( v.x + ( v.y / 255.0 ), v.z + ( v.w / 255.0 ) );\n}\nfloat viewZToOrthographicDepth( const in float viewZ, const in float near, const in float far ) {\n return ( viewZ + near ) / ( near - far );\n}\nfloat orthographicDepthToViewZ( const in float linearClipZ, const in float near, const in float far ) {\n return linearClipZ * ( near - far ) - near;\n}\nfloat viewZToPerspectiveDepth( const in float viewZ, const in float near, const in float far ) {\n return ( ( near + viewZ ) * far ) / ( ( far - near ) * viewZ );\n}\nfloat perspectiveDepthToViewZ( const in float invClipZ, const in float near, const in float far ) {\n return ( near * far ) / ( ( far - near ) * invClipZ - far );\n}"; var premultiplied_alpha_fragment = "#ifdef PREMULTIPLIED_ALPHA\n gl_FragColor.rgb *= gl_FragColor.a;\n#endif"; var project_vertex = "vec4 mvPosition = vec4( transformed, 1.0 );\n#ifdef USE_INSTANCING\n mvPosition = instanceMatrix * mvPosition;\n#endif\nmvPosition = modelViewMatrix * mvPosition;\ngl_Position = projectionMatrix * mvPosition;"; var dithering_fragment = "#ifdef DITHERING\n gl_FragColor.rgb = dithering( gl_FragColor.rgb );\n#endif"; var dithering_pars_fragment = "#ifdef DITHERING\n vec3 dithering( vec3 color ) {\n float grid_position = rand( gl_FragCoord.xy );\n vec3 dither_shift_RGB = vec3( 0.25 / 255.0, -0.25 / 255.0, 0.25 / 255.0 );\n dither_shift_RGB = mix( 2.0 * dither_shift_RGB, -2.0 * dither_shift_RGB, grid_position );\n return color + dither_shift_RGB;\n }\n#endif"; var roughnessmap_fragment = "float roughnessFactor = roughness;\n#ifdef USE_ROUGHNESSMAP\n vec4 texelRoughness = texture2D( roughnessMap, vUv );\n roughnessFactor *= texelRoughness.g;\n#endif"; var roughnessmap_pars_fragment = "#ifdef USE_ROUGHNESSMAP\n uniform sampler2D roughnessMap;\n#endif"; var shadowmap_pars_fragment = "#if NUM_SPOT_LIGHT_COORDS > 0\n varying vec4 vSpotLightCoord[ NUM_SPOT_LIGHT_COORDS ];\n#endif\n#if NUM_SPOT_LIGHT_MAPS > 0\n uniform sampler2D spotLightMap[ NUM_SPOT_LIGHT_MAPS ];\n#endif\n#ifdef USE_SHADOWMAP\n #if NUM_DIR_LIGHT_SHADOWS > 0\n uniform sampler2D directionalShadowMap[ NUM_DIR_LIGHT_SHADOWS ];\n varying vec4 vDirectionalShadowCoord[ NUM_DIR_LIGHT_SHADOWS ];\n struct DirectionalLightShadow {\n float shadowBias;\n float shadowNormalBias;\n float shadowRadius;\n vec2 shadowMapSize;\n };\n uniform DirectionalLightShadow directionalLightShadows[ NUM_DIR_LIGHT_SHADOWS ];\n #endif\n #if NUM_SPOT_LIGHT_SHADOWS > 0\n uniform sampler2D spotShadowMap[ NUM_SPOT_LIGHT_SHADOWS ];\n struct SpotLightShadow {\n float shadowBias;\n float shadowNormalBias;\n float shadowRadius;\n vec2 shadowMapSize;\n };\n uniform SpotLightShadow spotLightShadows[ NUM_SPOT_LIGHT_SHADOWS ];\n #endif\n #if NUM_POINT_LIGHT_SHADOWS > 0\n uniform sampler2D pointShadowMap[ NUM_POINT_LIGHT_SHADOWS ];\n varying vec4 vPointShadowCoord[ NUM_POINT_LIGHT_SHADOWS ];\n struct PointLightShadow {\n float shadowBias;\n float shadowNormalBias;\n float shadowRadius;\n vec2 shadowMapSize;\n float shadowCameraNear;\n float shadowCameraFar;\n };\n uniform PointLightShadow pointLightShadows[ NUM_POINT_LIGHT_SHADOWS ];\n #endif\n float texture2DCompare( sampler2D depths, vec2 uv, float compare ) {\n return step( compare, unpackRGBAToDepth( texture2D( depths, uv ) ) );\n }\n vec2 texture2DDistribution( sampler2D shadow, vec2 uv ) {\n return unpackRGBATo2Half( texture2D( shadow, uv ) );\n }\n float VSMShadow (sampler2D shadow, vec2 uv, float compare ){\n float occlusion = 1.0;\n vec2 distribution = texture2DDistribution( shadow, uv );\n float hard_shadow = step( compare , distribution.x );\n if (hard_shadow != 1.0 ) {\n float distance = compare - distribution.x ;\n float variance = max( 0.00000, distribution.y * distribution.y );\n float softness_probability = variance / (variance + distance * distance ); softness_probability = clamp( ( softness_probability - 0.3 ) / ( 0.95 - 0.3 ), 0.0, 1.0 ); occlusion = clamp( max( hard_shadow, softness_probability ), 0.0, 1.0 );\n }\n return occlusion;\n }\n float getShadow( sampler2D shadowMap, vec2 shadowMapSize, float shadowBias, float shadowRadius, vec4 shadowCoord ) {\n float shadow = 1.0;\n shadowCoord.xyz /= shadowCoord.w;\n shadowCoord.z += shadowBias;\n bvec4 inFrustumVec = bvec4 ( shadowCoord.x >= 0.0, shadowCoord.x <= 1.0, shadowCoord.y >= 0.0, shadowCoord.y <= 1.0 );\n bool inFrustum = all( inFrustumVec );\n bvec2 frustumTestVec = bvec2( inFrustum, shadowCoord.z <= 1.0 );\n bool frustumTest = all( frustumTestVec );\n if ( frustumTest ) {\n #if defined( SHADOWMAP_TYPE_PCF )\n vec2 texelSize = vec2( 1.0 ) / shadowMapSize;\n float dx0 = - texelSize.x * shadowRadius;\n float dy0 = - texelSize.y * shadowRadius;\n float dx1 = + texelSize.x * shadowRadius;\n float dy1 = + texelSize.y * shadowRadius;\n float dx2 = dx0 / 2.0;\n float dy2 = dy0 / 2.0;\n float dx3 = dx1 / 2.0;\n float dy3 = dy1 / 2.0;\n shadow = (\n texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx0, dy0 ), shadowCoord.z ) +\n texture2DCompare( shadowMap, shadowCoord.xy + vec2( 0.0, dy0 ), shadowCoord.z ) +\n texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx1, dy0 ), shadowCoord.z ) +\n texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx2, dy2 ), shadowCoord.z ) +\n texture2DCompare( shadowMap, shadowCoord.xy + vec2( 0.0, dy2 ), shadowCoord.z ) +\n texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx3, dy2 ), shadowCoord.z ) +\n texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx0, 0.0 ), shadowCoord.z ) +\n texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx2, 0.0 ), shadowCoord.z ) +\n texture2DCompare( shadowMap, shadowCoord.xy, shadowCoord.z ) +\n texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx3, 0.0 ), shadowCoord.z ) +\n texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx1, 0.0 ), shadowCoord.z ) +\n texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx2, dy3 ), shadowCoord.z ) +\n texture2DCompare( shadowMap, shadowCoord.xy + vec2( 0.0, dy3 ), shadowCoord.z ) +\n texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx3, dy3 ), shadowCoord.z ) +\n texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx0, dy1 ), shadowCoord.z ) +\n texture2DCompare( shadowMap, shadowCoord.xy + vec2( 0.0, dy1 ), shadowCoord.z ) +\n texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx1, dy1 ), shadowCoord.z )\n ) * ( 1.0 / 17.0 );\n #elif defined( SHADOWMAP_TYPE_PCF_SOFT )\n vec2 texelSize = vec2( 1.0 ) / shadowMapSize;\n float dx = texelSize.x;\n float dy = texelSize.y;\n vec2 uv = shadowCoord.xy;\n vec2 f = fract( uv * shadowMapSize + 0.5 );\n uv -= f * texelSize;\n shadow = (\n texture2DCompare( shadowMap, uv, shadowCoord.z ) +\n texture2DCompare( shadowMap, uv + vec2( dx, 0.0 ), shadowCoord.z ) +\n texture2DCompare( shadowMap, uv + vec2( 0.0, dy ), shadowCoord.z ) +\n texture2DCompare( shadowMap, uv + texelSize, shadowCoord.z ) +\n mix( texture2DCompare( shadowMap, uv + vec2( -dx, 0.0 ), shadowCoord.z ),\n texture2DCompare( shadowMap, uv + vec2( 2.0 * dx, 0.0 ), shadowCoord.z ),\n f.x ) +\n mix( texture2DCompare( shadowMap, uv + vec2( -dx, dy ), shadowCoord.z ),\n texture2DCompare( shadowMap, uv + vec2( 2.0 * dx, dy ), shadowCoord.z ),\n f.x ) +\n mix( texture2DCompare( shadowMap, uv + vec2( 0.0, -dy ), shadowCoord.z ),\n texture2DCompare( shadowMap, uv + vec2( 0.0, 2.0 * dy ), shadowCoord.z ),\n f.y ) +\n mix( texture2DCompare( shadowMap, uv + vec2( dx, -dy ), shadowCoord.z ),\n texture2DCompare( shadowMap, uv + vec2( dx, 2.0 * dy ), shadowCoord.z ),\n f.y ) +\n mix( mix( texture2DCompare( shadowMap, uv + vec2( -dx, -dy ), shadowCoord.z ),\n texture2DCompare( shadowMap, uv + vec2( 2.0 * dx, -dy ), shadowCoord.z ),\n f.x ),\n mix( texture2DCompare( shadowMap, uv + vec2( -dx, 2.0 * dy ), shadowCoord.z ),\n texture2DCompare( shadowMap, uv + vec2( 2.0 * dx, 2.0 * dy ), shadowCoord.z ),\n f.x ),\n f.y )\n ) * ( 1.0 / 9.0 );\n #elif defined( SHADOWMAP_TYPE_VSM )\n shadow = VSMShadow( shadowMap, shadowCoord.xy, shadowCoord.z );\n #else\n shadow = texture2DCompare( shadowMap, shadowCoord.xy, shadowCoord.z );\n #endif\n }\n return shadow;\n }\n vec2 cubeToUV( vec3 v, float texelSizeY ) {\n vec3 absV = abs( v );\n float scaleToCube = 1.0 / max( absV.x, max( absV.y, absV.z ) );\n absV *= scaleToCube;\n v *= scaleToCube * ( 1.0 - 2.0 * texelSizeY );\n vec2 planar = v.xy;\n float almostATexel = 1.5 * texelSizeY;\n float almostOne = 1.0 - almostATexel;\n if ( absV.z >= almostOne ) {\n if ( v.z > 0.0 )\n planar.x = 4.0 - v.x;\n } else if ( absV.x >= almostOne ) {\n float signX = sign( v.x );\n planar.x = v.z * signX + 2.0 * signX;\n } else if ( absV.y >= almostOne ) {\n float signY = sign( v.y );\n planar.x = v.x + 2.0 * signY + 2.0;\n planar.y = v.z * signY - 2.0;\n }\n return vec2( 0.125, 0.25 ) * planar + vec2( 0.375, 0.75 );\n }\n float getPointShadow( sampler2D shadowMap, vec2 shadowMapSize, float shadowBias, float shadowRadius, vec4 shadowCoord, float shadowCameraNear, float shadowCameraFar ) {\n vec2 texelSize = vec2( 1.0 ) / ( shadowMapSize * vec2( 4.0, 2.0 ) );\n vec3 lightToPosition = shadowCoord.xyz;\n float dp = ( length( lightToPosition ) - shadowCameraNear ) / ( shadowCameraFar - shadowCameraNear ); dp += shadowBias;\n vec3 bd3D = normalize( lightToPosition );\n #if defined( SHADOWMAP_TYPE_PCF ) || defined( SHADOWMAP_TYPE_PCF_SOFT ) || defined( SHADOWMAP_TYPE_VSM )\n vec2 offset = vec2( - 1, 1 ) * shadowRadius * texelSize.y;\n return (\n texture2DCompare( shadowMap, cubeToUV( bd3D + offset.xyy, texelSize.y ), dp ) +\n texture2DCompare( shadowMap, cubeToUV( bd3D + offset.yyy, texelSize.y ), dp ) +\n texture2DCompare( shadowMap, cubeToUV( bd3D + offset.xyx, texelSize.y ), dp ) +\n texture2DCompare( shadowMap, cubeToUV( bd3D + offset.yyx, texelSize.y ), dp ) +\n texture2DCompare( shadowMap, cubeToUV( bd3D, texelSize.y ), dp ) +\n texture2DCompare( shadowMap, cubeToUV( bd3D + offset.xxy, texelSize.y ), dp ) +\n texture2DCompare( shadowMap, cubeToUV( bd3D + offset.yxy, texelSize.y ), dp ) +\n texture2DCompare( shadowMap, cubeToUV( bd3D + offset.xxx, texelSize.y ), dp ) +\n texture2DCompare( shadowMap, cubeToUV( bd3D + offset.yxx, texelSize.y ), dp )\n ) * ( 1.0 / 9.0 );\n #else\n return texture2DCompare( shadowMap, cubeToUV( bd3D, texelSize.y ), dp );\n #endif\n }\n#endif"; var shadowmap_pars_vertex = "#if NUM_SPOT_LIGHT_COORDS > 0\n uniform mat4 spotLightMatrix[ NUM_SPOT_LIGHT_COORDS ];\n varying vec4 vSpotLightCoord[ NUM_SPOT_LIGHT_COORDS ];\n#endif\n#ifdef USE_SHADOWMAP\n #if NUM_DIR_LIGHT_SHADOWS > 0\n uniform mat4 directionalShadowMatrix[ NUM_DIR_LIGHT_SHADOWS ];\n varying vec4 vDirectionalShadowCoord[ NUM_DIR_LIGHT_SHADOWS ];\n struct DirectionalLightShadow {\n float shadowBias;\n float shadowNormalBias;\n float shadowRadius;\n vec2 shadowMapSize;\n };\n uniform DirectionalLightShadow directionalLightShadows[ NUM_DIR_LIGHT_SHADOWS ];\n #endif\n #if NUM_SPOT_LIGHT_SHADOWS > 0\n struct SpotLightShadow {\n float shadowBias;\n float shadowNormalBias;\n float shadowRadius;\n vec2 shadowMapSize;\n };\n uniform SpotLightShadow spotLightShadows[ NUM_SPOT_LIGHT_SHADOWS ];\n #endif\n #if NUM_POINT_LIGHT_SHADOWS > 0\n uniform mat4 pointShadowMatrix[ NUM_POINT_LIGHT_SHADOWS ];\n varying vec4 vPointShadowCoord[ NUM_POINT_LIGHT_SHADOWS ];\n struct PointLightShadow {\n float shadowBias;\n float shadowNormalBias;\n float shadowRadius;\n vec2 shadowMapSize;\n float shadowCameraNear;\n float shadowCameraFar;\n };\n uniform PointLightShadow pointLightShadows[ NUM_POINT_LIGHT_SHADOWS ];\n #endif\n#endif"; var shadowmap_vertex = "#if defined( USE_SHADOWMAP ) || ( NUM_SPOT_LIGHT_COORDS > 0 )\n #if NUM_DIR_LIGHT_SHADOWS > 0 || NUM_SPOT_LIGHT_COORDS > 0 || NUM_POINT_LIGHT_SHADOWS > 0\n vec3 shadowWorldNormal = inverseTransformDirection( transformedNormal, viewMatrix );\n vec4 shadowWorldPosition;\n #endif\n #if NUM_DIR_LIGHT_SHADOWS > 0\n #pragma unroll_loop_start\n for ( int i = 0; i < NUM_DIR_LIGHT_SHADOWS; i ++ ) {\n shadowWorldPosition = worldPosition + vec4( shadowWorldNormal * directionalLightShadows[ i ].shadowNormalBias, 0 );\n vDirectionalShadowCoord[ i ] = directionalShadowMatrix[ i ] * shadowWorldPosition;\n }\n #pragma unroll_loop_end\n #endif\n #if NUM_SPOT_LIGHT_COORDS > 0\n #pragma unroll_loop_start\n for ( int i = 0; i < NUM_SPOT_LIGHT_COORDS; i ++ ) {\n shadowWorldPosition = worldPosition;\n #if ( defined( USE_SHADOWMAP ) && UNROLLED_LOOP_INDEX < NUM_SPOT_LIGHT_SHADOWS )\n shadowWorldPosition.xyz += shadowWorldNormal * spotLightShadows[ i ].shadowNormalBias;\n #endif\n vSpotLightCoord[ i ] = spotLightMatrix[ i ] * shadowWorldPosition;\n }\n #pragma unroll_loop_end\n #endif\n #if NUM_POINT_LIGHT_SHADOWS > 0\n #pragma unroll_loop_start\n for ( int i = 0; i < NUM_POINT_LIGHT_SHADOWS; i ++ ) {\n shadowWorldPosition = worldPosition + vec4( shadowWorldNormal * pointLightShadows[ i ].shadowNormalBias, 0 );\n vPointShadowCoord[ i ] = pointShadowMatrix[ i ] * shadowWorldPosition;\n }\n #pragma unroll_loop_end\n #endif\n#endif"; var shadowmask_pars_fragment = "float getShadowMask() {\n float shadow = 1.0;\n #ifdef USE_SHADOWMAP\n #if NUM_DIR_LIGHT_SHADOWS > 0\n DirectionalLightShadow directionalLight;\n #pragma unroll_loop_start\n for ( int i = 0; i < NUM_DIR_LIGHT_SHADOWS; i ++ ) {\n directionalLight = directionalLightShadows[ i ];\n shadow *= receiveShadow ? getShadow( directionalShadowMap[ i ], directionalLight.shadowMapSize, directionalLight.shadowBias, directionalLight.shadowRadius, vDirectionalShadowCoord[ i ] ) : 1.0;\n }\n #pragma unroll_loop_end\n #endif\n #if NUM_SPOT_LIGHT_SHADOWS > 0\n SpotLightShadow spotLight;\n #pragma unroll_loop_start\n for ( int i = 0; i < NUM_SPOT_LIGHT_SHADOWS; i ++ ) {\n spotLight = spotLightShadows[ i ];\n shadow *= receiveShadow ? getShadow( spotShadowMap[ i ], spotLight.shadowMapSize, spotLight.shadowBias, spotLight.shadowRadius, vSpotLightCoord[ i ] ) : 1.0;\n }\n #pragma unroll_loop_end\n #endif\n #if NUM_POINT_LIGHT_SHADOWS > 0\n PointLightShadow pointLight;\n #pragma unroll_loop_start\n for ( int i = 0; i < NUM_POINT_LIGHT_SHADOWS; i ++ ) {\n pointLight = pointLightShadows[ i ];\n shadow *= receiveShadow ? getPointShadow( pointShadowMap[ i ], pointLight.shadowMapSize, pointLight.shadowBias, pointLight.shadowRadius, vPointShadowCoord[ i ], pointLight.shadowCameraNear, pointLight.shadowCameraFar ) : 1.0;\n }\n #pragma unroll_loop_end\n #endif\n #endif\n return shadow;\n}"; var skinbase_vertex = "#ifdef USE_SKINNING\n mat4 boneMatX = getBoneMatrix( skinIndex.x );\n mat4 boneMatY = getBoneMatrix( skinIndex.y );\n mat4 boneMatZ = getBoneMatrix( skinIndex.z );\n mat4 boneMatW = getBoneMatrix( skinIndex.w );\n#endif"; var skinning_pars_vertex = "#ifdef USE_SKINNING\n uniform mat4 bindMatrix;\n uniform mat4 bindMatrixInverse;\n uniform highp sampler2D boneTexture;\n uniform int boneTextureSize;\n mat4 getBoneMatrix( const in float i ) {\n float j = i * 4.0;\n float x = mod( j, float( boneTextureSize ) );\n float y = floor( j / float( boneTextureSize ) );\n float dx = 1.0 / float( boneTextureSize );\n float dy = 1.0 / float( boneTextureSize );\n y = dy * ( y + 0.5 );\n vec4 v1 = texture2D( boneTexture, vec2( dx * ( x + 0.5 ), y ) );\n vec4 v2 = texture2D( boneTexture, vec2( dx * ( x + 1.5 ), y ) );\n vec4 v3 = texture2D( boneTexture, vec2( dx * ( x + 2.5 ), y ) );\n vec4 v4 = texture2D( boneTexture, vec2( dx * ( x + 3.5 ), y ) );\n mat4 bone = mat4( v1, v2, v3, v4 );\n return bone;\n }\n#endif"; var skinning_vertex = "#ifdef USE_SKINNING\n vec4 skinVertex = bindMatrix * vec4( transformed, 1.0 );\n vec4 skinned = vec4( 0.0 );\n skinned += boneMatX * skinVertex * skinWeight.x;\n skinned += boneMatY * skinVertex * skinWeight.y;\n skinned += boneMatZ * skinVertex * skinWeight.z;\n skinned += boneMatW * skinVertex * skinWeight.w;\n transformed = ( bindMatrixInverse * skinned ).xyz;\n#endif"; var skinnormal_vertex = "#ifdef USE_SKINNING\n mat4 skinMatrix = mat4( 0.0 );\n skinMatrix += skinWeight.x * boneMatX;\n skinMatrix += skinWeight.y * boneMatY;\n skinMatrix += skinWeight.z * boneMatZ;\n skinMatrix += skinWeight.w * boneMatW;\n skinMatrix = bindMatrixInverse * skinMatrix * bindMatrix;\n objectNormal = vec4( skinMatrix * vec4( objectNormal, 0.0 ) ).xyz;\n #ifdef USE_TANGENT\n objectTangent = vec4( skinMatrix * vec4( objectTangent, 0.0 ) ).xyz;\n #endif\n#endif"; var specularmap_fragment = "float specularStrength;\n#ifdef USE_SPECULARMAP\n vec4 texelSpecular = texture2D( specularMap, vUv );\n specularStrength = texelSpecular.r;\n#else\n specularStrength = 1.0;\n#endif"; var specularmap_pars_fragment = "#ifdef USE_SPECULARMAP\n uniform sampler2D specularMap;\n#endif"; var tonemapping_fragment = "#if defined( TONE_MAPPING )\n gl_FragColor.rgb = toneMapping( gl_FragColor.rgb );\n#endif"; var tonemapping_pars_fragment = "#ifndef saturate\n#define saturate( a ) clamp( a, 0.0, 1.0 )\n#endif\nuniform float toneMappingExposure;\nvec3 LinearToneMapping( vec3 color ) {\n return toneMappingExposure * color;\n}\nvec3 ReinhardToneMapping( vec3 color ) {\n color *= toneMappingExposure;\n return saturate( color / ( vec3( 1.0 ) + color ) );\n}\nvec3 OptimizedCineonToneMapping( vec3 color ) {\n color *= toneMappingExposure;\n color = max( vec3( 0.0 ), color - 0.004 );\n return pow( ( color * ( 6.2 * color + 0.5 ) ) / ( color * ( 6.2 * color + 1.7 ) + 0.06 ), vec3( 2.2 ) );\n}\nvec3 RRTAndODTFit( vec3 v ) {\n vec3 a = v * ( v + 0.0245786 ) - 0.000090537;\n vec3 b = v * ( 0.983729 * v + 0.4329510 ) + 0.238081;\n return a / b;\n}\nvec3 ACESFilmicToneMapping( vec3 color ) {\n const mat3 ACESInputMat = mat3(\n vec3( 0.59719, 0.07600, 0.02840 ), vec3( 0.35458, 0.90834, 0.13383 ),\n vec3( 0.04823, 0.01566, 0.83777 )\n );\n const mat3 ACESOutputMat = mat3(\n vec3( 1.60475, -0.10208, -0.00327 ), vec3( -0.53108, 1.10813, -0.07276 ),\n vec3( -0.07367, -0.00605, 1.07602 )\n );\n color *= toneMappingExposure / 0.6;\n color = ACESInputMat * color;\n color = RRTAndODTFit( color );\n color = ACESOutputMat * color;\n return saturate( color );\n}\nvec3 CustomToneMapping( vec3 color ) { return color; }"; var transmission_fragment = "#ifdef USE_TRANSMISSION\n material.transmission = transmission;\n material.transmissionAlpha = 1.0;\n material.thickness = thickness;\n material.attenuationDistance = attenuationDistance;\n material.attenuationColor = attenuationColor;\n #ifdef USE_TRANSMISSIONMAP\n material.transmission *= texture2D( transmissionMap, vUv ).r;\n #endif\n #ifdef USE_THICKNESSMAP\n material.thickness *= texture2D( thicknessMap, vUv ).g;\n #endif\n vec3 pos = vWorldPosition;\n vec3 v = normalize( cameraPosition - pos );\n vec3 n = inverseTransformDirection( normal, viewMatrix );\n vec4 transmission = getIBLVolumeRefraction(\n n, v, material.roughness, material.diffuseColor, material.specularColor, material.specularF90,\n pos, modelMatrix, viewMatrix, projectionMatrix, material.ior, material.thickness,\n material.attenuationColor, material.attenuationDistance );\n material.transmissionAlpha = mix( material.transmissionAlpha, transmission.a, material.transmission );\n totalDiffuse = mix( totalDiffuse, transmission.rgb, material.transmission );\n#endif"; var transmission_pars_fragment = "#ifdef USE_TRANSMISSION\n uniform float transmission;\n uniform float thickness;\n uniform float attenuationDistance;\n uniform vec3 attenuationColor;\n #ifdef USE_TRANSMISSIONMAP\n uniform sampler2D transmissionMap;\n #endif\n #ifdef USE_THICKNESSMAP\n uniform sampler2D thicknessMap;\n #endif\n uniform vec2 transmissionSamplerSize;\n uniform sampler2D transmissionSamplerMap;\n uniform mat4 modelMatrix;\n uniform mat4 projectionMatrix;\n varying vec3 vWorldPosition;\n vec3 getVolumeTransmissionRay( const in vec3 n, const in vec3 v, const in float thickness, const in float ior, const in mat4 modelMatrix ) {\n vec3 refractionVector = refract( - v, normalize( n ), 1.0 / ior );\n vec3 modelScale;\n modelScale.x = length( vec3( modelMatrix[ 0 ].xyz ) );\n modelScale.y = length( vec3( modelMatrix[ 1 ].xyz ) );\n modelScale.z = length( vec3( modelMatrix[ 2 ].xyz ) );\n return normalize( refractionVector ) * thickness * modelScale;\n }\n float applyIorToRoughness( const in float roughness, const in float ior ) {\n return roughness * clamp( ior * 2.0 - 2.0, 0.0, 1.0 );\n }\n vec4 getTransmissionSample( const in vec2 fragCoord, const in float roughness, const in float ior ) {\n float framebufferLod = log2( transmissionSamplerSize.x ) * applyIorToRoughness( roughness, ior );\n #ifdef texture2DLodEXT\n return texture2DLodEXT( transmissionSamplerMap, fragCoord.xy, framebufferLod );\n #else\n return texture2D( transmissionSamplerMap, fragCoord.xy, framebufferLod );\n #endif\n }\n vec3 applyVolumeAttenuation( const in vec3 radiance, const in float transmissionDistance, const in vec3 attenuationColor, const in float attenuationDistance ) {\n if ( isinf( attenuationDistance ) ) {\n return radiance;\n } else {\n vec3 attenuationCoefficient = -log( attenuationColor ) / attenuationDistance;\n vec3 transmittance = exp( - attenuationCoefficient * transmissionDistance ); return transmittance * radiance;\n }\n }\n vec4 getIBLVolumeRefraction( const in vec3 n, const in vec3 v, const in float roughness, const in vec3 diffuseColor,\n const in vec3 specularColor, const in float specularF90, const in vec3 position, const in mat4 modelMatrix,\n const in mat4 viewMatrix, const in mat4 projMatrix, const in float ior, const in float thickness,\n const in vec3 attenuationColor, const in float attenuationDistance ) {\n vec3 transmissionRay = getVolumeTransmissionRay( n, v, thickness, ior, modelMatrix );\n vec3 refractedRayExit = position + transmissionRay;\n vec4 ndcPos = projMatrix * viewMatrix * vec4( refractedRayExit, 1.0 );\n vec2 refractionCoords = ndcPos.xy / ndcPos.w;\n refractionCoords += 1.0;\n refractionCoords /= 2.0;\n vec4 transmittedLight = getTransmissionSample( refractionCoords, roughness, ior );\n vec3 attenuatedColor = applyVolumeAttenuation( transmittedLight.rgb, length( transmissionRay ), attenuationColor, attenuationDistance );\n vec3 F = EnvironmentBRDF( n, v, specularColor, specularF90, roughness );\n return vec4( ( 1.0 - F ) * attenuatedColor * diffuseColor, transmittedLight.a );\n }\n#endif"; var uv_pars_fragment = "#if ( defined( USE_UV ) && ! defined( UVS_VERTEX_ONLY ) )\n varying vec2 vUv;\n#endif"; var uv_pars_vertex = "#ifdef USE_UV\n #ifdef UVS_VERTEX_ONLY\n vec2 vUv;\n #else\n varying vec2 vUv;\n #endif\n uniform mat3 uvTransform;\n#endif"; var uv_vertex = "#ifdef USE_UV\n vUv = ( uvTransform * vec3( uv, 1 ) ).xy;\n#endif"; var uv2_pars_fragment = "#if defined( USE_LIGHTMAP ) || defined( USE_AOMAP )\n varying vec2 vUv2;\n#endif"; var uv2_pars_vertex = "#if defined( USE_LIGHTMAP ) || defined( USE_AOMAP )\n attribute vec2 uv2;\n varying vec2 vUv2;\n uniform mat3 uv2Transform;\n#endif"; var uv2_vertex = "#if defined( USE_LIGHTMAP ) || defined( USE_AOMAP )\n vUv2 = ( uv2Transform * vec3( uv2, 1 ) ).xy;\n#endif"; var worldpos_vertex = "#if defined( USE_ENVMAP ) || defined( DISTANCE ) || defined ( USE_SHADOWMAP ) || defined ( USE_TRANSMISSION ) || NUM_SPOT_LIGHT_COORDS > 0\n vec4 worldPosition = vec4( transformed, 1.0 );\n #ifdef USE_INSTANCING\n worldPosition = instanceMatrix * worldPosition;\n #endif\n worldPosition = modelMatrix * worldPosition;\n#endif"; var vertex$h = "varying vec2 vUv;\nuniform mat3 uvTransform;\nvoid main() {\n vUv = ( uvTransform * vec3( uv, 1 ) ).xy;\n gl_Position = vec4( position.xy, 1.0, 1.0 );\n}"; var fragment$h = "uniform sampler2D t2D;\nvarying vec2 vUv;\nvoid main() {\n gl_FragColor = texture2D( t2D, vUv );\n #ifdef DECODE_VIDEO_TEXTURE\n gl_FragColor = vec4( mix( pow( gl_FragColor.rgb * 0.9478672986 + vec3( 0.0521327014 ), vec3( 2.4 ) ), gl_FragColor.rgb * 0.0773993808, vec3( lessThanEqual( gl_FragColor.rgb, vec3( 0.04045 ) ) ) ), gl_FragColor.w );\n #endif\n #include \n #include \n}"; var vertex$g = "varying vec3 vWorldDirection;\n#include \nvoid main() {\n vWorldDirection = transformDirection( position, modelMatrix );\n #include \n #include \n gl_Position.z = gl_Position.w;\n}"; var fragment$g = "#ifdef ENVMAP_TYPE_CUBE\n uniform samplerCube envMap;\n#elif defined( ENVMAP_TYPE_CUBE_UV )\n uniform sampler2D envMap;\n#endif\nuniform float flipEnvMap;\nuniform float backgroundBlurriness;\nvarying vec3 vWorldDirection;\n#include \nvoid main() {\n #ifdef ENVMAP_TYPE_CUBE\n vec4 texColor = textureCube( envMap, vec3( flipEnvMap * vWorldDirection.x, vWorldDirection.yz ) );\n #elif defined( ENVMAP_TYPE_CUBE_UV )\n vec4 texColor = textureCubeUV( envMap, vWorldDirection, backgroundBlurriness );\n #else\n vec4 texColor = vec4( 0.0, 0.0, 0.0, 1.0 );\n #endif\n gl_FragColor = texColor;\n #include \n #include \n}"; var vertex$f = "varying vec3 vWorldDirection;\n#include \nvoid main() {\n vWorldDirection = transformDirection( position, modelMatrix );\n #include \n #include \n gl_Position.z = gl_Position.w;\n}"; var fragment$f = "uniform samplerCube tCube;\nuniform float tFlip;\nuniform float opacity;\nvarying vec3 vWorldDirection;\nvoid main() {\n vec4 texColor = textureCube( tCube, vec3( tFlip * vWorldDirection.x, vWorldDirection.yz ) );\n gl_FragColor = texColor;\n gl_FragColor.a *= opacity;\n #include \n #include \n}"; var vertex$e = "#include \n#include \n#include \n#include \n#include \n#include \n#include \nvarying vec2 vHighPrecisionZW;\nvoid main() {\n #include \n #include \n #ifdef USE_DISPLACEMENTMAP\n #include \n #include \n #include \n #endif\n #include \n #include \n #include \n #include \n #include \n #include \n #include \n vHighPrecisionZW = gl_Position.zw;\n}"; var fragment$e = "#if DEPTH_PACKING == 3200\n uniform float opacity;\n#endif\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvarying vec2 vHighPrecisionZW;\nvoid main() {\n #include \n vec4 diffuseColor = vec4( 1.0 );\n #if DEPTH_PACKING == 3200\n diffuseColor.a = opacity;\n #endif\n #include \n #include \n #include \n #include \n float fragCoordZ = 0.5 * vHighPrecisionZW[0] / vHighPrecisionZW[1] + 0.5;\n #if DEPTH_PACKING == 3200\n gl_FragColor = vec4( vec3( 1.0 - fragCoordZ ), opacity );\n #elif DEPTH_PACKING == 3201\n gl_FragColor = packDepthToRGBA( fragCoordZ );\n #endif\n}"; var vertex$d = "#define DISTANCE\nvarying vec3 vWorldPosition;\n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n #include \n #include \n #ifdef USE_DISPLACEMENTMAP\n #include \n #include \n #include \n #endif\n #include \n #include \n #include \n #include \n #include \n #include \n #include \n vWorldPosition = worldPosition.xyz;\n}"; var fragment$d = "#define DISTANCE\nuniform vec3 referencePosition;\nuniform float nearDistance;\nuniform float farDistance;\nvarying vec3 vWorldPosition;\n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main () {\n #include \n vec4 diffuseColor = vec4( 1.0 );\n #include \n #include \n #include \n float dist = length( vWorldPosition - referencePosition );\n dist = ( dist - nearDistance ) / ( farDistance - nearDistance );\n dist = saturate( dist );\n gl_FragColor = packDepthToRGBA( dist );\n}"; var vertex$c = "varying vec3 vWorldDirection;\n#include \nvoid main() {\n vWorldDirection = transformDirection( position, modelMatrix );\n #include \n #include \n}"; var fragment$c = "uniform sampler2D tEquirect;\nvarying vec3 vWorldDirection;\n#include \nvoid main() {\n vec3 direction = normalize( vWorldDirection );\n vec2 sampleUV = equirectUv( direction );\n gl_FragColor = texture2D( tEquirect, sampleUV );\n #include \n #include \n}"; var vertex$b = "uniform float scale;\nattribute float lineDistance;\nvarying float vLineDistance;\n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n vLineDistance = scale * lineDistance;\n #include \n #include \n #include \n #include \n #include \n #include \n #include \n #include \n}"; var fragment$b = "uniform vec3 diffuse;\nuniform float opacity;\nuniform float dashSize;\nuniform float totalSize;\nvarying float vLineDistance;\n#include \n#include \n#include \n#include \n#include \nvoid main() {\n #include \n if ( mod( vLineDistance, totalSize ) > dashSize ) {\n discard;\n }\n vec3 outgoingLight = vec3( 0.0 );\n vec4 diffuseColor = vec4( diffuse, opacity );\n #include \n #include \n outgoingLight = diffuseColor.rgb;\n #include \n #include \n #include \n #include \n #include \n}"; var vertex$a = "#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n #include \n #include \n #include \n #include \n #if defined ( USE_ENVMAP ) || defined ( USE_SKINNING )\n #include \n #include \n #include \n #include \n #include \n #endif\n #include \n #include \n #include \n #include \n #include \n #include \n #include \n #include \n #include \n}"; var fragment$a = "uniform vec3 diffuse;\nuniform float opacity;\n#ifndef FLAT_SHADED\n varying vec3 vNormal;\n#endif\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n #include \n vec4 diffuseColor = vec4( diffuse, opacity );\n #include \n #include \n #include \n #include \n #include \n #include \n ReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );\n #ifdef USE_LIGHTMAP\n vec4 lightMapTexel = texture2D( lightMap, vUv2 );\n reflectedLight.indirectDiffuse += lightMapTexel.rgb * lightMapIntensity * RECIPROCAL_PI;\n #else\n reflectedLight.indirectDiffuse += vec3( 1.0 );\n #endif\n #include \n reflectedLight.indirectDiffuse *= diffuseColor.rgb;\n vec3 outgoingLight = reflectedLight.indirectDiffuse;\n #include \n #include \n #include \n #include \n #include \n #include \n #include \n}"; var vertex$9 = "#define LAMBERT\nvarying vec3 vViewPosition;\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n #include \n #include \n #include \n #include \n #include \n #include \n #include \n #include \n #include \n #include \n #include \n #include \n #include \n #include \n #include \n #include \n #include \n vViewPosition = - mvPosition.xyz;\n #include \n #include \n #include \n #include \n}"; var fragment$9 = "#define LAMBERT\nuniform vec3 diffuse;\nuniform vec3 emissive;\nuniform float opacity;\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n #include \n vec4 diffuseColor = vec4( diffuse, opacity );\n ReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );\n vec3 totalEmissiveRadiance = emissive;\n #include \n #include \n #include \n #include \n #include \n #include \n #include \n #include \n #include \n #include \n #include \n #include \n #include \n #include \n vec3 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + totalEmissiveRadiance;\n #include \n #include \n #include \n #include \n #include \n #include \n #include \n}"; var vertex$8 = "#define MATCAP\nvarying vec3 vViewPosition;\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n #include \n #include \n #include \n #include \n #include \n #include \n #include \n #include \n #include \n #include \n #include \n #include \n #include \n #include \n #include \n #include \n #include \n vViewPosition = - mvPosition.xyz;\n}"; var fragment$8 = "#define MATCAP\nuniform vec3 diffuse;\nuniform float opacity;\nuniform sampler2D matcap;\nvarying vec3 vViewPosition;\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n #include \n vec4 diffuseColor = vec4( diffuse, opacity );\n #include \n #include \n #include \n #include \n #include \n #include \n #include \n vec3 viewDir = normalize( vViewPosition );\n vec3 x = normalize( vec3( viewDir.z, 0.0, - viewDir.x ) );\n vec3 y = cross( viewDir, x );\n vec2 uv = vec2( dot( x, normal ), dot( y, normal ) ) * 0.495 + 0.5;\n #ifdef USE_MATCAP\n vec4 matcapColor = texture2D( matcap, uv );\n #else\n vec4 matcapColor = vec4( vec3( mix( 0.2, 0.8, uv.y ) ), 1.0 );\n #endif\n vec3 outgoingLight = diffuseColor.rgb * matcapColor.rgb;\n #include \n #include \n #include \n #include \n #include \n #include \n}"; var vertex$7 = "#define NORMAL\n#if defined( FLAT_SHADED ) || defined( USE_BUMPMAP ) || defined( TANGENTSPACE_NORMALMAP )\n varying vec3 vViewPosition;\n#endif\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n #include \n #include \n #include \n #include \n #include \n #include \n #include \n #include \n #include \n #include \n #include \n #include \n #include \n #include \n#if defined( FLAT_SHADED ) || defined( USE_BUMPMAP ) || defined( TANGENTSPACE_NORMALMAP )\n vViewPosition = - mvPosition.xyz;\n#endif\n}"; var fragment$7 = "#define NORMAL\nuniform float opacity;\n#if defined( FLAT_SHADED ) || defined( USE_BUMPMAP ) || defined( TANGENTSPACE_NORMALMAP )\n varying vec3 vViewPosition;\n#endif\n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n #include \n #include \n #include \n #include \n gl_FragColor = vec4( packNormalToRGB( normal ), opacity );\n #ifdef OPAQUE\n gl_FragColor.a = 1.0;\n #endif\n}"; var vertex$6 = "#define PHONG\nvarying vec3 vViewPosition;\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n #include \n #include \n #include \n #include \n #include \n #include \n #include \n #include \n #include \n #include \n #include \n #include \n #include \n #include \n #include \n #include \n #include \n vViewPosition = - mvPosition.xyz;\n #include \n #include \n #include \n #include \n}"; var fragment$6 = "#define PHONG\nuniform vec3 diffuse;\nuniform vec3 emissive;\nuniform vec3 specular;\nuniform float shininess;\nuniform float opacity;\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n #include \n vec4 diffuseColor = vec4( diffuse, opacity );\n ReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );\n vec3 totalEmissiveRadiance = emissive;\n #include \n #include \n #include \n #include \n #include \n #include \n #include \n #include \n #include \n #include \n #include \n #include \n #include \n #include \n vec3 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + reflectedLight.directSpecular + reflectedLight.indirectSpecular + totalEmissiveRadiance;\n #include \n #include \n #include \n #include \n #include \n #include \n #include \n}"; var vertex$5 = "#define STANDARD\nvarying vec3 vViewPosition;\n#ifdef USE_TRANSMISSION\n varying vec3 vWorldPosition;\n#endif\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n #include \n #include \n #include \n #include \n #include \n #include \n #include \n #include \n #include \n #include \n #include \n #include \n #include \n #include \n #include \n #include \n #include \n vViewPosition = - mvPosition.xyz;\n #include \n #include \n #include \n#ifdef USE_TRANSMISSION\n vWorldPosition = worldPosition.xyz;\n#endif\n}"; var fragment$5 = "#define STANDARD\n#ifdef PHYSICAL\n #define IOR\n #define SPECULAR\n#endif\nuniform vec3 diffuse;\nuniform vec3 emissive;\nuniform float roughness;\nuniform float metalness;\nuniform float opacity;\n#ifdef IOR\n uniform float ior;\n#endif\n#ifdef SPECULAR\n uniform float specularIntensity;\n uniform vec3 specularColor;\n #ifdef USE_SPECULARINTENSITYMAP\n uniform sampler2D specularIntensityMap;\n #endif\n #ifdef USE_SPECULARCOLORMAP\n uniform sampler2D specularColorMap;\n #endif\n#endif\n#ifdef USE_CLEARCOAT\n uniform float clearcoat;\n uniform float clearcoatRoughness;\n#endif\n#ifdef USE_IRIDESCENCE\n uniform float iridescence;\n uniform float iridescenceIOR;\n uniform float iridescenceThicknessMinimum;\n uniform float iridescenceThicknessMaximum;\n#endif\n#ifdef USE_SHEEN\n uniform vec3 sheenColor;\n uniform float sheenRoughness;\n #ifdef USE_SHEENCOLORMAP\n uniform sampler2D sheenColorMap;\n #endif\n #ifdef USE_SHEENROUGHNESSMAP\n uniform sampler2D sheenRoughnessMap;\n #endif\n#endif\nvarying vec3 vViewPosition;\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n #include \n vec4 diffuseColor = vec4( diffuse, opacity );\n ReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );\n vec3 totalEmissiveRadiance = emissive;\n #include \n #include \n #include \n #include \n #include \n #include \n #include \n #include \n #include \n #include \n #include \n #include \n #include \n #include \n #include \n #include \n #include \n vec3 totalDiffuse = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse;\n vec3 totalSpecular = reflectedLight.directSpecular + reflectedLight.indirectSpecular;\n #include \n vec3 outgoingLight = totalDiffuse + totalSpecular + totalEmissiveRadiance;\n #ifdef USE_SHEEN\n float sheenEnergyComp = 1.0 - 0.157 * max3( material.sheenColor );\n outgoingLight = outgoingLight * sheenEnergyComp + sheenSpecular;\n #endif\n #ifdef USE_CLEARCOAT\n float dotNVcc = saturate( dot( geometry.clearcoatNormal, geometry.viewDir ) );\n vec3 Fcc = F_Schlick( material.clearcoatF0, material.clearcoatF90, dotNVcc );\n outgoingLight = outgoingLight * ( 1.0 - material.clearcoat * Fcc ) + clearcoatSpecular * material.clearcoat;\n #endif\n #include \n #include \n #include \n #include \n #include \n #include \n}"; var vertex$4 = "#define TOON\nvarying vec3 vViewPosition;\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n #include \n #include \n #include \n #include \n #include \n #include \n #include \n #include \n #include \n #include \n #include \n #include \n #include \n #include \n #include \n #include \n #include \n vViewPosition = - mvPosition.xyz;\n #include \n #include \n #include \n}"; var fragment$4 = "#define TOON\nuniform vec3 diffuse;\nuniform vec3 emissive;\nuniform float opacity;\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n #include \n vec4 diffuseColor = vec4( diffuse, opacity );\n ReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );\n vec3 totalEmissiveRadiance = emissive;\n #include \n #include \n #include \n #include \n #include \n #include \n #include \n #include \n #include \n #include \n #include \n #include \n #include \n vec3 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + totalEmissiveRadiance;\n #include \n #include \n #include \n #include \n #include \n #include \n}"; var vertex$3 = "uniform float size;\nuniform float scale;\n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n #include \n #include \n #include \n #include \n #include \n gl_PointSize = size;\n #ifdef USE_SIZEATTENUATION\n bool isPerspective = isPerspectiveMatrix( projectionMatrix );\n if ( isPerspective ) gl_PointSize *= ( scale / - mvPosition.z );\n #endif\n #include \n #include \n #include \n #include \n}"; var fragment$3 = "uniform vec3 diffuse;\nuniform float opacity;\n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n #include \n vec3 outgoingLight = vec3( 0.0 );\n vec4 diffuseColor = vec4( diffuse, opacity );\n #include \n #include \n #include \n #include \n outgoingLight = diffuseColor.rgb;\n #include \n #include \n #include \n #include \n #include \n}"; var vertex$2 = "#include \n#include \n#include \n#include \n#include \nvoid main() {\n #include \n #include \n #include \n #include \n #include \n #include \n #include \n #include \n #include \n #include \n #include \n #include \n}"; var fragment$2 = "uniform vec3 color;\nuniform float opacity;\n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n gl_FragColor = vec4( color, opacity * ( 1.0 - getShadowMask() ) );\n #include \n #include \n #include \n}"; var vertex$1 = "uniform float rotation;\nuniform vec2 center;\n#include \n#include \n#include \n#include \n#include \nvoid main() {\n #include \n vec4 mvPosition = modelViewMatrix * vec4( 0.0, 0.0, 0.0, 1.0 );\n vec2 scale;\n scale.x = length( vec3( modelMatrix[ 0 ].x, modelMatrix[ 0 ].y, modelMatrix[ 0 ].z ) );\n scale.y = length( vec3( modelMatrix[ 1 ].x, modelMatrix[ 1 ].y, modelMatrix[ 1 ].z ) );\n #ifndef USE_SIZEATTENUATION\n bool isPerspective = isPerspectiveMatrix( projectionMatrix );\n if ( isPerspective ) scale *= - mvPosition.z;\n #endif\n vec2 alignedPosition = ( position.xy - ( center - vec2( 0.5 ) ) ) * scale;\n vec2 rotatedPosition;\n rotatedPosition.x = cos( rotation ) * alignedPosition.x - sin( rotation ) * alignedPosition.y;\n rotatedPosition.y = sin( rotation ) * alignedPosition.x + cos( rotation ) * alignedPosition.y;\n mvPosition.xy += rotatedPosition;\n gl_Position = projectionMatrix * mvPosition;\n #include \n #include \n #include \n}"; var fragment$1 = "uniform vec3 diffuse;\nuniform float opacity;\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n #include \n vec3 outgoingLight = vec3( 0.0 );\n vec4 diffuseColor = vec4( diffuse, opacity );\n #include \n #include \n #include \n #include \n outgoingLight = diffuseColor.rgb;\n #include \n #include \n #include \n #include \n}"; var ShaderChunk = { alphamap_fragment, alphamap_pars_fragment, alphatest_fragment, alphatest_pars_fragment, aomap_fragment, aomap_pars_fragment, begin_vertex, beginnormal_vertex, bsdfs, iridescence_fragment, bumpmap_pars_fragment, clipping_planes_fragment, clipping_planes_pars_fragment, clipping_planes_pars_vertex, clipping_planes_vertex, color_fragment, color_pars_fragment, color_pars_vertex, color_vertex, common, cube_uv_reflection_fragment, defaultnormal_vertex, displacementmap_pars_vertex, displacementmap_vertex, emissivemap_fragment, emissivemap_pars_fragment, encodings_fragment, encodings_pars_fragment, envmap_fragment, envmap_common_pars_fragment, envmap_pars_fragment, envmap_pars_vertex, envmap_physical_pars_fragment, envmap_vertex, fog_vertex, fog_pars_vertex, fog_fragment, fog_pars_fragment, gradientmap_pars_fragment, lightmap_fragment, lightmap_pars_fragment, lights_lambert_fragment, lights_lambert_pars_fragment, lights_pars_begin, lights_toon_fragment, lights_toon_pars_fragment, lights_phong_fragment, lights_phong_pars_fragment, lights_physical_fragment, lights_physical_pars_fragment, lights_fragment_begin, lights_fragment_maps, lights_fragment_end, logdepthbuf_fragment, logdepthbuf_pars_fragment, logdepthbuf_pars_vertex, logdepthbuf_vertex, map_fragment, map_pars_fragment, map_particle_fragment, map_particle_pars_fragment, metalnessmap_fragment, metalnessmap_pars_fragment, morphcolor_vertex, morphnormal_vertex, morphtarget_pars_vertex, morphtarget_vertex, normal_fragment_begin, normal_fragment_maps, normal_pars_fragment, normal_pars_vertex, normal_vertex, normalmap_pars_fragment, clearcoat_normal_fragment_begin, clearcoat_normal_fragment_maps, clearcoat_pars_fragment, iridescence_pars_fragment, output_fragment, packing, premultiplied_alpha_fragment, project_vertex, dithering_fragment, dithering_pars_fragment, roughnessmap_fragment, roughnessmap_pars_fragment, shadowmap_pars_fragment, shadowmap_pars_vertex, shadowmap_vertex, shadowmask_pars_fragment, skinbase_vertex, skinning_pars_vertex, skinning_vertex, skinnormal_vertex, specularmap_fragment, specularmap_pars_fragment, tonemapping_fragment, tonemapping_pars_fragment, transmission_fragment, transmission_pars_fragment, uv_pars_fragment, uv_pars_vertex, uv_vertex, uv2_pars_fragment, uv2_pars_vertex, uv2_vertex, worldpos_vertex, background_vert: vertex$h, background_frag: fragment$h, backgroundCube_vert: vertex$g, backgroundCube_frag: fragment$g, cube_vert: vertex$f, cube_frag: fragment$f, depth_vert: vertex$e, depth_frag: fragment$e, distanceRGBA_vert: vertex$d, distanceRGBA_frag: fragment$d, equirect_vert: vertex$c, equirect_frag: fragment$c, linedashed_vert: vertex$b, linedashed_frag: fragment$b, meshbasic_vert: vertex$a, meshbasic_frag: fragment$a, meshlambert_vert: vertex$9, meshlambert_frag: fragment$9, meshmatcap_vert: vertex$8, meshmatcap_frag: fragment$8, meshnormal_vert: vertex$7, meshnormal_frag: fragment$7, meshphong_vert: vertex$6, meshphong_frag: fragment$6, meshphysical_vert: vertex$5, meshphysical_frag: fragment$5, meshtoon_vert: vertex$4, meshtoon_frag: fragment$4, points_vert: vertex$3, points_frag: fragment$3, shadow_vert: vertex$2, shadow_frag: fragment$2, sprite_vert: vertex$1, sprite_frag: fragment$1 }; var UniformsLib = { common: { diffuse: { value: new Color(16777215) }, opacity: { value: 1 }, map: { value: null }, uvTransform: { value: new Matrix3() }, uv2Transform: { value: new Matrix3() }, alphaMap: { value: null }, alphaTest: { value: 0 } }, specularmap: { specularMap: { value: null } }, envmap: { envMap: { value: null }, flipEnvMap: { value: -1 }, reflectivity: { value: 1 }, // basic, lambert, phong ior: { value: 1.5 }, // physical refractionRatio: { value: 0.98 } // basic, lambert, phong }, aomap: { aoMap: { value: null }, aoMapIntensity: { value: 1 } }, lightmap: { lightMap: { value: null }, lightMapIntensity: { value: 1 } }, emissivemap: { emissiveMap: { value: null } }, bumpmap: { bumpMap: { value: null }, bumpScale: { value: 1 } }, normalmap: { normalMap: { value: null }, normalScale: { value: new Vector2(1, 1) } }, displacementmap: { displacementMap: { value: null }, displacementScale: { value: 1 }, displacementBias: { value: 0 } }, roughnessmap: { roughnessMap: { value: null } }, metalnessmap: { metalnessMap: { value: null } }, gradientmap: { gradientMap: { value: null } }, fog: { fogDensity: { value: 25e-5 }, fogNear: { value: 1 }, fogFar: { value: 2e3 }, fogColor: { value: new Color(16777215) } }, lights: { ambientLightColor: { value: [] }, lightProbe: { value: [] }, directionalLights: { value: [], properties: { direction: {}, color: {} } }, directionalLightShadows: { value: [], properties: { shadowBias: {}, shadowNormalBias: {}, shadowRadius: {}, shadowMapSize: {} } }, directionalShadowMap: { value: [] }, directionalShadowMatrix: { value: [] }, spotLights: { value: [], properties: { color: {}, position: {}, direction: {}, distance: {}, coneCos: {}, penumbraCos: {}, decay: {} } }, spotLightShadows: { value: [], properties: { shadowBias: {}, shadowNormalBias: {}, shadowRadius: {}, shadowMapSize: {} } }, spotLightMap: { value: [] }, spotShadowMap: { value: [] }, spotLightMatrix: { value: [] }, pointLights: { value: [], properties: { color: {}, position: {}, decay: {}, distance: {} } }, pointLightShadows: { value: [], properties: { shadowBias: {}, shadowNormalBias: {}, shadowRadius: {}, shadowMapSize: {}, shadowCameraNear: {}, shadowCameraFar: {} } }, pointShadowMap: { value: [] }, pointShadowMatrix: { value: [] }, hemisphereLights: { value: [], properties: { direction: {}, skyColor: {}, groundColor: {} } }, // TODO (abelnation): RectAreaLight BRDF data needs to be moved from example to main src rectAreaLights: { value: [], properties: { color: {}, position: {}, width: {}, height: {} } }, ltc_1: { value: null }, ltc_2: { value: null } }, points: { diffuse: { value: new Color(16777215) }, opacity: { value: 1 }, size: { value: 1 }, scale: { value: 1 }, map: { value: null }, alphaMap: { value: null }, alphaTest: { value: 0 }, uvTransform: { value: new Matrix3() } }, sprite: { diffuse: { value: new Color(16777215) }, opacity: { value: 1 }, center: { value: new Vector2(0.5, 0.5) }, rotation: { value: 0 }, map: { value: null }, alphaMap: { value: null }, alphaTest: { value: 0 }, uvTransform: { value: new Matrix3() } } }; var ShaderLib = { basic: { uniforms: mergeUniforms([ UniformsLib.common, UniformsLib.specularmap, UniformsLib.envmap, UniformsLib.aomap, UniformsLib.lightmap, UniformsLib.fog ]), vertexShader: ShaderChunk.meshbasic_vert, fragmentShader: ShaderChunk.meshbasic_frag }, lambert: { uniforms: mergeUniforms([ UniformsLib.common, UniformsLib.specularmap, UniformsLib.envmap, UniformsLib.aomap, UniformsLib.lightmap, UniformsLib.emissivemap, UniformsLib.bumpmap, UniformsLib.normalmap, UniformsLib.displacementmap, UniformsLib.fog, UniformsLib.lights, { emissive: { value: new Color(0) } } ]), vertexShader: ShaderChunk.meshlambert_vert, fragmentShader: ShaderChunk.meshlambert_frag }, phong: { uniforms: mergeUniforms([ UniformsLib.common, UniformsLib.specularmap, UniformsLib.envmap, UniformsLib.aomap, UniformsLib.lightmap, UniformsLib.emissivemap, UniformsLib.bumpmap, UniformsLib.normalmap, UniformsLib.displacementmap, UniformsLib.fog, UniformsLib.lights, { emissive: { value: new Color(0) }, specular: { value: new Color(1118481) }, shininess: { value: 30 } } ]), vertexShader: ShaderChunk.meshphong_vert, fragmentShader: ShaderChunk.meshphong_frag }, standard: { uniforms: mergeUniforms([ UniformsLib.common, UniformsLib.envmap, UniformsLib.aomap, UniformsLib.lightmap, UniformsLib.emissivemap, UniformsLib.bumpmap, UniformsLib.normalmap, UniformsLib.displacementmap, UniformsLib.roughnessmap, UniformsLib.metalnessmap, UniformsLib.fog, UniformsLib.lights, { emissive: { value: new Color(0) }, roughness: { value: 1 }, metalness: { value: 0 }, envMapIntensity: { value: 1 } // temporary } ]), vertexShader: ShaderChunk.meshphysical_vert, fragmentShader: ShaderChunk.meshphysical_frag }, toon: { uniforms: mergeUniforms([ UniformsLib.common, UniformsLib.aomap, UniformsLib.lightmap, UniformsLib.emissivemap, UniformsLib.bumpmap, UniformsLib.normalmap, UniformsLib.displacementmap, UniformsLib.gradientmap, UniformsLib.fog, UniformsLib.lights, { emissive: { value: new Color(0) } } ]), vertexShader: ShaderChunk.meshtoon_vert, fragmentShader: ShaderChunk.meshtoon_frag }, matcap: { uniforms: mergeUniforms([ UniformsLib.common, UniformsLib.bumpmap, UniformsLib.normalmap, UniformsLib.displacementmap, UniformsLib.fog, { matcap: { value: null } } ]), vertexShader: ShaderChunk.meshmatcap_vert, fragmentShader: ShaderChunk.meshmatcap_frag }, points: { uniforms: mergeUniforms([ UniformsLib.points, UniformsLib.fog ]), vertexShader: ShaderChunk.points_vert, fragmentShader: ShaderChunk.points_frag }, dashed: { uniforms: mergeUniforms([ UniformsLib.common, UniformsLib.fog, { scale: { value: 1 }, dashSize: { value: 1 }, totalSize: { value: 2 } } ]), vertexShader: ShaderChunk.linedashed_vert, fragmentShader: ShaderChunk.linedashed_frag }, depth: { uniforms: mergeUniforms([ UniformsLib.common, UniformsLib.displacementmap ]), vertexShader: ShaderChunk.depth_vert, fragmentShader: ShaderChunk.depth_frag }, normal: { uniforms: mergeUniforms([ UniformsLib.common, UniformsLib.bumpmap, UniformsLib.normalmap, UniformsLib.displacementmap, { opacity: { value: 1 } } ]), vertexShader: ShaderChunk.meshnormal_vert, fragmentShader: ShaderChunk.meshnormal_frag }, sprite: { uniforms: mergeUniforms([ UniformsLib.sprite, UniformsLib.fog ]), vertexShader: ShaderChunk.sprite_vert, fragmentShader: ShaderChunk.sprite_frag }, background: { uniforms: { uvTransform: { value: new Matrix3() }, t2D: { value: null } }, vertexShader: ShaderChunk.background_vert, fragmentShader: ShaderChunk.background_frag }, backgroundCube: { uniforms: { envMap: { value: null }, flipEnvMap: { value: -1 }, backgroundBlurriness: { value: 0 } }, vertexShader: ShaderChunk.backgroundCube_vert, fragmentShader: ShaderChunk.backgroundCube_frag }, cube: { uniforms: { tCube: { value: null }, tFlip: { value: -1 }, opacity: { value: 1 } }, vertexShader: ShaderChunk.cube_vert, fragmentShader: ShaderChunk.cube_frag }, equirect: { uniforms: { tEquirect: { value: null } }, vertexShader: ShaderChunk.equirect_vert, fragmentShader: ShaderChunk.equirect_frag }, distanceRGBA: { uniforms: mergeUniforms([ UniformsLib.common, UniformsLib.displacementmap, { referencePosition: { value: new Vector3() }, nearDistance: { value: 1 }, farDistance: { value: 1e3 } } ]), vertexShader: ShaderChunk.distanceRGBA_vert, fragmentShader: ShaderChunk.distanceRGBA_frag }, shadow: { uniforms: mergeUniforms([ UniformsLib.lights, UniformsLib.fog, { color: { value: new Color(0) }, opacity: { value: 1 } } ]), vertexShader: ShaderChunk.shadow_vert, fragmentShader: ShaderChunk.shadow_frag } }; ShaderLib.physical = { uniforms: mergeUniforms([ ShaderLib.standard.uniforms, { clearcoat: { value: 0 }, clearcoatMap: { value: null }, clearcoatRoughness: { value: 0 }, clearcoatRoughnessMap: { value: null }, clearcoatNormalScale: { value: new Vector2(1, 1) }, clearcoatNormalMap: { value: null }, iridescence: { value: 0 }, iridescenceMap: { value: null }, iridescenceIOR: { value: 1.3 }, iridescenceThicknessMinimum: { value: 100 }, iridescenceThicknessMaximum: { value: 400 }, iridescenceThicknessMap: { value: null }, sheen: { value: 0 }, sheenColor: { value: new Color(0) }, sheenColorMap: { value: null }, sheenRoughness: { value: 1 }, sheenRoughnessMap: { value: null }, transmission: { value: 0 }, transmissionMap: { value: null }, transmissionSamplerSize: { value: new Vector2() }, transmissionSamplerMap: { value: null }, thickness: { value: 0 }, thicknessMap: { value: null }, attenuationDistance: { value: 0 }, attenuationColor: { value: new Color(0) }, specularIntensity: { value: 1 }, specularIntensityMap: { value: null }, specularColor: { value: new Color(1, 1, 1) }, specularColorMap: { value: null } } ]), vertexShader: ShaderChunk.meshphysical_vert, fragmentShader: ShaderChunk.meshphysical_frag }; function WebGLBackground(renderer, cubemaps, cubeuvmaps, state, objects, alpha, premultipliedAlpha) { const clearColor = new Color(0); let clearAlpha = alpha === true ? 0 : 1; let planeMesh; let boxMesh; let currentBackground = null; let currentBackgroundVersion = 0; let currentTonemapping = null; function render2(renderList, scene) { let forceClear = false; let background = scene.isScene === true ? scene.background : null; if (background && background.isTexture) { const usePMREM = scene.backgroundBlurriness > 0; background = (usePMREM ? cubeuvmaps : cubemaps).get(background); } const xr = renderer.xr; const session = xr.getSession && xr.getSession(); if (session && session.environmentBlendMode === "additive") { background = null; } if (background === null) { setClear(clearColor, clearAlpha); } else if (background && background.isColor) { setClear(background, 1); forceClear = true; } if (renderer.autoClear || forceClear) { renderer.clear(renderer.autoClearColor, renderer.autoClearDepth, renderer.autoClearStencil); } if (background && (background.isCubeTexture || background.mapping === CubeUVReflectionMapping)) { if (boxMesh === void 0) { boxMesh = new Mesh( new BoxGeometry(1, 1, 1), new ShaderMaterial({ name: "BackgroundCubeMaterial", uniforms: cloneUniforms(ShaderLib.backgroundCube.uniforms), vertexShader: ShaderLib.backgroundCube.vertexShader, fragmentShader: ShaderLib.backgroundCube.fragmentShader, side: BackSide, depthTest: false, depthWrite: false, fog: false }) ); boxMesh.geometry.deleteAttribute("normal"); boxMesh.geometry.deleteAttribute("uv"); boxMesh.onBeforeRender = function(renderer2, scene2, camera2) { this.matrixWorld.copyPosition(camera2.matrixWorld); }; Object.defineProperty(boxMesh.material, "envMap", { get: function() { return this.uniforms.envMap.value; } }); objects.update(boxMesh); } boxMesh.material.uniforms.envMap.value = background; boxMesh.material.uniforms.flipEnvMap.value = background.isCubeTexture && background.isRenderTargetTexture === false ? -1 : 1; boxMesh.material.uniforms.backgroundBlurriness.value = scene.backgroundBlurriness; if (currentBackground !== background || currentBackgroundVersion !== background.version || currentTonemapping !== renderer.toneMapping) { boxMesh.material.needsUpdate = true; currentBackground = background; currentBackgroundVersion = background.version; currentTonemapping = renderer.toneMapping; } boxMesh.layers.enableAll(); renderList.unshift(boxMesh, boxMesh.geometry, boxMesh.material, 0, 0, null); } else if (background && background.isTexture) { if (planeMesh === void 0) { planeMesh = new Mesh( new PlaneGeometry(2, 2), new ShaderMaterial({ name: "BackgroundMaterial", uniforms: cloneUniforms(ShaderLib.background.uniforms), vertexShader: ShaderLib.background.vertexShader, fragmentShader: ShaderLib.background.fragmentShader, side: FrontSide, depthTest: false, depthWrite: false, fog: false }) ); planeMesh.geometry.deleteAttribute("normal"); Object.defineProperty(planeMesh.material, "map", { get: function() { return this.uniforms.t2D.value; } }); objects.update(planeMesh); } planeMesh.material.uniforms.t2D.value = background; if (background.matrixAutoUpdate === true) { background.updateMatrix(); } planeMesh.material.uniforms.uvTransform.value.copy(background.matrix); if (currentBackground !== background || currentBackgroundVersion !== background.version || currentTonemapping !== renderer.toneMapping) { planeMesh.material.needsUpdate = true; currentBackground = background; currentBackgroundVersion = background.version; currentTonemapping = renderer.toneMapping; } planeMesh.layers.enableAll(); renderList.unshift(planeMesh, planeMesh.geometry, planeMesh.material, 0, 0, null); } } function setClear(color, alpha2) { state.buffers.color.setClear(color.r, color.g, color.b, alpha2, premultipliedAlpha); } return { getClearColor: function() { return clearColor; }, setClearColor: function(color, alpha2 = 1) { clearColor.set(color); clearAlpha = alpha2; setClear(clearColor, clearAlpha); }, getClearAlpha: function() { return clearAlpha; }, setClearAlpha: function(alpha2) { clearAlpha = alpha2; setClear(clearColor, clearAlpha); }, render: render2 }; } function WebGLBindingStates(gl, extensions, attributes, capabilities) { const maxVertexAttributes = gl.getParameter(34921); const extension = capabilities.isWebGL2 ? null : extensions.get("OES_vertex_array_object"); const vaoAvailable = capabilities.isWebGL2 || extension !== null; const bindingStates = {}; const defaultState = createBindingState(null); let currentState = defaultState; let forceUpdate = false; function setup(object, material, program, geometry, index) { let updateBuffers = false; if (vaoAvailable) { const state = getBindingState(geometry, program, material); if (currentState !== state) { currentState = state; bindVertexArrayObject(currentState.object); } updateBuffers = needsUpdate(object, geometry, program, index); if (updateBuffers) saveCache(object, geometry, program, index); } else { const wireframe = material.wireframe === true; if (currentState.geometry !== geometry.id || currentState.program !== program.id || currentState.wireframe !== wireframe) { currentState.geometry = geometry.id; currentState.program = program.id; currentState.wireframe = wireframe; updateBuffers = true; } } if (index !== null) { attributes.update(index, 34963); } if (updateBuffers || forceUpdate) { forceUpdate = false; setupVertexAttributes(object, material, program, geometry); if (index !== null) { gl.bindBuffer(34963, attributes.get(index).buffer); } } } function createVertexArrayObject() { if (capabilities.isWebGL2) return gl.createVertexArray(); return extension.createVertexArrayOES(); } function bindVertexArrayObject(vao) { if (capabilities.isWebGL2) return gl.bindVertexArray(vao); return extension.bindVertexArrayOES(vao); } function deleteVertexArrayObject(vao) { if (capabilities.isWebGL2) return gl.deleteVertexArray(vao); return extension.deleteVertexArrayOES(vao); } function getBindingState(geometry, program, material) { const wireframe = material.wireframe === true; let programMap = bindingStates[geometry.id]; if (programMap === void 0) { programMap = {}; bindingStates[geometry.id] = programMap; } let stateMap = programMap[program.id]; if (stateMap === void 0) { stateMap = {}; programMap[program.id] = stateMap; } let state = stateMap[wireframe]; if (state === void 0) { state = createBindingState(createVertexArrayObject()); stateMap[wireframe] = state; } return state; } function createBindingState(vao) { const newAttributes = []; const enabledAttributes = []; const attributeDivisors = []; for (let i = 0; i < maxVertexAttributes; i++) { newAttributes[i] = 0; enabledAttributes[i] = 0; attributeDivisors[i] = 0; } return { // for backward compatibility on non-VAO support browser geometry: null, program: null, wireframe: false, newAttributes, enabledAttributes, attributeDivisors, object: vao, attributes: {}, index: null }; } function needsUpdate(object, geometry, program, index) { const cachedAttributes = currentState.attributes; const geometryAttributes = geometry.attributes; let attributesNum = 0; const programAttributes = program.getAttributes(); for (const name in programAttributes) { const programAttribute = programAttributes[name]; if (programAttribute.location >= 0) { const cachedAttribute = cachedAttributes[name]; let geometryAttribute = geometryAttributes[name]; if (geometryAttribute === void 0) { if (name === "instanceMatrix" && object.instanceMatrix) geometryAttribute = object.instanceMatrix; if (name === "instanceColor" && object.instanceColor) geometryAttribute = object.instanceColor; } if (cachedAttribute === void 0) return true; if (cachedAttribute.attribute !== geometryAttribute) return true; if (geometryAttribute && cachedAttribute.data !== geometryAttribute.data) return true; attributesNum++; } } if (currentState.attributesNum !== attributesNum) return true; if (currentState.index !== index) return true; return false; } function saveCache(object, geometry, program, index) { const cache2 = {}; const attributes2 = geometry.attributes; let attributesNum = 0; const programAttributes = program.getAttributes(); for (const name in programAttributes) { const programAttribute = programAttributes[name]; if (programAttribute.location >= 0) { let attribute = attributes2[name]; if (attribute === void 0) { if (name === "instanceMatrix" && object.instanceMatrix) attribute = object.instanceMatrix; if (name === "instanceColor" && object.instanceColor) attribute = object.instanceColor; } const data = {}; data.attribute = attribute; if (attribute && attribute.data) { data.data = attribute.data; } cache2[name] = data; attributesNum++; } } currentState.attributes = cache2; currentState.attributesNum = attributesNum; currentState.index = index; } function initAttributes() { const newAttributes = currentState.newAttributes; for (let i = 0, il = newAttributes.length; i < il; i++) { newAttributes[i] = 0; } } function enableAttribute(attribute) { enableAttributeAndDivisor(attribute, 0); } function enableAttributeAndDivisor(attribute, meshPerAttribute) { const newAttributes = currentState.newAttributes; const enabledAttributes = currentState.enabledAttributes; const attributeDivisors = currentState.attributeDivisors; newAttributes[attribute] = 1; if (enabledAttributes[attribute] === 0) { gl.enableVertexAttribArray(attribute); enabledAttributes[attribute] = 1; } if (attributeDivisors[attribute] !== meshPerAttribute) { const extension2 = capabilities.isWebGL2 ? gl : extensions.get("ANGLE_instanced_arrays"); extension2[capabilities.isWebGL2 ? "vertexAttribDivisor" : "vertexAttribDivisorANGLE"](attribute, meshPerAttribute); attributeDivisors[attribute] = meshPerAttribute; } } function disableUnusedAttributes() { const newAttributes = currentState.newAttributes; const enabledAttributes = currentState.enabledAttributes; for (let i = 0, il = enabledAttributes.length; i < il; i++) { if (enabledAttributes[i] !== newAttributes[i]) { gl.disableVertexAttribArray(i); enabledAttributes[i] = 0; } } } function vertexAttribPointer(index, size, type, normalized, stride, offset) { if (capabilities.isWebGL2 === true && (type === 5124 || type === 5125)) { gl.vertexAttribIPointer(index, size, type, stride, offset); } else { gl.vertexAttribPointer(index, size, type, normalized, stride, offset); } } function setupVertexAttributes(object, material, program, geometry) { if (capabilities.isWebGL2 === false && (object.isInstancedMesh || geometry.isInstancedBufferGeometry)) { if (extensions.get("ANGLE_instanced_arrays") === null) return; } initAttributes(); const geometryAttributes = geometry.attributes; const programAttributes = program.getAttributes(); const materialDefaultAttributeValues = material.defaultAttributeValues; for (const name in programAttributes) { const programAttribute = programAttributes[name]; if (programAttribute.location >= 0) { let geometryAttribute = geometryAttributes[name]; if (geometryAttribute === void 0) { if (name === "instanceMatrix" && object.instanceMatrix) geometryAttribute = object.instanceMatrix; if (name === "instanceColor" && object.instanceColor) geometryAttribute = object.instanceColor; } if (geometryAttribute !== void 0) { const normalized = geometryAttribute.normalized; const size = geometryAttribute.itemSize; const attribute = attributes.get(geometryAttribute); if (attribute === void 0) continue; const buffer = attribute.buffer; const type = attribute.type; const bytesPerElement = attribute.bytesPerElement; if (geometryAttribute.isInterleavedBufferAttribute) { const data = geometryAttribute.data; const stride = data.stride; const offset = geometryAttribute.offset; if (data.isInstancedInterleavedBuffer) { for (let i = 0; i < programAttribute.locationSize; i++) { enableAttributeAndDivisor(programAttribute.location + i, data.meshPerAttribute); } if (object.isInstancedMesh !== true && geometry._maxInstanceCount === void 0) { geometry._maxInstanceCount = data.meshPerAttribute * data.count; } } else { for (let i = 0; i < programAttribute.locationSize; i++) { enableAttribute(programAttribute.location + i); } } gl.bindBuffer(34962, buffer); for (let i = 0; i < programAttribute.locationSize; i++) { vertexAttribPointer( programAttribute.location + i, size / programAttribute.locationSize, type, normalized, stride * bytesPerElement, (offset + size / programAttribute.locationSize * i) * bytesPerElement ); } } else { if (geometryAttribute.isInstancedBufferAttribute) { for (let i = 0; i < programAttribute.locationSize; i++) { enableAttributeAndDivisor(programAttribute.location + i, geometryAttribute.meshPerAttribute); } if (object.isInstancedMesh !== true && geometry._maxInstanceCount === void 0) { geometry._maxInstanceCount = geometryAttribute.meshPerAttribute * geometryAttribute.count; } } else { for (let i = 0; i < programAttribute.locationSize; i++) { enableAttribute(programAttribute.location + i); } } gl.bindBuffer(34962, buffer); for (let i = 0; i < programAttribute.locationSize; i++) { vertexAttribPointer( programAttribute.location + i, size / programAttribute.locationSize, type, normalized, size * bytesPerElement, size / programAttribute.locationSize * i * bytesPerElement ); } } } else if (materialDefaultAttributeValues !== void 0) { const value = materialDefaultAttributeValues[name]; if (value !== void 0) { switch (value.length) { case 2: gl.vertexAttrib2fv(programAttribute.location, value); break; case 3: gl.vertexAttrib3fv(programAttribute.location, value); break; case 4: gl.vertexAttrib4fv(programAttribute.location, value); break; default: gl.vertexAttrib1fv(programAttribute.location, value); } } } } } disableUnusedAttributes(); } function dispose() { reset(); for (const geometryId in bindingStates) { const programMap = bindingStates[geometryId]; for (const programId in programMap) { const stateMap = programMap[programId]; for (const wireframe in stateMap) { deleteVertexArrayObject(stateMap[wireframe].object); delete stateMap[wireframe]; } delete programMap[programId]; } delete bindingStates[geometryId]; } } function releaseStatesOfGeometry(geometry) { if (bindingStates[geometry.id] === void 0) return; const programMap = bindingStates[geometry.id]; for (const programId in programMap) { const stateMap = programMap[programId]; for (const wireframe in stateMap) { deleteVertexArrayObject(stateMap[wireframe].object); delete stateMap[wireframe]; } delete programMap[programId]; } delete bindingStates[geometry.id]; } function releaseStatesOfProgram(program) { for (const geometryId in bindingStates) { const programMap = bindingStates[geometryId]; if (programMap[program.id] === void 0) continue; const stateMap = programMap[program.id]; for (const wireframe in stateMap) { deleteVertexArrayObject(stateMap[wireframe].object); delete stateMap[wireframe]; } delete programMap[program.id]; } } function reset() { resetDefaultState(); forceUpdate = true; if (currentState === defaultState) return; currentState = defaultState; bindVertexArrayObject(currentState.object); } function resetDefaultState() { defaultState.geometry = null; defaultState.program = null; defaultState.wireframe = false; } return { setup, reset, resetDefaultState, dispose, releaseStatesOfGeometry, releaseStatesOfProgram, initAttributes, enableAttribute, disableUnusedAttributes }; } function WebGLBufferRenderer(gl, extensions, info, capabilities) { const isWebGL2 = capabilities.isWebGL2; let mode; function setMode(value) { mode = value; } function render2(start, count) { gl.drawArrays(mode, start, count); info.update(count, mode, 1); } function renderInstances(start, count, primcount) { if (primcount === 0) return; let extension, methodName; if (isWebGL2) { extension = gl; methodName = "drawArraysInstanced"; } else { extension = extensions.get("ANGLE_instanced_arrays"); methodName = "drawArraysInstancedANGLE"; if (extension === null) { console.error("THREE.WebGLBufferRenderer: using THREE.InstancedBufferGeometry but hardware does not support extension ANGLE_instanced_arrays."); return; } } extension[methodName](mode, start, count, primcount); info.update(count, mode, primcount); } this.setMode = setMode; this.render = render2; this.renderInstances = renderInstances; } function WebGLCapabilities(gl, extensions, parameters) { let maxAnisotropy; function getMaxAnisotropy() { if (maxAnisotropy !== void 0) return maxAnisotropy; if (extensions.has("EXT_texture_filter_anisotropic") === true) { const extension = extensions.get("EXT_texture_filter_anisotropic"); maxAnisotropy = gl.getParameter(extension.MAX_TEXTURE_MAX_ANISOTROPY_EXT); } else { maxAnisotropy = 0; } return maxAnisotropy; } function getMaxPrecision(precision2) { if (precision2 === "highp") { if (gl.getShaderPrecisionFormat(35633, 36338).precision > 0 && gl.getShaderPrecisionFormat(35632, 36338).precision > 0) { return "highp"; } precision2 = "mediump"; } if (precision2 === "mediump") { if (gl.getShaderPrecisionFormat(35633, 36337).precision > 0 && gl.getShaderPrecisionFormat(35632, 36337).precision > 0) { return "mediump"; } } return "lowp"; } const isWebGL2 = typeof WebGL2RenderingContext !== "undefined" && gl instanceof WebGL2RenderingContext || typeof WebGL2ComputeRenderingContext !== "undefined" && gl instanceof WebGL2ComputeRenderingContext; let precision = parameters.precision !== void 0 ? parameters.precision : "highp"; const maxPrecision = getMaxPrecision(precision); if (maxPrecision !== precision) { console.warn("THREE.WebGLRenderer:", precision, "not supported, using", maxPrecision, "instead."); precision = maxPrecision; } const drawBuffers = isWebGL2 || extensions.has("WEBGL_draw_buffers"); const logarithmicDepthBuffer = parameters.logarithmicDepthBuffer === true; const maxTextures = gl.getParameter(34930); const maxVertexTextures = gl.getParameter(35660); const maxTextureSize = gl.getParameter(3379); const maxCubemapSize = gl.getParameter(34076); const maxAttributes = gl.getParameter(34921); const maxVertexUniforms = gl.getParameter(36347); const maxVaryings = gl.getParameter(36348); const maxFragmentUniforms = gl.getParameter(36349); const vertexTextures = maxVertexTextures > 0; const floatFragmentTextures = isWebGL2 || extensions.has("OES_texture_float"); const floatVertexTextures = vertexTextures && floatFragmentTextures; const maxSamples = isWebGL2 ? gl.getParameter(36183) : 0; return { isWebGL2, drawBuffers, getMaxAnisotropy, getMaxPrecision, precision, logarithmicDepthBuffer, maxTextures, maxVertexTextures, maxTextureSize, maxCubemapSize, maxAttributes, maxVertexUniforms, maxVaryings, maxFragmentUniforms, vertexTextures, floatFragmentTextures, floatVertexTextures, maxSamples }; } function WebGLClipping(properties) { const scope = this; let globalState = null, numGlobalPlanes = 0, localClippingEnabled = false, renderingShadows = false; const plane = new Plane(), viewNormalMatrix = new Matrix3(), uniform = { value: null, needsUpdate: false }; this.uniform = uniform; this.numPlanes = 0; this.numIntersection = 0; this.init = function(planes, enableLocalClipping, camera2) { const enabled = planes.length !== 0 || enableLocalClipping || // enable state of previous frame - the clipping code has to // run another frame in order to reset the state: numGlobalPlanes !== 0 || localClippingEnabled; localClippingEnabled = enableLocalClipping; globalState = projectPlanes(planes, camera2, 0); numGlobalPlanes = planes.length; return enabled; }; this.beginShadows = function() { renderingShadows = true; projectPlanes(null); }; this.endShadows = function() { renderingShadows = false; resetGlobalState(); }; this.setState = function(material, camera2, useCache) { const planes = material.clippingPlanes, clipIntersection = material.clipIntersection, clipShadows = material.clipShadows; const materialProperties = properties.get(material); if (!localClippingEnabled || planes === null || planes.length === 0 || renderingShadows && !clipShadows) { if (renderingShadows) { projectPlanes(null); } else { resetGlobalState(); } } else { const nGlobal = renderingShadows ? 0 : numGlobalPlanes, lGlobal = nGlobal * 4; let dstArray = materialProperties.clippingState || null; uniform.value = dstArray; dstArray = projectPlanes(planes, camera2, lGlobal, useCache); for (let i = 0; i !== lGlobal; ++i) { dstArray[i] = globalState[i]; } materialProperties.clippingState = dstArray; this.numIntersection = clipIntersection ? this.numPlanes : 0; this.numPlanes += nGlobal; } }; function resetGlobalState() { if (uniform.value !== globalState) { uniform.value = globalState; uniform.needsUpdate = numGlobalPlanes > 0; } scope.numPlanes = numGlobalPlanes; scope.numIntersection = 0; } function projectPlanes(planes, camera2, dstOffset, skipTransform) { const nPlanes = planes !== null ? planes.length : 0; let dstArray = null; if (nPlanes !== 0) { dstArray = uniform.value; if (skipTransform !== true || dstArray === null) { const flatSize = dstOffset + nPlanes * 4, viewMatrix = camera2.matrixWorldInverse; viewNormalMatrix.getNormalMatrix(viewMatrix); if (dstArray === null || dstArray.length < flatSize) { dstArray = new Float32Array(flatSize); } for (let i = 0, i4 = dstOffset; i !== nPlanes; ++i, i4 += 4) { plane.copy(planes[i]).applyMatrix4(viewMatrix, viewNormalMatrix); plane.normal.toArray(dstArray, i4); dstArray[i4 + 3] = plane.constant; } } uniform.value = dstArray; uniform.needsUpdate = true; } scope.numPlanes = nPlanes; scope.numIntersection = 0; return dstArray; } } function WebGLCubeMaps(renderer) { let cubemaps = /* @__PURE__ */ new WeakMap(); function mapTextureMapping(texture, mapping) { if (mapping === EquirectangularReflectionMapping) { texture.mapping = CubeReflectionMapping; } else if (mapping === EquirectangularRefractionMapping) { texture.mapping = CubeRefractionMapping; } return texture; } function get(texture) { if (texture && texture.isTexture && texture.isRenderTargetTexture === false) { const mapping = texture.mapping; if (mapping === EquirectangularReflectionMapping || mapping === EquirectangularRefractionMapping) { if (cubemaps.has(texture)) { const cubemap = cubemaps.get(texture).texture; return mapTextureMapping(cubemap, texture.mapping); } else { const image = texture.image; if (image && image.height > 0) { const renderTarget = new WebGLCubeRenderTarget(image.height / 2); renderTarget.fromEquirectangularTexture(renderer, texture); cubemaps.set(texture, renderTarget); texture.addEventListener("dispose", onTextureDispose); return mapTextureMapping(renderTarget.texture, texture.mapping); } else { return null; } } } } return texture; } function onTextureDispose(event) { const texture = event.target; texture.removeEventListener("dispose", onTextureDispose); const cubemap = cubemaps.get(texture); if (cubemap !== void 0) { cubemaps.delete(texture); cubemap.dispose(); } } function dispose() { cubemaps = /* @__PURE__ */ new WeakMap(); } return { get, dispose }; } var OrthographicCamera = class extends Camera { constructor(left = -1, right = 1, top = 1, bottom = -1, near = 0.1, far = 2e3) { super(); this.isOrthographicCamera = true; this.type = "OrthographicCamera"; this.zoom = 1; this.view = null; this.left = left; this.right = right; this.top = top; this.bottom = bottom; this.near = near; this.far = far; this.updateProjectionMatrix(); } copy(source, recursive) { super.copy(source, recursive); this.left = source.left; this.right = source.right; this.top = source.top; this.bottom = source.bottom; this.near = source.near; this.far = source.far; this.zoom = source.zoom; this.view = source.view === null ? null : Object.assign({}, source.view); return this; } setViewOffset(fullWidth, fullHeight, x2, y, width, height) { if (this.view === null) { this.view = { enabled: true, fullWidth: 1, fullHeight: 1, offsetX: 0, offsetY: 0, width: 1, height: 1 }; } this.view.enabled = true; this.view.fullWidth = fullWidth; this.view.fullHeight = fullHeight; this.view.offsetX = x2; this.view.offsetY = y; this.view.width = width; this.view.height = height; this.updateProjectionMatrix(); } clearViewOffset() { if (this.view !== null) { this.view.enabled = false; } this.updateProjectionMatrix(); } updateProjectionMatrix() { const dx = (this.right - this.left) / (2 * this.zoom); const dy = (this.top - this.bottom) / (2 * this.zoom); const cx = (this.right + this.left) / 2; const cy = (this.top + this.bottom) / 2; let left = cx - dx; let right = cx + dx; let top = cy + dy; let bottom = cy - dy; if (this.view !== null && this.view.enabled) { const scaleW = (this.right - this.left) / this.view.fullWidth / this.zoom; const scaleH = (this.top - this.bottom) / this.view.fullHeight / this.zoom; left += scaleW * this.view.offsetX; right = left + scaleW * this.view.width; top -= scaleH * this.view.offsetY; bottom = top - scaleH * this.view.height; } this.projectionMatrix.makeOrthographic(left, right, top, bottom, this.near, this.far); this.projectionMatrixInverse.copy(this.projectionMatrix).invert(); } toJSON(meta) { const data = super.toJSON(meta); data.object.zoom = this.zoom; data.object.left = this.left; data.object.right = this.right; data.object.top = this.top; data.object.bottom = this.bottom; data.object.near = this.near; data.object.far = this.far; if (this.view !== null) data.object.view = Object.assign({}, this.view); return data; } }; var LOD_MIN = 4; var EXTRA_LOD_SIGMA = [0.125, 0.215, 0.35, 0.446, 0.526, 0.582]; var MAX_SAMPLES = 20; var _flatCamera = new OrthographicCamera(); var _clearColor = new Color(); var _oldTarget = null; var PHI = (1 + Math.sqrt(5)) / 2; var INV_PHI = 1 / PHI; var _axisDirections = [ new Vector3(1, 1, 1), new Vector3(-1, 1, 1), new Vector3(1, 1, -1), new Vector3(-1, 1, -1), new Vector3(0, PHI, INV_PHI), new Vector3(0, PHI, -INV_PHI), new Vector3(INV_PHI, 0, PHI), new Vector3(-INV_PHI, 0, PHI), new Vector3(PHI, INV_PHI, 0), new Vector3(-PHI, INV_PHI, 0) ]; var PMREMGenerator = class { constructor(renderer) { this._renderer = renderer; this._pingPongRenderTarget = null; this._lodMax = 0; this._cubeSize = 0; this._lodPlanes = []; this._sizeLods = []; this._sigmas = []; this._blurMaterial = null; this._cubemapMaterial = null; this._equirectMaterial = null; this._compileMaterial(this._blurMaterial); } /** * Generates a PMREM from a supplied Scene, which can be faster than using an * image if networking bandwidth is low. Optional sigma specifies a blur radius * in radians to be applied to the scene before PMREM generation. Optional near * and far planes ensure the scene is rendered in its entirety (the cubeCamera * is placed at the origin). */ fromScene(scene, sigma = 0, near = 0.1, far = 100) { _oldTarget = this._renderer.getRenderTarget(); this._setSize(256); const cubeUVRenderTarget = this._allocateTargets(); cubeUVRenderTarget.depthBuffer = true; this._sceneToCubeUV(scene, near, far, cubeUVRenderTarget); if (sigma > 0) { this._blur(cubeUVRenderTarget, 0, 0, sigma); } this._applyPMREM(cubeUVRenderTarget); this._cleanup(cubeUVRenderTarget); return cubeUVRenderTarget; } /** * Generates a PMREM from an equirectangular texture, which can be either LDR * or HDR. The ideal input image size is 1k (1024 x 512), * as this matches best with the 256 x 256 cubemap output. */ fromEquirectangular(equirectangular, renderTarget = null) { return this._fromTexture(equirectangular, renderTarget); } /** * Generates a PMREM from an cubemap texture, which can be either LDR * or HDR. The ideal input cube size is 256 x 256, * as this matches best with the 256 x 256 cubemap output. */ fromCubemap(cubemap, renderTarget = null) { return this._fromTexture(cubemap, renderTarget); } /** * Pre-compiles the cubemap shader. You can get faster start-up by invoking this method during * your texture's network fetch for increased concurrency. */ compileCubemapShader() { if (this._cubemapMaterial === null) { this._cubemapMaterial = _getCubemapMaterial(); this._compileMaterial(this._cubemapMaterial); } } /** * Pre-compiles the equirectangular shader. You can get faster start-up by invoking this method during * your texture's network fetch for increased concurrency. */ compileEquirectangularShader() { if (this._equirectMaterial === null) { this._equirectMaterial = _getEquirectMaterial(); this._compileMaterial(this._equirectMaterial); } } /** * Disposes of the PMREMGenerator's internal memory. Note that PMREMGenerator is a static class, * so you should not need more than one PMREMGenerator object. If you do, calling dispose() on * one of them will cause any others to also become unusable. */ dispose() { this._dispose(); if (this._cubemapMaterial !== null) this._cubemapMaterial.dispose(); if (this._equirectMaterial !== null) this._equirectMaterial.dispose(); } // private interface _setSize(cubeSize) { this._lodMax = Math.floor(Math.log2(cubeSize)); this._cubeSize = Math.pow(2, this._lodMax); } _dispose() { if (this._blurMaterial !== null) this._blurMaterial.dispose(); if (this._pingPongRenderTarget !== null) this._pingPongRenderTarget.dispose(); for (let i = 0; i < this._lodPlanes.length; i++) { this._lodPlanes[i].dispose(); } } _cleanup(outputTarget) { this._renderer.setRenderTarget(_oldTarget); outputTarget.scissorTest = false; _setViewport(outputTarget, 0, 0, outputTarget.width, outputTarget.height); } _fromTexture(texture, renderTarget) { if (texture.mapping === CubeReflectionMapping || texture.mapping === CubeRefractionMapping) { this._setSize(texture.image.length === 0 ? 16 : texture.image[0].width || texture.image[0].image.width); } else { this._setSize(texture.image.width / 4); } _oldTarget = this._renderer.getRenderTarget(); const cubeUVRenderTarget = renderTarget || this._allocateTargets(); this._textureToCubeUV(texture, cubeUVRenderTarget); this._applyPMREM(cubeUVRenderTarget); this._cleanup(cubeUVRenderTarget); return cubeUVRenderTarget; } _allocateTargets() { const width = 3 * Math.max(this._cubeSize, 16 * 7); const height = 4 * this._cubeSize; const params = { magFilter: LinearFilter, minFilter: LinearFilter, generateMipmaps: false, type: HalfFloatType, format: RGBAFormat, encoding: LinearEncoding, depthBuffer: false }; const cubeUVRenderTarget = _createRenderTarget(width, height, params); if (this._pingPongRenderTarget === null || this._pingPongRenderTarget.width !== width) { if (this._pingPongRenderTarget !== null) { this._dispose(); } this._pingPongRenderTarget = _createRenderTarget(width, height, params); const { _lodMax } = this; ({ sizeLods: this._sizeLods, lodPlanes: this._lodPlanes, sigmas: this._sigmas } = _createPlanes(_lodMax)); this._blurMaterial = _getBlurShader(_lodMax, width, height); } return cubeUVRenderTarget; } _compileMaterial(material) { const tmpMesh = new Mesh(this._lodPlanes[0], material); this._renderer.compile(tmpMesh, _flatCamera); } _sceneToCubeUV(scene, near, far, cubeUVRenderTarget) { const fov2 = 90; const aspect2 = 1; const cubeCamera = new PerspectiveCamera(fov2, aspect2, near, far); const upSign = [1, -1, 1, 1, 1, 1]; const forwardSign = [1, 1, 1, -1, -1, -1]; const renderer = this._renderer; const originalAutoClear = renderer.autoClear; const toneMapping = renderer.toneMapping; renderer.getClearColor(_clearColor); renderer.toneMapping = NoToneMapping; renderer.autoClear = false; const backgroundMaterial = new MeshBasicMaterial({ name: "PMREM.Background", side: BackSide, depthWrite: false, depthTest: false }); const backgroundBox = new Mesh(new BoxGeometry(), backgroundMaterial); let useSolidColor = false; const background = scene.background; if (background) { if (background.isColor) { backgroundMaterial.color.copy(background); scene.background = null; useSolidColor = true; } } else { backgroundMaterial.color.copy(_clearColor); useSolidColor = true; } for (let i = 0; i < 6; i++) { const col = i % 3; if (col === 0) { cubeCamera.up.set(0, upSign[i], 0); cubeCamera.lookAt(forwardSign[i], 0, 0); } else if (col === 1) { cubeCamera.up.set(0, 0, upSign[i]); cubeCamera.lookAt(0, forwardSign[i], 0); } else { cubeCamera.up.set(0, upSign[i], 0); cubeCamera.lookAt(0, 0, forwardSign[i]); } const size = this._cubeSize; _setViewport(cubeUVRenderTarget, col * size, i > 2 ? size : 0, size, size); renderer.setRenderTarget(cubeUVRenderTarget); if (useSolidColor) { renderer.render(backgroundBox, cubeCamera); } renderer.render(scene, cubeCamera); } backgroundBox.geometry.dispose(); backgroundBox.material.dispose(); renderer.toneMapping = toneMapping; renderer.autoClear = originalAutoClear; scene.background = background; } _textureToCubeUV(texture, cubeUVRenderTarget) { const renderer = this._renderer; const isCubeTexture = texture.mapping === CubeReflectionMapping || texture.mapping === CubeRefractionMapping; if (isCubeTexture) { if (this._cubemapMaterial === null) { this._cubemapMaterial = _getCubemapMaterial(); } this._cubemapMaterial.uniforms.flipEnvMap.value = texture.isRenderTargetTexture === false ? -1 : 1; } else { if (this._equirectMaterial === null) { this._equirectMaterial = _getEquirectMaterial(); } } const material = isCubeTexture ? this._cubemapMaterial : this._equirectMaterial; const mesh = new Mesh(this._lodPlanes[0], material); const uniforms = material.uniforms; uniforms["envMap"].value = texture; const size = this._cubeSize; _setViewport(cubeUVRenderTarget, 0, 0, 3 * size, 2 * size); renderer.setRenderTarget(cubeUVRenderTarget); renderer.render(mesh, _flatCamera); } _applyPMREM(cubeUVRenderTarget) { const renderer = this._renderer; const autoClear = renderer.autoClear; renderer.autoClear = false; for (let i = 1; i < this._lodPlanes.length; i++) { const sigma = Math.sqrt(this._sigmas[i] * this._sigmas[i] - this._sigmas[i - 1] * this._sigmas[i - 1]); const poleAxis = _axisDirections[(i - 1) % _axisDirections.length]; this._blur(cubeUVRenderTarget, i - 1, i, sigma, poleAxis); } renderer.autoClear = autoClear; } /** * This is a two-pass Gaussian blur for a cubemap. Normally this is done * vertically and horizontally, but this breaks down on a cube. Here we apply * the blur latitudinally (around the poles), and then longitudinally (towards * the poles) to approximate the orthogonally-separable blur. It is least * accurate at the poles, but still does a decent job. */ _blur(cubeUVRenderTarget, lodIn, lodOut, sigma, poleAxis) { const pingPongRenderTarget = this._pingPongRenderTarget; this._halfBlur( cubeUVRenderTarget, pingPongRenderTarget, lodIn, lodOut, sigma, "latitudinal", poleAxis ); this._halfBlur( pingPongRenderTarget, cubeUVRenderTarget, lodOut, lodOut, sigma, "longitudinal", poleAxis ); } _halfBlur(targetIn, targetOut, lodIn, lodOut, sigmaRadians, direction, poleAxis) { const renderer = this._renderer; const blurMaterial = this._blurMaterial; if (direction !== "latitudinal" && direction !== "longitudinal") { console.error( "blur direction must be either latitudinal or longitudinal!" ); } const STANDARD_DEVIATIONS = 3; const blurMesh = new Mesh(this._lodPlanes[lodOut], blurMaterial); const blurUniforms = blurMaterial.uniforms; const pixels = this._sizeLods[lodIn] - 1; const radiansPerPixel = isFinite(sigmaRadians) ? Math.PI / (2 * pixels) : 2 * Math.PI / (2 * MAX_SAMPLES - 1); const sigmaPixels = sigmaRadians / radiansPerPixel; const samples = isFinite(sigmaRadians) ? 1 + Math.floor(STANDARD_DEVIATIONS * sigmaPixels) : MAX_SAMPLES; if (samples > MAX_SAMPLES) { console.warn(`sigmaRadians, ${sigmaRadians}, is too large and will clip, as it requested ${samples} samples when the maximum is set to ${MAX_SAMPLES}`); } const weights = []; let sum = 0; for (let i = 0; i < MAX_SAMPLES; ++i) { const x3 = i / sigmaPixels; const weight = Math.exp(-x3 * x3 / 2); weights.push(weight); if (i === 0) { sum += weight; } else if (i < samples) { sum += 2 * weight; } } for (let i = 0; i < weights.length; i++) { weights[i] = weights[i] / sum; } blurUniforms["envMap"].value = targetIn.texture; blurUniforms["samples"].value = samples; blurUniforms["weights"].value = weights; blurUniforms["latitudinal"].value = direction === "latitudinal"; if (poleAxis) { blurUniforms["poleAxis"].value = poleAxis; } const { _lodMax } = this; blurUniforms["dTheta"].value = radiansPerPixel; blurUniforms["mipInt"].value = _lodMax - lodIn; const outputSize = this._sizeLods[lodOut]; const x2 = 3 * outputSize * (lodOut > _lodMax - LOD_MIN ? lodOut - _lodMax + LOD_MIN : 0); const y = 4 * (this._cubeSize - outputSize); _setViewport(targetOut, x2, y, 3 * outputSize, 2 * outputSize); renderer.setRenderTarget(targetOut); renderer.render(blurMesh, _flatCamera); } }; function _createPlanes(lodMax) { const lodPlanes = []; const sizeLods = []; const sigmas = []; let lod = lodMax; const totalLods = lodMax - LOD_MIN + 1 + EXTRA_LOD_SIGMA.length; for (let i = 0; i < totalLods; i++) { const sizeLod = Math.pow(2, lod); sizeLods.push(sizeLod); let sigma = 1 / sizeLod; if (i > lodMax - LOD_MIN) { sigma = EXTRA_LOD_SIGMA[i - lodMax + LOD_MIN - 1]; } else if (i === 0) { sigma = 0; } sigmas.push(sigma); const texelSize = 1 / (sizeLod - 2); const min = -texelSize; const max2 = 1 + texelSize; const uv1 = [min, min, max2, min, max2, max2, min, min, max2, max2, min, max2]; const cubeFaces = 6; const vertices = 6; const positionSize = 3; const uvSize = 2; const faceIndexSize = 1; const position = new Float32Array(positionSize * vertices * cubeFaces); const uv = new Float32Array(uvSize * vertices * cubeFaces); const faceIndex = new Float32Array(faceIndexSize * vertices * cubeFaces); for (let face = 0; face < cubeFaces; face++) { const x2 = face % 3 * 2 / 3 - 1; const y = face > 2 ? 0 : -1; const coordinates = [ x2, y, 0, x2 + 2 / 3, y, 0, x2 + 2 / 3, y + 1, 0, x2, y, 0, x2 + 2 / 3, y + 1, 0, x2, y + 1, 0 ]; position.set(coordinates, positionSize * vertices * face); uv.set(uv1, uvSize * vertices * face); const fill = [face, face, face, face, face, face]; faceIndex.set(fill, faceIndexSize * vertices * face); } const planes = new BufferGeometry(); planes.setAttribute("position", new BufferAttribute(position, positionSize)); planes.setAttribute("uv", new BufferAttribute(uv, uvSize)); planes.setAttribute("faceIndex", new BufferAttribute(faceIndex, faceIndexSize)); lodPlanes.push(planes); if (lod > LOD_MIN) { lod--; } } return { lodPlanes, sizeLods, sigmas }; } function _createRenderTarget(width, height, params) { const cubeUVRenderTarget = new WebGLRenderTarget(width, height, params); cubeUVRenderTarget.texture.mapping = CubeUVReflectionMapping; cubeUVRenderTarget.texture.name = "PMREM.cubeUv"; cubeUVRenderTarget.scissorTest = true; return cubeUVRenderTarget; } function _setViewport(target2, x2, y, width, height) { target2.viewport.set(x2, y, width, height); target2.scissor.set(x2, y, width, height); } function _getBlurShader(lodMax, width, height) { const weights = new Float32Array(MAX_SAMPLES); const poleAxis = new Vector3(0, 1, 0); const shaderMaterial = new ShaderMaterial({ name: "SphericalGaussianBlur", defines: { "n": MAX_SAMPLES, "CUBEUV_TEXEL_WIDTH": 1 / width, "CUBEUV_TEXEL_HEIGHT": 1 / height, "CUBEUV_MAX_MIP": `${lodMax}.0` }, uniforms: { "envMap": { value: null }, "samples": { value: 1 }, "weights": { value: weights }, "latitudinal": { value: false }, "dTheta": { value: 0 }, "mipInt": { value: 0 }, "poleAxis": { value: poleAxis } }, vertexShader: _getCommonVertexShader(), fragmentShader: ( /* glsl */ ` precision mediump float; precision mediump int; varying vec3 vOutputDirection; uniform sampler2D envMap; uniform int samples; uniform float weights[ n ]; uniform bool latitudinal; uniform float dTheta; uniform float mipInt; uniform vec3 poleAxis; #define ENVMAP_TYPE_CUBE_UV #include vec3 getSample( float theta, vec3 axis ) { float cosTheta = cos( theta ); // Rodrigues' axis-angle rotation vec3 sampleDirection = vOutputDirection * cosTheta + cross( axis, vOutputDirection ) * sin( theta ) + axis * dot( axis, vOutputDirection ) * ( 1.0 - cosTheta ); return bilinearCubeUV( envMap, sampleDirection, mipInt ); } void main() { vec3 axis = latitudinal ? poleAxis : cross( poleAxis, vOutputDirection ); if ( all( equal( axis, vec3( 0.0 ) ) ) ) { axis = vec3( vOutputDirection.z, 0.0, - vOutputDirection.x ); } axis = normalize( axis ); gl_FragColor = vec4( 0.0, 0.0, 0.0, 1.0 ); gl_FragColor.rgb += weights[ 0 ] * getSample( 0.0, axis ); for ( int i = 1; i < n; i++ ) { if ( i >= samples ) { break; } float theta = dTheta * float( i ); gl_FragColor.rgb += weights[ i ] * getSample( -1.0 * theta, axis ); gl_FragColor.rgb += weights[ i ] * getSample( theta, axis ); } } ` ), blending: NoBlending, depthTest: false, depthWrite: false }); return shaderMaterial; } function _getEquirectMaterial() { return new ShaderMaterial({ name: "EquirectangularToCubeUV", uniforms: { "envMap": { value: null } }, vertexShader: _getCommonVertexShader(), fragmentShader: ( /* glsl */ ` precision mediump float; precision mediump int; varying vec3 vOutputDirection; uniform sampler2D envMap; #include void main() { vec3 outputDirection = normalize( vOutputDirection ); vec2 uv = equirectUv( outputDirection ); gl_FragColor = vec4( texture2D ( envMap, uv ).rgb, 1.0 ); } ` ), blending: NoBlending, depthTest: false, depthWrite: false }); } function _getCubemapMaterial() { return new ShaderMaterial({ name: "CubemapToCubeUV", uniforms: { "envMap": { value: null }, "flipEnvMap": { value: -1 } }, vertexShader: _getCommonVertexShader(), fragmentShader: ( /* glsl */ ` precision mediump float; precision mediump int; uniform float flipEnvMap; varying vec3 vOutputDirection; uniform samplerCube envMap; void main() { gl_FragColor = textureCube( envMap, vec3( flipEnvMap * vOutputDirection.x, vOutputDirection.yz ) ); } ` ), blending: NoBlending, depthTest: false, depthWrite: false }); } function _getCommonVertexShader() { return ( /* glsl */ ` precision mediump float; precision mediump int; attribute float faceIndex; varying vec3 vOutputDirection; // RH coordinate system; PMREM face-indexing convention vec3 getDirection( vec2 uv, float face ) { uv = 2.0 * uv - 1.0; vec3 direction = vec3( uv, 1.0 ); if ( face == 0.0 ) { direction = direction.zyx; // ( 1, v, u ) pos x } else if ( face == 1.0 ) { direction = direction.xzy; direction.xz *= -1.0; // ( -u, 1, -v ) pos y } else if ( face == 2.0 ) { direction.x *= -1.0; // ( -u, v, 1 ) pos z } else if ( face == 3.0 ) { direction = direction.zyx; direction.xz *= -1.0; // ( -1, v, -u ) neg x } else if ( face == 4.0 ) { direction = direction.xzy; direction.xy *= -1.0; // ( -u, -1, v ) neg y } else if ( face == 5.0 ) { direction.z *= -1.0; // ( u, v, -1 ) neg z } return direction; } void main() { vOutputDirection = getDirection( uv, faceIndex ); gl_Position = vec4( position, 1.0 ); } ` ); } function WebGLCubeUVMaps(renderer) { let cubeUVmaps = /* @__PURE__ */ new WeakMap(); let pmremGenerator = null; function get(texture) { if (texture && texture.isTexture) { const mapping = texture.mapping; const isEquirectMap = mapping === EquirectangularReflectionMapping || mapping === EquirectangularRefractionMapping; const isCubeMap = mapping === CubeReflectionMapping || mapping === CubeRefractionMapping; if (isEquirectMap || isCubeMap) { if (texture.isRenderTargetTexture && texture.needsPMREMUpdate === true) { texture.needsPMREMUpdate = false; let renderTarget = cubeUVmaps.get(texture); if (pmremGenerator === null) pmremGenerator = new PMREMGenerator(renderer); renderTarget = isEquirectMap ? pmremGenerator.fromEquirectangular(texture, renderTarget) : pmremGenerator.fromCubemap(texture, renderTarget); cubeUVmaps.set(texture, renderTarget); return renderTarget.texture; } else { if (cubeUVmaps.has(texture)) { return cubeUVmaps.get(texture).texture; } else { const image = texture.image; if (isEquirectMap && image && image.height > 0 || isCubeMap && image && isCubeTextureComplete(image)) { if (pmremGenerator === null) pmremGenerator = new PMREMGenerator(renderer); const renderTarget = isEquirectMap ? pmremGenerator.fromEquirectangular(texture) : pmremGenerator.fromCubemap(texture); cubeUVmaps.set(texture, renderTarget); texture.addEventListener("dispose", onTextureDispose); return renderTarget.texture; } else { return null; } } } } } return texture; } function isCubeTextureComplete(image) { let count = 0; const length = 6; for (let i = 0; i < length; i++) { if (image[i] !== void 0) count++; } return count === length; } function onTextureDispose(event) { const texture = event.target; texture.removeEventListener("dispose", onTextureDispose); const cubemapUV = cubeUVmaps.get(texture); if (cubemapUV !== void 0) { cubeUVmaps.delete(texture); cubemapUV.dispose(); } } function dispose() { cubeUVmaps = /* @__PURE__ */ new WeakMap(); if (pmremGenerator !== null) { pmremGenerator.dispose(); pmremGenerator = null; } } return { get, dispose }; } function WebGLExtensions(gl) { const extensions = {}; function getExtension(name) { if (extensions[name] !== void 0) { return extensions[name]; } let extension; switch (name) { case "WEBGL_depth_texture": extension = gl.getExtension("WEBGL_depth_texture") || gl.getExtension("MOZ_WEBGL_depth_texture") || gl.getExtension("WEBKIT_WEBGL_depth_texture"); break; case "EXT_texture_filter_anisotropic": extension = gl.getExtension("EXT_texture_filter_anisotropic") || gl.getExtension("MOZ_EXT_texture_filter_anisotropic") || gl.getExtension("WEBKIT_EXT_texture_filter_anisotropic"); break; case "WEBGL_compressed_texture_s3tc": extension = gl.getExtension("WEBGL_compressed_texture_s3tc") || gl.getExtension("MOZ_WEBGL_compressed_texture_s3tc") || gl.getExtension("WEBKIT_WEBGL_compressed_texture_s3tc"); break; case "WEBGL_compressed_texture_pvrtc": extension = gl.getExtension("WEBGL_compressed_texture_pvrtc") || gl.getExtension("WEBKIT_WEBGL_compressed_texture_pvrtc"); break; default: extension = gl.getExtension(name); } extensions[name] = extension; return extension; } return { has: function(name) { return getExtension(name) !== null; }, init: function(capabilities) { if (capabilities.isWebGL2) { getExtension("EXT_color_buffer_float"); } else { getExtension("WEBGL_depth_texture"); getExtension("OES_texture_float"); getExtension("OES_texture_half_float"); getExtension("OES_texture_half_float_linear"); getExtension("OES_standard_derivatives"); getExtension("OES_element_index_uint"); getExtension("OES_vertex_array_object"); getExtension("ANGLE_instanced_arrays"); } getExtension("OES_texture_float_linear"); getExtension("EXT_color_buffer_half_float"); getExtension("WEBGL_multisampled_render_to_texture"); }, get: function(name) { const extension = getExtension(name); if (extension === null) { console.warn("THREE.WebGLRenderer: " + name + " extension not supported."); } return extension; } }; } function WebGLGeometries(gl, attributes, info, bindingStates) { const geometries = {}; const wireframeAttributes = /* @__PURE__ */ new WeakMap(); function onGeometryDispose(event) { const geometry = event.target; if (geometry.index !== null) { attributes.remove(geometry.index); } for (const name in geometry.attributes) { attributes.remove(geometry.attributes[name]); } geometry.removeEventListener("dispose", onGeometryDispose); delete geometries[geometry.id]; const attribute = wireframeAttributes.get(geometry); if (attribute) { attributes.remove(attribute); wireframeAttributes.delete(geometry); } bindingStates.releaseStatesOfGeometry(geometry); if (geometry.isInstancedBufferGeometry === true) { delete geometry._maxInstanceCount; } info.memory.geometries--; } function get(object, geometry) { if (geometries[geometry.id] === true) return geometry; geometry.addEventListener("dispose", onGeometryDispose); geometries[geometry.id] = true; info.memory.geometries++; return geometry; } function update(geometry) { const geometryAttributes = geometry.attributes; for (const name in geometryAttributes) { attributes.update(geometryAttributes[name], 34962); } const morphAttributes = geometry.morphAttributes; for (const name in morphAttributes) { const array = morphAttributes[name]; for (let i = 0, l = array.length; i < l; i++) { attributes.update(array[i], 34962); } } } function updateWireframeAttribute(geometry) { const indices = []; const geometryIndex = geometry.index; const geometryPosition = geometry.attributes.position; let version = 0; if (geometryIndex !== null) { const array = geometryIndex.array; version = geometryIndex.version; for (let i = 0, l = array.length; i < l; i += 3) { const a = array[i + 0]; const b = array[i + 1]; const c = array[i + 2]; indices.push(a, b, b, c, c, a); } } else { const array = geometryPosition.array; version = geometryPosition.version; for (let i = 0, l = array.length / 3 - 1; i < l; i += 3) { const a = i + 0; const b = i + 1; const c = i + 2; indices.push(a, b, b, c, c, a); } } const attribute = new (arrayNeedsUint32(indices) ? Uint32BufferAttribute : Uint16BufferAttribute)(indices, 1); attribute.version = version; const previousAttribute = wireframeAttributes.get(geometry); if (previousAttribute) attributes.remove(previousAttribute); wireframeAttributes.set(geometry, attribute); } function getWireframeAttribute(geometry) { const currentAttribute = wireframeAttributes.get(geometry); if (currentAttribute) { const geometryIndex = geometry.index; if (geometryIndex !== null) { if (currentAttribute.version < geometryIndex.version) { updateWireframeAttribute(geometry); } } } else { updateWireframeAttribute(geometry); } return wireframeAttributes.get(geometry); } return { get, update, getWireframeAttribute }; } function WebGLIndexedBufferRenderer(gl, extensions, info, capabilities) { const isWebGL2 = capabilities.isWebGL2; let mode; function setMode(value) { mode = value; } let type, bytesPerElement; function setIndex(value) { type = value.type; bytesPerElement = value.bytesPerElement; } function render2(start, count) { gl.drawElements(mode, count, type, start * bytesPerElement); info.update(count, mode, 1); } function renderInstances(start, count, primcount) { if (primcount === 0) return; let extension, methodName; if (isWebGL2) { extension = gl; methodName = "drawElementsInstanced"; } else { extension = extensions.get("ANGLE_instanced_arrays"); methodName = "drawElementsInstancedANGLE"; if (extension === null) { console.error("THREE.WebGLIndexedBufferRenderer: using THREE.InstancedBufferGeometry but hardware does not support extension ANGLE_instanced_arrays."); return; } } extension[methodName](mode, count, type, start * bytesPerElement, primcount); info.update(count, mode, primcount); } this.setMode = setMode; this.setIndex = setIndex; this.render = render2; this.renderInstances = renderInstances; } function WebGLInfo(gl) { const memory = { geometries: 0, textures: 0 }; const render2 = { frame: 0, calls: 0, triangles: 0, points: 0, lines: 0 }; function update(count, mode, instanceCount) { render2.calls++; switch (mode) { case 4: render2.triangles += instanceCount * (count / 3); break; case 1: render2.lines += instanceCount * (count / 2); break; case 3: render2.lines += instanceCount * (count - 1); break; case 2: render2.lines += instanceCount * count; break; case 0: render2.points += instanceCount * count; break; default: console.error("THREE.WebGLInfo: Unknown draw mode:", mode); break; } } function reset() { render2.frame++; render2.calls = 0; render2.triangles = 0; render2.points = 0; render2.lines = 0; } return { memory, render: render2, programs: null, autoReset: true, reset, update }; } function numericalSort(a, b) { return a[0] - b[0]; } function absNumericalSort(a, b) { return Math.abs(b[1]) - Math.abs(a[1]); } function WebGLMorphtargets(gl, capabilities, textures) { const influencesList = {}; const morphInfluences = new Float32Array(8); const morphTextures = /* @__PURE__ */ new WeakMap(); const morph = new Vector4(); const workInfluences = []; for (let i = 0; i < 8; i++) { workInfluences[i] = [i, 0]; } function update(object, geometry, material, program) { const objectInfluences = object.morphTargetInfluences; if (capabilities.isWebGL2 === true) { const morphAttribute = geometry.morphAttributes.position || geometry.morphAttributes.normal || geometry.morphAttributes.color; const morphTargetsCount = morphAttribute !== void 0 ? morphAttribute.length : 0; let entry = morphTextures.get(geometry); if (entry === void 0 || entry.count !== morphTargetsCount) { let disposeTexture = function() { texture.dispose(); morphTextures.delete(geometry); geometry.removeEventListener("dispose", disposeTexture); }; if (entry !== void 0) entry.texture.dispose(); const hasMorphPosition = geometry.morphAttributes.position !== void 0; const hasMorphNormals = geometry.morphAttributes.normal !== void 0; const hasMorphColors = geometry.morphAttributes.color !== void 0; const morphTargets = geometry.morphAttributes.position || []; const morphNormals = geometry.morphAttributes.normal || []; const morphColors = geometry.morphAttributes.color || []; let vertexDataCount = 0; if (hasMorphPosition === true) vertexDataCount = 1; if (hasMorphNormals === true) vertexDataCount = 2; if (hasMorphColors === true) vertexDataCount = 3; let width = geometry.attributes.position.count * vertexDataCount; let height = 1; if (width > capabilities.maxTextureSize) { height = Math.ceil(width / capabilities.maxTextureSize); width = capabilities.maxTextureSize; } const buffer = new Float32Array(width * height * 4 * morphTargetsCount); const texture = new DataArrayTexture(buffer, width, height, morphTargetsCount); texture.type = FloatType; texture.needsUpdate = true; const vertexDataStride = vertexDataCount * 4; for (let i = 0; i < morphTargetsCount; i++) { const morphTarget = morphTargets[i]; const morphNormal = morphNormals[i]; const morphColor = morphColors[i]; const offset = width * height * 4 * i; for (let j = 0; j < morphTarget.count; j++) { const stride = j * vertexDataStride; if (hasMorphPosition === true) { morph.fromBufferAttribute(morphTarget, j); buffer[offset + stride + 0] = morph.x; buffer[offset + stride + 1] = morph.y; buffer[offset + stride + 2] = morph.z; buffer[offset + stride + 3] = 0; } if (hasMorphNormals === true) { morph.fromBufferAttribute(morphNormal, j); buffer[offset + stride + 4] = morph.x; buffer[offset + stride + 5] = morph.y; buffer[offset + stride + 6] = morph.z; buffer[offset + stride + 7] = 0; } if (hasMorphColors === true) { morph.fromBufferAttribute(morphColor, j); buffer[offset + stride + 8] = morph.x; buffer[offset + stride + 9] = morph.y; buffer[offset + stride + 10] = morph.z; buffer[offset + stride + 11] = morphColor.itemSize === 4 ? morph.w : 1; } } } entry = { count: morphTargetsCount, texture, size: new Vector2(width, height) }; morphTextures.set(geometry, entry); geometry.addEventListener("dispose", disposeTexture); } let morphInfluencesSum = 0; for (let i = 0; i < objectInfluences.length; i++) { morphInfluencesSum += objectInfluences[i]; } const morphBaseInfluence = geometry.morphTargetsRelative ? 1 : 1 - morphInfluencesSum; program.getUniforms().setValue(gl, "morphTargetBaseInfluence", morphBaseInfluence); program.getUniforms().setValue(gl, "morphTargetInfluences", objectInfluences); program.getUniforms().setValue(gl, "morphTargetsTexture", entry.texture, textures); program.getUniforms().setValue(gl, "morphTargetsTextureSize", entry.size); } else { const length = objectInfluences === void 0 ? 0 : objectInfluences.length; let influences = influencesList[geometry.id]; if (influences === void 0 || influences.length !== length) { influences = []; for (let i = 0; i < length; i++) { influences[i] = [i, 0]; } influencesList[geometry.id] = influences; } for (let i = 0; i < length; i++) { const influence = influences[i]; influence[0] = i; influence[1] = objectInfluences[i]; } influences.sort(absNumericalSort); for (let i = 0; i < 8; i++) { if (i < length && influences[i][1]) { workInfluences[i][0] = influences[i][0]; workInfluences[i][1] = influences[i][1]; } else { workInfluences[i][0] = Number.MAX_SAFE_INTEGER; workInfluences[i][1] = 0; } } workInfluences.sort(numericalSort); const morphTargets = geometry.morphAttributes.position; const morphNormals = geometry.morphAttributes.normal; let morphInfluencesSum = 0; for (let i = 0; i < 8; i++) { const influence = workInfluences[i]; const index = influence[0]; const value = influence[1]; if (index !== Number.MAX_SAFE_INTEGER && value) { if (morphTargets && geometry.getAttribute("morphTarget" + i) !== morphTargets[index]) { geometry.setAttribute("morphTarget" + i, morphTargets[index]); } if (morphNormals && geometry.getAttribute("morphNormal" + i) !== morphNormals[index]) { geometry.setAttribute("morphNormal" + i, morphNormals[index]); } morphInfluences[i] = value; morphInfluencesSum += value; } else { if (morphTargets && geometry.hasAttribute("morphTarget" + i) === true) { geometry.deleteAttribute("morphTarget" + i); } if (morphNormals && geometry.hasAttribute("morphNormal" + i) === true) { geometry.deleteAttribute("morphNormal" + i); } morphInfluences[i] = 0; } } const morphBaseInfluence = geometry.morphTargetsRelative ? 1 : 1 - morphInfluencesSum; program.getUniforms().setValue(gl, "morphTargetBaseInfluence", morphBaseInfluence); program.getUniforms().setValue(gl, "morphTargetInfluences", morphInfluences); } } return { update }; } function WebGLObjects(gl, geometries, attributes, info) { let updateMap = /* @__PURE__ */ new WeakMap(); function update(object) { const frame = info.render.frame; const geometry = object.geometry; const buffergeometry = geometries.get(object, geometry); if (updateMap.get(buffergeometry) !== frame) { geometries.update(buffergeometry); updateMap.set(buffergeometry, frame); } if (object.isInstancedMesh) { if (object.hasEventListener("dispose", onInstancedMeshDispose) === false) { object.addEventListener("dispose", onInstancedMeshDispose); } attributes.update(object.instanceMatrix, 34962); if (object.instanceColor !== null) { attributes.update(object.instanceColor, 34962); } } return buffergeometry; } function dispose() { updateMap = /* @__PURE__ */ new WeakMap(); } function onInstancedMeshDispose(event) { const instancedMesh = event.target; instancedMesh.removeEventListener("dispose", onInstancedMeshDispose); attributes.remove(instancedMesh.instanceMatrix); if (instancedMesh.instanceColor !== null) attributes.remove(instancedMesh.instanceColor); } return { update, dispose }; } var emptyTexture = new Texture(); var emptyArrayTexture = new DataArrayTexture(); var empty3dTexture = new Data3DTexture(); var emptyCubeTexture = new CubeTexture(); var arrayCacheF32 = []; var arrayCacheI32 = []; var mat4array = new Float32Array(16); var mat3array = new Float32Array(9); var mat2array = new Float32Array(4); function flatten(array, nBlocks, blockSize) { const firstElem = array[0]; if (firstElem <= 0 || firstElem > 0) return array; const n2 = nBlocks * blockSize; let r = arrayCacheF32[n2]; if (r === void 0) { r = new Float32Array(n2); arrayCacheF32[n2] = r; } if (nBlocks !== 0) { firstElem.toArray(r, 0); for (let i = 1, offset = 0; i !== nBlocks; ++i) { offset += blockSize; array[i].toArray(r, offset); } } return r; } function arraysEqual(a, b) { if (a.length !== b.length) return false; for (let i = 0, l = a.length; i < l; i++) { if (a[i] !== b[i]) return false; } return true; } function copyArray(a, b) { for (let i = 0, l = b.length; i < l; i++) { a[i] = b[i]; } } function allocTexUnits(textures, n2) { let r = arrayCacheI32[n2]; if (r === void 0) { r = new Int32Array(n2); arrayCacheI32[n2] = r; } for (let i = 0; i !== n2; ++i) { r[i] = textures.allocateTextureUnit(); } return r; } function setValueV1f(gl, v) { const cache2 = this.cache; if (cache2[0] === v) return; gl.uniform1f(this.addr, v); cache2[0] = v; } function setValueV2f(gl, v) { const cache2 = this.cache; if (v.x !== void 0) { if (cache2[0] !== v.x || cache2[1] !== v.y) { gl.uniform2f(this.addr, v.x, v.y); cache2[0] = v.x; cache2[1] = v.y; } } else { if (arraysEqual(cache2, v)) return; gl.uniform2fv(this.addr, v); copyArray(cache2, v); } } function setValueV3f(gl, v) { const cache2 = this.cache; if (v.x !== void 0) { if (cache2[0] !== v.x || cache2[1] !== v.y || cache2[2] !== v.z) { gl.uniform3f(this.addr, v.x, v.y, v.z); cache2[0] = v.x; cache2[1] = v.y; cache2[2] = v.z; } } else if (v.r !== void 0) { if (cache2[0] !== v.r || cache2[1] !== v.g || cache2[2] !== v.b) { gl.uniform3f(this.addr, v.r, v.g, v.b); cache2[0] = v.r; cache2[1] = v.g; cache2[2] = v.b; } } else { if (arraysEqual(cache2, v)) return; gl.uniform3fv(this.addr, v); copyArray(cache2, v); } } function setValueV4f(gl, v) { const cache2 = this.cache; if (v.x !== void 0) { if (cache2[0] !== v.x || cache2[1] !== v.y || cache2[2] !== v.z || cache2[3] !== v.w) { gl.uniform4f(this.addr, v.x, v.y, v.z, v.w); cache2[0] = v.x; cache2[1] = v.y; cache2[2] = v.z; cache2[3] = v.w; } } else { if (arraysEqual(cache2, v)) return; gl.uniform4fv(this.addr, v); copyArray(cache2, v); } } function setValueM2(gl, v) { const cache2 = this.cache; const elements = v.elements; if (elements === void 0) { if (arraysEqual(cache2, v)) return; gl.uniformMatrix2fv(this.addr, false, v); copyArray(cache2, v); } else { if (arraysEqual(cache2, elements)) return; mat2array.set(elements); gl.uniformMatrix2fv(this.addr, false, mat2array); copyArray(cache2, elements); } } function setValueM3(gl, v) { const cache2 = this.cache; const elements = v.elements; if (elements === void 0) { if (arraysEqual(cache2, v)) return; gl.uniformMatrix3fv(this.addr, false, v); copyArray(cache2, v); } else { if (arraysEqual(cache2, elements)) return; mat3array.set(elements); gl.uniformMatrix3fv(this.addr, false, mat3array); copyArray(cache2, elements); } } function setValueM4(gl, v) { const cache2 = this.cache; const elements = v.elements; if (elements === void 0) { if (arraysEqual(cache2, v)) return; gl.uniformMatrix4fv(this.addr, false, v); copyArray(cache2, v); } else { if (arraysEqual(cache2, elements)) return; mat4array.set(elements); gl.uniformMatrix4fv(this.addr, false, mat4array); copyArray(cache2, elements); } } function setValueV1i(gl, v) { const cache2 = this.cache; if (cache2[0] === v) return; gl.uniform1i(this.addr, v); cache2[0] = v; } function setValueV2i(gl, v) { const cache2 = this.cache; if (v.x !== void 0) { if (cache2[0] !== v.x || cache2[1] !== v.y) { gl.uniform2i(this.addr, v.x, v.y); cache2[0] = v.x; cache2[1] = v.y; } } else { if (arraysEqual(cache2, v)) return; gl.uniform2iv(this.addr, v); copyArray(cache2, v); } } function setValueV3i(gl, v) { const cache2 = this.cache; if (v.x !== void 0) { if (cache2[0] !== v.x || cache2[1] !== v.y || cache2[2] !== v.z) { gl.uniform3i(this.addr, v.x, v.y, v.z); cache2[0] = v.x; cache2[1] = v.y; cache2[2] = v.z; } } else { if (arraysEqual(cache2, v)) return; gl.uniform3iv(this.addr, v); copyArray(cache2, v); } } function setValueV4i(gl, v) { const cache2 = this.cache; if (v.x !== void 0) { if (cache2[0] !== v.x || cache2[1] !== v.y || cache2[2] !== v.z || cache2[3] !== v.w) { gl.uniform4i(this.addr, v.x, v.y, v.z, v.w); cache2[0] = v.x; cache2[1] = v.y; cache2[2] = v.z; cache2[3] = v.w; } } else { if (arraysEqual(cache2, v)) return; gl.uniform4iv(this.addr, v); copyArray(cache2, v); } } function setValueV1ui(gl, v) { const cache2 = this.cache; if (cache2[0] === v) return; gl.uniform1ui(this.addr, v); cache2[0] = v; } function setValueV2ui(gl, v) { const cache2 = this.cache; if (v.x !== void 0) { if (cache2[0] !== v.x || cache2[1] !== v.y) { gl.uniform2ui(this.addr, v.x, v.y); cache2[0] = v.x; cache2[1] = v.y; } } else { if (arraysEqual(cache2, v)) return; gl.uniform2uiv(this.addr, v); copyArray(cache2, v); } } function setValueV3ui(gl, v) { const cache2 = this.cache; if (v.x !== void 0) { if (cache2[0] !== v.x || cache2[1] !== v.y || cache2[2] !== v.z) { gl.uniform3ui(this.addr, v.x, v.y, v.z); cache2[0] = v.x; cache2[1] = v.y; cache2[2] = v.z; } } else { if (arraysEqual(cache2, v)) return; gl.uniform3uiv(this.addr, v); copyArray(cache2, v); } } function setValueV4ui(gl, v) { const cache2 = this.cache; if (v.x !== void 0) { if (cache2[0] !== v.x || cache2[1] !== v.y || cache2[2] !== v.z || cache2[3] !== v.w) { gl.uniform4ui(this.addr, v.x, v.y, v.z, v.w); cache2[0] = v.x; cache2[1] = v.y; cache2[2] = v.z; cache2[3] = v.w; } } else { if (arraysEqual(cache2, v)) return; gl.uniform4uiv(this.addr, v); copyArray(cache2, v); } } function setValueT1(gl, v, textures) { const cache2 = this.cache; const unit = textures.allocateTextureUnit(); if (cache2[0] !== unit) { gl.uniform1i(this.addr, unit); cache2[0] = unit; } textures.setTexture2D(v || emptyTexture, unit); } function setValueT3D1(gl, v, textures) { const cache2 = this.cache; const unit = textures.allocateTextureUnit(); if (cache2[0] !== unit) { gl.uniform1i(this.addr, unit); cache2[0] = unit; } textures.setTexture3D(v || empty3dTexture, unit); } function setValueT6(gl, v, textures) { const cache2 = this.cache; const unit = textures.allocateTextureUnit(); if (cache2[0] !== unit) { gl.uniform1i(this.addr, unit); cache2[0] = unit; } textures.setTextureCube(v || emptyCubeTexture, unit); } function setValueT2DArray1(gl, v, textures) { const cache2 = this.cache; const unit = textures.allocateTextureUnit(); if (cache2[0] !== unit) { gl.uniform1i(this.addr, unit); cache2[0] = unit; } textures.setTexture2DArray(v || emptyArrayTexture, unit); } function getSingularSetter(type) { switch (type) { case 5126: return setValueV1f; case 35664: return setValueV2f; case 35665: return setValueV3f; case 35666: return setValueV4f; case 35674: return setValueM2; case 35675: return setValueM3; case 35676: return setValueM4; case 5124: case 35670: return setValueV1i; case 35667: case 35671: return setValueV2i; case 35668: case 35672: return setValueV3i; case 35669: case 35673: return setValueV4i; case 5125: return setValueV1ui; case 36294: return setValueV2ui; case 36295: return setValueV3ui; case 36296: return setValueV4ui; case 35678: case 36198: case 36298: case 36306: case 35682: return setValueT1; case 35679: case 36299: case 36307: return setValueT3D1; case 35680: case 36300: case 36308: case 36293: return setValueT6; case 36289: case 36303: case 36311: case 36292: return setValueT2DArray1; } } function setValueV1fArray(gl, v) { gl.uniform1fv(this.addr, v); } function setValueV2fArray(gl, v) { const data = flatten(v, this.size, 2); gl.uniform2fv(this.addr, data); } function setValueV3fArray(gl, v) { const data = flatten(v, this.size, 3); gl.uniform3fv(this.addr, data); } function setValueV4fArray(gl, v) { const data = flatten(v, this.size, 4); gl.uniform4fv(this.addr, data); } function setValueM2Array(gl, v) { const data = flatten(v, this.size, 4); gl.uniformMatrix2fv(this.addr, false, data); } function setValueM3Array(gl, v) { const data = flatten(v, this.size, 9); gl.uniformMatrix3fv(this.addr, false, data); } function setValueM4Array(gl, v) { const data = flatten(v, this.size, 16); gl.uniformMatrix4fv(this.addr, false, data); } function setValueV1iArray(gl, v) { gl.uniform1iv(this.addr, v); } function setValueV2iArray(gl, v) { gl.uniform2iv(this.addr, v); } function setValueV3iArray(gl, v) { gl.uniform3iv(this.addr, v); } function setValueV4iArray(gl, v) { gl.uniform4iv(this.addr, v); } function setValueV1uiArray(gl, v) { gl.uniform1uiv(this.addr, v); } function setValueV2uiArray(gl, v) { gl.uniform2uiv(this.addr, v); } function setValueV3uiArray(gl, v) { gl.uniform3uiv(this.addr, v); } function setValueV4uiArray(gl, v) { gl.uniform4uiv(this.addr, v); } function setValueT1Array(gl, v, textures) { const cache2 = this.cache; const n2 = v.length; const units = allocTexUnits(textures, n2); if (!arraysEqual(cache2, units)) { gl.uniform1iv(this.addr, units); copyArray(cache2, units); } for (let i = 0; i !== n2; ++i) { textures.setTexture2D(v[i] || emptyTexture, units[i]); } } function setValueT3DArray(gl, v, textures) { const cache2 = this.cache; const n2 = v.length; const units = allocTexUnits(textures, n2); if (!arraysEqual(cache2, units)) { gl.uniform1iv(this.addr, units); copyArray(cache2, units); } for (let i = 0; i !== n2; ++i) { textures.setTexture3D(v[i] || empty3dTexture, units[i]); } } function setValueT6Array(gl, v, textures) { const cache2 = this.cache; const n2 = v.length; const units = allocTexUnits(textures, n2); if (!arraysEqual(cache2, units)) { gl.uniform1iv(this.addr, units); copyArray(cache2, units); } for (let i = 0; i !== n2; ++i) { textures.setTextureCube(v[i] || emptyCubeTexture, units[i]); } } function setValueT2DArrayArray(gl, v, textures) { const cache2 = this.cache; const n2 = v.length; const units = allocTexUnits(textures, n2); if (!arraysEqual(cache2, units)) { gl.uniform1iv(this.addr, units); copyArray(cache2, units); } for (let i = 0; i !== n2; ++i) { textures.setTexture2DArray(v[i] || emptyArrayTexture, units[i]); } } function getPureArraySetter(type) { switch (type) { case 5126: return setValueV1fArray; case 35664: return setValueV2fArray; case 35665: return setValueV3fArray; case 35666: return setValueV4fArray; case 35674: return setValueM2Array; case 35675: return setValueM3Array; case 35676: return setValueM4Array; case 5124: case 35670: return setValueV1iArray; case 35667: case 35671: return setValueV2iArray; case 35668: case 35672: return setValueV3iArray; case 35669: case 35673: return setValueV4iArray; case 5125: return setValueV1uiArray; case 36294: return setValueV2uiArray; case 36295: return setValueV3uiArray; case 36296: return setValueV4uiArray; case 35678: case 36198: case 36298: case 36306: case 35682: return setValueT1Array; case 35679: case 36299: case 36307: return setValueT3DArray; case 35680: case 36300: case 36308: case 36293: return setValueT6Array; case 36289: case 36303: case 36311: case 36292: return setValueT2DArrayArray; } } var SingleUniform = class { constructor(id, activeInfo, addr) { this.id = id; this.addr = addr; this.cache = []; this.setValue = getSingularSetter(activeInfo.type); } }; var PureArrayUniform = class { constructor(id, activeInfo, addr) { this.id = id; this.addr = addr; this.cache = []; this.size = activeInfo.size; this.setValue = getPureArraySetter(activeInfo.type); } }; var StructuredUniform = class { constructor(id) { this.id = id; this.seq = []; this.map = {}; } setValue(gl, value, textures) { const seq = this.seq; for (let i = 0, n2 = seq.length; i !== n2; ++i) { const u = seq[i]; u.setValue(gl, value[u.id], textures); } } }; var RePathPart = /(\w+)(\])?(\[|\.)?/g; function addUniform(container, uniformObject) { container.seq.push(uniformObject); container.map[uniformObject.id] = uniformObject; } function parseUniform(activeInfo, addr, container) { const path = activeInfo.name, pathLength = path.length; RePathPart.lastIndex = 0; while (true) { const match = RePathPart.exec(path), matchEnd = RePathPart.lastIndex; let id = match[1]; const idIsIndex = match[2] === "]", subscript = match[3]; if (idIsIndex) id = id | 0; if (subscript === void 0 || subscript === "[" && matchEnd + 2 === pathLength) { addUniform(container, subscript === void 0 ? new SingleUniform(id, activeInfo, addr) : new PureArrayUniform(id, activeInfo, addr)); break; } else { const map = container.map; let next = map[id]; if (next === void 0) { next = new StructuredUniform(id); addUniform(container, next); } container = next; } } } var WebGLUniforms = class { constructor(gl, program) { this.seq = []; this.map = {}; const n2 = gl.getProgramParameter(program, 35718); for (let i = 0; i < n2; ++i) { const info = gl.getActiveUniform(program, i), addr = gl.getUniformLocation(program, info.name); parseUniform(info, addr, this); } } setValue(gl, name, value, textures) { const u = this.map[name]; if (u !== void 0) u.setValue(gl, value, textures); } setOptional(gl, object, name) { const v = object[name]; if (v !== void 0) this.setValue(gl, name, v); } static upload(gl, seq, values, textures) { for (let i = 0, n2 = seq.length; i !== n2; ++i) { const u = seq[i], v = values[u.id]; if (v.needsUpdate !== false) { u.setValue(gl, v.value, textures); } } } static seqWithValue(seq, values) { const r = []; for (let i = 0, n2 = seq.length; i !== n2; ++i) { const u = seq[i]; if (u.id in values) r.push(u); } return r; } }; function WebGLShader(gl, type, string) { const shader = gl.createShader(type); gl.shaderSource(shader, string); gl.compileShader(shader); return shader; } var programIdCount = 0; function handleSource(string, errorLine) { const lines = string.split("\n"); const lines2 = []; const from = Math.max(errorLine - 6, 0); const to = Math.min(errorLine + 6, lines.length); for (let i = from; i < to; i++) { const line = i + 1; lines2.push(`${line === errorLine ? ">" : " "} ${line}: ${lines[i]}`); } return lines2.join("\n"); } function getEncodingComponents(encoding) { switch (encoding) { case LinearEncoding: return ["Linear", "( value )"]; case sRGBEncoding: return ["sRGB", "( value )"]; default: console.warn("THREE.WebGLProgram: Unsupported encoding:", encoding); return ["Linear", "( value )"]; } } function getShaderErrors(gl, shader, type) { const status = gl.getShaderParameter(shader, 35713); const errors = gl.getShaderInfoLog(shader).trim(); if (status && errors === "") return ""; const errorMatches = /ERROR: 0:(\d+)/.exec(errors); if (errorMatches) { const errorLine = parseInt(errorMatches[1]); return type.toUpperCase() + "\n\n" + errors + "\n\n" + handleSource(gl.getShaderSource(shader), errorLine); } else { return errors; } } function getTexelEncodingFunction(functionName, encoding) { const components = getEncodingComponents(encoding); return "vec4 " + functionName + "( vec4 value ) { return LinearTo" + components[0] + components[1] + "; }"; } function getToneMappingFunction(functionName, toneMapping) { let toneMappingName; switch (toneMapping) { case LinearToneMapping: toneMappingName = "Linear"; break; case ReinhardToneMapping: toneMappingName = "Reinhard"; break; case CineonToneMapping: toneMappingName = "OptimizedCineon"; break; case ACESFilmicToneMapping: toneMappingName = "ACESFilmic"; break; case CustomToneMapping: toneMappingName = "Custom"; break; default: console.warn("THREE.WebGLProgram: Unsupported toneMapping:", toneMapping); toneMappingName = "Linear"; } return "vec3 " + functionName + "( vec3 color ) { return " + toneMappingName + "ToneMapping( color ); }"; } function generateExtensions(parameters) { const chunks = [ parameters.extensionDerivatives || !!parameters.envMapCubeUVHeight || parameters.bumpMap || parameters.tangentSpaceNormalMap || parameters.clearcoatNormalMap || parameters.flatShading || parameters.shaderID === "physical" ? "#extension GL_OES_standard_derivatives : enable" : "", (parameters.extensionFragDepth || parameters.logarithmicDepthBuffer) && parameters.rendererExtensionFragDepth ? "#extension GL_EXT_frag_depth : enable" : "", parameters.extensionDrawBuffers && parameters.rendererExtensionDrawBuffers ? "#extension GL_EXT_draw_buffers : require" : "", (parameters.extensionShaderTextureLOD || parameters.envMap || parameters.transmission) && parameters.rendererExtensionShaderTextureLod ? "#extension GL_EXT_shader_texture_lod : enable" : "" ]; return chunks.filter(filterEmptyLine).join("\n"); } function generateDefines(defines) { const chunks = []; for (const name in defines) { const value = defines[name]; if (value === false) continue; chunks.push("#define " + name + " " + value); } return chunks.join("\n"); } function fetchAttributeLocations(gl, program) { const attributes = {}; const n2 = gl.getProgramParameter(program, 35721); for (let i = 0; i < n2; i++) { const info = gl.getActiveAttrib(program, i); const name = info.name; let locationSize = 1; if (info.type === 35674) locationSize = 2; if (info.type === 35675) locationSize = 3; if (info.type === 35676) locationSize = 4; attributes[name] = { type: info.type, location: gl.getAttribLocation(program, name), locationSize }; } return attributes; } function filterEmptyLine(string) { return string !== ""; } function replaceLightNums(string, parameters) { const numSpotLightCoords = parameters.numSpotLightShadows + parameters.numSpotLightMaps - parameters.numSpotLightShadowsWithMaps; return string.replace(/NUM_DIR_LIGHTS/g, parameters.numDirLights).replace(/NUM_SPOT_LIGHTS/g, parameters.numSpotLights).replace(/NUM_SPOT_LIGHT_MAPS/g, parameters.numSpotLightMaps).replace(/NUM_SPOT_LIGHT_COORDS/g, numSpotLightCoords).replace(/NUM_RECT_AREA_LIGHTS/g, parameters.numRectAreaLights).replace(/NUM_POINT_LIGHTS/g, parameters.numPointLights).replace(/NUM_HEMI_LIGHTS/g, parameters.numHemiLights).replace(/NUM_DIR_LIGHT_SHADOWS/g, parameters.numDirLightShadows).replace(/NUM_SPOT_LIGHT_SHADOWS_WITH_MAPS/g, parameters.numSpotLightShadowsWithMaps).replace(/NUM_SPOT_LIGHT_SHADOWS/g, parameters.numSpotLightShadows).replace(/NUM_POINT_LIGHT_SHADOWS/g, parameters.numPointLightShadows); } function replaceClippingPlaneNums(string, parameters) { return string.replace(/NUM_CLIPPING_PLANES/g, parameters.numClippingPlanes).replace(/UNION_CLIPPING_PLANES/g, parameters.numClippingPlanes - parameters.numClipIntersection); } var includePattern = /^[ \t]*#include +<([\w\d./]+)>/gm; function resolveIncludes(string) { return string.replace(includePattern, includeReplacer); } function includeReplacer(match, include) { const string = ShaderChunk[include]; if (string === void 0) { throw new Error("Can not resolve #include <" + include + ">"); } return resolveIncludes(string); } var unrollLoopPattern = /#pragma unroll_loop_start\s+for\s*\(\s*int\s+i\s*=\s*(\d+)\s*;\s*i\s*<\s*(\d+)\s*;\s*i\s*\+\+\s*\)\s*{([\s\S]+?)}\s+#pragma unroll_loop_end/g; function unrollLoops(string) { return string.replace(unrollLoopPattern, loopReplacer); } function loopReplacer(match, start, end, snippet) { let string = ""; for (let i = parseInt(start); i < parseInt(end); i++) { string += snippet.replace(/\[\s*i\s*\]/g, "[ " + i + " ]").replace(/UNROLLED_LOOP_INDEX/g, i); } return string; } function generatePrecision(parameters) { let precisionstring = "precision " + parameters.precision + " float;\nprecision " + parameters.precision + " int;"; if (parameters.precision === "highp") { precisionstring += "\n#define HIGH_PRECISION"; } else if (parameters.precision === "mediump") { precisionstring += "\n#define MEDIUM_PRECISION"; } else if (parameters.precision === "lowp") { precisionstring += "\n#define LOW_PRECISION"; } return precisionstring; } function generateShadowMapTypeDefine(parameters) { let shadowMapTypeDefine = "SHADOWMAP_TYPE_BASIC"; if (parameters.shadowMapType === PCFShadowMap) { shadowMapTypeDefine = "SHADOWMAP_TYPE_PCF"; } else if (parameters.shadowMapType === PCFSoftShadowMap) { shadowMapTypeDefine = "SHADOWMAP_TYPE_PCF_SOFT"; } else if (parameters.shadowMapType === VSMShadowMap) { shadowMapTypeDefine = "SHADOWMAP_TYPE_VSM"; } return shadowMapTypeDefine; } function generateEnvMapTypeDefine(parameters) { let envMapTypeDefine = "ENVMAP_TYPE_CUBE"; if (parameters.envMap) { switch (parameters.envMapMode) { case CubeReflectionMapping: case CubeRefractionMapping: envMapTypeDefine = "ENVMAP_TYPE_CUBE"; break; case CubeUVReflectionMapping: envMapTypeDefine = "ENVMAP_TYPE_CUBE_UV"; break; } } return envMapTypeDefine; } function generateEnvMapModeDefine(parameters) { let envMapModeDefine = "ENVMAP_MODE_REFLECTION"; if (parameters.envMap) { switch (parameters.envMapMode) { case CubeRefractionMapping: envMapModeDefine = "ENVMAP_MODE_REFRACTION"; break; } } return envMapModeDefine; } function generateEnvMapBlendingDefine(parameters) { let envMapBlendingDefine = "ENVMAP_BLENDING_NONE"; if (parameters.envMap) { switch (parameters.combine) { case MultiplyOperation: envMapBlendingDefine = "ENVMAP_BLENDING_MULTIPLY"; break; case MixOperation: envMapBlendingDefine = "ENVMAP_BLENDING_MIX"; break; case AddOperation: envMapBlendingDefine = "ENVMAP_BLENDING_ADD"; break; } } return envMapBlendingDefine; } function generateCubeUVSize(parameters) { const imageHeight = parameters.envMapCubeUVHeight; if (imageHeight === null) return null; const maxMip = Math.log2(imageHeight) - 2; const texelHeight = 1 / imageHeight; const texelWidth = 1 / (3 * Math.max(Math.pow(2, maxMip), 7 * 16)); return { texelWidth, texelHeight, maxMip }; } function WebGLProgram(renderer, cacheKey, parameters, bindingStates) { const gl = renderer.getContext(); const defines = parameters.defines; let vertexShader = parameters.vertexShader; let fragmentShader = parameters.fragmentShader; const shadowMapTypeDefine = generateShadowMapTypeDefine(parameters); const envMapTypeDefine = generateEnvMapTypeDefine(parameters); const envMapModeDefine = generateEnvMapModeDefine(parameters); const envMapBlendingDefine = generateEnvMapBlendingDefine(parameters); const envMapCubeUVSize = generateCubeUVSize(parameters); const customExtensions = parameters.isWebGL2 ? "" : generateExtensions(parameters); const customDefines = generateDefines(defines); const program = gl.createProgram(); let prefixVertex, prefixFragment; let versionString = parameters.glslVersion ? "#version " + parameters.glslVersion + "\n" : ""; if (parameters.isRawShaderMaterial) { prefixVertex = [ customDefines ].filter(filterEmptyLine).join("\n"); if (prefixVertex.length > 0) { prefixVertex += "\n"; } prefixFragment = [ customExtensions, customDefines ].filter(filterEmptyLine).join("\n"); if (prefixFragment.length > 0) { prefixFragment += "\n"; } } else { prefixVertex = [ generatePrecision(parameters), "#define SHADER_NAME " + parameters.shaderName, customDefines, parameters.instancing ? "#define USE_INSTANCING" : "", parameters.instancingColor ? "#define USE_INSTANCING_COLOR" : "", parameters.supportsVertexTextures ? "#define VERTEX_TEXTURES" : "", parameters.useFog && parameters.fog ? "#define USE_FOG" : "", parameters.useFog && parameters.fogExp2 ? "#define FOG_EXP2" : "", parameters.map ? "#define USE_MAP" : "", parameters.envMap ? "#define USE_ENVMAP" : "", parameters.envMap ? "#define " + envMapModeDefine : "", parameters.lightMap ? "#define USE_LIGHTMAP" : "", parameters.aoMap ? "#define USE_AOMAP" : "", parameters.emissiveMap ? "#define USE_EMISSIVEMAP" : "", parameters.bumpMap ? "#define USE_BUMPMAP" : "", parameters.normalMap ? "#define USE_NORMALMAP" : "", parameters.normalMap && parameters.objectSpaceNormalMap ? "#define OBJECTSPACE_NORMALMAP" : "", parameters.normalMap && parameters.tangentSpaceNormalMap ? "#define TANGENTSPACE_NORMALMAP" : "", parameters.clearcoatMap ? "#define USE_CLEARCOATMAP" : "", parameters.clearcoatRoughnessMap ? "#define USE_CLEARCOAT_ROUGHNESSMAP" : "", parameters.clearcoatNormalMap ? "#define USE_CLEARCOAT_NORMALMAP" : "", parameters.iridescenceMap ? "#define USE_IRIDESCENCEMAP" : "", parameters.iridescenceThicknessMap ? "#define USE_IRIDESCENCE_THICKNESSMAP" : "", parameters.displacementMap && parameters.supportsVertexTextures ? "#define USE_DISPLACEMENTMAP" : "", parameters.specularMap ? "#define USE_SPECULARMAP" : "", parameters.specularIntensityMap ? "#define USE_SPECULARINTENSITYMAP" : "", parameters.specularColorMap ? "#define USE_SPECULARCOLORMAP" : "", parameters.roughnessMap ? "#define USE_ROUGHNESSMAP" : "", parameters.metalnessMap ? "#define USE_METALNESSMAP" : "", parameters.alphaMap ? "#define USE_ALPHAMAP" : "", parameters.transmission ? "#define USE_TRANSMISSION" : "", parameters.transmissionMap ? "#define USE_TRANSMISSIONMAP" : "", parameters.thicknessMap ? "#define USE_THICKNESSMAP" : "", parameters.sheenColorMap ? "#define USE_SHEENCOLORMAP" : "", parameters.sheenRoughnessMap ? "#define USE_SHEENROUGHNESSMAP" : "", parameters.vertexTangents ? "#define USE_TANGENT" : "", parameters.vertexColors ? "#define USE_COLOR" : "", parameters.vertexAlphas ? "#define USE_COLOR_ALPHA" : "", parameters.vertexUvs ? "#define USE_UV" : "", parameters.uvsVertexOnly ? "#define UVS_VERTEX_ONLY" : "", parameters.flatShading ? "#define FLAT_SHADED" : "", parameters.skinning ? "#define USE_SKINNING" : "", parameters.morphTargets ? "#define USE_MORPHTARGETS" : "", parameters.morphNormals && parameters.flatShading === false ? "#define USE_MORPHNORMALS" : "", parameters.morphColors && parameters.isWebGL2 ? "#define USE_MORPHCOLORS" : "", parameters.morphTargetsCount > 0 && parameters.isWebGL2 ? "#define MORPHTARGETS_TEXTURE" : "", parameters.morphTargetsCount > 0 && parameters.isWebGL2 ? "#define MORPHTARGETS_TEXTURE_STRIDE " + parameters.morphTextureStride : "", parameters.morphTargetsCount > 0 && parameters.isWebGL2 ? "#define MORPHTARGETS_COUNT " + parameters.morphTargetsCount : "", parameters.doubleSided ? "#define DOUBLE_SIDED" : "", parameters.flipSided ? "#define FLIP_SIDED" : "", parameters.shadowMapEnabled ? "#define USE_SHADOWMAP" : "", parameters.shadowMapEnabled ? "#define " + shadowMapTypeDefine : "", parameters.sizeAttenuation ? "#define USE_SIZEATTENUATION" : "", parameters.logarithmicDepthBuffer ? "#define USE_LOGDEPTHBUF" : "", parameters.logarithmicDepthBuffer && parameters.rendererExtensionFragDepth ? "#define USE_LOGDEPTHBUF_EXT" : "", "uniform mat4 modelMatrix;", "uniform mat4 modelViewMatrix;", "uniform mat4 projectionMatrix;", "uniform mat4 viewMatrix;", "uniform mat3 normalMatrix;", "uniform vec3 cameraPosition;", "uniform bool isOrthographic;", "#ifdef USE_INSTANCING", " attribute mat4 instanceMatrix;", "#endif", "#ifdef USE_INSTANCING_COLOR", " attribute vec3 instanceColor;", "#endif", "attribute vec3 position;", "attribute vec3 normal;", "attribute vec2 uv;", "#ifdef USE_TANGENT", " attribute vec4 tangent;", "#endif", "#if defined( USE_COLOR_ALPHA )", " attribute vec4 color;", "#elif defined( USE_COLOR )", " attribute vec3 color;", "#endif", "#if ( defined( USE_MORPHTARGETS ) && ! defined( MORPHTARGETS_TEXTURE ) )", " attribute vec3 morphTarget0;", " attribute vec3 morphTarget1;", " attribute vec3 morphTarget2;", " attribute vec3 morphTarget3;", " #ifdef USE_MORPHNORMALS", " attribute vec3 morphNormal0;", " attribute vec3 morphNormal1;", " attribute vec3 morphNormal2;", " attribute vec3 morphNormal3;", " #else", " attribute vec3 morphTarget4;", " attribute vec3 morphTarget5;", " attribute vec3 morphTarget6;", " attribute vec3 morphTarget7;", " #endif", "#endif", "#ifdef USE_SKINNING", " attribute vec4 skinIndex;", " attribute vec4 skinWeight;", "#endif", "\n" ].filter(filterEmptyLine).join("\n"); prefixFragment = [ customExtensions, generatePrecision(parameters), "#define SHADER_NAME " + parameters.shaderName, customDefines, parameters.useFog && parameters.fog ? "#define USE_FOG" : "", parameters.useFog && parameters.fogExp2 ? "#define FOG_EXP2" : "", parameters.map ? "#define USE_MAP" : "", parameters.matcap ? "#define USE_MATCAP" : "", parameters.envMap ? "#define USE_ENVMAP" : "", parameters.envMap ? "#define " + envMapTypeDefine : "", parameters.envMap ? "#define " + envMapModeDefine : "", parameters.envMap ? "#define " + envMapBlendingDefine : "", envMapCubeUVSize ? "#define CUBEUV_TEXEL_WIDTH " + envMapCubeUVSize.texelWidth : "", envMapCubeUVSize ? "#define CUBEUV_TEXEL_HEIGHT " + envMapCubeUVSize.texelHeight : "", envMapCubeUVSize ? "#define CUBEUV_MAX_MIP " + envMapCubeUVSize.maxMip + ".0" : "", parameters.lightMap ? "#define USE_LIGHTMAP" : "", parameters.aoMap ? "#define USE_AOMAP" : "", parameters.emissiveMap ? "#define USE_EMISSIVEMAP" : "", parameters.bumpMap ? "#define USE_BUMPMAP" : "", parameters.normalMap ? "#define USE_NORMALMAP" : "", parameters.normalMap && parameters.objectSpaceNormalMap ? "#define OBJECTSPACE_NORMALMAP" : "", parameters.normalMap && parameters.tangentSpaceNormalMap ? "#define TANGENTSPACE_NORMALMAP" : "", parameters.clearcoat ? "#define USE_CLEARCOAT" : "", parameters.clearcoatMap ? "#define USE_CLEARCOATMAP" : "", parameters.clearcoatRoughnessMap ? "#define USE_CLEARCOAT_ROUGHNESSMAP" : "", parameters.clearcoatNormalMap ? "#define USE_CLEARCOAT_NORMALMAP" : "", parameters.iridescence ? "#define USE_IRIDESCENCE" : "", parameters.iridescenceMap ? "#define USE_IRIDESCENCEMAP" : "", parameters.iridescenceThicknessMap ? "#define USE_IRIDESCENCE_THICKNESSMAP" : "", parameters.specularMap ? "#define USE_SPECULARMAP" : "", parameters.specularIntensityMap ? "#define USE_SPECULARINTENSITYMAP" : "", parameters.specularColorMap ? "#define USE_SPECULARCOLORMAP" : "", parameters.roughnessMap ? "#define USE_ROUGHNESSMAP" : "", parameters.metalnessMap ? "#define USE_METALNESSMAP" : "", parameters.alphaMap ? "#define USE_ALPHAMAP" : "", parameters.alphaTest ? "#define USE_ALPHATEST" : "", parameters.sheen ? "#define USE_SHEEN" : "", parameters.sheenColorMap ? "#define USE_SHEENCOLORMAP" : "", parameters.sheenRoughnessMap ? "#define USE_SHEENROUGHNESSMAP" : "", parameters.transmission ? "#define USE_TRANSMISSION" : "", parameters.transmissionMap ? "#define USE_TRANSMISSIONMAP" : "", parameters.thicknessMap ? "#define USE_THICKNESSMAP" : "", parameters.decodeVideoTexture ? "#define DECODE_VIDEO_TEXTURE" : "", parameters.vertexTangents ? "#define USE_TANGENT" : "", parameters.vertexColors || parameters.instancingColor ? "#define USE_COLOR" : "", parameters.vertexAlphas ? "#define USE_COLOR_ALPHA" : "", parameters.vertexUvs ? "#define USE_UV" : "", parameters.uvsVertexOnly ? "#define UVS_VERTEX_ONLY" : "", parameters.gradientMap ? "#define USE_GRADIENTMAP" : "", parameters.flatShading ? "#define FLAT_SHADED" : "", parameters.doubleSided ? "#define DOUBLE_SIDED" : "", parameters.flipSided ? "#define FLIP_SIDED" : "", parameters.shadowMapEnabled ? "#define USE_SHADOWMAP" : "", parameters.shadowMapEnabled ? "#define " + shadowMapTypeDefine : "", parameters.premultipliedAlpha ? "#define PREMULTIPLIED_ALPHA" : "", parameters.physicallyCorrectLights ? "#define PHYSICALLY_CORRECT_LIGHTS" : "", parameters.logarithmicDepthBuffer ? "#define USE_LOGDEPTHBUF" : "", parameters.logarithmicDepthBuffer && parameters.rendererExtensionFragDepth ? "#define USE_LOGDEPTHBUF_EXT" : "", "uniform mat4 viewMatrix;", "uniform vec3 cameraPosition;", "uniform bool isOrthographic;", parameters.toneMapping !== NoToneMapping ? "#define TONE_MAPPING" : "", parameters.toneMapping !== NoToneMapping ? ShaderChunk["tonemapping_pars_fragment"] : "", // this code is required here because it is used by the toneMapping() function defined below parameters.toneMapping !== NoToneMapping ? getToneMappingFunction("toneMapping", parameters.toneMapping) : "", parameters.dithering ? "#define DITHERING" : "", parameters.opaque ? "#define OPAQUE" : "", ShaderChunk["encodings_pars_fragment"], // this code is required here because it is used by the various encoding/decoding function defined below getTexelEncodingFunction("linearToOutputTexel", parameters.outputEncoding), parameters.useDepthPacking ? "#define DEPTH_PACKING " + parameters.depthPacking : "", "\n" ].filter(filterEmptyLine).join("\n"); } vertexShader = resolveIncludes(vertexShader); vertexShader = replaceLightNums(vertexShader, parameters); vertexShader = replaceClippingPlaneNums(vertexShader, parameters); fragmentShader = resolveIncludes(fragmentShader); fragmentShader = replaceLightNums(fragmentShader, parameters); fragmentShader = replaceClippingPlaneNums(fragmentShader, parameters); vertexShader = unrollLoops(vertexShader); fragmentShader = unrollLoops(fragmentShader); if (parameters.isWebGL2 && parameters.isRawShaderMaterial !== true) { versionString = "#version 300 es\n"; prefixVertex = [ "precision mediump sampler2DArray;", "#define attribute in", "#define varying out", "#define texture2D texture" ].join("\n") + "\n" + prefixVertex; prefixFragment = [ "#define varying in", parameters.glslVersion === GLSL3 ? "" : "layout(location = 0) out highp vec4 pc_fragColor;", parameters.glslVersion === GLSL3 ? "" : "#define gl_FragColor pc_fragColor", "#define gl_FragDepthEXT gl_FragDepth", "#define texture2D texture", "#define textureCube texture", "#define texture2DProj textureProj", "#define texture2DLodEXT textureLod", "#define texture2DProjLodEXT textureProjLod", "#define textureCubeLodEXT textureLod", "#define texture2DGradEXT textureGrad", "#define texture2DProjGradEXT textureProjGrad", "#define textureCubeGradEXT textureGrad" ].join("\n") + "\n" + prefixFragment; } const vertexGlsl = versionString + prefixVertex + vertexShader; const fragmentGlsl = versionString + prefixFragment + fragmentShader; const glVertexShader = WebGLShader(gl, 35633, vertexGlsl); const glFragmentShader = WebGLShader(gl, 35632, fragmentGlsl); gl.attachShader(program, glVertexShader); gl.attachShader(program, glFragmentShader); if (parameters.index0AttributeName !== void 0) { gl.bindAttribLocation(program, 0, parameters.index0AttributeName); } else if (parameters.morphTargets === true) { gl.bindAttribLocation(program, 0, "position"); } gl.linkProgram(program); if (renderer.debug.checkShaderErrors) { const programLog = gl.getProgramInfoLog(program).trim(); const vertexLog = gl.getShaderInfoLog(glVertexShader).trim(); const fragmentLog = gl.getShaderInfoLog(glFragmentShader).trim(); let runnable = true; let haveDiagnostics = true; if (gl.getProgramParameter(program, 35714) === false) { runnable = false; const vertexErrors = getShaderErrors(gl, glVertexShader, "vertex"); const fragmentErrors = getShaderErrors(gl, glFragmentShader, "fragment"); console.error( "THREE.WebGLProgram: Shader Error " + gl.getError() + " - VALIDATE_STATUS " + gl.getProgramParameter(program, 35715) + "\n\nProgram Info Log: " + programLog + "\n" + vertexErrors + "\n" + fragmentErrors ); } else if (programLog !== "") { console.warn("THREE.WebGLProgram: Program Info Log:", programLog); } else if (vertexLog === "" || fragmentLog === "") { haveDiagnostics = false; } if (haveDiagnostics) { this.diagnostics = { runnable, programLog, vertexShader: { log: vertexLog, prefix: prefixVertex }, fragmentShader: { log: fragmentLog, prefix: prefixFragment } }; } } gl.deleteShader(glVertexShader); gl.deleteShader(glFragmentShader); let cachedUniforms; this.getUniforms = function() { if (cachedUniforms === void 0) { cachedUniforms = new WebGLUniforms(gl, program); } return cachedUniforms; }; let cachedAttributes; this.getAttributes = function() { if (cachedAttributes === void 0) { cachedAttributes = fetchAttributeLocations(gl, program); } return cachedAttributes; }; this.destroy = function() { bindingStates.releaseStatesOfProgram(this); gl.deleteProgram(program); this.program = void 0; }; this.name = parameters.shaderName; this.id = programIdCount++; this.cacheKey = cacheKey; this.usedTimes = 1; this.program = program; this.vertexShader = glVertexShader; this.fragmentShader = glFragmentShader; return this; } var _id = 0; var WebGLShaderCache = class { constructor() { this.shaderCache = /* @__PURE__ */ new Map(); this.materialCache = /* @__PURE__ */ new Map(); } update(material) { const vertexShader = material.vertexShader; const fragmentShader = material.fragmentShader; const vertexShaderStage = this._getShaderStage(vertexShader); const fragmentShaderStage = this._getShaderStage(fragmentShader); const materialShaders = this._getShaderCacheForMaterial(material); if (materialShaders.has(vertexShaderStage) === false) { materialShaders.add(vertexShaderStage); vertexShaderStage.usedTimes++; } if (materialShaders.has(fragmentShaderStage) === false) { materialShaders.add(fragmentShaderStage); fragmentShaderStage.usedTimes++; } return this; } remove(material) { const materialShaders = this.materialCache.get(material); for (const shaderStage of materialShaders) { shaderStage.usedTimes--; if (shaderStage.usedTimes === 0) this.shaderCache.delete(shaderStage.code); } this.materialCache.delete(material); return this; } getVertexShaderID(material) { return this._getShaderStage(material.vertexShader).id; } getFragmentShaderID(material) { return this._getShaderStage(material.fragmentShader).id; } dispose() { this.shaderCache.clear(); this.materialCache.clear(); } _getShaderCacheForMaterial(material) { const cache2 = this.materialCache; let set = cache2.get(material); if (set === void 0) { set = /* @__PURE__ */ new Set(); cache2.set(material, set); } return set; } _getShaderStage(code) { const cache2 = this.shaderCache; let stage = cache2.get(code); if (stage === void 0) { stage = new WebGLShaderStage(code); cache2.set(code, stage); } return stage; } }; var WebGLShaderStage = class { constructor(code) { this.id = _id++; this.code = code; this.usedTimes = 0; } }; function WebGLPrograms(renderer, cubemaps, cubeuvmaps, extensions, capabilities, bindingStates, clipping) { const _programLayers = new Layers(); const _customShaders = new WebGLShaderCache(); const programs = []; const isWebGL2 = capabilities.isWebGL2; const logarithmicDepthBuffer = capabilities.logarithmicDepthBuffer; const vertexTextures = capabilities.vertexTextures; let precision = capabilities.precision; const shaderIDs = { MeshDepthMaterial: "depth", MeshDistanceMaterial: "distanceRGBA", MeshNormalMaterial: "normal", MeshBasicMaterial: "basic", MeshLambertMaterial: "lambert", MeshPhongMaterial: "phong", MeshToonMaterial: "toon", MeshStandardMaterial: "physical", MeshPhysicalMaterial: "physical", MeshMatcapMaterial: "matcap", LineBasicMaterial: "basic", LineDashedMaterial: "dashed", PointsMaterial: "points", ShadowMaterial: "shadow", SpriteMaterial: "sprite" }; function getParameters(material, lights, shadows, scene, object) { const fog = scene.fog; const geometry = object.geometry; const environment = material.isMeshStandardMaterial ? scene.environment : null; const envMap = (material.isMeshStandardMaterial ? cubeuvmaps : cubemaps).get(material.envMap || environment); const envMapCubeUVHeight = !!envMap && envMap.mapping === CubeUVReflectionMapping ? envMap.image.height : null; const shaderID = shaderIDs[material.type]; if (material.precision !== null) { precision = capabilities.getMaxPrecision(material.precision); if (precision !== material.precision) { console.warn("THREE.WebGLProgram.getParameters:", material.precision, "not supported, using", precision, "instead."); } } const morphAttribute = geometry.morphAttributes.position || geometry.morphAttributes.normal || geometry.morphAttributes.color; const morphTargetsCount = morphAttribute !== void 0 ? morphAttribute.length : 0; let morphTextureStride = 0; if (geometry.morphAttributes.position !== void 0) morphTextureStride = 1; if (geometry.morphAttributes.normal !== void 0) morphTextureStride = 2; if (geometry.morphAttributes.color !== void 0) morphTextureStride = 3; let vertexShader, fragmentShader; let customVertexShaderID, customFragmentShaderID; if (shaderID) { const shader = ShaderLib[shaderID]; vertexShader = shader.vertexShader; fragmentShader = shader.fragmentShader; } else { vertexShader = material.vertexShader; fragmentShader = material.fragmentShader; _customShaders.update(material); customVertexShaderID = _customShaders.getVertexShaderID(material); customFragmentShaderID = _customShaders.getFragmentShaderID(material); } const currentRenderTarget = renderer.getRenderTarget(); const useAlphaTest = material.alphaTest > 0; const useClearcoat = material.clearcoat > 0; const useIridescence = material.iridescence > 0; const parameters = { isWebGL2, shaderID, shaderName: material.type, vertexShader, fragmentShader, defines: material.defines, customVertexShaderID, customFragmentShaderID, isRawShaderMaterial: material.isRawShaderMaterial === true, glslVersion: material.glslVersion, precision, instancing: object.isInstancedMesh === true, instancingColor: object.isInstancedMesh === true && object.instanceColor !== null, supportsVertexTextures: vertexTextures, outputEncoding: currentRenderTarget === null ? renderer.outputEncoding : currentRenderTarget.isXRRenderTarget === true ? currentRenderTarget.texture.encoding : LinearEncoding, map: !!material.map, matcap: !!material.matcap, envMap: !!envMap, envMapMode: envMap && envMap.mapping, envMapCubeUVHeight, lightMap: !!material.lightMap, aoMap: !!material.aoMap, emissiveMap: !!material.emissiveMap, bumpMap: !!material.bumpMap, normalMap: !!material.normalMap, objectSpaceNormalMap: material.normalMapType === ObjectSpaceNormalMap, tangentSpaceNormalMap: material.normalMapType === TangentSpaceNormalMap, decodeVideoTexture: !!material.map && material.map.isVideoTexture === true && material.map.encoding === sRGBEncoding, clearcoat: useClearcoat, clearcoatMap: useClearcoat && !!material.clearcoatMap, clearcoatRoughnessMap: useClearcoat && !!material.clearcoatRoughnessMap, clearcoatNormalMap: useClearcoat && !!material.clearcoatNormalMap, iridescence: useIridescence, iridescenceMap: useIridescence && !!material.iridescenceMap, iridescenceThicknessMap: useIridescence && !!material.iridescenceThicknessMap, displacementMap: !!material.displacementMap, roughnessMap: !!material.roughnessMap, metalnessMap: !!material.metalnessMap, specularMap: !!material.specularMap, specularIntensityMap: !!material.specularIntensityMap, specularColorMap: !!material.specularColorMap, opaque: material.transparent === false && material.blending === NormalBlending, alphaMap: !!material.alphaMap, alphaTest: useAlphaTest, gradientMap: !!material.gradientMap, sheen: material.sheen > 0, sheenColorMap: !!material.sheenColorMap, sheenRoughnessMap: !!material.sheenRoughnessMap, transmission: material.transmission > 0, transmissionMap: !!material.transmissionMap, thicknessMap: !!material.thicknessMap, combine: material.combine, vertexTangents: !!material.normalMap && !!geometry.attributes.tangent, vertexColors: material.vertexColors, vertexAlphas: material.vertexColors === true && !!geometry.attributes.color && geometry.attributes.color.itemSize === 4, vertexUvs: !!material.map || !!material.bumpMap || !!material.normalMap || !!material.specularMap || !!material.alphaMap || !!material.emissiveMap || !!material.roughnessMap || !!material.metalnessMap || !!material.clearcoatMap || !!material.clearcoatRoughnessMap || !!material.clearcoatNormalMap || !!material.iridescenceMap || !!material.iridescenceThicknessMap || !!material.displacementMap || !!material.transmissionMap || !!material.thicknessMap || !!material.specularIntensityMap || !!material.specularColorMap || !!material.sheenColorMap || !!material.sheenRoughnessMap, uvsVertexOnly: !(!!material.map || !!material.bumpMap || !!material.normalMap || !!material.specularMap || !!material.alphaMap || !!material.emissiveMap || !!material.roughnessMap || !!material.metalnessMap || !!material.clearcoatNormalMap || !!material.iridescenceMap || !!material.iridescenceThicknessMap || material.transmission > 0 || !!material.transmissionMap || !!material.thicknessMap || !!material.specularIntensityMap || !!material.specularColorMap || material.sheen > 0 || !!material.sheenColorMap || !!material.sheenRoughnessMap) && !!material.displacementMap, fog: !!fog, useFog: material.fog === true, fogExp2: fog && fog.isFogExp2, flatShading: !!material.flatShading, sizeAttenuation: material.sizeAttenuation, logarithmicDepthBuffer, skinning: object.isSkinnedMesh === true, morphTargets: geometry.morphAttributes.position !== void 0, morphNormals: geometry.morphAttributes.normal !== void 0, morphColors: geometry.morphAttributes.color !== void 0, morphTargetsCount, morphTextureStride, numDirLights: lights.directional.length, numPointLights: lights.point.length, numSpotLights: lights.spot.length, numSpotLightMaps: lights.spotLightMap.length, numRectAreaLights: lights.rectArea.length, numHemiLights: lights.hemi.length, numDirLightShadows: lights.directionalShadowMap.length, numPointLightShadows: lights.pointShadowMap.length, numSpotLightShadows: lights.spotShadowMap.length, numSpotLightShadowsWithMaps: lights.numSpotLightShadowsWithMaps, numClippingPlanes: clipping.numPlanes, numClipIntersection: clipping.numIntersection, dithering: material.dithering, shadowMapEnabled: renderer.shadowMap.enabled && shadows.length > 0, shadowMapType: renderer.shadowMap.type, toneMapping: material.toneMapped ? renderer.toneMapping : NoToneMapping, physicallyCorrectLights: renderer.physicallyCorrectLights, premultipliedAlpha: material.premultipliedAlpha, doubleSided: material.side === DoubleSide, flipSided: material.side === BackSide, useDepthPacking: !!material.depthPacking, depthPacking: material.depthPacking || 0, index0AttributeName: material.index0AttributeName, extensionDerivatives: material.extensions && material.extensions.derivatives, extensionFragDepth: material.extensions && material.extensions.fragDepth, extensionDrawBuffers: material.extensions && material.extensions.drawBuffers, extensionShaderTextureLOD: material.extensions && material.extensions.shaderTextureLOD, rendererExtensionFragDepth: isWebGL2 || extensions.has("EXT_frag_depth"), rendererExtensionDrawBuffers: isWebGL2 || extensions.has("WEBGL_draw_buffers"), rendererExtensionShaderTextureLod: isWebGL2 || extensions.has("EXT_shader_texture_lod"), customProgramCacheKey: material.customProgramCacheKey() }; return parameters; } function getProgramCacheKey(parameters) { const array = []; if (parameters.shaderID) { array.push(parameters.shaderID); } else { array.push(parameters.customVertexShaderID); array.push(parameters.customFragmentShaderID); } if (parameters.defines !== void 0) { for (const name in parameters.defines) { array.push(name); array.push(parameters.defines[name]); } } if (parameters.isRawShaderMaterial === false) { getProgramCacheKeyParameters(array, parameters); getProgramCacheKeyBooleans(array, parameters); array.push(renderer.outputEncoding); } array.push(parameters.customProgramCacheKey); return array.join(); } function getProgramCacheKeyParameters(array, parameters) { array.push(parameters.precision); array.push(parameters.outputEncoding); array.push(parameters.envMapMode); array.push(parameters.envMapCubeUVHeight); array.push(parameters.combine); array.push(parameters.vertexUvs); array.push(parameters.fogExp2); array.push(parameters.sizeAttenuation); array.push(parameters.morphTargetsCount); array.push(parameters.morphAttributeCount); array.push(parameters.numDirLights); array.push(parameters.numPointLights); array.push(parameters.numSpotLights); array.push(parameters.numSpotLightMaps); array.push(parameters.numHemiLights); array.push(parameters.numRectAreaLights); array.push(parameters.numDirLightShadows); array.push(parameters.numPointLightShadows); array.push(parameters.numSpotLightShadows); array.push(parameters.numSpotLightShadowsWithMaps); array.push(parameters.shadowMapType); array.push(parameters.toneMapping); array.push(parameters.numClippingPlanes); array.push(parameters.numClipIntersection); array.push(parameters.depthPacking); } function getProgramCacheKeyBooleans(array, parameters) { _programLayers.disableAll(); if (parameters.isWebGL2) _programLayers.enable(0); if (parameters.supportsVertexTextures) _programLayers.enable(1); if (parameters.instancing) _programLayers.enable(2); if (parameters.instancingColor) _programLayers.enable(3); if (parameters.map) _programLayers.enable(4); if (parameters.matcap) _programLayers.enable(5); if (parameters.envMap) _programLayers.enable(6); if (parameters.lightMap) _programLayers.enable(7); if (parameters.aoMap) _programLayers.enable(8); if (parameters.emissiveMap) _programLayers.enable(9); if (parameters.bumpMap) _programLayers.enable(10); if (parameters.normalMap) _programLayers.enable(11); if (parameters.objectSpaceNormalMap) _programLayers.enable(12); if (parameters.tangentSpaceNormalMap) _programLayers.enable(13); if (parameters.clearcoat) _programLayers.enable(14); if (parameters.clearcoatMap) _programLayers.enable(15); if (parameters.clearcoatRoughnessMap) _programLayers.enable(16); if (parameters.clearcoatNormalMap) _programLayers.enable(17); if (parameters.iridescence) _programLayers.enable(18); if (parameters.iridescenceMap) _programLayers.enable(19); if (parameters.iridescenceThicknessMap) _programLayers.enable(20); if (parameters.displacementMap) _programLayers.enable(21); if (parameters.specularMap) _programLayers.enable(22); if (parameters.roughnessMap) _programLayers.enable(23); if (parameters.metalnessMap) _programLayers.enable(24); if (parameters.gradientMap) _programLayers.enable(25); if (parameters.alphaMap) _programLayers.enable(26); if (parameters.alphaTest) _programLayers.enable(27); if (parameters.vertexColors) _programLayers.enable(28); if (parameters.vertexAlphas) _programLayers.enable(29); if (parameters.vertexUvs) _programLayers.enable(30); if (parameters.vertexTangents) _programLayers.enable(31); if (parameters.uvsVertexOnly) _programLayers.enable(32); array.push(_programLayers.mask); _programLayers.disableAll(); if (parameters.fog) _programLayers.enable(0); if (parameters.useFog) _programLayers.enable(1); if (parameters.flatShading) _programLayers.enable(2); if (parameters.logarithmicDepthBuffer) _programLayers.enable(3); if (parameters.skinning) _programLayers.enable(4); if (parameters.morphTargets) _programLayers.enable(5); if (parameters.morphNormals) _programLayers.enable(6); if (parameters.morphColors) _programLayers.enable(7); if (parameters.premultipliedAlpha) _programLayers.enable(8); if (parameters.shadowMapEnabled) _programLayers.enable(9); if (parameters.physicallyCorrectLights) _programLayers.enable(10); if (parameters.doubleSided) _programLayers.enable(11); if (parameters.flipSided) _programLayers.enable(12); if (parameters.useDepthPacking) _programLayers.enable(13); if (parameters.dithering) _programLayers.enable(14); if (parameters.specularIntensityMap) _programLayers.enable(15); if (parameters.specularColorMap) _programLayers.enable(16); if (parameters.transmission) _programLayers.enable(17); if (parameters.transmissionMap) _programLayers.enable(18); if (parameters.thicknessMap) _programLayers.enable(19); if (parameters.sheen) _programLayers.enable(20); if (parameters.sheenColorMap) _programLayers.enable(21); if (parameters.sheenRoughnessMap) _programLayers.enable(22); if (parameters.decodeVideoTexture) _programLayers.enable(23); if (parameters.opaque) _programLayers.enable(24); array.push(_programLayers.mask); } function getUniforms(material) { const shaderID = shaderIDs[material.type]; let uniforms; if (shaderID) { const shader = ShaderLib[shaderID]; uniforms = UniformsUtils.clone(shader.uniforms); } else { uniforms = material.uniforms; } return uniforms; } function acquireProgram(parameters, cacheKey) { let program; for (let p2 = 0, pl = programs.length; p2 < pl; p2++) { const preexistingProgram = programs[p2]; if (preexistingProgram.cacheKey === cacheKey) { program = preexistingProgram; ++program.usedTimes; break; } } if (program === void 0) { program = new WebGLProgram(renderer, cacheKey, parameters, bindingStates); programs.push(program); } return program; } function releaseProgram(program) { if (--program.usedTimes === 0) { const i = programs.indexOf(program); programs[i] = programs[programs.length - 1]; programs.pop(); program.destroy(); } } function releaseShaderCache(material) { _customShaders.remove(material); } function dispose() { _customShaders.dispose(); } return { getParameters, getProgramCacheKey, getUniforms, acquireProgram, releaseProgram, releaseShaderCache, // Exposed for resource monitoring & error feedback via renderer.info: programs, dispose }; } function WebGLProperties() { let properties = /* @__PURE__ */ new WeakMap(); function get(object) { let map = properties.get(object); if (map === void 0) { map = {}; properties.set(object, map); } return map; } function remove(object) { properties.delete(object); } function update(object, key, value) { properties.get(object)[key] = value; } function dispose() { properties = /* @__PURE__ */ new WeakMap(); } return { get, remove, update, dispose }; } function painterSortStable(a, b) { if (a.groupOrder !== b.groupOrder) { return a.groupOrder - b.groupOrder; } else if (a.renderOrder !== b.renderOrder) { return a.renderOrder - b.renderOrder; } else if (a.material.id !== b.material.id) { return a.material.id - b.material.id; } else if (a.z !== b.z) { return a.z - b.z; } else { return a.id - b.id; } } function reversePainterSortStable(a, b) { if (a.groupOrder !== b.groupOrder) { return a.groupOrder - b.groupOrder; } else if (a.renderOrder !== b.renderOrder) { return a.renderOrder - b.renderOrder; } else if (a.z !== b.z) { return b.z - a.z; } else { return a.id - b.id; } } function WebGLRenderList() { const renderItems = []; let renderItemsIndex = 0; const opaque = []; const transmissive = []; const transparent = []; function init() { renderItemsIndex = 0; opaque.length = 0; transmissive.length = 0; transparent.length = 0; } function getNextRenderItem(object, geometry, material, groupOrder, z, group) { let renderItem = renderItems[renderItemsIndex]; if (renderItem === void 0) { renderItem = { id: object.id, object, geometry, material, groupOrder, renderOrder: object.renderOrder, z, group }; renderItems[renderItemsIndex] = renderItem; } else { renderItem.id = object.id; renderItem.object = object; renderItem.geometry = geometry; renderItem.material = material; renderItem.groupOrder = groupOrder; renderItem.renderOrder = object.renderOrder; renderItem.z = z; renderItem.group = group; } renderItemsIndex++; return renderItem; } function push(object, geometry, material, groupOrder, z, group) { const renderItem = getNextRenderItem(object, geometry, material, groupOrder, z, group); if (material.transmission > 0) { transmissive.push(renderItem); } else if (material.transparent === true) { transparent.push(renderItem); } else { opaque.push(renderItem); } } function unshift(object, geometry, material, groupOrder, z, group) { const renderItem = getNextRenderItem(object, geometry, material, groupOrder, z, group); if (material.transmission > 0) { transmissive.unshift(renderItem); } else if (material.transparent === true) { transparent.unshift(renderItem); } else { opaque.unshift(renderItem); } } function sort(customOpaqueSort, customTransparentSort) { if (opaque.length > 1) opaque.sort(customOpaqueSort || painterSortStable); if (transmissive.length > 1) transmissive.sort(customTransparentSort || reversePainterSortStable); if (transparent.length > 1) transparent.sort(customTransparentSort || reversePainterSortStable); } function finish() { for (let i = renderItemsIndex, il = renderItems.length; i < il; i++) { const renderItem = renderItems[i]; if (renderItem.id === null) break; renderItem.id = null; renderItem.object = null; renderItem.geometry = null; renderItem.material = null; renderItem.group = null; } } return { opaque, transmissive, transparent, init, push, unshift, finish, sort }; } function WebGLRenderLists() { let lists = /* @__PURE__ */ new WeakMap(); function get(scene, renderCallDepth) { const listArray = lists.get(scene); let list; if (listArray === void 0) { list = new WebGLRenderList(); lists.set(scene, [list]); } else { if (renderCallDepth >= listArray.length) { list = new WebGLRenderList(); listArray.push(list); } else { list = listArray[renderCallDepth]; } } return list; } function dispose() { lists = /* @__PURE__ */ new WeakMap(); } return { get, dispose }; } function UniformsCache() { const lights = {}; return { get: function(light) { if (lights[light.id] !== void 0) { return lights[light.id]; } let uniforms; switch (light.type) { case "DirectionalLight": uniforms = { direction: new Vector3(), color: new Color() }; break; case "SpotLight": uniforms = { position: new Vector3(), direction: new Vector3(), color: new Color(), distance: 0, coneCos: 0, penumbraCos: 0, decay: 0 }; break; case "PointLight": uniforms = { position: new Vector3(), color: new Color(), distance: 0, decay: 0 }; break; case "HemisphereLight": uniforms = { direction: new Vector3(), skyColor: new Color(), groundColor: new Color() }; break; case "RectAreaLight": uniforms = { color: new Color(), position: new Vector3(), halfWidth: new Vector3(), halfHeight: new Vector3() }; break; } lights[light.id] = uniforms; return uniforms; } }; } function ShadowUniformsCache() { const lights = {}; return { get: function(light) { if (lights[light.id] !== void 0) { return lights[light.id]; } let uniforms; switch (light.type) { case "DirectionalLight": uniforms = { shadowBias: 0, shadowNormalBias: 0, shadowRadius: 1, shadowMapSize: new Vector2() }; break; case "SpotLight": uniforms = { shadowBias: 0, shadowNormalBias: 0, shadowRadius: 1, shadowMapSize: new Vector2() }; break; case "PointLight": uniforms = { shadowBias: 0, shadowNormalBias: 0, shadowRadius: 1, shadowMapSize: new Vector2(), shadowCameraNear: 1, shadowCameraFar: 1e3 }; break; } lights[light.id] = uniforms; return uniforms; } }; } var nextVersion = 0; function shadowCastingAndTexturingLightsFirst(lightA, lightB) { return (lightB.castShadow ? 2 : 0) - (lightA.castShadow ? 2 : 0) + (lightB.map ? 1 : 0) - (lightA.map ? 1 : 0); } function WebGLLights(extensions, capabilities) { const cache2 = new UniformsCache(); const shadowCache = ShadowUniformsCache(); const state = { version: 0, hash: { directionalLength: -1, pointLength: -1, spotLength: -1, rectAreaLength: -1, hemiLength: -1, numDirectionalShadows: -1, numPointShadows: -1, numSpotShadows: -1, numSpotMaps: -1 }, ambient: [0, 0, 0], probe: [], directional: [], directionalShadow: [], directionalShadowMap: [], directionalShadowMatrix: [], spot: [], spotLightMap: [], spotShadow: [], spotShadowMap: [], spotLightMatrix: [], rectArea: [], rectAreaLTC1: null, rectAreaLTC2: null, point: [], pointShadow: [], pointShadowMap: [], pointShadowMatrix: [], hemi: [], numSpotLightShadowsWithMaps: 0 }; for (let i = 0; i < 9; i++) state.probe.push(new Vector3()); const vector34 = new Vector3(); const matrix42 = new Matrix4(); const matrix422 = new Matrix4(); function setup(lights, physicallyCorrectLights) { let r = 0, g2 = 0, b = 0; for (let i = 0; i < 9; i++) state.probe[i].set(0, 0, 0); let directionalLength = 0; let pointLength = 0; let spotLength = 0; let rectAreaLength = 0; let hemiLength = 0; let numDirectionalShadows = 0; let numPointShadows = 0; let numSpotShadows = 0; let numSpotMaps = 0; let numSpotShadowsWithMaps = 0; lights.sort(shadowCastingAndTexturingLightsFirst); const scaleFactor = physicallyCorrectLights !== true ? Math.PI : 1; for (let i = 0, l = lights.length; i < l; i++) { const light = lights[i]; const color = light.color; const intensity = light.intensity; const distance = light.distance; const shadowMap = light.shadow && light.shadow.map ? light.shadow.map.texture : null; if (light.isAmbientLight) { r += color.r * intensity * scaleFactor; g2 += color.g * intensity * scaleFactor; b += color.b * intensity * scaleFactor; } else if (light.isLightProbe) { for (let j = 0; j < 9; j++) { state.probe[j].addScaledVector(light.sh.coefficients[j], intensity); } } else if (light.isDirectionalLight) { const uniforms = cache2.get(light); uniforms.color.copy(light.color).multiplyScalar(light.intensity * scaleFactor); if (light.castShadow) { const shadow = light.shadow; const shadowUniforms = shadowCache.get(light); shadowUniforms.shadowBias = shadow.bias; shadowUniforms.shadowNormalBias = shadow.normalBias; shadowUniforms.shadowRadius = shadow.radius; shadowUniforms.shadowMapSize = shadow.mapSize; state.directionalShadow[directionalLength] = shadowUniforms; state.directionalShadowMap[directionalLength] = shadowMap; state.directionalShadowMatrix[directionalLength] = light.shadow.matrix; numDirectionalShadows++; } state.directional[directionalLength] = uniforms; directionalLength++; } else if (light.isSpotLight) { const uniforms = cache2.get(light); uniforms.position.setFromMatrixPosition(light.matrixWorld); uniforms.color.copy(color).multiplyScalar(intensity * scaleFactor); uniforms.distance = distance; uniforms.coneCos = Math.cos(light.angle); uniforms.penumbraCos = Math.cos(light.angle * (1 - light.penumbra)); uniforms.decay = light.decay; state.spot[spotLength] = uniforms; const shadow = light.shadow; if (light.map) { state.spotLightMap[numSpotMaps] = light.map; numSpotMaps++; shadow.updateMatrices(light); if (light.castShadow) numSpotShadowsWithMaps++; } state.spotLightMatrix[spotLength] = shadow.matrix; if (light.castShadow) { const shadowUniforms = shadowCache.get(light); shadowUniforms.shadowBias = shadow.bias; shadowUniforms.shadowNormalBias = shadow.normalBias; shadowUniforms.shadowRadius = shadow.radius; shadowUniforms.shadowMapSize = shadow.mapSize; state.spotShadow[spotLength] = shadowUniforms; state.spotShadowMap[spotLength] = shadowMap; numSpotShadows++; } spotLength++; } else if (light.isRectAreaLight) { const uniforms = cache2.get(light); uniforms.color.copy(color).multiplyScalar(intensity); uniforms.halfWidth.set(light.width * 0.5, 0, 0); uniforms.halfHeight.set(0, light.height * 0.5, 0); state.rectArea[rectAreaLength] = uniforms; rectAreaLength++; } else if (light.isPointLight) { const uniforms = cache2.get(light); uniforms.color.copy(light.color).multiplyScalar(light.intensity * scaleFactor); uniforms.distance = light.distance; uniforms.decay = light.decay; if (light.castShadow) { const shadow = light.shadow; const shadowUniforms = shadowCache.get(light); shadowUniforms.shadowBias = shadow.bias; shadowUniforms.shadowNormalBias = shadow.normalBias; shadowUniforms.shadowRadius = shadow.radius; shadowUniforms.shadowMapSize = shadow.mapSize; shadowUniforms.shadowCameraNear = shadow.camera.near; shadowUniforms.shadowCameraFar = shadow.camera.far; state.pointShadow[pointLength] = shadowUniforms; state.pointShadowMap[pointLength] = shadowMap; state.pointShadowMatrix[pointLength] = light.shadow.matrix; numPointShadows++; } state.point[pointLength] = uniforms; pointLength++; } else if (light.isHemisphereLight) { const uniforms = cache2.get(light); uniforms.skyColor.copy(light.color).multiplyScalar(intensity * scaleFactor); uniforms.groundColor.copy(light.groundColor).multiplyScalar(intensity * scaleFactor); state.hemi[hemiLength] = uniforms; hemiLength++; } } if (rectAreaLength > 0) { if (capabilities.isWebGL2) { state.rectAreaLTC1 = UniformsLib.LTC_FLOAT_1; state.rectAreaLTC2 = UniformsLib.LTC_FLOAT_2; } else { if (extensions.has("OES_texture_float_linear") === true) { state.rectAreaLTC1 = UniformsLib.LTC_FLOAT_1; state.rectAreaLTC2 = UniformsLib.LTC_FLOAT_2; } else if (extensions.has("OES_texture_half_float_linear") === true) { state.rectAreaLTC1 = UniformsLib.LTC_HALF_1; state.rectAreaLTC2 = UniformsLib.LTC_HALF_2; } else { console.error("THREE.WebGLRenderer: Unable to use RectAreaLight. Missing WebGL extensions."); } } } state.ambient[0] = r; state.ambient[1] = g2; state.ambient[2] = b; const hash = state.hash; if (hash.directionalLength !== directionalLength || hash.pointLength !== pointLength || hash.spotLength !== spotLength || hash.rectAreaLength !== rectAreaLength || hash.hemiLength !== hemiLength || hash.numDirectionalShadows !== numDirectionalShadows || hash.numPointShadows !== numPointShadows || hash.numSpotShadows !== numSpotShadows || hash.numSpotMaps !== numSpotMaps) { state.directional.length = directionalLength; state.spot.length = spotLength; state.rectArea.length = rectAreaLength; state.point.length = pointLength; state.hemi.length = hemiLength; state.directionalShadow.length = numDirectionalShadows; state.directionalShadowMap.length = numDirectionalShadows; state.pointShadow.length = numPointShadows; state.pointShadowMap.length = numPointShadows; state.spotShadow.length = numSpotShadows; state.spotShadowMap.length = numSpotShadows; state.directionalShadowMatrix.length = numDirectionalShadows; state.pointShadowMatrix.length = numPointShadows; state.spotLightMatrix.length = numSpotShadows + numSpotMaps - numSpotShadowsWithMaps; state.spotLightMap.length = numSpotMaps; state.numSpotLightShadowsWithMaps = numSpotShadowsWithMaps; hash.directionalLength = directionalLength; hash.pointLength = pointLength; hash.spotLength = spotLength; hash.rectAreaLength = rectAreaLength; hash.hemiLength = hemiLength; hash.numDirectionalShadows = numDirectionalShadows; hash.numPointShadows = numPointShadows; hash.numSpotShadows = numSpotShadows; hash.numSpotMaps = numSpotMaps; state.version = nextVersion++; } } function setupView(lights, camera2) { let directionalLength = 0; let pointLength = 0; let spotLength = 0; let rectAreaLength = 0; let hemiLength = 0; const viewMatrix = camera2.matrixWorldInverse; for (let i = 0, l = lights.length; i < l; i++) { const light = lights[i]; if (light.isDirectionalLight) { const uniforms = state.directional[directionalLength]; uniforms.direction.setFromMatrixPosition(light.matrixWorld); vector34.setFromMatrixPosition(light.target.matrixWorld); uniforms.direction.sub(vector34); uniforms.direction.transformDirection(viewMatrix); directionalLength++; } else if (light.isSpotLight) { const uniforms = state.spot[spotLength]; uniforms.position.setFromMatrixPosition(light.matrixWorld); uniforms.position.applyMatrix4(viewMatrix); uniforms.direction.setFromMatrixPosition(light.matrixWorld); vector34.setFromMatrixPosition(light.target.matrixWorld); uniforms.direction.sub(vector34); uniforms.direction.transformDirection(viewMatrix); spotLength++; } else if (light.isRectAreaLight) { const uniforms = state.rectArea[rectAreaLength]; uniforms.position.setFromMatrixPosition(light.matrixWorld); uniforms.position.applyMatrix4(viewMatrix); matrix422.identity(); matrix42.copy(light.matrixWorld); matrix42.premultiply(viewMatrix); matrix422.extractRotation(matrix42); uniforms.halfWidth.set(light.width * 0.5, 0, 0); uniforms.halfHeight.set(0, light.height * 0.5, 0); uniforms.halfWidth.applyMatrix4(matrix422); uniforms.halfHeight.applyMatrix4(matrix422); rectAreaLength++; } else if (light.isPointLight) { const uniforms = state.point[pointLength]; uniforms.position.setFromMatrixPosition(light.matrixWorld); uniforms.position.applyMatrix4(viewMatrix); pointLength++; } else if (light.isHemisphereLight) { const uniforms = state.hemi[hemiLength]; uniforms.direction.setFromMatrixPosition(light.matrixWorld); uniforms.direction.transformDirection(viewMatrix); hemiLength++; } } } return { setup, setupView, state }; } function WebGLRenderState(extensions, capabilities) { const lights = new WebGLLights(extensions, capabilities); const lightsArray = []; const shadowsArray = []; function init() { lightsArray.length = 0; shadowsArray.length = 0; } function pushLight(light) { lightsArray.push(light); } function pushShadow(shadowLight) { shadowsArray.push(shadowLight); } function setupLights(physicallyCorrectLights) { lights.setup(lightsArray, physicallyCorrectLights); } function setupLightsView(camera2) { lights.setupView(lightsArray, camera2); } const state = { lightsArray, shadowsArray, lights }; return { init, state, setupLights, setupLightsView, pushLight, pushShadow }; } function WebGLRenderStates(extensions, capabilities) { let renderStates = /* @__PURE__ */ new WeakMap(); function get(scene, renderCallDepth = 0) { const renderStateArray = renderStates.get(scene); let renderState; if (renderStateArray === void 0) { renderState = new WebGLRenderState(extensions, capabilities); renderStates.set(scene, [renderState]); } else { if (renderCallDepth >= renderStateArray.length) { renderState = new WebGLRenderState(extensions, capabilities); renderStateArray.push(renderState); } else { renderState = renderStateArray[renderCallDepth]; } } return renderState; } function dispose() { renderStates = /* @__PURE__ */ new WeakMap(); } return { get, dispose }; } var MeshDepthMaterial = class extends Material { constructor(parameters) { super(); this.isMeshDepthMaterial = true; this.type = "MeshDepthMaterial"; this.depthPacking = BasicDepthPacking; this.map = null; this.alphaMap = null; this.displacementMap = null; this.displacementScale = 1; this.displacementBias = 0; this.wireframe = false; this.wireframeLinewidth = 1; this.setValues(parameters); } copy(source) { super.copy(source); this.depthPacking = source.depthPacking; this.map = source.map; this.alphaMap = source.alphaMap; this.displacementMap = source.displacementMap; this.displacementScale = source.displacementScale; this.displacementBias = source.displacementBias; this.wireframe = source.wireframe; this.wireframeLinewidth = source.wireframeLinewidth; return this; } }; var MeshDistanceMaterial = class extends Material { constructor(parameters) { super(); this.isMeshDistanceMaterial = true; this.type = "MeshDistanceMaterial"; this.referencePosition = new Vector3(); this.nearDistance = 1; this.farDistance = 1e3; this.map = null; this.alphaMap = null; this.displacementMap = null; this.displacementScale = 1; this.displacementBias = 0; this.setValues(parameters); } copy(source) { super.copy(source); this.referencePosition.copy(source.referencePosition); this.nearDistance = source.nearDistance; this.farDistance = source.farDistance; this.map = source.map; this.alphaMap = source.alphaMap; this.displacementMap = source.displacementMap; this.displacementScale = source.displacementScale; this.displacementBias = source.displacementBias; return this; } }; var vertex = "void main() {\n gl_Position = vec4( position, 1.0 );\n}"; var fragment = "uniform sampler2D shadow_pass;\nuniform vec2 resolution;\nuniform float radius;\n#include \nvoid main() {\n const float samples = float( VSM_SAMPLES );\n float mean = 0.0;\n float squared_mean = 0.0;\n float uvStride = samples <= 1.0 ? 0.0 : 2.0 / ( samples - 1.0 );\n float uvStart = samples <= 1.0 ? 0.0 : - 1.0;\n for ( float i = 0.0; i < samples; i ++ ) {\n float uvOffset = uvStart + i * uvStride;\n #ifdef HORIZONTAL_PASS\n vec2 distribution = unpackRGBATo2Half( texture2D( shadow_pass, ( gl_FragCoord.xy + vec2( uvOffset, 0.0 ) * radius ) / resolution ) );\n mean += distribution.x;\n squared_mean += distribution.y * distribution.y + distribution.x * distribution.x;\n #else\n float depth = unpackRGBAToDepth( texture2D( shadow_pass, ( gl_FragCoord.xy + vec2( 0.0, uvOffset ) * radius ) / resolution ) );\n mean += depth;\n squared_mean += depth * depth;\n #endif\n }\n mean = mean / samples;\n squared_mean = squared_mean / samples;\n float std_dev = sqrt( squared_mean - mean * mean );\n gl_FragColor = pack2HalfToRGBA( vec2( mean, std_dev ) );\n}"; function WebGLShadowMap(_renderer, _objects, _capabilities) { let _frustum = new Frustum(); const _shadowMapSize = new Vector2(), _viewportSize = new Vector2(), _viewport = new Vector4(), _depthMaterial = new MeshDepthMaterial({ depthPacking: RGBADepthPacking }), _distanceMaterial = new MeshDistanceMaterial(), _materialCache = {}, _maxTextureSize = _capabilities.maxTextureSize; const shadowSide = { 0: BackSide, 1: FrontSide, 2: DoubleSide }; const shadowMaterialVertical = new ShaderMaterial({ defines: { VSM_SAMPLES: 8 }, uniforms: { shadow_pass: { value: null }, resolution: { value: new Vector2() }, radius: { value: 4 } }, vertexShader: vertex, fragmentShader: fragment }); const shadowMaterialHorizontal = shadowMaterialVertical.clone(); shadowMaterialHorizontal.defines.HORIZONTAL_PASS = 1; const fullScreenTri = new BufferGeometry(); fullScreenTri.setAttribute( "position", new BufferAttribute( new Float32Array([-1, -1, 0.5, 3, -1, 0.5, -1, 3, 0.5]), 3 ) ); const fullScreenMesh = new Mesh(fullScreenTri, shadowMaterialVertical); const scope = this; this.enabled = false; this.autoUpdate = true; this.needsUpdate = false; this.type = PCFShadowMap; this.render = function(lights, scene, camera2) { if (scope.enabled === false) return; if (scope.autoUpdate === false && scope.needsUpdate === false) return; if (lights.length === 0) return; const currentRenderTarget = _renderer.getRenderTarget(); const activeCubeFace = _renderer.getActiveCubeFace(); const activeMipmapLevel = _renderer.getActiveMipmapLevel(); const _state = _renderer.state; _state.setBlending(NoBlending); _state.buffers.color.setClear(1, 1, 1, 1); _state.buffers.depth.setTest(true); _state.setScissorTest(false); for (let i = 0, il = lights.length; i < il; i++) { const light = lights[i]; const shadow = light.shadow; if (shadow === void 0) { console.warn("THREE.WebGLShadowMap:", light, "has no shadow."); continue; } if (shadow.autoUpdate === false && shadow.needsUpdate === false) continue; _shadowMapSize.copy(shadow.mapSize); const shadowFrameExtents = shadow.getFrameExtents(); _shadowMapSize.multiply(shadowFrameExtents); _viewportSize.copy(shadow.mapSize); if (_shadowMapSize.x > _maxTextureSize || _shadowMapSize.y > _maxTextureSize) { if (_shadowMapSize.x > _maxTextureSize) { _viewportSize.x = Math.floor(_maxTextureSize / shadowFrameExtents.x); _shadowMapSize.x = _viewportSize.x * shadowFrameExtents.x; shadow.mapSize.x = _viewportSize.x; } if (_shadowMapSize.y > _maxTextureSize) { _viewportSize.y = Math.floor(_maxTextureSize / shadowFrameExtents.y); _shadowMapSize.y = _viewportSize.y * shadowFrameExtents.y; shadow.mapSize.y = _viewportSize.y; } } if (shadow.map === null) { const pars = this.type !== VSMShadowMap ? { minFilter: NearestFilter, magFilter: NearestFilter } : {}; shadow.map = new WebGLRenderTarget(_shadowMapSize.x, _shadowMapSize.y, pars); shadow.map.texture.name = light.name + ".shadowMap"; shadow.camera.updateProjectionMatrix(); } _renderer.setRenderTarget(shadow.map); _renderer.clear(); const viewportCount = shadow.getViewportCount(); for (let vp = 0; vp < viewportCount; vp++) { const viewport = shadow.getViewport(vp); _viewport.set( _viewportSize.x * viewport.x, _viewportSize.y * viewport.y, _viewportSize.x * viewport.z, _viewportSize.y * viewport.w ); _state.viewport(_viewport); shadow.updateMatrices(light, vp); _frustum = shadow.getFrustum(); renderObject(scene, camera2, shadow.camera, light, this.type); } if (shadow.isPointLightShadow !== true && this.type === VSMShadowMap) { VSMPass(shadow, camera2); } shadow.needsUpdate = false; } scope.needsUpdate = false; _renderer.setRenderTarget(currentRenderTarget, activeCubeFace, activeMipmapLevel); }; function VSMPass(shadow, camera2) { const geometry = _objects.update(fullScreenMesh); if (shadowMaterialVertical.defines.VSM_SAMPLES !== shadow.blurSamples) { shadowMaterialVertical.defines.VSM_SAMPLES = shadow.blurSamples; shadowMaterialHorizontal.defines.VSM_SAMPLES = shadow.blurSamples; shadowMaterialVertical.needsUpdate = true; shadowMaterialHorizontal.needsUpdate = true; } if (shadow.mapPass === null) { shadow.mapPass = new WebGLRenderTarget(_shadowMapSize.x, _shadowMapSize.y); } shadowMaterialVertical.uniforms.shadow_pass.value = shadow.map.texture; shadowMaterialVertical.uniforms.resolution.value = shadow.mapSize; shadowMaterialVertical.uniforms.radius.value = shadow.radius; _renderer.setRenderTarget(shadow.mapPass); _renderer.clear(); _renderer.renderBufferDirect(camera2, null, geometry, shadowMaterialVertical, fullScreenMesh, null); shadowMaterialHorizontal.uniforms.shadow_pass.value = shadow.mapPass.texture; shadowMaterialHorizontal.uniforms.resolution.value = shadow.mapSize; shadowMaterialHorizontal.uniforms.radius.value = shadow.radius; _renderer.setRenderTarget(shadow.map); _renderer.clear(); _renderer.renderBufferDirect(camera2, null, geometry, shadowMaterialHorizontal, fullScreenMesh, null); } function getDepthMaterial(object, material, light, shadowCameraNear, shadowCameraFar, type) { let result = null; const customMaterial = light.isPointLight === true ? object.customDistanceMaterial : object.customDepthMaterial; if (customMaterial !== void 0) { result = customMaterial; } else { result = light.isPointLight === true ? _distanceMaterial : _depthMaterial; } if (_renderer.localClippingEnabled && material.clipShadows === true && Array.isArray(material.clippingPlanes) && material.clippingPlanes.length !== 0 || material.displacementMap && material.displacementScale !== 0 || material.alphaMap && material.alphaTest > 0) { const keyA = result.uuid, keyB = material.uuid; let materialsForVariant = _materialCache[keyA]; if (materialsForVariant === void 0) { materialsForVariant = {}; _materialCache[keyA] = materialsForVariant; } let cachedMaterial = materialsForVariant[keyB]; if (cachedMaterial === void 0) { cachedMaterial = result.clone(); materialsForVariant[keyB] = cachedMaterial; } result = cachedMaterial; } result.visible = material.visible; result.wireframe = material.wireframe; if (type === VSMShadowMap) { result.side = material.shadowSide !== null ? material.shadowSide : material.side; } else { result.side = material.shadowSide !== null ? material.shadowSide : shadowSide[material.side]; } result.alphaMap = material.alphaMap; result.alphaTest = material.alphaTest; result.clipShadows = material.clipShadows; result.clippingPlanes = material.clippingPlanes; result.clipIntersection = material.clipIntersection; result.displacementMap = material.displacementMap; result.displacementScale = material.displacementScale; result.displacementBias = material.displacementBias; result.wireframeLinewidth = material.wireframeLinewidth; result.linewidth = material.linewidth; if (light.isPointLight === true && result.isMeshDistanceMaterial === true) { result.referencePosition.setFromMatrixPosition(light.matrixWorld); result.nearDistance = shadowCameraNear; result.farDistance = shadowCameraFar; } return result; } function renderObject(object, camera2, shadowCamera, light, type) { if (object.visible === false) return; const visible = object.layers.test(camera2.layers); if (visible && (object.isMesh || object.isLine || object.isPoints)) { if ((object.castShadow || object.receiveShadow && type === VSMShadowMap) && (!object.frustumCulled || _frustum.intersectsObject(object))) { object.modelViewMatrix.multiplyMatrices(shadowCamera.matrixWorldInverse, object.matrixWorld); const geometry = _objects.update(object); const material = object.material; if (Array.isArray(material)) { const groups = geometry.groups; for (let k = 0, kl = groups.length; k < kl; k++) { const group = groups[k]; const groupMaterial = material[group.materialIndex]; if (groupMaterial && groupMaterial.visible) { const depthMaterial = getDepthMaterial(object, groupMaterial, light, shadowCamera.near, shadowCamera.far, type); _renderer.renderBufferDirect(shadowCamera, null, geometry, depthMaterial, object, group); } } } else if (material.visible) { const depthMaterial = getDepthMaterial(object, material, light, shadowCamera.near, shadowCamera.far, type); _renderer.renderBufferDirect(shadowCamera, null, geometry, depthMaterial, object, null); } } } const children = object.children; for (let i = 0, l = children.length; i < l; i++) { renderObject(children[i], camera2, shadowCamera, light, type); } } } function WebGLState(gl, extensions, capabilities) { const isWebGL2 = capabilities.isWebGL2; function ColorBuffer() { let locked = false; const color = new Vector4(); let currentColorMask = null; const currentColorClear = new Vector4(0, 0, 0, 0); return { setMask: function(colorMask) { if (currentColorMask !== colorMask && !locked) { gl.colorMask(colorMask, colorMask, colorMask, colorMask); currentColorMask = colorMask; } }, setLocked: function(lock) { locked = lock; }, setClear: function(r, g2, b, a, premultipliedAlpha) { if (premultipliedAlpha === true) { r *= a; g2 *= a; b *= a; } color.set(r, g2, b, a); if (currentColorClear.equals(color) === false) { gl.clearColor(r, g2, b, a); currentColorClear.copy(color); } }, reset: function() { locked = false; currentColorMask = null; currentColorClear.set(-1, 0, 0, 0); } }; } function DepthBuffer() { let locked = false; let currentDepthMask = null; let currentDepthFunc = null; let currentDepthClear = null; return { setTest: function(depthTest) { if (depthTest) { enable(2929); } else { disable(2929); } }, setMask: function(depthMask) { if (currentDepthMask !== depthMask && !locked) { gl.depthMask(depthMask); currentDepthMask = depthMask; } }, setFunc: function(depthFunc) { if (currentDepthFunc !== depthFunc) { switch (depthFunc) { case NeverDepth: gl.depthFunc(512); break; case AlwaysDepth: gl.depthFunc(519); break; case LessDepth: gl.depthFunc(513); break; case LessEqualDepth: gl.depthFunc(515); break; case EqualDepth: gl.depthFunc(514); break; case GreaterEqualDepth: gl.depthFunc(518); break; case GreaterDepth: gl.depthFunc(516); break; case NotEqualDepth: gl.depthFunc(517); break; default: gl.depthFunc(515); } currentDepthFunc = depthFunc; } }, setLocked: function(lock) { locked = lock; }, setClear: function(depth) { if (currentDepthClear !== depth) { gl.clearDepth(depth); currentDepthClear = depth; } }, reset: function() { locked = false; currentDepthMask = null; currentDepthFunc = null; currentDepthClear = null; } }; } function StencilBuffer() { let locked = false; let currentStencilMask = null; let currentStencilFunc = null; let currentStencilRef = null; let currentStencilFuncMask = null; let currentStencilFail = null; let currentStencilZFail = null; let currentStencilZPass = null; let currentStencilClear = null; return { setTest: function(stencilTest) { if (!locked) { if (stencilTest) { enable(2960); } else { disable(2960); } } }, setMask: function(stencilMask) { if (currentStencilMask !== stencilMask && !locked) { gl.stencilMask(stencilMask); currentStencilMask = stencilMask; } }, setFunc: function(stencilFunc, stencilRef, stencilMask) { if (currentStencilFunc !== stencilFunc || currentStencilRef !== stencilRef || currentStencilFuncMask !== stencilMask) { gl.stencilFunc(stencilFunc, stencilRef, stencilMask); currentStencilFunc = stencilFunc; currentStencilRef = stencilRef; currentStencilFuncMask = stencilMask; } }, setOp: function(stencilFail, stencilZFail, stencilZPass) { if (currentStencilFail !== stencilFail || currentStencilZFail !== stencilZFail || currentStencilZPass !== stencilZPass) { gl.stencilOp(stencilFail, stencilZFail, stencilZPass); currentStencilFail = stencilFail; currentStencilZFail = stencilZFail; currentStencilZPass = stencilZPass; } }, setLocked: function(lock) { locked = lock; }, setClear: function(stencil) { if (currentStencilClear !== stencil) { gl.clearStencil(stencil); currentStencilClear = stencil; } }, reset: function() { locked = false; currentStencilMask = null; currentStencilFunc = null; currentStencilRef = null; currentStencilFuncMask = null; currentStencilFail = null; currentStencilZFail = null; currentStencilZPass = null; currentStencilClear = null; } }; } const colorBuffer = new ColorBuffer(); const depthBuffer = new DepthBuffer(); const stencilBuffer = new StencilBuffer(); const uboBindings = /* @__PURE__ */ new WeakMap(); const uboProgamMap = /* @__PURE__ */ new WeakMap(); let enabledCapabilities = {}; let currentBoundFramebuffers = {}; let currentDrawbuffers = /* @__PURE__ */ new WeakMap(); let defaultDrawbuffers = []; let currentProgram = null; let currentBlendingEnabled = false; let currentBlending = null; let currentBlendEquation = null; let currentBlendSrc = null; let currentBlendDst = null; let currentBlendEquationAlpha = null; let currentBlendSrcAlpha = null; let currentBlendDstAlpha = null; let currentPremultipledAlpha = false; let currentFlipSided = null; let currentCullFace = null; let currentLineWidth = null; let currentPolygonOffsetFactor = null; let currentPolygonOffsetUnits = null; const maxTextures = gl.getParameter(35661); let lineWidthAvailable = false; let version = 0; const glVersion = gl.getParameter(7938); if (glVersion.indexOf("WebGL") !== -1) { version = parseFloat(/^WebGL (\d)/.exec(glVersion)[1]); lineWidthAvailable = version >= 1; } else if (glVersion.indexOf("OpenGL ES") !== -1) { version = parseFloat(/^OpenGL ES (\d)/.exec(glVersion)[1]); lineWidthAvailable = version >= 2; } let currentTextureSlot = null; let currentBoundTextures = {}; const scissorParam = gl.getParameter(3088); const viewportParam = gl.getParameter(2978); const currentScissor = new Vector4().fromArray(scissorParam); const currentViewport = new Vector4().fromArray(viewportParam); function createTexture(type, target2, count) { const data = new Uint8Array(4); const texture = gl.createTexture(); gl.bindTexture(type, texture); gl.texParameteri(type, 10241, 9728); gl.texParameteri(type, 10240, 9728); for (let i = 0; i < count; i++) { gl.texImage2D(target2 + i, 0, 6408, 1, 1, 0, 6408, 5121, data); } return texture; } const emptyTextures = {}; emptyTextures[3553] = createTexture(3553, 3553, 1); emptyTextures[34067] = createTexture(34067, 34069, 6); colorBuffer.setClear(0, 0, 0, 1); depthBuffer.setClear(1); stencilBuffer.setClear(0); enable(2929); depthBuffer.setFunc(LessEqualDepth); setFlipSided(false); setCullFace(CullFaceBack); enable(2884); setBlending(NoBlending); function enable(id) { if (enabledCapabilities[id] !== true) { gl.enable(id); enabledCapabilities[id] = true; } } function disable(id) { if (enabledCapabilities[id] !== false) { gl.disable(id); enabledCapabilities[id] = false; } } function bindFramebuffer(target2, framebuffer) { if (currentBoundFramebuffers[target2] !== framebuffer) { gl.bindFramebuffer(target2, framebuffer); currentBoundFramebuffers[target2] = framebuffer; if (isWebGL2) { if (target2 === 36009) { currentBoundFramebuffers[36160] = framebuffer; } if (target2 === 36160) { currentBoundFramebuffers[36009] = framebuffer; } } return true; } return false; } function drawBuffers(renderTarget, framebuffer) { let drawBuffers2 = defaultDrawbuffers; let needsUpdate = false; if (renderTarget) { drawBuffers2 = currentDrawbuffers.get(framebuffer); if (drawBuffers2 === void 0) { drawBuffers2 = []; currentDrawbuffers.set(framebuffer, drawBuffers2); } if (renderTarget.isWebGLMultipleRenderTargets) { const textures = renderTarget.texture; if (drawBuffers2.length !== textures.length || drawBuffers2[0] !== 36064) { for (let i = 0, il = textures.length; i < il; i++) { drawBuffers2[i] = 36064 + i; } drawBuffers2.length = textures.length; needsUpdate = true; } } else { if (drawBuffers2[0] !== 36064) { drawBuffers2[0] = 36064; needsUpdate = true; } } } else { if (drawBuffers2[0] !== 1029) { drawBuffers2[0] = 1029; needsUpdate = true; } } if (needsUpdate) { if (capabilities.isWebGL2) { gl.drawBuffers(drawBuffers2); } else { extensions.get("WEBGL_draw_buffers").drawBuffersWEBGL(drawBuffers2); } } } function useProgram(program) { if (currentProgram !== program) { gl.useProgram(program); currentProgram = program; return true; } return false; } const equationToGL = { [AddEquation]: 32774, [SubtractEquation]: 32778, [ReverseSubtractEquation]: 32779 }; if (isWebGL2) { equationToGL[MinEquation] = 32775; equationToGL[MaxEquation] = 32776; } else { const extension = extensions.get("EXT_blend_minmax"); if (extension !== null) { equationToGL[MinEquation] = extension.MIN_EXT; equationToGL[MaxEquation] = extension.MAX_EXT; } } const factorToGL = { [ZeroFactor]: 0, [OneFactor]: 1, [SrcColorFactor]: 768, [SrcAlphaFactor]: 770, [SrcAlphaSaturateFactor]: 776, [DstColorFactor]: 774, [DstAlphaFactor]: 772, [OneMinusSrcColorFactor]: 769, [OneMinusSrcAlphaFactor]: 771, [OneMinusDstColorFactor]: 775, [OneMinusDstAlphaFactor]: 773 }; function setBlending(blending, blendEquation, blendSrc, blendDst, blendEquationAlpha, blendSrcAlpha, blendDstAlpha, premultipliedAlpha) { if (blending === NoBlending) { if (currentBlendingEnabled === true) { disable(3042); currentBlendingEnabled = false; } return; } if (currentBlendingEnabled === false) { enable(3042); currentBlendingEnabled = true; } if (blending !== CustomBlending) { if (blending !== currentBlending || premultipliedAlpha !== currentPremultipledAlpha) { if (currentBlendEquation !== AddEquation || currentBlendEquationAlpha !== AddEquation) { gl.blendEquation(32774); currentBlendEquation = AddEquation; currentBlendEquationAlpha = AddEquation; } if (premultipliedAlpha) { switch (blending) { case NormalBlending: gl.blendFuncSeparate(1, 771, 1, 771); break; case AdditiveBlending: gl.blendFunc(1, 1); break; case SubtractiveBlending: gl.blendFuncSeparate(0, 769, 0, 1); break; case MultiplyBlending: gl.blendFuncSeparate(0, 768, 0, 770); break; default: console.error("THREE.WebGLState: Invalid blending: ", blending); break; } } else { switch (blending) { case NormalBlending: gl.blendFuncSeparate(770, 771, 1, 771); break; case AdditiveBlending: gl.blendFunc(770, 1); break; case SubtractiveBlending: gl.blendFuncSeparate(0, 769, 0, 1); break; case MultiplyBlending: gl.blendFunc(0, 768); break; default: console.error("THREE.WebGLState: Invalid blending: ", blending); break; } } currentBlendSrc = null; currentBlendDst = null; currentBlendSrcAlpha = null; currentBlendDstAlpha = null; currentBlending = blending; currentPremultipledAlpha = premultipliedAlpha; } return; } blendEquationAlpha = blendEquationAlpha || blendEquation; blendSrcAlpha = blendSrcAlpha || blendSrc; blendDstAlpha = blendDstAlpha || blendDst; if (blendEquation !== currentBlendEquation || blendEquationAlpha !== currentBlendEquationAlpha) { gl.blendEquationSeparate(equationToGL[blendEquation], equationToGL[blendEquationAlpha]); currentBlendEquation = blendEquation; currentBlendEquationAlpha = blendEquationAlpha; } if (blendSrc !== currentBlendSrc || blendDst !== currentBlendDst || blendSrcAlpha !== currentBlendSrcAlpha || blendDstAlpha !== currentBlendDstAlpha) { gl.blendFuncSeparate(factorToGL[blendSrc], factorToGL[blendDst], factorToGL[blendSrcAlpha], factorToGL[blendDstAlpha]); currentBlendSrc = blendSrc; currentBlendDst = blendDst; currentBlendSrcAlpha = blendSrcAlpha; currentBlendDstAlpha = blendDstAlpha; } currentBlending = blending; currentPremultipledAlpha = null; } function setMaterial(material, frontFaceCW) { material.side === DoubleSide ? disable(2884) : enable(2884); let flipSided = material.side === BackSide; if (frontFaceCW) flipSided = !flipSided; setFlipSided(flipSided); material.blending === NormalBlending && material.transparent === false ? setBlending(NoBlending) : setBlending(material.blending, material.blendEquation, material.blendSrc, material.blendDst, material.blendEquationAlpha, material.blendSrcAlpha, material.blendDstAlpha, material.premultipliedAlpha); depthBuffer.setFunc(material.depthFunc); depthBuffer.setTest(material.depthTest); depthBuffer.setMask(material.depthWrite); colorBuffer.setMask(material.colorWrite); const stencilWrite = material.stencilWrite; stencilBuffer.setTest(stencilWrite); if (stencilWrite) { stencilBuffer.setMask(material.stencilWriteMask); stencilBuffer.setFunc(material.stencilFunc, material.stencilRef, material.stencilFuncMask); stencilBuffer.setOp(material.stencilFail, material.stencilZFail, material.stencilZPass); } setPolygonOffset(material.polygonOffset, material.polygonOffsetFactor, material.polygonOffsetUnits); material.alphaToCoverage === true ? enable(32926) : disable(32926); } function setFlipSided(flipSided) { if (currentFlipSided !== flipSided) { if (flipSided) { gl.frontFace(2304); } else { gl.frontFace(2305); } currentFlipSided = flipSided; } } function setCullFace(cullFace) { if (cullFace !== CullFaceNone) { enable(2884); if (cullFace !== currentCullFace) { if (cullFace === CullFaceBack) { gl.cullFace(1029); } else if (cullFace === CullFaceFront) { gl.cullFace(1028); } else { gl.cullFace(1032); } } } else { disable(2884); } currentCullFace = cullFace; } function setLineWidth(width) { if (width !== currentLineWidth) { if (lineWidthAvailable) gl.lineWidth(width); currentLineWidth = width; } } function setPolygonOffset(polygonOffset, factor, units) { if (polygonOffset) { enable(32823); if (currentPolygonOffsetFactor !== factor || currentPolygonOffsetUnits !== units) { gl.polygonOffset(factor, units); currentPolygonOffsetFactor = factor; currentPolygonOffsetUnits = units; } } else { disable(32823); } } function setScissorTest(scissorTest) { if (scissorTest) { enable(3089); } else { disable(3089); } } function activeTexture(webglSlot) { if (webglSlot === void 0) webglSlot = 33984 + maxTextures - 1; if (currentTextureSlot !== webglSlot) { gl.activeTexture(webglSlot); currentTextureSlot = webglSlot; } } function bindTexture(webglType, webglTexture, webglSlot) { if (webglSlot === void 0) { if (currentTextureSlot === null) { webglSlot = 33984 + maxTextures - 1; } else { webglSlot = currentTextureSlot; } } let boundTexture = currentBoundTextures[webglSlot]; if (boundTexture === void 0) { boundTexture = { type: void 0, texture: void 0 }; currentBoundTextures[webglSlot] = boundTexture; } if (boundTexture.type !== webglType || boundTexture.texture !== webglTexture) { if (currentTextureSlot !== webglSlot) { gl.activeTexture(webglSlot); currentTextureSlot = webglSlot; } gl.bindTexture(webglType, webglTexture || emptyTextures[webglType]); boundTexture.type = webglType; boundTexture.texture = webglTexture; } } function unbindTexture() { const boundTexture = currentBoundTextures[currentTextureSlot]; if (boundTexture !== void 0 && boundTexture.type !== void 0) { gl.bindTexture(boundTexture.type, null); boundTexture.type = void 0; boundTexture.texture = void 0; } } function compressedTexImage2D() { try { gl.compressedTexImage2D.apply(gl, arguments); } catch (error) { console.error("THREE.WebGLState:", error); } } function compressedTexImage3D() { try { gl.compressedTexImage3D.apply(gl, arguments); } catch (error) { console.error("THREE.WebGLState:", error); } } function texSubImage2D() { try { gl.texSubImage2D.apply(gl, arguments); } catch (error) { console.error("THREE.WebGLState:", error); } } function texSubImage3D() { try { gl.texSubImage3D.apply(gl, arguments); } catch (error) { console.error("THREE.WebGLState:", error); } } function compressedTexSubImage2D() { try { gl.compressedTexSubImage2D.apply(gl, arguments); } catch (error) { console.error("THREE.WebGLState:", error); } } function compressedTexSubImage3D() { try { gl.compressedTexSubImage3D.apply(gl, arguments); } catch (error) { console.error("THREE.WebGLState:", error); } } function texStorage2D() { try { gl.texStorage2D.apply(gl, arguments); } catch (error) { console.error("THREE.WebGLState:", error); } } function texStorage3D() { try { gl.texStorage3D.apply(gl, arguments); } catch (error) { console.error("THREE.WebGLState:", error); } } function texImage2D() { try { gl.texImage2D.apply(gl, arguments); } catch (error) { console.error("THREE.WebGLState:", error); } } function texImage3D() { try { gl.texImage3D.apply(gl, arguments); } catch (error) { console.error("THREE.WebGLState:", error); } } function scissor(scissor2) { if (currentScissor.equals(scissor2) === false) { gl.scissor(scissor2.x, scissor2.y, scissor2.z, scissor2.w); currentScissor.copy(scissor2); } } function viewport(viewport2) { if (currentViewport.equals(viewport2) === false) { gl.viewport(viewport2.x, viewport2.y, viewport2.z, viewport2.w); currentViewport.copy(viewport2); } } function updateUBOMapping(uniformsGroup, program) { let mapping = uboProgamMap.get(program); if (mapping === void 0) { mapping = /* @__PURE__ */ new WeakMap(); uboProgamMap.set(program, mapping); } let blockIndex = mapping.get(uniformsGroup); if (blockIndex === void 0) { blockIndex = gl.getUniformBlockIndex(program, uniformsGroup.name); mapping.set(uniformsGroup, blockIndex); } } function uniformBlockBinding(uniformsGroup, program) { const mapping = uboProgamMap.get(program); const blockIndex = mapping.get(uniformsGroup); if (uboBindings.get(uniformsGroup) !== blockIndex) { gl.uniformBlockBinding(program, blockIndex, uniformsGroup.__bindingPointIndex); uboBindings.set(uniformsGroup, blockIndex); } } function reset() { gl.disable(3042); gl.disable(2884); gl.disable(2929); gl.disable(32823); gl.disable(3089); gl.disable(2960); gl.disable(32926); gl.blendEquation(32774); gl.blendFunc(1, 0); gl.blendFuncSeparate(1, 0, 1, 0); gl.colorMask(true, true, true, true); gl.clearColor(0, 0, 0, 0); gl.depthMask(true); gl.depthFunc(513); gl.clearDepth(1); gl.stencilMask(4294967295); gl.stencilFunc(519, 0, 4294967295); gl.stencilOp(7680, 7680, 7680); gl.clearStencil(0); gl.cullFace(1029); gl.frontFace(2305); gl.polygonOffset(0, 0); gl.activeTexture(33984); gl.bindFramebuffer(36160, null); if (isWebGL2 === true) { gl.bindFramebuffer(36009, null); gl.bindFramebuffer(36008, null); } gl.useProgram(null); gl.lineWidth(1); gl.scissor(0, 0, gl.canvas.width, gl.canvas.height); gl.viewport(0, 0, gl.canvas.width, gl.canvas.height); enabledCapabilities = {}; currentTextureSlot = null; currentBoundTextures = {}; currentBoundFramebuffers = {}; currentDrawbuffers = /* @__PURE__ */ new WeakMap(); defaultDrawbuffers = []; currentProgram = null; currentBlendingEnabled = false; currentBlending = null; currentBlendEquation = null; currentBlendSrc = null; currentBlendDst = null; currentBlendEquationAlpha = null; currentBlendSrcAlpha = null; currentBlendDstAlpha = null; currentPremultipledAlpha = false; currentFlipSided = null; currentCullFace = null; currentLineWidth = null; currentPolygonOffsetFactor = null; currentPolygonOffsetUnits = null; currentScissor.set(0, 0, gl.canvas.width, gl.canvas.height); currentViewport.set(0, 0, gl.canvas.width, gl.canvas.height); colorBuffer.reset(); depthBuffer.reset(); stencilBuffer.reset(); } return { buffers: { color: colorBuffer, depth: depthBuffer, stencil: stencilBuffer }, enable, disable, bindFramebuffer, drawBuffers, useProgram, setBlending, setMaterial, setFlipSided, setCullFace, setLineWidth, setPolygonOffset, setScissorTest, activeTexture, bindTexture, unbindTexture, compressedTexImage2D, compressedTexImage3D, texImage2D, texImage3D, updateUBOMapping, uniformBlockBinding, texStorage2D, texStorage3D, texSubImage2D, texSubImage3D, compressedTexSubImage2D, compressedTexSubImage3D, scissor, viewport, reset }; } function WebGLTextures(_gl, extensions, state, properties, capabilities, utils, info) { const isWebGL2 = capabilities.isWebGL2; const maxTextures = capabilities.maxTextures; const maxCubemapSize = capabilities.maxCubemapSize; const maxTextureSize = capabilities.maxTextureSize; const maxSamples = capabilities.maxSamples; const multisampledRTTExt = extensions.has("WEBGL_multisampled_render_to_texture") ? extensions.get("WEBGL_multisampled_render_to_texture") : null; const supportsInvalidateFramebuffer = /OculusBrowser/g.test(typeof navigator === "undefined" ? "" : navigator.userAgent); const _videoTextures = /* @__PURE__ */ new WeakMap(); let _canvas2; const _sources = /* @__PURE__ */ new WeakMap(); let useOffscreenCanvas = false; try { useOffscreenCanvas = typeof OffscreenCanvas !== "undefined" && new OffscreenCanvas(1, 1).getContext("2d") !== null; } catch (err) { } function createCanvas(width, height) { return useOffscreenCanvas ? ( // eslint-disable-next-line compat/compat new OffscreenCanvas(width, height) ) : createElementNS("canvas"); } function resizeImage(image, needsPowerOfTwo, needsNewCanvas, maxSize) { let scale = 1; if (image.width > maxSize || image.height > maxSize) { scale = maxSize / Math.max(image.width, image.height); } if (scale < 1 || needsPowerOfTwo === true) { if (typeof HTMLImageElement !== "undefined" && image instanceof HTMLImageElement || typeof HTMLCanvasElement !== "undefined" && image instanceof HTMLCanvasElement || typeof ImageBitmap !== "undefined" && image instanceof ImageBitmap) { const floor = needsPowerOfTwo ? floorPowerOfTwo : Math.floor; const width = floor(scale * image.width); const height = floor(scale * image.height); if (_canvas2 === void 0) _canvas2 = createCanvas(width, height); const canvas = needsNewCanvas ? createCanvas(width, height) : _canvas2; canvas.width = width; canvas.height = height; const context = canvas.getContext("2d"); context.drawImage(image, 0, 0, width, height); console.warn("THREE.WebGLRenderer: Texture has been resized from (" + image.width + "x" + image.height + ") to (" + width + "x" + height + ")."); return canvas; } else { if ("data" in image) { console.warn("THREE.WebGLRenderer: Image in DataTexture is too big (" + image.width + "x" + image.height + ")."); } return image; } } return image; } function isPowerOfTwo$1(image) { return isPowerOfTwo(image.width) && isPowerOfTwo(image.height); } function textureNeedsPowerOfTwo(texture) { if (isWebGL2) return false; return texture.wrapS !== ClampToEdgeWrapping || texture.wrapT !== ClampToEdgeWrapping || texture.minFilter !== NearestFilter && texture.minFilter !== LinearFilter; } function textureNeedsGenerateMipmaps(texture, supportsMips) { return texture.generateMipmaps && supportsMips && texture.minFilter !== NearestFilter && texture.minFilter !== LinearFilter; } function generateMipmap(target2) { _gl.generateMipmap(target2); } function getInternalFormat(internalFormatName, glFormat, glType, encoding, forceLinearEncoding = false) { if (isWebGL2 === false) return glFormat; if (internalFormatName !== null) { if (_gl[internalFormatName] !== void 0) return _gl[internalFormatName]; console.warn("THREE.WebGLRenderer: Attempt to use non-existing WebGL internal format '" + internalFormatName + "'"); } let internalFormat = glFormat; if (glFormat === 6403) { if (glType === 5126) internalFormat = 33326; if (glType === 5131) internalFormat = 33325; if (glType === 5121) internalFormat = 33321; } if (glFormat === 33319) { if (glType === 5126) internalFormat = 33328; if (glType === 5131) internalFormat = 33327; if (glType === 5121) internalFormat = 33323; } if (glFormat === 6408) { if (glType === 5126) internalFormat = 34836; if (glType === 5131) internalFormat = 34842; if (glType === 5121) internalFormat = encoding === sRGBEncoding && forceLinearEncoding === false ? 35907 : 32856; if (glType === 32819) internalFormat = 32854; if (glType === 32820) internalFormat = 32855; } if (internalFormat === 33325 || internalFormat === 33326 || internalFormat === 33327 || internalFormat === 33328 || internalFormat === 34842 || internalFormat === 34836) { extensions.get("EXT_color_buffer_float"); } return internalFormat; } function getMipLevels(texture, image, supportsMips) { if (textureNeedsGenerateMipmaps(texture, supportsMips) === true || texture.isFramebufferTexture && texture.minFilter !== NearestFilter && texture.minFilter !== LinearFilter) { return Math.log2(Math.max(image.width, image.height)) + 1; } else if (texture.mipmaps !== void 0 && texture.mipmaps.length > 0) { return texture.mipmaps.length; } else if (texture.isCompressedTexture && Array.isArray(texture.image)) { return image.mipmaps.length; } else { return 1; } } function filterFallback(f) { if (f === NearestFilter || f === NearestMipmapNearestFilter || f === NearestMipmapLinearFilter) { return 9728; } return 9729; } function onTextureDispose(event) { const texture = event.target; texture.removeEventListener("dispose", onTextureDispose); deallocateTexture(texture); if (texture.isVideoTexture) { _videoTextures.delete(texture); } } function onRenderTargetDispose(event) { const renderTarget = event.target; renderTarget.removeEventListener("dispose", onRenderTargetDispose); deallocateRenderTarget(renderTarget); } function deallocateTexture(texture) { const textureProperties = properties.get(texture); if (textureProperties.__webglInit === void 0) return; const source = texture.source; const webglTextures = _sources.get(source); if (webglTextures) { const webglTexture = webglTextures[textureProperties.__cacheKey]; webglTexture.usedTimes--; if (webglTexture.usedTimes === 0) { deleteTexture(texture); } if (Object.keys(webglTextures).length === 0) { _sources.delete(source); } } properties.remove(texture); } function deleteTexture(texture) { const textureProperties = properties.get(texture); _gl.deleteTexture(textureProperties.__webglTexture); const source = texture.source; const webglTextures = _sources.get(source); delete webglTextures[textureProperties.__cacheKey]; info.memory.textures--; } function deallocateRenderTarget(renderTarget) { const texture = renderTarget.texture; const renderTargetProperties = properties.get(renderTarget); const textureProperties = properties.get(texture); if (textureProperties.__webglTexture !== void 0) { _gl.deleteTexture(textureProperties.__webglTexture); info.memory.textures--; } if (renderTarget.depthTexture) { renderTarget.depthTexture.dispose(); } if (renderTarget.isWebGLCubeRenderTarget) { for (let i = 0; i < 6; i++) { _gl.deleteFramebuffer(renderTargetProperties.__webglFramebuffer[i]); if (renderTargetProperties.__webglDepthbuffer) _gl.deleteRenderbuffer(renderTargetProperties.__webglDepthbuffer[i]); } } else { _gl.deleteFramebuffer(renderTargetProperties.__webglFramebuffer); if (renderTargetProperties.__webglDepthbuffer) _gl.deleteRenderbuffer(renderTargetProperties.__webglDepthbuffer); if (renderTargetProperties.__webglMultisampledFramebuffer) _gl.deleteFramebuffer(renderTargetProperties.__webglMultisampledFramebuffer); if (renderTargetProperties.__webglColorRenderbuffer) { for (let i = 0; i < renderTargetProperties.__webglColorRenderbuffer.length; i++) { if (renderTargetProperties.__webglColorRenderbuffer[i]) _gl.deleteRenderbuffer(renderTargetProperties.__webglColorRenderbuffer[i]); } } if (renderTargetProperties.__webglDepthRenderbuffer) _gl.deleteRenderbuffer(renderTargetProperties.__webglDepthRenderbuffer); } if (renderTarget.isWebGLMultipleRenderTargets) { for (let i = 0, il = texture.length; i < il; i++) { const attachmentProperties = properties.get(texture[i]); if (attachmentProperties.__webglTexture) { _gl.deleteTexture(attachmentProperties.__webglTexture); info.memory.textures--; } properties.remove(texture[i]); } } properties.remove(texture); properties.remove(renderTarget); } let textureUnits = 0; function resetTextureUnits() { textureUnits = 0; } function allocateTextureUnit() { const textureUnit = textureUnits; if (textureUnit >= maxTextures) { console.warn("THREE.WebGLTextures: Trying to use " + textureUnit + " texture units while this GPU supports only " + maxTextures); } textureUnits += 1; return textureUnit; } function getTextureCacheKey(texture) { const array = []; array.push(texture.wrapS); array.push(texture.wrapT); array.push(texture.wrapR || 0); array.push(texture.magFilter); array.push(texture.minFilter); array.push(texture.anisotropy); array.push(texture.internalFormat); array.push(texture.format); array.push(texture.type); array.push(texture.generateMipmaps); array.push(texture.premultiplyAlpha); array.push(texture.flipY); array.push(texture.unpackAlignment); array.push(texture.encoding); return array.join(); } function setTexture2D(texture, slot) { const textureProperties = properties.get(texture); if (texture.isVideoTexture) updateVideoTexture(texture); if (texture.isRenderTargetTexture === false && texture.version > 0 && textureProperties.__version !== texture.version) { const image = texture.image; if (image === null) { console.warn("THREE.WebGLRenderer: Texture marked for update but no image data found."); } else if (image.complete === false) { console.warn("THREE.WebGLRenderer: Texture marked for update but image is incomplete"); } else { uploadTexture(textureProperties, texture, slot); return; } } state.bindTexture(3553, textureProperties.__webglTexture, 33984 + slot); } function setTexture2DArray(texture, slot) { const textureProperties = properties.get(texture); if (texture.version > 0 && textureProperties.__version !== texture.version) { uploadTexture(textureProperties, texture, slot); return; } state.bindTexture(35866, textureProperties.__webglTexture, 33984 + slot); } function setTexture3D(texture, slot) { const textureProperties = properties.get(texture); if (texture.version > 0 && textureProperties.__version !== texture.version) { uploadTexture(textureProperties, texture, slot); return; } state.bindTexture(32879, textureProperties.__webglTexture, 33984 + slot); } function setTextureCube(texture, slot) { const textureProperties = properties.get(texture); if (texture.version > 0 && textureProperties.__version !== texture.version) { uploadCubeTexture(textureProperties, texture, slot); return; } state.bindTexture(34067, textureProperties.__webglTexture, 33984 + slot); } const wrappingToGL = { [RepeatWrapping]: 10497, [ClampToEdgeWrapping]: 33071, [MirroredRepeatWrapping]: 33648 }; const filterToGL = { [NearestFilter]: 9728, [NearestMipmapNearestFilter]: 9984, [NearestMipmapLinearFilter]: 9986, [LinearFilter]: 9729, [LinearMipmapNearestFilter]: 9985, [LinearMipmapLinearFilter]: 9987 }; function setTextureParameters(textureType, texture, supportsMips) { if (supportsMips) { _gl.texParameteri(textureType, 10242, wrappingToGL[texture.wrapS]); _gl.texParameteri(textureType, 10243, wrappingToGL[texture.wrapT]); if (textureType === 32879 || textureType === 35866) { _gl.texParameteri(textureType, 32882, wrappingToGL[texture.wrapR]); } _gl.texParameteri(textureType, 10240, filterToGL[texture.magFilter]); _gl.texParameteri(textureType, 10241, filterToGL[texture.minFilter]); } else { _gl.texParameteri(textureType, 10242, 33071); _gl.texParameteri(textureType, 10243, 33071); if (textureType === 32879 || textureType === 35866) { _gl.texParameteri(textureType, 32882, 33071); } if (texture.wrapS !== ClampToEdgeWrapping || texture.wrapT !== ClampToEdgeWrapping) { console.warn("THREE.WebGLRenderer: Texture is not power of two. Texture.wrapS and Texture.wrapT should be set to THREE.ClampToEdgeWrapping."); } _gl.texParameteri(textureType, 10240, filterFallback(texture.magFilter)); _gl.texParameteri(textureType, 10241, filterFallback(texture.minFilter)); if (texture.minFilter !== NearestFilter && texture.minFilter !== LinearFilter) { console.warn("THREE.WebGLRenderer: Texture is not power of two. Texture.minFilter should be set to THREE.NearestFilter or THREE.LinearFilter."); } } if (extensions.has("EXT_texture_filter_anisotropic") === true) { const extension = extensions.get("EXT_texture_filter_anisotropic"); if (texture.type === FloatType && extensions.has("OES_texture_float_linear") === false) return; if (isWebGL2 === false && (texture.type === HalfFloatType && extensions.has("OES_texture_half_float_linear") === false)) return; if (texture.anisotropy > 1 || properties.get(texture).__currentAnisotropy) { _gl.texParameterf(textureType, extension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(texture.anisotropy, capabilities.getMaxAnisotropy())); properties.get(texture).__currentAnisotropy = texture.anisotropy; } } } function initTexture(textureProperties, texture) { let forceUpload = false; if (textureProperties.__webglInit === void 0) { textureProperties.__webglInit = true; texture.addEventListener("dispose", onTextureDispose); } const source = texture.source; let webglTextures = _sources.get(source); if (webglTextures === void 0) { webglTextures = {}; _sources.set(source, webglTextures); } const textureCacheKey = getTextureCacheKey(texture); if (textureCacheKey !== textureProperties.__cacheKey) { if (webglTextures[textureCacheKey] === void 0) { webglTextures[textureCacheKey] = { texture: _gl.createTexture(), usedTimes: 0 }; info.memory.textures++; forceUpload = true; } webglTextures[textureCacheKey].usedTimes++; const webglTexture = webglTextures[textureProperties.__cacheKey]; if (webglTexture !== void 0) { webglTextures[textureProperties.__cacheKey].usedTimes--; if (webglTexture.usedTimes === 0) { deleteTexture(texture); } } textureProperties.__cacheKey = textureCacheKey; textureProperties.__webglTexture = webglTextures[textureCacheKey].texture; } return forceUpload; } function uploadTexture(textureProperties, texture, slot) { let textureType = 3553; if (texture.isDataArrayTexture || texture.isCompressedArrayTexture) textureType = 35866; if (texture.isData3DTexture) textureType = 32879; const forceUpload = initTexture(textureProperties, texture); const source = texture.source; state.bindTexture(textureType, textureProperties.__webglTexture, 33984 + slot); const sourceProperties = properties.get(source); if (source.version !== sourceProperties.__version || forceUpload === true) { state.activeTexture(33984 + slot); _gl.pixelStorei(37440, texture.flipY); _gl.pixelStorei(37441, texture.premultiplyAlpha); _gl.pixelStorei(3317, texture.unpackAlignment); _gl.pixelStorei(37443, 0); const needsPowerOfTwo = textureNeedsPowerOfTwo(texture) && isPowerOfTwo$1(texture.image) === false; let image = resizeImage(texture.image, needsPowerOfTwo, false, maxTextureSize); image = verifyColorSpace(texture, image); const supportsMips = isPowerOfTwo$1(image) || isWebGL2, glFormat = utils.convert(texture.format, texture.encoding); let glType = utils.convert(texture.type), glInternalFormat = getInternalFormat(texture.internalFormat, glFormat, glType, texture.encoding, texture.isVideoTexture); setTextureParameters(textureType, texture, supportsMips); let mipmap; const mipmaps = texture.mipmaps; const useTexStorage = isWebGL2 && texture.isVideoTexture !== true; const allocateMemory = sourceProperties.__version === void 0 || forceUpload === true; const levels = getMipLevels(texture, image, supportsMips); if (texture.isDepthTexture) { glInternalFormat = 6402; if (isWebGL2) { if (texture.type === FloatType) { glInternalFormat = 36012; } else if (texture.type === UnsignedIntType) { glInternalFormat = 33190; } else if (texture.type === UnsignedInt248Type) { glInternalFormat = 35056; } else { glInternalFormat = 33189; } } else { if (texture.type === FloatType) { console.error("WebGLRenderer: Floating point depth texture requires WebGL2."); } } if (texture.format === DepthFormat && glInternalFormat === 6402) { if (texture.type !== UnsignedShortType && texture.type !== UnsignedIntType) { console.warn("THREE.WebGLRenderer: Use UnsignedShortType or UnsignedIntType for DepthFormat DepthTexture."); texture.type = UnsignedIntType; glType = utils.convert(texture.type); } } if (texture.format === DepthStencilFormat && glInternalFormat === 6402) { glInternalFormat = 34041; if (texture.type !== UnsignedInt248Type) { console.warn("THREE.WebGLRenderer: Use UnsignedInt248Type for DepthStencilFormat DepthTexture."); texture.type = UnsignedInt248Type; glType = utils.convert(texture.type); } } if (allocateMemory) { if (useTexStorage) { state.texStorage2D(3553, 1, glInternalFormat, image.width, image.height); } else { state.texImage2D(3553, 0, glInternalFormat, image.width, image.height, 0, glFormat, glType, null); } } } else if (texture.isDataTexture) { if (mipmaps.length > 0 && supportsMips) { if (useTexStorage && allocateMemory) { state.texStorage2D(3553, levels, glInternalFormat, mipmaps[0].width, mipmaps[0].height); } for (let i = 0, il = mipmaps.length; i < il; i++) { mipmap = mipmaps[i]; if (useTexStorage) { state.texSubImage2D(3553, i, 0, 0, mipmap.width, mipmap.height, glFormat, glType, mipmap.data); } else { state.texImage2D(3553, i, glInternalFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data); } } texture.generateMipmaps = false; } else { if (useTexStorage) { if (allocateMemory) { state.texStorage2D(3553, levels, glInternalFormat, image.width, image.height); } state.texSubImage2D(3553, 0, 0, 0, image.width, image.height, glFormat, glType, image.data); } else { state.texImage2D(3553, 0, glInternalFormat, image.width, image.height, 0, glFormat, glType, image.data); } } } else if (texture.isCompressedTexture) { if (texture.isCompressedArrayTexture) { if (useTexStorage && allocateMemory) { state.texStorage3D(35866, levels, glInternalFormat, mipmaps[0].width, mipmaps[0].height, image.depth); } for (let i = 0, il = mipmaps.length; i < il; i++) { mipmap = mipmaps[i]; if (texture.format !== RGBAFormat) { if (glFormat !== null) { if (useTexStorage) { state.compressedTexSubImage3D(35866, i, 0, 0, 0, mipmap.width, mipmap.height, image.depth, glFormat, mipmap.data, 0, 0); } else { state.compressedTexImage3D(35866, i, glInternalFormat, mipmap.width, mipmap.height, image.depth, 0, mipmap.data, 0, 0); } } else { console.warn("THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .uploadTexture()"); } } else { if (useTexStorage) { state.texSubImage3D(35866, i, 0, 0, 0, mipmap.width, mipmap.height, image.depth, glFormat, glType, mipmap.data); } else { state.texImage3D(35866, i, glInternalFormat, mipmap.width, mipmap.height, image.depth, 0, glFormat, glType, mipmap.data); } } } } else { if (useTexStorage && allocateMemory) { state.texStorage2D(3553, levels, glInternalFormat, mipmaps[0].width, mipmaps[0].height); } for (let i = 0, il = mipmaps.length; i < il; i++) { mipmap = mipmaps[i]; if (texture.format !== RGBAFormat) { if (glFormat !== null) { if (useTexStorage) { state.compressedTexSubImage2D(3553, i, 0, 0, mipmap.width, mipmap.height, glFormat, mipmap.data); } else { state.compressedTexImage2D(3553, i, glInternalFormat, mipmap.width, mipmap.height, 0, mipmap.data); } } else { console.warn("THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .uploadTexture()"); } } else { if (useTexStorage) { state.texSubImage2D(3553, i, 0, 0, mipmap.width, mipmap.height, glFormat, glType, mipmap.data); } else { state.texImage2D(3553, i, glInternalFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data); } } } } } else if (texture.isDataArrayTexture) { if (useTexStorage) { if (allocateMemory) { state.texStorage3D(35866, levels, glInternalFormat, image.width, image.height, image.depth); } state.texSubImage3D(35866, 0, 0, 0, 0, image.width, image.height, image.depth, glFormat, glType, image.data); } else { state.texImage3D(35866, 0, glInternalFormat, image.width, image.height, image.depth, 0, glFormat, glType, image.data); } } else if (texture.isData3DTexture) { if (useTexStorage) { if (allocateMemory) { state.texStorage3D(32879, levels, glInternalFormat, image.width, image.height, image.depth); } state.texSubImage3D(32879, 0, 0, 0, 0, image.width, image.height, image.depth, glFormat, glType, image.data); } else { state.texImage3D(32879, 0, glInternalFormat, image.width, image.height, image.depth, 0, glFormat, glType, image.data); } } else if (texture.isFramebufferTexture) { if (allocateMemory) { if (useTexStorage) { state.texStorage2D(3553, levels, glInternalFormat, image.width, image.height); } else { let width = image.width, height = image.height; for (let i = 0; i < levels; i++) { state.texImage2D(3553, i, glInternalFormat, width, height, 0, glFormat, glType, null); width >>= 1; height >>= 1; } } } } else { if (mipmaps.length > 0 && supportsMips) { if (useTexStorage && allocateMemory) { state.texStorage2D(3553, levels, glInternalFormat, mipmaps[0].width, mipmaps[0].height); } for (let i = 0, il = mipmaps.length; i < il; i++) { mipmap = mipmaps[i]; if (useTexStorage) { state.texSubImage2D(3553, i, 0, 0, glFormat, glType, mipmap); } else { state.texImage2D(3553, i, glInternalFormat, glFormat, glType, mipmap); } } texture.generateMipmaps = false; } else { if (useTexStorage) { if (allocateMemory) { state.texStorage2D(3553, levels, glInternalFormat, image.width, image.height); } state.texSubImage2D(3553, 0, 0, 0, glFormat, glType, image); } else { state.texImage2D(3553, 0, glInternalFormat, glFormat, glType, image); } } } if (textureNeedsGenerateMipmaps(texture, supportsMips)) { generateMipmap(textureType); } sourceProperties.__version = source.version; if (texture.onUpdate) texture.onUpdate(texture); } textureProperties.__version = texture.version; } function uploadCubeTexture(textureProperties, texture, slot) { if (texture.image.length !== 6) return; const forceUpload = initTexture(textureProperties, texture); const source = texture.source; state.bindTexture(34067, textureProperties.__webglTexture, 33984 + slot); const sourceProperties = properties.get(source); if (source.version !== sourceProperties.__version || forceUpload === true) { state.activeTexture(33984 + slot); _gl.pixelStorei(37440, texture.flipY); _gl.pixelStorei(37441, texture.premultiplyAlpha); _gl.pixelStorei(3317, texture.unpackAlignment); _gl.pixelStorei(37443, 0); const isCompressed = texture.isCompressedTexture || texture.image[0].isCompressedTexture; const isDataTexture = texture.image[0] && texture.image[0].isDataTexture; const cubeImage = []; for (let i = 0; i < 6; i++) { if (!isCompressed && !isDataTexture) { cubeImage[i] = resizeImage(texture.image[i], false, true, maxCubemapSize); } else { cubeImage[i] = isDataTexture ? texture.image[i].image : texture.image[i]; } cubeImage[i] = verifyColorSpace(texture, cubeImage[i]); } const image = cubeImage[0], supportsMips = isPowerOfTwo$1(image) || isWebGL2, glFormat = utils.convert(texture.format, texture.encoding), glType = utils.convert(texture.type), glInternalFormat = getInternalFormat(texture.internalFormat, glFormat, glType, texture.encoding); const useTexStorage = isWebGL2 && texture.isVideoTexture !== true; const allocateMemory = sourceProperties.__version === void 0 || forceUpload === true; let levels = getMipLevels(texture, image, supportsMips); setTextureParameters(34067, texture, supportsMips); let mipmaps; if (isCompressed) { if (useTexStorage && allocateMemory) { state.texStorage2D(34067, levels, glInternalFormat, image.width, image.height); } for (let i = 0; i < 6; i++) { mipmaps = cubeImage[i].mipmaps; for (let j = 0; j < mipmaps.length; j++) { const mipmap = mipmaps[j]; if (texture.format !== RGBAFormat) { if (glFormat !== null) { if (useTexStorage) { state.compressedTexSubImage2D(34069 + i, j, 0, 0, mipmap.width, mipmap.height, glFormat, mipmap.data); } else { state.compressedTexImage2D(34069 + i, j, glInternalFormat, mipmap.width, mipmap.height, 0, mipmap.data); } } else { console.warn("THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .setTextureCube()"); } } else { if (useTexStorage) { state.texSubImage2D(34069 + i, j, 0, 0, mipmap.width, mipmap.height, glFormat, glType, mipmap.data); } else { state.texImage2D(34069 + i, j, glInternalFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data); } } } } } else { mipmaps = texture.mipmaps; if (useTexStorage && allocateMemory) { if (mipmaps.length > 0) levels++; state.texStorage2D(34067, levels, glInternalFormat, cubeImage[0].width, cubeImage[0].height); } for (let i = 0; i < 6; i++) { if (isDataTexture) { if (useTexStorage) { state.texSubImage2D(34069 + i, 0, 0, 0, cubeImage[i].width, cubeImage[i].height, glFormat, glType, cubeImage[i].data); } else { state.texImage2D(34069 + i, 0, glInternalFormat, cubeImage[i].width, cubeImage[i].height, 0, glFormat, glType, cubeImage[i].data); } for (let j = 0; j < mipmaps.length; j++) { const mipmap = mipmaps[j]; const mipmapImage = mipmap.image[i].image; if (useTexStorage) { state.texSubImage2D(34069 + i, j + 1, 0, 0, mipmapImage.width, mipmapImage.height, glFormat, glType, mipmapImage.data); } else { state.texImage2D(34069 + i, j + 1, glInternalFormat, mipmapImage.width, mipmapImage.height, 0, glFormat, glType, mipmapImage.data); } } } else { if (useTexStorage) { state.texSubImage2D(34069 + i, 0, 0, 0, glFormat, glType, cubeImage[i]); } else { state.texImage2D(34069 + i, 0, glInternalFormat, glFormat, glType, cubeImage[i]); } for (let j = 0; j < mipmaps.length; j++) { const mipmap = mipmaps[j]; if (useTexStorage) { state.texSubImage2D(34069 + i, j + 1, 0, 0, glFormat, glType, mipmap.image[i]); } else { state.texImage2D(34069 + i, j + 1, glInternalFormat, glFormat, glType, mipmap.image[i]); } } } } } if (textureNeedsGenerateMipmaps(texture, supportsMips)) { generateMipmap(34067); } sourceProperties.__version = source.version; if (texture.onUpdate) texture.onUpdate(texture); } textureProperties.__version = texture.version; } function setupFrameBufferTexture(framebuffer, renderTarget, texture, attachment, textureTarget) { const glFormat = utils.convert(texture.format, texture.encoding); const glType = utils.convert(texture.type); const glInternalFormat = getInternalFormat(texture.internalFormat, glFormat, glType, texture.encoding); const renderTargetProperties = properties.get(renderTarget); if (!renderTargetProperties.__hasExternalTextures) { if (textureTarget === 32879 || textureTarget === 35866) { state.texImage3D(textureTarget, 0, glInternalFormat, renderTarget.width, renderTarget.height, renderTarget.depth, 0, glFormat, glType, null); } else { state.texImage2D(textureTarget, 0, glInternalFormat, renderTarget.width, renderTarget.height, 0, glFormat, glType, null); } } state.bindFramebuffer(36160, framebuffer); if (useMultisampledRTT(renderTarget)) { multisampledRTTExt.framebufferTexture2DMultisampleEXT(36160, attachment, textureTarget, properties.get(texture).__webglTexture, 0, getRenderTargetSamples(renderTarget)); } else if (textureTarget === 3553 || textureTarget >= 34069 && textureTarget <= 34074) { _gl.framebufferTexture2D(36160, attachment, textureTarget, properties.get(texture).__webglTexture, 0); } state.bindFramebuffer(36160, null); } function setupRenderBufferStorage(renderbuffer, renderTarget, isMultisample) { _gl.bindRenderbuffer(36161, renderbuffer); if (renderTarget.depthBuffer && !renderTarget.stencilBuffer) { let glInternalFormat = 33189; if (isMultisample || useMultisampledRTT(renderTarget)) { const depthTexture = renderTarget.depthTexture; if (depthTexture && depthTexture.isDepthTexture) { if (depthTexture.type === FloatType) { glInternalFormat = 36012; } else if (depthTexture.type === UnsignedIntType) { glInternalFormat = 33190; } } const samples = getRenderTargetSamples(renderTarget); if (useMultisampledRTT(renderTarget)) { multisampledRTTExt.renderbufferStorageMultisampleEXT(36161, samples, glInternalFormat, renderTarget.width, renderTarget.height); } else { _gl.renderbufferStorageMultisample(36161, samples, glInternalFormat, renderTarget.width, renderTarget.height); } } else { _gl.renderbufferStorage(36161, glInternalFormat, renderTarget.width, renderTarget.height); } _gl.framebufferRenderbuffer(36160, 36096, 36161, renderbuffer); } else if (renderTarget.depthBuffer && renderTarget.stencilBuffer) { const samples = getRenderTargetSamples(renderTarget); if (isMultisample && useMultisampledRTT(renderTarget) === false) { _gl.renderbufferStorageMultisample(36161, samples, 35056, renderTarget.width, renderTarget.height); } else if (useMultisampledRTT(renderTarget)) { multisampledRTTExt.renderbufferStorageMultisampleEXT(36161, samples, 35056, renderTarget.width, renderTarget.height); } else { _gl.renderbufferStorage(36161, 34041, renderTarget.width, renderTarget.height); } _gl.framebufferRenderbuffer(36160, 33306, 36161, renderbuffer); } else { const textures = renderTarget.isWebGLMultipleRenderTargets === true ? renderTarget.texture : [renderTarget.texture]; for (let i = 0; i < textures.length; i++) { const texture = textures[i]; const glFormat = utils.convert(texture.format, texture.encoding); const glType = utils.convert(texture.type); const glInternalFormat = getInternalFormat(texture.internalFormat, glFormat, glType, texture.encoding); const samples = getRenderTargetSamples(renderTarget); if (isMultisample && useMultisampledRTT(renderTarget) === false) { _gl.renderbufferStorageMultisample(36161, samples, glInternalFormat, renderTarget.width, renderTarget.height); } else if (useMultisampledRTT(renderTarget)) { multisampledRTTExt.renderbufferStorageMultisampleEXT(36161, samples, glInternalFormat, renderTarget.width, renderTarget.height); } else { _gl.renderbufferStorage(36161, glInternalFormat, renderTarget.width, renderTarget.height); } } } _gl.bindRenderbuffer(36161, null); } function setupDepthTexture(framebuffer, renderTarget) { const isCube = renderTarget && renderTarget.isWebGLCubeRenderTarget; if (isCube) throw new Error("Depth Texture with cube render targets is not supported"); state.bindFramebuffer(36160, framebuffer); if (!(renderTarget.depthTexture && renderTarget.depthTexture.isDepthTexture)) { throw new Error("renderTarget.depthTexture must be an instance of THREE.DepthTexture"); } if (!properties.get(renderTarget.depthTexture).__webglTexture || renderTarget.depthTexture.image.width !== renderTarget.width || renderTarget.depthTexture.image.height !== renderTarget.height) { renderTarget.depthTexture.image.width = renderTarget.width; renderTarget.depthTexture.image.height = renderTarget.height; renderTarget.depthTexture.needsUpdate = true; } setTexture2D(renderTarget.depthTexture, 0); const webglDepthTexture = properties.get(renderTarget.depthTexture).__webglTexture; const samples = getRenderTargetSamples(renderTarget); if (renderTarget.depthTexture.format === DepthFormat) { if (useMultisampledRTT(renderTarget)) { multisampledRTTExt.framebufferTexture2DMultisampleEXT(36160, 36096, 3553, webglDepthTexture, 0, samples); } else { _gl.framebufferTexture2D(36160, 36096, 3553, webglDepthTexture, 0); } } else if (renderTarget.depthTexture.format === DepthStencilFormat) { if (useMultisampledRTT(renderTarget)) { multisampledRTTExt.framebufferTexture2DMultisampleEXT(36160, 33306, 3553, webglDepthTexture, 0, samples); } else { _gl.framebufferTexture2D(36160, 33306, 3553, webglDepthTexture, 0); } } else { throw new Error("Unknown depthTexture format"); } } function setupDepthRenderbuffer(renderTarget) { const renderTargetProperties = properties.get(renderTarget); const isCube = renderTarget.isWebGLCubeRenderTarget === true; if (renderTarget.depthTexture && !renderTargetProperties.__autoAllocateDepthBuffer) { if (isCube) throw new Error("target.depthTexture not supported in Cube render targets"); setupDepthTexture(renderTargetProperties.__webglFramebuffer, renderTarget); } else { if (isCube) { renderTargetProperties.__webglDepthbuffer = []; for (let i = 0; i < 6; i++) { state.bindFramebuffer(36160, renderTargetProperties.__webglFramebuffer[i]); renderTargetProperties.__webglDepthbuffer[i] = _gl.createRenderbuffer(); setupRenderBufferStorage(renderTargetProperties.__webglDepthbuffer[i], renderTarget, false); } } else { state.bindFramebuffer(36160, renderTargetProperties.__webglFramebuffer); renderTargetProperties.__webglDepthbuffer = _gl.createRenderbuffer(); setupRenderBufferStorage(renderTargetProperties.__webglDepthbuffer, renderTarget, false); } } state.bindFramebuffer(36160, null); } function rebindTextures(renderTarget, colorTexture, depthTexture) { const renderTargetProperties = properties.get(renderTarget); if (colorTexture !== void 0) { setupFrameBufferTexture(renderTargetProperties.__webglFramebuffer, renderTarget, renderTarget.texture, 36064, 3553); } if (depthTexture !== void 0) { setupDepthRenderbuffer(renderTarget); } } function setupRenderTarget(renderTarget) { const texture = renderTarget.texture; const renderTargetProperties = properties.get(renderTarget); const textureProperties = properties.get(texture); renderTarget.addEventListener("dispose", onRenderTargetDispose); if (renderTarget.isWebGLMultipleRenderTargets !== true) { if (textureProperties.__webglTexture === void 0) { textureProperties.__webglTexture = _gl.createTexture(); } textureProperties.__version = texture.version; info.memory.textures++; } const isCube = renderTarget.isWebGLCubeRenderTarget === true; const isMultipleRenderTargets = renderTarget.isWebGLMultipleRenderTargets === true; const supportsMips = isPowerOfTwo$1(renderTarget) || isWebGL2; if (isCube) { renderTargetProperties.__webglFramebuffer = []; for (let i = 0; i < 6; i++) { renderTargetProperties.__webglFramebuffer[i] = _gl.createFramebuffer(); } } else { renderTargetProperties.__webglFramebuffer = _gl.createFramebuffer(); if (isMultipleRenderTargets) { if (capabilities.drawBuffers) { const textures = renderTarget.texture; for (let i = 0, il = textures.length; i < il; i++) { const attachmentProperties = properties.get(textures[i]); if (attachmentProperties.__webglTexture === void 0) { attachmentProperties.__webglTexture = _gl.createTexture(); info.memory.textures++; } } } else { console.warn("THREE.WebGLRenderer: WebGLMultipleRenderTargets can only be used with WebGL2 or WEBGL_draw_buffers extension."); } } if (isWebGL2 && renderTarget.samples > 0 && useMultisampledRTT(renderTarget) === false) { const textures = isMultipleRenderTargets ? texture : [texture]; renderTargetProperties.__webglMultisampledFramebuffer = _gl.createFramebuffer(); renderTargetProperties.__webglColorRenderbuffer = []; state.bindFramebuffer(36160, renderTargetProperties.__webglMultisampledFramebuffer); for (let i = 0; i < textures.length; i++) { const texture2 = textures[i]; renderTargetProperties.__webglColorRenderbuffer[i] = _gl.createRenderbuffer(); _gl.bindRenderbuffer(36161, renderTargetProperties.__webglColorRenderbuffer[i]); const glFormat = utils.convert(texture2.format, texture2.encoding); const glType = utils.convert(texture2.type); const glInternalFormat = getInternalFormat(texture2.internalFormat, glFormat, glType, texture2.encoding, renderTarget.isXRRenderTarget === true); const samples = getRenderTargetSamples(renderTarget); _gl.renderbufferStorageMultisample(36161, samples, glInternalFormat, renderTarget.width, renderTarget.height); _gl.framebufferRenderbuffer(36160, 36064 + i, 36161, renderTargetProperties.__webglColorRenderbuffer[i]); } _gl.bindRenderbuffer(36161, null); if (renderTarget.depthBuffer) { renderTargetProperties.__webglDepthRenderbuffer = _gl.createRenderbuffer(); setupRenderBufferStorage(renderTargetProperties.__webglDepthRenderbuffer, renderTarget, true); } state.bindFramebuffer(36160, null); } } if (isCube) { state.bindTexture(34067, textureProperties.__webglTexture); setTextureParameters(34067, texture, supportsMips); for (let i = 0; i < 6; i++) { setupFrameBufferTexture(renderTargetProperties.__webglFramebuffer[i], renderTarget, texture, 36064, 34069 + i); } if (textureNeedsGenerateMipmaps(texture, supportsMips)) { generateMipmap(34067); } state.unbindTexture(); } else if (isMultipleRenderTargets) { const textures = renderTarget.texture; for (let i = 0, il = textures.length; i < il; i++) { const attachment = textures[i]; const attachmentProperties = properties.get(attachment); state.bindTexture(3553, attachmentProperties.__webglTexture); setTextureParameters(3553, attachment, supportsMips); setupFrameBufferTexture(renderTargetProperties.__webglFramebuffer, renderTarget, attachment, 36064 + i, 3553); if (textureNeedsGenerateMipmaps(attachment, supportsMips)) { generateMipmap(3553); } } state.unbindTexture(); } else { let glTextureType = 3553; if (renderTarget.isWebGL3DRenderTarget || renderTarget.isWebGLArrayRenderTarget) { if (isWebGL2) { glTextureType = renderTarget.isWebGL3DRenderTarget ? 32879 : 35866; } else { console.error("THREE.WebGLTextures: THREE.Data3DTexture and THREE.DataArrayTexture only supported with WebGL2."); } } state.bindTexture(glTextureType, textureProperties.__webglTexture); setTextureParameters(glTextureType, texture, supportsMips); setupFrameBufferTexture(renderTargetProperties.__webglFramebuffer, renderTarget, texture, 36064, glTextureType); if (textureNeedsGenerateMipmaps(texture, supportsMips)) { generateMipmap(glTextureType); } state.unbindTexture(); } if (renderTarget.depthBuffer) { setupDepthRenderbuffer(renderTarget); } } function updateRenderTargetMipmap(renderTarget) { const supportsMips = isPowerOfTwo$1(renderTarget) || isWebGL2; const textures = renderTarget.isWebGLMultipleRenderTargets === true ? renderTarget.texture : [renderTarget.texture]; for (let i = 0, il = textures.length; i < il; i++) { const texture = textures[i]; if (textureNeedsGenerateMipmaps(texture, supportsMips)) { const target2 = renderTarget.isWebGLCubeRenderTarget ? 34067 : 3553; const webglTexture = properties.get(texture).__webglTexture; state.bindTexture(target2, webglTexture); generateMipmap(target2); state.unbindTexture(); } } } function updateMultisampleRenderTarget(renderTarget) { if (isWebGL2 && renderTarget.samples > 0 && useMultisampledRTT(renderTarget) === false) { const textures = renderTarget.isWebGLMultipleRenderTargets ? renderTarget.texture : [renderTarget.texture]; const width = renderTarget.width; const height = renderTarget.height; let mask = 16384; const invalidationArray = []; const depthStyle = renderTarget.stencilBuffer ? 33306 : 36096; const renderTargetProperties = properties.get(renderTarget); const isMultipleRenderTargets = renderTarget.isWebGLMultipleRenderTargets === true; if (isMultipleRenderTargets) { for (let i = 0; i < textures.length; i++) { state.bindFramebuffer(36160, renderTargetProperties.__webglMultisampledFramebuffer); _gl.framebufferRenderbuffer(36160, 36064 + i, 36161, null); state.bindFramebuffer(36160, renderTargetProperties.__webglFramebuffer); _gl.framebufferTexture2D(36009, 36064 + i, 3553, null, 0); } } state.bindFramebuffer(36008, renderTargetProperties.__webglMultisampledFramebuffer); state.bindFramebuffer(36009, renderTargetProperties.__webglFramebuffer); for (let i = 0; i < textures.length; i++) { invalidationArray.push(36064 + i); if (renderTarget.depthBuffer) { invalidationArray.push(depthStyle); } const ignoreDepthValues = renderTargetProperties.__ignoreDepthValues !== void 0 ? renderTargetProperties.__ignoreDepthValues : false; if (ignoreDepthValues === false) { if (renderTarget.depthBuffer) mask |= 256; if (renderTarget.stencilBuffer) mask |= 1024; } if (isMultipleRenderTargets) { _gl.framebufferRenderbuffer(36008, 36064, 36161, renderTargetProperties.__webglColorRenderbuffer[i]); } if (ignoreDepthValues === true) { _gl.invalidateFramebuffer(36008, [depthStyle]); _gl.invalidateFramebuffer(36009, [depthStyle]); } if (isMultipleRenderTargets) { const webglTexture = properties.get(textures[i]).__webglTexture; _gl.framebufferTexture2D(36009, 36064, 3553, webglTexture, 0); } _gl.blitFramebuffer(0, 0, width, height, 0, 0, width, height, mask, 9728); if (supportsInvalidateFramebuffer) { _gl.invalidateFramebuffer(36008, invalidationArray); } } state.bindFramebuffer(36008, null); state.bindFramebuffer(36009, null); if (isMultipleRenderTargets) { for (let i = 0; i < textures.length; i++) { state.bindFramebuffer(36160, renderTargetProperties.__webglMultisampledFramebuffer); _gl.framebufferRenderbuffer(36160, 36064 + i, 36161, renderTargetProperties.__webglColorRenderbuffer[i]); const webglTexture = properties.get(textures[i]).__webglTexture; state.bindFramebuffer(36160, renderTargetProperties.__webglFramebuffer); _gl.framebufferTexture2D(36009, 36064 + i, 3553, webglTexture, 0); } } state.bindFramebuffer(36009, renderTargetProperties.__webglMultisampledFramebuffer); } } function getRenderTargetSamples(renderTarget) { return Math.min(maxSamples, renderTarget.samples); } function useMultisampledRTT(renderTarget) { const renderTargetProperties = properties.get(renderTarget); return isWebGL2 && renderTarget.samples > 0 && extensions.has("WEBGL_multisampled_render_to_texture") === true && renderTargetProperties.__useRenderToTexture !== false; } function updateVideoTexture(texture) { const frame = info.render.frame; if (_videoTextures.get(texture) !== frame) { _videoTextures.set(texture, frame); texture.update(); } } function verifyColorSpace(texture, image) { const encoding = texture.encoding; const format = texture.format; const type = texture.type; if (texture.isCompressedTexture === true || texture.isVideoTexture === true || texture.format === _SRGBAFormat) return image; if (encoding !== LinearEncoding) { if (encoding === sRGBEncoding) { if (isWebGL2 === false) { if (extensions.has("EXT_sRGB") === true && format === RGBAFormat) { texture.format = _SRGBAFormat; texture.minFilter = LinearFilter; texture.generateMipmaps = false; } else { image = ImageUtils.sRGBToLinear(image); } } else { if (format !== RGBAFormat || type !== UnsignedByteType) { console.warn("THREE.WebGLTextures: sRGB encoded textures have to use RGBAFormat and UnsignedByteType."); } } } else { console.error("THREE.WebGLTextures: Unsupported texture encoding:", encoding); } } return image; } this.allocateTextureUnit = allocateTextureUnit; this.resetTextureUnits = resetTextureUnits; this.setTexture2D = setTexture2D; this.setTexture2DArray = setTexture2DArray; this.setTexture3D = setTexture3D; this.setTextureCube = setTextureCube; this.rebindTextures = rebindTextures; this.setupRenderTarget = setupRenderTarget; this.updateRenderTargetMipmap = updateRenderTargetMipmap; this.updateMultisampleRenderTarget = updateMultisampleRenderTarget; this.setupDepthRenderbuffer = setupDepthRenderbuffer; this.setupFrameBufferTexture = setupFrameBufferTexture; this.useMultisampledRTT = useMultisampledRTT; } function WebGLUtils(gl, extensions, capabilities) { const isWebGL2 = capabilities.isWebGL2; function convert(p2, encoding = null) { let extension; if (p2 === UnsignedByteType) return 5121; if (p2 === UnsignedShort4444Type) return 32819; if (p2 === UnsignedShort5551Type) return 32820; if (p2 === ByteType) return 5120; if (p2 === ShortType) return 5122; if (p2 === UnsignedShortType) return 5123; if (p2 === IntType) return 5124; if (p2 === UnsignedIntType) return 5125; if (p2 === FloatType) return 5126; if (p2 === HalfFloatType) { if (isWebGL2) return 5131; extension = extensions.get("OES_texture_half_float"); if (extension !== null) { return extension.HALF_FLOAT_OES; } else { return null; } } if (p2 === AlphaFormat) return 6406; if (p2 === RGBAFormat) return 6408; if (p2 === LuminanceFormat) return 6409; if (p2 === LuminanceAlphaFormat) return 6410; if (p2 === DepthFormat) return 6402; if (p2 === DepthStencilFormat) return 34041; if (p2 === RedFormat) return 6403; if (p2 === RGBFormat) { console.warn("THREE.WebGLRenderer: THREE.RGBFormat has been removed. Use THREE.RGBAFormat instead. https://github.com/mrdoob/three.js/pull/23228"); return 6408; } if (p2 === _SRGBAFormat) { extension = extensions.get("EXT_sRGB"); if (extension !== null) { return extension.SRGB_ALPHA_EXT; } else { return null; } } if (p2 === RedIntegerFormat) return 36244; if (p2 === RGFormat) return 33319; if (p2 === RGIntegerFormat) return 33320; if (p2 === RGBAIntegerFormat) return 36249; if (p2 === RGB_S3TC_DXT1_Format || p2 === RGBA_S3TC_DXT1_Format || p2 === RGBA_S3TC_DXT3_Format || p2 === RGBA_S3TC_DXT5_Format) { if (encoding === sRGBEncoding) { extension = extensions.get("WEBGL_compressed_texture_s3tc_srgb"); if (extension !== null) { if (p2 === RGB_S3TC_DXT1_Format) return extension.COMPRESSED_SRGB_S3TC_DXT1_EXT; if (p2 === RGBA_S3TC_DXT1_Format) return extension.COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT; if (p2 === RGBA_S3TC_DXT3_Format) return extension.COMPRESSED_SRGB_ALPHA_S3TC_DXT3_EXT; if (p2 === RGBA_S3TC_DXT5_Format) return extension.COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT; } else { return null; } } else { extension = extensions.get("WEBGL_compressed_texture_s3tc"); if (extension !== null) { if (p2 === RGB_S3TC_DXT1_Format) return extension.COMPRESSED_RGB_S3TC_DXT1_EXT; if (p2 === RGBA_S3TC_DXT1_Format) return extension.COMPRESSED_RGBA_S3TC_DXT1_EXT; if (p2 === RGBA_S3TC_DXT3_Format) return extension.COMPRESSED_RGBA_S3TC_DXT3_EXT; if (p2 === RGBA_S3TC_DXT5_Format) return extension.COMPRESSED_RGBA_S3TC_DXT5_EXT; } else { return null; } } } if (p2 === RGB_PVRTC_4BPPV1_Format || p2 === RGB_PVRTC_2BPPV1_Format || p2 === RGBA_PVRTC_4BPPV1_Format || p2 === RGBA_PVRTC_2BPPV1_Format) { extension = extensions.get("WEBGL_compressed_texture_pvrtc"); if (extension !== null) { if (p2 === RGB_PVRTC_4BPPV1_Format) return extension.COMPRESSED_RGB_PVRTC_4BPPV1_IMG; if (p2 === RGB_PVRTC_2BPPV1_Format) return extension.COMPRESSED_RGB_PVRTC_2BPPV1_IMG; if (p2 === RGBA_PVRTC_4BPPV1_Format) return extension.COMPRESSED_RGBA_PVRTC_4BPPV1_IMG; if (p2 === RGBA_PVRTC_2BPPV1_Format) return extension.COMPRESSED_RGBA_PVRTC_2BPPV1_IMG; } else { return null; } } if (p2 === RGB_ETC1_Format) { extension = extensions.get("WEBGL_compressed_texture_etc1"); if (extension !== null) { return extension.COMPRESSED_RGB_ETC1_WEBGL; } else { return null; } } if (p2 === RGB_ETC2_Format || p2 === RGBA_ETC2_EAC_Format) { extension = extensions.get("WEBGL_compressed_texture_etc"); if (extension !== null) { if (p2 === RGB_ETC2_Format) return encoding === sRGBEncoding ? extension.COMPRESSED_SRGB8_ETC2 : extension.COMPRESSED_RGB8_ETC2; if (p2 === RGBA_ETC2_EAC_Format) return encoding === sRGBEncoding ? extension.COMPRESSED_SRGB8_ALPHA8_ETC2_EAC : extension.COMPRESSED_RGBA8_ETC2_EAC; } else { return null; } } if (p2 === RGBA_ASTC_4x4_Format || p2 === RGBA_ASTC_5x4_Format || p2 === RGBA_ASTC_5x5_Format || p2 === RGBA_ASTC_6x5_Format || p2 === RGBA_ASTC_6x6_Format || p2 === RGBA_ASTC_8x5_Format || p2 === RGBA_ASTC_8x6_Format || p2 === RGBA_ASTC_8x8_Format || p2 === RGBA_ASTC_10x5_Format || p2 === RGBA_ASTC_10x6_Format || p2 === RGBA_ASTC_10x8_Format || p2 === RGBA_ASTC_10x10_Format || p2 === RGBA_ASTC_12x10_Format || p2 === RGBA_ASTC_12x12_Format) { extension = extensions.get("WEBGL_compressed_texture_astc"); if (extension !== null) { if (p2 === RGBA_ASTC_4x4_Format) return encoding === sRGBEncoding ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR : extension.COMPRESSED_RGBA_ASTC_4x4_KHR; if (p2 === RGBA_ASTC_5x4_Format) return encoding === sRGBEncoding ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_5x4_KHR : extension.COMPRESSED_RGBA_ASTC_5x4_KHR; if (p2 === RGBA_ASTC_5x5_Format) return encoding === sRGBEncoding ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_5x5_KHR : extension.COMPRESSED_RGBA_ASTC_5x5_KHR; if (p2 === RGBA_ASTC_6x5_Format) return encoding === sRGBEncoding ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_6x5_KHR : extension.COMPRESSED_RGBA_ASTC_6x5_KHR; if (p2 === RGBA_ASTC_6x6_Format) return encoding === sRGBEncoding ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_6x6_KHR : extension.COMPRESSED_RGBA_ASTC_6x6_KHR; if (p2 === RGBA_ASTC_8x5_Format) return encoding === sRGBEncoding ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_8x5_KHR : extension.COMPRESSED_RGBA_ASTC_8x5_KHR; if (p2 === RGBA_ASTC_8x6_Format) return encoding === sRGBEncoding ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_8x6_KHR : extension.COMPRESSED_RGBA_ASTC_8x6_KHR; if (p2 === RGBA_ASTC_8x8_Format) return encoding === sRGBEncoding ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_8x8_KHR : extension.COMPRESSED_RGBA_ASTC_8x8_KHR; if (p2 === RGBA_ASTC_10x5_Format) return encoding === sRGBEncoding ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_10x5_KHR : extension.COMPRESSED_RGBA_ASTC_10x5_KHR; if (p2 === RGBA_ASTC_10x6_Format) return encoding === sRGBEncoding ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_10x6_KHR : extension.COMPRESSED_RGBA_ASTC_10x6_KHR; if (p2 === RGBA_ASTC_10x8_Format) return encoding === sRGBEncoding ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_10x8_KHR : extension.COMPRESSED_RGBA_ASTC_10x8_KHR; if (p2 === RGBA_ASTC_10x10_Format) return encoding === sRGBEncoding ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_10x10_KHR : extension.COMPRESSED_RGBA_ASTC_10x10_KHR; if (p2 === RGBA_ASTC_12x10_Format) return encoding === sRGBEncoding ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_12x10_KHR : extension.COMPRESSED_RGBA_ASTC_12x10_KHR; if (p2 === RGBA_ASTC_12x12_Format) return encoding === sRGBEncoding ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_12x12_KHR : extension.COMPRESSED_RGBA_ASTC_12x12_KHR; } else { return null; } } if (p2 === RGBA_BPTC_Format) { extension = extensions.get("EXT_texture_compression_bptc"); if (extension !== null) { if (p2 === RGBA_BPTC_Format) return encoding === sRGBEncoding ? extension.COMPRESSED_SRGB_ALPHA_BPTC_UNORM_EXT : extension.COMPRESSED_RGBA_BPTC_UNORM_EXT; } else { return null; } } if (p2 === UnsignedInt248Type) { if (isWebGL2) return 34042; extension = extensions.get("WEBGL_depth_texture"); if (extension !== null) { return extension.UNSIGNED_INT_24_8_WEBGL; } else { return null; } } return gl[p2] !== void 0 ? gl[p2] : null; } return { convert }; } var ArrayCamera = class extends PerspectiveCamera { constructor(array = []) { super(); this.isArrayCamera = true; this.cameras = array; } }; var Group = class extends Object3D { constructor() { super(); this.isGroup = true; this.type = "Group"; } }; var _moveEvent = { type: "move" }; var WebXRController = class { constructor() { this._targetRay = null; this._grip = null; this._hand = null; } getHandSpace() { if (this._hand === null) { this._hand = new Group(); this._hand.matrixAutoUpdate = false; this._hand.visible = false; this._hand.joints = {}; this._hand.inputState = { pinching: false }; } return this._hand; } getTargetRaySpace() { if (this._targetRay === null) { this._targetRay = new Group(); this._targetRay.matrixAutoUpdate = false; this._targetRay.visible = false; this._targetRay.hasLinearVelocity = false; this._targetRay.linearVelocity = new Vector3(); this._targetRay.hasAngularVelocity = false; this._targetRay.angularVelocity = new Vector3(); } return this._targetRay; } getGripSpace() { if (this._grip === null) { this._grip = new Group(); this._grip.matrixAutoUpdate = false; this._grip.visible = false; this._grip.hasLinearVelocity = false; this._grip.linearVelocity = new Vector3(); this._grip.hasAngularVelocity = false; this._grip.angularVelocity = new Vector3(); } return this._grip; } dispatchEvent(event) { if (this._targetRay !== null) { this._targetRay.dispatchEvent(event); } if (this._grip !== null) { this._grip.dispatchEvent(event); } if (this._hand !== null) { this._hand.dispatchEvent(event); } return this; } disconnect(inputSource) { this.dispatchEvent({ type: "disconnected", data: inputSource }); if (this._targetRay !== null) { this._targetRay.visible = false; } if (this._grip !== null) { this._grip.visible = false; } if (this._hand !== null) { this._hand.visible = false; } return this; } update(inputSource, frame, referenceSpace) { let inputPose = null; let gripPose = null; let handPose = null; const targetRay = this._targetRay; const grip = this._grip; const hand = this._hand; if (inputSource && frame.session.visibilityState !== "visible-blurred") { if (hand && inputSource.hand) { handPose = true; for (const inputjoint of inputSource.hand.values()) { const jointPose = frame.getJointPose(inputjoint, referenceSpace); if (hand.joints[inputjoint.jointName] === void 0) { const joint2 = new Group(); joint2.matrixAutoUpdate = false; joint2.visible = false; hand.joints[inputjoint.jointName] = joint2; hand.add(joint2); } const joint = hand.joints[inputjoint.jointName]; if (jointPose !== null) { joint.matrix.fromArray(jointPose.transform.matrix); joint.matrix.decompose(joint.position, joint.rotation, joint.scale); joint.jointRadius = jointPose.radius; } joint.visible = jointPose !== null; } const indexTip = hand.joints["index-finger-tip"]; const thumbTip = hand.joints["thumb-tip"]; const distance = indexTip.position.distanceTo(thumbTip.position); const distanceToPinch = 0.02; const threshold = 5e-3; if (hand.inputState.pinching && distance > distanceToPinch + threshold) { hand.inputState.pinching = false; this.dispatchEvent({ type: "pinchend", handedness: inputSource.handedness, target: this }); } else if (!hand.inputState.pinching && distance <= distanceToPinch - threshold) { hand.inputState.pinching = true; this.dispatchEvent({ type: "pinchstart", handedness: inputSource.handedness, target: this }); } } else { if (grip !== null && inputSource.gripSpace) { gripPose = frame.getPose(inputSource.gripSpace, referenceSpace); if (gripPose !== null) { grip.matrix.fromArray(gripPose.transform.matrix); grip.matrix.decompose(grip.position, grip.rotation, grip.scale); if (gripPose.linearVelocity) { grip.hasLinearVelocity = true; grip.linearVelocity.copy(gripPose.linearVelocity); } else { grip.hasLinearVelocity = false; } if (gripPose.angularVelocity) { grip.hasAngularVelocity = true; grip.angularVelocity.copy(gripPose.angularVelocity); } else { grip.hasAngularVelocity = false; } } } } if (targetRay !== null) { inputPose = frame.getPose(inputSource.targetRaySpace, referenceSpace); if (inputPose === null && gripPose !== null) { inputPose = gripPose; } if (inputPose !== null) { targetRay.matrix.fromArray(inputPose.transform.matrix); targetRay.matrix.decompose(targetRay.position, targetRay.rotation, targetRay.scale); if (inputPose.linearVelocity) { targetRay.hasLinearVelocity = true; targetRay.linearVelocity.copy(inputPose.linearVelocity); } else { targetRay.hasLinearVelocity = false; } if (inputPose.angularVelocity) { targetRay.hasAngularVelocity = true; targetRay.angularVelocity.copy(inputPose.angularVelocity); } else { targetRay.hasAngularVelocity = false; } this.dispatchEvent(_moveEvent); } } } if (targetRay !== null) { targetRay.visible = inputPose !== null; } if (grip !== null) { grip.visible = gripPose !== null; } if (hand !== null) { hand.visible = handPose !== null; } return this; } }; var DepthTexture = class extends Texture { constructor(width, height, type, mapping, wrapS, wrapT, magFilter, minFilter, anisotropy, format) { format = format !== void 0 ? format : DepthFormat; if (format !== DepthFormat && format !== DepthStencilFormat) { throw new Error("DepthTexture format must be either THREE.DepthFormat or THREE.DepthStencilFormat"); } if (type === void 0 && format === DepthFormat) type = UnsignedIntType; if (type === void 0 && format === DepthStencilFormat) type = UnsignedInt248Type; super(null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy); this.isDepthTexture = true; this.image = { width, height }; this.magFilter = magFilter !== void 0 ? magFilter : NearestFilter; this.minFilter = minFilter !== void 0 ? minFilter : NearestFilter; this.flipY = false; this.generateMipmaps = false; } }; var WebXRManager = class extends EventDispatcher { constructor(renderer, gl) { super(); const scope = this; let session = null; let framebufferScaleFactor = 1; let referenceSpace = null; let referenceSpaceType = "local-floor"; let customReferenceSpace = null; let pose = null; let glBinding = null; let glProjLayer = null; let glBaseLayer = null; let xrFrame = null; const attributes = gl.getContextAttributes(); let initialRenderTarget = null; let newRenderTarget = null; const controllers = []; const controllerInputSources = []; const cameraL = new PerspectiveCamera(); cameraL.layers.enable(1); cameraL.viewport = new Vector4(); const cameraR = new PerspectiveCamera(); cameraR.layers.enable(2); cameraR.viewport = new Vector4(); const cameras = [cameraL, cameraR]; const cameraVR = new ArrayCamera(); cameraVR.layers.enable(1); cameraVR.layers.enable(2); let _currentDepthNear = null; let _currentDepthFar = null; this.cameraAutoUpdate = true; this.enabled = false; this.isPresenting = false; this.getController = function(index) { let controller = controllers[index]; if (controller === void 0) { controller = new WebXRController(); controllers[index] = controller; } return controller.getTargetRaySpace(); }; this.getControllerGrip = function(index) { let controller = controllers[index]; if (controller === void 0) { controller = new WebXRController(); controllers[index] = controller; } return controller.getGripSpace(); }; this.getHand = function(index) { let controller = controllers[index]; if (controller === void 0) { controller = new WebXRController(); controllers[index] = controller; } return controller.getHandSpace(); }; function onSessionEvent(event) { const controllerIndex = controllerInputSources.indexOf(event.inputSource); if (controllerIndex === -1) { return; } const controller = controllers[controllerIndex]; if (controller !== void 0) { controller.dispatchEvent({ type: event.type, data: event.inputSource }); } } function onSessionEnd() { session.removeEventListener("select", onSessionEvent); session.removeEventListener("selectstart", onSessionEvent); session.removeEventListener("selectend", onSessionEvent); session.removeEventListener("squeeze", onSessionEvent); session.removeEventListener("squeezestart", onSessionEvent); session.removeEventListener("squeezeend", onSessionEvent); session.removeEventListener("end", onSessionEnd); session.removeEventListener("inputsourceschange", onInputSourcesChange); for (let i = 0; i < controllers.length; i++) { const inputSource = controllerInputSources[i]; if (inputSource === null) continue; controllerInputSources[i] = null; controllers[i].disconnect(inputSource); } _currentDepthNear = null; _currentDepthFar = null; renderer.setRenderTarget(initialRenderTarget); glBaseLayer = null; glProjLayer = null; glBinding = null; session = null; newRenderTarget = null; animation.stop(); scope.isPresenting = false; scope.dispatchEvent({ type: "sessionend" }); } this.setFramebufferScaleFactor = function(value) { framebufferScaleFactor = value; if (scope.isPresenting === true) { console.warn("THREE.WebXRManager: Cannot change framebuffer scale while presenting."); } }; this.setReferenceSpaceType = function(value) { referenceSpaceType = value; if (scope.isPresenting === true) { console.warn("THREE.WebXRManager: Cannot change reference space type while presenting."); } }; this.getReferenceSpace = function() { return customReferenceSpace || referenceSpace; }; this.setReferenceSpace = function(space) { customReferenceSpace = space; }; this.getBaseLayer = function() { return glProjLayer !== null ? glProjLayer : glBaseLayer; }; this.getBinding = function() { return glBinding; }; this.getFrame = function() { return xrFrame; }; this.getSession = function() { return session; }; this.setSession = async function(value) { session = value; if (session !== null) { initialRenderTarget = renderer.getRenderTarget(); session.addEventListener("select", onSessionEvent); session.addEventListener("selectstart", onSessionEvent); session.addEventListener("selectend", onSessionEvent); session.addEventListener("squeeze", onSessionEvent); session.addEventListener("squeezestart", onSessionEvent); session.addEventListener("squeezeend", onSessionEvent); session.addEventListener("end", onSessionEnd); session.addEventListener("inputsourceschange", onInputSourcesChange); if (attributes.xrCompatible !== true) { await gl.makeXRCompatible(); } if (session.renderState.layers === void 0 || renderer.capabilities.isWebGL2 === false) { const layerInit = { antialias: session.renderState.layers === void 0 ? attributes.antialias : true, alpha: attributes.alpha, depth: attributes.depth, stencil: attributes.stencil, framebufferScaleFactor }; glBaseLayer = new XRWebGLLayer(session, gl, layerInit); session.updateRenderState({ baseLayer: glBaseLayer }); newRenderTarget = new WebGLRenderTarget( glBaseLayer.framebufferWidth, glBaseLayer.framebufferHeight, { format: RGBAFormat, type: UnsignedByteType, encoding: renderer.outputEncoding, stencilBuffer: attributes.stencil } ); } else { let depthFormat = null; let depthType = null; let glDepthFormat = null; if (attributes.depth) { glDepthFormat = attributes.stencil ? 35056 : 33190; depthFormat = attributes.stencil ? DepthStencilFormat : DepthFormat; depthType = attributes.stencil ? UnsignedInt248Type : UnsignedIntType; } const projectionlayerInit = { colorFormat: 32856, depthFormat: glDepthFormat, scaleFactor: framebufferScaleFactor }; glBinding = new XRWebGLBinding(session, gl); glProjLayer = glBinding.createProjectionLayer(projectionlayerInit); session.updateRenderState({ layers: [glProjLayer] }); newRenderTarget = new WebGLRenderTarget( glProjLayer.textureWidth, glProjLayer.textureHeight, { format: RGBAFormat, type: UnsignedByteType, depthTexture: new DepthTexture(glProjLayer.textureWidth, glProjLayer.textureHeight, depthType, void 0, void 0, void 0, void 0, void 0, void 0, depthFormat), stencilBuffer: attributes.stencil, encoding: renderer.outputEncoding, samples: attributes.antialias ? 4 : 0 } ); const renderTargetProperties = renderer.properties.get(newRenderTarget); renderTargetProperties.__ignoreDepthValues = glProjLayer.ignoreDepthValues; } newRenderTarget.isXRRenderTarget = true; this.setFoveation(1); customReferenceSpace = null; referenceSpace = await session.requestReferenceSpace(referenceSpaceType); animation.setContext(session); animation.start(); scope.isPresenting = true; scope.dispatchEvent({ type: "sessionstart" }); } }; function onInputSourcesChange(event) { for (let i = 0; i < event.removed.length; i++) { const inputSource = event.removed[i]; const index = controllerInputSources.indexOf(inputSource); if (index >= 0) { controllerInputSources[index] = null; controllers[index].dispatchEvent({ type: "disconnected", data: inputSource }); } } for (let i = 0; i < event.added.length; i++) { const inputSource = event.added[i]; let controllerIndex = controllerInputSources.indexOf(inputSource); if (controllerIndex === -1) { for (let i2 = 0; i2 < controllers.length; i2++) { if (i2 >= controllerInputSources.length) { controllerInputSources.push(inputSource); controllerIndex = i2; break; } else if (controllerInputSources[i2] === null) { controllerInputSources[i2] = inputSource; controllerIndex = i2; break; } } if (controllerIndex === -1) break; } const controller = controllers[controllerIndex]; if (controller) { controller.dispatchEvent({ type: "connected", data: inputSource }); } } } const cameraLPos = new Vector3(); const cameraRPos = new Vector3(); function setProjectionFromUnion(camera2, cameraL2, cameraR2) { cameraLPos.setFromMatrixPosition(cameraL2.matrixWorld); cameraRPos.setFromMatrixPosition(cameraR2.matrixWorld); const ipd = cameraLPos.distanceTo(cameraRPos); const projL = cameraL2.projectionMatrix.elements; const projR = cameraR2.projectionMatrix.elements; const near = projL[14] / (projL[10] - 1); const far = projL[14] / (projL[10] + 1); const topFov = (projL[9] + 1) / projL[5]; const bottomFov = (projL[9] - 1) / projL[5]; const leftFov = (projL[8] - 1) / projL[0]; const rightFov = (projR[8] + 1) / projR[0]; const left = near * leftFov; const right = near * rightFov; const zOffset = ipd / (-leftFov + rightFov); const xOffset = zOffset * -leftFov; cameraL2.matrixWorld.decompose(camera2.position, camera2.quaternion, camera2.scale); camera2.translateX(xOffset); camera2.translateZ(zOffset); camera2.matrixWorld.compose(camera2.position, camera2.quaternion, camera2.scale); camera2.matrixWorldInverse.copy(camera2.matrixWorld).invert(); const near2 = near + zOffset; const far2 = far + zOffset; const left2 = left - xOffset; const right2 = right + (ipd - xOffset); const top2 = topFov * far / far2 * near2; const bottom2 = bottomFov * far / far2 * near2; camera2.projectionMatrix.makePerspective(left2, right2, top2, bottom2, near2, far2); } function updateCamera(camera2, parent) { if (parent === null) { camera2.matrixWorld.copy(camera2.matrix); } else { camera2.matrixWorld.multiplyMatrices(parent.matrixWorld, camera2.matrix); } camera2.matrixWorldInverse.copy(camera2.matrixWorld).invert(); } this.updateCamera = function(camera2) { if (session === null) return; cameraVR.near = cameraR.near = cameraL.near = camera2.near; cameraVR.far = cameraR.far = cameraL.far = camera2.far; if (_currentDepthNear !== cameraVR.near || _currentDepthFar !== cameraVR.far) { session.updateRenderState({ depthNear: cameraVR.near, depthFar: cameraVR.far }); _currentDepthNear = cameraVR.near; _currentDepthFar = cameraVR.far; } const parent = camera2.parent; const cameras2 = cameraVR.cameras; updateCamera(cameraVR, parent); for (let i = 0; i < cameras2.length; i++) { updateCamera(cameras2[i], parent); } cameraVR.matrixWorld.decompose(cameraVR.position, cameraVR.quaternion, cameraVR.scale); camera2.matrix.copy(cameraVR.matrix); camera2.matrix.decompose(camera2.position, camera2.quaternion, camera2.scale); const children = camera2.children; for (let i = 0, l = children.length; i < l; i++) { children[i].updateMatrixWorld(true); } if (cameras2.length === 2) { setProjectionFromUnion(cameraVR, cameraL, cameraR); } else { cameraVR.projectionMatrix.copy(cameraL.projectionMatrix); } }; this.getCamera = function() { return cameraVR; }; this.getFoveation = function() { if (glProjLayer !== null) { return glProjLayer.fixedFoveation; } if (glBaseLayer !== null) { return glBaseLayer.fixedFoveation; } return void 0; }; this.setFoveation = function(foveation) { if (glProjLayer !== null) { glProjLayer.fixedFoveation = foveation; } if (glBaseLayer !== null && glBaseLayer.fixedFoveation !== void 0) { glBaseLayer.fixedFoveation = foveation; } }; let onAnimationFrameCallback = null; function onAnimationFrame(time, frame) { pose = frame.getViewerPose(customReferenceSpace || referenceSpace); xrFrame = frame; if (pose !== null) { const views = pose.views; if (glBaseLayer !== null) { renderer.setRenderTargetFramebuffer(newRenderTarget, glBaseLayer.framebuffer); renderer.setRenderTarget(newRenderTarget); } let cameraVRNeedsUpdate = false; if (views.length !== cameraVR.cameras.length) { cameraVR.cameras.length = 0; cameraVRNeedsUpdate = true; } for (let i = 0; i < views.length; i++) { const view2 = views[i]; let viewport = null; if (glBaseLayer !== null) { viewport = glBaseLayer.getViewport(view2); } else { const glSubImage = glBinding.getViewSubImage(glProjLayer, view2); viewport = glSubImage.viewport; if (i === 0) { renderer.setRenderTargetTextures( newRenderTarget, glSubImage.colorTexture, glProjLayer.ignoreDepthValues ? void 0 : glSubImage.depthStencilTexture ); renderer.setRenderTarget(newRenderTarget); } } let camera2 = cameras[i]; if (camera2 === void 0) { camera2 = new PerspectiveCamera(); camera2.layers.enable(i); camera2.viewport = new Vector4(); cameras[i] = camera2; } camera2.matrix.fromArray(view2.transform.matrix); camera2.projectionMatrix.fromArray(view2.projectionMatrix); camera2.viewport.set(viewport.x, viewport.y, viewport.width, viewport.height); if (i === 0) { cameraVR.matrix.copy(camera2.matrix); } if (cameraVRNeedsUpdate === true) { cameraVR.cameras.push(camera2); } } } for (let i = 0; i < controllers.length; i++) { const inputSource = controllerInputSources[i]; const controller = controllers[i]; if (inputSource !== null && controller !== void 0) { controller.update(inputSource, frame, customReferenceSpace || referenceSpace); } } if (onAnimationFrameCallback) onAnimationFrameCallback(time, frame); xrFrame = null; } const animation = new WebGLAnimation(); animation.setAnimationLoop(onAnimationFrame); this.setAnimationLoop = function(callback) { onAnimationFrameCallback = callback; }; this.dispose = function() { }; } }; function WebGLMaterials(renderer, properties) { function refreshFogUniforms(uniforms, fog) { uniforms.fogColor.value.copy(fog.color); if (fog.isFog) { uniforms.fogNear.value = fog.near; uniforms.fogFar.value = fog.far; } else if (fog.isFogExp2) { uniforms.fogDensity.value = fog.density; } } function refreshMaterialUniforms(uniforms, material, pixelRatio, height, transmissionRenderTarget) { if (material.isMeshBasicMaterial) { refreshUniformsCommon(uniforms, material); } else if (material.isMeshLambertMaterial) { refreshUniformsCommon(uniforms, material); } else if (material.isMeshToonMaterial) { refreshUniformsCommon(uniforms, material); refreshUniformsToon(uniforms, material); } else if (material.isMeshPhongMaterial) { refreshUniformsCommon(uniforms, material); refreshUniformsPhong(uniforms, material); } else if (material.isMeshStandardMaterial) { refreshUniformsCommon(uniforms, material); refreshUniformsStandard(uniforms, material); if (material.isMeshPhysicalMaterial) { refreshUniformsPhysical(uniforms, material, transmissionRenderTarget); } } else if (material.isMeshMatcapMaterial) { refreshUniformsCommon(uniforms, material); refreshUniformsMatcap(uniforms, material); } else if (material.isMeshDepthMaterial) { refreshUniformsCommon(uniforms, material); } else if (material.isMeshDistanceMaterial) { refreshUniformsCommon(uniforms, material); refreshUniformsDistance(uniforms, material); } else if (material.isMeshNormalMaterial) { refreshUniformsCommon(uniforms, material); } else if (material.isLineBasicMaterial) { refreshUniformsLine(uniforms, material); if (material.isLineDashedMaterial) { refreshUniformsDash(uniforms, material); } } else if (material.isPointsMaterial) { refreshUniformsPoints(uniforms, material, pixelRatio, height); } else if (material.isSpriteMaterial) { refreshUniformsSprites(uniforms, material); } else if (material.isShadowMaterial) { uniforms.color.value.copy(material.color); uniforms.opacity.value = material.opacity; } else if (material.isShaderMaterial) { material.uniformsNeedUpdate = false; } } function refreshUniformsCommon(uniforms, material) { uniforms.opacity.value = material.opacity; if (material.color) { uniforms.diffuse.value.copy(material.color); } if (material.emissive) { uniforms.emissive.value.copy(material.emissive).multiplyScalar(material.emissiveIntensity); } if (material.map) { uniforms.map.value = material.map; } if (material.alphaMap) { uniforms.alphaMap.value = material.alphaMap; } if (material.bumpMap) { uniforms.bumpMap.value = material.bumpMap; uniforms.bumpScale.value = material.bumpScale; if (material.side === BackSide) uniforms.bumpScale.value *= -1; } if (material.displacementMap) { uniforms.displacementMap.value = material.displacementMap; uniforms.displacementScale.value = material.displacementScale; uniforms.displacementBias.value = material.displacementBias; } if (material.emissiveMap) { uniforms.emissiveMap.value = material.emissiveMap; } if (material.normalMap) { uniforms.normalMap.value = material.normalMap; uniforms.normalScale.value.copy(material.normalScale); if (material.side === BackSide) uniforms.normalScale.value.negate(); } if (material.specularMap) { uniforms.specularMap.value = material.specularMap; } if (material.alphaTest > 0) { uniforms.alphaTest.value = material.alphaTest; } const envMap = properties.get(material).envMap; if (envMap) { uniforms.envMap.value = envMap; uniforms.flipEnvMap.value = envMap.isCubeTexture && envMap.isRenderTargetTexture === false ? -1 : 1; uniforms.reflectivity.value = material.reflectivity; uniforms.ior.value = material.ior; uniforms.refractionRatio.value = material.refractionRatio; } if (material.lightMap) { uniforms.lightMap.value = material.lightMap; const scaleFactor = renderer.physicallyCorrectLights !== true ? Math.PI : 1; uniforms.lightMapIntensity.value = material.lightMapIntensity * scaleFactor; } if (material.aoMap) { uniforms.aoMap.value = material.aoMap; uniforms.aoMapIntensity.value = material.aoMapIntensity; } let uvScaleMap; if (material.map) { uvScaleMap = material.map; } else if (material.specularMap) { uvScaleMap = material.specularMap; } else if (material.displacementMap) { uvScaleMap = material.displacementMap; } else if (material.normalMap) { uvScaleMap = material.normalMap; } else if (material.bumpMap) { uvScaleMap = material.bumpMap; } else if (material.roughnessMap) { uvScaleMap = material.roughnessMap; } else if (material.metalnessMap) { uvScaleMap = material.metalnessMap; } else if (material.alphaMap) { uvScaleMap = material.alphaMap; } else if (material.emissiveMap) { uvScaleMap = material.emissiveMap; } else if (material.clearcoatMap) { uvScaleMap = material.clearcoatMap; } else if (material.clearcoatNormalMap) { uvScaleMap = material.clearcoatNormalMap; } else if (material.clearcoatRoughnessMap) { uvScaleMap = material.clearcoatRoughnessMap; } else if (material.iridescenceMap) { uvScaleMap = material.iridescenceMap; } else if (material.iridescenceThicknessMap) { uvScaleMap = material.iridescenceThicknessMap; } else if (material.specularIntensityMap) { uvScaleMap = material.specularIntensityMap; } else if (material.specularColorMap) { uvScaleMap = material.specularColorMap; } else if (material.transmissionMap) { uvScaleMap = material.transmissionMap; } else if (material.thicknessMap) { uvScaleMap = material.thicknessMap; } else if (material.sheenColorMap) { uvScaleMap = material.sheenColorMap; } else if (material.sheenRoughnessMap) { uvScaleMap = material.sheenRoughnessMap; } if (uvScaleMap !== void 0) { if (uvScaleMap.isWebGLRenderTarget) { uvScaleMap = uvScaleMap.texture; } if (uvScaleMap.matrixAutoUpdate === true) { uvScaleMap.updateMatrix(); } uniforms.uvTransform.value.copy(uvScaleMap.matrix); } let uv2ScaleMap; if (material.aoMap) { uv2ScaleMap = material.aoMap; } else if (material.lightMap) { uv2ScaleMap = material.lightMap; } if (uv2ScaleMap !== void 0) { if (uv2ScaleMap.isWebGLRenderTarget) { uv2ScaleMap = uv2ScaleMap.texture; } if (uv2ScaleMap.matrixAutoUpdate === true) { uv2ScaleMap.updateMatrix(); } uniforms.uv2Transform.value.copy(uv2ScaleMap.matrix); } } function refreshUniformsLine(uniforms, material) { uniforms.diffuse.value.copy(material.color); uniforms.opacity.value = material.opacity; } function refreshUniformsDash(uniforms, material) { uniforms.dashSize.value = material.dashSize; uniforms.totalSize.value = material.dashSize + material.gapSize; uniforms.scale.value = material.scale; } function refreshUniformsPoints(uniforms, material, pixelRatio, height) { uniforms.diffuse.value.copy(material.color); uniforms.opacity.value = material.opacity; uniforms.size.value = material.size * pixelRatio; uniforms.scale.value = height * 0.5; if (material.map) { uniforms.map.value = material.map; } if (material.alphaMap) { uniforms.alphaMap.value = material.alphaMap; } if (material.alphaTest > 0) { uniforms.alphaTest.value = material.alphaTest; } let uvScaleMap; if (material.map) { uvScaleMap = material.map; } else if (material.alphaMap) { uvScaleMap = material.alphaMap; } if (uvScaleMap !== void 0) { if (uvScaleMap.matrixAutoUpdate === true) { uvScaleMap.updateMatrix(); } uniforms.uvTransform.value.copy(uvScaleMap.matrix); } } function refreshUniformsSprites(uniforms, material) { uniforms.diffuse.value.copy(material.color); uniforms.opacity.value = material.opacity; uniforms.rotation.value = material.rotation; if (material.map) { uniforms.map.value = material.map; } if (material.alphaMap) { uniforms.alphaMap.value = material.alphaMap; } if (material.alphaTest > 0) { uniforms.alphaTest.value = material.alphaTest; } let uvScaleMap; if (material.map) { uvScaleMap = material.map; } else if (material.alphaMap) { uvScaleMap = material.alphaMap; } if (uvScaleMap !== void 0) { if (uvScaleMap.matrixAutoUpdate === true) { uvScaleMap.updateMatrix(); } uniforms.uvTransform.value.copy(uvScaleMap.matrix); } } function refreshUniformsPhong(uniforms, material) { uniforms.specular.value.copy(material.specular); uniforms.shininess.value = Math.max(material.shininess, 1e-4); } function refreshUniformsToon(uniforms, material) { if (material.gradientMap) { uniforms.gradientMap.value = material.gradientMap; } } function refreshUniformsStandard(uniforms, material) { uniforms.roughness.value = material.roughness; uniforms.metalness.value = material.metalness; if (material.roughnessMap) { uniforms.roughnessMap.value = material.roughnessMap; } if (material.metalnessMap) { uniforms.metalnessMap.value = material.metalnessMap; } const envMap = properties.get(material).envMap; if (envMap) { uniforms.envMapIntensity.value = material.envMapIntensity; } } function refreshUniformsPhysical(uniforms, material, transmissionRenderTarget) { uniforms.ior.value = material.ior; if (material.sheen > 0) { uniforms.sheenColor.value.copy(material.sheenColor).multiplyScalar(material.sheen); uniforms.sheenRoughness.value = material.sheenRoughness; if (material.sheenColorMap) { uniforms.sheenColorMap.value = material.sheenColorMap; } if (material.sheenRoughnessMap) { uniforms.sheenRoughnessMap.value = material.sheenRoughnessMap; } } if (material.clearcoat > 0) { uniforms.clearcoat.value = material.clearcoat; uniforms.clearcoatRoughness.value = material.clearcoatRoughness; if (material.clearcoatMap) { uniforms.clearcoatMap.value = material.clearcoatMap; } if (material.clearcoatRoughnessMap) { uniforms.clearcoatRoughnessMap.value = material.clearcoatRoughnessMap; } if (material.clearcoatNormalMap) { uniforms.clearcoatNormalScale.value.copy(material.clearcoatNormalScale); uniforms.clearcoatNormalMap.value = material.clearcoatNormalMap; if (material.side === BackSide) { uniforms.clearcoatNormalScale.value.negate(); } } } if (material.iridescence > 0) { uniforms.iridescence.value = material.iridescence; uniforms.iridescenceIOR.value = material.iridescenceIOR; uniforms.iridescenceThicknessMinimum.value = material.iridescenceThicknessRange[0]; uniforms.iridescenceThicknessMaximum.value = material.iridescenceThicknessRange[1]; if (material.iridescenceMap) { uniforms.iridescenceMap.value = material.iridescenceMap; } if (material.iridescenceThicknessMap) { uniforms.iridescenceThicknessMap.value = material.iridescenceThicknessMap; } } if (material.transmission > 0) { uniforms.transmission.value = material.transmission; uniforms.transmissionSamplerMap.value = transmissionRenderTarget.texture; uniforms.transmissionSamplerSize.value.set(transmissionRenderTarget.width, transmissionRenderTarget.height); if (material.transmissionMap) { uniforms.transmissionMap.value = material.transmissionMap; } uniforms.thickness.value = material.thickness; if (material.thicknessMap) { uniforms.thicknessMap.value = material.thicknessMap; } uniforms.attenuationDistance.value = material.attenuationDistance; uniforms.attenuationColor.value.copy(material.attenuationColor); } uniforms.specularIntensity.value = material.specularIntensity; uniforms.specularColor.value.copy(material.specularColor); if (material.specularIntensityMap) { uniforms.specularIntensityMap.value = material.specularIntensityMap; } if (material.specularColorMap) { uniforms.specularColorMap.value = material.specularColorMap; } } function refreshUniformsMatcap(uniforms, material) { if (material.matcap) { uniforms.matcap.value = material.matcap; } } function refreshUniformsDistance(uniforms, material) { uniforms.referencePosition.value.copy(material.referencePosition); uniforms.nearDistance.value = material.nearDistance; uniforms.farDistance.value = material.farDistance; } return { refreshFogUniforms, refreshMaterialUniforms }; } function WebGLUniformsGroups(gl, info, capabilities, state) { let buffers = {}; let updateList = {}; let allocatedBindingPoints = []; const maxBindingPoints = capabilities.isWebGL2 ? gl.getParameter(35375) : 0; function bind(uniformsGroup, program) { const webglProgram = program.program; state.uniformBlockBinding(uniformsGroup, webglProgram); } function update(uniformsGroup, program) { let buffer = buffers[uniformsGroup.id]; if (buffer === void 0) { prepareUniformsGroup(uniformsGroup); buffer = createBuffer(uniformsGroup); buffers[uniformsGroup.id] = buffer; uniformsGroup.addEventListener("dispose", onUniformsGroupsDispose); } const webglProgram = program.program; state.updateUBOMapping(uniformsGroup, webglProgram); const frame = info.render.frame; if (updateList[uniformsGroup.id] !== frame) { updateBufferData(uniformsGroup); updateList[uniformsGroup.id] = frame; } } function createBuffer(uniformsGroup) { const bindingPointIndex = allocateBindingPointIndex(); uniformsGroup.__bindingPointIndex = bindingPointIndex; const buffer = gl.createBuffer(); const size = uniformsGroup.__size; const usage = uniformsGroup.usage; gl.bindBuffer(35345, buffer); gl.bufferData(35345, size, usage); gl.bindBuffer(35345, null); gl.bindBufferBase(35345, bindingPointIndex, buffer); return buffer; } function allocateBindingPointIndex() { for (let i = 0; i < maxBindingPoints; i++) { if (allocatedBindingPoints.indexOf(i) === -1) { allocatedBindingPoints.push(i); return i; } } console.error("THREE.WebGLRenderer: Maximum number of simultaneously usable uniforms groups reached."); return 0; } function updateBufferData(uniformsGroup) { const buffer = buffers[uniformsGroup.id]; const uniforms = uniformsGroup.uniforms; const cache2 = uniformsGroup.__cache; gl.bindBuffer(35345, buffer); for (let i = 0, il = uniforms.length; i < il; i++) { const uniform = uniforms[i]; if (hasUniformChanged(uniform, i, cache2) === true) { const value = uniform.value; const offset = uniform.__offset; if (typeof value === "number") { uniform.__data[0] = value; gl.bufferSubData(35345, offset, uniform.__data); } else { if (uniform.value.isMatrix3) { uniform.__data[0] = uniform.value.elements[0]; uniform.__data[1] = uniform.value.elements[1]; uniform.__data[2] = uniform.value.elements[2]; uniform.__data[3] = uniform.value.elements[0]; uniform.__data[4] = uniform.value.elements[3]; uniform.__data[5] = uniform.value.elements[4]; uniform.__data[6] = uniform.value.elements[5]; uniform.__data[7] = uniform.value.elements[0]; uniform.__data[8] = uniform.value.elements[6]; uniform.__data[9] = uniform.value.elements[7]; uniform.__data[10] = uniform.value.elements[8]; uniform.__data[11] = uniform.value.elements[0]; } else { value.toArray(uniform.__data); } gl.bufferSubData(35345, offset, uniform.__data); } } } gl.bindBuffer(35345, null); } function hasUniformChanged(uniform, index, cache2) { const value = uniform.value; if (cache2[index] === void 0) { if (typeof value === "number") { cache2[index] = value; } else { cache2[index] = value.clone(); } return true; } else { if (typeof value === "number") { if (cache2[index] !== value) { cache2[index] = value; return true; } } else { const cachedObject = cache2[index]; if (cachedObject.equals(value) === false) { cachedObject.copy(value); return true; } } } return false; } function prepareUniformsGroup(uniformsGroup) { const uniforms = uniformsGroup.uniforms; let offset = 0; const chunkSize = 16; let chunkOffset = 0; for (let i = 0, l = uniforms.length; i < l; i++) { const uniform = uniforms[i]; const info2 = getUniformSize(uniform); uniform.__data = new Float32Array(info2.storage / Float32Array.BYTES_PER_ELEMENT); uniform.__offset = offset; if (i > 0) { chunkOffset = offset % chunkSize; const remainingSizeInChunk = chunkSize - chunkOffset; if (chunkOffset !== 0 && remainingSizeInChunk - info2.boundary < 0) { offset += chunkSize - chunkOffset; uniform.__offset = offset; } } offset += info2.storage; } chunkOffset = offset % chunkSize; if (chunkOffset > 0) offset += chunkSize - chunkOffset; uniformsGroup.__size = offset; uniformsGroup.__cache = {}; return this; } function getUniformSize(uniform) { const value = uniform.value; const info2 = { boundary: 0, // bytes storage: 0 // bytes }; if (typeof value === "number") { info2.boundary = 4; info2.storage = 4; } else if (value.isVector2) { info2.boundary = 8; info2.storage = 8; } else if (value.isVector3 || value.isColor) { info2.boundary = 16; info2.storage = 12; } else if (value.isVector4) { info2.boundary = 16; info2.storage = 16; } else if (value.isMatrix3) { info2.boundary = 48; info2.storage = 48; } else if (value.isMatrix4) { info2.boundary = 64; info2.storage = 64; } else if (value.isTexture) { console.warn("THREE.WebGLRenderer: Texture samplers can not be part of an uniforms group."); } else { console.warn("THREE.WebGLRenderer: Unsupported uniform value type.", value); } return info2; } function onUniformsGroupsDispose(event) { const uniformsGroup = event.target; uniformsGroup.removeEventListener("dispose", onUniformsGroupsDispose); const index = allocatedBindingPoints.indexOf(uniformsGroup.__bindingPointIndex); allocatedBindingPoints.splice(index, 1); gl.deleteBuffer(buffers[uniformsGroup.id]); delete buffers[uniformsGroup.id]; delete updateList[uniformsGroup.id]; } function dispose() { for (const id in buffers) { gl.deleteBuffer(buffers[id]); } allocatedBindingPoints = []; buffers = {}; updateList = {}; } return { bind, update, dispose }; } function createCanvasElement() { const canvas = createElementNS("canvas"); canvas.style.display = "block"; return canvas; } function WebGLRenderer(parameters = {}) { this.isWebGLRenderer = true; const _canvas2 = parameters.canvas !== void 0 ? parameters.canvas : createCanvasElement(), _context = parameters.context !== void 0 ? parameters.context : null, _depth = parameters.depth !== void 0 ? parameters.depth : true, _stencil = parameters.stencil !== void 0 ? parameters.stencil : true, _antialias = parameters.antialias !== void 0 ? parameters.antialias : false, _premultipliedAlpha = parameters.premultipliedAlpha !== void 0 ? parameters.premultipliedAlpha : true, _preserveDrawingBuffer = parameters.preserveDrawingBuffer !== void 0 ? parameters.preserveDrawingBuffer : false, _powerPreference = parameters.powerPreference !== void 0 ? parameters.powerPreference : "default", _failIfMajorPerformanceCaveat = parameters.failIfMajorPerformanceCaveat !== void 0 ? parameters.failIfMajorPerformanceCaveat : false; let _alpha; if (_context !== null) { _alpha = _context.getContextAttributes().alpha; } else { _alpha = parameters.alpha !== void 0 ? parameters.alpha : false; } let currentRenderList = null; let currentRenderState = null; const renderListStack = []; const renderStateStack = []; this.domElement = _canvas2; this.debug = { /** * Enables error checking and reporting when shader programs are being compiled * @type {boolean} */ checkShaderErrors: true }; this.autoClear = true; this.autoClearColor = true; this.autoClearDepth = true; this.autoClearStencil = true; this.sortObjects = true; this.clippingPlanes = []; this.localClippingEnabled = false; this.outputEncoding = LinearEncoding; this.physicallyCorrectLights = false; this.toneMapping = NoToneMapping; this.toneMappingExposure = 1; Object.defineProperties(this, { // @deprecated since r136, 0e21088102b4de7e0a0a33140620b7a3424b9e6d gammaFactor: { get: function() { console.warn("THREE.WebGLRenderer: .gammaFactor has been removed."); return 2; }, set: function() { console.warn("THREE.WebGLRenderer: .gammaFactor has been removed."); } } }); const _this = this; let _isContextLost = false; let _currentActiveCubeFace = 0; let _currentActiveMipmapLevel = 0; let _currentRenderTarget = null; let _currentMaterialId = -1; let _currentCamera = null; const _currentViewport = new Vector4(); const _currentScissor = new Vector4(); let _currentScissorTest = null; let _width = _canvas2.width; let _height = _canvas2.height; let _pixelRatio = 1; let _opaqueSort = null; let _transparentSort = null; const _viewport = new Vector4(0, 0, _width, _height); const _scissor = new Vector4(0, 0, _width, _height); let _scissorTest = false; const _frustum = new Frustum(); let _clippingEnabled = false; let _localClippingEnabled = false; let _transmissionRenderTarget = null; const _projScreenMatrix2 = new Matrix4(); const _vector22 = new Vector2(); const _vector32 = new Vector3(); const _emptyScene = { background: null, fog: null, environment: null, overrideMaterial: null, isScene: true }; function getTargetPixelRatio() { return _currentRenderTarget === null ? _pixelRatio : 1; } let _gl = _context; function getContext(contextNames, contextAttributes) { for (let i = 0; i < contextNames.length; i++) { const contextName = contextNames[i]; const context = _canvas2.getContext(contextName, contextAttributes); if (context !== null) return context; } return null; } try { const contextAttributes = { alpha: true, depth: _depth, stencil: _stencil, antialias: _antialias, premultipliedAlpha: _premultipliedAlpha, preserveDrawingBuffer: _preserveDrawingBuffer, powerPreference: _powerPreference, failIfMajorPerformanceCaveat: _failIfMajorPerformanceCaveat }; if ("setAttribute" in _canvas2) _canvas2.setAttribute("data-engine", `three.js r${REVISION}`); _canvas2.addEventListener("webglcontextlost", onContextLost, false); _canvas2.addEventListener("webglcontextrestored", onContextRestore, false); _canvas2.addEventListener("webglcontextcreationerror", onContextCreationError, false); if (_gl === null) { const contextNames = ["webgl2", "webgl", "experimental-webgl"]; if (_this.isWebGL1Renderer === true) { contextNames.shift(); } _gl = getContext(contextNames, contextAttributes); if (_gl === null) { if (getContext(contextNames)) { throw new Error("Error creating WebGL context with your selected attributes."); } else { throw new Error("Error creating WebGL context."); } } } if (_gl.getShaderPrecisionFormat === void 0) { _gl.getShaderPrecisionFormat = function() { return { "rangeMin": 1, "rangeMax": 1, "precision": 1 }; }; } } catch (error) { console.error("THREE.WebGLRenderer: " + error.message); throw error; } let extensions, capabilities, state, info; let properties, textures, cubemaps, cubeuvmaps, attributes, geometries, objects; let programCache, materials, renderLists, renderStates, clipping, shadowMap; let background, morphtargets, bufferRenderer, indexedBufferRenderer; let utils, bindingStates, uniformsGroups; function initGLContext() { extensions = new WebGLExtensions(_gl); capabilities = new WebGLCapabilities(_gl, extensions, parameters); extensions.init(capabilities); utils = new WebGLUtils(_gl, extensions, capabilities); state = new WebGLState(_gl, extensions, capabilities); info = new WebGLInfo(); properties = new WebGLProperties(); textures = new WebGLTextures(_gl, extensions, state, properties, capabilities, utils, info); cubemaps = new WebGLCubeMaps(_this); cubeuvmaps = new WebGLCubeUVMaps(_this); attributes = new WebGLAttributes(_gl, capabilities); bindingStates = new WebGLBindingStates(_gl, extensions, attributes, capabilities); geometries = new WebGLGeometries(_gl, attributes, info, bindingStates); objects = new WebGLObjects(_gl, geometries, attributes, info); morphtargets = new WebGLMorphtargets(_gl, capabilities, textures); clipping = new WebGLClipping(properties); programCache = new WebGLPrograms(_this, cubemaps, cubeuvmaps, extensions, capabilities, bindingStates, clipping); materials = new WebGLMaterials(_this, properties); renderLists = new WebGLRenderLists(); renderStates = new WebGLRenderStates(extensions, capabilities); background = new WebGLBackground(_this, cubemaps, cubeuvmaps, state, objects, _alpha, _premultipliedAlpha); shadowMap = new WebGLShadowMap(_this, objects, capabilities); uniformsGroups = new WebGLUniformsGroups(_gl, info, capabilities, state); bufferRenderer = new WebGLBufferRenderer(_gl, extensions, info, capabilities); indexedBufferRenderer = new WebGLIndexedBufferRenderer(_gl, extensions, info, capabilities); info.programs = programCache.programs; _this.capabilities = capabilities; _this.extensions = extensions; _this.properties = properties; _this.renderLists = renderLists; _this.shadowMap = shadowMap; _this.state = state; _this.info = info; } initGLContext(); const xr = new WebXRManager(_this, _gl); this.xr = xr; this.getContext = function() { return _gl; }; this.getContextAttributes = function() { return _gl.getContextAttributes(); }; this.forceContextLoss = function() { const extension = extensions.get("WEBGL_lose_context"); if (extension) extension.loseContext(); }; this.forceContextRestore = function() { const extension = extensions.get("WEBGL_lose_context"); if (extension) extension.restoreContext(); }; this.getPixelRatio = function() { return _pixelRatio; }; this.setPixelRatio = function(value) { if (value === void 0) return; _pixelRatio = value; this.setSize(_width, _height, false); }; this.getSize = function(target2) { return target2.set(_width, _height); }; this.setSize = function(width, height, updateStyle) { if (xr.isPresenting) { console.warn("THREE.WebGLRenderer: Can't change size while VR device is presenting."); return; } _width = width; _height = height; _canvas2.width = Math.floor(width * _pixelRatio); _canvas2.height = Math.floor(height * _pixelRatio); if (updateStyle !== false) { _canvas2.style.width = width + "px"; _canvas2.style.height = height + "px"; } this.setViewport(0, 0, width, height); }; this.getDrawingBufferSize = function(target2) { return target2.set(_width * _pixelRatio, _height * _pixelRatio).floor(); }; this.setDrawingBufferSize = function(width, height, pixelRatio) { _width = width; _height = height; _pixelRatio = pixelRatio; _canvas2.width = Math.floor(width * pixelRatio); _canvas2.height = Math.floor(height * pixelRatio); this.setViewport(0, 0, width, height); }; this.getCurrentViewport = function(target2) { return target2.copy(_currentViewport); }; this.getViewport = function(target2) { return target2.copy(_viewport); }; this.setViewport = function(x2, y, width, height) { if (x2.isVector4) { _viewport.set(x2.x, x2.y, x2.z, x2.w); } else { _viewport.set(x2, y, width, height); } state.viewport(_currentViewport.copy(_viewport).multiplyScalar(_pixelRatio).floor()); }; this.getScissor = function(target2) { return target2.copy(_scissor); }; this.setScissor = function(x2, y, width, height) { if (x2.isVector4) { _scissor.set(x2.x, x2.y, x2.z, x2.w); } else { _scissor.set(x2, y, width, height); } state.scissor(_currentScissor.copy(_scissor).multiplyScalar(_pixelRatio).floor()); }; this.getScissorTest = function() { return _scissorTest; }; this.setScissorTest = function(boolean) { state.setScissorTest(_scissorTest = boolean); }; this.setOpaqueSort = function(method) { _opaqueSort = method; }; this.setTransparentSort = function(method) { _transparentSort = method; }; this.getClearColor = function(target2) { return target2.copy(background.getClearColor()); }; this.setClearColor = function() { background.setClearColor.apply(background, arguments); }; this.getClearAlpha = function() { return background.getClearAlpha(); }; this.setClearAlpha = function() { background.setClearAlpha.apply(background, arguments); }; this.clear = function(color = true, depth = true, stencil = true) { let bits2 = 0; if (color) bits2 |= 16384; if (depth) bits2 |= 256; if (stencil) bits2 |= 1024; _gl.clear(bits2); }; this.clearColor = function() { this.clear(true, false, false); }; this.clearDepth = function() { this.clear(false, true, false); }; this.clearStencil = function() { this.clear(false, false, true); }; this.dispose = function() { _canvas2.removeEventListener("webglcontextlost", onContextLost, false); _canvas2.removeEventListener("webglcontextrestored", onContextRestore, false); _canvas2.removeEventListener("webglcontextcreationerror", onContextCreationError, false); renderLists.dispose(); renderStates.dispose(); properties.dispose(); cubemaps.dispose(); cubeuvmaps.dispose(); objects.dispose(); bindingStates.dispose(); uniformsGroups.dispose(); programCache.dispose(); xr.dispose(); xr.removeEventListener("sessionstart", onXRSessionStart); xr.removeEventListener("sessionend", onXRSessionEnd); if (_transmissionRenderTarget) { _transmissionRenderTarget.dispose(); _transmissionRenderTarget = null; } animation.stop(); }; function onContextLost(event) { event.preventDefault(); console.log("THREE.WebGLRenderer: Context Lost."); _isContextLost = true; } function onContextRestore() { console.log("THREE.WebGLRenderer: Context Restored."); _isContextLost = false; const infoAutoReset = info.autoReset; const shadowMapEnabled = shadowMap.enabled; const shadowMapAutoUpdate = shadowMap.autoUpdate; const shadowMapNeedsUpdate = shadowMap.needsUpdate; const shadowMapType = shadowMap.type; initGLContext(); info.autoReset = infoAutoReset; shadowMap.enabled = shadowMapEnabled; shadowMap.autoUpdate = shadowMapAutoUpdate; shadowMap.needsUpdate = shadowMapNeedsUpdate; shadowMap.type = shadowMapType; } function onContextCreationError(event) { console.error("THREE.WebGLRenderer: A WebGL context could not be created. Reason: ", event.statusMessage); } function onMaterialDispose(event) { const material = event.target; material.removeEventListener("dispose", onMaterialDispose); deallocateMaterial(material); } function deallocateMaterial(material) { releaseMaterialProgramReferences(material); properties.remove(material); } function releaseMaterialProgramReferences(material) { const programs = properties.get(material).programs; if (programs !== void 0) { programs.forEach(function(program) { programCache.releaseProgram(program); }); if (material.isShaderMaterial) { programCache.releaseShaderCache(material); } } } this.renderBufferDirect = function(camera2, scene, geometry, material, object, group) { if (scene === null) scene = _emptyScene; const frontFaceCW = object.isMesh && object.matrixWorld.determinant() < 0; const program = setProgram(camera2, scene, geometry, material, object); state.setMaterial(material, frontFaceCW); let index = geometry.index; const position = geometry.attributes.position; if (index === null) { if (position === void 0 || position.count === 0) return; } else if (index.count === 0) { return; } let rangeFactor = 1; if (material.wireframe === true) { index = geometries.getWireframeAttribute(geometry); rangeFactor = 2; } bindingStates.setup(object, material, program, geometry, index); let attribute; let renderer = bufferRenderer; if (index !== null) { attribute = attributes.get(index); renderer = indexedBufferRenderer; renderer.setIndex(attribute); } const dataCount = index !== null ? index.count : position.count; const rangeStart = geometry.drawRange.start * rangeFactor; const rangeCount = geometry.drawRange.count * rangeFactor; const groupStart = group !== null ? group.start * rangeFactor : 0; const groupCount = group !== null ? group.count * rangeFactor : Infinity; const drawStart = Math.max(rangeStart, groupStart); const drawEnd = Math.min(dataCount, rangeStart + rangeCount, groupStart + groupCount) - 1; const drawCount = Math.max(0, drawEnd - drawStart + 1); if (drawCount === 0) return; if (object.isMesh) { if (material.wireframe === true) { state.setLineWidth(material.wireframeLinewidth * getTargetPixelRatio()); renderer.setMode(1); } else { renderer.setMode(4); } } else if (object.isLine) { let lineWidth = material.linewidth; if (lineWidth === void 0) lineWidth = 1; state.setLineWidth(lineWidth * getTargetPixelRatio()); if (object.isLineSegments) { renderer.setMode(1); } else if (object.isLineLoop) { renderer.setMode(2); } else { renderer.setMode(3); } } else if (object.isPoints) { renderer.setMode(0); } else if (object.isSprite) { renderer.setMode(4); } if (object.isInstancedMesh) { renderer.renderInstances(drawStart, drawCount, object.count); } else if (geometry.isInstancedBufferGeometry) { const instanceCount = Math.min(geometry.instanceCount, geometry._maxInstanceCount); renderer.renderInstances(drawStart, drawCount, instanceCount); } else { renderer.render(drawStart, drawCount); } }; this.compile = function(scene, camera2) { function prepare(material, scene2, object) { if (material.transparent === true && material.side === DoubleSide) { material.side = BackSide; material.needsUpdate = true; getProgram(material, scene2, object); material.side = FrontSide; material.needsUpdate = true; getProgram(material, scene2, object); material.side = DoubleSide; } else { getProgram(material, scene2, object); } } currentRenderState = renderStates.get(scene); currentRenderState.init(); renderStateStack.push(currentRenderState); scene.traverseVisible(function(object) { if (object.isLight && object.layers.test(camera2.layers)) { currentRenderState.pushLight(object); if (object.castShadow) { currentRenderState.pushShadow(object); } } }); currentRenderState.setupLights(_this.physicallyCorrectLights); scene.traverse(function(object) { const material = object.material; if (material) { if (Array.isArray(material)) { for (let i = 0; i < material.length; i++) { const material2 = material[i]; prepare(material2, scene, object); } } else { prepare(material, scene, object); } } }); renderStateStack.pop(); currentRenderState = null; }; let onAnimationFrameCallback = null; function onAnimationFrame(time) { if (onAnimationFrameCallback) onAnimationFrameCallback(time); } function onXRSessionStart() { animation.stop(); } function onXRSessionEnd() { animation.start(); } const animation = new WebGLAnimation(); animation.setAnimationLoop(onAnimationFrame); if (typeof self !== "undefined") animation.setContext(self); this.setAnimationLoop = function(callback) { onAnimationFrameCallback = callback; xr.setAnimationLoop(callback); callback === null ? animation.stop() : animation.start(); }; xr.addEventListener("sessionstart", onXRSessionStart); xr.addEventListener("sessionend", onXRSessionEnd); this.render = function(scene, camera2) { if (camera2 !== void 0 && camera2.isCamera !== true) { console.error("THREE.WebGLRenderer.render: camera is not an instance of THREE.Camera."); return; } if (_isContextLost === true) return; if (scene.matrixWorldAutoUpdate === true) scene.updateMatrixWorld(); if (camera2.parent === null && camera2.matrixWorldAutoUpdate === true) camera2.updateMatrixWorld(); if (xr.enabled === true && xr.isPresenting === true) { if (xr.cameraAutoUpdate === true) xr.updateCamera(camera2); camera2 = xr.getCamera(); } if (scene.isScene === true) scene.onBeforeRender(_this, scene, camera2, _currentRenderTarget); currentRenderState = renderStates.get(scene, renderStateStack.length); currentRenderState.init(); renderStateStack.push(currentRenderState); _projScreenMatrix2.multiplyMatrices(camera2.projectionMatrix, camera2.matrixWorldInverse); _frustum.setFromProjectionMatrix(_projScreenMatrix2); _localClippingEnabled = this.localClippingEnabled; _clippingEnabled = clipping.init(this.clippingPlanes, _localClippingEnabled, camera2); currentRenderList = renderLists.get(scene, renderListStack.length); currentRenderList.init(); renderListStack.push(currentRenderList); projectObject(scene, camera2, 0, _this.sortObjects); currentRenderList.finish(); if (_this.sortObjects === true) { currentRenderList.sort(_opaqueSort, _transparentSort); } if (_clippingEnabled === true) clipping.beginShadows(); const shadowsArray = currentRenderState.state.shadowsArray; shadowMap.render(shadowsArray, scene, camera2); if (_clippingEnabled === true) clipping.endShadows(); if (this.info.autoReset === true) this.info.reset(); background.render(currentRenderList, scene); currentRenderState.setupLights(_this.physicallyCorrectLights); if (camera2.isArrayCamera) { const cameras = camera2.cameras; for (let i = 0, l = cameras.length; i < l; i++) { const camera22 = cameras[i]; renderScene(currentRenderList, scene, camera22, camera22.viewport); } } else { renderScene(currentRenderList, scene, camera2); } if (_currentRenderTarget !== null) { textures.updateMultisampleRenderTarget(_currentRenderTarget); textures.updateRenderTargetMipmap(_currentRenderTarget); } if (scene.isScene === true) scene.onAfterRender(_this, scene, camera2); bindingStates.resetDefaultState(); _currentMaterialId = -1; _currentCamera = null; renderStateStack.pop(); if (renderStateStack.length > 0) { currentRenderState = renderStateStack[renderStateStack.length - 1]; } else { currentRenderState = null; } renderListStack.pop(); if (renderListStack.length > 0) { currentRenderList = renderListStack[renderListStack.length - 1]; } else { currentRenderList = null; } }; function projectObject(object, camera2, groupOrder, sortObjects) { if (object.visible === false) return; const visible = object.layers.test(camera2.layers); if (visible) { if (object.isGroup) { groupOrder = object.renderOrder; } else if (object.isLOD) { if (object.autoUpdate === true) object.update(camera2); } else if (object.isLight) { currentRenderState.pushLight(object); if (object.castShadow) { currentRenderState.pushShadow(object); } } else if (object.isSprite) { if (!object.frustumCulled || _frustum.intersectsSprite(object)) { if (sortObjects) { _vector32.setFromMatrixPosition(object.matrixWorld).applyMatrix4(_projScreenMatrix2); } const geometry = objects.update(object); const material = object.material; if (material.visible) { currentRenderList.push(object, geometry, material, groupOrder, _vector32.z, null); } } } else if (object.isMesh || object.isLine || object.isPoints) { if (object.isSkinnedMesh) { if (object.skeleton.frame !== info.render.frame) { object.skeleton.update(); object.skeleton.frame = info.render.frame; } } if (!object.frustumCulled || _frustum.intersectsObject(object)) { if (sortObjects) { _vector32.setFromMatrixPosition(object.matrixWorld).applyMatrix4(_projScreenMatrix2); } const geometry = objects.update(object); const material = object.material; if (Array.isArray(material)) { const groups = geometry.groups; for (let i = 0, l = groups.length; i < l; i++) { const group = groups[i]; const groupMaterial = material[group.materialIndex]; if (groupMaterial && groupMaterial.visible) { currentRenderList.push(object, geometry, groupMaterial, groupOrder, _vector32.z, group); } } } else if (material.visible) { currentRenderList.push(object, geometry, material, groupOrder, _vector32.z, null); } } } } const children = object.children; for (let i = 0, l = children.length; i < l; i++) { projectObject(children[i], camera2, groupOrder, sortObjects); } } function renderScene(currentRenderList2, scene, camera2, viewport) { const opaqueObjects = currentRenderList2.opaque; const transmissiveObjects = currentRenderList2.transmissive; const transparentObjects = currentRenderList2.transparent; currentRenderState.setupLightsView(camera2); if (transmissiveObjects.length > 0) renderTransmissionPass(opaqueObjects, scene, camera2); if (viewport) state.viewport(_currentViewport.copy(viewport)); if (opaqueObjects.length > 0) renderObjects(opaqueObjects, scene, camera2); if (transmissiveObjects.length > 0) renderObjects(transmissiveObjects, scene, camera2); if (transparentObjects.length > 0) renderObjects(transparentObjects, scene, camera2); state.buffers.depth.setTest(true); state.buffers.depth.setMask(true); state.buffers.color.setMask(true); state.setPolygonOffset(false); } function renderTransmissionPass(opaqueObjects, scene, camera2) { const isWebGL2 = capabilities.isWebGL2; if (_transmissionRenderTarget === null) { _transmissionRenderTarget = new WebGLRenderTarget(1, 1, { generateMipmaps: true, type: extensions.has("EXT_color_buffer_half_float") ? HalfFloatType : UnsignedByteType, minFilter: LinearMipmapLinearFilter, samples: isWebGL2 && _antialias === true ? 4 : 0 }); } _this.getDrawingBufferSize(_vector22); if (isWebGL2) { _transmissionRenderTarget.setSize(_vector22.x, _vector22.y); } else { _transmissionRenderTarget.setSize(floorPowerOfTwo(_vector22.x), floorPowerOfTwo(_vector22.y)); } const currentRenderTarget = _this.getRenderTarget(); _this.setRenderTarget(_transmissionRenderTarget); _this.clear(); const currentToneMapping = _this.toneMapping; _this.toneMapping = NoToneMapping; renderObjects(opaqueObjects, scene, camera2); _this.toneMapping = currentToneMapping; textures.updateMultisampleRenderTarget(_transmissionRenderTarget); textures.updateRenderTargetMipmap(_transmissionRenderTarget); _this.setRenderTarget(currentRenderTarget); } function renderObjects(renderList, scene, camera2) { const overrideMaterial = scene.isScene === true ? scene.overrideMaterial : null; for (let i = 0, l = renderList.length; i < l; i++) { const renderItem = renderList[i]; const object = renderItem.object; const geometry = renderItem.geometry; const material = overrideMaterial === null ? renderItem.material : overrideMaterial; const group = renderItem.group; if (object.layers.test(camera2.layers)) { renderObject(object, scene, camera2, geometry, material, group); } } } function renderObject(object, scene, camera2, geometry, material, group) { object.onBeforeRender(_this, scene, camera2, geometry, material, group); object.modelViewMatrix.multiplyMatrices(camera2.matrixWorldInverse, object.matrixWorld); object.normalMatrix.getNormalMatrix(object.modelViewMatrix); material.onBeforeRender(_this, scene, camera2, geometry, object, group); if (material.transparent === true && material.side === DoubleSide) { material.side = BackSide; material.needsUpdate = true; _this.renderBufferDirect(camera2, scene, geometry, material, object, group); material.side = FrontSide; material.needsUpdate = true; _this.renderBufferDirect(camera2, scene, geometry, material, object, group); material.side = DoubleSide; } else { _this.renderBufferDirect(camera2, scene, geometry, material, object, group); } object.onAfterRender(_this, scene, camera2, geometry, material, group); } function getProgram(material, scene, object) { if (scene.isScene !== true) scene = _emptyScene; const materialProperties = properties.get(material); const lights = currentRenderState.state.lights; const shadowsArray = currentRenderState.state.shadowsArray; const lightsStateVersion = lights.state.version; const parameters2 = programCache.getParameters(material, lights.state, shadowsArray, scene, object); const programCacheKey = programCache.getProgramCacheKey(parameters2); let programs = materialProperties.programs; materialProperties.environment = material.isMeshStandardMaterial ? scene.environment : null; materialProperties.fog = scene.fog; materialProperties.envMap = (material.isMeshStandardMaterial ? cubeuvmaps : cubemaps).get(material.envMap || materialProperties.environment); if (programs === void 0) { material.addEventListener("dispose", onMaterialDispose); programs = /* @__PURE__ */ new Map(); materialProperties.programs = programs; } let program = programs.get(programCacheKey); if (program !== void 0) { if (materialProperties.currentProgram === program && materialProperties.lightsStateVersion === lightsStateVersion) { updateCommonMaterialProperties(material, parameters2); return program; } } else { parameters2.uniforms = programCache.getUniforms(material); material.onBuild(object, parameters2, _this); material.onBeforeCompile(parameters2, _this); program = programCache.acquireProgram(parameters2, programCacheKey); programs.set(programCacheKey, program); materialProperties.uniforms = parameters2.uniforms; } const uniforms = materialProperties.uniforms; if (!material.isShaderMaterial && !material.isRawShaderMaterial || material.clipping === true) { uniforms.clippingPlanes = clipping.uniform; } updateCommonMaterialProperties(material, parameters2); materialProperties.needsLights = materialNeedsLights(material); materialProperties.lightsStateVersion = lightsStateVersion; if (materialProperties.needsLights) { uniforms.ambientLightColor.value = lights.state.ambient; uniforms.lightProbe.value = lights.state.probe; uniforms.directionalLights.value = lights.state.directional; uniforms.directionalLightShadows.value = lights.state.directionalShadow; uniforms.spotLights.value = lights.state.spot; uniforms.spotLightShadows.value = lights.state.spotShadow; uniforms.rectAreaLights.value = lights.state.rectArea; uniforms.ltc_1.value = lights.state.rectAreaLTC1; uniforms.ltc_2.value = lights.state.rectAreaLTC2; uniforms.pointLights.value = lights.state.point; uniforms.pointLightShadows.value = lights.state.pointShadow; uniforms.hemisphereLights.value = lights.state.hemi; uniforms.directionalShadowMap.value = lights.state.directionalShadowMap; uniforms.directionalShadowMatrix.value = lights.state.directionalShadowMatrix; uniforms.spotShadowMap.value = lights.state.spotShadowMap; uniforms.spotLightMatrix.value = lights.state.spotLightMatrix; uniforms.spotLightMap.value = lights.state.spotLightMap; uniforms.pointShadowMap.value = lights.state.pointShadowMap; uniforms.pointShadowMatrix.value = lights.state.pointShadowMatrix; } const progUniforms = program.getUniforms(); const uniformsList = WebGLUniforms.seqWithValue(progUniforms.seq, uniforms); materialProperties.currentProgram = program; materialProperties.uniformsList = uniformsList; return program; } function updateCommonMaterialProperties(material, parameters2) { const materialProperties = properties.get(material); materialProperties.outputEncoding = parameters2.outputEncoding; materialProperties.instancing = parameters2.instancing; materialProperties.skinning = parameters2.skinning; materialProperties.morphTargets = parameters2.morphTargets; materialProperties.morphNormals = parameters2.morphNormals; materialProperties.morphColors = parameters2.morphColors; materialProperties.morphTargetsCount = parameters2.morphTargetsCount; materialProperties.numClippingPlanes = parameters2.numClippingPlanes; materialProperties.numIntersection = parameters2.numClipIntersection; materialProperties.vertexAlphas = parameters2.vertexAlphas; materialProperties.vertexTangents = parameters2.vertexTangents; materialProperties.toneMapping = parameters2.toneMapping; } function setProgram(camera2, scene, geometry, material, object) { if (scene.isScene !== true) scene = _emptyScene; textures.resetTextureUnits(); const fog = scene.fog; const environment = material.isMeshStandardMaterial ? scene.environment : null; const encoding = _currentRenderTarget === null ? _this.outputEncoding : _currentRenderTarget.isXRRenderTarget === true ? _currentRenderTarget.texture.encoding : LinearEncoding; const envMap = (material.isMeshStandardMaterial ? cubeuvmaps : cubemaps).get(material.envMap || environment); const vertexAlphas = material.vertexColors === true && !!geometry.attributes.color && geometry.attributes.color.itemSize === 4; const vertexTangents = !!material.normalMap && !!geometry.attributes.tangent; const morphTargets = !!geometry.morphAttributes.position; const morphNormals = !!geometry.morphAttributes.normal; const morphColors = !!geometry.morphAttributes.color; const toneMapping = material.toneMapped ? _this.toneMapping : NoToneMapping; const morphAttribute = geometry.morphAttributes.position || geometry.morphAttributes.normal || geometry.morphAttributes.color; const morphTargetsCount = morphAttribute !== void 0 ? morphAttribute.length : 0; const materialProperties = properties.get(material); const lights = currentRenderState.state.lights; if (_clippingEnabled === true) { if (_localClippingEnabled === true || camera2 !== _currentCamera) { const useCache = camera2 === _currentCamera && material.id === _currentMaterialId; clipping.setState(material, camera2, useCache); } } let needsProgramChange = false; if (material.version === materialProperties.__version) { if (materialProperties.needsLights && materialProperties.lightsStateVersion !== lights.state.version) { needsProgramChange = true; } else if (materialProperties.outputEncoding !== encoding) { needsProgramChange = true; } else if (object.isInstancedMesh && materialProperties.instancing === false) { needsProgramChange = true; } else if (!object.isInstancedMesh && materialProperties.instancing === true) { needsProgramChange = true; } else if (object.isSkinnedMesh && materialProperties.skinning === false) { needsProgramChange = true; } else if (!object.isSkinnedMesh && materialProperties.skinning === true) { needsProgramChange = true; } else if (materialProperties.envMap !== envMap) { needsProgramChange = true; } else if (material.fog === true && materialProperties.fog !== fog) { needsProgramChange = true; } else if (materialProperties.numClippingPlanes !== void 0 && (materialProperties.numClippingPlanes !== clipping.numPlanes || materialProperties.numIntersection !== clipping.numIntersection)) { needsProgramChange = true; } else if (materialProperties.vertexAlphas !== vertexAlphas) { needsProgramChange = true; } else if (materialProperties.vertexTangents !== vertexTangents) { needsProgramChange = true; } else if (materialProperties.morphTargets !== morphTargets) { needsProgramChange = true; } else if (materialProperties.morphNormals !== morphNormals) { needsProgramChange = true; } else if (materialProperties.morphColors !== morphColors) { needsProgramChange = true; } else if (materialProperties.toneMapping !== toneMapping) { needsProgramChange = true; } else if (capabilities.isWebGL2 === true && materialProperties.morphTargetsCount !== morphTargetsCount) { needsProgramChange = true; } } else { needsProgramChange = true; materialProperties.__version = material.version; } let program = materialProperties.currentProgram; if (needsProgramChange === true) { program = getProgram(material, scene, object); } let refreshProgram = false; let refreshMaterial = false; let refreshLights = false; const p_uniforms = program.getUniforms(), m_uniforms = materialProperties.uniforms; if (state.useProgram(program.program)) { refreshProgram = true; refreshMaterial = true; refreshLights = true; } if (material.id !== _currentMaterialId) { _currentMaterialId = material.id; refreshMaterial = true; } if (refreshProgram || _currentCamera !== camera2) { p_uniforms.setValue(_gl, "projectionMatrix", camera2.projectionMatrix); if (capabilities.logarithmicDepthBuffer) { p_uniforms.setValue( _gl, "logDepthBufFC", 2 / (Math.log(camera2.far + 1) / Math.LN2) ); } if (_currentCamera !== camera2) { _currentCamera = camera2; refreshMaterial = true; refreshLights = true; } if (material.isShaderMaterial || material.isMeshPhongMaterial || material.isMeshToonMaterial || material.isMeshStandardMaterial || material.envMap) { const uCamPos = p_uniforms.map.cameraPosition; if (uCamPos !== void 0) { uCamPos.setValue( _gl, _vector32.setFromMatrixPosition(camera2.matrixWorld) ); } } if (material.isMeshPhongMaterial || material.isMeshToonMaterial || material.isMeshLambertMaterial || material.isMeshBasicMaterial || material.isMeshStandardMaterial || material.isShaderMaterial) { p_uniforms.setValue(_gl, "isOrthographic", camera2.isOrthographicCamera === true); } if (material.isMeshPhongMaterial || material.isMeshToonMaterial || material.isMeshLambertMaterial || material.isMeshBasicMaterial || material.isMeshStandardMaterial || material.isShaderMaterial || material.isShadowMaterial || object.isSkinnedMesh) { p_uniforms.setValue(_gl, "viewMatrix", camera2.matrixWorldInverse); } } if (object.isSkinnedMesh) { p_uniforms.setOptional(_gl, object, "bindMatrix"); p_uniforms.setOptional(_gl, object, "bindMatrixInverse"); const skeleton = object.skeleton; if (skeleton) { if (capabilities.floatVertexTextures) { if (skeleton.boneTexture === null) skeleton.computeBoneTexture(); p_uniforms.setValue(_gl, "boneTexture", skeleton.boneTexture, textures); p_uniforms.setValue(_gl, "boneTextureSize", skeleton.boneTextureSize); } else { console.warn("THREE.WebGLRenderer: SkinnedMesh can only be used with WebGL 2. With WebGL 1 OES_texture_float and vertex textures support is required."); } } } const morphAttributes = geometry.morphAttributes; if (morphAttributes.position !== void 0 || morphAttributes.normal !== void 0 || morphAttributes.color !== void 0 && capabilities.isWebGL2 === true) { morphtargets.update(object, geometry, material, program); } if (refreshMaterial || materialProperties.receiveShadow !== object.receiveShadow) { materialProperties.receiveShadow = object.receiveShadow; p_uniforms.setValue(_gl, "receiveShadow", object.receiveShadow); } if (material.isMeshGouraudMaterial && material.envMap !== null) { m_uniforms.envMap.value = envMap; m_uniforms.flipEnvMap.value = envMap.isCubeTexture && envMap.isRenderTargetTexture === false ? -1 : 1; } if (refreshMaterial) { p_uniforms.setValue(_gl, "toneMappingExposure", _this.toneMappingExposure); if (materialProperties.needsLights) { markUniformsLightsNeedsUpdate(m_uniforms, refreshLights); } if (fog && material.fog === true) { materials.refreshFogUniforms(m_uniforms, fog); } materials.refreshMaterialUniforms(m_uniforms, material, _pixelRatio, _height, _transmissionRenderTarget); WebGLUniforms.upload(_gl, materialProperties.uniformsList, m_uniforms, textures); } if (material.isShaderMaterial && material.uniformsNeedUpdate === true) { WebGLUniforms.upload(_gl, materialProperties.uniformsList, m_uniforms, textures); material.uniformsNeedUpdate = false; } if (material.isSpriteMaterial) { p_uniforms.setValue(_gl, "center", object.center); } p_uniforms.setValue(_gl, "modelViewMatrix", object.modelViewMatrix); p_uniforms.setValue(_gl, "normalMatrix", object.normalMatrix); p_uniforms.setValue(_gl, "modelMatrix", object.matrixWorld); if (material.isShaderMaterial || material.isRawShaderMaterial) { const groups = material.uniformsGroups; for (let i = 0, l = groups.length; i < l; i++) { if (capabilities.isWebGL2) { const group = groups[i]; uniformsGroups.update(group, program); uniformsGroups.bind(group, program); } else { console.warn("THREE.WebGLRenderer: Uniform Buffer Objects can only be used with WebGL 2."); } } } return program; } function markUniformsLightsNeedsUpdate(uniforms, value) { uniforms.ambientLightColor.needsUpdate = value; uniforms.lightProbe.needsUpdate = value; uniforms.directionalLights.needsUpdate = value; uniforms.directionalLightShadows.needsUpdate = value; uniforms.pointLights.needsUpdate = value; uniforms.pointLightShadows.needsUpdate = value; uniforms.spotLights.needsUpdate = value; uniforms.spotLightShadows.needsUpdate = value; uniforms.rectAreaLights.needsUpdate = value; uniforms.hemisphereLights.needsUpdate = value; } function materialNeedsLights(material) { return material.isMeshLambertMaterial || material.isMeshToonMaterial || material.isMeshPhongMaterial || material.isMeshStandardMaterial || material.isShadowMaterial || material.isShaderMaterial && material.lights === true; } this.getActiveCubeFace = function() { return _currentActiveCubeFace; }; this.getActiveMipmapLevel = function() { return _currentActiveMipmapLevel; }; this.getRenderTarget = function() { return _currentRenderTarget; }; this.setRenderTargetTextures = function(renderTarget, colorTexture, depthTexture) { properties.get(renderTarget.texture).__webglTexture = colorTexture; properties.get(renderTarget.depthTexture).__webglTexture = depthTexture; const renderTargetProperties = properties.get(renderTarget); renderTargetProperties.__hasExternalTextures = true; if (renderTargetProperties.__hasExternalTextures) { renderTargetProperties.__autoAllocateDepthBuffer = depthTexture === void 0; if (!renderTargetProperties.__autoAllocateDepthBuffer) { if (extensions.has("WEBGL_multisampled_render_to_texture") === true) { console.warn("THREE.WebGLRenderer: Render-to-texture extension was disabled because an external texture was provided"); renderTargetProperties.__useRenderToTexture = false; } } } }; this.setRenderTargetFramebuffer = function(renderTarget, defaultFramebuffer) { const renderTargetProperties = properties.get(renderTarget); renderTargetProperties.__webglFramebuffer = defaultFramebuffer; renderTargetProperties.__useDefaultFramebuffer = defaultFramebuffer === void 0; }; this.setRenderTarget = function(renderTarget, activeCubeFace = 0, activeMipmapLevel = 0) { _currentRenderTarget = renderTarget; _currentActiveCubeFace = activeCubeFace; _currentActiveMipmapLevel = activeMipmapLevel; let useDefaultFramebuffer = true; let framebuffer = null; let isCube = false; let isRenderTarget3D = false; if (renderTarget) { const renderTargetProperties = properties.get(renderTarget); if (renderTargetProperties.__useDefaultFramebuffer !== void 0) { state.bindFramebuffer(36160, null); useDefaultFramebuffer = false; } else if (renderTargetProperties.__webglFramebuffer === void 0) { textures.setupRenderTarget(renderTarget); } else if (renderTargetProperties.__hasExternalTextures) { textures.rebindTextures(renderTarget, properties.get(renderTarget.texture).__webglTexture, properties.get(renderTarget.depthTexture).__webglTexture); } const texture = renderTarget.texture; if (texture.isData3DTexture || texture.isDataArrayTexture || texture.isCompressedArrayTexture) { isRenderTarget3D = true; } const __webglFramebuffer = properties.get(renderTarget).__webglFramebuffer; if (renderTarget.isWebGLCubeRenderTarget) { framebuffer = __webglFramebuffer[activeCubeFace]; isCube = true; } else if (capabilities.isWebGL2 && renderTarget.samples > 0 && textures.useMultisampledRTT(renderTarget) === false) { framebuffer = properties.get(renderTarget).__webglMultisampledFramebuffer; } else { framebuffer = __webglFramebuffer; } _currentViewport.copy(renderTarget.viewport); _currentScissor.copy(renderTarget.scissor); _currentScissorTest = renderTarget.scissorTest; } else { _currentViewport.copy(_viewport).multiplyScalar(_pixelRatio).floor(); _currentScissor.copy(_scissor).multiplyScalar(_pixelRatio).floor(); _currentScissorTest = _scissorTest; } const framebufferBound = state.bindFramebuffer(36160, framebuffer); if (framebufferBound && capabilities.drawBuffers && useDefaultFramebuffer) { state.drawBuffers(renderTarget, framebuffer); } state.viewport(_currentViewport); state.scissor(_currentScissor); state.setScissorTest(_currentScissorTest); if (isCube) { const textureProperties = properties.get(renderTarget.texture); _gl.framebufferTexture2D(36160, 36064, 34069 + activeCubeFace, textureProperties.__webglTexture, activeMipmapLevel); } else if (isRenderTarget3D) { const textureProperties = properties.get(renderTarget.texture); const layer = activeCubeFace || 0; _gl.framebufferTextureLayer(36160, 36064, textureProperties.__webglTexture, activeMipmapLevel || 0, layer); } _currentMaterialId = -1; }; this.readRenderTargetPixels = function(renderTarget, x2, y, width, height, buffer, activeCubeFaceIndex) { if (!(renderTarget && renderTarget.isWebGLRenderTarget)) { console.error("THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not THREE.WebGLRenderTarget."); return; } let framebuffer = properties.get(renderTarget).__webglFramebuffer; if (renderTarget.isWebGLCubeRenderTarget && activeCubeFaceIndex !== void 0) { framebuffer = framebuffer[activeCubeFaceIndex]; } if (framebuffer) { state.bindFramebuffer(36160, framebuffer); try { const texture = renderTarget.texture; const textureFormat = texture.format; const textureType = texture.type; if (textureFormat !== RGBAFormat && utils.convert(textureFormat) !== _gl.getParameter(35739)) { console.error("THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not in RGBA or implementation defined format."); return; } const halfFloatSupportedByExt = textureType === HalfFloatType && (extensions.has("EXT_color_buffer_half_float") || capabilities.isWebGL2 && extensions.has("EXT_color_buffer_float")); if (textureType !== UnsignedByteType && utils.convert(textureType) !== _gl.getParameter(35738) && // Edge and Chrome Mac < 52 (#9513) !(textureType === FloatType && (capabilities.isWebGL2 || extensions.has("OES_texture_float") || extensions.has("WEBGL_color_buffer_float"))) && // Chrome Mac >= 52 and Firefox !halfFloatSupportedByExt) { console.error("THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not in UnsignedByteType or implementation defined type."); return; } if (x2 >= 0 && x2 <= renderTarget.width - width && (y >= 0 && y <= renderTarget.height - height)) { _gl.readPixels(x2, y, width, height, utils.convert(textureFormat), utils.convert(textureType), buffer); } } finally { const framebuffer2 = _currentRenderTarget !== null ? properties.get(_currentRenderTarget).__webglFramebuffer : null; state.bindFramebuffer(36160, framebuffer2); } } }; this.copyFramebufferToTexture = function(position, texture, level = 0) { const levelScale = Math.pow(2, -level); const width = Math.floor(texture.image.width * levelScale); const height = Math.floor(texture.image.height * levelScale); textures.setTexture2D(texture, 0); _gl.copyTexSubImage2D(3553, level, 0, 0, position.x, position.y, width, height); state.unbindTexture(); }; this.copyTextureToTexture = function(position, srcTexture, dstTexture, level = 0) { const width = srcTexture.image.width; const height = srcTexture.image.height; const glFormat = utils.convert(dstTexture.format); const glType = utils.convert(dstTexture.type); textures.setTexture2D(dstTexture, 0); _gl.pixelStorei(37440, dstTexture.flipY); _gl.pixelStorei(37441, dstTexture.premultiplyAlpha); _gl.pixelStorei(3317, dstTexture.unpackAlignment); if (srcTexture.isDataTexture) { _gl.texSubImage2D(3553, level, position.x, position.y, width, height, glFormat, glType, srcTexture.image.data); } else { if (srcTexture.isCompressedTexture) { _gl.compressedTexSubImage2D(3553, level, position.x, position.y, srcTexture.mipmaps[0].width, srcTexture.mipmaps[0].height, glFormat, srcTexture.mipmaps[0].data); } else { _gl.texSubImage2D(3553, level, position.x, position.y, glFormat, glType, srcTexture.image); } } if (level === 0 && dstTexture.generateMipmaps) _gl.generateMipmap(3553); state.unbindTexture(); }; this.copyTextureToTexture3D = function(sourceBox, position, srcTexture, dstTexture, level = 0) { if (_this.isWebGL1Renderer) { console.warn("THREE.WebGLRenderer.copyTextureToTexture3D: can only be used with WebGL2."); return; } const width = sourceBox.max.x - sourceBox.min.x + 1; const height = sourceBox.max.y - sourceBox.min.y + 1; const depth = sourceBox.max.z - sourceBox.min.z + 1; const glFormat = utils.convert(dstTexture.format); const glType = utils.convert(dstTexture.type); let glTarget; if (dstTexture.isData3DTexture) { textures.setTexture3D(dstTexture, 0); glTarget = 32879; } else if (dstTexture.isDataArrayTexture) { textures.setTexture2DArray(dstTexture, 0); glTarget = 35866; } else { console.warn("THREE.WebGLRenderer.copyTextureToTexture3D: only supports THREE.DataTexture3D and THREE.DataTexture2DArray."); return; } _gl.pixelStorei(37440, dstTexture.flipY); _gl.pixelStorei(37441, dstTexture.premultiplyAlpha); _gl.pixelStorei(3317, dstTexture.unpackAlignment); const unpackRowLen = _gl.getParameter(3314); const unpackImageHeight = _gl.getParameter(32878); const unpackSkipPixels = _gl.getParameter(3316); const unpackSkipRows = _gl.getParameter(3315); const unpackSkipImages = _gl.getParameter(32877); const image = srcTexture.isCompressedTexture ? srcTexture.mipmaps[0] : srcTexture.image; _gl.pixelStorei(3314, image.width); _gl.pixelStorei(32878, image.height); _gl.pixelStorei(3316, sourceBox.min.x); _gl.pixelStorei(3315, sourceBox.min.y); _gl.pixelStorei(32877, sourceBox.min.z); if (srcTexture.isDataTexture || srcTexture.isData3DTexture) { _gl.texSubImage3D(glTarget, level, position.x, position.y, position.z, width, height, depth, glFormat, glType, image.data); } else { if (srcTexture.isCompressedArrayTexture) { console.warn("THREE.WebGLRenderer.copyTextureToTexture3D: untested support for compressed srcTexture."); _gl.compressedTexSubImage3D(glTarget, level, position.x, position.y, position.z, width, height, depth, glFormat, image.data); } else { _gl.texSubImage3D(glTarget, level, position.x, position.y, position.z, width, height, depth, glFormat, glType, image); } } _gl.pixelStorei(3314, unpackRowLen); _gl.pixelStorei(32878, unpackImageHeight); _gl.pixelStorei(3316, unpackSkipPixels); _gl.pixelStorei(3315, unpackSkipRows); _gl.pixelStorei(32877, unpackSkipImages); if (level === 0 && dstTexture.generateMipmaps) _gl.generateMipmap(glTarget); state.unbindTexture(); }; this.initTexture = function(texture) { if (texture.isCubeTexture) { textures.setTextureCube(texture, 0); } else if (texture.isData3DTexture) { textures.setTexture3D(texture, 0); } else if (texture.isDataArrayTexture || texture.isCompressedArrayTexture) { textures.setTexture2DArray(texture, 0); } else { textures.setTexture2D(texture, 0); } state.unbindTexture(); }; this.resetState = function() { _currentActiveCubeFace = 0; _currentActiveMipmapLevel = 0; _currentRenderTarget = null; state.reset(); bindingStates.reset(); }; if (typeof __THREE_DEVTOOLS__ !== "undefined") { __THREE_DEVTOOLS__.dispatchEvent(new CustomEvent("observe", { detail: this })); } } var WebGL1Renderer = class extends WebGLRenderer { }; WebGL1Renderer.prototype.isWebGL1Renderer = true; var Scene = class extends Object3D { constructor() { super(); this.isScene = true; this.type = "Scene"; this.background = null; this.environment = null; this.fog = null; this.backgroundBlurriness = 0; this.overrideMaterial = null; if (typeof __THREE_DEVTOOLS__ !== "undefined") { __THREE_DEVTOOLS__.dispatchEvent(new CustomEvent("observe", { detail: this })); } } copy(source, recursive) { super.copy(source, recursive); if (source.background !== null) this.background = source.background.clone(); if (source.environment !== null) this.environment = source.environment.clone(); if (source.fog !== null) this.fog = source.fog.clone(); this.backgroundBlurriness = source.backgroundBlurriness; if (source.overrideMaterial !== null) this.overrideMaterial = source.overrideMaterial.clone(); this.matrixAutoUpdate = source.matrixAutoUpdate; return this; } toJSON(meta) { const data = super.toJSON(meta); if (this.fog !== null) data.object.fog = this.fog.toJSON(); if (this.backgroundBlurriness > 0) data.backgroundBlurriness = this.backgroundBlurriness; return data; } // @deprecated get autoUpdate() { console.warn("THREE.Scene: autoUpdate was renamed to matrixWorldAutoUpdate in r144."); return this.matrixWorldAutoUpdate; } set autoUpdate(value) { console.warn("THREE.Scene: autoUpdate was renamed to matrixWorldAutoUpdate in r144."); this.matrixWorldAutoUpdate = value; } }; var InterleavedBuffer = class { constructor(array, stride) { this.isInterleavedBuffer = true; this.array = array; this.stride = stride; this.count = array !== void 0 ? array.length / stride : 0; this.usage = StaticDrawUsage; this.updateRange = { offset: 0, count: -1 }; this.version = 0; this.uuid = generateUUID(); } onUploadCallback() { } set needsUpdate(value) { if (value === true) this.version++; } setUsage(value) { this.usage = value; return this; } copy(source) { this.array = new source.array.constructor(source.array); this.count = source.count; this.stride = source.stride; this.usage = source.usage; return this; } copyAt(index1, attribute, index2) { index1 *= this.stride; index2 *= attribute.stride; for (let i = 0, l = this.stride; i < l; i++) { this.array[index1 + i] = attribute.array[index2 + i]; } return this; } set(value, offset = 0) { this.array.set(value, offset); return this; } clone(data) { if (data.arrayBuffers === void 0) { data.arrayBuffers = {}; } if (this.array.buffer._uuid === void 0) { this.array.buffer._uuid = generateUUID(); } if (data.arrayBuffers[this.array.buffer._uuid] === void 0) { data.arrayBuffers[this.array.buffer._uuid] = this.array.slice(0).buffer; } const array = new this.array.constructor(data.arrayBuffers[this.array.buffer._uuid]); const ib = new this.constructor(array, this.stride); ib.setUsage(this.usage); return ib; } onUpload(callback) { this.onUploadCallback = callback; return this; } toJSON(data) { if (data.arrayBuffers === void 0) { data.arrayBuffers = {}; } if (this.array.buffer._uuid === void 0) { this.array.buffer._uuid = generateUUID(); } if (data.arrayBuffers[this.array.buffer._uuid] === void 0) { data.arrayBuffers[this.array.buffer._uuid] = Array.from(new Uint32Array(this.array.buffer)); } return { uuid: this.uuid, buffer: this.array.buffer._uuid, type: this.array.constructor.name, stride: this.stride }; } }; var _vector$6 = new Vector3(); var InterleavedBufferAttribute = class _InterleavedBufferAttribute { constructor(interleavedBuffer, itemSize, offset, normalized = false) { this.isInterleavedBufferAttribute = true; this.name = ""; this.data = interleavedBuffer; this.itemSize = itemSize; this.offset = offset; this.normalized = normalized === true; } get count() { return this.data.count; } get array() { return this.data.array; } set needsUpdate(value) { this.data.needsUpdate = value; } applyMatrix4(m) { for (let i = 0, l = this.data.count; i < l; i++) { _vector$6.fromBufferAttribute(this, i); _vector$6.applyMatrix4(m); this.setXYZ(i, _vector$6.x, _vector$6.y, _vector$6.z); } return this; } applyNormalMatrix(m) { for (let i = 0, l = this.count; i < l; i++) { _vector$6.fromBufferAttribute(this, i); _vector$6.applyNormalMatrix(m); this.setXYZ(i, _vector$6.x, _vector$6.y, _vector$6.z); } return this; } transformDirection(m) { for (let i = 0, l = this.count; i < l; i++) { _vector$6.fromBufferAttribute(this, i); _vector$6.transformDirection(m); this.setXYZ(i, _vector$6.x, _vector$6.y, _vector$6.z); } return this; } setX(index, x2) { if (this.normalized) x2 = normalize(x2, this.array); this.data.array[index * this.data.stride + this.offset] = x2; return this; } setY(index, y) { if (this.normalized) y = normalize(y, this.array); this.data.array[index * this.data.stride + this.offset + 1] = y; return this; } setZ(index, z) { if (this.normalized) z = normalize(z, this.array); this.data.array[index * this.data.stride + this.offset + 2] = z; return this; } setW(index, w) { if (this.normalized) w = normalize(w, this.array); this.data.array[index * this.data.stride + this.offset + 3] = w; return this; } getX(index) { let x2 = this.data.array[index * this.data.stride + this.offset]; if (this.normalized) x2 = denormalize(x2, this.array); return x2; } getY(index) { let y = this.data.array[index * this.data.stride + this.offset + 1]; if (this.normalized) y = denormalize(y, this.array); return y; } getZ(index) { let z = this.data.array[index * this.data.stride + this.offset + 2]; if (this.normalized) z = denormalize(z, this.array); return z; } getW(index) { let w = this.data.array[index * this.data.stride + this.offset + 3]; if (this.normalized) w = denormalize(w, this.array); return w; } setXY(index, x2, y) { index = index * this.data.stride + this.offset; if (this.normalized) { x2 = normalize(x2, this.array); y = normalize(y, this.array); } this.data.array[index + 0] = x2; this.data.array[index + 1] = y; return this; } setXYZ(index, x2, y, z) { index = index * this.data.stride + this.offset; if (this.normalized) { x2 = normalize(x2, this.array); y = normalize(y, this.array); z = normalize(z, this.array); } this.data.array[index + 0] = x2; this.data.array[index + 1] = y; this.data.array[index + 2] = z; return this; } setXYZW(index, x2, y, z, w) { index = index * this.data.stride + this.offset; if (this.normalized) { x2 = normalize(x2, this.array); y = normalize(y, this.array); z = normalize(z, this.array); w = normalize(w, this.array); } this.data.array[index + 0] = x2; this.data.array[index + 1] = y; this.data.array[index + 2] = z; this.data.array[index + 3] = w; return this; } clone(data) { if (data === void 0) { console.log("THREE.InterleavedBufferAttribute.clone(): Cloning an interleaved buffer attribute will deinterleave buffer data."); const array = []; for (let i = 0; i < this.count; i++) { const index = i * this.data.stride + this.offset; for (let j = 0; j < this.itemSize; j++) { array.push(this.data.array[index + j]); } } return new BufferAttribute(new this.array.constructor(array), this.itemSize, this.normalized); } else { if (data.interleavedBuffers === void 0) { data.interleavedBuffers = {}; } if (data.interleavedBuffers[this.data.uuid] === void 0) { data.interleavedBuffers[this.data.uuid] = this.data.clone(data); } return new _InterleavedBufferAttribute(data.interleavedBuffers[this.data.uuid], this.itemSize, this.offset, this.normalized); } } toJSON(data) { if (data === void 0) { console.log("THREE.InterleavedBufferAttribute.toJSON(): Serializing an interleaved buffer attribute will deinterleave buffer data."); const array = []; for (let i = 0; i < this.count; i++) { const index = i * this.data.stride + this.offset; for (let j = 0; j < this.itemSize; j++) { array.push(this.data.array[index + j]); } } return { itemSize: this.itemSize, type: this.array.constructor.name, array, normalized: this.normalized }; } else { if (data.interleavedBuffers === void 0) { data.interleavedBuffers = {}; } if (data.interleavedBuffers[this.data.uuid] === void 0) { data.interleavedBuffers[this.data.uuid] = this.data.toJSON(data); } return { isInterleavedBufferAttribute: true, itemSize: this.itemSize, data: this.data.uuid, offset: this.offset, normalized: this.normalized }; } } }; var _intersectPoint = new Vector3(); var _worldScale = new Vector3(); var _mvPosition = new Vector3(); var _alignedPosition = new Vector2(); var _rotatedPosition = new Vector2(); var _viewWorldMatrix = new Matrix4(); var _vA = new Vector3(); var _vB = new Vector3(); var _vC = new Vector3(); var _uvA = new Vector2(); var _uvB = new Vector2(); var _uvC = new Vector2(); var _v1$2 = new Vector3(); var _v2$1 = new Vector3(); var _basePosition = new Vector3(); var _skinIndex = new Vector4(); var _skinWeight = new Vector4(); var _vector$5 = new Vector3(); var _matrix = new Matrix4(); var SkinnedMesh = class extends Mesh { constructor(geometry, material) { super(geometry, material); this.isSkinnedMesh = true; this.type = "SkinnedMesh"; this.bindMode = "attached"; this.bindMatrix = new Matrix4(); this.bindMatrixInverse = new Matrix4(); } copy(source, recursive) { super.copy(source, recursive); this.bindMode = source.bindMode; this.bindMatrix.copy(source.bindMatrix); this.bindMatrixInverse.copy(source.bindMatrixInverse); this.skeleton = source.skeleton; return this; } bind(skeleton, bindMatrix) { this.skeleton = skeleton; if (bindMatrix === void 0) { this.updateMatrixWorld(true); this.skeleton.calculateInverses(); bindMatrix = this.matrixWorld; } this.bindMatrix.copy(bindMatrix); this.bindMatrixInverse.copy(bindMatrix).invert(); } pose() { this.skeleton.pose(); } normalizeSkinWeights() { const vector = new Vector4(); const skinWeight = this.geometry.attributes.skinWeight; for (let i = 0, l = skinWeight.count; i < l; i++) { vector.fromBufferAttribute(skinWeight, i); const scale = 1 / vector.manhattanLength(); if (scale !== Infinity) { vector.multiplyScalar(scale); } else { vector.set(1, 0, 0, 0); } skinWeight.setXYZW(i, vector.x, vector.y, vector.z, vector.w); } } updateMatrixWorld(force) { super.updateMatrixWorld(force); if (this.bindMode === "attached") { this.bindMatrixInverse.copy(this.matrixWorld).invert(); } else if (this.bindMode === "detached") { this.bindMatrixInverse.copy(this.bindMatrix).invert(); } else { console.warn("THREE.SkinnedMesh: Unrecognized bindMode: " + this.bindMode); } } boneTransform(index, target2) { const skeleton = this.skeleton; const geometry = this.geometry; _skinIndex.fromBufferAttribute(geometry.attributes.skinIndex, index); _skinWeight.fromBufferAttribute(geometry.attributes.skinWeight, index); _basePosition.copy(target2).applyMatrix4(this.bindMatrix); target2.set(0, 0, 0); for (let i = 0; i < 4; i++) { const weight = _skinWeight.getComponent(i); if (weight !== 0) { const boneIndex = _skinIndex.getComponent(i); _matrix.multiplyMatrices(skeleton.bones[boneIndex].matrixWorld, skeleton.boneInverses[boneIndex]); target2.addScaledVector(_vector$5.copy(_basePosition).applyMatrix4(_matrix), weight); } } return target2.applyMatrix4(this.bindMatrixInverse); } }; var Bone = class extends Object3D { constructor() { super(); this.isBone = true; this.type = "Bone"; } }; var DataTexture = class extends Texture { constructor(data = null, width = 1, height = 1, format, type, mapping, wrapS, wrapT, magFilter = NearestFilter, minFilter = NearestFilter, anisotropy, encoding) { super(null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, encoding); this.isDataTexture = true; this.image = { data, width, height }; this.generateMipmaps = false; this.flipY = false; this.unpackAlignment = 1; } }; var _offsetMatrix = new Matrix4(); var _identityMatrix = new Matrix4(); var Skeleton = class _Skeleton { constructor(bones = [], boneInverses = []) { this.uuid = generateUUID(); this.bones = bones.slice(0); this.boneInverses = boneInverses; this.boneMatrices = null; this.boneTexture = null; this.boneTextureSize = 0; this.frame = -1; this.init(); } init() { const bones = this.bones; const boneInverses = this.boneInverses; this.boneMatrices = new Float32Array(bones.length * 16); if (boneInverses.length === 0) { this.calculateInverses(); } else { if (bones.length !== boneInverses.length) { console.warn("THREE.Skeleton: Number of inverse bone matrices does not match amount of bones."); this.boneInverses = []; for (let i = 0, il = this.bones.length; i < il; i++) { this.boneInverses.push(new Matrix4()); } } } } calculateInverses() { this.boneInverses.length = 0; for (let i = 0, il = this.bones.length; i < il; i++) { const inverse = new Matrix4(); if (this.bones[i]) { inverse.copy(this.bones[i].matrixWorld).invert(); } this.boneInverses.push(inverse); } } pose() { for (let i = 0, il = this.bones.length; i < il; i++) { const bone = this.bones[i]; if (bone) { bone.matrixWorld.copy(this.boneInverses[i]).invert(); } } for (let i = 0, il = this.bones.length; i < il; i++) { const bone = this.bones[i]; if (bone) { if (bone.parent && bone.parent.isBone) { bone.matrix.copy(bone.parent.matrixWorld).invert(); bone.matrix.multiply(bone.matrixWorld); } else { bone.matrix.copy(bone.matrixWorld); } bone.matrix.decompose(bone.position, bone.quaternion, bone.scale); } } } update() { const bones = this.bones; const boneInverses = this.boneInverses; const boneMatrices = this.boneMatrices; const boneTexture = this.boneTexture; for (let i = 0, il = bones.length; i < il; i++) { const matrix = bones[i] ? bones[i].matrixWorld : _identityMatrix; _offsetMatrix.multiplyMatrices(matrix, boneInverses[i]); _offsetMatrix.toArray(boneMatrices, i * 16); } if (boneTexture !== null) { boneTexture.needsUpdate = true; } } clone() { return new _Skeleton(this.bones, this.boneInverses); } computeBoneTexture() { let size = Math.sqrt(this.bones.length * 4); size = ceilPowerOfTwo(size); size = Math.max(size, 4); const boneMatrices = new Float32Array(size * size * 4); boneMatrices.set(this.boneMatrices); const boneTexture = new DataTexture(boneMatrices, size, size, RGBAFormat, FloatType); boneTexture.needsUpdate = true; this.boneMatrices = boneMatrices; this.boneTexture = boneTexture; this.boneTextureSize = size; return this; } getBoneByName(name) { for (let i = 0, il = this.bones.length; i < il; i++) { const bone = this.bones[i]; if (bone.name === name) { return bone; } } return void 0; } dispose() { if (this.boneTexture !== null) { this.boneTexture.dispose(); this.boneTexture = null; } } fromJSON(json, bones) { this.uuid = json.uuid; for (let i = 0, l = json.bones.length; i < l; i++) { const uuid = json.bones[i]; let bone = bones[uuid]; if (bone === void 0) { console.warn("THREE.Skeleton: No bone found with UUID:", uuid); bone = new Bone(); } this.bones.push(bone); this.boneInverses.push(new Matrix4().fromArray(json.boneInverses[i])); } this.init(); return this; } toJSON() { const data = { metadata: { version: 4.5, type: "Skeleton", generator: "Skeleton.toJSON" }, bones: [], boneInverses: [] }; data.uuid = this.uuid; const bones = this.bones; const boneInverses = this.boneInverses; for (let i = 0, l = bones.length; i < l; i++) { const bone = bones[i]; data.bones.push(bone.uuid); const boneInverse = boneInverses[i]; data.boneInverses.push(boneInverse.toArray()); } return data; } }; var InstancedBufferAttribute = class extends BufferAttribute { constructor(array, itemSize, normalized, meshPerAttribute = 1) { super(array, itemSize, normalized); this.isInstancedBufferAttribute = true; this.meshPerAttribute = meshPerAttribute; } copy(source) { super.copy(source); this.meshPerAttribute = source.meshPerAttribute; return this; } toJSON() { const data = super.toJSON(); data.meshPerAttribute = this.meshPerAttribute; data.isInstancedBufferAttribute = true; return data; } }; var _instanceLocalMatrix = new Matrix4(); var _instanceWorldMatrix = new Matrix4(); var _instanceIntersects = []; var _identity = new Matrix4(); var _mesh = new Mesh(); var InstancedMesh = class extends Mesh { constructor(geometry, material, count) { super(geometry, material); this.isInstancedMesh = true; this.instanceMatrix = new InstancedBufferAttribute(new Float32Array(count * 16), 16); this.instanceColor = null; this.count = count; this.frustumCulled = false; for (let i = 0; i < count; i++) { this.setMatrixAt(i, _identity); } } copy(source, recursive) { super.copy(source, recursive); this.instanceMatrix.copy(source.instanceMatrix); if (source.instanceColor !== null) this.instanceColor = source.instanceColor.clone(); this.count = source.count; return this; } getColorAt(index, color) { color.fromArray(this.instanceColor.array, index * 3); } getMatrixAt(index, matrix) { matrix.fromArray(this.instanceMatrix.array, index * 16); } raycast(raycaster2, intersects2) { const matrixWorld = this.matrixWorld; const raycastTimes = this.count; _mesh.geometry = this.geometry; _mesh.material = this.material; if (_mesh.material === void 0) return; for (let instanceId = 0; instanceId < raycastTimes; instanceId++) { this.getMatrixAt(instanceId, _instanceLocalMatrix); _instanceWorldMatrix.multiplyMatrices(matrixWorld, _instanceLocalMatrix); _mesh.matrixWorld = _instanceWorldMatrix; _mesh.raycast(raycaster2, _instanceIntersects); for (let i = 0, l = _instanceIntersects.length; i < l; i++) { const intersect = _instanceIntersects[i]; intersect.instanceId = instanceId; intersect.object = this; intersects2.push(intersect); } _instanceIntersects.length = 0; } } setColorAt(index, color) { if (this.instanceColor === null) { this.instanceColor = new InstancedBufferAttribute(new Float32Array(this.instanceMatrix.count * 3), 3); } color.toArray(this.instanceColor.array, index * 3); } setMatrixAt(index, matrix) { matrix.toArray(this.instanceMatrix.array, index * 16); } updateMorphTargets() { } dispose() { this.dispatchEvent({ type: "dispose" }); } }; var LineBasicMaterial = class extends Material { constructor(parameters) { super(); this.isLineBasicMaterial = true; this.type = "LineBasicMaterial"; this.color = new Color(16777215); this.linewidth = 1; this.linecap = "round"; this.linejoin = "round"; this.fog = true; this.setValues(parameters); } copy(source) { super.copy(source); this.color.copy(source.color); this.linewidth = source.linewidth; this.linecap = source.linecap; this.linejoin = source.linejoin; this.fog = source.fog; return this; } }; var _start$1 = new Vector3(); var _end$1 = new Vector3(); var _inverseMatrix$1 = new Matrix4(); var _ray$1 = new Ray(); var _sphere$1 = new Sphere(); var Line = class extends Object3D { constructor(geometry = new BufferGeometry(), material = new LineBasicMaterial()) { super(); this.isLine = true; this.type = "Line"; this.geometry = geometry; this.material = material; this.updateMorphTargets(); } copy(source, recursive) { super.copy(source, recursive); this.material = source.material; this.geometry = source.geometry; return this; } computeLineDistances() { const geometry = this.geometry; if (geometry.index === null) { const positionAttribute = geometry.attributes.position; const lineDistances = [0]; for (let i = 1, l = positionAttribute.count; i < l; i++) { _start$1.fromBufferAttribute(positionAttribute, i - 1); _end$1.fromBufferAttribute(positionAttribute, i); lineDistances[i] = lineDistances[i - 1]; lineDistances[i] += _start$1.distanceTo(_end$1); } geometry.setAttribute("lineDistance", new Float32BufferAttribute(lineDistances, 1)); } else { console.warn("THREE.Line.computeLineDistances(): Computation only possible with non-indexed BufferGeometry."); } return this; } raycast(raycaster2, intersects2) { const geometry = this.geometry; const matrixWorld = this.matrixWorld; const threshold = raycaster2.params.Line.threshold; const drawRange = geometry.drawRange; if (geometry.boundingSphere === null) geometry.computeBoundingSphere(); _sphere$1.copy(geometry.boundingSphere); _sphere$1.applyMatrix4(matrixWorld); _sphere$1.radius += threshold; if (raycaster2.ray.intersectsSphere(_sphere$1) === false) return; _inverseMatrix$1.copy(matrixWorld).invert(); _ray$1.copy(raycaster2.ray).applyMatrix4(_inverseMatrix$1); const localThreshold = threshold / ((this.scale.x + this.scale.y + this.scale.z) / 3); const localThresholdSq = localThreshold * localThreshold; const vStart = new Vector3(); const vEnd = new Vector3(); const interSegment = new Vector3(); const interRay = new Vector3(); const step = this.isLineSegments ? 2 : 1; const index = geometry.index; const attributes = geometry.attributes; const positionAttribute = attributes.position; if (index !== null) { const start = Math.max(0, drawRange.start); const end = Math.min(index.count, drawRange.start + drawRange.count); for (let i = start, l = end - 1; i < l; i += step) { const a = index.getX(i); const b = index.getX(i + 1); vStart.fromBufferAttribute(positionAttribute, a); vEnd.fromBufferAttribute(positionAttribute, b); const distSq = _ray$1.distanceSqToSegment(vStart, vEnd, interRay, interSegment); if (distSq > localThresholdSq) continue; interRay.applyMatrix4(this.matrixWorld); const distance = raycaster2.ray.origin.distanceTo(interRay); if (distance < raycaster2.near || distance > raycaster2.far) continue; intersects2.push({ distance, // What do we want? intersection point on the ray or on the segment?? // point: raycaster.ray.at( distance ), point: interSegment.clone().applyMatrix4(this.matrixWorld), index: i, face: null, faceIndex: null, object: this }); } } else { const start = Math.max(0, drawRange.start); const end = Math.min(positionAttribute.count, drawRange.start + drawRange.count); for (let i = start, l = end - 1; i < l; i += step) { vStart.fromBufferAttribute(positionAttribute, i); vEnd.fromBufferAttribute(positionAttribute, i + 1); const distSq = _ray$1.distanceSqToSegment(vStart, vEnd, interRay, interSegment); if (distSq > localThresholdSq) continue; interRay.applyMatrix4(this.matrixWorld); const distance = raycaster2.ray.origin.distanceTo(interRay); if (distance < raycaster2.near || distance > raycaster2.far) continue; intersects2.push({ distance, // What do we want? intersection point on the ray or on the segment?? // point: raycaster.ray.at( distance ), point: interSegment.clone().applyMatrix4(this.matrixWorld), index: i, face: null, faceIndex: null, object: this }); } } } updateMorphTargets() { const geometry = this.geometry; const morphAttributes = geometry.morphAttributes; const keys = Object.keys(morphAttributes); if (keys.length > 0) { const morphAttribute = morphAttributes[keys[0]]; if (morphAttribute !== void 0) { this.morphTargetInfluences = []; this.morphTargetDictionary = {}; for (let m = 0, ml = morphAttribute.length; m < ml; m++) { const name = morphAttribute[m].name || String(m); this.morphTargetInfluences.push(0); this.morphTargetDictionary[name] = m; } } } } }; var _start = new Vector3(); var _end = new Vector3(); var LineSegments = class extends Line { constructor(geometry, material) { super(geometry, material); this.isLineSegments = true; this.type = "LineSegments"; } computeLineDistances() { const geometry = this.geometry; if (geometry.index === null) { const positionAttribute = geometry.attributes.position; const lineDistances = []; for (let i = 0, l = positionAttribute.count; i < l; i += 2) { _start.fromBufferAttribute(positionAttribute, i); _end.fromBufferAttribute(positionAttribute, i + 1); lineDistances[i] = i === 0 ? 0 : lineDistances[i - 1]; lineDistances[i + 1] = lineDistances[i] + _start.distanceTo(_end); } geometry.setAttribute("lineDistance", new Float32BufferAttribute(lineDistances, 1)); } else { console.warn("THREE.LineSegments.computeLineDistances(): Computation only possible with non-indexed BufferGeometry."); } return this; } }; var LineLoop = class extends Line { constructor(geometry, material) { super(geometry, material); this.isLineLoop = true; this.type = "LineLoop"; } }; var PointsMaterial = class extends Material { constructor(parameters) { super(); this.isPointsMaterial = true; this.type = "PointsMaterial"; this.color = new Color(16777215); this.map = null; this.alphaMap = null; this.size = 1; this.sizeAttenuation = true; this.fog = true; this.setValues(parameters); } copy(source) { super.copy(source); this.color.copy(source.color); this.map = source.map; this.alphaMap = source.alphaMap; this.size = source.size; this.sizeAttenuation = source.sizeAttenuation; this.fog = source.fog; return this; } }; var _inverseMatrix = new Matrix4(); var _ray = new Ray(); var _sphere = new Sphere(); var _position$2 = new Vector3(); var Points = class extends Object3D { constructor(geometry = new BufferGeometry(), material = new PointsMaterial()) { super(); this.isPoints = true; this.type = "Points"; this.geometry = geometry; this.material = material; this.updateMorphTargets(); } copy(source, recursive) { super.copy(source, recursive); this.material = source.material; this.geometry = source.geometry; return this; } raycast(raycaster2, intersects2) { const geometry = this.geometry; const matrixWorld = this.matrixWorld; const threshold = raycaster2.params.Points.threshold; const drawRange = geometry.drawRange; if (geometry.boundingSphere === null) geometry.computeBoundingSphere(); _sphere.copy(geometry.boundingSphere); _sphere.applyMatrix4(matrixWorld); _sphere.radius += threshold; if (raycaster2.ray.intersectsSphere(_sphere) === false) return; _inverseMatrix.copy(matrixWorld).invert(); _ray.copy(raycaster2.ray).applyMatrix4(_inverseMatrix); const localThreshold = threshold / ((this.scale.x + this.scale.y + this.scale.z) / 3); const localThresholdSq = localThreshold * localThreshold; const index = geometry.index; const attributes = geometry.attributes; const positionAttribute = attributes.position; if (index !== null) { const start = Math.max(0, drawRange.start); const end = Math.min(index.count, drawRange.start + drawRange.count); for (let i = start, il = end; i < il; i++) { const a = index.getX(i); _position$2.fromBufferAttribute(positionAttribute, a); testPoint(_position$2, a, localThresholdSq, matrixWorld, raycaster2, intersects2, this); } } else { const start = Math.max(0, drawRange.start); const end = Math.min(positionAttribute.count, drawRange.start + drawRange.count); for (let i = start, l = end; i < l; i++) { _position$2.fromBufferAttribute(positionAttribute, i); testPoint(_position$2, i, localThresholdSq, matrixWorld, raycaster2, intersects2, this); } } } updateMorphTargets() { const geometry = this.geometry; const morphAttributes = geometry.morphAttributes; const keys = Object.keys(morphAttributes); if (keys.length > 0) { const morphAttribute = morphAttributes[keys[0]]; if (morphAttribute !== void 0) { this.morphTargetInfluences = []; this.morphTargetDictionary = {}; for (let m = 0, ml = morphAttribute.length; m < ml; m++) { const name = morphAttribute[m].name || String(m); this.morphTargetInfluences.push(0); this.morphTargetDictionary[name] = m; } } } } }; function testPoint(point, index, localThresholdSq, matrixWorld, raycaster2, intersects2, object) { const rayPointDistanceSq = _ray.distanceSqToPoint(point); if (rayPointDistanceSq < localThresholdSq) { const intersectPoint = new Vector3(); _ray.closestPointToPoint(point, intersectPoint); intersectPoint.applyMatrix4(matrixWorld); const distance = raycaster2.ray.origin.distanceTo(intersectPoint); if (distance < raycaster2.near || distance > raycaster2.far) return; intersects2.push({ distance, distanceToRay: Math.sqrt(rayPointDistanceSq), point: intersectPoint, index, face: null, object }); } } var CompressedTexture = class extends Texture { constructor(mipmaps, width, height, format, type, mapping, wrapS, wrapT, magFilter, minFilter, anisotropy, encoding) { super(null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, encoding); this.isCompressedTexture = true; this.image = { width, height }; this.mipmaps = mipmaps; this.flipY = false; this.generateMipmaps = false; } }; var CompressedArrayTexture = class extends CompressedTexture { constructor(mipmaps, width, height, depth, format, type) { super(mipmaps, width, height, format, type); this.isCompressedArrayTexture = true; this.image.depth = depth; this.wrapR = ClampToEdgeWrapping; } }; var Curve = class { constructor() { this.type = "Curve"; this.arcLengthDivisions = 200; } // Virtual base class method to overwrite and implement in subclasses // - t [0 .. 1] getPoint() { console.warn("THREE.Curve: .getPoint() not implemented."); return null; } // Get point at relative position in curve according to arc length // - u [0 .. 1] getPointAt(u, optionalTarget) { const t2 = this.getUtoTmapping(u); return this.getPoint(t2, optionalTarget); } // Get sequence of points using getPoint( t ) getPoints(divisions = 5) { const points = []; for (let d = 0; d <= divisions; d++) { points.push(this.getPoint(d / divisions)); } return points; } // Get sequence of points using getPointAt( u ) getSpacedPoints(divisions = 5) { const points = []; for (let d = 0; d <= divisions; d++) { points.push(this.getPointAt(d / divisions)); } return points; } // Get total curve arc length getLength() { const lengths = this.getLengths(); return lengths[lengths.length - 1]; } // Get list of cumulative segment lengths getLengths(divisions = this.arcLengthDivisions) { if (this.cacheArcLengths && this.cacheArcLengths.length === divisions + 1 && !this.needsUpdate) { return this.cacheArcLengths; } this.needsUpdate = false; const cache2 = []; let current, last = this.getPoint(0); let sum = 0; cache2.push(0); for (let p2 = 1; p2 <= divisions; p2++) { current = this.getPoint(p2 / divisions); sum += current.distanceTo(last); cache2.push(sum); last = current; } this.cacheArcLengths = cache2; return cache2; } updateArcLengths() { this.needsUpdate = true; this.getLengths(); } // Given u ( 0 .. 1 ), get a t to find p. This gives you points which are equidistant getUtoTmapping(u, distance) { const arcLengths = this.getLengths(); let i = 0; const il = arcLengths.length; let targetArcLength; if (distance) { targetArcLength = distance; } else { targetArcLength = u * arcLengths[il - 1]; } let low = 0, high = il - 1, comparison; while (low <= high) { i = Math.floor(low + (high - low) / 2); comparison = arcLengths[i] - targetArcLength; if (comparison < 0) { low = i + 1; } else if (comparison > 0) { high = i - 1; } else { high = i; break; } } i = high; if (arcLengths[i] === targetArcLength) { return i / (il - 1); } const lengthBefore = arcLengths[i]; const lengthAfter = arcLengths[i + 1]; const segmentLength = lengthAfter - lengthBefore; const segmentFraction = (targetArcLength - lengthBefore) / segmentLength; const t2 = (i + segmentFraction) / (il - 1); return t2; } // Returns a unit vector tangent at t // In case any sub curve does not implement its tangent derivation, // 2 points a small delta apart will be used to find its gradient // which seems to give a reasonable approximation getTangent(t2, optionalTarget) { const delta = 1e-4; let t1 = t2 - delta; let t22 = t2 + delta; if (t1 < 0) t1 = 0; if (t22 > 1) t22 = 1; const pt1 = this.getPoint(t1); const pt2 = this.getPoint(t22); const tangent = optionalTarget || (pt1.isVector2 ? new Vector2() : new Vector3()); tangent.copy(pt2).sub(pt1).normalize(); return tangent; } getTangentAt(u, optionalTarget) { const t2 = this.getUtoTmapping(u); return this.getTangent(t2, optionalTarget); } computeFrenetFrames(segments, closed) { const normal = new Vector3(); const tangents = []; const normals = []; const binormals = []; const vec = new Vector3(); const mat = new Matrix4(); for (let i = 0; i <= segments; i++) { const u = i / segments; tangents[i] = this.getTangentAt(u, new Vector3()); } normals[0] = new Vector3(); binormals[0] = new Vector3(); let min = Number.MAX_VALUE; const tx = Math.abs(tangents[0].x); const ty = Math.abs(tangents[0].y); const tz = Math.abs(tangents[0].z); if (tx <= min) { min = tx; normal.set(1, 0, 0); } if (ty <= min) { min = ty; normal.set(0, 1, 0); } if (tz <= min) { normal.set(0, 0, 1); } vec.crossVectors(tangents[0], normal).normalize(); normals[0].crossVectors(tangents[0], vec); binormals[0].crossVectors(tangents[0], normals[0]); for (let i = 1; i <= segments; i++) { normals[i] = normals[i - 1].clone(); binormals[i] = binormals[i - 1].clone(); vec.crossVectors(tangents[i - 1], tangents[i]); if (vec.length() > Number.EPSILON) { vec.normalize(); const theta = Math.acos(clamp(tangents[i - 1].dot(tangents[i]), -1, 1)); normals[i].applyMatrix4(mat.makeRotationAxis(vec, theta)); } binormals[i].crossVectors(tangents[i], normals[i]); } if (closed === true) { let theta = Math.acos(clamp(normals[0].dot(normals[segments]), -1, 1)); theta /= segments; if (tangents[0].dot(vec.crossVectors(normals[0], normals[segments])) > 0) { theta = -theta; } for (let i = 1; i <= segments; i++) { normals[i].applyMatrix4(mat.makeRotationAxis(tangents[i], theta * i)); binormals[i].crossVectors(tangents[i], normals[i]); } } return { tangents, normals, binormals }; } clone() { return new this.constructor().copy(this); } copy(source) { this.arcLengthDivisions = source.arcLengthDivisions; return this; } toJSON() { const data = { metadata: { version: 4.5, type: "Curve", generator: "Curve.toJSON" } }; data.arcLengthDivisions = this.arcLengthDivisions; data.type = this.type; return data; } fromJSON(json) { this.arcLengthDivisions = json.arcLengthDivisions; return this; } }; var EllipseCurve = class extends Curve { constructor(aX = 0, aY = 0, xRadius = 1, yRadius = 1, aStartAngle = 0, aEndAngle = Math.PI * 2, aClockwise = false, aRotation = 0) { super(); this.isEllipseCurve = true; this.type = "EllipseCurve"; this.aX = aX; this.aY = aY; this.xRadius = xRadius; this.yRadius = yRadius; this.aStartAngle = aStartAngle; this.aEndAngle = aEndAngle; this.aClockwise = aClockwise; this.aRotation = aRotation; } getPoint(t2, optionalTarget) { const point = optionalTarget || new Vector2(); const twoPi = Math.PI * 2; let deltaAngle = this.aEndAngle - this.aStartAngle; const samePoints = Math.abs(deltaAngle) < Number.EPSILON; while (deltaAngle < 0) deltaAngle += twoPi; while (deltaAngle > twoPi) deltaAngle -= twoPi; if (deltaAngle < Number.EPSILON) { if (samePoints) { deltaAngle = 0; } else { deltaAngle = twoPi; } } if (this.aClockwise === true && !samePoints) { if (deltaAngle === twoPi) { deltaAngle = -twoPi; } else { deltaAngle = deltaAngle - twoPi; } } const angle = this.aStartAngle + t2 * deltaAngle; let x2 = this.aX + this.xRadius * Math.cos(angle); let y = this.aY + this.yRadius * Math.sin(angle); if (this.aRotation !== 0) { const cos = Math.cos(this.aRotation); const sin = Math.sin(this.aRotation); const tx = x2 - this.aX; const ty = y - this.aY; x2 = tx * cos - ty * sin + this.aX; y = tx * sin + ty * cos + this.aY; } return point.set(x2, y); } copy(source) { super.copy(source); this.aX = source.aX; this.aY = source.aY; this.xRadius = source.xRadius; this.yRadius = source.yRadius; this.aStartAngle = source.aStartAngle; this.aEndAngle = source.aEndAngle; this.aClockwise = source.aClockwise; this.aRotation = source.aRotation; return this; } toJSON() { const data = super.toJSON(); data.aX = this.aX; data.aY = this.aY; data.xRadius = this.xRadius; data.yRadius = this.yRadius; data.aStartAngle = this.aStartAngle; data.aEndAngle = this.aEndAngle; data.aClockwise = this.aClockwise; data.aRotation = this.aRotation; return data; } fromJSON(json) { super.fromJSON(json); this.aX = json.aX; this.aY = json.aY; this.xRadius = json.xRadius; this.yRadius = json.yRadius; this.aStartAngle = json.aStartAngle; this.aEndAngle = json.aEndAngle; this.aClockwise = json.aClockwise; this.aRotation = json.aRotation; return this; } }; var ArcCurve = class extends EllipseCurve { constructor(aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise) { super(aX, aY, aRadius, aRadius, aStartAngle, aEndAngle, aClockwise); this.isArcCurve = true; this.type = "ArcCurve"; } }; function CubicPoly() { let c0 = 0, c1 = 0, c2 = 0, c3 = 0; function init(x0, x1, t0, t1) { c0 = x0; c1 = t0; c2 = -3 * x0 + 3 * x1 - 2 * t0 - t1; c3 = 2 * x0 - 2 * x1 + t0 + t1; } return { initCatmullRom: function(x0, x1, x2, x3, tension) { init(x1, x2, tension * (x2 - x0), tension * (x3 - x1)); }, initNonuniformCatmullRom: function(x0, x1, x2, x3, dt0, dt1, dt2) { let t1 = (x1 - x0) / dt0 - (x2 - x0) / (dt0 + dt1) + (x2 - x1) / dt1; let t2 = (x2 - x1) / dt1 - (x3 - x1) / (dt1 + dt2) + (x3 - x2) / dt2; t1 *= dt1; t2 *= dt1; init(x1, x2, t1, t2); }, calc: function(t2) { const t22 = t2 * t2; const t3 = t22 * t2; return c0 + c1 * t2 + c2 * t22 + c3 * t3; } }; } var tmp = new Vector3(); var px = new CubicPoly(); var py = new CubicPoly(); var pz = new CubicPoly(); var CatmullRomCurve3 = class extends Curve { constructor(points = [], closed = false, curveType = "centripetal", tension = 0.5) { super(); this.isCatmullRomCurve3 = true; this.type = "CatmullRomCurve3"; this.points = points; this.closed = closed; this.curveType = curveType; this.tension = tension; } getPoint(t2, optionalTarget = new Vector3()) { const point = optionalTarget; const points = this.points; const l = points.length; const p2 = (l - (this.closed ? 0 : 1)) * t2; let intPoint = Math.floor(p2); let weight = p2 - intPoint; if (this.closed) { intPoint += intPoint > 0 ? 0 : (Math.floor(Math.abs(intPoint) / l) + 1) * l; } else if (weight === 0 && intPoint === l - 1) { intPoint = l - 2; weight = 1; } let p0, p3; if (this.closed || intPoint > 0) { p0 = points[(intPoint - 1) % l]; } else { tmp.subVectors(points[0], points[1]).add(points[0]); p0 = tmp; } const p1 = points[intPoint % l]; const p22 = points[(intPoint + 1) % l]; if (this.closed || intPoint + 2 < l) { p3 = points[(intPoint + 2) % l]; } else { tmp.subVectors(points[l - 1], points[l - 2]).add(points[l - 1]); p3 = tmp; } if (this.curveType === "centripetal" || this.curveType === "chordal") { const pow = this.curveType === "chordal" ? 0.5 : 0.25; let dt0 = Math.pow(p0.distanceToSquared(p1), pow); let dt1 = Math.pow(p1.distanceToSquared(p22), pow); let dt2 = Math.pow(p22.distanceToSquared(p3), pow); if (dt1 < 1e-4) dt1 = 1; if (dt0 < 1e-4) dt0 = dt1; if (dt2 < 1e-4) dt2 = dt1; px.initNonuniformCatmullRom(p0.x, p1.x, p22.x, p3.x, dt0, dt1, dt2); py.initNonuniformCatmullRom(p0.y, p1.y, p22.y, p3.y, dt0, dt1, dt2); pz.initNonuniformCatmullRom(p0.z, p1.z, p22.z, p3.z, dt0, dt1, dt2); } else if (this.curveType === "catmullrom") { px.initCatmullRom(p0.x, p1.x, p22.x, p3.x, this.tension); py.initCatmullRom(p0.y, p1.y, p22.y, p3.y, this.tension); pz.initCatmullRom(p0.z, p1.z, p22.z, p3.z, this.tension); } point.set( px.calc(weight), py.calc(weight), pz.calc(weight) ); return point; } copy(source) { super.copy(source); this.points = []; for (let i = 0, l = source.points.length; i < l; i++) { const point = source.points[i]; this.points.push(point.clone()); } this.closed = source.closed; this.curveType = source.curveType; this.tension = source.tension; return this; } toJSON() { const data = super.toJSON(); data.points = []; for (let i = 0, l = this.points.length; i < l; i++) { const point = this.points[i]; data.points.push(point.toArray()); } data.closed = this.closed; data.curveType = this.curveType; data.tension = this.tension; return data; } fromJSON(json) { super.fromJSON(json); this.points = []; for (let i = 0, l = json.points.length; i < l; i++) { const point = json.points[i]; this.points.push(new Vector3().fromArray(point)); } this.closed = json.closed; this.curveType = json.curveType; this.tension = json.tension; return this; } }; function CatmullRom(t2, p0, p1, p2, p3) { const v0 = (p2 - p0) * 0.5; const v1 = (p3 - p1) * 0.5; const t22 = t2 * t2; const t3 = t2 * t22; return (2 * p1 - 2 * p2 + v0 + v1) * t3 + (-3 * p1 + 3 * p2 - 2 * v0 - v1) * t22 + v0 * t2 + p1; } function QuadraticBezierP0(t2, p2) { const k = 1 - t2; return k * k * p2; } function QuadraticBezierP1(t2, p2) { return 2 * (1 - t2) * t2 * p2; } function QuadraticBezierP2(t2, p2) { return t2 * t2 * p2; } function QuadraticBezier(t2, p0, p1, p2) { return QuadraticBezierP0(t2, p0) + QuadraticBezierP1(t2, p1) + QuadraticBezierP2(t2, p2); } function CubicBezierP0(t2, p2) { const k = 1 - t2; return k * k * k * p2; } function CubicBezierP1(t2, p2) { const k = 1 - t2; return 3 * k * k * t2 * p2; } function CubicBezierP2(t2, p2) { return 3 * (1 - t2) * t2 * t2 * p2; } function CubicBezierP3(t2, p2) { return t2 * t2 * t2 * p2; } function CubicBezier(t2, p0, p1, p2, p3) { return CubicBezierP0(t2, p0) + CubicBezierP1(t2, p1) + CubicBezierP2(t2, p2) + CubicBezierP3(t2, p3); } var CubicBezierCurve = class extends Curve { constructor(v0 = new Vector2(), v1 = new Vector2(), v2 = new Vector2(), v3 = new Vector2()) { super(); this.isCubicBezierCurve = true; this.type = "CubicBezierCurve"; this.v0 = v0; this.v1 = v1; this.v2 = v2; this.v3 = v3; } getPoint(t2, optionalTarget = new Vector2()) { const point = optionalTarget; const v0 = this.v0, v1 = this.v1, v2 = this.v2, v3 = this.v3; point.set( CubicBezier(t2, v0.x, v1.x, v2.x, v3.x), CubicBezier(t2, v0.y, v1.y, v2.y, v3.y) ); return point; } copy(source) { super.copy(source); this.v0.copy(source.v0); this.v1.copy(source.v1); this.v2.copy(source.v2); this.v3.copy(source.v3); return this; } toJSON() { const data = super.toJSON(); data.v0 = this.v0.toArray(); data.v1 = this.v1.toArray(); data.v2 = this.v2.toArray(); data.v3 = this.v3.toArray(); return data; } fromJSON(json) { super.fromJSON(json); this.v0.fromArray(json.v0); this.v1.fromArray(json.v1); this.v2.fromArray(json.v2); this.v3.fromArray(json.v3); return this; } }; var CubicBezierCurve3 = class extends Curve { constructor(v0 = new Vector3(), v1 = new Vector3(), v2 = new Vector3(), v3 = new Vector3()) { super(); this.isCubicBezierCurve3 = true; this.type = "CubicBezierCurve3"; this.v0 = v0; this.v1 = v1; this.v2 = v2; this.v3 = v3; } getPoint(t2, optionalTarget = new Vector3()) { const point = optionalTarget; const v0 = this.v0, v1 = this.v1, v2 = this.v2, v3 = this.v3; point.set( CubicBezier(t2, v0.x, v1.x, v2.x, v3.x), CubicBezier(t2, v0.y, v1.y, v2.y, v3.y), CubicBezier(t2, v0.z, v1.z, v2.z, v3.z) ); return point; } copy(source) { super.copy(source); this.v0.copy(source.v0); this.v1.copy(source.v1); this.v2.copy(source.v2); this.v3.copy(source.v3); return this; } toJSON() { const data = super.toJSON(); data.v0 = this.v0.toArray(); data.v1 = this.v1.toArray(); data.v2 = this.v2.toArray(); data.v3 = this.v3.toArray(); return data; } fromJSON(json) { super.fromJSON(json); this.v0.fromArray(json.v0); this.v1.fromArray(json.v1); this.v2.fromArray(json.v2); this.v3.fromArray(json.v3); return this; } }; var LineCurve = class extends Curve { constructor(v1 = new Vector2(), v2 = new Vector2()) { super(); this.isLineCurve = true; this.type = "LineCurve"; this.v1 = v1; this.v2 = v2; } getPoint(t2, optionalTarget = new Vector2()) { const point = optionalTarget; if (t2 === 1) { point.copy(this.v2); } else { point.copy(this.v2).sub(this.v1); point.multiplyScalar(t2).add(this.v1); } return point; } // Line curve is linear, so we can overwrite default getPointAt getPointAt(u, optionalTarget) { return this.getPoint(u, optionalTarget); } getTangent(t2, optionalTarget) { const tangent = optionalTarget || new Vector2(); tangent.copy(this.v2).sub(this.v1).normalize(); return tangent; } copy(source) { super.copy(source); this.v1.copy(source.v1); this.v2.copy(source.v2); return this; } toJSON() { const data = super.toJSON(); data.v1 = this.v1.toArray(); data.v2 = this.v2.toArray(); return data; } fromJSON(json) { super.fromJSON(json); this.v1.fromArray(json.v1); this.v2.fromArray(json.v2); return this; } }; var LineCurve3 = class extends Curve { constructor(v1 = new Vector3(), v2 = new Vector3()) { super(); this.isLineCurve3 = true; this.type = "LineCurve3"; this.v1 = v1; this.v2 = v2; } getPoint(t2, optionalTarget = new Vector3()) { const point = optionalTarget; if (t2 === 1) { point.copy(this.v2); } else { point.copy(this.v2).sub(this.v1); point.multiplyScalar(t2).add(this.v1); } return point; } // Line curve is linear, so we can overwrite default getPointAt getPointAt(u, optionalTarget) { return this.getPoint(u, optionalTarget); } copy(source) { super.copy(source); this.v1.copy(source.v1); this.v2.copy(source.v2); return this; } toJSON() { const data = super.toJSON(); data.v1 = this.v1.toArray(); data.v2 = this.v2.toArray(); return data; } fromJSON(json) { super.fromJSON(json); this.v1.fromArray(json.v1); this.v2.fromArray(json.v2); return this; } }; var QuadraticBezierCurve = class extends Curve { constructor(v0 = new Vector2(), v1 = new Vector2(), v2 = new Vector2()) { super(); this.isQuadraticBezierCurve = true; this.type = "QuadraticBezierCurve"; this.v0 = v0; this.v1 = v1; this.v2 = v2; } getPoint(t2, optionalTarget = new Vector2()) { const point = optionalTarget; const v0 = this.v0, v1 = this.v1, v2 = this.v2; point.set( QuadraticBezier(t2, v0.x, v1.x, v2.x), QuadraticBezier(t2, v0.y, v1.y, v2.y) ); return point; } copy(source) { super.copy(source); this.v0.copy(source.v0); this.v1.copy(source.v1); this.v2.copy(source.v2); return this; } toJSON() { const data = super.toJSON(); data.v0 = this.v0.toArray(); data.v1 = this.v1.toArray(); data.v2 = this.v2.toArray(); return data; } fromJSON(json) { super.fromJSON(json); this.v0.fromArray(json.v0); this.v1.fromArray(json.v1); this.v2.fromArray(json.v2); return this; } }; var QuadraticBezierCurve3 = class extends Curve { constructor(v0 = new Vector3(), v1 = new Vector3(), v2 = new Vector3()) { super(); this.isQuadraticBezierCurve3 = true; this.type = "QuadraticBezierCurve3"; this.v0 = v0; this.v1 = v1; this.v2 = v2; } getPoint(t2, optionalTarget = new Vector3()) { const point = optionalTarget; const v0 = this.v0, v1 = this.v1, v2 = this.v2; point.set( QuadraticBezier(t2, v0.x, v1.x, v2.x), QuadraticBezier(t2, v0.y, v1.y, v2.y), QuadraticBezier(t2, v0.z, v1.z, v2.z) ); return point; } copy(source) { super.copy(source); this.v0.copy(source.v0); this.v1.copy(source.v1); this.v2.copy(source.v2); return this; } toJSON() { const data = super.toJSON(); data.v0 = this.v0.toArray(); data.v1 = this.v1.toArray(); data.v2 = this.v2.toArray(); return data; } fromJSON(json) { super.fromJSON(json); this.v0.fromArray(json.v0); this.v1.fromArray(json.v1); this.v2.fromArray(json.v2); return this; } }; var SplineCurve = class extends Curve { constructor(points = []) { super(); this.isSplineCurve = true; this.type = "SplineCurve"; this.points = points; } getPoint(t2, optionalTarget = new Vector2()) { const point = optionalTarget; const points = this.points; const p2 = (points.length - 1) * t2; const intPoint = Math.floor(p2); const weight = p2 - intPoint; const p0 = points[intPoint === 0 ? intPoint : intPoint - 1]; const p1 = points[intPoint]; const p22 = points[intPoint > points.length - 2 ? points.length - 1 : intPoint + 1]; const p3 = points[intPoint > points.length - 3 ? points.length - 1 : intPoint + 2]; point.set( CatmullRom(weight, p0.x, p1.x, p22.x, p3.x), CatmullRom(weight, p0.y, p1.y, p22.y, p3.y) ); return point; } copy(source) { super.copy(source); this.points = []; for (let i = 0, l = source.points.length; i < l; i++) { const point = source.points[i]; this.points.push(point.clone()); } return this; } toJSON() { const data = super.toJSON(); data.points = []; for (let i = 0, l = this.points.length; i < l; i++) { const point = this.points[i]; data.points.push(point.toArray()); } return data; } fromJSON(json) { super.fromJSON(json); this.points = []; for (let i = 0, l = json.points.length; i < l; i++) { const point = json.points[i]; this.points.push(new Vector2().fromArray(point)); } return this; } }; var Curves = Object.freeze({ __proto__: null, ArcCurve, CatmullRomCurve3, CubicBezierCurve, CubicBezierCurve3, EllipseCurve, LineCurve, LineCurve3, QuadraticBezierCurve, QuadraticBezierCurve3, SplineCurve }); var CurvePath = class extends Curve { constructor() { super(); this.type = "CurvePath"; this.curves = []; this.autoClose = false; } add(curve) { this.curves.push(curve); } closePath() { const startPoint = this.curves[0].getPoint(0); const endPoint = this.curves[this.curves.length - 1].getPoint(1); if (!startPoint.equals(endPoint)) { this.curves.push(new LineCurve(endPoint, startPoint)); } } // To get accurate point with reference to // entire path distance at time t, // following has to be done: // 1. Length of each sub path have to be known // 2. Locate and identify type of curve // 3. Get t for the curve // 4. Return curve.getPointAt(t') getPoint(t2, optionalTarget) { const d = t2 * this.getLength(); const curveLengths = this.getCurveLengths(); let i = 0; while (i < curveLengths.length) { if (curveLengths[i] >= d) { const diff = curveLengths[i] - d; const curve = this.curves[i]; const segmentLength = curve.getLength(); const u = segmentLength === 0 ? 0 : 1 - diff / segmentLength; return curve.getPointAt(u, optionalTarget); } i++; } return null; } // We cannot use the default THREE.Curve getPoint() with getLength() because in // THREE.Curve, getLength() depends on getPoint() but in THREE.CurvePath // getPoint() depends on getLength getLength() { const lens = this.getCurveLengths(); return lens[lens.length - 1]; } // cacheLengths must be recalculated. updateArcLengths() { this.needsUpdate = true; this.cacheLengths = null; this.getCurveLengths(); } // Compute lengths and cache them // We cannot overwrite getLengths() because UtoT mapping uses it. getCurveLengths() { if (this.cacheLengths && this.cacheLengths.length === this.curves.length) { return this.cacheLengths; } const lengths = []; let sums = 0; for (let i = 0, l = this.curves.length; i < l; i++) { sums += this.curves[i].getLength(); lengths.push(sums); } this.cacheLengths = lengths; return lengths; } getSpacedPoints(divisions = 40) { const points = []; for (let i = 0; i <= divisions; i++) { points.push(this.getPoint(i / divisions)); } if (this.autoClose) { points.push(points[0]); } return points; } getPoints(divisions = 12) { const points = []; let last; for (let i = 0, curves = this.curves; i < curves.length; i++) { const curve = curves[i]; const resolution = curve.isEllipseCurve ? divisions * 2 : curve.isLineCurve || curve.isLineCurve3 ? 1 : curve.isSplineCurve ? divisions * curve.points.length : divisions; const pts = curve.getPoints(resolution); for (let j = 0; j < pts.length; j++) { const point = pts[j]; if (last && last.equals(point)) continue; points.push(point); last = point; } } if (this.autoClose && points.length > 1 && !points[points.length - 1].equals(points[0])) { points.push(points[0]); } return points; } copy(source) { super.copy(source); this.curves = []; for (let i = 0, l = source.curves.length; i < l; i++) { const curve = source.curves[i]; this.curves.push(curve.clone()); } this.autoClose = source.autoClose; return this; } toJSON() { const data = super.toJSON(); data.autoClose = this.autoClose; data.curves = []; for (let i = 0, l = this.curves.length; i < l; i++) { const curve = this.curves[i]; data.curves.push(curve.toJSON()); } return data; } fromJSON(json) { super.fromJSON(json); this.autoClose = json.autoClose; this.curves = []; for (let i = 0, l = json.curves.length; i < l; i++) { const curve = json.curves[i]; this.curves.push(new Curves[curve.type]().fromJSON(curve)); } return this; } }; var Path = class extends CurvePath { constructor(points) { super(); this.type = "Path"; this.currentPoint = new Vector2(); if (points) { this.setFromPoints(points); } } setFromPoints(points) { this.moveTo(points[0].x, points[0].y); for (let i = 1, l = points.length; i < l; i++) { this.lineTo(points[i].x, points[i].y); } return this; } moveTo(x2, y) { this.currentPoint.set(x2, y); return this; } lineTo(x2, y) { const curve = new LineCurve(this.currentPoint.clone(), new Vector2(x2, y)); this.curves.push(curve); this.currentPoint.set(x2, y); return this; } quadraticCurveTo(aCPx, aCPy, aX, aY) { const curve = new QuadraticBezierCurve( this.currentPoint.clone(), new Vector2(aCPx, aCPy), new Vector2(aX, aY) ); this.curves.push(curve); this.currentPoint.set(aX, aY); return this; } bezierCurveTo(aCP1x, aCP1y, aCP2x, aCP2y, aX, aY) { const curve = new CubicBezierCurve( this.currentPoint.clone(), new Vector2(aCP1x, aCP1y), new Vector2(aCP2x, aCP2y), new Vector2(aX, aY) ); this.curves.push(curve); this.currentPoint.set(aX, aY); return this; } splineThru(pts) { const npts = [this.currentPoint.clone()].concat(pts); const curve = new SplineCurve(npts); this.curves.push(curve); this.currentPoint.copy(pts[pts.length - 1]); return this; } arc(aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise) { const x0 = this.currentPoint.x; const y0 = this.currentPoint.y; this.absarc( aX + x0, aY + y0, aRadius, aStartAngle, aEndAngle, aClockwise ); return this; } absarc(aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise) { this.absellipse(aX, aY, aRadius, aRadius, aStartAngle, aEndAngle, aClockwise); return this; } ellipse(aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation) { const x0 = this.currentPoint.x; const y0 = this.currentPoint.y; this.absellipse(aX + x0, aY + y0, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation); return this; } absellipse(aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation) { const curve = new EllipseCurve(aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation); if (this.curves.length > 0) { const firstPoint = curve.getPoint(0); if (!firstPoint.equals(this.currentPoint)) { this.lineTo(firstPoint.x, firstPoint.y); } } this.curves.push(curve); const lastPoint = curve.getPoint(1); this.currentPoint.copy(lastPoint); return this; } copy(source) { super.copy(source); this.currentPoint.copy(source.currentPoint); return this; } toJSON() { const data = super.toJSON(); data.currentPoint = this.currentPoint.toArray(); return data; } fromJSON(json) { super.fromJSON(json); this.currentPoint.fromArray(json.currentPoint); return this; } }; var LatheGeometry = class _LatheGeometry extends BufferGeometry { constructor(points = [new Vector2(0, -0.5), new Vector2(0.5, 0), new Vector2(0, 0.5)], segments = 12, phiStart = 0, phiLength = Math.PI * 2) { super(); this.type = "LatheGeometry"; this.parameters = { points, segments, phiStart, phiLength }; segments = Math.floor(segments); phiLength = clamp(phiLength, 0, Math.PI * 2); const indices = []; const vertices = []; const uvs = []; const initNormals = []; const normals = []; const inverseSegments = 1 / segments; const vertex2 = new Vector3(); const uv = new Vector2(); const normal = new Vector3(); const curNormal = new Vector3(); const prevNormal = new Vector3(); let dx = 0; let dy = 0; for (let j = 0; j <= points.length - 1; j++) { switch (j) { case 0: dx = points[j + 1].x - points[j].x; dy = points[j + 1].y - points[j].y; normal.x = dy * 1; normal.y = -dx; normal.z = dy * 0; prevNormal.copy(normal); normal.normalize(); initNormals.push(normal.x, normal.y, normal.z); break; case points.length - 1: initNormals.push(prevNormal.x, prevNormal.y, prevNormal.z); break; default: dx = points[j + 1].x - points[j].x; dy = points[j + 1].y - points[j].y; normal.x = dy * 1; normal.y = -dx; normal.z = dy * 0; curNormal.copy(normal); normal.x += prevNormal.x; normal.y += prevNormal.y; normal.z += prevNormal.z; normal.normalize(); initNormals.push(normal.x, normal.y, normal.z); prevNormal.copy(curNormal); } } for (let i = 0; i <= segments; i++) { const phi = phiStart + i * inverseSegments * phiLength; const sin = Math.sin(phi); const cos = Math.cos(phi); for (let j = 0; j <= points.length - 1; j++) { vertex2.x = points[j].x * sin; vertex2.y = points[j].y; vertex2.z = points[j].x * cos; vertices.push(vertex2.x, vertex2.y, vertex2.z); uv.x = i / segments; uv.y = j / (points.length - 1); uvs.push(uv.x, uv.y); const x2 = initNormals[3 * j + 0] * sin; const y = initNormals[3 * j + 1]; const z = initNormals[3 * j + 0] * cos; normals.push(x2, y, z); } } for (let i = 0; i < segments; i++) { for (let j = 0; j < points.length - 1; j++) { const base = j + i * points.length; const a = base; const b = base + points.length; const c = base + points.length + 1; const d = base + 1; indices.push(a, b, d); indices.push(c, d, b); } } this.setIndex(indices); this.setAttribute("position", new Float32BufferAttribute(vertices, 3)); this.setAttribute("uv", new Float32BufferAttribute(uvs, 2)); this.setAttribute("normal", new Float32BufferAttribute(normals, 3)); } static fromJSON(data) { return new _LatheGeometry(data.points, data.segments, data.phiStart, data.phiLength); } }; var CapsuleGeometry = class _CapsuleGeometry extends LatheGeometry { constructor(radius = 1, length = 1, capSegments = 4, radialSegments = 8) { const path = new Path(); path.absarc(0, -length / 2, radius, Math.PI * 1.5, 0); path.absarc(0, length / 2, radius, 0, Math.PI * 0.5); super(path.getPoints(capSegments), radialSegments); this.type = "CapsuleGeometry"; this.parameters = { radius, height: length, capSegments, radialSegments }; } static fromJSON(data) { return new _CapsuleGeometry(data.radius, data.length, data.capSegments, data.radialSegments); } }; var CircleGeometry = class _CircleGeometry extends BufferGeometry { constructor(radius = 1, segments = 8, thetaStart = 0, thetaLength = Math.PI * 2) { super(); this.type = "CircleGeometry"; this.parameters = { radius, segments, thetaStart, thetaLength }; segments = Math.max(3, segments); const indices = []; const vertices = []; const normals = []; const uvs = []; const vertex2 = new Vector3(); const uv = new Vector2(); vertices.push(0, 0, 0); normals.push(0, 0, 1); uvs.push(0.5, 0.5); for (let s = 0, i = 3; s <= segments; s++, i += 3) { const segment = thetaStart + s / segments * thetaLength; vertex2.x = radius * Math.cos(segment); vertex2.y = radius * Math.sin(segment); vertices.push(vertex2.x, vertex2.y, vertex2.z); normals.push(0, 0, 1); uv.x = (vertices[i] / radius + 1) / 2; uv.y = (vertices[i + 1] / radius + 1) / 2; uvs.push(uv.x, uv.y); } for (let i = 1; i <= segments; i++) { indices.push(i, i + 1, 0); } this.setIndex(indices); this.setAttribute("position", new Float32BufferAttribute(vertices, 3)); this.setAttribute("normal", new Float32BufferAttribute(normals, 3)); this.setAttribute("uv", new Float32BufferAttribute(uvs, 2)); } static fromJSON(data) { return new _CircleGeometry(data.radius, data.segments, data.thetaStart, data.thetaLength); } }; var CylinderGeometry = class _CylinderGeometry extends BufferGeometry { constructor(radiusTop = 1, radiusBottom = 1, height = 1, radialSegments = 8, heightSegments = 1, openEnded = false, thetaStart = 0, thetaLength = Math.PI * 2) { super(); this.type = "CylinderGeometry"; this.parameters = { radiusTop, radiusBottom, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength }; const scope = this; radialSegments = Math.floor(radialSegments); heightSegments = Math.floor(heightSegments); const indices = []; const vertices = []; const normals = []; const uvs = []; let index = 0; const indexArray = []; const halfHeight = height / 2; let groupStart = 0; generateTorso(); if (openEnded === false) { if (radiusTop > 0) generateCap(true); if (radiusBottom > 0) generateCap(false); } this.setIndex(indices); this.setAttribute("position", new Float32BufferAttribute(vertices, 3)); this.setAttribute("normal", new Float32BufferAttribute(normals, 3)); this.setAttribute("uv", new Float32BufferAttribute(uvs, 2)); function generateTorso() { const normal = new Vector3(); const vertex2 = new Vector3(); let groupCount = 0; const slope = (radiusBottom - radiusTop) / height; for (let y = 0; y <= heightSegments; y++) { const indexRow = []; const v = y / heightSegments; const radius = v * (radiusBottom - radiusTop) + radiusTop; for (let x2 = 0; x2 <= radialSegments; x2++) { const u = x2 / radialSegments; const theta = u * thetaLength + thetaStart; const sinTheta = Math.sin(theta); const cosTheta = Math.cos(theta); vertex2.x = radius * sinTheta; vertex2.y = -v * height + halfHeight; vertex2.z = radius * cosTheta; vertices.push(vertex2.x, vertex2.y, vertex2.z); normal.set(sinTheta, slope, cosTheta).normalize(); normals.push(normal.x, normal.y, normal.z); uvs.push(u, 1 - v); indexRow.push(index++); } indexArray.push(indexRow); } for (let x2 = 0; x2 < radialSegments; x2++) { for (let y = 0; y < heightSegments; y++) { const a = indexArray[y][x2]; const b = indexArray[y + 1][x2]; const c = indexArray[y + 1][x2 + 1]; const d = indexArray[y][x2 + 1]; indices.push(a, b, d); indices.push(b, c, d); groupCount += 6; } } scope.addGroup(groupStart, groupCount, 0); groupStart += groupCount; } function generateCap(top) { const centerIndexStart = index; const uv = new Vector2(); const vertex2 = new Vector3(); let groupCount = 0; const radius = top === true ? radiusTop : radiusBottom; const sign2 = top === true ? 1 : -1; for (let x2 = 1; x2 <= radialSegments; x2++) { vertices.push(0, halfHeight * sign2, 0); normals.push(0, sign2, 0); uvs.push(0.5, 0.5); index++; } const centerIndexEnd = index; for (let x2 = 0; x2 <= radialSegments; x2++) { const u = x2 / radialSegments; const theta = u * thetaLength + thetaStart; const cosTheta = Math.cos(theta); const sinTheta = Math.sin(theta); vertex2.x = radius * sinTheta; vertex2.y = halfHeight * sign2; vertex2.z = radius * cosTheta; vertices.push(vertex2.x, vertex2.y, vertex2.z); normals.push(0, sign2, 0); uv.x = cosTheta * 0.5 + 0.5; uv.y = sinTheta * 0.5 * sign2 + 0.5; uvs.push(uv.x, uv.y); index++; } for (let x2 = 0; x2 < radialSegments; x2++) { const c = centerIndexStart + x2; const i = centerIndexEnd + x2; if (top === true) { indices.push(i, i + 1, c); } else { indices.push(i + 1, i, c); } groupCount += 3; } scope.addGroup(groupStart, groupCount, top === true ? 1 : 2); groupStart += groupCount; } } static fromJSON(data) { return new _CylinderGeometry(data.radiusTop, data.radiusBottom, data.height, data.radialSegments, data.heightSegments, data.openEnded, data.thetaStart, data.thetaLength); } }; var ConeGeometry = class _ConeGeometry extends CylinderGeometry { constructor(radius = 1, height = 1, radialSegments = 8, heightSegments = 1, openEnded = false, thetaStart = 0, thetaLength = Math.PI * 2) { super(0, radius, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength); this.type = "ConeGeometry"; this.parameters = { radius, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength }; } static fromJSON(data) { return new _ConeGeometry(data.radius, data.height, data.radialSegments, data.heightSegments, data.openEnded, data.thetaStart, data.thetaLength); } }; var PolyhedronGeometry = class _PolyhedronGeometry extends BufferGeometry { constructor(vertices = [], indices = [], radius = 1, detail = 0) { super(); this.type = "PolyhedronGeometry"; this.parameters = { vertices, indices, radius, detail }; const vertexBuffer = []; const uvBuffer = []; subdivide(detail); applyRadius(radius); generateUVs(); this.setAttribute("position", new Float32BufferAttribute(vertexBuffer, 3)); this.setAttribute("normal", new Float32BufferAttribute(vertexBuffer.slice(), 3)); this.setAttribute("uv", new Float32BufferAttribute(uvBuffer, 2)); if (detail === 0) { this.computeVertexNormals(); } else { this.normalizeNormals(); } function subdivide(detail2) { const a = new Vector3(); const b = new Vector3(); const c = new Vector3(); for (let i = 0; i < indices.length; i += 3) { getVertexByIndex(indices[i + 0], a); getVertexByIndex(indices[i + 1], b); getVertexByIndex(indices[i + 2], c); subdivideFace(a, b, c, detail2); } } function subdivideFace(a, b, c, detail2) { const cols = detail2 + 1; const v = []; for (let i = 0; i <= cols; i++) { v[i] = []; const aj = a.clone().lerp(c, i / cols); const bj = b.clone().lerp(c, i / cols); const rows = cols - i; for (let j = 0; j <= rows; j++) { if (j === 0 && i === cols) { v[i][j] = aj; } else { v[i][j] = aj.clone().lerp(bj, j / rows); } } } for (let i = 0; i < cols; i++) { for (let j = 0; j < 2 * (cols - i) - 1; j++) { const k = Math.floor(j / 2); if (j % 2 === 0) { pushVertex(v[i][k + 1]); pushVertex(v[i + 1][k]); pushVertex(v[i][k]); } else { pushVertex(v[i][k + 1]); pushVertex(v[i + 1][k + 1]); pushVertex(v[i + 1][k]); } } } } function applyRadius(radius2) { const vertex2 = new Vector3(); for (let i = 0; i < vertexBuffer.length; i += 3) { vertex2.x = vertexBuffer[i + 0]; vertex2.y = vertexBuffer[i + 1]; vertex2.z = vertexBuffer[i + 2]; vertex2.normalize().multiplyScalar(radius2); vertexBuffer[i + 0] = vertex2.x; vertexBuffer[i + 1] = vertex2.y; vertexBuffer[i + 2] = vertex2.z; } } function generateUVs() { const vertex2 = new Vector3(); for (let i = 0; i < vertexBuffer.length; i += 3) { vertex2.x = vertexBuffer[i + 0]; vertex2.y = vertexBuffer[i + 1]; vertex2.z = vertexBuffer[i + 2]; const u = azimuth(vertex2) / 2 / Math.PI + 0.5; const v = inclination(vertex2) / Math.PI + 0.5; uvBuffer.push(u, 1 - v); } correctUVs(); correctSeam(); } function correctSeam() { for (let i = 0; i < uvBuffer.length; i += 6) { const x0 = uvBuffer[i + 0]; const x1 = uvBuffer[i + 2]; const x2 = uvBuffer[i + 4]; const max2 = Math.max(x0, x1, x2); const min = Math.min(x0, x1, x2); if (max2 > 0.9 && min < 0.1) { if (x0 < 0.2) uvBuffer[i + 0] += 1; if (x1 < 0.2) uvBuffer[i + 2] += 1; if (x2 < 0.2) uvBuffer[i + 4] += 1; } } } function pushVertex(vertex2) { vertexBuffer.push(vertex2.x, vertex2.y, vertex2.z); } function getVertexByIndex(index, vertex2) { const stride = index * 3; vertex2.x = vertices[stride + 0]; vertex2.y = vertices[stride + 1]; vertex2.z = vertices[stride + 2]; } function correctUVs() { const a = new Vector3(); const b = new Vector3(); const c = new Vector3(); const centroid = new Vector3(); const uvA = new Vector2(); const uvB = new Vector2(); const uvC = new Vector2(); for (let i = 0, j = 0; i < vertexBuffer.length; i += 9, j += 6) { a.set(vertexBuffer[i + 0], vertexBuffer[i + 1], vertexBuffer[i + 2]); b.set(vertexBuffer[i + 3], vertexBuffer[i + 4], vertexBuffer[i + 5]); c.set(vertexBuffer[i + 6], vertexBuffer[i + 7], vertexBuffer[i + 8]); uvA.set(uvBuffer[j + 0], uvBuffer[j + 1]); uvB.set(uvBuffer[j + 2], uvBuffer[j + 3]); uvC.set(uvBuffer[j + 4], uvBuffer[j + 5]); centroid.copy(a).add(b).add(c).divideScalar(3); const azi = azimuth(centroid); correctUV(uvA, j + 0, a, azi); correctUV(uvB, j + 2, b, azi); correctUV(uvC, j + 4, c, azi); } } function correctUV(uv, stride, vector, azimuth2) { if (azimuth2 < 0 && uv.x === 1) { uvBuffer[stride] = uv.x - 1; } if (vector.x === 0 && vector.z === 0) { uvBuffer[stride] = azimuth2 / 2 / Math.PI + 0.5; } } function azimuth(vector) { return Math.atan2(vector.z, -vector.x); } function inclination(vector) { return Math.atan2(-vector.y, Math.sqrt(vector.x * vector.x + vector.z * vector.z)); } } static fromJSON(data) { return new _PolyhedronGeometry(data.vertices, data.indices, data.radius, data.details); } }; var DodecahedronGeometry = class _DodecahedronGeometry extends PolyhedronGeometry { constructor(radius = 1, detail = 0) { const t2 = (1 + Math.sqrt(5)) / 2; const r = 1 / t2; const vertices = [ // (±1, ±1, ±1) -1, -1, -1, -1, -1, 1, -1, 1, -1, -1, 1, 1, 1, -1, -1, 1, -1, 1, 1, 1, -1, 1, 1, 1, // (0, ±1/φ, ±φ) 0, -r, -t2, 0, -r, t2, 0, r, -t2, 0, r, t2, // (±1/φ, ±φ, 0) -r, -t2, 0, -r, t2, 0, r, -t2, 0, r, t2, 0, // (±φ, 0, ±1/φ) -t2, 0, -r, t2, 0, -r, -t2, 0, r, t2, 0, r ]; const indices = [ 3, 11, 7, 3, 7, 15, 3, 15, 13, 7, 19, 17, 7, 17, 6, 7, 6, 15, 17, 4, 8, 17, 8, 10, 17, 10, 6, 8, 0, 16, 8, 16, 2, 8, 2, 10, 0, 12, 1, 0, 1, 18, 0, 18, 16, 6, 10, 2, 6, 2, 13, 6, 13, 15, 2, 16, 18, 2, 18, 3, 2, 3, 13, 18, 1, 9, 18, 9, 11, 18, 11, 3, 4, 14, 12, 4, 12, 0, 4, 0, 8, 11, 9, 5, 11, 5, 19, 11, 19, 7, 19, 5, 14, 19, 14, 4, 19, 4, 17, 1, 12, 14, 1, 14, 5, 1, 5, 9 ]; super(vertices, indices, radius, detail); this.type = "DodecahedronGeometry"; this.parameters = { radius, detail }; } static fromJSON(data) { return new _DodecahedronGeometry(data.radius, data.detail); } }; var _v0 = new Vector3(); var _v1$1 = new Vector3(); var _normal = new Vector3(); var _triangle = new Triangle(); var EdgesGeometry = class extends BufferGeometry { constructor(geometry = null, thresholdAngle = 1) { super(); this.type = "EdgesGeometry"; this.parameters = { geometry, thresholdAngle }; if (geometry !== null) { const precisionPoints = 4; const precision = Math.pow(10, precisionPoints); const thresholdDot = Math.cos(DEG2RAD * thresholdAngle); const indexAttr = geometry.getIndex(); const positionAttr = geometry.getAttribute("position"); const indexCount = indexAttr ? indexAttr.count : positionAttr.count; const indexArr = [0, 0, 0]; const vertKeys = ["a", "b", "c"]; const hashes = new Array(3); const edgeData = {}; const vertices = []; for (let i = 0; i < indexCount; i += 3) { if (indexAttr) { indexArr[0] = indexAttr.getX(i); indexArr[1] = indexAttr.getX(i + 1); indexArr[2] = indexAttr.getX(i + 2); } else { indexArr[0] = i; indexArr[1] = i + 1; indexArr[2] = i + 2; } const { a, b, c } = _triangle; a.fromBufferAttribute(positionAttr, indexArr[0]); b.fromBufferAttribute(positionAttr, indexArr[1]); c.fromBufferAttribute(positionAttr, indexArr[2]); _triangle.getNormal(_normal); hashes[0] = `${Math.round(a.x * precision)},${Math.round(a.y * precision)},${Math.round(a.z * precision)}`; hashes[1] = `${Math.round(b.x * precision)},${Math.round(b.y * precision)},${Math.round(b.z * precision)}`; hashes[2] = `${Math.round(c.x * precision)},${Math.round(c.y * precision)},${Math.round(c.z * precision)}`; if (hashes[0] === hashes[1] || hashes[1] === hashes[2] || hashes[2] === hashes[0]) { continue; } for (let j = 0; j < 3; j++) { const jNext = (j + 1) % 3; const vecHash0 = hashes[j]; const vecHash1 = hashes[jNext]; const v0 = _triangle[vertKeys[j]]; const v1 = _triangle[vertKeys[jNext]]; const hash = `${vecHash0}_${vecHash1}`; const reverseHash = `${vecHash1}_${vecHash0}`; if (reverseHash in edgeData && edgeData[reverseHash]) { if (_normal.dot(edgeData[reverseHash].normal) <= thresholdDot) { vertices.push(v0.x, v0.y, v0.z); vertices.push(v1.x, v1.y, v1.z); } edgeData[reverseHash] = null; } else if (!(hash in edgeData)) { edgeData[hash] = { index0: indexArr[j], index1: indexArr[jNext], normal: _normal.clone() }; } } } for (const key in edgeData) { if (edgeData[key]) { const { index0, index1 } = edgeData[key]; _v0.fromBufferAttribute(positionAttr, index0); _v1$1.fromBufferAttribute(positionAttr, index1); vertices.push(_v0.x, _v0.y, _v0.z); vertices.push(_v1$1.x, _v1$1.y, _v1$1.z); } } this.setAttribute("position", new Float32BufferAttribute(vertices, 3)); } } }; var Shape = class extends Path { constructor(points) { super(points); this.uuid = generateUUID(); this.type = "Shape"; this.holes = []; } getPointsHoles(divisions) { const holesPts = []; for (let i = 0, l = this.holes.length; i < l; i++) { holesPts[i] = this.holes[i].getPoints(divisions); } return holesPts; } // get points of shape and holes (keypoints based on segments parameter) extractPoints(divisions) { return { shape: this.getPoints(divisions), holes: this.getPointsHoles(divisions) }; } copy(source) { super.copy(source); this.holes = []; for (let i = 0, l = source.holes.length; i < l; i++) { const hole = source.holes[i]; this.holes.push(hole.clone()); } return this; } toJSON() { const data = super.toJSON(); data.uuid = this.uuid; data.holes = []; for (let i = 0, l = this.holes.length; i < l; i++) { const hole = this.holes[i]; data.holes.push(hole.toJSON()); } return data; } fromJSON(json) { super.fromJSON(json); this.uuid = json.uuid; this.holes = []; for (let i = 0, l = json.holes.length; i < l; i++) { const hole = json.holes[i]; this.holes.push(new Path().fromJSON(hole)); } return this; } }; var Earcut = { triangulate: function(data, holeIndices, dim = 2) { const hasHoles = holeIndices && holeIndices.length; const outerLen = hasHoles ? holeIndices[0] * dim : data.length; let outerNode = linkedList(data, 0, outerLen, dim, true); const triangles = []; if (!outerNode || outerNode.next === outerNode.prev) return triangles; let minX, minY, maxX, maxY, x2, y, invSize; if (hasHoles) outerNode = eliminateHoles(data, holeIndices, outerNode, dim); if (data.length > 80 * dim) { minX = maxX = data[0]; minY = maxY = data[1]; for (let i = dim; i < outerLen; i += dim) { x2 = data[i]; y = data[i + 1]; if (x2 < minX) minX = x2; if (y < minY) minY = y; if (x2 > maxX) maxX = x2; if (y > maxY) maxY = y; } invSize = Math.max(maxX - minX, maxY - minY); invSize = invSize !== 0 ? 32767 / invSize : 0; } earcutLinked(outerNode, triangles, dim, minX, minY, invSize, 0); return triangles; } }; function linkedList(data, start, end, dim, clockwise) { let i, last; if (clockwise === signedArea(data, start, end, dim) > 0) { for (i = start; i < end; i += dim) last = insertNode(i, data[i], data[i + 1], last); } else { for (i = end - dim; i >= start; i -= dim) last = insertNode(i, data[i], data[i + 1], last); } if (last && equals(last, last.next)) { removeNode(last); last = last.next; } return last; } function filterPoints(start, end) { if (!start) return start; if (!end) end = start; let p2 = start, again; do { again = false; if (!p2.steiner && (equals(p2, p2.next) || area(p2.prev, p2, p2.next) === 0)) { removeNode(p2); p2 = end = p2.prev; if (p2 === p2.next) break; again = true; } else { p2 = p2.next; } } while (again || p2 !== end); return end; } function earcutLinked(ear, triangles, dim, minX, minY, invSize, pass) { if (!ear) return; if (!pass && invSize) indexCurve(ear, minX, minY, invSize); let stop = ear, prev, next; while (ear.prev !== ear.next) { prev = ear.prev; next = ear.next; if (invSize ? isEarHashed(ear, minX, minY, invSize) : isEar(ear)) { triangles.push(prev.i / dim | 0); triangles.push(ear.i / dim | 0); triangles.push(next.i / dim | 0); removeNode(ear); ear = next.next; stop = next.next; continue; } ear = next; if (ear === stop) { if (!pass) { earcutLinked(filterPoints(ear), triangles, dim, minX, minY, invSize, 1); } else if (pass === 1) { ear = cureLocalIntersections(filterPoints(ear), triangles, dim); earcutLinked(ear, triangles, dim, minX, minY, invSize, 2); } else if (pass === 2) { splitEarcut(ear, triangles, dim, minX, minY, invSize); } break; } } } function isEar(ear) { const a = ear.prev, b = ear, c = ear.next; if (area(a, b, c) >= 0) return false; const ax = a.x, bx = b.x, cx = c.x, ay = a.y, by = b.y, cy = c.y; const x0 = ax < bx ? ax < cx ? ax : cx : bx < cx ? bx : cx, y0 = ay < by ? ay < cy ? ay : cy : by < cy ? by : cy, x1 = ax > bx ? ax > cx ? ax : cx : bx > cx ? bx : cx, y1 = ay > by ? ay > cy ? ay : cy : by > cy ? by : cy; let p2 = c.next; while (p2 !== a) { if (p2.x >= x0 && p2.x <= x1 && p2.y >= y0 && p2.y <= y1 && pointInTriangle(ax, ay, bx, by, cx, cy, p2.x, p2.y) && area(p2.prev, p2, p2.next) >= 0) return false; p2 = p2.next; } return true; } function isEarHashed(ear, minX, minY, invSize) { const a = ear.prev, b = ear, c = ear.next; if (area(a, b, c) >= 0) return false; const ax = a.x, bx = b.x, cx = c.x, ay = a.y, by = b.y, cy = c.y; const x0 = ax < bx ? ax < cx ? ax : cx : bx < cx ? bx : cx, y0 = ay < by ? ay < cy ? ay : cy : by < cy ? by : cy, x1 = ax > bx ? ax > cx ? ax : cx : bx > cx ? bx : cx, y1 = ay > by ? ay > cy ? ay : cy : by > cy ? by : cy; const minZ = zOrder(x0, y0, minX, minY, invSize), maxZ = zOrder(x1, y1, minX, minY, invSize); let p2 = ear.prevZ, n2 = ear.nextZ; while (p2 && p2.z >= minZ && n2 && n2.z <= maxZ) { if (p2.x >= x0 && p2.x <= x1 && p2.y >= y0 && p2.y <= y1 && p2 !== a && p2 !== c && pointInTriangle(ax, ay, bx, by, cx, cy, p2.x, p2.y) && area(p2.prev, p2, p2.next) >= 0) return false; p2 = p2.prevZ; if (n2.x >= x0 && n2.x <= x1 && n2.y >= y0 && n2.y <= y1 && n2 !== a && n2 !== c && pointInTriangle(ax, ay, bx, by, cx, cy, n2.x, n2.y) && area(n2.prev, n2, n2.next) >= 0) return false; n2 = n2.nextZ; } while (p2 && p2.z >= minZ) { if (p2.x >= x0 && p2.x <= x1 && p2.y >= y0 && p2.y <= y1 && p2 !== a && p2 !== c && pointInTriangle(ax, ay, bx, by, cx, cy, p2.x, p2.y) && area(p2.prev, p2, p2.next) >= 0) return false; p2 = p2.prevZ; } while (n2 && n2.z <= maxZ) { if (n2.x >= x0 && n2.x <= x1 && n2.y >= y0 && n2.y <= y1 && n2 !== a && n2 !== c && pointInTriangle(ax, ay, bx, by, cx, cy, n2.x, n2.y) && area(n2.prev, n2, n2.next) >= 0) return false; n2 = n2.nextZ; } return true; } function cureLocalIntersections(start, triangles, dim) { let p2 = start; do { const a = p2.prev, b = p2.next.next; if (!equals(a, b) && intersects(a, p2, p2.next, b) && locallyInside(a, b) && locallyInside(b, a)) { triangles.push(a.i / dim | 0); triangles.push(p2.i / dim | 0); triangles.push(b.i / dim | 0); removeNode(p2); removeNode(p2.next); p2 = start = b; } p2 = p2.next; } while (p2 !== start); return filterPoints(p2); } function splitEarcut(start, triangles, dim, minX, minY, invSize) { let a = start; do { let b = a.next.next; while (b !== a.prev) { if (a.i !== b.i && isValidDiagonal(a, b)) { let c = splitPolygon(a, b); a = filterPoints(a, a.next); c = filterPoints(c, c.next); earcutLinked(a, triangles, dim, minX, minY, invSize, 0); earcutLinked(c, triangles, dim, minX, minY, invSize, 0); return; } b = b.next; } a = a.next; } while (a !== start); } function eliminateHoles(data, holeIndices, outerNode, dim) { const queue = []; let i, len, start, end, list; for (i = 0, len = holeIndices.length; i < len; i++) { start = holeIndices[i] * dim; end = i < len - 1 ? holeIndices[i + 1] * dim : data.length; list = linkedList(data, start, end, dim, false); if (list === list.next) list.steiner = true; queue.push(getLeftmost(list)); } queue.sort(compareX); for (i = 0; i < queue.length; i++) { outerNode = eliminateHole(queue[i], outerNode); } return outerNode; } function compareX(a, b) { return a.x - b.x; } function eliminateHole(hole, outerNode) { const bridge = findHoleBridge(hole, outerNode); if (!bridge) { return outerNode; } const bridgeReverse = splitPolygon(bridge, hole); filterPoints(bridgeReverse, bridgeReverse.next); return filterPoints(bridge, bridge.next); } function findHoleBridge(hole, outerNode) { let p2 = outerNode, qx = -Infinity, m; const hx = hole.x, hy = hole.y; do { if (hy <= p2.y && hy >= p2.next.y && p2.next.y !== p2.y) { const x2 = p2.x + (hy - p2.y) * (p2.next.x - p2.x) / (p2.next.y - p2.y); if (x2 <= hx && x2 > qx) { qx = x2; m = p2.x < p2.next.x ? p2 : p2.next; if (x2 === hx) return m; } } p2 = p2.next; } while (p2 !== outerNode); if (!m) return null; const stop = m, mx = m.x, my = m.y; let tanMin = Infinity, tan; p2 = m; do { if (hx >= p2.x && p2.x >= mx && hx !== p2.x && pointInTriangle(hy < my ? hx : qx, hy, mx, my, hy < my ? qx : hx, hy, p2.x, p2.y)) { tan = Math.abs(hy - p2.y) / (hx - p2.x); if (locallyInside(p2, hole) && (tan < tanMin || tan === tanMin && (p2.x > m.x || p2.x === m.x && sectorContainsSector(m, p2)))) { m = p2; tanMin = tan; } } p2 = p2.next; } while (p2 !== stop); return m; } function sectorContainsSector(m, p2) { return area(m.prev, m, p2.prev) < 0 && area(p2.next, m, m.next) < 0; } function indexCurve(start, minX, minY, invSize) { let p2 = start; do { if (p2.z === 0) p2.z = zOrder(p2.x, p2.y, minX, minY, invSize); p2.prevZ = p2.prev; p2.nextZ = p2.next; p2 = p2.next; } while (p2 !== start); p2.prevZ.nextZ = null; p2.prevZ = null; sortLinked(p2); } function sortLinked(list) { let i, p2, q, e, tail, numMerges, pSize, qSize, inSize = 1; do { p2 = list; list = null; tail = null; numMerges = 0; while (p2) { numMerges++; q = p2; pSize = 0; for (i = 0; i < inSize; i++) { pSize++; q = q.nextZ; if (!q) break; } qSize = inSize; while (pSize > 0 || qSize > 0 && q) { if (pSize !== 0 && (qSize === 0 || !q || p2.z <= q.z)) { e = p2; p2 = p2.nextZ; pSize--; } else { e = q; q = q.nextZ; qSize--; } if (tail) tail.nextZ = e; else list = e; e.prevZ = tail; tail = e; } p2 = q; } tail.nextZ = null; inSize *= 2; } while (numMerges > 1); return list; } function zOrder(x2, y, minX, minY, invSize) { x2 = (x2 - minX) * invSize | 0; y = (y - minY) * invSize | 0; x2 = (x2 | x2 << 8) & 16711935; x2 = (x2 | x2 << 4) & 252645135; x2 = (x2 | x2 << 2) & 858993459; x2 = (x2 | x2 << 1) & 1431655765; y = (y | y << 8) & 16711935; y = (y | y << 4) & 252645135; y = (y | y << 2) & 858993459; y = (y | y << 1) & 1431655765; return x2 | y << 1; } function getLeftmost(start) { let p2 = start, leftmost = start; do { if (p2.x < leftmost.x || p2.x === leftmost.x && p2.y < leftmost.y) leftmost = p2; p2 = p2.next; } while (p2 !== start); return leftmost; } function pointInTriangle(ax, ay, bx, by, cx, cy, px2, py2) { return (cx - px2) * (ay - py2) >= (ax - px2) * (cy - py2) && (ax - px2) * (by - py2) >= (bx - px2) * (ay - py2) && (bx - px2) * (cy - py2) >= (cx - px2) * (by - py2); } function isValidDiagonal(a, b) { return a.next.i !== b.i && a.prev.i !== b.i && !intersectsPolygon(a, b) && // dones't intersect other edges (locallyInside(a, b) && locallyInside(b, a) && middleInside(a, b) && // locally visible (area(a.prev, a, b.prev) || area(a, b.prev, b)) || // does not create opposite-facing sectors equals(a, b) && area(a.prev, a, a.next) > 0 && area(b.prev, b, b.next) > 0); } function area(p2, q, r) { return (q.y - p2.y) * (r.x - q.x) - (q.x - p2.x) * (r.y - q.y); } function equals(p1, p2) { return p1.x === p2.x && p1.y === p2.y; } function intersects(p1, q1, p2, q2) { const o1 = sign(area(p1, q1, p2)); const o2 = sign(area(p1, q1, q2)); const o3 = sign(area(p2, q2, p1)); const o4 = sign(area(p2, q2, q1)); if (o1 !== o2 && o3 !== o4) return true; if (o1 === 0 && onSegment(p1, p2, q1)) return true; if (o2 === 0 && onSegment(p1, q2, q1)) return true; if (o3 === 0 && onSegment(p2, p1, q2)) return true; if (o4 === 0 && onSegment(p2, q1, q2)) return true; return false; } function onSegment(p2, q, r) { return q.x <= Math.max(p2.x, r.x) && q.x >= Math.min(p2.x, r.x) && q.y <= Math.max(p2.y, r.y) && q.y >= Math.min(p2.y, r.y); } function sign(num) { return num > 0 ? 1 : num < 0 ? -1 : 0; } function intersectsPolygon(a, b) { let p2 = a; do { if (p2.i !== a.i && p2.next.i !== a.i && p2.i !== b.i && p2.next.i !== b.i && intersects(p2, p2.next, a, b)) return true; p2 = p2.next; } while (p2 !== a); return false; } function locallyInside(a, b) { return area(a.prev, a, a.next) < 0 ? area(a, b, a.next) >= 0 && area(a, a.prev, b) >= 0 : area(a, b, a.prev) < 0 || area(a, a.next, b) < 0; } function middleInside(a, b) { let p2 = a, inside = false; const px2 = (a.x + b.x) / 2, py2 = (a.y + b.y) / 2; do { if (p2.y > py2 !== p2.next.y > py2 && p2.next.y !== p2.y && px2 < (p2.next.x - p2.x) * (py2 - p2.y) / (p2.next.y - p2.y) + p2.x) inside = !inside; p2 = p2.next; } while (p2 !== a); return inside; } function splitPolygon(a, b) { const a2 = new Node2(a.i, a.x, a.y), b22 = new Node2(b.i, b.x, b.y), an = a.next, bp = b.prev; a.next = b; b.prev = a; a2.next = an; an.prev = a2; b22.next = a2; a2.prev = b22; bp.next = b22; b22.prev = bp; return b22; } function insertNode(i, x2, y, last) { const p2 = new Node2(i, x2, y); if (!last) { p2.prev = p2; p2.next = p2; } else { p2.next = last.next; p2.prev = last; last.next.prev = p2; last.next = p2; } return p2; } function removeNode(p2) { p2.next.prev = p2.prev; p2.prev.next = p2.next; if (p2.prevZ) p2.prevZ.nextZ = p2.nextZ; if (p2.nextZ) p2.nextZ.prevZ = p2.prevZ; } function Node2(i, x2, y) { this.i = i; this.x = x2; this.y = y; this.prev = null; this.next = null; this.z = 0; this.prevZ = null; this.nextZ = null; this.steiner = false; } function signedArea(data, start, end, dim) { let sum = 0; for (let i = start, j = end - dim; i < end; i += dim) { sum += (data[j] - data[i]) * (data[i + 1] + data[j + 1]); j = i; } return sum; } var ShapeUtils = class _ShapeUtils { // calculate area of the contour polygon static area(contour) { const n2 = contour.length; let a = 0; for (let p2 = n2 - 1, q = 0; q < n2; p2 = q++) { a += contour[p2].x * contour[q].y - contour[q].x * contour[p2].y; } return a * 0.5; } static isClockWise(pts) { return _ShapeUtils.area(pts) < 0; } static triangulateShape(contour, holes) { const vertices = []; const holeIndices = []; const faces = []; removeDupEndPts(contour); addContour(vertices, contour); let holeIndex = contour.length; holes.forEach(removeDupEndPts); for (let i = 0; i < holes.length; i++) { holeIndices.push(holeIndex); holeIndex += holes[i].length; addContour(vertices, holes[i]); } const triangles = Earcut.triangulate(vertices, holeIndices); for (let i = 0; i < triangles.length; i += 3) { faces.push(triangles.slice(i, i + 3)); } return faces; } }; function removeDupEndPts(points) { const l = points.length; if (l > 2 && points[l - 1].equals(points[0])) { points.pop(); } } function addContour(vertices, contour) { for (let i = 0; i < contour.length; i++) { vertices.push(contour[i].x); vertices.push(contour[i].y); } } var ExtrudeGeometry = class _ExtrudeGeometry extends BufferGeometry { constructor(shapes = new Shape([new Vector2(0.5, 0.5), new Vector2(-0.5, 0.5), new Vector2(-0.5, -0.5), new Vector2(0.5, -0.5)]), options = {}) { super(); this.type = "ExtrudeGeometry"; this.parameters = { shapes, options }; shapes = Array.isArray(shapes) ? shapes : [shapes]; const scope = this; const verticesArray = []; const uvArray = []; for (let i = 0, l = shapes.length; i < l; i++) { const shape = shapes[i]; addShape(shape); } this.setAttribute("position", new Float32BufferAttribute(verticesArray, 3)); this.setAttribute("uv", new Float32BufferAttribute(uvArray, 2)); this.computeVertexNormals(); function addShape(shape) { const placeholder = []; const curveSegments = options.curveSegments !== void 0 ? options.curveSegments : 12; const steps = options.steps !== void 0 ? options.steps : 1; const depth = options.depth !== void 0 ? options.depth : 1; let bevelEnabled = options.bevelEnabled !== void 0 ? options.bevelEnabled : true; let bevelThickness = options.bevelThickness !== void 0 ? options.bevelThickness : 0.2; let bevelSize = options.bevelSize !== void 0 ? options.bevelSize : bevelThickness - 0.1; let bevelOffset = options.bevelOffset !== void 0 ? options.bevelOffset : 0; let bevelSegments = options.bevelSegments !== void 0 ? options.bevelSegments : 3; const extrudePath = options.extrudePath; const uvgen = options.UVGenerator !== void 0 ? options.UVGenerator : WorldUVGenerator; let extrudePts, extrudeByPath = false; let splineTube, binormal, normal, position2; if (extrudePath) { extrudePts = extrudePath.getSpacedPoints(steps); extrudeByPath = true; bevelEnabled = false; splineTube = extrudePath.computeFrenetFrames(steps, false); binormal = new Vector3(); normal = new Vector3(); position2 = new Vector3(); } if (!bevelEnabled) { bevelSegments = 0; bevelThickness = 0; bevelSize = 0; bevelOffset = 0; } const shapePoints = shape.extractPoints(curveSegments); let vertices = shapePoints.shape; const holes = shapePoints.holes; const reverse = !ShapeUtils.isClockWise(vertices); if (reverse) { vertices = vertices.reverse(); for (let h = 0, hl = holes.length; h < hl; h++) { const ahole = holes[h]; if (ShapeUtils.isClockWise(ahole)) { holes[h] = ahole.reverse(); } } } const faces = ShapeUtils.triangulateShape(vertices, holes); const contour = vertices; for (let h = 0, hl = holes.length; h < hl; h++) { const ahole = holes[h]; vertices = vertices.concat(ahole); } function scalePt2(pt, vec, size) { if (!vec) console.error("THREE.ExtrudeGeometry: vec does not exist"); return vec.clone().multiplyScalar(size).add(pt); } const vlen = vertices.length, flen = faces.length; function getBevelVec(inPt, inPrev, inNext) { let v_trans_x, v_trans_y, shrink_by; const v_prev_x = inPt.x - inPrev.x, v_prev_y = inPt.y - inPrev.y; const v_next_x = inNext.x - inPt.x, v_next_y = inNext.y - inPt.y; const v_prev_lensq = v_prev_x * v_prev_x + v_prev_y * v_prev_y; const collinear0 = v_prev_x * v_next_y - v_prev_y * v_next_x; if (Math.abs(collinear0) > Number.EPSILON) { const v_prev_len = Math.sqrt(v_prev_lensq); const v_next_len = Math.sqrt(v_next_x * v_next_x + v_next_y * v_next_y); const ptPrevShift_x = inPrev.x - v_prev_y / v_prev_len; const ptPrevShift_y = inPrev.y + v_prev_x / v_prev_len; const ptNextShift_x = inNext.x - v_next_y / v_next_len; const ptNextShift_y = inNext.y + v_next_x / v_next_len; const sf = ((ptNextShift_x - ptPrevShift_x) * v_next_y - (ptNextShift_y - ptPrevShift_y) * v_next_x) / (v_prev_x * v_next_y - v_prev_y * v_next_x); v_trans_x = ptPrevShift_x + v_prev_x * sf - inPt.x; v_trans_y = ptPrevShift_y + v_prev_y * sf - inPt.y; const v_trans_lensq = v_trans_x * v_trans_x + v_trans_y * v_trans_y; if (v_trans_lensq <= 2) { return new Vector2(v_trans_x, v_trans_y); } else { shrink_by = Math.sqrt(v_trans_lensq / 2); } } else { let direction_eq = false; if (v_prev_x > Number.EPSILON) { if (v_next_x > Number.EPSILON) { direction_eq = true; } } else { if (v_prev_x < -Number.EPSILON) { if (v_next_x < -Number.EPSILON) { direction_eq = true; } } else { if (Math.sign(v_prev_y) === Math.sign(v_next_y)) { direction_eq = true; } } } if (direction_eq) { v_trans_x = -v_prev_y; v_trans_y = v_prev_x; shrink_by = Math.sqrt(v_prev_lensq); } else { v_trans_x = v_prev_x; v_trans_y = v_prev_y; shrink_by = Math.sqrt(v_prev_lensq / 2); } } return new Vector2(v_trans_x / shrink_by, v_trans_y / shrink_by); } const contourMovements = []; for (let i = 0, il = contour.length, j = il - 1, k = i + 1; i < il; i++, j++, k++) { if (j === il) j = 0; if (k === il) k = 0; contourMovements[i] = getBevelVec(contour[i], contour[j], contour[k]); } const holesMovements = []; let oneHoleMovements, verticesMovements = contourMovements.concat(); for (let h = 0, hl = holes.length; h < hl; h++) { const ahole = holes[h]; oneHoleMovements = []; for (let i = 0, il = ahole.length, j = il - 1, k = i + 1; i < il; i++, j++, k++) { if (j === il) j = 0; if (k === il) k = 0; oneHoleMovements[i] = getBevelVec(ahole[i], ahole[j], ahole[k]); } holesMovements.push(oneHoleMovements); verticesMovements = verticesMovements.concat(oneHoleMovements); } for (let b = 0; b < bevelSegments; b++) { const t2 = b / bevelSegments; const z = bevelThickness * Math.cos(t2 * Math.PI / 2); const bs2 = bevelSize * Math.sin(t2 * Math.PI / 2) + bevelOffset; for (let i = 0, il = contour.length; i < il; i++) { const vert = scalePt2(contour[i], contourMovements[i], bs2); v(vert.x, vert.y, -z); } for (let h = 0, hl = holes.length; h < hl; h++) { const ahole = holes[h]; oneHoleMovements = holesMovements[h]; for (let i = 0, il = ahole.length; i < il; i++) { const vert = scalePt2(ahole[i], oneHoleMovements[i], bs2); v(vert.x, vert.y, -z); } } } const bs = bevelSize + bevelOffset; for (let i = 0; i < vlen; i++) { const vert = bevelEnabled ? scalePt2(vertices[i], verticesMovements[i], bs) : vertices[i]; if (!extrudeByPath) { v(vert.x, vert.y, 0); } else { normal.copy(splineTube.normals[0]).multiplyScalar(vert.x); binormal.copy(splineTube.binormals[0]).multiplyScalar(vert.y); position2.copy(extrudePts[0]).add(normal).add(binormal); v(position2.x, position2.y, position2.z); } } for (let s = 1; s <= steps; s++) { for (let i = 0; i < vlen; i++) { const vert = bevelEnabled ? scalePt2(vertices[i], verticesMovements[i], bs) : vertices[i]; if (!extrudeByPath) { v(vert.x, vert.y, depth / steps * s); } else { normal.copy(splineTube.normals[s]).multiplyScalar(vert.x); binormal.copy(splineTube.binormals[s]).multiplyScalar(vert.y); position2.copy(extrudePts[s]).add(normal).add(binormal); v(position2.x, position2.y, position2.z); } } } for (let b = bevelSegments - 1; b >= 0; b--) { const t2 = b / bevelSegments; const z = bevelThickness * Math.cos(t2 * Math.PI / 2); const bs2 = bevelSize * Math.sin(t2 * Math.PI / 2) + bevelOffset; for (let i = 0, il = contour.length; i < il; i++) { const vert = scalePt2(contour[i], contourMovements[i], bs2); v(vert.x, vert.y, depth + z); } for (let h = 0, hl = holes.length; h < hl; h++) { const ahole = holes[h]; oneHoleMovements = holesMovements[h]; for (let i = 0, il = ahole.length; i < il; i++) { const vert = scalePt2(ahole[i], oneHoleMovements[i], bs2); if (!extrudeByPath) { v(vert.x, vert.y, depth + z); } else { v(vert.x, vert.y + extrudePts[steps - 1].y, extrudePts[steps - 1].x + z); } } } } buildLidFaces(); buildSideFaces(); function buildLidFaces() { const start = verticesArray.length / 3; if (bevelEnabled) { let layer = 0; let offset = vlen * layer; for (let i = 0; i < flen; i++) { const face = faces[i]; f3(face[2] + offset, face[1] + offset, face[0] + offset); } layer = steps + bevelSegments * 2; offset = vlen * layer; for (let i = 0; i < flen; i++) { const face = faces[i]; f3(face[0] + offset, face[1] + offset, face[2] + offset); } } else { for (let i = 0; i < flen; i++) { const face = faces[i]; f3(face[2], face[1], face[0]); } for (let i = 0; i < flen; i++) { const face = faces[i]; f3(face[0] + vlen * steps, face[1] + vlen * steps, face[2] + vlen * steps); } } scope.addGroup(start, verticesArray.length / 3 - start, 0); } function buildSideFaces() { const start = verticesArray.length / 3; let layeroffset = 0; sidewalls(contour, layeroffset); layeroffset += contour.length; for (let h = 0, hl = holes.length; h < hl; h++) { const ahole = holes[h]; sidewalls(ahole, layeroffset); layeroffset += ahole.length; } scope.addGroup(start, verticesArray.length / 3 - start, 1); } function sidewalls(contour2, layeroffset) { let i = contour2.length; while (--i >= 0) { const j = i; let k = i - 1; if (k < 0) k = contour2.length - 1; for (let s = 0, sl = steps + bevelSegments * 2; s < sl; s++) { const slen1 = vlen * s; const slen2 = vlen * (s + 1); const a = layeroffset + j + slen1, b = layeroffset + k + slen1, c = layeroffset + k + slen2, d = layeroffset + j + slen2; f4(a, b, c, d); } } } function v(x2, y, z) { placeholder.push(x2); placeholder.push(y); placeholder.push(z); } function f3(a, b, c) { addVertex(a); addVertex(b); addVertex(c); const nextIndex = verticesArray.length / 3; const uvs = uvgen.generateTopUV(scope, verticesArray, nextIndex - 3, nextIndex - 2, nextIndex - 1); addUV(uvs[0]); addUV(uvs[1]); addUV(uvs[2]); } function f4(a, b, c, d) { addVertex(a); addVertex(b); addVertex(d); addVertex(b); addVertex(c); addVertex(d); const nextIndex = verticesArray.length / 3; const uvs = uvgen.generateSideWallUV(scope, verticesArray, nextIndex - 6, nextIndex - 3, nextIndex - 2, nextIndex - 1); addUV(uvs[0]); addUV(uvs[1]); addUV(uvs[3]); addUV(uvs[1]); addUV(uvs[2]); addUV(uvs[3]); } function addVertex(index) { verticesArray.push(placeholder[index * 3 + 0]); verticesArray.push(placeholder[index * 3 + 1]); verticesArray.push(placeholder[index * 3 + 2]); } function addUV(vector23) { uvArray.push(vector23.x); uvArray.push(vector23.y); } } } toJSON() { const data = super.toJSON(); const shapes = this.parameters.shapes; const options = this.parameters.options; return toJSON$1(shapes, options, data); } static fromJSON(data, shapes) { const geometryShapes = []; for (let j = 0, jl = data.shapes.length; j < jl; j++) { const shape = shapes[data.shapes[j]]; geometryShapes.push(shape); } const extrudePath = data.options.extrudePath; if (extrudePath !== void 0) { data.options.extrudePath = new Curves[extrudePath.type]().fromJSON(extrudePath); } return new _ExtrudeGeometry(geometryShapes, data.options); } }; var WorldUVGenerator = { generateTopUV: function(geometry, vertices, indexA, indexB, indexC) { const a_x = vertices[indexA * 3]; const a_y = vertices[indexA * 3 + 1]; const b_x = vertices[indexB * 3]; const b_y = vertices[indexB * 3 + 1]; const c_x = vertices[indexC * 3]; const c_y = vertices[indexC * 3 + 1]; return [ new Vector2(a_x, a_y), new Vector2(b_x, b_y), new Vector2(c_x, c_y) ]; }, generateSideWallUV: function(geometry, vertices, indexA, indexB, indexC, indexD) { const a_x = vertices[indexA * 3]; const a_y = vertices[indexA * 3 + 1]; const a_z = vertices[indexA * 3 + 2]; const b_x = vertices[indexB * 3]; const b_y = vertices[indexB * 3 + 1]; const b_z = vertices[indexB * 3 + 2]; const c_x = vertices[indexC * 3]; const c_y = vertices[indexC * 3 + 1]; const c_z = vertices[indexC * 3 + 2]; const d_x = vertices[indexD * 3]; const d_y = vertices[indexD * 3 + 1]; const d_z = vertices[indexD * 3 + 2]; if (Math.abs(a_y - b_y) < Math.abs(a_x - b_x)) { return [ new Vector2(a_x, 1 - a_z), new Vector2(b_x, 1 - b_z), new Vector2(c_x, 1 - c_z), new Vector2(d_x, 1 - d_z) ]; } else { return [ new Vector2(a_y, 1 - a_z), new Vector2(b_y, 1 - b_z), new Vector2(c_y, 1 - c_z), new Vector2(d_y, 1 - d_z) ]; } } }; function toJSON$1(shapes, options, data) { data.shapes = []; if (Array.isArray(shapes)) { for (let i = 0, l = shapes.length; i < l; i++) { const shape = shapes[i]; data.shapes.push(shape.uuid); } } else { data.shapes.push(shapes.uuid); } data.options = Object.assign({}, options); if (options.extrudePath !== void 0) data.options.extrudePath = options.extrudePath.toJSON(); return data; } var IcosahedronGeometry = class _IcosahedronGeometry extends PolyhedronGeometry { constructor(radius = 1, detail = 0) { const t2 = (1 + Math.sqrt(5)) / 2; const vertices = [ -1, t2, 0, 1, t2, 0, -1, -t2, 0, 1, -t2, 0, 0, -1, t2, 0, 1, t2, 0, -1, -t2, 0, 1, -t2, t2, 0, -1, t2, 0, 1, -t2, 0, -1, -t2, 0, 1 ]; const indices = [ 0, 11, 5, 0, 5, 1, 0, 1, 7, 0, 7, 10, 0, 10, 11, 1, 5, 9, 5, 11, 4, 11, 10, 2, 10, 7, 6, 7, 1, 8, 3, 9, 4, 3, 4, 2, 3, 2, 6, 3, 6, 8, 3, 8, 9, 4, 9, 5, 2, 4, 11, 6, 2, 10, 8, 6, 7, 9, 8, 1 ]; super(vertices, indices, radius, detail); this.type = "IcosahedronGeometry"; this.parameters = { radius, detail }; } static fromJSON(data) { return new _IcosahedronGeometry(data.radius, data.detail); } }; var OctahedronGeometry = class _OctahedronGeometry extends PolyhedronGeometry { constructor(radius = 1, detail = 0) { const vertices = [ 1, 0, 0, -1, 0, 0, 0, 1, 0, 0, -1, 0, 0, 0, 1, 0, 0, -1 ]; const indices = [ 0, 2, 4, 0, 4, 3, 0, 3, 5, 0, 5, 2, 1, 2, 5, 1, 5, 3, 1, 3, 4, 1, 4, 2 ]; super(vertices, indices, radius, detail); this.type = "OctahedronGeometry"; this.parameters = { radius, detail }; } static fromJSON(data) { return new _OctahedronGeometry(data.radius, data.detail); } }; var RingGeometry = class _RingGeometry extends BufferGeometry { constructor(innerRadius = 0.5, outerRadius = 1, thetaSegments = 8, phiSegments = 1, thetaStart = 0, thetaLength = Math.PI * 2) { super(); this.type = "RingGeometry"; this.parameters = { innerRadius, outerRadius, thetaSegments, phiSegments, thetaStart, thetaLength }; thetaSegments = Math.max(3, thetaSegments); phiSegments = Math.max(1, phiSegments); const indices = []; const vertices = []; const normals = []; const uvs = []; let radius = innerRadius; const radiusStep = (outerRadius - innerRadius) / phiSegments; const vertex2 = new Vector3(); const uv = new Vector2(); for (let j = 0; j <= phiSegments; j++) { for (let i = 0; i <= thetaSegments; i++) { const segment = thetaStart + i / thetaSegments * thetaLength; vertex2.x = radius * Math.cos(segment); vertex2.y = radius * Math.sin(segment); vertices.push(vertex2.x, vertex2.y, vertex2.z); normals.push(0, 0, 1); uv.x = (vertex2.x / outerRadius + 1) / 2; uv.y = (vertex2.y / outerRadius + 1) / 2; uvs.push(uv.x, uv.y); } radius += radiusStep; } for (let j = 0; j < phiSegments; j++) { const thetaSegmentLevel = j * (thetaSegments + 1); for (let i = 0; i < thetaSegments; i++) { const segment = i + thetaSegmentLevel; const a = segment; const b = segment + thetaSegments + 1; const c = segment + thetaSegments + 2; const d = segment + 1; indices.push(a, b, d); indices.push(b, c, d); } } this.setIndex(indices); this.setAttribute("position", new Float32BufferAttribute(vertices, 3)); this.setAttribute("normal", new Float32BufferAttribute(normals, 3)); this.setAttribute("uv", new Float32BufferAttribute(uvs, 2)); } static fromJSON(data) { return new _RingGeometry(data.innerRadius, data.outerRadius, data.thetaSegments, data.phiSegments, data.thetaStart, data.thetaLength); } }; var ShapeGeometry = class _ShapeGeometry extends BufferGeometry { constructor(shapes = new Shape([new Vector2(0, 0.5), new Vector2(-0.5, -0.5), new Vector2(0.5, -0.5)]), curveSegments = 12) { super(); this.type = "ShapeGeometry"; this.parameters = { shapes, curveSegments }; const indices = []; const vertices = []; const normals = []; const uvs = []; let groupStart = 0; let groupCount = 0; if (Array.isArray(shapes) === false) { addShape(shapes); } else { for (let i = 0; i < shapes.length; i++) { addShape(shapes[i]); this.addGroup(groupStart, groupCount, i); groupStart += groupCount; groupCount = 0; } } this.setIndex(indices); this.setAttribute("position", new Float32BufferAttribute(vertices, 3)); this.setAttribute("normal", new Float32BufferAttribute(normals, 3)); this.setAttribute("uv", new Float32BufferAttribute(uvs, 2)); function addShape(shape) { const indexOffset = vertices.length / 3; const points = shape.extractPoints(curveSegments); let shapeVertices = points.shape; const shapeHoles = points.holes; if (ShapeUtils.isClockWise(shapeVertices) === false) { shapeVertices = shapeVertices.reverse(); } for (let i = 0, l = shapeHoles.length; i < l; i++) { const shapeHole = shapeHoles[i]; if (ShapeUtils.isClockWise(shapeHole) === true) { shapeHoles[i] = shapeHole.reverse(); } } const faces = ShapeUtils.triangulateShape(shapeVertices, shapeHoles); for (let i = 0, l = shapeHoles.length; i < l; i++) { const shapeHole = shapeHoles[i]; shapeVertices = shapeVertices.concat(shapeHole); } for (let i = 0, l = shapeVertices.length; i < l; i++) { const vertex2 = shapeVertices[i]; vertices.push(vertex2.x, vertex2.y, 0); normals.push(0, 0, 1); uvs.push(vertex2.x, vertex2.y); } for (let i = 0, l = faces.length; i < l; i++) { const face = faces[i]; const a = face[0] + indexOffset; const b = face[1] + indexOffset; const c = face[2] + indexOffset; indices.push(a, b, c); groupCount += 3; } } } toJSON() { const data = super.toJSON(); const shapes = this.parameters.shapes; return toJSON(shapes, data); } static fromJSON(data, shapes) { const geometryShapes = []; for (let j = 0, jl = data.shapes.length; j < jl; j++) { const shape = shapes[data.shapes[j]]; geometryShapes.push(shape); } return new _ShapeGeometry(geometryShapes, data.curveSegments); } }; function toJSON(shapes, data) { data.shapes = []; if (Array.isArray(shapes)) { for (let i = 0, l = shapes.length; i < l; i++) { const shape = shapes[i]; data.shapes.push(shape.uuid); } } else { data.shapes.push(shapes.uuid); } return data; } var SphereGeometry = class _SphereGeometry extends BufferGeometry { constructor(radius = 1, widthSegments = 32, heightSegments = 16, phiStart = 0, phiLength = Math.PI * 2, thetaStart = 0, thetaLength = Math.PI) { super(); this.type = "SphereGeometry"; this.parameters = { radius, widthSegments, heightSegments, phiStart, phiLength, thetaStart, thetaLength }; widthSegments = Math.max(3, Math.floor(widthSegments)); heightSegments = Math.max(2, Math.floor(heightSegments)); const thetaEnd = Math.min(thetaStart + thetaLength, Math.PI); let index = 0; const grid = []; const vertex2 = new Vector3(); const normal = new Vector3(); const indices = []; const vertices = []; const normals = []; const uvs = []; for (let iy = 0; iy <= heightSegments; iy++) { const verticesRow = []; const v = iy / heightSegments; let uOffset = 0; if (iy == 0 && thetaStart == 0) { uOffset = 0.5 / widthSegments; } else if (iy == heightSegments && thetaEnd == Math.PI) { uOffset = -0.5 / widthSegments; } for (let ix = 0; ix <= widthSegments; ix++) { const u = ix / widthSegments; vertex2.x = -radius * Math.cos(phiStart + u * phiLength) * Math.sin(thetaStart + v * thetaLength); vertex2.y = radius * Math.cos(thetaStart + v * thetaLength); vertex2.z = radius * Math.sin(phiStart + u * phiLength) * Math.sin(thetaStart + v * thetaLength); vertices.push(vertex2.x, vertex2.y, vertex2.z); normal.copy(vertex2).normalize(); normals.push(normal.x, normal.y, normal.z); uvs.push(u + uOffset, 1 - v); verticesRow.push(index++); } grid.push(verticesRow); } for (let iy = 0; iy < heightSegments; iy++) { for (let ix = 0; ix < widthSegments; ix++) { const a = grid[iy][ix + 1]; const b = grid[iy][ix]; const c = grid[iy + 1][ix]; const d = grid[iy + 1][ix + 1]; if (iy !== 0 || thetaStart > 0) indices.push(a, b, d); if (iy !== heightSegments - 1 || thetaEnd < Math.PI) indices.push(b, c, d); } } this.setIndex(indices); this.setAttribute("position", new Float32BufferAttribute(vertices, 3)); this.setAttribute("normal", new Float32BufferAttribute(normals, 3)); this.setAttribute("uv", new Float32BufferAttribute(uvs, 2)); } static fromJSON(data) { return new _SphereGeometry(data.radius, data.widthSegments, data.heightSegments, data.phiStart, data.phiLength, data.thetaStart, data.thetaLength); } }; var TetrahedronGeometry = class _TetrahedronGeometry extends PolyhedronGeometry { constructor(radius = 1, detail = 0) { const vertices = [ 1, 1, 1, -1, -1, 1, -1, 1, -1, 1, -1, -1 ]; const indices = [ 2, 1, 0, 0, 3, 2, 1, 3, 0, 2, 3, 1 ]; super(vertices, indices, radius, detail); this.type = "TetrahedronGeometry"; this.parameters = { radius, detail }; } static fromJSON(data) { return new _TetrahedronGeometry(data.radius, data.detail); } }; var TorusGeometry = class _TorusGeometry extends BufferGeometry { constructor(radius = 1, tube = 0.4, radialSegments = 8, tubularSegments = 6, arc = Math.PI * 2) { super(); this.type = "TorusGeometry"; this.parameters = { radius, tube, radialSegments, tubularSegments, arc }; radialSegments = Math.floor(radialSegments); tubularSegments = Math.floor(tubularSegments); const indices = []; const vertices = []; const normals = []; const uvs = []; const center = new Vector3(); const vertex2 = new Vector3(); const normal = new Vector3(); for (let j = 0; j <= radialSegments; j++) { for (let i = 0; i <= tubularSegments; i++) { const u = i / tubularSegments * arc; const v = j / radialSegments * Math.PI * 2; vertex2.x = (radius + tube * Math.cos(v)) * Math.cos(u); vertex2.y = (radius + tube * Math.cos(v)) * Math.sin(u); vertex2.z = tube * Math.sin(v); vertices.push(vertex2.x, vertex2.y, vertex2.z); center.x = radius * Math.cos(u); center.y = radius * Math.sin(u); normal.subVectors(vertex2, center).normalize(); normals.push(normal.x, normal.y, normal.z); uvs.push(i / tubularSegments); uvs.push(j / radialSegments); } } for (let j = 1; j <= radialSegments; j++) { for (let i = 1; i <= tubularSegments; i++) { const a = (tubularSegments + 1) * j + i - 1; const b = (tubularSegments + 1) * (j - 1) + i - 1; const c = (tubularSegments + 1) * (j - 1) + i; const d = (tubularSegments + 1) * j + i; indices.push(a, b, d); indices.push(b, c, d); } } this.setIndex(indices); this.setAttribute("position", new Float32BufferAttribute(vertices, 3)); this.setAttribute("normal", new Float32BufferAttribute(normals, 3)); this.setAttribute("uv", new Float32BufferAttribute(uvs, 2)); } static fromJSON(data) { return new _TorusGeometry(data.radius, data.tube, data.radialSegments, data.tubularSegments, data.arc); } }; var TorusKnotGeometry = class _TorusKnotGeometry extends BufferGeometry { constructor(radius = 1, tube = 0.4, tubularSegments = 64, radialSegments = 8, p2 = 2, q = 3) { super(); this.type = "TorusKnotGeometry"; this.parameters = { radius, tube, tubularSegments, radialSegments, p: p2, q }; tubularSegments = Math.floor(tubularSegments); radialSegments = Math.floor(radialSegments); const indices = []; const vertices = []; const normals = []; const uvs = []; const vertex2 = new Vector3(); const normal = new Vector3(); const P1 = new Vector3(); const P2 = new Vector3(); const B2 = new Vector3(); const T = new Vector3(); const N = new Vector3(); for (let i = 0; i <= tubularSegments; ++i) { const u = i / tubularSegments * p2 * Math.PI * 2; calculatePositionOnCurve(u, p2, q, radius, P1); calculatePositionOnCurve(u + 0.01, p2, q, radius, P2); T.subVectors(P2, P1); N.addVectors(P2, P1); B2.crossVectors(T, N); N.crossVectors(B2, T); B2.normalize(); N.normalize(); for (let j = 0; j <= radialSegments; ++j) { const v = j / radialSegments * Math.PI * 2; const cx = -tube * Math.cos(v); const cy = tube * Math.sin(v); vertex2.x = P1.x + (cx * N.x + cy * B2.x); vertex2.y = P1.y + (cx * N.y + cy * B2.y); vertex2.z = P1.z + (cx * N.z + cy * B2.z); vertices.push(vertex2.x, vertex2.y, vertex2.z); normal.subVectors(vertex2, P1).normalize(); normals.push(normal.x, normal.y, normal.z); uvs.push(i / tubularSegments); uvs.push(j / radialSegments); } } for (let j = 1; j <= tubularSegments; j++) { for (let i = 1; i <= radialSegments; i++) { const a = (radialSegments + 1) * (j - 1) + (i - 1); const b = (radialSegments + 1) * j + (i - 1); const c = (radialSegments + 1) * j + i; const d = (radialSegments + 1) * (j - 1) + i; indices.push(a, b, d); indices.push(b, c, d); } } this.setIndex(indices); this.setAttribute("position", new Float32BufferAttribute(vertices, 3)); this.setAttribute("normal", new Float32BufferAttribute(normals, 3)); this.setAttribute("uv", new Float32BufferAttribute(uvs, 2)); function calculatePositionOnCurve(u, p3, q2, radius2, position) { const cu = Math.cos(u); const su = Math.sin(u); const quOverP = q2 / p3 * u; const cs = Math.cos(quOverP); position.x = radius2 * (2 + cs) * 0.5 * cu; position.y = radius2 * (2 + cs) * su * 0.5; position.z = radius2 * Math.sin(quOverP) * 0.5; } } static fromJSON(data) { return new _TorusKnotGeometry(data.radius, data.tube, data.tubularSegments, data.radialSegments, data.p, data.q); } }; var TubeGeometry = class _TubeGeometry extends BufferGeometry { constructor(path = new QuadraticBezierCurve3(new Vector3(-1, -1, 0), new Vector3(-1, 1, 0), new Vector3(1, 1, 0)), tubularSegments = 64, radius = 1, radialSegments = 8, closed = false) { super(); this.type = "TubeGeometry"; this.parameters = { path, tubularSegments, radius, radialSegments, closed }; const frames = path.computeFrenetFrames(tubularSegments, closed); this.tangents = frames.tangents; this.normals = frames.normals; this.binormals = frames.binormals; const vertex2 = new Vector3(); const normal = new Vector3(); const uv = new Vector2(); let P = new Vector3(); const vertices = []; const normals = []; const uvs = []; const indices = []; generateBufferData(); this.setIndex(indices); this.setAttribute("position", new Float32BufferAttribute(vertices, 3)); this.setAttribute("normal", new Float32BufferAttribute(normals, 3)); this.setAttribute("uv", new Float32BufferAttribute(uvs, 2)); function generateBufferData() { for (let i = 0; i < tubularSegments; i++) { generateSegment(i); } generateSegment(closed === false ? tubularSegments : 0); generateUVs(); generateIndices(); } function generateSegment(i) { P = path.getPointAt(i / tubularSegments, P); const N = frames.normals[i]; const B2 = frames.binormals[i]; for (let j = 0; j <= radialSegments; j++) { const v = j / radialSegments * Math.PI * 2; const sin = Math.sin(v); const cos = -Math.cos(v); normal.x = cos * N.x + sin * B2.x; normal.y = cos * N.y + sin * B2.y; normal.z = cos * N.z + sin * B2.z; normal.normalize(); normals.push(normal.x, normal.y, normal.z); vertex2.x = P.x + radius * normal.x; vertex2.y = P.y + radius * normal.y; vertex2.z = P.z + radius * normal.z; vertices.push(vertex2.x, vertex2.y, vertex2.z); } } function generateIndices() { for (let j = 1; j <= tubularSegments; j++) { for (let i = 1; i <= radialSegments; i++) { const a = (radialSegments + 1) * (j - 1) + (i - 1); const b = (radialSegments + 1) * j + (i - 1); const c = (radialSegments + 1) * j + i; const d = (radialSegments + 1) * (j - 1) + i; indices.push(a, b, d); indices.push(b, c, d); } } } function generateUVs() { for (let i = 0; i <= tubularSegments; i++) { for (let j = 0; j <= radialSegments; j++) { uv.x = i / tubularSegments; uv.y = j / radialSegments; uvs.push(uv.x, uv.y); } } } } toJSON() { const data = super.toJSON(); data.path = this.parameters.path.toJSON(); return data; } static fromJSON(data) { return new _TubeGeometry( new Curves[data.path.type]().fromJSON(data.path), data.tubularSegments, data.radius, data.radialSegments, data.closed ); } }; var WireframeGeometry = class extends BufferGeometry { constructor(geometry = null) { super(); this.type = "WireframeGeometry"; this.parameters = { geometry }; if (geometry !== null) { const vertices = []; const edges = /* @__PURE__ */ new Set(); const start = new Vector3(); const end = new Vector3(); if (geometry.index !== null) { const position = geometry.attributes.position; const indices = geometry.index; let groups = geometry.groups; if (groups.length === 0) { groups = [{ start: 0, count: indices.count, materialIndex: 0 }]; } for (let o = 0, ol = groups.length; o < ol; ++o) { const group = groups[o]; const groupStart = group.start; const groupCount = group.count; for (let i = groupStart, l = groupStart + groupCount; i < l; i += 3) { for (let j = 0; j < 3; j++) { const index1 = indices.getX(i + j); const index2 = indices.getX(i + (j + 1) % 3); start.fromBufferAttribute(position, index1); end.fromBufferAttribute(position, index2); if (isUniqueEdge(start, end, edges) === true) { vertices.push(start.x, start.y, start.z); vertices.push(end.x, end.y, end.z); } } } } } else { const position = geometry.attributes.position; for (let i = 0, l = position.count / 3; i < l; i++) { for (let j = 0; j < 3; j++) { const index1 = 3 * i + j; const index2 = 3 * i + (j + 1) % 3; start.fromBufferAttribute(position, index1); end.fromBufferAttribute(position, index2); if (isUniqueEdge(start, end, edges) === true) { vertices.push(start.x, start.y, start.z); vertices.push(end.x, end.y, end.z); } } } } this.setAttribute("position", new Float32BufferAttribute(vertices, 3)); } } }; function isUniqueEdge(start, end, edges) { const hash1 = `${start.x},${start.y},${start.z}-${end.x},${end.y},${end.z}`; const hash2 = `${end.x},${end.y},${end.z}-${start.x},${start.y},${start.z}`; if (edges.has(hash1) === true || edges.has(hash2) === true) { return false; } else { edges.add(hash1); edges.add(hash2); return true; } } var Geometries = Object.freeze({ __proto__: null, BoxGeometry, CapsuleGeometry, CircleGeometry, ConeGeometry, CylinderGeometry, DodecahedronGeometry, EdgesGeometry, ExtrudeGeometry, IcosahedronGeometry, LatheGeometry, OctahedronGeometry, PlaneGeometry, PolyhedronGeometry, RingGeometry, ShapeGeometry, SphereGeometry, TetrahedronGeometry, TorusGeometry, TorusKnotGeometry, TubeGeometry, WireframeGeometry }); var MeshStandardMaterial = class extends Material { constructor(parameters) { super(); this.isMeshStandardMaterial = true; this.defines = { "STANDARD": "" }; this.type = "MeshStandardMaterial"; this.color = new Color(16777215); this.roughness = 1; this.metalness = 0; this.map = null; this.lightMap = null; this.lightMapIntensity = 1; this.aoMap = null; this.aoMapIntensity = 1; this.emissive = new Color(0); this.emissiveIntensity = 1; this.emissiveMap = null; this.bumpMap = null; this.bumpScale = 1; this.normalMap = null; this.normalMapType = TangentSpaceNormalMap; this.normalScale = new Vector2(1, 1); this.displacementMap = null; this.displacementScale = 1; this.displacementBias = 0; this.roughnessMap = null; this.metalnessMap = null; this.alphaMap = null; this.envMap = null; this.envMapIntensity = 1; this.wireframe = false; this.wireframeLinewidth = 1; this.wireframeLinecap = "round"; this.wireframeLinejoin = "round"; this.flatShading = false; this.fog = true; this.setValues(parameters); } copy(source) { super.copy(source); this.defines = { "STANDARD": "" }; this.color.copy(source.color); this.roughness = source.roughness; this.metalness = source.metalness; this.map = source.map; this.lightMap = source.lightMap; this.lightMapIntensity = source.lightMapIntensity; this.aoMap = source.aoMap; this.aoMapIntensity = source.aoMapIntensity; this.emissive.copy(source.emissive); this.emissiveMap = source.emissiveMap; this.emissiveIntensity = source.emissiveIntensity; this.bumpMap = source.bumpMap; this.bumpScale = source.bumpScale; this.normalMap = source.normalMap; this.normalMapType = source.normalMapType; this.normalScale.copy(source.normalScale); this.displacementMap = source.displacementMap; this.displacementScale = source.displacementScale; this.displacementBias = source.displacementBias; this.roughnessMap = source.roughnessMap; this.metalnessMap = source.metalnessMap; this.alphaMap = source.alphaMap; this.envMap = source.envMap; this.envMapIntensity = source.envMapIntensity; this.wireframe = source.wireframe; this.wireframeLinewidth = source.wireframeLinewidth; this.wireframeLinecap = source.wireframeLinecap; this.wireframeLinejoin = source.wireframeLinejoin; this.flatShading = source.flatShading; this.fog = source.fog; return this; } }; var MeshPhysicalMaterial = class extends MeshStandardMaterial { constructor(parameters) { super(); this.isMeshPhysicalMaterial = true; this.defines = { "STANDARD": "", "PHYSICAL": "" }; this.type = "MeshPhysicalMaterial"; this.clearcoatMap = null; this.clearcoatRoughness = 0; this.clearcoatRoughnessMap = null; this.clearcoatNormalScale = new Vector2(1, 1); this.clearcoatNormalMap = null; this.ior = 1.5; Object.defineProperty(this, "reflectivity", { get: function() { return clamp(2.5 * (this.ior - 1) / (this.ior + 1), 0, 1); }, set: function(reflectivity) { this.ior = (1 + 0.4 * reflectivity) / (1 - 0.4 * reflectivity); } }); this.iridescenceMap = null; this.iridescenceIOR = 1.3; this.iridescenceThicknessRange = [100, 400]; this.iridescenceThicknessMap = null; this.sheenColor = new Color(0); this.sheenColorMap = null; this.sheenRoughness = 1; this.sheenRoughnessMap = null; this.transmissionMap = null; this.thickness = 0; this.thicknessMap = null; this.attenuationDistance = Infinity; this.attenuationColor = new Color(1, 1, 1); this.specularIntensity = 1; this.specularIntensityMap = null; this.specularColor = new Color(1, 1, 1); this.specularColorMap = null; this._sheen = 0; this._clearcoat = 0; this._iridescence = 0; this._transmission = 0; this.setValues(parameters); } get sheen() { return this._sheen; } set sheen(value) { if (this._sheen > 0 !== value > 0) { this.version++; } this._sheen = value; } get clearcoat() { return this._clearcoat; } set clearcoat(value) { if (this._clearcoat > 0 !== value > 0) { this.version++; } this._clearcoat = value; } get iridescence() { return this._iridescence; } set iridescence(value) { if (this._iridescence > 0 !== value > 0) { this.version++; } this._iridescence = value; } get transmission() { return this._transmission; } set transmission(value) { if (this._transmission > 0 !== value > 0) { this.version++; } this._transmission = value; } copy(source) { super.copy(source); this.defines = { "STANDARD": "", "PHYSICAL": "" }; this.clearcoat = source.clearcoat; this.clearcoatMap = source.clearcoatMap; this.clearcoatRoughness = source.clearcoatRoughness; this.clearcoatRoughnessMap = source.clearcoatRoughnessMap; this.clearcoatNormalMap = source.clearcoatNormalMap; this.clearcoatNormalScale.copy(source.clearcoatNormalScale); this.ior = source.ior; this.iridescence = source.iridescence; this.iridescenceMap = source.iridescenceMap; this.iridescenceIOR = source.iridescenceIOR; this.iridescenceThicknessRange = [...source.iridescenceThicknessRange]; this.iridescenceThicknessMap = source.iridescenceThicknessMap; this.sheen = source.sheen; this.sheenColor.copy(source.sheenColor); this.sheenColorMap = source.sheenColorMap; this.sheenRoughness = source.sheenRoughness; this.sheenRoughnessMap = source.sheenRoughnessMap; this.transmission = source.transmission; this.transmissionMap = source.transmissionMap; this.thickness = source.thickness; this.thicknessMap = source.thicknessMap; this.attenuationDistance = source.attenuationDistance; this.attenuationColor.copy(source.attenuationColor); this.specularIntensity = source.specularIntensity; this.specularIntensityMap = source.specularIntensityMap; this.specularColor.copy(source.specularColor); this.specularColorMap = source.specularColorMap; return this; } }; function arraySlice(array, from, to) { if (isTypedArray(array)) { return new array.constructor(array.subarray(from, to !== void 0 ? to : array.length)); } return array.slice(from, to); } function convertArray(array, type, forceClone) { if (!array || // let 'undefined' and 'null' pass !forceClone && array.constructor === type) return array; if (typeof type.BYTES_PER_ELEMENT === "number") { return new type(array); } return Array.prototype.slice.call(array); } function isTypedArray(object) { return ArrayBuffer.isView(object) && !(object instanceof DataView); } function getKeyframeOrder(times) { function compareTime(i, j) { return times[i] - times[j]; } const n2 = times.length; const result = new Array(n2); for (let i = 0; i !== n2; ++i) result[i] = i; result.sort(compareTime); return result; } function sortedArray(values, stride, order) { const nValues = values.length; const result = new values.constructor(nValues); for (let i = 0, dstOffset = 0; dstOffset !== nValues; ++i) { const srcOffset = order[i] * stride; for (let j = 0; j !== stride; ++j) { result[dstOffset++] = values[srcOffset + j]; } } return result; } function flattenJSON(jsonKeys, times, values, valuePropertyName) { let i = 1, key = jsonKeys[0]; while (key !== void 0 && key[valuePropertyName] === void 0) { key = jsonKeys[i++]; } if (key === void 0) return; let value = key[valuePropertyName]; if (value === void 0) return; if (Array.isArray(value)) { do { value = key[valuePropertyName]; if (value !== void 0) { times.push(key.time); values.push.apply(values, value); } key = jsonKeys[i++]; } while (key !== void 0); } else if (value.toArray !== void 0) { do { value = key[valuePropertyName]; if (value !== void 0) { times.push(key.time); value.toArray(values, values.length); } key = jsonKeys[i++]; } while (key !== void 0); } else { do { value = key[valuePropertyName]; if (value !== void 0) { times.push(key.time); values.push(value); } key = jsonKeys[i++]; } while (key !== void 0); } } function subclip(sourceClip, name, startFrame, endFrame, fps = 30) { const clip = sourceClip.clone(); clip.name = name; const tracks = []; for (let i = 0; i < clip.tracks.length; ++i) { const track = clip.tracks[i]; const valueSize = track.getValueSize(); const times = []; const values = []; for (let j = 0; j < track.times.length; ++j) { const frame = track.times[j] * fps; if (frame < startFrame || frame >= endFrame) continue; times.push(track.times[j]); for (let k = 0; k < valueSize; ++k) { values.push(track.values[j * valueSize + k]); } } if (times.length === 0) continue; track.times = convertArray(times, track.times.constructor); track.values = convertArray(values, track.values.constructor); tracks.push(track); } clip.tracks = tracks; let minStartTime = Infinity; for (let i = 0; i < clip.tracks.length; ++i) { if (minStartTime > clip.tracks[i].times[0]) { minStartTime = clip.tracks[i].times[0]; } } for (let i = 0; i < clip.tracks.length; ++i) { clip.tracks[i].shift(-1 * minStartTime); } clip.resetDuration(); return clip; } function makeClipAdditive(targetClip, referenceFrame = 0, referenceClip = targetClip, fps = 30) { if (fps <= 0) fps = 30; const numTracks = referenceClip.tracks.length; const referenceTime = referenceFrame / fps; for (let i = 0; i < numTracks; ++i) { const referenceTrack = referenceClip.tracks[i]; const referenceTrackType = referenceTrack.ValueTypeName; if (referenceTrackType === "bool" || referenceTrackType === "string") continue; const targetTrack = targetClip.tracks.find(function(track) { return track.name === referenceTrack.name && track.ValueTypeName === referenceTrackType; }); if (targetTrack === void 0) continue; let referenceOffset = 0; const referenceValueSize = referenceTrack.getValueSize(); if (referenceTrack.createInterpolant.isInterpolantFactoryMethodGLTFCubicSpline) { referenceOffset = referenceValueSize / 3; } let targetOffset = 0; const targetValueSize = targetTrack.getValueSize(); if (targetTrack.createInterpolant.isInterpolantFactoryMethodGLTFCubicSpline) { targetOffset = targetValueSize / 3; } const lastIndex = referenceTrack.times.length - 1; let referenceValue; if (referenceTime <= referenceTrack.times[0]) { const startIndex = referenceOffset; const endIndex = referenceValueSize - referenceOffset; referenceValue = arraySlice(referenceTrack.values, startIndex, endIndex); } else if (referenceTime >= referenceTrack.times[lastIndex]) { const startIndex = lastIndex * referenceValueSize + referenceOffset; const endIndex = startIndex + referenceValueSize - referenceOffset; referenceValue = arraySlice(referenceTrack.values, startIndex, endIndex); } else { const interpolant = referenceTrack.createInterpolant(); const startIndex = referenceOffset; const endIndex = referenceValueSize - referenceOffset; interpolant.evaluate(referenceTime); referenceValue = arraySlice(interpolant.resultBuffer, startIndex, endIndex); } if (referenceTrackType === "quaternion") { const referenceQuat = new Quaternion().fromArray(referenceValue).normalize().conjugate(); referenceQuat.toArray(referenceValue); } const numTimes = targetTrack.times.length; for (let j = 0; j < numTimes; ++j) { const valueStart = j * targetValueSize + targetOffset; if (referenceTrackType === "quaternion") { Quaternion.multiplyQuaternionsFlat( targetTrack.values, valueStart, referenceValue, 0, targetTrack.values, valueStart ); } else { const valueEnd = targetValueSize - targetOffset * 2; for (let k = 0; k < valueEnd; ++k) { targetTrack.values[valueStart + k] -= referenceValue[k]; } } } } targetClip.blendMode = AdditiveAnimationBlendMode; return targetClip; } var AnimationUtils = Object.freeze({ __proto__: null, arraySlice, convertArray, isTypedArray, getKeyframeOrder, sortedArray, flattenJSON, subclip, makeClipAdditive }); var Interpolant = class { constructor(parameterPositions, sampleValues, sampleSize, resultBuffer) { this.parameterPositions = parameterPositions; this._cachedIndex = 0; this.resultBuffer = resultBuffer !== void 0 ? resultBuffer : new sampleValues.constructor(sampleSize); this.sampleValues = sampleValues; this.valueSize = sampleSize; this.settings = null; this.DefaultSettings_ = {}; } evaluate(t2) { const pp = this.parameterPositions; let i1 = this._cachedIndex, t1 = pp[i1], t0 = pp[i1 - 1]; validate_interval: { seek: { let right; linear_scan: { forward_scan: if (!(t2 < t1)) { for (let giveUpAt = i1 + 2; ; ) { if (t1 === void 0) { if (t2 < t0) break forward_scan; i1 = pp.length; this._cachedIndex = i1; return this.copySampleValue_(i1 - 1); } if (i1 === giveUpAt) break; t0 = t1; t1 = pp[++i1]; if (t2 < t1) { break seek; } } right = pp.length; break linear_scan; } if (!(t2 >= t0)) { const t1global = pp[1]; if (t2 < t1global) { i1 = 2; t0 = t1global; } for (let giveUpAt = i1 - 2; ; ) { if (t0 === void 0) { this._cachedIndex = 0; return this.copySampleValue_(0); } if (i1 === giveUpAt) break; t1 = t0; t0 = pp[--i1 - 1]; if (t2 >= t0) { break seek; } } right = i1; i1 = 0; break linear_scan; } break validate_interval; } while (i1 < right) { const mid = i1 + right >>> 1; if (t2 < pp[mid]) { right = mid; } else { i1 = mid + 1; } } t1 = pp[i1]; t0 = pp[i1 - 1]; if (t0 === void 0) { this._cachedIndex = 0; return this.copySampleValue_(0); } if (t1 === void 0) { i1 = pp.length; this._cachedIndex = i1; return this.copySampleValue_(i1 - 1); } } this._cachedIndex = i1; this.intervalChanged_(i1, t0, t1); } return this.interpolate_(i1, t0, t2, t1); } getSettings_() { return this.settings || this.DefaultSettings_; } copySampleValue_(index) { const result = this.resultBuffer, values = this.sampleValues, stride = this.valueSize, offset = index * stride; for (let i = 0; i !== stride; ++i) { result[i] = values[offset + i]; } return result; } // Template methods for derived classes: interpolate_() { throw new Error("call to abstract method"); } intervalChanged_() { } }; var CubicInterpolant = class extends Interpolant { constructor(parameterPositions, sampleValues, sampleSize, resultBuffer) { super(parameterPositions, sampleValues, sampleSize, resultBuffer); this._weightPrev = -0; this._offsetPrev = -0; this._weightNext = -0; this._offsetNext = -0; this.DefaultSettings_ = { endingStart: ZeroCurvatureEnding, endingEnd: ZeroCurvatureEnding }; } intervalChanged_(i1, t0, t1) { const pp = this.parameterPositions; let iPrev = i1 - 2, iNext = i1 + 1, tPrev = pp[iPrev], tNext = pp[iNext]; if (tPrev === void 0) { switch (this.getSettings_().endingStart) { case ZeroSlopeEnding: iPrev = i1; tPrev = 2 * t0 - t1; break; case WrapAroundEnding: iPrev = pp.length - 2; tPrev = t0 + pp[iPrev] - pp[iPrev + 1]; break; default: iPrev = i1; tPrev = t1; } } if (tNext === void 0) { switch (this.getSettings_().endingEnd) { case ZeroSlopeEnding: iNext = i1; tNext = 2 * t1 - t0; break; case WrapAroundEnding: iNext = 1; tNext = t1 + pp[1] - pp[0]; break; default: iNext = i1 - 1; tNext = t0; } } const halfDt = (t1 - t0) * 0.5, stride = this.valueSize; this._weightPrev = halfDt / (t0 - tPrev); this._weightNext = halfDt / (tNext - t1); this._offsetPrev = iPrev * stride; this._offsetNext = iNext * stride; } interpolate_(i1, t0, t2, t1) { const result = this.resultBuffer, values = this.sampleValues, stride = this.valueSize, o1 = i1 * stride, o0 = o1 - stride, oP = this._offsetPrev, oN = this._offsetNext, wP = this._weightPrev, wN = this._weightNext, p2 = (t2 - t0) / (t1 - t0), pp = p2 * p2, ppp = pp * p2; const sP = -wP * ppp + 2 * wP * pp - wP * p2; const s0 = (1 + wP) * ppp + (-1.5 - 2 * wP) * pp + (-0.5 + wP) * p2 + 1; const s1 = (-1 - wN) * ppp + (1.5 + wN) * pp + 0.5 * p2; const sN = wN * ppp - wN * pp; for (let i = 0; i !== stride; ++i) { result[i] = sP * values[oP + i] + s0 * values[o0 + i] + s1 * values[o1 + i] + sN * values[oN + i]; } return result; } }; var LinearInterpolant = class extends Interpolant { constructor(parameterPositions, sampleValues, sampleSize, resultBuffer) { super(parameterPositions, sampleValues, sampleSize, resultBuffer); } interpolate_(i1, t0, t2, t1) { const result = this.resultBuffer, values = this.sampleValues, stride = this.valueSize, offset1 = i1 * stride, offset0 = offset1 - stride, weight1 = (t2 - t0) / (t1 - t0), weight0 = 1 - weight1; for (let i = 0; i !== stride; ++i) { result[i] = values[offset0 + i] * weight0 + values[offset1 + i] * weight1; } return result; } }; var DiscreteInterpolant = class extends Interpolant { constructor(parameterPositions, sampleValues, sampleSize, resultBuffer) { super(parameterPositions, sampleValues, sampleSize, resultBuffer); } interpolate_(i1) { return this.copySampleValue_(i1 - 1); } }; var KeyframeTrack = class { constructor(name, times, values, interpolation) { if (name === void 0) throw new Error("THREE.KeyframeTrack: track name is undefined"); if (times === void 0 || times.length === 0) throw new Error("THREE.KeyframeTrack: no keyframes in track named " + name); this.name = name; this.times = convertArray(times, this.TimeBufferType); this.values = convertArray(values, this.ValueBufferType); this.setInterpolation(interpolation || this.DefaultInterpolation); } // Serialization (in static context, because of constructor invocation // and automatic invocation of .toJSON): static toJSON(track) { const trackType = track.constructor; let json; if (trackType.toJSON !== this.toJSON) { json = trackType.toJSON(track); } else { json = { "name": track.name, "times": convertArray(track.times, Array), "values": convertArray(track.values, Array) }; const interpolation = track.getInterpolation(); if (interpolation !== track.DefaultInterpolation) { json.interpolation = interpolation; } } json.type = track.ValueTypeName; return json; } InterpolantFactoryMethodDiscrete(result) { return new DiscreteInterpolant(this.times, this.values, this.getValueSize(), result); } InterpolantFactoryMethodLinear(result) { return new LinearInterpolant(this.times, this.values, this.getValueSize(), result); } InterpolantFactoryMethodSmooth(result) { return new CubicInterpolant(this.times, this.values, this.getValueSize(), result); } setInterpolation(interpolation) { let factoryMethod; switch (interpolation) { case InterpolateDiscrete: factoryMethod = this.InterpolantFactoryMethodDiscrete; break; case InterpolateLinear: factoryMethod = this.InterpolantFactoryMethodLinear; break; case InterpolateSmooth: factoryMethod = this.InterpolantFactoryMethodSmooth; break; } if (factoryMethod === void 0) { const message = "unsupported interpolation for " + this.ValueTypeName + " keyframe track named " + this.name; if (this.createInterpolant === void 0) { if (interpolation !== this.DefaultInterpolation) { this.setInterpolation(this.DefaultInterpolation); } else { throw new Error(message); } } console.warn("THREE.KeyframeTrack:", message); return this; } this.createInterpolant = factoryMethod; return this; } getInterpolation() { switch (this.createInterpolant) { case this.InterpolantFactoryMethodDiscrete: return InterpolateDiscrete; case this.InterpolantFactoryMethodLinear: return InterpolateLinear; case this.InterpolantFactoryMethodSmooth: return InterpolateSmooth; } } getValueSize() { return this.values.length / this.times.length; } // move all keyframes either forwards or backwards in time shift(timeOffset) { if (timeOffset !== 0) { const times = this.times; for (let i = 0, n2 = times.length; i !== n2; ++i) { times[i] += timeOffset; } } return this; } // scale all keyframe times by a factor (useful for frame <-> seconds conversions) scale(timeScale) { if (timeScale !== 1) { const times = this.times; for (let i = 0, n2 = times.length; i !== n2; ++i) { times[i] *= timeScale; } } return this; } // removes keyframes before and after animation without changing any values within the range [startTime, endTime]. // IMPORTANT: We do not shift around keys to the start of the track time, because for interpolated keys this will change their values trim(startTime, endTime) { const times = this.times, nKeys = times.length; let from = 0, to = nKeys - 1; while (from !== nKeys && times[from] < startTime) { ++from; } while (to !== -1 && times[to] > endTime) { --to; } ++to; if (from !== 0 || to !== nKeys) { if (from >= to) { to = Math.max(to, 1); from = to - 1; } const stride = this.getValueSize(); this.times = arraySlice(times, from, to); this.values = arraySlice(this.values, from * stride, to * stride); } return this; } // ensure we do not get a GarbageInGarbageOut situation, make sure tracks are at least minimally viable validate() { let valid = true; const valueSize = this.getValueSize(); if (valueSize - Math.floor(valueSize) !== 0) { console.error("THREE.KeyframeTrack: Invalid value size in track.", this); valid = false; } const times = this.times, values = this.values, nKeys = times.length; if (nKeys === 0) { console.error("THREE.KeyframeTrack: Track is empty.", this); valid = false; } let prevTime = null; for (let i = 0; i !== nKeys; i++) { const currTime = times[i]; if (typeof currTime === "number" && isNaN(currTime)) { console.error("THREE.KeyframeTrack: Time is not a valid number.", this, i, currTime); valid = false; break; } if (prevTime !== null && prevTime > currTime) { console.error("THREE.KeyframeTrack: Out of order keys.", this, i, currTime, prevTime); valid = false; break; } prevTime = currTime; } if (values !== void 0) { if (isTypedArray(values)) { for (let i = 0, n2 = values.length; i !== n2; ++i) { const value = values[i]; if (isNaN(value)) { console.error("THREE.KeyframeTrack: Value is not a valid number.", this, i, value); valid = false; break; } } } } return valid; } // removes equivalent sequential keys as common in morph target sequences // (0,0,0,0,1,1,1,0,0,0,0,0,0,0) --> (0,0,1,1,0,0) optimize() { const times = arraySlice(this.times), values = arraySlice(this.values), stride = this.getValueSize(), smoothInterpolation = this.getInterpolation() === InterpolateSmooth, lastIndex = times.length - 1; let writeIndex = 1; for (let i = 1; i < lastIndex; ++i) { let keep = false; const time = times[i]; const timeNext = times[i + 1]; if (time !== timeNext && (i !== 1 || time !== times[0])) { if (!smoothInterpolation) { const offset = i * stride, offsetP = offset - stride, offsetN = offset + stride; for (let j = 0; j !== stride; ++j) { const value = values[offset + j]; if (value !== values[offsetP + j] || value !== values[offsetN + j]) { keep = true; break; } } } else { keep = true; } } if (keep) { if (i !== writeIndex) { times[writeIndex] = times[i]; const readOffset = i * stride, writeOffset = writeIndex * stride; for (let j = 0; j !== stride; ++j) { values[writeOffset + j] = values[readOffset + j]; } } ++writeIndex; } } if (lastIndex > 0) { times[writeIndex] = times[lastIndex]; for (let readOffset = lastIndex * stride, writeOffset = writeIndex * stride, j = 0; j !== stride; ++j) { values[writeOffset + j] = values[readOffset + j]; } ++writeIndex; } if (writeIndex !== times.length) { this.times = arraySlice(times, 0, writeIndex); this.values = arraySlice(values, 0, writeIndex * stride); } else { this.times = times; this.values = values; } return this; } clone() { const times = arraySlice(this.times, 0); const values = arraySlice(this.values, 0); const TypedKeyframeTrack = this.constructor; const track = new TypedKeyframeTrack(this.name, times, values); track.createInterpolant = this.createInterpolant; return track; } }; KeyframeTrack.prototype.TimeBufferType = Float32Array; KeyframeTrack.prototype.ValueBufferType = Float32Array; KeyframeTrack.prototype.DefaultInterpolation = InterpolateLinear; var BooleanKeyframeTrack = class extends KeyframeTrack { }; BooleanKeyframeTrack.prototype.ValueTypeName = "bool"; BooleanKeyframeTrack.prototype.ValueBufferType = Array; BooleanKeyframeTrack.prototype.DefaultInterpolation = InterpolateDiscrete; BooleanKeyframeTrack.prototype.InterpolantFactoryMethodLinear = void 0; BooleanKeyframeTrack.prototype.InterpolantFactoryMethodSmooth = void 0; var ColorKeyframeTrack = class extends KeyframeTrack { }; ColorKeyframeTrack.prototype.ValueTypeName = "color"; var NumberKeyframeTrack = class extends KeyframeTrack { }; NumberKeyframeTrack.prototype.ValueTypeName = "number"; var QuaternionLinearInterpolant = class extends Interpolant { constructor(parameterPositions, sampleValues, sampleSize, resultBuffer) { super(parameterPositions, sampleValues, sampleSize, resultBuffer); } interpolate_(i1, t0, t2, t1) { const result = this.resultBuffer, values = this.sampleValues, stride = this.valueSize, alpha = (t2 - t0) / (t1 - t0); let offset = i1 * stride; for (let end = offset + stride; offset !== end; offset += 4) { Quaternion.slerpFlat(result, 0, values, offset - stride, values, offset, alpha); } return result; } }; var QuaternionKeyframeTrack = class extends KeyframeTrack { InterpolantFactoryMethodLinear(result) { return new QuaternionLinearInterpolant(this.times, this.values, this.getValueSize(), result); } }; QuaternionKeyframeTrack.prototype.ValueTypeName = "quaternion"; QuaternionKeyframeTrack.prototype.DefaultInterpolation = InterpolateLinear; QuaternionKeyframeTrack.prototype.InterpolantFactoryMethodSmooth = void 0; var StringKeyframeTrack = class extends KeyframeTrack { }; StringKeyframeTrack.prototype.ValueTypeName = "string"; StringKeyframeTrack.prototype.ValueBufferType = Array; StringKeyframeTrack.prototype.DefaultInterpolation = InterpolateDiscrete; StringKeyframeTrack.prototype.InterpolantFactoryMethodLinear = void 0; StringKeyframeTrack.prototype.InterpolantFactoryMethodSmooth = void 0; var VectorKeyframeTrack = class extends KeyframeTrack { }; VectorKeyframeTrack.prototype.ValueTypeName = "vector"; var AnimationClip = class { constructor(name, duration = -1, tracks, blendMode = NormalAnimationBlendMode) { this.name = name; this.tracks = tracks; this.duration = duration; this.blendMode = blendMode; this.uuid = generateUUID(); if (this.duration < 0) { this.resetDuration(); } } static parse(json) { const tracks = [], jsonTracks = json.tracks, frameTime = 1 / (json.fps || 1); for (let i = 0, n2 = jsonTracks.length; i !== n2; ++i) { tracks.push(parseKeyframeTrack(jsonTracks[i]).scale(frameTime)); } const clip = new this(json.name, json.duration, tracks, json.blendMode); clip.uuid = json.uuid; return clip; } static toJSON(clip) { const tracks = [], clipTracks = clip.tracks; const json = { "name": clip.name, "duration": clip.duration, "tracks": tracks, "uuid": clip.uuid, "blendMode": clip.blendMode }; for (let i = 0, n2 = clipTracks.length; i !== n2; ++i) { tracks.push(KeyframeTrack.toJSON(clipTracks[i])); } return json; } static CreateFromMorphTargetSequence(name, morphTargetSequence, fps, noLoop) { const numMorphTargets = morphTargetSequence.length; const tracks = []; for (let i = 0; i < numMorphTargets; i++) { let times = []; let values = []; times.push( (i + numMorphTargets - 1) % numMorphTargets, i, (i + 1) % numMorphTargets ); values.push(0, 1, 0); const order = getKeyframeOrder(times); times = sortedArray(times, 1, order); values = sortedArray(values, 1, order); if (!noLoop && times[0] === 0) { times.push(numMorphTargets); values.push(values[0]); } tracks.push( new NumberKeyframeTrack( ".morphTargetInfluences[" + morphTargetSequence[i].name + "]", times, values ).scale(1 / fps) ); } return new this(name, -1, tracks); } static findByName(objectOrClipArray, name) { let clipArray = objectOrClipArray; if (!Array.isArray(objectOrClipArray)) { const o = objectOrClipArray; clipArray = o.geometry && o.geometry.animations || o.animations; } for (let i = 0; i < clipArray.length; i++) { if (clipArray[i].name === name) { return clipArray[i]; } } return null; } static CreateClipsFromMorphTargetSequences(morphTargets, fps, noLoop) { const animationToMorphTargets = {}; const pattern = /^([\w-]*?)([\d]+)$/; for (let i = 0, il = morphTargets.length; i < il; i++) { const morphTarget = morphTargets[i]; const parts = morphTarget.name.match(pattern); if (parts && parts.length > 1) { const name = parts[1]; let animationMorphTargets = animationToMorphTargets[name]; if (!animationMorphTargets) { animationToMorphTargets[name] = animationMorphTargets = []; } animationMorphTargets.push(morphTarget); } } const clips = []; for (const name in animationToMorphTargets) { clips.push(this.CreateFromMorphTargetSequence(name, animationToMorphTargets[name], fps, noLoop)); } return clips; } // parse the animation.hierarchy format static parseAnimation(animation, bones) { if (!animation) { console.error("THREE.AnimationClip: No animation in JSONLoader data."); return null; } const addNonemptyTrack = function(trackType, trackName, animationKeys, propertyName, destTracks) { if (animationKeys.length !== 0) { const times = []; const values = []; flattenJSON(animationKeys, times, values, propertyName); if (times.length !== 0) { destTracks.push(new trackType(trackName, times, values)); } } }; const tracks = []; const clipName = animation.name || "default"; const fps = animation.fps || 30; const blendMode = animation.blendMode; let duration = animation.length || -1; const hierarchyTracks = animation.hierarchy || []; for (let h = 0; h < hierarchyTracks.length; h++) { const animationKeys = hierarchyTracks[h].keys; if (!animationKeys || animationKeys.length === 0) continue; if (animationKeys[0].morphTargets) { const morphTargetNames = {}; let k; for (k = 0; k < animationKeys.length; k++) { if (animationKeys[k].morphTargets) { for (let m = 0; m < animationKeys[k].morphTargets.length; m++) { morphTargetNames[animationKeys[k].morphTargets[m]] = -1; } } } for (const morphTargetName in morphTargetNames) { const times = []; const values = []; for (let m = 0; m !== animationKeys[k].morphTargets.length; ++m) { const animationKey = animationKeys[k]; times.push(animationKey.time); values.push(animationKey.morphTarget === morphTargetName ? 1 : 0); } tracks.push(new NumberKeyframeTrack(".morphTargetInfluence[" + morphTargetName + "]", times, values)); } duration = morphTargetNames.length * fps; } else { const boneName = ".bones[" + bones[h].name + "]"; addNonemptyTrack( VectorKeyframeTrack, boneName + ".position", animationKeys, "pos", tracks ); addNonemptyTrack( QuaternionKeyframeTrack, boneName + ".quaternion", animationKeys, "rot", tracks ); addNonemptyTrack( VectorKeyframeTrack, boneName + ".scale", animationKeys, "scl", tracks ); } } if (tracks.length === 0) { return null; } const clip = new this(clipName, duration, tracks, blendMode); return clip; } resetDuration() { const tracks = this.tracks; let duration = 0; for (let i = 0, n2 = tracks.length; i !== n2; ++i) { const track = this.tracks[i]; duration = Math.max(duration, track.times[track.times.length - 1]); } this.duration = duration; return this; } trim() { for (let i = 0; i < this.tracks.length; i++) { this.tracks[i].trim(0, this.duration); } return this; } validate() { let valid = true; for (let i = 0; i < this.tracks.length; i++) { valid = valid && this.tracks[i].validate(); } return valid; } optimize() { for (let i = 0; i < this.tracks.length; i++) { this.tracks[i].optimize(); } return this; } clone() { const tracks = []; for (let i = 0; i < this.tracks.length; i++) { tracks.push(this.tracks[i].clone()); } return new this.constructor(this.name, this.duration, tracks, this.blendMode); } toJSON() { return this.constructor.toJSON(this); } }; function getTrackTypeForValueTypeName(typeName) { switch (typeName.toLowerCase()) { case "scalar": case "double": case "float": case "number": case "integer": return NumberKeyframeTrack; case "vector": case "vector2": case "vector3": case "vector4": return VectorKeyframeTrack; case "color": return ColorKeyframeTrack; case "quaternion": return QuaternionKeyframeTrack; case "bool": case "boolean": return BooleanKeyframeTrack; case "string": return StringKeyframeTrack; } throw new Error("THREE.KeyframeTrack: Unsupported typeName: " + typeName); } function parseKeyframeTrack(json) { if (json.type === void 0) { throw new Error("THREE.KeyframeTrack: track type undefined, can not parse"); } const trackType = getTrackTypeForValueTypeName(json.type); if (json.times === void 0) { const times = [], values = []; flattenJSON(json.keys, times, values, "value"); json.times = times; json.values = values; } if (trackType.parse !== void 0) { return trackType.parse(json); } else { return new trackType(json.name, json.times, json.values, json.interpolation); } } var Cache = { enabled: false, files: {}, add: function(key, file) { if (this.enabled === false) return; this.files[key] = file; }, get: function(key) { if (this.enabled === false) return; return this.files[key]; }, remove: function(key) { delete this.files[key]; }, clear: function() { this.files = {}; } }; var LoadingManager = class { constructor(onLoad, onProgress, onError) { const scope = this; let isLoading = false; let itemsLoaded = 0; let itemsTotal = 0; let urlModifier = void 0; const handlers = []; this.onStart = void 0; this.onLoad = onLoad; this.onProgress = onProgress; this.onError = onError; this.itemStart = function(url) { itemsTotal++; if (isLoading === false) { if (scope.onStart !== void 0) { scope.onStart(url, itemsLoaded, itemsTotal); } } isLoading = true; }; this.itemEnd = function(url) { itemsLoaded++; if (scope.onProgress !== void 0) { scope.onProgress(url, itemsLoaded, itemsTotal); } if (itemsLoaded === itemsTotal) { isLoading = false; if (scope.onLoad !== void 0) { scope.onLoad(); } } }; this.itemError = function(url) { if (scope.onError !== void 0) { scope.onError(url); } }; this.resolveURL = function(url) { if (urlModifier) { return urlModifier(url); } return url; }; this.setURLModifier = function(transform) { urlModifier = transform; return this; }; this.addHandler = function(regex, loader) { handlers.push(regex, loader); return this; }; this.removeHandler = function(regex) { const index = handlers.indexOf(regex); if (index !== -1) { handlers.splice(index, 2); } return this; }; this.getHandler = function(file) { for (let i = 0, l = handlers.length; i < l; i += 2) { const regex = handlers[i]; const loader = handlers[i + 1]; if (regex.global) regex.lastIndex = 0; if (regex.test(file)) { return loader; } } return null; }; } }; var DefaultLoadingManager = new LoadingManager(); var Loader = class { constructor(manager) { this.manager = manager !== void 0 ? manager : DefaultLoadingManager; this.crossOrigin = "anonymous"; this.withCredentials = false; this.path = ""; this.resourcePath = ""; this.requestHeader = {}; } load() { } loadAsync(url, onProgress) { const scope = this; return new Promise(function(resolve, reject) { scope.load(url, resolve, onProgress, reject); }); } parse() { } setCrossOrigin(crossOrigin) { this.crossOrigin = crossOrigin; return this; } setWithCredentials(value) { this.withCredentials = value; return this; } setPath(path) { this.path = path; return this; } setResourcePath(resourcePath) { this.resourcePath = resourcePath; return this; } setRequestHeader(requestHeader) { this.requestHeader = requestHeader; return this; } }; var loading = {}; var HttpError = class extends Error { constructor(message, response) { super(message); this.response = response; } }; var FileLoader = class extends Loader { constructor(manager) { super(manager); } load(url, onLoad, onProgress, onError) { if (url === void 0) url = ""; if (this.path !== void 0) url = this.path + url; url = this.manager.resolveURL(url); const cached = Cache.get(url); if (cached !== void 0) { this.manager.itemStart(url); setTimeout(() => { if (onLoad) onLoad(cached); this.manager.itemEnd(url); }, 0); return cached; } if (loading[url] !== void 0) { loading[url].push({ onLoad, onProgress, onError }); return; } loading[url] = []; loading[url].push({ onLoad, onProgress, onError }); const req = new Request(url, { headers: new Headers(this.requestHeader), credentials: this.withCredentials ? "include" : "same-origin" // An abort controller could be added within a future PR }); const mimeType = this.mimeType; const responseType = this.responseType; fetch(req).then((response) => { if (response.status === 200 || response.status === 0) { if (response.status === 0) { console.warn("THREE.FileLoader: HTTP Status 0 received."); } if (typeof ReadableStream === "undefined" || response.body === void 0 || response.body.getReader === void 0) { return response; } const callbacks = loading[url]; const reader = response.body.getReader(); const contentLength = response.headers.get("Content-Length"); const total = contentLength ? parseInt(contentLength) : 0; const lengthComputable = total !== 0; let loaded = 0; const stream = new ReadableStream({ start(controller) { readData(); function readData() { reader.read().then(({ done, value }) => { if (done) { controller.close(); } else { loaded += value.byteLength; const event = new ProgressEvent("progress", { lengthComputable, loaded, total }); for (let i = 0, il = callbacks.length; i < il; i++) { const callback = callbacks[i]; if (callback.onProgress) callback.onProgress(event); } controller.enqueue(value); readData(); } }); } } }); return new Response(stream); } else { throw new HttpError(`fetch for "${response.url}" responded with ${response.status}: ${response.statusText}`, response); } }).then((response) => { switch (responseType) { case "arraybuffer": return response.arrayBuffer(); case "blob": return response.blob(); case "document": return response.text().then((text) => { const parser = new DOMParser(); return parser.parseFromString(text, mimeType); }); case "json": return response.json(); default: if (mimeType === void 0) { return response.text(); } else { const re = /charset="?([^;"\s]*)"?/i; const exec = re.exec(mimeType); const label = exec && exec[1] ? exec[1].toLowerCase() : void 0; const decoder = new TextDecoder(label); return response.arrayBuffer().then((ab) => decoder.decode(ab)); } } }).then((data) => { Cache.add(url, data); const callbacks = loading[url]; delete loading[url]; for (let i = 0, il = callbacks.length; i < il; i++) { const callback = callbacks[i]; if (callback.onLoad) callback.onLoad(data); } }).catch((err) => { const callbacks = loading[url]; if (callbacks === void 0) { this.manager.itemError(url); throw err; } delete loading[url]; for (let i = 0, il = callbacks.length; i < il; i++) { const callback = callbacks[i]; if (callback.onError) callback.onError(err); } this.manager.itemError(url); }).finally(() => { this.manager.itemEnd(url); }); this.manager.itemStart(url); } setResponseType(value) { this.responseType = value; return this; } setMimeType(value) { this.mimeType = value; return this; } }; var ImageLoader = class extends Loader { constructor(manager) { super(manager); } load(url, onLoad, onProgress, onError) { if (this.path !== void 0) url = this.path + url; url = this.manager.resolveURL(url); const scope = this; const cached = Cache.get(url); if (cached !== void 0) { scope.manager.itemStart(url); setTimeout(function() { if (onLoad) onLoad(cached); scope.manager.itemEnd(url); }, 0); return cached; } const image = createElementNS("img"); function onImageLoad() { removeEventListeners(); Cache.add(url, this); if (onLoad) onLoad(this); scope.manager.itemEnd(url); } function onImageError(event) { removeEventListeners(); if (onError) onError(event); scope.manager.itemError(url); scope.manager.itemEnd(url); } function removeEventListeners() { image.removeEventListener("load", onImageLoad, false); image.removeEventListener("error", onImageError, false); } image.addEventListener("load", onImageLoad, false); image.addEventListener("error", onImageError, false); if (url.slice(0, 5) !== "data:") { if (this.crossOrigin !== void 0) image.crossOrigin = this.crossOrigin; } scope.manager.itemStart(url); image.src = url; return image; } }; var DataTextureLoader = class extends Loader { constructor(manager) { super(manager); } load(url, onLoad, onProgress, onError) { const scope = this; const texture = new DataTexture(); const loader = new FileLoader(this.manager); loader.setResponseType("arraybuffer"); loader.setRequestHeader(this.requestHeader); loader.setPath(this.path); loader.setWithCredentials(scope.withCredentials); loader.load(url, function(buffer) { const texData = scope.parse(buffer); if (!texData) return; if (texData.image !== void 0) { texture.image = texData.image; } else if (texData.data !== void 0) { texture.image.width = texData.width; texture.image.height = texData.height; texture.image.data = texData.data; } texture.wrapS = texData.wrapS !== void 0 ? texData.wrapS : ClampToEdgeWrapping; texture.wrapT = texData.wrapT !== void 0 ? texData.wrapT : ClampToEdgeWrapping; texture.magFilter = texData.magFilter !== void 0 ? texData.magFilter : LinearFilter; texture.minFilter = texData.minFilter !== void 0 ? texData.minFilter : LinearFilter; texture.anisotropy = texData.anisotropy !== void 0 ? texData.anisotropy : 1; if (texData.encoding !== void 0) { texture.encoding = texData.encoding; } if (texData.flipY !== void 0) { texture.flipY = texData.flipY; } if (texData.format !== void 0) { texture.format = texData.format; } if (texData.type !== void 0) { texture.type = texData.type; } if (texData.mipmaps !== void 0) { texture.mipmaps = texData.mipmaps; texture.minFilter = LinearMipmapLinearFilter; } if (texData.mipmapCount === 1) { texture.minFilter = LinearFilter; } if (texData.generateMipmaps !== void 0) { texture.generateMipmaps = texData.generateMipmaps; } texture.needsUpdate = true; if (onLoad) onLoad(texture, texData); }, onProgress, onError); return texture; } }; var TextureLoader = class extends Loader { constructor(manager) { super(manager); } load(url, onLoad, onProgress, onError) { const texture = new Texture(); const loader = new ImageLoader(this.manager); loader.setCrossOrigin(this.crossOrigin); loader.setPath(this.path); loader.load(url, function(image) { texture.image = image; texture.needsUpdate = true; if (onLoad !== void 0) { onLoad(texture); } }, onProgress, onError); return texture; } }; var Light = class extends Object3D { constructor(color, intensity = 1) { super(); this.isLight = true; this.type = "Light"; this.color = new Color(color); this.intensity = intensity; } dispose() { } copy(source, recursive) { super.copy(source, recursive); this.color.copy(source.color); this.intensity = source.intensity; return this; } toJSON(meta) { const data = super.toJSON(meta); data.object.color = this.color.getHex(); data.object.intensity = this.intensity; if (this.groundColor !== void 0) data.object.groundColor = this.groundColor.getHex(); if (this.distance !== void 0) data.object.distance = this.distance; if (this.angle !== void 0) data.object.angle = this.angle; if (this.decay !== void 0) data.object.decay = this.decay; if (this.penumbra !== void 0) data.object.penumbra = this.penumbra; if (this.shadow !== void 0) data.object.shadow = this.shadow.toJSON(); return data; } }; var _projScreenMatrix$1 = new Matrix4(); var _lightPositionWorld$1 = new Vector3(); var _lookTarget$1 = new Vector3(); var LightShadow = class { constructor(camera2) { this.camera = camera2; this.bias = 0; this.normalBias = 0; this.radius = 1; this.blurSamples = 8; this.mapSize = new Vector2(512, 512); this.map = null; this.mapPass = null; this.matrix = new Matrix4(); this.autoUpdate = true; this.needsUpdate = false; this._frustum = new Frustum(); this._frameExtents = new Vector2(1, 1); this._viewportCount = 1; this._viewports = [ new Vector4(0, 0, 1, 1) ]; } getViewportCount() { return this._viewportCount; } getFrustum() { return this._frustum; } updateMatrices(light) { const shadowCamera = this.camera; const shadowMatrix = this.matrix; _lightPositionWorld$1.setFromMatrixPosition(light.matrixWorld); shadowCamera.position.copy(_lightPositionWorld$1); _lookTarget$1.setFromMatrixPosition(light.target.matrixWorld); shadowCamera.lookAt(_lookTarget$1); shadowCamera.updateMatrixWorld(); _projScreenMatrix$1.multiplyMatrices(shadowCamera.projectionMatrix, shadowCamera.matrixWorldInverse); this._frustum.setFromProjectionMatrix(_projScreenMatrix$1); shadowMatrix.set( 0.5, 0, 0, 0.5, 0, 0.5, 0, 0.5, 0, 0, 0.5, 0.5, 0, 0, 0, 1 ); shadowMatrix.multiply(_projScreenMatrix$1); } getViewport(viewportIndex) { return this._viewports[viewportIndex]; } getFrameExtents() { return this._frameExtents; } dispose() { if (this.map) { this.map.dispose(); } if (this.mapPass) { this.mapPass.dispose(); } } copy(source) { this.camera = source.camera.clone(); this.bias = source.bias; this.radius = source.radius; this.mapSize.copy(source.mapSize); return this; } clone() { return new this.constructor().copy(this); } toJSON() { const object = {}; if (this.bias !== 0) object.bias = this.bias; if (this.normalBias !== 0) object.normalBias = this.normalBias; if (this.radius !== 1) object.radius = this.radius; if (this.mapSize.x !== 512 || this.mapSize.y !== 512) object.mapSize = this.mapSize.toArray(); object.camera = this.camera.toJSON(false).object; delete object.camera.matrix; return object; } }; var SpotLightShadow = class extends LightShadow { constructor() { super(new PerspectiveCamera(50, 1, 0.5, 500)); this.isSpotLightShadow = true; this.focus = 1; } updateMatrices(light) { const camera2 = this.camera; const fov2 = RAD2DEG * 2 * light.angle * this.focus; const aspect2 = this.mapSize.width / this.mapSize.height; const far = light.distance || camera2.far; if (fov2 !== camera2.fov || aspect2 !== camera2.aspect || far !== camera2.far) { camera2.fov = fov2; camera2.aspect = aspect2; camera2.far = far; camera2.updateProjectionMatrix(); } super.updateMatrices(light); } copy(source) { super.copy(source); this.focus = source.focus; return this; } }; var SpotLight = class extends Light { constructor(color, intensity, distance = 0, angle = Math.PI / 3, penumbra = 0, decay = 1) { super(color, intensity); this.isSpotLight = true; this.type = "SpotLight"; this.position.copy(Object3D.DefaultUp); this.updateMatrix(); this.target = new Object3D(); this.distance = distance; this.angle = angle; this.penumbra = penumbra; this.decay = decay; this.map = null; this.shadow = new SpotLightShadow(); } get power() { return this.intensity * Math.PI; } set power(power) { this.intensity = power / Math.PI; } dispose() { this.shadow.dispose(); } copy(source, recursive) { super.copy(source, recursive); this.distance = source.distance; this.angle = source.angle; this.penumbra = source.penumbra; this.decay = source.decay; this.target = source.target.clone(); this.shadow = source.shadow.clone(); return this; } }; var _projScreenMatrix = new Matrix4(); var _lightPositionWorld = new Vector3(); var _lookTarget = new Vector3(); var PointLightShadow = class extends LightShadow { constructor() { super(new PerspectiveCamera(90, 1, 0.5, 500)); this.isPointLightShadow = true; this._frameExtents = new Vector2(4, 2); this._viewportCount = 6; this._viewports = [ // These viewports map a cube-map onto a 2D texture with the // following orientation: // // xzXZ // y Y // // X - Positive x direction // x - Negative x direction // Y - Positive y direction // y - Negative y direction // Z - Positive z direction // z - Negative z direction // positive X new Vector4(2, 1, 1, 1), // negative X new Vector4(0, 1, 1, 1), // positive Z new Vector4(3, 1, 1, 1), // negative Z new Vector4(1, 1, 1, 1), // positive Y new Vector4(3, 0, 1, 1), // negative Y new Vector4(1, 0, 1, 1) ]; this._cubeDirections = [ new Vector3(1, 0, 0), new Vector3(-1, 0, 0), new Vector3(0, 0, 1), new Vector3(0, 0, -1), new Vector3(0, 1, 0), new Vector3(0, -1, 0) ]; this._cubeUps = [ new Vector3(0, 1, 0), new Vector3(0, 1, 0), new Vector3(0, 1, 0), new Vector3(0, 1, 0), new Vector3(0, 0, 1), new Vector3(0, 0, -1) ]; } updateMatrices(light, viewportIndex = 0) { const camera2 = this.camera; const shadowMatrix = this.matrix; const far = light.distance || camera2.far; if (far !== camera2.far) { camera2.far = far; camera2.updateProjectionMatrix(); } _lightPositionWorld.setFromMatrixPosition(light.matrixWorld); camera2.position.copy(_lightPositionWorld); _lookTarget.copy(camera2.position); _lookTarget.add(this._cubeDirections[viewportIndex]); camera2.up.copy(this._cubeUps[viewportIndex]); camera2.lookAt(_lookTarget); camera2.updateMatrixWorld(); shadowMatrix.makeTranslation(-_lightPositionWorld.x, -_lightPositionWorld.y, -_lightPositionWorld.z); _projScreenMatrix.multiplyMatrices(camera2.projectionMatrix, camera2.matrixWorldInverse); this._frustum.setFromProjectionMatrix(_projScreenMatrix); } }; var PointLight = class extends Light { constructor(color, intensity, distance = 0, decay = 1) { super(color, intensity); this.isPointLight = true; this.type = "PointLight"; this.distance = distance; this.decay = decay; this.shadow = new PointLightShadow(); } get power() { return this.intensity * 4 * Math.PI; } set power(power) { this.intensity = power / (4 * Math.PI); } dispose() { this.shadow.dispose(); } copy(source, recursive) { super.copy(source, recursive); this.distance = source.distance; this.decay = source.decay; this.shadow = source.shadow.clone(); return this; } }; var DirectionalLightShadow = class extends LightShadow { constructor() { super(new OrthographicCamera(-5, 5, 5, -5, 0.5, 500)); this.isDirectionalLightShadow = true; } }; var DirectionalLight = class extends Light { constructor(color, intensity) { super(color, intensity); this.isDirectionalLight = true; this.type = "DirectionalLight"; this.position.copy(Object3D.DefaultUp); this.updateMatrix(); this.target = new Object3D(); this.shadow = new DirectionalLightShadow(); } dispose() { this.shadow.dispose(); } copy(source) { super.copy(source); this.target = source.target.clone(); this.shadow = source.shadow.clone(); return this; } }; var SphericalHarmonics3 = class { constructor() { this.isSphericalHarmonics3 = true; this.coefficients = []; for (let i = 0; i < 9; i++) { this.coefficients.push(new Vector3()); } } set(coefficients) { for (let i = 0; i < 9; i++) { this.coefficients[i].copy(coefficients[i]); } return this; } zero() { for (let i = 0; i < 9; i++) { this.coefficients[i].set(0, 0, 0); } return this; } // get the radiance in the direction of the normal // target is a Vector3 getAt(normal, target2) { const x2 = normal.x, y = normal.y, z = normal.z; const coeff = this.coefficients; target2.copy(coeff[0]).multiplyScalar(0.282095); target2.addScaledVector(coeff[1], 0.488603 * y); target2.addScaledVector(coeff[2], 0.488603 * z); target2.addScaledVector(coeff[3], 0.488603 * x2); target2.addScaledVector(coeff[4], 1.092548 * (x2 * y)); target2.addScaledVector(coeff[5], 1.092548 * (y * z)); target2.addScaledVector(coeff[6], 0.315392 * (3 * z * z - 1)); target2.addScaledVector(coeff[7], 1.092548 * (x2 * z)); target2.addScaledVector(coeff[8], 0.546274 * (x2 * x2 - y * y)); return target2; } // get the irradiance (radiance convolved with cosine lobe) in the direction of the normal // target is a Vector3 // https://graphics.stanford.edu/papers/envmap/envmap.pdf getIrradianceAt(normal, target2) { const x2 = normal.x, y = normal.y, z = normal.z; const coeff = this.coefficients; target2.copy(coeff[0]).multiplyScalar(0.886227); target2.addScaledVector(coeff[1], 2 * 0.511664 * y); target2.addScaledVector(coeff[2], 2 * 0.511664 * z); target2.addScaledVector(coeff[3], 2 * 0.511664 * x2); target2.addScaledVector(coeff[4], 2 * 0.429043 * x2 * y); target2.addScaledVector(coeff[5], 2 * 0.429043 * y * z); target2.addScaledVector(coeff[6], 0.743125 * z * z - 0.247708); target2.addScaledVector(coeff[7], 2 * 0.429043 * x2 * z); target2.addScaledVector(coeff[8], 0.429043 * (x2 * x2 - y * y)); return target2; } add(sh) { for (let i = 0; i < 9; i++) { this.coefficients[i].add(sh.coefficients[i]); } return this; } addScaledSH(sh, s) { for (let i = 0; i < 9; i++) { this.coefficients[i].addScaledVector(sh.coefficients[i], s); } return this; } scale(s) { for (let i = 0; i < 9; i++) { this.coefficients[i].multiplyScalar(s); } return this; } lerp(sh, alpha) { for (let i = 0; i < 9; i++) { this.coefficients[i].lerp(sh.coefficients[i], alpha); } return this; } equals(sh) { for (let i = 0; i < 9; i++) { if (!this.coefficients[i].equals(sh.coefficients[i])) { return false; } } return true; } copy(sh) { return this.set(sh.coefficients); } clone() { return new this.constructor().copy(this); } fromArray(array, offset = 0) { const coefficients = this.coefficients; for (let i = 0; i < 9; i++) { coefficients[i].fromArray(array, offset + i * 3); } return this; } toArray(array = [], offset = 0) { const coefficients = this.coefficients; for (let i = 0; i < 9; i++) { coefficients[i].toArray(array, offset + i * 3); } return array; } // evaluate the basis functions // shBasis is an Array[ 9 ] static getBasisAt(normal, shBasis) { const x2 = normal.x, y = normal.y, z = normal.z; shBasis[0] = 0.282095; shBasis[1] = 0.488603 * y; shBasis[2] = 0.488603 * z; shBasis[3] = 0.488603 * x2; shBasis[4] = 1.092548 * x2 * y; shBasis[5] = 1.092548 * y * z; shBasis[6] = 0.315392 * (3 * z * z - 1); shBasis[7] = 1.092548 * x2 * z; shBasis[8] = 0.546274 * (x2 * x2 - y * y); } }; var LightProbe = class extends Light { constructor(sh = new SphericalHarmonics3(), intensity = 1) { super(void 0, intensity); this.isLightProbe = true; this.sh = sh; } copy(source) { super.copy(source); this.sh.copy(source.sh); return this; } fromJSON(json) { this.intensity = json.intensity; this.sh.fromArray(json.sh); return this; } toJSON(meta) { const data = super.toJSON(meta); data.object.sh = this.sh.toArray(); return data; } }; var LoaderUtils = class { static decodeText(array) { if (typeof TextDecoder !== "undefined") { return new TextDecoder().decode(array); } let s = ""; for (let i = 0, il = array.length; i < il; i++) { s += String.fromCharCode(array[i]); } try { return decodeURIComponent(escape(s)); } catch (e) { return s; } } static extractUrlBase(url) { const index = url.lastIndexOf("/"); if (index === -1) return "./"; return url.slice(0, index + 1); } static resolveURL(url, path) { if (typeof url !== "string" || url === "") return ""; if (/^https?:\/\//i.test(path) && /^\//.test(url)) { path = path.replace(/(^https?:\/\/[^\/]+).*/i, "$1"); } if (/^(https?:)?\/\//i.test(url)) return url; if (/^data:.*,.*$/i.test(url)) return url; if (/^blob:.*$/i.test(url)) return url; return path + url; } }; var ImageBitmapLoader = class extends Loader { constructor(manager) { super(manager); this.isImageBitmapLoader = true; if (typeof createImageBitmap === "undefined") { console.warn("THREE.ImageBitmapLoader: createImageBitmap() not supported."); } if (typeof fetch === "undefined") { console.warn("THREE.ImageBitmapLoader: fetch() not supported."); } this.options = { premultiplyAlpha: "none" }; } setOptions(options) { this.options = options; return this; } load(url, onLoad, onProgress, onError) { if (url === void 0) url = ""; if (this.path !== void 0) url = this.path + url; url = this.manager.resolveURL(url); const scope = this; const cached = Cache.get(url); if (cached !== void 0) { scope.manager.itemStart(url); setTimeout(function() { if (onLoad) onLoad(cached); scope.manager.itemEnd(url); }, 0); return cached; } const fetchOptions = {}; fetchOptions.credentials = this.crossOrigin === "anonymous" ? "same-origin" : "include"; fetchOptions.headers = this.requestHeader; fetch(url, fetchOptions).then(function(res) { return res.blob(); }).then(function(blob) { return createImageBitmap(blob, Object.assign(scope.options, { colorSpaceConversion: "none" })); }).then(function(imageBitmap) { Cache.add(url, imageBitmap); if (onLoad) onLoad(imageBitmap); scope.manager.itemEnd(url); }).catch(function(e) { if (onError) onError(e); scope.manager.itemError(url); scope.manager.itemEnd(url); }); scope.manager.itemStart(url); } }; var _eyeRight = new Matrix4(); var _eyeLeft = new Matrix4(); var _projectionMatrix = new Matrix4(); var _position$1 = new Vector3(); var _quaternion$1 = new Quaternion(); var _scale$1 = new Vector3(); var _orientation$1 = new Vector3(); var _position = new Vector3(); var _quaternion = new Quaternion(); var _scale = new Vector3(); var _orientation = new Vector3(); var PropertyMixer = class { constructor(binding, typeName, valueSize) { this.binding = binding; this.valueSize = valueSize; let mixFunction, mixFunctionAdditive, setIdentity; switch (typeName) { case "quaternion": mixFunction = this._slerp; mixFunctionAdditive = this._slerpAdditive; setIdentity = this._setAdditiveIdentityQuaternion; this.buffer = new Float64Array(valueSize * 6); this._workIndex = 5; break; case "string": case "bool": mixFunction = this._select; mixFunctionAdditive = this._select; setIdentity = this._setAdditiveIdentityOther; this.buffer = new Array(valueSize * 5); break; default: mixFunction = this._lerp; mixFunctionAdditive = this._lerpAdditive; setIdentity = this._setAdditiveIdentityNumeric; this.buffer = new Float64Array(valueSize * 5); } this._mixBufferRegion = mixFunction; this._mixBufferRegionAdditive = mixFunctionAdditive; this._setIdentity = setIdentity; this._origIndex = 3; this._addIndex = 4; this.cumulativeWeight = 0; this.cumulativeWeightAdditive = 0; this.useCount = 0; this.referenceCount = 0; } // accumulate data in the 'incoming' region into 'accu' accumulate(accuIndex, weight) { const buffer = this.buffer, stride = this.valueSize, offset = accuIndex * stride + stride; let currentWeight = this.cumulativeWeight; if (currentWeight === 0) { for (let i = 0; i !== stride; ++i) { buffer[offset + i] = buffer[i]; } currentWeight = weight; } else { currentWeight += weight; const mix = weight / currentWeight; this._mixBufferRegion(buffer, offset, 0, mix, stride); } this.cumulativeWeight = currentWeight; } // accumulate data in the 'incoming' region into 'add' accumulateAdditive(weight) { const buffer = this.buffer, stride = this.valueSize, offset = stride * this._addIndex; if (this.cumulativeWeightAdditive === 0) { this._setIdentity(); } this._mixBufferRegionAdditive(buffer, offset, 0, weight, stride); this.cumulativeWeightAdditive += weight; } // apply the state of 'accu' to the binding when accus differ apply(accuIndex) { const stride = this.valueSize, buffer = this.buffer, offset = accuIndex * stride + stride, weight = this.cumulativeWeight, weightAdditive = this.cumulativeWeightAdditive, binding = this.binding; this.cumulativeWeight = 0; this.cumulativeWeightAdditive = 0; if (weight < 1) { const originalValueOffset = stride * this._origIndex; this._mixBufferRegion( buffer, offset, originalValueOffset, 1 - weight, stride ); } if (weightAdditive > 0) { this._mixBufferRegionAdditive(buffer, offset, this._addIndex * stride, 1, stride); } for (let i = stride, e = stride + stride; i !== e; ++i) { if (buffer[i] !== buffer[i + stride]) { binding.setValue(buffer, offset); break; } } } // remember the state of the bound property and copy it to both accus saveOriginalState() { const binding = this.binding; const buffer = this.buffer, stride = this.valueSize, originalValueOffset = stride * this._origIndex; binding.getValue(buffer, originalValueOffset); for (let i = stride, e = originalValueOffset; i !== e; ++i) { buffer[i] = buffer[originalValueOffset + i % stride]; } this._setIdentity(); this.cumulativeWeight = 0; this.cumulativeWeightAdditive = 0; } // apply the state previously taken via 'saveOriginalState' to the binding restoreOriginalState() { const originalValueOffset = this.valueSize * 3; this.binding.setValue(this.buffer, originalValueOffset); } _setAdditiveIdentityNumeric() { const startIndex = this._addIndex * this.valueSize; const endIndex = startIndex + this.valueSize; for (let i = startIndex; i < endIndex; i++) { this.buffer[i] = 0; } } _setAdditiveIdentityQuaternion() { this._setAdditiveIdentityNumeric(); this.buffer[this._addIndex * this.valueSize + 3] = 1; } _setAdditiveIdentityOther() { const startIndex = this._origIndex * this.valueSize; const targetIndex = this._addIndex * this.valueSize; for (let i = 0; i < this.valueSize; i++) { this.buffer[targetIndex + i] = this.buffer[startIndex + i]; } } // mix functions _select(buffer, dstOffset, srcOffset, t2, stride) { if (t2 >= 0.5) { for (let i = 0; i !== stride; ++i) { buffer[dstOffset + i] = buffer[srcOffset + i]; } } } _slerp(buffer, dstOffset, srcOffset, t2) { Quaternion.slerpFlat(buffer, dstOffset, buffer, dstOffset, buffer, srcOffset, t2); } _slerpAdditive(buffer, dstOffset, srcOffset, t2, stride) { const workOffset = this._workIndex * stride; Quaternion.multiplyQuaternionsFlat(buffer, workOffset, buffer, dstOffset, buffer, srcOffset); Quaternion.slerpFlat(buffer, dstOffset, buffer, dstOffset, buffer, workOffset, t2); } _lerp(buffer, dstOffset, srcOffset, t2, stride) { const s = 1 - t2; for (let i = 0; i !== stride; ++i) { const j = dstOffset + i; buffer[j] = buffer[j] * s + buffer[srcOffset + i] * t2; } } _lerpAdditive(buffer, dstOffset, srcOffset, t2, stride) { for (let i = 0; i !== stride; ++i) { const j = dstOffset + i; buffer[j] = buffer[j] + buffer[srcOffset + i] * t2; } } }; var _RESERVED_CHARS_RE = "\\[\\]\\.:\\/"; var _reservedRe = new RegExp("[" + _RESERVED_CHARS_RE + "]", "g"); var _wordChar = "[^" + _RESERVED_CHARS_RE + "]"; var _wordCharOrDot = "[^" + _RESERVED_CHARS_RE.replace("\\.", "") + "]"; var _directoryRe = /((?:WC+[\/:])*)/.source.replace("WC", _wordChar); var _nodeRe = /(WCOD+)?/.source.replace("WCOD", _wordCharOrDot); var _objectRe = /(?:\.(WC+)(?:\[(.+)\])?)?/.source.replace("WC", _wordChar); var _propertyRe = /\.(WC+)(?:\[(.+)\])?/.source.replace("WC", _wordChar); var _trackRe = new RegExp( "^" + _directoryRe + _nodeRe + _objectRe + _propertyRe + "$" ); var _supportedObjectNames = ["material", "materials", "bones", "map"]; var Composite = class { constructor(targetGroup, path, optionalParsedPath) { const parsedPath = optionalParsedPath || PropertyBinding.parseTrackName(path); this._targetGroup = targetGroup; this._bindings = targetGroup.subscribe_(path, parsedPath); } getValue(array, offset) { this.bind(); const firstValidIndex = this._targetGroup.nCachedObjects_, binding = this._bindings[firstValidIndex]; if (binding !== void 0) binding.getValue(array, offset); } setValue(array, offset) { const bindings = this._bindings; for (let i = this._targetGroup.nCachedObjects_, n2 = bindings.length; i !== n2; ++i) { bindings[i].setValue(array, offset); } } bind() { const bindings = this._bindings; for (let i = this._targetGroup.nCachedObjects_, n2 = bindings.length; i !== n2; ++i) { bindings[i].bind(); } } unbind() { const bindings = this._bindings; for (let i = this._targetGroup.nCachedObjects_, n2 = bindings.length; i !== n2; ++i) { bindings[i].unbind(); } } }; var PropertyBinding = class _PropertyBinding { constructor(rootNode, path, parsedPath) { this.path = path; this.parsedPath = parsedPath || _PropertyBinding.parseTrackName(path); this.node = _PropertyBinding.findNode(rootNode, this.parsedPath.nodeName) || rootNode; this.rootNode = rootNode; this.getValue = this._getValue_unbound; this.setValue = this._setValue_unbound; } static create(root, path, parsedPath) { if (!(root && root.isAnimationObjectGroup)) { return new _PropertyBinding(root, path, parsedPath); } else { return new _PropertyBinding.Composite(root, path, parsedPath); } } /** * Replaces spaces with underscores and removes unsupported characters from * node names, to ensure compatibility with parseTrackName(). * * @param {string} name Node name to be sanitized. * @return {string} */ static sanitizeNodeName(name) { return name.replace(/\s/g, "_").replace(_reservedRe, ""); } static parseTrackName(trackName) { const matches = _trackRe.exec(trackName); if (matches === null) { throw new Error("PropertyBinding: Cannot parse trackName: " + trackName); } const results = { // directoryName: matches[ 1 ], // (tschw) currently unused nodeName: matches[2], objectName: matches[3], objectIndex: matches[4], propertyName: matches[5], // required propertyIndex: matches[6] }; const lastDot = results.nodeName && results.nodeName.lastIndexOf("."); if (lastDot !== void 0 && lastDot !== -1) { const objectName = results.nodeName.substring(lastDot + 1); if (_supportedObjectNames.indexOf(objectName) !== -1) { results.nodeName = results.nodeName.substring(0, lastDot); results.objectName = objectName; } } if (results.propertyName === null || results.propertyName.length === 0) { throw new Error("PropertyBinding: can not parse propertyName from trackName: " + trackName); } return results; } static findNode(root, nodeName) { if (nodeName === void 0 || nodeName === "" || nodeName === "." || nodeName === -1 || nodeName === root.name || nodeName === root.uuid) { return root; } if (root.skeleton) { const bone = root.skeleton.getBoneByName(nodeName); if (bone !== void 0) { return bone; } } if (root.children) { const searchNodeSubtree = function(children) { for (let i = 0; i < children.length; i++) { const childNode = children[i]; if (childNode.name === nodeName || childNode.uuid === nodeName) { return childNode; } const result = searchNodeSubtree(childNode.children); if (result) return result; } return null; }; const subTreeNode = searchNodeSubtree(root.children); if (subTreeNode) { return subTreeNode; } } return null; } // these are used to "bind" a nonexistent property _getValue_unavailable() { } _setValue_unavailable() { } // Getters _getValue_direct(buffer, offset) { buffer[offset] = this.targetObject[this.propertyName]; } _getValue_array(buffer, offset) { const source = this.resolvedProperty; for (let i = 0, n2 = source.length; i !== n2; ++i) { buffer[offset++] = source[i]; } } _getValue_arrayElement(buffer, offset) { buffer[offset] = this.resolvedProperty[this.propertyIndex]; } _getValue_toArray(buffer, offset) { this.resolvedProperty.toArray(buffer, offset); } // Direct _setValue_direct(buffer, offset) { this.targetObject[this.propertyName] = buffer[offset]; } _setValue_direct_setNeedsUpdate(buffer, offset) { this.targetObject[this.propertyName] = buffer[offset]; this.targetObject.needsUpdate = true; } _setValue_direct_setMatrixWorldNeedsUpdate(buffer, offset) { this.targetObject[this.propertyName] = buffer[offset]; this.targetObject.matrixWorldNeedsUpdate = true; } // EntireArray _setValue_array(buffer, offset) { const dest = this.resolvedProperty; for (let i = 0, n2 = dest.length; i !== n2; ++i) { dest[i] = buffer[offset++]; } } _setValue_array_setNeedsUpdate(buffer, offset) { const dest = this.resolvedProperty; for (let i = 0, n2 = dest.length; i !== n2; ++i) { dest[i] = buffer[offset++]; } this.targetObject.needsUpdate = true; } _setValue_array_setMatrixWorldNeedsUpdate(buffer, offset) { const dest = this.resolvedProperty; for (let i = 0, n2 = dest.length; i !== n2; ++i) { dest[i] = buffer[offset++]; } this.targetObject.matrixWorldNeedsUpdate = true; } // ArrayElement _setValue_arrayElement(buffer, offset) { this.resolvedProperty[this.propertyIndex] = buffer[offset]; } _setValue_arrayElement_setNeedsUpdate(buffer, offset) { this.resolvedProperty[this.propertyIndex] = buffer[offset]; this.targetObject.needsUpdate = true; } _setValue_arrayElement_setMatrixWorldNeedsUpdate(buffer, offset) { this.resolvedProperty[this.propertyIndex] = buffer[offset]; this.targetObject.matrixWorldNeedsUpdate = true; } // HasToFromArray _setValue_fromArray(buffer, offset) { this.resolvedProperty.fromArray(buffer, offset); } _setValue_fromArray_setNeedsUpdate(buffer, offset) { this.resolvedProperty.fromArray(buffer, offset); this.targetObject.needsUpdate = true; } _setValue_fromArray_setMatrixWorldNeedsUpdate(buffer, offset) { this.resolvedProperty.fromArray(buffer, offset); this.targetObject.matrixWorldNeedsUpdate = true; } _getValue_unbound(targetArray, offset) { this.bind(); this.getValue(targetArray, offset); } _setValue_unbound(sourceArray, offset) { this.bind(); this.setValue(sourceArray, offset); } // create getter / setter pair for a property in the scene graph bind() { let targetObject = this.node; const parsedPath = this.parsedPath; const objectName = parsedPath.objectName; const propertyName = parsedPath.propertyName; let propertyIndex = parsedPath.propertyIndex; if (!targetObject) { targetObject = _PropertyBinding.findNode(this.rootNode, parsedPath.nodeName) || this.rootNode; this.node = targetObject; } this.getValue = this._getValue_unavailable; this.setValue = this._setValue_unavailable; if (!targetObject) { console.error("THREE.PropertyBinding: Trying to update node for track: " + this.path + " but it wasn't found."); return; } if (objectName) { let objectIndex = parsedPath.objectIndex; switch (objectName) { case "materials": if (!targetObject.material) { console.error("THREE.PropertyBinding: Can not bind to material as node does not have a material.", this); return; } if (!targetObject.material.materials) { console.error("THREE.PropertyBinding: Can not bind to material.materials as node.material does not have a materials array.", this); return; } targetObject = targetObject.material.materials; break; case "bones": if (!targetObject.skeleton) { console.error("THREE.PropertyBinding: Can not bind to bones as node does not have a skeleton.", this); return; } targetObject = targetObject.skeleton.bones; for (let i = 0; i < targetObject.length; i++) { if (targetObject[i].name === objectIndex) { objectIndex = i; break; } } break; case "map": if ("map" in targetObject) { targetObject = targetObject.map; break; } if (!targetObject.material) { console.error("THREE.PropertyBinding: Can not bind to material as node does not have a material.", this); return; } if (!targetObject.material.map) { console.error("THREE.PropertyBinding: Can not bind to material.map as node.material does not have a map.", this); return; } targetObject = targetObject.material.map; break; default: if (targetObject[objectName] === void 0) { console.error("THREE.PropertyBinding: Can not bind to objectName of node undefined.", this); return; } targetObject = targetObject[objectName]; } if (objectIndex !== void 0) { if (targetObject[objectIndex] === void 0) { console.error("THREE.PropertyBinding: Trying to bind to objectIndex of objectName, but is undefined.", this, targetObject); return; } targetObject = targetObject[objectIndex]; } } const nodeProperty = targetObject[propertyName]; if (nodeProperty === void 0) { const nodeName = parsedPath.nodeName; console.error("THREE.PropertyBinding: Trying to update property for track: " + nodeName + "." + propertyName + " but it wasn't found.", targetObject); return; } let versioning = this.Versioning.None; this.targetObject = targetObject; if (targetObject.needsUpdate !== void 0) { versioning = this.Versioning.NeedsUpdate; } else if (targetObject.matrixWorldNeedsUpdate !== void 0) { versioning = this.Versioning.MatrixWorldNeedsUpdate; } let bindingType = this.BindingType.Direct; if (propertyIndex !== void 0) { if (propertyName === "morphTargetInfluences") { if (!targetObject.geometry) { console.error("THREE.PropertyBinding: Can not bind to morphTargetInfluences because node does not have a geometry.", this); return; } if (!targetObject.geometry.morphAttributes) { console.error("THREE.PropertyBinding: Can not bind to morphTargetInfluences because node does not have a geometry.morphAttributes.", this); return; } if (targetObject.morphTargetDictionary[propertyIndex] !== void 0) { propertyIndex = targetObject.morphTargetDictionary[propertyIndex]; } } bindingType = this.BindingType.ArrayElement; this.resolvedProperty = nodeProperty; this.propertyIndex = propertyIndex; } else if (nodeProperty.fromArray !== void 0 && nodeProperty.toArray !== void 0) { bindingType = this.BindingType.HasFromToArray; this.resolvedProperty = nodeProperty; } else if (Array.isArray(nodeProperty)) { bindingType = this.BindingType.EntireArray; this.resolvedProperty = nodeProperty; } else { this.propertyName = propertyName; } this.getValue = this.GetterByBindingType[bindingType]; this.setValue = this.SetterByBindingTypeAndVersioning[bindingType][versioning]; } unbind() { this.node = null; this.getValue = this._getValue_unbound; this.setValue = this._setValue_unbound; } }; PropertyBinding.Composite = Composite; PropertyBinding.prototype.BindingType = { Direct: 0, EntireArray: 1, ArrayElement: 2, HasFromToArray: 3 }; PropertyBinding.prototype.Versioning = { None: 0, NeedsUpdate: 1, MatrixWorldNeedsUpdate: 2 }; PropertyBinding.prototype.GetterByBindingType = [ PropertyBinding.prototype._getValue_direct, PropertyBinding.prototype._getValue_array, PropertyBinding.prototype._getValue_arrayElement, PropertyBinding.prototype._getValue_toArray ]; PropertyBinding.prototype.SetterByBindingTypeAndVersioning = [ [ // Direct PropertyBinding.prototype._setValue_direct, PropertyBinding.prototype._setValue_direct_setNeedsUpdate, PropertyBinding.prototype._setValue_direct_setMatrixWorldNeedsUpdate ], [ // EntireArray PropertyBinding.prototype._setValue_array, PropertyBinding.prototype._setValue_array_setNeedsUpdate, PropertyBinding.prototype._setValue_array_setMatrixWorldNeedsUpdate ], [ // ArrayElement PropertyBinding.prototype._setValue_arrayElement, PropertyBinding.prototype._setValue_arrayElement_setNeedsUpdate, PropertyBinding.prototype._setValue_arrayElement_setMatrixWorldNeedsUpdate ], [ // HasToFromArray PropertyBinding.prototype._setValue_fromArray, PropertyBinding.prototype._setValue_fromArray_setNeedsUpdate, PropertyBinding.prototype._setValue_fromArray_setMatrixWorldNeedsUpdate ] ]; var AnimationAction = class { constructor(mixer, clip, localRoot = null, blendMode = clip.blendMode) { this._mixer = mixer; this._clip = clip; this._localRoot = localRoot; this.blendMode = blendMode; const tracks = clip.tracks, nTracks = tracks.length, interpolants = new Array(nTracks); const interpolantSettings = { endingStart: ZeroCurvatureEnding, endingEnd: ZeroCurvatureEnding }; for (let i = 0; i !== nTracks; ++i) { const interpolant = tracks[i].createInterpolant(null); interpolants[i] = interpolant; interpolant.settings = interpolantSettings; } this._interpolantSettings = interpolantSettings; this._interpolants = interpolants; this._propertyBindings = new Array(nTracks); this._cacheIndex = null; this._byClipCacheIndex = null; this._timeScaleInterpolant = null; this._weightInterpolant = null; this.loop = LoopRepeat; this._loopCount = -1; this._startTime = null; this.time = 0; this.timeScale = 1; this._effectiveTimeScale = 1; this.weight = 1; this._effectiveWeight = 1; this.repetitions = Infinity; this.paused = false; this.enabled = true; this.clampWhenFinished = false; this.zeroSlopeAtStart = true; this.zeroSlopeAtEnd = true; } // State & Scheduling play() { this._mixer._activateAction(this); return this; } stop() { this._mixer._deactivateAction(this); return this.reset(); } reset() { this.paused = false; this.enabled = true; this.time = 0; this._loopCount = -1; this._startTime = null; return this.stopFading().stopWarping(); } isRunning() { return this.enabled && !this.paused && this.timeScale !== 0 && this._startTime === null && this._mixer._isActiveAction(this); } // return true when play has been called isScheduled() { return this._mixer._isActiveAction(this); } startAt(time) { this._startTime = time; return this; } setLoop(mode, repetitions) { this.loop = mode; this.repetitions = repetitions; return this; } // Weight // set the weight stopping any scheduled fading // although .enabled = false yields an effective weight of zero, this // method does *not* change .enabled, because it would be confusing setEffectiveWeight(weight) { this.weight = weight; this._effectiveWeight = this.enabled ? weight : 0; return this.stopFading(); } // return the weight considering fading and .enabled getEffectiveWeight() { return this._effectiveWeight; } fadeIn(duration) { return this._scheduleFading(duration, 0, 1); } fadeOut(duration) { return this._scheduleFading(duration, 1, 0); } crossFadeFrom(fadeOutAction, duration, warp) { fadeOutAction.fadeOut(duration); this.fadeIn(duration); if (warp) { const fadeInDuration = this._clip.duration, fadeOutDuration = fadeOutAction._clip.duration, startEndRatio = fadeOutDuration / fadeInDuration, endStartRatio = fadeInDuration / fadeOutDuration; fadeOutAction.warp(1, startEndRatio, duration); this.warp(endStartRatio, 1, duration); } return this; } crossFadeTo(fadeInAction, duration, warp) { return fadeInAction.crossFadeFrom(this, duration, warp); } stopFading() { const weightInterpolant = this._weightInterpolant; if (weightInterpolant !== null) { this._weightInterpolant = null; this._mixer._takeBackControlInterpolant(weightInterpolant); } return this; } // Time Scale Control // set the time scale stopping any scheduled warping // although .paused = true yields an effective time scale of zero, this // method does *not* change .paused, because it would be confusing setEffectiveTimeScale(timeScale) { this.timeScale = timeScale; this._effectiveTimeScale = this.paused ? 0 : timeScale; return this.stopWarping(); } // return the time scale considering warping and .paused getEffectiveTimeScale() { return this._effectiveTimeScale; } setDuration(duration) { this.timeScale = this._clip.duration / duration; return this.stopWarping(); } syncWith(action) { this.time = action.time; this.timeScale = action.timeScale; return this.stopWarping(); } halt(duration) { return this.warp(this._effectiveTimeScale, 0, duration); } warp(startTimeScale, endTimeScale, duration) { const mixer = this._mixer, now = mixer.time, timeScale = this.timeScale; let interpolant = this._timeScaleInterpolant; if (interpolant === null) { interpolant = mixer._lendControlInterpolant(); this._timeScaleInterpolant = interpolant; } const times = interpolant.parameterPositions, values = interpolant.sampleValues; times[0] = now; times[1] = now + duration; values[0] = startTimeScale / timeScale; values[1] = endTimeScale / timeScale; return this; } stopWarping() { const timeScaleInterpolant = this._timeScaleInterpolant; if (timeScaleInterpolant !== null) { this._timeScaleInterpolant = null; this._mixer._takeBackControlInterpolant(timeScaleInterpolant); } return this; } // Object Accessors getMixer() { return this._mixer; } getClip() { return this._clip; } getRoot() { return this._localRoot || this._mixer._root; } // Interna _update(time, deltaTime, timeDirection, accuIndex) { if (!this.enabled) { this._updateWeight(time); return; } const startTime = this._startTime; if (startTime !== null) { const timeRunning = (time - startTime) * timeDirection; if (timeRunning < 0 || timeDirection === 0) { deltaTime = 0; } else { this._startTime = null; deltaTime = timeDirection * timeRunning; } } deltaTime *= this._updateTimeScale(time); const clipTime = this._updateTime(deltaTime); const weight = this._updateWeight(time); if (weight > 0) { const interpolants = this._interpolants; const propertyMixers = this._propertyBindings; switch (this.blendMode) { case AdditiveAnimationBlendMode: for (let j = 0, m = interpolants.length; j !== m; ++j) { interpolants[j].evaluate(clipTime); propertyMixers[j].accumulateAdditive(weight); } break; case NormalAnimationBlendMode: default: for (let j = 0, m = interpolants.length; j !== m; ++j) { interpolants[j].evaluate(clipTime); propertyMixers[j].accumulate(accuIndex, weight); } } } } _updateWeight(time) { let weight = 0; if (this.enabled) { weight = this.weight; const interpolant = this._weightInterpolant; if (interpolant !== null) { const interpolantValue = interpolant.evaluate(time)[0]; weight *= interpolantValue; if (time > interpolant.parameterPositions[1]) { this.stopFading(); if (interpolantValue === 0) { this.enabled = false; } } } } this._effectiveWeight = weight; return weight; } _updateTimeScale(time) { let timeScale = 0; if (!this.paused) { timeScale = this.timeScale; const interpolant = this._timeScaleInterpolant; if (interpolant !== null) { const interpolantValue = interpolant.evaluate(time)[0]; timeScale *= interpolantValue; if (time > interpolant.parameterPositions[1]) { this.stopWarping(); if (timeScale === 0) { this.paused = true; } else { this.timeScale = timeScale; } } } } this._effectiveTimeScale = timeScale; return timeScale; } _updateTime(deltaTime) { const duration = this._clip.duration; const loop = this.loop; let time = this.time + deltaTime; let loopCount = this._loopCount; const pingPong = loop === LoopPingPong; if (deltaTime === 0) { if (loopCount === -1) return time; return pingPong && (loopCount & 1) === 1 ? duration - time : time; } if (loop === LoopOnce) { if (loopCount === -1) { this._loopCount = 0; this._setEndings(true, true, false); } handle_stop: { if (time >= duration) { time = duration; } else if (time < 0) { time = 0; } else { this.time = time; break handle_stop; } if (this.clampWhenFinished) this.paused = true; else this.enabled = false; this.time = time; this._mixer.dispatchEvent({ type: "finished", action: this, direction: deltaTime < 0 ? -1 : 1 }); } } else { if (loopCount === -1) { if (deltaTime >= 0) { loopCount = 0; this._setEndings(true, this.repetitions === 0, pingPong); } else { this._setEndings(this.repetitions === 0, true, pingPong); } } if (time >= duration || time < 0) { const loopDelta = Math.floor(time / duration); time -= duration * loopDelta; loopCount += Math.abs(loopDelta); const pending = this.repetitions - loopCount; if (pending <= 0) { if (this.clampWhenFinished) this.paused = true; else this.enabled = false; time = deltaTime > 0 ? duration : 0; this.time = time; this._mixer.dispatchEvent({ type: "finished", action: this, direction: deltaTime > 0 ? 1 : -1 }); } else { if (pending === 1) { const atStart = deltaTime < 0; this._setEndings(atStart, !atStart, pingPong); } else { this._setEndings(false, false, pingPong); } this._loopCount = loopCount; this.time = time; this._mixer.dispatchEvent({ type: "loop", action: this, loopDelta }); } } else { this.time = time; } if (pingPong && (loopCount & 1) === 1) { return duration - time; } } return time; } _setEndings(atStart, atEnd, pingPong) { const settings = this._interpolantSettings; if (pingPong) { settings.endingStart = ZeroSlopeEnding; settings.endingEnd = ZeroSlopeEnding; } else { if (atStart) { settings.endingStart = this.zeroSlopeAtStart ? ZeroSlopeEnding : ZeroCurvatureEnding; } else { settings.endingStart = WrapAroundEnding; } if (atEnd) { settings.endingEnd = this.zeroSlopeAtEnd ? ZeroSlopeEnding : ZeroCurvatureEnding; } else { settings.endingEnd = WrapAroundEnding; } } } _scheduleFading(duration, weightNow, weightThen) { const mixer = this._mixer, now = mixer.time; let interpolant = this._weightInterpolant; if (interpolant === null) { interpolant = mixer._lendControlInterpolant(); this._weightInterpolant = interpolant; } const times = interpolant.parameterPositions, values = interpolant.sampleValues; times[0] = now; values[0] = weightNow; times[1] = now + duration; values[1] = weightThen; return this; } }; var _controlInterpolantsResultBuffer = new Float32Array(1); var AnimationMixer = class extends EventDispatcher { constructor(root) { super(); this._root = root; this._initMemoryManager(); this._accuIndex = 0; this.time = 0; this.timeScale = 1; } _bindAction(action, prototypeAction) { const root = action._localRoot || this._root, tracks = action._clip.tracks, nTracks = tracks.length, bindings = action._propertyBindings, interpolants = action._interpolants, rootUuid = root.uuid, bindingsByRoot = this._bindingsByRootAndName; let bindingsByName = bindingsByRoot[rootUuid]; if (bindingsByName === void 0) { bindingsByName = {}; bindingsByRoot[rootUuid] = bindingsByName; } for (let i = 0; i !== nTracks; ++i) { const track = tracks[i], trackName = track.name; let binding = bindingsByName[trackName]; if (binding !== void 0) { ++binding.referenceCount; bindings[i] = binding; } else { binding = bindings[i]; if (binding !== void 0) { if (binding._cacheIndex === null) { ++binding.referenceCount; this._addInactiveBinding(binding, rootUuid, trackName); } continue; } const path = prototypeAction && prototypeAction._propertyBindings[i].binding.parsedPath; binding = new PropertyMixer( PropertyBinding.create(root, trackName, path), track.ValueTypeName, track.getValueSize() ); ++binding.referenceCount; this._addInactiveBinding(binding, rootUuid, trackName); bindings[i] = binding; } interpolants[i].resultBuffer = binding.buffer; } } _activateAction(action) { if (!this._isActiveAction(action)) { if (action._cacheIndex === null) { const rootUuid = (action._localRoot || this._root).uuid, clipUuid = action._clip.uuid, actionsForClip = this._actionsByClip[clipUuid]; this._bindAction( action, actionsForClip && actionsForClip.knownActions[0] ); this._addInactiveAction(action, clipUuid, rootUuid); } const bindings = action._propertyBindings; for (let i = 0, n2 = bindings.length; i !== n2; ++i) { const binding = bindings[i]; if (binding.useCount++ === 0) { this._lendBinding(binding); binding.saveOriginalState(); } } this._lendAction(action); } } _deactivateAction(action) { if (this._isActiveAction(action)) { const bindings = action._propertyBindings; for (let i = 0, n2 = bindings.length; i !== n2; ++i) { const binding = bindings[i]; if (--binding.useCount === 0) { binding.restoreOriginalState(); this._takeBackBinding(binding); } } this._takeBackAction(action); } } // Memory manager _initMemoryManager() { this._actions = []; this._nActiveActions = 0; this._actionsByClip = {}; this._bindings = []; this._nActiveBindings = 0; this._bindingsByRootAndName = {}; this._controlInterpolants = []; this._nActiveControlInterpolants = 0; const scope = this; this.stats = { actions: { get total() { return scope._actions.length; }, get inUse() { return scope._nActiveActions; } }, bindings: { get total() { return scope._bindings.length; }, get inUse() { return scope._nActiveBindings; } }, controlInterpolants: { get total() { return scope._controlInterpolants.length; }, get inUse() { return scope._nActiveControlInterpolants; } } }; } // Memory management for AnimationAction objects _isActiveAction(action) { const index = action._cacheIndex; return index !== null && index < this._nActiveActions; } _addInactiveAction(action, clipUuid, rootUuid) { const actions = this._actions, actionsByClip = this._actionsByClip; let actionsForClip = actionsByClip[clipUuid]; if (actionsForClip === void 0) { actionsForClip = { knownActions: [action], actionByRoot: {} }; action._byClipCacheIndex = 0; actionsByClip[clipUuid] = actionsForClip; } else { const knownActions = actionsForClip.knownActions; action._byClipCacheIndex = knownActions.length; knownActions.push(action); } action._cacheIndex = actions.length; actions.push(action); actionsForClip.actionByRoot[rootUuid] = action; } _removeInactiveAction(action) { const actions = this._actions, lastInactiveAction = actions[actions.length - 1], cacheIndex = action._cacheIndex; lastInactiveAction._cacheIndex = cacheIndex; actions[cacheIndex] = lastInactiveAction; actions.pop(); action._cacheIndex = null; const clipUuid = action._clip.uuid, actionsByClip = this._actionsByClip, actionsForClip = actionsByClip[clipUuid], knownActionsForClip = actionsForClip.knownActions, lastKnownAction = knownActionsForClip[knownActionsForClip.length - 1], byClipCacheIndex = action._byClipCacheIndex; lastKnownAction._byClipCacheIndex = byClipCacheIndex; knownActionsForClip[byClipCacheIndex] = lastKnownAction; knownActionsForClip.pop(); action._byClipCacheIndex = null; const actionByRoot = actionsForClip.actionByRoot, rootUuid = (action._localRoot || this._root).uuid; delete actionByRoot[rootUuid]; if (knownActionsForClip.length === 0) { delete actionsByClip[clipUuid]; } this._removeInactiveBindingsForAction(action); } _removeInactiveBindingsForAction(action) { const bindings = action._propertyBindings; for (let i = 0, n2 = bindings.length; i !== n2; ++i) { const binding = bindings[i]; if (--binding.referenceCount === 0) { this._removeInactiveBinding(binding); } } } _lendAction(action) { const actions = this._actions, prevIndex = action._cacheIndex, lastActiveIndex = this._nActiveActions++, firstInactiveAction = actions[lastActiveIndex]; action._cacheIndex = lastActiveIndex; actions[lastActiveIndex] = action; firstInactiveAction._cacheIndex = prevIndex; actions[prevIndex] = firstInactiveAction; } _takeBackAction(action) { const actions = this._actions, prevIndex = action._cacheIndex, firstInactiveIndex = --this._nActiveActions, lastActiveAction = actions[firstInactiveIndex]; action._cacheIndex = firstInactiveIndex; actions[firstInactiveIndex] = action; lastActiveAction._cacheIndex = prevIndex; actions[prevIndex] = lastActiveAction; } // Memory management for PropertyMixer objects _addInactiveBinding(binding, rootUuid, trackName) { const bindingsByRoot = this._bindingsByRootAndName, bindings = this._bindings; let bindingByName = bindingsByRoot[rootUuid]; if (bindingByName === void 0) { bindingByName = {}; bindingsByRoot[rootUuid] = bindingByName; } bindingByName[trackName] = binding; binding._cacheIndex = bindings.length; bindings.push(binding); } _removeInactiveBinding(binding) { const bindings = this._bindings, propBinding = binding.binding, rootUuid = propBinding.rootNode.uuid, trackName = propBinding.path, bindingsByRoot = this._bindingsByRootAndName, bindingByName = bindingsByRoot[rootUuid], lastInactiveBinding = bindings[bindings.length - 1], cacheIndex = binding._cacheIndex; lastInactiveBinding._cacheIndex = cacheIndex; bindings[cacheIndex] = lastInactiveBinding; bindings.pop(); delete bindingByName[trackName]; if (Object.keys(bindingByName).length === 0) { delete bindingsByRoot[rootUuid]; } } _lendBinding(binding) { const bindings = this._bindings, prevIndex = binding._cacheIndex, lastActiveIndex = this._nActiveBindings++, firstInactiveBinding = bindings[lastActiveIndex]; binding._cacheIndex = lastActiveIndex; bindings[lastActiveIndex] = binding; firstInactiveBinding._cacheIndex = prevIndex; bindings[prevIndex] = firstInactiveBinding; } _takeBackBinding(binding) { const bindings = this._bindings, prevIndex = binding._cacheIndex, firstInactiveIndex = --this._nActiveBindings, lastActiveBinding = bindings[firstInactiveIndex]; binding._cacheIndex = firstInactiveIndex; bindings[firstInactiveIndex] = binding; lastActiveBinding._cacheIndex = prevIndex; bindings[prevIndex] = lastActiveBinding; } // Memory management of Interpolants for weight and time scale _lendControlInterpolant() { const interpolants = this._controlInterpolants, lastActiveIndex = this._nActiveControlInterpolants++; let interpolant = interpolants[lastActiveIndex]; if (interpolant === void 0) { interpolant = new LinearInterpolant( new Float32Array(2), new Float32Array(2), 1, _controlInterpolantsResultBuffer ); interpolant.__cacheIndex = lastActiveIndex; interpolants[lastActiveIndex] = interpolant; } return interpolant; } _takeBackControlInterpolant(interpolant) { const interpolants = this._controlInterpolants, prevIndex = interpolant.__cacheIndex, firstInactiveIndex = --this._nActiveControlInterpolants, lastActiveInterpolant = interpolants[firstInactiveIndex]; interpolant.__cacheIndex = firstInactiveIndex; interpolants[firstInactiveIndex] = interpolant; lastActiveInterpolant.__cacheIndex = prevIndex; interpolants[prevIndex] = lastActiveInterpolant; } // return an action for a clip optionally using a custom root target // object (this method allocates a lot of dynamic memory in case a // previously unknown clip/root combination is specified) clipAction(clip, optionalRoot, blendMode) { const root = optionalRoot || this._root, rootUuid = root.uuid; let clipObject = typeof clip === "string" ? AnimationClip.findByName(root, clip) : clip; const clipUuid = clipObject !== null ? clipObject.uuid : clip; const actionsForClip = this._actionsByClip[clipUuid]; let prototypeAction = null; if (blendMode === void 0) { if (clipObject !== null) { blendMode = clipObject.blendMode; } else { blendMode = NormalAnimationBlendMode; } } if (actionsForClip !== void 0) { const existingAction = actionsForClip.actionByRoot[rootUuid]; if (existingAction !== void 0 && existingAction.blendMode === blendMode) { return existingAction; } prototypeAction = actionsForClip.knownActions[0]; if (clipObject === null) clipObject = prototypeAction._clip; } if (clipObject === null) return null; const newAction = new AnimationAction(this, clipObject, optionalRoot, blendMode); this._bindAction(newAction, prototypeAction); this._addInactiveAction(newAction, clipUuid, rootUuid); return newAction; } // get an existing action existingAction(clip, optionalRoot) { const root = optionalRoot || this._root, rootUuid = root.uuid, clipObject = typeof clip === "string" ? AnimationClip.findByName(root, clip) : clip, clipUuid = clipObject ? clipObject.uuid : clip, actionsForClip = this._actionsByClip[clipUuid]; if (actionsForClip !== void 0) { return actionsForClip.actionByRoot[rootUuid] || null; } return null; } // deactivates all previously scheduled actions stopAllAction() { const actions = this._actions, nActions = this._nActiveActions; for (let i = nActions - 1; i >= 0; --i) { actions[i].stop(); } return this; } // advance the time and update apply the animation update(deltaTime) { deltaTime *= this.timeScale; const actions = this._actions, nActions = this._nActiveActions, time = this.time += deltaTime, timeDirection = Math.sign(deltaTime), accuIndex = this._accuIndex ^= 1; for (let i = 0; i !== nActions; ++i) { const action = actions[i]; action._update(time, deltaTime, timeDirection, accuIndex); } const bindings = this._bindings, nBindings = this._nActiveBindings; for (let i = 0; i !== nBindings; ++i) { bindings[i].apply(accuIndex); } return this; } // Allows you to seek to a specific time in an animation. setTime(timeInSeconds) { this.time = 0; for (let i = 0; i < this._actions.length; i++) { this._actions[i].time = 0; } return this.update(timeInSeconds); } // return this mixer's root target object getRoot() { return this._root; } // free all resources specific to a particular clip uncacheClip(clip) { const actions = this._actions, clipUuid = clip.uuid, actionsByClip = this._actionsByClip, actionsForClip = actionsByClip[clipUuid]; if (actionsForClip !== void 0) { const actionsToRemove = actionsForClip.knownActions; for (let i = 0, n2 = actionsToRemove.length; i !== n2; ++i) { const action = actionsToRemove[i]; this._deactivateAction(action); const cacheIndex = action._cacheIndex, lastInactiveAction = actions[actions.length - 1]; action._cacheIndex = null; action._byClipCacheIndex = null; lastInactiveAction._cacheIndex = cacheIndex; actions[cacheIndex] = lastInactiveAction; actions.pop(); this._removeInactiveBindingsForAction(action); } delete actionsByClip[clipUuid]; } } // free all resources specific to a particular root target object uncacheRoot(root) { const rootUuid = root.uuid, actionsByClip = this._actionsByClip; for (const clipUuid in actionsByClip) { const actionByRoot = actionsByClip[clipUuid].actionByRoot, action = actionByRoot[rootUuid]; if (action !== void 0) { this._deactivateAction(action); this._removeInactiveAction(action); } } const bindingsByRoot = this._bindingsByRootAndName, bindingByName = bindingsByRoot[rootUuid]; if (bindingByName !== void 0) { for (const trackName in bindingByName) { const binding = bindingByName[trackName]; binding.restoreOriginalState(); this._removeInactiveBinding(binding); } } } // remove a targeted clip from the cache uncacheAction(clip, optionalRoot) { const action = this.existingAction(clip, optionalRoot); if (action !== null) { this._deactivateAction(action); this._removeInactiveAction(action); } } }; var Raycaster = class { constructor(origin, direction, near = 0, far = Infinity) { this.ray = new Ray(origin, direction); this.near = near; this.far = far; this.camera = null; this.layers = new Layers(); this.params = { Mesh: {}, Line: { threshold: 1 }, LOD: {}, Points: { threshold: 1 }, Sprite: {} }; } set(origin, direction) { this.ray.set(origin, direction); } setFromCamera(coords, camera2) { if (camera2.isPerspectiveCamera) { this.ray.origin.setFromMatrixPosition(camera2.matrixWorld); this.ray.direction.set(coords.x, coords.y, 0.5).unproject(camera2).sub(this.ray.origin).normalize(); this.camera = camera2; } else if (camera2.isOrthographicCamera) { this.ray.origin.set(coords.x, coords.y, (camera2.near + camera2.far) / (camera2.near - camera2.far)).unproject(camera2); this.ray.direction.set(0, 0, -1).transformDirection(camera2.matrixWorld); this.camera = camera2; } else { console.error("THREE.Raycaster: Unsupported camera type: " + camera2.type); } } intersectObject(object, recursive = true, intersects2 = []) { intersectObject(object, this, intersects2, recursive); intersects2.sort(ascSort); return intersects2; } intersectObjects(objects, recursive = true, intersects2 = []) { for (let i = 0, l = objects.length; i < l; i++) { intersectObject(objects[i], this, intersects2, recursive); } intersects2.sort(ascSort); return intersects2; } }; function ascSort(a, b) { return a.distance - b.distance; } function intersectObject(object, raycaster2, intersects2, recursive) { if (object.layers.test(raycaster2.layers)) { object.raycast(raycaster2, intersects2); } if (recursive === true) { const children = object.children; for (let i = 0, l = children.length; i < l; i++) { intersectObject(children[i], raycaster2, intersects2, true); } } } var Spherical = class { constructor(radius = 1, phi = 0, theta = 0) { this.radius = radius; this.phi = phi; this.theta = theta; return this; } set(radius, phi, theta) { this.radius = radius; this.phi = phi; this.theta = theta; return this; } copy(other) { this.radius = other.radius; this.phi = other.phi; this.theta = other.theta; return this; } // restrict phi to be between EPS and PI-EPS makeSafe() { const EPS = 1e-6; this.phi = Math.max(EPS, Math.min(Math.PI - EPS, this.phi)); return this; } setFromVector3(v) { return this.setFromCartesianCoords(v.x, v.y, v.z); } setFromCartesianCoords(x2, y, z) { this.radius = Math.sqrt(x2 * x2 + y * y + z * z); if (this.radius === 0) { this.theta = 0; this.phi = 0; } else { this.theta = Math.atan2(x2, z); this.phi = Math.acos(clamp(y / this.radius, -1, 1)); } return this; } clone() { return new this.constructor().copy(this); } }; var _vector$4 = new Vector2(); var _startP = new Vector3(); var _startEnd = new Vector3(); var _vector$3 = new Vector3(); var _vector$2 = new Vector3(); var _boneMatrix = new Matrix4(); var _matrixWorldInv = new Matrix4(); var _vector$1 = new Vector3(); var _color1 = new Color(); var _color2 = new Color(); var _v1 = new Vector3(); var _v2 = new Vector3(); var _v3 = new Vector3(); var _vector = new Vector3(); var _camera = new Camera(); var _box = new Box3(); var _axis = new Vector3(); var _tables = _generateTables(); function _generateTables() { const buffer = new ArrayBuffer(4); const floatView = new Float32Array(buffer); const uint32View = new Uint32Array(buffer); const baseTable = new Uint32Array(512); const shiftTable = new Uint32Array(512); for (let i = 0; i < 256; ++i) { const e = i - 127; if (e < -27) { baseTable[i] = 0; baseTable[i | 256] = 32768; shiftTable[i] = 24; shiftTable[i | 256] = 24; } else if (e < -14) { baseTable[i] = 1024 >> -e - 14; baseTable[i | 256] = 1024 >> -e - 14 | 32768; shiftTable[i] = -e - 1; shiftTable[i | 256] = -e - 1; } else if (e <= 15) { baseTable[i] = e + 15 << 10; baseTable[i | 256] = e + 15 << 10 | 32768; shiftTable[i] = 13; shiftTable[i | 256] = 13; } else if (e < 128) { baseTable[i] = 31744; baseTable[i | 256] = 64512; shiftTable[i] = 24; shiftTable[i | 256] = 24; } else { baseTable[i] = 31744; baseTable[i | 256] = 64512; shiftTable[i] = 13; shiftTable[i | 256] = 13; } } const mantissaTable = new Uint32Array(2048); const exponentTable = new Uint32Array(64); const offsetTable = new Uint32Array(64); for (let i = 1; i < 1024; ++i) { let m = i << 13; let e = 0; while ((m & 8388608) === 0) { m <<= 1; e -= 8388608; } m &= ~8388608; e += 947912704; mantissaTable[i] = m | e; } for (let i = 1024; i < 2048; ++i) { mantissaTable[i] = 939524096 + (i - 1024 << 13); } for (let i = 1; i < 31; ++i) { exponentTable[i] = i << 23; } exponentTable[31] = 1199570944; exponentTable[32] = 2147483648; for (let i = 33; i < 63; ++i) { exponentTable[i] = 2147483648 + (i - 32 << 23); } exponentTable[63] = 3347054592; for (let i = 1; i < 64; ++i) { if (i !== 32) { offsetTable[i] = 1024; } } return { floatView, uint32View, baseTable, shiftTable, mantissaTable, exponentTable, offsetTable }; } function toHalfFloat(val) { if (Math.abs(val) > 65504) console.warn("THREE.DataUtils.toHalfFloat(): Value out of range."); val = clamp(val, -65504, 65504); _tables.floatView[0] = val; const f = _tables.uint32View[0]; const e = f >> 23 & 511; return _tables.baseTable[e] + ((f & 8388607) >> _tables.shiftTable[e]); } function fromHalfFloat(val) { const m = val >> 10; _tables.uint32View[0] = _tables.mantissaTable[_tables.offsetTable[m] + (val & 1023)] + _tables.exponentTable[m]; return _tables.floatView[0]; } var DataUtils = Object.freeze({ __proto__: null, toHalfFloat, fromHalfFloat }); if (typeof __THREE_DEVTOOLS__ !== "undefined") { __THREE_DEVTOOLS__.dispatchEvent(new CustomEvent("register", { detail: { revision: REVISION } })); } if (typeof window !== "undefined") { if (window.__THREE__) { console.warn("WARNING: Multiple instances of Three.js being imported."); } else { window.__THREE__ = REVISION; } } // node_modules/@google/model-viewer/lib/constants.js var HAS_WEBXR_DEVICE_API = navigator.xr != null && self.XRSession != null && navigator.xr.isSessionSupported != null; var HAS_WEBXR_HIT_TEST_API = HAS_WEBXR_DEVICE_API && self.XRSession.prototype.requestHitTestSource != null; var HAS_RESIZE_OBSERVER = self.ResizeObserver != null; var HAS_INTERSECTION_OBSERVER = self.IntersectionObserver != null; var IS_WEBXR_AR_CANDIDATE = HAS_WEBXR_HIT_TEST_API; var IS_MOBILE = (() => { const userAgent = navigator.userAgent || navigator.vendor || self.opera; let check = false; if (/(android|bb\d+|meego).+mobile|avantgo|bada\/|blackberry|blazer|compal|elaine|fennec|hiptop|iemobile|ip(hone|od)|iris|kindle|lge |maemo|midp|mmp|mobile.+firefox|netfront|opera m(ob|in)i|palm( os)?|phone|p(ixi|re)\/|plucker|pocket|psp|series(4|6)0|symbian|treo|up\.(browser|link)|vodafone|wap|windows ce|xda|xiino/i.test(userAgent) || /1207|6310|6590|3gso|4thp|50[1-6]i|770s|802s|a wa|abac|ac(er|oo|s\-)|ai(ko|rn)|al(av|ca|co)|amoi|an(ex|ny|yw)|aptu|ar(ch|go)|as(te|us)|attw|au(di|\-m|r |s )|avan|be(ck|ll|nq)|bi(lb|rd)|bl(ac|az)|br(e|v)w|bumb|bw\-(n|u)|c55\/|capi|ccwa|cdm\-|cell|chtm|cldc|cmd\-|co(mp|nd)|craw|da(it|ll|ng)|dbte|dc\-s|devi|dica|dmob|do(c|p)o|ds(12|\-d)|el(49|ai)|em(l2|ul)|er(ic|k0)|esl8|ez([4-7]0|os|wa|ze)|fetc|fly(\-|_)|g1 u|g560|gene|gf\-5|g\-mo|go(\.w|od)|gr(ad|un)|haie|hcit|hd\-(m|p|t)|hei\-|hi(pt|ta)|hp( i|ip)|hs\-c|ht(c(\-| |_|a|g|p|s|t)|tp)|hu(aw|tc)|i\-(20|go|ma)|i230|iac( |\-|\/)|ibro|idea|ig01|ikom|im1k|inno|ipaq|iris|ja(t|v)a|jbro|jemu|jigs|kddi|keji|kgt( |\/)|klon|kpt |kwc\-|kyo(c|k)|le(no|xi)|lg( g|\/(k|l|u)|50|54|\-[a-w])|libw|lynx|m1\-w|m3ga|m50\/|ma(te|ui|xo)|mc(01|21|ca)|m\-cr|me(rc|ri)|mi(o8|oa|ts)|mmef|mo(01|02|bi|de|do|t(\-| |o|v)|zz)|mt(50|p1|v )|mwbp|mywa|n10[0-2]|n20[2-3]|n30(0|2)|n50(0|2|5)|n7(0(0|1)|10)|ne((c|m)\-|on|tf|wf|wg|wt)|nok(6|i)|nzph|o2im|op(ti|wv)|oran|owg1|p800|pan(a|d|t)|pdxg|pg(13|\-([1-8]|c))|phil|pire|pl(ay|uc)|pn\-2|po(ck|rt|se)|prox|psio|pt\-g|qa\-a|qc(07|12|21|32|60|\-[2-7]|i\-)|qtek|r380|r600|raks|rim9|ro(ve|zo)|s55\/|sa(ge|ma|mm|ms|ny|va)|sc(01|h\-|oo|p\-)|sdk\/|se(c(\-|0|1)|47|mc|nd|ri)|sgh\-|shar|sie(\-|m)|sk\-0|sl(45|id)|sm(al|ar|b3|it|t5)|so(ft|ny)|sp(01|h\-|v\-|v )|sy(01|mb)|t2(18|50)|t6(00|10|18)|ta(gt|lk)|tcl\-|tdg\-|tel(i|m)|tim\-|t\-mo|to(pl|sh)|ts(70|m\-|m3|m5)|tx\-9|up(\.b|g1|si)|utst|v400|v750|veri|vi(rg|te)|vk(40|5[0-3]|\-v)|vm40|voda|vulc|vx(52|53|60|61|70|80|81|83|85|98)|w3c(\-| )|webc|whit|wi(g |nc|nw)|wmlb|wonu|x700|yas\-|your|zeto|zte\-/i.test(userAgent.substr(0, 4))) { check = true; } return check; })(); var IS_CHROMEOS = /\bCrOS\b/.test(navigator.userAgent); var IS_ANDROID = /android/i.test(navigator.userAgent); var IS_IOS = /iPad|iPhone|iPod/.test(navigator.userAgent) && !self.MSStream || navigator.platform === "MacIntel" && navigator.maxTouchPoints > 1; var IS_SAFARI = /Safari\//.test(navigator.userAgent); var IS_FIREFOX = /firefox/i.test(navigator.userAgent); var IS_OCULUS = /OculusBrowser/.test(navigator.userAgent); var IS_IOS_CHROME = IS_IOS && /CriOS\//.test(navigator.userAgent); var IS_SCENEVIEWER_CANDIDATE = IS_ANDROID && !IS_FIREFOX && !IS_OCULUS; var IS_WKWEBVIEW = Boolean(window.webkit && window.webkit.messageHandlers); var IS_AR_QUICKLOOK_CANDIDATE = (() => { if (IS_IOS) { if (!IS_WKWEBVIEW) { const tempAnchor = document.createElement("a"); return Boolean(tempAnchor.relList && tempAnchor.relList.supports && tempAnchor.relList.supports("ar")); } else { return Boolean(/CriOS\/|EdgiOS\/|FxiOS\/|GSA\/|DuckDuckGo\//.test(navigator.userAgent)); } } else { return false; } })(); // node_modules/@google/model-viewer/lib/utilities.js var deserializeUrl = (url) => !!url && url !== "null" ? toFullUrl(url) : null; var assertIsArCandidate = () => { if (IS_WEBXR_AR_CANDIDATE) { return; } const missingApis = []; if (!HAS_WEBXR_DEVICE_API) { missingApis.push("WebXR Device API"); } if (!HAS_WEBXR_HIT_TEST_API) { missingApis.push("WebXR Hit Test API"); } throw new Error(`The following APIs are required for AR, but are missing in this browser: ${missingApis.join(", ")}`); }; var toFullUrl = (partialUrl) => { const url = new URL(partialUrl, window.location.toString()); return url.toString(); }; var throttle = (fn, ms) => { let timer = null; const throttled = (...args) => { if (timer != null) { return; } fn(...args); timer = self.setTimeout(() => timer = null, ms); }; throttled.flush = () => { if (timer != null) { self.clearTimeout(timer); timer = null; } }; return throttled; }; var debounce = (fn, ms) => { let timer = null; return (...args) => { if (timer != null) { self.clearTimeout(timer); } timer = self.setTimeout(() => { timer = null; fn(...args); }, ms); }; }; var clamp2 = (value, lowerLimit, upperLimit) => Math.max(lowerLimit, Math.min(upperLimit, value)); var CAPPED_DEVICE_PIXEL_RATIO = 1; var resolveDpr = (() => { const HAS_META_VIEWPORT_TAG = (() => { var _a12; if ((_a12 = document.documentElement.getAttribute("itemtype")) === null || _a12 === void 0 ? void 0 : _a12.includes("schema.org/SearchResultsPage")) { return true; } const metas = document.head != null ? Array.from(document.head.querySelectorAll("meta")) : []; for (const meta of metas) { if (meta.name === "viewport") { return true; } } return false; })(); if (!HAS_META_VIEWPORT_TAG) { console.warn('No detected; will cap pixel density at 1.'); } return () => HAS_META_VIEWPORT_TAG ? window.devicePixelRatio : CAPPED_DEVICE_PIXEL_RATIO; })(); var isDebugMode = (() => { const debugQueryParameterName = "model-viewer-debug-mode"; const debugQueryParameter = new RegExp(`[?&]${debugQueryParameterName}(&|$)`); return () => self.ModelViewerElement && self.ModelViewerElement.debugMode || self.location && self.location.search && self.location.search.match(debugQueryParameter); })(); var timePasses = (ms = 0) => new Promise((resolve) => setTimeout(resolve, ms)); var waitForEvent = (target2, eventName, predicate = null) => new Promise((resolve) => { function handler(event) { if (!predicate || predicate(event)) { resolve(event); target2.removeEventListener(eventName, handler); } } target2.addEventListener(eventName, handler); }); // node_modules/@google/model-viewer/lib/features/environment.js var __decorate = function(decorators, target2, key, desc) { var c = arguments.length, r = c < 3 ? target2 : desc === null ? desc = Object.getOwnPropertyDescriptor(target2, key) : desc, d; if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target2, key, desc); else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target2, key, r) : d(target2, key)) || r; return c > 3 && r && Object.defineProperty(target2, key, r), r; }; var BASE_OPACITY = 0.5; var DEFAULT_SHADOW_INTENSITY = 0; var DEFAULT_SHADOW_SOFTNESS = 1; var DEFAULT_EXPOSURE = 1; var $currentEnvironmentMap = Symbol("currentEnvironmentMap"); var $currentBackground = Symbol("currentBackground"); var $updateEnvironment = Symbol("updateEnvironment"); var $cancelEnvironmentUpdate = Symbol("cancelEnvironmentUpdate"); var EnvironmentMixin = (ModelViewerElement2) => { var _a12, _b11, _c6; class EnvironmentModelViewerElement extends ModelViewerElement2 { constructor() { super(...arguments); this.environmentImage = null; this.skyboxImage = null; this.shadowIntensity = DEFAULT_SHADOW_INTENSITY; this.shadowSoftness = DEFAULT_SHADOW_SOFTNESS; this.exposure = DEFAULT_EXPOSURE; this[_a12] = null; this[_b11] = null; this[_c6] = null; } updated(changedProperties) { super.updated(changedProperties); if (changedProperties.has("shadowIntensity")) { this[$scene].setShadowIntensity(this.shadowIntensity * BASE_OPACITY); this[$needsRender](); } if (changedProperties.has("shadowSoftness")) { this[$scene].setShadowSoftness(this.shadowSoftness); this[$needsRender](); } if (changedProperties.has("exposure")) { this[$scene].exposure = this.exposure; this[$needsRender](); } if ((changedProperties.has("environmentImage") || changedProperties.has("skyboxImage")) && this[$shouldAttemptPreload]()) { this[$updateEnvironment](); } } hasBakedShadow() { return this[$scene].bakedShadows.size > 0; } async [(_a12 = $currentEnvironmentMap, _b11 = $currentBackground, _c6 = $cancelEnvironmentUpdate, $updateEnvironment)]() { const { skyboxImage, environmentImage } = this; if (this[$cancelEnvironmentUpdate] != null) { this[$cancelEnvironmentUpdate](); this[$cancelEnvironmentUpdate] = null; } const { textureUtils } = this[$renderer]; if (textureUtils == null) { return; } const updateEnvProgress = this[$progressTracker].beginActivity(); try { const { environmentMap, skybox } = await textureUtils.generateEnvironmentMapAndSkybox(deserializeUrl(skyboxImage), environmentImage, (progress) => updateEnvProgress(clamp2(progress, 0, 1))); if (this[$currentEnvironmentMap] !== environmentMap) { this[$currentEnvironmentMap] = environmentMap; this.dispatchEvent(new CustomEvent("environment-change")); } if (skybox != null) { this[$currentBackground] = skybox.name === environmentMap.name ? environmentMap : skybox; } else { this[$currentBackground] = null; } this[$scene].setEnvironmentAndSkybox(this[$currentEnvironmentMap], this[$currentBackground]); this[$scene].dispatchEvent({ type: "envmap-update" }); } catch (errorOrPromise) { if (errorOrPromise instanceof Error) { this[$scene].setEnvironmentAndSkybox(null, null); throw errorOrPromise; } } finally { updateEnvProgress(1); } } } __decorate([ property({ type: String, attribute: "environment-image" }) ], EnvironmentModelViewerElement.prototype, "environmentImage", void 0); __decorate([ property({ type: String, attribute: "skybox-image" }) ], EnvironmentModelViewerElement.prototype, "skyboxImage", void 0); __decorate([ property({ type: Number, attribute: "shadow-intensity" }) ], EnvironmentModelViewerElement.prototype, "shadowIntensity", void 0); __decorate([ property({ type: Number, attribute: "shadow-softness" }) ], EnvironmentModelViewerElement.prototype, "shadowSoftness", void 0); __decorate([ property({ type: Number }) ], EnvironmentModelViewerElement.prototype, "exposure", void 0); return EnvironmentModelViewerElement; }; // node_modules/@google/model-viewer/lib/assets/close-material-svg.js var close_material_svg_default = html` `; // node_modules/@google/model-viewer/lib/assets/controls-svg.js var controls_svg_default = html` `; // node_modules/@google/model-viewer/lib/assets/view-in-ar-material-svg.js var view_in_ar_material_svg_default = html` `; // node_modules/@google/model-viewer/lib/template.js var templateResult = html`
`; var makeTemplate = (shadowRoot) => { render(templateResult, shadowRoot); }; // node_modules/three/examples/jsm/loaders/DRACOLoader.js var _taskCache = /* @__PURE__ */ new WeakMap(); var DRACOLoader = class extends Loader { constructor(manager) { super(manager); this.decoderPath = ""; this.decoderConfig = {}; this.decoderBinary = null; this.decoderPending = null; this.workerLimit = 4; this.workerPool = []; this.workerNextTaskID = 1; this.workerSourceURL = ""; this.defaultAttributeIDs = { position: "POSITION", normal: "NORMAL", color: "COLOR", uv: "TEX_COORD" }; this.defaultAttributeTypes = { position: "Float32Array", normal: "Float32Array", color: "Float32Array", uv: "Float32Array" }; } setDecoderPath(path) { this.decoderPath = path; return this; } setDecoderConfig(config) { this.decoderConfig = config; return this; } setWorkerLimit(workerLimit) { this.workerLimit = workerLimit; return this; } load(url, onLoad, onProgress, onError) { const loader = new FileLoader(this.manager); loader.setPath(this.path); loader.setResponseType("arraybuffer"); loader.setRequestHeader(this.requestHeader); loader.setWithCredentials(this.withCredentials); loader.load(url, (buffer) => { this.decodeDracoFile(buffer, onLoad).catch(onError); }, onProgress, onError); } decodeDracoFile(buffer, callback, attributeIDs, attributeTypes) { const taskConfig = { attributeIDs: attributeIDs || this.defaultAttributeIDs, attributeTypes: attributeTypes || this.defaultAttributeTypes, useUniqueIDs: !!attributeIDs }; return this.decodeGeometry(buffer, taskConfig).then(callback); } decodeGeometry(buffer, taskConfig) { const taskKey = JSON.stringify(taskConfig); if (_taskCache.has(buffer)) { const cachedTask = _taskCache.get(buffer); if (cachedTask.key === taskKey) { return cachedTask.promise; } else if (buffer.byteLength === 0) { throw new Error( "THREE.DRACOLoader: Unable to re-decode a buffer with different settings. Buffer has already been transferred." ); } } let worker; const taskID = this.workerNextTaskID++; const taskCost = buffer.byteLength; const geometryPending = this._getWorker(taskID, taskCost).then((_worker) => { worker = _worker; return new Promise((resolve, reject) => { worker._callbacks[taskID] = { resolve, reject }; worker.postMessage({ type: "decode", id: taskID, taskConfig, buffer }, [buffer]); }); }).then((message) => this._createGeometry(message.geometry)); geometryPending.catch(() => true).then(() => { if (worker && taskID) { this._releaseTask(worker, taskID); } }); _taskCache.set(buffer, { key: taskKey, promise: geometryPending }); return geometryPending; } _createGeometry(geometryData) { const geometry = new BufferGeometry(); if (geometryData.index) { geometry.setIndex(new BufferAttribute(geometryData.index.array, 1)); } for (let i = 0; i < geometryData.attributes.length; i++) { const attribute = geometryData.attributes[i]; const name = attribute.name; const array = attribute.array; const itemSize = attribute.itemSize; geometry.setAttribute(name, new BufferAttribute(array, itemSize)); } return geometry; } _loadLibrary(url, responseType) { const loader = new FileLoader(this.manager); loader.setPath(this.decoderPath); loader.setResponseType(responseType); loader.setWithCredentials(this.withCredentials); return new Promise((resolve, reject) => { loader.load(url, resolve, void 0, reject); }); } preload() { this._initDecoder(); return this; } _initDecoder() { if (this.decoderPending) return this.decoderPending; const useJS = typeof WebAssembly !== "object" || this.decoderConfig.type === "js"; const librariesPending = []; if (useJS) { librariesPending.push(this._loadLibrary("draco_decoder.js", "text")); } else { librariesPending.push(this._loadLibrary("draco_wasm_wrapper.js", "text")); librariesPending.push(this._loadLibrary("draco_decoder.wasm", "arraybuffer")); } this.decoderPending = Promise.all(librariesPending).then((libraries) => { const jsContent = libraries[0]; if (!useJS) { this.decoderConfig.wasmBinary = libraries[1]; } const fn = DRACOWorker.toString(); const body = [ "/* draco decoder */", jsContent, "", "/* worker */", fn.substring(fn.indexOf("{") + 1, fn.lastIndexOf("}")) ].join("\n"); this.workerSourceURL = URL.createObjectURL(new Blob([body])); }); return this.decoderPending; } _getWorker(taskID, taskCost) { return this._initDecoder().then(() => { if (this.workerPool.length < this.workerLimit) { const worker2 = new Worker(this.workerSourceURL); worker2._callbacks = {}; worker2._taskCosts = {}; worker2._taskLoad = 0; worker2.postMessage({ type: "init", decoderConfig: this.decoderConfig }); worker2.onmessage = function(e) { const message = e.data; switch (message.type) { case "decode": worker2._callbacks[message.id].resolve(message); break; case "error": worker2._callbacks[message.id].reject(message); break; default: console.error('THREE.DRACOLoader: Unexpected message, "' + message.type + '"'); } }; this.workerPool.push(worker2); } else { this.workerPool.sort(function(a, b) { return a._taskLoad > b._taskLoad ? -1 : 1; }); } const worker = this.workerPool[this.workerPool.length - 1]; worker._taskCosts[taskID] = taskCost; worker._taskLoad += taskCost; return worker; }); } _releaseTask(worker, taskID) { worker._taskLoad -= worker._taskCosts[taskID]; delete worker._callbacks[taskID]; delete worker._taskCosts[taskID]; } debug() { console.log("Task load: ", this.workerPool.map((worker) => worker._taskLoad)); } dispose() { for (let i = 0; i < this.workerPool.length; ++i) { this.workerPool[i].terminate(); } this.workerPool.length = 0; return this; } }; function DRACOWorker() { let decoderConfig; let decoderPending; onmessage = function(e) { const message = e.data; switch (message.type) { case "init": decoderConfig = message.decoderConfig; decoderPending = new Promise(function(resolve) { decoderConfig.onModuleLoaded = function(draco) { resolve({ draco }); }; DracoDecoderModule(decoderConfig); }); break; case "decode": const buffer = message.buffer; const taskConfig = message.taskConfig; decoderPending.then((module) => { const draco = module.draco; const decoder = new draco.Decoder(); const decoderBuffer = new draco.DecoderBuffer(); decoderBuffer.Init(new Int8Array(buffer), buffer.byteLength); try { const geometry = decodeGeometry(draco, decoder, decoderBuffer, taskConfig); const buffers = geometry.attributes.map((attr) => attr.array.buffer); if (geometry.index) buffers.push(geometry.index.array.buffer); self.postMessage({ type: "decode", id: message.id, geometry }, buffers); } catch (error) { console.error(error); self.postMessage({ type: "error", id: message.id, error: error.message }); } finally { draco.destroy(decoderBuffer); draco.destroy(decoder); } }); break; } }; function decodeGeometry(draco, decoder, decoderBuffer, taskConfig) { const attributeIDs = taskConfig.attributeIDs; const attributeTypes = taskConfig.attributeTypes; let dracoGeometry; let decodingStatus; const geometryType = decoder.GetEncodedGeometryType(decoderBuffer); if (geometryType === draco.TRIANGULAR_MESH) { dracoGeometry = new draco.Mesh(); decodingStatus = decoder.DecodeBufferToMesh(decoderBuffer, dracoGeometry); } else if (geometryType === draco.POINT_CLOUD) { dracoGeometry = new draco.PointCloud(); decodingStatus = decoder.DecodeBufferToPointCloud(decoderBuffer, dracoGeometry); } else { throw new Error("THREE.DRACOLoader: Unexpected geometry type."); } if (!decodingStatus.ok() || dracoGeometry.ptr === 0) { throw new Error("THREE.DRACOLoader: Decoding failed: " + decodingStatus.error_msg()); } const geometry = { index: null, attributes: [] }; for (const attributeName in attributeIDs) { const attributeType = self[attributeTypes[attributeName]]; let attribute; let attributeID; if (taskConfig.useUniqueIDs) { attributeID = attributeIDs[attributeName]; attribute = decoder.GetAttributeByUniqueId(dracoGeometry, attributeID); } else { attributeID = decoder.GetAttributeId(dracoGeometry, draco[attributeIDs[attributeName]]); if (attributeID === -1) continue; attribute = decoder.GetAttribute(dracoGeometry, attributeID); } geometry.attributes.push(decodeAttribute(draco, decoder, dracoGeometry, attributeName, attributeType, attribute)); } if (geometryType === draco.TRIANGULAR_MESH) { geometry.index = decodeIndex(draco, decoder, dracoGeometry); } draco.destroy(dracoGeometry); return geometry; } function decodeIndex(draco, decoder, dracoGeometry) { const numFaces = dracoGeometry.num_faces(); const numIndices = numFaces * 3; const byteLength = numIndices * 4; const ptr = draco._malloc(byteLength); decoder.GetTrianglesUInt32Array(dracoGeometry, byteLength, ptr); const index = new Uint32Array(draco.HEAPF32.buffer, ptr, numIndices).slice(); draco._free(ptr); return { array: index, itemSize: 1 }; } function decodeAttribute(draco, decoder, dracoGeometry, attributeName, attributeType, attribute) { const numComponents = attribute.num_components(); const numPoints = dracoGeometry.num_points(); const numValues = numPoints * numComponents; const byteLength = numValues * attributeType.BYTES_PER_ELEMENT; const dataType = getDracoDataType(draco, attributeType); const ptr = draco._malloc(byteLength); decoder.GetAttributeDataArrayForAllPoints(dracoGeometry, attribute, dataType, byteLength, ptr); const array = new attributeType(draco.HEAPF32.buffer, ptr, numValues).slice(); draco._free(ptr); return { name: attributeName, array, itemSize: numComponents }; } function getDracoDataType(draco, attributeType) { switch (attributeType) { case Float32Array: return draco.DT_FLOAT32; case Int8Array: return draco.DT_INT8; case Int16Array: return draco.DT_INT16; case Int32Array: return draco.DT_INT32; case Uint8Array: return draco.DT_UINT8; case Uint16Array: return draco.DT_UINT16; case Uint32Array: return draco.DT_UINT32; } } } // node_modules/three/examples/jsm/loaders/GLTFLoader.js var GLTFLoader = class extends Loader { constructor(manager) { super(manager); this.dracoLoader = null; this.ktx2Loader = null; this.meshoptDecoder = null; this.pluginCallbacks = []; this.register(function(parser) { return new GLTFMaterialsClearcoatExtension(parser); }); this.register(function(parser) { return new GLTFTextureBasisUExtension(parser); }); this.register(function(parser) { return new GLTFTextureWebPExtension(parser); }); this.register(function(parser) { return new GLTFMaterialsSheenExtension(parser); }); this.register(function(parser) { return new GLTFMaterialsTransmissionExtension(parser); }); this.register(function(parser) { return new GLTFMaterialsVolumeExtension(parser); }); this.register(function(parser) { return new GLTFMaterialsIorExtension(parser); }); this.register(function(parser) { return new GLTFMaterialsEmissiveStrengthExtension(parser); }); this.register(function(parser) { return new GLTFMaterialsSpecularExtension(parser); }); this.register(function(parser) { return new GLTFMaterialsIridescenceExtension(parser); }); this.register(function(parser) { return new GLTFLightsExtension(parser); }); this.register(function(parser) { return new GLTFMeshoptCompression(parser); }); this.register(function(parser) { return new GLTFMeshGpuInstancing(parser); }); } load(url, onLoad, onProgress, onError) { const scope = this; let resourcePath; if (this.resourcePath !== "") { resourcePath = this.resourcePath; } else if (this.path !== "") { resourcePath = this.path; } else { resourcePath = LoaderUtils.extractUrlBase(url); } this.manager.itemStart(url); const _onError = function(e) { if (onError) { onError(e); } else { console.error(e); } scope.manager.itemError(url); scope.manager.itemEnd(url); }; const loader = new FileLoader(this.manager); loader.setPath(this.path); loader.setResponseType("arraybuffer"); loader.setRequestHeader(this.requestHeader); loader.setWithCredentials(this.withCredentials); loader.load(url, function(data) { try { scope.parse(data, resourcePath, function(gltf) { onLoad(gltf); scope.manager.itemEnd(url); }, _onError); } catch (e) { _onError(e); } }, onProgress, _onError); } setDRACOLoader(dracoLoader2) { this.dracoLoader = dracoLoader2; return this; } setDDSLoader() { throw new Error( 'THREE.GLTFLoader: "MSFT_texture_dds" no longer supported. Please update to "KHR_texture_basisu".' ); } setKTX2Loader(ktx2Loader2) { this.ktx2Loader = ktx2Loader2; return this; } setMeshoptDecoder(meshoptDecoder2) { this.meshoptDecoder = meshoptDecoder2; return this; } register(callback) { if (this.pluginCallbacks.indexOf(callback) === -1) { this.pluginCallbacks.push(callback); } return this; } unregister(callback) { if (this.pluginCallbacks.indexOf(callback) !== -1) { this.pluginCallbacks.splice(this.pluginCallbacks.indexOf(callback), 1); } return this; } parse(data, path, onLoad, onError) { let json; const extensions = {}; const plugins = {}; if (typeof data === "string") { json = JSON.parse(data); } else if (data instanceof ArrayBuffer) { const magic = LoaderUtils.decodeText(new Uint8Array(data, 0, 4)); if (magic === BINARY_EXTENSION_HEADER_MAGIC) { try { extensions[EXTENSIONS.KHR_BINARY_GLTF] = new GLTFBinaryExtension(data); } catch (error) { if (onError) onError(error); return; } json = JSON.parse(extensions[EXTENSIONS.KHR_BINARY_GLTF].content); } else { json = JSON.parse(LoaderUtils.decodeText(new Uint8Array(data))); } } else { json = data; } if (json.asset === void 0 || json.asset.version[0] < 2) { if (onError) onError(new Error("THREE.GLTFLoader: Unsupported asset. glTF versions >=2.0 are supported.")); return; } const parser = new GLTFParser(json, { path: path || this.resourcePath || "", crossOrigin: this.crossOrigin, requestHeader: this.requestHeader, manager: this.manager, ktx2Loader: this.ktx2Loader, meshoptDecoder: this.meshoptDecoder }); parser.fileLoader.setRequestHeader(this.requestHeader); for (let i = 0; i < this.pluginCallbacks.length; i++) { const plugin = this.pluginCallbacks[i](parser); plugins[plugin.name] = plugin; extensions[plugin.name] = true; } if (json.extensionsUsed) { for (let i = 0; i < json.extensionsUsed.length; ++i) { const extensionName = json.extensionsUsed[i]; const extensionsRequired = json.extensionsRequired || []; switch (extensionName) { case EXTENSIONS.KHR_MATERIALS_UNLIT: extensions[extensionName] = new GLTFMaterialsUnlitExtension(); break; case EXTENSIONS.KHR_MATERIALS_PBR_SPECULAR_GLOSSINESS: extensions[extensionName] = new GLTFMaterialsPbrSpecularGlossinessExtension(); break; case EXTENSIONS.KHR_DRACO_MESH_COMPRESSION: extensions[extensionName] = new GLTFDracoMeshCompressionExtension(json, this.dracoLoader); break; case EXTENSIONS.KHR_TEXTURE_TRANSFORM: extensions[extensionName] = new GLTFTextureTransformExtension(); break; case EXTENSIONS.KHR_MESH_QUANTIZATION: extensions[extensionName] = new GLTFMeshQuantizationExtension(); break; default: if (extensionsRequired.indexOf(extensionName) >= 0 && plugins[extensionName] === void 0) { console.warn('THREE.GLTFLoader: Unknown extension "' + extensionName + '".'); } } } } parser.setExtensions(extensions); parser.setPlugins(plugins); parser.parse(onLoad, onError); } parseAsync(data, path) { const scope = this; return new Promise(function(resolve, reject) { scope.parse(data, path, resolve, reject); }); } }; function GLTFRegistry() { let objects = {}; return { get: function(key) { return objects[key]; }, add: function(key, object) { objects[key] = object; }, remove: function(key) { delete objects[key]; }, removeAll: function() { objects = {}; } }; } var EXTENSIONS = { KHR_BINARY_GLTF: "KHR_binary_glTF", KHR_DRACO_MESH_COMPRESSION: "KHR_draco_mesh_compression", KHR_LIGHTS_PUNCTUAL: "KHR_lights_punctual", KHR_MATERIALS_CLEARCOAT: "KHR_materials_clearcoat", KHR_MATERIALS_IOR: "KHR_materials_ior", KHR_MATERIALS_PBR_SPECULAR_GLOSSINESS: "KHR_materials_pbrSpecularGlossiness", KHR_MATERIALS_SHEEN: "KHR_materials_sheen", KHR_MATERIALS_SPECULAR: "KHR_materials_specular", KHR_MATERIALS_TRANSMISSION: "KHR_materials_transmission", KHR_MATERIALS_IRIDESCENCE: "KHR_materials_iridescence", KHR_MATERIALS_UNLIT: "KHR_materials_unlit", KHR_MATERIALS_VOLUME: "KHR_materials_volume", KHR_TEXTURE_BASISU: "KHR_texture_basisu", KHR_TEXTURE_TRANSFORM: "KHR_texture_transform", KHR_MESH_QUANTIZATION: "KHR_mesh_quantization", KHR_MATERIALS_EMISSIVE_STRENGTH: "KHR_materials_emissive_strength", EXT_TEXTURE_WEBP: "EXT_texture_webp", EXT_MESHOPT_COMPRESSION: "EXT_meshopt_compression", EXT_MESH_GPU_INSTANCING: "EXT_mesh_gpu_instancing" }; var GLTFLightsExtension = class { constructor(parser) { this.parser = parser; this.name = EXTENSIONS.KHR_LIGHTS_PUNCTUAL; this.cache = { refs: {}, uses: {} }; } _markDefs() { const parser = this.parser; const nodeDefs = this.parser.json.nodes || []; for (let nodeIndex = 0, nodeLength = nodeDefs.length; nodeIndex < nodeLength; nodeIndex++) { const nodeDef = nodeDefs[nodeIndex]; if (nodeDef.extensions && nodeDef.extensions[this.name] && nodeDef.extensions[this.name].light !== void 0) { parser._addNodeRef(this.cache, nodeDef.extensions[this.name].light); } } } _loadLight(lightIndex) { const parser = this.parser; const cacheKey = "light:" + lightIndex; let dependency = parser.cache.get(cacheKey); if (dependency) return dependency; const json = parser.json; const extensions = json.extensions && json.extensions[this.name] || {}; const lightDefs = extensions.lights || []; const lightDef = lightDefs[lightIndex]; let lightNode; const color = new Color(16777215); if (lightDef.color !== void 0) color.fromArray(lightDef.color); const range = lightDef.range !== void 0 ? lightDef.range : 0; switch (lightDef.type) { case "directional": lightNode = new DirectionalLight(color); lightNode.target.position.set(0, 0, -1); lightNode.add(lightNode.target); break; case "point": lightNode = new PointLight(color); lightNode.distance = range; break; case "spot": lightNode = new SpotLight(color); lightNode.distance = range; lightDef.spot = lightDef.spot || {}; lightDef.spot.innerConeAngle = lightDef.spot.innerConeAngle !== void 0 ? lightDef.spot.innerConeAngle : 0; lightDef.spot.outerConeAngle = lightDef.spot.outerConeAngle !== void 0 ? lightDef.spot.outerConeAngle : Math.PI / 4; lightNode.angle = lightDef.spot.outerConeAngle; lightNode.penumbra = 1 - lightDef.spot.innerConeAngle / lightDef.spot.outerConeAngle; lightNode.target.position.set(0, 0, -1); lightNode.add(lightNode.target); break; default: throw new Error("THREE.GLTFLoader: Unexpected light type: " + lightDef.type); } lightNode.position.set(0, 0, 0); lightNode.decay = 2; if (lightDef.intensity !== void 0) lightNode.intensity = lightDef.intensity; lightNode.name = parser.createUniqueName(lightDef.name || "light_" + lightIndex); dependency = Promise.resolve(lightNode); parser.cache.add(cacheKey, dependency); return dependency; } createNodeAttachment(nodeIndex) { const self2 = this; const parser = this.parser; const json = parser.json; const nodeDef = json.nodes[nodeIndex]; const lightDef = nodeDef.extensions && nodeDef.extensions[this.name] || {}; const lightIndex = lightDef.light; if (lightIndex === void 0) return null; return this._loadLight(lightIndex).then(function(light) { return parser._getNodeRef(self2.cache, lightIndex, light); }); } }; var GLTFMaterialsUnlitExtension = class { constructor() { this.name = EXTENSIONS.KHR_MATERIALS_UNLIT; } getMaterialType() { return MeshBasicMaterial; } extendParams(materialParams, materialDef, parser) { const pending = []; materialParams.color = new Color(1, 1, 1); materialParams.opacity = 1; const metallicRoughness = materialDef.pbrMetallicRoughness; if (metallicRoughness) { if (Array.isArray(metallicRoughness.baseColorFactor)) { const array = metallicRoughness.baseColorFactor; materialParams.color.fromArray(array); materialParams.opacity = array[3]; } if (metallicRoughness.baseColorTexture !== void 0) { pending.push(parser.assignTexture(materialParams, "map", metallicRoughness.baseColorTexture, sRGBEncoding)); } } return Promise.all(pending); } }; var GLTFMaterialsEmissiveStrengthExtension = class { constructor(parser) { this.parser = parser; this.name = EXTENSIONS.KHR_MATERIALS_EMISSIVE_STRENGTH; } extendMaterialParams(materialIndex, materialParams) { const parser = this.parser; const materialDef = parser.json.materials[materialIndex]; if (!materialDef.extensions || !materialDef.extensions[this.name]) { return Promise.resolve(); } const emissiveStrength = materialDef.extensions[this.name].emissiveStrength; if (emissiveStrength !== void 0) { materialParams.emissiveIntensity = emissiveStrength; } return Promise.resolve(); } }; var GLTFMaterialsClearcoatExtension = class { constructor(parser) { this.parser = parser; this.name = EXTENSIONS.KHR_MATERIALS_CLEARCOAT; } getMaterialType(materialIndex) { const parser = this.parser; const materialDef = parser.json.materials[materialIndex]; if (!materialDef.extensions || !materialDef.extensions[this.name]) return null; return MeshPhysicalMaterial; } extendMaterialParams(materialIndex, materialParams) { const parser = this.parser; const materialDef = parser.json.materials[materialIndex]; if (!materialDef.extensions || !materialDef.extensions[this.name]) { return Promise.resolve(); } const pending = []; const extension = materialDef.extensions[this.name]; if (extension.clearcoatFactor !== void 0) { materialParams.clearcoat = extension.clearcoatFactor; } if (extension.clearcoatTexture !== void 0) { pending.push(parser.assignTexture(materialParams, "clearcoatMap", extension.clearcoatTexture)); } if (extension.clearcoatRoughnessFactor !== void 0) { materialParams.clearcoatRoughness = extension.clearcoatRoughnessFactor; } if (extension.clearcoatRoughnessTexture !== void 0) { pending.push(parser.assignTexture(materialParams, "clearcoatRoughnessMap", extension.clearcoatRoughnessTexture)); } if (extension.clearcoatNormalTexture !== void 0) { pending.push(parser.assignTexture(materialParams, "clearcoatNormalMap", extension.clearcoatNormalTexture)); if (extension.clearcoatNormalTexture.scale !== void 0) { const scale = extension.clearcoatNormalTexture.scale; materialParams.clearcoatNormalScale = new Vector2(scale, scale); } } return Promise.all(pending); } }; var GLTFMaterialsIridescenceExtension = class { constructor(parser) { this.parser = parser; this.name = EXTENSIONS.KHR_MATERIALS_IRIDESCENCE; } getMaterialType(materialIndex) { const parser = this.parser; const materialDef = parser.json.materials[materialIndex]; if (!materialDef.extensions || !materialDef.extensions[this.name]) return null; return MeshPhysicalMaterial; } extendMaterialParams(materialIndex, materialParams) { const parser = this.parser; const materialDef = parser.json.materials[materialIndex]; if (!materialDef.extensions || !materialDef.extensions[this.name]) { return Promise.resolve(); } const pending = []; const extension = materialDef.extensions[this.name]; if (extension.iridescenceFactor !== void 0) { materialParams.iridescence = extension.iridescenceFactor; } if (extension.iridescenceTexture !== void 0) { pending.push(parser.assignTexture(materialParams, "iridescenceMap", extension.iridescenceTexture)); } if (extension.iridescenceIor !== void 0) { materialParams.iridescenceIOR = extension.iridescenceIor; } if (materialParams.iridescenceThicknessRange === void 0) { materialParams.iridescenceThicknessRange = [100, 400]; } if (extension.iridescenceThicknessMinimum !== void 0) { materialParams.iridescenceThicknessRange[0] = extension.iridescenceThicknessMinimum; } if (extension.iridescenceThicknessMaximum !== void 0) { materialParams.iridescenceThicknessRange[1] = extension.iridescenceThicknessMaximum; } if (extension.iridescenceThicknessTexture !== void 0) { pending.push(parser.assignTexture(materialParams, "iridescenceThicknessMap", extension.iridescenceThicknessTexture)); } return Promise.all(pending); } }; var GLTFMaterialsSheenExtension = class { constructor(parser) { this.parser = parser; this.name = EXTENSIONS.KHR_MATERIALS_SHEEN; } getMaterialType(materialIndex) { const parser = this.parser; const materialDef = parser.json.materials[materialIndex]; if (!materialDef.extensions || !materialDef.extensions[this.name]) return null; return MeshPhysicalMaterial; } extendMaterialParams(materialIndex, materialParams) { const parser = this.parser; const materialDef = parser.json.materials[materialIndex]; if (!materialDef.extensions || !materialDef.extensions[this.name]) { return Promise.resolve(); } const pending = []; materialParams.sheenColor = new Color(0, 0, 0); materialParams.sheenRoughness = 0; materialParams.sheen = 1; const extension = materialDef.extensions[this.name]; if (extension.sheenColorFactor !== void 0) { materialParams.sheenColor.fromArray(extension.sheenColorFactor); } if (extension.sheenRoughnessFactor !== void 0) { materialParams.sheenRoughness = extension.sheenRoughnessFactor; } if (extension.sheenColorTexture !== void 0) { pending.push(parser.assignTexture(materialParams, "sheenColorMap", extension.sheenColorTexture, sRGBEncoding)); } if (extension.sheenRoughnessTexture !== void 0) { pending.push(parser.assignTexture(materialParams, "sheenRoughnessMap", extension.sheenRoughnessTexture)); } return Promise.all(pending); } }; var GLTFMaterialsTransmissionExtension = class { constructor(parser) { this.parser = parser; this.name = EXTENSIONS.KHR_MATERIALS_TRANSMISSION; } getMaterialType(materialIndex) { const parser = this.parser; const materialDef = parser.json.materials[materialIndex]; if (!materialDef.extensions || !materialDef.extensions[this.name]) return null; return MeshPhysicalMaterial; } extendMaterialParams(materialIndex, materialParams) { const parser = this.parser; const materialDef = parser.json.materials[materialIndex]; if (!materialDef.extensions || !materialDef.extensions[this.name]) { return Promise.resolve(); } const pending = []; const extension = materialDef.extensions[this.name]; if (extension.transmissionFactor !== void 0) { materialParams.transmission = extension.transmissionFactor; } if (extension.transmissionTexture !== void 0) { pending.push(parser.assignTexture(materialParams, "transmissionMap", extension.transmissionTexture)); } return Promise.all(pending); } }; var GLTFMaterialsVolumeExtension = class { constructor(parser) { this.parser = parser; this.name = EXTENSIONS.KHR_MATERIALS_VOLUME; } getMaterialType(materialIndex) { const parser = this.parser; const materialDef = parser.json.materials[materialIndex]; if (!materialDef.extensions || !materialDef.extensions[this.name]) return null; return MeshPhysicalMaterial; } extendMaterialParams(materialIndex, materialParams) { const parser = this.parser; const materialDef = parser.json.materials[materialIndex]; if (!materialDef.extensions || !materialDef.extensions[this.name]) { return Promise.resolve(); } const pending = []; const extension = materialDef.extensions[this.name]; materialParams.thickness = extension.thicknessFactor !== void 0 ? extension.thicknessFactor : 0; if (extension.thicknessTexture !== void 0) { pending.push(parser.assignTexture(materialParams, "thicknessMap", extension.thicknessTexture)); } materialParams.attenuationDistance = extension.attenuationDistance || Infinity; const colorArray = extension.attenuationColor || [1, 1, 1]; materialParams.attenuationColor = new Color(colorArray[0], colorArray[1], colorArray[2]); return Promise.all(pending); } }; var GLTFMaterialsIorExtension = class { constructor(parser) { this.parser = parser; this.name = EXTENSIONS.KHR_MATERIALS_IOR; } getMaterialType(materialIndex) { const parser = this.parser; const materialDef = parser.json.materials[materialIndex]; if (!materialDef.extensions || !materialDef.extensions[this.name]) return null; return MeshPhysicalMaterial; } extendMaterialParams(materialIndex, materialParams) { const parser = this.parser; const materialDef = parser.json.materials[materialIndex]; if (!materialDef.extensions || !materialDef.extensions[this.name]) { return Promise.resolve(); } const extension = materialDef.extensions[this.name]; materialParams.ior = extension.ior !== void 0 ? extension.ior : 1.5; return Promise.resolve(); } }; var GLTFMaterialsSpecularExtension = class { constructor(parser) { this.parser = parser; this.name = EXTENSIONS.KHR_MATERIALS_SPECULAR; } getMaterialType(materialIndex) { const parser = this.parser; const materialDef = parser.json.materials[materialIndex]; if (!materialDef.extensions || !materialDef.extensions[this.name]) return null; return MeshPhysicalMaterial; } extendMaterialParams(materialIndex, materialParams) { const parser = this.parser; const materialDef = parser.json.materials[materialIndex]; if (!materialDef.extensions || !materialDef.extensions[this.name]) { return Promise.resolve(); } const pending = []; const extension = materialDef.extensions[this.name]; materialParams.specularIntensity = extension.specularFactor !== void 0 ? extension.specularFactor : 1; if (extension.specularTexture !== void 0) { pending.push(parser.assignTexture(materialParams, "specularIntensityMap", extension.specularTexture)); } const colorArray = extension.specularColorFactor || [1, 1, 1]; materialParams.specularColor = new Color(colorArray[0], colorArray[1], colorArray[2]); if (extension.specularColorTexture !== void 0) { pending.push(parser.assignTexture(materialParams, "specularColorMap", extension.specularColorTexture, sRGBEncoding)); } return Promise.all(pending); } }; var GLTFTextureBasisUExtension = class { constructor(parser) { this.parser = parser; this.name = EXTENSIONS.KHR_TEXTURE_BASISU; } loadTexture(textureIndex) { const parser = this.parser; const json = parser.json; const textureDef = json.textures[textureIndex]; if (!textureDef.extensions || !textureDef.extensions[this.name]) { return null; } const extension = textureDef.extensions[this.name]; const loader = parser.options.ktx2Loader; if (!loader) { if (json.extensionsRequired && json.extensionsRequired.indexOf(this.name) >= 0) { throw new Error("THREE.GLTFLoader: setKTX2Loader must be called before loading KTX2 textures"); } else { return null; } } return parser.loadTextureImage(textureIndex, extension.source, loader); } }; var GLTFTextureWebPExtension = class { constructor(parser) { this.parser = parser; this.name = EXTENSIONS.EXT_TEXTURE_WEBP; this.isSupported = null; } loadTexture(textureIndex) { const name = this.name; const parser = this.parser; const json = parser.json; const textureDef = json.textures[textureIndex]; if (!textureDef.extensions || !textureDef.extensions[name]) { return null; } const extension = textureDef.extensions[name]; const source = json.images[extension.source]; let loader = parser.textureLoader; if (source.uri) { const handler = parser.options.manager.getHandler(source.uri); if (handler !== null) loader = handler; } return this.detectSupport().then(function(isSupported) { if (isSupported) return parser.loadTextureImage(textureIndex, extension.source, loader); if (json.extensionsRequired && json.extensionsRequired.indexOf(name) >= 0) { throw new Error("THREE.GLTFLoader: WebP required by asset but unsupported."); } return parser.loadTexture(textureIndex); }); } detectSupport() { if (!this.isSupported) { this.isSupported = new Promise(function(resolve) { const image = new Image(); image.src = "data:image/webp;base64,UklGRiIAAABXRUJQVlA4IBYAAAAwAQCdASoBAAEADsD+JaQAA3AAAAAA"; image.onload = image.onerror = function() { resolve(image.height === 1); }; }); } return this.isSupported; } }; var GLTFMeshoptCompression = class { constructor(parser) { this.name = EXTENSIONS.EXT_MESHOPT_COMPRESSION; this.parser = parser; } loadBufferView(index) { const json = this.parser.json; const bufferView = json.bufferViews[index]; if (bufferView.extensions && bufferView.extensions[this.name]) { const extensionDef = bufferView.extensions[this.name]; const buffer = this.parser.getDependency("buffer", extensionDef.buffer); const decoder = this.parser.options.meshoptDecoder; if (!decoder || !decoder.supported) { if (json.extensionsRequired && json.extensionsRequired.indexOf(this.name) >= 0) { throw new Error("THREE.GLTFLoader: setMeshoptDecoder must be called before loading compressed files"); } else { return null; } } return buffer.then(function(res) { const byteOffset = extensionDef.byteOffset || 0; const byteLength = extensionDef.byteLength || 0; const count = extensionDef.count; const stride = extensionDef.byteStride; const source = new Uint8Array(res, byteOffset, byteLength); if (decoder.decodeGltfBufferAsync) { return decoder.decodeGltfBufferAsync(count, stride, source, extensionDef.mode, extensionDef.filter).then(function(res2) { return res2.buffer; }); } else { return decoder.ready.then(function() { const result = new ArrayBuffer(count * stride); decoder.decodeGltfBuffer(new Uint8Array(result), count, stride, source, extensionDef.mode, extensionDef.filter); return result; }); } }); } else { return null; } } }; var GLTFMeshGpuInstancing = class { constructor(parser) { this.name = EXTENSIONS.EXT_MESH_GPU_INSTANCING; this.parser = parser; } createNodeMesh(nodeIndex) { const json = this.parser.json; const nodeDef = json.nodes[nodeIndex]; if (!nodeDef.extensions || !nodeDef.extensions[this.name] || nodeDef.mesh === void 0) { return null; } const meshDef = json.meshes[nodeDef.mesh]; for (const primitive of meshDef.primitives) { if (primitive.mode !== WEBGL_CONSTANTS.TRIANGLES && primitive.mode !== WEBGL_CONSTANTS.TRIANGLE_STRIP && primitive.mode !== WEBGL_CONSTANTS.TRIANGLE_FAN && primitive.mode !== void 0) { return null; } } const extensionDef = nodeDef.extensions[this.name]; const attributesDef = extensionDef.attributes; const pending = []; const attributes = {}; for (const key in attributesDef) { pending.push(this.parser.getDependency("accessor", attributesDef[key]).then((accessor) => { attributes[key] = accessor; return attributes[key]; })); } if (pending.length < 1) { return null; } pending.push(this.parser.createNodeMesh(nodeIndex)); return Promise.all(pending).then((results) => { const nodeObject = results.pop(); const meshes = nodeObject.isGroup ? nodeObject.children : [nodeObject]; const count = results[0].count; const instancedMeshes = []; for (const mesh of meshes) { const m = new Matrix4(); const p2 = new Vector3(); const q = new Quaternion(); const s = new Vector3(1, 1, 1); const instancedMesh = new InstancedMesh(mesh.geometry, mesh.material, count); for (let i = 0; i < count; i++) { if (attributes.TRANSLATION) { p2.fromBufferAttribute(attributes.TRANSLATION, i); } if (attributes.ROTATION) { q.fromBufferAttribute(attributes.ROTATION, i); } if (attributes.SCALE) { s.fromBufferAttribute(attributes.SCALE, i); } instancedMesh.setMatrixAt(i, m.compose(p2, q, s)); } for (const attributeName in attributes) { if (attributeName !== "TRANSLATION" && attributeName !== "ROTATION" && attributeName !== "SCALE") { mesh.geometry.setAttribute(attributeName, attributes[attributeName]); } } Object3D.prototype.copy.call(instancedMesh, mesh); instancedMesh.frustumCulled = false; this.parser.assignFinalMaterial(instancedMesh); instancedMeshes.push(instancedMesh); } if (nodeObject.isGroup) { nodeObject.clear(); nodeObject.add(...instancedMeshes); return nodeObject; } return instancedMeshes[0]; }); } }; var BINARY_EXTENSION_HEADER_MAGIC = "glTF"; var BINARY_EXTENSION_HEADER_LENGTH = 12; var BINARY_EXTENSION_CHUNK_TYPES = { JSON: 1313821514, BIN: 5130562 }; var GLTFBinaryExtension = class { constructor(data) { this.name = EXTENSIONS.KHR_BINARY_GLTF; this.content = null; this.body = null; const headerView = new DataView(data, 0, BINARY_EXTENSION_HEADER_LENGTH); this.header = { magic: LoaderUtils.decodeText(new Uint8Array(data.slice(0, 4))), version: headerView.getUint32(4, true), length: headerView.getUint32(8, true) }; if (this.header.magic !== BINARY_EXTENSION_HEADER_MAGIC) { throw new Error("THREE.GLTFLoader: Unsupported glTF-Binary header."); } else if (this.header.version < 2) { throw new Error("THREE.GLTFLoader: Legacy binary file detected."); } const chunkContentsLength = this.header.length - BINARY_EXTENSION_HEADER_LENGTH; const chunkView = new DataView(data, BINARY_EXTENSION_HEADER_LENGTH); let chunkIndex = 0; while (chunkIndex < chunkContentsLength) { const chunkLength = chunkView.getUint32(chunkIndex, true); chunkIndex += 4; const chunkType = chunkView.getUint32(chunkIndex, true); chunkIndex += 4; if (chunkType === BINARY_EXTENSION_CHUNK_TYPES.JSON) { const contentArray = new Uint8Array(data, BINARY_EXTENSION_HEADER_LENGTH + chunkIndex, chunkLength); this.content = LoaderUtils.decodeText(contentArray); } else if (chunkType === BINARY_EXTENSION_CHUNK_TYPES.BIN) { const byteOffset = BINARY_EXTENSION_HEADER_LENGTH + chunkIndex; this.body = data.slice(byteOffset, byteOffset + chunkLength); } chunkIndex += chunkLength; } if (this.content === null) { throw new Error("THREE.GLTFLoader: JSON content not found."); } } }; var GLTFDracoMeshCompressionExtension = class { constructor(json, dracoLoader2) { if (!dracoLoader2) { throw new Error("THREE.GLTFLoader: No DRACOLoader instance provided."); } this.name = EXTENSIONS.KHR_DRACO_MESH_COMPRESSION; this.json = json; this.dracoLoader = dracoLoader2; this.dracoLoader.preload(); } decodePrimitive(primitive, parser) { const json = this.json; const dracoLoader2 = this.dracoLoader; const bufferViewIndex = primitive.extensions[this.name].bufferView; const gltfAttributeMap = primitive.extensions[this.name].attributes; const threeAttributeMap = {}; const attributeNormalizedMap = {}; const attributeTypeMap = {}; for (const attributeName in gltfAttributeMap) { const threeAttributeName = ATTRIBUTES[attributeName] || attributeName.toLowerCase(); threeAttributeMap[threeAttributeName] = gltfAttributeMap[attributeName]; } for (const attributeName in primitive.attributes) { const threeAttributeName = ATTRIBUTES[attributeName] || attributeName.toLowerCase(); if (gltfAttributeMap[attributeName] !== void 0) { const accessorDef = json.accessors[primitive.attributes[attributeName]]; const componentType = WEBGL_COMPONENT_TYPES[accessorDef.componentType]; attributeTypeMap[threeAttributeName] = componentType.name; attributeNormalizedMap[threeAttributeName] = accessorDef.normalized === true; } } return parser.getDependency("bufferView", bufferViewIndex).then(function(bufferView) { return new Promise(function(resolve) { dracoLoader2.decodeDracoFile(bufferView, function(geometry) { for (const attributeName in geometry.attributes) { const attribute = geometry.attributes[attributeName]; const normalized = attributeNormalizedMap[attributeName]; if (normalized !== void 0) attribute.normalized = normalized; } resolve(geometry); }, threeAttributeMap, attributeTypeMap); }); }); } }; var GLTFTextureTransformExtension = class { constructor() { this.name = EXTENSIONS.KHR_TEXTURE_TRANSFORM; } extendTexture(texture, transform) { if (transform.texCoord !== void 0) { console.warn('THREE.GLTFLoader: Custom UV sets in "' + this.name + '" extension not yet supported.'); } if (transform.offset === void 0 && transform.rotation === void 0 && transform.scale === void 0) { return texture; } texture = texture.clone(); if (transform.offset !== void 0) { texture.offset.fromArray(transform.offset); } if (transform.rotation !== void 0) { texture.rotation = transform.rotation; } if (transform.scale !== void 0) { texture.repeat.fromArray(transform.scale); } texture.needsUpdate = true; return texture; } }; var GLTFMeshStandardSGMaterial = class extends MeshStandardMaterial { constructor(params) { super(); this.isGLTFSpecularGlossinessMaterial = true; const specularMapParsFragmentChunk = [ "#ifdef USE_SPECULARMAP", " uniform sampler2D specularMap;", "#endif" ].join("\n"); const glossinessMapParsFragmentChunk = [ "#ifdef USE_GLOSSINESSMAP", " uniform sampler2D glossinessMap;", "#endif" ].join("\n"); const specularMapFragmentChunk = [ "vec3 specularFactor = specular;", "#ifdef USE_SPECULARMAP", " vec4 texelSpecular = texture2D( specularMap, vUv );", " // reads channel RGB, compatible with a glTF Specular-Glossiness (RGBA) texture", " specularFactor *= texelSpecular.rgb;", "#endif" ].join("\n"); const glossinessMapFragmentChunk = [ "float glossinessFactor = glossiness;", "#ifdef USE_GLOSSINESSMAP", " vec4 texelGlossiness = texture2D( glossinessMap, vUv );", " // reads channel A, compatible with a glTF Specular-Glossiness (RGBA) texture", " glossinessFactor *= texelGlossiness.a;", "#endif" ].join("\n"); const lightPhysicalFragmentChunk = [ "PhysicalMaterial material;", "material.diffuseColor = diffuseColor.rgb * ( 1. - max( specularFactor.r, max( specularFactor.g, specularFactor.b ) ) );", "vec3 dxy = max( abs( dFdx( geometryNormal ) ), abs( dFdy( geometryNormal ) ) );", "float geometryRoughness = max( max( dxy.x, dxy.y ), dxy.z );", "material.roughness = max( 1.0 - glossinessFactor, 0.0525 ); // 0.0525 corresponds to the base mip of a 256 cubemap.", "material.roughness += geometryRoughness;", "material.roughness = min( material.roughness, 1.0 );", "material.specularColor = specularFactor;" ].join("\n"); const uniforms = { specular: { value: new Color().setHex(16777215) }, glossiness: { value: 1 }, specularMap: { value: null }, glossinessMap: { value: null } }; this._extraUniforms = uniforms; this.onBeforeCompile = function(shader) { for (const uniformName in uniforms) { shader.uniforms[uniformName] = uniforms[uniformName]; } shader.fragmentShader = shader.fragmentShader.replace("uniform float roughness;", "uniform vec3 specular;").replace("uniform float metalness;", "uniform float glossiness;").replace("#include ", specularMapParsFragmentChunk).replace("#include ", glossinessMapParsFragmentChunk).replace("#include ", specularMapFragmentChunk).replace("#include ", glossinessMapFragmentChunk).replace("#include ", lightPhysicalFragmentChunk); }; Object.defineProperties(this, { specular: { get: function() { return uniforms.specular.value; }, set: function(v) { uniforms.specular.value = v; } }, specularMap: { get: function() { return uniforms.specularMap.value; }, set: function(v) { uniforms.specularMap.value = v; if (v) { this.defines.USE_SPECULARMAP = ""; } else { delete this.defines.USE_SPECULARMAP; } } }, glossiness: { get: function() { return uniforms.glossiness.value; }, set: function(v) { uniforms.glossiness.value = v; } }, glossinessMap: { get: function() { return uniforms.glossinessMap.value; }, set: function(v) { uniforms.glossinessMap.value = v; if (v) { this.defines.USE_GLOSSINESSMAP = ""; this.defines.USE_UV = ""; } else { delete this.defines.USE_GLOSSINESSMAP; delete this.defines.USE_UV; } } } }); delete this.metalness; delete this.roughness; delete this.metalnessMap; delete this.roughnessMap; this.setValues(params); } copy(source) { super.copy(source); this.specularMap = source.specularMap; this.specular.copy(source.specular); this.glossinessMap = source.glossinessMap; this.glossiness = source.glossiness; delete this.metalness; delete this.roughness; delete this.metalnessMap; delete this.roughnessMap; return this; } }; var GLTFMaterialsPbrSpecularGlossinessExtension = class { constructor() { this.name = EXTENSIONS.KHR_MATERIALS_PBR_SPECULAR_GLOSSINESS; this.specularGlossinessParams = [ "color", "map", "lightMap", "lightMapIntensity", "aoMap", "aoMapIntensity", "emissive", "emissiveIntensity", "emissiveMap", "bumpMap", "bumpScale", "normalMap", "normalMapType", "displacementMap", "displacementScale", "displacementBias", "specularMap", "specular", "glossinessMap", "glossiness", "alphaMap", "envMap", "envMapIntensity" ]; } getMaterialType() { return GLTFMeshStandardSGMaterial; } extendParams(materialParams, materialDef, parser) { const pbrSpecularGlossiness = materialDef.extensions[this.name]; materialParams.color = new Color(1, 1, 1); materialParams.opacity = 1; const pending = []; if (Array.isArray(pbrSpecularGlossiness.diffuseFactor)) { const array = pbrSpecularGlossiness.diffuseFactor; materialParams.color.fromArray(array); materialParams.opacity = array[3]; } if (pbrSpecularGlossiness.diffuseTexture !== void 0) { pending.push(parser.assignTexture(materialParams, "map", pbrSpecularGlossiness.diffuseTexture, sRGBEncoding)); } materialParams.emissive = new Color(0, 0, 0); materialParams.glossiness = pbrSpecularGlossiness.glossinessFactor !== void 0 ? pbrSpecularGlossiness.glossinessFactor : 1; materialParams.specular = new Color(1, 1, 1); if (Array.isArray(pbrSpecularGlossiness.specularFactor)) { materialParams.specular.fromArray(pbrSpecularGlossiness.specularFactor); } if (pbrSpecularGlossiness.specularGlossinessTexture !== void 0) { const specGlossMapDef = pbrSpecularGlossiness.specularGlossinessTexture; pending.push(parser.assignTexture(materialParams, "glossinessMap", specGlossMapDef)); pending.push(parser.assignTexture(materialParams, "specularMap", specGlossMapDef, sRGBEncoding)); } return Promise.all(pending); } createMaterial(materialParams) { const material = new GLTFMeshStandardSGMaterial(materialParams); material.fog = true; material.color = materialParams.color; material.map = materialParams.map === void 0 ? null : materialParams.map; material.lightMap = null; material.lightMapIntensity = 1; material.aoMap = materialParams.aoMap === void 0 ? null : materialParams.aoMap; material.aoMapIntensity = 1; material.emissive = materialParams.emissive; material.emissiveIntensity = materialParams.emissiveIntensity === void 0 ? 1 : materialParams.emissiveIntensity; material.emissiveMap = materialParams.emissiveMap === void 0 ? null : materialParams.emissiveMap; material.bumpMap = materialParams.bumpMap === void 0 ? null : materialParams.bumpMap; material.bumpScale = 1; material.normalMap = materialParams.normalMap === void 0 ? null : materialParams.normalMap; material.normalMapType = TangentSpaceNormalMap; if (materialParams.normalScale) material.normalScale = materialParams.normalScale; material.displacementMap = null; material.displacementScale = 1; material.displacementBias = 0; material.specularMap = materialParams.specularMap === void 0 ? null : materialParams.specularMap; material.specular = materialParams.specular; material.glossinessMap = materialParams.glossinessMap === void 0 ? null : materialParams.glossinessMap; material.glossiness = materialParams.glossiness; material.alphaMap = null; material.envMap = materialParams.envMap === void 0 ? null : materialParams.envMap; material.envMapIntensity = 1; return material; } }; var GLTFMeshQuantizationExtension = class { constructor() { this.name = EXTENSIONS.KHR_MESH_QUANTIZATION; } }; var GLTFCubicSplineInterpolant = class extends Interpolant { constructor(parameterPositions, sampleValues, sampleSize, resultBuffer) { super(parameterPositions, sampleValues, sampleSize, resultBuffer); } copySampleValue_(index) { const result = this.resultBuffer, values = this.sampleValues, valueSize = this.valueSize, offset = index * valueSize * 3 + valueSize; for (let i = 0; i !== valueSize; i++) { result[i] = values[offset + i]; } return result; } interpolate_(i1, t0, t2, t1) { const result = this.resultBuffer; const values = this.sampleValues; const stride = this.valueSize; const stride2 = stride * 2; const stride3 = stride * 3; const td2 = t1 - t0; const p2 = (t2 - t0) / td2; const pp = p2 * p2; const ppp = pp * p2; const offset1 = i1 * stride3; const offset0 = offset1 - stride3; const s2 = -2 * ppp + 3 * pp; const s3 = ppp - pp; const s0 = 1 - s2; const s1 = s3 - pp + p2; for (let i = 0; i !== stride; i++) { const p0 = values[offset0 + i + stride]; const m0 = values[offset0 + i + stride2] * td2; const p1 = values[offset1 + i + stride]; const m1 = values[offset1 + i] * td2; result[i] = s0 * p0 + s1 * m0 + s2 * p1 + s3 * m1; } return result; } }; var _q = new Quaternion(); var GLTFCubicSplineQuaternionInterpolant = class extends GLTFCubicSplineInterpolant { interpolate_(i1, t0, t2, t1) { const result = super.interpolate_(i1, t0, t2, t1); _q.fromArray(result).normalize().toArray(result); return result; } }; var WEBGL_CONSTANTS = { FLOAT: 5126, //FLOAT_MAT2: 35674, FLOAT_MAT3: 35675, FLOAT_MAT4: 35676, FLOAT_VEC2: 35664, FLOAT_VEC3: 35665, FLOAT_VEC4: 35666, LINEAR: 9729, REPEAT: 10497, SAMPLER_2D: 35678, POINTS: 0, LINES: 1, LINE_LOOP: 2, LINE_STRIP: 3, TRIANGLES: 4, TRIANGLE_STRIP: 5, TRIANGLE_FAN: 6, UNSIGNED_BYTE: 5121, UNSIGNED_SHORT: 5123 }; var WEBGL_COMPONENT_TYPES = { 5120: Int8Array, 5121: Uint8Array, 5122: Int16Array, 5123: Uint16Array, 5125: Uint32Array, 5126: Float32Array }; var WEBGL_FILTERS = { 9728: NearestFilter, 9729: LinearFilter, 9984: NearestMipmapNearestFilter, 9985: LinearMipmapNearestFilter, 9986: NearestMipmapLinearFilter, 9987: LinearMipmapLinearFilter }; var WEBGL_WRAPPINGS = { 33071: ClampToEdgeWrapping, 33648: MirroredRepeatWrapping, 10497: RepeatWrapping }; var WEBGL_TYPE_SIZES = { "SCALAR": 1, "VEC2": 2, "VEC3": 3, "VEC4": 4, "MAT2": 4, "MAT3": 9, "MAT4": 16 }; var ATTRIBUTES = { POSITION: "position", NORMAL: "normal", TANGENT: "tangent", TEXCOORD_0: "uv", TEXCOORD_1: "uv2", COLOR_0: "color", WEIGHTS_0: "skinWeight", JOINTS_0: "skinIndex" }; var PATH_PROPERTIES = { scale: "scale", translation: "position", rotation: "quaternion", weights: "morphTargetInfluences" }; var INTERPOLATION = { CUBICSPLINE: void 0, // We use a custom interpolant (GLTFCubicSplineInterpolation) for CUBICSPLINE tracks. Each // keyframe track will be initialized with a default interpolation type, then modified. LINEAR: InterpolateLinear, STEP: InterpolateDiscrete }; var ALPHA_MODES = { OPAQUE: "OPAQUE", MASK: "MASK", BLEND: "BLEND" }; function createDefaultMaterial(cache2) { if (cache2["DefaultMaterial"] === void 0) { cache2["DefaultMaterial"] = new MeshStandardMaterial({ color: 16777215, emissive: 0, metalness: 1, roughness: 1, transparent: false, depthTest: true, side: FrontSide }); } return cache2["DefaultMaterial"]; } function addUnknownExtensionsToUserData(knownExtensions, object, objectDef) { for (const name in objectDef.extensions) { if (knownExtensions[name] === void 0) { object.userData.gltfExtensions = object.userData.gltfExtensions || {}; object.userData.gltfExtensions[name] = objectDef.extensions[name]; } } } function assignExtrasToUserData(object, gltfDef) { if (gltfDef.extras !== void 0) { if (typeof gltfDef.extras === "object") { Object.assign(object.userData, gltfDef.extras); } else { console.warn("THREE.GLTFLoader: Ignoring primitive type .extras, " + gltfDef.extras); } } } function addMorphTargets(geometry, targets, parser) { let hasMorphPosition = false; let hasMorphNormal = false; let hasMorphColor = false; for (let i = 0, il = targets.length; i < il; i++) { const target2 = targets[i]; if (target2.POSITION !== void 0) hasMorphPosition = true; if (target2.NORMAL !== void 0) hasMorphNormal = true; if (target2.COLOR_0 !== void 0) hasMorphColor = true; if (hasMorphPosition && hasMorphNormal && hasMorphColor) break; } if (!hasMorphPosition && !hasMorphNormal && !hasMorphColor) return Promise.resolve(geometry); const pendingPositionAccessors = []; const pendingNormalAccessors = []; const pendingColorAccessors = []; for (let i = 0, il = targets.length; i < il; i++) { const target2 = targets[i]; if (hasMorphPosition) { const pendingAccessor = target2.POSITION !== void 0 ? parser.getDependency("accessor", target2.POSITION) : geometry.attributes.position; pendingPositionAccessors.push(pendingAccessor); } if (hasMorphNormal) { const pendingAccessor = target2.NORMAL !== void 0 ? parser.getDependency("accessor", target2.NORMAL) : geometry.attributes.normal; pendingNormalAccessors.push(pendingAccessor); } if (hasMorphColor) { const pendingAccessor = target2.COLOR_0 !== void 0 ? parser.getDependency("accessor", target2.COLOR_0) : geometry.attributes.color; pendingColorAccessors.push(pendingAccessor); } } return Promise.all([ Promise.all(pendingPositionAccessors), Promise.all(pendingNormalAccessors), Promise.all(pendingColorAccessors) ]).then(function(accessors) { const morphPositions = accessors[0]; const morphNormals = accessors[1]; const morphColors = accessors[2]; if (hasMorphPosition) geometry.morphAttributes.position = morphPositions; if (hasMorphNormal) geometry.morphAttributes.normal = morphNormals; if (hasMorphColor) geometry.morphAttributes.color = morphColors; geometry.morphTargetsRelative = true; return geometry; }); } function updateMorphTargets(mesh, meshDef) { mesh.updateMorphTargets(); if (meshDef.weights !== void 0) { for (let i = 0, il = meshDef.weights.length; i < il; i++) { mesh.morphTargetInfluences[i] = meshDef.weights[i]; } } if (meshDef.extras && Array.isArray(meshDef.extras.targetNames)) { const targetNames = meshDef.extras.targetNames; if (mesh.morphTargetInfluences.length === targetNames.length) { mesh.morphTargetDictionary = {}; for (let i = 0, il = targetNames.length; i < il; i++) { mesh.morphTargetDictionary[targetNames[i]] = i; } } else { console.warn("THREE.GLTFLoader: Invalid extras.targetNames length. Ignoring names."); } } } function createPrimitiveKey(primitiveDef) { const dracoExtension = primitiveDef.extensions && primitiveDef.extensions[EXTENSIONS.KHR_DRACO_MESH_COMPRESSION]; let geometryKey; if (dracoExtension) { geometryKey = "draco:" + dracoExtension.bufferView + ":" + dracoExtension.indices + ":" + createAttributesKey(dracoExtension.attributes); } else { geometryKey = primitiveDef.indices + ":" + createAttributesKey(primitiveDef.attributes) + ":" + primitiveDef.mode; } return geometryKey; } function createAttributesKey(attributes) { let attributesKey = ""; const keys = Object.keys(attributes).sort(); for (let i = 0, il = keys.length; i < il; i++) { attributesKey += keys[i] + ":" + attributes[keys[i]] + ";"; } return attributesKey; } function getNormalizedComponentScale(constructor) { switch (constructor) { case Int8Array: return 1 / 127; case Uint8Array: return 1 / 255; case Int16Array: return 1 / 32767; case Uint16Array: return 1 / 65535; default: throw new Error("THREE.GLTFLoader: Unsupported normalized accessor component type."); } } function getImageURIMimeType(uri) { if (uri.search(/\.jpe?g($|\?)/i) > 0 || uri.search(/^data\:image\/jpeg/) === 0) return "image/jpeg"; if (uri.search(/\.webp($|\?)/i) > 0 || uri.search(/^data\:image\/webp/) === 0) return "image/webp"; return "image/png"; } var GLTFParser = class { constructor(json = {}, options = {}) { this.json = json; this.extensions = {}; this.plugins = {}; this.options = options; this.cache = new GLTFRegistry(); this.associations = /* @__PURE__ */ new Map(); this.primitiveCache = {}; this.meshCache = { refs: {}, uses: {} }; this.cameraCache = { refs: {}, uses: {} }; this.lightCache = { refs: {}, uses: {} }; this.sourceCache = {}; this.textureCache = {}; this.nodeNamesUsed = {}; const isSafari = /^((?!chrome|android).)*safari/i.test(navigator.userAgent) === true; const isFirefox = navigator.userAgent.indexOf("Firefox") > -1; const firefoxVersion = isFirefox ? navigator.userAgent.match(/Firefox\/([0-9]+)\./)[1] : -1; if (typeof createImageBitmap === "undefined" || isSafari || isFirefox && firefoxVersion < 98) { this.textureLoader = new TextureLoader(this.options.manager); } else { this.textureLoader = new ImageBitmapLoader(this.options.manager); } this.textureLoader.setCrossOrigin(this.options.crossOrigin); this.textureLoader.setRequestHeader(this.options.requestHeader); this.fileLoader = new FileLoader(this.options.manager); this.fileLoader.setResponseType("arraybuffer"); if (this.options.crossOrigin === "use-credentials") { this.fileLoader.setWithCredentials(true); } } setExtensions(extensions) { this.extensions = extensions; } setPlugins(plugins) { this.plugins = plugins; } parse(onLoad, onError) { const parser = this; const json = this.json; const extensions = this.extensions; this.cache.removeAll(); this._invokeAll(function(ext) { return ext._markDefs && ext._markDefs(); }); Promise.all(this._invokeAll(function(ext) { return ext.beforeRoot && ext.beforeRoot(); })).then(function() { return Promise.all([ parser.getDependencies("scene"), parser.getDependencies("animation"), parser.getDependencies("camera") ]); }).then(function(dependencies) { const result = { scene: dependencies[0][json.scene || 0], scenes: dependencies[0], animations: dependencies[1], cameras: dependencies[2], asset: json.asset, parser, userData: {} }; addUnknownExtensionsToUserData(extensions, result, json); assignExtrasToUserData(result, json); Promise.all(parser._invokeAll(function(ext) { return ext.afterRoot && ext.afterRoot(result); })).then(function() { onLoad(result); }); }).catch(onError); } /** * Marks the special nodes/meshes in json for efficient parse. */ _markDefs() { const nodeDefs = this.json.nodes || []; const skinDefs = this.json.skins || []; const meshDefs = this.json.meshes || []; for (let skinIndex = 0, skinLength = skinDefs.length; skinIndex < skinLength; skinIndex++) { const joints = skinDefs[skinIndex].joints; for (let i = 0, il = joints.length; i < il; i++) { nodeDefs[joints[i]].isBone = true; } } for (let nodeIndex = 0, nodeLength = nodeDefs.length; nodeIndex < nodeLength; nodeIndex++) { const nodeDef = nodeDefs[nodeIndex]; if (nodeDef.mesh !== void 0) { this._addNodeRef(this.meshCache, nodeDef.mesh); if (nodeDef.skin !== void 0) { meshDefs[nodeDef.mesh].isSkinnedMesh = true; } } if (nodeDef.camera !== void 0) { this._addNodeRef(this.cameraCache, nodeDef.camera); } } } /** * Counts references to shared node / Object3D resources. These resources * can be reused, or "instantiated", at multiple nodes in the scene * hierarchy. Mesh, Camera, and Light instances are instantiated and must * be marked. Non-scenegraph resources (like Materials, Geometries, and * Textures) can be reused directly and are not marked here. * * Example: CesiumMilkTruck sample model reuses "Wheel" meshes. */ _addNodeRef(cache2, index) { if (index === void 0) return; if (cache2.refs[index] === void 0) { cache2.refs[index] = cache2.uses[index] = 0; } cache2.refs[index]++; } /** Returns a reference to a shared resource, cloning it if necessary. */ _getNodeRef(cache2, index, object) { if (cache2.refs[index] <= 1) return object; const ref = object.clone(); const updateMappings = (original, clone2) => { const mappings = this.associations.get(original); if (mappings != null) { this.associations.set(clone2, mappings); } for (const [i, child] of original.children.entries()) { updateMappings(child, clone2.children[i]); } }; updateMappings(object, ref); ref.name += "_instance_" + cache2.uses[index]++; return ref; } _invokeOne(func) { const extensions = Object.values(this.plugins); extensions.push(this); for (let i = 0; i < extensions.length; i++) { const result = func(extensions[i]); if (result) return result; } return null; } _invokeAll(func) { const extensions = Object.values(this.plugins); extensions.unshift(this); const pending = []; for (let i = 0; i < extensions.length; i++) { const result = func(extensions[i]); if (result) pending.push(result); } return pending; } /** * Requests the specified dependency asynchronously, with caching. * @param {string} type * @param {number} index * @return {Promise} */ getDependency(type, index) { const cacheKey = type + ":" + index; let dependency = this.cache.get(cacheKey); if (!dependency) { switch (type) { case "scene": dependency = this.loadScene(index); break; case "node": dependency = this.loadNode(index); break; case "mesh": dependency = this._invokeOne(function(ext) { return ext.loadMesh && ext.loadMesh(index); }); break; case "accessor": dependency = this.loadAccessor(index); break; case "bufferView": dependency = this._invokeOne(function(ext) { return ext.loadBufferView && ext.loadBufferView(index); }); break; case "buffer": dependency = this.loadBuffer(index); break; case "material": dependency = this._invokeOne(function(ext) { return ext.loadMaterial && ext.loadMaterial(index); }); break; case "texture": dependency = this._invokeOne(function(ext) { return ext.loadTexture && ext.loadTexture(index); }); break; case "skin": dependency = this.loadSkin(index); break; case "animation": dependency = this._invokeOne(function(ext) { return ext.loadAnimation && ext.loadAnimation(index); }); break; case "camera": dependency = this.loadCamera(index); break; default: throw new Error("Unknown type: " + type); } this.cache.add(cacheKey, dependency); } return dependency; } /** * Requests all dependencies of the specified type asynchronously, with caching. * @param {string} type * @return {Promise>} */ getDependencies(type) { let dependencies = this.cache.get(type); if (!dependencies) { const parser = this; const defs = this.json[type + (type === "mesh" ? "es" : "s")] || []; dependencies = Promise.all(defs.map(function(def, index) { return parser.getDependency(type, index); })); this.cache.add(type, dependencies); } return dependencies; } /** * Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#buffers-and-buffer-views * @param {number} bufferIndex * @return {Promise} */ loadBuffer(bufferIndex) { const bufferDef = this.json.buffers[bufferIndex]; const loader = this.fileLoader; if (bufferDef.type && bufferDef.type !== "arraybuffer") { throw new Error("THREE.GLTFLoader: " + bufferDef.type + " buffer type is not supported."); } if (bufferDef.uri === void 0 && bufferIndex === 0) { return Promise.resolve(this.extensions[EXTENSIONS.KHR_BINARY_GLTF].body); } const options = this.options; return new Promise(function(resolve, reject) { loader.load(LoaderUtils.resolveURL(bufferDef.uri, options.path), resolve, void 0, function() { reject(new Error('THREE.GLTFLoader: Failed to load buffer "' + bufferDef.uri + '".')); }); }); } /** * Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#buffers-and-buffer-views * @param {number} bufferViewIndex * @return {Promise} */ loadBufferView(bufferViewIndex) { const bufferViewDef = this.json.bufferViews[bufferViewIndex]; return this.getDependency("buffer", bufferViewDef.buffer).then(function(buffer) { const byteLength = bufferViewDef.byteLength || 0; const byteOffset = bufferViewDef.byteOffset || 0; return buffer.slice(byteOffset, byteOffset + byteLength); }); } /** * Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#accessors * @param {number} accessorIndex * @return {Promise} */ loadAccessor(accessorIndex) { const parser = this; const json = this.json; const accessorDef = this.json.accessors[accessorIndex]; if (accessorDef.bufferView === void 0 && accessorDef.sparse === void 0) { return Promise.resolve(null); } const pendingBufferViews = []; if (accessorDef.bufferView !== void 0) { pendingBufferViews.push(this.getDependency("bufferView", accessorDef.bufferView)); } else { pendingBufferViews.push(null); } if (accessorDef.sparse !== void 0) { pendingBufferViews.push(this.getDependency("bufferView", accessorDef.sparse.indices.bufferView)); pendingBufferViews.push(this.getDependency("bufferView", accessorDef.sparse.values.bufferView)); } return Promise.all(pendingBufferViews).then(function(bufferViews) { const bufferView = bufferViews[0]; const itemSize = WEBGL_TYPE_SIZES[accessorDef.type]; const TypedArray = WEBGL_COMPONENT_TYPES[accessorDef.componentType]; const elementBytes = TypedArray.BYTES_PER_ELEMENT; const itemBytes = elementBytes * itemSize; const byteOffset = accessorDef.byteOffset || 0; const byteStride = accessorDef.bufferView !== void 0 ? json.bufferViews[accessorDef.bufferView].byteStride : void 0; const normalized = accessorDef.normalized === true; let array, bufferAttribute; if (byteStride && byteStride !== itemBytes) { const ibSlice = Math.floor(byteOffset / byteStride); const ibCacheKey = "InterleavedBuffer:" + accessorDef.bufferView + ":" + accessorDef.componentType + ":" + ibSlice + ":" + accessorDef.count; let ib = parser.cache.get(ibCacheKey); if (!ib) { array = new TypedArray(bufferView, ibSlice * byteStride, accessorDef.count * byteStride / elementBytes); ib = new InterleavedBuffer(array, byteStride / elementBytes); parser.cache.add(ibCacheKey, ib); } bufferAttribute = new InterleavedBufferAttribute(ib, itemSize, byteOffset % byteStride / elementBytes, normalized); } else { if (bufferView === null) { array = new TypedArray(accessorDef.count * itemSize); } else { array = new TypedArray(bufferView, byteOffset, accessorDef.count * itemSize); } bufferAttribute = new BufferAttribute(array, itemSize, normalized); } if (accessorDef.sparse !== void 0) { const itemSizeIndices = WEBGL_TYPE_SIZES.SCALAR; const TypedArrayIndices = WEBGL_COMPONENT_TYPES[accessorDef.sparse.indices.componentType]; const byteOffsetIndices = accessorDef.sparse.indices.byteOffset || 0; const byteOffsetValues = accessorDef.sparse.values.byteOffset || 0; const sparseIndices = new TypedArrayIndices(bufferViews[1], byteOffsetIndices, accessorDef.sparse.count * itemSizeIndices); const sparseValues = new TypedArray(bufferViews[2], byteOffsetValues, accessorDef.sparse.count * itemSize); if (bufferView !== null) { bufferAttribute = new BufferAttribute(bufferAttribute.array.slice(), bufferAttribute.itemSize, bufferAttribute.normalized); } for (let i = 0, il = sparseIndices.length; i < il; i++) { const index = sparseIndices[i]; bufferAttribute.setX(index, sparseValues[i * itemSize]); if (itemSize >= 2) bufferAttribute.setY(index, sparseValues[i * itemSize + 1]); if (itemSize >= 3) bufferAttribute.setZ(index, sparseValues[i * itemSize + 2]); if (itemSize >= 4) bufferAttribute.setW(index, sparseValues[i * itemSize + 3]); if (itemSize >= 5) throw new Error("THREE.GLTFLoader: Unsupported itemSize in sparse BufferAttribute."); } } return bufferAttribute; }); } /** * Specification: https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#textures * @param {number} textureIndex * @return {Promise} */ loadTexture(textureIndex) { const json = this.json; const options = this.options; const textureDef = json.textures[textureIndex]; const sourceIndex = textureDef.source; const sourceDef = json.images[sourceIndex]; let loader = this.textureLoader; if (sourceDef.uri) { const handler = options.manager.getHandler(sourceDef.uri); if (handler !== null) loader = handler; } return this.loadTextureImage(textureIndex, sourceIndex, loader); } loadTextureImage(textureIndex, sourceIndex, loader) { const parser = this; const json = this.json; const textureDef = json.textures[textureIndex]; const sourceDef = json.images[sourceIndex]; const cacheKey = (sourceDef.uri || sourceDef.bufferView) + ":" + textureDef.sampler; if (this.textureCache[cacheKey]) { return this.textureCache[cacheKey]; } const promise = this.loadImageSource(sourceIndex, loader).then(function(texture) { texture.flipY = false; texture.name = textureDef.name || sourceDef.name || ""; const samplers = json.samplers || {}; const sampler = samplers[textureDef.sampler] || {}; texture.magFilter = WEBGL_FILTERS[sampler.magFilter] || LinearFilter; texture.minFilter = WEBGL_FILTERS[sampler.minFilter] || LinearMipmapLinearFilter; texture.wrapS = WEBGL_WRAPPINGS[sampler.wrapS] || RepeatWrapping; texture.wrapT = WEBGL_WRAPPINGS[sampler.wrapT] || RepeatWrapping; parser.associations.set(texture, { textures: textureIndex }); return texture; }).catch(function() { return null; }); this.textureCache[cacheKey] = promise; return promise; } loadImageSource(sourceIndex, loader) { const parser = this; const json = this.json; const options = this.options; if (this.sourceCache[sourceIndex] !== void 0) { return this.sourceCache[sourceIndex].then((texture) => texture.clone()); } const sourceDef = json.images[sourceIndex]; const URL2 = self.URL || self.webkitURL; let sourceURI = sourceDef.uri || ""; let isObjectURL = false; if (sourceDef.bufferView !== void 0) { sourceURI = parser.getDependency("bufferView", sourceDef.bufferView).then(function(bufferView) { isObjectURL = true; const blob = new Blob([bufferView], { type: sourceDef.mimeType }); sourceURI = URL2.createObjectURL(blob); return sourceURI; }); } else if (sourceDef.uri === void 0) { throw new Error("THREE.GLTFLoader: Image " + sourceIndex + " is missing URI and bufferView"); } const promise = Promise.resolve(sourceURI).then(function(sourceURI2) { return new Promise(function(resolve, reject) { let onLoad = resolve; if (loader.isImageBitmapLoader === true) { onLoad = function(imageBitmap) { const texture = new Texture(imageBitmap); texture.needsUpdate = true; resolve(texture); }; } loader.load(LoaderUtils.resolveURL(sourceURI2, options.path), onLoad, void 0, reject); }); }).then(function(texture) { if (isObjectURL === true) { URL2.revokeObjectURL(sourceURI); } texture.userData.mimeType = sourceDef.mimeType || getImageURIMimeType(sourceDef.uri); return texture; }).catch(function(error) { console.error("THREE.GLTFLoader: Couldn't load texture", sourceURI); throw error; }); this.sourceCache[sourceIndex] = promise; return promise; } /** * Asynchronously assigns a texture to the given material parameters. * @param {Object} materialParams * @param {string} mapName * @param {Object} mapDef * @return {Promise} */ assignTexture(materialParams, mapName, mapDef, encoding) { const parser = this; return this.getDependency("texture", mapDef.index).then(function(texture) { if (mapDef.texCoord !== void 0 && mapDef.texCoord != 0 && !(mapName === "aoMap" && mapDef.texCoord == 1)) { console.warn("THREE.GLTFLoader: Custom UV set " + mapDef.texCoord + " for texture " + mapName + " not yet supported."); } if (parser.extensions[EXTENSIONS.KHR_TEXTURE_TRANSFORM]) { const transform = mapDef.extensions !== void 0 ? mapDef.extensions[EXTENSIONS.KHR_TEXTURE_TRANSFORM] : void 0; if (transform) { const gltfReference = parser.associations.get(texture); texture = parser.extensions[EXTENSIONS.KHR_TEXTURE_TRANSFORM].extendTexture(texture, transform); parser.associations.set(texture, gltfReference); } } if (encoding !== void 0) { texture.encoding = encoding; } materialParams[mapName] = texture; return texture; }); } /** * Assigns final material to a Mesh, Line, or Points instance. The instance * already has a material (generated from the glTF material options alone) * but reuse of the same glTF material may require multiple threejs materials * to accommodate different primitive types, defines, etc. New materials will * be created if necessary, and reused from a cache. * @param {Object3D} mesh Mesh, Line, or Points instance. */ assignFinalMaterial(mesh) { const geometry = mesh.geometry; let material = mesh.material; const useDerivativeTangents = geometry.attributes.tangent === void 0; const useVertexColors = geometry.attributes.color !== void 0; const useFlatShading = geometry.attributes.normal === void 0; if (mesh.isPoints) { const cacheKey = "PointsMaterial:" + material.uuid; let pointsMaterial = this.cache.get(cacheKey); if (!pointsMaterial) { pointsMaterial = new PointsMaterial(); Material.prototype.copy.call(pointsMaterial, material); pointsMaterial.color.copy(material.color); pointsMaterial.map = material.map; pointsMaterial.sizeAttenuation = false; this.cache.add(cacheKey, pointsMaterial); } material = pointsMaterial; } else if (mesh.isLine) { const cacheKey = "LineBasicMaterial:" + material.uuid; let lineMaterial = this.cache.get(cacheKey); if (!lineMaterial) { lineMaterial = new LineBasicMaterial(); Material.prototype.copy.call(lineMaterial, material); lineMaterial.color.copy(material.color); this.cache.add(cacheKey, lineMaterial); } material = lineMaterial; } if (useDerivativeTangents || useVertexColors || useFlatShading) { let cacheKey = "ClonedMaterial:" + material.uuid + ":"; if (material.isGLTFSpecularGlossinessMaterial) cacheKey += "specular-glossiness:"; if (useDerivativeTangents) cacheKey += "derivative-tangents:"; if (useVertexColors) cacheKey += "vertex-colors:"; if (useFlatShading) cacheKey += "flat-shading:"; let cachedMaterial = this.cache.get(cacheKey); if (!cachedMaterial) { cachedMaterial = material.clone(); if (useVertexColors) cachedMaterial.vertexColors = true; if (useFlatShading) cachedMaterial.flatShading = true; if (useDerivativeTangents) { if (cachedMaterial.normalScale) cachedMaterial.normalScale.y *= -1; if (cachedMaterial.clearcoatNormalScale) cachedMaterial.clearcoatNormalScale.y *= -1; } this.cache.add(cacheKey, cachedMaterial); this.associations.set(cachedMaterial, this.associations.get(material)); } material = cachedMaterial; } if (material.aoMap && geometry.attributes.uv2 === void 0 && geometry.attributes.uv !== void 0) { geometry.setAttribute("uv2", geometry.attributes.uv); } mesh.material = material; } getMaterialType() { return MeshStandardMaterial; } /** * Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#materials * @param {number} materialIndex * @return {Promise} */ loadMaterial(materialIndex) { const parser = this; const json = this.json; const extensions = this.extensions; const materialDef = json.materials[materialIndex]; let materialType; const materialParams = {}; const materialExtensions = materialDef.extensions || {}; const pending = []; if (materialExtensions[EXTENSIONS.KHR_MATERIALS_PBR_SPECULAR_GLOSSINESS]) { const sgExtension = extensions[EXTENSIONS.KHR_MATERIALS_PBR_SPECULAR_GLOSSINESS]; materialType = sgExtension.getMaterialType(); pending.push(sgExtension.extendParams(materialParams, materialDef, parser)); } else if (materialExtensions[EXTENSIONS.KHR_MATERIALS_UNLIT]) { const kmuExtension = extensions[EXTENSIONS.KHR_MATERIALS_UNLIT]; materialType = kmuExtension.getMaterialType(); pending.push(kmuExtension.extendParams(materialParams, materialDef, parser)); } else { const metallicRoughness = materialDef.pbrMetallicRoughness || {}; materialParams.color = new Color(1, 1, 1); materialParams.opacity = 1; if (Array.isArray(metallicRoughness.baseColorFactor)) { const array = metallicRoughness.baseColorFactor; materialParams.color.fromArray(array); materialParams.opacity = array[3]; } if (metallicRoughness.baseColorTexture !== void 0) { pending.push(parser.assignTexture(materialParams, "map", metallicRoughness.baseColorTexture, sRGBEncoding)); } materialParams.metalness = metallicRoughness.metallicFactor !== void 0 ? metallicRoughness.metallicFactor : 1; materialParams.roughness = metallicRoughness.roughnessFactor !== void 0 ? metallicRoughness.roughnessFactor : 1; if (metallicRoughness.metallicRoughnessTexture !== void 0) { pending.push(parser.assignTexture(materialParams, "metalnessMap", metallicRoughness.metallicRoughnessTexture)); pending.push(parser.assignTexture(materialParams, "roughnessMap", metallicRoughness.metallicRoughnessTexture)); } materialType = this._invokeOne(function(ext) { return ext.getMaterialType && ext.getMaterialType(materialIndex); }); pending.push(Promise.all(this._invokeAll(function(ext) { return ext.extendMaterialParams && ext.extendMaterialParams(materialIndex, materialParams); }))); } if (materialDef.doubleSided === true) { materialParams.side = DoubleSide; } const alphaMode = materialDef.alphaMode || ALPHA_MODES.OPAQUE; if (alphaMode === ALPHA_MODES.BLEND) { materialParams.transparent = true; materialParams.depthWrite = false; } else { materialParams.transparent = false; if (alphaMode === ALPHA_MODES.MASK) { materialParams.alphaTest = materialDef.alphaCutoff !== void 0 ? materialDef.alphaCutoff : 0.5; } } if (materialDef.normalTexture !== void 0 && materialType !== MeshBasicMaterial) { pending.push(parser.assignTexture(materialParams, "normalMap", materialDef.normalTexture)); materialParams.normalScale = new Vector2(1, 1); if (materialDef.normalTexture.scale !== void 0) { const scale = materialDef.normalTexture.scale; materialParams.normalScale.set(scale, scale); } } if (materialDef.occlusionTexture !== void 0 && materialType !== MeshBasicMaterial) { pending.push(parser.assignTexture(materialParams, "aoMap", materialDef.occlusionTexture)); if (materialDef.occlusionTexture.strength !== void 0) { materialParams.aoMapIntensity = materialDef.occlusionTexture.strength; } } if (materialDef.emissiveFactor !== void 0 && materialType !== MeshBasicMaterial) { materialParams.emissive = new Color().fromArray(materialDef.emissiveFactor); } if (materialDef.emissiveTexture !== void 0 && materialType !== MeshBasicMaterial) { pending.push(parser.assignTexture(materialParams, "emissiveMap", materialDef.emissiveTexture, sRGBEncoding)); } return Promise.all(pending).then(function() { let material; if (materialType === GLTFMeshStandardSGMaterial) { material = extensions[EXTENSIONS.KHR_MATERIALS_PBR_SPECULAR_GLOSSINESS].createMaterial(materialParams); } else { material = new materialType(materialParams); } if (materialDef.name) material.name = materialDef.name; assignExtrasToUserData(material, materialDef); parser.associations.set(material, { materials: materialIndex }); if (materialDef.extensions) addUnknownExtensionsToUserData(extensions, material, materialDef); return material; }); } /** When Object3D instances are targeted by animation, they need unique names. */ createUniqueName(originalName) { const sanitizedName = PropertyBinding.sanitizeNodeName(originalName || ""); let name = sanitizedName; for (let i = 1; this.nodeNamesUsed[name]; ++i) { name = sanitizedName + "_" + i; } this.nodeNamesUsed[name] = true; return name; } /** * Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#geometry * * Creates BufferGeometries from primitives. * * @param {Array} primitives * @return {Promise>} */ loadGeometries(primitives) { const parser = this; const extensions = this.extensions; const cache2 = this.primitiveCache; function createDracoPrimitive(primitive) { return extensions[EXTENSIONS.KHR_DRACO_MESH_COMPRESSION].decodePrimitive(primitive, parser).then(function(geometry) { return addPrimitiveAttributes(geometry, primitive, parser); }); } const pending = []; for (let i = 0, il = primitives.length; i < il; i++) { const primitive = primitives[i]; const cacheKey = createPrimitiveKey(primitive); const cached = cache2[cacheKey]; if (cached) { pending.push(cached.promise); } else { let geometryPromise; if (primitive.extensions && primitive.extensions[EXTENSIONS.KHR_DRACO_MESH_COMPRESSION]) { geometryPromise = createDracoPrimitive(primitive); } else { geometryPromise = addPrimitiveAttributes(new BufferGeometry(), primitive, parser); } cache2[cacheKey] = { primitive, promise: geometryPromise }; pending.push(geometryPromise); } } return Promise.all(pending); } /** * Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#meshes * @param {number} meshIndex * @return {Promise} */ loadMesh(meshIndex) { const parser = this; const json = this.json; const extensions = this.extensions; const meshDef = json.meshes[meshIndex]; const primitives = meshDef.primitives; const pending = []; for (let i = 0, il = primitives.length; i < il; i++) { const material = primitives[i].material === void 0 ? createDefaultMaterial(this.cache) : this.getDependency("material", primitives[i].material); pending.push(material); } pending.push(parser.loadGeometries(primitives)); return Promise.all(pending).then(function(results) { const materials = results.slice(0, results.length - 1); const geometries = results[results.length - 1]; const meshes = []; for (let i = 0, il = geometries.length; i < il; i++) { const geometry = geometries[i]; const primitive = primitives[i]; let mesh; const material = materials[i]; if (primitive.mode === WEBGL_CONSTANTS.TRIANGLES || primitive.mode === WEBGL_CONSTANTS.TRIANGLE_STRIP || primitive.mode === WEBGL_CONSTANTS.TRIANGLE_FAN || primitive.mode === void 0) { mesh = meshDef.isSkinnedMesh === true ? new SkinnedMesh(geometry, material) : new Mesh(geometry, material); if (mesh.isSkinnedMesh === true && !mesh.geometry.attributes.skinWeight.normalized) { mesh.normalizeSkinWeights(); } if (primitive.mode === WEBGL_CONSTANTS.TRIANGLE_STRIP) { mesh.geometry = toTrianglesDrawMode(mesh.geometry, TriangleStripDrawMode); } else if (primitive.mode === WEBGL_CONSTANTS.TRIANGLE_FAN) { mesh.geometry = toTrianglesDrawMode(mesh.geometry, TriangleFanDrawMode); } } else if (primitive.mode === WEBGL_CONSTANTS.LINES) { mesh = new LineSegments(geometry, material); } else if (primitive.mode === WEBGL_CONSTANTS.LINE_STRIP) { mesh = new Line(geometry, material); } else if (primitive.mode === WEBGL_CONSTANTS.LINE_LOOP) { mesh = new LineLoop(geometry, material); } else if (primitive.mode === WEBGL_CONSTANTS.POINTS) { mesh = new Points(geometry, material); } else { throw new Error("THREE.GLTFLoader: Primitive mode unsupported: " + primitive.mode); } if (Object.keys(mesh.geometry.morphAttributes).length > 0) { updateMorphTargets(mesh, meshDef); } mesh.name = parser.createUniqueName(meshDef.name || "mesh_" + meshIndex); assignExtrasToUserData(mesh, meshDef); if (primitive.extensions) addUnknownExtensionsToUserData(extensions, mesh, primitive); parser.assignFinalMaterial(mesh); meshes.push(mesh); } for (let i = 0, il = meshes.length; i < il; i++) { parser.associations.set(meshes[i], { meshes: meshIndex, primitives: i }); } if (meshes.length === 1) { return meshes[0]; } const group = new Group(); parser.associations.set(group, { meshes: meshIndex }); for (let i = 0, il = meshes.length; i < il; i++) { group.add(meshes[i]); } return group; }); } /** * Specification: https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#cameras * @param {number} cameraIndex * @return {Promise} */ loadCamera(cameraIndex) { let camera2; const cameraDef = this.json.cameras[cameraIndex]; const params = cameraDef[cameraDef.type]; if (!params) { console.warn("THREE.GLTFLoader: Missing camera parameters."); return; } if (cameraDef.type === "perspective") { camera2 = new PerspectiveCamera(MathUtils.radToDeg(params.yfov), params.aspectRatio || 1, params.znear || 1, params.zfar || 2e6); } else if (cameraDef.type === "orthographic") { camera2 = new OrthographicCamera(-params.xmag, params.xmag, params.ymag, -params.ymag, params.znear, params.zfar); } if (cameraDef.name) camera2.name = this.createUniqueName(cameraDef.name); assignExtrasToUserData(camera2, cameraDef); return Promise.resolve(camera2); } /** * Specification: https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#skins * @param {number} skinIndex * @return {Promise} */ loadSkin(skinIndex) { const skinDef = this.json.skins[skinIndex]; const skinEntry = { joints: skinDef.joints }; if (skinDef.inverseBindMatrices === void 0) { return Promise.resolve(skinEntry); } return this.getDependency("accessor", skinDef.inverseBindMatrices).then(function(accessor) { skinEntry.inverseBindMatrices = accessor; return skinEntry; }); } /** * Specification: https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#animations * @param {number} animationIndex * @return {Promise} */ loadAnimation(animationIndex) { const json = this.json; const animationDef = json.animations[animationIndex]; const pendingNodes = []; const pendingInputAccessors = []; const pendingOutputAccessors = []; const pendingSamplers = []; const pendingTargets = []; for (let i = 0, il = animationDef.channels.length; i < il; i++) { const channel = animationDef.channels[i]; const sampler = animationDef.samplers[channel.sampler]; const target2 = channel.target; const name = target2.node; const input = animationDef.parameters !== void 0 ? animationDef.parameters[sampler.input] : sampler.input; const output = animationDef.parameters !== void 0 ? animationDef.parameters[sampler.output] : sampler.output; pendingNodes.push(this.getDependency("node", name)); pendingInputAccessors.push(this.getDependency("accessor", input)); pendingOutputAccessors.push(this.getDependency("accessor", output)); pendingSamplers.push(sampler); pendingTargets.push(target2); } return Promise.all([ Promise.all(pendingNodes), Promise.all(pendingInputAccessors), Promise.all(pendingOutputAccessors), Promise.all(pendingSamplers), Promise.all(pendingTargets) ]).then(function(dependencies) { const nodes = dependencies[0]; const inputAccessors = dependencies[1]; const outputAccessors = dependencies[2]; const samplers = dependencies[3]; const targets = dependencies[4]; const tracks = []; for (let i = 0, il = nodes.length; i < il; i++) { const node = nodes[i]; const inputAccessor = inputAccessors[i]; const outputAccessor = outputAccessors[i]; const sampler = samplers[i]; const target2 = targets[i]; if (node === void 0) continue; node.updateMatrix(); let TypedKeyframeTrack; switch (PATH_PROPERTIES[target2.path]) { case PATH_PROPERTIES.weights: TypedKeyframeTrack = NumberKeyframeTrack; break; case PATH_PROPERTIES.rotation: TypedKeyframeTrack = QuaternionKeyframeTrack; break; case PATH_PROPERTIES.position: case PATH_PROPERTIES.scale: default: TypedKeyframeTrack = VectorKeyframeTrack; break; } const targetName = node.name ? node.name : node.uuid; const interpolation = sampler.interpolation !== void 0 ? INTERPOLATION[sampler.interpolation] : InterpolateLinear; const targetNames = []; if (PATH_PROPERTIES[target2.path] === PATH_PROPERTIES.weights) { node.traverse(function(object) { if (object.morphTargetInfluences) { targetNames.push(object.name ? object.name : object.uuid); } }); } else { targetNames.push(targetName); } let outputArray = outputAccessor.array; if (outputAccessor.normalized) { const scale = getNormalizedComponentScale(outputArray.constructor); const scaled = new Float32Array(outputArray.length); for (let j = 0, jl = outputArray.length; j < jl; j++) { scaled[j] = outputArray[j] * scale; } outputArray = scaled; } for (let j = 0, jl = targetNames.length; j < jl; j++) { const track = new TypedKeyframeTrack( targetNames[j] + "." + PATH_PROPERTIES[target2.path], inputAccessor.array, outputArray, interpolation ); if (sampler.interpolation === "CUBICSPLINE") { track.createInterpolant = function InterpolantFactoryMethodGLTFCubicSpline(result) { const interpolantType = this instanceof QuaternionKeyframeTrack ? GLTFCubicSplineQuaternionInterpolant : GLTFCubicSplineInterpolant; return new interpolantType(this.times, this.values, this.getValueSize() / 3, result); }; track.createInterpolant.isInterpolantFactoryMethodGLTFCubicSpline = true; } tracks.push(track); } } const name = animationDef.name ? animationDef.name : "animation_" + animationIndex; return new AnimationClip(name, void 0, tracks); }); } createNodeMesh(nodeIndex) { const json = this.json; const parser = this; const nodeDef = json.nodes[nodeIndex]; if (nodeDef.mesh === void 0) return null; return parser.getDependency("mesh", nodeDef.mesh).then(function(mesh) { const node = parser._getNodeRef(parser.meshCache, nodeDef.mesh, mesh); if (nodeDef.weights !== void 0) { node.traverse(function(o) { if (!o.isMesh) return; for (let i = 0, il = nodeDef.weights.length; i < il; i++) { o.morphTargetInfluences[i] = nodeDef.weights[i]; } }); } return node; }); } /** * Specification: https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#nodes-and-hierarchy * @param {number} nodeIndex * @return {Promise} */ loadNode(nodeIndex) { const json = this.json; const extensions = this.extensions; const parser = this; const nodeDef = json.nodes[nodeIndex]; const nodeName = nodeDef.name ? parser.createUniqueName(nodeDef.name) : ""; return function() { const pending = []; const meshPromise = parser._invokeOne(function(ext) { return ext.createNodeMesh && ext.createNodeMesh(nodeIndex); }); if (meshPromise) { pending.push(meshPromise); } if (nodeDef.camera !== void 0) { pending.push(parser.getDependency("camera", nodeDef.camera).then(function(camera2) { return parser._getNodeRef(parser.cameraCache, nodeDef.camera, camera2); })); } parser._invokeAll(function(ext) { return ext.createNodeAttachment && ext.createNodeAttachment(nodeIndex); }).forEach(function(promise) { pending.push(promise); }); return Promise.all(pending); }().then(function(objects) { let node; if (nodeDef.isBone === true) { node = new Bone(); } else if (objects.length > 1) { node = new Group(); } else if (objects.length === 1) { node = objects[0]; } else { node = new Object3D(); } if (node !== objects[0]) { for (let i = 0, il = objects.length; i < il; i++) { node.add(objects[i]); } } if (nodeDef.name) { node.userData.name = nodeDef.name; node.name = nodeName; } assignExtrasToUserData(node, nodeDef); if (nodeDef.extensions) addUnknownExtensionsToUserData(extensions, node, nodeDef); if (nodeDef.matrix !== void 0) { const matrix = new Matrix4(); matrix.fromArray(nodeDef.matrix); node.applyMatrix4(matrix); } else { if (nodeDef.translation !== void 0) { node.position.fromArray(nodeDef.translation); } if (nodeDef.rotation !== void 0) { node.quaternion.fromArray(nodeDef.rotation); } if (nodeDef.scale !== void 0) { node.scale.fromArray(nodeDef.scale); } } if (!parser.associations.has(node)) { parser.associations.set(node, {}); } parser.associations.get(node).nodes = nodeIndex; return node; }); } /** * Specification: https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#scenes * @param {number} sceneIndex * @return {Promise} */ loadScene(sceneIndex) { const json = this.json; const extensions = this.extensions; const sceneDef = this.json.scenes[sceneIndex]; const parser = this; const scene = new Group(); if (sceneDef.name) scene.name = parser.createUniqueName(sceneDef.name); assignExtrasToUserData(scene, sceneDef); if (sceneDef.extensions) addUnknownExtensionsToUserData(extensions, scene, sceneDef); const nodeIds = sceneDef.nodes || []; const pending = []; for (let i = 0, il = nodeIds.length; i < il; i++) { pending.push(buildNodeHierarchy(nodeIds[i], scene, json, parser)); } return Promise.all(pending).then(function() { const reduceAssociations = (node) => { const reducedAssociations = /* @__PURE__ */ new Map(); for (const [key, value] of parser.associations) { if (key instanceof Material || key instanceof Texture) { reducedAssociations.set(key, value); } } node.traverse((node2) => { const mappings = parser.associations.get(node2); if (mappings != null) { reducedAssociations.set(node2, mappings); } }); return reducedAssociations; }; parser.associations = reduceAssociations(scene); return scene; }); } }; function buildNodeHierarchy(nodeId, parentObject, json, parser) { const nodeDef = json.nodes[nodeId]; return parser.getDependency("node", nodeId).then(function(node) { if (nodeDef.skin === void 0) return node; let skinEntry; return parser.getDependency("skin", nodeDef.skin).then(function(skin) { skinEntry = skin; const pendingJoints = []; for (let i = 0, il = skinEntry.joints.length; i < il; i++) { pendingJoints.push(parser.getDependency("node", skinEntry.joints[i])); } return Promise.all(pendingJoints); }).then(function(jointNodes) { node.traverse(function(mesh) { if (!mesh.isMesh) return; const bones = []; const boneInverses = []; for (let j = 0, jl = jointNodes.length; j < jl; j++) { const jointNode = jointNodes[j]; if (jointNode) { bones.push(jointNode); const mat = new Matrix4(); if (skinEntry.inverseBindMatrices !== void 0) { mat.fromArray(skinEntry.inverseBindMatrices.array, j * 16); } boneInverses.push(mat); } else { console.warn('THREE.GLTFLoader: Joint "%s" could not be found.', skinEntry.joints[j]); } } mesh.bind(new Skeleton(bones, boneInverses), mesh.matrixWorld); }); return node; }); }).then(function(node) { parentObject.add(node); const pending = []; if (nodeDef.children) { const children = nodeDef.children; for (let i = 0, il = children.length; i < il; i++) { const child = children[i]; pending.push(buildNodeHierarchy(child, node, json, parser)); } } return Promise.all(pending); }); } function computeBounds(geometry, primitiveDef, parser) { const attributes = primitiveDef.attributes; const box = new Box3(); if (attributes.POSITION !== void 0) { const accessor = parser.json.accessors[attributes.POSITION]; const min = accessor.min; const max2 = accessor.max; if (min !== void 0 && max2 !== void 0) { box.set( new Vector3(min[0], min[1], min[2]), new Vector3(max2[0], max2[1], max2[2]) ); if (accessor.normalized) { const boxScale = getNormalizedComponentScale(WEBGL_COMPONENT_TYPES[accessor.componentType]); box.min.multiplyScalar(boxScale); box.max.multiplyScalar(boxScale); } } else { console.warn("THREE.GLTFLoader: Missing min/max properties for accessor POSITION."); return; } } else { return; } const targets = primitiveDef.targets; if (targets !== void 0) { const maxDisplacement = new Vector3(); const vector = new Vector3(); for (let i = 0, il = targets.length; i < il; i++) { const target2 = targets[i]; if (target2.POSITION !== void 0) { const accessor = parser.json.accessors[target2.POSITION]; const min = accessor.min; const max2 = accessor.max; if (min !== void 0 && max2 !== void 0) { vector.setX(Math.max(Math.abs(min[0]), Math.abs(max2[0]))); vector.setY(Math.max(Math.abs(min[1]), Math.abs(max2[1]))); vector.setZ(Math.max(Math.abs(min[2]), Math.abs(max2[2]))); if (accessor.normalized) { const boxScale = getNormalizedComponentScale(WEBGL_COMPONENT_TYPES[accessor.componentType]); vector.multiplyScalar(boxScale); } maxDisplacement.max(vector); } else { console.warn("THREE.GLTFLoader: Missing min/max properties for accessor POSITION."); } } } box.expandByVector(maxDisplacement); } geometry.boundingBox = box; const sphere = new Sphere(); box.getCenter(sphere.center); sphere.radius = box.min.distanceTo(box.max) / 2; geometry.boundingSphere = sphere; } function addPrimitiveAttributes(geometry, primitiveDef, parser) { const attributes = primitiveDef.attributes; const pending = []; function assignAttributeAccessor(accessorIndex, attributeName) { return parser.getDependency("accessor", accessorIndex).then(function(accessor) { geometry.setAttribute(attributeName, accessor); }); } for (const gltfAttributeName in attributes) { const threeAttributeName = ATTRIBUTES[gltfAttributeName] || gltfAttributeName.toLowerCase(); if (threeAttributeName in geometry.attributes) continue; pending.push(assignAttributeAccessor(attributes[gltfAttributeName], threeAttributeName)); } if (primitiveDef.indices !== void 0 && !geometry.index) { const accessor = parser.getDependency("accessor", primitiveDef.indices).then(function(accessor2) { geometry.setIndex(accessor2); }); pending.push(accessor); } assignExtrasToUserData(geometry, primitiveDef); computeBounds(geometry, primitiveDef, parser); return Promise.all(pending).then(function() { return primitiveDef.targets !== void 0 ? addMorphTargets(geometry, primitiveDef.targets, parser) : geometry; }); } function toTrianglesDrawMode(geometry, drawMode) { let index = geometry.getIndex(); if (index === null) { const indices = []; const position = geometry.getAttribute("position"); if (position !== void 0) { for (let i = 0; i < position.count; i++) { indices.push(i); } geometry.setIndex(indices); index = geometry.getIndex(); } else { console.error("THREE.GLTFLoader.toTrianglesDrawMode(): Undefined position attribute. Processing not possible."); return geometry; } } const numberOfTriangles = index.count - 2; const newIndices = []; if (drawMode === TriangleFanDrawMode) { for (let i = 1; i <= numberOfTriangles; i++) { newIndices.push(index.getX(0)); newIndices.push(index.getX(i)); newIndices.push(index.getX(i + 1)); } } else { for (let i = 0; i < numberOfTriangles; i++) { if (i % 2 === 0) { newIndices.push(index.getX(i)); newIndices.push(index.getX(i + 1)); newIndices.push(index.getX(i + 2)); } else { newIndices.push(index.getX(i + 2)); newIndices.push(index.getX(i + 1)); newIndices.push(index.getX(i)); } } } if (newIndices.length / 3 !== numberOfTriangles) { console.error("THREE.GLTFLoader.toTrianglesDrawMode(): Unable to generate correct amount of triangles."); } const newGeometry = geometry.clone(); newGeometry.setIndex(newIndices); return newGeometry; } // node_modules/three/examples/jsm/utils/WorkerPool.js var WorkerPool = class { constructor(pool = 4) { this.pool = pool; this.queue = []; this.workers = []; this.workersResolve = []; this.workerStatus = 0; } _initWorker(workerId) { if (!this.workers[workerId]) { const worker = this.workerCreator(); worker.addEventListener("message", this._onMessage.bind(this, workerId)); this.workers[workerId] = worker; } } _getIdleWorker() { for (let i = 0; i < this.pool; i++) if (!(this.workerStatus & 1 << i)) return i; return -1; } _onMessage(workerId, msg) { const resolve = this.workersResolve[workerId]; resolve && resolve(msg); if (this.queue.length) { const { resolve: resolve2, msg: msg2, transfer } = this.queue.shift(); this.workersResolve[workerId] = resolve2; this.workers[workerId].postMessage(msg2, transfer); } else { this.workerStatus ^= 1 << workerId; } } setWorkerCreator(workerCreator) { this.workerCreator = workerCreator; } setWorkerLimit(pool) { this.pool = pool; } postMessage(msg, transfer) { return new Promise((resolve) => { const workerId = this._getIdleWorker(); if (workerId !== -1) { this._initWorker(workerId); this.workerStatus |= 1 << workerId; this.workersResolve[workerId] = resolve; this.workers[workerId].postMessage(msg, transfer); } else { this.queue.push({ resolve, msg, transfer }); } }); } dispose() { this.workers.forEach((worker) => worker.terminate()); this.workersResolve.length = 0; this.workers.length = 0; this.queue.length = 0; this.workerStatus = 0; } }; // node_modules/three/examples/jsm/libs/ktx-parse.module.js var t = 0; var n = 2; var p = 1; var x = 2; var nt = 0; var ct = 9; var gt = 15; var yt = 16; var dt = 22; var Ot = 37; var Ft = 43; var $t = 76; var se = 83; var pe = 97; var xe = 100; var de = 103; var Ae = 109; var Si = class { constructor() { this.vkFormat = 0, this.typeSize = 1, this.pixelWidth = 0, this.pixelHeight = 0, this.pixelDepth = 0, this.layerCount = 0, this.faceCount = 1, this.supercompressionScheme = 0, this.levels = [], this.dataFormatDescriptor = [{ vendorId: 0, descriptorType: 0, descriptorBlockSize: 0, versionNumber: 2, colorModel: 0, colorPrimaries: 1, transferFunction: 2, flags: 0, texelBlockDimension: [0, 0, 0, 0], bytesPlane: [0, 0, 0, 0, 0, 0, 0, 0], samples: [] }], this.keyValue = {}, this.globalData = null; } }; var Ii = class { constructor(t2, e, n2, i) { this._dataView = new DataView(t2.buffer, t2.byteOffset + e, n2), this._littleEndian = i, this._offset = 0; } _nextUint8() { const t2 = this._dataView.getUint8(this._offset); return this._offset += 1, t2; } _nextUint16() { const t2 = this._dataView.getUint16(this._offset, this._littleEndian); return this._offset += 2, t2; } _nextUint32() { const t2 = this._dataView.getUint32(this._offset, this._littleEndian); return this._offset += 4, t2; } _nextUint64() { const t2 = this._dataView.getUint32(this._offset, this._littleEndian) + 2 ** 32 * this._dataView.getUint32(this._offset + 4, this._littleEndian); return this._offset += 8, t2; } _nextInt32() { const t2 = this._dataView.getInt32(this._offset, this._littleEndian); return this._offset += 4, t2; } _skip(t2) { return this._offset += t2, this; } _scan(t2, e = 0) { const n2 = this._offset; let i = 0; for (; this._dataView.getUint8(this._offset) !== e && i < t2; ) i++, this._offset++; return i < t2 && this._offset++, new Uint8Array(this._dataView.buffer, this._dataView.byteOffset + n2, i); } }; var Oi = new Uint8Array([0]); var Ti = [171, 75, 84, 88, 32, 50, 48, 187, 13, 10, 26, 10]; function Ei(t2) { return "undefined" != typeof TextDecoder ? new TextDecoder().decode(t2) : Buffer.from(t2).toString("utf8"); } function Pi(t2) { const e = new Uint8Array(t2.buffer, t2.byteOffset, Ti.length); if (e[0] !== Ti[0] || e[1] !== Ti[1] || e[2] !== Ti[2] || e[3] !== Ti[3] || e[4] !== Ti[4] || e[5] !== Ti[5] || e[6] !== Ti[6] || e[7] !== Ti[7] || e[8] !== Ti[8] || e[9] !== Ti[9] || e[10] !== Ti[10] || e[11] !== Ti[11]) throw new Error("Missing KTX 2.0 identifier."); const n2 = new Si(), i = 17 * Uint32Array.BYTES_PER_ELEMENT, s = new Ii(t2, Ti.length, i, true); n2.vkFormat = s._nextUint32(), n2.typeSize = s._nextUint32(), n2.pixelWidth = s._nextUint32(), n2.pixelHeight = s._nextUint32(), n2.pixelDepth = s._nextUint32(), n2.layerCount = s._nextUint32(), n2.faceCount = s._nextUint32(); const a = s._nextUint32(); n2.supercompressionScheme = s._nextUint32(); const r = s._nextUint32(), o = s._nextUint32(), l = s._nextUint32(), f = s._nextUint32(), U = s._nextUint64(), c = s._nextUint64(), h = new Ii(t2, Ti.length + i, 3 * a * 8, true); for (let e2 = 0; e2 < a; e2++) n2.levels.push({ levelData: new Uint8Array(t2.buffer, t2.byteOffset + h._nextUint64(), h._nextUint64()), uncompressedByteLength: h._nextUint64() }); const _ = new Ii(t2, r, o, true), p2 = { vendorId: _._skip(4)._nextUint16(), descriptorType: _._nextUint16(), versionNumber: _._nextUint16(), descriptorBlockSize: _._nextUint16(), colorModel: _._nextUint8(), colorPrimaries: _._nextUint8(), transferFunction: _._nextUint8(), flags: _._nextUint8(), texelBlockDimension: [_._nextUint8(), _._nextUint8(), _._nextUint8(), _._nextUint8()], bytesPlane: [_._nextUint8(), _._nextUint8(), _._nextUint8(), _._nextUint8(), _._nextUint8(), _._nextUint8(), _._nextUint8(), _._nextUint8()], samples: [] }, g2 = (p2.descriptorBlockSize / 4 - 6) / 4; for (let t3 = 0; t3 < g2; t3++) { const e2 = { bitOffset: _._nextUint16(), bitLength: _._nextUint8(), channelType: _._nextUint8(), samplePosition: [_._nextUint8(), _._nextUint8(), _._nextUint8(), _._nextUint8()], sampleLower: -Infinity, sampleUpper: Infinity }; 64 & e2.channelType ? (e2.sampleLower = _._nextInt32(), e2.sampleUpper = _._nextInt32()) : (e2.sampleLower = _._nextUint32(), e2.sampleUpper = _._nextUint32()), p2.samples[t3] = e2; } n2.dataFormatDescriptor.length = 0, n2.dataFormatDescriptor.push(p2); const y = new Ii(t2, l, f, true); for (; y._offset < f; ) { const t3 = y._nextUint32(), e2 = y._scan(t3), i2 = Ei(e2), s2 = y._scan(t3 - e2.byteLength); n2.keyValue[i2] = i2.match(/^ktx/i) ? Ei(s2) : s2, y._offset % 4 && y._skip(4 - y._offset % 4); } if (c <= 0) return n2; const x2 = new Ii(t2, U, c, true), u = x2._nextUint16(), b = x2._nextUint16(), d = x2._nextUint32(), m = x2._nextUint32(), w = x2._nextUint32(), D = x2._nextUint32(), B2 = []; for (let t3 = 0; t3 < a; t3++) B2.push({ imageFlags: x2._nextUint32(), rgbSliceByteOffset: x2._nextUint32(), rgbSliceByteLength: x2._nextUint32(), alphaSliceByteOffset: x2._nextUint32(), alphaSliceByteLength: x2._nextUint32() }); const L = U + x2._offset, A2 = L + d, k = A2 + m, v = k + w, S = new Uint8Array(t2.buffer, t2.byteOffset + L, d), I2 = new Uint8Array(t2.buffer, t2.byteOffset + A2, m), O = new Uint8Array(t2.buffer, t2.byteOffset + k, w), T = new Uint8Array(t2.buffer, t2.byteOffset + v, D); return n2.globalData = { endpointCount: u, selectorCount: b, imageDescs: B2, endpointsData: S, selectorsData: I2, tablesData: O, extendedData: T }, n2; } // node_modules/three/examples/jsm/libs/zstddec.module.js var A; var I; var B; var g = { env: { emscripten_notify_memory_growth: function(A2) { B = new Uint8Array(I.exports.memory.buffer); } } }; var Q = class { init() { return A || (A = "undefined" != typeof fetch ? fetch("data:application/wasm;base64," + C).then((A2) => A2.arrayBuffer()).then((A2) => WebAssembly.instantiate(A2, g)).then(this._init) : WebAssembly.instantiate(Buffer.from(C, "base64"), g).then(this._init), A); } _init(A2) { I = A2.instance, g.env.emscripten_notify_memory_growth(0); } decode(A2, g2 = 0) { if (!I) throw new Error("ZSTDDecoder: Await .init() before decoding."); const Q2 = A2.byteLength, C2 = I.exports.malloc(Q2); B.set(A2, C2), g2 = g2 || Number(I.exports.ZSTD_findDecompressedSize(C2, Q2)); const E = I.exports.malloc(g2), i = I.exports.ZSTD_decompress(E, g2, C2, Q2), D = B.slice(E, E + i); return I.exports.free(C2), I.exports.free(E), D; } }; var C = "AGFzbQEAAAABpQEVYAF/AX9gAn9/AGADf39/AX9gBX9/f39/AX9gAX8AYAJ/fwF/YAR/f39/AX9gA39/fwBgBn9/f39/fwF/YAd/f39/f39/AX9gAn9/AX5gAn5+AX5gAABgBX9/f39/AGAGf39/f39/AGAIf39/f39/f38AYAl/f39/f39/f38AYAABf2AIf39/f39/f38Bf2ANf39/f39/f39/f39/fwF/YAF/AX4CJwEDZW52H2Vtc2NyaXB0ZW5fbm90aWZ5X21lbW9yeV9ncm93dGgABANpaAEFAAAFAgEFCwACAQABAgIFBQcAAwABDgsBAQcAEhMHAAUBDAQEAAANBwQCAgYCBAgDAwMDBgEACQkHBgICAAYGAgQUBwYGAwIGAAMCAQgBBwUGCgoEEQAEBAEIAwgDBQgDEA8IAAcABAUBcAECAgUEAQCAAgYJAX8BQaCgwAILB2AHBm1lbW9yeQIABm1hbGxvYwAoBGZyZWUAJgxaU1REX2lzRXJyb3IAaBlaU1REX2ZpbmREZWNvbXByZXNzZWRTaXplAFQPWlNURF9kZWNvbXByZXNzAEoGX3N0YXJ0ACQJBwEAQQELASQKussBaA8AIAAgACgCBCABajYCBAsZACAAKAIAIAAoAgRBH3F0QQAgAWtBH3F2CwgAIABBiH9LC34BBH9BAyEBIAAoAgQiA0EgTQRAIAAoAggiASAAKAIQTwRAIAAQDQ8LIAAoAgwiAiABRgRAQQFBAiADQSBJGw8LIAAgASABIAJrIANBA3YiBCABIARrIAJJIgEbIgJrIgQ2AgggACADIAJBA3RrNgIEIAAgBCgAADYCAAsgAQsUAQF/IAAgARACIQIgACABEAEgAgv3AQECfyACRQRAIABCADcCACAAQQA2AhAgAEIANwIIQbh/DwsgACABNgIMIAAgAUEEajYCECACQQRPBEAgACABIAJqIgFBfGoiAzYCCCAAIAMoAAA2AgAgAUF/ai0AACIBBEAgAEEIIAEQFGs2AgQgAg8LIABBADYCBEF/DwsgACABNgIIIAAgAS0AACIDNgIAIAJBfmoiBEEBTQRAIARBAWtFBEAgACABLQACQRB0IANyIgM2AgALIAAgAS0AAUEIdCADajYCAAsgASACakF/ai0AACIBRQRAIABBADYCBEFsDwsgAEEoIAEQFCACQQN0ams2AgQgAgsWACAAIAEpAAA3AAAgACABKQAINwAICy8BAX8gAUECdEGgHWooAgAgACgCAEEgIAEgACgCBGprQR9xdnEhAiAAIAEQASACCyEAIAFCz9bTvtLHq9lCfiAAfEIfiUKHla+vmLbem55/fgsdAQF/IAAoAgggACgCDEYEfyAAKAIEQSBGBUEACwuCBAEDfyACQYDAAE8EQCAAIAEgAhBnIAAPCyAAIAJqIQMCQCAAIAFzQQNxRQRAAkAgAkEBSARAIAAhAgwBCyAAQQNxRQRAIAAhAgwBCyAAIQIDQCACIAEtAAA6AAAgAUEBaiEBIAJBAWoiAiADTw0BIAJBA3ENAAsLAkAgA0F8cSIEQcAASQ0AIAIgBEFAaiIFSw0AA0AgAiABKAIANgIAIAIgASgCBDYCBCACIAEoAgg2AgggAiABKAIMNgIMIAIgASgCEDYCECACIAEoAhQ2AhQgAiABKAIYNgIYIAIgASgCHDYCHCACIAEoAiA2AiAgAiABKAIkNgIkIAIgASgCKDYCKCACIAEoAiw2AiwgAiABKAIwNgIwIAIgASgCNDYCNCACIAEoAjg2AjggAiABKAI8NgI8IAFBQGshASACQUBrIgIgBU0NAAsLIAIgBE8NAQNAIAIgASgCADYCACABQQRqIQEgAkEEaiICIARJDQALDAELIANBBEkEQCAAIQIMAQsgA0F8aiIEIABJBEAgACECDAELIAAhAgNAIAIgAS0AADoAACACIAEtAAE6AAEgAiABLQACOgACIAIgAS0AAzoAAyABQQRqIQEgAkEEaiICIARNDQALCyACIANJBEADQCACIAEtAAA6AAAgAUEBaiEBIAJBAWoiAiADRw0ACwsgAAsMACAAIAEpAAA3AAALQQECfyAAKAIIIgEgACgCEEkEQEEDDwsgACAAKAIEIgJBB3E2AgQgACABIAJBA3ZrIgE2AgggACABKAAANgIAQQALDAAgACABKAIANgAAC/cCAQJ/AkAgACABRg0AAkAgASACaiAASwRAIAAgAmoiBCABSw0BCyAAIAEgAhALDwsgACABc0EDcSEDAkACQCAAIAFJBEAgAwRAIAAhAwwDCyAAQQNxRQRAIAAhAwwCCyAAIQMDQCACRQ0EIAMgAS0AADoAACABQQFqIQEgAkF/aiECIANBAWoiA0EDcQ0ACwwBCwJAIAMNACAEQQNxBEADQCACRQ0FIAAgAkF/aiICaiIDIAEgAmotAAA6AAAgA0EDcQ0ACwsgAkEDTQ0AA0AgACACQXxqIgJqIAEgAmooAgA2AgAgAkEDSw0ACwsgAkUNAgNAIAAgAkF/aiICaiABIAJqLQAAOgAAIAINAAsMAgsgAkEDTQ0AIAIhBANAIAMgASgCADYCACABQQRqIQEgA0EEaiEDIARBfGoiBEEDSw0ACyACQQNxIQILIAJFDQADQCADIAEtAAA6AAAgA0EBaiEDIAFBAWohASACQX9qIgINAAsLIAAL8wICAn8BfgJAIAJFDQAgACACaiIDQX9qIAE6AAAgACABOgAAIAJBA0kNACADQX5qIAE6AAAgACABOgABIANBfWogAToAACAAIAE6AAIgAkEHSQ0AIANBfGogAToAACAAIAE6AAMgAkEJSQ0AIABBACAAa0EDcSIEaiIDIAFB/wFxQYGChAhsIgE2AgAgAyACIARrQXxxIgRqIgJBfGogATYCACAEQQlJDQAgAyABNgIIIAMgATYCBCACQXhqIAE2AgAgAkF0aiABNgIAIARBGUkNACADIAE2AhggAyABNgIUIAMgATYCECADIAE2AgwgAkFwaiABNgIAIAJBbGogATYCACACQWhqIAE2AgAgAkFkaiABNgIAIAQgA0EEcUEYciIEayICQSBJDQAgAa0iBUIghiAFhCEFIAMgBGohAQNAIAEgBTcDGCABIAU3AxAgASAFNwMIIAEgBTcDACABQSBqIQEgAkFgaiICQR9LDQALCyAACy8BAn8gACgCBCAAKAIAQQJ0aiICLQACIQMgACACLwEAIAEgAi0AAxAIajYCACADCy8BAn8gACgCBCAAKAIAQQJ0aiICLQACIQMgACACLwEAIAEgAi0AAxAFajYCACADCx8AIAAgASACKAIEEAg2AgAgARAEGiAAIAJBCGo2AgQLCAAgAGdBH3MLugUBDX8jAEEQayIKJAACfyAEQQNNBEAgCkEANgIMIApBDGogAyAEEAsaIAAgASACIApBDGpBBBAVIgBBbCAAEAMbIAAgACAESxsMAQsgAEEAIAEoAgBBAXRBAmoQECENQVQgAygAACIGQQ9xIgBBCksNABogAiAAQQVqNgIAIAMgBGoiAkF8aiEMIAJBeWohDiACQXtqIRAgAEEGaiELQQQhBSAGQQR2IQRBICAAdCIAQQFyIQkgASgCACEPQQAhAiADIQYCQANAIAlBAkggAiAPS3JFBEAgAiEHAkAgCARAA0AgBEH//wNxQf//A0YEQCAHQRhqIQcgBiAQSQR/IAZBAmoiBigAACAFdgUgBUEQaiEFIARBEHYLIQQMAQsLA0AgBEEDcSIIQQNGBEAgBUECaiEFIARBAnYhBCAHQQNqIQcMAQsLIAcgCGoiByAPSw0EIAVBAmohBQNAIAIgB0kEQCANIAJBAXRqQQA7AQAgAkEBaiECDAELCyAGIA5LQQAgBiAFQQN1aiIHIAxLG0UEQCAHKAAAIAVBB3EiBXYhBAwCCyAEQQJ2IQQLIAYhBwsCfyALQX9qIAQgAEF/anEiBiAAQQF0QX9qIgggCWsiEUkNABogBCAIcSIEQQAgESAEIABIG2shBiALCyEIIA0gAkEBdGogBkF/aiIEOwEAIAlBASAGayAEIAZBAUgbayEJA0AgCSAASARAIABBAXUhACALQX9qIQsMAQsLAn8gByAOS0EAIAcgBSAIaiIFQQN1aiIGIAxLG0UEQCAFQQdxDAELIAUgDCIGIAdrQQN0awshBSACQQFqIQIgBEUhCCAGKAAAIAVBH3F2IQQMAQsLQWwgCUEBRyAFQSBKcg0BGiABIAJBf2o2AgAgBiAFQQdqQQN1aiADawwBC0FQCyEAIApBEGokACAACwkAQQFBBSAAGwsMACAAIAEoAAA2AAALqgMBCn8jAEHwAGsiCiQAIAJBAWohDiAAQQhqIQtBgIAEIAVBf2p0QRB1IQxBACECQQEhBkEBIAV0IglBf2oiDyEIA0AgAiAORkUEQAJAIAEgAkEBdCINai8BACIHQf//A0YEQCALIAhBA3RqIAI2AgQgCEF/aiEIQQEhBwwBCyAGQQAgDCAHQRB0QRB1ShshBgsgCiANaiAHOwEAIAJBAWohAgwBCwsgACAFNgIEIAAgBjYCACAJQQN2IAlBAXZqQQNqIQxBACEAQQAhBkEAIQIDQCAGIA5GBEADQAJAIAAgCUYNACAKIAsgAEEDdGoiASgCBCIGQQF0aiICIAIvAQAiAkEBajsBACABIAUgAhAUayIIOgADIAEgAiAIQf8BcXQgCWs7AQAgASAEIAZBAnQiAmooAgA6AAIgASACIANqKAIANgIEIABBAWohAAwBCwsFIAEgBkEBdGouAQAhDUEAIQcDQCAHIA1ORQRAIAsgAkEDdGogBjYCBANAIAIgDGogD3EiAiAISw0ACyAHQQFqIQcMAQsLIAZBAWohBgwBCwsgCkHwAGokAAsjAEIAIAEQCSAAhUKHla+vmLbem55/fkLj3MqV/M7y9YV/fAsQACAAQn43AwggACABNgIACyQBAX8gAARAIAEoAgQiAgRAIAEoAgggACACEQEADwsgABAmCwsfACAAIAEgAi8BABAINgIAIAEQBBogACACQQRqNgIEC0oBAX9BoCAoAgAiASAAaiIAQX9MBEBBiCBBMDYCAEF/DwsCQCAAPwBBEHRNDQAgABBmDQBBiCBBMDYCAEF/DwtBoCAgADYCACABC9cBAQh/Qbp/IQoCQCACKAIEIgggAigCACIJaiIOIAEgAGtLDQBBbCEKIAkgBCADKAIAIgtrSw0AIAAgCWoiBCACKAIIIgxrIQ0gACABQWBqIg8gCyAJQQAQKSADIAkgC2o2AgACQAJAIAwgBCAFa00EQCANIQUMAQsgDCAEIAZrSw0CIAcgDSAFayIAaiIBIAhqIAdNBEAgBCABIAgQDxoMAgsgBCABQQAgAGsQDyEBIAIgACAIaiIINgIEIAEgAGshBAsgBCAPIAUgCEEBECkLIA4hCgsgCgubAgEBfyMAQYABayINJAAgDSADNgJ8AkAgAkEDSwRAQX8hCQwBCwJAAkACQAJAIAJBAWsOAwADAgELIAZFBEBBuH8hCQwEC0FsIQkgBS0AACICIANLDQMgACAHIAJBAnQiAmooAgAgAiAIaigCABA7IAEgADYCAEEBIQkMAwsgASAJNgIAQQAhCQwCCyAKRQRAQWwhCQwCC0EAIQkgC0UgDEEZSHINAUEIIAR0QQhqIQBBACECA0AgAiAATw0CIAJBQGshAgwAAAsAC0FsIQkgDSANQfwAaiANQfgAaiAFIAYQFSICEAMNACANKAJ4IgMgBEsNACAAIA0gDSgCfCAHIAggAxAYIAEgADYCACACIQkLIA1BgAFqJAAgCQsLACAAIAEgAhALGgsQACAALwAAIAAtAAJBEHRyCy8AAn9BuH8gAUEISQ0AGkFyIAAoAAQiAEF3Sw0AGkG4fyAAQQhqIgAgACABSxsLCwkAIAAgATsAAAsDAAELigYBBX8gACAAKAIAIgVBfnE2AgBBACAAIAVBAXZqQYQgKAIAIgQgAEYbIQECQAJAIAAoAgQiAkUNACACKAIAIgNBAXENACACQQhqIgUgA0EBdkF4aiIDQQggA0EISxtnQR9zQQJ0QYAfaiIDKAIARgRAIAMgAigCDDYCAAsgAigCCCIDBEAgAyACKAIMNgIECyACKAIMIgMEQCADIAIoAgg2AgALIAIgAigCACAAKAIAQX5xajYCAEGEICEAAkACQCABRQ0AIAEgAjYCBCABKAIAIgNBAXENASADQQF2QXhqIgNBCCADQQhLG2dBH3NBAnRBgB9qIgMoAgAgAUEIakYEQCADIAEoAgw2AgALIAEoAggiAwRAIAMgASgCDDYCBAsgASgCDCIDBEAgAyABKAIINgIAQYQgKAIAIQQLIAIgAigCACABKAIAQX5xajYCACABIARGDQAgASABKAIAQQF2akEEaiEACyAAIAI2AgALIAIoAgBBAXZBeGoiAEEIIABBCEsbZ0Efc0ECdEGAH2oiASgCACEAIAEgBTYCACACIAA2AgwgAkEANgIIIABFDQEgACAFNgIADwsCQCABRQ0AIAEoAgAiAkEBcQ0AIAJBAXZBeGoiAkEIIAJBCEsbZ0Efc0ECdEGAH2oiAigCACABQQhqRgRAIAIgASgCDDYCAAsgASgCCCICBEAgAiABKAIMNgIECyABKAIMIgIEQCACIAEoAgg2AgBBhCAoAgAhBAsgACAAKAIAIAEoAgBBfnFqIgI2AgACQCABIARHBEAgASABKAIAQQF2aiAANgIEIAAoAgAhAgwBC0GEICAANgIACyACQQF2QXhqIgFBCCABQQhLG2dBH3NBAnRBgB9qIgIoAgAhASACIABBCGoiAjYCACAAIAE2AgwgAEEANgIIIAFFDQEgASACNgIADwsgBUEBdkF4aiIBQQggAUEISxtnQR9zQQJ0QYAfaiICKAIAIQEgAiAAQQhqIgI2AgAgACABNgIMIABBADYCCCABRQ0AIAEgAjYCAAsLDgAgAARAIABBeGoQJQsLgAIBA38CQCAAQQ9qQXhxQYQgKAIAKAIAQQF2ayICEB1Bf0YNAAJAQYQgKAIAIgAoAgAiAUEBcQ0AIAFBAXZBeGoiAUEIIAFBCEsbZ0Efc0ECdEGAH2oiASgCACAAQQhqRgRAIAEgACgCDDYCAAsgACgCCCIBBEAgASAAKAIMNgIECyAAKAIMIgFFDQAgASAAKAIINgIAC0EBIQEgACAAKAIAIAJBAXRqIgI2AgAgAkEBcQ0AIAJBAXZBeGoiAkEIIAJBCEsbZ0Efc0ECdEGAH2oiAygCACECIAMgAEEIaiIDNgIAIAAgAjYCDCAAQQA2AgggAkUNACACIAM2AgALIAELtwIBA38CQAJAIABBASAAGyICEDgiAA0AAkACQEGEICgCACIARQ0AIAAoAgAiA0EBcQ0AIAAgA0EBcjYCACADQQF2QXhqIgFBCCABQQhLG2dBH3NBAnRBgB9qIgEoAgAgAEEIakYEQCABIAAoAgw2AgALIAAoAggiAQRAIAEgACgCDDYCBAsgACgCDCIBBEAgASAAKAIINgIACyACECchAkEAIQFBhCAoAgAhACACDQEgACAAKAIAQX5xNgIAQQAPCyACQQ9qQXhxIgMQHSICQX9GDQIgAkEHakF4cSIAIAJHBEAgACACaxAdQX9GDQMLAkBBhCAoAgAiAUUEQEGAICAANgIADAELIAAgATYCBAtBhCAgADYCACAAIANBAXRBAXI2AgAMAQsgAEUNAQsgAEEIaiEBCyABC7kDAQJ/IAAgA2ohBQJAIANBB0wEQANAIAAgBU8NAiAAIAItAAA6AAAgAEEBaiEAIAJBAWohAgwAAAsACyAEQQFGBEACQCAAIAJrIgZBB00EQCAAIAItAAA6AAAgACACLQABOgABIAAgAi0AAjoAAiAAIAItAAM6AAMgAEEEaiACIAZBAnQiBkHAHmooAgBqIgIQFyACIAZB4B5qKAIAayECDAELIAAgAhAMCyACQQhqIQIgAEEIaiEACwJAAkACQAJAIAUgAU0EQCAAIANqIQEgBEEBRyAAIAJrQQ9Kcg0BA0AgACACEAwgAkEIaiECIABBCGoiACABSQ0ACwwFCyAAIAFLBEAgACEBDAQLIARBAUcgACACa0EPSnINASAAIQMgAiEEA0AgAyAEEAwgBEEIaiEEIANBCGoiAyABSQ0ACwwCCwNAIAAgAhAHIAJBEGohAiAAQRBqIgAgAUkNAAsMAwsgACEDIAIhBANAIAMgBBAHIARBEGohBCADQRBqIgMgAUkNAAsLIAIgASAAa2ohAgsDQCABIAVPDQEgASACLQAAOgAAIAFBAWohASACQQFqIQIMAAALAAsLQQECfyAAIAAoArjgASIDNgLE4AEgACgCvOABIQQgACABNgK84AEgACABIAJqNgK44AEgACABIAQgA2tqNgLA4AELpgEBAX8gACAAKALs4QEQFjYCyOABIABCADcD+OABIABCADcDuOABIABBwOABakIANwMAIABBqNAAaiIBQYyAgOAANgIAIABBADYCmOIBIABCADcDiOEBIABCAzcDgOEBIABBrNABakHgEikCADcCACAAQbTQAWpB6BIoAgA2AgAgACABNgIMIAAgAEGYIGo2AgggACAAQaAwajYCBCAAIABBEGo2AgALYQEBf0G4fyEDAkAgAUEDSQ0AIAIgABAhIgFBA3YiADYCCCACIAFBAXE2AgQgAiABQQF2QQNxIgM2AgACQCADQX9qIgFBAksNAAJAIAFBAWsOAgEAAgtBbA8LIAAhAwsgAwsMACAAIAEgAkEAEC4LiAQCA38CfiADEBYhBCAAQQBBKBAQIQAgBCACSwRAIAQPCyABRQRAQX8PCwJAAkAgA0EBRg0AIAEoAAAiBkGo6r5pRg0AQXYhAyAGQXBxQdDUtMIBRw0BQQghAyACQQhJDQEgAEEAQSgQECEAIAEoAAQhASAAQQE2AhQgACABrTcDAEEADwsgASACIAMQLyIDIAJLDQAgACADNgIYQXIhAyABIARqIgVBf2otAAAiAkEIcQ0AIAJBIHEiBkUEQEFwIQMgBS0AACIFQacBSw0BIAVBB3GtQgEgBUEDdkEKaq2GIgdCA4h+IAd8IQggBEEBaiEECyACQQZ2IQMgAkECdiEFAkAgAkEDcUF/aiICQQJLBEBBACECDAELAkACQAJAIAJBAWsOAgECAAsgASAEai0AACECIARBAWohBAwCCyABIARqLwAAIQIgBEECaiEEDAELIAEgBGooAAAhAiAEQQRqIQQLIAVBAXEhBQJ+AkACQAJAIANBf2oiA0ECTQRAIANBAWsOAgIDAQtCfyAGRQ0DGiABIARqMQAADAMLIAEgBGovAACtQoACfAwCCyABIARqKAAArQwBCyABIARqKQAACyEHIAAgBTYCICAAIAI2AhwgACAHNwMAQQAhAyAAQQA2AhQgACAHIAggBhsiBzcDCCAAIAdCgIAIIAdCgIAIVBs+AhALIAMLWwEBf0G4fyEDIAIQFiICIAFNBH8gACACakF/ai0AACIAQQNxQQJ0QaAeaigCACACaiAAQQZ2IgFBAnRBsB5qKAIAaiAAQSBxIgBFaiABRSAAQQV2cWoFQbh/CwsdACAAKAKQ4gEQWiAAQQA2AqDiASAAQgA3A5DiAQu1AwEFfyMAQZACayIKJABBuH8hBgJAIAVFDQAgBCwAACIIQf8BcSEHAkAgCEF/TARAIAdBgn9qQQF2IgggBU8NAkFsIQYgB0GBf2oiBUGAAk8NAiAEQQFqIQdBACEGA0AgBiAFTwRAIAUhBiAIIQcMAwUgACAGaiAHIAZBAXZqIgQtAABBBHY6AAAgACAGQQFyaiAELQAAQQ9xOgAAIAZBAmohBgwBCwAACwALIAcgBU8NASAAIARBAWogByAKEFMiBhADDQELIAYhBEEAIQYgAUEAQTQQECEJQQAhBQNAIAQgBkcEQCAAIAZqIggtAAAiAUELSwRAQWwhBgwDBSAJIAFBAnRqIgEgASgCAEEBajYCACAGQQFqIQZBASAILQAAdEEBdSAFaiEFDAILAAsLQWwhBiAFRQ0AIAUQFEEBaiIBQQxLDQAgAyABNgIAQQFBASABdCAFayIDEBQiAXQgA0cNACAAIARqIAFBAWoiADoAACAJIABBAnRqIgAgACgCAEEBajYCACAJKAIEIgBBAkkgAEEBcXINACACIARBAWo2AgAgB0EBaiEGCyAKQZACaiQAIAYLxhEBDH8jAEHwAGsiBSQAQWwhCwJAIANBCkkNACACLwAAIQogAi8AAiEJIAIvAAQhByAFQQhqIAQQDgJAIAMgByAJIApqakEGaiIMSQ0AIAUtAAohCCAFQdgAaiACQQZqIgIgChAGIgsQAw0BIAVBQGsgAiAKaiICIAkQBiILEAMNASAFQShqIAIgCWoiAiAHEAYiCxADDQEgBUEQaiACIAdqIAMgDGsQBiILEAMNASAAIAFqIg9BfWohECAEQQRqIQZBASELIAAgAUEDakECdiIDaiIMIANqIgIgA2oiDiEDIAIhBCAMIQcDQCALIAMgEElxBEAgACAGIAVB2ABqIAgQAkECdGoiCS8BADsAACAFQdgAaiAJLQACEAEgCS0AAyELIAcgBiAFQUBrIAgQAkECdGoiCS8BADsAACAFQUBrIAktAAIQASAJLQADIQogBCAGIAVBKGogCBACQQJ0aiIJLwEAOwAAIAVBKGogCS0AAhABIAktAAMhCSADIAYgBUEQaiAIEAJBAnRqIg0vAQA7AAAgBUEQaiANLQACEAEgDS0AAyENIAAgC2oiCyAGIAVB2ABqIAgQAkECdGoiAC8BADsAACAFQdgAaiAALQACEAEgAC0AAyEAIAcgCmoiCiAGIAVBQGsgCBACQQJ0aiIHLwEAOwAAIAVBQGsgBy0AAhABIActAAMhByAEIAlqIgkgBiAFQShqIAgQAkECdGoiBC8BADsAACAFQShqIAQtAAIQASAELQADIQQgAyANaiIDIAYgBUEQaiAIEAJBAnRqIg0vAQA7AAAgBUEQaiANLQACEAEgACALaiEAIAcgCmohByAEIAlqIQQgAyANLQADaiEDIAVB2ABqEA0gBUFAaxANciAFQShqEA1yIAVBEGoQDXJFIQsMAQsLIAQgDksgByACS3INAEFsIQsgACAMSw0BIAxBfWohCQNAQQAgACAJSSAFQdgAahAEGwRAIAAgBiAFQdgAaiAIEAJBAnRqIgovAQA7AAAgBUHYAGogCi0AAhABIAAgCi0AA2oiACAGIAVB2ABqIAgQAkECdGoiCi8BADsAACAFQdgAaiAKLQACEAEgACAKLQADaiEADAEFIAxBfmohCgNAIAVB2ABqEAQgACAKS3JFBEAgACAGIAVB2ABqIAgQAkECdGoiCS8BADsAACAFQdgAaiAJLQACEAEgACAJLQADaiEADAELCwNAIAAgCk0EQCAAIAYgBUHYAGogCBACQQJ0aiIJLwEAOwAAIAVB2ABqIAktAAIQASAAIAktAANqIQAMAQsLAkAgACAMTw0AIAAgBiAFQdgAaiAIEAIiAEECdGoiDC0AADoAACAMLQADQQFGBEAgBUHYAGogDC0AAhABDAELIAUoAlxBH0sNACAFQdgAaiAGIABBAnRqLQACEAEgBSgCXEEhSQ0AIAVBIDYCXAsgAkF9aiEMA0BBACAHIAxJIAVBQGsQBBsEQCAHIAYgBUFAayAIEAJBAnRqIgAvAQA7AAAgBUFAayAALQACEAEgByAALQADaiIAIAYgBUFAayAIEAJBAnRqIgcvAQA7AAAgBUFAayAHLQACEAEgACAHLQADaiEHDAEFIAJBfmohDANAIAVBQGsQBCAHIAxLckUEQCAHIAYgBUFAayAIEAJBAnRqIgAvAQA7AAAgBUFAayAALQACEAEgByAALQADaiEHDAELCwNAIAcgDE0EQCAHIAYgBUFAayAIEAJBAnRqIgAvAQA7AAAgBUFAayAALQACEAEgByAALQADaiEHDAELCwJAIAcgAk8NACAHIAYgBUFAayAIEAIiAEECdGoiAi0AADoAACACLQADQQFGBEAgBUFAayACLQACEAEMAQsgBSgCREEfSw0AIAVBQGsgBiAAQQJ0ai0AAhABIAUoAkRBIUkNACAFQSA2AkQLIA5BfWohAgNAQQAgBCACSSAFQShqEAQbBEAgBCAGIAVBKGogCBACQQJ0aiIALwEAOwAAIAVBKGogAC0AAhABIAQgAC0AA2oiACAGIAVBKGogCBACQQJ0aiIELwEAOwAAIAVBKGogBC0AAhABIAAgBC0AA2ohBAwBBSAOQX5qIQIDQCAFQShqEAQgBCACS3JFBEAgBCAGIAVBKGogCBACQQJ0aiIALwEAOwAAIAVBKGogAC0AAhABIAQgAC0AA2ohBAwBCwsDQCAEIAJNBEAgBCAGIAVBKGogCBACQQJ0aiIALwEAOwAAIAVBKGogAC0AAhABIAQgAC0AA2ohBAwBCwsCQCAEIA5PDQAgBCAGIAVBKGogCBACIgBBAnRqIgItAAA6AAAgAi0AA0EBRgRAIAVBKGogAi0AAhABDAELIAUoAixBH0sNACAFQShqIAYgAEECdGotAAIQASAFKAIsQSFJDQAgBUEgNgIsCwNAQQAgAyAQSSAFQRBqEAQbBEAgAyAGIAVBEGogCBACQQJ0aiIALwEAOwAAIAVBEGogAC0AAhABIAMgAC0AA2oiACAGIAVBEGogCBACQQJ0aiICLwEAOwAAIAVBEGogAi0AAhABIAAgAi0AA2ohAwwBBSAPQX5qIQIDQCAFQRBqEAQgAyACS3JFBEAgAyAGIAVBEGogCBACQQJ0aiIALwEAOwAAIAVBEGogAC0AAhABIAMgAC0AA2ohAwwBCwsDQCADIAJNBEAgAyAGIAVBEGogCBACQQJ0aiIALwEAOwAAIAVBEGogAC0AAhABIAMgAC0AA2ohAwwBCwsCQCADIA9PDQAgAyAGIAVBEGogCBACIgBBAnRqIgItAAA6AAAgAi0AA0EBRgRAIAVBEGogAi0AAhABDAELIAUoAhRBH0sNACAFQRBqIAYgAEECdGotAAIQASAFKAIUQSFJDQAgBUEgNgIUCyABQWwgBUHYAGoQCiAFQUBrEApxIAVBKGoQCnEgBUEQahAKcRshCwwJCwAACwALAAALAAsAAAsACwAACwALQWwhCwsgBUHwAGokACALC7UEAQ5/IwBBEGsiBiQAIAZBBGogABAOQVQhBQJAIARB3AtJDQAgBi0ABCEHIANB8ARqQQBB7AAQECEIIAdBDEsNACADQdwJaiIJIAggBkEIaiAGQQxqIAEgAhAxIhAQA0UEQCAGKAIMIgQgB0sNASADQdwFaiEPIANBpAVqIREgAEEEaiESIANBqAVqIQEgBCEFA0AgBSICQX9qIQUgCCACQQJ0aigCAEUNAAsgAkEBaiEOQQEhBQNAIAUgDk9FBEAgCCAFQQJ0IgtqKAIAIQwgASALaiAKNgIAIAVBAWohBSAKIAxqIQoMAQsLIAEgCjYCAEEAIQUgBigCCCELA0AgBSALRkUEQCABIAUgCWotAAAiDEECdGoiDSANKAIAIg1BAWo2AgAgDyANQQF0aiINIAw6AAEgDSAFOgAAIAVBAWohBQwBCwtBACEBIANBADYCqAUgBEF/cyAHaiEJQQEhBQNAIAUgDk9FBEAgCCAFQQJ0IgtqKAIAIQwgAyALaiABNgIAIAwgBSAJanQgAWohASAFQQFqIQUMAQsLIAcgBEEBaiIBIAJrIgRrQQFqIQgDQEEBIQUgBCAIT0UEQANAIAUgDk9FBEAgBUECdCIJIAMgBEE0bGpqIAMgCWooAgAgBHY2AgAgBUEBaiEFDAELCyAEQQFqIQQMAQsLIBIgByAPIAogESADIAIgARBkIAZBAToABSAGIAc6AAYgACAGKAIENgIACyAQIQULIAZBEGokACAFC8ENAQt/IwBB8ABrIgUkAEFsIQkCQCADQQpJDQAgAi8AACEKIAIvAAIhDCACLwAEIQYgBUEIaiAEEA4CQCADIAYgCiAMampBBmoiDUkNACAFLQAKIQcgBUHYAGogAkEGaiICIAoQBiIJEAMNASAFQUBrIAIgCmoiAiAMEAYiCRADDQEgBUEoaiACIAxqIgIgBhAGIgkQAw0BIAVBEGogAiAGaiADIA1rEAYiCRADDQEgACABaiIOQX1qIQ8gBEEEaiEGQQEhCSAAIAFBA2pBAnYiAmoiCiACaiIMIAJqIg0hAyAMIQQgCiECA0AgCSADIA9JcQRAIAYgBUHYAGogBxACQQF0aiIILQAAIQsgBUHYAGogCC0AARABIAAgCzoAACAGIAVBQGsgBxACQQF0aiIILQAAIQsgBUFAayAILQABEAEgAiALOgAAIAYgBUEoaiAHEAJBAXRqIggtAAAhCyAFQShqIAgtAAEQASAEIAs6AAAgBiAFQRBqIAcQAkEBdGoiCC0AACELIAVBEGogCC0AARABIAMgCzoAACAGIAVB2ABqIAcQAkEBdGoiCC0AACELIAVB2ABqIAgtAAEQASAAIAs6AAEgBiAFQUBrIAcQAkEBdGoiCC0AACELIAVBQGsgCC0AARABIAIgCzoAASAGIAVBKGogBxACQQF0aiIILQAAIQsgBUEoaiAILQABEAEgBCALOgABIAYgBUEQaiAHEAJBAXRqIggtAAAhCyAFQRBqIAgtAAEQASADIAs6AAEgA0ECaiEDIARBAmohBCACQQJqIQIgAEECaiEAIAkgBUHYAGoQDUVxIAVBQGsQDUVxIAVBKGoQDUVxIAVBEGoQDUVxIQkMAQsLIAQgDUsgAiAMS3INAEFsIQkgACAKSw0BIApBfWohCQNAIAVB2ABqEAQgACAJT3JFBEAgBiAFQdgAaiAHEAJBAXRqIggtAAAhCyAFQdgAaiAILQABEAEgACALOgAAIAYgBUHYAGogBxACQQF0aiIILQAAIQsgBUHYAGogCC0AARABIAAgCzoAASAAQQJqIQAMAQsLA0AgBUHYAGoQBCAAIApPckUEQCAGIAVB2ABqIAcQAkEBdGoiCS0AACEIIAVB2ABqIAktAAEQASAAIAg6AAAgAEEBaiEADAELCwNAIAAgCkkEQCAGIAVB2ABqIAcQAkEBdGoiCS0AACEIIAVB2ABqIAktAAEQASAAIAg6AAAgAEEBaiEADAELCyAMQX1qIQADQCAFQUBrEAQgAiAAT3JFBEAgBiAFQUBrIAcQAkEBdGoiCi0AACEJIAVBQGsgCi0AARABIAIgCToAACAGIAVBQGsgBxACQQF0aiIKLQAAIQkgBUFAayAKLQABEAEgAiAJOgABIAJBAmohAgwBCwsDQCAFQUBrEAQgAiAMT3JFBEAgBiAFQUBrIAcQAkEBdGoiAC0AACEKIAVBQGsgAC0AARABIAIgCjoAACACQQFqIQIMAQsLA0AgAiAMSQRAIAYgBUFAayAHEAJBAXRqIgAtAAAhCiAFQUBrIAAtAAEQASACIAo6AAAgAkEBaiECDAELCyANQX1qIQADQCAFQShqEAQgBCAAT3JFBEAgBiAFQShqIAcQAkEBdGoiAi0AACEKIAVBKGogAi0AARABIAQgCjoAACAGIAVBKGogBxACQQF0aiICLQAAIQogBUEoaiACLQABEAEgBCAKOgABIARBAmohBAwBCwsDQCAFQShqEAQgBCANT3JFBEAgBiAFQShqIAcQAkEBdGoiAC0AACECIAVBKGogAC0AARABIAQgAjoAACAEQQFqIQQMAQsLA0AgBCANSQRAIAYgBUEoaiAHEAJBAXRqIgAtAAAhAiAFQShqIAAtAAEQASAEIAI6AAAgBEEBaiEEDAELCwNAIAVBEGoQBCADIA9PckUEQCAGIAVBEGogBxACQQF0aiIALQAAIQIgBUEQaiAALQABEAEgAyACOgAAIAYgBUEQaiAHEAJBAXRqIgAtAAAhAiAFQRBqIAAtAAEQASADIAI6AAEgA0ECaiEDDAELCwNAIAVBEGoQBCADIA5PckUEQCAGIAVBEGogBxACQQF0aiIALQAAIQIgBUEQaiAALQABEAEgAyACOgAAIANBAWohAwwBCwsDQCADIA5JBEAgBiAFQRBqIAcQAkEBdGoiAC0AACECIAVBEGogAC0AARABIAMgAjoAACADQQFqIQMMAQsLIAFBbCAFQdgAahAKIAVBQGsQCnEgBUEoahAKcSAFQRBqEApxGyEJDAELQWwhCQsgBUHwAGokACAJC8oCAQR/IwBBIGsiBSQAIAUgBBAOIAUtAAIhByAFQQhqIAIgAxAGIgIQA0UEQCAEQQRqIQIgACABaiIDQX1qIQQDQCAFQQhqEAQgACAET3JFBEAgAiAFQQhqIAcQAkEBdGoiBi0AACEIIAVBCGogBi0AARABIAAgCDoAACACIAVBCGogBxACQQF0aiIGLQAAIQggBUEIaiAGLQABEAEgACAIOgABIABBAmohAAwBCwsDQCAFQQhqEAQgACADT3JFBEAgAiAFQQhqIAcQAkEBdGoiBC0AACEGIAVBCGogBC0AARABIAAgBjoAACAAQQFqIQAMAQsLA0AgACADT0UEQCACIAVBCGogBxACQQF0aiIELQAAIQYgBUEIaiAELQABEAEgACAGOgAAIABBAWohAAwBCwsgAUFsIAVBCGoQChshAgsgBUEgaiQAIAILtgMBCX8jAEEQayIGJAAgBkEANgIMIAZBADYCCEFUIQQCQAJAIANBQGsiDCADIAZBCGogBkEMaiABIAIQMSICEAMNACAGQQRqIAAQDiAGKAIMIgcgBi0ABEEBaksNASAAQQRqIQogBkEAOgAFIAYgBzoABiAAIAYoAgQ2AgAgB0EBaiEJQQEhBANAIAQgCUkEQCADIARBAnRqIgEoAgAhACABIAU2AgAgACAEQX9qdCAFaiEFIARBAWohBAwBCwsgB0EBaiEHQQAhBSAGKAIIIQkDQCAFIAlGDQEgAyAFIAxqLQAAIgRBAnRqIgBBASAEdEEBdSILIAAoAgAiAWoiADYCACAHIARrIQhBACEEAkAgC0EDTQRAA0AgBCALRg0CIAogASAEakEBdGoiACAIOgABIAAgBToAACAEQQFqIQQMAAALAAsDQCABIABPDQEgCiABQQF0aiIEIAg6AAEgBCAFOgAAIAQgCDoAAyAEIAU6AAIgBCAIOgAFIAQgBToABCAEIAg6AAcgBCAFOgAGIAFBBGohAQwAAAsACyAFQQFqIQUMAAALAAsgAiEECyAGQRBqJAAgBAutAQECfwJAQYQgKAIAIABHIAAoAgBBAXYiAyABa0F4aiICQXhxQQhHcgR/IAIFIAMQJ0UNASACQQhqC0EQSQ0AIAAgACgCACICQQFxIAAgAWpBD2pBeHEiASAAa0EBdHI2AgAgASAANgIEIAEgASgCAEEBcSAAIAJBAXZqIAFrIgJBAXRyNgIAQYQgIAEgAkH/////B3FqQQRqQYQgKAIAIABGGyABNgIAIAEQJQsLygIBBX8CQAJAAkAgAEEIIABBCEsbZ0EfcyAAaUEBR2oiAUEESSAAIAF2cg0AIAFBAnRB/B5qKAIAIgJFDQADQCACQXhqIgMoAgBBAXZBeGoiBSAATwRAIAIgBUEIIAVBCEsbZ0Efc0ECdEGAH2oiASgCAEYEQCABIAIoAgQ2AgALDAMLIARBHksNASAEQQFqIQQgAigCBCICDQALC0EAIQMgAUEgTw0BA0AgAUECdEGAH2ooAgAiAkUEQCABQR5LIQIgAUEBaiEBIAJFDQEMAwsLIAIgAkF4aiIDKAIAQQF2QXhqIgFBCCABQQhLG2dBH3NBAnRBgB9qIgEoAgBGBEAgASACKAIENgIACwsgAigCACIBBEAgASACKAIENgIECyACKAIEIgEEQCABIAIoAgA2AgALIAMgAygCAEEBcjYCACADIAAQNwsgAwvhCwINfwV+IwBB8ABrIgckACAHIAAoAvDhASIINgJcIAEgAmohDSAIIAAoAoDiAWohDwJAAkAgBUUEQCABIQQMAQsgACgCxOABIRAgACgCwOABIREgACgCvOABIQ4gAEEBNgKM4QFBACEIA0AgCEEDRwRAIAcgCEECdCICaiAAIAJqQazQAWooAgA2AkQgCEEBaiEIDAELC0FsIQwgB0EYaiADIAQQBhADDQEgB0EsaiAHQRhqIAAoAgAQEyAHQTRqIAdBGGogACgCCBATIAdBPGogB0EYaiAAKAIEEBMgDUFgaiESIAEhBEEAIQwDQCAHKAIwIAcoAixBA3RqKQIAIhRCEIinQf8BcSEIIAcoAkAgBygCPEEDdGopAgAiFUIQiKdB/wFxIQsgBygCOCAHKAI0QQN0aikCACIWQiCIpyEJIBVCIIghFyAUQiCIpyECAkAgFkIQiKdB/wFxIgNBAk8EQAJAIAZFIANBGUlyRQRAIAkgB0EYaiADQSAgBygCHGsiCiAKIANLGyIKEAUgAyAKayIDdGohCSAHQRhqEAQaIANFDQEgB0EYaiADEAUgCWohCQwBCyAHQRhqIAMQBSAJaiEJIAdBGGoQBBoLIAcpAkQhGCAHIAk2AkQgByAYNwNIDAELAkAgA0UEQCACBEAgBygCRCEJDAMLIAcoAkghCQwBCwJAAkAgB0EYakEBEAUgCSACRWpqIgNBA0YEQCAHKAJEQX9qIgMgA0VqIQkMAQsgA0ECdCAHaigCRCIJIAlFaiEJIANBAUYNAQsgByAHKAJINgJMCwsgByAHKAJENgJIIAcgCTYCRAsgF6chAyALBEAgB0EYaiALEAUgA2ohAwsgCCALakEUTwRAIAdBGGoQBBoLIAgEQCAHQRhqIAgQBSACaiECCyAHQRhqEAQaIAcgB0EYaiAUQhiIp0H/AXEQCCAUp0H//wNxajYCLCAHIAdBGGogFUIYiKdB/wFxEAggFadB//8DcWo2AjwgB0EYahAEGiAHIAdBGGogFkIYiKdB/wFxEAggFqdB//8DcWo2AjQgByACNgJgIAcoAlwhCiAHIAk2AmggByADNgJkAkACQAJAIAQgAiADaiILaiASSw0AIAIgCmoiEyAPSw0AIA0gBGsgC0Egak8NAQsgByAHKQNoNwMQIAcgBykDYDcDCCAEIA0gB0EIaiAHQdwAaiAPIA4gESAQEB4hCwwBCyACIARqIQggBCAKEAcgAkERTwRAIARBEGohAgNAIAIgCkEQaiIKEAcgAkEQaiICIAhJDQALCyAIIAlrIQIgByATNgJcIAkgCCAOa0sEQCAJIAggEWtLBEBBbCELDAILIBAgAiAOayICaiIKIANqIBBNBEAgCCAKIAMQDxoMAgsgCCAKQQAgAmsQDyEIIAcgAiADaiIDNgJkIAggAmshCCAOIQILIAlBEE8EQCADIAhqIQMDQCAIIAIQByACQRBqIQIgCEEQaiIIIANJDQALDAELAkAgCUEHTQRAIAggAi0AADoAACAIIAItAAE6AAEgCCACLQACOgACIAggAi0AAzoAAyAIQQRqIAIgCUECdCIDQcAeaigCAGoiAhAXIAIgA0HgHmooAgBrIQIgBygCZCEDDAELIAggAhAMCyADQQlJDQAgAyAIaiEDIAhBCGoiCCACQQhqIgJrQQ9MBEADQCAIIAIQDCACQQhqIQIgCEEIaiIIIANJDQAMAgALAAsDQCAIIAIQByACQRBqIQIgCEEQaiIIIANJDQALCyAHQRhqEAQaIAsgDCALEAMiAhshDCAEIAQgC2ogAhshBCAFQX9qIgUNAAsgDBADDQFBbCEMIAdBGGoQBEECSQ0BQQAhCANAIAhBA0cEQCAAIAhBAnQiAmpBrNABaiACIAdqKAJENgIAIAhBAWohCAwBCwsgBygCXCEIC0G6fyEMIA8gCGsiACANIARrSw0AIAQEfyAEIAggABALIABqBUEACyABayEMCyAHQfAAaiQAIAwLkRcCFn8FfiMAQdABayIHJAAgByAAKALw4QEiCDYCvAEgASACaiESIAggACgCgOIBaiETAkACQCAFRQRAIAEhAwwBCyAAKALE4AEhESAAKALA4AEhFSAAKAK84AEhDyAAQQE2AozhAUEAIQgDQCAIQQNHBEAgByAIQQJ0IgJqIAAgAmpBrNABaigCADYCVCAIQQFqIQgMAQsLIAcgETYCZCAHIA82AmAgByABIA9rNgJoQWwhECAHQShqIAMgBBAGEAMNASAFQQQgBUEESBshFyAHQTxqIAdBKGogACgCABATIAdBxABqIAdBKGogACgCCBATIAdBzABqIAdBKGogACgCBBATQQAhBCAHQeAAaiEMIAdB5ABqIQoDQCAHQShqEARBAksgBCAXTnJFBEAgBygCQCAHKAI8QQN0aikCACIdQhCIp0H/AXEhCyAHKAJQIAcoAkxBA3RqKQIAIh5CEIinQf8BcSEJIAcoAkggBygCREEDdGopAgAiH0IgiKchCCAeQiCIISAgHUIgiKchAgJAIB9CEIinQf8BcSIDQQJPBEACQCAGRSADQRlJckUEQCAIIAdBKGogA0EgIAcoAixrIg0gDSADSxsiDRAFIAMgDWsiA3RqIQggB0EoahAEGiADRQ0BIAdBKGogAxAFIAhqIQgMAQsgB0EoaiADEAUgCGohCCAHQShqEAQaCyAHKQJUISEgByAINgJUIAcgITcDWAwBCwJAIANFBEAgAgRAIAcoAlQhCAwDCyAHKAJYIQgMAQsCQAJAIAdBKGpBARAFIAggAkVqaiIDQQNGBEAgBygCVEF/aiIDIANFaiEIDAELIANBAnQgB2ooAlQiCCAIRWohCCADQQFGDQELIAcgBygCWDYCXAsLIAcgBygCVDYCWCAHIAg2AlQLICCnIQMgCQRAIAdBKGogCRAFIANqIQMLIAkgC2pBFE8EQCAHQShqEAQaCyALBEAgB0EoaiALEAUgAmohAgsgB0EoahAEGiAHIAcoAmggAmoiCSADajYCaCAKIAwgCCAJSxsoAgAhDSAHIAdBKGogHUIYiKdB/wFxEAggHadB//8DcWo2AjwgByAHQShqIB5CGIinQf8BcRAIIB6nQf//A3FqNgJMIAdBKGoQBBogB0EoaiAfQhiIp0H/AXEQCCEOIAdB8ABqIARBBHRqIgsgCSANaiAIazYCDCALIAg2AgggCyADNgIEIAsgAjYCACAHIA4gH6dB//8DcWo2AkQgBEEBaiEEDAELCyAEIBdIDQEgEkFgaiEYIAdB4ABqIRogB0HkAGohGyABIQMDQCAHQShqEARBAksgBCAFTnJFBEAgBygCQCAHKAI8QQN0aikCACIdQhCIp0H/AXEhCyAHKAJQIAcoAkxBA3RqKQIAIh5CEIinQf8BcSEIIAcoAkggBygCREEDdGopAgAiH0IgiKchCSAeQiCIISAgHUIgiKchDAJAIB9CEIinQf8BcSICQQJPBEACQCAGRSACQRlJckUEQCAJIAdBKGogAkEgIAcoAixrIgogCiACSxsiChAFIAIgCmsiAnRqIQkgB0EoahAEGiACRQ0BIAdBKGogAhAFIAlqIQkMAQsgB0EoaiACEAUgCWohCSAHQShqEAQaCyAHKQJUISEgByAJNgJUIAcgITcDWAwBCwJAIAJFBEAgDARAIAcoAlQhCQwDCyAHKAJYIQkMAQsCQAJAIAdBKGpBARAFIAkgDEVqaiICQQNGBEAgBygCVEF/aiICIAJFaiEJDAELIAJBAnQgB2ooAlQiCSAJRWohCSACQQFGDQELIAcgBygCWDYCXAsLIAcgBygCVDYCWCAHIAk2AlQLICCnIRQgCARAIAdBKGogCBAFIBRqIRQLIAggC2pBFE8EQCAHQShqEAQaCyALBEAgB0EoaiALEAUgDGohDAsgB0EoahAEGiAHIAcoAmggDGoiGSAUajYCaCAbIBogCSAZSxsoAgAhHCAHIAdBKGogHUIYiKdB/wFxEAggHadB//8DcWo2AjwgByAHQShqIB5CGIinQf8BcRAIIB6nQf//A3FqNgJMIAdBKGoQBBogByAHQShqIB9CGIinQf8BcRAIIB+nQf//A3FqNgJEIAcgB0HwAGogBEEDcUEEdGoiDSkDCCIdNwPIASAHIA0pAwAiHjcDwAECQAJAAkAgBygCvAEiDiAepyICaiIWIBNLDQAgAyAHKALEASIKIAJqIgtqIBhLDQAgEiADayALQSBqTw0BCyAHIAcpA8gBNwMQIAcgBykDwAE3AwggAyASIAdBCGogB0G8AWogEyAPIBUgERAeIQsMAQsgAiADaiEIIAMgDhAHIAJBEU8EQCADQRBqIQIDQCACIA5BEGoiDhAHIAJBEGoiAiAISQ0ACwsgCCAdpyIOayECIAcgFjYCvAEgDiAIIA9rSwRAIA4gCCAVa0sEQEFsIQsMAgsgESACIA9rIgJqIhYgCmogEU0EQCAIIBYgChAPGgwCCyAIIBZBACACaxAPIQggByACIApqIgo2AsQBIAggAmshCCAPIQILIA5BEE8EQCAIIApqIQoDQCAIIAIQByACQRBqIQIgCEEQaiIIIApJDQALDAELAkAgDkEHTQRAIAggAi0AADoAACAIIAItAAE6AAEgCCACLQACOgACIAggAi0AAzoAAyAIQQRqIAIgDkECdCIKQcAeaigCAGoiAhAXIAIgCkHgHmooAgBrIQIgBygCxAEhCgwBCyAIIAIQDAsgCkEJSQ0AIAggCmohCiAIQQhqIgggAkEIaiICa0EPTARAA0AgCCACEAwgAkEIaiECIAhBCGoiCCAKSQ0ADAIACwALA0AgCCACEAcgAkEQaiECIAhBEGoiCCAKSQ0ACwsgCxADBEAgCyEQDAQFIA0gDDYCACANIBkgHGogCWs2AgwgDSAJNgIIIA0gFDYCBCAEQQFqIQQgAyALaiEDDAILAAsLIAQgBUgNASAEIBdrIQtBACEEA0AgCyAFSARAIAcgB0HwAGogC0EDcUEEdGoiAikDCCIdNwPIASAHIAIpAwAiHjcDwAECQAJAAkAgBygCvAEiDCAepyICaiIKIBNLDQAgAyAHKALEASIJIAJqIhBqIBhLDQAgEiADayAQQSBqTw0BCyAHIAcpA8gBNwMgIAcgBykDwAE3AxggAyASIAdBGGogB0G8AWogEyAPIBUgERAeIRAMAQsgAiADaiEIIAMgDBAHIAJBEU8EQCADQRBqIQIDQCACIAxBEGoiDBAHIAJBEGoiAiAISQ0ACwsgCCAdpyIGayECIAcgCjYCvAEgBiAIIA9rSwRAIAYgCCAVa0sEQEFsIRAMAgsgESACIA9rIgJqIgwgCWogEU0EQCAIIAwgCRAPGgwCCyAIIAxBACACaxAPIQggByACIAlqIgk2AsQBIAggAmshCCAPIQILIAZBEE8EQCAIIAlqIQYDQCAIIAIQByACQRBqIQIgCEEQaiIIIAZJDQALDAELAkAgBkEHTQRAIAggAi0AADoAACAIIAItAAE6AAEgCCACLQACOgACIAggAi0AAzoAAyAIQQRqIAIgBkECdCIGQcAeaigCAGoiAhAXIAIgBkHgHmooAgBrIQIgBygCxAEhCQwBCyAIIAIQDAsgCUEJSQ0AIAggCWohBiAIQQhqIgggAkEIaiICa0EPTARAA0AgCCACEAwgAkEIaiECIAhBCGoiCCAGSQ0ADAIACwALA0AgCCACEAcgAkEQaiECIAhBEGoiCCAGSQ0ACwsgEBADDQMgC0EBaiELIAMgEGohAwwBCwsDQCAEQQNHBEAgACAEQQJ0IgJqQazQAWogAiAHaigCVDYCACAEQQFqIQQMAQsLIAcoArwBIQgLQbp/IRAgEyAIayIAIBIgA2tLDQAgAwR/IAMgCCAAEAsgAGoFQQALIAFrIRALIAdB0AFqJAAgEAslACAAQgA3AgAgAEEAOwEIIABBADoACyAAIAE2AgwgACACOgAKC7QFAQN/IwBBMGsiBCQAIABB/wFqIgVBfWohBgJAIAMvAQIEQCAEQRhqIAEgAhAGIgIQAw0BIARBEGogBEEYaiADEBwgBEEIaiAEQRhqIAMQHCAAIQMDQAJAIARBGGoQBCADIAZPckUEQCADIARBEGogBEEYahASOgAAIAMgBEEIaiAEQRhqEBI6AAEgBEEYahAERQ0BIANBAmohAwsgBUF+aiEFAn8DQEG6fyECIAMiASAFSw0FIAEgBEEQaiAEQRhqEBI6AAAgAUEBaiEDIARBGGoQBEEDRgRAQQIhAiAEQQhqDAILIAMgBUsNBSABIARBCGogBEEYahASOgABIAFBAmohA0EDIQIgBEEYahAEQQNHDQALIARBEGoLIQUgAyAFIARBGGoQEjoAACABIAJqIABrIQIMAwsgAyAEQRBqIARBGGoQEjoAAiADIARBCGogBEEYahASOgADIANBBGohAwwAAAsACyAEQRhqIAEgAhAGIgIQAw0AIARBEGogBEEYaiADEBwgBEEIaiAEQRhqIAMQHCAAIQMDQAJAIARBGGoQBCADIAZPckUEQCADIARBEGogBEEYahAROgAAIAMgBEEIaiAEQRhqEBE6AAEgBEEYahAERQ0BIANBAmohAwsgBUF+aiEFAn8DQEG6fyECIAMiASAFSw0EIAEgBEEQaiAEQRhqEBE6AAAgAUEBaiEDIARBGGoQBEEDRgRAQQIhAiAEQQhqDAILIAMgBUsNBCABIARBCGogBEEYahAROgABIAFBAmohA0EDIQIgBEEYahAEQQNHDQALIARBEGoLIQUgAyAFIARBGGoQEToAACABIAJqIABrIQIMAgsgAyAEQRBqIARBGGoQEToAAiADIARBCGogBEEYahAROgADIANBBGohAwwAAAsACyAEQTBqJAAgAgtpAQF/An8CQAJAIAJBB00NACABKAAAQbfIwuF+Rw0AIAAgASgABDYCmOIBQWIgAEEQaiABIAIQPiIDEAMNAhogAEKBgICAEDcDiOEBIAAgASADaiACIANrECoMAQsgACABIAIQKgtBAAsLrQMBBn8jAEGAAWsiAyQAQWIhCAJAIAJBCUkNACAAQZjQAGogAUEIaiIEIAJBeGogAEGY0AAQMyIFEAMiBg0AIANBHzYCfCADIANB/ABqIANB+ABqIAQgBCAFaiAGGyIEIAEgAmoiAiAEaxAVIgUQAw0AIAMoAnwiBkEfSw0AIAMoAngiB0EJTw0AIABBiCBqIAMgBkGAC0GADCAHEBggA0E0NgJ8IAMgA0H8AGogA0H4AGogBCAFaiIEIAIgBGsQFSIFEAMNACADKAJ8IgZBNEsNACADKAJ4IgdBCk8NACAAQZAwaiADIAZBgA1B4A4gBxAYIANBIzYCfCADIANB/ABqIANB+ABqIAQgBWoiBCACIARrEBUiBRADDQAgAygCfCIGQSNLDQAgAygCeCIHQQpPDQAgACADIAZBwBBB0BEgBxAYIAQgBWoiBEEMaiIFIAJLDQAgAiAFayEFQQAhAgNAIAJBA0cEQCAEKAAAIgZBf2ogBU8NAiAAIAJBAnRqQZzQAWogBjYCACACQQFqIQIgBEEEaiEEDAELCyAEIAFrIQgLIANBgAFqJAAgCAtGAQN/IABBCGohAyAAKAIEIQJBACEAA0AgACACdkUEQCABIAMgAEEDdGotAAJBFktqIQEgAEEBaiEADAELCyABQQggAmt0C4YDAQV/Qbh/IQcCQCADRQ0AIAItAAAiBEUEQCABQQA2AgBBAUG4fyADQQFGGw8LAn8gAkEBaiIFIARBGHRBGHUiBkF/Sg0AGiAGQX9GBEAgA0EDSA0CIAUvAABBgP4BaiEEIAJBA2oMAQsgA0ECSA0BIAItAAEgBEEIdHJBgIB+aiEEIAJBAmoLIQUgASAENgIAIAVBAWoiASACIANqIgNLDQBBbCEHIABBEGogACAFLQAAIgVBBnZBI0EJIAEgAyABa0HAEEHQEUHwEiAAKAKM4QEgACgCnOIBIAQQHyIGEAMiCA0AIABBmCBqIABBCGogBUEEdkEDcUEfQQggASABIAZqIAgbIgEgAyABa0GAC0GADEGAFyAAKAKM4QEgACgCnOIBIAQQHyIGEAMiCA0AIABBoDBqIABBBGogBUECdkEDcUE0QQkgASABIAZqIAgbIgEgAyABa0GADUHgDkGQGSAAKAKM4QEgACgCnOIBIAQQHyIAEAMNACAAIAFqIAJrIQcLIAcLrQMBCn8jAEGABGsiCCQAAn9BUiACQf8BSw0AGkFUIANBDEsNABogAkEBaiELIABBBGohCUGAgAQgA0F/anRBEHUhCkEAIQJBASEEQQEgA3QiB0F/aiIMIQUDQCACIAtGRQRAAkAgASACQQF0Ig1qLwEAIgZB//8DRgRAIAkgBUECdGogAjoAAiAFQX9qIQVBASEGDAELIARBACAKIAZBEHRBEHVKGyEECyAIIA1qIAY7AQAgAkEBaiECDAELCyAAIAQ7AQIgACADOwEAIAdBA3YgB0EBdmpBA2ohBkEAIQRBACECA0AgBCALRkUEQCABIARBAXRqLgEAIQpBACEAA0AgACAKTkUEQCAJIAJBAnRqIAQ6AAIDQCACIAZqIAxxIgIgBUsNAAsgAEEBaiEADAELCyAEQQFqIQQMAQsLQX8gAg0AGkEAIQIDfyACIAdGBH9BAAUgCCAJIAJBAnRqIgAtAAJBAXRqIgEgAS8BACIBQQFqOwEAIAAgAyABEBRrIgU6AAMgACABIAVB/wFxdCAHazsBACACQQFqIQIMAQsLCyEFIAhBgARqJAAgBQvjBgEIf0FsIQcCQCACQQNJDQACQAJAAkACQCABLQAAIgNBA3EiCUEBaw4DAwEAAgsgACgCiOEBDQBBYg8LIAJBBUkNAkEDIQYgASgAACEFAn8CQAJAIANBAnZBA3EiCEF+aiIEQQFNBEAgBEEBaw0BDAILIAVBDnZB/wdxIQQgBUEEdkH/B3EhAyAIRQwCCyAFQRJ2IQRBBCEGIAVBBHZB//8AcSEDQQAMAQsgBUEEdkH//w9xIgNBgIAISw0DIAEtAARBCnQgBUEWdnIhBEEFIQZBAAshBSAEIAZqIgogAksNAgJAIANBgQZJDQAgACgCnOIBRQ0AQQAhAgNAIAJBg4ABSw0BIAJBQGshAgwAAAsACwJ/IAlBA0YEQCABIAZqIQEgAEHw4gFqIQIgACgCDCEGIAUEQCACIAMgASAEIAYQXwwCCyACIAMgASAEIAYQXQwBCyAAQbjQAWohAiABIAZqIQEgAEHw4gFqIQYgAEGo0ABqIQggBQRAIAggBiADIAEgBCACEF4MAQsgCCAGIAMgASAEIAIQXAsQAw0CIAAgAzYCgOIBIABBATYCiOEBIAAgAEHw4gFqNgLw4QEgCUECRgRAIAAgAEGo0ABqNgIMCyAAIANqIgBBiOMBakIANwAAIABBgOMBakIANwAAIABB+OIBakIANwAAIABB8OIBakIANwAAIAoPCwJ/AkACQAJAIANBAnZBA3FBf2oiBEECSw0AIARBAWsOAgACAQtBASEEIANBA3YMAgtBAiEEIAEvAABBBHYMAQtBAyEEIAEQIUEEdgsiAyAEaiIFQSBqIAJLBEAgBSACSw0CIABB8OIBaiABIARqIAMQCyEBIAAgAzYCgOIBIAAgATYC8OEBIAEgA2oiAEIANwAYIABCADcAECAAQgA3AAggAEIANwAAIAUPCyAAIAM2AoDiASAAIAEgBGo2AvDhASAFDwsCfwJAAkACQCADQQJ2QQNxQX9qIgRBAksNACAEQQFrDgIAAgELQQEhByADQQN2DAILQQIhByABLwAAQQR2DAELIAJBBEkgARAhIgJBj4CAAUtyDQFBAyEHIAJBBHYLIQIgAEHw4gFqIAEgB2otAAAgAkEgahAQIQEgACACNgKA4gEgACABNgLw4QEgB0EBaiEHCyAHC0sAIABC+erQ0OfJoeThADcDICAAQgA3AxggAELP1tO+0ser2UI3AxAgAELW64Lu6v2J9eAANwMIIABCADcDACAAQShqQQBBKBAQGgviAgICfwV+IABBKGoiASAAKAJIaiECAn4gACkDACIDQiBaBEAgACkDECIEQgeJIAApAwgiBUIBiXwgACkDGCIGQgyJfCAAKQMgIgdCEol8IAUQGSAEEBkgBhAZIAcQGQwBCyAAKQMYQsXP2bLx5brqJ3wLIAN8IQMDQCABQQhqIgAgAk0EQEIAIAEpAAAQCSADhUIbiUKHla+vmLbem55/fkLj3MqV/M7y9YV/fCEDIAAhAQwBCwsCQCABQQRqIgAgAksEQCABIQAMAQsgASgAAK1Ch5Wvr5i23puef34gA4VCF4lCz9bTvtLHq9lCfkL5893xmfaZqxZ8IQMLA0AgACACSQRAIAAxAABCxc/ZsvHluuonfiADhUILiUKHla+vmLbem55/fiEDIABBAWohAAwBCwsgA0IhiCADhULP1tO+0ser2UJ+IgNCHYggA4VC+fPd8Zn2masWfiIDQiCIIAOFC+8CAgJ/BH4gACAAKQMAIAKtfDcDAAJAAkAgACgCSCIDIAJqIgRBH00EQCABRQ0BIAAgA2pBKGogASACECAgACgCSCACaiEEDAELIAEgAmohAgJ/IAMEQCAAQShqIgQgA2ogAUEgIANrECAgACAAKQMIIAQpAAAQCTcDCCAAIAApAxAgACkAMBAJNwMQIAAgACkDGCAAKQA4EAk3AxggACAAKQMgIABBQGspAAAQCTcDICAAKAJIIQMgAEEANgJIIAEgA2tBIGohAQsgAUEgaiACTQsEQCACQWBqIQMgACkDICEFIAApAxghBiAAKQMQIQcgACkDCCEIA0AgCCABKQAAEAkhCCAHIAEpAAgQCSEHIAYgASkAEBAJIQYgBSABKQAYEAkhBSABQSBqIgEgA00NAAsgACAFNwMgIAAgBjcDGCAAIAc3AxAgACAINwMICyABIAJPDQEgAEEoaiABIAIgAWsiBBAgCyAAIAQ2AkgLCy8BAX8gAEUEQEG2f0EAIAMbDwtBun8hBCADIAFNBH8gACACIAMQEBogAwVBun8LCy8BAX8gAEUEQEG2f0EAIAMbDwtBun8hBCADIAFNBH8gACACIAMQCxogAwVBun8LC6gCAQZ/IwBBEGsiByQAIABB2OABaikDAEKAgIAQViEIQbh/IQUCQCAEQf//B0sNACAAIAMgBBBCIgUQAyIGDQAgACgCnOIBIQkgACAHQQxqIAMgAyAFaiAGGyIKIARBACAFIAYbayIGEEAiAxADBEAgAyEFDAELIAcoAgwhBCABRQRAQbp/IQUgBEEASg0BCyAGIANrIQUgAyAKaiEDAkAgCQRAIABBADYCnOIBDAELAkACQAJAIARBBUgNACAAQdjgAWopAwBCgICACFgNAAwBCyAAQQA2ApziAQwBCyAAKAIIED8hBiAAQQA2ApziASAGQRRPDQELIAAgASACIAMgBSAEIAgQOSEFDAELIAAgASACIAMgBSAEIAgQOiEFCyAHQRBqJAAgBQtnACAAQdDgAWogASACIAAoAuzhARAuIgEQAwRAIAEPC0G4fyECAkAgAQ0AIABB7OABaigCACIBBEBBYCECIAAoApjiASABRw0BC0EAIQIgAEHw4AFqKAIARQ0AIABBkOEBahBDCyACCycBAX8QVyIERQRAQUAPCyAEIAAgASACIAMgBBBLEE8hACAEEFYgAAs/AQF/AkACQAJAIAAoAqDiAUEBaiIBQQJLDQAgAUEBaw4CAAECCyAAEDBBAA8LIABBADYCoOIBCyAAKAKU4gELvAMCB38BfiMAQRBrIgkkAEG4fyEGAkAgBCgCACIIQQVBCSAAKALs4QEiBRtJDQAgAygCACIHQQFBBSAFGyAFEC8iBRADBEAgBSEGDAELIAggBUEDakkNACAAIAcgBRBJIgYQAw0AIAEgAmohCiAAQZDhAWohCyAIIAVrIQIgBSAHaiEHIAEhBQNAIAcgAiAJECwiBhADDQEgAkF9aiICIAZJBEBBuH8hBgwCCyAJKAIAIghBAksEQEFsIQYMAgsgB0EDaiEHAn8CQAJAAkAgCEEBaw4CAgABCyAAIAUgCiAFayAHIAYQSAwCCyAFIAogBWsgByAGEEcMAQsgBSAKIAVrIActAAAgCSgCCBBGCyIIEAMEQCAIIQYMAgsgACgC8OABBEAgCyAFIAgQRQsgAiAGayECIAYgB2ohByAFIAhqIQUgCSgCBEUNAAsgACkD0OABIgxCf1IEQEFsIQYgDCAFIAFrrFINAQsgACgC8OABBEBBaiEGIAJBBEkNASALEEQhDCAHKAAAIAynRw0BIAdBBGohByACQXxqIQILIAMgBzYCACAEIAI2AgAgBSABayEGCyAJQRBqJAAgBgsuACAAECsCf0EAQQAQAw0AGiABRSACRXJFBEBBYiAAIAEgAhA9EAMNARoLQQALCzcAIAEEQCAAIAAoAsTgASABKAIEIAEoAghqRzYCnOIBCyAAECtBABADIAFFckUEQCAAIAEQWwsL0QIBB38jAEEQayIGJAAgBiAENgIIIAYgAzYCDCAFBEAgBSgCBCEKIAUoAgghCQsgASEIAkACQANAIAAoAuzhARAWIQsCQANAIAQgC0kNASADKAAAQXBxQdDUtMIBRgRAIAMgBBAiIgcQAw0EIAQgB2shBCADIAdqIQMMAQsLIAYgAzYCDCAGIAQ2AggCQCAFBEAgACAFEE5BACEHQQAQA0UNAQwFCyAAIAogCRBNIgcQAw0ECyAAIAgQUCAMQQFHQQAgACAIIAIgBkEMaiAGQQhqEEwiByIDa0EAIAMQAxtBCkdyRQRAQbh/IQcMBAsgBxADDQMgAiAHayECIAcgCGohCEEBIQwgBigCDCEDIAYoAgghBAwBCwsgBiADNgIMIAYgBDYCCEG4fyEHIAQNASAIIAFrIQcMAQsgBiADNgIMIAYgBDYCCAsgBkEQaiQAIAcLRgECfyABIAAoArjgASICRwRAIAAgAjYCxOABIAAgATYCuOABIAAoArzgASEDIAAgATYCvOABIAAgASADIAJrajYCwOABCwutAgIEfwF+IwBBQGoiBCQAAkACQCACQQhJDQAgASgAAEFwcUHQ1LTCAUcNACABIAIQIiEBIABCADcDCCAAQQA2AgQgACABNgIADAELIARBGGogASACEC0iAxADBEAgACADEBoMAQsgAwRAIABBuH8QGgwBCyACIAQoAjAiA2shAiABIANqIQMDQAJAIAAgAyACIARBCGoQLCIFEAMEfyAFBSACIAVBA2oiBU8NAUG4fwsQGgwCCyAGQQFqIQYgAiAFayECIAMgBWohAyAEKAIMRQ0ACyAEKAI4BEAgAkEDTQRAIABBuH8QGgwCCyADQQRqIQMLIAQoAighAiAEKQMYIQcgAEEANgIEIAAgAyABazYCACAAIAIgBmytIAcgB0J/URs3AwgLIARBQGskAAslAQF/IwBBEGsiAiQAIAIgACABEFEgAigCACEAIAJBEGokACAAC30BBH8jAEGQBGsiBCQAIARB/wE2AggCQCAEQRBqIARBCGogBEEMaiABIAIQFSIGEAMEQCAGIQUMAQtBVCEFIAQoAgwiB0EGSw0AIAMgBEEQaiAEKAIIIAcQQSIFEAMNACAAIAEgBmogAiAGayADEDwhBQsgBEGQBGokACAFC4cBAgJ/An5BABAWIQMCQANAIAEgA08EQAJAIAAoAABBcHFB0NS0wgFGBEAgACABECIiAhADRQ0BQn4PCyAAIAEQVSIEQn1WDQMgBCAFfCIFIARUIQJCfiEEIAINAyAAIAEQUiICEAMNAwsgASACayEBIAAgAmohAAwBCwtCfiAFIAEbIQQLIAQLPwIBfwF+IwBBMGsiAiQAAn5CfiACQQhqIAAgARAtDQAaQgAgAigCHEEBRg0AGiACKQMICyEDIAJBMGokACADC40BAQJ/IwBBMGsiASQAAkAgAEUNACAAKAKI4gENACABIABB/OEBaigCADYCKCABIAApAvThATcDICAAEDAgACgCqOIBIQIgASABKAIoNgIYIAEgASkDIDcDECACIAFBEGoQGyAAQQA2AqjiASABIAEoAig2AgggASABKQMgNwMAIAAgARAbCyABQTBqJAALKgECfyMAQRBrIgAkACAAQQA2AgggAEIANwMAIAAQWCEBIABBEGokACABC4cBAQN/IwBBEGsiAiQAAkAgACgCAEUgACgCBEVzDQAgAiAAKAIINgIIIAIgACkCADcDAAJ/IAIoAgAiAQRAIAIoAghBqOMJIAERBQAMAQtBqOMJECgLIgFFDQAgASAAKQIANwL04QEgAUH84QFqIAAoAgg2AgAgARBZIAEhAwsgAkEQaiQAIAMLywEBAn8jAEEgayIBJAAgAEGBgIDAADYCtOIBIABBADYCiOIBIABBADYC7OEBIABCADcDkOIBIABBADYCpOMJIABBADYC3OIBIABCADcCzOIBIABBADYCvOIBIABBADYCxOABIABCADcCnOIBIABBpOIBakIANwIAIABBrOIBakEANgIAIAFCADcCECABQgA3AhggASABKQMYNwMIIAEgASkDEDcDACABKAIIQQh2QQFxIQIgAEEANgLg4gEgACACNgKM4gEgAUEgaiQAC3YBA38jAEEwayIBJAAgAARAIAEgAEHE0AFqIgIoAgA2AiggASAAKQK80AE3AyAgACgCACEDIAEgAigCADYCGCABIAApArzQATcDECADIAFBEGoQGyABIAEoAig2AgggASABKQMgNwMAIAAgARAbCyABQTBqJAALzAEBAX8gACABKAK00AE2ApjiASAAIAEoAgQiAjYCwOABIAAgAjYCvOABIAAgAiABKAIIaiICNgK44AEgACACNgLE4AEgASgCuNABBEAgAEKBgICAEDcDiOEBIAAgAUGk0ABqNgIMIAAgAUGUIGo2AgggACABQZwwajYCBCAAIAFBDGo2AgAgAEGs0AFqIAFBqNABaigCADYCACAAQbDQAWogAUGs0AFqKAIANgIAIABBtNABaiABQbDQAWooAgA2AgAPCyAAQgA3A4jhAQs7ACACRQRAQbp/DwsgBEUEQEFsDwsgAiAEEGAEQCAAIAEgAiADIAQgBRBhDwsgACABIAIgAyAEIAUQZQtGAQF/IwBBEGsiBSQAIAVBCGogBBAOAn8gBS0ACQRAIAAgASACIAMgBBAyDAELIAAgASACIAMgBBA0CyEAIAVBEGokACAACzQAIAAgAyAEIAUQNiIFEAMEQCAFDwsgBSAESQR/IAEgAiADIAVqIAQgBWsgABA1BUG4fwsLRgEBfyMAQRBrIgUkACAFQQhqIAQQDgJ/IAUtAAkEQCAAIAEgAiADIAQQYgwBCyAAIAEgAiADIAQQNQshACAFQRBqJAAgAAtZAQF/QQ8hAiABIABJBEAgAUEEdCAAbiECCyAAQQh2IgEgAkEYbCIAQYwIaigCAGwgAEGICGooAgBqIgJBA3YgAmogAEGACGooAgAgAEGECGooAgAgAWxqSQs3ACAAIAMgBCAFQYAQEDMiBRADBEAgBQ8LIAUgBEkEfyABIAIgAyAFaiAEIAVrIAAQMgVBuH8LC78DAQN/IwBBIGsiBSQAIAVBCGogAiADEAYiAhADRQRAIAAgAWoiB0F9aiEGIAUgBBAOIARBBGohAiAFLQACIQMDQEEAIAAgBkkgBUEIahAEGwRAIAAgAiAFQQhqIAMQAkECdGoiBC8BADsAACAFQQhqIAQtAAIQASAAIAQtAANqIgQgAiAFQQhqIAMQAkECdGoiAC8BADsAACAFQQhqIAAtAAIQASAEIAAtAANqIQAMAQUgB0F+aiEEA0AgBUEIahAEIAAgBEtyRQRAIAAgAiAFQQhqIAMQAkECdGoiBi8BADsAACAFQQhqIAYtAAIQASAAIAYtAANqIQAMAQsLA0AgACAES0UEQCAAIAIgBUEIaiADEAJBAnRqIgYvAQA7AAAgBUEIaiAGLQACEAEgACAGLQADaiEADAELCwJAIAAgB08NACAAIAIgBUEIaiADEAIiA0ECdGoiAC0AADoAACAALQADQQFGBEAgBUEIaiAALQACEAEMAQsgBSgCDEEfSw0AIAVBCGogAiADQQJ0ai0AAhABIAUoAgxBIUkNACAFQSA2AgwLIAFBbCAFQQhqEAobIQILCwsgBUEgaiQAIAILkgIBBH8jAEFAaiIJJAAgCSADQTQQCyEDAkAgBEECSA0AIAMgBEECdGooAgAhCSADQTxqIAgQIyADQQE6AD8gAyACOgA+QQAhBCADKAI8IQoDQCAEIAlGDQEgACAEQQJ0aiAKNgEAIARBAWohBAwAAAsAC0EAIQkDQCAGIAlGRQRAIAMgBSAJQQF0aiIKLQABIgtBAnRqIgwoAgAhBCADQTxqIAotAABBCHQgCGpB//8DcRAjIANBAjoAPyADIAcgC2siCiACajoAPiAEQQEgASAKa3RqIQogAygCPCELA0AgACAEQQJ0aiALNgEAIARBAWoiBCAKSQ0ACyAMIAo2AgAgCUEBaiEJDAELCyADQUBrJAALowIBCX8jAEHQAGsiCSQAIAlBEGogBUE0EAsaIAcgBmshDyAHIAFrIRADQAJAIAMgCkcEQEEBIAEgByACIApBAXRqIgYtAAEiDGsiCGsiC3QhDSAGLQAAIQ4gCUEQaiAMQQJ0aiIMKAIAIQYgCyAPTwRAIAAgBkECdGogCyAIIAUgCEE0bGogCCAQaiIIQQEgCEEBShsiCCACIAQgCEECdGooAgAiCEEBdGogAyAIayAHIA4QYyAGIA1qIQgMAgsgCUEMaiAOECMgCUEBOgAPIAkgCDoADiAGIA1qIQggCSgCDCELA0AgBiAITw0CIAAgBkECdGogCzYBACAGQQFqIQYMAAALAAsgCUHQAGokAA8LIAwgCDYCACAKQQFqIQoMAAALAAs0ACAAIAMgBCAFEDYiBRADBEAgBQ8LIAUgBEkEfyABIAIgAyAFaiAEIAVrIAAQNAVBuH8LCyMAIAA/AEEQdGtB//8DakEQdkAAQX9GBEBBAA8LQQAQAEEBCzsBAX8gAgRAA0AgACABIAJBgCAgAkGAIEkbIgMQCyEAIAFBgCBqIQEgAEGAIGohACACIANrIgINAAsLCwYAIAAQAwsLqBUJAEGICAsNAQAAAAEAAAACAAAAAgBBoAgLswYBAAAAAQAAAAIAAAACAAAAJgAAAIIAAAAhBQAASgAAAGcIAAAmAAAAwAEAAIAAAABJBQAASgAAAL4IAAApAAAALAIAAIAAAABJBQAASgAAAL4IAAAvAAAAygIAAIAAAACKBQAASgAAAIQJAAA1AAAAcwMAAIAAAACdBQAASgAAAKAJAAA9AAAAgQMAAIAAAADrBQAASwAAAD4KAABEAAAAngMAAIAAAABNBgAASwAAAKoKAABLAAAAswMAAIAAAADBBgAATQAAAB8NAABNAAAAUwQAAIAAAAAjCAAAUQAAAKYPAABUAAAAmQQAAIAAAABLCQAAVwAAALESAABYAAAA2gQAAIAAAABvCQAAXQAAACMUAABUAAAARQUAAIAAAABUCgAAagAAAIwUAABqAAAArwUAAIAAAAB2CQAAfAAAAE4QAAB8AAAA0gIAAIAAAABjBwAAkQAAAJAHAACSAAAAAAAAAAEAAAABAAAABQAAAA0AAAAdAAAAPQAAAH0AAAD9AAAA/QEAAP0DAAD9BwAA/Q8AAP0fAAD9PwAA/X8AAP3/AAD9/wEA/f8DAP3/BwD9/w8A/f8fAP3/PwD9/38A/f//AP3//wH9//8D/f//B/3//w/9//8f/f//P/3//38AAAAAAQAAAAIAAAADAAAABAAAAAUAAAAGAAAABwAAAAgAAAAJAAAACgAAAAsAAAAMAAAADQAAAA4AAAAPAAAAEAAAABEAAAASAAAAEwAAABQAAAAVAAAAFgAAABcAAAAYAAAAGQAAABoAAAAbAAAAHAAAAB0AAAAeAAAAHwAAAAMAAAAEAAAABQAAAAYAAAAHAAAACAAAAAkAAAAKAAAACwAAAAwAAAANAAAADgAAAA8AAAAQAAAAEQAAABIAAAATAAAAFAAAABUAAAAWAAAAFwAAABgAAAAZAAAAGgAAABsAAAAcAAAAHQAAAB4AAAAfAAAAIAAAACEAAAAiAAAAIwAAACUAAAAnAAAAKQAAACsAAAAvAAAAMwAAADsAAABDAAAAUwAAAGMAAACDAAAAAwEAAAMCAAADBAAAAwgAAAMQAAADIAAAA0AAAAOAAAADAAEAQeAPC1EBAAAAAQAAAAEAAAABAAAAAgAAAAIAAAADAAAAAwAAAAQAAAAEAAAABQAAAAcAAAAIAAAACQAAAAoAAAALAAAADAAAAA0AAAAOAAAADwAAABAAQcQQC4sBAQAAAAIAAAADAAAABAAAAAUAAAAGAAAABwAAAAgAAAAJAAAACgAAAAsAAAAMAAAADQAAAA4AAAAPAAAAEAAAABIAAAAUAAAAFgAAABgAAAAcAAAAIAAAACgAAAAwAAAAQAAAAIAAAAAAAQAAAAIAAAAEAAAACAAAABAAAAAgAAAAQAAAAIAAAAAAAQBBkBIL5gQBAAAAAQAAAAEAAAABAAAAAgAAAAIAAAADAAAAAwAAAAQAAAAGAAAABwAAAAgAAAAJAAAACgAAAAsAAAAMAAAADQAAAA4AAAAPAAAAEAAAAAEAAAAEAAAACAAAAAAAAAABAAEBBgAAAAAAAAQAAAAAEAAABAAAAAAgAAAFAQAAAAAAAAUDAAAAAAAABQQAAAAAAAAFBgAAAAAAAAUHAAAAAAAABQkAAAAAAAAFCgAAAAAAAAUMAAAAAAAABg4AAAAAAAEFEAAAAAAAAQUUAAAAAAABBRYAAAAAAAIFHAAAAAAAAwUgAAAAAAAEBTAAAAAgAAYFQAAAAAAABwWAAAAAAAAIBgABAAAAAAoGAAQAAAAADAYAEAAAIAAABAAAAAAAAAAEAQAAAAAAAAUCAAAAIAAABQQAAAAAAAAFBQAAACAAAAUHAAAAAAAABQgAAAAgAAAFCgAAAAAAAAULAAAAAAAABg0AAAAgAAEFEAAAAAAAAQUSAAAAIAABBRYAAAAAAAIFGAAAACAAAwUgAAAAAAADBSgAAAAAAAYEQAAAABAABgRAAAAAIAAHBYAAAAAAAAkGAAIAAAAACwYACAAAMAAABAAAAAAQAAAEAQAAACAAAAUCAAAAIAAABQMAAAAgAAAFBQAAACAAAAUGAAAAIAAABQgAAAAgAAAFCQAAACAAAAULAAAAIAAABQwAAAAAAAAGDwAAACAAAQUSAAAAIAABBRQAAAAgAAIFGAAAACAAAgUcAAAAIAADBSgAAAAgAAQFMAAAAAAAEAYAAAEAAAAPBgCAAAAAAA4GAEAAAAAADQYAIABBgBcLhwIBAAEBBQAAAAAAAAUAAAAAAAAGBD0AAAAAAAkF/QEAAAAADwX9fwAAAAAVBf3/HwAAAAMFBQAAAAAABwR9AAAAAAAMBf0PAAAAABIF/f8DAAAAFwX9/38AAAAFBR0AAAAAAAgE/QAAAAAADgX9PwAAAAAUBf3/DwAAAAIFAQAAABAABwR9AAAAAAALBf0HAAAAABEF/f8BAAAAFgX9/z8AAAAEBQ0AAAAQAAgE/QAAAAAADQX9HwAAAAATBf3/BwAAAAEFAQAAABAABgQ9AAAAAAAKBf0DAAAAABAF/f8AAAAAHAX9//8PAAAbBf3//wcAABoF/f//AwAAGQX9//8BAAAYBf3//wBBkBkLhgQBAAEBBgAAAAAAAAYDAAAAAAAABAQAAAAgAAAFBQAAAAAAAAUGAAAAAAAABQgAAAAAAAAFCQAAAAAAAAULAAAAAAAABg0AAAAAAAAGEAAAAAAAAAYTAAAAAAAABhYAAAAAAAAGGQAAAAAAAAYcAAAAAAAABh8AAAAAAAAGIgAAAAAAAQYlAAAAAAABBikAAAAAAAIGLwAAAAAAAwY7AAAAAAAEBlMAAAAAAAcGgwAAAAAACQYDAgAAEAAABAQAAAAAAAAEBQAAACAAAAUGAAAAAAAABQcAAAAgAAAFCQAAAAAAAAUKAAAAAAAABgwAAAAAAAAGDwAAAAAAAAYSAAAAAAAABhUAAAAAAAAGGAAAAAAAAAYbAAAAAAAABh4AAAAAAAAGIQAAAAAAAQYjAAAAAAABBicAAAAAAAIGKwAAAAAAAwYzAAAAAAAEBkMAAAAAAAUGYwAAAAAACAYDAQAAIAAABAQAAAAwAAAEBAAAABAAAAQFAAAAIAAABQcAAAAgAAAFCAAAACAAAAUKAAAAIAAABQsAAAAAAAAGDgAAAAAAAAYRAAAAAAAABhQAAAAAAAAGFwAAAAAAAAYaAAAAAAAABh0AAAAAAAAGIAAAAAAAEAYDAAEAAAAPBgOAAAAAAA4GA0AAAAAADQYDIAAAAAAMBgMQAAAAAAsGAwgAAAAACgYDBABBpB0L2QEBAAAAAwAAAAcAAAAPAAAAHwAAAD8AAAB/AAAA/wAAAP8BAAD/AwAA/wcAAP8PAAD/HwAA/z8AAP9/AAD//wAA//8BAP//AwD//wcA//8PAP//HwD//z8A//9/AP///wD///8B////A////wf///8P////H////z////9/AAAAAAEAAAACAAAABAAAAAAAAAACAAAABAAAAAgAAAAAAAAAAQAAAAIAAAABAAAABAAAAAQAAAAEAAAABAAAAAgAAAAIAAAACAAAAAcAAAAIAAAACQAAAAoAAAALAEGgIAsDwBBQ"; // node_modules/three/examples/jsm/loaders/KTX2Loader.js var _taskCache2 = /* @__PURE__ */ new WeakMap(); var _activeLoaders = 0; var _zstd; var KTX2Loader = class _KTX2Loader extends Loader { constructor(manager) { super(manager); this.transcoderPath = ""; this.transcoderBinary = null; this.transcoderPending = null; this.workerPool = new WorkerPool(); this.workerSourceURL = ""; this.workerConfig = null; if (typeof MSC_TRANSCODER !== "undefined") { console.warn( 'THREE.KTX2Loader: Please update to latest "basis_transcoder". "msc_basis_transcoder" is no longer supported in three.js r125+.' ); } } setTranscoderPath(path) { this.transcoderPath = path; return this; } setWorkerLimit(num) { this.workerPool.setWorkerLimit(num); return this; } detectSupport(renderer) { this.workerConfig = { astcSupported: renderer.extensions.has("WEBGL_compressed_texture_astc"), etc1Supported: renderer.extensions.has("WEBGL_compressed_texture_etc1"), etc2Supported: renderer.extensions.has("WEBGL_compressed_texture_etc"), dxtSupported: renderer.extensions.has("WEBGL_compressed_texture_s3tc"), bptcSupported: renderer.extensions.has("EXT_texture_compression_bptc"), pvrtcSupported: renderer.extensions.has("WEBGL_compressed_texture_pvrtc") || renderer.extensions.has("WEBKIT_WEBGL_compressed_texture_pvrtc") }; if (renderer.capabilities.isWebGL2) { this.workerConfig.etc1Supported = false; } return this; } init() { if (!this.transcoderPending) { const jsLoader = new FileLoader(this.manager); jsLoader.setPath(this.transcoderPath); jsLoader.setWithCredentials(this.withCredentials); const jsContent = jsLoader.loadAsync("basis_transcoder.js"); const binaryLoader = new FileLoader(this.manager); binaryLoader.setPath(this.transcoderPath); binaryLoader.setResponseType("arraybuffer"); binaryLoader.setWithCredentials(this.withCredentials); const binaryContent = binaryLoader.loadAsync("basis_transcoder.wasm"); this.transcoderPending = Promise.all([jsContent, binaryContent]).then(([jsContent2, binaryContent2]) => { const fn = _KTX2Loader.BasisWorker.toString(); const body = [ "/* constants */", "let _EngineFormat = " + JSON.stringify(_KTX2Loader.EngineFormat), "let _TranscoderFormat = " + JSON.stringify(_KTX2Loader.TranscoderFormat), "let _BasisFormat = " + JSON.stringify(_KTX2Loader.BasisFormat), "/* basis_transcoder.js */", jsContent2, "/* worker */", fn.substring(fn.indexOf("{") + 1, fn.lastIndexOf("}")) ].join("\n"); this.workerSourceURL = URL.createObjectURL(new Blob([body])); this.transcoderBinary = binaryContent2; this.workerPool.setWorkerCreator(() => { const worker = new Worker(this.workerSourceURL); const transcoderBinary = this.transcoderBinary.slice(0); worker.postMessage({ type: "init", config: this.workerConfig, transcoderBinary }, [transcoderBinary]); return worker; }); }); if (_activeLoaders > 0) { console.warn( "THREE.KTX2Loader: Multiple active KTX2 loaders may cause performance issues. Use a single KTX2Loader instance, or call .dispose() on old instances." ); } _activeLoaders++; } return this.transcoderPending; } load(url, onLoad, onProgress, onError) { if (this.workerConfig === null) { throw new Error("THREE.KTX2Loader: Missing initialization with `.detectSupport( renderer )`."); } const loader = new FileLoader(this.manager); loader.setResponseType("arraybuffer"); loader.setWithCredentials(this.withCredentials); loader.load(url, (buffer) => { if (_taskCache2.has(buffer)) { const cachedTask = _taskCache2.get(buffer); return cachedTask.promise.then(onLoad).catch(onError); } this._createTexture(buffer).then((texture) => onLoad ? onLoad(texture) : null).catch(onError); }, onProgress, onError); } _createTextureFrom(transcodeResult, container) { const { mipmaps, width, height, format, type, error, dfdTransferFn, dfdFlags } = transcodeResult; if (type === "error") return Promise.reject(error); const texture = container.layerCount > 1 ? new CompressedArrayTexture(mipmaps, width, height, container.layerCount, format, UnsignedByteType) : new CompressedTexture(mipmaps, width, height, format, UnsignedByteType); texture.minFilter = mipmaps.length === 1 ? LinearFilter : LinearMipmapLinearFilter; texture.magFilter = LinearFilter; texture.generateMipmaps = false; texture.needsUpdate = true; texture.encoding = dfdTransferFn === x ? sRGBEncoding : LinearEncoding; texture.premultiplyAlpha = !!(dfdFlags & p); return texture; } /** * @param {ArrayBuffer} buffer * @param {object?} config * @return {Promise} */ async _createTexture(buffer, config = {}) { const container = Pi(new Uint8Array(buffer)); if (container.vkFormat !== nt) { return createDataTexture(container); } const taskConfig = config; const texturePending = this.init().then(() => { return this.workerPool.postMessage({ type: "transcode", buffer, taskConfig }, [buffer]); }).then((e) => this._createTextureFrom(e.data, container)); _taskCache2.set(buffer, { promise: texturePending }); return texturePending; } dispose() { this.workerPool.dispose(); if (this.workerSourceURL) URL.revokeObjectURL(this.workerSourceURL); _activeLoaders--; return this; } }; KTX2Loader.BasisFormat = { ETC1S: 0, UASTC_4x4: 1 }; KTX2Loader.TranscoderFormat = { ETC1: 0, ETC2: 1, BC1: 2, BC3: 3, BC4: 4, BC5: 5, BC7_M6_OPAQUE_ONLY: 6, BC7_M5: 7, PVRTC1_4_RGB: 8, PVRTC1_4_RGBA: 9, ASTC_4x4: 10, ATC_RGB: 11, ATC_RGBA_INTERPOLATED_ALPHA: 12, RGBA32: 13, RGB565: 14, BGR565: 15, RGBA4444: 16 }; KTX2Loader.EngineFormat = { RGBAFormat, RGBA_ASTC_4x4_Format, RGBA_BPTC_Format, RGBA_ETC2_EAC_Format, RGBA_PVRTC_4BPPV1_Format, RGBA_S3TC_DXT5_Format, RGB_ETC1_Format, RGB_ETC2_Format, RGB_PVRTC_4BPPV1_Format, RGB_S3TC_DXT1_Format }; KTX2Loader.BasisWorker = function() { let config; let transcoderPending; let BasisModule; const EngineFormat = _EngineFormat; const TranscoderFormat = _TranscoderFormat; const BasisFormat = _BasisFormat; self.addEventListener("message", function(e) { const message = e.data; switch (message.type) { case "init": config = message.config; init(message.transcoderBinary); break; case "transcode": transcoderPending.then(() => { try { const { width, height, hasAlpha, mipmaps, format, dfdTransferFn, dfdFlags } = transcode(message.buffer); const buffers = []; for (let i = 0; i < mipmaps.length; ++i) { buffers.push(mipmaps[i].data.buffer); } self.postMessage({ type: "transcode", id: message.id, width, height, hasAlpha, mipmaps, format, dfdTransferFn, dfdFlags }, buffers); } catch (error) { console.error(error); self.postMessage({ type: "error", id: message.id, error: error.message }); } }); break; } }); function init(wasmBinary) { transcoderPending = new Promise((resolve) => { BasisModule = { wasmBinary, onRuntimeInitialized: resolve }; BASIS(BasisModule); }).then(() => { BasisModule.initializeBasis(); if (BasisModule.KTX2File === void 0) { console.warn("THREE.KTX2Loader: Please update Basis Universal transcoder."); } }); } function transcode(buffer) { const ktx2File = new BasisModule.KTX2File(new Uint8Array(buffer)); function cleanup() { ktx2File.close(); ktx2File.delete(); } if (!ktx2File.isValid()) { cleanup(); throw new Error("THREE.KTX2Loader: Invalid or unsupported .ktx2 file"); } const basisFormat = ktx2File.isUASTC() ? BasisFormat.UASTC_4x4 : BasisFormat.ETC1S; const width = ktx2File.getWidth(); const height = ktx2File.getHeight(); const layers = ktx2File.getLayers() || 1; const levels = ktx2File.getLevels(); const hasAlpha = ktx2File.getHasAlpha(); const dfdTransferFn = ktx2File.getDFDTransferFunc(); const dfdFlags = ktx2File.getDFDFlags(); const { transcoderFormat, engineFormat } = getTranscoderFormat(basisFormat, width, height, hasAlpha); if (!width || !height || !levels) { cleanup(); throw new Error("THREE.KTX2Loader: Invalid texture"); } if (!ktx2File.startTranscoding()) { cleanup(); throw new Error("THREE.KTX2Loader: .startTranscoding failed"); } const mipmaps = []; for (let mip = 0; mip < levels; mip++) { const layerMips = []; let mipWidth, mipHeight; for (let layer = 0; layer < layers; layer++) { const levelInfo = ktx2File.getImageLevelInfo(mip, layer, 0); mipWidth = levelInfo.origWidth; mipHeight = levelInfo.origHeight; const dst = new Uint8Array(ktx2File.getImageTranscodedSizeInBytes(mip, layer, 0, transcoderFormat)); const status = ktx2File.transcodeImage( dst, mip, layer, 0, transcoderFormat, 0, -1, -1 ); if (!status) { cleanup(); throw new Error("THREE.KTX2Loader: .transcodeImage failed."); } layerMips.push(dst); } mipmaps.push({ data: concat(layerMips), width: mipWidth, height: mipHeight }); } cleanup(); return { width, height, hasAlpha, mipmaps, format: engineFormat, dfdTransferFn, dfdFlags }; } const FORMAT_OPTIONS = [ { if: "astcSupported", basisFormat: [BasisFormat.UASTC_4x4], transcoderFormat: [TranscoderFormat.ASTC_4x4, TranscoderFormat.ASTC_4x4], engineFormat: [EngineFormat.RGBA_ASTC_4x4_Format, EngineFormat.RGBA_ASTC_4x4_Format], priorityETC1S: Infinity, priorityUASTC: 1, needsPowerOfTwo: false }, { if: "bptcSupported", basisFormat: [BasisFormat.ETC1S, BasisFormat.UASTC_4x4], transcoderFormat: [TranscoderFormat.BC7_M5, TranscoderFormat.BC7_M5], engineFormat: [EngineFormat.RGBA_BPTC_Format, EngineFormat.RGBA_BPTC_Format], priorityETC1S: 3, priorityUASTC: 2, needsPowerOfTwo: false }, { if: "dxtSupported", basisFormat: [BasisFormat.ETC1S, BasisFormat.UASTC_4x4], transcoderFormat: [TranscoderFormat.BC1, TranscoderFormat.BC3], engineFormat: [EngineFormat.RGB_S3TC_DXT1_Format, EngineFormat.RGBA_S3TC_DXT5_Format], priorityETC1S: 4, priorityUASTC: 5, needsPowerOfTwo: false }, { if: "etc2Supported", basisFormat: [BasisFormat.ETC1S, BasisFormat.UASTC_4x4], transcoderFormat: [TranscoderFormat.ETC1, TranscoderFormat.ETC2], engineFormat: [EngineFormat.RGB_ETC2_Format, EngineFormat.RGBA_ETC2_EAC_Format], priorityETC1S: 1, priorityUASTC: 3, needsPowerOfTwo: false }, { if: "etc1Supported", basisFormat: [BasisFormat.ETC1S, BasisFormat.UASTC_4x4], transcoderFormat: [TranscoderFormat.ETC1], engineFormat: [EngineFormat.RGB_ETC1_Format], priorityETC1S: 2, priorityUASTC: 4, needsPowerOfTwo: false }, { if: "pvrtcSupported", basisFormat: [BasisFormat.ETC1S, BasisFormat.UASTC_4x4], transcoderFormat: [TranscoderFormat.PVRTC1_4_RGB, TranscoderFormat.PVRTC1_4_RGBA], engineFormat: [EngineFormat.RGB_PVRTC_4BPPV1_Format, EngineFormat.RGBA_PVRTC_4BPPV1_Format], priorityETC1S: 5, priorityUASTC: 6, needsPowerOfTwo: true } ]; const ETC1S_OPTIONS = FORMAT_OPTIONS.sort(function(a, b) { return a.priorityETC1S - b.priorityETC1S; }); const UASTC_OPTIONS = FORMAT_OPTIONS.sort(function(a, b) { return a.priorityUASTC - b.priorityUASTC; }); function getTranscoderFormat(basisFormat, width, height, hasAlpha) { let transcoderFormat; let engineFormat; const options = basisFormat === BasisFormat.ETC1S ? ETC1S_OPTIONS : UASTC_OPTIONS; for (let i = 0; i < options.length; i++) { const opt = options[i]; if (!config[opt.if]) continue; if (!opt.basisFormat.includes(basisFormat)) continue; if (hasAlpha && opt.transcoderFormat.length < 2) continue; if (opt.needsPowerOfTwo && !(isPowerOfTwo2(width) && isPowerOfTwo2(height))) continue; transcoderFormat = opt.transcoderFormat[hasAlpha ? 1 : 0]; engineFormat = opt.engineFormat[hasAlpha ? 1 : 0]; return { transcoderFormat, engineFormat }; } console.warn("THREE.KTX2Loader: No suitable compressed texture format found. Decoding to RGBA32."); transcoderFormat = TranscoderFormat.RGBA32; engineFormat = EngineFormat.RGBAFormat; return { transcoderFormat, engineFormat }; } function isPowerOfTwo2(value) { if (value <= 2) return true; return (value & value - 1) === 0 && value !== 0; } function concat(arrays) { let totalByteLength = 0; for (const array of arrays) { totalByteLength += array.byteLength; } const result = new Uint8Array(totalByteLength); let byteOffset = 0; for (const array of arrays) { result.set(array, byteOffset); byteOffset += array.byteLength; } return result; } }; var FORMAT_MAP = { [Ae]: RGBAFormat, [pe]: RGBAFormat, [Ot]: RGBAFormat, [Ft]: RGBAFormat, [de]: RGFormat, [se]: RGFormat, [yt]: RGFormat, [dt]: RGFormat, [xe]: RedFormat, [$t]: RedFormat, [gt]: RedFormat, [ct]: RedFormat }; var TYPE_MAP = { [Ae]: FloatType, [pe]: HalfFloatType, [Ot]: UnsignedByteType, [Ft]: UnsignedByteType, [de]: FloatType, [se]: HalfFloatType, [yt]: UnsignedByteType, [dt]: UnsignedByteType, [xe]: FloatType, [$t]: HalfFloatType, [gt]: UnsignedByteType, [ct]: UnsignedByteType }; var ENCODING_MAP = { [Ft]: sRGBEncoding, [dt]: sRGBEncoding, [gt]: sRGBEncoding }; async function createDataTexture(container) { const { vkFormat, pixelWidth, pixelHeight, pixelDepth } = container; if (FORMAT_MAP[vkFormat] === void 0) { throw new Error("THREE.KTX2Loader: Unsupported vkFormat."); } const level = container.levels[0]; let levelData; let view2; if (container.supercompressionScheme === t) { levelData = level.levelData; } else if (container.supercompressionScheme === n) { if (!_zstd) { _zstd = new Promise(async (resolve) => { const zstd = new Q(); await zstd.init(); resolve(zstd); }); } levelData = (await _zstd).decode(level.levelData, level.uncompressedByteLength); } else { throw new Error("THREE.KTX2Loader: Unsupported supercompressionScheme."); } if (TYPE_MAP[vkFormat] === FloatType) { view2 = new Float32Array( levelData.buffer, levelData.byteOffset, levelData.byteLength / Float32Array.BYTES_PER_ELEMENT ); } else if (TYPE_MAP[vkFormat] === HalfFloatType) { view2 = new Uint16Array( levelData.buffer, levelData.byteOffset, levelData.byteLength / Uint16Array.BYTES_PER_ELEMENT ); } else { view2 = levelData; } const texture = pixelDepth === 0 ? new DataTexture(view2, pixelWidth, pixelHeight) : new Data3DTexture(view2, pixelWidth, pixelHeight, pixelDepth); texture.type = TYPE_MAP[vkFormat]; texture.format = FORMAT_MAP[vkFormat]; texture.encoding = ENCODING_MAP[vkFormat] || LinearEncoding; texture.needsUpdate = true; return Promise.resolve(texture); } // node_modules/@google/model-viewer/lib/utilities/cache-eviction-policy.js var _a; var _b; var $retainerCount = Symbol("retainerCount"); var $recentlyUsed = Symbol("recentlyUsed"); var $evict = Symbol("evict"); var $evictionThreshold = Symbol("evictionThreshold"); var $cache = Symbol("cache"); var CacheEvictionPolicy = class { constructor(cache2, evictionThreshold = 5) { this[_a] = /* @__PURE__ */ new Map(); this[_b] = []; this[$cache] = cache2; this[$evictionThreshold] = evictionThreshold; } /** * The eviction threshold is the maximum number of items to hold * in cache indefinitely. Items within the threshold (in recently * used order) will continue to be cached even if they have zero * retainers. */ set evictionThreshold(value) { this[$evictionThreshold] = value; this[$evict](); } get evictionThreshold() { return this[$evictionThreshold]; } /** * A reference to the cache that operates under this policy */ get cache() { return this[$cache]; } /** * Given an item key, returns the number of retainers of that item */ retainerCount(key) { return this[$retainerCount].get(key) || 0; } /** * Resets the internal tracking of cache item retainers. Use only in cases * where it is certain that all retained cache items have been accounted for! */ reset() { this[$retainerCount].clear(); this[$recentlyUsed] = []; } /** * Mark a given cache item as retained, where the item is represented * by its key. An item can have any number of retainers. */ retain(key) { if (!this[$retainerCount].has(key)) { this[$retainerCount].set(key, 0); } this[$retainerCount].set(key, this[$retainerCount].get(key) + 1); const recentlyUsedIndex = this[$recentlyUsed].indexOf(key); if (recentlyUsedIndex !== -1) { this[$recentlyUsed].splice(recentlyUsedIndex, 1); } this[$recentlyUsed].unshift(key); this[$evict](); } /** * Mark a given cache item as released by one of its retainers, where the item * is represented by its key. When all retainers of an item have released it, * the item is considered evictable. */ release(key) { if (this[$retainerCount].has(key)) { this[$retainerCount].set(key, Math.max(this[$retainerCount].get(key) - 1, 0)); } this[$evict](); } [(_a = $retainerCount, _b = $recentlyUsed, $evict)]() { if (this[$recentlyUsed].length < this[$evictionThreshold]) { return; } for (let i = this[$recentlyUsed].length - 1; i >= this[$evictionThreshold]; --i) { const key = this[$recentlyUsed][i]; const retainerCount = this[$retainerCount].get(key); if (retainerCount === 0) { this[$cache].delete(key); this[$recentlyUsed].splice(i, 1); } } } }; // node_modules/@google/model-viewer/lib/three-components/gltf-instance/VariantMaterialLoaderPlugin.js var ensureUniqueNames = (variantNames) => { const uniqueNames = []; const knownNames = /* @__PURE__ */ new Set(); for (const name of variantNames) { let uniqueName = name; let suffix = 0; while (knownNames.has(uniqueName)) { uniqueName = name + "." + ++suffix; } knownNames.add(uniqueName); uniqueNames.push(uniqueName); } return uniqueNames; }; var mappingsArrayToTable = (extensionDef) => { const table = /* @__PURE__ */ new Map(); for (const mapping of extensionDef.mappings) { for (const variant of mapping.variants) { table.set(variant, { material: null, gltfMaterialIndex: mapping.material }); } } return table; }; var GLTFMaterialsVariantsExtension = class { constructor(parser) { this.parser = parser; this.name = "KHR_materials_variants"; } // Note that the following properties will be overridden even if they are // pre-defined // - gltf.userData.variants // - mesh.userData.variantMaterials afterRoot(gltf) { const parser = this.parser; const json = parser.json; if (json.extensions === void 0 || json.extensions[this.name] === void 0) { return null; } const extensionDef = json.extensions[this.name]; const variantsDef = extensionDef.variants || []; const variants = ensureUniqueNames(variantsDef.map((v) => v.name)); for (const scene of gltf.scenes) { scene.traverse((object) => { const mesh = object; if (!mesh.isMesh) { return; } const association = parser.associations.get(mesh); if (association == null || association.meshes == null || association.primitives == null) { return; } const meshDef = json.meshes[association.meshes]; const primitivesDef = meshDef.primitives; const primitiveDef = primitivesDef[association.primitives]; const extensionsDef = primitiveDef.extensions; if (!extensionsDef || !extensionsDef[this.name]) { return; } mesh.userData.variantMaterials = mappingsArrayToTable(extensionsDef[this.name]); }); } gltf.userData.variants = variants; return Promise.resolve(); } }; // node_modules/@google/model-viewer/lib/three-components/CachingGLTFLoader.js var _a2; var _b2; var loadWithLoader = (url, loader, progressCallback = () => { }) => { const onProgress = (event) => { const fraction = event.loaded / event.total; progressCallback(Math.max(0, Math.min(1, isFinite(fraction) ? fraction : 1))); }; return new Promise((resolve, reject) => { loader.load(url, resolve, onProgress, reject); }); }; var fetchScript = (src) => { return new Promise((resolve, reject) => { const script = document.createElement("script"); document.body.appendChild(script); script.onload = resolve; script.onerror = reject; script.async = true; script.src = src; }); }; var cache = /* @__PURE__ */ new Map(); var preloaded = /* @__PURE__ */ new Map(); var dracoDecoderLocation; var dracoLoader = new DRACOLoader(); var ktx2TranscoderLocation; var ktx2Loader = new KTX2Loader(); var meshoptDecoderLocation; var meshoptDecoder; var $loader = Symbol("loader"); var $evictionPolicy = Symbol("evictionPolicy"); var $GLTFInstance = Symbol("GLTFInstance"); var CachingGLTFLoader = class _CachingGLTFLoader extends EventDispatcher { constructor(GLTFInstance2) { super(); this[_b2] = new GLTFLoader().register((parser) => new GLTFMaterialsVariantsExtension(parser)); this[$GLTFInstance] = GLTFInstance2; this[$loader].setDRACOLoader(dracoLoader); this[$loader].setKTX2Loader(ktx2Loader); } static setDRACODecoderLocation(url) { dracoDecoderLocation = url; dracoLoader.setDecoderPath(url); } static getDRACODecoderLocation() { return dracoDecoderLocation; } static setKTX2TranscoderLocation(url) { ktx2TranscoderLocation = url; ktx2Loader.setTranscoderPath(url); } static getKTX2TranscoderLocation() { return ktx2TranscoderLocation; } static setMeshoptDecoderLocation(url) { if (meshoptDecoderLocation !== url) { meshoptDecoderLocation = url; meshoptDecoder = fetchScript(url).then(() => MeshoptDecoder.ready).then(() => MeshoptDecoder); } } static getMeshoptDecoderLocation() { return meshoptDecoderLocation; } static initializeKTX2Loader(renderer) { ktx2Loader.detectSupport(renderer); } static get cache() { return cache; } /** @nocollapse */ static clearCache() { cache.forEach((_value, url) => { this.delete(url); }); this[$evictionPolicy].reset(); } static has(url) { return cache.has(url); } /** @nocollapse */ static async delete(url) { if (!this.has(url)) { return; } const gltfLoads = cache.get(url); preloaded.delete(url); cache.delete(url); const gltf = await gltfLoads; gltf.dispose(); } /** * Returns true if the model that corresponds to the specified url is * available in our local cache. */ static hasFinishedLoading(url) { return !!preloaded.get(url); } get [(_a2 = $evictionPolicy, _b2 = $loader, $evictionPolicy)]() { return this.constructor[$evictionPolicy]; } /** * Preloads a glTF, populating the cache. Returns a promise that resolves * when the cache is populated. */ async preload(url, element, progressCallback = () => { }) { this[$loader].setWithCredentials(_CachingGLTFLoader.withCredentials); this.dispatchEvent({ type: "preload", element, src: url }); if (!cache.has(url)) { if (meshoptDecoder != null) { this[$loader].setMeshoptDecoder(await meshoptDecoder); } const rawGLTFLoads = loadWithLoader(url, this[$loader], (progress) => { progressCallback(progress * 0.8); }); const GLTFInstance2 = this[$GLTFInstance]; const gltfInstanceLoads = rawGLTFLoads.then((rawGLTF) => { return GLTFInstance2.prepare(rawGLTF); }).then((preparedGLTF) => { progressCallback(0.9); return new GLTFInstance2(preparedGLTF); }).catch((reason) => { console.error(reason); return new GLTFInstance2(); }); cache.set(url, gltfInstanceLoads); } await cache.get(url); preloaded.set(url, true); if (progressCallback) { progressCallback(1); } } /** * Loads a glTF from the specified url and resolves a unique clone of the * glTF. If the glTF has already been loaded, makes a clone of the cached * copy. */ async load(url, element, progressCallback = () => { }) { await this.preload(url, element, progressCallback); const gltf = await cache.get(url); const clone2 = await gltf.clone(); this[$evictionPolicy].retain(url); clone2.dispose = () => { this[$evictionPolicy].release(url); }; return clone2; } }; CachingGLTFLoader[_a2] = new CacheEvictionPolicy(CachingGLTFLoader); // node_modules/three/examples/jsm/renderers/CSS2DRenderer.js var CSS2DObject = class extends Object3D { constructor(element = document.createElement("div")) { super(); this.isCSS2DObject = true; this.element = element; this.element.style.position = "absolute"; this.element.style.userSelect = "none"; this.element.setAttribute("draggable", false); this.addEventListener("removed", function() { this.traverse(function(object) { if (object.element instanceof Element && object.element.parentNode !== null) { object.element.parentNode.removeChild(object.element); } }); }); } copy(source, recursive) { super.copy(source, recursive); this.element = source.element.cloneNode(true); return this; } }; var _vector3 = new Vector3(); var _viewMatrix = new Matrix4(); var _viewProjectionMatrix = new Matrix4(); var _a3 = new Vector3(); var _b3 = new Vector3(); var CSS2DRenderer = class { constructor(parameters = {}) { const _this = this; let _width, _height; let _widthHalf, _heightHalf; const cache2 = { objects: /* @__PURE__ */ new WeakMap() }; const domElement = parameters.element !== void 0 ? parameters.element : document.createElement("div"); domElement.style.overflow = "hidden"; this.domElement = domElement; this.getSize = function() { return { width: _width, height: _height }; }; this.render = function(scene, camera2) { if (scene.matrixWorldAutoUpdate === true) scene.updateMatrixWorld(); if (camera2.parent === null && camera2.matrixWorldAutoUpdate === true) camera2.updateMatrixWorld(); _viewMatrix.copy(camera2.matrixWorldInverse); _viewProjectionMatrix.multiplyMatrices(camera2.projectionMatrix, _viewMatrix); renderObject(scene, scene, camera2); zOrder2(scene); }; this.setSize = function(width, height) { _width = width; _height = height; _widthHalf = _width / 2; _heightHalf = _height / 2; domElement.style.width = width + "px"; domElement.style.height = height + "px"; }; function renderObject(object, scene, camera2) { if (object.isCSS2DObject) { _vector3.setFromMatrixPosition(object.matrixWorld); _vector3.applyMatrix4(_viewProjectionMatrix); const visible = object.visible === true && (_vector3.z >= -1 && _vector3.z <= 1) && object.layers.test(camera2.layers) === true; object.element.style.display = visible === true ? "" : "none"; if (visible === true) { object.onBeforeRender(_this, scene, camera2); const element = object.element; element.style.transform = "translate(-50%,-50%) translate(" + (_vector3.x * _widthHalf + _widthHalf) + "px," + (-_vector3.y * _heightHalf + _heightHalf) + "px)"; if (element.parentNode !== domElement) { domElement.appendChild(element); } object.onAfterRender(_this, scene, camera2); } const objectData = { distanceToCameraSquared: getDistanceToSquared(camera2, object) }; cache2.objects.set(object, objectData); } for (let i = 0, l = object.children.length; i < l; i++) { renderObject(object.children[i], scene, camera2); } } function getDistanceToSquared(object1, object2) { _a3.setFromMatrixPosition(object1.matrixWorld); _b3.setFromMatrixPosition(object2.matrixWorld); return _a3.distanceToSquared(_b3); } function filterAndFlatten(scene) { const result = []; scene.traverse(function(object) { if (object.isCSS2DObject) result.push(object); }); return result; } function zOrder2(scene) { const sorted = filterAndFlatten(scene).sort(function(a, b) { if (a.renderOrder !== b.renderOrder) { return b.renderOrder - a.renderOrder; } const distanceA = cache2.objects.get(a).distanceToCameraSquared; const distanceB = cache2.objects.get(b).distanceToCameraSquared; return distanceA - distanceB; }); const zMax = sorted.length; for (let i = 0, l = sorted.length; i < l; i++) { sorted[i].element.style.zIndex = zMax - i; } } } }; // node_modules/three/examples/jsm/exporters/GLTFExporter.js var GLTFExporter = class { constructor() { this.pluginCallbacks = []; this.register(function(writer) { return new GLTFLightExtension(writer); }); this.register(function(writer) { return new GLTFMaterialsUnlitExtension2(writer); }); this.register(function(writer) { return new GLTFMaterialsPBRSpecularGlossiness(writer); }); this.register(function(writer) { return new GLTFMaterialsTransmissionExtension2(writer); }); this.register(function(writer) { return new GLTFMaterialsVolumeExtension2(writer); }); this.register(function(writer) { return new GLTFMaterialsClearcoatExtension2(writer); }); this.register(function(writer) { return new GLTFMaterialsIridescenceExtension2(writer); }); } register(callback) { if (this.pluginCallbacks.indexOf(callback) === -1) { this.pluginCallbacks.push(callback); } return this; } unregister(callback) { if (this.pluginCallbacks.indexOf(callback) !== -1) { this.pluginCallbacks.splice(this.pluginCallbacks.indexOf(callback), 1); } return this; } /** * Parse scenes and generate GLTF output * @param {Scene or [THREE.Scenes]} input Scene or Array of THREE.Scenes * @param {Function} onDone Callback on completed * @param {Function} onError Callback on errors * @param {Object} options options */ parse(input, onDone, onError, options) { const writer = new GLTFWriter(); const plugins = []; for (let i = 0, il = this.pluginCallbacks.length; i < il; i++) { plugins.push(this.pluginCallbacks[i](writer)); } writer.setPlugins(plugins); writer.write(input, onDone, options).catch(onError); } parseAsync(input, options) { const scope = this; return new Promise(function(resolve, reject) { scope.parse(input, resolve, reject, options); }); } }; var WEBGL_CONSTANTS2 = { POINTS: 0, LINES: 1, LINE_LOOP: 2, LINE_STRIP: 3, TRIANGLES: 4, TRIANGLE_STRIP: 5, TRIANGLE_FAN: 6, UNSIGNED_BYTE: 5121, UNSIGNED_SHORT: 5123, FLOAT: 5126, UNSIGNED_INT: 5125, ARRAY_BUFFER: 34962, ELEMENT_ARRAY_BUFFER: 34963, NEAREST: 9728, LINEAR: 9729, NEAREST_MIPMAP_NEAREST: 9984, LINEAR_MIPMAP_NEAREST: 9985, NEAREST_MIPMAP_LINEAR: 9986, LINEAR_MIPMAP_LINEAR: 9987, CLAMP_TO_EDGE: 33071, MIRRORED_REPEAT: 33648, REPEAT: 10497 }; var THREE_TO_WEBGL = {}; THREE_TO_WEBGL[NearestFilter] = WEBGL_CONSTANTS2.NEAREST; THREE_TO_WEBGL[NearestMipmapNearestFilter] = WEBGL_CONSTANTS2.NEAREST_MIPMAP_NEAREST; THREE_TO_WEBGL[NearestMipmapLinearFilter] = WEBGL_CONSTANTS2.NEAREST_MIPMAP_LINEAR; THREE_TO_WEBGL[LinearFilter] = WEBGL_CONSTANTS2.LINEAR; THREE_TO_WEBGL[LinearMipmapNearestFilter] = WEBGL_CONSTANTS2.LINEAR_MIPMAP_NEAREST; THREE_TO_WEBGL[LinearMipmapLinearFilter] = WEBGL_CONSTANTS2.LINEAR_MIPMAP_LINEAR; THREE_TO_WEBGL[ClampToEdgeWrapping] = WEBGL_CONSTANTS2.CLAMP_TO_EDGE; THREE_TO_WEBGL[RepeatWrapping] = WEBGL_CONSTANTS2.REPEAT; THREE_TO_WEBGL[MirroredRepeatWrapping] = WEBGL_CONSTANTS2.MIRRORED_REPEAT; var PATH_PROPERTIES2 = { scale: "scale", position: "translation", quaternion: "rotation", morphTargetInfluences: "weights" }; var GLB_HEADER_BYTES = 12; var GLB_HEADER_MAGIC = 1179937895; var GLB_VERSION = 2; var GLB_CHUNK_PREFIX_BYTES = 8; var GLB_CHUNK_TYPE_JSON = 1313821514; var GLB_CHUNK_TYPE_BIN = 5130562; function equalArray(array1, array2) { return array1.length === array2.length && array1.every(function(element, index) { return element === array2[index]; }); } function stringToArrayBuffer(text) { return new TextEncoder().encode(text).buffer; } function isIdentityMatrix(matrix) { return equalArray(matrix.elements, [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1]); } function getMinMax(attribute, start, count) { const output = { min: new Array(attribute.itemSize).fill(Number.POSITIVE_INFINITY), max: new Array(attribute.itemSize).fill(Number.NEGATIVE_INFINITY) }; for (let i = start; i < start + count; i++) { for (let a = 0; a < attribute.itemSize; a++) { let value; if (attribute.itemSize > 4) { value = attribute.array[i * attribute.itemSize + a]; } else { if (a === 0) value = attribute.getX(i); else if (a === 1) value = attribute.getY(i); else if (a === 2) value = attribute.getZ(i); else if (a === 3) value = attribute.getW(i); } output.min[a] = Math.min(output.min[a], value); output.max[a] = Math.max(output.max[a], value); } } return output; } function getPaddedBufferSize(bufferSize) { return Math.ceil(bufferSize / 4) * 4; } function getPaddedArrayBuffer(arrayBuffer, paddingByte = 0) { const paddedLength = getPaddedBufferSize(arrayBuffer.byteLength); if (paddedLength !== arrayBuffer.byteLength) { const array = new Uint8Array(paddedLength); array.set(new Uint8Array(arrayBuffer)); if (paddingByte !== 0) { for (let i = arrayBuffer.byteLength; i < paddedLength; i++) { array[i] = paddingByte; } } return array.buffer; } return arrayBuffer; } function getCanvas() { if (typeof document === "undefined" && typeof OffscreenCanvas !== "undefined") { return new OffscreenCanvas(1, 1); } return document.createElement("canvas"); } function getToBlobPromise(canvas, mimeType) { if (canvas.toBlob !== void 0) { return new Promise((resolve) => canvas.toBlob(resolve, mimeType)); } let quality; if (mimeType === "image/jpeg") { quality = 0.92; } else if (mimeType === "image/webp") { quality = 0.8; } return canvas.convertToBlob({ type: mimeType, quality }); } var GLTFWriter = class { constructor() { this.plugins = []; this.options = {}; this.pending = []; this.buffers = []; this.byteOffset = 0; this.buffers = []; this.nodeMap = /* @__PURE__ */ new Map(); this.skins = []; this.extensionsUsed = {}; this.uids = /* @__PURE__ */ new Map(); this.uid = 0; this.json = { asset: { version: "2.0", generator: "THREE.GLTFExporter" } }; this.cache = { meshes: /* @__PURE__ */ new Map(), attributes: /* @__PURE__ */ new Map(), attributesNormalized: /* @__PURE__ */ new Map(), materials: /* @__PURE__ */ new Map(), textures: /* @__PURE__ */ new Map(), images: /* @__PURE__ */ new Map() }; } setPlugins(plugins) { this.plugins = plugins; } /** * Parse scenes and generate GLTF output * @param {Scene or [THREE.Scenes]} input Scene or Array of THREE.Scenes * @param {Function} onDone Callback on completed * @param {Object} options options */ async write(input, onDone, options) { this.options = Object.assign({}, { // default options binary: false, trs: false, onlyVisible: true, maxTextureSize: Infinity, animations: [], includeCustomExtensions: false }, options); if (this.options.animations.length > 0) { this.options.trs = true; } this.processInput(input); await Promise.all(this.pending); const writer = this; const buffers = writer.buffers; const json = writer.json; options = writer.options; const extensionsUsed = writer.extensionsUsed; const blob = new Blob(buffers, { type: "application/octet-stream" }); const extensionsUsedList = Object.keys(extensionsUsed); if (extensionsUsedList.length > 0) json.extensionsUsed = extensionsUsedList; if (json.buffers && json.buffers.length > 0) json.buffers[0].byteLength = blob.size; if (options.binary === true) { const reader = new FileReader(); reader.readAsArrayBuffer(blob); reader.onloadend = function() { const binaryChunk = getPaddedArrayBuffer(reader.result); const binaryChunkPrefix = new DataView(new ArrayBuffer(GLB_CHUNK_PREFIX_BYTES)); binaryChunkPrefix.setUint32(0, binaryChunk.byteLength, true); binaryChunkPrefix.setUint32(4, GLB_CHUNK_TYPE_BIN, true); const jsonChunk = getPaddedArrayBuffer(stringToArrayBuffer(JSON.stringify(json)), 32); const jsonChunkPrefix = new DataView(new ArrayBuffer(GLB_CHUNK_PREFIX_BYTES)); jsonChunkPrefix.setUint32(0, jsonChunk.byteLength, true); jsonChunkPrefix.setUint32(4, GLB_CHUNK_TYPE_JSON, true); const header = new ArrayBuffer(GLB_HEADER_BYTES); const headerView = new DataView(header); headerView.setUint32(0, GLB_HEADER_MAGIC, true); headerView.setUint32(4, GLB_VERSION, true); const totalByteLength = GLB_HEADER_BYTES + jsonChunkPrefix.byteLength + jsonChunk.byteLength + binaryChunkPrefix.byteLength + binaryChunk.byteLength; headerView.setUint32(8, totalByteLength, true); const glbBlob = new Blob([ header, jsonChunkPrefix, jsonChunk, binaryChunkPrefix, binaryChunk ], { type: "application/octet-stream" }); const glbReader = new FileReader(); glbReader.readAsArrayBuffer(glbBlob); glbReader.onloadend = function() { onDone(glbReader.result); }; }; } else { if (json.buffers && json.buffers.length > 0) { const reader = new FileReader(); reader.readAsDataURL(blob); reader.onloadend = function() { const base64data = reader.result; json.buffers[0].uri = base64data; onDone(json); }; } else { onDone(json); } } } /** * Serializes a userData. * * @param {THREE.Object3D|THREE.Material} object * @param {Object} objectDef */ serializeUserData(object, objectDef) { if (Object.keys(object.userData).length === 0) return; const options = this.options; const extensionsUsed = this.extensionsUsed; try { const json = JSON.parse(JSON.stringify(object.userData)); if (options.includeCustomExtensions && json.gltfExtensions) { if (objectDef.extensions === void 0) objectDef.extensions = {}; for (const extensionName in json.gltfExtensions) { objectDef.extensions[extensionName] = json.gltfExtensions[extensionName]; extensionsUsed[extensionName] = true; } delete json.gltfExtensions; } if (Object.keys(json).length > 0) objectDef.extras = json; } catch (error) { console.warn("THREE.GLTFExporter: userData of '" + object.name + "' won't be serialized because of JSON.stringify error - " + error.message); } } /** * Returns ids for buffer attributes. * @param {Object} object * @return {Integer} */ getUID(attribute, isRelativeCopy = false) { if (this.uids.has(attribute) === false) { const uids2 = /* @__PURE__ */ new Map(); uids2.set(true, this.uid++); uids2.set(false, this.uid++); this.uids.set(attribute, uids2); } const uids = this.uids.get(attribute); return uids.get(isRelativeCopy); } /** * Checks if normal attribute values are normalized. * * @param {BufferAttribute} normal * @returns {Boolean} */ isNormalizedNormalAttribute(normal) { const cache2 = this.cache; if (cache2.attributesNormalized.has(normal)) return false; const v = new Vector3(); for (let i = 0, il = normal.count; i < il; i++) { if (Math.abs(v.fromBufferAttribute(normal, i).length() - 1) > 5e-4) return false; } return true; } /** * Creates normalized normal buffer attribute. * * @param {BufferAttribute} normal * @returns {BufferAttribute} * */ createNormalizedNormalAttribute(normal) { const cache2 = this.cache; if (cache2.attributesNormalized.has(normal)) return cache2.attributesNormalized.get(normal); const attribute = normal.clone(); const v = new Vector3(); for (let i = 0, il = attribute.count; i < il; i++) { v.fromBufferAttribute(attribute, i); if (v.x === 0 && v.y === 0 && v.z === 0) { v.setX(1); } else { v.normalize(); } attribute.setXYZ(i, v.x, v.y, v.z); } cache2.attributesNormalized.set(normal, attribute); return attribute; } /** * Applies a texture transform, if present, to the map definition. Requires * the KHR_texture_transform extension. * * @param {Object} mapDef * @param {THREE.Texture} texture */ applyTextureTransform(mapDef, texture) { let didTransform = false; const transformDef = {}; if (texture.offset.x !== 0 || texture.offset.y !== 0) { transformDef.offset = texture.offset.toArray(); didTransform = true; } if (texture.rotation !== 0) { transformDef.rotation = texture.rotation; didTransform = true; } if (texture.repeat.x !== 1 || texture.repeat.y !== 1) { transformDef.scale = texture.repeat.toArray(); didTransform = true; } if (didTransform) { mapDef.extensions = mapDef.extensions || {}; mapDef.extensions["KHR_texture_transform"] = transformDef; this.extensionsUsed["KHR_texture_transform"] = true; } } buildMetalRoughTexture(metalnessMap, roughnessMap) { if (metalnessMap === roughnessMap) return metalnessMap; function getEncodingConversion(map) { if (map.encoding === sRGBEncoding) { return function SRGBToLinear2(c) { return c < 0.04045 ? c * 0.0773993808 : Math.pow(c * 0.9478672986 + 0.0521327014, 2.4); }; } return function LinearToLinear(c) { return c; }; } console.warn("THREE.GLTFExporter: Merged metalnessMap and roughnessMap textures."); const metalness = metalnessMap == null ? void 0 : metalnessMap.image; const roughness = roughnessMap == null ? void 0 : roughnessMap.image; const width = Math.max((metalness == null ? void 0 : metalness.width) || 0, (roughness == null ? void 0 : roughness.width) || 0); const height = Math.max((metalness == null ? void 0 : metalness.height) || 0, (roughness == null ? void 0 : roughness.height) || 0); const canvas = getCanvas(); canvas.width = width; canvas.height = height; const context = canvas.getContext("2d"); context.fillStyle = "#00ffff"; context.fillRect(0, 0, width, height); const composite = context.getImageData(0, 0, width, height); if (metalness) { context.drawImage(metalness, 0, 0, width, height); const convert = getEncodingConversion(metalnessMap); const data = context.getImageData(0, 0, width, height).data; for (let i = 2; i < data.length; i += 4) { composite.data[i] = convert(data[i] / 256) * 256; } } if (roughness) { context.drawImage(roughness, 0, 0, width, height); const convert = getEncodingConversion(roughnessMap); const data = context.getImageData(0, 0, width, height).data; for (let i = 1; i < data.length; i += 4) { composite.data[i] = convert(data[i] / 256) * 256; } } context.putImageData(composite, 0, 0); const reference = metalnessMap || roughnessMap; const texture = reference.clone(); texture.source = new Source(canvas); texture.encoding = LinearEncoding; return texture; } /** * Process a buffer to append to the default one. * @param {ArrayBuffer} buffer * @return {Integer} */ processBuffer(buffer) { const json = this.json; const buffers = this.buffers; if (!json.buffers) json.buffers = [{ byteLength: 0 }]; buffers.push(buffer); return 0; } /** * Process and generate a BufferView * @param {BufferAttribute} attribute * @param {number} componentType * @param {number} start * @param {number} count * @param {number} target (Optional) Target usage of the BufferView * @return {Object} */ processBufferView(attribute, componentType, start, count, target2) { const json = this.json; if (!json.bufferViews) json.bufferViews = []; let componentSize; if (componentType === WEBGL_CONSTANTS2.UNSIGNED_BYTE) { componentSize = 1; } else if (componentType === WEBGL_CONSTANTS2.UNSIGNED_SHORT) { componentSize = 2; } else { componentSize = 4; } const byteLength = getPaddedBufferSize(count * attribute.itemSize * componentSize); const dataView = new DataView(new ArrayBuffer(byteLength)); let offset = 0; for (let i = start; i < start + count; i++) { for (let a = 0; a < attribute.itemSize; a++) { let value; if (attribute.itemSize > 4) { value = attribute.array[i * attribute.itemSize + a]; } else { if (a === 0) value = attribute.getX(i); else if (a === 1) value = attribute.getY(i); else if (a === 2) value = attribute.getZ(i); else if (a === 3) value = attribute.getW(i); } if (componentType === WEBGL_CONSTANTS2.FLOAT) { dataView.setFloat32(offset, value, true); } else if (componentType === WEBGL_CONSTANTS2.UNSIGNED_INT) { dataView.setUint32(offset, value, true); } else if (componentType === WEBGL_CONSTANTS2.UNSIGNED_SHORT) { dataView.setUint16(offset, value, true); } else if (componentType === WEBGL_CONSTANTS2.UNSIGNED_BYTE) { dataView.setUint8(offset, value); } offset += componentSize; } } const bufferViewDef = { buffer: this.processBuffer(dataView.buffer), byteOffset: this.byteOffset, byteLength }; if (target2 !== void 0) bufferViewDef.target = target2; if (target2 === WEBGL_CONSTANTS2.ARRAY_BUFFER) { bufferViewDef.byteStride = attribute.itemSize * componentSize; } this.byteOffset += byteLength; json.bufferViews.push(bufferViewDef); const output = { id: json.bufferViews.length - 1, byteLength: 0 }; return output; } /** * Process and generate a BufferView from an image Blob. * @param {Blob} blob * @return {Promise} */ processBufferViewImage(blob) { const writer = this; const json = writer.json; if (!json.bufferViews) json.bufferViews = []; return new Promise(function(resolve) { const reader = new FileReader(); reader.readAsArrayBuffer(blob); reader.onloadend = function() { const buffer = getPaddedArrayBuffer(reader.result); const bufferViewDef = { buffer: writer.processBuffer(buffer), byteOffset: writer.byteOffset, byteLength: buffer.byteLength }; writer.byteOffset += buffer.byteLength; resolve(json.bufferViews.push(bufferViewDef) - 1); }; }); } /** * Process attribute to generate an accessor * @param {BufferAttribute} attribute Attribute to process * @param {THREE.BufferGeometry} geometry (Optional) Geometry used for truncated draw range * @param {Integer} start (Optional) * @param {Integer} count (Optional) * @return {Integer|null} Index of the processed accessor on the "accessors" array */ processAccessor(attribute, geometry, start, count) { const json = this.json; const types = { 1: "SCALAR", 2: "VEC2", 3: "VEC3", 4: "VEC4", 16: "MAT4" }; let componentType; if (attribute.array.constructor === Float32Array) { componentType = WEBGL_CONSTANTS2.FLOAT; } else if (attribute.array.constructor === Uint32Array) { componentType = WEBGL_CONSTANTS2.UNSIGNED_INT; } else if (attribute.array.constructor === Uint16Array) { componentType = WEBGL_CONSTANTS2.UNSIGNED_SHORT; } else if (attribute.array.constructor === Uint8Array) { componentType = WEBGL_CONSTANTS2.UNSIGNED_BYTE; } else { throw new Error("THREE.GLTFExporter: Unsupported bufferAttribute component type."); } if (start === void 0) start = 0; if (count === void 0) count = attribute.count; if (count === 0) return null; const minMax = getMinMax(attribute, start, count); let bufferViewTarget; if (geometry !== void 0) { bufferViewTarget = attribute === geometry.index ? WEBGL_CONSTANTS2.ELEMENT_ARRAY_BUFFER : WEBGL_CONSTANTS2.ARRAY_BUFFER; } const bufferView = this.processBufferView(attribute, componentType, start, count, bufferViewTarget); const accessorDef = { bufferView: bufferView.id, byteOffset: bufferView.byteOffset, componentType, count, max: minMax.max, min: minMax.min, type: types[attribute.itemSize] }; if (attribute.normalized === true) accessorDef.normalized = true; if (!json.accessors) json.accessors = []; return json.accessors.push(accessorDef) - 1; } /** * Process image * @param {Image} image to process * @param {Integer} format of the image (RGBAFormat) * @param {Boolean} flipY before writing out the image * @param {String} mimeType export format * @return {Integer} Index of the processed texture in the "images" array */ processImage(image, format, flipY, mimeType = "image/png") { const writer = this; const cache2 = writer.cache; const json = writer.json; const options = writer.options; const pending = writer.pending; if (!cache2.images.has(image)) cache2.images.set(image, {}); const cachedImages = cache2.images.get(image); const key = mimeType + ":flipY/" + flipY.toString(); if (cachedImages[key] !== void 0) return cachedImages[key]; if (!json.images) json.images = []; const imageDef = { mimeType }; const canvas = getCanvas(); canvas.width = Math.min(image.width, options.maxTextureSize); canvas.height = Math.min(image.height, options.maxTextureSize); const ctx = canvas.getContext("2d"); if (flipY === true) { ctx.translate(0, canvas.height); ctx.scale(1, -1); } if (image.data !== void 0) { if (format !== RGBAFormat) { console.error("GLTFExporter: Only RGBAFormat is supported."); } if (image.width > options.maxTextureSize || image.height > options.maxTextureSize) { console.warn("GLTFExporter: Image size is bigger than maxTextureSize", image); } const data = new Uint8ClampedArray(image.height * image.width * 4); for (let i = 0; i < data.length; i += 4) { data[i + 0] = image.data[i + 0]; data[i + 1] = image.data[i + 1]; data[i + 2] = image.data[i + 2]; data[i + 3] = image.data[i + 3]; } ctx.putImageData(new ImageData(data, image.width, image.height), 0, 0); } else { ctx.drawImage(image, 0, 0, canvas.width, canvas.height); } if (options.binary === true) { pending.push( getToBlobPromise(canvas, mimeType).then((blob) => writer.processBufferViewImage(blob)).then((bufferViewIndex) => { imageDef.bufferView = bufferViewIndex; }) ); } else { if (canvas.toDataURL !== void 0) { imageDef.uri = canvas.toDataURL(mimeType); } else { pending.push( getToBlobPromise(canvas, mimeType).then((blob) => new FileReader().readAsDataURL(blob)).then((dataURL) => { imageDef.uri = dataURL; }) ); } } const index = json.images.push(imageDef) - 1; cachedImages[key] = index; return index; } /** * Process sampler * @param {Texture} map Texture to process * @return {Integer} Index of the processed texture in the "samplers" array */ processSampler(map) { const json = this.json; if (!json.samplers) json.samplers = []; const samplerDef = { magFilter: THREE_TO_WEBGL[map.magFilter], minFilter: THREE_TO_WEBGL[map.minFilter], wrapS: THREE_TO_WEBGL[map.wrapS], wrapT: THREE_TO_WEBGL[map.wrapT] }; return json.samplers.push(samplerDef) - 1; } /** * Process texture * @param {Texture} map Map to process * @return {Integer} Index of the processed texture in the "textures" array */ processTexture(map) { const cache2 = this.cache; const json = this.json; if (cache2.textures.has(map)) return cache2.textures.get(map); if (!json.textures) json.textures = []; let mimeType = map.userData.mimeType; if (mimeType === "image/webp") mimeType = "image/png"; const textureDef = { sampler: this.processSampler(map), source: this.processImage(map.image, map.format, map.flipY, mimeType) }; if (map.name) textureDef.name = map.name; this._invokeAll(function(ext) { ext.writeTexture && ext.writeTexture(map, textureDef); }); const index = json.textures.push(textureDef) - 1; cache2.textures.set(map, index); return index; } /** * Process material * @param {THREE.Material} material Material to process * @return {Integer|null} Index of the processed material in the "materials" array */ processMaterial(material) { const cache2 = this.cache; const json = this.json; if (cache2.materials.has(material)) return cache2.materials.get(material); if (material.isShaderMaterial) { console.warn("GLTFExporter: THREE.ShaderMaterial not supported."); return null; } if (!json.materials) json.materials = []; const materialDef = { pbrMetallicRoughness: {} }; if (material.isMeshStandardMaterial !== true && material.isMeshBasicMaterial !== true) { console.warn("GLTFExporter: Use MeshStandardMaterial or MeshBasicMaterial for best results."); } const color = material.color.toArray().concat([material.opacity]); if (!equalArray(color, [1, 1, 1, 1])) { materialDef.pbrMetallicRoughness.baseColorFactor = color; } if (material.isMeshStandardMaterial) { materialDef.pbrMetallicRoughness.metallicFactor = material.metalness; materialDef.pbrMetallicRoughness.roughnessFactor = material.roughness; } else { materialDef.pbrMetallicRoughness.metallicFactor = 0.5; materialDef.pbrMetallicRoughness.roughnessFactor = 0.5; } if (material.metalnessMap || material.roughnessMap) { const metalRoughTexture = this.buildMetalRoughTexture(material.metalnessMap, material.roughnessMap); const metalRoughMapDef = { index: this.processTexture(metalRoughTexture) }; this.applyTextureTransform(metalRoughMapDef, metalRoughTexture); materialDef.pbrMetallicRoughness.metallicRoughnessTexture = metalRoughMapDef; } if (material.map) { const baseColorMapDef = { index: this.processTexture(material.map) }; this.applyTextureTransform(baseColorMapDef, material.map); materialDef.pbrMetallicRoughness.baseColorTexture = baseColorMapDef; } if (material.emissive) { const emissive = material.emissive.clone().multiplyScalar(material.emissiveIntensity); const maxEmissiveComponent = Math.max(emissive.r, emissive.g, emissive.b); if (maxEmissiveComponent > 1) { emissive.multiplyScalar(1 / maxEmissiveComponent); console.warn("THREE.GLTFExporter: Some emissive components exceed 1; emissive has been limited"); } if (maxEmissiveComponent > 0) { materialDef.emissiveFactor = emissive.toArray(); } if (material.emissiveMap) { const emissiveMapDef = { index: this.processTexture(material.emissiveMap) }; this.applyTextureTransform(emissiveMapDef, material.emissiveMap); materialDef.emissiveTexture = emissiveMapDef; } } if (material.normalMap) { const normalMapDef = { index: this.processTexture(material.normalMap) }; if (material.normalScale && material.normalScale.x !== 1) { normalMapDef.scale = material.normalScale.x; } this.applyTextureTransform(normalMapDef, material.normalMap); materialDef.normalTexture = normalMapDef; } if (material.aoMap) { const occlusionMapDef = { index: this.processTexture(material.aoMap), texCoord: 1 }; if (material.aoMapIntensity !== 1) { occlusionMapDef.strength = material.aoMapIntensity; } this.applyTextureTransform(occlusionMapDef, material.aoMap); materialDef.occlusionTexture = occlusionMapDef; } if (material.transparent) { materialDef.alphaMode = "BLEND"; } else { if (material.alphaTest > 0) { materialDef.alphaMode = "MASK"; materialDef.alphaCutoff = material.alphaTest; } } if (material.side === DoubleSide) materialDef.doubleSided = true; if (material.name !== "") materialDef.name = material.name; this.serializeUserData(material, materialDef); this._invokeAll(function(ext) { ext.writeMaterial && ext.writeMaterial(material, materialDef); }); const index = json.materials.push(materialDef) - 1; cache2.materials.set(material, index); return index; } /** * Process mesh * @param {THREE.Mesh} mesh Mesh to process * @return {Integer|null} Index of the processed mesh in the "meshes" array */ processMesh(mesh) { const cache2 = this.cache; const json = this.json; const meshCacheKeyParts = [mesh.geometry.uuid]; if (Array.isArray(mesh.material)) { for (let i = 0, l = mesh.material.length; i < l; i++) { meshCacheKeyParts.push(mesh.material[i].uuid); } } else { meshCacheKeyParts.push(mesh.material.uuid); } const meshCacheKey = meshCacheKeyParts.join(":"); if (cache2.meshes.has(meshCacheKey)) return cache2.meshes.get(meshCacheKey); const geometry = mesh.geometry; let mode; if (mesh.isLineSegments) { mode = WEBGL_CONSTANTS2.LINES; } else if (mesh.isLineLoop) { mode = WEBGL_CONSTANTS2.LINE_LOOP; } else if (mesh.isLine) { mode = WEBGL_CONSTANTS2.LINE_STRIP; } else if (mesh.isPoints) { mode = WEBGL_CONSTANTS2.POINTS; } else { mode = mesh.material.wireframe ? WEBGL_CONSTANTS2.LINES : WEBGL_CONSTANTS2.TRIANGLES; } const meshDef = {}; const attributes = {}; const primitives = []; const targets = []; const nameConversion = { uv: "TEXCOORD_0", uv2: "TEXCOORD_1", color: "COLOR_0", skinWeight: "WEIGHTS_0", skinIndex: "JOINTS_0" }; const originalNormal = geometry.getAttribute("normal"); if (originalNormal !== void 0 && !this.isNormalizedNormalAttribute(originalNormal)) { console.warn("THREE.GLTFExporter: Creating normalized normal attribute from the non-normalized one."); geometry.setAttribute("normal", this.createNormalizedNormalAttribute(originalNormal)); } let modifiedAttribute = null; for (let attributeName in geometry.attributes) { if (attributeName.slice(0, 5) === "morph") continue; const attribute = geometry.attributes[attributeName]; attributeName = nameConversion[attributeName] || attributeName.toUpperCase(); const validVertexAttributes = /^(POSITION|NORMAL|TANGENT|TEXCOORD_\d+|COLOR_\d+|JOINTS_\d+|WEIGHTS_\d+)$/; if (!validVertexAttributes.test(attributeName)) attributeName = "_" + attributeName; if (cache2.attributes.has(this.getUID(attribute))) { attributes[attributeName] = cache2.attributes.get(this.getUID(attribute)); continue; } modifiedAttribute = null; const array = attribute.array; if (attributeName === "JOINTS_0" && !(array instanceof Uint16Array) && !(array instanceof Uint8Array)) { console.warn('GLTFExporter: Attribute "skinIndex" converted to type UNSIGNED_SHORT.'); modifiedAttribute = new BufferAttribute(new Uint16Array(array), attribute.itemSize, attribute.normalized); } const accessor = this.processAccessor(modifiedAttribute || attribute, geometry); if (accessor !== null) { attributes[attributeName] = accessor; cache2.attributes.set(this.getUID(attribute), accessor); } } if (originalNormal !== void 0) geometry.setAttribute("normal", originalNormal); if (Object.keys(attributes).length === 0) return null; if (mesh.morphTargetInfluences !== void 0 && mesh.morphTargetInfluences.length > 0) { const weights = []; const targetNames = []; const reverseDictionary = {}; if (mesh.morphTargetDictionary !== void 0) { for (const key in mesh.morphTargetDictionary) { reverseDictionary[mesh.morphTargetDictionary[key]] = key; } } for (let i = 0; i < mesh.morphTargetInfluences.length; ++i) { const target2 = {}; let warned = false; for (const attributeName in geometry.morphAttributes) { if (attributeName !== "position" && attributeName !== "normal") { if (!warned) { console.warn("GLTFExporter: Only POSITION and NORMAL morph are supported."); warned = true; } continue; } const attribute = geometry.morphAttributes[attributeName][i]; const gltfAttributeName = attributeName.toUpperCase(); const baseAttribute = geometry.attributes[attributeName]; if (cache2.attributes.has(this.getUID(attribute, true))) { target2[gltfAttributeName] = cache2.attributes.get(this.getUID(attribute, true)); continue; } const relativeAttribute = attribute.clone(); if (!geometry.morphTargetsRelative) { for (let j = 0, jl = attribute.count; j < jl; j++) { relativeAttribute.setXYZ( j, attribute.getX(j) - baseAttribute.getX(j), attribute.getY(j) - baseAttribute.getY(j), attribute.getZ(j) - baseAttribute.getZ(j) ); } } target2[gltfAttributeName] = this.processAccessor(relativeAttribute, geometry); cache2.attributes.set(this.getUID(baseAttribute, true), target2[gltfAttributeName]); } targets.push(target2); weights.push(mesh.morphTargetInfluences[i]); if (mesh.morphTargetDictionary !== void 0) targetNames.push(reverseDictionary[i]); } meshDef.weights = weights; if (targetNames.length > 0) { meshDef.extras = {}; meshDef.extras.targetNames = targetNames; } } const isMultiMaterial = Array.isArray(mesh.material); if (isMultiMaterial && geometry.groups.length === 0) return null; const materials = isMultiMaterial ? mesh.material : [mesh.material]; const groups = isMultiMaterial ? geometry.groups : [{ materialIndex: 0, start: void 0, count: void 0 }]; for (let i = 0, il = groups.length; i < il; i++) { const primitive = { mode, attributes }; this.serializeUserData(geometry, primitive); if (targets.length > 0) primitive.targets = targets; if (geometry.index !== null) { let cacheKey = this.getUID(geometry.index); if (groups[i].start !== void 0 || groups[i].count !== void 0) { cacheKey += ":" + groups[i].start + ":" + groups[i].count; } if (cache2.attributes.has(cacheKey)) { primitive.indices = cache2.attributes.get(cacheKey); } else { primitive.indices = this.processAccessor(geometry.index, geometry, groups[i].start, groups[i].count); cache2.attributes.set(cacheKey, primitive.indices); } if (primitive.indices === null) delete primitive.indices; } const material = this.processMaterial(materials[groups[i].materialIndex]); if (material !== null) primitive.material = material; primitives.push(primitive); } meshDef.primitives = primitives; if (!json.meshes) json.meshes = []; this._invokeAll(function(ext) { ext.writeMesh && ext.writeMesh(mesh, meshDef); }); const index = json.meshes.push(meshDef) - 1; cache2.meshes.set(meshCacheKey, index); return index; } /** * Process camera * @param {THREE.Camera} camera Camera to process * @return {Integer} Index of the processed mesh in the "camera" array */ processCamera(camera2) { const json = this.json; if (!json.cameras) json.cameras = []; const isOrtho = camera2.isOrthographicCamera; const cameraDef = { type: isOrtho ? "orthographic" : "perspective" }; if (isOrtho) { cameraDef.orthographic = { xmag: camera2.right * 2, ymag: camera2.top * 2, zfar: camera2.far <= 0 ? 1e-3 : camera2.far, znear: camera2.near < 0 ? 0 : camera2.near }; } else { cameraDef.perspective = { aspectRatio: camera2.aspect, yfov: MathUtils.degToRad(camera2.fov), zfar: camera2.far <= 0 ? 1e-3 : camera2.far, znear: camera2.near < 0 ? 0 : camera2.near }; } if (camera2.name !== "") cameraDef.name = camera2.type; return json.cameras.push(cameraDef) - 1; } /** * Creates glTF animation entry from AnimationClip object. * * Status: * - Only properties listed in PATH_PROPERTIES may be animated. * * @param {THREE.AnimationClip} clip * @param {THREE.Object3D} root * @return {number|null} */ processAnimation(clip, root) { const json = this.json; const nodeMap = this.nodeMap; if (!json.animations) json.animations = []; clip = GLTFExporter.Utils.mergeMorphTargetTracks(clip.clone(), root); const tracks = clip.tracks; const channels = []; const samplers = []; for (let i = 0; i < tracks.length; ++i) { const track = tracks[i]; const trackBinding = PropertyBinding.parseTrackName(track.name); let trackNode = PropertyBinding.findNode(root, trackBinding.nodeName); const trackProperty = PATH_PROPERTIES2[trackBinding.propertyName]; if (trackBinding.objectName === "bones") { if (trackNode.isSkinnedMesh === true) { trackNode = trackNode.skeleton.getBoneByName(trackBinding.objectIndex); } else { trackNode = void 0; } } if (!trackNode || !trackProperty) { console.warn('THREE.GLTFExporter: Could not export animation track "%s".', track.name); return null; } const inputItemSize = 1; let outputItemSize = track.values.length / track.times.length; if (trackProperty === PATH_PROPERTIES2.morphTargetInfluences) { outputItemSize /= trackNode.morphTargetInfluences.length; } let interpolation; if (track.createInterpolant.isInterpolantFactoryMethodGLTFCubicSpline === true) { interpolation = "CUBICSPLINE"; outputItemSize /= 3; } else if (track.getInterpolation() === InterpolateDiscrete) { interpolation = "STEP"; } else { interpolation = "LINEAR"; } samplers.push({ input: this.processAccessor(new BufferAttribute(track.times, inputItemSize)), output: this.processAccessor(new BufferAttribute(track.values, outputItemSize)), interpolation }); channels.push({ sampler: samplers.length - 1, target: { node: nodeMap.get(trackNode), path: trackProperty } }); } json.animations.push({ name: clip.name || "clip_" + json.animations.length, samplers, channels }); return json.animations.length - 1; } /** * @param {THREE.Object3D} object * @return {number|null} */ processSkin(object) { const json = this.json; const nodeMap = this.nodeMap; const node = json.nodes[nodeMap.get(object)]; const skeleton = object.skeleton; if (skeleton === void 0) return null; const rootJoint = object.skeleton.bones[0]; if (rootJoint === void 0) return null; const joints = []; const inverseBindMatrices = new Float32Array(skeleton.bones.length * 16); const temporaryBoneInverse = new Matrix4(); for (let i = 0; i < skeleton.bones.length; ++i) { joints.push(nodeMap.get(skeleton.bones[i])); temporaryBoneInverse.copy(skeleton.boneInverses[i]); temporaryBoneInverse.multiply(object.bindMatrix).toArray(inverseBindMatrices, i * 16); } if (json.skins === void 0) json.skins = []; json.skins.push({ inverseBindMatrices: this.processAccessor(new BufferAttribute(inverseBindMatrices, 16)), joints, skeleton: nodeMap.get(rootJoint) }); const skinIndex = node.skin = json.skins.length - 1; return skinIndex; } /** * Process Object3D node * @param {THREE.Object3D} node Object3D to processNode * @return {Integer} Index of the node in the nodes list */ processNode(object) { const json = this.json; const options = this.options; const nodeMap = this.nodeMap; if (!json.nodes) json.nodes = []; const nodeDef = {}; if (options.trs) { const rotation = object.quaternion.toArray(); const position = object.position.toArray(); const scale = object.scale.toArray(); if (!equalArray(rotation, [0, 0, 0, 1])) { nodeDef.rotation = rotation; } if (!equalArray(position, [0, 0, 0])) { nodeDef.translation = position; } if (!equalArray(scale, [1, 1, 1])) { nodeDef.scale = scale; } } else { if (object.matrixAutoUpdate) { object.updateMatrix(); } if (isIdentityMatrix(object.matrix) === false) { nodeDef.matrix = object.matrix.elements; } } if (object.name !== "") nodeDef.name = String(object.name); this.serializeUserData(object, nodeDef); if (object.isMesh || object.isLine || object.isPoints) { const meshIndex = this.processMesh(object); if (meshIndex !== null) nodeDef.mesh = meshIndex; } else if (object.isCamera) { nodeDef.camera = this.processCamera(object); } if (object.isSkinnedMesh) this.skins.push(object); if (object.children.length > 0) { const children = []; for (let i = 0, l = object.children.length; i < l; i++) { const child = object.children[i]; if (child.visible || options.onlyVisible === false) { const nodeIndex2 = this.processNode(child); if (nodeIndex2 !== null) children.push(nodeIndex2); } } if (children.length > 0) nodeDef.children = children; } this._invokeAll(function(ext) { ext.writeNode && ext.writeNode(object, nodeDef); }); const nodeIndex = json.nodes.push(nodeDef) - 1; nodeMap.set(object, nodeIndex); return nodeIndex; } /** * Process Scene * @param {Scene} node Scene to process */ processScene(scene) { const json = this.json; const options = this.options; if (!json.scenes) { json.scenes = []; json.scene = 0; } const sceneDef = {}; if (scene.name !== "") sceneDef.name = scene.name; json.scenes.push(sceneDef); const nodes = []; for (let i = 0, l = scene.children.length; i < l; i++) { const child = scene.children[i]; if (child.visible || options.onlyVisible === false) { const nodeIndex = this.processNode(child); if (nodeIndex !== null) nodes.push(nodeIndex); } } if (nodes.length > 0) sceneDef.nodes = nodes; this.serializeUserData(scene, sceneDef); } /** * Creates a Scene to hold a list of objects and parse it * @param {Array} objects List of objects to process */ processObjects(objects) { const scene = new Scene(); scene.name = "AuxScene"; for (let i = 0; i < objects.length; i++) { scene.children.push(objects[i]); } this.processScene(scene); } /** * @param {THREE.Object3D|Array} input */ processInput(input) { const options = this.options; input = input instanceof Array ? input : [input]; this._invokeAll(function(ext) { ext.beforeParse && ext.beforeParse(input); }); const objectsWithoutScene = []; for (let i = 0; i < input.length; i++) { if (input[i] instanceof Scene) { this.processScene(input[i]); } else { objectsWithoutScene.push(input[i]); } } if (objectsWithoutScene.length > 0) this.processObjects(objectsWithoutScene); for (let i = 0; i < this.skins.length; ++i) { this.processSkin(this.skins[i]); } for (let i = 0; i < options.animations.length; ++i) { this.processAnimation(options.animations[i], input[0]); } this._invokeAll(function(ext) { ext.afterParse && ext.afterParse(input); }); } _invokeAll(func) { for (let i = 0, il = this.plugins.length; i < il; i++) { func(this.plugins[i]); } } }; var GLTFLightExtension = class { constructor(writer) { this.writer = writer; this.name = "KHR_lights_punctual"; } writeNode(light, nodeDef) { if (!light.isLight) return; if (!light.isDirectionalLight && !light.isPointLight && !light.isSpotLight) { console.warn("THREE.GLTFExporter: Only directional, point, and spot lights are supported.", light); return; } const writer = this.writer; const json = writer.json; const extensionsUsed = writer.extensionsUsed; const lightDef = {}; if (light.name) lightDef.name = light.name; lightDef.color = light.color.toArray(); lightDef.intensity = light.intensity; if (light.isDirectionalLight) { lightDef.type = "directional"; } else if (light.isPointLight) { lightDef.type = "point"; if (light.distance > 0) lightDef.range = light.distance; } else if (light.isSpotLight) { lightDef.type = "spot"; if (light.distance > 0) lightDef.range = light.distance; lightDef.spot = {}; lightDef.spot.innerConeAngle = (light.penumbra - 1) * light.angle * -1; lightDef.spot.outerConeAngle = light.angle; } if (light.decay !== void 0 && light.decay !== 2) { console.warn("THREE.GLTFExporter: Light decay may be lost. glTF is physically-based, and expects light.decay=2."); } if (light.target && (light.target.parent !== light || light.target.position.x !== 0 || light.target.position.y !== 0 || light.target.position.z !== -1)) { console.warn("THREE.GLTFExporter: Light direction may be lost. For best results, make light.target a child of the light with position 0,0,-1."); } if (!extensionsUsed[this.name]) { json.extensions = json.extensions || {}; json.extensions[this.name] = { lights: [] }; extensionsUsed[this.name] = true; } const lights = json.extensions[this.name].lights; lights.push(lightDef); nodeDef.extensions = nodeDef.extensions || {}; nodeDef.extensions[this.name] = { light: lights.length - 1 }; } }; var GLTFMaterialsUnlitExtension2 = class { constructor(writer) { this.writer = writer; this.name = "KHR_materials_unlit"; } writeMaterial(material, materialDef) { if (!material.isMeshBasicMaterial) return; const writer = this.writer; const extensionsUsed = writer.extensionsUsed; materialDef.extensions = materialDef.extensions || {}; materialDef.extensions[this.name] = {}; extensionsUsed[this.name] = true; materialDef.pbrMetallicRoughness.metallicFactor = 0; materialDef.pbrMetallicRoughness.roughnessFactor = 0.9; } }; var GLTFMaterialsPBRSpecularGlossiness = class { constructor(writer) { this.writer = writer; this.name = "KHR_materials_pbrSpecularGlossiness"; } writeMaterial(material, materialDef) { if (!material.isGLTFSpecularGlossinessMaterial) return; const writer = this.writer; const extensionsUsed = writer.extensionsUsed; const extensionDef = {}; if (materialDef.pbrMetallicRoughness.baseColorFactor) { extensionDef.diffuseFactor = materialDef.pbrMetallicRoughness.baseColorFactor; } const specularFactor = [1, 1, 1]; material.specular.toArray(specularFactor, 0); extensionDef.specularFactor = specularFactor; extensionDef.glossinessFactor = material.glossiness; if (materialDef.pbrMetallicRoughness.baseColorTexture) { extensionDef.diffuseTexture = materialDef.pbrMetallicRoughness.baseColorTexture; } if (material.specularMap) { const specularMapDef = { index: writer.processTexture(material.specularMap) }; writer.applyTextureTransform(specularMapDef, material.specularMap); extensionDef.specularGlossinessTexture = specularMapDef; } materialDef.extensions = materialDef.extensions || {}; materialDef.extensions[this.name] = extensionDef; extensionsUsed[this.name] = true; } }; var GLTFMaterialsClearcoatExtension2 = class { constructor(writer) { this.writer = writer; this.name = "KHR_materials_clearcoat"; } writeMaterial(material, materialDef) { if (!material.isMeshPhysicalMaterial) return; const writer = this.writer; const extensionsUsed = writer.extensionsUsed; const extensionDef = {}; extensionDef.clearcoatFactor = material.clearcoat; if (material.clearcoatMap) { const clearcoatMapDef = { index: writer.processTexture(material.clearcoatMap) }; writer.applyTextureTransform(clearcoatMapDef, material.clearcoatMap); extensionDef.clearcoatTexture = clearcoatMapDef; } extensionDef.clearcoatRoughnessFactor = material.clearcoatRoughness; if (material.clearcoatRoughnessMap) { const clearcoatRoughnessMapDef = { index: writer.processTexture(material.clearcoatRoughnessMap) }; writer.applyTextureTransform(clearcoatRoughnessMapDef, material.clearcoatRoughnessMap); extensionDef.clearcoatRoughnessTexture = clearcoatRoughnessMapDef; } if (material.clearcoatNormalMap) { const clearcoatNormalMapDef = { index: writer.processTexture(material.clearcoatNormalMap) }; writer.applyTextureTransform(clearcoatNormalMapDef, material.clearcoatNormalMap); extensionDef.clearcoatNormalTexture = clearcoatNormalMapDef; } materialDef.extensions = materialDef.extensions || {}; materialDef.extensions[this.name] = extensionDef; extensionsUsed[this.name] = true; } }; var GLTFMaterialsIridescenceExtension2 = class { constructor(writer) { this.writer = writer; this.name = "KHR_materials_iridescence"; } writeMaterial(material, materialDef) { if (!material.isMeshPhysicalMaterial) return; const writer = this.writer; const extensionsUsed = writer.extensionsUsed; const extensionDef = {}; extensionDef.iridescenceFactor = material.iridescence; if (material.iridescenceMap) { const iridescenceMapDef = { index: writer.processTexture(material.iridescenceMap) }; writer.applyTextureTransform(iridescenceMapDef, material.iridescenceMap); extensionDef.iridescenceTexture = iridescenceMapDef; } extensionDef.iridescenceIor = material.iridescenceIOR; extensionDef.iridescenceThicknessMinimum = material.iridescenceThicknessRange[0]; extensionDef.iridescenceThicknessMaximum = material.iridescenceThicknessRange[1]; if (material.iridescenceThicknessMap) { const iridescenceThicknessMapDef = { index: writer.processTexture(material.iridescenceThicknessMap) }; writer.applyTextureTransform(iridescenceThicknessMapDef, material.iridescenceThicknessMap); extensionDef.iridescenceThicknessTexture = iridescenceThicknessMapDef; } materialDef.extensions = materialDef.extensions || {}; materialDef.extensions[this.name] = extensionDef; extensionsUsed[this.name] = true; } }; var GLTFMaterialsTransmissionExtension2 = class { constructor(writer) { this.writer = writer; this.name = "KHR_materials_transmission"; } writeMaterial(material, materialDef) { if (!material.isMeshPhysicalMaterial || material.transmission === 0) return; const writer = this.writer; const extensionsUsed = writer.extensionsUsed; const extensionDef = {}; extensionDef.transmissionFactor = material.transmission; if (material.transmissionMap) { const transmissionMapDef = { index: writer.processTexture(material.transmissionMap) }; writer.applyTextureTransform(transmissionMapDef, material.transmissionMap); extensionDef.transmissionTexture = transmissionMapDef; } materialDef.extensions = materialDef.extensions || {}; materialDef.extensions[this.name] = extensionDef; extensionsUsed[this.name] = true; } }; var GLTFMaterialsVolumeExtension2 = class { constructor(writer) { this.writer = writer; this.name = "KHR_materials_volume"; } writeMaterial(material, materialDef) { if (!material.isMeshPhysicalMaterial || material.transmission === 0) return; const writer = this.writer; const extensionsUsed = writer.extensionsUsed; const extensionDef = {}; extensionDef.thicknessFactor = material.thickness; if (material.thicknessMap) { const thicknessMapDef = { index: writer.processTexture(material.thicknessMap) }; writer.applyTextureTransform(thicknessMapDef, material.thicknessMap); extensionDef.thicknessTexture = thicknessMapDef; } extensionDef.attenuationDistance = material.attenuationDistance; extensionDef.attenuationColor = material.attenuationColor.toArray(); materialDef.extensions = materialDef.extensions || {}; materialDef.extensions[this.name] = extensionDef; extensionsUsed[this.name] = true; } }; GLTFExporter.Utils = { insertKeyframe: function(track, time) { const tolerance = 1e-3; const valueSize = track.getValueSize(); const times = new track.TimeBufferType(track.times.length + 1); const values = new track.ValueBufferType(track.values.length + valueSize); const interpolant = track.createInterpolant(new track.ValueBufferType(valueSize)); let index; if (track.times.length === 0) { times[0] = time; for (let i = 0; i < valueSize; i++) { values[i] = 0; } index = 0; } else if (time < track.times[0]) { if (Math.abs(track.times[0] - time) < tolerance) return 0; times[0] = time; times.set(track.times, 1); values.set(interpolant.evaluate(time), 0); values.set(track.values, valueSize); index = 0; } else if (time > track.times[track.times.length - 1]) { if (Math.abs(track.times[track.times.length - 1] - time) < tolerance) { return track.times.length - 1; } times[times.length - 1] = time; times.set(track.times, 0); values.set(track.values, 0); values.set(interpolant.evaluate(time), track.values.length); index = times.length - 1; } else { for (let i = 0; i < track.times.length; i++) { if (Math.abs(track.times[i] - time) < tolerance) return i; if (track.times[i] < time && track.times[i + 1] > time) { times.set(track.times.slice(0, i + 1), 0); times[i + 1] = time; times.set(track.times.slice(i + 1), i + 2); values.set(track.values.slice(0, (i + 1) * valueSize), 0); values.set(interpolant.evaluate(time), (i + 1) * valueSize); values.set(track.values.slice((i + 1) * valueSize), (i + 2) * valueSize); index = i + 1; break; } } } track.times = times; track.values = values; return index; }, mergeMorphTargetTracks: function(clip, root) { const tracks = []; const mergedTracks = {}; const sourceTracks = clip.tracks; for (let i = 0; i < sourceTracks.length; ++i) { let sourceTrack = sourceTracks[i]; const sourceTrackBinding = PropertyBinding.parseTrackName(sourceTrack.name); const sourceTrackNode = PropertyBinding.findNode(root, sourceTrackBinding.nodeName); if (sourceTrackBinding.propertyName !== "morphTargetInfluences" || sourceTrackBinding.propertyIndex === void 0) { tracks.push(sourceTrack); continue; } if (sourceTrack.createInterpolant !== sourceTrack.InterpolantFactoryMethodDiscrete && sourceTrack.createInterpolant !== sourceTrack.InterpolantFactoryMethodLinear) { if (sourceTrack.createInterpolant.isInterpolantFactoryMethodGLTFCubicSpline) { throw new Error("THREE.GLTFExporter: Cannot merge tracks with glTF CUBICSPLINE interpolation."); } console.warn("THREE.GLTFExporter: Morph target interpolation mode not yet supported. Using LINEAR instead."); sourceTrack = sourceTrack.clone(); sourceTrack.setInterpolation(InterpolateLinear); } const targetCount = sourceTrackNode.morphTargetInfluences.length; const targetIndex = sourceTrackNode.morphTargetDictionary[sourceTrackBinding.propertyIndex]; if (targetIndex === void 0) { throw new Error("THREE.GLTFExporter: Morph target name not found: " + sourceTrackBinding.propertyIndex); } let mergedTrack; if (mergedTracks[sourceTrackNode.uuid] === void 0) { mergedTrack = sourceTrack.clone(); const values = new mergedTrack.ValueBufferType(targetCount * mergedTrack.times.length); for (let j = 0; j < mergedTrack.times.length; j++) { values[j * targetCount + targetIndex] = mergedTrack.values[j]; } mergedTrack.name = (sourceTrackBinding.nodeName || "") + ".morphTargetInfluences"; mergedTrack.values = values; mergedTracks[sourceTrackNode.uuid] = mergedTrack; tracks.push(mergedTrack); continue; } const sourceInterpolant = sourceTrack.createInterpolant(new sourceTrack.ValueBufferType(1)); mergedTrack = mergedTracks[sourceTrackNode.uuid]; for (let j = 0; j < mergedTrack.times.length; j++) { mergedTrack.values[j * targetCount + targetIndex] = sourceInterpolant.evaluate(mergedTrack.times[j]); } for (let j = 0; j < sourceTrack.times.length; j++) { const keyframeIndex = this.insertKeyframe(mergedTrack, sourceTrack.times[j]); mergedTrack.values[keyframeIndex * targetCount + targetIndex] = sourceTrack.values[j]; } } clip.tracks = tracks; return clip; } }; // node_modules/@google/model-viewer/lib/three-components/gltf-instance/VariantMaterialExporterPlugin.js var compatibleObject = (object) => { return object.material !== void 0 && // easier than (!object.isMesh && !object.isLine && // !object.isPoints) object.userData && // just in case object.userData.variantMaterials && // Is this line costly? !!Array.from(object.userData.variantMaterials.values()).filter((m) => compatibleMaterial(m.material)); }; var compatibleMaterial = (material) => { return material && material.isMaterial && !Array.isArray(material); }; var GLTFExporterMaterialsVariantsExtension = class { constructor(writer) { this.writer = writer; this.name = "KHR_materials_variants"; this.variantNames = []; } beforeParse(objects) { const variantNameSet = /* @__PURE__ */ new Set(); for (const object of objects) { object.traverse((o) => { if (!compatibleObject(o)) { return; } const variantMaterials = o.userData.variantMaterials; const variantDataMap = o.userData.variantData; for (const [variantName, variantData] of variantDataMap) { const variantMaterial = variantMaterials.get(variantData.index); if (variantMaterial && compatibleMaterial(variantMaterial.material)) { variantNameSet.add(variantName); } } }); } variantNameSet.forEach((name) => this.variantNames.push(name)); } writeMesh(mesh, meshDef) { if (!compatibleObject(mesh)) { return; } const userData = mesh.userData; const variantMaterials = userData.variantMaterials; const variantDataMap = userData.variantData; const mappingTable = /* @__PURE__ */ new Map(); const reIndexedVariants = /* @__PURE__ */ new Map(); const variants = Array.from(variantDataMap.values()).sort((a, b) => { return a.index - b.index; }); for (const [i, variantData] of variants.entries()) { reIndexedVariants.set(variantData.index, i); } for (const variantData of variantDataMap.values()) { const variantInstance = variantMaterials.get(variantData.index); if (!variantInstance || !compatibleMaterial(variantInstance.material)) { continue; } const materialIndex = this.writer.processMaterial(variantInstance.material); if (!mappingTable.has(materialIndex)) { mappingTable.set(materialIndex, { material: materialIndex, variants: [] }); } mappingTable.get(materialIndex).variants.push(reIndexedVariants.get(variantData.index)); } const mappingsDef = Array.from(mappingTable.values()).map((m) => { return m.variants.sort((a, b) => a - b) && m; }).sort((a, b) => a.material - b.material); if (mappingsDef.length === 0) { return; } const originalMaterialIndex = compatibleMaterial(userData.originalMaterial) ? this.writer.processMaterial(userData.originalMaterial) : -1; for (const primitiveDef of meshDef.primitives) { if (originalMaterialIndex >= 0) { primitiveDef.material = originalMaterialIndex; } primitiveDef.extensions = primitiveDef.extensions || {}; primitiveDef.extensions[this.name] = { mappings: mappingsDef }; } } afterParse() { if (this.variantNames.length === 0) { return; } const root = this.writer.json; root.extensions = root.extensions || {}; const variantsDef = this.variantNames.map((n2) => { return { name: n2 }; }); root.extensions[this.name] = { variants: variantsDef }; this.writer.extensionsUsed[this.name] = true; } }; // node_modules/three/examples/jsm/webxr/XREstimatedLight.js var SessionLightProbe = class { constructor(xrLight, renderer, lightProbe, environmentEstimation, estimationStartCallback) { this.xrLight = xrLight; this.renderer = renderer; this.lightProbe = lightProbe; this.xrWebGLBinding = null; this.estimationStartCallback = estimationStartCallback; this.frameCallback = this.onXRFrame.bind(this); const session = renderer.xr.getSession(); if (environmentEstimation && "XRWebGLBinding" in window) { const cubeRenderTarget = new WebGLCubeRenderTarget(16); xrLight.environment = cubeRenderTarget.texture; const gl = renderer.getContext(); switch (session.preferredReflectionFormat) { case "srgba8": gl.getExtension("EXT_sRGB"); break; case "rgba16f": gl.getExtension("OES_texture_half_float"); break; } this.xrWebGLBinding = new XRWebGLBinding(session, gl); this.lightProbe.addEventListener("reflectionchange", () => { this.updateReflection(); }); } session.requestAnimationFrame(this.frameCallback); } updateReflection() { const textureProperties = this.renderer.properties.get(this.xrLight.environment); if (textureProperties) { const cubeMap = this.xrWebGLBinding.getReflectionCubeMap(this.lightProbe); if (cubeMap) { textureProperties.__webglTexture = cubeMap; this.xrLight.environment.needsPMREMUpdate = true; } } } onXRFrame(time, xrFrame) { if (!this.xrLight) { return; } const session = xrFrame.session; session.requestAnimationFrame(this.frameCallback); const lightEstimate = xrFrame.getLightEstimate(this.lightProbe); if (lightEstimate) { this.xrLight.lightProbe.sh.fromArray(lightEstimate.sphericalHarmonicsCoefficients); this.xrLight.lightProbe.intensity = 1; const intensityScalar = Math.max( 1, Math.max( lightEstimate.primaryLightIntensity.x, Math.max( lightEstimate.primaryLightIntensity.y, lightEstimate.primaryLightIntensity.z ) ) ); this.xrLight.directionalLight.color.setRGB( lightEstimate.primaryLightIntensity.x / intensityScalar, lightEstimate.primaryLightIntensity.y / intensityScalar, lightEstimate.primaryLightIntensity.z / intensityScalar ); this.xrLight.directionalLight.intensity = intensityScalar; this.xrLight.directionalLight.position.copy(lightEstimate.primaryLightDirection); if (this.estimationStartCallback) { this.estimationStartCallback(); this.estimationStartCallback = null; } } } dispose() { this.xrLight = null; this.renderer = null; this.lightProbe = null; this.xrWebGLBinding = null; } }; var XREstimatedLight = class extends Group { constructor(renderer, environmentEstimation = true) { super(); this.lightProbe = new LightProbe(); this.lightProbe.intensity = 0; this.add(this.lightProbe); this.directionalLight = new DirectionalLight(); this.directionalLight.intensity = 0; this.add(this.directionalLight); this.environment = null; let sessionLightProbe = null; let estimationStarted = false; renderer.xr.addEventListener("sessionstart", () => { const session = renderer.xr.getSession(); if ("requestLightProbe" in session) { session.requestLightProbe({ reflectionFormat: session.preferredReflectionFormat }).then((probe) => { sessionLightProbe = new SessionLightProbe(this, renderer, probe, environmentEstimation, () => { estimationStarted = true; this.dispatchEvent({ type: "estimationstart" }); }); }); } }); renderer.xr.addEventListener("sessionend", () => { if (sessionLightProbe) { sessionLightProbe.dispose(); sessionLightProbe = null; } if (estimationStarted) { this.dispatchEvent({ type: "estimationend" }); } }); this.dispose = () => { if (sessionLightProbe) { sessionLightProbe.dispose(); sessionLightProbe = null; } this.remove(this.lightProbe); this.lightProbe = null; this.remove(this.directionalLight); this.directionalLight = null; this.environment = null; }; } }; // node_modules/@google/model-viewer/lib/three-components/Damper.js var SETTLING_TIME = 1e4; var MIN_DECAY_MILLISECONDS = 1e-3; var DECAY_MILLISECONDS = 50; var Damper = class { constructor(decayMilliseconds = DECAY_MILLISECONDS) { this.velocity = 0; this.naturalFrequency = 0; this.setDecayTime(decayMilliseconds); } setDecayTime(decayMilliseconds) { this.naturalFrequency = 1 / Math.max(MIN_DECAY_MILLISECONDS, decayMilliseconds); } update(x2, xGoal, timeStepMilliseconds, xNormalization) { const nilSpeed = 2e-4 * this.naturalFrequency; if (x2 == null || xNormalization === 0) { return xGoal; } if (x2 === xGoal && this.velocity === 0) { return xGoal; } if (timeStepMilliseconds < 0) { return x2; } const deltaX = x2 - xGoal; const intermediateVelocity = this.velocity + this.naturalFrequency * deltaX; const intermediateX = deltaX + timeStepMilliseconds * intermediateVelocity; const decay = Math.exp(-this.naturalFrequency * timeStepMilliseconds); const newVelocity = (intermediateVelocity - this.naturalFrequency * intermediateX) * decay; const acceleration = -this.naturalFrequency * (newVelocity + intermediateVelocity * decay); if (Math.abs(newVelocity) < nilSpeed * Math.abs(xNormalization) && acceleration * deltaX >= 0) { this.velocity = 0; return xGoal; } else { this.velocity = newVelocity; return xGoal + intermediateX * decay; } } }; // node_modules/@google/model-viewer/lib/three-components/PlacementBox.js var RADIUS = 0.2; var LINE_WIDTH = 0.03; var MAX_OPACITY = 0.75; var SEGMENTS = 12; var DELTA_PHI = Math.PI / (2 * SEGMENTS); var vector2 = new Vector2(); var addCorner = (vertices, cornerX, cornerY) => { let phi = cornerX > 0 ? cornerY > 0 ? 0 : -Math.PI / 2 : cornerY > 0 ? Math.PI / 2 : Math.PI; for (let i = 0; i <= SEGMENTS; ++i) { vertices.push(cornerX + (RADIUS - LINE_WIDTH) * Math.cos(phi), cornerY + (RADIUS - LINE_WIDTH) * Math.sin(phi), 0, cornerX + RADIUS * Math.cos(phi), cornerY + RADIUS * Math.sin(phi), 0); phi += DELTA_PHI; } }; var PlacementBox = class extends Mesh { constructor(scene, side) { const geometry = new BufferGeometry(); const triangles = []; const vertices = []; const { size, boundingBox } = scene; const x2 = size.x / 2; const y = (side === "back" ? size.y : size.z) / 2; addCorner(vertices, x2, y); addCorner(vertices, -x2, y); addCorner(vertices, -x2, -y); addCorner(vertices, x2, -y); const numVertices = vertices.length / 3; for (let i2 = 0; i2 < numVertices - 2; i2 += 2) { triangles.push(i2, i2 + 1, i2 + 3, i2, i2 + 3, i2 + 2); } const i = numVertices - 2; triangles.push(i, i + 1, 1, i, 1, 0); geometry.setAttribute("position", new Float32BufferAttribute(vertices, 3)); geometry.setIndex(triangles); super(geometry); this.side = side; const material = this.material; material.side = DoubleSide; material.transparent = true; material.opacity = 0; this.goalOpacity = 0; this.opacityDamper = new Damper(); this.hitPlane = new Mesh(new PlaneGeometry(2 * (x2 + RADIUS), 2 * (y + RADIUS))); this.hitPlane.visible = false; this.hitPlane.material.side = DoubleSide; this.add(this.hitPlane); boundingBox.getCenter(this.position); switch (side) { case "bottom": this.rotateX(-Math.PI / 2); this.shadowHeight = boundingBox.min.y; this.position.y = this.shadowHeight; break; case "back": this.shadowHeight = boundingBox.min.z; this.position.z = this.shadowHeight; } scene.target.add(this); this.offsetHeight = 0; } /** * Get the world hit position if the touch coordinates hit the box, and null * otherwise. Pass the scene in to get access to its raycaster. */ getHit(scene, screenX, screenY) { vector2.set(screenX, -screenY); this.hitPlane.visible = true; const hitResult = scene.positionAndNormalFromPoint(vector2, this.hitPlane); this.hitPlane.visible = false; return hitResult == null ? null : hitResult.position; } getExpandedHit(scene, screenX, screenY) { this.hitPlane.scale.set(1e3, 1e3, 1e3); this.hitPlane.updateMatrixWorld(); const hitResult = this.getHit(scene, screenX, screenY); this.hitPlane.scale.set(1, 1, 1); return hitResult; } /** * Offset the height of the box relative to the bottom of the scene. Positive * is up, so generally only negative values are used. */ set offsetHeight(offset) { offset -= 1e-3; if (this.side === "back") { this.position.z = this.shadowHeight + offset; } else { this.position.y = this.shadowHeight + offset; } } get offsetHeight() { if (this.side === "back") { return this.position.z - this.shadowHeight; } else { return this.position.y - this.shadowHeight; } } /** * Set the box's visibility; it will fade in and out. */ set show(visible) { this.goalOpacity = visible ? MAX_OPACITY : 0; } /** * Call on each frame with the frame delta to fade the box. */ updateOpacity(delta) { const material = this.material; material.opacity = this.opacityDamper.update(material.opacity, this.goalOpacity, delta, 1); this.visible = material.opacity > 0; } /** * Call this to clean up Three's cache when you remove the box. */ dispose() { var _a12; const { geometry, material } = this.hitPlane; geometry.dispose(); material.dispose(); this.geometry.dispose(); this.material.dispose(); (_a12 = this.parent) === null || _a12 === void 0 ? void 0 : _a12.remove(this); } }; // node_modules/@google/model-viewer/lib/three-components/ARRenderer.js var INIT_FRAMES = 30; var AR_SHADOW_INTENSITY = 0.8; var ROTATION_RATE = 1.5; var HIT_ANGLE_DEG = 20; var SCALE_SNAP_HIGH = 1.3; var SCALE_SNAP_LOW = 1 / SCALE_SNAP_HIGH; var MIN_VIEWPORT_SCALE = 0.25; var MAX_DISTANCE = 10; var ARStatus = { NOT_PRESENTING: "not-presenting", SESSION_STARTED: "session-started", OBJECT_PLACED: "object-placed", FAILED: "failed" }; var ARTracking = { TRACKING: "tracking", NOT_TRACKING: "not-tracking" }; var vector3 = new Vector3(); var matrix4 = new Matrix4(); var hitPosition = new Vector3(); var camera = new PerspectiveCamera(45, 1, 0.1, 100); var ARRenderer = class extends EventDispatcher { constructor(renderer) { super(); this.renderer = renderer; this.currentSession = null; this.placeOnWall = false; this.placementBox = null; this.lastTick = null; this.turntableRotation = null; this.oldShadowIntensity = null; this.frame = null; this.initialHitSource = null; this.transientHitTestSource = null; this.inputSource = null; this._presentedScene = null; this.resolveCleanup = null; this.exitWebXRButtonContainer = null; this.overlay = null; this.xrLight = null; this.tracking = true; this.frames = 0; this.initialized = false; this.oldTarget = new Vector3(); this.placementComplete = false; this.isTranslating = false; this.isRotating = false; this.isTwoFingering = false; this.lastDragPosition = new Vector3(); this.firstRatio = 0; this.lastAngle = 0; this.goalPosition = new Vector3(); this.goalYaw = 0; this.goalScale = 1; this.xDamper = new Damper(); this.yDamper = new Damper(); this.zDamper = new Damper(); this.yawDamper = new Damper(); this.scaleDamper = new Damper(); this.onExitWebXRButtonContainerClick = () => this.stopPresenting(); this.onUpdateScene = () => { if (this.placementBox != null && this.isPresenting) { this.placementBox.dispose(); this.placementBox = new PlacementBox(this.presentedScene, this.placeOnWall ? "back" : "bottom"); } }; this.onSelectStart = (event) => { const hitSource = this.transientHitTestSource; if (hitSource == null) { return; } const fingers = this.frame.getHitTestResultsForTransientInput(hitSource); const scene = this.presentedScene; const box = this.placementBox; if (fingers.length === 1) { this.inputSource = event.inputSource; const { axes } = this.inputSource.gamepad; const hitPosition2 = box.getHit(this.presentedScene, axes[0], axes[1]); box.show = true; if (hitPosition2 != null) { this.isTranslating = true; this.lastDragPosition.copy(hitPosition2); } else if (this.placeOnWall === false) { this.isRotating = true; this.lastAngle = axes[0] * ROTATION_RATE; } } else if (fingers.length === 2) { box.show = true; this.isTwoFingering = true; const { separation } = this.fingerPolar(fingers); this.firstRatio = separation / scene.scale.x; } }; this.onSelectEnd = () => { this.isTranslating = false; this.isRotating = false; this.isTwoFingering = false; this.inputSource = null; this.goalPosition.y += this.placementBox.offsetHeight * this.presentedScene.scale.x; this.placementBox.show = false; }; this.threeRenderer = renderer.threeRenderer; this.threeRenderer.xr.enabled = true; } async resolveARSession() { assertIsArCandidate(); const session = await navigator.xr.requestSession("immersive-ar", { requiredFeatures: ["hit-test"], optionalFeatures: ["dom-overlay", "light-estimation"], domOverlay: this.overlay ? { root: this.overlay } : void 0 }); this.threeRenderer.xr.setReferenceSpaceType("local"); await this.threeRenderer.xr.setSession(session); this.threeRenderer.xr.cameraAutoUpdate = false; return session; } /** * The currently presented scene, if any */ get presentedScene() { return this._presentedScene; } /** * Resolves to true if the renderer has detected all the necessary qualities * to support presentation in AR. */ async supportsPresentation() { try { assertIsArCandidate(); return await navigator.xr.isSessionSupported("immersive-ar"); } catch (error) { console.warn("Request to present in WebXR denied:"); console.warn(error); console.warn("Falling back to next ar-mode"); return false; } } /** * Present a scene in AR */ async present(scene, environmentEstimation = false) { if (this.isPresenting) { console.warn("Cannot present while a model is already presenting"); } let waitForAnimationFrame = new Promise((resolve, _reject) => { requestAnimationFrame(() => resolve()); }); scene.setHotspotsVisibility(false); scene.queueRender(); await waitForAnimationFrame; this._presentedScene = scene; this.overlay = scene.element.shadowRoot.querySelector("div.default"); if (environmentEstimation === true) { this.xrLight = new XREstimatedLight(this.threeRenderer); this.xrLight.addEventListener("estimationstart", () => { if (!this.isPresenting || this.xrLight == null) { return; } const scene2 = this.presentedScene; scene2.add(this.xrLight); scene2.environment = this.xrLight.environment; }); } const currentSession = await this.resolveARSession(); currentSession.addEventListener("end", () => { this.postSessionCleanup(); }, { once: true }); const exitButton = scene.element.shadowRoot.querySelector(".slot.exit-webxr-ar-button"); exitButton.classList.add("enabled"); exitButton.addEventListener("click", this.onExitWebXRButtonContainerClick); this.exitWebXRButtonContainer = exitButton; const viewerRefSpace = await currentSession.requestReferenceSpace("viewer"); this.tracking = true; this.frames = 0; this.initialized = false; this.turntableRotation = scene.yaw; this.goalYaw = scene.yaw; this.goalScale = 1; scene.background = null; this.oldShadowIntensity = scene.shadowIntensity; scene.setShadowIntensity(0.01); this.oldTarget.copy(scene.getTarget()); scene.element.addEventListener("load", this.onUpdateScene); const radians = HIT_ANGLE_DEG * Math.PI / 180; const ray = this.placeOnWall === true ? void 0 : new XRRay(new DOMPoint(0, 0, 0), { x: 0, y: -Math.sin(radians), z: -Math.cos(radians) }); currentSession.requestHitTestSource({ space: viewerRefSpace, offsetRay: ray }).then((hitTestSource) => { this.initialHitSource = hitTestSource; }); this.currentSession = currentSession; this.placementBox = new PlacementBox(scene, this.placeOnWall ? "back" : "bottom"); this.placementComplete = false; this.lastTick = performance.now(); this.dispatchEvent({ type: "status", status: ARStatus.SESSION_STARTED }); } /** * If currently presenting a scene in AR, stops presentation and exits AR. */ async stopPresenting() { if (!this.isPresenting) { return; } const cleanupPromise = new Promise((resolve) => { this.resolveCleanup = resolve; }); try { await this.currentSession.end(); await cleanupPromise; } catch (error) { console.warn("Error while trying to end WebXR AR session"); console.warn(error); this.postSessionCleanup(); } } /** * True if a scene is currently in the process of being presented in AR */ get isPresenting() { return this.presentedScene != null; } get target() { return this.oldTarget; } updateTarget() { const scene = this.presentedScene; if (scene != null) { const target2 = scene.getTarget(); this.oldTarget.copy(target2); if (this.placeOnWall) { target2.z = scene.boundingBox.min.z; } else { target2.y = scene.boundingBox.min.y; } scene.setTarget(target2.x, target2.y, target2.z); } } postSessionCleanup() { const session = this.currentSession; if (session != null) { session.removeEventListener("selectstart", this.onSelectStart); session.removeEventListener("selectend", this.onSelectEnd); this.currentSession = null; } const scene = this.presentedScene; this._presentedScene = null; if (scene != null) { const { element } = scene; if (this.xrLight != null) { scene.remove(this.xrLight); this.xrLight.dispose(); this.xrLight = null; } scene.position.set(0, 0, 0); scene.scale.set(1, 1, 1); scene.setShadowOffset(0); const yaw = this.turntableRotation; if (yaw != null) { scene.yaw = yaw; } const intensity = this.oldShadowIntensity; if (intensity != null) { scene.setShadowIntensity(intensity); } scene.setEnvironmentAndSkybox(element[$currentEnvironmentMap], element[$currentBackground]); const point = this.oldTarget; scene.setTarget(point.x, point.y, point.z); scene.xrCamera = null; scene.element.removeEventListener("load", this.onUpdateScene); scene.orientHotspots(0); element.requestUpdate("cameraTarget"); element.requestUpdate("maxCameraOrbit"); element[$onResize](element.getBoundingClientRect()); } this.renderer.height = 0; const exitButton = this.exitWebXRButtonContainer; if (exitButton != null) { exitButton.classList.remove("enabled"); exitButton.removeEventListener("click", this.onExitWebXRButtonContainerClick); this.exitWebXRButtonContainer = null; } const hitSource = this.transientHitTestSource; if (hitSource != null) { hitSource.cancel(); this.transientHitTestSource = null; } const hitSourceInitial = this.initialHitSource; if (hitSourceInitial != null) { hitSourceInitial.cancel(); this.initialHitSource = null; } if (this.placementBox != null) { this.placementBox.dispose(); this.placementBox = null; } this.lastTick = null; this.turntableRotation = null; this.oldShadowIntensity = null; this.frame = null; this.inputSource = null; this.overlay = null; if (this.resolveCleanup != null) { this.resolveCleanup(); } this.dispatchEvent({ type: "status", status: ARStatus.NOT_PRESENTING }); } updateView(view2) { const scene = this.presentedScene; const xr = this.threeRenderer.xr; xr.updateCamera(camera); scene.xrCamera = xr.getCamera(); const { elements } = scene.getCamera().matrixWorld; scene.orientHotspots(Math.atan2(elements[1], elements[5])); if (!this.initialized) { this.placeInitially(); this.initialized = true; } if (view2.requestViewportScale && view2.recommendedViewportScale) { const scale = view2.recommendedViewportScale; view2.requestViewportScale(Math.max(scale, MIN_VIEWPORT_SCALE)); } const layer = this.currentSession.renderState.baseLayer; const viewport = layer.getViewport(view2); this.threeRenderer.setViewport(viewport.x, viewport.y, viewport.width, viewport.height); } placeInitially() { const scene = this.presentedScene; const { position, element } = scene; const xrCamera = scene.getCamera(); const { width, height } = this.overlay.getBoundingClientRect(); scene.setSize(width, height); xrCamera.projectionMatrixInverse.copy(xrCamera.projectionMatrix).invert(); const { theta, radius } = element.getCameraOrbit(); const cameraDirection = xrCamera.getWorldDirection(vector3); scene.yaw = Math.atan2(-cameraDirection.x, -cameraDirection.z) - theta; this.goalYaw = scene.yaw; position.copy(xrCamera.position).add(cameraDirection.multiplyScalar(radius)); this.updateTarget(); const target2 = scene.getTarget(); position.add(target2).sub(this.oldTarget); this.goalPosition.copy(position); scene.setHotspotsVisibility(true); const { session } = this.frame; session.addEventListener("selectstart", this.onSelectStart); session.addEventListener("selectend", this.onSelectEnd); session.requestHitTestSourceForTransientInput({ profile: "generic-touchscreen" }).then((hitTestSource) => { this.transientHitTestSource = hitTestSource; }); } getTouchLocation() { const { axes } = this.inputSource.gamepad; let location = this.placementBox.getExpandedHit(this.presentedScene, axes[0], axes[1]); if (location != null) { vector3.copy(location).sub(this.presentedScene.getCamera().position); if (vector3.length() > MAX_DISTANCE) return null; } return location; } getHitPoint(hitResult) { const refSpace = this.threeRenderer.xr.getReferenceSpace(); const pose = hitResult.getPose(refSpace); if (pose == null) { return null; } const hitMatrix = matrix4.fromArray(pose.transform.matrix); if (this.placeOnWall === true) { this.goalYaw = Math.atan2(hitMatrix.elements[4], hitMatrix.elements[6]); } return hitMatrix.elements[5] > 0.75 !== this.placeOnWall ? hitPosition.setFromMatrixPosition(hitMatrix) : null; } moveToFloor(frame) { const hitSource = this.initialHitSource; if (hitSource == null) { return; } const hitTestResults = frame.getHitTestResults(hitSource); if (hitTestResults.length == 0) { return; } const hit = hitTestResults[0]; const hitPoint = this.getHitPoint(hit); if (hitPoint == null) { return; } this.placementBox.show = true; if (!this.isTranslating) { if (this.placeOnWall) { this.goalPosition.copy(hitPoint); } else { this.goalPosition.y = hitPoint.y; } } hitSource.cancel(); this.initialHitSource = null; this.dispatchEvent({ type: "status", status: ARStatus.OBJECT_PLACED }); } fingerPolar(fingers) { const fingerOne = fingers[0].inputSource.gamepad.axes; const fingerTwo = fingers[1].inputSource.gamepad.axes; const deltaX = fingerTwo[0] - fingerOne[0]; const deltaY = fingerTwo[1] - fingerOne[1]; const angle = Math.atan2(deltaY, deltaX); let deltaYaw = this.lastAngle - angle; if (deltaYaw > Math.PI) { deltaYaw -= 2 * Math.PI; } else if (deltaYaw < -Math.PI) { deltaYaw += 2 * Math.PI; } this.lastAngle = angle; return { separation: Math.sqrt(deltaX * deltaX + deltaY * deltaY), deltaYaw }; } processInput(frame) { const hitSource = this.transientHitTestSource; if (hitSource == null) { return; } if (!this.isTranslating && !this.isTwoFingering && !this.isRotating) { return; } const fingers = frame.getHitTestResultsForTransientInput(hitSource); const scene = this.presentedScene; const scale = scene.scale.x; if (this.isTwoFingering) { if (fingers.length < 2) { this.isTwoFingering = false; } else { const { separation, deltaYaw } = this.fingerPolar(fingers); if (this.placeOnWall === false) { this.goalYaw += deltaYaw; } if (scene.canScale) { const scale2 = separation / this.firstRatio; this.goalScale = scale2 < SCALE_SNAP_HIGH && scale2 > SCALE_SNAP_LOW ? 1 : scale2; } } return; } else if (fingers.length === 2) { this.isTranslating = false; this.isRotating = false; this.isTwoFingering = true; const { separation } = this.fingerPolar(fingers); this.firstRatio = separation / scale; return; } if (this.isRotating) { const angle = this.inputSource.gamepad.axes[0] * ROTATION_RATE; this.goalYaw += angle - this.lastAngle; this.lastAngle = angle; } else if (this.isTranslating) { fingers.forEach((finger) => { if (finger.inputSource !== this.inputSource) { return; } let hit = null; if (finger.results.length > 0) { hit = this.getHitPoint(finger.results[0]); } if (hit == null) { hit = this.getTouchLocation(); } if (hit == null) { return; } this.goalPosition.sub(this.lastDragPosition); if (this.placeOnWall === false) { const offset = hit.y - this.lastDragPosition.y; if (offset < 0) { this.placementBox.offsetHeight = offset / scale; this.presentedScene.setShadowOffset(offset); const cameraPosition = vector3.copy(scene.getCamera().position); const alpha = -offset / (cameraPosition.y - hit.y); cameraPosition.multiplyScalar(alpha); hit.multiplyScalar(1 - alpha).add(cameraPosition); } } this.goalPosition.add(hit); this.lastDragPosition.copy(hit); }); } } moveScene(delta) { const scene = this.presentedScene; const { position, yaw } = scene; const boundingRadius = scene.boundingSphere.radius; const goal = this.goalPosition; const oldScale = scene.scale.x; const box = this.placementBox; if (!goal.equals(position) || this.goalScale !== oldScale) { let { x: x2, y, z } = position; x2 = this.xDamper.update(x2, goal.x, delta, boundingRadius); y = this.yDamper.update(y, goal.y, delta, boundingRadius); z = this.zDamper.update(z, goal.z, delta, boundingRadius); position.set(x2, y, z); const newScale = this.scaleDamper.update(oldScale, this.goalScale, delta, 1); scene.scale.set(newScale, newScale, newScale); if (!this.isTranslating) { const offset = goal.y - y; if (this.placementComplete && this.placeOnWall === false) { box.offsetHeight = offset / newScale; scene.setShadowOffset(offset); } else if (offset === 0) { this.placementComplete = true; box.show = false; scene.setShadowIntensity(AR_SHADOW_INTENSITY); } } } box.updateOpacity(delta); scene.updateTarget(delta); scene.yaw = this.yawDamper.update(yaw, this.goalYaw, delta, Math.PI); } /** * Only public to make it testable. */ onWebXRFrame(time, frame) { this.frame = frame; ++this.frames; const refSpace = this.threeRenderer.xr.getReferenceSpace(); const pose = frame.getViewerPose(refSpace); if (pose == null && this.tracking === true && this.frames > INIT_FRAMES) { this.tracking = false; this.dispatchEvent({ type: "tracking", status: ARTracking.NOT_TRACKING }); } const scene = this.presentedScene; if (pose == null || scene == null || !scene.element.loaded) { this.threeRenderer.clear(); return; } if (this.tracking === false) { this.tracking = true; this.dispatchEvent({ type: "tracking", status: ARTracking.TRACKING }); } let isFirstView = true; for (const view2 of pose.views) { this.updateView(view2); if (isFirstView) { this.moveToFloor(frame); this.processInput(frame); const delta = time - this.lastTick; this.moveScene(delta); this.renderer.preRender(scene, time, delta); this.lastTick = time; scene.renderShadow(this.threeRenderer); } this.threeRenderer.render(scene, scene.getCamera()); isFirstView = false; } } }; // node_modules/@google/model-viewer/lib/three-components/Debugger.js var Debugger = class { constructor(renderer) { renderer.threeRenderer.debug = { checkShaderErrors: true }; Promise.resolve().then(() => { self.dispatchEvent(new CustomEvent("model-viewer-renderer-debug", { detail: { renderer, THREE: { ShaderMaterial, Texture, Mesh, Scene, PlaneGeometry, OrthographicCamera, WebGLRenderTarget } } })); }); } addScene(scene) { self.dispatchEvent(new CustomEvent("model-viewer-scene-added-debug", { detail: { scene } })); } removeScene(scene) { self.dispatchEvent(new CustomEvent("model-viewer-scene-removed-debug", { detail: { scene } })); } }; // node_modules/three/examples/jsm/utils/SkeletonUtils.js function clone(source) { const sourceLookup = /* @__PURE__ */ new Map(); const cloneLookup = /* @__PURE__ */ new Map(); const clone2 = source.clone(); parallelTraverse(source, clone2, function(sourceNode, clonedNode) { sourceLookup.set(clonedNode, sourceNode); cloneLookup.set(sourceNode, clonedNode); }); clone2.traverse(function(node) { if (!node.isSkinnedMesh) return; const clonedMesh = node; const sourceMesh = sourceLookup.get(node); const sourceBones = sourceMesh.skeleton.bones; clonedMesh.skeleton = sourceMesh.skeleton.clone(); clonedMesh.bindMatrix.copy(sourceMesh.bindMatrix); clonedMesh.skeleton.bones = sourceBones.map(function(bone) { return cloneLookup.get(bone); }); clonedMesh.bind(clonedMesh.skeleton, clonedMesh.bindMatrix); }); return clone2; } function parallelTraverse(a, b, callback) { callback(a, b); for (let i = 0; i < a.children.length; i++) { parallelTraverse(a.children[i], b.children[i], callback); } } // node_modules/@google/model-viewer/lib/three-components/GLTFInstance.js var $prepared = Symbol("prepared"); var $prepare = Symbol("prepare"); var $preparedGLTF = Symbol("preparedGLTF"); var $clone = Symbol("clone"); var GLTFInstance = class { constructor(preparedGLTF) { this[$preparedGLTF] = preparedGLTF; } /** * Prepares a given GLTF for presentation and future cloning. A GLTF that is * prepared can safely have this method invoked on it multiple times; it will * only be prepared once, including after being cloned. */ static prepare(source) { if (source.scene == null) { throw new Error("Model does not have a scene"); } if (source[$prepared]) { return source; } const prepared = this[$prepare](source); prepared[$prepared] = true; return prepared; } /** * Override in an inheriting class to apply specialty one-time preparations * for a given input GLTF. */ static [$prepare](source) { const { scene } = source; const scenes = [scene]; return Object.assign(Object.assign({}, source), { scene, scenes }); } get parser() { return this[$preparedGLTF].parser; } get animations() { return this[$preparedGLTF].animations; } get scene() { return this[$preparedGLTF].scene; } get scenes() { return this[$preparedGLTF].scenes; } get cameras() { return this[$preparedGLTF].cameras; } get asset() { return this[$preparedGLTF].asset; } get userData() { return this[$preparedGLTF].userData; } /** * Creates and returns a copy of this instance. */ clone() { const GLTFInstanceConstructor = this.constructor; const clonedGLTF = this[$clone](); return new GLTFInstanceConstructor(clonedGLTF); } /** * Cleans up any retained memory that might not otherwise be released when * this instance is done being used. */ dispose() { this.scenes.forEach((scene) => { scene.traverse((object) => { if (!object.isMesh) { return; } const mesh = object; const materials = Array.isArray(mesh.material) ? mesh.material : [mesh.material]; materials.forEach((material) => { for (const propertyName in material) { const texture = material[propertyName]; if (texture instanceof Texture) { const image = texture.source.data; if (image.close != null) { image.close(); } texture.dispose(); } } material.dispose(); }); mesh.geometry.dispose(); }); }); } /** * Override in an inheriting class to implement specialized cloning strategies */ [$clone]() { const source = this[$preparedGLTF]; const scene = clone(this.scene); cloneVariantMaterials(scene, this.scene); const scenes = [scene]; const userData = source.userData ? Object.assign({}, source.userData) : {}; return Object.assign(Object.assign({}, source), { scene, scenes, userData }); } }; var cloneVariantMaterials = (dst, src) => { traversePair(dst, src, (dst2, src2) => { if (src2.userData.variantMaterials !== void 0) { dst2.userData.variantMaterials = new Map(src2.userData.variantMaterials); } if (src2.userData.variantData !== void 0) { dst2.userData.variantData = src2.userData.variantData; } if (src2.userData.originalMaterial !== void 0) { dst2.userData.originalMaterial = src2.userData.originalMaterial; } }); }; var traversePair = (obj1, obj2, callback) => { callback(obj1, obj2); for (let i = 0; i < obj1.children.length; i++) { traversePair(obj1.children[i], obj2.children[i], callback); } }; // node_modules/@google/model-viewer/lib/three-components/gltf-instance/correlated-scene-graph.js var $threeGLTF = Symbol("threeGLTF"); var $gltf = Symbol("gltf"); var $gltfElementMap = Symbol("gltfElementMap"); var $threeObjectMap = Symbol("threeObjectMap"); var $parallelTraverseThreeScene = Symbol("parallelTraverseThreeScene"); var $correlateOriginalThreeGLTF = Symbol("correlateOriginalThreeGLTF"); var $correlateCloneThreeGLTF = Symbol("correlateCloneThreeGLTF"); var CorrelatedSceneGraph = class _CorrelatedSceneGraph { constructor(threeGLTF, gltf, threeObjectMap, gltfElementMap) { this[$threeGLTF] = threeGLTF; this[$gltf] = gltf; this[$gltfElementMap] = gltfElementMap; this[$threeObjectMap] = threeObjectMap; } /** * Produce a CorrelatedSceneGraph from a naturally generated Three.js GLTF. * Such GLTFs are produced by Three.js' GLTFLoader, and contain cached * details that expedite the correlation step. * * If a CorrelatedSceneGraph is provided as the second argument, re-correlates * a cloned Three.js GLTF with a clone of the glTF hierarchy used to produce * the upstream Three.js GLTF that the clone was created from. The result * CorrelatedSceneGraph is representative of the cloned hierarchy. */ static from(threeGLTF, upstreamCorrelatedSceneGraph) { if (upstreamCorrelatedSceneGraph != null) { return this[$correlateCloneThreeGLTF](threeGLTF, upstreamCorrelatedSceneGraph); } else { return this[$correlateOriginalThreeGLTF](threeGLTF); } } static [$correlateOriginalThreeGLTF](threeGLTF) { const gltf = threeGLTF.parser.json; const associations = threeGLTF.parser.associations; const gltfElementMap = /* @__PURE__ */ new Map(); const defaultMaterial = { name: "Default" }; const defaultReference = { type: "materials", index: -1 }; for (const threeMaterial of associations.keys()) { if (threeMaterial instanceof Material && associations.get(threeMaterial) == null) { if (defaultReference.index < 0) { if (gltf.materials == null) { gltf.materials = []; } defaultReference.index = gltf.materials.length; gltf.materials.push(defaultMaterial); } threeMaterial.name = defaultMaterial.name; associations.set(threeMaterial, { materials: defaultReference.index }); } } for (const [threeObject, gltfMappings] of associations) { if (gltfMappings) { const objWithUserData = threeObject; objWithUserData.userData = objWithUserData.userData || {}; objWithUserData.userData.associations = gltfMappings; } for (const mapping in gltfMappings) { if (mapping != null && mapping !== "primitives") { const type = mapping; const elementArray = gltf[type] || []; const gltfElement = elementArray[gltfMappings[type]]; if (gltfElement == null) { continue; } let threeObjects = gltfElementMap.get(gltfElement); if (threeObjects == null) { threeObjects = /* @__PURE__ */ new Set(); gltfElementMap.set(gltfElement, threeObjects); } threeObjects.add(threeObject); } } } return new _CorrelatedSceneGraph(threeGLTF, gltf, associations, gltfElementMap); } /** * Transfers the association between a raw glTF and a Three.js scene graph * to a clone of the Three.js scene graph, resolved as a new * CorrelatedSceneGraph instance. */ static [$correlateCloneThreeGLTF](cloneThreeGLTF, upstreamCorrelatedSceneGraph) { const originalThreeGLTF = upstreamCorrelatedSceneGraph.threeGLTF; const originalGLTF = upstreamCorrelatedSceneGraph.gltf; const cloneGLTF = JSON.parse(JSON.stringify(originalGLTF)); const cloneThreeObjectMap = /* @__PURE__ */ new Map(); const cloneGLTFElementMap = /* @__PURE__ */ new Map(); for (let i = 0; i < originalThreeGLTF.scenes.length; i++) { this[$parallelTraverseThreeScene](originalThreeGLTF.scenes[i], cloneThreeGLTF.scenes[i], (object, cloneObject) => { const elementReference = upstreamCorrelatedSceneGraph.threeObjectMap.get(object); if (elementReference == null) { return; } for (const mapping in elementReference) { if (mapping != null && mapping !== "primitives") { const type = mapping; const index = elementReference[type]; const cloneElement = cloneGLTF[type][index]; const mappings = cloneThreeObjectMap.get(cloneObject) || {}; mappings[type] = index; cloneThreeObjectMap.set(cloneObject, mappings); const cloneObjects = cloneGLTFElementMap.get(cloneElement) || /* @__PURE__ */ new Set(); cloneObjects.add(cloneObject); cloneGLTFElementMap.set(cloneElement, cloneObjects); } } }); } return new _CorrelatedSceneGraph(cloneThreeGLTF, cloneGLTF, cloneThreeObjectMap, cloneGLTFElementMap); } /** * Traverses two presumably identical Three.js scenes, and invokes a * callback for each Object3D or Material encountered, including the initial * scene. Adapted from * https://github.com/mrdoob/three.js/blob/7c1424c5819ab622a346dd630ee4e6431388021e/examples/jsm/utils/SkeletonUtils.js#L586-L596 */ static [$parallelTraverseThreeScene](sceneOne, sceneTwo, callback) { const isMesh = (object) => { return object.isMesh; }; const traverse = (a, b) => { callback(a, b); if (a.isObject3D) { if (isMesh(a)) { if (Array.isArray(a.material)) { for (let i = 0; i < a.material.length; ++i) { traverse(a.material[i], b.material[i]); } } else { traverse(a.material, b.material); } } for (let i = 0; i < a.children.length; ++i) { traverse(a.children[i], b.children[i]); } } }; traverse(sceneOne, sceneTwo); } /** * The source Three.js GLTF result given to us by a Three.js GLTFLoader. */ get threeGLTF() { return this[$threeGLTF]; } /** * The in-memory deserialized source glTF. */ get gltf() { return this[$gltf]; } /** * A Map of glTF element references to arrays of corresponding Three.js * object references. Three.js objects are kept in arrays to account for * cases where more than one Three.js object corresponds to a single glTF * element. */ get gltfElementMap() { return this[$gltfElementMap]; } /** * A map of individual Three.js objects to corresponding elements in the * source glTF. */ get threeObjectMap() { return this[$threeObjectMap]; } }; // node_modules/@google/model-viewer/lib/three-components/gltf-instance/ModelViewerGLTFInstance.js var $correlatedSceneGraph = Symbol("correlatedSceneGraph"); var ModelViewerGLTFInstance = class extends GLTFInstance { /** * @override */ static [$prepare](source) { const prepared = super[$prepare](source); if (prepared[$correlatedSceneGraph] == null) { prepared[$correlatedSceneGraph] = CorrelatedSceneGraph.from(prepared); } const { scene } = prepared; const nullSphere = new Sphere(void 0, Infinity); scene.traverse((node) => { node.renderOrder = 1e3; node.frustumCulled = false; if (!node.name) { node.name = node.uuid; } const mesh = node; if (mesh.isMesh) { const { geometry } = mesh; mesh.castShadow = true; if (mesh.isSkinnedMesh) { geometry.boundingSphere = nullSphere; geometry.boundingBox = null; } const material = mesh.material; if (material.isMeshBasicMaterial === true) { material.toneMapped = false; } material.shadowSide = FrontSide; if (material.aoMap) { const { gltf, threeObjectMap } = prepared[$correlatedSceneGraph]; const gltfRef = threeObjectMap.get(material); if (gltf.materials != null && gltfRef != null && gltfRef.materials != null) { const gltfMaterial = gltf.materials[gltfRef.materials]; if (gltfMaterial.occlusionTexture && gltfMaterial.occlusionTexture.texCoord === 0 && geometry.attributes.uv != null) { geometry.setAttribute("uv2", geometry.attributes.uv); } } } } }); return prepared; } get correlatedSceneGraph() { return this[$preparedGLTF][$correlatedSceneGraph]; } /** * @override */ [$clone]() { const clone2 = super[$clone](); const sourceUUIDToClonedMaterial = /* @__PURE__ */ new Map(); clone2.scene.traverse((node) => { if (node.isMesh) { const mesh = node; const material = mesh.material; if (material != null) { if (sourceUUIDToClonedMaterial.has(material.uuid)) { mesh.material = sourceUUIDToClonedMaterial.get(material.uuid); return; } mesh.material = material.clone(); sourceUUIDToClonedMaterial.set(material.uuid, mesh.material); } } }); clone2[$correlatedSceneGraph] = CorrelatedSceneGraph.from(clone2, this.correlatedSceneGraph); return clone2; } }; // node_modules/three/examples/jsm/loaders/RGBELoader.js var RGBELoader = class extends DataTextureLoader { constructor(manager) { super(manager); this.type = HalfFloatType; } // adapted from http://www.graphics.cornell.edu/~bjw/rgbe.html parse(buffer) { const RGBE_RETURN_FAILURE = -1, rgbe_read_error = 1, rgbe_write_error = 2, rgbe_format_error = 3, rgbe_memory_error = 4, rgbe_error = function(rgbe_error_code, msg) { switch (rgbe_error_code) { case rgbe_read_error: console.error("THREE.RGBELoader Read Error: " + (msg || "")); break; case rgbe_write_error: console.error("THREE.RGBELoader Write Error: " + (msg || "")); break; case rgbe_format_error: console.error("THREE.RGBELoader Bad File Format: " + (msg || "")); break; default: case rgbe_memory_error: console.error("THREE.RGBELoader: Error: " + (msg || "")); } return RGBE_RETURN_FAILURE; }, RGBE_VALID_PROGRAMTYPE = 1, RGBE_VALID_FORMAT = 2, RGBE_VALID_DIMENSIONS = 4, NEWLINE = "\n", fgets = function(buffer2, lineLimit, consume) { const chunkSize = 128; lineLimit = !lineLimit ? 1024 : lineLimit; let p2 = buffer2.pos, i = -1, len = 0, s = "", chunk = String.fromCharCode.apply(null, new Uint16Array(buffer2.subarray(p2, p2 + chunkSize))); while (0 > (i = chunk.indexOf(NEWLINE)) && len < lineLimit && p2 < buffer2.byteLength) { s += chunk; len += chunk.length; p2 += chunkSize; chunk += String.fromCharCode.apply(null, new Uint16Array(buffer2.subarray(p2, p2 + chunkSize))); } if (-1 < i) { if (false !== consume) buffer2.pos += len + i + 1; return s + chunk.slice(0, i); } return false; }, RGBE_ReadHeader = function(buffer2) { const magic_token_re = /^#\?(\S+)/, gamma_re = /^\s*GAMMA\s*=\s*(\d+(\.\d+)?)\s*$/, exposure_re = /^\s*EXPOSURE\s*=\s*(\d+(\.\d+)?)\s*$/, format_re = /^\s*FORMAT=(\S+)\s*$/, dimensions_re = /^\s*\-Y\s+(\d+)\s+\+X\s+(\d+)\s*$/, header = { valid: 0, /* indicate which fields are valid */ string: "", /* the actual header string */ comments: "", /* comments found in header */ programtype: "RGBE", /* listed at beginning of file to identify it after "#?". defaults to "RGBE" */ format: "", /* RGBE format, default 32-bit_rle_rgbe */ gamma: 1, /* image has already been gamma corrected with given gamma. defaults to 1.0 (no correction) */ exposure: 1, /* a value of 1.0 in an image corresponds to watts/steradian/m^2. defaults to 1.0 */ width: 0, height: 0 /* image dimensions, width/height */ }; let line, match; if (buffer2.pos >= buffer2.byteLength || !(line = fgets(buffer2))) { return rgbe_error(rgbe_read_error, "no header found"); } if (!(match = line.match(magic_token_re))) { return rgbe_error(rgbe_format_error, "bad initial token"); } header.valid |= RGBE_VALID_PROGRAMTYPE; header.programtype = match[1]; header.string += line + "\n"; while (true) { line = fgets(buffer2); if (false === line) break; header.string += line + "\n"; if ("#" === line.charAt(0)) { header.comments += line + "\n"; continue; } if (match = line.match(gamma_re)) { header.gamma = parseFloat(match[1]); } if (match = line.match(exposure_re)) { header.exposure = parseFloat(match[1]); } if (match = line.match(format_re)) { header.valid |= RGBE_VALID_FORMAT; header.format = match[1]; } if (match = line.match(dimensions_re)) { header.valid |= RGBE_VALID_DIMENSIONS; header.height = parseInt(match[1], 10); header.width = parseInt(match[2], 10); } if (header.valid & RGBE_VALID_FORMAT && header.valid & RGBE_VALID_DIMENSIONS) break; } if (!(header.valid & RGBE_VALID_FORMAT)) { return rgbe_error(rgbe_format_error, "missing format specifier"); } if (!(header.valid & RGBE_VALID_DIMENSIONS)) { return rgbe_error(rgbe_format_error, "missing image size specifier"); } return header; }, RGBE_ReadPixels_RLE = function(buffer2, w, h) { const scanline_width = w; if ( // run length encoding is not allowed so read flat scanline_width < 8 || scanline_width > 32767 || // this file is not run length encoded (2 !== buffer2[0] || 2 !== buffer2[1] || buffer2[2] & 128) ) { return new Uint8Array(buffer2); } if (scanline_width !== (buffer2[2] << 8 | buffer2[3])) { return rgbe_error(rgbe_format_error, "wrong scanline width"); } const data_rgba = new Uint8Array(4 * w * h); if (!data_rgba.length) { return rgbe_error(rgbe_memory_error, "unable to allocate buffer space"); } let offset = 0, pos = 0; const ptr_end = 4 * scanline_width; const rgbeStart = new Uint8Array(4); const scanline_buffer = new Uint8Array(ptr_end); let num_scanlines = h; while (num_scanlines > 0 && pos < buffer2.byteLength) { if (pos + 4 > buffer2.byteLength) { return rgbe_error(rgbe_read_error); } rgbeStart[0] = buffer2[pos++]; rgbeStart[1] = buffer2[pos++]; rgbeStart[2] = buffer2[pos++]; rgbeStart[3] = buffer2[pos++]; if (2 != rgbeStart[0] || 2 != rgbeStart[1] || (rgbeStart[2] << 8 | rgbeStart[3]) != scanline_width) { return rgbe_error(rgbe_format_error, "bad rgbe scanline format"); } let ptr = 0, count; while (ptr < ptr_end && pos < buffer2.byteLength) { count = buffer2[pos++]; const isEncodedRun = count > 128; if (isEncodedRun) count -= 128; if (0 === count || ptr + count > ptr_end) { return rgbe_error(rgbe_format_error, "bad scanline data"); } if (isEncodedRun) { const byteValue = buffer2[pos++]; for (let i = 0; i < count; i++) { scanline_buffer[ptr++] = byteValue; } } else { scanline_buffer.set(buffer2.subarray(pos, pos + count), ptr); ptr += count; pos += count; } } const l = scanline_width; for (let i = 0; i < l; i++) { let off = 0; data_rgba[offset] = scanline_buffer[i + off]; off += scanline_width; data_rgba[offset + 1] = scanline_buffer[i + off]; off += scanline_width; data_rgba[offset + 2] = scanline_buffer[i + off]; off += scanline_width; data_rgba[offset + 3] = scanline_buffer[i + off]; offset += 4; } num_scanlines--; } return data_rgba; }; const RGBEByteToRGBFloat = function(sourceArray, sourceOffset, destArray, destOffset) { const e = sourceArray[sourceOffset + 3]; const scale = Math.pow(2, e - 128) / 255; destArray[destOffset + 0] = sourceArray[sourceOffset + 0] * scale; destArray[destOffset + 1] = sourceArray[sourceOffset + 1] * scale; destArray[destOffset + 2] = sourceArray[sourceOffset + 2] * scale; destArray[destOffset + 3] = 1; }; const RGBEByteToRGBHalf = function(sourceArray, sourceOffset, destArray, destOffset) { const e = sourceArray[sourceOffset + 3]; const scale = Math.pow(2, e - 128) / 255; destArray[destOffset + 0] = DataUtils.toHalfFloat(Math.min(sourceArray[sourceOffset + 0] * scale, 65504)); destArray[destOffset + 1] = DataUtils.toHalfFloat(Math.min(sourceArray[sourceOffset + 1] * scale, 65504)); destArray[destOffset + 2] = DataUtils.toHalfFloat(Math.min(sourceArray[sourceOffset + 2] * scale, 65504)); destArray[destOffset + 3] = DataUtils.toHalfFloat(1); }; const byteArray = new Uint8Array(buffer); byteArray.pos = 0; const rgbe_header_info = RGBE_ReadHeader(byteArray); if (RGBE_RETURN_FAILURE !== rgbe_header_info) { const w = rgbe_header_info.width, h = rgbe_header_info.height, image_rgba_data = RGBE_ReadPixels_RLE(byteArray.subarray(byteArray.pos), w, h); if (RGBE_RETURN_FAILURE !== image_rgba_data) { let data, type; let numElements; switch (this.type) { case FloatType: numElements = image_rgba_data.length / 4; const floatArray = new Float32Array(numElements * 4); for (let j = 0; j < numElements; j++) { RGBEByteToRGBFloat(image_rgba_data, j * 4, floatArray, j * 4); } data = floatArray; type = FloatType; break; case HalfFloatType: numElements = image_rgba_data.length / 4; const halfArray = new Uint16Array(numElements * 4); for (let j = 0; j < numElements; j++) { RGBEByteToRGBHalf(image_rgba_data, j * 4, halfArray, j * 4); } data = halfArray; type = HalfFloatType; break; default: console.error("THREE.RGBELoader: unsupported type: ", this.type); break; } return { width: w, height: h, data, header: rgbe_header_info.string, gamma: rgbe_header_info.gamma, exposure: rgbe_header_info.exposure, type }; } } return null; } setDataType(value) { this.type = value; return this; } load(url, onLoad, onProgress, onError) { function onLoadCallback(texture, texData) { switch (texture.type) { case FloatType: case HalfFloatType: texture.encoding = LinearEncoding; texture.minFilter = LinearFilter; texture.magFilter = LinearFilter; texture.generateMipmaps = false; texture.flipY = true; break; } if (onLoad) onLoad(texture, texData); } return super.load(url, onLoadCallback, onProgress, onError); } }; // node_modules/@google/model-viewer/lib/three-components/EnvironmentScene.js var EnvironmentScene = class extends Scene { constructor() { super(); this.position.y = -3.5; const geometry = new BoxGeometry(); geometry.deleteAttribute("uv"); const roomMaterial = new MeshStandardMaterial({ metalness: 0, side: BackSide }); const boxMaterial = new MeshStandardMaterial({ metalness: 0 }); const mainLight = new PointLight(16777215, 500, 28, 2); mainLight.position.set(0.418, 16.199, 0.3); this.add(mainLight); const room = new Mesh(geometry, roomMaterial); room.position.set(-0.757, 13.219, 0.717); room.scale.set(31.713, 28.305, 28.591); this.add(room); const box1 = new Mesh(geometry, boxMaterial); box1.position.set(-10.906, 2.009, 1.846); box1.rotation.set(0, -0.195, 0); box1.scale.set(2.328, 7.905, 4.651); this.add(box1); const box2 = new Mesh(geometry, boxMaterial); box2.position.set(-5.607, -0.754, -0.758); box2.rotation.set(0, 0.994, 0); box2.scale.set(1.97, 1.534, 3.955); this.add(box2); const box3 = new Mesh(geometry, boxMaterial); box3.position.set(6.167, 0.857, 7.803); box3.rotation.set(0, 0.561, 0); box3.scale.set(3.927, 6.285, 3.687); this.add(box3); const box4 = new Mesh(geometry, boxMaterial); box4.position.set(-2.017, 0.018, 6.124); box4.rotation.set(0, 0.333, 0); box4.scale.set(2.002, 4.566, 2.064); this.add(box4); const box5 = new Mesh(geometry, boxMaterial); box5.position.set(2.291, -0.756, -2.621); box5.rotation.set(0, -0.286, 0); box5.scale.set(1.546, 1.552, 1.496); this.add(box5); const box6 = new Mesh(geometry, boxMaterial); box6.position.set(-2.193, -0.369, -5.547); box6.rotation.set(0, 0.516, 0); box6.scale.set(3.875, 3.487, 2.986); this.add(box6); const light1 = new Mesh(geometry, this.createAreaLightMaterial(50)); light1.position.set(-16.116, 14.37, 8.208); light1.scale.set(0.1, 2.428, 2.739); this.add(light1); const light2 = new Mesh(geometry, this.createAreaLightMaterial(50)); light2.position.set(-16.109, 18.021, -8.207); light2.scale.set(0.1, 2.425, 2.751); this.add(light2); const light3 = new Mesh(geometry, this.createAreaLightMaterial(17)); light3.position.set(14.904, 12.198, -1.832); light3.scale.set(0.15, 4.265, 6.331); this.add(light3); const light4 = new Mesh(geometry, this.createAreaLightMaterial(43)); light4.position.set(-0.462, 8.89, 14.52); light4.scale.set(4.38, 5.441, 0.088); this.add(light4); const light5 = new Mesh(geometry, this.createAreaLightMaterial(20)); light5.position.set(3.235, 11.486, -12.541); light5.scale.set(2.5, 2, 0.1); this.add(light5); const light6 = new Mesh(geometry, this.createAreaLightMaterial(100)); light6.position.set(0, 20, 0); light6.scale.set(1, 0.1, 1); this.add(light6); } createAreaLightMaterial(intensity) { const material = new MeshBasicMaterial(); material.color.setScalar(intensity); return material; } }; // node_modules/@google/model-viewer/lib/three-components/EnvironmentSceneAlt.js var EnvironmentSceneAlt = class extends Scene { constructor() { super(); this.position.y = -3.5; const geometry = new BoxGeometry(); geometry.deleteAttribute("uv"); const roomMaterial = new MeshStandardMaterial({ metalness: 0, side: BackSide }); const boxMaterial = new MeshStandardMaterial({ metalness: 0 }); const mainLight = new PointLight(16777215, 400, 28, 2); mainLight.position.set(0.5, 14, 0.5); this.add(mainLight); const room = new Mesh(geometry, roomMaterial); room.position.set(0, 13.2, 0); room.scale.set(31.5, 28.5, 31.5); this.add(room); const box1 = new Mesh(geometry, boxMaterial); box1.position.set(-10.906, -1, 1.846); box1.rotation.set(0, -0.195, 0); box1.scale.set(2.328, 7.905, 4.651); this.add(box1); const box2 = new Mesh(geometry, boxMaterial); box2.position.set(-5.607, -0.754, -0.758); box2.rotation.set(0, 0.994, 0); box2.scale.set(1.97, 1.534, 3.955); this.add(box2); const box3 = new Mesh(geometry, boxMaterial); box3.position.set(6.167, -0.16, 7.803); box3.rotation.set(0, 0.561, 0); box3.scale.set(3.927, 6.285, 3.687); this.add(box3); const box4 = new Mesh(geometry, boxMaterial); box4.position.set(-2.017, 0.018, 6.124); box4.rotation.set(0, 0.333, 0); box4.scale.set(2.002, 4.566, 2.064); this.add(box4); const box5 = new Mesh(geometry, boxMaterial); box5.position.set(2.291, -0.756, -2.621); box5.rotation.set(0, -0.286, 0); box5.scale.set(1.546, 1.552, 1.496); this.add(box5); const box6 = new Mesh(geometry, boxMaterial); box6.position.set(-2.193, -0.369, -5.547); box6.rotation.set(0, 0.516, 0); box6.scale.set(3.875, 3.487, 2.986); this.add(box6); const light1 = new Mesh(geometry, this.createAreaLightMaterial(80)); light1.position.set(-14, 10, 8); light1.scale.set(0.1, 2.5, 2.5); this.add(light1); const light2 = new Mesh(geometry, this.createAreaLightMaterial(80)); light2.position.set(-14, 14, -4); light2.scale.set(0.1, 2.5, 2.5); this.add(light2); const light3 = new Mesh(geometry, this.createAreaLightMaterial(23)); light3.position.set(14, 12, 0); light3.scale.set(0.1, 5, 5); this.add(light3); const light4 = new Mesh(geometry, this.createAreaLightMaterial(16)); light4.position.set(0, 9, 14); light4.scale.set(5, 5, 0.1); this.add(light4); const light5 = new Mesh(geometry, this.createAreaLightMaterial(80)); light5.position.set(7, 8, -14); light5.scale.set(2.5, 2.5, 0.1); this.add(light5); const light6 = new Mesh(geometry, this.createAreaLightMaterial(80)); light6.position.set(-7, 16, -14); light6.scale.set(2.5, 2.5, 0.1); this.add(light6); const light7 = new Mesh(geometry, this.createAreaLightMaterial(1)); light7.position.set(0, 20, 0); light7.scale.set(0.1, 0.1, 0.1); this.add(light7); } createAreaLightMaterial(intensity) { const material = new MeshBasicMaterial(); material.color.setScalar(intensity); return material; } }; // node_modules/@google/model-viewer/lib/three-components/TextureUtils.js var GENERATED_SIGMA = 0.04; var MAX_SAMPLES2 = 20; var HDR_FILE_RE = /\.hdr(\.js)?$/; var ldrLoader = new TextureLoader(); var hdrLoader = new RGBELoader(); hdrLoader.setDataType(HalfFloatType); var TextureUtils = class extends EventDispatcher { constructor(threeRenderer) { super(); this.threeRenderer = threeRenderer; this.generatedEnvironmentMap = null; this.generatedEnvironmentMapAlt = null; this.skyboxCache = /* @__PURE__ */ new Map(); this.blurMaterial = null; this.blurScene = null; } async load(url, progressCallback = () => { }) { try { const isHDR = HDR_FILE_RE.test(url); const loader = isHDR ? hdrLoader : ldrLoader; const texture = await new Promise((resolve, reject) => loader.load(url, resolve, (event) => { progressCallback(event.loaded / event.total * 0.9); }, reject)); progressCallback(1); texture.name = url; texture.mapping = EquirectangularReflectionMapping; if (!isHDR) { texture.encoding = sRGBEncoding; } return texture; } finally { if (progressCallback) { progressCallback(1); } } } /** * Returns a { skybox, environmentMap } object with the targets/textures * accordingly. `skybox` is a WebGLRenderCubeTarget, and `environmentMap` * is a Texture from a WebGLRenderCubeTarget. */ async generateEnvironmentMapAndSkybox(skyboxUrl = null, environmentMapUrl = null, progressCallback = () => { }) { const useAltEnvironment = environmentMapUrl !== "legacy"; if (environmentMapUrl === "legacy" || environmentMapUrl === "neutral") { environmentMapUrl = null; } environmentMapUrl = deserializeUrl(environmentMapUrl); let skyboxLoads = Promise.resolve(null); let environmentMapLoads; if (!!skyboxUrl) { skyboxLoads = this.loadEquirectFromUrl(skyboxUrl, progressCallback); } if (!!environmentMapUrl) { environmentMapLoads = this.loadEquirectFromUrl(environmentMapUrl, progressCallback); } else if (!!skyboxUrl) { environmentMapLoads = this.loadEquirectFromUrl(skyboxUrl, progressCallback); } else { environmentMapLoads = useAltEnvironment ? this.loadGeneratedEnvironmentMapAlt() : this.loadGeneratedEnvironmentMap(); } const [environmentMap, skybox] = await Promise.all([environmentMapLoads, skyboxLoads]); if (environmentMap == null) { throw new Error("Failed to load environment map."); } return { environmentMap, skybox }; } /** * Loads an equirect Texture from a given URL, for use as a skybox. */ async loadEquirectFromUrl(url, progressCallback) { if (!this.skyboxCache.has(url)) { const skyboxMapLoads = this.load(url, progressCallback); this.skyboxCache.set(url, skyboxMapLoads); } return this.skyboxCache.get(url); } async GenerateEnvironmentMap(scene, name) { await timePasses(); const renderer = this.threeRenderer; const cubeTarget = new WebGLCubeRenderTarget(256, { generateMipmaps: false, type: HalfFloatType, format: RGBAFormat, encoding: LinearEncoding, depthBuffer: true }); const cubeCamera = new CubeCamera(0.1, 100, cubeTarget); const generatedEnvironmentMap = cubeCamera.renderTarget.texture; generatedEnvironmentMap.name = name; const outputEncoding = renderer.outputEncoding; const toneMapping = renderer.toneMapping; renderer.toneMapping = NoToneMapping; renderer.outputEncoding = LinearEncoding; cubeCamera.update(renderer, scene); this.blurCubemap(cubeTarget, GENERATED_SIGMA); renderer.toneMapping = toneMapping; renderer.outputEncoding = outputEncoding; return generatedEnvironmentMap; } /** * Loads a dynamically generated environment map. */ async loadGeneratedEnvironmentMap() { if (this.generatedEnvironmentMap == null) { this.generatedEnvironmentMap = this.GenerateEnvironmentMap(new EnvironmentScene(), "legacy"); } return this.generatedEnvironmentMap; } /** * Loads a dynamically generated environment map, designed to be neutral and * color-preserving. Shows less contrast around the different sides of the * object. */ async loadGeneratedEnvironmentMapAlt() { if (this.generatedEnvironmentMapAlt == null) { this.generatedEnvironmentMapAlt = this.GenerateEnvironmentMap(new EnvironmentSceneAlt(), "neutral"); } return this.generatedEnvironmentMapAlt; } blurCubemap(cubeTarget, sigma) { if (this.blurMaterial == null) { this.blurMaterial = this.getBlurShader(MAX_SAMPLES2); const box = new BoxGeometry(); const blurMesh = new Mesh(box, this.blurMaterial); this.blurScene = new Scene(); this.blurScene.add(blurMesh); } const tempTarget = cubeTarget.clone(); this.halfblur(cubeTarget, tempTarget, sigma, "latitudinal"); this.halfblur(tempTarget, cubeTarget, sigma, "longitudinal"); } halfblur(targetIn, targetOut, sigmaRadians, direction) { const STANDARD_DEVIATIONS = 3; const pixels = targetIn.width; const radiansPerPixel = isFinite(sigmaRadians) ? Math.PI / (2 * pixels) : 2 * Math.PI / (2 * MAX_SAMPLES2 - 1); const sigmaPixels = sigmaRadians / radiansPerPixel; const samples = isFinite(sigmaRadians) ? 1 + Math.floor(STANDARD_DEVIATIONS * sigmaPixels) : MAX_SAMPLES2; if (samples > MAX_SAMPLES2) { console.warn(`sigmaRadians, ${sigmaRadians}, is too large and will clip, as it requested ${samples} samples when the maximum is set to ${MAX_SAMPLES2}`); } const weights = []; let sum = 0; for (let i = 0; i < MAX_SAMPLES2; ++i) { const x2 = i / sigmaPixels; const weight = Math.exp(-x2 * x2 / 2); weights.push(weight); if (i == 0) { sum += weight; } else if (i < samples) { sum += 2 * weight; } } for (let i = 0; i < weights.length; i++) { weights[i] = weights[i] / sum; } const blurUniforms = this.blurMaterial.uniforms; blurUniforms["envMap"].value = targetIn.texture; blurUniforms["samples"].value = samples; blurUniforms["weights"].value = weights; blurUniforms["latitudinal"].value = direction === "latitudinal"; blurUniforms["dTheta"].value = radiansPerPixel; const cubeCamera = new CubeCamera(0.1, 100, targetOut); cubeCamera.update(this.threeRenderer, this.blurScene); } getBlurShader(maxSamples) { const weights = new Float32Array(maxSamples); const poleAxis = new Vector3(0, 1, 0); const shaderMaterial = new ShaderMaterial({ name: "SphericalGaussianBlur", defines: { "n": maxSamples }, uniforms: { "envMap": { value: null }, "samples": { value: 1 }, "weights": { value: weights }, "latitudinal": { value: false }, "dTheta": { value: 0 }, "poleAxis": { value: poleAxis } }, vertexShader: ( /* glsl */ ` varying vec3 vOutputDirection; void main() { vOutputDirection = vec3( position ); gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 ); } ` ), fragmentShader: ( /* glsl */ ` varying vec3 vOutputDirection; uniform samplerCube envMap; uniform int samples; uniform float weights[ n ]; uniform bool latitudinal; uniform float dTheta; uniform vec3 poleAxis; vec3 getSample( float theta, vec3 axis ) { float cosTheta = cos( theta ); // Rodrigues' axis-angle rotation vec3 sampleDirection = vOutputDirection * cosTheta + cross( axis, vOutputDirection ) * sin( theta ) + axis * dot( axis, vOutputDirection ) * ( 1.0 - cosTheta ); return vec3( textureCube( envMap, sampleDirection ) ); } void main() { vec3 axis = latitudinal ? poleAxis : cross( poleAxis, vOutputDirection ); if ( all( equal( axis, vec3( 0.0 ) ) ) ) { axis = vec3( vOutputDirection.z, 0.0, - vOutputDirection.x ); } axis = normalize( axis ); gl_FragColor = vec4( 0.0, 0.0, 0.0, 1.0 ); gl_FragColor.rgb += weights[ 0 ] * getSample( 0.0, axis ); for ( int i = 1; i < n; i++ ) { if ( i >= samples ) { break; } float theta = dTheta * float( i ); gl_FragColor.rgb += weights[ i ] * getSample( -1.0 * theta, axis ); gl_FragColor.rgb += weights[ i ] * getSample( theta, axis ); } } ` ), blending: NoBlending, depthTest: false, depthWrite: false, side: BackSide }); return shaderMaterial; } async dispose() { for (const [, promise] of this.skyboxCache) { const skybox = await promise; skybox.dispose(); } if (this.generatedEnvironmentMap != null) { (await this.generatedEnvironmentMap).dispose(); this.generatedEnvironmentMap = null; } if (this.generatedEnvironmentMapAlt != null) { (await this.generatedEnvironmentMapAlt).dispose(); this.generatedEnvironmentMapAlt = null; } if (this.blurMaterial != null) { this.blurMaterial.dispose(); } } }; // node_modules/@google/model-viewer/lib/three-components/Renderer.js var DURATION_DECAY = 0.2; var LOW_FRAME_DURATION_MS = 40; var HIGH_FRAME_DURATION_MS = 60; var MAX_AVG_CHANGE_MS = 5; var SCALE_STEPS = [1, 0.79, 0.62, 0.5, 0.4, 0.31, 0.25]; var DEFAULT_LAST_STEP = 3; var DEFAULT_POWER_PREFERENCE = "high-performance"; var Renderer = class _Renderer extends EventDispatcher { constructor(options) { super(); this.loader = new CachingGLTFLoader(ModelViewerGLTFInstance); this.width = 0; this.height = 0; this.dpr = 1; this.debugger = null; this.scenes = /* @__PURE__ */ new Set(); this.multipleScenesVisible = false; this.lastTick = performance.now(); this.renderedLastFrame = false; this.scaleStep = 0; this.lastStep = DEFAULT_LAST_STEP; this.avgFrameDuration = (HIGH_FRAME_DURATION_MS + LOW_FRAME_DURATION_MS) / 2; this.onWebGLContextLost = (event) => { this.dispatchEvent({ type: "contextlost", sourceEvent: event }); }; this.onWebGLContextRestored = () => { var _a12; (_a12 = this.textureUtils) === null || _a12 === void 0 ? void 0 : _a12.dispose(); this.textureUtils = new TextureUtils(this.threeRenderer); for (const scene of this.scenes) { scene.element[$updateEnvironment](); } }; this.dpr = resolveDpr(); this.canvas3D = document.createElement("canvas"); this.canvas3D.id = "webgl-canvas"; this.canvas3D.classList.add("show"); try { this.threeRenderer = new WebGLRenderer({ canvas: this.canvas3D, alpha: true, antialias: true, powerPreference: options.powerPreference, preserveDrawingBuffer: true }); this.threeRenderer.autoClear = true; this.threeRenderer.outputEncoding = sRGBEncoding; this.threeRenderer.physicallyCorrectLights = true; this.threeRenderer.setPixelRatio(1); this.debugger = !!options.debug ? new Debugger(this) : null; this.threeRenderer.debug = { checkShaderErrors: !!this.debugger }; this.threeRenderer.toneMapping = ACESFilmicToneMapping; } catch (error) { console.warn(error); } this.arRenderer = new ARRenderer(this); this.textureUtils = this.canRender ? new TextureUtils(this.threeRenderer) : null; CachingGLTFLoader.initializeKTX2Loader(this.threeRenderer); this.canvas3D.addEventListener("webglcontextlost", this.onWebGLContextLost); this.canvas3D.addEventListener("webglcontextrestored", this.onWebGLContextRestored); this.updateRendererSize(); } static get singleton() { return this._singleton; } static resetSingleton() { const elements = this._singleton.dispose(); for (const element of elements) { element.disconnectedCallback(); } this._singleton = new _Renderer({ powerPreference: (self.ModelViewerElement || {}).powerPreference || DEFAULT_POWER_PREFERENCE, debug: isDebugMode() }); for (const element of elements) { element.connectedCallback(); } } get canRender() { return this.threeRenderer != null; } get scaleFactor() { return SCALE_STEPS[this.scaleStep]; } set minScale(scale) { let i = 1; while (i < SCALE_STEPS.length) { if (SCALE_STEPS[i] < scale) { break; } ++i; } this.lastStep = i - 1; } registerScene(scene) { this.scenes.add(scene); scene.forceRescale(); const size = new Vector2(); this.threeRenderer.getSize(size); scene.canvas.width = size.x; scene.canvas.height = size.y; if (this.canRender && this.scenes.size > 0) { this.threeRenderer.setAnimationLoop((time, frame) => this.render(time, frame)); } if (this.debugger != null) { this.debugger.addScene(scene); } } unregisterScene(scene) { this.scenes.delete(scene); if (this.canvas3D.parentElement === scene.canvas.parentElement) { scene.canvas.parentElement.removeChild(this.canvas3D); } if (this.canRender && this.scenes.size === 0) { this.threeRenderer.setAnimationLoop(null); } if (this.debugger != null) { this.debugger.removeScene(scene); } } displayCanvas(scene) { return this.multipleScenesVisible ? scene.element[$canvas] : this.canvas3D; } /** * The function enables an optimization, where when there is only a single * element, we can use the renderer's 3D canvas directly for * display. Otherwise we need to use the element's 2D canvas and copy the * renderer's result into it. */ countVisibleScenes() { const { canvas3D } = this; let visibleScenes = 0; let canvas3DScene = null; for (const scene of this.scenes) { const { element } = scene; if (element.modelIsVisible && scene.externalRenderer == null) { ++visibleScenes; } if (canvas3D.parentElement === scene.canvas.parentElement) { canvas3DScene = scene; } } const multipleScenesVisible = visibleScenes > 1; if (canvas3DScene != null) { const newlyMultiple = multipleScenesVisible && !this.multipleScenesVisible; const disappearing = !canvas3DScene.element.modelIsVisible; if (newlyMultiple || disappearing) { const { width, height } = this.sceneSize(canvas3DScene); this.copyPixels(canvas3DScene, width, height); canvas3D.parentElement.removeChild(canvas3D); } } this.multipleScenesVisible = multipleScenesVisible; } /** * Updates the renderer's size based on the largest scene and any changes to * device pixel ratio. */ updateRendererSize() { const dpr = resolveDpr(); if (dpr !== this.dpr) { for (const scene of this.scenes) { const { element } = scene; element[$updateSize](element.getBoundingClientRect()); } } let width = 0; let height = 0; for (const scene of this.scenes) { width = Math.max(width, scene.width); height = Math.max(height, scene.height); } if (width === this.width && height === this.height && dpr === this.dpr) { return; } this.width = width; this.height = height; this.dpr = dpr; width = Math.ceil(width * dpr); height = Math.ceil(height * dpr); if (this.canRender) { this.threeRenderer.setSize(width, height, false); } for (const scene of this.scenes) { const { canvas } = scene; canvas.width = width; canvas.height = height; scene.forceRescale(); } } updateRendererScale(delta) { const scaleStep = this.scaleStep; this.avgFrameDuration += clamp2(DURATION_DECAY * (delta - this.avgFrameDuration), -MAX_AVG_CHANGE_MS, MAX_AVG_CHANGE_MS); if (this.avgFrameDuration > HIGH_FRAME_DURATION_MS) { ++this.scaleStep; } else if (this.avgFrameDuration < LOW_FRAME_DURATION_MS && this.scaleStep > 0) { --this.scaleStep; } this.scaleStep = Math.min(this.scaleStep, this.lastStep); if (scaleStep !== this.scaleStep) { this.avgFrameDuration = (HIGH_FRAME_DURATION_MS + LOW_FRAME_DURATION_MS) / 2; } } shouldRender(scene) { if (!scene.shouldRender()) { if (scene.scaleStep != 0) { scene.scaleStep = 0; this.rescaleCanvas(scene); } else { return false; } } else if (scene.scaleStep != this.scaleStep) { scene.scaleStep = this.scaleStep; this.rescaleCanvas(scene); } return true; } rescaleCanvas(scene) { const scale = SCALE_STEPS[scene.scaleStep]; const width = Math.ceil(this.width / scale); const height = Math.ceil(this.height / scale); const { style: style2 } = scene.canvas; style2.width = `${width}px`; style2.height = `${height}px`; this.canvas3D.style.width = `${width}px`; this.canvas3D.style.height = `${height}px`; const renderedDpr = this.dpr * scale; const reason = scale < 1 ? "GPU throttling" : this.dpr !== window.devicePixelRatio ? "No meta viewport tag" : ""; scene.element.dispatchEvent(new CustomEvent("render-scale", { detail: { reportedDpr: window.devicePixelRatio, renderedDpr, minimumDpr: this.dpr * SCALE_STEPS[this.lastStep], pixelWidth: Math.ceil(scene.width * renderedDpr), pixelHeight: Math.ceil(scene.height * renderedDpr), reason } })); } sceneSize(scene) { const { dpr } = this; const scaleFactor = SCALE_STEPS[scene.scaleStep]; const width = Math.min(Math.ceil(scene.width * scaleFactor * dpr), this.canvas3D.width); const height = Math.min(Math.ceil(scene.height * scaleFactor * dpr), this.canvas3D.height); return { width, height }; } copyPixels(scene, width, height) { const context2D = scene.context; if (context2D == null) { console.log("could not acquire 2d context"); return; } context2D.clearRect(0, 0, width, height); context2D.drawImage(this.canvas3D, 0, 0, width, height, 0, 0, width, height); scene.canvas.classList.add("show"); } /** * Returns an array version of this.scenes where the non-visible ones are * first. This allows eager scenes to be rendered before they are visible, * without needing the multi-canvas render path. */ orderedScenes() { const scenes = []; for (const visible of [false, true]) { for (const scene of this.scenes) { if (scene.element.modelIsVisible === visible) { scenes.push(scene); } } } return scenes; } get isPresenting() { return this.arRenderer.isPresenting; } /** * This method takes care of updating the element and renderer state based on * the time that has passed since the last rendered frame. */ preRender(scene, t2, delta) { const { element, exposure } = scene; element[$tick](t2, delta); const exposureIsNumber = typeof exposure === "number" && !Number.isNaN(exposure); this.threeRenderer.toneMappingExposure = exposureIsNumber ? exposure : 1; } render(t2, frame) { if (frame != null) { this.arRenderer.onWebXRFrame(t2, frame); return; } const delta = t2 - this.lastTick; this.lastTick = t2; if (!this.canRender || this.isPresenting) { return; } this.countVisibleScenes(); this.updateRendererSize(); if (this.renderedLastFrame) { this.updateRendererScale(delta); this.renderedLastFrame = false; } const { canvas3D } = this; for (const scene of this.orderedScenes()) { const { element } = scene; if (!element.loaded || !element.modelIsVisible && scene.renderCount > 0) { continue; } this.preRender(scene, t2, delta); if (!this.shouldRender(scene)) { continue; } if (scene.externalRenderer != null) { const camera2 = scene.getCamera(); camera2.updateMatrix(); const { matrix, projectionMatrix } = camera2; const viewMatrix = matrix.elements.slice(); const target2 = scene.getTarget(); viewMatrix[12] += target2.x; viewMatrix[13] += target2.y; viewMatrix[14] += target2.z; scene.externalRenderer.render({ viewMatrix, projectionMatrix: projectionMatrix.elements }); continue; } if (!element.modelIsVisible && !this.multipleScenesVisible) { for (const visibleScene of this.scenes) { if (visibleScene.element.modelIsVisible) { visibleScene.queueRender(); } } } const { width, height } = this.sceneSize(scene); scene.renderShadow(this.threeRenderer); this.threeRenderer.setRenderTarget(null); this.threeRenderer.setViewport(0, Math.ceil(this.height * this.dpr) - height, width, height); this.threeRenderer.render(scene, scene.camera); if (this.multipleScenesVisible || scene.renderCount === 0) { this.copyPixels(scene, width, height); } else { if (canvas3D.parentElement !== scene.canvas.parentElement) { scene.canvas.parentElement.appendChild(canvas3D); scene.canvas.classList.remove("show"); } } scene.hasRendered(); ++scene.renderCount; this.renderedLastFrame = true; } } dispose() { if (this.textureUtils != null) { this.textureUtils.dispose(); } if (this.threeRenderer != null) { this.threeRenderer.dispose(); } this.textureUtils = null; this.threeRenderer = null; const elements = []; for (const scene of this.scenes) { elements.push(scene.element); } this.canvas3D.removeEventListener("webglcontextlost", this.onWebGLContextLost); this.canvas3D.removeEventListener("webglcontextrestored", this.onWebGLContextRestored); return elements; } }; Renderer._singleton = new Renderer({ powerPreference: (self.ModelViewerElement || {}).powerPreference || DEFAULT_POWER_PREFERENCE, debug: isDebugMode() }); // node_modules/@google/model-viewer/lib/features/scene-graph/three-dom-element.js var $correlatedObjects = Symbol("correlatedObjects"); var $sourceObject = Symbol("sourceObject"); var $onUpdate = Symbol("onUpdate"); var ThreeDOMElement = class { constructor(onUpdate, element, correlatedObjects = null) { this[$onUpdate] = onUpdate; this[$sourceObject] = element; this[$correlatedObjects] = correlatedObjects; } }; // node_modules/@google/model-viewer/lib/features/scene-graph/image.js var quadMaterial = new MeshBasicMaterial(); var quad = new PlaneGeometry(2, 2); var adhocNum = 0; var $threeTexture = Symbol("threeTexture"); var $applyTexture = Symbol("applyTexture"); var Image2 = class extends ThreeDOMElement { get [$threeTexture]() { var _a12; console.assert(this[$correlatedObjects] != null && this[$correlatedObjects].size > 0, "Image correlated object is undefined"); return (_a12 = this[$correlatedObjects]) === null || _a12 === void 0 ? void 0 : _a12.values().next().value; } constructor(onUpdate, texture, gltfImage) { gltfImage = gltfImage !== null && gltfImage !== void 0 ? gltfImage : { name: texture && texture.image && texture.image.src ? texture.image.src.split("/").pop() : "adhoc_image", uri: texture && texture.image && texture.image.src ? texture.image.src : "adhoc_image" + adhocNum++ }; super(onUpdate, gltfImage, new Set(texture ? [texture] : [])); } get name() { return this[$sourceObject].name || ""; } get uri() { return this[$sourceObject].uri; } get bufferView() { return this[$sourceObject].bufferView; } get type() { return this.uri != null ? "external" : "embedded"; } set name(name) { this[$sourceObject].name = name; } async createThumbnail(width, height) { const scene = new Scene(); quadMaterial.map = this[$threeTexture]; const mesh = new Mesh(quad, quadMaterial); scene.add(mesh); const camera2 = new OrthographicCamera(-1, 1, 1, -1, 0, 1); const { threeRenderer } = Renderer.singleton; const renderTarget = new WebGLRenderTarget(width, height); threeRenderer.setRenderTarget(renderTarget); threeRenderer.render(scene, camera2); threeRenderer.setRenderTarget(null); const buffer = new Uint8Array(width * height * 4); threeRenderer.readRenderTargetPixels(renderTarget, 0, 0, width, height, buffer); blobCanvas.width = width; blobCanvas.height = height; const blobContext = blobCanvas.getContext("2d"); const imageData = blobContext.createImageData(width, height); imageData.data.set(buffer); blobContext.putImageData(imageData, 0, 0); return new Promise(async (resolve, reject) => { blobCanvas.toBlob((blob) => { if (!blob) { return reject("Failed to capture thumbnail."); } resolve(URL.createObjectURL(blob)); }, "image/png"); }); } }; // node_modules/@google/model-viewer/lib/three-components/gltf-instance/gltf-2.0.js var Filter; (function(Filter2) { Filter2[Filter2["Nearest"] = 9728] = "Nearest"; Filter2[Filter2["Linear"] = 9729] = "Linear"; Filter2[Filter2["NearestMipmapNearest"] = 9984] = "NearestMipmapNearest"; Filter2[Filter2["LinearMipmapNearest"] = 9985] = "LinearMipmapNearest"; Filter2[Filter2["NearestMipmapLinear"] = 9986] = "NearestMipmapLinear"; Filter2[Filter2["LinearMipmapLinear"] = 9987] = "LinearMipmapLinear"; })(Filter || (Filter = {})); var Wrap; (function(Wrap2) { Wrap2[Wrap2["ClampToEdge"] = 33071] = "ClampToEdge"; Wrap2[Wrap2["MirroredRepeat"] = 33648] = "MirroredRepeat"; Wrap2[Wrap2["Repeat"] = 10497] = "Repeat"; })(Wrap || (Wrap = {})); // node_modules/@google/model-viewer/lib/features/scene-graph/sampler.js var isMinFilter = (() => { const minFilterValues = [ Filter.Nearest, Filter.Linear, Filter.NearestMipmapNearest, Filter.LinearMipmapLinear, Filter.NearestMipmapLinear, Filter.LinearMipmapLinear ]; return (value) => minFilterValues.indexOf(value) > -1; })(); var isMagFilter = (() => { const magFilterValues = [Filter.Nearest, Filter.Linear]; return (value) => magFilterValues.indexOf(value) > -1; })(); var isWrapMode = (() => { const wrapModes = [Wrap.ClampToEdge, Wrap.MirroredRepeat, Wrap.Repeat]; return (value) => wrapModes.indexOf(value) > -1; })(); var isValidSamplerValue = (property2, value) => { switch (property2) { case "minFilter": return isMinFilter(value); case "magFilter": return isMagFilter(value); case "wrapS": case "wrapT": return isWrapMode(value); default: throw new Error(`Cannot configure property "${property2}" on Sampler`); } }; var $threeTextures = Symbol("threeTextures"); var $setProperty = Symbol("setProperty"); var $sourceSampler = Symbol("sourceSampler"); var Sampler = class extends ThreeDOMElement { get [$threeTextures]() { console.assert(this[$correlatedObjects] != null && this[$correlatedObjects].size > 0, "Sampler correlated object is undefined"); return this[$correlatedObjects]; } get [$sourceSampler]() { console.assert(this[$sourceObject] != null, "Sampler source is undefined"); return this[$sourceObject]; } constructor(onUpdate, texture, gltfSampler) { gltfSampler = gltfSampler !== null && gltfSampler !== void 0 ? gltfSampler : {}; if (gltfSampler.minFilter == null) { gltfSampler.minFilter = texture ? texture.minFilter : Filter.LinearMipmapLinear; } if (gltfSampler.magFilter == null) { gltfSampler.magFilter = texture ? texture.magFilter : Filter.Linear; } if (gltfSampler.wrapS == null) { gltfSampler.wrapS = texture ? texture.wrapS : Wrap.Repeat; } if (gltfSampler.wrapT == null) { gltfSampler.wrapT = texture ? texture.wrapT : Wrap.Repeat; } super(onUpdate, gltfSampler, new Set(texture ? [texture] : [])); } get name() { return this[$sourceObject].name || ""; } get minFilter() { return this[$sourceSampler].minFilter; } get magFilter() { return this[$sourceSampler].magFilter; } get wrapS() { return this[$sourceSampler].wrapS; } get wrapT() { return this[$sourceSampler].wrapT; } setMinFilter(filter) { this[$setProperty]("minFilter", filter); } setMagFilter(filter) { this[$setProperty]("magFilter", filter); } setWrapS(mode) { this[$setProperty]("wrapS", mode); } setWrapT(mode) { this[$setProperty]("wrapT", mode); } [$setProperty](property2, value) { const sampler = this[$sourceSampler]; if (sampler != null) { if (isValidSamplerValue(property2, value)) { sampler[property2] = value; for (const texture of this[$threeTextures]) { texture[property2] = value; texture.needsUpdate = true; } } this[$onUpdate](); } } }; // node_modules/@google/model-viewer/lib/features/scene-graph/texture.js var $image = Symbol("image"); var $sampler = Symbol("sampler"); var Texture2 = class extends ThreeDOMElement { constructor(onUpdate, threeTexture, gltfTexture = null, gltfSampler = null, gltfImage = null) { super(onUpdate, gltfTexture ? gltfTexture : {}, new Set(threeTexture ? [threeTexture] : [])); this[$sampler] = new Sampler(onUpdate, threeTexture, gltfSampler); this[$image] = new Image2(onUpdate, threeTexture, gltfImage); } get name() { return this[$sourceObject].name || ""; } set name(name) { this[$sourceObject].name = name; } get sampler() { return this[$sampler]; } get source() { return this[$image]; } }; // node_modules/@google/model-viewer/lib/features/scene-graph/texture-info.js var _a4; var _b4; var $texture = Symbol("texture"); var $transform = Symbol("transform"); var $materials = Symbol("materials"); var $usage = Symbol("usage"); var TextureUsage; (function(TextureUsage2) { TextureUsage2[TextureUsage2["Base"] = 0] = "Base"; TextureUsage2[TextureUsage2["MetallicRoughness"] = 1] = "MetallicRoughness"; TextureUsage2[TextureUsage2["Normal"] = 2] = "Normal"; TextureUsage2[TextureUsage2["Occlusion"] = 3] = "Occlusion"; TextureUsage2[TextureUsage2["Emissive"] = 4] = "Emissive"; })(TextureUsage || (TextureUsage = {})); var TextureInfo = class { constructor(onUpdate, usage, threeTexture, material, gltf, gltfTextureInfo) { this[_a4] = null; this[_b4] = { rotation: 0, scale: new Vector2(1, 1), offset: new Vector2(0, 0) }; if (gltfTextureInfo && threeTexture) { const gltfTexture = gltf.textures ? gltf.textures[gltfTextureInfo.index] : null; const sampler = gltfTexture ? gltf.samplers ? gltf.samplers[gltfTexture.sampler] : null : null; const image = gltfTexture ? gltf.images ? gltf.images[gltfTexture.source] : null : null; this[$transform].rotation = threeTexture.rotation; this[$transform].scale.copy(threeTexture.repeat); this[$transform].offset.copy(threeTexture.offset); this[$texture] = new Texture2(onUpdate, threeTexture, gltfTexture, sampler, image); } this.onUpdate = onUpdate; this[$materials] = material; this[$usage] = usage; } get texture() { return this[$texture]; } setTexture(texture) { const threeTexture = texture != null ? texture.source[$threeTexture] : null; let encoding = sRGBEncoding; this[$texture] = texture; if (this[$materials]) { for (const material of this[$materials]) { switch (this[$usage]) { case TextureUsage.Base: material.map = threeTexture; break; case TextureUsage.MetallicRoughness: encoding = LinearEncoding; material.metalnessMap = threeTexture; material.roughnessMap = threeTexture; break; case TextureUsage.Normal: encoding = LinearEncoding; material.normalMap = threeTexture; break; case TextureUsage.Occlusion: encoding = LinearEncoding; material.aoMap = threeTexture; break; case TextureUsage.Emissive: material.emissiveMap = threeTexture; break; default: } material.needsUpdate = true; } } if (threeTexture) { threeTexture.encoding = encoding; threeTexture.rotation = this[$transform].rotation; threeTexture.repeat = this[$transform].scale; threeTexture.offset = this[$transform].offset; } this.onUpdate(); } }; _a4 = $texture, _b4 = $transform; // node_modules/@google/model-viewer/lib/features/scene-graph/pbr-metallic-roughness.js var $threeMaterials = Symbol("threeMaterials"); var $baseColorTexture = Symbol("baseColorTexture"); var $metallicRoughnessTexture = Symbol("metallicRoughnessTexture"); var PBRMetallicRoughness = class extends ThreeDOMElement { constructor(onUpdate, gltf, pbrMetallicRoughness, correlatedMaterials) { super(onUpdate, pbrMetallicRoughness, correlatedMaterials); if (pbrMetallicRoughness.baseColorFactor == null) { pbrMetallicRoughness.baseColorFactor = [1, 1, 1, 1]; } if (pbrMetallicRoughness.roughnessFactor == null) { pbrMetallicRoughness.roughnessFactor = 1; } if (pbrMetallicRoughness.metallicFactor == null) { pbrMetallicRoughness.metallicFactor = 1; } const { baseColorTexture: gltfBaseColorTexture, metallicRoughnessTexture: gltfMetallicRoughnessTexture } = pbrMetallicRoughness; const { map, metalnessMap } = correlatedMaterials.values().next().value; this[$baseColorTexture] = new TextureInfo(onUpdate, TextureUsage.Base, map, correlatedMaterials, gltf, gltfBaseColorTexture ? gltfBaseColorTexture : null); this[$metallicRoughnessTexture] = new TextureInfo(onUpdate, TextureUsage.MetallicRoughness, metalnessMap, correlatedMaterials, gltf, gltfMetallicRoughnessTexture ? gltfMetallicRoughnessTexture : null); } get [$threeMaterials]() { return this[$correlatedObjects]; } get baseColorFactor() { return this[$sourceObject].baseColorFactor; } get metallicFactor() { return this[$sourceObject].metallicFactor; } get roughnessFactor() { return this[$sourceObject].roughnessFactor; } get baseColorTexture() { return this[$baseColorTexture]; } get metallicRoughnessTexture() { return this[$metallicRoughnessTexture]; } setBaseColorFactor(rgba) { const color = new Color(); if (rgba instanceof Array) { color.fromArray(rgba); } else { color.set(rgba).convertSRGBToLinear(); } for (const material of this[$threeMaterials]) { material.color.set(color); if (rgba instanceof Array) { material.opacity = rgba[3]; } else { rgba = [0, 0, 0, material.opacity]; color.toArray(rgba); } } const pbrMetallicRoughness = this[$sourceObject]; pbrMetallicRoughness.baseColorFactor = rgba; this[$onUpdate](); } setMetallicFactor(value) { for (const material of this[$threeMaterials]) { material.metalness = value; } const pbrMetallicRoughness = this[$sourceObject]; pbrMetallicRoughness.metallicFactor = value; this[$onUpdate](); } setRoughnessFactor(value) { for (const material of this[$threeMaterials]) { material.roughness = value; } const pbrMetallicRoughness = this[$sourceObject]; pbrMetallicRoughness.roughnessFactor = value; this[$onUpdate](); } }; // node_modules/@google/model-viewer/lib/features/scene-graph/material.js var _a5; var $pbrMetallicRoughness = Symbol("pbrMetallicRoughness"); var $normalTexture = Symbol("normalTexture"); var $occlusionTexture = Symbol("occlusionTexture"); var $emissiveTexture = Symbol("emissiveTexture"); var $backingThreeMaterial = Symbol("backingThreeMaterial"); var $applyAlphaCutoff = Symbol("applyAlphaCutoff"); var $lazyLoadGLTFInfo = Symbol("lazyLoadGLTFInfo"); var $initialize = Symbol("initialize"); var $getLoadedMaterial = Symbol("getLoadedMaterial"); var $ensureMaterialIsLoaded = Symbol("ensureMaterialIsLoaded"); var $gltfIndex = Symbol("gltfIndex"); var $setActive = Symbol("setActive"); var $variantIndices = Symbol("variantIndices"); var $isActive = Symbol("isActive"); var $variantSet = Symbol("variantSet"); var $modelVariants = Symbol("modelVariants"); var Material2 = class extends ThreeDOMElement { constructor(onUpdate, gltf, gltfMaterial, gltfIndex, isActive, modelVariants, correlatedMaterials, lazyLoadInfo = void 0) { super(onUpdate, gltfMaterial, correlatedMaterials); this[_a5] = /* @__PURE__ */ new Set(); this[$gltfIndex] = gltfIndex; this[$isActive] = isActive; this[$modelVariants] = modelVariants; if (lazyLoadInfo == null) { this[$initialize](gltf); } else { this[$lazyLoadGLTFInfo] = lazyLoadInfo; } } get [(_a5 = $variantSet, $backingThreeMaterial)]() { return this[$correlatedObjects].values().next().value; } [$initialize](gltf) { const onUpdate = this[$onUpdate]; const gltfMaterial = this[$sourceObject]; const correlatedMaterials = this[$correlatedObjects]; if (gltfMaterial.extensions && gltfMaterial.extensions["KHR_materials_pbrSpecularGlossiness"]) { console.warn(`Material ${gltfMaterial.name} uses a deprecated extension "KHR_materials_pbrSpecularGlossiness", please use "pbrMetallicRoughness" instead. Specular Glossiness materials are currently supported for rendering, but not for our scene-graph API, nor for auto-generation of USDZ for Quick Look.`); } if (gltfMaterial.pbrMetallicRoughness == null) { gltfMaterial.pbrMetallicRoughness = {}; } this[$pbrMetallicRoughness] = new PBRMetallicRoughness(onUpdate, gltf, gltfMaterial.pbrMetallicRoughness, correlatedMaterials); if (gltfMaterial.emissiveFactor == null) { gltfMaterial.emissiveFactor = [0, 0, 0]; } if (gltfMaterial.doubleSided == null) { gltfMaterial.doubleSided = false; } if (gltfMaterial.alphaMode == null) { gltfMaterial.alphaMode = "OPAQUE"; } if (gltfMaterial.alphaCutoff == null) { gltfMaterial.alphaCutoff = 0.5; } const { normalTexture: gltfNormalTexture, occlusionTexture: gltfOcclusionTexture, emissiveTexture: gltfEmissiveTexture } = gltfMaterial; const { normalMap, aoMap, emissiveMap } = correlatedMaterials.values().next().value; this[$normalTexture] = new TextureInfo(onUpdate, TextureUsage.Normal, normalMap, correlatedMaterials, gltf, gltfNormalTexture ? gltfNormalTexture : null); this[$occlusionTexture] = new TextureInfo(onUpdate, TextureUsage.Occlusion, aoMap, correlatedMaterials, gltf, gltfOcclusionTexture ? gltfOcclusionTexture : null); this[$emissiveTexture] = new TextureInfo(onUpdate, TextureUsage.Emissive, emissiveMap, correlatedMaterials, gltf, gltfEmissiveTexture ? gltfEmissiveTexture : null); } async [$getLoadedMaterial]() { if (this[$lazyLoadGLTFInfo] != null) { const { set, material } = await this[$lazyLoadGLTFInfo].doLazyLoad(); this[$correlatedObjects] = set; this[$initialize](this[$lazyLoadGLTFInfo].gltf); this[$lazyLoadGLTFInfo] = void 0; this.ensureLoaded = async () => { }; return material; } return this[$correlatedObjects].values().next().value; } [$ensureMaterialIsLoaded]() { if (this[$lazyLoadGLTFInfo] == null) { return; } throw new Error(`Material "${this.name}" has not been loaded, call 'await myMaterial.ensureLoaded()' before using an unloaded material.`); } async ensureLoaded() { await this[$getLoadedMaterial](); } get isLoaded() { return this[$lazyLoadGLTFInfo] == null; } get isActive() { return this[$isActive]; } [$setActive](isActive) { this[$isActive] = isActive; } get name() { return this[$sourceObject].name; } set name(name) { const sourceMaterial = this[$sourceObject]; if (sourceMaterial != null) { sourceMaterial.name = name; } if (this[$correlatedObjects] != null) { for (const threeMaterial of this[$correlatedObjects]) { threeMaterial.name = name; } } } get pbrMetallicRoughness() { this[$ensureMaterialIsLoaded](); return this[$pbrMetallicRoughness]; } get normalTexture() { this[$ensureMaterialIsLoaded](); return this[$normalTexture]; } get occlusionTexture() { this[$ensureMaterialIsLoaded](); return this[$occlusionTexture]; } get emissiveTexture() { this[$ensureMaterialIsLoaded](); return this[$emissiveTexture]; } get emissiveFactor() { this[$ensureMaterialIsLoaded](); return this[$sourceObject].emissiveFactor; } get index() { return this[$gltfIndex]; } [$variantIndices]() { return this[$variantSet]; } hasVariant(name) { const variantData = this[$modelVariants].get(name); return variantData != null && this[$variantSet].has(variantData.index); } setEmissiveFactor(rgb) { this[$ensureMaterialIsLoaded](); const color = new Color(); if (rgb instanceof Array) { color.fromArray(rgb); } else { color.set(rgb).convertSRGBToLinear(); } for (const material of this[$correlatedObjects]) { material.emissive.set(color); } this[$sourceObject].emissiveFactor = color.toArray(); this[$onUpdate](); } [$applyAlphaCutoff]() { this[$ensureMaterialIsLoaded](); const gltfMaterial = this[$sourceObject]; for (const material of this[$correlatedObjects]) { if (this[$sourceObject].alphaMode === "MASK") { material.alphaTest = gltfMaterial.alphaCutoff; } else { material.alphaTest = void 0; } material.needsUpdate = true; } } setAlphaCutoff(cutoff) { this[$ensureMaterialIsLoaded](); this[$sourceObject].alphaCutoff = cutoff; this[$applyAlphaCutoff](); this[$onUpdate](); } getAlphaCutoff() { this[$ensureMaterialIsLoaded](); return this[$sourceObject].alphaCutoff; } setDoubleSided(doubleSided) { this[$ensureMaterialIsLoaded](); for (const material of this[$correlatedObjects]) { material.side = doubleSided ? DoubleSide : FrontSide; material.needsUpdate = true; } this[$sourceObject].doubleSided = doubleSided; this[$onUpdate](); } getDoubleSided() { this[$ensureMaterialIsLoaded](); return this[$sourceObject].doubleSided; } setAlphaMode(alphaMode) { this[$ensureMaterialIsLoaded](); const enableTransparency = (material, enabled) => { material.transparent = enabled; material.depthWrite = !enabled; }; this[$sourceObject].alphaMode = alphaMode; for (const material of this[$correlatedObjects]) { enableTransparency(material, alphaMode === "BLEND"); this[$applyAlphaCutoff](); material.needsUpdate = true; } this[$onUpdate](); } getAlphaMode() { this[$ensureMaterialIsLoaded](); return this[$sourceObject].alphaMode; } }; // node_modules/@google/model-viewer/lib/features/scene-graph/nodes/primitive-node.js var _a6; var _b5; var _c; var _d; var _e; var $materials2 = Symbol("materials"); var $variantToMaterialMap = Symbol("variantToMaterialMap"); var $modelVariants2 = Symbol("modelVariants"); var $mesh = Symbol("mesh"); var $primitives = Symbol("primitives"); var $loadVariant = Symbol("loadVariant"); var $prepareVariantsForExport = Symbol("prepareVariantsForExport"); var $switchVariant = Symbol("switchVariant"); var $children = Symbol("children"); var $initialMaterialIdx = Symbol("initialMaterialIdx"); var $activeMaterialIdx = Symbol("activeMaterialIdx"); var Node3 = class { constructor(name) { this.name = ""; this[_a6] = new Array(); this.name = name; } }; _a6 = $children; var PrimitiveNode = class extends Node3 { constructor(mesh, mvMaterials, modelVariants, correlatedSceneGraph) { super(mesh.name); this[_b5] = /* @__PURE__ */ new Map(); this[_c] = /* @__PURE__ */ new Map(); this[_d] = 0; this[_e] = 0; this[$mesh] = mesh; const { gltf, threeGLTF, threeObjectMap } = correlatedSceneGraph; this[$modelVariants2] = modelVariants; this.mesh.userData.variantData = modelVariants; const materialMappings = threeObjectMap.get(mesh.material); if (materialMappings.materials != null) { this[$initialMaterialIdx] = this[$activeMaterialIdx] = materialMappings.materials; } else { console.error(`Primitive (${mesh.name}) missing initial material reference.`); } const associations = mesh.userData.associations || {}; if (associations.meshes == null) { console.error("Mesh is missing primitive index association"); return; } const meshElementArray = gltf["meshes"] || []; const gltfPrimitives = meshElementArray[associations.meshes].primitives || []; const gltfPrimitive = gltfPrimitives[associations.primitives]; if (gltfPrimitive == null) { console.error("Mesh primitive definition is missing."); return; } if (gltfPrimitive.material != null) { this[$materials2].set(gltfPrimitive.material, mvMaterials[gltfPrimitive.material]); } else { const defaultIdx = mvMaterials.findIndex((mat) => { return mat.name === "Default"; }); if (defaultIdx >= 0) { this[$materials2].set(defaultIdx, mvMaterials[defaultIdx]); } else { console.warn("gltfPrimitive has no material!"); } } if (gltfPrimitive.extensions && gltfPrimitive.extensions["KHR_materials_variants"]) { const variantsExtension = gltfPrimitive.extensions["KHR_materials_variants"]; const extensions = threeGLTF.parser.json.extensions; const variantNames = extensions["KHR_materials_variants"].variants; for (const mapping of variantsExtension.mappings) { const mvMaterial = mvMaterials[mapping.material]; this[$materials2].set(mapping.material, mvMaterial); for (const variant of mapping.variants) { const { name } = variantNames[variant]; this[$variantToMaterialMap].set(variant, mvMaterial); mvMaterial[$variantIndices]().add(variant); if (!modelVariants.has(name)) { modelVariants.set(name, { name, index: variant }); } } } } } get mesh() { return this[$mesh]; } async setActiveMaterial(material) { const mvMaterial = this[$materials2].get(material); if (mvMaterial != null) { this.mesh.material = await mvMaterial[$getLoadedMaterial](); this[$activeMaterialIdx] = material; } return this.mesh.material; } getActiveMaterial() { return this[$materials2].get(this[$activeMaterialIdx]); } getMaterial(index) { return this[$materials2].get(index); } async enableVariant(name) { if (name == null) { return this.setActiveMaterial(this[$initialMaterialIdx]); } if (this[$variantToMaterialMap] != null && this[$modelVariants2].has(name)) { const modelVariants = this[$modelVariants2].get(name); return this.enableVariantHelper(modelVariants.index); } return null; } async enableVariantHelper(index) { if (this[$variantToMaterialMap] != null && index != null) { const material = this[$variantToMaterialMap].get(index); if (material != null) { return this.setActiveMaterial(material.index); } } return null; } async instantiateVariants() { if (this[$variantToMaterialMap] == null) { return; } for (const index of this[$variantToMaterialMap].keys()) { const variantMaterial = this.mesh.userData.variantMaterials.get(index); if (variantMaterial.material != null) { continue; } const threeMaterial = await this.enableVariantHelper(index); if (threeMaterial != null) { variantMaterial.material = threeMaterial; } } } get variantInfo() { return this[$variantToMaterialMap]; } addVariant(materialVariant, variantName) { if (!this.ensureVariantIsUnused(variantName)) { return false; } if (!this[$modelVariants2].has(variantName)) { this[$modelVariants2].set(variantName, { name: variantName, index: this[$modelVariants2].size }); } const modelVariantData = this[$modelVariants2].get(variantName); const variantIndex = modelVariantData.index; materialVariant[$variantIndices]().add(variantIndex); this[$variantToMaterialMap].set(variantIndex, materialVariant); this[$materials2].set(materialVariant.index, materialVariant); this.updateVariantUserData(variantIndex, materialVariant); return true; } deleteVariant(variantIndex) { if (this.variantInfo.has(variantIndex)) { this.variantInfo.delete(variantIndex); const userDataMap = this.mesh.userData.variantMaterials; if (userDataMap != null) { userDataMap.delete(variantIndex); } } } updateVariantUserData(variantIndex, materialVariant) { materialVariant[$variantIndices]().add(variantIndex); this.mesh.userData.variantData = this[$modelVariants2]; this.mesh.userData.variantMaterials = this.mesh.userData.variantMaterials || /* @__PURE__ */ new Map(); const map = this.mesh.userData.variantMaterials; map.set(variantIndex, { material: materialVariant[$correlatedObjects].values().next().value, gltfMaterialIndex: materialVariant.index }); } ensureVariantIsUnused(variantName) { const modelVariants = this[$modelVariants2].get(variantName); if (modelVariants != null && this.variantInfo.has(modelVariants.index)) { console.warn(`Primitive cannot add variant '${variantName}' for this material, it already exists.`); return false; } return true; } }; _b5 = $materials2, _c = $variantToMaterialMap, _d = $initialMaterialIdx, _e = $activeMaterialIdx; // node_modules/@google/model-viewer/lib/features/scene-graph/model.js var _a7; var _b6; var _c2; var _d2; var _e2; var _f; var $materials3 = Symbol("materials"); var $hierarchy = Symbol("hierarchy"); var $roots = Symbol("roots"); var $primitivesList = Symbol("primitives"); var $loadVariant2 = Symbol("loadVariant"); var $correlatedSceneGraph2 = Symbol("correlatedSceneGraph"); var $prepareVariantsForExport2 = Symbol("prepareVariantsForExport"); var $switchVariant2 = Symbol("switchVariant"); var $threeScene = Symbol("threeScene"); var $materialsFromPoint = Symbol("materialsFromPoint"); var $materialFromPoint = Symbol("materialFromPoint"); var $variantData = Symbol("variantData"); var $availableVariants = Symbol("availableVariants"); var $modelOnUpdate = Symbol("modelOnUpdate"); var $cloneMaterial = Symbol("cloneMaterial"); var LazyLoader = class { constructor(gltf, gltfElementMap, mapKey, doLazyLoad) { this.gltf = gltf; this.gltfElementMap = gltfElementMap; this.mapKey = mapKey; this.doLazyLoad = doLazyLoad; } }; var Model = class { constructor(correlatedSceneGraph, onUpdate = () => { }) { this[_a7] = new Array(); this[_b6] = new Array(); this[_c2] = new Array(); this[_d2] = new Array(); this[_e2] = () => { }; this[_f] = /* @__PURE__ */ new Map(); this[$modelOnUpdate] = onUpdate; this[$correlatedSceneGraph2] = correlatedSceneGraph; const { gltf, threeGLTF, gltfElementMap } = correlatedSceneGraph; this[$threeScene] = threeGLTF.scene; for (const [i, material] of gltf.materials.entries()) { const correlatedMaterial = gltfElementMap.get(material); if (correlatedMaterial != null) { this[$materials3].push(new Material2(onUpdate, gltf, material, i, true, this[$variantData], correlatedMaterial)); } else { const elementArray = gltf["materials"] || []; const gltfMaterialDef = elementArray[i]; const capturedMatIndex = i; const materialLoadCallback = async () => { const threeMaterial = await threeGLTF.parser.getDependency("material", capturedMatIndex); const threeMaterialSet = /* @__PURE__ */ new Set(); gltfElementMap.set(gltfMaterialDef, threeMaterialSet); threeMaterialSet.add(threeMaterial); return { set: threeMaterialSet, material: threeMaterial }; }; this[$materials3].push(new Material2(onUpdate, gltf, gltfMaterialDef, i, false, this[$variantData], correlatedMaterial, new LazyLoader(gltf, gltfElementMap, gltfMaterialDef, materialLoadCallback))); } } const parentMap = /* @__PURE__ */ new Map(); const nodeStack = new Array(); for (const object of threeGLTF.scene.children) { nodeStack.push(object); } while (nodeStack.length > 0) { const object = nodeStack.pop(); let node = null; if (object instanceof Mesh) { node = new PrimitiveNode(object, this.materials, this[$variantData], correlatedSceneGraph); this[$primitivesList].push(node); } else { node = new Node3(object.name); } const parent = parentMap.get(object); if (parent != null) { parent[$children].push(node); } else { this[$roots].push(node); } this[$hierarchy].push(node); for (const child of object.children) { nodeStack.push(child); parentMap.set(object, node); } } } /** * Materials are listed in the order of the GLTF materials array, plus a * default material at the end if one is used. * * TODO(#1003): How do we handle non-active scenes? */ get materials() { return this[$materials3]; } [(_a7 = $materials3, _b6 = $hierarchy, _c2 = $roots, _d2 = $primitivesList, _e2 = $modelOnUpdate, _f = $variantData, $availableVariants)]() { const variants = Array.from(this[$variantData].values()); variants.sort((a, b) => { return a.index - b.index; }); return variants.map((data) => { return data.name; }); } getMaterialByName(name) { const matches = this[$materials3].filter((material) => { return material.name === name; }); if (matches.length > 0) { return matches[0]; } return null; } /** * Intersects a ray with the Model and returns a list of materials whose * objects were intersected. */ [$materialsFromPoint](raycaster2) { const hits = raycaster2.intersectObject(this[$threeScene], true); return hits.map((hit) => { const found = this[$hierarchy].find((node) => { if (node instanceof PrimitiveNode) { const primitive = node; if (primitive.mesh === hit.object) { return true; } } return false; }); if (found != null) { return found.getActiveMaterial(); } return null; }); } /** * Intersects a ray with the Model and returns the first material whose * object was intersected. */ [$materialFromPoint](raycaster2) { const materials = this[$materialsFromPoint](raycaster2); if (materials.length > 0) { return materials[0]; } return null; } /** * Switches model variant to the variant name provided, or switches to * default/initial materials if 'null' is provided. */ async [$switchVariant2](variantName) { for (const primitive of this[$primitivesList]) { await primitive.enableVariant(variantName); } for (const material of this.materials) { material[$setActive](false); } for (const primitive of this[$primitivesList]) { this.materials[primitive.getActiveMaterial().index][$setActive](true); } } async [$prepareVariantsForExport2]() { const promises = new Array(); for (const primitive of this[$primitivesList]) { promises.push(primitive.instantiateVariants()); } await Promise.all(promises); } [$cloneMaterial](index, newMaterialName) { const material = this.materials[index]; if (!material.isLoaded) { console.error(`Cloning an unloaded material, call 'material.ensureLoaded() before cloning the material.`); } const threeMaterialSet = material[$correlatedObjects]; const gltfSourceMaterial = JSON.parse(JSON.stringify(material[$sourceObject])); gltfSourceMaterial.name = newMaterialName; const gltf = this[$correlatedSceneGraph2].gltf; gltf.materials.push(gltfSourceMaterial); const clonedSet = /* @__PURE__ */ new Set(); for (const [i, threeMaterial] of threeMaterialSet.entries()) { const clone2 = threeMaterial.clone(); clone2.name = newMaterialName + (threeMaterialSet.size > 1 ? "_inst" + i : ""); clonedSet.add(clone2); } const clonedMaterial = new Material2( this[$modelOnUpdate], this[$correlatedSceneGraph2].gltf, gltfSourceMaterial, this[$materials3].length, false, // Cloned as inactive. this[$variantData], clonedSet ); this[$materials3].push(clonedMaterial); return clonedMaterial; } createMaterialInstanceForVariant(originalMaterialIndex, newMaterialName, variantName, activateVariant = true) { let variantMaterialInstance = null; for (const primitive of this[$primitivesList]) { const variantData = this[$variantData].get(variantName); if (variantData != null && primitive.variantInfo.has(variantData.index)) { continue; } if (primitive.getMaterial(originalMaterialIndex) == null) { continue; } if (!this.hasVariant(variantName)) { this.createVariant(variantName); } if (variantMaterialInstance == null) { variantMaterialInstance = this[$cloneMaterial](originalMaterialIndex, newMaterialName); } primitive.addVariant(variantMaterialInstance, variantName); } if (activateVariant && variantMaterialInstance != null) { variantMaterialInstance[$setActive](true); this.materials[originalMaterialIndex][$setActive](false); for (const primitive of this[$primitivesList]) { primitive.enableVariant(variantName); } } return variantMaterialInstance; } createVariant(variantName) { if (!this[$variantData].has(variantName)) { this[$variantData].set(variantName, { name: variantName, index: this[$variantData].size }); } else { console.warn(`Variant '${variantName}'' already exists`); } } hasVariant(variantName) { return this[$variantData].has(variantName); } setMaterialToVariant(materialIndex, targetVariantName) { if (this[$availableVariants]().find((name) => name === targetVariantName) == null) { console.warn(`Can't add material to '${targetVariantName}', the variant does not exist.'`); return; } if (materialIndex < 0 || materialIndex >= this.materials.length) { console.error(`setMaterialToVariant(): materialIndex is out of bounds.`); return; } for (const primitive of this[$primitivesList]) { const material = primitive.getMaterial(materialIndex); if (material != null) { primitive.addVariant(material, targetVariantName); } } } updateVariantName(currentName, newName) { const variantData = this[$variantData].get(currentName); if (variantData == null) { return; } variantData.name = newName; this[$variantData].set(newName, variantData); this[$variantData].delete(currentName); } deleteVariant(variantName) { const variant = this[$variantData].get(variantName); if (variant == null) { return; } for (const material of this.materials) { if (material.hasVariant(variantName)) { material[$variantSet].delete(variant.index); } } for (const primitive of this[$primitivesList]) { primitive.deleteVariant(variant.index); } this[$variantData].delete(variantName); } }; // node_modules/@google/model-viewer/lib/features/scene-graph.js var __decorate2 = function(decorators, target2, key, desc) { var c = arguments.length, r = c < 3 ? target2 : desc === null ? desc = Object.getOwnPropertyDescriptor(target2, key) : desc, d; if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target2, key, desc); else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target2, key, r) : d(target2, key)) || r; return c > 3 && r && Object.defineProperty(target2, key, r), r; }; var $currentGLTF = Symbol("currentGLTF"); var $originalGltfJson = Symbol("originalGltfJson"); var $model = Symbol("model"); var $getOnUpdateMethod = Symbol("getOnUpdateMethod"); var $textureLoader = Symbol("textureLoader"); var SceneGraphMixin = (ModelViewerElement2) => { var _a12, _b11, _c6, _d5; class SceneGraphModelViewerElement extends ModelViewerElement2 { constructor() { super(...arguments); this[_a12] = void 0; this[_b11] = null; this[_c6] = new TextureLoader(); this[_d5] = null; this.variantName = null; this.orientation = "0 0 0"; this.scale = "1 1 1"; } // Scene-graph API: /** @export */ get model() { return this[$model]; } get availableVariants() { return this.model ? this.model[$availableVariants]() : []; } /** * Returns a deep copy of the gltf JSON as loaded. It will not reflect * changes to the scene-graph, nor will editing it have any effect. */ get originalGltfJson() { return this[$originalGltfJson]; } [(_a12 = $model, _b11 = $currentGLTF, _c6 = $textureLoader, _d5 = $originalGltfJson, $getOnUpdateMethod)]() { return () => { this[$needsRender](); }; } async createTexture(uri, type = "image/png") { const currentGLTF = this[$currentGLTF]; const texture = await new Promise((resolve) => this[$textureLoader].load(uri, resolve)); if (!currentGLTF || !texture) { return null; } texture.encoding = sRGBEncoding; texture.wrapS = RepeatWrapping; texture.wrapT = RepeatWrapping; texture.flipY = false; texture.userData.mimeType = type; return new Texture2(this[$getOnUpdateMethod](), texture); } async updated(changedProperties) { super.updated(changedProperties); if (changedProperties.has("variantName")) { const updateVariantProgress = this[$progressTracker].beginActivity(); updateVariantProgress(0.1); const model = this[$model]; const { variantName } = this; if (model != null) { await model[$switchVariant2](variantName); this[$needsRender](); this.dispatchEvent(new CustomEvent("variant-applied")); } updateVariantProgress(1); } if (changedProperties.has("orientation") || changedProperties.has("scale")) { if (!this.loaded) { return; } const scene = this[$scene]; scene.applyTransform(); scene.updateBoundingBox(); scene.updateShadow(); this[$renderer].arRenderer.onUpdateScene(); this[$needsRender](); } } [$onModelLoad]() { super[$onModelLoad](); const { currentGLTF } = this[$scene]; if (currentGLTF != null) { const { correlatedSceneGraph } = currentGLTF; if (correlatedSceneGraph != null && currentGLTF !== this[$currentGLTF]) { this[$model] = new Model(correlatedSceneGraph, this[$getOnUpdateMethod]()); this[$originalGltfJson] = JSON.parse(JSON.stringify(correlatedSceneGraph.gltf)); } if ("variants" in currentGLTF.userData) { this.requestUpdate("variantName"); } } this[$currentGLTF] = currentGLTF; } /** @export */ async exportScene(options) { const scene = this[$scene]; return new Promise(async (resolve, reject) => { const opts = { binary: true, onlyVisible: true, maxTextureSize: Infinity, includeCustomExtensions: false, forceIndices: false }; Object.assign(opts, options); opts.animations = scene.animations; opts.truncateDrawRange = true; const shadow = scene.shadow; let visible = false; if (shadow != null) { visible = shadow.visible; shadow.visible = false; } await this[$model][$prepareVariantsForExport2](); const exporter = new GLTFExporter().register((writer) => new GLTFExporterMaterialsVariantsExtension(writer)); exporter.parse(scene.model, (gltf) => { return resolve(new Blob([opts.binary ? gltf : JSON.stringify(gltf)], { type: opts.binary ? "application/octet-stream" : "application/json" })); }, () => { return reject("glTF export failed"); }, opts); if (shadow != null) { shadow.visible = visible; } }); } materialFromPoint(pixelX, pixelY) { const scene = this[$scene]; const ndcCoords = scene.getNDC(pixelX, pixelY); scene.raycaster.setFromCamera(ndcCoords, scene.getCamera()); return this[$model][$materialFromPoint](scene.raycaster); } } __decorate2([ property({ type: String, attribute: "variant-name" }) ], SceneGraphModelViewerElement.prototype, "variantName", void 0); __decorate2([ property({ type: String, attribute: "orientation" }) ], SceneGraphModelViewerElement.prototype, "orientation", void 0); __decorate2([ property({ type: String, attribute: "scale" }) ], SceneGraphModelViewerElement.prototype, "scale", void 0); return SceneGraphModelViewerElement; }; // node_modules/@google/model-viewer/lib/styles/parsers.js var numberNode = (value, unit) => ({ type: "number", number: value, unit }); var parseExpressions = (() => { const cache2 = {}; const MAX_PARSE_ITERATIONS = 1e3; return (inputString) => { const cacheKey = inputString; if (cacheKey in cache2) { return cache2[cacheKey]; } const expressions = []; let parseIterations = 0; while (inputString) { if (++parseIterations > MAX_PARSE_ITERATIONS) { inputString = ""; break; } const expressionParseResult = parseExpression(inputString); const expression = expressionParseResult.nodes[0]; if (expression == null || expression.terms.length === 0) { break; } expressions.push(expression); inputString = expressionParseResult.remainingInput; } return cache2[cacheKey] = expressions; }; })(); var parseExpression = (() => { const IS_IDENT_RE = /^(\-\-|[a-z\u0240-\uffff])/i; const IS_OPERATOR_RE = /^([\*\+\/]|[\-]\s)/i; const IS_EXPRESSION_END_RE = /^[\),]/; const FUNCTION_ARGUMENTS_FIRST_TOKEN = "("; const HEX_FIRST_TOKEN = "#"; return (inputString) => { const terms = []; while (inputString.length) { inputString = inputString.trim(); if (IS_EXPRESSION_END_RE.test(inputString)) { break; } else if (inputString[0] === FUNCTION_ARGUMENTS_FIRST_TOKEN) { const { nodes, remainingInput } = parseFunctionArguments(inputString); inputString = remainingInput; terms.push({ type: "function", name: { type: "ident", value: "calc" }, arguments: nodes }); } else if (IS_IDENT_RE.test(inputString)) { const identParseResult = parseIdent(inputString); const identNode = identParseResult.nodes[0]; inputString = identParseResult.remainingInput; if (inputString[0] === FUNCTION_ARGUMENTS_FIRST_TOKEN) { const { nodes, remainingInput } = parseFunctionArguments(inputString); terms.push({ type: "function", name: identNode, arguments: nodes }); inputString = remainingInput; } else { terms.push(identNode); } } else if (IS_OPERATOR_RE.test(inputString)) { terms.push({ type: "operator", value: inputString[0] }); inputString = inputString.slice(1); } else { const { nodes, remainingInput } = inputString[0] === HEX_FIRST_TOKEN ? parseHex(inputString) : parseNumber(inputString); if (nodes.length === 0) { break; } terms.push(nodes[0]); inputString = remainingInput; } } return { nodes: [{ type: "expression", terms }], remainingInput: inputString }; }; })(); var parseIdent = (() => { const NOT_IDENT_RE = /[^a-z0-9_\-\u0240-\uffff]/i; return (inputString) => { const match = inputString.match(NOT_IDENT_RE); const ident = match == null ? inputString : inputString.substr(0, match.index); const remainingInput = match == null ? "" : inputString.substr(match.index); return { nodes: [{ type: "ident", value: ident }], remainingInput }; }; })(); var parseNumber = (() => { const VALUE_RE = /[\+\-]?(\d+[\.]\d+|\d+|[\.]\d+)([eE][\+\-]?\d+)?/; const UNIT_RE = /^[a-z%]+/i; const ALLOWED_UNITS = /^(m|mm|cm|rad|deg|[%])$/; return (inputString) => { const valueMatch = inputString.match(VALUE_RE); const value = valueMatch == null ? "0" : valueMatch[0]; inputString = value == null ? inputString : inputString.slice(value.length); const unitMatch = inputString.match(UNIT_RE); let unit = unitMatch != null && unitMatch[0] !== "" ? unitMatch[0] : null; const remainingInput = unitMatch == null ? inputString : inputString.slice(unit.length); if (unit != null && !ALLOWED_UNITS.test(unit)) { unit = null; } return { nodes: [{ type: "number", number: parseFloat(value) || 0, unit }], remainingInput }; }; })(); var parseHex = (() => { const HEX_RE = /^[a-f0-9]*/i; return (inputString) => { inputString = inputString.slice(1).trim(); const hexMatch = inputString.match(HEX_RE); const nodes = hexMatch == null ? [] : [{ type: "hex", value: hexMatch[0] }]; return { nodes, remainingInput: hexMatch == null ? inputString : inputString.slice(hexMatch[0].length) }; }; })(); var parseFunctionArguments = (inputString) => { const expressionNodes = []; inputString = inputString.slice(1).trim(); while (inputString.length) { const expressionParseResult = parseExpression(inputString); expressionNodes.push(expressionParseResult.nodes[0]); inputString = expressionParseResult.remainingInput.trim(); if (inputString[0] === ",") { inputString = inputString.slice(1).trim(); } else if (inputString[0] === ")") { inputString = inputString.slice(1); break; } } return { nodes: expressionNodes, remainingInput: inputString }; }; var $visitedTypes = Symbol("visitedTypes"); var ASTWalker = class { constructor(visitedTypes) { this[$visitedTypes] = visitedTypes; } /** * Walk the given set of ASTs, and invoke the provided callback for nodes that * match the filtered set that the ASTWalker was constructed with. */ walk(ast, callback) { const remaining = ast.slice(); while (remaining.length) { const next = remaining.shift(); if (this[$visitedTypes].indexOf(next.type) > -1) { callback(next); } switch (next.type) { case "expression": remaining.unshift(...next.terms); break; case "function": remaining.unshift(next.name, ...next.arguments); break; } } } }; var ZERO = Object.freeze({ type: "number", number: 0, unit: null }); // node_modules/@google/model-viewer/lib/styles/conversions.js var degreesToRadians = (numberNode2, fallbackRadianValue = 0) => { let { number, unit } = numberNode2; if (!isFinite(number)) { number = fallbackRadianValue; unit = "rad"; } else if (numberNode2.unit === "rad" || numberNode2.unit == null) { return numberNode2; } const valueIsDegrees = unit === "deg" && number != null; const value = valueIsDegrees ? number : 0; const radians = value * Math.PI / 180; return { type: "number", number: radians, unit: "rad" }; }; var lengthToBaseMeters = (numberNode2, fallbackMeterValue = 0) => { let { number, unit } = numberNode2; if (!isFinite(number)) { number = fallbackMeterValue; unit = "m"; } else if (numberNode2.unit === "m") { return numberNode2; } let scale; switch (unit) { default: scale = 1; break; case "cm": scale = 1 / 100; break; case "mm": scale = 1 / 1e3; break; } const value = scale * number; return { type: "number", number: value, unit: "m" }; }; var normalizeUnit = (() => { const identity = (node) => node; const unitNormalizers = { "rad": identity, "deg": degreesToRadians, "m": identity, "mm": lengthToBaseMeters, "cm": lengthToBaseMeters }; return (node, fallback = ZERO) => { if (!isFinite(node.number)) { node.number = fallback.number; node.unit = fallback.unit; } const { unit } = node; if (unit == null) { return node; } const normalize2 = unitNormalizers[unit]; if (normalize2 == null) { return fallback; } return normalize2(node); }; })(); // node_modules/@google/model-viewer/lib/three-components/Hotspot.js var Hotspot = class extends CSS2DObject { constructor(config) { super(document.createElement("div")); this.normal = new Vector3(0, 1, 0); this.initialized = false; this.referenceCount = 1; this.pivot = document.createElement("div"); this.slot = document.createElement("slot"); this.element.classList.add("annotation-wrapper"); this.slot.name = config.name; this.element.appendChild(this.pivot); this.pivot.appendChild(this.slot); this.updatePosition(config.position); this.updateNormal(config.normal); } get facingCamera() { return !this.element.classList.contains("hide"); } /** * Sets the hotspot to be in the highly visible foreground state. */ show() { if (!this.facingCamera || !this.initialized) { this.updateVisibility(true); } } /** * Sets the hotspot to be in the diminished background state. */ hide() { if (this.facingCamera || !this.initialized) { this.updateVisibility(false); } } /** * Call this when adding elements to the same slot to keep track. */ increment() { this.referenceCount++; } /** * Call this when removing elements from the slot; returns true when the slot * is unused. */ decrement() { if (this.referenceCount > 0) { --this.referenceCount; } return this.referenceCount === 0; } /** * Change the position of the hotspot to the input string, in the same format * as the data-position attribute. */ updatePosition(position) { if (position == null) return; const positionNodes = parseExpressions(position)[0].terms; for (let i = 0; i < 3; ++i) { this.position.setComponent(i, normalizeUnit(positionNodes[i]).number); } this.updateMatrixWorld(); } /** * Change the hotspot's normal to the input string, in the same format as the * data-normal attribute. */ updateNormal(normal) { if (normal == null) return; const normalNodes = parseExpressions(normal)[0].terms; for (let i = 0; i < 3; ++i) { this.normal.setComponent(i, normalizeUnit(normalNodes[i]).number); } } orient(radians) { this.pivot.style.transform = `rotate(${radians}rad)`; } updateVisibility(show) { if (show) { this.element.classList.remove("hide"); } else { this.element.classList.add("hide"); } this.slot.assignedNodes().forEach((node) => { if (node.nodeType !== Node.ELEMENT_NODE) { return; } const element = node; const visibilityAttribute = element.dataset.visibilityAttribute; if (visibilityAttribute != null) { const attributeName = `data-${visibilityAttribute}`; if (show) { element.setAttribute(attributeName, ""); } else { element.removeAttribute(attributeName); } } element.dispatchEvent(new CustomEvent("hotspot-visibility", { detail: { visible: show } })); }); this.initialized = true; } }; // node_modules/@google/model-viewer/lib/three-components/ModelUtils.js var reduceVertices = (model, func, initialValue) => { let value = initialValue; const vertex2 = new Vector3(); model.traverseVisible((object) => { let i, l; object.updateWorldMatrix(false, false); const geometry = object.geometry; if (geometry !== void 0) { if (geometry.isGeometry) { const vertices = geometry.vertices; for (i = 0, l = vertices.length; i < l; i++) { vertex2.copy(vertices[i]); if (object.isSkinnedMesh) { object.boneTransform(i, vertex2); } else { vertex2.applyMatrix4(object.matrixWorld); } value = func(value, vertex2); } } else if (geometry.isBufferGeometry) { const { position } = geometry.attributes; if (position !== void 0) { for (i = 0, l = position.count; i < l; i++) { vertex2.fromBufferAttribute(position, i); if (object.isSkinnedMesh) { object.boneTransform(i, vertex2); } else { vertex2.applyMatrix4(object.matrixWorld); } value = func(value, vertex2); } } } } }); return value; }; // node_modules/three/examples/jsm/shaders/HorizontalBlurShader.js var HorizontalBlurShader = { uniforms: { "tDiffuse": { value: null }, "h": { value: 1 / 512 } }, vertexShader: ( /* glsl */ ` varying vec2 vUv; void main() { vUv = uv; gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 ); }` ), fragmentShader: ( /* glsl */ ` uniform sampler2D tDiffuse; uniform float h; varying vec2 vUv; void main() { vec4 sum = vec4( 0.0 ); sum += texture2D( tDiffuse, vec2( vUv.x - 4.0 * h, vUv.y ) ) * 0.051; sum += texture2D( tDiffuse, vec2( vUv.x - 3.0 * h, vUv.y ) ) * 0.0918; sum += texture2D( tDiffuse, vec2( vUv.x - 2.0 * h, vUv.y ) ) * 0.12245; sum += texture2D( tDiffuse, vec2( vUv.x - 1.0 * h, vUv.y ) ) * 0.1531; sum += texture2D( tDiffuse, vec2( vUv.x, vUv.y ) ) * 0.1633; sum += texture2D( tDiffuse, vec2( vUv.x + 1.0 * h, vUv.y ) ) * 0.1531; sum += texture2D( tDiffuse, vec2( vUv.x + 2.0 * h, vUv.y ) ) * 0.12245; sum += texture2D( tDiffuse, vec2( vUv.x + 3.0 * h, vUv.y ) ) * 0.0918; sum += texture2D( tDiffuse, vec2( vUv.x + 4.0 * h, vUv.y ) ) * 0.051; gl_FragColor = sum; }` ) }; // node_modules/three/examples/jsm/shaders/VerticalBlurShader.js var VerticalBlurShader = { uniforms: { "tDiffuse": { value: null }, "v": { value: 1 / 512 } }, vertexShader: ( /* glsl */ ` varying vec2 vUv; void main() { vUv = uv; gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 ); }` ), fragmentShader: ( /* glsl */ ` uniform sampler2D tDiffuse; uniform float v; varying vec2 vUv; void main() { vec4 sum = vec4( 0.0 ); sum += texture2D( tDiffuse, vec2( vUv.x, vUv.y - 4.0 * v ) ) * 0.051; sum += texture2D( tDiffuse, vec2( vUv.x, vUv.y - 3.0 * v ) ) * 0.0918; sum += texture2D( tDiffuse, vec2( vUv.x, vUv.y - 2.0 * v ) ) * 0.12245; sum += texture2D( tDiffuse, vec2( vUv.x, vUv.y - 1.0 * v ) ) * 0.1531; sum += texture2D( tDiffuse, vec2( vUv.x, vUv.y ) ) * 0.1633; sum += texture2D( tDiffuse, vec2( vUv.x, vUv.y + 1.0 * v ) ) * 0.1531; sum += texture2D( tDiffuse, vec2( vUv.x, vUv.y + 2.0 * v ) ) * 0.12245; sum += texture2D( tDiffuse, vec2( vUv.x, vUv.y + 3.0 * v ) ) * 0.0918; sum += texture2D( tDiffuse, vec2( vUv.x, vUv.y + 4.0 * v ) ) * 0.051; gl_FragColor = sum; }` ) }; // node_modules/three/src/math/MathUtils.js var DEG2RAD2 = Math.PI / 180; var RAD2DEG2 = 180 / Math.PI; function lerp2(x2, y, t2) { return (1 - t2) * x2 + t2 * y; } // node_modules/@google/model-viewer/lib/three-components/Shadow.js var LOG_MAX_RESOLUTION = 9; var LOG_MIN_RESOLUTION = 6; var ANIMATION_SCALING = 2; var DEFAULT_HARD_INTENSITY = 0.3; var Shadow = class extends Object3D { constructor(scene, softness, side) { super(); this.camera = new OrthographicCamera(); this.renderTarget = null; this.renderTargetBlur = null; this.depthMaterial = new MeshDepthMaterial(); this.horizontalBlurMaterial = new ShaderMaterial(HorizontalBlurShader); this.verticalBlurMaterial = new ShaderMaterial(VerticalBlurShader); this.intensity = 0; this.softness = 1; this.boundingBox = new Box3(); this.size = new Vector3(); this.maxDimension = 0; this.isAnimated = false; this.needsUpdate = false; const { camera: camera2 } = this; camera2.rotation.x = Math.PI / 2; camera2.left = -0.5; camera2.right = 0.5; camera2.bottom = -0.5; camera2.top = 0.5; this.add(camera2); const plane = new PlaneGeometry(); const shadowMaterial = new MeshBasicMaterial({ // color: new Color(1, 0, 0), opacity: 1, transparent: true, side: BackSide }); this.floor = new Mesh(plane, shadowMaterial); this.floor.userData.shadow = true; camera2.add(this.floor); this.blurPlane = new Mesh(plane); this.blurPlane.visible = false; camera2.add(this.blurPlane); scene.target.add(this); this.depthMaterial.onBeforeCompile = function(shader) { shader.fragmentShader = shader.fragmentShader.replace("gl_FragColor = vec4( vec3( 1.0 - fragCoordZ ), opacity );", "gl_FragColor = vec4( vec3( 0.0 ), ( 1.0 - fragCoordZ ) * opacity );"); }; this.horizontalBlurMaterial.depthTest = false; this.verticalBlurMaterial.depthTest = false; this.setScene(scene, softness, side); } /** * Update the shadow's size and position for a new scene. Softness is also * needed, as this controls the shadow's resolution. */ setScene(scene, softness, side) { const { boundingBox, size, rotation, position } = this; this.isAnimated = scene.animationNames.length > 0; this.boundingBox.copy(scene.boundingBox); this.size.copy(scene.size); this.maxDimension = Math.max(size.x, size.y, size.z) * (this.isAnimated ? ANIMATION_SCALING : 1); this.boundingBox.getCenter(position); if (side === "back") { const { min, max: max2 } = boundingBox; [min.y, min.z] = [min.z, min.y]; [max2.y, max2.z] = [max2.z, max2.y]; [size.y, size.z] = [size.z, size.y]; rotation.x = Math.PI / 2; rotation.y = Math.PI; } else { rotation.x = 0; rotation.y = 0; } if (this.isAnimated) { const minY = boundingBox.min.y; const maxY = boundingBox.max.y; size.y = this.maxDimension; boundingBox.expandByVector(size.subScalar(this.maxDimension).multiplyScalar(-0.5)); boundingBox.min.y = minY; boundingBox.max.y = maxY; size.set(this.maxDimension, maxY - minY, this.maxDimension); } if (side === "bottom") { position.y = boundingBox.min.y; } else { position.z = boundingBox.min.y; } this.setSoftness(softness); } /** * Update the shadow's resolution based on softness (between 0 and 1). Should * not be called frequently, as this results in reallocation. */ setSoftness(softness) { this.softness = softness; const { size, camera: camera2 } = this; const scaleY = this.isAnimated ? ANIMATION_SCALING : 1; const resolution = scaleY * Math.pow(2, LOG_MAX_RESOLUTION - softness * (LOG_MAX_RESOLUTION - LOG_MIN_RESOLUTION)); this.setMapSize(resolution); const softFar = size.y / 2; const hardFar = size.y * scaleY; camera2.near = 0; camera2.far = lerp2(hardFar, softFar, softness); this.depthMaterial.opacity = 1 / softness; camera2.updateProjectionMatrix(); this.setIntensity(this.intensity); this.setOffset(0); } /** * Lower-level version of the above function. */ setMapSize(maxMapSize) { const { size } = this; if (this.isAnimated) { maxMapSize *= ANIMATION_SCALING; } const baseWidth = Math.floor(size.x > size.z ? maxMapSize : maxMapSize * size.x / size.z); const baseHeight = Math.floor(size.x > size.z ? maxMapSize * size.z / size.x : maxMapSize); const TAP_WIDTH = 10; const width = TAP_WIDTH + baseWidth; const height = TAP_WIDTH + baseHeight; if (this.renderTarget != null && (this.renderTarget.width !== width || this.renderTarget.height !== height)) { this.renderTarget.dispose(); this.renderTarget = null; this.renderTargetBlur.dispose(); this.renderTargetBlur = null; } if (this.renderTarget == null) { const params = { format: RGBAFormat }; this.renderTarget = new WebGLRenderTarget(width, height, params); this.renderTargetBlur = new WebGLRenderTarget(width, height, params); this.floor.material.map = this.renderTarget.texture; } this.camera.scale.set(size.x * (1 + TAP_WIDTH / baseWidth), size.z * (1 + TAP_WIDTH / baseHeight), 1); this.needsUpdate = true; } /** * Set the shadow's intensity (0 to 1), which is just its opacity. Turns off * shadow rendering if zero. */ setIntensity(intensity) { this.intensity = intensity; if (intensity > 0) { this.visible = true; this.floor.visible = true; this.floor.material.opacity = intensity * lerp2(DEFAULT_HARD_INTENSITY, 1, this.softness * this.softness); } else { this.visible = false; this.floor.visible = false; } } getIntensity() { return this.intensity; } /** * An offset can be specified to move the * shadow vertically relative to the bottom of the scene. Positive is up, so * values are generally negative. A small offset keeps our shadow from * z-fighting with any baked-in shadow plane. */ setOffset(offset) { this.floor.position.z = -offset + 1e-3 * this.maxDimension; } render(renderer, scene) { scene.overrideMaterial = this.depthMaterial; const initialClearAlpha = renderer.getClearAlpha(); renderer.setClearAlpha(0); this.floor.visible = false; const xrEnabled = renderer.xr.enabled; renderer.xr.enabled = false; const oldRenderTarget = renderer.getRenderTarget(); renderer.setRenderTarget(this.renderTarget); renderer.render(scene, this.camera); scene.overrideMaterial = null; this.floor.visible = true; this.blurShadow(renderer); renderer.xr.enabled = xrEnabled; renderer.setRenderTarget(oldRenderTarget); renderer.setClearAlpha(initialClearAlpha); } blurShadow(renderer) { const { camera: camera2, horizontalBlurMaterial, verticalBlurMaterial, renderTarget, renderTargetBlur, blurPlane } = this; blurPlane.visible = true; blurPlane.material = horizontalBlurMaterial; horizontalBlurMaterial.uniforms.h.value = 1 / this.renderTarget.width; horizontalBlurMaterial.uniforms.tDiffuse.value = this.renderTarget.texture; renderer.setRenderTarget(renderTargetBlur); renderer.render(blurPlane, camera2); blurPlane.material = verticalBlurMaterial; verticalBlurMaterial.uniforms.v.value = 1 / this.renderTarget.height; verticalBlurMaterial.uniforms.tDiffuse.value = this.renderTargetBlur.texture; renderer.setRenderTarget(renderTarget); renderer.render(blurPlane, camera2); blurPlane.visible = false; } dispose() { if (this.renderTarget != null) { this.renderTarget.dispose(); } if (this.renderTargetBlur != null) { this.renderTargetBlur.dispose(); } this.depthMaterial.dispose(); this.horizontalBlurMaterial.dispose(); this.verticalBlurMaterial.dispose(); this.floor.material.dispose(); this.floor.geometry.dispose(); this.blurPlane.geometry.dispose(); this.removeFromParent(); } }; // node_modules/@google/model-viewer/lib/three-components/ModelScene.js var MIN_SHADOW_RATIO = 100; var view = new Vector3(); var target = new Vector3(); var normalWorld = new Vector3(); var raycaster = new Raycaster(); var vector32 = new Vector3(); var ndc = new Vector2(); var ModelScene = class extends Scene { constructor({ canvas, element, width, height }) { super(); this.annotationRenderer = new CSS2DRenderer(); this.schemaElement = document.createElement("script"); this.width = 1; this.height = 1; this.aspect = 1; this.scaleStep = 0; this.renderCount = 0; this.externalRenderer = null; this.camera = new PerspectiveCamera(45, 1, 0.1, 100); this.xrCamera = null; this.url = null; this.target = new Object3D(); this.animationNames = []; this.boundingBox = new Box3(); this.boundingSphere = new Sphere(); this.size = new Vector3(); this.idealAspect = 0; this.framedFoVDeg = 0; this.shadow = null; this.shadowIntensity = 0; this.shadowSoftness = 1; this.bakedShadows = /* @__PURE__ */ new Set(); this.exposure = 1; this.canScale = true; this.isDirty = false; this.goalTarget = new Vector3(); this.targetDamperX = new Damper(); this.targetDamperY = new Damper(); this.targetDamperZ = new Damper(); this._currentGLTF = null; this._model = null; this.cancelPendingSourceChange = null; this.animationsByName = /* @__PURE__ */ new Map(); this.currentAnimationAction = null; this.name = "ModelScene"; this.element = element; this.canvas = canvas; this.camera = new PerspectiveCamera(45, 1, 0.1, 100); this.camera.name = "MainCamera"; this.add(this.target); this.setSize(width, height); this.target.name = "Target"; this.mixer = new AnimationMixer(this.target); const { domElement } = this.annotationRenderer; const { style: style2 } = domElement; style2.display = "none"; style2.pointerEvents = "none"; style2.position = "absolute"; style2.top = "0"; this.element.shadowRoot.querySelector(".default").appendChild(domElement); this.schemaElement.setAttribute("type", "application/ld+json"); } /** * Function to create the context lazily, as when there is only one * element, the renderer's 3D context can be displayed * directly. This extra context is necessary to copy the renderings into when * there are more than one. */ get context() { return this.canvas.getContext("2d"); } getCamera() { return this.xrCamera != null ? this.xrCamera : this.camera; } queueRender() { this.isDirty = true; } shouldRender() { return this.isDirty; } hasRendered() { this.isDirty = false; } forceRescale() { this.scaleStep = -1; this.queueRender(); } /** * Pass in a THREE.Object3D to be controlled * by this model. */ async setObject(model) { this.reset(); this._model = model; this.target.add(model); await this.setupScene(); } /** * Sets the model via URL. */ async setSource(url, progressCallback = () => { }) { if (!url || url === this.url) { progressCallback(1); return; } this.reset(); this.url = url; if (this.externalRenderer != null) { const framingInfo = await this.externalRenderer.load(progressCallback); this.boundingSphere.radius = framingInfo.framedRadius; this.idealAspect = framingInfo.fieldOfViewAspect; return; } if (this.cancelPendingSourceChange != null) { this.cancelPendingSourceChange(); this.cancelPendingSourceChange = null; } let gltf; try { gltf = await new Promise(async (resolve, reject) => { this.cancelPendingSourceChange = () => reject(); try { const result = await this.element[$renderer].loader.load(url, this.element, progressCallback); resolve(result); } catch (error) { reject(error); } }); } catch (error) { if (error == null) { return; } throw error; } this.cancelPendingSourceChange = null; this.reset(); this.url = url; this._currentGLTF = gltf; if (gltf != null) { this._model = gltf.scene; this.target.add(gltf.scene); } const { animations } = gltf; const animationsByName = /* @__PURE__ */ new Map(); const animationNames = []; for (const animation of animations) { animationsByName.set(animation.name, animation); animationNames.push(animation.name); } this.animations = animations; this.animationsByName = animationsByName; this.animationNames = animationNames; await this.setupScene(); } async setupScene() { this.applyTransform(); this.updateBoundingBox(); await this.updateFraming(); this.updateShadow(); this.setShadowIntensity(this.shadowIntensity); } reset() { this.url = null; this.queueRender(); if (this.shadow != null) { this.shadow.setIntensity(0); } this.bakedShadows.clear(); const { _model } = this; if (_model != null) { _model.removeFromParent(); this._model = null; } const gltf = this._currentGLTF; if (gltf != null) { gltf.dispose(); this._currentGLTF = null; } if (this.currentAnimationAction != null) { this.currentAnimationAction.stop(); this.currentAnimationAction = null; } this.mixer.stopAllAction(); this.mixer.uncacheRoot(this); } dispose() { this.reset(); if (this.shadow != null) { this.shadow.dispose(); this.shadow = null; } this.element[$currentGLTF] = null; this.element[$originalGltfJson] = null; this.element[$model] = null; } get currentGLTF() { return this._currentGLTF; } /** * Updates the ModelScene for a new container size in CSS pixels. */ setSize(width, height) { if (this.width === width && this.height === height) { return; } this.width = Math.max(width, 1); this.height = Math.max(height, 1); this.annotationRenderer.setSize(width, height); this.aspect = this.width / this.height; if (this.externalRenderer != null) { const dpr = resolveDpr(); this.externalRenderer.resize(width * dpr, height * dpr); } this.queueRender(); } markBakedShadow(mesh) { mesh.userData.shadow = true; this.bakedShadows.add(mesh); } unmarkBakedShadow(mesh) { mesh.userData.shadow = false; mesh.visible = true; this.bakedShadows.delete(mesh); this.boundingBox.expandByObject(mesh); } findBakedShadows(group) { const boundingBox = new Box3(); group.traverse((object) => { const mesh = object; if (!mesh.isMesh) { return; } const material = mesh.material; if (!material.transparent) { return; } boundingBox.setFromObject(mesh); const size = boundingBox.getSize(vector32); const minDim = Math.min(size.x, size.y, size.z); const maxDim = Math.max(size.x, size.y, size.z); if (maxDim < MIN_SHADOW_RATIO * minDim) { return; } this.markBakedShadow(mesh); }); } checkBakedShadows() { const { min, max: max2 } = this.boundingBox; const shadowBox = new Box3(); this.boundingBox.getSize(this.size); for (const mesh of this.bakedShadows) { shadowBox.setFromObject(mesh); if (shadowBox.min.y < min.y + this.size.y / MIN_SHADOW_RATIO && shadowBox.min.x <= min.x && shadowBox.max.x >= max2.x && shadowBox.min.z <= min.z && shadowBox.max.z >= max2.z) { continue; } if (shadowBox.min.z < min.z + this.size.z / MIN_SHADOW_RATIO && shadowBox.min.x <= min.x && shadowBox.max.x >= max2.x && shadowBox.min.y <= min.y && shadowBox.max.y >= max2.y) { continue; } this.unmarkBakedShadow(mesh); } } applyTransform() { const { model } = this; if (model == null) { return; } const orientation = parseExpressions(this.element.orientation)[0].terms; const roll = normalizeUnit(orientation[0]).number; const pitch = normalizeUnit(orientation[1]).number; const yaw = normalizeUnit(orientation[2]).number; model.quaternion.setFromEuler(new Euler(pitch, yaw, roll, "YXZ")); const scale = parseExpressions(this.element.scale)[0].terms; model.scale.set(scale[0].number, scale[1].number, scale[2].number); } updateBoundingBox() { const { model } = this; if (model == null) { return; } this.target.remove(model); this.findBakedShadows(model); const bound = (box, vertex2) => { return box.expandByPoint(vertex2); }; this.setBakedShadowVisibility(false); this.boundingBox = reduceVertices(model, bound, new Box3()); if (this.boundingBox.isEmpty()) { this.setBakedShadowVisibility(true); this.bakedShadows.forEach((mesh) => this.unmarkBakedShadow(mesh)); this.boundingBox = reduceVertices(model, bound, new Box3()); } this.checkBakedShadows(); this.setBakedShadowVisibility(); this.boundingBox.getSize(this.size); this.target.add(model); } /** * Calculates the boundingSphere and idealAspect that allows the 3D * object to be framed tightly in a 2D window of any aspect ratio without * clipping at any camera orbit. The camera's center target point can be * optionally specified. If no center is specified, it defaults to the center * of the bounding box, which means asymmetric models will tend to be tight on * one side instead of both. Proper choice of center can correct this. */ async updateFraming() { const { model } = this; if (model == null) { return; } this.target.remove(model); this.setBakedShadowVisibility(false); const { center } = this.boundingSphere; this.element.requestUpdate("cameraTarget"); await this.element.updateComplete; center.copy(this.getTarget()); const radiusSquared = (value, vertex2) => { return Math.max(value, center.distanceToSquared(vertex2)); }; this.boundingSphere.radius = Math.sqrt(reduceVertices(model, radiusSquared, 0)); const horizontalTanFov = (value, vertex2) => { vertex2.sub(center); const radiusXZ = Math.sqrt(vertex2.x * vertex2.x + vertex2.z * vertex2.z); return Math.max(value, radiusXZ / (this.idealCameraDistance() - Math.abs(vertex2.y))); }; this.idealAspect = reduceVertices(model, horizontalTanFov, 0) / Math.tan(this.framedFoVDeg / 2 * Math.PI / 180); this.setBakedShadowVisibility(); this.target.add(model); } setBakedShadowVisibility(visible = this.shadowIntensity <= 0) { for (const shadow of this.bakedShadows) { shadow.visible = visible; } } idealCameraDistance() { const halfFovRad = this.framedFoVDeg / 2 * Math.PI / 180; return this.boundingSphere.radius / Math.sin(halfFovRad); } /** * Set's the framedFieldOfView based on the aspect ratio of the window in * order to keep the model fully visible at any camera orientation. */ adjustedFoV(fovDeg) { const vertical = Math.tan(fovDeg / 2 * Math.PI / 180) * Math.max(1, this.idealAspect / this.aspect); return 2 * Math.atan(vertical) * 180 / Math.PI; } getNDC(clientX, clientY) { if (this.xrCamera != null) { ndc.set(clientX / window.screen.width, clientY / window.screen.height); } else { const rect = this.element.getBoundingClientRect(); ndc.set((clientX - rect.x) / this.width, (clientY - rect.y) / this.height); } ndc.multiplyScalar(2).subScalar(1); ndc.y *= -1; return ndc; } /** * Returns the size of the corresponding canvas element. */ getSize() { return { width: this.width, height: this.height }; } setEnvironmentAndSkybox(environment, skybox) { if (this.element[$renderer].arRenderer.presentedScene === this) { return; } this.environment = environment; this.background = skybox; this.queueRender(); } /** * Sets the point in model coordinates the model should orbit/pivot around. */ setTarget(modelX, modelY, modelZ) { this.goalTarget.set(-modelX, -modelY, -modelZ); } /** * Set the decay time of, affects the speed of target transitions. */ setTargetDamperDecayTime(decayMilliseconds) { this.targetDamperX.setDecayTime(decayMilliseconds); this.targetDamperY.setDecayTime(decayMilliseconds); this.targetDamperZ.setDecayTime(decayMilliseconds); } /** * Gets the point in model coordinates the model should orbit/pivot around. */ getTarget() { return this.goalTarget.clone().multiplyScalar(-1); } /** * Shifts the model to the target point immediately instead of easing in. */ jumpToGoal() { this.updateTarget(SETTLING_TIME); } /** * This should be called every frame with the frame delta to cause the target * to transition to its set point. */ updateTarget(delta) { const goal = this.goalTarget; const target2 = this.target.position; if (!goal.equals(target2)) { const normalization = this.boundingSphere.radius / 10; let { x: x2, y, z } = target2; x2 = this.targetDamperX.update(x2, goal.x, delta, normalization); y = this.targetDamperY.update(y, goal.y, delta, normalization); z = this.targetDamperZ.update(z, goal.z, delta, normalization); this.target.position.set(x2, y, z); this.target.updateMatrixWorld(); this.queueRender(); return true; } else { return false; } } /** * Yaw the +z (front) of the model toward the indicated world coordinates. */ pointTowards(worldX, worldZ) { const { x: x2, z } = this.position; this.yaw = Math.atan2(worldX - x2, worldZ - z); } get model() { return this._model; } /** * Yaw is the scene's orientation about the y-axis, around the rotation * center. */ set yaw(radiansY) { this.rotation.y = radiansY; this.queueRender(); } get yaw() { return this.rotation.y; } set animationTime(value) { this.mixer.setTime(value); this.queueShadowRender(); } get animationTime() { if (this.currentAnimationAction != null) { const loopCount = Math.max(this.currentAnimationAction._loopCount, 0); if (this.currentAnimationAction.loop === LoopPingPong && (loopCount & 1) === 1) { return this.duration - this.currentAnimationAction.time; } else { return this.currentAnimationAction.time; } } return 0; } set animationTimeScale(value) { this.mixer.timeScale = value; } get animationTimeScale() { return this.mixer.timeScale; } get duration() { if (this.currentAnimationAction != null && this.currentAnimationAction.getClip()) { return this.currentAnimationAction.getClip().duration; } return 0; } get hasActiveAnimation() { return this.currentAnimationAction != null; } /** * Plays an animation if there are any associated with the current model. * Accepts an optional string name of an animation to play. If no name is * provided, or if no animation is found by the given name, always falls back * to playing the first animation. */ playAnimation(name = null, crossfadeTime = 0, loopMode = LoopRepeat, repetitionCount = Infinity) { if (this._currentGLTF == null) { return; } const { animations } = this; if (animations == null || animations.length === 0) { console.warn(`Cannot play animation (model does not have any animations)`); return; } let animationClip = null; if (name != null) { animationClip = this.animationsByName.get(name); if (animationClip == null) { const parsedAnimationIndex = parseInt(name); if (!isNaN(parsedAnimationIndex) && parsedAnimationIndex >= 0 && parsedAnimationIndex < animations.length) { animationClip = animations[parsedAnimationIndex]; } } } if (animationClip == null) { animationClip = animations[0]; } try { const { currentAnimationAction: lastAnimationAction } = this; const action = this.mixer.clipAction(animationClip, this); this.currentAnimationAction = action; if (this.element.paused) { this.mixer.stopAllAction(); } else { action.paused = false; if (lastAnimationAction != null && action !== lastAnimationAction) { action.crossFadeFrom(lastAnimationAction, crossfadeTime, false); } else if (this.animationTimeScale > 0 && this.animationTime == this.duration) { this.animationTime = 0; } } action.setLoop(loopMode, repetitionCount); action.enabled = true; action.clampWhenFinished = true; action.play(); } catch (error) { console.error(error); } } stopAnimation() { this.currentAnimationAction = null; this.mixer.stopAllAction(); } updateAnimation(step) { this.mixer.update(step); this.queueShadowRender(); } subscribeMixerEvent(event, callback) { this.mixer.addEventListener(event, callback); } /** * Call if the object has been changed in such a way that the shadow's shape * has changed (not a rotation about the Y axis). */ updateShadow() { const shadow = this.shadow; if (shadow != null) { const side = this.element.arPlacement === "wall" ? "back" : "bottom"; shadow.setScene(this, this.shadowSoftness, side); shadow.needsUpdate = true; } } renderShadow(renderer) { const shadow = this.shadow; if (shadow != null && shadow.needsUpdate == true) { shadow.render(renderer, this); shadow.needsUpdate = false; } } queueShadowRender() { if (this.shadow != null) { this.shadow.needsUpdate = true; } } /** * Sets the shadow's intensity, lazily creating the shadow as necessary. */ setShadowIntensity(shadowIntensity) { this.shadowIntensity = shadowIntensity; if (this._currentGLTF == null) { return; } this.setBakedShadowVisibility(); if (shadowIntensity <= 0 && this.shadow == null) { return; } if (this.shadow == null) { const side = this.element.arPlacement === "wall" ? "back" : "bottom"; this.shadow = new Shadow(this, this.shadowSoftness, side); } this.shadow.setIntensity(shadowIntensity); } /** * Sets the shadow's softness by mapping a [0, 1] softness parameter to the * shadow's resolution. This involves reallocation, so it should not be * changed frequently. Softer shadows are cheaper to render. */ setShadowSoftness(softness) { this.shadowSoftness = softness; const shadow = this.shadow; if (shadow != null) { shadow.setSoftness(softness); } } /** * Shift the floor vertically from the bottom of the model's bounding box by * offset (should generally be negative). */ setShadowOffset(offset) { const shadow = this.shadow; if (shadow != null) { shadow.setOffset(offset); } } get raycaster() { return raycaster; } /** * This method returns the world position, model-space normal and texture * coordinate of the point on the mesh corresponding to the input pixel * coordinates given relative to the model-viewer element. If the mesh * is not hit, the result is null. */ positionAndNormalFromPoint(ndcPosition, object = this) { this.raycaster.setFromCamera(ndcPosition, this.getCamera()); const hits = this.raycaster.intersectObject(object, true); const hit = hits.find((hit2) => hit2.object.visible && !hit2.object.userData.shadow); if (hit == null || hit.face == null) { return null; } if (hit.uv == null) { return { position: hit.point, normal: hit.face.normal, uv: null }; } hit.face.normal.applyNormalMatrix(new Matrix3().getNormalMatrix(hit.object.matrixWorld)); return { position: hit.point, normal: hit.face.normal, uv: hit.uv }; } /** * The following methods are for operating on the set of Hotspot objects * attached to the scene. These come from DOM elements, provided to slots by * the Annotation Mixin. */ addHotspot(hotspot) { this.target.add(hotspot); this.annotationRenderer.domElement.appendChild(hotspot.element); } removeHotspot(hotspot) { this.target.remove(hotspot); } /** * Helper method to apply a function to all hotspots. */ forHotspots(func) { const { children } = this.target; for (let i = 0, l = children.length; i < l; i++) { const hotspot = children[i]; if (hotspot instanceof Hotspot) { func(hotspot); } } } /** * Update the CSS visibility of the hotspots based on whether their normals * point toward the camera. */ updateHotspots(viewerPosition) { this.forHotspots((hotspot) => { view.copy(viewerPosition); target.setFromMatrixPosition(hotspot.matrixWorld); view.sub(target); normalWorld.copy(hotspot.normal).transformDirection(this.target.matrixWorld); if (view.dot(normalWorld) < 0) { hotspot.hide(); } else { hotspot.show(); } }); } /** * Rotate all hotspots to an absolute orientation given by the input number of * radians. Zero returns them to upright. */ orientHotspots(radians) { this.forHotspots((hotspot) => { hotspot.orient(radians); }); } /** * Set the rendering visibility of all hotspots. This is used to hide them * during transitions and such. */ setHotspotsVisibility(visible) { this.forHotspots((hotspot) => { hotspot.visible = visible; }); } updateSchema(src) { var _a12; const { schemaElement, element } = this; const { alt, poster, iosSrc } = element; if (src != null) { const encoding = [{ "@type": "MediaObject", contentUrl: src, encodingFormat: ((_a12 = src.split(".").pop()) === null || _a12 === void 0 ? void 0 : _a12.toLowerCase()) === "gltf" ? "model/gltf+json" : "model/gltf-binary" }]; if (iosSrc) { encoding.push({ "@type": "MediaObject", contentUrl: iosSrc, encodingFormat: "model/vnd.usdz+zip" }); } const structuredData = { "@context": "http://schema.org/", "@type": "3DModel", image: poster !== null && poster !== void 0 ? poster : void 0, name: alt !== null && alt !== void 0 ? alt : void 0, encoding }; schemaElement.textContent = JSON.stringify(structuredData); document.head.appendChild(schemaElement); } else if (schemaElement.parentElement != null) { schemaElement.parentElement.removeChild(schemaElement); } } }; // node_modules/@google/model-viewer/lib/utilities/data-conversion.js var dataUrlToBlob = async (base64DataUrl) => { return new Promise((resolve, reject) => { const sliceSize = 512; const typeMatch = base64DataUrl.match(/data:(.*);/); if (!typeMatch) { return reject(new Error(`${base64DataUrl} is not a valid data Url`)); } const type = typeMatch[1]; const base64 = base64DataUrl.replace(/data:image\/\w+;base64,/, ""); const byteCharacters = atob(base64); const byteArrays = []; for (let offset = 0; offset < byteCharacters.length; offset += sliceSize) { const slice = byteCharacters.slice(offset, offset + sliceSize); const byteNumbers = new Array(slice.length); for (let i = 0; i < slice.length; i++) { byteNumbers[i] = slice.charCodeAt(i); } const byteArray = new Uint8Array(byteNumbers); byteArrays.push(byteArray); } resolve(new Blob(byteArrays, { type })); }); }; // node_modules/@google/model-viewer/lib/utilities/progress-tracker.js var ProgressTracker = class extends EventTarget { constructor() { super(...arguments); this.ongoingActivities = /* @__PURE__ */ new Set(); this.totalProgress = 0; } /** * The total number of activities currently being tracked. */ get ongoingActivityCount() { return this.ongoingActivities.size; } /** * Registers a new activity to be tracked by the progress tracker. The method * returns a special callback that should be invoked whenever new progress is * ready to be reported. The progress should be reported as a value between 0 * and 1, where 0 would represent the beginning of the action and 1 would * represent its completion. * * There is no built-in notion of a time-out for ongoing activities, so once * an ongoing activity is begun, it is up to the consumer of this API to * update the progress until that activity is no longer ongoing. * * Progress is only allowed to move forward for any given activity. If a lower * progress is reported than the previously reported progress, it will be * ignored. */ beginActivity() { const activity = { progress: 0, completed: false }; this.ongoingActivities.add(activity); if (this.ongoingActivityCount === 1) { this.announceTotalProgress(activity, 0); } return (progress) => { let nextProgress; nextProgress = Math.max(clamp2(progress, 0, 1), activity.progress); if (nextProgress !== activity.progress) { this.announceTotalProgress(activity, nextProgress); } return activity.progress; }; } announceTotalProgress(updatedActivity, nextProgress) { let progressLeft = 0; let completedActivities = 0; if (nextProgress == 1) updatedActivity.completed = true; for (const activity of this.ongoingActivities) { const { progress } = activity; progressLeft += 1 - progress; if (activity.completed === true) { completedActivities++; } } const lastProgress = updatedActivity.progress; updatedActivity.progress = nextProgress; this.totalProgress += (nextProgress - lastProgress) * (1 - this.totalProgress) / progressLeft; const totalProgress = completedActivities === this.ongoingActivityCount ? 1 : this.totalProgress; this.dispatchEvent(new CustomEvent("progress", { detail: { totalProgress } })); if (completedActivities === this.ongoingActivityCount) { this.totalProgress = 0; this.ongoingActivities.clear(); } } }; // node_modules/@google/model-viewer/lib/model-viewer-base.js var __decorate3 = function(decorators, target2, key, desc) { var c = arguments.length, r = c < 3 ? target2 : desc === null ? desc = Object.getOwnPropertyDescriptor(target2, key) : desc, d; if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target2, key, desc); else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target2, key, r) : d(target2, key)) || r; return c > 3 && r && Object.defineProperty(target2, key, r), r; }; var _a8; var _b7; var _c3; var _d3; var _e3; var _f3; var _g; var _h; var _j; var _k; var _l; var _m; var _o; var CLEAR_MODEL_TIMEOUT_MS = 1e3; var FALLBACK_SIZE_UPDATE_THRESHOLD_MS = 50; var ANNOUNCE_MODEL_VISIBILITY_DEBOUNCE_THRESHOLD = 0; var UNSIZED_MEDIA_WIDTH = 300; var UNSIZED_MEDIA_HEIGHT = 150; var blobCanvas = document.createElement("canvas"); var $fallbackResizeHandler = Symbol("fallbackResizeHandler"); var $defaultAriaLabel = Symbol("defaultAriaLabel"); var $resizeObserver = Symbol("resizeObserver"); var $clearModelTimeout = Symbol("clearModelTimeout"); var $onContextLost = Symbol("onContextLost"); var $loaded = Symbol("loaded"); var $status = Symbol("status"); var $onFocus = Symbol("onFocus"); var $onBlur = Symbol("onBlur"); var $updateSize = Symbol("updateSize"); var $intersectionObserver = Symbol("intersectionObserver"); var $isElementInViewport = Symbol("isElementInViewport"); var $announceModelVisibility = Symbol("announceModelVisibility"); var $ariaLabel = Symbol("ariaLabel"); var $altDefaulted = Symbol("altDefaulted"); var $statusElement = Symbol("statusElement"); var $updateStatus = Symbol("updateStatus"); var $loadedTime = Symbol("loadedTime"); var $updateSource = Symbol("updateSource"); var $markLoaded = Symbol("markLoaded"); var $container = Symbol("container"); var $userInputElement = Symbol("input"); var $canvas = Symbol("canvas"); var $scene = Symbol("scene"); var $needsRender = Symbol("needsRender"); var $tick = Symbol("tick"); var $onModelLoad = Symbol("onModelLoad"); var $onResize = Symbol("onResize"); var $renderer = Symbol("renderer"); var $progressTracker = Symbol("progressTracker"); var $getLoaded = Symbol("getLoaded"); var $getModelIsVisible = Symbol("getModelIsVisible"); var $shouldAttemptPreload = Symbol("shouldAttemptPreload"); var toVector3D = (v) => { return { x: v.x, y: v.y, z: v.z, toString() { return `${this.x}m ${this.y}m ${this.z}m`; } }; }; var toVector2D = (v) => { return { u: v.x, v: v.y, toString() { return `${this.u} ${this.v}`; } }; }; var ModelViewerElementBase = class extends ReactiveElement { /** * Creates a new ModelViewerElement. */ constructor() { super(); this.alt = null; this.src = null; this.withCredentials = false; this.generateSchema = false; this[_a8] = false; this[_b7] = false; this[_c3] = 0; this[_d3] = ""; this[_e3] = null; this[_f3] = debounce(() => { const boundingRect = this.getBoundingClientRect(); this[$updateSize](boundingRect); }, FALLBACK_SIZE_UPDATE_THRESHOLD_MS); this[_g] = debounce((oldVisibility) => { const newVisibility = this.modelIsVisible; if (newVisibility !== oldVisibility) { this.dispatchEvent(new CustomEvent("model-visibility", { detail: { visible: newVisibility } })); } }, ANNOUNCE_MODEL_VISIBILITY_DEBOUNCE_THRESHOLD); this[_h] = null; this[_j] = null; this[_k] = new ProgressTracker(); this[_l] = () => { this[$statusElement].textContent = this[$status]; }; this[_m] = () => { this[$statusElement].textContent = ""; }; this[_o] = (event) => { this.dispatchEvent(new CustomEvent("error", { detail: { type: "webglcontextlost", sourceError: event.sourceEvent } })); }; this.attachShadow({ mode: "open" }); const shadowRoot = this.shadowRoot; makeTemplate(shadowRoot); this[$container] = shadowRoot.querySelector(".container"); this[$userInputElement] = shadowRoot.querySelector(".userInput"); this[$canvas] = shadowRoot.querySelector("canvas"); this[$statusElement] = shadowRoot.querySelector("#status"); this[$defaultAriaLabel] = this[$userInputElement].getAttribute("aria-label"); let width, height; if (this.isConnected) { const rect = this.getBoundingClientRect(); width = rect.width; height = rect.height; } else { width = UNSIZED_MEDIA_WIDTH; height = UNSIZED_MEDIA_HEIGHT; } this[$scene] = new ModelScene({ canvas: this[$canvas], element: this, width, height }); Promise.resolve().then(() => { this[$updateSize](this.getBoundingClientRect()); }); if (HAS_RESIZE_OBSERVER) { this[$resizeObserver] = new ResizeObserver((entries) => { if (this[$renderer].isPresenting) { return; } for (let entry of entries) { if (entry.target === this) { this[$updateSize](entry.contentRect); } } }); } if (HAS_INTERSECTION_OBSERVER) { this[$intersectionObserver] = new IntersectionObserver((entries) => { for (let entry of entries) { if (entry.target === this) { const oldVisibility = this.modelIsVisible; this[$isElementInViewport] = entry.isIntersecting; this[$announceModelVisibility](oldVisibility); if (this[$isElementInViewport] && !this.loaded) { this[$updateSource](); } } } }, { root: null, // We used to have margin here, but it was causing animated models below // the fold to steal the frame budget. Weirder still, it would also // cause input events to be swallowed, sometimes for seconds on the // model above the fold, but only when the animated model was completely // below. Setting this margin to zero fixed it. rootMargin: "0px", // With zero threshold, an element adjacent to but not intersecting the // viewport will be reported as intersecting, which will cause // unnecessary rendering. Any slight positive threshold alleviates this. threshold: 1e-5 }); } else { this[$isElementInViewport] = true; } } static get is() { return "model-viewer"; } /** @export */ static set modelCacheSize(value) { CachingGLTFLoader[$evictionPolicy].evictionThreshold = value; } /** @export */ static get modelCacheSize() { return CachingGLTFLoader[$evictionPolicy].evictionThreshold; } /** @export */ static set minimumRenderScale(value) { if (value > 1) { console.warn(" minimumRenderScale has been clamped to a maximum value of 1."); } if (value <= 0) { console.warn(" minimumRenderScale has been clamped to a minimum value of 0.25."); } Renderer.singleton.minScale = value; } /** @export */ static get minimumRenderScale() { return Renderer.singleton.minScale; } /** @export */ get loaded() { return this[$getLoaded](); } get [(_a8 = $isElementInViewport, _b7 = $loaded, _c3 = $loadedTime, _d3 = $status, _e3 = $clearModelTimeout, _f3 = $fallbackResizeHandler, _g = $announceModelVisibility, _h = $resizeObserver, _j = $intersectionObserver, _k = $progressTracker, $renderer)]() { return Renderer.singleton; } /** @export */ get modelIsVisible() { return this[$getModelIsVisible](); } connectedCallback() { super.connectedCallback && super.connectedCallback(); if (HAS_RESIZE_OBSERVER) { this[$resizeObserver].observe(this); } else { self.addEventListener("resize", this[$fallbackResizeHandler]); } if (HAS_INTERSECTION_OBSERVER) { this[$intersectionObserver].observe(this); } this.addEventListener("focus", this[$onFocus]); this.addEventListener("blur", this[$onBlur]); const renderer = this[$renderer]; renderer.addEventListener("contextlost", this[$onContextLost]); renderer.registerScene(this[$scene]); if (this[$clearModelTimeout] != null) { self.clearTimeout(this[$clearModelTimeout]); this[$clearModelTimeout] = null; this.requestUpdate("src", null); } } disconnectedCallback() { super.disconnectedCallback && super.disconnectedCallback(); if (HAS_RESIZE_OBSERVER) { this[$resizeObserver].unobserve(this); } else { self.removeEventListener("resize", this[$fallbackResizeHandler]); } if (HAS_INTERSECTION_OBSERVER) { this[$intersectionObserver].unobserve(this); } this.removeEventListener("focus", this[$onFocus]); this.removeEventListener("blur", this[$onBlur]); const renderer = this[$renderer]; renderer.removeEventListener("contextlost", this[$onContextLost]); renderer.unregisterScene(this[$scene]); this[$clearModelTimeout] = self.setTimeout(() => { this[$scene].dispose(); this[$clearModelTimeout] = null; }, CLEAR_MODEL_TIMEOUT_MS); } updated(changedProperties) { super.updated(changedProperties); if (changedProperties.has("src")) { if (this.src == null) { this[$loaded] = false; this[$loadedTime] = 0; this[$scene].reset(); } else if (this.src !== this[$scene].url) { this[$loaded] = false; this[$loadedTime] = 0; this[$updateSource](); } } if (changedProperties.has("alt")) { this[$userInputElement].setAttribute("aria-label", this[$ariaLabel]); } if (changedProperties.has("withCredentials")) { CachingGLTFLoader.withCredentials = this.withCredentials; } if (changedProperties.has("generateSchema")) { if (this.generateSchema) { this[$scene].updateSchema(this.src); } else { this[$scene].updateSchema(null); } } } /** @export */ toDataURL(type, encoderOptions) { return this[$renderer].displayCanvas(this[$scene]).toDataURL(type, encoderOptions); } /** @export */ async toBlob(options) { const mimeType = options ? options.mimeType : void 0; const qualityArgument = options ? options.qualityArgument : void 0; const useIdealAspect = options ? options.idealAspect : void 0; const { width, height, idealAspect, aspect: aspect2 } = this[$scene]; const { dpr, scaleFactor } = this[$renderer]; let outputWidth = width * scaleFactor * dpr; let outputHeight = height * scaleFactor * dpr; let offsetX = 0; let offsetY = 0; if (useIdealAspect === true) { if (idealAspect > aspect2) { const oldHeight = outputHeight; outputHeight = Math.round(outputWidth / idealAspect); offsetY = (oldHeight - outputHeight) / 2; } else { const oldWidth = outputWidth; outputWidth = Math.round(outputHeight * idealAspect); offsetX = (oldWidth - outputWidth) / 2; } } blobCanvas.width = outputWidth; blobCanvas.height = outputHeight; try { return new Promise(async (resolve, reject) => { blobCanvas.getContext("2d").drawImage(this[$renderer].displayCanvas(this[$scene]), offsetX, offsetY, outputWidth, outputHeight, 0, 0, outputWidth, outputHeight); if (blobCanvas.msToBlob) { if (!mimeType || mimeType === "image/png") { return resolve(blobCanvas.msToBlob()); } } if (!blobCanvas.toBlob) { return resolve(await dataUrlToBlob(blobCanvas.toDataURL(mimeType, qualityArgument))); } blobCanvas.toBlob((blob) => { if (!blob) { return reject(new Error("Unable to retrieve canvas blob")); } resolve(blob); }, mimeType, qualityArgument); }); } finally { this[$updateSize]({ width, height }); } ; } registerRenderer(renderer) { this[$scene].externalRenderer = renderer; } unregisterRenderer() { this[$scene].externalRenderer = null; } get [$ariaLabel]() { return this[$altDefaulted]; } get [$altDefaulted]() { return this.alt == null || this.alt === "null" ? this[$defaultAriaLabel] : this.alt; } // NOTE(cdata): Although this may seem extremely redundant, it is required in // order to support overloading when TypeScript is compiled to ES5 // @see https://github.com/Polymer/lit-element/pull/745 // @see https://github.com/microsoft/TypeScript/issues/338 [$getLoaded]() { return this[$loaded]; } // @see [$getLoaded] [$getModelIsVisible]() { return this.loaded && this[$isElementInViewport]; } [$shouldAttemptPreload]() { return !!this.src && this[$isElementInViewport]; } /** * Called on initialization and when the resize observer fires. */ [$updateSize]({ width, height }) { this[$container].style.width = `${width}px`; this[$container].style.height = `${height}px`; this[$onResize]({ width: parseFloat(width), height: parseFloat(height) }); } [$tick](_time, _delta) { } [$markLoaded]() { if (this[$loaded]) { return; } this[$loaded] = true; this[$loadedTime] = performance.now(); } [$needsRender]() { this[$scene].queueRender(); } [$onModelLoad]() { } [$updateStatus](status) { this[$status] = status; const rootNode = this.getRootNode(); if (rootNode != null && rootNode.activeElement === this && this[$statusElement].textContent != status) { this[$statusElement].textContent = status; } } [(_l = $onFocus, _m = $onBlur, $onResize)](e) { this[$scene].setSize(e.width, e.height); } /** * Parses the element for an appropriate source URL and * sets the views to use the new model based. */ async [(_o = $onContextLost, $updateSource)]() { const scene = this[$scene]; if (this.loaded || !this[$shouldAttemptPreload]() || this.src === scene.url) { return; } if (this.generateSchema) { scene.updateSchema(this.src); } this[$updateStatus]("Loading"); scene.stopAnimation(); const updateSourceProgress = this[$progressTracker].beginActivity(); const source = this.src; try { const srcUpdated = scene.setSource(source, (progress) => updateSourceProgress(clamp2(progress, 0, 1) * 0.95)); const envUpdated = this[$updateEnvironment](); await Promise.all([srcUpdated, envUpdated]); this[$markLoaded](); this[$onModelLoad](); await new Promise((resolve) => { requestAnimationFrame(() => { requestAnimationFrame(() => { this.dispatchEvent(new CustomEvent("load", { detail: { url: source } })); resolve(); }); }); }); } catch (error) { this.dispatchEvent(new CustomEvent("error", { detail: { type: "loadfailure", sourceError: error } })); } finally { updateSourceProgress(1); } } }; __decorate3([ property({ type: String }) ], ModelViewerElementBase.prototype, "alt", void 0); __decorate3([ property({ type: String }) ], ModelViewerElementBase.prototype, "src", void 0); __decorate3([ property({ type: Boolean, attribute: "with-credentials" }) ], ModelViewerElementBase.prototype, "withCredentials", void 0); __decorate3([ property({ type: Boolean, attribute: "generate-schema" }) ], ModelViewerElementBase.prototype, "generateSchema", void 0); // node_modules/@google/model-viewer/lib/features/animation.js var __decorate4 = function(decorators, target2, key, desc) { var c = arguments.length, r = c < 3 ? target2 : desc === null ? desc = Object.getOwnPropertyDescriptor(target2, key) : desc, d; if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target2, key, desc); else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target2, key, r) : d(target2, key)) || r; return c > 3 && r && Object.defineProperty(target2, key, r), r; }; var MILLISECONDS_PER_SECOND = 1e3; var $changeAnimation = Symbol("changeAnimation"); var $paused = Symbol("paused"); var DEFAULT_PLAY_OPTIONS = { repetitions: Infinity, pingpong: false }; var AnimationMixin = (ModelViewerElement2) => { var _a12; class AnimationModelViewerElement extends ModelViewerElement2 { constructor(...args) { super(args); this.autoplay = false; this.animationName = void 0; this.animationCrossfadeDuration = 300; this[_a12] = true; this[$scene].subscribeMixerEvent("loop", (e) => { const count = e.action._loopCount; this.dispatchEvent(new CustomEvent("loop", { detail: { count } })); }); this[$scene].subscribeMixerEvent("finished", () => { this[$paused] = true; this.dispatchEvent(new CustomEvent("finished")); }); } /** * Returns an array */ get availableAnimations() { if (this.loaded) { return this[$scene].animationNames; } return []; } get duration() { return this[$scene].duration; } get paused() { return this[$paused]; } get currentTime() { return this[$scene].animationTime; } set currentTime(value) { this[$scene].animationTime = value; this[$needsRender](); } get timeScale() { return this[$scene].animationTimeScale; } set timeScale(value) { this[$scene].animationTimeScale = value; } pause() { if (this[$paused]) { return; } this[$paused] = true; this.dispatchEvent(new CustomEvent("pause")); } play(options) { if (this.availableAnimations.length > 0) { this[$paused] = false; this[$changeAnimation](options); this.dispatchEvent(new CustomEvent("play")); } } [(_a12 = $paused, $onModelLoad)]() { super[$onModelLoad](); this[$paused] = true; if (this.autoplay) { this.play(); } } [$tick](_time, delta) { super[$tick](_time, delta); if (this[$paused] || !this[$getModelIsVisible]() && !this[$renderer].isPresenting) { return; } this[$scene].updateAnimation(delta / MILLISECONDS_PER_SECOND); this[$needsRender](); } updated(changedProperties) { super.updated(changedProperties); if (changedProperties.has("autoplay") && this.autoplay) { this.play(); } if (changedProperties.has("animationName")) { this[$changeAnimation](); } } [$changeAnimation](options = DEFAULT_PLAY_OPTIONS) { var _b11; const repetitions = (_b11 = options.repetitions) !== null && _b11 !== void 0 ? _b11 : Infinity; const mode = options.pingpong ? LoopPingPong : repetitions === 1 ? LoopOnce : LoopRepeat; this[$scene].playAnimation(this.animationName, this.animationCrossfadeDuration / MILLISECONDS_PER_SECOND, mode, repetitions); if (this[$paused]) { this[$scene].updateAnimation(0); this[$needsRender](); } } } __decorate4([ property({ type: Boolean }) ], AnimationModelViewerElement.prototype, "autoplay", void 0); __decorate4([ property({ type: String, attribute: "animation-name" }) ], AnimationModelViewerElement.prototype, "animationName", void 0); __decorate4([ property({ type: Number, attribute: "animation-crossfade-duration" }) ], AnimationModelViewerElement.prototype, "animationCrossfadeDuration", void 0); return AnimationModelViewerElement; }; // node_modules/@google/model-viewer/lib/features/annotation.js var $hotspotMap = Symbol("hotspotMap"); var $mutationCallback = Symbol("mutationCallback"); var $observer = Symbol("observer"); var $addHotspot = Symbol("addHotspot"); var $removeHotspot = Symbol("removeHotspot"); var worldToModel = new Matrix4(); var worldToModelNormal = new Matrix3(); var AnnotationMixin = (ModelViewerElement2) => { var _a12, _b11, _c6; class AnnotationModelViewerElement extends ModelViewerElement2 { constructor() { super(...arguments); this[_a12] = /* @__PURE__ */ new Map(); this[_b11] = (mutations) => { mutations.forEach((mutation) => { if (!(mutation instanceof MutationRecord) || mutation.type === "childList") { mutation.addedNodes.forEach((node) => { this[$addHotspot](node); }); mutation.removedNodes.forEach((node) => { this[$removeHotspot](node); }); this[$needsRender](); } }); }; this[_c6] = new MutationObserver(this[$mutationCallback]); } connectedCallback() { super.connectedCallback(); for (let i = 0; i < this.children.length; ++i) { this[$addHotspot](this.children[i]); } const { ShadyDOM } = self; if (ShadyDOM == null) { this[$observer].observe(this, { childList: true }); } else { this[$observer] = ShadyDOM.observeChildren(this, this[$mutationCallback]); } } disconnectedCallback() { super.disconnectedCallback(); const { ShadyDOM } = self; if (ShadyDOM == null) { this[$observer].disconnect(); } else { ShadyDOM.unobserveChildren(this[$observer]); } } [(_a12 = $hotspotMap, _b11 = $mutationCallback, _c6 = $observer, $tick)](time, delta) { super[$tick](time, delta); const scene = this[$scene]; const { annotationRenderer } = scene; const camera2 = scene.getCamera(); if (scene.shouldRender()) { scene.updateHotspots(camera2.position); annotationRenderer.domElement.style.display = ""; annotationRenderer.render(scene, camera2); } } /** * Since the data-position and data-normal attributes are not observed, use * this method to move a hotspot. Keep in mind that all hotspots with the * same slot name use a single location and the first definition takes * precedence, until updated with this method. */ updateHotspot(config) { const hotspot = this[$hotspotMap].get(config.name); if (hotspot == null) { return; } hotspot.updatePosition(config.position); hotspot.updateNormal(config.normal); this[$needsRender](); } /** * This method returns in-scene data about a requested hotspot including * its position in screen (canvas) space and its current visibility. */ queryHotspot(name) { const hotspot = this[$hotspotMap].get(name); if (hotspot == null) { return null; } const position = toVector3D(hotspot.position); const normal = toVector3D(hotspot.normal); const facingCamera = hotspot.facingCamera; const scene = this[$scene]; const camera2 = scene.getCamera(); const vector = new Vector3(); vector.setFromMatrixPosition(hotspot.matrixWorld); vector.project(camera2); const widthHalf = scene.width / 2; const heightHalf = scene.height / 2; vector.x = vector.x * widthHalf + widthHalf; vector.y = -(vector.y * heightHalf) + heightHalf; const canvasPosition = toVector3D(new Vector3(vector.x, vector.y, vector.z)); if (!Number.isFinite(canvasPosition.x) || !Number.isFinite(canvasPosition.y)) { return null; } return { position, normal, canvasPosition, facingCamera }; } /** * This method returns the model position, normal and texture coordinate * of the point on the mesh corresponding to the input pixel coordinates * given relative to the model-viewer element. The position and normal * are returned as strings in the format suitable for putting in a * hotspot's data-position and data-normal attributes. If the mesh is * not hit, the result is null. */ positionAndNormalFromPoint(pixelX, pixelY) { const scene = this[$scene]; const ndcPosition = scene.getNDC(pixelX, pixelY); const hit = scene.positionAndNormalFromPoint(ndcPosition); if (hit == null) { return null; } worldToModel.copy(scene.target.matrixWorld).invert(); const position = toVector3D(hit.position.applyMatrix4(worldToModel)); worldToModelNormal.getNormalMatrix(worldToModel); const normal = toVector3D(hit.normal.applyNormalMatrix(worldToModelNormal)); let uv = null; if (hit.uv != null) { uv = toVector2D(hit.uv); } return { position, normal, uv }; } [$addHotspot](node) { if (!(node instanceof HTMLElement && node.slot.indexOf("hotspot") === 0)) { return; } let hotspot = this[$hotspotMap].get(node.slot); if (hotspot != null) { hotspot.increment(); } else { hotspot = new Hotspot({ name: node.slot, position: node.dataset.position, normal: node.dataset.normal }); this[$hotspotMap].set(node.slot, hotspot); this[$scene].addHotspot(hotspot); } this[$scene].queueRender(); } [$removeHotspot](node) { if (!(node instanceof HTMLElement)) { return; } const hotspot = this[$hotspotMap].get(node.slot); if (!hotspot) { return; } if (hotspot.decrement()) { this[$scene].removeHotspot(hotspot); this[$hotspotMap].delete(node.slot); } this[$scene].queueRender(); } } return AnnotationModelViewerElement; }; // node_modules/three/examples/jsm/libs/fflate.module.js var ch2 = {}; var durl = function(c) { return URL.createObjectURL(new Blob([c], { type: "text/javascript" })); }; var cwk = function(u) { return new Worker(u); }; try { URL.revokeObjectURL(durl("")); } catch (e) { durl = function(c) { return "data:application/javascript;charset=UTF-8," + encodeURI(c); }; cwk = function(u) { return new Worker(u, { type: "module" }); }; } var wk = function(c, id, msg, transfer, cb) { var w = cwk(ch2[id] || (ch2[id] = durl(c))); w.onerror = function(e) { return cb(e.error, null); }; w.onmessage = function(e) { return cb(null, e.data); }; w.postMessage(msg, transfer); return w; }; var u8 = Uint8Array; var u16 = Uint16Array; var u32 = Uint32Array; var fleb = new u8([ 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5, 0, /* unused */ 0, 0, /* impossible */ 0 ]); var fdeb = new u8([ 0, 0, 0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9, 10, 10, 11, 11, 12, 12, 13, 13, /* unused */ 0, 0 ]); var clim = new u8([16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15]); var freb = function(eb, start) { var b = new u16(31); for (var i = 0; i < 31; ++i) { b[i] = start += 1 << eb[i - 1]; } var r = new u32(b[30]); for (var i = 1; i < 30; ++i) { for (var j = b[i]; j < b[i + 1]; ++j) { r[j] = j - b[i] << 5 | i; } } return [b, r]; }; var _a9 = freb(fleb, 2); var fl = _a9[0]; var revfl = _a9[1]; fl[28] = 258, revfl[258] = 28; var _b8 = freb(fdeb, 0); var fd = _b8[0]; var revfd = _b8[1]; var rev = new u16(32768); for (i = 0; i < 32768; ++i) { x2 = (i & 43690) >>> 1 | (i & 21845) << 1; x2 = (x2 & 52428) >>> 2 | (x2 & 13107) << 2; x2 = (x2 & 61680) >>> 4 | (x2 & 3855) << 4; rev[i] = ((x2 & 65280) >>> 8 | (x2 & 255) << 8) >>> 1; } var x2; var i; var hMap = function(cd, mb, r) { var s = cd.length; var i = 0; var l = new u16(mb); for (; i < s; ++i) ++l[cd[i] - 1]; var le = new u16(mb); for (i = 0; i < mb; ++i) { le[i] = le[i - 1] + l[i - 1] << 1; } var co; if (r) { co = new u16(1 << mb); var rvb = 15 - mb; for (i = 0; i < s; ++i) { if (cd[i]) { var sv = i << 4 | cd[i]; var r_1 = mb - cd[i]; var v = le[cd[i] - 1]++ << r_1; for (var m = v | (1 << r_1) - 1; v <= m; ++v) { co[rev[v] >>> rvb] = sv; } } } } else { co = new u16(s); for (i = 0; i < s; ++i) { if (cd[i]) { co[i] = rev[le[cd[i] - 1]++] >>> 15 - cd[i]; } } } return co; }; var flt = new u8(288); for (i = 0; i < 144; ++i) flt[i] = 8; var i; for (i = 144; i < 256; ++i) flt[i] = 9; var i; for (i = 256; i < 280; ++i) flt[i] = 7; var i; for (i = 280; i < 288; ++i) flt[i] = 8; var i; var fdt = new u8(32); for (i = 0; i < 32; ++i) fdt[i] = 5; var i; var flm = hMap(flt, 9, 0); var flrm = hMap(flt, 9, 1); var fdm = hMap(fdt, 5, 0); var fdrm = hMap(fdt, 5, 1); var max = function(a) { var m = a[0]; for (var i = 1; i < a.length; ++i) { if (a[i] > m) m = a[i]; } return m; }; var bits = function(d, p2, m) { var o = p2 / 8 | 0; return (d[o] | d[o + 1] << 8) >> (p2 & 7) & m; }; var bits16 = function(d, p2) { var o = p2 / 8 | 0; return (d[o] | d[o + 1] << 8 | d[o + 2] << 16) >> (p2 & 7); }; var shft = function(p2) { return (p2 / 8 | 0) + (p2 & 7 && 1); }; var slc = function(v, s, e) { if (s == null || s < 0) s = 0; if (e == null || e > v.length) e = v.length; var n2 = new (v instanceof u16 ? u16 : v instanceof u32 ? u32 : u8)(e - s); n2.set(v.subarray(s, e)); return n2; }; var inflt = function(dat, buf, st) { var sl = dat.length; if (!sl || st && !st.l && sl < 5) return buf || new u8(0); var noBuf = !buf || st; var noSt = !st || st.i; if (!st) st = {}; if (!buf) buf = new u8(sl * 3); var cbuf = function(l2) { var bl = buf.length; if (l2 > bl) { var nbuf = new u8(Math.max(bl * 2, l2)); nbuf.set(buf); buf = nbuf; } }; var final = st.f || 0, pos = st.p || 0, bt = st.b || 0, lm = st.l, dm = st.d, lbt = st.m, dbt = st.n; var tbts = sl * 8; do { if (!lm) { st.f = final = bits(dat, pos, 1); var type = bits(dat, pos + 1, 3); pos += 3; if (!type) { var s = shft(pos) + 4, l = dat[s - 4] | dat[s - 3] << 8, t2 = s + l; if (t2 > sl) { if (noSt) throw "unexpected EOF"; break; } if (noBuf) cbuf(bt + l); buf.set(dat.subarray(s, t2), bt); st.b = bt += l, st.p = pos = t2 * 8; continue; } else if (type == 1) lm = flrm, dm = fdrm, lbt = 9, dbt = 5; else if (type == 2) { var hLit = bits(dat, pos, 31) + 257, hcLen = bits(dat, pos + 10, 15) + 4; var tl = hLit + bits(dat, pos + 5, 31) + 1; pos += 14; var ldt = new u8(tl); var clt = new u8(19); for (var i = 0; i < hcLen; ++i) { clt[clim[i]] = bits(dat, pos + i * 3, 7); } pos += hcLen * 3; var clb = max(clt), clbmsk = (1 << clb) - 1; var clm = hMap(clt, clb, 1); for (var i = 0; i < tl; ) { var r = clm[bits(dat, pos, clbmsk)]; pos += r & 15; var s = r >>> 4; if (s < 16) { ldt[i++] = s; } else { var c = 0, n2 = 0; if (s == 16) n2 = 3 + bits(dat, pos, 3), pos += 2, c = ldt[i - 1]; else if (s == 17) n2 = 3 + bits(dat, pos, 7), pos += 3; else if (s == 18) n2 = 11 + bits(dat, pos, 127), pos += 7; while (n2--) ldt[i++] = c; } } var lt = ldt.subarray(0, hLit), dt2 = ldt.subarray(hLit); lbt = max(lt); dbt = max(dt2); lm = hMap(lt, lbt, 1); dm = hMap(dt2, dbt, 1); } else throw "invalid block type"; if (pos > tbts) { if (noSt) throw "unexpected EOF"; break; } } if (noBuf) cbuf(bt + 131072); var lms = (1 << lbt) - 1, dms = (1 << dbt) - 1; var lpos = pos; for (; ; lpos = pos) { var c = lm[bits16(dat, pos) & lms], sym = c >>> 4; pos += c & 15; if (pos > tbts) { if (noSt) throw "unexpected EOF"; break; } if (!c) throw "invalid length/literal"; if (sym < 256) buf[bt++] = sym; else if (sym == 256) { lpos = pos, lm = null; break; } else { var add = sym - 254; if (sym > 264) { var i = sym - 257, b = fleb[i]; add = bits(dat, pos, (1 << b) - 1) + fl[i]; pos += b; } var d = dm[bits16(dat, pos) & dms], dsym = d >>> 4; if (!d) throw "invalid distance"; pos += d & 15; var dt2 = fd[dsym]; if (dsym > 3) { var b = fdeb[dsym]; dt2 += bits16(dat, pos) & (1 << b) - 1, pos += b; } if (pos > tbts) { if (noSt) throw "unexpected EOF"; break; } if (noBuf) cbuf(bt + 131072); var end = bt + add; for (; bt < end; bt += 4) { buf[bt] = buf[bt - dt2]; buf[bt + 1] = buf[bt + 1 - dt2]; buf[bt + 2] = buf[bt + 2 - dt2]; buf[bt + 3] = buf[bt + 3 - dt2]; } bt = end; } } st.l = lm, st.p = lpos, st.b = bt; if (lm) final = 1, st.m = lbt, st.d = dm, st.n = dbt; } while (!final); return bt == buf.length ? buf : slc(buf, 0, bt); }; var wbits = function(d, p2, v) { v <<= p2 & 7; var o = p2 / 8 | 0; d[o] |= v; d[o + 1] |= v >>> 8; }; var wbits16 = function(d, p2, v) { v <<= p2 & 7; var o = p2 / 8 | 0; d[o] |= v; d[o + 1] |= v >>> 8; d[o + 2] |= v >>> 16; }; var hTree = function(d, mb) { var t2 = []; for (var i = 0; i < d.length; ++i) { if (d[i]) t2.push({ s: i, f: d[i] }); } var s = t2.length; var t22 = t2.slice(); if (!s) return [et, 0]; if (s == 1) { var v = new u8(t2[0].s + 1); v[t2[0].s] = 1; return [v, 1]; } t2.sort(function(a, b) { return a.f - b.f; }); t2.push({ s: -1, f: 25001 }); var l = t2[0], r = t2[1], i0 = 0, i1 = 1, i2 = 2; t2[0] = { s: -1, f: l.f + r.f, l, r }; while (i1 != s - 1) { l = t2[t2[i0].f < t2[i2].f ? i0++ : i2++]; r = t2[i0 != i1 && t2[i0].f < t2[i2].f ? i0++ : i2++]; t2[i1++] = { s: -1, f: l.f + r.f, l, r }; } var maxSym = t22[0].s; for (var i = 1; i < s; ++i) { if (t22[i].s > maxSym) maxSym = t22[i].s; } var tr = new u16(maxSym + 1); var mbt = ln(t2[i1 - 1], tr, 0); if (mbt > mb) { var i = 0, dt2 = 0; var lft = mbt - mb, cst = 1 << lft; t22.sort(function(a, b) { return tr[b.s] - tr[a.s] || a.f - b.f; }); for (; i < s; ++i) { var i2_1 = t22[i].s; if (tr[i2_1] > mb) { dt2 += cst - (1 << mbt - tr[i2_1]); tr[i2_1] = mb; } else break; } dt2 >>>= lft; while (dt2 > 0) { var i2_2 = t22[i].s; if (tr[i2_2] < mb) dt2 -= 1 << mb - tr[i2_2]++ - 1; else ++i; } for (; i >= 0 && dt2; --i) { var i2_3 = t22[i].s; if (tr[i2_3] == mb) { --tr[i2_3]; ++dt2; } } mbt = mb; } return [new u8(tr), mbt]; }; var ln = function(n2, l, d) { return n2.s == -1 ? Math.max(ln(n2.l, l, d + 1), ln(n2.r, l, d + 1)) : l[n2.s] = d; }; var lc = function(c) { var s = c.length; while (s && !c[--s]) ; var cl = new u16(++s); var cli = 0, cln = c[0], cls = 1; var w = function(v) { cl[cli++] = v; }; for (var i = 1; i <= s; ++i) { if (c[i] == cln && i != s) ++cls; else { if (!cln && cls > 2) { for (; cls > 138; cls -= 138) w(32754); if (cls > 2) { w(cls > 10 ? cls - 11 << 5 | 28690 : cls - 3 << 5 | 12305); cls = 0; } } else if (cls > 3) { w(cln), --cls; for (; cls > 6; cls -= 6) w(8304); if (cls > 2) w(cls - 3 << 5 | 8208), cls = 0; } while (cls--) w(cln); cls = 1; cln = c[i]; } } return [cl.subarray(0, cli), s]; }; var clen = function(cf, cl) { var l = 0; for (var i = 0; i < cl.length; ++i) l += cf[i] * cl[i]; return l; }; var wfblk = function(out, pos, dat) { var s = dat.length; var o = shft(pos + 2); out[o] = s & 255; out[o + 1] = s >>> 8; out[o + 2] = out[o] ^ 255; out[o + 3] = out[o + 1] ^ 255; for (var i = 0; i < s; ++i) out[o + i + 4] = dat[i]; return (o + 4 + s) * 8; }; var wblk = function(dat, out, final, syms, lf, df, eb, li, bs, bl, p2) { wbits(out, p2++, final); ++lf[256]; var _a12 = hTree(lf, 15), dlt = _a12[0], mlb = _a12[1]; var _b11 = hTree(df, 15), ddt = _b11[0], mdb = _b11[1]; var _c6 = lc(dlt), lclt = _c6[0], nlc = _c6[1]; var _d5 = lc(ddt), lcdt = _d5[0], ndc2 = _d5[1]; var lcfreq = new u16(19); for (var i = 0; i < lclt.length; ++i) lcfreq[lclt[i] & 31]++; for (var i = 0; i < lcdt.length; ++i) lcfreq[lcdt[i] & 31]++; var _e4 = hTree(lcfreq, 7), lct = _e4[0], mlcb = _e4[1]; var nlcc = 19; for (; nlcc > 4 && !lct[clim[nlcc - 1]]; --nlcc) ; var flen = bl + 5 << 3; var ftlen = clen(lf, flt) + clen(df, fdt) + eb; var dtlen = clen(lf, dlt) + clen(df, ddt) + eb + 14 + 3 * nlcc + clen(lcfreq, lct) + (2 * lcfreq[16] + 3 * lcfreq[17] + 7 * lcfreq[18]); if (flen <= ftlen && flen <= dtlen) return wfblk(out, p2, dat.subarray(bs, bs + bl)); var lm, ll, dm, dl; wbits(out, p2, 1 + (dtlen < ftlen)), p2 += 2; if (dtlen < ftlen) { lm = hMap(dlt, mlb, 0), ll = dlt, dm = hMap(ddt, mdb, 0), dl = ddt; var llm = hMap(lct, mlcb, 0); wbits(out, p2, nlc - 257); wbits(out, p2 + 5, ndc2 - 1); wbits(out, p2 + 10, nlcc - 4); p2 += 14; for (var i = 0; i < nlcc; ++i) wbits(out, p2 + 3 * i, lct[clim[i]]); p2 += 3 * nlcc; var lcts = [lclt, lcdt]; for (var it = 0; it < 2; ++it) { var clct = lcts[it]; for (var i = 0; i < clct.length; ++i) { var len = clct[i] & 31; wbits(out, p2, llm[len]), p2 += lct[len]; if (len > 15) wbits(out, p2, clct[i] >>> 5 & 127), p2 += clct[i] >>> 12; } } } else { lm = flm, ll = flt, dm = fdm, dl = fdt; } for (var i = 0; i < li; ++i) { if (syms[i] > 255) { var len = syms[i] >>> 18 & 31; wbits16(out, p2, lm[len + 257]), p2 += ll[len + 257]; if (len > 7) wbits(out, p2, syms[i] >>> 23 & 31), p2 += fleb[len]; var dst = syms[i] & 31; wbits16(out, p2, dm[dst]), p2 += dl[dst]; if (dst > 3) wbits16(out, p2, syms[i] >>> 5 & 8191), p2 += fdeb[dst]; } else { wbits16(out, p2, lm[syms[i]]), p2 += ll[syms[i]]; } } wbits16(out, p2, lm[256]); return p2 + ll[256]; }; var deo = new u32([65540, 131080, 131088, 131104, 262176, 1048704, 1048832, 2114560, 2117632]); var et = new u8(0); var dflt = function(dat, lvl, plvl, pre, post, lst) { var s = dat.length; var o = new u8(pre + s + 5 * (1 + Math.ceil(s / 7e3)) + post); var w = o.subarray(pre, o.length - post); var pos = 0; if (!lvl || s < 8) { for (var i = 0; i <= s; i += 65535) { var e = i + 65535; if (e < s) { pos = wfblk(w, pos, dat.subarray(i, e)); } else { w[i] = lst; pos = wfblk(w, pos, dat.subarray(i, s)); } } } else { var opt = deo[lvl - 1]; var n2 = opt >>> 13, c = opt & 8191; var msk_1 = (1 << plvl) - 1; var prev = new u16(32768), head = new u16(msk_1 + 1); var bs1_1 = Math.ceil(plvl / 3), bs2_1 = 2 * bs1_1; var hsh = function(i2) { return (dat[i2] ^ dat[i2 + 1] << bs1_1 ^ dat[i2 + 2] << bs2_1) & msk_1; }; var syms = new u32(25e3); var lf = new u16(288), df = new u16(32); var lc_1 = 0, eb = 0, i = 0, li = 0, wi = 0, bs = 0; for (; i < s; ++i) { var hv = hsh(i); var imod = i & 32767, pimod = head[hv]; prev[imod] = pimod; head[hv] = imod; if (wi <= i) { var rem = s - i; if ((lc_1 > 7e3 || li > 24576) && rem > 423) { pos = wblk(dat, w, 0, syms, lf, df, eb, li, bs, i - bs, pos); li = lc_1 = eb = 0, bs = i; for (var j = 0; j < 286; ++j) lf[j] = 0; for (var j = 0; j < 30; ++j) df[j] = 0; } var l = 2, d = 0, ch_1 = c, dif = imod - pimod & 32767; if (rem > 2 && hv == hsh(i - dif)) { var maxn = Math.min(n2, rem) - 1; var maxd = Math.min(32767, i); var ml = Math.min(258, rem); while (dif <= maxd && --ch_1 && imod != pimod) { if (dat[i + l] == dat[i + l - dif]) { var nl = 0; for (; nl < ml && dat[i + nl] == dat[i + nl - dif]; ++nl) ; if (nl > l) { l = nl, d = dif; if (nl > maxn) break; var mmd = Math.min(dif, nl - 2); var md = 0; for (var j = 0; j < mmd; ++j) { var ti = i - dif + j + 32768 & 32767; var pti = prev[ti]; var cd = ti - pti + 32768 & 32767; if (cd > md) md = cd, pimod = ti; } } } imod = pimod, pimod = prev[imod]; dif += imod - pimod + 32768 & 32767; } } if (d) { syms[li++] = 268435456 | revfl[l] << 18 | revfd[d]; var lin = revfl[l] & 31, din = revfd[d] & 31; eb += fleb[lin] + fdeb[din]; ++lf[257 + lin]; ++df[din]; wi = i + l; ++lc_1; } else { syms[li++] = dat[i]; ++lf[dat[i]]; } } } pos = wblk(dat, w, lst, syms, lf, df, eb, li, bs, i - bs, pos); if (!lst && pos & 7) pos = wfblk(w, pos + 1, et); } return slc(o, 0, pre + shft(pos) + post); }; var crct = function() { var t2 = new u32(256); for (var i = 0; i < 256; ++i) { var c = i, k = 9; while (--k) c = (c & 1 && 3988292384) ^ c >>> 1; t2[i] = c; } return t2; }(); var crc = function() { var c = -1; return { p: function(d) { var cr = c; for (var i = 0; i < d.length; ++i) cr = crct[cr & 255 ^ d[i]] ^ cr >>> 8; c = cr; }, d: function() { return ~c; } }; }; var adler = function() { var a = 1, b = 0; return { p: function(d) { var n2 = a, m = b; var l = d.length; for (var i = 0; i != l; ) { var e = Math.min(i + 2655, l); for (; i < e; ++i) m += n2 += d[i]; n2 = (n2 & 65535) + 15 * (n2 >> 16), m = (m & 65535) + 15 * (m >> 16); } a = n2, b = m; }, d: function() { a %= 65521, b %= 65521; return (a & 255) << 24 | a >>> 8 << 16 | (b & 255) << 8 | b >>> 8; } }; }; var dopt = function(dat, opt, pre, post, st) { return dflt(dat, opt.level == null ? 6 : opt.level, opt.mem == null ? Math.ceil(Math.max(8, Math.min(13, Math.log(dat.length))) * 1.5) : 12 + opt.mem, pre, post, !st); }; var mrg = function(a, b) { var o = {}; for (var k in a) o[k] = a[k]; for (var k in b) o[k] = b[k]; return o; }; var wcln = function(fn, fnStr, td2) { var dt2 = fn(); var st = fn.toString(); var ks = st.slice(st.indexOf("[") + 1, st.lastIndexOf("]")).replace(/ /g, "").split(","); for (var i = 0; i < dt2.length; ++i) { var v = dt2[i], k = ks[i]; if (typeof v == "function") { fnStr += ";" + k + "="; var st_1 = v.toString(); if (v.prototype) { if (st_1.indexOf("[native code]") != -1) { var spInd = st_1.indexOf(" ", 8) + 1; fnStr += st_1.slice(spInd, st_1.indexOf("(", spInd)); } else { fnStr += st_1; for (var t2 in v.prototype) fnStr += ";" + k + ".prototype." + t2 + "=" + v.prototype[t2].toString(); } } else fnStr += st_1; } else td2[k] = v; } return [fnStr, td2]; }; var ch = []; var cbfs = function(v) { var tl = []; for (var k in v) { if (v[k] instanceof u8 || v[k] instanceof u16 || v[k] instanceof u32) tl.push((v[k] = new v[k].constructor(v[k])).buffer); } return tl; }; var wrkr = function(fns, init, id, cb) { var _a12; if (!ch[id]) { var fnStr = "", td_1 = {}, m = fns.length - 1; for (var i = 0; i < m; ++i) _a12 = wcln(fns[i], fnStr, td_1), fnStr = _a12[0], td_1 = _a12[1]; ch[id] = wcln(fns[m], fnStr, td_1); } var td2 = mrg({}, ch[id][1]); return wk(ch[id][0] + ";onmessage=function(e){for(var k in e.data)self[k]=e.data[k];onmessage=" + init.toString() + "}", id, td2, cbfs(td2), cb); }; var bInflt = function() { return [u8, u16, u32, fleb, fdeb, clim, fl, fd, flrm, fdrm, rev, hMap, max, bits, bits16, shft, slc, inflt, inflateSync, pbf, gu8]; }; var bDflt = function() { return [u8, u16, u32, fleb, fdeb, clim, revfl, revfd, flm, flt, fdm, fdt, rev, deo, et, hMap, wbits, wbits16, hTree, ln, lc, clen, wfblk, wblk, shft, slc, dflt, dopt, deflateSync, pbf]; }; var gze = function() { return [gzh, gzhl, wbytes, crc, crct]; }; var guze = function() { return [gzs, gzl]; }; var zle = function() { return [zlh, wbytes, adler]; }; var zule = function() { return [zlv]; }; var pbf = function(msg) { return postMessage(msg, [msg.buffer]); }; var gu8 = function(o) { return o && o.size && new u8(o.size); }; var astrm = function(strm) { strm.ondata = function(dat, final) { return postMessage([dat, final], [dat.buffer]); }; return function(ev) { return strm.push(ev.data[0], ev.data[1]); }; }; var astrmify = function(fns, strm, opts, init, id) { var t2; var w = wrkr(fns, init, id, function(err, dat) { if (err) w.terminate(), strm.ondata.call(strm, err); else { if (dat[1]) w.terminate(); strm.ondata.call(strm, err, dat[0], dat[1]); } }); w.postMessage(opts); strm.push = function(d, f) { if (t2) throw "stream finished"; if (!strm.ondata) throw "no stream handler"; w.postMessage([d, t2 = f], [d.buffer]); }; strm.terminate = function() { w.terminate(); }; }; var b2 = function(d, b) { return d[b] | d[b + 1] << 8; }; var b4 = function(d, b) { return (d[b] | d[b + 1] << 8 | d[b + 2] << 16 | d[b + 3] << 24) >>> 0; }; var b8 = function(d, b) { return b4(d, b) + b4(d, b + 4) * 4294967296; }; var wbytes = function(d, b, v) { for (; v; ++b) d[b] = v, v >>>= 8; }; var gzh = function(c, o) { var fn = o.filename; c[0] = 31, c[1] = 139, c[2] = 8, c[8] = o.level < 2 ? 4 : o.level == 9 ? 2 : 0, c[9] = 3; if (o.mtime != 0) wbytes(c, 4, Math.floor(new Date(o.mtime || Date.now()) / 1e3)); if (fn) { c[3] = 8; for (var i = 0; i <= fn.length; ++i) c[i + 10] = fn.charCodeAt(i); } }; var gzs = function(d) { if (d[0] != 31 || d[1] != 139 || d[2] != 8) throw "invalid gzip data"; var flg = d[3]; var st = 10; if (flg & 4) st += d[10] | (d[11] << 8) + 2; for (var zs = (flg >> 3 & 1) + (flg >> 4 & 1); zs > 0; zs -= !d[st++]) ; return st + (flg & 2); }; var gzl = function(d) { var l = d.length; return (d[l - 4] | d[l - 3] << 8 | d[l - 2] << 16 | d[l - 1] << 24) >>> 0; }; var gzhl = function(o) { return 10 + (o.filename && o.filename.length + 1 || 0); }; var zlh = function(c, o) { var lv = o.level, fl2 = lv == 0 ? 0 : lv < 6 ? 1 : lv == 9 ? 3 : 2; c[0] = 120, c[1] = fl2 << 6 | (fl2 ? 32 - 2 * fl2 : 1); }; var zlv = function(d) { if ((d[0] & 15) != 8 || d[0] >>> 4 > 7 || (d[0] << 8 | d[1]) % 31) throw "invalid zlib data"; if (d[1] & 32) throw "invalid zlib data: preset dictionaries not supported"; }; function AsyncCmpStrm(opts, cb) { if (!cb && typeof opts == "function") cb = opts, opts = {}; this.ondata = cb; return opts; } var Deflate = function() { function Deflate2(opts, cb) { if (!cb && typeof opts == "function") cb = opts, opts = {}; this.ondata = cb; this.o = opts || {}; } Deflate2.prototype.p = function(c, f) { this.ondata(dopt(c, this.o, 0, 0, !f), f); }; Deflate2.prototype.push = function(chunk, final) { if (this.d) throw "stream finished"; if (!this.ondata) throw "no stream handler"; this.d = final; this.p(chunk, final || false); }; return Deflate2; }(); var AsyncDeflate = function() { function AsyncDeflate2(opts, cb) { astrmify([ bDflt, function() { return [astrm, Deflate]; } ], this, AsyncCmpStrm.call(this, opts, cb), function(ev) { var strm = new Deflate(ev.data); onmessage = astrm(strm); }, 6); } return AsyncDeflate2; }(); function deflateSync(data, opts) { return dopt(data, opts || {}, 0, 0); } var Inflate = function() { function Inflate2(cb) { this.s = {}; this.p = new u8(0); this.ondata = cb; } Inflate2.prototype.e = function(c) { if (this.d) throw "stream finished"; if (!this.ondata) throw "no stream handler"; var l = this.p.length; var n2 = new u8(l + c.length); n2.set(this.p), n2.set(c, l), this.p = n2; }; Inflate2.prototype.c = function(final) { this.d = this.s.i = final || false; var bts = this.s.b; var dt2 = inflt(this.p, this.o, this.s); this.ondata(slc(dt2, bts, this.s.b), this.d); this.o = slc(dt2, this.s.b - 32768), this.s.b = this.o.length; this.p = slc(this.p, this.s.p / 8 | 0), this.s.p &= 7; }; Inflate2.prototype.push = function(chunk, final) { this.e(chunk), this.c(final); }; return Inflate2; }(); var AsyncInflate = function() { function AsyncInflate2(cb) { this.ondata = cb; astrmify([ bInflt, function() { return [astrm, Inflate]; } ], this, 0, function() { var strm = new Inflate(); onmessage = astrm(strm); }, 7); } return AsyncInflate2; }(); function inflateSync(data, out) { return inflt(data, out); } var Gzip = function() { function Gzip2(opts, cb) { this.c = crc(); this.l = 0; this.v = 1; Deflate.call(this, opts, cb); } Gzip2.prototype.push = function(chunk, final) { Deflate.prototype.push.call(this, chunk, final); }; Gzip2.prototype.p = function(c, f) { this.c.p(c); this.l += c.length; var raw = dopt(c, this.o, this.v && gzhl(this.o), f && 8, !f); if (this.v) gzh(raw, this.o), this.v = 0; if (f) wbytes(raw, raw.length - 8, this.c.d()), wbytes(raw, raw.length - 4, this.l); this.ondata(raw, f); }; return Gzip2; }(); var AsyncGzip = function() { function AsyncGzip2(opts, cb) { astrmify([ bDflt, gze, function() { return [astrm, Deflate, Gzip]; } ], this, AsyncCmpStrm.call(this, opts, cb), function(ev) { var strm = new Gzip(ev.data); onmessage = astrm(strm); }, 8); } return AsyncGzip2; }(); var Gunzip = function() { function Gunzip2(cb) { this.v = 1; Inflate.call(this, cb); } Gunzip2.prototype.push = function(chunk, final) { Inflate.prototype.e.call(this, chunk); if (this.v) { var s = this.p.length > 3 ? gzs(this.p) : 4; if (s >= this.p.length && !final) return; this.p = this.p.subarray(s), this.v = 0; } if (final) { if (this.p.length < 8) throw "invalid gzip stream"; this.p = this.p.subarray(0, -8); } Inflate.prototype.c.call(this, final); }; return Gunzip2; }(); var AsyncGunzip = function() { function AsyncGunzip2(cb) { this.ondata = cb; astrmify([ bInflt, guze, function() { return [astrm, Inflate, Gunzip]; } ], this, 0, function() { var strm = new Gunzip(); onmessage = astrm(strm); }, 9); } return AsyncGunzip2; }(); var Zlib = function() { function Zlib2(opts, cb) { this.c = adler(); this.v = 1; Deflate.call(this, opts, cb); } Zlib2.prototype.push = function(chunk, final) { Deflate.prototype.push.call(this, chunk, final); }; Zlib2.prototype.p = function(c, f) { this.c.p(c); var raw = dopt(c, this.o, this.v && 2, f && 4, !f); if (this.v) zlh(raw, this.o), this.v = 0; if (f) wbytes(raw, raw.length - 4, this.c.d()); this.ondata(raw, f); }; return Zlib2; }(); var AsyncZlib = function() { function AsyncZlib2(opts, cb) { astrmify([ bDflt, zle, function() { return [astrm, Deflate, Zlib]; } ], this, AsyncCmpStrm.call(this, opts, cb), function(ev) { var strm = new Zlib(ev.data); onmessage = astrm(strm); }, 10); } return AsyncZlib2; }(); var Unzlib = function() { function Unzlib2(cb) { this.v = 1; Inflate.call(this, cb); } Unzlib2.prototype.push = function(chunk, final) { Inflate.prototype.e.call(this, chunk); if (this.v) { if (this.p.length < 2 && !final) return; this.p = this.p.subarray(2), this.v = 0; } if (final) { if (this.p.length < 4) throw "invalid zlib stream"; this.p = this.p.subarray(0, -4); } Inflate.prototype.c.call(this, final); }; return Unzlib2; }(); var AsyncUnzlib = function() { function AsyncUnzlib2(cb) { this.ondata = cb; astrmify([ bInflt, zule, function() { return [astrm, Inflate, Unzlib]; } ], this, 0, function() { var strm = new Unzlib(); onmessage = astrm(strm); }, 11); } return AsyncUnzlib2; }(); var Decompress = function() { function Decompress2(cb) { this.G = Gunzip; this.I = Inflate; this.Z = Unzlib; this.ondata = cb; } Decompress2.prototype.push = function(chunk, final) { if (!this.ondata) throw "no stream handler"; if (!this.s) { if (this.p && this.p.length) { var n2 = new u8(this.p.length + chunk.length); n2.set(this.p), n2.set(chunk, this.p.length); } else this.p = chunk; if (this.p.length > 2) { var _this_1 = this; var cb = function() { _this_1.ondata.apply(_this_1, arguments); }; this.s = this.p[0] == 31 && this.p[1] == 139 && this.p[2] == 8 ? new this.G(cb) : (this.p[0] & 15) != 8 || this.p[0] >> 4 > 7 || (this.p[0] << 8 | this.p[1]) % 31 ? new this.I(cb) : new this.Z(cb); this.s.push(this.p, final); this.p = null; } } else this.s.push(chunk, final); }; return Decompress2; }(); var AsyncDecompress = function() { function AsyncDecompress2(cb) { this.G = AsyncGunzip; this.I = AsyncInflate; this.Z = AsyncUnzlib; this.ondata = cb; } AsyncDecompress2.prototype.push = function(chunk, final) { Decompress.prototype.push.call(this, chunk, final); }; return AsyncDecompress2; }(); var fltn = function(d, p2, t2, o) { for (var k in d) { var val = d[k], n2 = p2 + k; if (val instanceof u8) t2[n2] = [val, o]; else if (Array.isArray(val)) t2[n2] = [val[0], mrg(o, val[1])]; else fltn(val, n2 + "/", t2, o); } }; var te = typeof TextEncoder != "undefined" && new TextEncoder(); var td = typeof TextDecoder != "undefined" && new TextDecoder(); var tds = 0; try { td.decode(et, { stream: true }); tds = 1; } catch (e) { } var dutf8 = function(d) { for (var r = "", i = 0; ; ) { var c = d[i++]; var eb = (c > 127) + (c > 223) + (c > 239); if (i + eb > d.length) return [r, slc(d, i - 1)]; if (!eb) r += String.fromCharCode(c); else if (eb == 3) { c = ((c & 15) << 18 | (d[i++] & 63) << 12 | (d[i++] & 63) << 6 | d[i++] & 63) - 65536, r += String.fromCharCode(55296 | c >> 10, 56320 | c & 1023); } else if (eb & 1) r += String.fromCharCode((c & 31) << 6 | d[i++] & 63); else r += String.fromCharCode((c & 15) << 12 | (d[i++] & 63) << 6 | d[i++] & 63); } }; var DecodeUTF8 = function() { function DecodeUTF82(cb) { this.ondata = cb; if (tds) this.t = new TextDecoder(); else this.p = et; } DecodeUTF82.prototype.push = function(chunk, final) { if (!this.ondata) throw "no callback"; final = !!final; if (this.t) { this.ondata(this.t.decode(chunk, { stream: true }), final); if (final) { if (this.t.decode().length) throw "invalid utf-8 data"; this.t = null; } return; } if (!this.p) throw "stream finished"; var dat = new u8(this.p.length + chunk.length); dat.set(this.p); dat.set(chunk, this.p.length); var _a12 = dutf8(dat), ch3 = _a12[0], np = _a12[1]; if (final) { if (np.length) throw "invalid utf-8 data"; this.p = null; } else this.p = np; this.ondata(ch3, final); }; return DecodeUTF82; }(); var EncodeUTF8 = function() { function EncodeUTF82(cb) { this.ondata = cb; } EncodeUTF82.prototype.push = function(chunk, final) { if (!this.ondata) throw "no callback"; if (this.d) throw "stream finished"; this.ondata(strToU8(chunk), this.d = final || false); }; return EncodeUTF82; }(); function strToU8(str, latin1) { if (latin1) { var ar_1 = new u8(str.length); for (var i = 0; i < str.length; ++i) ar_1[i] = str.charCodeAt(i); return ar_1; } if (te) return te.encode(str); var l = str.length; var ar = new u8(str.length + (str.length >> 1)); var ai = 0; var w = function(v) { ar[ai++] = v; }; for (var i = 0; i < l; ++i) { if (ai + 5 > ar.length) { var n2 = new u8(ai + 8 + (l - i << 1)); n2.set(ar); ar = n2; } var c = str.charCodeAt(i); if (c < 128 || latin1) w(c); else if (c < 2048) w(192 | c >> 6), w(128 | c & 63); else if (c > 55295 && c < 57344) c = 65536 + (c & 1023 << 10) | str.charCodeAt(++i) & 1023, w(240 | c >> 18), w(128 | c >> 12 & 63), w(128 | c >> 6 & 63), w(128 | c & 63); else w(224 | c >> 12), w(128 | c >> 6 & 63), w(128 | c & 63); } return slc(ar, 0, ai); } function strFromU8(dat, latin1) { if (latin1) { var r = ""; for (var i = 0; i < dat.length; i += 16384) r += String.fromCharCode.apply(null, dat.subarray(i, i + 16384)); return r; } else if (td) return td.decode(dat); else { var _a12 = dutf8(dat), out = _a12[0], ext = _a12[1]; if (ext.length) throw "invalid utf-8 data"; return out; } } var dbf = function(l) { return l == 1 ? 3 : l < 6 ? 2 : l == 9 ? 1 : 0; }; var z64e = function(d, b) { for (; b2(d, b) != 1; b += 4 + b2(d, b + 2)) ; return [b8(d, b + 12), b8(d, b + 4), b8(d, b + 20)]; }; var exfl = function(ex) { var le = 0; if (ex) { for (var k in ex) { var l = ex[k].length; if (l > 65535) throw "extra field too long"; le += l + 4; } } return le; }; var wzh = function(d, b, f, fn, u, c, ce, co) { var fl2 = fn.length, ex = f.extra, col = co && co.length; var exl = exfl(ex); wbytes(d, b, ce != null ? 33639248 : 67324752), b += 4; if (ce != null) d[b++] = 20, d[b++] = f.os; d[b] = 20, b += 2; d[b++] = f.flag << 1 | (c == null && 8), d[b++] = u && 8; d[b++] = f.compression & 255, d[b++] = f.compression >> 8; var dt2 = new Date(f.mtime == null ? Date.now() : f.mtime), y = dt2.getFullYear() - 1980; if (y < 0 || y > 119) throw "date not in range 1980-2099"; wbytes(d, b, y << 25 | dt2.getMonth() + 1 << 21 | dt2.getDate() << 16 | dt2.getHours() << 11 | dt2.getMinutes() << 5 | dt2.getSeconds() >>> 1), b += 4; if (c != null) { wbytes(d, b, f.crc); wbytes(d, b + 4, c); wbytes(d, b + 8, f.size); } wbytes(d, b + 12, fl2); wbytes(d, b + 14, exl), b += 16; if (ce != null) { wbytes(d, b, col); wbytes(d, b + 6, f.attrs); wbytes(d, b + 10, ce), b += 14; } d.set(fn, b); b += fl2; if (exl) { for (var k in ex) { var exf = ex[k], l = exf.length; wbytes(d, b, +k); wbytes(d, b + 2, l); d.set(exf, b + 4), b += 4 + l; } } if (col) d.set(co, b), b += col; return b; }; var wzf = function(o, b, c, d, e) { wbytes(o, b, 101010256); wbytes(o, b + 8, c); wbytes(o, b + 10, c); wbytes(o, b + 12, d); wbytes(o, b + 16, e); }; var ZipPassThrough = function() { function ZipPassThrough2(filename) { this.filename = filename; this.c = crc(); this.size = 0; this.compression = 0; } ZipPassThrough2.prototype.process = function(chunk, final) { this.ondata(null, chunk, final); }; ZipPassThrough2.prototype.push = function(chunk, final) { if (!this.ondata) throw "no callback - add to ZIP archive before pushing"; this.c.p(chunk); this.size += chunk.length; if (final) this.crc = this.c.d(); this.process(chunk, final || false); }; return ZipPassThrough2; }(); var ZipDeflate = function() { function ZipDeflate2(filename, opts) { var _this_1 = this; if (!opts) opts = {}; ZipPassThrough.call(this, filename); this.d = new Deflate(opts, function(dat, final) { _this_1.ondata(null, dat, final); }); this.compression = 8; this.flag = dbf(opts.level); } ZipDeflate2.prototype.process = function(chunk, final) { try { this.d.push(chunk, final); } catch (e) { this.ondata(e, null, final); } }; ZipDeflate2.prototype.push = function(chunk, final) { ZipPassThrough.prototype.push.call(this, chunk, final); }; return ZipDeflate2; }(); var AsyncZipDeflate = function() { function AsyncZipDeflate2(filename, opts) { var _this_1 = this; if (!opts) opts = {}; ZipPassThrough.call(this, filename); this.d = new AsyncDeflate(opts, function(err, dat, final) { _this_1.ondata(err, dat, final); }); this.compression = 8; this.flag = dbf(opts.level); this.terminate = this.d.terminate; } AsyncZipDeflate2.prototype.process = function(chunk, final) { this.d.push(chunk, final); }; AsyncZipDeflate2.prototype.push = function(chunk, final) { ZipPassThrough.prototype.push.call(this, chunk, final); }; return AsyncZipDeflate2; }(); var Zip = function() { function Zip2(cb) { this.ondata = cb; this.u = []; this.d = 1; } Zip2.prototype.add = function(file) { var _this_1 = this; if (this.d & 2) throw "stream finished"; var f = strToU8(file.filename), fl2 = f.length; var com = file.comment, o = com && strToU8(com); var u = fl2 != file.filename.length || o && com.length != o.length; var hl = fl2 + exfl(file.extra) + 30; if (fl2 > 65535) throw "filename too long"; var header = new u8(hl); wzh(header, 0, file, f, u); var chks = [header]; var pAll = function() { for (var _i = 0, chks_1 = chks; _i < chks_1.length; _i++) { var chk = chks_1[_i]; _this_1.ondata(null, chk, false); } chks = []; }; var tr = this.d; this.d = 0; var ind = this.u.length; var uf = mrg(file, { f, u, o, t: function() { if (file.terminate) file.terminate(); }, r: function() { pAll(); if (tr) { var nxt = _this_1.u[ind + 1]; if (nxt) nxt.r(); else _this_1.d = 1; } tr = 1; } }); var cl = 0; file.ondata = function(err, dat, final) { if (err) { _this_1.ondata(err, dat, final); _this_1.terminate(); } else { cl += dat.length; chks.push(dat); if (final) { var dd = new u8(16); wbytes(dd, 0, 134695760); wbytes(dd, 4, file.crc); wbytes(dd, 8, cl); wbytes(dd, 12, file.size); chks.push(dd); uf.c = cl, uf.b = hl + cl + 16, uf.crc = file.crc, uf.size = file.size; if (tr) uf.r(); tr = 1; } else if (tr) pAll(); } }; this.u.push(uf); }; Zip2.prototype.end = function() { var _this_1 = this; if (this.d & 2) { if (this.d & 1) throw "stream finishing"; throw "stream finished"; } if (this.d) this.e(); else this.u.push({ r: function() { if (!(_this_1.d & 1)) return; _this_1.u.splice(-1, 1); _this_1.e(); }, t: function() { } }); this.d = 3; }; Zip2.prototype.e = function() { var bt = 0, l = 0, tl = 0; for (var _i = 0, _a12 = this.u; _i < _a12.length; _i++) { var f = _a12[_i]; tl += 46 + f.f.length + exfl(f.extra) + (f.o ? f.o.length : 0); } var out = new u8(tl + 22); for (var _b11 = 0, _c6 = this.u; _b11 < _c6.length; _b11++) { var f = _c6[_b11]; wzh(out, bt, f, f.f, f.u, f.c, l, f.o); bt += 46 + f.f.length + exfl(f.extra) + (f.o ? f.o.length : 0), l += f.b; } wzf(out, bt, this.u.length, tl, l); this.ondata(null, out, true); this.d = 2; }; Zip2.prototype.terminate = function() { for (var _i = 0, _a12 = this.u; _i < _a12.length; _i++) { var f = _a12[_i]; f.t(); } this.d = 2; }; return Zip2; }(); function zipSync(data, opts) { if (!opts) opts = {}; var r = {}; var files = []; fltn(data, "", r, opts); var o = 0; var tot = 0; for (var fn in r) { var _a12 = r[fn], file = _a12[0], p2 = _a12[1]; var compression = p2.level == 0 ? 0 : 8; var f = strToU8(fn), s = f.length; var com = p2.comment, m = com && strToU8(com), ms = m && m.length; var exl = exfl(p2.extra); if (s > 65535) throw "filename too long"; var d = compression ? deflateSync(file, p2) : file, l = d.length; var c = crc(); c.p(file); files.push(mrg(p2, { size: file.length, crc: c.d(), c: d, f, m, u: s != fn.length || m && com.length != ms, o, compression })); o += 30 + s + exl + l; tot += 76 + 2 * (s + exl) + (ms || 0) + l; } var out = new u8(tot + 22), oe = o, cdl = tot - o; for (var i = 0; i < files.length; ++i) { var f = files[i]; wzh(out, f.o, f, f.f, f.u, f.c.length); var badd = 30 + f.f.length + exfl(f.extra); out.set(f.c, f.o + badd); wzh(out, o, f, f.f, f.u, f.c.length, f.o, f.m), o += 16 + badd + (f.m ? f.m.length : 0); } wzf(out, o, files.length, cdl, oe); return out; } var UnzipPassThrough = function() { function UnzipPassThrough2() { } UnzipPassThrough2.prototype.push = function(data, final) { this.ondata(null, data, final); }; UnzipPassThrough2.compression = 0; return UnzipPassThrough2; }(); var UnzipInflate = function() { function UnzipInflate2() { var _this_1 = this; this.i = new Inflate(function(dat, final) { _this_1.ondata(null, dat, final); }); } UnzipInflate2.prototype.push = function(data, final) { try { this.i.push(data, final); } catch (e) { this.ondata(e, data, final); } }; UnzipInflate2.compression = 8; return UnzipInflate2; }(); var AsyncUnzipInflate = function() { function AsyncUnzipInflate2(_, sz) { var _this_1 = this; if (sz < 32e4) { this.i = new Inflate(function(dat, final) { _this_1.ondata(null, dat, final); }); } else { this.i = new AsyncInflate(function(err, dat, final) { _this_1.ondata(err, dat, final); }); this.terminate = this.i.terminate; } } AsyncUnzipInflate2.prototype.push = function(data, final) { if (this.i.terminate) data = slc(data, 0); this.i.push(data, final); }; AsyncUnzipInflate2.compression = 8; return AsyncUnzipInflate2; }(); var Unzip = function() { function Unzip2(cb) { this.onfile = cb; this.k = []; this.o = { 0: UnzipPassThrough }; this.p = et; } Unzip2.prototype.push = function(chunk, final) { var _this_1 = this; if (!this.onfile) throw "no callback"; if (!this.p) throw "stream finished"; if (this.c > 0) { var len = Math.min(this.c, chunk.length); var toAdd = chunk.subarray(0, len); this.c -= len; if (this.d) this.d.push(toAdd, !this.c); else this.k[0].push(toAdd); chunk = chunk.subarray(len); if (chunk.length) return this.push(chunk, final); } else { var f = 0, i = 0, is = void 0, buf = void 0; if (!this.p.length) buf = chunk; else if (!chunk.length) buf = this.p; else { buf = new u8(this.p.length + chunk.length); buf.set(this.p), buf.set(chunk, this.p.length); } var l = buf.length, oc = this.c, add = oc && this.d; var _loop_2 = function() { var _a12; var sig = b4(buf, i); if (sig == 67324752) { f = 1, is = i; this_1.d = null; this_1.c = 0; var bf = b2(buf, i + 6), cmp_1 = b2(buf, i + 8), u = bf & 2048, dd = bf & 8, fnl = b2(buf, i + 26), es = b2(buf, i + 28); if (l > i + 30 + fnl + es) { var chks_2 = []; this_1.k.unshift(chks_2); f = 2; var sc_1 = b4(buf, i + 18), su_1 = b4(buf, i + 22); var fn_1 = strFromU8(buf.subarray(i + 30, i += 30 + fnl), !u); if (sc_1 == 4294967295) { _a12 = dd ? [-2] : z64e(buf, i), sc_1 = _a12[0], su_1 = _a12[1]; } else if (dd) sc_1 = -1; i += es; this_1.c = sc_1; var d_1; var file_1 = { name: fn_1, compression: cmp_1, start: function() { if (!file_1.ondata) throw "no callback"; if (!sc_1) file_1.ondata(null, et, true); else { var ctr = _this_1.o[cmp_1]; if (!ctr) throw "unknown compression type " + cmp_1; d_1 = sc_1 < 0 ? new ctr(fn_1) : new ctr(fn_1, sc_1, su_1); d_1.ondata = function(err, dat3, final2) { file_1.ondata(err, dat3, final2); }; for (var _i = 0, chks_3 = chks_2; _i < chks_3.length; _i++) { var dat2 = chks_3[_i]; d_1.push(dat2, false); } if (_this_1.k[0] == chks_2 && _this_1.c) _this_1.d = d_1; else d_1.push(et, true); } }, terminate: function() { if (d_1 && d_1.terminate) d_1.terminate(); } }; if (sc_1 >= 0) file_1.size = sc_1, file_1.originalSize = su_1; this_1.onfile(file_1); } return "break"; } else if (oc) { if (sig == 134695760) { is = i += 12 + (oc == -2 && 8), f = 3, this_1.c = 0; return "break"; } else if (sig == 33639248) { is = i -= 4, f = 3, this_1.c = 0; return "break"; } } }; var this_1 = this; for (; i < l - 4; ++i) { var state_1 = _loop_2(); if (state_1 === "break") break; } this.p = et; if (oc < 0) { var dat = f ? buf.subarray(0, is - 12 - (oc == -2 && 8) - (b4(buf, is - 16) == 134695760 && 4)) : buf.subarray(0, i); if (add) add.push(dat, !!f); else this.k[+(f == 2)].push(dat); } if (f & 2) return this.push(buf.subarray(i), final); this.p = buf.subarray(i); } if (final) { if (this.c) throw "invalid zip file"; this.p = null; } }; Unzip2.prototype.register = function(decoder) { this.o[decoder.compression] = decoder; }; return Unzip2; }(); // node_modules/three/examples/jsm/exporters/USDZExporter.js var USDZExporter = class { async parse(scene) { const files = {}; const modelFileName = "model.usda"; files[modelFileName] = null; let output = buildHeader(); const materials = {}; const textures = {}; scene.traverseVisible((object) => { if (object.isMesh) { const geometry = object.geometry; const material = object.material; if (material.isMeshStandardMaterial) { const geometryFileName = "geometries/Geometry_" + geometry.id + ".usd"; if (!(geometryFileName in files)) { const meshObject = buildMeshObject(geometry); files[geometryFileName] = buildUSDFileAsString(meshObject); } if (!(material.uuid in materials)) { materials[material.uuid] = material; } output += buildXform(object, geometry, material); } else { console.warn("THREE.USDZExporter: Unsupported material type (USDZ only supports MeshStandardMaterial)", object); } } else if (object.isCamera) { output += buildCamera(object); } }); output += buildMaterials(materials, textures); files[modelFileName] = strToU8(output); output = null; for (const id in textures) { const texture = textures[id]; const color = id.split("_")[1]; const isRGBA = texture.format === 1023; const canvas = imageToCanvas(texture.image, color); const blob = await new Promise((resolve) => canvas.toBlob(resolve, isRGBA ? "image/png" : "image/jpeg", 1)); files[`textures/Texture_${id}.${isRGBA ? "png" : "jpg"}`] = new Uint8Array(await blob.arrayBuffer()); } let offset = 0; for (const filename in files) { const file = files[filename]; const headerSize = 34 + filename.length; offset += headerSize; const offsetMod64 = offset & 63; if (offsetMod64 !== 4) { const padLength = 64 - offsetMod64; const padding = new Uint8Array(padLength); files[filename] = [file, { extra: { 12345: padding } }]; } offset = file.length; } return zipSync(files, { level: 0 }); } }; function imageToCanvas(image, color) { if (typeof HTMLImageElement !== "undefined" && image instanceof HTMLImageElement || typeof HTMLCanvasElement !== "undefined" && image instanceof HTMLCanvasElement || typeof OffscreenCanvas !== "undefined" && image instanceof OffscreenCanvas || typeof ImageBitmap !== "undefined" && image instanceof ImageBitmap) { const scale = 1024 / Math.max(image.width, image.height); const canvas = document.createElement("canvas"); canvas.width = image.width * Math.min(1, scale); canvas.height = image.height * Math.min(1, scale); const context = canvas.getContext("2d"); context.drawImage(image, 0, 0, canvas.width, canvas.height); if (color !== void 0) { const hex = parseInt(color, 16); const r = (hex >> 16 & 255) / 255; const g2 = (hex >> 8 & 255) / 255; const b = (hex & 255) / 255; const imagedata = context.getImageData(0, 0, canvas.width, canvas.height); const data = imagedata.data; for (let i = 0; i < data.length; i += 4) { data[i + 0] = data[i + 0] * r; data[i + 1] = data[i + 1] * g2; data[i + 2] = data[i + 2] * b; } context.putImageData(imagedata, 0, 0); } return canvas; } } var PRECISION = 7; function buildHeader() { return `#usda 1.0 ( customLayerData = { string creator = "Three.js USDZExporter" } metersPerUnit = 1 upAxis = "Y" ) `; } function buildUSDFileAsString(dataToInsert) { let output = buildHeader(); output += dataToInsert; return strToU8(output); } function buildXform(object, geometry, material) { const name = "Object_" + object.id; const transform = buildMatrix(object.matrixWorld); if (object.matrixWorld.determinant() < 0) { console.warn("THREE.USDZExporter: USDZ does not support negative scales", object); } return `def Xform "${name}" ( prepend references = @./geometries/Geometry_${geometry.id}.usd@ ) { matrix4d xformOp:transform = ${transform} uniform token[] xformOpOrder = ["xformOp:transform"] rel material:binding = } `; } function buildMatrix(matrix) { const array = matrix.elements; return `( ${buildMatrixRow(array, 0)}, ${buildMatrixRow(array, 4)}, ${buildMatrixRow(array, 8)}, ${buildMatrixRow(array, 12)} )`; } function buildMatrixRow(array, offset) { return `(${array[offset + 0]}, ${array[offset + 1]}, ${array[offset + 2]}, ${array[offset + 3]})`; } function buildMeshObject(geometry) { const mesh = buildMesh(geometry); return ` def "Geometry" { ${mesh} } `; } function buildMesh(geometry) { const name = "Geometry"; const attributes = geometry.attributes; const count = attributes.position.count; return ` def Mesh "${name}" { int[] faceVertexCounts = [${buildMeshVertexCount(geometry)}] int[] faceVertexIndices = [${buildMeshVertexIndices(geometry)}] normal3f[] normals = [${buildVector3Array(attributes.normal, count)}] ( interpolation = "vertex" ) point3f[] points = [${buildVector3Array(attributes.position, count)}] float2[] primvars:st = [${buildVector2Array(attributes.uv, count)}] ( interpolation = "vertex" ) uniform token subdivisionScheme = "none" } `; } function buildMeshVertexCount(geometry) { const count = geometry.index !== null ? geometry.index.count : geometry.attributes.position.count; return Array(count / 3).fill(3).join(", "); } function buildMeshVertexIndices(geometry) { const index = geometry.index; const array = []; if (index !== null) { for (let i = 0; i < index.count; i++) { array.push(index.getX(i)); } } else { const length = geometry.attributes.position.count; for (let i = 0; i < length; i++) { array.push(i); } } return array.join(", "); } function buildVector3Array(attribute, count) { if (attribute === void 0) { console.warn("USDZExporter: Normals missing."); return Array(count).fill("(0, 0, 0)").join(", "); } const array = []; for (let i = 0; i < attribute.count; i++) { const x2 = attribute.getX(i); const y = attribute.getY(i); const z = attribute.getZ(i); array.push(`(${x2.toPrecision(PRECISION)}, ${y.toPrecision(PRECISION)}, ${z.toPrecision(PRECISION)})`); } return array.join(", "); } function buildVector2Array(attribute, count) { if (attribute === void 0) { console.warn("USDZExporter: UVs missing."); return Array(count).fill("(0, 0)").join(", "); } const array = []; for (let i = 0; i < attribute.count; i++) { const x2 = attribute.getX(i); const y = attribute.getY(i); array.push(`(${x2.toPrecision(PRECISION)}, ${1 - y.toPrecision(PRECISION)})`); } return array.join(", "); } function buildMaterials(materials, textures) { const array = []; for (const uuid in materials) { const material = materials[uuid]; array.push(buildMaterial(material, textures)); } return `def "Materials" { ${array.join("")} } `; } function buildMaterial(material, textures) { const pad = " "; const inputs = []; const samplers = []; function buildTexture(texture, mapType, color) { const id = texture.id + (color ? "_" + color.getHexString() : ""); const isRGBA = texture.format === 1023; textures[id] = texture; return ` def Shader "Transform2d_${mapType}" ( sdrMetadata = { string role = "math" } ) { uniform token info:id = "UsdTransform2d" float2 inputs:in.connect = float2 inputs:scale = ${buildVector2(texture.repeat)} float2 inputs:translation = ${buildVector2(texture.offset)} float2 outputs:result } def Shader "Texture_${texture.id}_${mapType}" { uniform token info:id = "UsdUVTexture" asset inputs:file = @textures/Texture_${id}.${isRGBA ? "png" : "jpg"}@ float2 inputs:st.connect = token inputs:wrapS = "repeat" token inputs:wrapT = "repeat" float outputs:r float outputs:g float outputs:b float3 outputs:rgb ${material.transparent || material.alphaTest > 0 ? "float outputs:a" : ""} }`; } if (material.side === DoubleSide) { console.warn("THREE.USDZExporter: USDZ does not support double sided materials", material); } if (material.map !== null) { inputs.push(`${pad}color3f inputs:diffuseColor.connect = `); if (material.transparent) { inputs.push(`${pad}float inputs:opacity.connect = `); } else if (material.alphaTest > 0) { inputs.push(`${pad}float inputs:opacity.connect = `); inputs.push(`${pad}float inputs:opacityThreshold = ${material.alphaTest}`); } samplers.push(buildTexture(material.map, "diffuse", material.color)); } else { inputs.push(`${pad}color3f inputs:diffuseColor = ${buildColor(material.color)}`); } if (material.emissiveMap !== null) { inputs.push(`${pad}color3f inputs:emissiveColor.connect = `); samplers.push(buildTexture(material.emissiveMap, "emissive")); } else if (material.emissive.getHex() > 0) { inputs.push(`${pad}color3f inputs:emissiveColor = ${buildColor(material.emissive)}`); } if (material.normalMap !== null) { inputs.push(`${pad}normal3f inputs:normal.connect = `); samplers.push(buildTexture(material.normalMap, "normal")); } if (material.aoMap !== null) { inputs.push(`${pad}float inputs:occlusion.connect = `); samplers.push(buildTexture(material.aoMap, "occlusion")); } if (material.roughnessMap !== null && material.roughness === 1) { inputs.push(`${pad}float inputs:roughness.connect = `); samplers.push(buildTexture(material.roughnessMap, "roughness")); } else { inputs.push(`${pad}float inputs:roughness = ${material.roughness}`); } if (material.metalnessMap !== null && material.metalness === 1) { inputs.push(`${pad}float inputs:metallic.connect = `); samplers.push(buildTexture(material.metalnessMap, "metallic")); } else { inputs.push(`${pad}float inputs:metallic = ${material.metalness}`); } if (material.alphaMap !== null) { inputs.push(`${pad}float inputs:opacity.connect = `); inputs.push(`${pad}float inputs:opacityThreshold = 0.0001`); samplers.push(buildTexture(material.alphaMap, "opacity")); } else { inputs.push(`${pad}float inputs:opacity = ${material.opacity}`); } if (material.isMeshPhysicalMaterial) { inputs.push(`${pad}float inputs:clearcoat = ${material.clearcoat}`); inputs.push(`${pad}float inputs:clearcoatRoughness = ${material.clearcoatRoughness}`); inputs.push(`${pad}float inputs:ior = ${material.ior}`); } return ` def Material "Material_${material.id}" { def Shader "PreviewSurface" { uniform token info:id = "UsdPreviewSurface" ${inputs.join("\n")} int inputs:useSpecularWorkflow = 0 token outputs:surface } token outputs:surface.connect = token inputs:frame:stPrimvarName = "st" def Shader "uvReader_st" { uniform token info:id = "UsdPrimvarReader_float2" token inputs:varname.connect = float2 inputs:fallback = (0.0, 0.0) float2 outputs:result } ${samplers.join("\n")} } `; } function buildColor(color) { return `(${color.r}, ${color.g}, ${color.b})`; } function buildVector2(vector) { return `(${vector.x}, ${vector.y})`; } function buildCamera(camera2) { const name = camera2.name ? camera2.name : "Camera_" + camera2.id; const transform = buildMatrix(camera2.matrixWorld); if (camera2.matrixWorld.determinant() < 0) { console.warn("THREE.USDZExporter: USDZ does not support negative scales", camera2); } if (camera2.isOrthographicCamera) { return `def Camera "${name}" { matrix4d xformOp:transform = ${transform} uniform token[] xformOpOrder = ["xformOp:transform"] float2 clippingRange = (${camera2.near}, ${camera2.far}) float horizontalAperture = ${(Math.abs(camera2.left) + Math.abs(camera2.right)) * 10} float verticalAperture = ${(Math.abs(camera2.top) + Math.abs(camera2.bottom)) * 10} token projection = "orthographic" } `; } else { return `def Camera "${name}" { matrix4d xformOp:transform = ${transform} uniform token[] xformOpOrder = ["xformOp:transform"] float2 clippingRange = (${camera2.near}, ${camera2.far}) float focalLength = ${camera2.getFocalLength()} float focusDistance = ${camera2.focus} float horizontalAperture = ${camera2.getFilmWidth()} token projection = "perspective" float verticalAperture = ${camera2.getFilmHeight()} } `; } } // node_modules/@google/model-viewer/lib/styles/deserializers.js var enumerationDeserializer = (allowedNames) => (valueString) => { try { const expressions = parseExpressions(valueString); const names = (expressions.length ? expressions[0].terms : []).filter((valueNode) => valueNode && valueNode.type === "ident").map((valueNode) => valueNode.value).filter((name) => allowedNames.indexOf(name) > -1); const result = /* @__PURE__ */ new Set(); for (const name of names) { result.add(name); } return result; } catch (_error) { } return /* @__PURE__ */ new Set(); }; // node_modules/@google/model-viewer/lib/features/ar.js var __decorate5 = function(decorators, target2, key, desc) { var c = arguments.length, r = c < 3 ? target2 : desc === null ? desc = Object.getOwnPropertyDescriptor(target2, key) : desc, d; if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target2, key, desc); else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target2, key, r) : d(target2, key)) || r; return c > 3 && r && Object.defineProperty(target2, key, r), r; }; var isWebXRBlocked = false; var isSceneViewerBlocked = false; var noArViewerSigil = "#model-viewer-no-ar-fallback"; var deserializeARModes = enumerationDeserializer(["quick-look", "scene-viewer", "webxr", "none"]); var DEFAULT_AR_MODES = "webxr scene-viewer quick-look"; var ARMode = { QUICK_LOOK: "quick-look", SCENE_VIEWER: "scene-viewer", WEBXR: "webxr", NONE: "none" }; var $arButtonContainer = Symbol("arButtonContainer"); var $enterARWithWebXR = Symbol("enterARWithWebXR"); var $openSceneViewer = Symbol("openSceneViewer"); var $openIOSARQuickLook = Symbol("openIOSARQuickLook"); var $canActivateAR = Symbol("canActivateAR"); var $arMode = Symbol("arMode"); var $arModes = Symbol("arModes"); var $arAnchor = Symbol("arAnchor"); var $preload = Symbol("preload"); var $onARButtonContainerClick = Symbol("onARButtonContainerClick"); var $onARStatus = Symbol("onARStatus"); var $onARTracking = Symbol("onARTracking"); var $onARTap = Symbol("onARTap"); var $selectARMode = Symbol("selectARMode"); var $triggerLoad = Symbol("triggerLoad"); var ARMixin = (ModelViewerElement2) => { var _a12, _b11, _c6, _d5, _e4, _f4, _g2, _h2, _j2, _k2; class ARModelViewerElement extends ModelViewerElement2 { constructor() { super(...arguments); this.ar = false; this.arScale = "auto"; this.arPlacement = "floor"; this.arModes = DEFAULT_AR_MODES; this.iosSrc = null; this.xrEnvironment = false; this[_a12] = false; this[_b11] = this.shadowRoot.querySelector(".ar-button"); this[_c6] = document.createElement("a"); this[_d5] = /* @__PURE__ */ new Set(); this[_e4] = ARMode.NONE; this[_f4] = false; this[_g2] = (event) => { event.preventDefault(); this.activateAR(); }; this[_h2] = ({ status }) => { if (status === ARStatus.NOT_PRESENTING || this[$renderer].arRenderer.presentedScene === this[$scene]) { this.setAttribute("ar-status", status); this.dispatchEvent(new CustomEvent("ar-status", { detail: { status } })); if (status === ARStatus.NOT_PRESENTING) { this.removeAttribute("ar-tracking"); } else if (status === ARStatus.SESSION_STARTED) { this.setAttribute("ar-tracking", ARTracking.TRACKING); } } }; this[_j2] = ({ status }) => { this.setAttribute("ar-tracking", status); this.dispatchEvent(new CustomEvent("ar-tracking", { detail: { status } })); }; this[_k2] = (event) => { if (event.data == "_apple_ar_quicklook_button_tapped") { this.dispatchEvent(new CustomEvent("quick-look-button-tapped")); } }; } get canActivateAR() { return this[$arMode] !== ARMode.NONE; } connectedCallback() { super.connectedCallback(); this[$renderer].arRenderer.addEventListener("status", this[$onARStatus]); this.setAttribute("ar-status", ARStatus.NOT_PRESENTING); this[$renderer].arRenderer.addEventListener("tracking", this[$onARTracking]); this[$arAnchor].addEventListener("message", this[$onARTap]); } disconnectedCallback() { super.disconnectedCallback(); this[$renderer].arRenderer.removeEventListener("status", this[$onARStatus]); this[$renderer].arRenderer.removeEventListener("tracking", this[$onARTracking]); this[$arAnchor].removeEventListener("message", this[$onARTap]); } update(changedProperties) { super.update(changedProperties); if (changedProperties.has("arScale")) { this[$scene].canScale = this.arScale !== "fixed"; } if (changedProperties.has("arPlacement")) { this[$scene].updateShadow(); this[$needsRender](); } if (changedProperties.has("arModes")) { this[$arModes] = deserializeARModes(this.arModes); } if (changedProperties.has("ar") || changedProperties.has("arModes") || changedProperties.has("src") || changedProperties.has("iosSrc")) { this[$selectARMode](); } } /** * Activates AR. Note that for any mode that is not WebXR-based, this * method most likely has to be called synchronous from a user * interaction handler. Otherwise, attempts to activate modes that * require user interaction will most likely be ignored. */ async activateAR() { switch (this[$arMode]) { case ARMode.QUICK_LOOK: this[$openIOSARQuickLook](); break; case ARMode.WEBXR: await this[$enterARWithWebXR](); break; case ARMode.SCENE_VIEWER: this[$openSceneViewer](); break; default: console.warn("No AR Mode can be activated. This is probably due to missing configuration or device capabilities"); break; } } async [(_a12 = $canActivateAR, _b11 = $arButtonContainer, _c6 = $arAnchor, _d5 = $arModes, _e4 = $arMode, _f4 = $preload, _g2 = $onARButtonContainerClick, _h2 = $onARStatus, _j2 = $onARTracking, _k2 = $onARTap, $selectARMode)]() { let arMode = ARMode.NONE; if (this.ar) { if (this.src != null) { for (const value of this[$arModes]) { if (value === "webxr" && IS_WEBXR_AR_CANDIDATE && !isWebXRBlocked && await this[$renderer].arRenderer.supportsPresentation()) { arMode = ARMode.WEBXR; break; } if (value === "scene-viewer" && IS_SCENEVIEWER_CANDIDATE && !isSceneViewerBlocked) { arMode = ARMode.SCENE_VIEWER; break; } if (value === "quick-look" && IS_AR_QUICKLOOK_CANDIDATE) { arMode = ARMode.QUICK_LOOK; break; } } } if (arMode === ARMode.NONE && this.iosSrc != null && IS_AR_QUICKLOOK_CANDIDATE) { arMode = ARMode.QUICK_LOOK; } } if (arMode !== ARMode.NONE) { this[$arButtonContainer].classList.add("enabled"); this[$arButtonContainer].addEventListener("click", this[$onARButtonContainerClick]); } else if (this[$arButtonContainer].classList.contains("enabled")) { this[$arButtonContainer].removeEventListener("click", this[$onARButtonContainerClick]); this[$arButtonContainer].classList.remove("enabled"); const status = ARStatus.FAILED; this.setAttribute("ar-status", status); this.dispatchEvent(new CustomEvent("ar-status", { detail: { status } })); } this[$arMode] = arMode; } async [$enterARWithWebXR]() { console.log("Attempting to present in AR with WebXR..."); await this[$triggerLoad](); try { this[$arButtonContainer].removeEventListener("click", this[$onARButtonContainerClick]); const { arRenderer } = this[$renderer]; arRenderer.placeOnWall = this.arPlacement === "wall"; await arRenderer.present(this[$scene], this.xrEnvironment); } catch (error) { console.warn("Error while trying to present in AR with WebXR"); console.error(error); await this[$renderer].arRenderer.stopPresenting(); isWebXRBlocked = true; console.warn("Falling back to next ar-mode"); await this[$selectARMode](); this.activateAR(); } finally { this[$selectARMode](); } } async [$triggerLoad]() { if (!this.loaded) { this[$preload] = true; this[$updateSource](); await waitForEvent(this, "load"); this[$preload] = false; } } [$shouldAttemptPreload]() { return super[$shouldAttemptPreload]() || this[$preload]; } /** * Takes a URL and a title string, and attempts to launch Scene Viewer on * the current device. */ [$openSceneViewer]() { const location = self.location.toString(); const locationUrl = new URL(location); const modelUrl = new URL(this.src, location); const params = new URLSearchParams(modelUrl.search); locationUrl.hash = noArViewerSigil; params.set("mode", "ar_preferred"); if (!params.has("disable_occlusion")) { params.set("disable_occlusion", "true"); } if (this.arScale === "fixed") { params.set("resizable", "false"); } if (this.arPlacement === "wall") { params.set("enable_vertical_placement", "true"); } if (params.has("sound")) { const soundUrl = new URL(params.get("sound"), location); params.set("sound", soundUrl.toString()); } if (params.has("link")) { const linkUrl = new URL(params.get("link"), location); params.set("link", linkUrl.toString()); } const intent = `intent://arvr.google.com/scene-viewer/1.0?${params.toString() + "&file=" + encodeURIComponent(modelUrl.toString())}#Intent;scheme=https;package=com.google.ar.core;action=android.intent.action.VIEW;S.browser_fallback_url=${encodeURIComponent(locationUrl.toString())};end;`; const undoHashChange = () => { if (self.location.hash === noArViewerSigil) { isSceneViewerBlocked = true; self.history.back(); console.warn("Error while trying to present in AR with Scene Viewer"); console.warn("Falling back to next ar-mode"); this[$selectARMode](); } }; self.addEventListener("hashchange", undoHashChange, { once: true }); this[$arAnchor].setAttribute("href", intent); console.log("Attempting to present in AR with Scene Viewer..."); this[$arAnchor].click(); } /** * Takes a URL to a USDZ file and sets the appropriate fields so that * Safari iOS can intent to their AR Quick Look. */ async [$openIOSARQuickLook]() { const generateUsdz = !this.iosSrc; this[$arButtonContainer].classList.remove("enabled"); const objectURL = generateUsdz ? await this.prepareUSDZ() : this.iosSrc; const modelUrl = new URL(objectURL, self.location.toString()); if (generateUsdz) { const location = self.location.toString(); const locationUrl = new URL(location); const srcUrl = new URL(this.src, locationUrl); if (srcUrl.hash) { modelUrl.hash = srcUrl.hash; } } if (this.arScale === "fixed") { if (modelUrl.hash) { modelUrl.hash += "&"; } modelUrl.hash += "allowsContentScaling=0"; } const anchor = this[$arAnchor]; anchor.setAttribute("rel", "ar"); const img = document.createElement("img"); anchor.appendChild(img); anchor.setAttribute("href", modelUrl.toString()); if (generateUsdz) { anchor.setAttribute("download", "model.usdz"); } anchor.style.display = "none"; if (!anchor.isConnected) this.shadowRoot.appendChild(anchor); console.log("Attempting to present in AR with Quick Look..."); anchor.click(); anchor.removeChild(img); if (generateUsdz) { URL.revokeObjectURL(objectURL); } this[$arButtonContainer].classList.add("enabled"); } async prepareUSDZ() { const updateSourceProgress = this[$progressTracker].beginActivity(); await this[$triggerLoad](); const { model, shadow } = this[$scene]; if (model == null) { return ""; } let visible = false; if (shadow != null) { visible = shadow.visible; shadow.visible = false; } updateSourceProgress(0.2); const exporter = new USDZExporter(); const arraybuffer = await exporter.parse(model); const blob = new Blob([arraybuffer], { type: "model/vnd.usdz+zip" }); const url = URL.createObjectURL(blob); updateSourceProgress(1); if (shadow != null) { shadow.visible = visible; } return url; } } __decorate5([ property({ type: Boolean, attribute: "ar" }) ], ARModelViewerElement.prototype, "ar", void 0); __decorate5([ property({ type: String, attribute: "ar-scale" }) ], ARModelViewerElement.prototype, "arScale", void 0); __decorate5([ property({ type: String, attribute: "ar-placement" }) ], ARModelViewerElement.prototype, "arPlacement", void 0); __decorate5([ property({ type: String, attribute: "ar-modes" }) ], ARModelViewerElement.prototype, "arModes", void 0); __decorate5([ property({ type: String, attribute: "ios-src" }) ], ARModelViewerElement.prototype, "iosSrc", void 0); __decorate5([ property({ type: Boolean, attribute: "xr-environment" }) ], ARModelViewerElement.prototype, "xrEnvironment", void 0); return ARModelViewerElement; }; // node_modules/@google/model-viewer/lib/styles/evaluators.js var _a10; var _b9; var _c4; var $evaluate = Symbol("evaluate"); var $lastValue = Symbol("lastValue"); var Evaluator = class _Evaluator { constructor() { this[_a10] = null; } /** * An Evaluatable is a NumberNode or an Evaluator that evaluates a NumberNode * as the result of invoking its evaluate method. This is mainly used to * ensure that CSS function nodes are cast to the corresponding Evaluators * that will resolve the result of the function, but is also used to ensure * that a percentage nested at arbitrary depth in the expression will always * be evaluated against the correct basis. */ static evaluatableFor(node, basis = ZERO) { if (node instanceof _Evaluator) { return node; } if (node.type === "number") { if (node.unit === "%") { return new PercentageEvaluator(node, basis); } return node; } switch (node.name.value) { case "calc": return new CalcEvaluator(node, basis); case "env": return new EnvEvaluator(node); } return ZERO; } /** * If the input is an Evaluator, returns the result of evaluating it. * Otherwise, returns the input. * * This is a helper to aide in resolving a NumberNode without conditionally * checking if the Evaluatable is an Evaluator everywhere. */ static evaluate(evaluatable) { if (evaluatable instanceof _Evaluator) { return evaluatable.evaluate(); } return evaluatable; } /** * If the input is an Evaluator, returns the value of its isConstant property. * Returns true for all other input values. */ static isConstant(evaluatable) { if (evaluatable instanceof _Evaluator) { return evaluatable.isConstant; } return true; } /** * This method applies a set of structured intrinsic metadata to an evaluated * result from a parsed CSS-like string of expressions. Intrinsics provide * sufficient metadata (e.g., basis values, analogs for keywords) such that * omitted values in the input string can be backfilled, and keywords can be * converted to concrete numbers. * * The result of applying intrinsics is a tuple of NumberNode values whose * units match the units used by the basis of the intrinsics. * * The following is a high-level description of how intrinsics are applied: * * 1. Determine the value of 'auto' for the current term * 2. If there is no corresponding input value for this term, substitute the * 'auto' value. * 3. If the term is an IdentNode, treat it as a keyword and perform the * appropriate substitution. * 4. If the term is still null, fallback to the 'auto' value * 5. If the term is a percentage, apply it to the basis and return that * value * 6. Normalize the unit of the term * 7. If the term's unit does not match the basis unit, return the basis * value * 8. Return the term as is */ static applyIntrinsics(evaluated, intrinsics) { const { basis, keywords } = intrinsics; const { auto } = keywords; return basis.map((basisNode, index) => { const autoSubstituteNode = auto[index] == null ? basisNode : auto[index]; let evaluatedNode = evaluated[index] ? evaluated[index] : autoSubstituteNode; if (evaluatedNode.type === "ident") { const keyword = evaluatedNode.value; if (keyword in keywords) { evaluatedNode = keywords[keyword][index]; } } if (evaluatedNode == null || evaluatedNode.type === "ident") { evaluatedNode = autoSubstituteNode; } if (evaluatedNode.unit === "%") { return numberNode(evaluatedNode.number / 100 * basisNode.number, basisNode.unit); } evaluatedNode = normalizeUnit(evaluatedNode, basisNode); if (evaluatedNode.unit !== basisNode.unit) { return basisNode; } return evaluatedNode; }); } /** * If true, the Evaluator will only evaluate its AST one time. If false, the * Evaluator will re-evaluate the AST each time that the public evaluate * method is invoked. */ get isConstant() { return false; } /** * Evaluate the Evaluator and return the result. If the Evaluator is constant, * the corresponding AST will only be evaluated once, and the result of * evaluating it the first time will be returned on all subsequent * evaluations. */ evaluate() { if (!this.isConstant || this[$lastValue] == null) { this[$lastValue] = this[$evaluate](); } return this[$lastValue]; } }; _a10 = $lastValue; var $percentage = Symbol("percentage"); var $basis = Symbol("basis"); var PercentageEvaluator = class extends Evaluator { constructor(percentage, basis) { super(); this[$percentage] = percentage; this[$basis] = basis; } get isConstant() { return true; } [$evaluate]() { return numberNode(this[$percentage].number / 100 * this[$basis].number, this[$basis].unit); } }; var $identNode = Symbol("identNode"); var EnvEvaluator = class extends Evaluator { constructor(envFunction) { super(); this[_b9] = null; const identNode = envFunction.arguments.length ? envFunction.arguments[0].terms[0] : null; if (identNode != null && identNode.type === "ident") { this[$identNode] = identNode; } } get isConstant() { return false; } [(_b9 = $identNode, $evaluate)]() { if (this[$identNode] != null) { switch (this[$identNode].value) { case "window-scroll-y": const verticalScrollPosition = window.pageYOffset; const verticalScrollMax = Math.max(document.body.scrollHeight, document.body.offsetHeight, document.documentElement.clientHeight, document.documentElement.scrollHeight, document.documentElement.offsetHeight); const scrollY = verticalScrollPosition / (verticalScrollMax - window.innerHeight) || 0; return { type: "number", number: scrollY, unit: null }; } } return ZERO; } }; var IS_MULTIPLICATION_RE = /[\*\/]/; var $evaluator = Symbol("evaluator"); var CalcEvaluator = class extends Evaluator { constructor(calcFunction, basis = ZERO) { super(); this[_c4] = null; if (calcFunction.arguments.length !== 1) { return; } const terms = calcFunction.arguments[0].terms.slice(); const secondOrderTerms = []; while (terms.length) { const term = terms.shift(); if (secondOrderTerms.length > 0) { const previousTerm = secondOrderTerms[secondOrderTerms.length - 1]; if (previousTerm.type === "operator" && IS_MULTIPLICATION_RE.test(previousTerm.value)) { const operator = secondOrderTerms.pop(); const leftValue = secondOrderTerms.pop(); if (leftValue == null) { return; } secondOrderTerms.push(new OperatorEvaluator(operator, Evaluator.evaluatableFor(leftValue, basis), Evaluator.evaluatableFor(term, basis))); continue; } } secondOrderTerms.push(term.type === "operator" ? term : Evaluator.evaluatableFor(term, basis)); } while (secondOrderTerms.length > 2) { const [left, operator, right] = secondOrderTerms.splice(0, 3); if (operator.type !== "operator") { return; } secondOrderTerms.unshift(new OperatorEvaluator(operator, Evaluator.evaluatableFor(left, basis), Evaluator.evaluatableFor(right, basis))); } if (secondOrderTerms.length === 1) { this[$evaluator] = secondOrderTerms[0]; } } get isConstant() { return this[$evaluator] == null || Evaluator.isConstant(this[$evaluator]); } [(_c4 = $evaluator, $evaluate)]() { return this[$evaluator] != null ? Evaluator.evaluate(this[$evaluator]) : ZERO; } }; var $operator = Symbol("operator"); var $left = Symbol("left"); var $right = Symbol("right"); var OperatorEvaluator = class extends Evaluator { constructor(operator, left, right) { super(); this[$operator] = operator; this[$left] = left; this[$right] = right; } get isConstant() { return Evaluator.isConstant(this[$left]) && Evaluator.isConstant(this[$right]); } [$evaluate]() { const leftNode = normalizeUnit(Evaluator.evaluate(this[$left])); const rightNode = normalizeUnit(Evaluator.evaluate(this[$right])); const { number: leftValue, unit: leftUnit } = leftNode; const { number: rightValue, unit: rightUnit } = rightNode; if (rightUnit != null && leftUnit != null && rightUnit != leftUnit) { return ZERO; } const unit = leftUnit || rightUnit; let value; switch (this[$operator].value) { case "+": value = leftValue + rightValue; break; case "-": value = leftValue - rightValue; break; case "/": value = leftValue / rightValue; break; case "*": value = leftValue * rightValue; break; default: return ZERO; } return { type: "number", number: value, unit }; } }; var $evaluatables = Symbol("evaluatables"); var $intrinsics = Symbol("intrinsics"); var StyleEvaluator = class extends Evaluator { constructor(expressions, intrinsics) { super(); this[$intrinsics] = intrinsics; const firstExpression = expressions[0]; const terms = firstExpression != null ? firstExpression.terms : []; this[$evaluatables] = intrinsics.basis.map((basisNode, index) => { const term = terms[index]; if (term == null) { return { type: "ident", value: "auto" }; } if (term.type === "ident") { return term; } return Evaluator.evaluatableFor(term, basisNode); }); } get isConstant() { for (const evaluatable of this[$evaluatables]) { if (!Evaluator.isConstant(evaluatable)) { return false; } } return true; } [$evaluate]() { const evaluated = this[$evaluatables].map((evaluatable) => Evaluator.evaluate(evaluatable)); return Evaluator.applyIntrinsics(evaluated, this[$intrinsics]).map((numberNode2) => numberNode2.number); } }; // node_modules/@google/model-viewer/lib/styles/style-effector.js var _a11; var _b10; var _c5; var _d4; var $instances = Symbol("instances"); var $activateListener = Symbol("activateListener"); var $deactivateListener = Symbol("deactivateListener"); var $notifyInstances = Symbol("notifyInstances"); var $notify = Symbol("notify"); var $scrollCallback = Symbol("callback"); var ScrollObserver = class _ScrollObserver { constructor(callback) { this[$scrollCallback] = callback; } static [$notifyInstances]() { for (const instance of _ScrollObserver[$instances]) { instance[$notify](); } } static [(_a11 = $instances, $activateListener)]() { window.addEventListener("scroll", this[$notifyInstances], { passive: true }); } static [$deactivateListener]() { window.removeEventListener("scroll", this[$notifyInstances]); } /** * Listen for scroll events. The configured callback (passed to the * constructor) will be invoked for subsequent global scroll events. */ observe() { if (_ScrollObserver[$instances].size === 0) { _ScrollObserver[$activateListener](); } _ScrollObserver[$instances].add(this); } /** * Stop listening for scroll events. */ disconnect() { _ScrollObserver[$instances].delete(this); if (_ScrollObserver[$instances].size === 0) { _ScrollObserver[$deactivateListener](); } } [$notify]() { this[$scrollCallback](); } }; ScrollObserver[_a11] = /* @__PURE__ */ new Set(); var $computeStyleCallback = Symbol("computeStyleCallback"); var $astWalker = Symbol("astWalker"); var $dependencies = Symbol("dependencies"); var $onScroll = Symbol("onScroll"); var StyleEffector = class { constructor(callback) { this[_b10] = {}; this[_c5] = new ASTWalker(["function"]); this[_d4] = () => { this[$computeStyleCallback]({ relatedState: "window-scroll" }); }; this[$computeStyleCallback] = callback; } /** * Sets the expressions that govern when the StyleEffector callback will be * invoked. */ observeEffectsFor(ast) { const newDependencies = {}; const oldDependencies = this[$dependencies]; this[$astWalker].walk(ast, (functionNode) => { const { name } = functionNode; const firstArgument = functionNode.arguments[0]; const firstTerm = firstArgument.terms[0]; if (name.value !== "env" || firstTerm == null || firstTerm.type !== "ident") { return; } switch (firstTerm.value) { case "window-scroll-y": if (newDependencies["window-scroll"] == null) { const observer = "window-scroll" in oldDependencies ? oldDependencies["window-scroll"] : new ScrollObserver(this[$onScroll]); observer.observe(); delete oldDependencies["window-scroll"]; newDependencies["window-scroll"] = observer; } break; } }); for (const environmentState in oldDependencies) { const observer = oldDependencies[environmentState]; observer.disconnect(); } this[$dependencies] = newDependencies; } /** * Disposes of the StyleEffector by disconnecting all observers of external * effects. */ dispose() { for (const environmentState in this[$dependencies]) { const observer = this[$dependencies][environmentState]; observer.disconnect(); } } }; _b10 = $dependencies, _c5 = $astWalker, _d4 = $onScroll; // node_modules/@google/model-viewer/lib/decorators.js var style = (config) => { const observeEffects = config.observeEffects || false; const getIntrinsics = config.intrinsics instanceof Function ? config.intrinsics : () => config.intrinsics; return (proto, propertyName) => { const originalUpdated = proto.updated; const originalConnectedCallback = proto.connectedCallback; const originalDisconnectedCallback = proto.disconnectedCallback; const $styleEffector = Symbol(`${propertyName}StyleEffector`); const $styleEvaluator = Symbol(`${propertyName}StyleEvaluator`); const $updateEvaluator = Symbol(`${propertyName}UpdateEvaluator`); const $evaluateAndSync = Symbol(`${propertyName}EvaluateAndSync`); Object.defineProperties(proto, { [$styleEffector]: { value: null, writable: true }, [$styleEvaluator]: { value: null, writable: true }, [$updateEvaluator]: { value: function() { const ast = parseExpressions(this[propertyName]); this[$styleEvaluator] = new StyleEvaluator(ast, getIntrinsics(this)); if (this[$styleEffector] == null && observeEffects) { this[$styleEffector] = new StyleEffector(() => this[$evaluateAndSync]()); } if (this[$styleEffector] != null) { this[$styleEffector].observeEffectsFor(ast); } } }, [$evaluateAndSync]: { value: function() { if (this[$styleEvaluator] == null) { return; } const result = this[$styleEvaluator].evaluate(); this[config.updateHandler](result); } }, updated: { value: function(changedProperties) { if (changedProperties.has(propertyName)) { this[$updateEvaluator](); this[$evaluateAndSync](); } originalUpdated.call(this, changedProperties); } }, connectedCallback: { value: function() { originalConnectedCallback.call(this); this.requestUpdate(propertyName, this[propertyName]); } }, disconnectedCallback: { value: function() { originalDisconnectedCallback.call(this); if (this[$styleEffector] != null) { this[$styleEffector].dispose(); this[$styleEffector] = null; } } } }); }; }; // node_modules/@google/model-viewer/lib/three-components/SmoothControls.js var PAN_SENSITIVITY = 0.018; var TAP_DISTANCE = 2; var TAP_MS = 300; var vector22 = new Vector2(); var vector33 = new Vector3(); var DEFAULT_OPTIONS = Object.freeze({ minimumRadius: 0, maximumRadius: Infinity, minimumPolarAngle: Math.PI / 8, maximumPolarAngle: Math.PI - Math.PI / 8, minimumAzimuthalAngle: -Infinity, maximumAzimuthalAngle: Infinity, minimumFieldOfView: 10, maximumFieldOfView: 45, touchAction: "none" }); var KEYBOARD_ORBIT_INCREMENT = Math.PI / 8; var ZOOM_SENSITIVITY = 0.04; var PAN_KEY_INCREMENT = 10; var ChangeSource = { USER_INTERACTION: "user-interaction", NONE: "none", AUTOMATIC: "automatic" }; var SmoothControls = class extends EventDispatcher { constructor(camera2, element, scene) { super(); this.camera = camera2; this.element = element; this.scene = scene; this.orbitSensitivity = 1; this.inputSensitivity = 1; this.changeSource = ChangeSource.NONE; this._interactionEnabled = false; this._disableZoom = false; this.isUserPointing = false; this.enablePan = true; this.enableTap = true; this.panProjection = new Matrix3(); this.panPerPixel = 0; this.spherical = new Spherical(); this.goalSpherical = new Spherical(); this.thetaDamper = new Damper(); this.phiDamper = new Damper(); this.radiusDamper = new Damper(); this.logFov = Math.log(DEFAULT_OPTIONS.maximumFieldOfView); this.goalLogFov = this.logFov; this.fovDamper = new Damper(); this.touchMode = null; this.pointers = []; this.startTime = 0; this.startPointerPosition = { clientX: 0, clientY: 0 }; this.lastSeparation = 0; this.touchDecided = false; this.onContext = (event) => { if (this.enablePan) { event.preventDefault(); } else { for (const pointer of this.pointers) { this.onPointerUp(new PointerEvent("pointercancel", Object.assign(Object.assign({}, this.startPointerPosition), { pointerId: pointer.id }))); } } }; this.touchModeZoom = (dx, dy) => { if (!this._disableZoom) { const touchDistance = this.twoTouchDistance(this.pointers[0], this.pointers[1]); const deltaZoom = ZOOM_SENSITIVITY * (this.lastSeparation - touchDistance) * 50 / this.scene.height; this.lastSeparation = touchDistance; this.userAdjustOrbit(0, 0, deltaZoom); } if (this.panPerPixel > 0) { this.movePan(dx, dy); } }; this.disableScroll = (event) => { event.preventDefault(); }; this.touchModeRotate = (dx, dy) => { const { touchAction } = this._options; if (!this.touchDecided && touchAction !== "none") { this.touchDecided = true; const dxMag = Math.abs(dx); const dyMag = Math.abs(dy); if (this.changeSource === ChangeSource.USER_INTERACTION && (touchAction === "pan-y" && dyMag > dxMag || touchAction === "pan-x" && dxMag > dyMag)) { this.touchMode = null; return; } else { this.element.addEventListener("touchmove", this.disableScroll, { passive: false }); } } this.handleSinglePointerMove(dx, dy); }; this.onPointerDown = (event) => { if (this.pointers.length > 2) { return; } const { element: element2 } = this; if (this.pointers.length === 0) { element2.addEventListener("pointermove", this.onPointerMove); element2.addEventListener("pointerup", this.onPointerUp); this.touchMode = null; this.touchDecided = false; this.startPointerPosition.clientX = event.clientX; this.startPointerPosition.clientY = event.clientY; this.startTime = performance.now(); } try { element2.setPointerCapture(event.pointerId); } catch (_a12) { } this.pointers.push({ clientX: event.clientX, clientY: event.clientY, id: event.pointerId }); this.isUserPointing = false; if (event.pointerType === "touch") { this.changeSource = event.altKey ? ( // set by interact() in controls.ts ChangeSource.AUTOMATIC ) : ChangeSource.USER_INTERACTION; this.onTouchChange(event); } else { this.changeSource = ChangeSource.USER_INTERACTION; this.onMouseDown(event); } }; this.onPointerMove = (event) => { const pointer = this.pointers.find((pointer2) => pointer2.id === event.pointerId); if (pointer == null) { return; } const numTouches = this.pointers.length; const dx = (event.clientX - pointer.clientX) / numTouches; const dy = (event.clientY - pointer.clientY) / numTouches; if (dx === 0 && dy === 0) { return; } pointer.clientX = event.clientX; pointer.clientY = event.clientY; if (event.pointerType === "touch") { this.changeSource = event.altKey ? ( // set by interact() in controls.ts ChangeSource.AUTOMATIC ) : ChangeSource.USER_INTERACTION; if (this.touchMode !== null) { this.touchMode(dx, dy); } } else { this.changeSource = ChangeSource.USER_INTERACTION; if (this.panPerPixel > 0) { this.movePan(dx, dy); } else { this.handleSinglePointerMove(dx, dy); } } }; this.onPointerUp = (event) => { const { element: element2 } = this; const index = this.pointers.findIndex((pointer) => pointer.id === event.pointerId); if (index !== -1) { this.pointers.splice(index, 1); } if (this.panPerPixel > 0 && !event.altKey) { this.resetRadius(); } if (this.pointers.length === 0) { element2.removeEventListener("pointermove", this.onPointerMove); element2.removeEventListener("pointerup", this.onPointerUp); element2.removeEventListener("touchmove", this.disableScroll); if (this.enablePan && this.enableTap) { this.recenter(event); } } else if (this.touchMode !== null) { this.onTouchChange(event); } this.scene.element[$panElement].style.opacity = 0; element2.style.cursor = "grab"; this.panPerPixel = 0; if (this.isUserPointing) { this.dispatchEvent({ type: "pointer-change-end" }); } }; this.onWheel = (event) => { this.changeSource = ChangeSource.USER_INTERACTION; const deltaZoom = event.deltaY * (event.deltaMode == 1 ? 18 : 1) * ZOOM_SENSITIVITY / 30; this.userAdjustOrbit(0, 0, deltaZoom); event.preventDefault(); }; this.onKeyDown = (event) => { const { changeSource } = this; this.changeSource = ChangeSource.USER_INTERACTION; const relevantKey = event.shiftKey && this.enablePan ? this.panKeyCodeHandler(event) : this.orbitZoomKeyCodeHandler(event); if (relevantKey) { event.preventDefault(); } else { this.changeSource = changeSource; } }; this._options = Object.assign({}, DEFAULT_OPTIONS); this.setOrbit(0, Math.PI / 2, 1); this.setFieldOfView(100); this.jumpToGoal(); } get interactionEnabled() { return this._interactionEnabled; } enableInteraction() { if (this._interactionEnabled === false) { const { element } = this; element.addEventListener("pointerdown", this.onPointerDown); element.addEventListener("pointercancel", this.onPointerUp); if (!this._disableZoom) { element.addEventListener("wheel", this.onWheel); } element.addEventListener("keydown", this.onKeyDown); element.addEventListener("touchmove", () => { }, { passive: false }); element.addEventListener("contextmenu", this.onContext); this.element.style.cursor = "grab"; this._interactionEnabled = true; this.updateTouchActionStyle(); } } disableInteraction() { if (this._interactionEnabled === true) { const { element } = this; element.removeEventListener("pointerdown", this.onPointerDown); element.removeEventListener("pointermove", this.onPointerMove); element.removeEventListener("pointerup", this.onPointerUp); element.removeEventListener("pointercancel", this.onPointerUp); element.removeEventListener("wheel", this.onWheel); element.removeEventListener("keydown", this.onKeyDown); element.removeEventListener("contextmenu", this.onContext); element.style.cursor = ""; this.touchMode = null; this._interactionEnabled = false; this.updateTouchActionStyle(); } } /** * The options that are currently configured for the controls instance. */ get options() { return this._options; } set disableZoom(disable) { if (this._disableZoom != disable) { this._disableZoom = disable; if (disable === true) { this.element.removeEventListener("wheel", this.onWheel); } else { this.element.addEventListener("wheel", this.onWheel); } this.updateTouchActionStyle(); } } /** * Copy the spherical values that represent the current camera orbital * position relative to the configured target into a provided Spherical * instance. If no Spherical is provided, a new Spherical will be allocated * to copy the values into. The Spherical that values are copied into is * returned. */ getCameraSpherical(target2 = new Spherical()) { return target2.copy(this.spherical); } /** * Returns the camera's current vertical field of view in degrees. */ getFieldOfView() { return this.camera.fov; } /** * Configure the _options of the controls. Configured _options will be * merged with whatever _options have already been configured for this * controls instance. */ applyOptions(_options) { Object.assign(this._options, _options); this.setOrbit(); this.setFieldOfView(Math.exp(this.goalLogFov)); } /** * Sets the near and far planes of the camera. */ updateNearFar(nearPlane, farPlane) { this.camera.near = Math.max(nearPlane, farPlane / 1e3); this.camera.far = farPlane; this.camera.updateProjectionMatrix(); } /** * Sets the aspect ratio of the camera */ updateAspect(aspect2) { this.camera.aspect = aspect2; this.camera.updateProjectionMatrix(); } /** * Set the absolute orbital goal of the camera. The change will be * applied over a number of frames depending on configured acceleration and * dampening _options. * * Returns true if invoking the method will result in the camera changing * position and/or rotation, otherwise false. */ setOrbit(goalTheta = this.goalSpherical.theta, goalPhi = this.goalSpherical.phi, goalRadius = this.goalSpherical.radius) { const { minimumAzimuthalAngle, maximumAzimuthalAngle, minimumPolarAngle, maximumPolarAngle, minimumRadius, maximumRadius } = this._options; const { theta, phi, radius } = this.goalSpherical; const nextTheta = clamp2(goalTheta, minimumAzimuthalAngle, maximumAzimuthalAngle); if (!isFinite(minimumAzimuthalAngle) && !isFinite(maximumAzimuthalAngle)) { this.spherical.theta = this.wrapAngle(this.spherical.theta - nextTheta) + nextTheta; } const nextPhi = clamp2(goalPhi, minimumPolarAngle, maximumPolarAngle); const nextRadius = clamp2(goalRadius, minimumRadius, maximumRadius); if (nextTheta === theta && nextPhi === phi && nextRadius === radius) { return false; } this.goalSpherical.theta = nextTheta; this.goalSpherical.phi = nextPhi; this.goalSpherical.radius = nextRadius; this.goalSpherical.makeSafe(); return true; } /** * Subset of setOrbit() above, which only sets the camera's radius. */ setRadius(radius) { this.goalSpherical.radius = radius; this.setOrbit(); } /** * Sets the goal field of view for the camera */ setFieldOfView(fov2) { const { minimumFieldOfView, maximumFieldOfView } = this._options; fov2 = clamp2(fov2, minimumFieldOfView, maximumFieldOfView); this.goalLogFov = Math.log(fov2); } /** * Sets the smoothing decay time. */ setDamperDecayTime(decayMilliseconds) { this.thetaDamper.setDecayTime(decayMilliseconds); this.phiDamper.setDecayTime(decayMilliseconds); this.radiusDamper.setDecayTime(decayMilliseconds); this.fovDamper.setDecayTime(decayMilliseconds); } /** * Adjust the orbital position of the camera relative to its current orbital * position. Does not let the theta goal get more than pi ahead of the current * theta, which ensures interpolation continues in the direction of the delta. * The deltaZoom parameter adjusts both the field of view and the orbit radius * such that they progress across their allowed ranges in sync. */ adjustOrbit(deltaTheta, deltaPhi, deltaZoom) { const { theta, phi, radius } = this.goalSpherical; const { minimumRadius, maximumRadius, minimumFieldOfView, maximumFieldOfView } = this._options; const dTheta = this.spherical.theta - theta; const dThetaLimit = Math.PI - 1e-3; const goalTheta = theta - clamp2(deltaTheta, -dThetaLimit - dTheta, dThetaLimit - dTheta); const goalPhi = phi - deltaPhi; const deltaRatio = deltaZoom === 0 ? 0 : ((deltaZoom > 0 ? maximumRadius : minimumRadius) - radius) / (Math.log(deltaZoom > 0 ? maximumFieldOfView : minimumFieldOfView) - this.goalLogFov); const goalRadius = radius + deltaZoom * (isFinite(deltaRatio) ? deltaRatio : (maximumRadius - minimumRadius) * 2); this.setOrbit(goalTheta, goalPhi, goalRadius); if (deltaZoom !== 0) { const goalLogFov = this.goalLogFov + deltaZoom; this.setFieldOfView(Math.exp(goalLogFov)); } } /** * Move the camera instantly instead of accelerating toward the goal * parameters. */ jumpToGoal() { this.update(0, SETTLING_TIME); } /** * Update controls. In most cases, this will result in the camera * interpolating its position and rotation until it lines up with the * designated goal orbital position. * * Time and delta are measured in milliseconds. */ update(_time, delta) { if (this.isStationary()) { return; } const { maximumPolarAngle, maximumRadius } = this._options; const dTheta = this.spherical.theta - this.goalSpherical.theta; if (Math.abs(dTheta) > Math.PI && !isFinite(this._options.minimumAzimuthalAngle) && !isFinite(this._options.maximumAzimuthalAngle)) { this.spherical.theta -= Math.sign(dTheta) * 2 * Math.PI; } this.spherical.theta = this.thetaDamper.update(this.spherical.theta, this.goalSpherical.theta, delta, Math.PI); this.spherical.phi = this.phiDamper.update(this.spherical.phi, this.goalSpherical.phi, delta, maximumPolarAngle); this.spherical.radius = this.radiusDamper.update(this.spherical.radius, this.goalSpherical.radius, delta, maximumRadius); this.logFov = this.fovDamper.update(this.logFov, this.goalLogFov, delta, 1); this.moveCamera(); } updateTouchActionStyle() { const { style: style2 } = this.element; if (this._interactionEnabled) { const { touchAction } = this._options; if (this._disableZoom && touchAction !== "none") { style2.touchAction = "manipulation"; } else { style2.touchAction = touchAction; } } else { style2.touchAction = ""; } } isStationary() { return this.goalSpherical.theta === this.spherical.theta && this.goalSpherical.phi === this.spherical.phi && this.goalSpherical.radius === this.spherical.radius && this.goalLogFov === this.logFov; } dispatchChange() { this.dispatchEvent({ type: "change", source: this.changeSource }); } moveCamera() { this.spherical.makeSafe(); this.camera.position.setFromSpherical(this.spherical); this.camera.setRotationFromEuler(new Euler(this.spherical.phi - Math.PI / 2, this.spherical.theta, 0, "YXZ")); if (this.camera.fov !== Math.exp(this.logFov)) { this.camera.fov = Math.exp(this.logFov); this.camera.updateProjectionMatrix(); } this.dispatchChange(); } userAdjustOrbit(deltaTheta, deltaPhi, deltaZoom) { this.adjustOrbit(deltaTheta * this.orbitSensitivity * this.inputSensitivity, deltaPhi * this.orbitSensitivity * this.inputSensitivity, deltaZoom * this.inputSensitivity); this.dispatchChange(); } // Wraps to between -pi and pi wrapAngle(radians) { const normalized = (radians + Math.PI) / (2 * Math.PI); const wrapped = normalized - Math.floor(normalized); return wrapped * 2 * Math.PI - Math.PI; } pixelLengthToSphericalAngle(pixelLength) { return 2 * Math.PI * pixelLength / this.element.clientHeight; } twoTouchDistance(touchOne, touchTwo) { const { clientX: xOne, clientY: yOne } = touchOne; const { clientX: xTwo, clientY: yTwo } = touchTwo; const xDelta = xTwo - xOne; const yDelta = yTwo - yOne; return Math.sqrt(xDelta * xDelta + yDelta * yDelta); } handleSinglePointerMove(dx, dy) { const deltaTheta = this.pixelLengthToSphericalAngle(dx); const deltaPhi = this.pixelLengthToSphericalAngle(dy); if (this.isUserPointing === false) { this.isUserPointing = true; this.dispatchEvent({ type: "pointer-change-start" }); } this.userAdjustOrbit(deltaTheta, deltaPhi, 0); } initializePan() { const { theta, phi } = this.spherical; const psi = theta - this.scene.yaw; this.panPerPixel = PAN_SENSITIVITY / this.scene.height; this.panProjection.set(-Math.cos(psi), -Math.cos(phi) * Math.sin(psi), 0, 0, Math.sin(phi), 0, Math.sin(psi), -Math.cos(phi) * Math.cos(psi), 0); } movePan(dx, dy) { const { scene } = this; const dxy = vector33.set(dx, dy, 0).multiplyScalar(this.inputSensitivity); const metersPerPixel = this.spherical.radius * Math.exp(this.logFov) * this.panPerPixel; dxy.multiplyScalar(metersPerPixel); const target2 = scene.getTarget(); target2.add(dxy.applyMatrix3(this.panProjection)); scene.boundingSphere.clampPoint(target2, target2); scene.setTarget(target2.x, target2.y, target2.z); this.dispatchChange(); } recenter(pointer) { if (performance.now() > this.startTime + TAP_MS || Math.abs(pointer.clientX - this.startPointerPosition.clientX) > TAP_DISTANCE || Math.abs(pointer.clientY - this.startPointerPosition.clientY) > TAP_DISTANCE) { return; } const { scene } = this; const hit = scene.positionAndNormalFromPoint(scene.getNDC(pointer.clientX, pointer.clientY)); if (hit == null) { const { cameraTarget } = scene.element; scene.element.cameraTarget = ""; scene.element.cameraTarget = cameraTarget; this.userAdjustOrbit(0, 0, 1); } else { scene.target.worldToLocal(hit.position); scene.setTarget(hit.position.x, hit.position.y, hit.position.z); } } resetRadius() { const { scene } = this; const hit = scene.positionAndNormalFromPoint(vector22.set(0, 0)); if (hit == null) { return; } scene.target.worldToLocal(hit.position); const goalTarget = scene.getTarget(); const { theta, phi } = this.spherical; const psi = theta - scene.yaw; const n2 = vector33.set(Math.sin(phi) * Math.sin(psi), Math.cos(phi), Math.sin(phi) * Math.cos(psi)); const dr = n2.dot(hit.position.sub(goalTarget)); goalTarget.add(n2.multiplyScalar(dr)); scene.setTarget(goalTarget.x, goalTarget.y, goalTarget.z); this.setOrbit(void 0, void 0, this.goalSpherical.radius - dr); } onTouchChange(event) { if (this.pointers.length === 1) { this.touchMode = this.touchModeRotate; } else { if (this._disableZoom) { this.touchMode = null; this.element.removeEventListener("touchmove", this.disableScroll); return; } this.touchMode = this.touchDecided && this.touchMode === null ? null : this.touchModeZoom; this.touchDecided = true; this.element.addEventListener("touchmove", this.disableScroll, { passive: false }); this.lastSeparation = this.twoTouchDistance(this.pointers[0], this.pointers[1]); if (this.enablePan && this.touchMode != null) { this.initializePan(); if (!event.altKey) { this.scene.element[$panElement].style.opacity = 1; } } } } onMouseDown(event) { this.panPerPixel = 0; if (this.enablePan && (event.button === 2 || event.ctrlKey || event.metaKey || event.shiftKey)) { this.initializePan(); this.scene.element[$panElement].style.opacity = 1; } this.element.style.cursor = "grabbing"; } /** * Handles the orbit and Zoom key presses * Uses constants for the increment. * @param event The keyboard event for the .key value * @returns boolean to indicate if the key event has been handled */ orbitZoomKeyCodeHandler(event) { let relevantKey = true; switch (event.key) { case "PageUp": this.userAdjustOrbit(0, 0, ZOOM_SENSITIVITY); break; case "PageDown": this.userAdjustOrbit(0, 0, -1 * ZOOM_SENSITIVITY); break; case "ArrowUp": this.userAdjustOrbit(0, -KEYBOARD_ORBIT_INCREMENT, 0); break; case "ArrowDown": this.userAdjustOrbit(0, KEYBOARD_ORBIT_INCREMENT, 0); break; case "ArrowLeft": this.userAdjustOrbit(-KEYBOARD_ORBIT_INCREMENT, 0, 0); break; case "ArrowRight": this.userAdjustOrbit(KEYBOARD_ORBIT_INCREMENT, 0, 0); break; default: relevantKey = false; break; } return relevantKey; } /** * Handles the Pan key presses * Uses constants for the increment. * @param event The keyboard event for the .key value * @returns boolean to indicate if the key event has been handled */ panKeyCodeHandler(event) { this.initializePan(); let relevantKey = true; switch (event.key) { case "ArrowUp": this.movePan(0, -1 * PAN_KEY_INCREMENT); break; case "ArrowDown": this.movePan(0, PAN_KEY_INCREMENT); break; case "ArrowLeft": this.movePan(-1 * PAN_KEY_INCREMENT, 0); break; case "ArrowRight": this.movePan(PAN_KEY_INCREMENT, 0); break; default: relevantKey = false; break; } return relevantKey; } }; // node_modules/@google/model-viewer/lib/utilities/animation.js var easeInOutQuad = (t2) => t2 < 0.5 ? 2 * t2 * t2 : -1 + (4 - 2 * t2) * t2; var interpolate = (start, end, ease = easeInOutQuad) => (time) => start + (end - start) * ease(time); var sequence = (tracks, weights) => { const cumulativeSum = (sum) => (value) => sum += value; const times = weights.map(cumulativeSum(0)); return (time) => { time = clamp2(time, 0, 1); time *= times[times.length - 1]; const i = times.findIndex((val) => val >= time); const start = i < 1 ? 0 : times[i - 1]; const end = times[i]; return tracks[i]((time - start) / (end - start)); }; }; var timeline = (path) => { const tracks = []; const weights = []; let lastValue = path.initialValue; for (let i = 0; i < path.keyframes.length; ++i) { const keyframe = path.keyframes[i]; const { value, frames } = keyframe; const ease = keyframe.ease || easeInOutQuad; const track = interpolate(lastValue, value, ease); tracks.push(track); weights.push(frames); lastValue = value; } return sequence(tracks, weights); }; // node_modules/@google/model-viewer/lib/features/controls.js var __decorate6 = function(decorators, target2, key, desc) { var c = arguments.length, r = c < 3 ? target2 : desc === null ? desc = Object.getOwnPropertyDescriptor(target2, key) : desc, d; if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target2, key, desc); else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target2, key, r) : d(target2, key)) || r; return c > 3 && r && Object.defineProperty(target2, key, r), r; }; var PROMPT_ANIMATION_TIME = 5e3; var wiggle = timeline({ initialValue: 0, keyframes: [ { frames: 5, value: -1 }, { frames: 1, value: -1 }, { frames: 8, value: 1 }, { frames: 1, value: 1 }, { frames: 5, value: 0 }, { frames: 18, value: 0 } ] }); var fade = timeline({ initialValue: 0, keyframes: [ { frames: 1, value: 1 }, { frames: 5, value: 1 }, { frames: 1, value: 0 }, { frames: 6, value: 0 } ] }); var DEFAULT_FOV_DEG = 30; var DEFAULT_MIN_FOV_DEG = 12; var DEFAULT_CAMERA_ORBIT = "0deg 75deg 105%"; var DEFAULT_CAMERA_TARGET = "auto auto auto"; var DEFAULT_FIELD_OF_VIEW = "auto"; var MINIMUM_RADIUS_RATIO = 2.2; var AZIMUTHAL_QUADRANT_LABELS = ["front", "right", "back", "left"]; var POLAR_TRIENT_LABELS = ["upper-", "", "lower-"]; var DEFAULT_INTERACTION_PROMPT_THRESHOLD = 3e3; var INTERACTION_PROMPT = ". Use mouse, touch or arrow keys to move."; var InteractionPromptStrategy = { AUTO: "auto", NONE: "none" }; var InteractionPromptStyle = { BASIC: "basic", WIGGLE: "wiggle" }; var TouchAction = { PAN_Y: "pan-y", PAN_X: "pan-x", NONE: "none" }; var fieldOfViewIntrinsics = () => { return { basis: [degreesToRadians(numberNode(DEFAULT_FOV_DEG, "deg"))], keywords: { auto: [null] } }; }; var minFieldOfViewIntrinsics = () => { return { basis: [degreesToRadians(numberNode(DEFAULT_MIN_FOV_DEG, "deg"))], keywords: { auto: [null] } }; }; var cameraOrbitIntrinsics = (() => { const defaultTerms = parseExpressions(DEFAULT_CAMERA_ORBIT)[0].terms; const theta = normalizeUnit(defaultTerms[0]); const phi = normalizeUnit(defaultTerms[1]); return (element) => { const radius = element[$scene].idealCameraDistance(); return { basis: [theta, phi, numberNode(radius, "m")], keywords: { auto: [null, null, numberNode(105, "%")] } }; }; })(); var minCameraOrbitIntrinsics = (element) => { const radius = MINIMUM_RADIUS_RATIO * element[$scene].boundingSphere.radius; return { basis: [ numberNode(-Infinity, "rad"), numberNode(Math.PI / 8, "rad"), numberNode(radius, "m") ], keywords: { auto: [null, null, null] } }; }; var maxCameraOrbitIntrinsics = (element) => { const orbitIntrinsics = cameraOrbitIntrinsics(element); const evaluator = new StyleEvaluator([], orbitIntrinsics); const defaultRadius = evaluator.evaluate()[2]; return { basis: [ numberNode(Infinity, "rad"), numberNode(Math.PI - Math.PI / 8, "rad"), numberNode(defaultRadius, "m") ], keywords: { auto: [null, null, null] } }; }; var cameraTargetIntrinsics = (element) => { const center = element[$scene].boundingBox.getCenter(new Vector3()); return { basis: [ numberNode(center.x, "m"), numberNode(center.y, "m"), numberNode(center.z, "m") ], keywords: { auto: [null, null, null] } }; }; var HALF_PI = Math.PI / 2; var THIRD_PI = Math.PI / 3; var QUARTER_PI = HALF_PI / 2; var TAU = 2 * Math.PI; var $controls = Symbol("controls"); var $panElement = Symbol("panElement"); var $promptElement = Symbol("promptElement"); var $promptAnimatedContainer = Symbol("promptAnimatedContainer"); var $fingerAnimatedContainers = Symbol("fingerAnimatedContainers"); var $deferInteractionPrompt = Symbol("deferInteractionPrompt"); var $updateAria = Symbol("updateAria"); var $updateCameraForRadius = Symbol("updateCameraForRadius"); var $onChange = Symbol("onChange"); var $onPointerChange = Symbol("onPointerChange"); var $waitingToPromptUser = Symbol("waitingToPromptUser"); var $userHasInteracted = Symbol("userHasInteracted"); var $promptElementVisibleTime = Symbol("promptElementVisibleTime"); var $lastPromptOffset = Symbol("lastPromptOffset"); var $lastSpherical = Symbol("lastSpherical"); var $jumpCamera = Symbol("jumpCamera"); var $initialized = Symbol("initialized"); var $maintainThetaPhi = Symbol("maintainThetaPhi"); var $syncCameraOrbit = Symbol("syncCameraOrbit"); var $syncFieldOfView = Symbol("syncFieldOfView"); var $syncCameraTarget = Symbol("syncCameraTarget"); var $syncMinCameraOrbit = Symbol("syncMinCameraOrbit"); var $syncMaxCameraOrbit = Symbol("syncMaxCameraOrbit"); var $syncMinFieldOfView = Symbol("syncMinFieldOfView"); var $syncMaxFieldOfView = Symbol("syncMaxFieldOfView"); var ControlsMixin = (ModelViewerElement2) => { var _a12, _b11, _c6, _d5, _e4, _f4, _g2, _h2, _j2, _k2, _l2, _m2, _o2, _p, _q2; class ControlsModelViewerElement extends ModelViewerElement2 { constructor() { super(...arguments); this.cameraControls = false; this.cameraOrbit = DEFAULT_CAMERA_ORBIT; this.cameraTarget = DEFAULT_CAMERA_TARGET; this.fieldOfView = DEFAULT_FIELD_OF_VIEW; this.minCameraOrbit = "auto"; this.maxCameraOrbit = "auto"; this.minFieldOfView = "auto"; this.maxFieldOfView = "auto"; this.interactionPromptThreshold = DEFAULT_INTERACTION_PROMPT_THRESHOLD; this.interactionPrompt = InteractionPromptStrategy.AUTO; this.interactionPromptStyle = InteractionPromptStyle.WIGGLE; this.orbitSensitivity = 1; this.touchAction = TouchAction.NONE; this.disableZoom = false; this.disablePan = false; this.disableTap = false; this.interpolationDecay = DECAY_MILLISECONDS; this[_a12] = this.shadowRoot.querySelector(".interaction-prompt"); this[_b11] = this.shadowRoot.querySelector("#prompt"); this[_c6] = [ this.shadowRoot.querySelector("#finger0"), this.shadowRoot.querySelector("#finger1") ]; this[_d5] = this.shadowRoot.querySelector(".pan-target"); this[_e4] = 0; this[_f4] = Infinity; this[_g2] = false; this[_h2] = false; this[_j2] = new SmoothControls(this[$scene].camera, this[$userInputElement], this[$scene]); this[_k2] = new Spherical(); this[_l2] = false; this[_m2] = false; this[_o2] = false; this[_p] = ({ source }) => { this[$updateAria](); this[$needsRender](); if (source === ChangeSource.USER_INTERACTION) { this[$userHasInteracted] = true; this[$deferInteractionPrompt](); } this.dispatchEvent(new CustomEvent("camera-change", { detail: { source } })); }; this[_q2] = (event) => { if (event.type === "pointer-change-start") { this[$container].classList.add("pointer-tumbling"); } else { this[$container].classList.remove("pointer-tumbling"); } }; } get inputSensitivity() { return this[$controls].inputSensitivity; } set inputSensitivity(value) { this[$controls].inputSensitivity = value; } getCameraOrbit() { const { theta, phi, radius } = this[$lastSpherical]; return { theta, phi, radius, toString() { return `${this.theta}rad ${this.phi}rad ${this.radius}m`; } }; } getCameraTarget() { return toVector3D(this[$renderer].isPresenting ? this[$renderer].arRenderer.target : this[$scene].getTarget()); } getFieldOfView() { return this[$controls].getFieldOfView(); } // Provided so user code does not have to parse these from attributes. getMinimumFieldOfView() { return this[$controls].options.minimumFieldOfView; } getMaximumFieldOfView() { return this[$controls].options.maximumFieldOfView; } getIdealAspect() { return this[$scene].idealAspect; } jumpCameraToGoal() { this[$jumpCamera] = true; this.requestUpdate($jumpCamera, false); } resetInteractionPrompt() { this[$lastPromptOffset] = 0; this[$promptElementVisibleTime] = Infinity; this[$userHasInteracted] = false; this[$waitingToPromptUser] = this.interactionPrompt === InteractionPromptStrategy.AUTO && this.cameraControls; } zoom(keyPresses) { const event = new WheelEvent("wheel", { deltaY: -30 * keyPresses }); this[$userInputElement].dispatchEvent(event); } connectedCallback() { super.connectedCallback(); this[$controls].addEventListener("change", this[$onChange]); this[$controls].addEventListener("pointer-change-start", this[$onPointerChange]); this[$controls].addEventListener("pointer-change-end", this[$onPointerChange]); } disconnectedCallback() { super.disconnectedCallback(); this[$controls].removeEventListener("change", this[$onChange]); this[$controls].removeEventListener("pointer-change-start", this[$onPointerChange]); this[$controls].removeEventListener("pointer-change-end", this[$onPointerChange]); } updated(changedProperties) { super.updated(changedProperties); const controls = this[$controls]; const scene = this[$scene]; if (changedProperties.has("cameraControls")) { if (this.cameraControls) { controls.enableInteraction(); if (this.interactionPrompt === InteractionPromptStrategy.AUTO) { this[$waitingToPromptUser] = true; } } else { controls.disableInteraction(); this[$deferInteractionPrompt](); } this[$userInputElement].setAttribute("aria-label", this[$ariaLabel]); } if (changedProperties.has("disableZoom")) { controls.disableZoom = this.disableZoom; } if (changedProperties.has("disablePan")) { controls.enablePan = !this.disablePan; } if (changedProperties.has("disableTap")) { controls.enableTap = !this.disableTap; } if (changedProperties.has("interactionPrompt") || changedProperties.has("cameraControls") || changedProperties.has("src")) { if (this.interactionPrompt === InteractionPromptStrategy.AUTO && this.cameraControls && !this[$userHasInteracted]) { this[$waitingToPromptUser] = true; } else { this[$deferInteractionPrompt](); } } if (changedProperties.has("interactionPromptStyle")) { this[$promptAnimatedContainer].style.opacity = this.interactionPromptStyle == InteractionPromptStyle.BASIC ? "1" : "0"; } if (changedProperties.has("touchAction")) { const touchAction = this.touchAction; controls.applyOptions({ touchAction }); controls.updateTouchActionStyle(); } if (changedProperties.has("orbitSensitivity")) { controls.orbitSensitivity = this.orbitSensitivity; } if (changedProperties.has("interpolationDecay")) { controls.setDamperDecayTime(this.interpolationDecay); scene.setTargetDamperDecayTime(this.interpolationDecay); } if (this[$jumpCamera] === true) { Promise.resolve().then(() => { controls.jumpToGoal(); scene.jumpToGoal(); this[$jumpCamera] = false; }); } } async updateFraming() { const scene = this[$scene]; const oldFramedFoV = scene.adjustedFoV(scene.framedFoVDeg); await scene.updateFraming(); const newFramedFoV = scene.adjustedFoV(scene.framedFoVDeg); const zoom = this[$controls].getFieldOfView() / oldFramedFoV; this[$controls].setFieldOfView(newFramedFoV * zoom); this[$maintainThetaPhi] = true; this.requestUpdate("maxFieldOfView"); this.requestUpdate("fieldOfView"); this.requestUpdate("minCameraOrbit"); this.requestUpdate("maxCameraOrbit"); this.requestUpdate("cameraOrbit"); await this.updateComplete; } interact(duration, finger0, finger1) { const inputElement = this[$userInputElement]; const fingerElements = this[$fingerAnimatedContainers]; if (fingerElements[0].style.opacity === "1") { console.warn("interact() failed because an existing interaction is running."); return; } const xy = new Array(); xy.push({ x: timeline(finger0.x), y: timeline(finger0.y) }); const positions = [{ x: xy[0].x(0), y: xy[0].y(0) }]; if (finger1 != null) { xy.push({ x: timeline(finger1.x), y: timeline(finger1.y) }); positions.push({ x: xy[1].x(0), y: xy[1].y(0) }); } let startTime = performance.now(); const { width, height } = this[$scene]; const dispatchTouches = (type) => { for (const [i, position] of positions.entries()) { const { style: style2 } = fingerElements[i]; style2.transform = `translateX(${width * position.x}px) translateY(${height * position.y}px)`; if (type === "pointerdown") { style2.opacity = "1"; } else if (type === "pointerup") { style2.opacity = "0"; } const init = { pointerId: i - 5678, pointerType: "touch", target: inputElement, clientX: width * position.x, clientY: height * position.y, altKey: true // flag that this is not a user interaction }; inputElement.dispatchEvent(new PointerEvent(type, init)); } }; const moveTouches = () => { const { changeSource } = this[$controls]; if (changeSource !== ChangeSource.AUTOMATIC || !inputElement.isConnected) { for (const fingerElement of this[$fingerAnimatedContainers]) { fingerElement.style.opacity = "0"; } dispatchTouches("pointercancel"); this.dispatchEvent(new CustomEvent("interact-stopped", { detail: { source: changeSource } })); document.removeEventListener("visibilitychange", onVisibilityChange); return; } const time = Math.min(1, (performance.now() - startTime) / duration); for (const [i, position] of positions.entries()) { position.x = xy[i].x(time); position.y = xy[i].y(time); } dispatchTouches("pointermove"); if (time < 1) { requestAnimationFrame(moveTouches); } else { dispatchTouches("pointerup"); this.dispatchEvent(new CustomEvent("interact-stopped", { detail: { source: changeSource } })); document.removeEventListener("visibilitychange", onVisibilityChange); } }; const onVisibilityChange = () => { let elapsed = 0; if (document.visibilityState === "hidden") { elapsed = performance.now() - startTime; } else { startTime = performance.now() - elapsed; } }; document.addEventListener("visibilitychange", onVisibilityChange); dispatchTouches("pointerdown"); requestAnimationFrame(moveTouches); } [(_a12 = $promptElement, _b11 = $promptAnimatedContainer, _c6 = $fingerAnimatedContainers, _d5 = $panElement, _e4 = $lastPromptOffset, _f4 = $promptElementVisibleTime, _g2 = $userHasInteracted, _h2 = $waitingToPromptUser, _j2 = $controls, _k2 = $lastSpherical, _l2 = $jumpCamera, _m2 = $initialized, _o2 = $maintainThetaPhi, $syncFieldOfView)](style2) { const scene = this[$scene]; scene.framedFoVDeg = style2[0] * 180 / Math.PI; this[$controls].setFieldOfView(scene.adjustedFoV(scene.framedFoVDeg)); } [$syncCameraOrbit](style2) { const controls = this[$controls]; if (this[$maintainThetaPhi]) { const { theta, phi } = this.getCameraOrbit(); style2[0] = theta; style2[1] = phi; this[$maintainThetaPhi] = false; } controls.changeSource = ChangeSource.NONE; controls.setOrbit(style2[0], style2[1], style2[2]); } [$syncMinCameraOrbit](style2) { this[$controls].applyOptions({ minimumAzimuthalAngle: style2[0], minimumPolarAngle: style2[1], minimumRadius: style2[2] }); this.jumpCameraToGoal(); } [$syncMaxCameraOrbit](style2) { this[$controls].applyOptions({ maximumAzimuthalAngle: style2[0], maximumPolarAngle: style2[1], maximumRadius: style2[2] }); this[$updateCameraForRadius](style2[2]); this.jumpCameraToGoal(); } [$syncMinFieldOfView](style2) { this[$controls].applyOptions({ minimumFieldOfView: style2[0] * 180 / Math.PI }); this.jumpCameraToGoal(); } [$syncMaxFieldOfView](style2) { const fov2 = this[$scene].adjustedFoV(style2[0] * 180 / Math.PI); this[$controls].applyOptions({ maximumFieldOfView: fov2 }); this.jumpCameraToGoal(); } [$syncCameraTarget](style2) { const [x2, y, z] = style2; if (!this[$renderer].arRenderer.isPresenting) { this[$scene].setTarget(x2, y, z); } this[$controls].changeSource = ChangeSource.NONE; this[$renderer].arRenderer.updateTarget(); } [$tick](time, delta) { super[$tick](time, delta); if (this[$renderer].isPresenting || !this[$getModelIsVisible]()) { return; } const controls = this[$controls]; const scene = this[$scene]; const now = performance.now(); if (this[$waitingToPromptUser]) { if (this.loaded && now > this[$loadedTime] + this.interactionPromptThreshold) { this[$waitingToPromptUser] = false; this[$promptElementVisibleTime] = now; this[$promptElement].classList.add("visible"); } } if (isFinite(this[$promptElementVisibleTime]) && this.interactionPromptStyle === InteractionPromptStyle.WIGGLE) { const animationTime = (now - this[$promptElementVisibleTime]) / PROMPT_ANIMATION_TIME % 1; const offset = wiggle(animationTime); const opacity = fade(animationTime); this[$promptAnimatedContainer].style.opacity = `${opacity}`; if (offset !== this[$lastPromptOffset]) { const xOffset = offset * scene.width * 0.05; const deltaTheta = (offset - this[$lastPromptOffset]) * Math.PI / 16; this[$promptAnimatedContainer].style.transform = `translateX(${xOffset}px)`; controls.changeSource = ChangeSource.AUTOMATIC; controls.adjustOrbit(deltaTheta, 0, 0); this[$lastPromptOffset] = offset; } } controls.update(time, delta); if (scene.updateTarget(delta)) { this[$onChange]({ type: "change", source: controls.changeSource }); } } [$deferInteractionPrompt]() { this[$waitingToPromptUser] = false; this[$promptElement].classList.remove("visible"); this[$promptElementVisibleTime] = Infinity; } /** * Updates the camera's near and far planes to enclose the scene when * orbiting at the supplied radius. */ [$updateCameraForRadius](radius) { const maximumRadius = Math.max(this[$scene].boundingSphere.radius, radius); const near = 0; const far = 2 * maximumRadius; this[$controls].updateNearFar(near, far); } [$updateAria]() { const { theta, phi } = this[$controls].getCameraSpherical(this[$lastSpherical]); const azimuthalQuadrant = (4 + Math.floor((theta % TAU + QUARTER_PI) / HALF_PI)) % 4; const polarTrient = Math.floor(phi / THIRD_PI); const azimuthalQuadrantLabel = AZIMUTHAL_QUADRANT_LABELS[azimuthalQuadrant]; const polarTrientLabel = POLAR_TRIENT_LABELS[polarTrient]; this[$updateStatus](`View from stage ${polarTrientLabel}${azimuthalQuadrantLabel}`); } get [$ariaLabel]() { return super[$ariaLabel] + (this.cameraControls ? INTERACTION_PROMPT : ""); } async [$onResize](event) { const controls = this[$controls]; const scene = this[$scene]; const oldFramedFoV = scene.adjustedFoV(scene.framedFoVDeg); super[$onResize](event); const fovRatio = scene.adjustedFoV(scene.framedFoVDeg) / oldFramedFoV; const fov2 = controls.getFieldOfView() * (isFinite(fovRatio) ? fovRatio : 1); controls.updateAspect(this[$scene].aspect); this.requestUpdate("maxFieldOfView", this.maxFieldOfView); await this.updateComplete; this[$controls].setFieldOfView(fov2); this.jumpCameraToGoal(); } [$onModelLoad]() { super[$onModelLoad](); if (this[$initialized]) { this[$maintainThetaPhi] = true; } else { this[$initialized] = true; } this.requestUpdate("maxFieldOfView", this.maxFieldOfView); this.requestUpdate("fieldOfView", this.fieldOfView); this.requestUpdate("minCameraOrbit", this.minCameraOrbit); this.requestUpdate("maxCameraOrbit", this.maxCameraOrbit); this.requestUpdate("cameraOrbit", this.cameraOrbit); this.requestUpdate("cameraTarget", this.cameraTarget); this.jumpCameraToGoal(); } } _p = $onChange, _q2 = $onPointerChange; __decorate6([ property({ type: Boolean, attribute: "camera-controls" }) ], ControlsModelViewerElement.prototype, "cameraControls", void 0); __decorate6([ style({ intrinsics: cameraOrbitIntrinsics, observeEffects: true, updateHandler: $syncCameraOrbit }), property({ type: String, attribute: "camera-orbit", hasChanged: () => true }) ], ControlsModelViewerElement.prototype, "cameraOrbit", void 0); __decorate6([ style({ intrinsics: cameraTargetIntrinsics, observeEffects: true, updateHandler: $syncCameraTarget }), property({ type: String, attribute: "camera-target", hasChanged: () => true }) ], ControlsModelViewerElement.prototype, "cameraTarget", void 0); __decorate6([ style({ intrinsics: fieldOfViewIntrinsics, observeEffects: true, updateHandler: $syncFieldOfView }), property({ type: String, attribute: "field-of-view", hasChanged: () => true }) ], ControlsModelViewerElement.prototype, "fieldOfView", void 0); __decorate6([ style({ intrinsics: minCameraOrbitIntrinsics, updateHandler: $syncMinCameraOrbit }), property({ type: String, attribute: "min-camera-orbit", hasChanged: () => true }) ], ControlsModelViewerElement.prototype, "minCameraOrbit", void 0); __decorate6([ style({ intrinsics: maxCameraOrbitIntrinsics, updateHandler: $syncMaxCameraOrbit }), property({ type: String, attribute: "max-camera-orbit", hasChanged: () => true }) ], ControlsModelViewerElement.prototype, "maxCameraOrbit", void 0); __decorate6([ style({ intrinsics: minFieldOfViewIntrinsics, updateHandler: $syncMinFieldOfView }), property({ type: String, attribute: "min-field-of-view", hasChanged: () => true }) ], ControlsModelViewerElement.prototype, "minFieldOfView", void 0); __decorate6([ style({ intrinsics: fieldOfViewIntrinsics, updateHandler: $syncMaxFieldOfView }), property({ type: String, attribute: "max-field-of-view", hasChanged: () => true }) ], ControlsModelViewerElement.prototype, "maxFieldOfView", void 0); __decorate6([ property({ type: Number, attribute: "interaction-prompt-threshold" }) ], ControlsModelViewerElement.prototype, "interactionPromptThreshold", void 0); __decorate6([ property({ type: String, attribute: "interaction-prompt" }) ], ControlsModelViewerElement.prototype, "interactionPrompt", void 0); __decorate6([ property({ type: String, attribute: "interaction-prompt-style" }) ], ControlsModelViewerElement.prototype, "interactionPromptStyle", void 0); __decorate6([ property({ type: Number, attribute: "orbit-sensitivity" }) ], ControlsModelViewerElement.prototype, "orbitSensitivity", void 0); __decorate6([ property({ type: String, attribute: "touch-action" }) ], ControlsModelViewerElement.prototype, "touchAction", void 0); __decorate6([ property({ type: Boolean, attribute: "disable-zoom" }) ], ControlsModelViewerElement.prototype, "disableZoom", void 0); __decorate6([ property({ type: Boolean, attribute: "disable-pan" }) ], ControlsModelViewerElement.prototype, "disablePan", void 0); __decorate6([ property({ type: Boolean, attribute: "disable-tap" }) ], ControlsModelViewerElement.prototype, "disableTap", void 0); __decorate6([ property({ type: Number, attribute: "interpolation-decay" }) ], ControlsModelViewerElement.prototype, "interpolationDecay", void 0); return ControlsModelViewerElement; }; // node_modules/@google/model-viewer/lib/features/loading.js var __decorate7 = function(decorators, target2, key, desc) { var c = arguments.length, r = c < 3 ? target2 : desc === null ? desc = Object.getOwnPropertyDescriptor(target2, key) : desc, d; if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target2, key, desc); else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target2, key, r) : d(target2, key)) || r; return c > 3 && r && Object.defineProperty(target2, key, r), r; }; var PROGRESS_BAR_UPDATE_THRESHOLD = 100; var DEFAULT_DRACO_DECODER_LOCATION = "https://www.gstatic.com/draco/versioned/decoders/1.4.1/"; var DEFAULT_KTX2_TRANSCODER_LOCATION = "https://www.gstatic.com/basis-universal/versioned/2021-04-15-ba1c3e4/"; var RevealStrategy = { AUTO: "auto", MANUAL: "manual" }; var LoadingStrategy = { AUTO: "auto", LAZY: "lazy", EAGER: "eager" }; var $defaultProgressBarElement = Symbol("defaultProgressBarElement"); var $posterContainerElement = Symbol("posterContainerElement"); var $defaultPosterElement = Symbol("defaultPosterElement"); var $shouldDismissPoster = Symbol("shouldDismissPoster"); var $hidePoster = Symbol("hidePoster"); var $modelIsRevealed = Symbol("modelIsRevealed"); var $updateProgressBar = Symbol("updateProgressBar"); var $ariaLabelCallToAction = Symbol("ariaLabelCallToAction"); var $onProgress = Symbol("onProgress"); var LoadingMixin = (ModelViewerElement2) => { var _a12, _b11, _c6, _d5, _e4, _f4, _g2, _h2; class LoadingModelViewerElement extends ModelViewerElement2 { constructor(...args) { super(...args); this.poster = null; this.reveal = RevealStrategy.AUTO; this.loading = LoadingStrategy.AUTO; this[_a12] = false; this[_b11] = false; this[_c6] = this.shadowRoot.querySelector(".slot.poster"); this[_d5] = this.shadowRoot.querySelector("#default-poster"); this[_e4] = this.shadowRoot.querySelector("#default-progress-bar > .bar"); this[_f4] = this[$defaultPosterElement].getAttribute("aria-label"); this[_g2] = throttle((progress) => { const parentNode = this[$defaultProgressBarElement].parentNode; requestAnimationFrame(() => { this[$defaultProgressBarElement].style.transform = `scaleX(${progress})`; if (progress === 0) { parentNode.removeChild(this[$defaultProgressBarElement]); parentNode.appendChild(this[$defaultProgressBarElement]); } if (progress === 1) { this[$defaultProgressBarElement].classList.add("hide"); } else { this[$defaultProgressBarElement].classList.remove("hide"); } }); }, PROGRESS_BAR_UPDATE_THRESHOLD); this[_h2] = (event) => { const progress = event.detail.totalProgress; if (progress === 1) { this[$updateProgressBar].flush(); if (this.loaded && (this[$shouldDismissPoster] || this.reveal === RevealStrategy.AUTO)) { this[$hidePoster](); } } this[$updateProgressBar](progress); this.dispatchEvent(new CustomEvent("progress", { detail: { totalProgress: progress } })); }; const ModelViewerElement3 = self.ModelViewerElement || {}; const dracoDecoderLocation2 = ModelViewerElement3.dracoDecoderLocation || DEFAULT_DRACO_DECODER_LOCATION; CachingGLTFLoader.setDRACODecoderLocation(dracoDecoderLocation2); const ktx2TranscoderLocation2 = ModelViewerElement3.ktx2TranscoderLocation || DEFAULT_KTX2_TRANSCODER_LOCATION; CachingGLTFLoader.setKTX2TranscoderLocation(ktx2TranscoderLocation2); if (ModelViewerElement3.meshoptDecoderLocation) { CachingGLTFLoader.setMeshoptDecoderLocation(ModelViewerElement3.meshoptDecoderLocation); } } static set dracoDecoderLocation(value) { CachingGLTFLoader.setDRACODecoderLocation(value); } static get dracoDecoderLocation() { return CachingGLTFLoader.getDRACODecoderLocation(); } static set ktx2TranscoderLocation(value) { CachingGLTFLoader.setKTX2TranscoderLocation(value); } static get ktx2TranscoderLocation() { return CachingGLTFLoader.getKTX2TranscoderLocation(); } static set meshoptDecoderLocation(value) { CachingGLTFLoader.setMeshoptDecoderLocation(value); } static get meshoptDecoderLocation() { return CachingGLTFLoader.getMeshoptDecoderLocation(); } /** * If provided, the callback will be passed each resource URL before a * request is sent. The callback may return the original URL, or a new URL * to override loading behavior. This behavior can be used to load assets * from .ZIP files, drag-and-drop APIs, and Data URIs. */ static mapURLs(callback) { Renderer.singleton.loader[$loader].manager.setURLModifier(callback); } /** * Dismisses the poster, causing the model to load and render if * necessary. This is currently effectively the same as interacting with * the poster via user input. */ dismissPoster() { if (this.loaded) { this[$hidePoster](); } else { this[$shouldDismissPoster] = true; this[$updateSource](); } } /** * Displays the poster, hiding the 3D model. If this is called after the 3D * model has been revealed, then it must be dismissed by a call to * dismissPoster(). */ showPoster() { const posterContainerElement = this[$posterContainerElement]; if (posterContainerElement.classList.contains("show")) { return; } posterContainerElement.classList.add("show"); this[$userInputElement].classList.remove("show"); const defaultPosterElement = this[$defaultPosterElement]; defaultPosterElement.removeAttribute("tabindex"); defaultPosterElement.removeAttribute("aria-hidden"); const oldVisibility = this.modelIsVisible; this[$modelIsRevealed] = false; this[$announceModelVisibility](oldVisibility); } /** * Returns the model's bounding box dimensions in meters, independent of * turntable rotation. */ getDimensions() { return toVector3D(this[$scene].size); } getBoundingBoxCenter() { return toVector3D(this[$scene].boundingBox.getCenter(new Vector3())); } connectedCallback() { super.connectedCallback(); this.showPoster(); this[$progressTracker].addEventListener("progress", this[$onProgress]); } disconnectedCallback() { super.disconnectedCallback(); this[$progressTracker].removeEventListener("progress", this[$onProgress]); } async updated(changedProperties) { super.updated(changedProperties); if (changedProperties.has("poster") && this.poster != null) { this[$defaultPosterElement].style.backgroundImage = `url(${this.poster})`; } if (changedProperties.has("alt")) { this[$defaultPosterElement].setAttribute("aria-label", this[$altDefaulted]); } if (changedProperties.has("reveal") || changedProperties.has("loading")) { this[$updateSource](); } } [(_a12 = $modelIsRevealed, _b11 = $shouldDismissPoster, _c6 = $posterContainerElement, _d5 = $defaultPosterElement, _e4 = $defaultProgressBarElement, _f4 = $ariaLabelCallToAction, _g2 = $updateProgressBar, _h2 = $onProgress, $shouldAttemptPreload)]() { return !!this.src && (this[$shouldDismissPoster] || this.loading === LoadingStrategy.EAGER || this.reveal === RevealStrategy.AUTO && this[$isElementInViewport]); } [$hidePoster]() { this[$shouldDismissPoster] = false; const posterContainerElement = this[$posterContainerElement]; if (!posterContainerElement.classList.contains("show")) { return; } posterContainerElement.classList.remove("show"); this[$userInputElement].classList.add("show"); const oldVisibility = this.modelIsVisible; this[$modelIsRevealed] = true; this[$announceModelVisibility](oldVisibility); const root = this.getRootNode(); if (root && root.activeElement === this) { this[$userInputElement].focus(); } const defaultPosterElement = this[$defaultPosterElement]; defaultPosterElement.setAttribute("aria-hidden", "true"); defaultPosterElement.tabIndex = -1; this.dispatchEvent(new CustomEvent("poster-dismissed")); } [$getModelIsVisible]() { return super[$getModelIsVisible]() && this[$modelIsRevealed]; } } __decorate7([ property({ type: String }) ], LoadingModelViewerElement.prototype, "poster", void 0); __decorate7([ property({ type: String }) ], LoadingModelViewerElement.prototype, "reveal", void 0); __decorate7([ property({ type: String }) ], LoadingModelViewerElement.prototype, "loading", void 0); return LoadingModelViewerElement; }; // node_modules/@google/model-viewer/lib/features/staging.js var __decorate8 = function(decorators, target2, key, desc) { var c = arguments.length, r = c < 3 ? target2 : desc === null ? desc = Object.getOwnPropertyDescriptor(target2, key) : desc, d; if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target2, key, desc); else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target2, key, r) : d(target2, key)) || r; return c > 3 && r && Object.defineProperty(target2, key, r), r; }; var DEFAULT_ROTATION_SPEED = Math.PI / 32; var AUTO_ROTATE_DELAY_DEFAULT = 3e3; var rotationRateIntrinsics = { basis: [degreesToRadians(numberNode(DEFAULT_ROTATION_SPEED, "rad"))], keywords: { auto: [null] } }; var $autoRotateStartTime = Symbol("autoRotateStartTime"); var $radiansPerSecond = Symbol("radiansPerSecond"); var $syncRotationRate = Symbol("syncRotationRate"); var $onCameraChange = Symbol("onCameraChange"); var StagingMixin = (ModelViewerElement2) => { var _a12, _b11, _c6; class StagingModelViewerElement extends ModelViewerElement2 { constructor() { super(...arguments); this.autoRotate = false; this.autoRotateDelay = AUTO_ROTATE_DELAY_DEFAULT; this.rotationPerSecond = "auto"; this[_a12] = performance.now(); this[_b11] = 0; this[_c6] = (event) => { if (!this.autoRotate) { return; } if (event.detail.source === "user-interaction") { this[$autoRotateStartTime] = performance.now(); } }; } connectedCallback() { super.connectedCallback(); this.addEventListener("camera-change", this[$onCameraChange]); this[$autoRotateStartTime] = performance.now(); } disconnectedCallback() { super.disconnectedCallback(); this.removeEventListener("camera-change", this[$onCameraChange]); this[$autoRotateStartTime] = performance.now(); } updated(changedProperties) { super.updated(changedProperties); if (changedProperties.has("autoRotate")) { this[$autoRotateStartTime] = performance.now(); } } [(_a12 = $autoRotateStartTime, _b11 = $radiansPerSecond, $syncRotationRate)](style2) { this[$radiansPerSecond] = style2[0]; } [$tick](time, delta) { super[$tick](time, delta); if (!this.autoRotate || !this[$getModelIsVisible]() || this[$renderer].isPresenting) { return; } const rotationDelta = Math.min(delta, time - this[$autoRotateStartTime] - this.autoRotateDelay); if (rotationDelta > 0) { this[$scene].yaw = this.turntableRotation + this[$radiansPerSecond] * rotationDelta * 1e-3; } } get turntableRotation() { return this[$scene].yaw; } resetTurntableRotation(theta = 0) { this[$scene].yaw = theta; } } _c6 = $onCameraChange; __decorate8([ property({ type: Boolean, attribute: "auto-rotate" }) ], StagingModelViewerElement.prototype, "autoRotate", void 0); __decorate8([ property({ type: Number, attribute: "auto-rotate-delay" }) ], StagingModelViewerElement.prototype, "autoRotateDelay", void 0); __decorate8([ style({ intrinsics: rotationRateIntrinsics, updateHandler: $syncRotationRate }), property({ type: String, attribute: "rotation-per-second" }) ], StagingModelViewerElement.prototype, "rotationPerSecond", void 0); return StagingModelViewerElement; }; // node_modules/@google/model-viewer/lib/utilities/focus-visible.js var FocusVisiblePolyfillMixin = (SuperClass) => { var _a12; const coordinateWithPolyfill = (instance) => { if (instance.shadowRoot == null || instance.hasAttribute("data-js-focus-visible")) { return () => { }; } if (self.applyFocusVisiblePolyfill) { self.applyFocusVisiblePolyfill(instance.shadowRoot); } else { const coordinationHandler = () => { self.applyFocusVisiblePolyfill(instance.shadowRoot); }; self.addEventListener("focus-visible-polyfill-ready", coordinationHandler, { once: true }); return () => { self.removeEventListener("focus-visible-polyfill-ready", coordinationHandler); }; } return () => { }; }; const $endPolyfillCoordination = Symbol("endPolyfillCoordination"); class FocusVisibleCoordinator extends SuperClass { constructor() { super(...arguments); this[_a12] = null; } // Attempt to coordinate with the polyfill when connected to the // document: connectedCallback() { super.connectedCallback && super.connectedCallback(); if (this[$endPolyfillCoordination] == null) { this[$endPolyfillCoordination] = coordinateWithPolyfill(this); } } disconnectedCallback() { super.disconnectedCallback && super.disconnectedCallback(); if (this[$endPolyfillCoordination] != null) { this[$endPolyfillCoordination](); this[$endPolyfillCoordination] = null; } } } _a12 = $endPolyfillCoordination; ; return FocusVisibleCoordinator; }; // node_modules/@google/model-viewer/lib/model-viewer.js var ModelViewerElement = AnnotationMixin(SceneGraphMixin(StagingMixin(EnvironmentMixin(ControlsMixin(ARMixin(LoadingMixin(AnimationMixin(FocusVisiblePolyfillMixin(ModelViewerElementBase))))))))); customElements.define("model-viewer", ModelViewerElement); // node_modules/thirdweb/dist/esm/react/web/ui/MediaRenderer/ModelViewer.js var import_react = __toESM(require_react(), 1); var ModelViewer = (() => import_react.default.forwardRef(function Model_Viewer({ src, alt, poster, style: style2, className }, ref) { return (0, import_jsx_runtime.jsx)("div", { style: { ...style2 }, className, ref, children: src ? ( // @ts-expect-error - model-viewer is not a standard HTML element (0, import_jsx_runtime.jsx)("model-viewer", { src, alt: alt || "3D Model", "camera-controls": true, poster: poster ? poster : null, style: { width: "100%", height: "100%" } }) ) : null }); }))(); var ModelViewer_default = ModelViewer; export { ModelViewer_default as default }; /*! Bundled license information: three/build/three.module.js: (** * @license * Copyright 2010-2022 Three.js Authors * SPDX-License-Identifier: MIT *) @google/model-viewer/lib/constants.js: (* @license * Copyright 2019 Google LLC. All Rights Reserved. * Licensed under the Apache License, Version 2.0 (the 'License'); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an 'AS IS' BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *) @google/model-viewer/lib/utilities.js: (* @license * Copyright 2019 Google LLC. All Rights Reserved. * Licensed under the Apache License, Version 2.0 (the 'License'); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an 'AS IS' BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *) @google/model-viewer/lib/features/environment.js: (* @license * Copyright 2019 Google LLC. All Rights Reserved. * Licensed under the Apache License, Version 2.0 (the 'License'); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an 'AS IS' BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *) @google/model-viewer/lib/assets/close-material-svg.js: (* @license * Copyright 2019 Google LLC. All Rights Reserved. * Licensed under the Apache License, Version 2.0 (the 'License'); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an 'AS IS' BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *) @google/model-viewer/lib/assets/controls-svg.js: (* @license * Copyright 2019 Google LLC. All Rights Reserved. * Licensed under the Apache License, Version 2.0 (the 'License'); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an 'AS IS' BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *) @google/model-viewer/lib/assets/view-in-ar-material-svg.js: (* @license * Copyright 2019 Google LLC. All Rights Reserved. * Licensed under the Apache License, Version 2.0 (the 'License'); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an 'AS IS' BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *) @google/model-viewer/lib/template.js: (* @license * Copyright 2019 Google LLC. All Rights Reserved. * Licensed under the Apache License, Version 2.0 (the 'License'); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an 'AS IS' BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *) @google/model-viewer/lib/utilities/cache-eviction-policy.js: (* @license * Copyright 2019 Google LLC. All Rights Reserved. * Licensed under the Apache License, Version 2.0 (the 'License'); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an 'AS IS' BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *) @google/model-viewer/lib/three-components/gltf-instance/VariantMaterialLoaderPlugin.js: (* @license * Copyright 2021 Google LLC. All Rights Reserved. * Licensed under the Apache License, Version 2.0 (the 'License'); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an 'AS IS' BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *) @google/model-viewer/lib/three-components/CachingGLTFLoader.js: (* @license * Copyright 2019 Google LLC. All Rights Reserved. * Licensed under the Apache License, Version 2.0 (the 'License'); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an 'AS IS' BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *) @google/model-viewer/lib/three-components/gltf-instance/VariantMaterialExporterPlugin.js: (* @license * Copyright 2021 Google LLC. All Rights Reserved. * Licensed under the Apache License, Version 2.0 (the 'License'); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an 'AS IS' BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *) @google/model-viewer/lib/three-components/Damper.js: (* @license * Copyright 2020 Google LLC. All Rights Reserved. * Licensed under the Apache License, Version 2.0 (the 'License'); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an 'AS IS' BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *) @google/model-viewer/lib/three-components/PlacementBox.js: (* @license * Copyright 2020 Google LLC. All Rights Reserved. * Licensed under the Apache License, Version 2.0 (the 'License'); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an 'AS IS' BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *) @google/model-viewer/lib/three-components/ARRenderer.js: (* @license * Copyright 2019 Google LLC. All Rights Reserved. * Licensed under the Apache License, Version 2.0 (the 'License'); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an 'AS IS' BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *) @google/model-viewer/lib/three-components/Debugger.js: (* @license * Copyright 2019 Google LLC. All Rights Reserved. * Licensed under the Apache License, Version 2.0 (the 'License'); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an 'AS IS' BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *) @google/model-viewer/lib/three-components/GLTFInstance.js: (* @license * Copyright 2020 Google LLC. All Rights Reserved. * Licensed under the Apache License, Version 2.0 (the 'License'); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an 'AS IS' BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *) @google/model-viewer/lib/three-components/gltf-instance/ModelViewerGLTFInstance.js: (* @license * Copyright 2020 Google LLC. All Rights Reserved. * Licensed under the Apache License, Version 2.0 (the 'License'); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an 'AS IS' BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *) @google/model-viewer/lib/three-components/EnvironmentScene.js: (* @license * Copyright 2021 Google LLC. All Rights Reserved. * Licensed under the Apache License, Version 2.0 (the 'License'); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an 'AS IS' BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *) @google/model-viewer/lib/three-components/EnvironmentSceneAlt.js: (* @license * Copyright 2021 Google LLC. All Rights Reserved. * Licensed under the Apache License, Version 2.0 (the 'License'); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an 'AS IS' BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *) @google/model-viewer/lib/three-components/TextureUtils.js: (* @license * Copyright 2019 Google LLC. All Rights Reserved. * Licensed under the Apache License, Version 2.0 (the 'License'); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an 'AS IS' BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *) @google/model-viewer/lib/three-components/Renderer.js: (* @license * Copyright 2019 Google LLC. All Rights Reserved. * Licensed under the Apache License, Version 2.0 (the 'License'); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an 'AS IS' BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *) @google/model-viewer/lib/features/scene-graph/three-dom-element.js: (* @license * Copyright 2020 Google LLC. All Rights Reserved. * Licensed under the Apache License, Version 2.0 (the 'License'); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an 'AS IS' BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *) @google/model-viewer/lib/features/scene-graph/image.js: (* @license * Copyright 2020 Google LLC. All Rights Reserved. * Licensed under the Apache License, Version 2.0 (the 'License'); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an 'AS IS' BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *) @google/model-viewer/lib/features/scene-graph/sampler.js: (* @license * Copyright 2020 Google LLC. All Rights Reserved. * Licensed under the Apache License, Version 2.0 (the 'License'); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an 'AS IS' BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *) @google/model-viewer/lib/features/scene-graph/texture.js: (* @license * Copyright 2020 Google LLC. All Rights Reserved. * Licensed under the Apache License, Version 2.0 (the 'License'); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an 'AS IS' BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *) @google/model-viewer/lib/features/scene-graph/texture-info.js: (* @license * Copyright 2020 Google LLC. All Rights Reserved. * Licensed under the Apache License, Version 2.0 (the 'License'); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an 'AS IS' BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *) @google/model-viewer/lib/features/scene-graph/pbr-metallic-roughness.js: (* @license * Copyright 2020 Google LLC. All Rights Reserved. * Licensed under the Apache License, Version 2.0 (the 'License'); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an 'AS IS' BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *) @google/model-viewer/lib/features/scene-graph/material.js: (* @license * Copyright 2020 Google LLC. All Rights Reserved. * Licensed under the Apache License, Version 2.0 (the 'License'); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an 'AS IS' BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *) @google/model-viewer/lib/features/scene-graph/model.js: (* @license * Copyright 2020 Google LLC. All Rights Reserved. * Licensed under the Apache License, Version 2.0 (the 'License'); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an 'AS IS' BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *) @google/model-viewer/lib/features/scene-graph.js: (* @license * Copyright 2020 Google LLC. All Rights Reserved. * Licensed under the Apache License, Version 2.0 (the 'License'); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an 'AS IS' BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *) @google/model-viewer/lib/styles/parsers.js: (* @license * Copyright 2019 Google LLC. All Rights Reserved. * Licensed under the Apache License, Version 2.0 (the 'License'); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an 'AS IS' BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *) @google/model-viewer/lib/styles/conversions.js: (* @license * Copyright 2019 Google LLC. All Rights Reserved. * Licensed under the Apache License, Version 2.0 (the 'License'); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an 'AS IS' BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *) @google/model-viewer/lib/three-components/Hotspot.js: (* @license * Copyright 2020 Google LLC. All Rights Reserved. * Licensed under the Apache License, Version 2.0 (the 'License'); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an 'AS IS' BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *) @google/model-viewer/lib/three-components/ModelUtils.js: (* @license * Copyright 2019 Google LLC. All Rights Reserved. * Licensed under the Apache License, Version 2.0 (the 'License'); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an 'AS IS' BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *) @google/model-viewer/lib/three-components/Shadow.js: (* @license * Copyright 2022 Google LLC. All Rights Reserved. * Licensed under the Apache License, Version 2.0 (the 'License'); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an 'AS IS' BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *) @google/model-viewer/lib/three-components/ModelScene.js: (* @license * Copyright 2019 Google LLC. All Rights Reserved. * Licensed under the Apache License, Version 2.0 (the 'License'); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an 'AS IS' BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *) @google/model-viewer/lib/utilities/data-conversion.js: (* @license * Copyright 2019 Google LLC. All Rights Reserved. * Licensed under the Apache License, Version 2.0 (the 'License'); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an 'AS IS' BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *) @google/model-viewer/lib/utilities/progress-tracker.js: (* @license * Copyright 2019 Google LLC. All Rights Reserved. * Licensed under the Apache License, Version 2.0 (the 'License'); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an 'AS IS' BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *) @google/model-viewer/lib/model-viewer-base.js: (* @license * Copyright 2019 Google LLC. All Rights Reserved. * Licensed under the Apache License, Version 2.0 (the 'License'); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an 'AS IS' BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *) @google/model-viewer/lib/features/animation.js: (* @license * Copyright 2019 Google LLC. All Rights Reserved. * Licensed under the Apache License, Version 2.0 (the 'License'); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an 'AS IS' BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *) @google/model-viewer/lib/features/annotation.js: (* @license * Copyright 2019 Google LLC. All Rights Reserved. * Licensed under the Apache License, Version 2.0 (the 'License'); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an 'AS IS' BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *) three/examples/jsm/libs/fflate.module.js: (*! fflate - fast JavaScript compression/decompression Licensed under MIT. https://github.com/101arrowz/fflate/blob/master/LICENSE version 0.6.9 *) @google/model-viewer/lib/styles/deserializers.js: (* @license * Copyright 2019 Google LLC. All Rights Reserved. * Licensed under the Apache License, Version 2.0 (the 'License'); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an 'AS IS' BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *) @google/model-viewer/lib/features/ar.js: (* @license * Copyright 2019 Google LLC. All Rights Reserved. * Licensed under the Apache License, Version 2.0 (the 'License'); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an 'AS IS' BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *) @google/model-viewer/lib/styles/evaluators.js: (* @license * Copyright 2019 Google LLC. All Rights Reserved. * Licensed under the Apache License, Version 2.0 (the 'License'); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an 'AS IS' BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *) @google/model-viewer/lib/styles/style-effector.js: (* @license * Copyright 2019 Google LLC. All Rights Reserved. * Licensed under the Apache License, Version 2.0 (the 'License'); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an 'AS IS' BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *) @google/model-viewer/lib/decorators.js: (* @license * Copyright 2019 Google LLC. All Rights Reserved. * Licensed under the Apache License, Version 2.0 (the 'License'); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an 'AS IS' BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *) @google/model-viewer/lib/three-components/SmoothControls.js: (* @license * Licensed under the Apache License, Version 2.0 (the 'License'); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an 'AS IS' BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *) @google/model-viewer/lib/utilities/animation.js: (* @license * Copyright 2019 Google LLC. All Rights Reserved. * Licensed under the Apache License, Version 2.0 (the 'License'); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an 'AS IS' BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *) @google/model-viewer/lib/features/controls.js: (* @license * Copyright 2019 Google LLC. All Rights Reserved. * Licensed under the Apache License, Version 2.0 (the 'License'); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an 'AS IS' BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *) @google/model-viewer/lib/features/loading.js: (* @license * Copyright 2019 Google LLC. All Rights Reserved. * Licensed under the Apache License, Version 2.0 (the 'License'); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an 'AS IS' BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *) @google/model-viewer/lib/features/staging.js: (* @license * Copyright 2019 Google LLC. All Rights Reserved. * Licensed under the Apache License, Version 2.0 (the 'License'); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an 'AS IS' BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *) @google/model-viewer/lib/model-viewer.js: (* @license * Copyright 2019 Google LLC. All Rights Reserved. * Licensed under the Apache License, Version 2.0 (the 'License'); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an 'AS IS' BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *) */ //# sourceMappingURL=ModelViewer-GZZWO7FG.js.map ================================================ FILE: 17-Crowd-Funding-Dapp/Frontend/.vite/deps_temp_6cf5ba4c/QRCodeRenderer-ZNSMXL36.js ================================================ "use client"; import { require_jsx_runtime } from "./chunk-U3QNWT4A.js"; import { require_react } from "./chunk-2MTJELC7.js"; import { __toESM } from "./chunk-SEVZ5PBP.js"; // node_modules/thirdweb/dist/esm/react/web/ui/components/QRCode/QRCodeRenderer.js var import_jsx_runtime = __toESM(require_jsx_runtime(), 1); var import_react = __toESM(require_react(), 1); // node_modules/uqr/dist/index.mjs var QrCodeDataType = ((QrCodeDataType2) => { QrCodeDataType2[QrCodeDataType2["Border"] = -1] = "Border"; QrCodeDataType2[QrCodeDataType2["Data"] = 0] = "Data"; QrCodeDataType2[QrCodeDataType2["Function"] = 1] = "Function"; QrCodeDataType2[QrCodeDataType2["Position"] = 2] = "Position"; QrCodeDataType2[QrCodeDataType2["Timing"] = 3] = "Timing"; QrCodeDataType2[QrCodeDataType2["Alignment"] = 4] = "Alignment"; return QrCodeDataType2; })(QrCodeDataType || {}); var __defProp = Object.defineProperty; var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value; var __publicField = (obj, key, value) => { __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value); return value; }; var LOW = [0, 1]; var MEDIUM = [1, 0]; var QUARTILE = [2, 3]; var HIGH = [3, 2]; var EccMap = { L: LOW, M: MEDIUM, Q: QUARTILE, H: HIGH }; var NUMERIC_REGEX = /^[0-9]*$/; var ALPHANUMERIC_REGEX = /^[A-Z0-9 $%*+.\/:-]*$/; var ALPHANUMERIC_CHARSET = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ $%*+-./:"; var MIN_VERSION = 1; var MAX_VERSION = 40; var PENALTY_N1 = 3; var PENALTY_N2 = 3; var PENALTY_N3 = 40; var PENALTY_N4 = 10; var ECC_CODEWORDS_PER_BLOCK = [ // Version: (note that index 0 is for padding, and is set to an illegal value) // 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40 Error correction level [-1, 7, 10, 15, 20, 26, 18, 20, 24, 30, 18, 20, 24, 26, 30, 22, 24, 28, 30, 28, 28, 28, 28, 30, 30, 26, 28, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30], // Low [-1, 10, 16, 26, 18, 24, 16, 18, 22, 22, 26, 30, 22, 22, 24, 24, 28, 28, 26, 26, 26, 26, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28], // Medium [-1, 13, 22, 18, 26, 18, 24, 18, 22, 20, 24, 28, 26, 24, 20, 30, 24, 28, 28, 26, 30, 28, 30, 30, 30, 30, 28, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30], // Quartile [-1, 17, 28, 22, 16, 22, 28, 26, 26, 24, 28, 24, 28, 22, 24, 24, 30, 28, 28, 26, 28, 30, 24, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30] // High ]; var NUM_ERROR_CORRECTION_BLOCKS = [ // Version: (note that index 0 is for padding, and is set to an illegal value) // 0, 1, 2, 3, 4, 5, 6, 7, 8, 9,10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40 Error correction level [-1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 4, 4, 4, 4, 4, 6, 6, 6, 6, 7, 8, 8, 9, 9, 10, 12, 12, 12, 13, 14, 15, 16, 17, 18, 19, 19, 20, 21, 22, 24, 25], // Low [-1, 1, 1, 1, 2, 2, 4, 4, 4, 5, 5, 5, 8, 9, 9, 10, 10, 11, 13, 14, 16, 17, 17, 18, 20, 21, 23, 25, 26, 28, 29, 31, 33, 35, 37, 38, 40, 43, 45, 47, 49], // Medium [-1, 1, 1, 2, 2, 4, 4, 6, 6, 8, 8, 8, 10, 12, 16, 12, 17, 16, 18, 21, 20, 23, 23, 25, 27, 29, 34, 34, 35, 38, 40, 43, 45, 48, 51, 53, 56, 59, 62, 65, 68], // Quartile [-1, 1, 1, 2, 4, 4, 4, 5, 6, 8, 8, 11, 11, 16, 16, 18, 16, 19, 21, 25, 25, 25, 34, 30, 32, 35, 37, 40, 42, 45, 48, 51, 54, 57, 60, 63, 66, 70, 74, 77, 81] // High ]; var QrCode = class { /* -- Constructor (low level) and fields -- */ // Creates a new QR Code with the given version number, // error correction level, data codeword bytes, and mask number. // This is a low-level API that most users should not use directly. // A mid-level API is the encodeSegments() function. constructor(version, ecc, dataCodewords, msk) { this.version = version; this.ecc = ecc; __publicField(this, "size"); __publicField(this, "mask"); __publicField(this, "modules", []); __publicField(this, "types", []); if (version < MIN_VERSION || version > MAX_VERSION) throw new RangeError("Version value out of range"); if (msk < -1 || msk > 7) throw new RangeError("Mask value out of range"); this.size = version * 4 + 17; const row = Array.from({ length: this.size }, () => false); for (let i = 0; i < this.size; i++) { this.modules.push(row.slice()); this.types.push(row.map(() => 0)); } this.drawFunctionPatterns(); const allCodewords = this.addEccAndInterleave(dataCodewords); this.drawCodewords(allCodewords); if (msk === -1) { let minPenalty = 1e9; for (let i = 0; i < 8; i++) { this.applyMask(i); this.drawFormatBits(i); const penalty = this.getPenaltyScore(); if (penalty < minPenalty) { msk = i; minPenalty = penalty; } this.applyMask(i); } } this.mask = msk; this.applyMask(msk); this.drawFormatBits(msk); } /* -- Accessor methods -- */ // Returns the color of the module (pixel) at the given coordinates, which is false // for light or true for dark. The top left corner has the coordinates (x=0, y=0). // If the given coordinates are out of bounds, then false (light) is returned. getModule(x, y) { return x >= 0 && x < this.size && y >= 0 && y < this.size && this.modules[y][x]; } /* -- Private helper methods for constructor: Drawing function modules -- */ // Reads this object's version field, and draws and marks all function modules. drawFunctionPatterns() { for (let i = 0; i < this.size; i++) { this.setFunctionModule(6, i, i % 2 === 0, QrCodeDataType.Timing); this.setFunctionModule(i, 6, i % 2 === 0, QrCodeDataType.Timing); } this.drawFinderPattern(3, 3); this.drawFinderPattern(this.size - 4, 3); this.drawFinderPattern(3, this.size - 4); const alignPatPos = this.getAlignmentPatternPositions(); const numAlign = alignPatPos.length; for (let i = 0; i < numAlign; i++) { for (let j = 0; j < numAlign; j++) { if (!(i === 0 && j === 0 || i === 0 && j === numAlign - 1 || i === numAlign - 1 && j === 0)) this.drawAlignmentPattern(alignPatPos[i], alignPatPos[j]); } } this.drawFormatBits(0); this.drawVersion(); } // Draws two copies of the format bits (with its own error correction code) // based on the given mask and this object's error correction level field. drawFormatBits(mask) { const data = this.ecc[1] << 3 | mask; let rem = data; for (let i = 0; i < 10; i++) rem = rem << 1 ^ (rem >>> 9) * 1335; const bits = (data << 10 | rem) ^ 21522; for (let i = 0; i <= 5; i++) this.setFunctionModule(8, i, getBit(bits, i)); this.setFunctionModule(8, 7, getBit(bits, 6)); this.setFunctionModule(8, 8, getBit(bits, 7)); this.setFunctionModule(7, 8, getBit(bits, 8)); for (let i = 9; i < 15; i++) this.setFunctionModule(14 - i, 8, getBit(bits, i)); for (let i = 0; i < 8; i++) this.setFunctionModule(this.size - 1 - i, 8, getBit(bits, i)); for (let i = 8; i < 15; i++) this.setFunctionModule(8, this.size - 15 + i, getBit(bits, i)); this.setFunctionModule(8, this.size - 8, true); } // Draws two copies of the version bits (with its own error correction code), // based on this object's version field, iff 7 <= version <= 40. drawVersion() { if (this.version < 7) return; let rem = this.version; for (let i = 0; i < 12; i++) rem = rem << 1 ^ (rem >>> 11) * 7973; const bits = this.version << 12 | rem; for (let i = 0; i < 18; i++) { const color = getBit(bits, i); const a = this.size - 11 + i % 3; const b = Math.floor(i / 3); this.setFunctionModule(a, b, color); this.setFunctionModule(b, a, color); } } // Draws a 9*9 finder pattern including the border separator, // with the center module at (x, y). Modules can be out of bounds. drawFinderPattern(x, y) { for (let dy = -4; dy <= 4; dy++) { for (let dx = -4; dx <= 4; dx++) { const dist = Math.max(Math.abs(dx), Math.abs(dy)); const xx = x + dx; const yy = y + dy; if (xx >= 0 && xx < this.size && yy >= 0 && yy < this.size) this.setFunctionModule(xx, yy, dist !== 2 && dist !== 4, QrCodeDataType.Position); } } } // Draws a 5*5 alignment pattern, with the center module // at (x, y). All modules must be in bounds. drawAlignmentPattern(x, y) { for (let dy = -2; dy <= 2; dy++) { for (let dx = -2; dx <= 2; dx++) { this.setFunctionModule( x + dx, y + dy, Math.max(Math.abs(dx), Math.abs(dy)) !== 1, QrCodeDataType.Alignment ); } } } // Sets the color of a module and marks it as a function module. // Only used by the constructor. Coordinates must be in bounds. setFunctionModule(x, y, isDark, type = QrCodeDataType.Function) { this.modules[y][x] = isDark; this.types[y][x] = type; } /* -- Private helper methods for constructor: Codewords and masking -- */ // Returns a new byte string representing the given data with the appropriate error correction // codewords appended to it, based on this object's version and error correction level. addEccAndInterleave(data) { const ver = this.version; const ecl = this.ecc; if (data.length !== getNumDataCodewords(ver, ecl)) throw new RangeError("Invalid argument"); const numBlocks = NUM_ERROR_CORRECTION_BLOCKS[ecl[0]][ver]; const blockEccLen = ECC_CODEWORDS_PER_BLOCK[ecl[0]][ver]; const rawCodewords = Math.floor(getNumRawDataModules(ver) / 8); const numShortBlocks = numBlocks - rawCodewords % numBlocks; const shortBlockLen = Math.floor(rawCodewords / numBlocks); const blocks = []; const rsDiv = reedSolomonComputeDivisor(blockEccLen); for (let i = 0, k = 0; i < numBlocks; i++) { const dat = data.slice(k, k + shortBlockLen - blockEccLen + (i < numShortBlocks ? 0 : 1)); k += dat.length; const ecc = reedSolomonComputeRemainder(dat, rsDiv); if (i < numShortBlocks) dat.push(0); blocks.push(dat.concat(ecc)); } const result = []; for (let i = 0; i < blocks[0].length; i++) { blocks.forEach((block, j) => { if (i !== shortBlockLen - blockEccLen || j >= numShortBlocks) result.push(block[i]); }); } return result; } // Draws the given sequence of 8-bit codewords (data and error correction) onto the entire // data area of this QR Code. Function modules need to be marked off before this is called. drawCodewords(data) { if (data.length !== Math.floor(getNumRawDataModules(this.version) / 8)) throw new RangeError("Invalid argument"); let i = 0; for (let right = this.size - 1; right >= 1; right -= 2) { if (right === 6) right = 5; for (let vert = 0; vert < this.size; vert++) { for (let j = 0; j < 2; j++) { const x = right - j; const upward = (right + 1 & 2) === 0; const y = upward ? this.size - 1 - vert : vert; if (!this.types[y][x] && i < data.length * 8) { this.modules[y][x] = getBit(data[i >>> 3], 7 - (i & 7)); i++; } } } } } // XORs the codeword modules in this QR Code with the given mask pattern. // The function modules must be marked and the codeword bits must be drawn // before masking. Due to the arithmetic of XOR, calling applyMask() with // the same mask value a second time will undo the mask. A final well-formed // QR Code needs exactly one (not zero, two, etc.) mask applied. applyMask(mask) { if (mask < 0 || mask > 7) throw new RangeError("Mask value out of range"); for (let y = 0; y < this.size; y++) { for (let x = 0; x < this.size; x++) { let invert; switch (mask) { case 0: invert = (x + y) % 2 === 0; break; case 1: invert = y % 2 === 0; break; case 2: invert = x % 3 === 0; break; case 3: invert = (x + y) % 3 === 0; break; case 4: invert = (Math.floor(x / 3) + Math.floor(y / 2)) % 2 === 0; break; case 5: invert = x * y % 2 + x * y % 3 === 0; break; case 6: invert = (x * y % 2 + x * y % 3) % 2 === 0; break; case 7: invert = ((x + y) % 2 + x * y % 3) % 2 === 0; break; default: throw new Error("Unreachable"); } if (!this.types[y][x] && invert) this.modules[y][x] = !this.modules[y][x]; } } } // Calculates and returns the penalty score based on state of this QR Code's current modules. // This is used by the automatic mask choice algorithm to find the mask pattern that yields the lowest score. getPenaltyScore() { let result = 0; for (let y = 0; y < this.size; y++) { let runColor = false; let runX = 0; const runHistory = [0, 0, 0, 0, 0, 0, 0]; for (let x = 0; x < this.size; x++) { if (this.modules[y][x] === runColor) { runX++; if (runX === 5) result += PENALTY_N1; else if (runX > 5) result++; } else { this.finderPenaltyAddHistory(runX, runHistory); if (!runColor) result += this.finderPenaltyCountPatterns(runHistory) * PENALTY_N3; runColor = this.modules[y][x]; runX = 1; } } result += this.finderPenaltyTerminateAndCount(runColor, runX, runHistory) * PENALTY_N3; } for (let x = 0; x < this.size; x++) { let runColor = false; let runY = 0; const runHistory = [0, 0, 0, 0, 0, 0, 0]; for (let y = 0; y < this.size; y++) { if (this.modules[y][x] === runColor) { runY++; if (runY === 5) result += PENALTY_N1; else if (runY > 5) result++; } else { this.finderPenaltyAddHistory(runY, runHistory); if (!runColor) result += this.finderPenaltyCountPatterns(runHistory) * PENALTY_N3; runColor = this.modules[y][x]; runY = 1; } } result += this.finderPenaltyTerminateAndCount(runColor, runY, runHistory) * PENALTY_N3; } for (let y = 0; y < this.size - 1; y++) { for (let x = 0; x < this.size - 1; x++) { const color = this.modules[y][x]; if (color === this.modules[y][x + 1] && color === this.modules[y + 1][x] && color === this.modules[y + 1][x + 1]) result += PENALTY_N2; } } let dark = 0; for (const row of this.modules) dark = row.reduce((sum, color) => sum + (color ? 1 : 0), dark); const total = this.size * this.size; const k = Math.ceil(Math.abs(dark * 20 - total * 10) / total) - 1; result += k * PENALTY_N4; return result; } /* -- Private helper functions -- */ // Returns an ascending list of positions of alignment patterns for this version number. // Each position is in the range [0,177), and are used on both the x and y axes. // This could be implemented as lookup table of 40 variable-length lists of integers. getAlignmentPatternPositions() { if (this.version === 1) { return []; } else { const numAlign = Math.floor(this.version / 7) + 2; const step = this.version === 32 ? 26 : Math.ceil((this.version * 4 + 4) / (numAlign * 2 - 2)) * 2; const result = [6]; for (let pos = this.size - 7; result.length < numAlign; pos -= step) result.splice(1, 0, pos); return result; } } // Can only be called immediately after a light run is added, and // returns either 0, 1, or 2. A helper function for getPenaltyScore(). finderPenaltyCountPatterns(runHistory) { const n = runHistory[1]; const core = n > 0 && runHistory[2] === n && runHistory[3] === n * 3 && runHistory[4] === n && runHistory[5] === n; return (core && runHistory[0] >= n * 4 && runHistory[6] >= n ? 1 : 0) + (core && runHistory[6] >= n * 4 && runHistory[0] >= n ? 1 : 0); } // Must be called at the end of a line (row or column) of modules. A helper function for getPenaltyScore(). finderPenaltyTerminateAndCount(currentRunColor, currentRunLength, runHistory) { if (currentRunColor) { this.finderPenaltyAddHistory(currentRunLength, runHistory); currentRunLength = 0; } currentRunLength += this.size; this.finderPenaltyAddHistory(currentRunLength, runHistory); return this.finderPenaltyCountPatterns(runHistory); } // Pushes the given value to the front and drops the last value. A helper function for getPenaltyScore(). finderPenaltyAddHistory(currentRunLength, runHistory) { if (runHistory[0] === 0) currentRunLength += this.size; runHistory.pop(); runHistory.unshift(currentRunLength); } }; function appendBits(val, len, bb) { if (len < 0 || len > 31 || val >>> len !== 0) throw new RangeError("Value out of range"); for (let i = len - 1; i >= 0; i--) bb.push(val >>> i & 1); } function getBit(x, i) { return (x >>> i & 1) !== 0; } var QrSegment = class { // Creates a new QR Code segment with the given attributes and data. // The character count (numChars) must agree with the mode and the bit buffer length, // but the constraint isn't checked. The given bit buffer is cloned and stored. constructor(mode, numChars, bitData) { this.mode = mode; this.numChars = numChars; this.bitData = bitData; if (numChars < 0) throw new RangeError("Invalid argument"); this.bitData = bitData.slice(); } /* -- Methods -- */ // Returns a new copy of the data bits of this segment. getData() { return this.bitData.slice(); } }; var MODE_NUMERIC = [1, 10, 12, 14]; var MODE_ALPHANUMERIC = [2, 9, 11, 13]; var MODE_BYTE = [4, 8, 16, 16]; function numCharCountBits(mode, ver) { return mode[Math.floor((ver + 7) / 17) + 1]; } function makeBytes(data) { const bb = []; for (const b of data) appendBits(b, 8, bb); return new QrSegment(MODE_BYTE, data.length, bb); } function makeNumeric(digits) { if (!isNumeric(digits)) throw new RangeError("String contains non-numeric characters"); const bb = []; for (let i = 0; i < digits.length; ) { const n = Math.min(digits.length - i, 3); appendBits(Number.parseInt(digits.substring(i, i + n), 10), n * 3 + 1, bb); i += n; } return new QrSegment(MODE_NUMERIC, digits.length, bb); } function makeAlphanumeric(text) { if (!isAlphanumeric(text)) throw new RangeError("String contains unencodable characters in alphanumeric mode"); const bb = []; let i; for (i = 0; i + 2 <= text.length; i += 2) { let temp = ALPHANUMERIC_CHARSET.indexOf(text.charAt(i)) * 45; temp += ALPHANUMERIC_CHARSET.indexOf(text.charAt(i + 1)); appendBits(temp, 11, bb); } if (i < text.length) appendBits(ALPHANUMERIC_CHARSET.indexOf(text.charAt(i)), 6, bb); return new QrSegment(MODE_ALPHANUMERIC, text.length, bb); } function makeSegments(text) { if (text === "") return []; else if (isNumeric(text)) return [makeNumeric(text)]; else if (isAlphanumeric(text)) return [makeAlphanumeric(text)]; else return [makeBytes(toUtf8ByteArray(text))]; } function isNumeric(text) { return NUMERIC_REGEX.test(text); } function isAlphanumeric(text) { return ALPHANUMERIC_REGEX.test(text); } function getTotalBits(segs, version) { let result = 0; for (const seg of segs) { const ccbits = numCharCountBits(seg.mode, version); if (seg.numChars >= 1 << ccbits) return Number.POSITIVE_INFINITY; result += 4 + ccbits + seg.bitData.length; } return result; } function toUtf8ByteArray(str) { str = encodeURI(str); const result = []; for (let i = 0; i < str.length; i++) { if (str.charAt(i) !== "%") { result.push(str.charCodeAt(i)); } else { result.push(Number.parseInt(str.substring(i + 1, i + 3), 16)); i += 2; } } return result; } function getNumRawDataModules(ver) { if (ver < MIN_VERSION || ver > MAX_VERSION) throw new RangeError("Version number out of range"); let result = (16 * ver + 128) * ver + 64; if (ver >= 2) { const numAlign = Math.floor(ver / 7) + 2; result -= (25 * numAlign - 10) * numAlign - 55; if (ver >= 7) result -= 36; } return result; } function getNumDataCodewords(ver, ecl) { return Math.floor(getNumRawDataModules(ver) / 8) - ECC_CODEWORDS_PER_BLOCK[ecl[0]][ver] * NUM_ERROR_CORRECTION_BLOCKS[ecl[0]][ver]; } function reedSolomonComputeDivisor(degree) { if (degree < 1 || degree > 255) throw new RangeError("Degree out of range"); const result = []; for (let i = 0; i < degree - 1; i++) result.push(0); result.push(1); let root = 1; for (let i = 0; i < degree; i++) { for (let j = 0; j < result.length; j++) { result[j] = reedSolomonMultiply(result[j], root); if (j + 1 < result.length) result[j] ^= result[j + 1]; } root = reedSolomonMultiply(root, 2); } return result; } function reedSolomonComputeRemainder(data, divisor) { const result = divisor.map((_) => 0); for (const b of data) { const factor = b ^ result.shift(); result.push(0); divisor.forEach((coef, i) => result[i] ^= reedSolomonMultiply(coef, factor)); } return result; } function reedSolomonMultiply(x, y) { if (x >>> 8 !== 0 || y >>> 8 !== 0) throw new RangeError("Byte out of range"); let z = 0; for (let i = 7; i >= 0; i--) { z = z << 1 ^ (z >>> 7) * 285; z ^= (y >>> i & 1) * x; } return z; } function encodeSegments(segs, ecl, minVersion = 1, maxVersion = 40, mask = -1, boostEcl = true) { if (!(MIN_VERSION <= minVersion && minVersion <= maxVersion && maxVersion <= MAX_VERSION) || mask < -1 || mask > 7) throw new RangeError("Invalid value"); let version; let dataUsedBits; for (version = minVersion; ; version++) { const dataCapacityBits2 = getNumDataCodewords(version, ecl) * 8; const usedBits = getTotalBits(segs, version); if (usedBits <= dataCapacityBits2) { dataUsedBits = usedBits; break; } if (version >= maxVersion) throw new RangeError("Data too long"); } for (const newEcl of [MEDIUM, QUARTILE, HIGH]) { if (boostEcl && dataUsedBits <= getNumDataCodewords(version, newEcl) * 8) ecl = newEcl; } const bb = []; for (const seg of segs) { appendBits(seg.mode[0], 4, bb); appendBits(seg.numChars, numCharCountBits(seg.mode, version), bb); for (const b of seg.getData()) bb.push(b); } const dataCapacityBits = getNumDataCodewords(version, ecl) * 8; appendBits(0, Math.min(4, dataCapacityBits - bb.length), bb); appendBits(0, (8 - bb.length % 8) % 8, bb); for (let padByte = 236; bb.length < dataCapacityBits; padByte ^= 236 ^ 17) appendBits(padByte, 8, bb); const dataCodewords = Array.from({ length: Math.ceil(bb.length / 8) }, () => 0); bb.forEach((b, i) => dataCodewords[i >>> 3] |= b << 7 - (i & 7)); return new QrCode(version, ecl, dataCodewords, mask); } function encode(data, options) { var _a; const { ecc = "L", boostEcc = false, minVersion = 1, maxVersion = 40, maskPattern = -1, border = 1 } = options || {}; const segment = typeof data === "string" ? makeSegments(data) : Array.isArray(data) ? [makeBytes(data)] : void 0; if (!segment) throw new Error(`uqr only supports encoding string and binary data, but got: ${typeof data}`); const qr = encodeSegments( segment, EccMap[ecc], minVersion, maxVersion, maskPattern, boostEcc ); const result = addBorder({ version: qr.version, maskPattern: qr.mask, size: qr.size, data: qr.modules, types: qr.types }, border); if (options == null ? void 0 : options.invert) result.data = result.data.map((row) => row.map((mod) => !mod)); (_a = options == null ? void 0 : options.onEncoded) == null ? void 0 : _a.call(options, result); return result; } function addBorder(input, border = 1) { if (!border) return input; const { size } = input; const newSize = size + border * 2; input.size = newSize; input.data.forEach((row) => { for (let i = 0; i < border; i++) { row.unshift(false); row.push(false); } }); for (let i = 0; i < border; i++) { input.data.unshift(Array.from({ length: newSize }, (_) => false)); input.data.push(Array.from({ length: newSize }, (_) => false)); } const b = QrCodeDataType.Border; input.types.forEach((row) => { for (let i = 0; i < border; i++) { row.unshift(b); row.push(b); } }); for (let i = 0; i < border; i++) { input.types.unshift(Array.from({ length: newSize }, (_) => b)); input.types.push(Array.from({ length: newSize }, (_) => b)); } return input; } // node_modules/thirdweb/dist/esm/react/web/ui/components/QRCode/QRCodeRenderer.js function QRCodeRenderer({ ecl = "M", size: sizeProp = 200, uri, clearSize = 0, image, imageBackground = "transparent" }) { const logoSize = clearSize; const size = sizeProp - 10 * 2; const dots = (0, import_react.useMemo)(() => { const dotsArray = []; const matrix = encode(uri, { ecc: ecl, border: 0 }).data; const cellSize = size / matrix.length; const qrList = [ { x: 0, y: 0 }, { x: 1, y: 0 }, { x: 0, y: 1 } ]; for (const { x, y } of qrList) { const x1 = (matrix.length - 7) * cellSize * x; const y1 = (matrix.length - 7) * cellSize * y; for (let i = 0; i < 3; i++) { dotsArray.push((0, import_jsx_runtime.jsx)("rect", { fill: i % 2 !== 0 ? "var(--ck-qr-background, var(--ck-body-background))" : "var(--ck-qr-dot-color)", rx: (i - 2) * -5 + (i === 0 ? 2 : 3), ry: (i - 2) * -5 + (i === 0 ? 2 : 3), width: cellSize * (7 - i * 2), height: cellSize * (7 - i * 2), x: x1 + cellSize * i, y: y1 + cellSize * i }, `${i}-${x}-${y}`)); } } if (image) { const x1 = (matrix.length - 7) * cellSize * 1; const y1 = (matrix.length - 7) * cellSize * 1; dotsArray.push((0, import_jsx_runtime.jsxs)(import_jsx_runtime.Fragment, { children: [(0, import_jsx_runtime.jsx)("rect", { fill: imageBackground, rx: (0 - 2) * -5 + 2, ry: (0 - 2) * -5 + 2, width: cellSize * (7 - 0 * 2), height: cellSize * (7 - 0 * 2), x: x1 + cellSize * 0, y: y1 + cellSize * 0 }), (0, import_jsx_runtime.jsx)("foreignObject", { width: cellSize * (7 - 0 * 2), height: cellSize * (7 - 0 * 2), x: x1 + cellSize * 0, y: y1 + cellSize * 0, children: (0, import_jsx_runtime.jsx)("div", { style: { borderRadius: (0 - 2) * -5 + 2, overflow: "hidden" }, children: image }) })] })); } const clearArenaSize = Math.floor((logoSize + 25) / cellSize); const matrixMiddleStart = matrix.length / 2 - clearArenaSize / 2; const matrixMiddleEnd = matrix.length / 2 + clearArenaSize / 2 - 1; matrix.forEach((row, i) => { row.forEach((_, j) => { var _a; if ((_a = matrix[i]) == null ? void 0 : _a[j]) { if (!(i < 7 && j < 7 || i > matrix.length - 8 && j < 7 || i < 7 && j > matrix.length - 8)) { if (image || !(i > matrixMiddleStart && i < matrixMiddleEnd && j > matrixMiddleStart && j < matrixMiddleEnd)) { dotsArray.push((0, import_jsx_runtime.jsx)("circle", { cx: i * cellSize + cellSize / 2, cy: j * cellSize + cellSize / 2, fill: "var(--ck-qr-dot-color)", r: cellSize / 3 }, `circle-${i}-${// biome-ignore lint/suspicious/noArrayIndexKey: its the only thing available for the key here j}`)); } } } }); }); return dotsArray; }, [ecl, image, imageBackground, logoSize, size, uri]); return (0, import_jsx_runtime.jsxs)("svg", { height: size, width: size, viewBox: `0 0 ${size} ${size}`, style: { width: size, height: size }, role: "presentation", children: [(0, import_jsx_runtime.jsx)("rect", { fill: "transparent", height: size, width: size }), dots] }); } var QRCodeRenderer_default = QRCodeRenderer; export { QRCodeRenderer_default as default }; //# sourceMappingURL=QRCodeRenderer-ZNSMXL36.js.map ================================================ FILE: 17-Crowd-Funding-Dapp/Frontend/.vite/deps_temp_6cf5ba4c/adapter-F5WOI5K5.js ================================================ import "./chunk-SEVZ5PBP.js"; // node_modules/thirdweb/dist/esm/wallets/custom/adapter/index.js var wallet = { id: "adapter", name: "Wallet", homepage: "https://thirdweb.com", app: { browser: null, ios: null, android: null, mac: null, windows: null, linux: null, chrome: null, firefox: null, safari: null, edge: null, opera: null }, rdns: null, mobile: { native: null, universal: null }, desktop: { native: null, universal: null } }; export { wallet }; //# sourceMappingURL=adapter-F5WOI5K5.js.map ================================================ FILE: 17-Crowd-Funding-Dapp/Frontend/.vite/deps_temp_6cf5ba4c/ai-M4CK2DAC.js ================================================ import "./chunk-SEVZ5PBP.js"; // node_modules/thirdweb/dist/esm/wallets/__generated__/wallet/ai.hacken/index.js var wallet = { id: "ai.hacken", name: "hAI by Hacken", homepage: "https://hacken.ai", image_id: "d2ff6baf-5051-4bf2-edec-32450b451000", app: { browser: "https://hacken.ai", ios: "https://apps.apple.com/us/app/hai-by-hacken/id1501384789", android: "https://play.google.com/store/apps/details?id=com.hackenai.hackenaiapp&hl=en_US", mac: null, windows: null, linux: null, chrome: null, firefox: null, safari: null, edge: null, opera: null }, rdns: null, mobile: { native: "hai://", universal: "https://hacken.ai" }, desktop: { native: null, universal: null } }; export { wallet }; //# sourceMappingURL=ai-M4CK2DAC.js.map ================================================ FILE: 17-Crowd-Funding-Dapp/Frontend/.vite/deps_temp_6cf5ba4c/ai.spotonchain-Q44G73RV.js ================================================ import "./chunk-SEVZ5PBP.js"; // node_modules/thirdweb/dist/esm/wallets/__generated__/wallet/ai.spotonchain.platform/index.js var wallet = { id: "ai.spotonchain.platform", name: "Spot On Chain App", homepage: "https://platform.spotonchain.ai", image_id: "1bcb5ed6-f6c9-4b0d-f891-b70c48b93d00", app: { browser: null, ios: "https://apps.apple.com/us/app/spot-on-chain/id6449733489", android: "https://play.google.com/store/apps/details?id=network.spotonchain", mac: null, windows: null, linux: null, chrome: null, firefox: null, safari: null, edge: null, opera: null }, rdns: null, mobile: { native: "spotonchain://", universal: "https://spotonchain.ai/" }, desktop: { native: null, universal: null } }; export { wallet }; //# sourceMappingURL=ai.spotonchain-Q44G73RV.js.map ================================================ FILE: 17-Crowd-Funding-Dapp/Frontend/.vite/deps_temp_6cf5ba4c/app-3BIDNXMN.js ================================================ import "./chunk-SEVZ5PBP.js"; // node_modules/thirdweb/dist/esm/wallets/__generated__/wallet/app.ryipay/index.js var wallet = { id: "app.ryipay", name: "RYIPAY", homepage: "https://ryipay.app/", image_id: "2f0918f7-f135-4b62-4765-ac183f14e500", app: { browser: null, ios: "https://apps.apple.com/us/app/ryipay-wallet/id1620995066", android: "https://play.google.com/store/apps/details?id=io.ryi.pay", mac: null, windows: null, linux: null, chrome: null, firefox: null, safari: null, edge: null, opera: null }, rdns: null, mobile: { native: "ryipay://", universal: "https://ryipay.page.link/3N7P" }, desktop: { native: null, universal: null } }; export { wallet }; //# sourceMappingURL=app-3BIDNXMN.js.map ================================================ FILE: 17-Crowd-Funding-Dapp/Frontend/.vite/deps_temp_6cf5ba4c/app-4OQAM2FO.js ================================================ import "./chunk-SEVZ5PBP.js"; // node_modules/thirdweb/dist/esm/wallets/__generated__/wallet/app.utorg/index.js var wallet = { id: "app.utorg", name: "UTORG", homepage: "https://utorg.app", image_id: "39c77c0b-d6ea-419d-92b7-513a5eac2c00", app: { browser: null, ios: "https://apps.apple.com/app/utorg-bitcoin-crypto-wallet/id6444720908", android: "https://play.google.com/store/apps/details?id=com.utorg", mac: "", windows: null, linux: null, chrome: null, firefox: null, safari: null, edge: null, opera: null }, rdns: null, mobile: { native: "utorg://mainactivity", universal: "https://link.utorg.com/zp0f" }, desktop: { native: "utorg://mainactivity", universal: null } }; export { wallet }; //# sourceMappingURL=app-4OQAM2FO.js.map ================================================ FILE: 17-Crowd-Funding-Dapp/Frontend/.vite/deps_temp_6cf5ba4c/app-4WB6G67C.js ================================================ import "./chunk-SEVZ5PBP.js"; // node_modules/thirdweb/dist/esm/wallets/__generated__/wallet/app.gamic/index.js var wallet = { id: "app.gamic", name: "Gamic", homepage: "https://gamic.app", image_id: "cf404c15-391c-4144-1ec0-17f1b119ed00", app: { browser: "https://gamic.app/", ios: "https://apps.apple.com/us/app/gamic-spaces-chat-connect/id1673683070", android: "https://play.google.com/store/apps/details?id=app.gamic.guild.gamic_guild_mobile", mac: null, windows: null, linux: null, chrome: null, firefox: null, safari: null, edge: null, opera: null }, rdns: null, mobile: { native: "gamic://", universal: "https://www.gamic.app/wc" }, desktop: { native: "gamic://", universal: null } }; export { wallet }; //# sourceMappingURL=app-4WB6G67C.js.map ================================================ FILE: 17-Crowd-Funding-Dapp/Frontend/.vite/deps_temp_6cf5ba4c/app-5BPIXU3J.js ================================================ import "./chunk-SEVZ5PBP.js"; // node_modules/thirdweb/dist/esm/wallets/__generated__/wallet/app.keplr/index.js var wallet = { id: "app.keplr", name: "Keplr", homepage: "https://keplr.app", image_id: "527324b0-3849-462b-9a1a-72b53bdfea00", app: { browser: "https://wallet.keplr.app", ios: "https://apps.apple.com/us/app/keplr-wallet/id1567851089", android: "https://play.google.com/store/apps/details?id=com.chainapsis.keplr&hl=en&gl=US", mac: null, windows: null, linux: null, chrome: "https://chrome.google.com/webstore/detail/keplr/dmkamcknogkgcdfhhbddcghachkejeap?hl=en", firefox: "https://addons.mozilla.org/en-US/firefox/addon/keplr/", safari: null, edge: "https://microsoftedge.microsoft.com/addons/detail/keplr/ocodgmmffbkkeecmadcijjhkmeohinei", opera: null }, rdns: "app.keplr", mobile: { native: "keplrwallet://wcV2", universal: null }, desktop: { native: null, universal: null } }; export { wallet }; //# sourceMappingURL=app-5BPIXU3J.js.map ================================================ FILE: 17-Crowd-Funding-Dapp/Frontend/.vite/deps_temp_6cf5ba4c/app-5PJX72YN.js ================================================ import "./chunk-SEVZ5PBP.js"; // node_modules/thirdweb/dist/esm/wallets/__generated__/wallet/app.walletnow/index.js var wallet = { id: "app.walletnow", name: "NOW Wallet", homepage: "https://walletnow.app/", image_id: "b6ee4efc-f53e-475b-927b-a7ded6211700", app: { browser: null, ios: "https://apps.apple.com/app/now-wallet-bitcoin-crypto/id1591216386", android: "https://play.google.com/store/apps/details?id=com.nowwallet", mac: "https://apps.apple.com/app/now-wallet-bitcoin-crypto/id1591216386", windows: "https://apps.microsoft.com/detail/xpdc4v0j3zkvhh", linux: null, chrome: null, firefox: null, safari: null, edge: null, opera: null }, rdns: null, mobile: { native: "nowwallet://", universal: "https://walletnow.app.link" }, desktop: { native: "nowwallet://", universal: "https://walletnow.app.link" } }; export { wallet }; //# sourceMappingURL=app-5PJX72YN.js.map ================================================ FILE: 17-Crowd-Funding-Dapp/Frontend/.vite/deps_temp_6cf5ba4c/app-6X4TWE2O.js ================================================ import "./chunk-SEVZ5PBP.js"; // node_modules/thirdweb/dist/esm/wallets/__generated__/wallet/app.edge/index.js var wallet = { id: "app.edge", name: "Edge Wallet", homepage: "https://edge.app/", image_id: "f601bc29-4298-422f-dbf7-34dac2884f00", app: { browser: null, ios: "https://apps.apple.com/us/app/edge-bitcoin-wallet/id1344400091", android: "https://play.google.com/store/apps/details?id=co.edgesecure.app", mac: null, windows: null, linux: null, chrome: null, firefox: null, safari: null, edge: null, opera: null }, rdns: null, mobile: { native: "edge://", universal: "https://deep.edge.app/wc" }, desktop: { native: null, universal: null } }; export { wallet }; //# sourceMappingURL=app-6X4TWE2O.js.map ================================================ FILE: 17-Crowd-Funding-Dapp/Frontend/.vite/deps_temp_6cf5ba4c/app-BJYH6WND.js ================================================ import "./chunk-SEVZ5PBP.js"; // node_modules/thirdweb/dist/esm/wallets/__generated__/wallet/app.ammer/index.js var wallet = { id: "app.ammer", name: "Ammer Wallet", homepage: "https://ammer.app/", image_id: "7d38dd8e-92ee-44bf-1ca4-818531de1900", app: { browser: null, ios: "https://apps.apple.com/us/app/ammer-wallet/id1599698329", android: null, mac: null, windows: null, linux: null, chrome: null, firefox: null, safari: null, edge: null, opera: null }, rdns: null, mobile: { native: "ammerwallet://", universal: null }, desktop: { native: null, universal: null } }; export { wallet }; //# sourceMappingURL=app-BJYH6WND.js.map ================================================ FILE: 17-Crowd-Funding-Dapp/Frontend/.vite/deps_temp_6cf5ba4c/app-C6AFF7V2.js ================================================ import "./chunk-SEVZ5PBP.js"; // node_modules/thirdweb/dist/esm/wallets/__generated__/wallet/app.catecoin/index.js var wallet = { id: "app.catecoin", name: "Catecoin Wallet", homepage: "https://catecoin.app", image_id: "d017bc54-db4d-4f07-2de2-69790ce92400", app: { browser: "https://wallet.catecoin.club/", ios: "https://apps.apple.com/app/id1637850589?platform=iphone", android: "https://play.google.com/store/apps/details?id=com.crypto.wallet.catecoin", mac: "", windows: null, linux: null, chrome: null, firefox: null, safari: null, edge: null, opera: null }, rdns: null, mobile: { native: "catecoin://", universal: "https://catecoin.app/apple-app-site-association" }, desktop: { native: null, universal: null } }; export { wallet }; //# sourceMappingURL=app-C6AFF7V2.js.map ================================================ FILE: 17-Crowd-Funding-Dapp/Frontend/.vite/deps_temp_6cf5ba4c/app-CEHOPHKL.js ================================================ import "./chunk-SEVZ5PBP.js"; // node_modules/thirdweb/dist/esm/wallets/__generated__/wallet/app.nicegram/index.js var wallet = { id: "app.nicegram", name: "Nicegram Wallet", homepage: "https://nicegram.app", image_id: "929745a4-5830-480b-f6ab-bb3a854bc700", app: { browser: null, ios: "https://apps.apple.com/app/apple-store/id1608870673", android: "https://play.google.com/store/apps/details?id=app.nicegram", mac: null, windows: null, linux: null, chrome: null, firefox: null, safari: null, edge: null, opera: null }, rdns: null, mobile: { native: "ncg://wallet/home", universal: "https://nicegram.app/" }, desktop: { native: null, universal: null } }; export { wallet }; //# sourceMappingURL=app-CEHOPHKL.js.map ================================================ FILE: 17-Crowd-Funding-Dapp/Frontend/.vite/deps_temp_6cf5ba4c/app-FEBEDQ5O.js ================================================ import "./chunk-SEVZ5PBP.js"; // node_modules/thirdweb/dist/esm/wallets/__generated__/wallet/app.status/index.js var wallet = { id: "app.status", name: "Status", homepage: "https://status.app/", image_id: "1e5fb93a-3a0a-40b9-8a86-b14a775aae00", app: { browser: null, ios: "https://apps.apple.com/us/app/status-gateway-to-ethereum/id1178893006", android: "https://play.google.com/store/apps/details?id=im.status.ethereum", mac: "https://status.app/help/getting-started", windows: "https://status.app/help/getting-started", linux: "https://status.app/help/getting-started", chrome: null, firefox: null, safari: null, edge: null, opera: null }, rdns: null, mobile: { native: "status-app://", universal: "https://status.app" }, desktop: { native: null, universal: null } }; export { wallet }; //# sourceMappingURL=app-FEBEDQ5O.js.map ================================================ FILE: 17-Crowd-Funding-Dapp/Frontend/.vite/deps_temp_6cf5ba4c/app-FXWSJIOW.js ================================================ import "./chunk-SEVZ5PBP.js"; // node_modules/thirdweb/dist/esm/wallets/__generated__/wallet/app.keeper-wallet/index.js var wallet = { id: "app.keeper-wallet", name: "Keeper", homepage: "https://keeper-wallet.app", image_id: "41f6ac85-8f4e-4d9f-b37b-92b43fa7f400", app: { browser: "https://chrome.google.com/webstore/detail/keeper-wallet/lpilbniiabackdjcionkobglmddfbcjo", ios: "https://apps.apple.com/us/app/keeper-wallet/id6444443920", android: "https://play.google.com/store/apps/details?id=app.keeper.wallet", mac: "", windows: null, linux: null, chrome: null, firefox: null, safari: null, edge: null, opera: null }, rdns: null, mobile: { native: null, universal: "https://link.keeper-wallet.app" }, desktop: { native: null, universal: null } }; export { wallet }; //# sourceMappingURL=app-FXWSJIOW.js.map ================================================ FILE: 17-Crowd-Funding-Dapp/Frontend/.vite/deps_temp_6cf5ba4c/app-HGBIYGYJ.js ================================================ import "./chunk-SEVZ5PBP.js"; // node_modules/thirdweb/dist/esm/wallets/__generated__/wallet/app.dfinnwallet/index.js var wallet = { id: "app.dfinnwallet", name: "Dfinn Wallet", homepage: "https://dfinnwallet.app", image_id: "9a9c59ce-6346-4af8-db19-778533fb6000", app: { browser: null, ios: "https://apps.apple.com/us/app/dfinn-wallet/id6451134219", android: "https://play.google.com/store/apps/details?id=money.dfinn.wallet", mac: null, windows: null, linux: null, chrome: null, firefox: null, safari: null, edge: null, opera: null }, rdns: null, mobile: { native: "dfinnwallet://", universal: "https://dfinnwallet-link.vercel.app/" }, desktop: { native: null, universal: null } }; export { wallet }; //# sourceMappingURL=app-HGBIYGYJ.js.map ================================================ FILE: 17-Crowd-Funding-Dapp/Frontend/.vite/deps_temp_6cf5ba4c/app-HRMMGDE2.js ================================================ import "./chunk-SEVZ5PBP.js"; // node_modules/thirdweb/dist/esm/wallets/__generated__/wallet/app.linen/index.js var wallet = { id: "app.linen", name: "Linen", homepage: "https://linen.app/", image_id: "aff3e4e1-92a9-4066-f48f-3591947cf200", app: { browser: null, ios: "https://apps.apple.com/app/linen-app-investing-in-defi/id1480509067", android: "https://play.google.com/store/apps/details?id=app.linen.wallet", mac: "", windows: null, linux: null, chrome: null, firefox: null, safari: null, edge: null, opera: null }, rdns: null, mobile: { native: "linen://", universal: "https://linen.app/" }, desktop: { native: null, universal: null } }; export { wallet }; //# sourceMappingURL=app-HRMMGDE2.js.map ================================================ FILE: 17-Crowd-Funding-Dapp/Frontend/.vite/deps_temp_6cf5ba4c/app-IC2A3RDS.js ================================================ import "./chunk-SEVZ5PBP.js"; // node_modules/thirdweb/dist/esm/wallets/__generated__/wallet/app.stickey/index.js var wallet = { id: "app.stickey", name: "Stickey Wallet", homepage: "https://stickey.app", image_id: "12aab9fb-f3d4-4248-10e0-4eda17a5de00", app: { browser: "https://stickey.app", ios: "https://apps.apple.com/app/id1671113083", android: "https://play.google.com/store/apps/details?id=app.stickey", mac: null, windows: null, linux: null, chrome: null, firefox: null, safari: null, edge: null, opera: null }, rdns: null, mobile: { native: "stickyapp://", universal: "https://stickeyapp.page.link" }, desktop: { native: "stickyapp://", universal: "https://stickeyapp.page.link" } }; export { wallet }; //# sourceMappingURL=app-IC2A3RDS.js.map ================================================ FILE: 17-Crowd-Funding-Dapp/Frontend/.vite/deps_temp_6cf5ba4c/app-ICREXY5T.js ================================================ import "./chunk-SEVZ5PBP.js"; // node_modules/thirdweb/dist/esm/wallets/__generated__/wallet/app.subwallet/index.js var wallet = { id: "app.subwallet", name: "SubWallet", homepage: "https://www.subwallet.app/", image_id: "03f5c08c-fb30-46a0-ca5c-d8fdd7250b00", app: { browser: null, ios: "https://apps.apple.com/us/app/subwallet-polkadot-wallet/id1633050285", android: "https://play.google.com/store/apps/details?id=app.subwallet.mobile&hl=en_US", mac: null, windows: null, linux: null, chrome: "https://chrome.google.com/webstore/detail/subwallet-polkadot-wallet/onhogfjeacnfoofkfgppdlbmlmnplgbn", firefox: "https://addons.mozilla.org/en-US/firefox/addon/subwallet/", safari: null, edge: "https://chrome.google.com/webstore/detail/subwallet-polkadot-wallet/onhogfjeacnfoofkfgppdlbmlmnplgbn", opera: null }, rdns: "app.subwallet", mobile: { native: "subwallet://", universal: "https://mobile.subwallet.app/" }, desktop: { native: null, universal: null } }; export { wallet }; //# sourceMappingURL=app-ICREXY5T.js.map ================================================ FILE: 17-Crowd-Funding-Dapp/Frontend/.vite/deps_temp_6cf5ba4c/app-IEYL7BOV.js ================================================ import "./chunk-SEVZ5PBP.js"; // node_modules/thirdweb/dist/esm/wallets/__generated__/wallet/app.phantom/index.js var wallet = { id: "app.phantom", name: "Phantom", homepage: "https://phantom.app/", image_id: "c38443bb-b3c1-4697-e569-408de3fcc100", app: { browser: null, ios: null, android: null, mac: null, windows: null, linux: null, chrome: "https://chrome.google.com/webstore/detail/phantom/bfnaelmomeimhlpmgjnjophhpkkoljpa", firefox: "https://addons.mozilla.org/en-US/firefox/addon/phantom-app/", safari: null, edge: "https://chrome.google.com/webstore/detail/phantom/bfnaelmomeimhlpmgjnjophhpkkoljpa", opera: null }, rdns: "app.phantom", mobile: { native: null, universal: null }, desktop: { native: null, universal: null } }; export { wallet }; //# sourceMappingURL=app-IEYL7BOV.js.map ================================================ FILE: 17-Crowd-Funding-Dapp/Frontend/.vite/deps_temp_6cf5ba4c/app-IVIV25DE.js ================================================ import "./chunk-SEVZ5PBP.js"; // node_modules/thirdweb/dist/esm/wallets/__generated__/wallet/app.backpack/index.js var wallet = { id: "app.backpack", name: "Backpack", homepage: "https://backpack.app", image_id: "71ca9daf-a31e-4d2a-fd01-f5dc2dc66900", app: { browser: null, ios: "https://apps.apple.com/us/app/backpack-wallet-exchange/id6445964121", android: "https://play.google.com/store/apps/details?id=app.backpack.mobile", mac: null, windows: null, linux: null, chrome: "https://chrome.google.com/webstore/detail/backpack/aflkmfhebedbjioipglgcbcmnbpgliof", firefox: null, safari: null, edge: null, opera: null }, rdns: "app.backpack", mobile: { native: "backpack://", universal: "https://backpack.app/ul/v1" }, desktop: { native: null, universal: null } }; export { wallet }; //# sourceMappingURL=app-IVIV25DE.js.map ================================================ FILE: 17-Crowd-Funding-Dapp/Frontend/.vite/deps_temp_6cf5ba4c/app-J7XLYP5E.js ================================================ import "./chunk-SEVZ5PBP.js"; // node_modules/thirdweb/dist/esm/wallets/__generated__/wallet/app.wombat/index.js var wallet = { id: "app.wombat", name: "Wombat", homepage: "https://wombat.app", image_id: "e675efa3-4ffc-4199-9c22-b9692baea900", app: { browser: null, ios: "https://apps.apple.com/app/wombat-home-of-nft-gaming/id1474392110", android: "https://play.google.com/store/apps/details?id=io.getwombat.android", mac: null, windows: null, linux: null, chrome: null, firefox: null, safari: null, edge: null, opera: null }, rdns: null, mobile: { native: "wombat-wc://", universal: null }, desktop: { native: "wombat://", universal: null } }; export { wallet }; //# sourceMappingURL=app-J7XLYP5E.js.map ================================================ FILE: 17-Crowd-Funding-Dapp/Frontend/.vite/deps_temp_6cf5ba4c/app-JGIJQHBM.js ================================================ import "./chunk-SEVZ5PBP.js"; // node_modules/thirdweb/dist/esm/wallets/__generated__/wallet/app.ultimate/index.js var wallet = { id: "app.ultimate", name: "Ultimate", homepage: "https://ultimate.app/", image_id: "1ed9823d-64dd-4ab6-2f3f-22c8ff228f00", app: { browser: null, ios: "https://apps.apple.com/app/id1629053410", android: null, mac: null, windows: null, linux: null, chrome: null, firefox: null, safari: null, edge: null, opera: null }, rdns: null, mobile: { native: "ultimate://", universal: null }, desktop: { native: null, universal: null } }; export { wallet }; //# sourceMappingURL=app-JGIJQHBM.js.map ================================================ FILE: 17-Crowd-Funding-Dapp/Frontend/.vite/deps_temp_6cf5ba4c/app-JPKIQZES.js ================================================ import "./chunk-SEVZ5PBP.js"; // node_modules/thirdweb/dist/esm/wallets/__generated__/wallet/app.coinstats/index.js var wallet = { id: "app.coinstats", name: "CoinStats", homepage: "https://coinstats.app", image_id: "b2a00908-f144-4a49-cc0a-9d7422ad5e00", app: { browser: null, ios: "https://apps.apple.com/us/app/id1247849330", android: "https://play.google.com/store/apps/details?id=com.coinstats.crypto.portfolio", mac: "https://apps.apple.com/us/app/id1247849330", windows: null, linux: null, chrome: null, firefox: null, safari: null, edge: null, opera: null }, rdns: null, mobile: { native: "coinstats://", universal: "http://coinstats.app" }, desktop: { native: "coinstats://", universal: null } }; export { wallet }; //# sourceMappingURL=app-JPKIQZES.js.map ================================================ FILE: 17-Crowd-Funding-Dapp/Frontend/.vite/deps_temp_6cf5ba4c/app-KCNXS7XQ.js ================================================ import "./chunk-SEVZ5PBP.js"; // node_modules/thirdweb/dist/esm/wallets/__generated__/wallet/app.omni/index.js var wallet = { id: "app.omni", name: "Omni", homepage: "https://omni.app", image_id: "2cd67b4c-282b-4809-e7c0-a88cd5116f00", app: { browser: null, ios: "https://apps.apple.com/de/app/steakwallet/id1569375204?l=en", android: "https://play.google.com/store/apps/details?id=fi.steakwallet.app", mac: null, windows: null, linux: null, chrome: null, firefox: null, safari: null, edge: null, opera: null }, rdns: null, mobile: { native: "omni://", universal: "https://links.omni.app" }, desktop: { native: null, universal: null } }; export { wallet }; //# sourceMappingURL=app-KCNXS7XQ.js.map ================================================ FILE: 17-Crowd-Funding-Dapp/Frontend/.vite/deps_temp_6cf5ba4c/app-LUGTXPGI.js ================================================ import "./chunk-SEVZ5PBP.js"; // node_modules/thirdweb/dist/esm/wallets/__generated__/wallet/app.tofee/index.js var wallet = { id: "app.tofee", name: "Tofee Wallet Official", homepage: "https://tofee.app/", image_id: "d4dbb723-b1ec-4cfc-daab-1d559a151f00", app: { browser: null, ios: "https://apps.apple.com/in/app/tofee/id6504269605", android: null, mac: null, windows: null, linux: null, chrome: null, firefox: null, safari: null, edge: null, opera: null }, rdns: null, mobile: { native: "tofee://wallet", universal: "https://tofee.app/" }, desktop: { native: null, universal: null } }; export { wallet }; //# sourceMappingURL=app-LUGTXPGI.js.map ================================================ FILE: 17-Crowd-Funding-Dapp/Frontend/.vite/deps_temp_6cf5ba4c/app-M6LRY2SK.js ================================================ import "./chunk-SEVZ5PBP.js"; // node_modules/thirdweb/dist/esm/wallets/__generated__/wallet/app.keyring/index.js var wallet = { id: "app.keyring", name: "KEYRING PRO", homepage: "https://keyring.app/", image_id: "dda0f0fb-34e8-4a57-dcea-b008e7d1ff00", app: { browser: "https://keyring.app/", ios: "https://apps.apple.com/us/app/keyring-pro-wallet-management/id1546824976", android: "https://play.google.com/store/apps/details?id=co.bacoor.keyring", mac: null, windows: null, linux: null, chrome: null, firefox: null, safari: null, edge: null, opera: null }, rdns: null, mobile: { native: "keyring://", universal: "https://keyring.app/" }, desktop: { native: null, universal: null } }; export { wallet }; //# sourceMappingURL=app-M6LRY2SK.js.map ================================================ FILE: 17-Crowd-Funding-Dapp/Frontend/.vite/deps_temp_6cf5ba4c/app-MFHNNKPC.js ================================================ import "./chunk-SEVZ5PBP.js"; // node_modules/thirdweb/dist/esm/wallets/__generated__/wallet/app.clot/index.js var wallet = { id: "app.clot", name: "Clot", homepage: "https://clot.app", image_id: "a7d2716d-69b8-4422-9797-ed63b1f9c000", app: { browser: "https://clot.app", ios: "https://apps.apple.com/app/clot-wallet/id1584113315", android: null, mac: null, windows: null, linux: null, chrome: null, firefox: null, safari: null, edge: null, opera: null }, rdns: null, mobile: { native: "clot://", universal: null }, desktop: { native: null, universal: null } }; export { wallet }; //# sourceMappingURL=app-MFHNNKPC.js.map ================================================ FILE: 17-Crowd-Funding-Dapp/Frontend/.vite/deps_temp_6cf5ba4c/app-MS6Z5MIK.js ================================================ import "./chunk-SEVZ5PBP.js"; // node_modules/thirdweb/dist/esm/wallets/__generated__/wallet/app.everspace/index.js var wallet = { id: "app.everspace", name: "Everspace", homepage: "https://everspace.app", image_id: "80eaa630-6392-4b0a-a604-0a0f808e4d00", app: { browser: "https://everspace.app/", ios: "https://apps.apple.com/ru/app/everspace/id1585434994?l=en", android: "https://play.google.com/store/apps/details?id=com.oberton.app", mac: null, windows: null, linux: null, chrome: null, firefox: null, safari: null, edge: null, opera: null }, rdns: null, mobile: { native: "everspace://", universal: "https://everspace.app/deeplink" }, desktop: { native: null, universal: null } }; export { wallet }; //# sourceMappingURL=app-MS6Z5MIK.js.map ================================================ FILE: 17-Crowd-Funding-Dapp/Frontend/.vite/deps_temp_6cf5ba4c/app-O5DHUCKC.js ================================================ import "./chunk-SEVZ5PBP.js"; // node_modules/thirdweb/dist/esm/wallets/__generated__/wallet/app.krystal/index.js var wallet = { id: "app.krystal", name: "Krystal", homepage: "https://krystal.app/", image_id: "d2b59965-4eb8-4828-d3d4-fbc0b3379e00", app: { browser: "https://defi.krystal.app/", ios: "https://apps.apple.com/us/app/krystal-one-platform-all-defi/id1558105691", android: "https://play.google.com/store/apps/details?id=com.kyrd.krystal", mac: null, windows: null, linux: null, chrome: null, firefox: null, safari: null, edge: null, opera: null }, rdns: null, mobile: { native: "krystalwallet://", universal: "https://wallet.krystal.app/" }, desktop: { native: null, universal: null } }; export { wallet }; //# sourceMappingURL=app-O5DHUCKC.js.map ================================================ FILE: 17-Crowd-Funding-Dapp/Frontend/.vite/deps_temp_6cf5ba4c/app-OXRH4XRW.js ================================================ import "./chunk-SEVZ5PBP.js"; // node_modules/thirdweb/dist/esm/wallets/__generated__/wallet/app.m1nty/index.js var wallet = { id: "app.m1nty", name: "M1NTY", homepage: "https://m1nty.app", image_id: "6ccb7754-acd8-4de2-797e-a587a53d3900", app: { browser: "https://m1nty.app", ios: "https://apps.apple.com/app/m1nty/id1643737318", android: "https://play.google.com/store/apps/details?id=app.m1nty.android", mac: null, windows: null, linux: null, chrome: null, firefox: null, safari: null, edge: null, opera: null }, rdns: null, mobile: { native: "m1nty://", universal: null }, desktop: { native: null, universal: null } }; export { wallet }; //# sourceMappingURL=app-OXRH4XRW.js.map ================================================ FILE: 17-Crowd-Funding-Dapp/Frontend/.vite/deps_temp_6cf5ba4c/app-PUVYKP42.js ================================================ import "./chunk-SEVZ5PBP.js"; // node_modules/thirdweb/dist/esm/wallets/__generated__/wallet/app.zeal/index.js var wallet = { id: "app.zeal", name: "Zeal", homepage: "https://www.zeal.app/", image_id: "5416fb0b-9aec-4ffe-b7cd-c04c79ea4300", app: { browser: null, ios: null, android: null, mac: null, windows: null, linux: null, chrome: "https://chrome.google.com/webstore/detail/zeal-wallet/heamnjbnflcikcggoiplibfommfbkjpj?hl=en&authuser=0", firefox: null, safari: null, edge: null, opera: null }, rdns: "app.zeal", mobile: { native: "zeal://walletconnect/", universal: null }, desktop: { native: null, universal: null } }; export { wallet }; //# sourceMappingURL=app-PUVYKP42.js.map ================================================ FILE: 17-Crowd-Funding-Dapp/Frontend/.vite/deps_temp_6cf5ba4c/app-QASKZRBP.js ================================================ import "./chunk-SEVZ5PBP.js"; // node_modules/thirdweb/dist/esm/wallets/__generated__/wallet/app.sinum/index.js var wallet = { id: "app.sinum", name: "Sinum", homepage: "https://sinum.app/", image_id: "560d5efa-3fd1-4ac4-9229-f720395ab500", app: { browser: "https://app.sinum.io", ios: "https://apps.apple.com/gb/app/sinumapp/id6466151819?mt=8", android: "https://play.google.com/store/apps/details?id=io.sinum.wallet&referrer=af_tranid%3DnU7l_g2aK5j8sdqWOykU7g%26c%3DMAIN+WEBSITE+TO+ANDROID%26pid%3DMAIN+ANDROID&pli=1", mac: null, windows: null, linux: null, chrome: null, firefox: null, safari: null, edge: null, opera: null }, rdns: null, mobile: { native: "sinum://", universal: null }, desktop: { native: null, universal: null } }; export { wallet }; //# sourceMappingURL=app-QASKZRBP.js.map ================================================ FILE: 17-Crowd-Funding-Dapp/Frontend/.vite/deps_temp_6cf5ba4c/app-R4JLN24B.js ================================================ import "./chunk-SEVZ5PBP.js"; // node_modules/thirdweb/dist/esm/wallets/__generated__/wallet/app.imem/index.js var wallet = { id: "app.imem", name: "iMe", homepage: "https://imem.app/", image_id: "25aa3abf-901b-4d82-bb89-c5ade54c0c00", app: { browser: null, ios: "https://apps.apple.com/us/app/ime-messenger/id1450480822", android: "https://play.google.com/store/apps/details?id=com.iMe.android", mac: "", windows: null, linux: null, chrome: null, firefox: null, safari: null, edge: null, opera: null }, rdns: null, mobile: { native: "wc://", universal: null }, desktop: { native: null, universal: null } }; export { wallet }; //# sourceMappingURL=app-R4JLN24B.js.map ================================================ FILE: 17-Crowd-Funding-Dapp/Frontend/.vite/deps_temp_6cf5ba4c/app-RQXR7MZ5.js ================================================ import "./chunk-SEVZ5PBP.js"; // node_modules/thirdweb/dist/esm/wallets/__generated__/wallet/app.core/index.js var wallet = { id: "app.core", name: "Core", homepage: "https://core.app/?utm_source=referral&utm_medium=website&utm_campaign=walletconnect", image_id: "35f9c46e-cc57-4aa7-315d-e6ccb2a1d600", app: { browser: null, ios: "https://apps.apple.com/us/app/core-crypto-wallet-nfts/id6443685999", android: "https://play.google.com/store/apps/details?id=com.avaxwallet&hl=en_US&gl=US", mac: null, windows: null, linux: null, chrome: "https://chrome.google.com/webstore/detail/core-crypto-wallet-nft-ex/agoakfejjabomempkjlepdflaleeobhb", firefox: null, safari: null, edge: null, opera: null }, rdns: null, mobile: { native: "core://", universal: "https://core.app" }, desktop: { native: null, universal: null } }; export { wallet }; //# sourceMappingURL=app-RQXR7MZ5.js.map ================================================ FILE: 17-Crowd-Funding-Dapp/Frontend/.vite/deps_temp_6cf5ba4c/app-RRYWU2T6.js ================================================ import "./chunk-SEVZ5PBP.js"; // node_modules/thirdweb/dist/esm/wallets/__generated__/wallet/app.onto/index.js var wallet = { id: "app.onto", name: "ONTO", homepage: "https://onto.app", image_id: "14934596-632e-4b29-d45f-61109e959000", app: { browser: null, ios: "https://apps.apple.com/us/app/onto-an-ontology-dapp/id1436009823", android: "https://play.google.com/store/apps/details?id=com.github.ontio.onto", mac: null, windows: null, linux: null, chrome: null, firefox: null, safari: null, edge: null, opera: null }, rdns: null, mobile: { native: "ontoprovider://", universal: null }, desktop: { native: null, universal: null } }; export { wallet }; //# sourceMappingURL=app-RRYWU2T6.js.map ================================================ FILE: 17-Crowd-Funding-Dapp/Frontend/.vite/deps_temp_6cf5ba4c/app-SFALV7Q7.js ================================================ import "./chunk-SEVZ5PBP.js"; // node_modules/thirdweb/dist/esm/wallets/__generated__/wallet/app.kabila/index.js var wallet = { id: "app.kabila", name: "Kabila Wallet", homepage: "https://kabila.app/", image_id: "e6263e25-7f31-4186-5ad4-75e17312c500", app: { browser: "https://wallet.kabila.app/", ios: "https://apps.apple.com/es/app/kabila-wallet/id6467106529", android: "https://play.google.com/store/apps/details?id=wallet.kabila.app&hl=es_419&gl=US", mac: null, windows: null, linux: null, chrome: "https://chromewebstore.google.com/detail/kabila-wallet/cnoepnljjcacmnjnopbhjelpmfokpijm", firefox: null, safari: null, edge: null, opera: null }, rdns: null, mobile: { native: null, universal: "https://wallet.kabila.app" }, desktop: { native: null, universal: "https://wallet.kabila.app" } }; export { wallet }; //# sourceMappingURL=app-SFALV7Q7.js.map ================================================ FILE: 17-Crowd-Funding-Dapp/Frontend/.vite/deps_temp_6cf5ba4c/app-VCRSWMVS.js ================================================ import "./chunk-SEVZ5PBP.js"; // node_modules/thirdweb/dist/esm/wallets/__generated__/wallet/app.pluswallet/index.js var wallet = { id: "app.pluswallet", name: "Plus Wallet", homepage: "https://pluswallet.app", image_id: "2c21491b-58ce-47bb-ace9-bdef71f43600", app: { browser: null, ios: "https://apps.apple.com/us/app/plus-wallet-app/id6467651848", android: "https://play.google.com/store/apps/details?id=com.PlusWallet", mac: null, windows: null, linux: null, chrome: null, firefox: null, safari: null, edge: null, opera: null }, rdns: null, mobile: { native: "pluswallet://", universal: "https://pluswallet.app" }, desktop: { native: null, universal: null } }; export { wallet }; //# sourceMappingURL=app-VCRSWMVS.js.map ================================================ FILE: 17-Crowd-Funding-Dapp/Frontend/.vite/deps_temp_6cf5ba4c/app-XKLTXZZ5.js ================================================ import "./chunk-SEVZ5PBP.js"; // node_modules/thirdweb/dist/esm/wallets/__generated__/wallet/app.herewallet/index.js var wallet = { id: "app.herewallet", name: "HERE Wallet", homepage: "https://herewallet.app", image_id: "21cadc07-2f45-4860-3358-83a2057b6300", app: { browser: null, ios: "https://download.herewallet.app?ios", android: "https://download.herewallet.app?android", mac: "", windows: null, linux: null, chrome: null, firefox: null, safari: null, edge: null, opera: null }, rdns: null, mobile: { native: "herewallet://", universal: "https://my.herewallet" }, desktop: { native: null, universal: null } }; export { wallet }; //# sourceMappingURL=app-XKLTXZZ5.js.map ================================================ FILE: 17-Crowd-Funding-Dapp/Frontend/.vite/deps_temp_6cf5ba4c/app-XMYPKI5F.js ================================================ import "./chunk-SEVZ5PBP.js"; // node_modules/thirdweb/dist/esm/wallets/__generated__/wallet/app.beewallet/index.js var wallet = { id: "app.beewallet", name: "Bee Wallet", homepage: "https://www.beewallet.app", image_id: "f90bc33f-f085-40cf-7538-fae5ae84f900", app: { browser: null, ios: "https://apps.apple.com/lt/app/bee-for-uniswap-pancakeswap/id1617257467", android: null, mac: null, windows: null, linux: null, chrome: null, firefox: null, safari: null, edge: null, opera: null }, rdns: null, mobile: { native: "beewallet.app://", universal: "https://beewallet.app/wc" }, desktop: { native: null, universal: null } }; export { wallet }; //# sourceMappingURL=app-XMYPKI5F.js.map ================================================ FILE: 17-Crowd-Funding-Dapp/Frontend/.vite/deps_temp_6cf5ba4c/app-YG5QZHYU.js ================================================ import "./chunk-SEVZ5PBP.js"; // node_modules/thirdweb/dist/esm/wallets/__generated__/wallet/app.nightly/index.js var wallet = { id: "app.nightly", name: "Nightly", homepage: "https://nightly.app", image_id: "7fb6e288-6d7e-4f29-d934-8b3f229c2d00", app: { browser: null, ios: "https://apps.apple.com/pl/app/nightly-multichain-wallet/id6444768157", android: "https://play.google.com/store/apps/details?id=com.nightlymobile&pli=1", mac: null, windows: null, linux: null, chrome: "https://chromewebstore.google.com/detail/nightly/fiikommddbeccaoicoejoniammnalkfa", firefox: null, safari: null, edge: "https://chromewebstore.google.com/detail/nightly/fiikommddbeccaoicoejoniammnalkfa", opera: "https://chromewebstore.google.com/detail/nightly/fiikommddbeccaoicoejoniammnalkfa" }, rdns: "app.nightly", mobile: { native: null, universal: null }, desktop: { native: null, universal: null } }; export { wallet }; //# sourceMappingURL=app-YG5QZHYU.js.map ================================================ FILE: 17-Crowd-Funding-Dapp/Frontend/.vite/deps_temp_6cf5ba4c/app-Z3ZKSY2N.js ================================================ import "./chunk-SEVZ5PBP.js"; // node_modules/thirdweb/dist/esm/wallets/__generated__/wallet/app.fizzwallet/index.js var wallet = { id: "app.fizzwallet", name: "Fizz", homepage: "https://www.fizzwallet.app/", image_id: "f9d4db84-2e9f-4fbe-684f-c1e921c98800", app: { browser: null, ios: "https://apps.apple.com/kr/app/fizz-fun-ezzy-crypto-wallet/id6447460538", android: null, mac: null, windows: null, linux: null, chrome: null, firefox: null, safari: null, edge: null, opera: null }, rdns: null, mobile: { native: "fizz://wallet-connect", universal: null }, desktop: { native: null, universal: null } }; export { wallet }; //# sourceMappingURL=app-Z3ZKSY2N.js.map ================================================ FILE: 17-Crowd-Funding-Dapp/Frontend/.vite/deps_temp_6cf5ba4c/app.core-FOKZSNJL.js ================================================ import "./chunk-SEVZ5PBP.js"; // node_modules/thirdweb/dist/esm/wallets/__generated__/wallet/app.core.extension/index.js var wallet = { id: "app.core.extension", name: "Core", homepage: "https://core.app/?utm_source=referral&utm_medium=website&utm_campaign=walletconnect", image_id: "core.svg", app: { browser: null, ios: "https://apps.apple.com/us/app/core-crypto-wallet-nfts/id6443685999", android: "https://play.google.com/store/apps/details?id=com.avaxwallet&hl=en_US&gl=US", mac: null, windows: null, linux: null, chrome: "https://chrome.google.com/webstore/detail/core-crypto-wallet-nft-ex/agoakfejjabomempkjlepdflaleeobhb", firefox: null, safari: null, edge: null, opera: null }, rdns: "app.core.extension", mobile: { native: null, universal: null }, desktop: { native: null, universal: null } }; export { wallet }; //# sourceMappingURL=app.core-FOKZSNJL.js.map ================================================ FILE: 17-Crowd-Funding-Dapp/Frontend/.vite/deps_temp_6cf5ba4c/app.qubic-45GFYY2N.js ================================================ import "./chunk-SEVZ5PBP.js"; // node_modules/thirdweb/dist/esm/wallets/__generated__/wallet/app.qubic.wallet/index.js var wallet = { id: "app.qubic.wallet", name: "Qubic Wallet", homepage: "https://wallet.qubic.app", image_id: "535c91a5-a43c-4104-233c-439449ffcd00", app: { browser: "https://wallet.qubic.app", ios: "https://apps.apple.com/app/qubic-%E6%9C%80%E7%B0%A1%E5%96%AE%E4%B8%8A%E6%89%8B%E7%9A%84%E8%99%9B%E6%93%AC%E8%B2%A8%E5%B9%A3%E9%8C%A2%E5%8C%85/id1563987988?itsct=apps_box_link&itscg=30200", android: "https://play.google.com/store/apps/details?id=app.qubic.wallet", mac: null, windows: null, linux: null, chrome: null, firefox: null, safari: null, edge: null, opera: null }, rdns: null, mobile: { native: "qubic://", universal: "https://wallet.qubic.app" }, desktop: { native: null, universal: null } }; export { wallet }; //# sourceMappingURL=app.qubic-45GFYY2N.js.map ================================================ FILE: 17-Crowd-Funding-Dapp/Frontend/.vite/deps_temp_6cf5ba4c/arweave-57OCWZ5C.js ================================================ import { resolveArweaveScheme } from "./chunk-6FLJU7W7.js"; import "./chunk-SEVZ5PBP.js"; export { resolveArweaveScheme }; //# sourceMappingURL=arweave-57OCWZ5C.js.map ================================================ FILE: 17-Crowd-Funding-Dapp/Frontend/.vite/deps_temp_6cf5ba4c/auth-ZNEFTCXD.js ================================================ import { authenticate, authenticateWithRedirect, getProfiles, getUserEmail, getUserPhoneNumber, linkProfile, preAuthenticate } from "./chunk-65EUCVOP.js"; import "./chunk-6WNCTW75.js"; import "./chunk-QLJVAXYD.js"; import "./chunk-CLN3QXW2.js"; import "./chunk-N24CESYN.js"; import "./chunk-NJUWOGZE.js"; import "./chunk-TFBEDS4S.js"; import "./chunk-GOA7IGSB.js"; import "./chunk-QHKZ43P6.js"; import "./chunk-3GSJ2FQJ.js"; import "./chunk-P7ZDTV2E.js"; import "./chunk-SNQ54XRM.js"; import "./chunk-SEVZ5PBP.js"; export { authenticate, authenticateWithRedirect, getProfiles, getUserEmail, getUserPhoneNumber, linkProfile, preAuthenticate }; //# sourceMappingURL=auth-ZNEFTCXD.js.map ================================================ FILE: 17-Crowd-Funding-Dapp/Frontend/.vite/deps_temp_6cf5ba4c/baby-VXQWXU2X.js ================================================ import "./chunk-SEVZ5PBP.js"; // node_modules/thirdweb/dist/esm/wallets/__generated__/wallet/baby.smart/index.js var wallet = { id: "baby.smart", name: "Smart.Baby", homepage: "https://smart.baby", image_id: "7f408502-e3d1-48f1-a81f-654a3f338f00", app: { browser: null, ios: null, android: "https://smartbaby.oss-cn-hongkong.aliyuncs.com/wallet/20230912/e94cee9101074e54a717415cccd11a87.apk", mac: null, windows: null, linux: null, chrome: null, firefox: null, safari: null, edge: null, opera: null }, rdns: null, mobile: { native: "smartbody://?uri=", universal: null }, desktop: { native: null, universal: null } }; export { wallet }; //# sourceMappingURL=baby-VXQWXU2X.js.map ================================================ FILE: 17-Crowd-Funding-Dapp/Frontend/.vite/deps_temp_6cf5ba4c/balanceOf-77XLALLF.js ================================================ import { detectMethod } from "./chunk-PK5NRJAC.js"; import { readContract } from "./chunk-AG4NO6K6.js"; import "./chunk-NPJBMLFY.js"; import "./chunk-YPFLLHK6.js"; import "./chunk-7EY5MWB2.js"; import { encodeAbiParameters } from "./chunk-U7TO6S3N.js"; import "./chunk-LO5SQBMX.js"; import "./chunk-EIVAOYE5.js"; import "./chunk-67BSOYLQ.js"; import "./chunk-B7XHB4Z2.js"; import "./chunk-O6UZ65WN.js"; import { decodeAbiParameters } from "./chunk-GINVHONX.js"; import "./chunk-O6LGEXJ4.js"; import "./chunk-ME5GAE4N.js"; import "./chunk-I5DK3TWY.js"; import "./chunk-NJUWOGZE.js"; import "./chunk-TFBEDS4S.js"; import "./chunk-GOA7IGSB.js"; import "./chunk-QHKZ43P6.js"; import "./chunk-3GSJ2FQJ.js"; import "./chunk-P7ZDTV2E.js"; import "./chunk-SNQ54XRM.js"; import "./chunk-BBNNHC5G.js"; import "./chunk-Y3WKETHV.js"; import "./chunk-SPELR2RL.js"; import "./chunk-SEVZ5PBP.js"; // node_modules/thirdweb/dist/esm/extensions/erc1155/__generated__/IERC1155/read/balanceOf.js var FN_SELECTOR = "0x00fdd58e"; var FN_INPUTS = [ { type: "address", name: "_owner" }, { type: "uint256", name: "tokenId" } ]; var FN_OUTPUTS = [ { type: "uint256" } ]; function isBalanceOfSupported(availableSelectors) { return detectMethod({ availableSelectors, method: [FN_SELECTOR, FN_INPUTS, FN_OUTPUTS] }); } function encodeBalanceOfParams(options) { return encodeAbiParameters(FN_INPUTS, [options.owner, options.tokenId]); } function encodeBalanceOf(options) { return FN_SELECTOR + encodeBalanceOfParams(options).slice(2); } function decodeBalanceOfResult(result) { return decodeAbiParameters(FN_OUTPUTS, result)[0]; } async function balanceOf(options) { return readContract({ contract: options.contract, method: [FN_SELECTOR, FN_INPUTS, FN_OUTPUTS], params: [options.owner, options.tokenId] }); } export { FN_SELECTOR, balanceOf, decodeBalanceOfResult, encodeBalanceOf, encodeBalanceOfParams, isBalanceOfSupported }; //# sourceMappingURL=balanceOf-77XLALLF.js.map ================================================ FILE: 17-Crowd-Funding-Dapp/Frontend/.vite/deps_temp_6cf5ba4c/biconomy-PIJEZ3DY.js ================================================ import { ZERO_ADDRESS } from "./chunk-673YCYST.js"; import { getContract } from "./chunk-7VZHRFCE.js"; import { readContract } from "./chunk-AG4NO6K6.js"; import "./chunk-NPJBMLFY.js"; import "./chunk-YPFLLHK6.js"; import "./chunk-7EY5MWB2.js"; import "./chunk-U7TO6S3N.js"; import "./chunk-LO5SQBMX.js"; import "./chunk-EIVAOYE5.js"; import { keccak256 } from "./chunk-67BSOYLQ.js"; import "./chunk-B7XHB4Z2.js"; import "./chunk-O6UZ65WN.js"; import { encodeAbiParameters } from "./chunk-GINVHONX.js"; import "./chunk-O6LGEXJ4.js"; import "./chunk-ME5GAE4N.js"; import "./chunk-I5DK3TWY.js"; import { stringify } from "./chunk-NJUWOGZE.js"; import "./chunk-TFBEDS4S.js"; import "./chunk-GOA7IGSB.js"; import "./chunk-QHKZ43P6.js"; import "./chunk-3GSJ2FQJ.js"; import "./chunk-P7ZDTV2E.js"; import "./chunk-SNQ54XRM.js"; import { isHex } from "./chunk-BBNNHC5G.js"; import "./chunk-Y3WKETHV.js"; import "./chunk-SPELR2RL.js"; import "./chunk-SEVZ5PBP.js"; // node_modules/thirdweb/dist/esm/transaction/actions/gasless/providers/biconomy.js var BATCH_ID = 0n; async function prepareBiconomyTransaction({ account, serializableTransaction, transaction, gasless }) { const forwarderContract = getContract({ address: gasless.relayerForwarderAddress, chain: transaction.chain, client: transaction.client }); const nonce = await readContract({ contract: forwarderContract, method: "function getNonce(address,uint256) view returns (uint256)", params: [account.address, BATCH_ID] }); const deadline = Math.floor(Date.now() / 1e3) + (gasless.deadlineSeconds ?? 3600); const request = { from: account.address, to: serializableTransaction.to, token: ZERO_ADDRESS, txGas: serializableTransaction.gas, tokenGasPrice: 0n, batchId: BATCH_ID, batchNonce: nonce, deadline, data: serializableTransaction.data }; if (!request.to) { throw new Error("Cannot send a transaction without a `to` address"); } if (!request.txGas) { throw new Error("Cannot send a transaction without a `gas` value"); } if (!request.data) { throw new Error("Cannot send a transaction without a `data` value"); } const message = encodeAbiParameters([ { type: "address" }, { type: "address" }, { type: "address" }, { type: "uint256" }, { type: "uint256" }, { type: "uint256" }, { type: "uint256" }, { type: "bytes32" } ], [ request.from, request.to, request.token, request.txGas, request.tokenGasPrice, request.batchId, request.batchNonce, keccak256(request.data) ]); const signature = await account.signMessage({ message }); return [request, signature]; } async function relayBiconomyTransaction(options) { var _a; const [request, signature] = await prepareBiconomyTransaction(options); const response = await fetch("https://api.biconomy.io/api/v2/meta-tx/native", { method: "POST", body: stringify({ apiId: options.gasless.apiId, params: [request, signature], from: request.from, to: request.to, gasLimit: request.txGas }), headers: { "x-api-key": options.gasless.apiKey, "Content-Type": "application/json;charset=utf-8" } }); if (!response.ok) { (_a = response.body) == null ? void 0 : _a.cancel(); throw new Error(`Failed to send transaction: ${await response.text()}`); } const json = await response.json(); const transactionHash = json.txHash; if (isHex(transactionHash)) { return { transactionHash, chain: options.transaction.chain, client: options.transaction.client }; } throw new Error(`Failed to send transaction: ${stringify(json)}`); } export { prepareBiconomyTransaction, relayBiconomyTransaction }; //# sourceMappingURL=biconomy-PIJEZ3DY.js.map ================================================ FILE: 17-Crowd-Funding-Dapp/Frontend/.vite/deps_temp_6cf5ba4c/buyFromListing-NAQIOY7I.js ================================================ import { getListing, isGetListingSupported, isListingValid } from "./chunk-M3WBOOWW.js"; import "./chunk-QLCPWJYR.js"; import "./chunk-GGVPULQZ.js"; import "./chunk-6RU56BH7.js"; import "./chunk-QVNJVROL.js"; import { once, prepareContractCall } from "./chunk-6XF6HOWC.js"; import "./chunk-CXAZLQ2Z.js"; import "./chunk-QC3K2OKT.js"; import "./chunk-UY2SRO54.js"; import { isNativeTokenAddress } from "./chunk-673YCYST.js"; import { detectMethod } from "./chunk-PK5NRJAC.js"; import "./chunk-7VZHRFCE.js"; import "./chunk-CNLOA7AS.js"; import "./chunk-AG4NO6K6.js"; import "./chunk-NPJBMLFY.js"; import "./chunk-YPFLLHK6.js"; import "./chunk-7EY5MWB2.js"; import "./chunk-U7TO6S3N.js"; import "./chunk-LO5SQBMX.js"; import "./chunk-EIVAOYE5.js"; import "./chunk-67BSOYLQ.js"; import "./chunk-B7XHB4Z2.js"; import "./chunk-O6UZ65WN.js"; import "./chunk-GINVHONX.js"; import "./chunk-O6LGEXJ4.js"; import "./chunk-ME5GAE4N.js"; import "./chunk-I5DK3TWY.js"; import "./chunk-NJUWOGZE.js"; import "./chunk-TFBEDS4S.js"; import "./chunk-GOA7IGSB.js"; import "./chunk-QHKZ43P6.js"; import "./chunk-3GSJ2FQJ.js"; import "./chunk-P7ZDTV2E.js"; import "./chunk-SNQ54XRM.js"; import "./chunk-BBNNHC5G.js"; import "./chunk-Y3WKETHV.js"; import "./chunk-SPELR2RL.js"; import "./chunk-SEVZ5PBP.js"; // node_modules/thirdweb/dist/esm/extensions/marketplace/__generated__/IDirectListings/write/buyFromListing.js var FN_SELECTOR = "0x704232dc"; var FN_INPUTS = [ { type: "uint256", name: "_listingId" }, { type: "address", name: "_buyFor" }, { type: "uint256", name: "_quantity" }, { type: "address", name: "_currency" }, { type: "uint256", name: "_expectedTotalPrice" } ]; var FN_OUTPUTS = []; function isBuyFromListingSupported(availableSelectors) { return detectMethod({ availableSelectors, method: [FN_SELECTOR, FN_INPUTS, FN_OUTPUTS] }); } function buyFromListing(options) { const asyncOptions = once(async () => { return "asyncParams" in options ? await options.asyncParams() : options; }); return prepareContractCall({ contract: options.contract, method: [FN_SELECTOR, FN_INPUTS, FN_OUTPUTS], params: async () => { const resolvedOptions = await asyncOptions(); return [ resolvedOptions.listingId, resolvedOptions.buyFor, resolvedOptions.quantity, resolvedOptions.currency, resolvedOptions.expectedTotalPrice ]; }, value: async () => { var _a; return (_a = (await asyncOptions()).overrides) == null ? void 0 : _a.value; }, accessList: async () => { var _a; return (_a = (await asyncOptions()).overrides) == null ? void 0 : _a.accessList; }, gas: async () => { var _a; return (_a = (await asyncOptions()).overrides) == null ? void 0 : _a.gas; }, gasPrice: async () => { var _a; return (_a = (await asyncOptions()).overrides) == null ? void 0 : _a.gasPrice; }, maxFeePerGas: async () => { var _a; return (_a = (await asyncOptions()).overrides) == null ? void 0 : _a.maxFeePerGas; }, maxPriorityFeePerGas: async () => { var _a; return (_a = (await asyncOptions()).overrides) == null ? void 0 : _a.maxPriorityFeePerGas; }, nonce: async () => { var _a; return (_a = (await asyncOptions()).overrides) == null ? void 0 : _a.nonce; }, extraGas: async () => { var _a; return (_a = (await asyncOptions()).overrides) == null ? void 0 : _a.extraGas; }, erc20Value: async () => { var _a; return (_a = (await asyncOptions()).overrides) == null ? void 0 : _a.erc20Value; } }); } // node_modules/thirdweb/dist/esm/extensions/marketplace/direct-listings/write/buyFromListing.js function buyFromListing2(options) { return buyFromListing({ contract: options.contract, asyncParams: async () => { const listing = await getListing({ contract: options.contract, listingId: options.listingId }); const listingValidity = await isListingValid({ contract: options.contract, listing, quantity: options.quantity }); if (!listingValidity.valid) { throw new Error(listingValidity.reason); } return { listingId: options.listingId, quantity: options.quantity, buyFor: options.recipient, currency: listing.currencyContractAddress, expectedTotalPrice: listing.pricePerToken * options.quantity, overrides: { value: isNativeTokenAddress(listing.currencyContractAddress) ? listing.pricePerToken * options.quantity : 0n, extraGas: 50000n // add extra gas to account for router call } }; } }); } function isBuyFromListingSupported2(availableSelectors) { return isBuyFromListingSupported(availableSelectors) && isGetListingSupported(availableSelectors); } export { buyFromListing2 as buyFromListing, isBuyFromListingSupported2 as isBuyFromListingSupported }; //# sourceMappingURL=buyFromListing-NAQIOY7I.js.map ================================================ FILE: 17-Crowd-Funding-Dapp/Frontend/.vite/deps_temp_6cf5ba4c/cc-VULA5ISR.js ================================================ import "./chunk-SEVZ5PBP.js"; // node_modules/thirdweb/dist/esm/wallets/__generated__/wallet/cc.dropp/index.js var wallet = { id: "cc.dropp", name: "Dropp", homepage: "https://dropp.cc/", image_id: "526fb7ea-d0da-482a-ac84-7e38afea1700", app: { browser: null, ios: "https://apps.apple.com/us/app/dropp-cc/id1544894404", android: "https://play.google.com/store/apps/details?id=cc.dropp.wallet", mac: null, windows: null, linux: null, chrome: "https://chrome.google.com/webstore/detail/dropp-extension/hgfpnmhnmmneldokmpncjmeijkapgbbf?hl=en-US", firefox: null, safari: null, edge: null, opera: null }, rdns: null, mobile: { native: "dropp://", universal: null }, desktop: { native: null, universal: null } }; export { wallet }; //# sourceMappingURL=cc-VULA5ISR.js.map ================================================ FILE: 17-Crowd-Funding-Dapp/Frontend/.vite/deps_temp_6cf5ba4c/cc-XODV5KUP.js ================================================ import "./chunk-SEVZ5PBP.js"; // node_modules/thirdweb/dist/esm/wallets/__generated__/wallet/cc.avacus/index.js var wallet = { id: "cc.avacus", name: "Avacus", homepage: "https://avacus.cc", image_id: "a7106965-91cc-4a73-4688-c5c72ae0ed00", app: { browser: null, ios: "https://apps.apple.com/us/app/id6449657442", android: "https://play.google.com/store/apps/details?id=io.sowaka.avacus", mac: null, windows: null, linux: null, chrome: null, firefox: null, safari: null, edge: null, opera: null }, rdns: null, mobile: { native: "avacus://", universal: "https://avacus.app.link" }, desktop: { native: null, universal: null } }; export { wallet }; //# sourceMappingURL=cc-XODV5KUP.js.map ================================================ FILE: 17-Crowd-Funding-Dapp/Frontend/.vite/deps_temp_6cf5ba4c/cc.localtrade-QLM7DIOM.js ================================================ import "./chunk-SEVZ5PBP.js"; // node_modules/thirdweb/dist/esm/wallets/__generated__/wallet/cc.localtrade.lab/index.js var wallet = { id: "cc.localtrade.lab", name: "LocalTrade Wallet", homepage: "https://lab.localtrade.cc", image_id: "fcc60983-74ae-484a-4242-87cb6f05f100", app: { browser: "https://docs.localtrade.cc/products/defi-wallet-mvp-for-ios", ios: "https://apps.apple.com/app/localtrade-defi-wallet/id1602772298", android: "https://play.google.com/store/apps/details?id=com.localtrade.wallet", mac: null, windows: null, linux: null, chrome: null, firefox: null, safari: null, edge: null, opera: null }, rdns: null, mobile: { native: null, universal: "https://ws.lab.localtrade.cc" }, desktop: { native: null, universal: null } }; export { wallet }; //# sourceMappingURL=cc.localtrade-QLM7DIOM.js.map ================================================ FILE: 17-Crowd-Funding-Dapp/Frontend/.vite/deps_temp_6cf5ba4c/ccip-BECV2KBX.js ================================================ import { ccipRequest, offchainLookup, offchainLookupAbiItem, offchainLookupSignature } from "./chunk-GINVHONX.js"; import "./chunk-O6LGEXJ4.js"; import "./chunk-ME5GAE4N.js"; import "./chunk-SEVZ5PBP.js"; export { ccipRequest, offchainLookup, offchainLookupAbiItem, offchainLookupSignature }; //# sourceMappingURL=ccip-BECV2KBX.js.map ================================================ FILE: 17-Crowd-Funding-Dapp/Frontend/.vite/deps_temp_6cf5ba4c/ch-DJKOH7L6.js ================================================ import "./chunk-SEVZ5PBP.js"; // node_modules/thirdweb/dist/esm/wallets/__generated__/wallet/ch.dssecurity/index.js var wallet = { id: "ch.dssecurity", name: "DS Security SA", homepage: "https://www.dssecurity.ch", image_id: "149a10a6-8914-44ea-424a-236017890100", app: { browser: "https://wiki.polygon.technology/docs/tools/wallets/metamask/config-polygon-on-metamask#polygon-scan", ios: "https://dssecurity.ch", android: "https://dssecurity.ch", mac: "https://dssecurity.ch", windows: "https://dssecurity.ch", linux: "https://dssecurity.ch", chrome: "https://dssecurity.ch", firefox: "https://dssecurity.ch", safari: "https://dssecurity.ch", edge: "https://dssecurity.ch", opera: "https://dssecurity.ch" }, rdns: null, mobile: { native: null, universal: "https://www.coinbase.com/wallet/" }, desktop: { native: null, universal: "https://www.coinbase.com/wallet/" } }; export { wallet }; //# sourceMappingURL=ch-DJKOH7L6.js.map ================================================ FILE: 17-Crowd-Funding-Dapp/Frontend/.vite/deps_temp_6cf5ba4c/checkContractWalletSignature-6DFUQS7E.js ================================================ import { isValidSignature } from "./chunk-U55JVTZU.js"; import "./chunk-PK5NRJAC.js"; import "./chunk-AG4NO6K6.js"; import "./chunk-NPJBMLFY.js"; import "./chunk-YPFLLHK6.js"; import "./chunk-7EY5MWB2.js"; import "./chunk-U7TO6S3N.js"; import { hashMessage } from "./chunk-LO5SQBMX.js"; import "./chunk-EIVAOYE5.js"; import "./chunk-67BSOYLQ.js"; import "./chunk-B7XHB4Z2.js"; import "./chunk-O6UZ65WN.js"; import "./chunk-GINVHONX.js"; import "./chunk-O6LGEXJ4.js"; import "./chunk-ME5GAE4N.js"; import "./chunk-I5DK3TWY.js"; import "./chunk-NJUWOGZE.js"; import "./chunk-TFBEDS4S.js"; import "./chunk-GOA7IGSB.js"; import "./chunk-QHKZ43P6.js"; import "./chunk-3GSJ2FQJ.js"; import "./chunk-P7ZDTV2E.js"; import "./chunk-SNQ54XRM.js"; import { isHex } from "./chunk-BBNNHC5G.js"; import "./chunk-Y3WKETHV.js"; import "./chunk-SPELR2RL.js"; import "./chunk-SEVZ5PBP.js"; // node_modules/thirdweb/dist/esm/extensions/erc1271/checkContractWalletSignature.js var MAGIC_VALUE = "0x1626ba7e"; async function checkContractWalletSignature(options) { if (!isHex(options.signature)) { throw new Error("The signature must be a valid hex string."); } const result = await isValidSignature({ contract: options.contract, hash: hashMessage(options.message), signature: options.signature }); return result === MAGIC_VALUE; } export { checkContractWalletSignature }; //# sourceMappingURL=checkContractWalletSignature-6DFUQS7E.js.map ================================================ FILE: 17-Crowd-Funding-Dapp/Frontend/.vite/deps_temp_6cf5ba4c/checkContractWalletSignedTypedData-SEVCYJA7.js ================================================ import { isValidSignature } from "./chunk-U55JVTZU.js"; import "./chunk-PK5NRJAC.js"; import "./chunk-AG4NO6K6.js"; import "./chunk-NPJBMLFY.js"; import "./chunk-YPFLLHK6.js"; import "./chunk-7EY5MWB2.js"; import "./chunk-U7TO6S3N.js"; import { hashTypedData } from "./chunk-LO5SQBMX.js"; import "./chunk-EIVAOYE5.js"; import "./chunk-67BSOYLQ.js"; import "./chunk-B7XHB4Z2.js"; import "./chunk-O6UZ65WN.js"; import "./chunk-GINVHONX.js"; import "./chunk-O6LGEXJ4.js"; import "./chunk-ME5GAE4N.js"; import "./chunk-I5DK3TWY.js"; import "./chunk-NJUWOGZE.js"; import "./chunk-TFBEDS4S.js"; import "./chunk-GOA7IGSB.js"; import "./chunk-QHKZ43P6.js"; import "./chunk-3GSJ2FQJ.js"; import "./chunk-P7ZDTV2E.js"; import "./chunk-SNQ54XRM.js"; import { isHex } from "./chunk-BBNNHC5G.js"; import "./chunk-Y3WKETHV.js"; import "./chunk-SPELR2RL.js"; import "./chunk-SEVZ5PBP.js"; // node_modules/thirdweb/dist/esm/extensions/erc1271/checkContractWalletSignedTypedData.js var MAGIC_VALUE = "0x1626ba7e"; async function checkContractWalletSignedTypedData(options) { if (!isHex(options.signature)) { throw new Error("The signature must be a valid hex string."); } const result = await isValidSignature({ contract: options.contract, hash: hashTypedData(options.data), signature: options.signature }); return result === MAGIC_VALUE; } export { checkContractWalletSignedTypedData }; //# sourceMappingURL=checkContractWalletSignedTypedData-SEVCYJA7.js.map ================================================ FILE: 17-Crowd-Funding-Dapp/Frontend/.vite/deps_temp_6cf5ba4c/chunk-253DMNI3.js ================================================ import { detectMethod } from "./chunk-PK5NRJAC.js"; import { readContract } from "./chunk-AG4NO6K6.js"; import { decodeAbiParameters } from "./chunk-GINVHONX.js"; // node_modules/thirdweb/dist/esm/extensions/erc721/__generated__/IDropSinglePhase/read/claimCondition.js var FN_SELECTOR = "0xd637ed59"; var FN_INPUTS = []; var FN_OUTPUTS = [ { type: "tuple", name: "condition", components: [ { type: "uint256", name: "startTimestamp" }, { type: "uint256", name: "maxClaimableSupply" }, { type: "uint256", name: "supplyClaimed" }, { type: "uint256", name: "quantityLimitPerWallet" }, { type: "bytes32", name: "merkleRoot" }, { type: "uint256", name: "pricePerToken" }, { type: "address", name: "currency" }, { type: "string", name: "metadata" } ] } ]; function isClaimConditionSupported(availableSelectors) { return detectMethod({ availableSelectors, method: [FN_SELECTOR, FN_INPUTS, FN_OUTPUTS] }); } function decodeClaimConditionResult(result) { return decodeAbiParameters(FN_OUTPUTS, result)[0]; } async function claimCondition(options) { return readContract({ contract: options.contract, method: [FN_SELECTOR, FN_INPUTS, FN_OUTPUTS], params: [] }); } export { FN_SELECTOR, isClaimConditionSupported, decodeClaimConditionResult, claimCondition }; //# sourceMappingURL=chunk-253DMNI3.js.map ================================================ FILE: 17-Crowd-Funding-Dapp/Frontend/.vite/deps_temp_6cf5ba4c/chunk-2HYPHUAF.js ================================================ import { getDefaultAccountFactory } from "./chunk-FNI7M3UI.js"; import { isContractDeployed } from "./chunk-Q3TN3POE.js"; import { createWalletEmitter, trackConnect } from "./chunk-CLN3QXW2.js"; import { isZkSyncChain } from "./chunk-7ZCK2FX5.js"; import { getContract } from "./chunk-7VZHRFCE.js"; import { getCachedChainIfExists } from "./chunk-TFBEDS4S.js"; // node_modules/thirdweb/dist/esm/wallets/smart/smart-wallet.js function smartWallet(createOptions) { const emitter = createWalletEmitter(); let account = void 0; let adminAccount = void 0; let chain = void 0; let lastConnectOptions; const _smartWallet = { id: "smart", subscribe: emitter.subscribe, getChain() { if (!chain) { return void 0; } chain = getCachedChainIfExists(chain.id) || chain; return chain; }, getConfig: () => createOptions, getAccount: () => account, getAdminAccount: () => adminAccount, autoConnect: async (options) => { const { connectSmartWallet } = await import("./smart-7AYCEGLU.js"); const [connectedAccount, connectedChain] = await connectSmartWallet(_smartWallet, options, createOptions); lastConnectOptions = options; account = connectedAccount; chain = connectedChain; trackConnect({ client: options.client, walletType: "smart", walletAddress: account.address, chainId: chain.id }); return account; }, connect: async (options) => { const { connectSmartWallet } = await import("./smart-7AYCEGLU.js"); const [connectedAccount, connectedChain] = await connectSmartWallet(_smartWallet, options, createOptions); adminAccount = options.personalAccount; lastConnectOptions = options; account = connectedAccount; chain = connectedChain; trackConnect({ client: options.client, walletType: "smart", walletAddress: account.address, chainId: chain.id }); emitter.emit("accountChanged", account); return account; }, disconnect: async () => { account = void 0; chain = void 0; const { disconnectSmartWallet } = await import("./smart-7AYCEGLU.js"); await disconnectSmartWallet(_smartWallet); emitter.emit("disconnect", void 0); }, switchChain: async (newChain) => { var _a; if (!lastConnectOptions) { throw new Error("Cannot switch chain without a previous connection"); } const isZksyncChain = await isZkSyncChain(newChain); if (!isZksyncChain) { const factory = getContract({ address: createOptions.factoryAddress || getDefaultAccountFactory((_a = createOptions.overrides) == null ? void 0 : _a.entrypointAddress), chain: newChain, client: lastConnectOptions.client }); const isDeployed = await isContractDeployed(factory); if (!isDeployed) { throw new Error(`Factory contract not deployed on chain: ${newChain.id}`); } } const { connectSmartWallet } = await import("./smart-7AYCEGLU.js"); const [connectedAccount, connectedChain] = await connectSmartWallet(_smartWallet, { ...lastConnectOptions, chain: newChain }, createOptions); account = connectedAccount; chain = connectedChain; emitter.emit("chainChanged", newChain); } }; return _smartWallet; } export { smartWallet }; //# sourceMappingURL=chunk-2HYPHUAF.js.map ================================================ FILE: 17-Crowd-Funding-Dapp/Frontend/.vite/deps_temp_6cf5ba4c/chunk-2MTJELC7.js ================================================ import { __commonJS } from "./chunk-SEVZ5PBP.js"; // node_modules/react/cjs/react.development.js var require_react_development = __commonJS({ "node_modules/react/cjs/react.development.js"(exports, module) { "use strict"; if (true) { (function() { "use strict"; if (typeof __REACT_DEVTOOLS_GLOBAL_HOOK__ !== "undefined" && typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStart === "function") { __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStart(new Error()); } var ReactVersion = "18.3.1"; var REACT_ELEMENT_TYPE = Symbol.for("react.element"); var REACT_PORTAL_TYPE = Symbol.for("react.portal"); var REACT_FRAGMENT_TYPE = Symbol.for("react.fragment"); var REACT_STRICT_MODE_TYPE = Symbol.for("react.strict_mode"); var REACT_PROFILER_TYPE = Symbol.for("react.profiler"); var REACT_PROVIDER_TYPE = Symbol.for("react.provider"); var REACT_CONTEXT_TYPE = Symbol.for("react.context"); var REACT_FORWARD_REF_TYPE = Symbol.for("react.forward_ref"); var REACT_SUSPENSE_TYPE = Symbol.for("react.suspense"); var REACT_SUSPENSE_LIST_TYPE = Symbol.for("react.suspense_list"); var REACT_MEMO_TYPE = Symbol.for("react.memo"); var REACT_LAZY_TYPE = Symbol.for("react.lazy"); var REACT_OFFSCREEN_TYPE = Symbol.for("react.offscreen"); var MAYBE_ITERATOR_SYMBOL = Symbol.iterator; var FAUX_ITERATOR_SYMBOL = "@@iterator"; function getIteratorFn(maybeIterable) { if (maybeIterable === null || typeof maybeIterable !== "object") { return null; } var maybeIterator = MAYBE_ITERATOR_SYMBOL && maybeIterable[MAYBE_ITERATOR_SYMBOL] || maybeIterable[FAUX_ITERATOR_SYMBOL]; if (typeof maybeIterator === "function") { return maybeIterator; } return null; } var ReactCurrentDispatcher = { /** * @internal * @type {ReactComponent} */ current: null }; var ReactCurrentBatchConfig = { transition: null }; var ReactCurrentActQueue = { current: null, // Used to reproduce behavior of `batchedUpdates` in legacy mode. isBatchingLegacy: false, didScheduleLegacyUpdate: false }; var ReactCurrentOwner = { /** * @internal * @type {ReactComponent} */ current: null }; var ReactDebugCurrentFrame = {}; var currentExtraStackFrame = null; function setExtraStackFrame(stack) { { currentExtraStackFrame = stack; } } { ReactDebugCurrentFrame.setExtraStackFrame = function(stack) { { currentExtraStackFrame = stack; } }; ReactDebugCurrentFrame.getCurrentStack = null; ReactDebugCurrentFrame.getStackAddendum = function() { var stack = ""; if (currentExtraStackFrame) { stack += currentExtraStackFrame; } var impl = ReactDebugCurrentFrame.getCurrentStack; if (impl) { stack += impl() || ""; } return stack; }; } var enableScopeAPI = false; var enableCacheElement = false; var enableTransitionTracing = false; var enableLegacyHidden = false; var enableDebugTracing = false; var ReactSharedInternals = { ReactCurrentDispatcher, ReactCurrentBatchConfig, ReactCurrentOwner }; { ReactSharedInternals.ReactDebugCurrentFrame = ReactDebugCurrentFrame; ReactSharedInternals.ReactCurrentActQueue = ReactCurrentActQueue; } function warn(format) { { { for (var _len = arguments.length, args = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) { args[_key - 1] = arguments[_key]; } printWarning("warn", format, args); } } } function error(format) { { { for (var _len2 = arguments.length, args = new Array(_len2 > 1 ? _len2 - 1 : 0), _key2 = 1; _key2 < _len2; _key2++) { args[_key2 - 1] = arguments[_key2]; } printWarning("error", format, args); } } } function printWarning(level, format, args) { { var ReactDebugCurrentFrame2 = ReactSharedInternals.ReactDebugCurrentFrame; var stack = ReactDebugCurrentFrame2.getStackAddendum(); if (stack !== "") { format += "%s"; args = args.concat([stack]); } var argsWithFormat = args.map(function(item) { return String(item); }); argsWithFormat.unshift("Warning: " + format); Function.prototype.apply.call(console[level], console, argsWithFormat); } } var didWarnStateUpdateForUnmountedComponent = {}; function warnNoop(publicInstance, callerName) { { var _constructor = publicInstance.constructor; var componentName = _constructor && (_constructor.displayName || _constructor.name) || "ReactClass"; var warningKey = componentName + "." + callerName; if (didWarnStateUpdateForUnmountedComponent[warningKey]) { return; } error("Can't call %s on a component that is not yet mounted. This is a no-op, but it might indicate a bug in your application. Instead, assign to `this.state` directly or define a `state = {};` class property with the desired state in the %s component.", callerName, componentName); didWarnStateUpdateForUnmountedComponent[warningKey] = true; } } var ReactNoopUpdateQueue = { /** * Checks whether or not this composite component is mounted. * @param {ReactClass} publicInstance The instance we want to test. * @return {boolean} True if mounted, false otherwise. * @protected * @final */ isMounted: function(publicInstance) { return false; }, /** * Forces an update. This should only be invoked when it is known with * certainty that we are **not** in a DOM transaction. * * You may want to call this when you know that some deeper aspect of the * component's state has changed but `setState` was not called. * * This will not invoke `shouldComponentUpdate`, but it will invoke * `componentWillUpdate` and `componentDidUpdate`. * * @param {ReactClass} publicInstance The instance that should rerender. * @param {?function} callback Called after component is updated. * @param {?string} callerName name of the calling function in the public API. * @internal */ enqueueForceUpdate: function(publicInstance, callback, callerName) { warnNoop(publicInstance, "forceUpdate"); }, /** * Replaces all of the state. Always use this or `setState` to mutate state. * You should treat `this.state` as immutable. * * There is no guarantee that `this.state` will be immediately updated, so * accessing `this.state` after calling this method may return the old value. * * @param {ReactClass} publicInstance The instance that should rerender. * @param {object} completeState Next state. * @param {?function} callback Called after component is updated. * @param {?string} callerName name of the calling function in the public API. * @internal */ enqueueReplaceState: function(publicInstance, completeState, callback, callerName) { warnNoop(publicInstance, "replaceState"); }, /** * Sets a subset of the state. This only exists because _pendingState is * internal. This provides a merging strategy that is not available to deep * properties which is confusing. TODO: Expose pendingState or don't use it * during the merge. * * @param {ReactClass} publicInstance The instance that should rerender. * @param {object} partialState Next partial state to be merged with state. * @param {?function} callback Called after component is updated. * @param {?string} Name of the calling function in the public API. * @internal */ enqueueSetState: function(publicInstance, partialState, callback, callerName) { warnNoop(publicInstance, "setState"); } }; var assign = Object.assign; var emptyObject = {}; { Object.freeze(emptyObject); } function Component(props, context, updater) { this.props = props; this.context = context; this.refs = emptyObject; this.updater = updater || ReactNoopUpdateQueue; } Component.prototype.isReactComponent = {}; Component.prototype.setState = function(partialState, callback) { if (typeof partialState !== "object" && typeof partialState !== "function" && partialState != null) { throw new Error("setState(...): takes an object of state variables to update or a function which returns an object of state variables."); } this.updater.enqueueSetState(this, partialState, callback, "setState"); }; Component.prototype.forceUpdate = function(callback) { this.updater.enqueueForceUpdate(this, callback, "forceUpdate"); }; { var deprecatedAPIs = { isMounted: ["isMounted", "Instead, make sure to clean up subscriptions and pending requests in componentWillUnmount to prevent memory leaks."], replaceState: ["replaceState", "Refactor your code to use setState instead (see https://github.com/facebook/react/issues/3236)."] }; var defineDeprecationWarning = function(methodName, info) { Object.defineProperty(Component.prototype, methodName, { get: function() { warn("%s(...) is deprecated in plain JavaScript React classes. %s", info[0], info[1]); return void 0; } }); }; for (var fnName in deprecatedAPIs) { if (deprecatedAPIs.hasOwnProperty(fnName)) { defineDeprecationWarning(fnName, deprecatedAPIs[fnName]); } } } function ComponentDummy() { } ComponentDummy.prototype = Component.prototype; function PureComponent(props, context, updater) { this.props = props; this.context = context; this.refs = emptyObject; this.updater = updater || ReactNoopUpdateQueue; } var pureComponentPrototype = PureComponent.prototype = new ComponentDummy(); pureComponentPrototype.constructor = PureComponent; assign(pureComponentPrototype, Component.prototype); pureComponentPrototype.isPureReactComponent = true; function createRef() { var refObject = { current: null }; { Object.seal(refObject); } return refObject; } var isArrayImpl = Array.isArray; function isArray(a) { return isArrayImpl(a); } function typeName(value) { { var hasToStringTag = typeof Symbol === "function" && Symbol.toStringTag; var type = hasToStringTag && value[Symbol.toStringTag] || value.constructor.name || "Object"; return type; } } function willCoercionThrow(value) { { try { testStringCoercion(value); return false; } catch (e) { return true; } } } function testStringCoercion(value) { return "" + value; } function checkKeyStringCoercion(value) { { if (willCoercionThrow(value)) { error("The provided key is an unsupported type %s. This value must be coerced to a string before before using it here.", typeName(value)); return testStringCoercion(value); } } } function getWrappedName(outerType, innerType, wrapperName) { var displayName = outerType.displayName; if (displayName) { return displayName; } var functionName = innerType.displayName || innerType.name || ""; return functionName !== "" ? wrapperName + "(" + functionName + ")" : wrapperName; } function getContextName(type) { return type.displayName || "Context"; } function getComponentNameFromType(type) { if (type == null) { return null; } { if (typeof type.tag === "number") { error("Received an unexpected object in getComponentNameFromType(). This is likely a bug in React. Please file an issue."); } } if (typeof type === "function") { return type.displayName || type.name || null; } if (typeof type === "string") { return type; } switch (type) { case REACT_FRAGMENT_TYPE: return "Fragment"; case REACT_PORTAL_TYPE: return "Portal"; case REACT_PROFILER_TYPE: return "Profiler"; case REACT_STRICT_MODE_TYPE: return "StrictMode"; case REACT_SUSPENSE_TYPE: return "Suspense"; case REACT_SUSPENSE_LIST_TYPE: return "SuspenseList"; } if (typeof type === "object") { switch (type.$$typeof) { case REACT_CONTEXT_TYPE: var context = type; return getContextName(context) + ".Consumer"; case REACT_PROVIDER_TYPE: var provider = type; return getContextName(provider._context) + ".Provider"; case REACT_FORWARD_REF_TYPE: return getWrappedName(type, type.render, "ForwardRef"); case REACT_MEMO_TYPE: var outerName = type.displayName || null; if (outerName !== null) { return outerName; } return getComponentNameFromType(type.type) || "Memo"; case REACT_LAZY_TYPE: { var lazyComponent = type; var payload = lazyComponent._payload; var init = lazyComponent._init; try { return getComponentNameFromType(init(payload)); } catch (x) { return null; } } } } return null; } var hasOwnProperty = Object.prototype.hasOwnProperty; var RESERVED_PROPS = { key: true, ref: true, __self: true, __source: true }; var specialPropKeyWarningShown, specialPropRefWarningShown, didWarnAboutStringRefs; { didWarnAboutStringRefs = {}; } function hasValidRef(config) { { if (hasOwnProperty.call(config, "ref")) { var getter = Object.getOwnPropertyDescriptor(config, "ref").get; if (getter && getter.isReactWarning) { return false; } } } return config.ref !== void 0; } function hasValidKey(config) { { if (hasOwnProperty.call(config, "key")) { var getter = Object.getOwnPropertyDescriptor(config, "key").get; if (getter && getter.isReactWarning) { return false; } } } return config.key !== void 0; } function defineKeyPropWarningGetter(props, displayName) { var warnAboutAccessingKey = function() { { if (!specialPropKeyWarningShown) { specialPropKeyWarningShown = true; error("%s: `key` is not a prop. Trying to access it will result in `undefined` being returned. If you need to access the same value within the child component, you should pass it as a different prop. (https://reactjs.org/link/special-props)", displayName); } } }; warnAboutAccessingKey.isReactWarning = true; Object.defineProperty(props, "key", { get: warnAboutAccessingKey, configurable: true }); } function defineRefPropWarningGetter(props, displayName) { var warnAboutAccessingRef = function() { { if (!specialPropRefWarningShown) { specialPropRefWarningShown = true; error("%s: `ref` is not a prop. Trying to access it will result in `undefined` being returned. If you need to access the same value within the child component, you should pass it as a different prop. (https://reactjs.org/link/special-props)", displayName); } } }; warnAboutAccessingRef.isReactWarning = true; Object.defineProperty(props, "ref", { get: warnAboutAccessingRef, configurable: true }); } function warnIfStringRefCannotBeAutoConverted(config) { { if (typeof config.ref === "string" && ReactCurrentOwner.current && config.__self && ReactCurrentOwner.current.stateNode !== config.__self) { var componentName = getComponentNameFromType(ReactCurrentOwner.current.type); if (!didWarnAboutStringRefs[componentName]) { error('Component "%s" contains the string ref "%s". Support for string refs will be removed in a future major release. This case cannot be automatically converted to an arrow function. We ask you to manually fix this case by using useRef() or createRef() instead. Learn more about using refs safely here: https://reactjs.org/link/strict-mode-string-ref', componentName, config.ref); didWarnAboutStringRefs[componentName] = true; } } } } var ReactElement = function(type, key, ref, self, source, owner, props) { var element = { // This tag allows us to uniquely identify this as a React Element $$typeof: REACT_ELEMENT_TYPE, // Built-in properties that belong on the element type, key, ref, props, // Record the component responsible for creating this element. _owner: owner }; { element._store = {}; Object.defineProperty(element._store, "validated", { configurable: false, enumerable: false, writable: true, value: false }); Object.defineProperty(element, "_self", { configurable: false, enumerable: false, writable: false, value: self }); Object.defineProperty(element, "_source", { configurable: false, enumerable: false, writable: false, value: source }); if (Object.freeze) { Object.freeze(element.props); Object.freeze(element); } } return element; }; function createElement(type, config, children) { var propName; var props = {}; var key = null; var ref = null; var self = null; var source = null; if (config != null) { if (hasValidRef(config)) { ref = config.ref; { warnIfStringRefCannotBeAutoConverted(config); } } if (hasValidKey(config)) { { checkKeyStringCoercion(config.key); } key = "" + config.key; } self = config.__self === void 0 ? null : config.__self; source = config.__source === void 0 ? null : config.__source; for (propName in config) { if (hasOwnProperty.call(config, propName) && !RESERVED_PROPS.hasOwnProperty(propName)) { props[propName] = config[propName]; } } } var childrenLength = arguments.length - 2; if (childrenLength === 1) { props.children = children; } else if (childrenLength > 1) { var childArray = Array(childrenLength); for (var i = 0; i < childrenLength; i++) { childArray[i] = arguments[i + 2]; } { if (Object.freeze) { Object.freeze(childArray); } } props.children = childArray; } if (type && type.defaultProps) { var defaultProps = type.defaultProps; for (propName in defaultProps) { if (props[propName] === void 0) { props[propName] = defaultProps[propName]; } } } { if (key || ref) { var displayName = typeof type === "function" ? type.displayName || type.name || "Unknown" : type; if (key) { defineKeyPropWarningGetter(props, displayName); } if (ref) { defineRefPropWarningGetter(props, displayName); } } } return ReactElement(type, key, ref, self, source, ReactCurrentOwner.current, props); } function cloneAndReplaceKey(oldElement, newKey) { var newElement = ReactElement(oldElement.type, newKey, oldElement.ref, oldElement._self, oldElement._source, oldElement._owner, oldElement.props); return newElement; } function cloneElement(element, config, children) { if (element === null || element === void 0) { throw new Error("React.cloneElement(...): The argument must be a React element, but you passed " + element + "."); } var propName; var props = assign({}, element.props); var key = element.key; var ref = element.ref; var self = element._self; var source = element._source; var owner = element._owner; if (config != null) { if (hasValidRef(config)) { ref = config.ref; owner = ReactCurrentOwner.current; } if (hasValidKey(config)) { { checkKeyStringCoercion(config.key); } key = "" + config.key; } var defaultProps; if (element.type && element.type.defaultProps) { defaultProps = element.type.defaultProps; } for (propName in config) { if (hasOwnProperty.call(config, propName) && !RESERVED_PROPS.hasOwnProperty(propName)) { if (config[propName] === void 0 && defaultProps !== void 0) { props[propName] = defaultProps[propName]; } else { props[propName] = config[propName]; } } } } var childrenLength = arguments.length - 2; if (childrenLength === 1) { props.children = children; } else if (childrenLength > 1) { var childArray = Array(childrenLength); for (var i = 0; i < childrenLength; i++) { childArray[i] = arguments[i + 2]; } props.children = childArray; } return ReactElement(element.type, key, ref, self, source, owner, props); } function isValidElement(object) { return typeof object === "object" && object !== null && object.$$typeof === REACT_ELEMENT_TYPE; } var SEPARATOR = "."; var SUBSEPARATOR = ":"; function escape(key) { var escapeRegex = /[=:]/g; var escaperLookup = { "=": "=0", ":": "=2" }; var escapedString = key.replace(escapeRegex, function(match) { return escaperLookup[match]; }); return "$" + escapedString; } var didWarnAboutMaps = false; var userProvidedKeyEscapeRegex = /\/+/g; function escapeUserProvidedKey(text) { return text.replace(userProvidedKeyEscapeRegex, "$&/"); } function getElementKey(element, index) { if (typeof element === "object" && element !== null && element.key != null) { { checkKeyStringCoercion(element.key); } return escape("" + element.key); } return index.toString(36); } function mapIntoArray(children, array, escapedPrefix, nameSoFar, callback) { var type = typeof children; if (type === "undefined" || type === "boolean") { children = null; } var invokeCallback = false; if (children === null) { invokeCallback = true; } else { switch (type) { case "string": case "number": invokeCallback = true; break; case "object": switch (children.$$typeof) { case REACT_ELEMENT_TYPE: case REACT_PORTAL_TYPE: invokeCallback = true; } } } if (invokeCallback) { var _child = children; var mappedChild = callback(_child); var childKey = nameSoFar === "" ? SEPARATOR + getElementKey(_child, 0) : nameSoFar; if (isArray(mappedChild)) { var escapedChildKey = ""; if (childKey != null) { escapedChildKey = escapeUserProvidedKey(childKey) + "/"; } mapIntoArray(mappedChild, array, escapedChildKey, "", function(c) { return c; }); } else if (mappedChild != null) { if (isValidElement(mappedChild)) { { if (mappedChild.key && (!_child || _child.key !== mappedChild.key)) { checkKeyStringCoercion(mappedChild.key); } } mappedChild = cloneAndReplaceKey( mappedChild, // Keep both the (mapped) and old keys if they differ, just as // traverseAllChildren used to do for objects as children escapedPrefix + // $FlowFixMe Flow incorrectly thinks React.Portal doesn't have a key (mappedChild.key && (!_child || _child.key !== mappedChild.key) ? ( // $FlowFixMe Flow incorrectly thinks existing element's key can be a number // eslint-disable-next-line react-internal/safe-string-coercion escapeUserProvidedKey("" + mappedChild.key) + "/" ) : "") + childKey ); } array.push(mappedChild); } return 1; } var child; var nextName; var subtreeCount = 0; var nextNamePrefix = nameSoFar === "" ? SEPARATOR : nameSoFar + SUBSEPARATOR; if (isArray(children)) { for (var i = 0; i < children.length; i++) { child = children[i]; nextName = nextNamePrefix + getElementKey(child, i); subtreeCount += mapIntoArray(child, array, escapedPrefix, nextName, callback); } } else { var iteratorFn = getIteratorFn(children); if (typeof iteratorFn === "function") { var iterableChildren = children; { if (iteratorFn === iterableChildren.entries) { if (!didWarnAboutMaps) { warn("Using Maps as children is not supported. Use an array of keyed ReactElements instead."); } didWarnAboutMaps = true; } } var iterator = iteratorFn.call(iterableChildren); var step; var ii = 0; while (!(step = iterator.next()).done) { child = step.value; nextName = nextNamePrefix + getElementKey(child, ii++); subtreeCount += mapIntoArray(child, array, escapedPrefix, nextName, callback); } } else if (type === "object") { var childrenString = String(children); throw new Error("Objects are not valid as a React child (found: " + (childrenString === "[object Object]" ? "object with keys {" + Object.keys(children).join(", ") + "}" : childrenString) + "). If you meant to render a collection of children, use an array instead."); } } return subtreeCount; } function mapChildren(children, func, context) { if (children == null) { return children; } var result = []; var count = 0; mapIntoArray(children, result, "", "", function(child) { return func.call(context, child, count++); }); return result; } function countChildren(children) { var n = 0; mapChildren(children, function() { n++; }); return n; } function forEachChildren(children, forEachFunc, forEachContext) { mapChildren(children, function() { forEachFunc.apply(this, arguments); }, forEachContext); } function toArray(children) { return mapChildren(children, function(child) { return child; }) || []; } function onlyChild(children) { if (!isValidElement(children)) { throw new Error("React.Children.only expected to receive a single React element child."); } return children; } function createContext(defaultValue) { var context = { $$typeof: REACT_CONTEXT_TYPE, // As a workaround to support multiple concurrent renderers, we categorize // some renderers as primary and others as secondary. We only expect // there to be two concurrent renderers at most: React Native (primary) and // Fabric (secondary); React DOM (primary) and React ART (secondary). // Secondary renderers store their context values on separate fields. _currentValue: defaultValue, _currentValue2: defaultValue, // Used to track how many concurrent renderers this context currently // supports within in a single renderer. Such as parallel server rendering. _threadCount: 0, // These are circular Provider: null, Consumer: null, // Add these to use same hidden class in VM as ServerContext _defaultValue: null, _globalName: null }; context.Provider = { $$typeof: REACT_PROVIDER_TYPE, _context: context }; var hasWarnedAboutUsingNestedContextConsumers = false; var hasWarnedAboutUsingConsumerProvider = false; var hasWarnedAboutDisplayNameOnConsumer = false; { var Consumer = { $$typeof: REACT_CONTEXT_TYPE, _context: context }; Object.defineProperties(Consumer, { Provider: { get: function() { if (!hasWarnedAboutUsingConsumerProvider) { hasWarnedAboutUsingConsumerProvider = true; error("Rendering is not supported and will be removed in a future major release. Did you mean to render instead?"); } return context.Provider; }, set: function(_Provider) { context.Provider = _Provider; } }, _currentValue: { get: function() { return context._currentValue; }, set: function(_currentValue) { context._currentValue = _currentValue; } }, _currentValue2: { get: function() { return context._currentValue2; }, set: function(_currentValue2) { context._currentValue2 = _currentValue2; } }, _threadCount: { get: function() { return context._threadCount; }, set: function(_threadCount) { context._threadCount = _threadCount; } }, Consumer: { get: function() { if (!hasWarnedAboutUsingNestedContextConsumers) { hasWarnedAboutUsingNestedContextConsumers = true; error("Rendering is not supported and will be removed in a future major release. Did you mean to render instead?"); } return context.Consumer; } }, displayName: { get: function() { return context.displayName; }, set: function(displayName) { if (!hasWarnedAboutDisplayNameOnConsumer) { warn("Setting `displayName` on Context.Consumer has no effect. You should set it directly on the context with Context.displayName = '%s'.", displayName); hasWarnedAboutDisplayNameOnConsumer = true; } } } }); context.Consumer = Consumer; } { context._currentRenderer = null; context._currentRenderer2 = null; } return context; } var Uninitialized = -1; var Pending = 0; var Resolved = 1; var Rejected = 2; function lazyInitializer(payload) { if (payload._status === Uninitialized) { var ctor = payload._result; var thenable = ctor(); thenable.then(function(moduleObject2) { if (payload._status === Pending || payload._status === Uninitialized) { var resolved = payload; resolved._status = Resolved; resolved._result = moduleObject2; } }, function(error2) { if (payload._status === Pending || payload._status === Uninitialized) { var rejected = payload; rejected._status = Rejected; rejected._result = error2; } }); if (payload._status === Uninitialized) { var pending = payload; pending._status = Pending; pending._result = thenable; } } if (payload._status === Resolved) { var moduleObject = payload._result; { if (moduleObject === void 0) { error("lazy: Expected the result of a dynamic import() call. Instead received: %s\n\nYour code should look like: \n const MyComponent = lazy(() => import('./MyComponent'))\n\nDid you accidentally put curly braces around the import?", moduleObject); } } { if (!("default" in moduleObject)) { error("lazy: Expected the result of a dynamic import() call. Instead received: %s\n\nYour code should look like: \n const MyComponent = lazy(() => import('./MyComponent'))", moduleObject); } } return moduleObject.default; } else { throw payload._result; } } function lazy(ctor) { var payload = { // We use these fields to store the result. _status: Uninitialized, _result: ctor }; var lazyType = { $$typeof: REACT_LAZY_TYPE, _payload: payload, _init: lazyInitializer }; { var defaultProps; var propTypes; Object.defineProperties(lazyType, { defaultProps: { configurable: true, get: function() { return defaultProps; }, set: function(newDefaultProps) { error("React.lazy(...): It is not supported to assign `defaultProps` to a lazy component import. Either specify them where the component is defined, or create a wrapping component around it."); defaultProps = newDefaultProps; Object.defineProperty(lazyType, "defaultProps", { enumerable: true }); } }, propTypes: { configurable: true, get: function() { return propTypes; }, set: function(newPropTypes) { error("React.lazy(...): It is not supported to assign `propTypes` to a lazy component import. Either specify them where the component is defined, or create a wrapping component around it."); propTypes = newPropTypes; Object.defineProperty(lazyType, "propTypes", { enumerable: true }); } } }); } return lazyType; } function forwardRef(render) { { if (render != null && render.$$typeof === REACT_MEMO_TYPE) { error("forwardRef requires a render function but received a `memo` component. Instead of forwardRef(memo(...)), use memo(forwardRef(...))."); } else if (typeof render !== "function") { error("forwardRef requires a render function but was given %s.", render === null ? "null" : typeof render); } else { if (render.length !== 0 && render.length !== 2) { error("forwardRef render functions accept exactly two parameters: props and ref. %s", render.length === 1 ? "Did you forget to use the ref parameter?" : "Any additional parameter will be undefined."); } } if (render != null) { if (render.defaultProps != null || render.propTypes != null) { error("forwardRef render functions do not support propTypes or defaultProps. Did you accidentally pass a React component?"); } } } var elementType = { $$typeof: REACT_FORWARD_REF_TYPE, render }; { var ownName; Object.defineProperty(elementType, "displayName", { enumerable: false, configurable: true, get: function() { return ownName; }, set: function(name) { ownName = name; if (!render.name && !render.displayName) { render.displayName = name; } } }); } return elementType; } var REACT_MODULE_REFERENCE; { REACT_MODULE_REFERENCE = Symbol.for("react.module.reference"); } function isValidElementType(type) { if (typeof type === "string" || typeof type === "function") { return true; } if (type === REACT_FRAGMENT_TYPE || type === REACT_PROFILER_TYPE || enableDebugTracing || type === REACT_STRICT_MODE_TYPE || type === REACT_SUSPENSE_TYPE || type === REACT_SUSPENSE_LIST_TYPE || enableLegacyHidden || type === REACT_OFFSCREEN_TYPE || enableScopeAPI || enableCacheElement || enableTransitionTracing) { return true; } if (typeof type === "object" && type !== null) { if (type.$$typeof === REACT_LAZY_TYPE || type.$$typeof === REACT_MEMO_TYPE || type.$$typeof === REACT_PROVIDER_TYPE || type.$$typeof === REACT_CONTEXT_TYPE || type.$$typeof === REACT_FORWARD_REF_TYPE || // This needs to include all possible module reference object // types supported by any Flight configuration anywhere since // we don't know which Flight build this will end up being used // with. type.$$typeof === REACT_MODULE_REFERENCE || type.getModuleId !== void 0) { return true; } } return false; } function memo(type, compare) { { if (!isValidElementType(type)) { error("memo: The first argument must be a component. Instead received: %s", type === null ? "null" : typeof type); } } var elementType = { $$typeof: REACT_MEMO_TYPE, type, compare: compare === void 0 ? null : compare }; { var ownName; Object.defineProperty(elementType, "displayName", { enumerable: false, configurable: true, get: function() { return ownName; }, set: function(name) { ownName = name; if (!type.name && !type.displayName) { type.displayName = name; } } }); } return elementType; } function resolveDispatcher() { var dispatcher = ReactCurrentDispatcher.current; { if (dispatcher === null) { error("Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen for one of the following reasons:\n1. You might have mismatching versions of React and the renderer (such as React DOM)\n2. You might be breaking the Rules of Hooks\n3. You might have more than one copy of React in the same app\nSee https://reactjs.org/link/invalid-hook-call for tips about how to debug and fix this problem."); } } return dispatcher; } function useContext(Context) { var dispatcher = resolveDispatcher(); { if (Context._context !== void 0) { var realContext = Context._context; if (realContext.Consumer === Context) { error("Calling useContext(Context.Consumer) is not supported, may cause bugs, and will be removed in a future major release. Did you mean to call useContext(Context) instead?"); } else if (realContext.Provider === Context) { error("Calling useContext(Context.Provider) is not supported. Did you mean to call useContext(Context) instead?"); } } } return dispatcher.useContext(Context); } function useState(initialState) { var dispatcher = resolveDispatcher(); return dispatcher.useState(initialState); } function useReducer(reducer, initialArg, init) { var dispatcher = resolveDispatcher(); return dispatcher.useReducer(reducer, initialArg, init); } function useRef(initialValue) { var dispatcher = resolveDispatcher(); return dispatcher.useRef(initialValue); } function useEffect(create, deps) { var dispatcher = resolveDispatcher(); return dispatcher.useEffect(create, deps); } function useInsertionEffect(create, deps) { var dispatcher = resolveDispatcher(); return dispatcher.useInsertionEffect(create, deps); } function useLayoutEffect(create, deps) { var dispatcher = resolveDispatcher(); return dispatcher.useLayoutEffect(create, deps); } function useCallback(callback, deps) { var dispatcher = resolveDispatcher(); return dispatcher.useCallback(callback, deps); } function useMemo(create, deps) { var dispatcher = resolveDispatcher(); return dispatcher.useMemo(create, deps); } function useImperativeHandle(ref, create, deps) { var dispatcher = resolveDispatcher(); return dispatcher.useImperativeHandle(ref, create, deps); } function useDebugValue(value, formatterFn) { { var dispatcher = resolveDispatcher(); return dispatcher.useDebugValue(value, formatterFn); } } function useTransition() { var dispatcher = resolveDispatcher(); return dispatcher.useTransition(); } function useDeferredValue(value) { var dispatcher = resolveDispatcher(); return dispatcher.useDeferredValue(value); } function useId() { var dispatcher = resolveDispatcher(); return dispatcher.useId(); } function useSyncExternalStore(subscribe, getSnapshot, getServerSnapshot) { var dispatcher = resolveDispatcher(); return dispatcher.useSyncExternalStore(subscribe, getSnapshot, getServerSnapshot); } var disabledDepth = 0; var prevLog; var prevInfo; var prevWarn; var prevError; var prevGroup; var prevGroupCollapsed; var prevGroupEnd; function disabledLog() { } disabledLog.__reactDisabledLog = true; function disableLogs() { { if (disabledDepth === 0) { prevLog = console.log; prevInfo = console.info; prevWarn = console.warn; prevError = console.error; prevGroup = console.group; prevGroupCollapsed = console.groupCollapsed; prevGroupEnd = console.groupEnd; var props = { configurable: true, enumerable: true, value: disabledLog, writable: true }; Object.defineProperties(console, { info: props, log: props, warn: props, error: props, group: props, groupCollapsed: props, groupEnd: props }); } disabledDepth++; } } function reenableLogs() { { disabledDepth--; if (disabledDepth === 0) { var props = { configurable: true, enumerable: true, writable: true }; Object.defineProperties(console, { log: assign({}, props, { value: prevLog }), info: assign({}, props, { value: prevInfo }), warn: assign({}, props, { value: prevWarn }), error: assign({}, props, { value: prevError }), group: assign({}, props, { value: prevGroup }), groupCollapsed: assign({}, props, { value: prevGroupCollapsed }), groupEnd: assign({}, props, { value: prevGroupEnd }) }); } if (disabledDepth < 0) { error("disabledDepth fell below zero. This is a bug in React. Please file an issue."); } } } var ReactCurrentDispatcher$1 = ReactSharedInternals.ReactCurrentDispatcher; var prefix; function describeBuiltInComponentFrame(name, source, ownerFn) { { if (prefix === void 0) { try { throw Error(); } catch (x) { var match = x.stack.trim().match(/\n( *(at )?)/); prefix = match && match[1] || ""; } } return "\n" + prefix + name; } } var reentry = false; var componentFrameCache; { var PossiblyWeakMap = typeof WeakMap === "function" ? WeakMap : Map; componentFrameCache = new PossiblyWeakMap(); } function describeNativeComponentFrame(fn, construct) { if (!fn || reentry) { return ""; } { var frame = componentFrameCache.get(fn); if (frame !== void 0) { return frame; } } var control; reentry = true; var previousPrepareStackTrace = Error.prepareStackTrace; Error.prepareStackTrace = void 0; var previousDispatcher; { previousDispatcher = ReactCurrentDispatcher$1.current; ReactCurrentDispatcher$1.current = null; disableLogs(); } try { if (construct) { var Fake = function() { throw Error(); }; Object.defineProperty(Fake.prototype, "props", { set: function() { throw Error(); } }); if (typeof Reflect === "object" && Reflect.construct) { try { Reflect.construct(Fake, []); } catch (x) { control = x; } Reflect.construct(fn, [], Fake); } else { try { Fake.call(); } catch (x) { control = x; } fn.call(Fake.prototype); } } else { try { throw Error(); } catch (x) { control = x; } fn(); } } catch (sample) { if (sample && control && typeof sample.stack === "string") { var sampleLines = sample.stack.split("\n"); var controlLines = control.stack.split("\n"); var s = sampleLines.length - 1; var c = controlLines.length - 1; while (s >= 1 && c >= 0 && sampleLines[s] !== controlLines[c]) { c--; } for (; s >= 1 && c >= 0; s--, c--) { if (sampleLines[s] !== controlLines[c]) { if (s !== 1 || c !== 1) { do { s--; c--; if (c < 0 || sampleLines[s] !== controlLines[c]) { var _frame = "\n" + sampleLines[s].replace(" at new ", " at "); if (fn.displayName && _frame.includes("")) { _frame = _frame.replace("", fn.displayName); } { if (typeof fn === "function") { componentFrameCache.set(fn, _frame); } } return _frame; } } while (s >= 1 && c >= 0); } break; } } } } finally { reentry = false; { ReactCurrentDispatcher$1.current = previousDispatcher; reenableLogs(); } Error.prepareStackTrace = previousPrepareStackTrace; } var name = fn ? fn.displayName || fn.name : ""; var syntheticFrame = name ? describeBuiltInComponentFrame(name) : ""; { if (typeof fn === "function") { componentFrameCache.set(fn, syntheticFrame); } } return syntheticFrame; } function describeFunctionComponentFrame(fn, source, ownerFn) { { return describeNativeComponentFrame(fn, false); } } function shouldConstruct(Component2) { var prototype = Component2.prototype; return !!(prototype && prototype.isReactComponent); } function describeUnknownElementTypeFrameInDEV(type, source, ownerFn) { if (type == null) { return ""; } if (typeof type === "function") { { return describeNativeComponentFrame(type, shouldConstruct(type)); } } if (typeof type === "string") { return describeBuiltInComponentFrame(type); } switch (type) { case REACT_SUSPENSE_TYPE: return describeBuiltInComponentFrame("Suspense"); case REACT_SUSPENSE_LIST_TYPE: return describeBuiltInComponentFrame("SuspenseList"); } if (typeof type === "object") { switch (type.$$typeof) { case REACT_FORWARD_REF_TYPE: return describeFunctionComponentFrame(type.render); case REACT_MEMO_TYPE: return describeUnknownElementTypeFrameInDEV(type.type, source, ownerFn); case REACT_LAZY_TYPE: { var lazyComponent = type; var payload = lazyComponent._payload; var init = lazyComponent._init; try { return describeUnknownElementTypeFrameInDEV(init(payload), source, ownerFn); } catch (x) { } } } } return ""; } var loggedTypeFailures = {}; var ReactDebugCurrentFrame$1 = ReactSharedInternals.ReactDebugCurrentFrame; function setCurrentlyValidatingElement(element) { { if (element) { var owner = element._owner; var stack = describeUnknownElementTypeFrameInDEV(element.type, element._source, owner ? owner.type : null); ReactDebugCurrentFrame$1.setExtraStackFrame(stack); } else { ReactDebugCurrentFrame$1.setExtraStackFrame(null); } } } function checkPropTypes(typeSpecs, values, location, componentName, element) { { var has = Function.call.bind(hasOwnProperty); for (var typeSpecName in typeSpecs) { if (has(typeSpecs, typeSpecName)) { var error$1 = void 0; try { if (typeof typeSpecs[typeSpecName] !== "function") { var err = Error((componentName || "React class") + ": " + location + " type `" + typeSpecName + "` is invalid; it must be a function, usually from the `prop-types` package, but received `" + typeof typeSpecs[typeSpecName] + "`.This often happens because of typos such as `PropTypes.function` instead of `PropTypes.func`."); err.name = "Invariant Violation"; throw err; } error$1 = typeSpecs[typeSpecName](values, typeSpecName, componentName, location, null, "SECRET_DO_NOT_PASS_THIS_OR_YOU_WILL_BE_FIRED"); } catch (ex) { error$1 = ex; } if (error$1 && !(error$1 instanceof Error)) { setCurrentlyValidatingElement(element); error("%s: type specification of %s `%s` is invalid; the type checker function must return `null` or an `Error` but returned a %s. You may have forgotten to pass an argument to the type checker creator (arrayOf, instanceOf, objectOf, oneOf, oneOfType, and shape all require an argument).", componentName || "React class", location, typeSpecName, typeof error$1); setCurrentlyValidatingElement(null); } if (error$1 instanceof Error && !(error$1.message in loggedTypeFailures)) { loggedTypeFailures[error$1.message] = true; setCurrentlyValidatingElement(element); error("Failed %s type: %s", location, error$1.message); setCurrentlyValidatingElement(null); } } } } } function setCurrentlyValidatingElement$1(element) { { if (element) { var owner = element._owner; var stack = describeUnknownElementTypeFrameInDEV(element.type, element._source, owner ? owner.type : null); setExtraStackFrame(stack); } else { setExtraStackFrame(null); } } } var propTypesMisspellWarningShown; { propTypesMisspellWarningShown = false; } function getDeclarationErrorAddendum() { if (ReactCurrentOwner.current) { var name = getComponentNameFromType(ReactCurrentOwner.current.type); if (name) { return "\n\nCheck the render method of `" + name + "`."; } } return ""; } function getSourceInfoErrorAddendum(source) { if (source !== void 0) { var fileName = source.fileName.replace(/^.*[\\\/]/, ""); var lineNumber = source.lineNumber; return "\n\nCheck your code at " + fileName + ":" + lineNumber + "."; } return ""; } function getSourceInfoErrorAddendumForProps(elementProps) { if (elementProps !== null && elementProps !== void 0) { return getSourceInfoErrorAddendum(elementProps.__source); } return ""; } var ownerHasKeyUseWarning = {}; function getCurrentComponentErrorInfo(parentType) { var info = getDeclarationErrorAddendum(); if (!info) { var parentName = typeof parentType === "string" ? parentType : parentType.displayName || parentType.name; if (parentName) { info = "\n\nCheck the top-level render call using <" + parentName + ">."; } } return info; } function validateExplicitKey(element, parentType) { if (!element._store || element._store.validated || element.key != null) { return; } element._store.validated = true; var currentComponentErrorInfo = getCurrentComponentErrorInfo(parentType); if (ownerHasKeyUseWarning[currentComponentErrorInfo]) { return; } ownerHasKeyUseWarning[currentComponentErrorInfo] = true; var childOwner = ""; if (element && element._owner && element._owner !== ReactCurrentOwner.current) { childOwner = " It was passed a child from " + getComponentNameFromType(element._owner.type) + "."; } { setCurrentlyValidatingElement$1(element); error('Each child in a list should have a unique "key" prop.%s%s See https://reactjs.org/link/warning-keys for more information.', currentComponentErrorInfo, childOwner); setCurrentlyValidatingElement$1(null); } } function validateChildKeys(node, parentType) { if (typeof node !== "object") { return; } if (isArray(node)) { for (var i = 0; i < node.length; i++) { var child = node[i]; if (isValidElement(child)) { validateExplicitKey(child, parentType); } } } else if (isValidElement(node)) { if (node._store) { node._store.validated = true; } } else if (node) { var iteratorFn = getIteratorFn(node); if (typeof iteratorFn === "function") { if (iteratorFn !== node.entries) { var iterator = iteratorFn.call(node); var step; while (!(step = iterator.next()).done) { if (isValidElement(step.value)) { validateExplicitKey(step.value, parentType); } } } } } } function validatePropTypes(element) { { var type = element.type; if (type === null || type === void 0 || typeof type === "string") { return; } var propTypes; if (typeof type === "function") { propTypes = type.propTypes; } else if (typeof type === "object" && (type.$$typeof === REACT_FORWARD_REF_TYPE || // Note: Memo only checks outer props here. // Inner props are checked in the reconciler. type.$$typeof === REACT_MEMO_TYPE)) { propTypes = type.propTypes; } else { return; } if (propTypes) { var name = getComponentNameFromType(type); checkPropTypes(propTypes, element.props, "prop", name, element); } else if (type.PropTypes !== void 0 && !propTypesMisspellWarningShown) { propTypesMisspellWarningShown = true; var _name = getComponentNameFromType(type); error("Component %s declared `PropTypes` instead of `propTypes`. Did you misspell the property assignment?", _name || "Unknown"); } if (typeof type.getDefaultProps === "function" && !type.getDefaultProps.isReactClassApproved) { error("getDefaultProps is only used on classic React.createClass definitions. Use a static property named `defaultProps` instead."); } } } function validateFragmentProps(fragment) { { var keys = Object.keys(fragment.props); for (var i = 0; i < keys.length; i++) { var key = keys[i]; if (key !== "children" && key !== "key") { setCurrentlyValidatingElement$1(fragment); error("Invalid prop `%s` supplied to `React.Fragment`. React.Fragment can only have `key` and `children` props.", key); setCurrentlyValidatingElement$1(null); break; } } if (fragment.ref !== null) { setCurrentlyValidatingElement$1(fragment); error("Invalid attribute `ref` supplied to `React.Fragment`."); setCurrentlyValidatingElement$1(null); } } } function createElementWithValidation(type, props, children) { var validType = isValidElementType(type); if (!validType) { var info = ""; if (type === void 0 || typeof type === "object" && type !== null && Object.keys(type).length === 0) { info += " You likely forgot to export your component from the file it's defined in, or you might have mixed up default and named imports."; } var sourceInfo = getSourceInfoErrorAddendumForProps(props); if (sourceInfo) { info += sourceInfo; } else { info += getDeclarationErrorAddendum(); } var typeString; if (type === null) { typeString = "null"; } else if (isArray(type)) { typeString = "array"; } else if (type !== void 0 && type.$$typeof === REACT_ELEMENT_TYPE) { typeString = "<" + (getComponentNameFromType(type.type) || "Unknown") + " />"; info = " Did you accidentally export a JSX literal instead of a component?"; } else { typeString = typeof type; } { error("React.createElement: type is invalid -- expected a string (for built-in components) or a class/function (for composite components) but got: %s.%s", typeString, info); } } var element = createElement.apply(this, arguments); if (element == null) { return element; } if (validType) { for (var i = 2; i < arguments.length; i++) { validateChildKeys(arguments[i], type); } } if (type === REACT_FRAGMENT_TYPE) { validateFragmentProps(element); } else { validatePropTypes(element); } return element; } var didWarnAboutDeprecatedCreateFactory = false; function createFactoryWithValidation(type) { var validatedFactory = createElementWithValidation.bind(null, type); validatedFactory.type = type; { if (!didWarnAboutDeprecatedCreateFactory) { didWarnAboutDeprecatedCreateFactory = true; warn("React.createFactory() is deprecated and will be removed in a future major release. Consider using JSX or use React.createElement() directly instead."); } Object.defineProperty(validatedFactory, "type", { enumerable: false, get: function() { warn("Factory.type is deprecated. Access the class directly before passing it to createFactory."); Object.defineProperty(this, "type", { value: type }); return type; } }); } return validatedFactory; } function cloneElementWithValidation(element, props, children) { var newElement = cloneElement.apply(this, arguments); for (var i = 2; i < arguments.length; i++) { validateChildKeys(arguments[i], newElement.type); } validatePropTypes(newElement); return newElement; } function startTransition(scope, options) { var prevTransition = ReactCurrentBatchConfig.transition; ReactCurrentBatchConfig.transition = {}; var currentTransition = ReactCurrentBatchConfig.transition; { ReactCurrentBatchConfig.transition._updatedFibers = /* @__PURE__ */ new Set(); } try { scope(); } finally { ReactCurrentBatchConfig.transition = prevTransition; { if (prevTransition === null && currentTransition._updatedFibers) { var updatedFibersCount = currentTransition._updatedFibers.size; if (updatedFibersCount > 10) { warn("Detected a large number of updates inside startTransition. If this is due to a subscription please re-write it to use React provided hooks. Otherwise concurrent mode guarantees are off the table."); } currentTransition._updatedFibers.clear(); } } } } var didWarnAboutMessageChannel = false; var enqueueTaskImpl = null; function enqueueTask(task) { if (enqueueTaskImpl === null) { try { var requireString = ("require" + Math.random()).slice(0, 7); var nodeRequire = module && module[requireString]; enqueueTaskImpl = nodeRequire.call(module, "timers").setImmediate; } catch (_err) { enqueueTaskImpl = function(callback) { { if (didWarnAboutMessageChannel === false) { didWarnAboutMessageChannel = true; if (typeof MessageChannel === "undefined") { error("This browser does not have a MessageChannel implementation, so enqueuing tasks via await act(async () => ...) will fail. Please file an issue at https://github.com/facebook/react/issues if you encounter this warning."); } } } var channel = new MessageChannel(); channel.port1.onmessage = callback; channel.port2.postMessage(void 0); }; } } return enqueueTaskImpl(task); } var actScopeDepth = 0; var didWarnNoAwaitAct = false; function act(callback) { { var prevActScopeDepth = actScopeDepth; actScopeDepth++; if (ReactCurrentActQueue.current === null) { ReactCurrentActQueue.current = []; } var prevIsBatchingLegacy = ReactCurrentActQueue.isBatchingLegacy; var result; try { ReactCurrentActQueue.isBatchingLegacy = true; result = callback(); if (!prevIsBatchingLegacy && ReactCurrentActQueue.didScheduleLegacyUpdate) { var queue = ReactCurrentActQueue.current; if (queue !== null) { ReactCurrentActQueue.didScheduleLegacyUpdate = false; flushActQueue(queue); } } } catch (error2) { popActScope(prevActScopeDepth); throw error2; } finally { ReactCurrentActQueue.isBatchingLegacy = prevIsBatchingLegacy; } if (result !== null && typeof result === "object" && typeof result.then === "function") { var thenableResult = result; var wasAwaited = false; var thenable = { then: function(resolve, reject) { wasAwaited = true; thenableResult.then(function(returnValue2) { popActScope(prevActScopeDepth); if (actScopeDepth === 0) { recursivelyFlushAsyncActWork(returnValue2, resolve, reject); } else { resolve(returnValue2); } }, function(error2) { popActScope(prevActScopeDepth); reject(error2); }); } }; { if (!didWarnNoAwaitAct && typeof Promise !== "undefined") { Promise.resolve().then(function() { }).then(function() { if (!wasAwaited) { didWarnNoAwaitAct = true; error("You called act(async () => ...) without await. This could lead to unexpected testing behaviour, interleaving multiple act calls and mixing their scopes. You should - await act(async () => ...);"); } }); } } return thenable; } else { var returnValue = result; popActScope(prevActScopeDepth); if (actScopeDepth === 0) { var _queue = ReactCurrentActQueue.current; if (_queue !== null) { flushActQueue(_queue); ReactCurrentActQueue.current = null; } var _thenable = { then: function(resolve, reject) { if (ReactCurrentActQueue.current === null) { ReactCurrentActQueue.current = []; recursivelyFlushAsyncActWork(returnValue, resolve, reject); } else { resolve(returnValue); } } }; return _thenable; } else { var _thenable2 = { then: function(resolve, reject) { resolve(returnValue); } }; return _thenable2; } } } } function popActScope(prevActScopeDepth) { { if (prevActScopeDepth !== actScopeDepth - 1) { error("You seem to have overlapping act() calls, this is not supported. Be sure to await previous act() calls before making a new one. "); } actScopeDepth = prevActScopeDepth; } } function recursivelyFlushAsyncActWork(returnValue, resolve, reject) { { var queue = ReactCurrentActQueue.current; if (queue !== null) { try { flushActQueue(queue); enqueueTask(function() { if (queue.length === 0) { ReactCurrentActQueue.current = null; resolve(returnValue); } else { recursivelyFlushAsyncActWork(returnValue, resolve, reject); } }); } catch (error2) { reject(error2); } } else { resolve(returnValue); } } } var isFlushing = false; function flushActQueue(queue) { { if (!isFlushing) { isFlushing = true; var i = 0; try { for (; i < queue.length; i++) { var callback = queue[i]; do { callback = callback(true); } while (callback !== null); } queue.length = 0; } catch (error2) { queue = queue.slice(i + 1); throw error2; } finally { isFlushing = false; } } } } var createElement$1 = createElementWithValidation; var cloneElement$1 = cloneElementWithValidation; var createFactory = createFactoryWithValidation; var Children = { map: mapChildren, forEach: forEachChildren, count: countChildren, toArray, only: onlyChild }; exports.Children = Children; exports.Component = Component; exports.Fragment = REACT_FRAGMENT_TYPE; exports.Profiler = REACT_PROFILER_TYPE; exports.PureComponent = PureComponent; exports.StrictMode = REACT_STRICT_MODE_TYPE; exports.Suspense = REACT_SUSPENSE_TYPE; exports.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED = ReactSharedInternals; exports.act = act; exports.cloneElement = cloneElement$1; exports.createContext = createContext; exports.createElement = createElement$1; exports.createFactory = createFactory; exports.createRef = createRef; exports.forwardRef = forwardRef; exports.isValidElement = isValidElement; exports.lazy = lazy; exports.memo = memo; exports.startTransition = startTransition; exports.unstable_act = act; exports.useCallback = useCallback; exports.useContext = useContext; exports.useDebugValue = useDebugValue; exports.useDeferredValue = useDeferredValue; exports.useEffect = useEffect; exports.useId = useId; exports.useImperativeHandle = useImperativeHandle; exports.useInsertionEffect = useInsertionEffect; exports.useLayoutEffect = useLayoutEffect; exports.useMemo = useMemo; exports.useReducer = useReducer; exports.useRef = useRef; exports.useState = useState; exports.useSyncExternalStore = useSyncExternalStore; exports.useTransition = useTransition; exports.version = ReactVersion; if (typeof __REACT_DEVTOOLS_GLOBAL_HOOK__ !== "undefined" && typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStop === "function") { __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStop(new Error()); } })(); } } }); // node_modules/react/index.js var require_react = __commonJS({ "node_modules/react/index.js"(exports, module) { if (false) { module.exports = null; } else { module.exports = require_react_development(); } } }); export { require_react }; /*! Bundled license information: react/cjs/react.development.js: (** * @license React * react.development.js * * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. *) */ //# sourceMappingURL=chunk-2MTJELC7.js.map ================================================ FILE: 17-Crowd-Funding-Dapp/Frontend/.vite/deps_temp_6cf5ba4c/chunk-2RRVHQYX.js ================================================ // node_modules/thirdweb/dist/esm/wallets/coinbase/utils.js async function showCoinbasePopup(provider) { var _a, _b; await ((_b = (_a = provider == null ? void 0 : provider.communicator) == null ? void 0 : _a.waitForPopupLoaded) == null ? void 0 : _b.call(_a)); } export { showCoinbasePopup }; //# sourceMappingURL=chunk-2RRVHQYX.js.map ================================================ FILE: 17-Crowd-Funding-Dapp/Frontend/.vite/deps_temp_6cf5ba4c/chunk-35YKZJSE.js ================================================ // node_modules/proxy-compare/dist/index.modern.js var e = Symbol(); var t = Symbol(); var s = Object.getPrototypeOf; var c = /* @__PURE__ */ new WeakMap(); var l = (e2) => e2 && (c.has(e2) ? c.get(e2) : s(e2) === Object.prototype || s(e2) === Array.prototype); var y = (e2) => l(e2) && e2[t] || null; var h = (e2, t2 = true) => { c.set(e2, t2); }; // node_modules/valtio/esm/vanilla.mjs var isObject = (x) => typeof x === "object" && x !== null; var proxyStateMap = /* @__PURE__ */ new WeakMap(); var refSet = /* @__PURE__ */ new WeakSet(); var buildProxyFunction = (objectIs = Object.is, newProxy = (target, handler) => new Proxy(target, handler), canProxy = (x) => isObject(x) && !refSet.has(x) && (Array.isArray(x) || !(Symbol.iterator in x)) && !(x instanceof WeakMap) && !(x instanceof WeakSet) && !(x instanceof Error) && !(x instanceof Number) && !(x instanceof Date) && !(x instanceof String) && !(x instanceof RegExp) && !(x instanceof ArrayBuffer), defaultHandlePromise = (promise) => { switch (promise.status) { case "fulfilled": return promise.value; case "rejected": throw promise.reason; default: throw promise; } }, snapCache = /* @__PURE__ */ new WeakMap(), createSnapshot = (target, version, handlePromise = defaultHandlePromise) => { const cache = snapCache.get(target); if ((cache == null ? void 0 : cache[0]) === version) { return cache[1]; } const snap = Array.isArray(target) ? [] : Object.create(Object.getPrototypeOf(target)); h(snap, true); snapCache.set(target, [version, snap]); Reflect.ownKeys(target).forEach((key) => { if (Object.getOwnPropertyDescriptor(snap, key)) { return; } const value = Reflect.get(target, key); const desc = { value, enumerable: true, // This is intentional to avoid copying with proxy-compare. // It's still non-writable, so it avoids assigning a value. configurable: true }; if (refSet.has(value)) { h(value, false); } else if (value instanceof Promise) { delete desc.value; desc.get = () => handlePromise(value); } else if (proxyStateMap.has(value)) { const [target2, ensureVersion] = proxyStateMap.get( value ); desc.value = createSnapshot( target2, ensureVersion(), handlePromise ); } Object.defineProperty(snap, key, desc); }); return Object.preventExtensions(snap); }, proxyCache = /* @__PURE__ */ new WeakMap(), versionHolder = [1, 1], proxyFunction = (initialObject) => { if (!isObject(initialObject)) { throw new Error("object required"); } const found = proxyCache.get(initialObject); if (found) { return found; } let version = versionHolder[0]; const listeners = /* @__PURE__ */ new Set(); const notifyUpdate = (op, nextVersion = ++versionHolder[0]) => { if (version !== nextVersion) { version = nextVersion; listeners.forEach((listener) => listener(op, nextVersion)); } }; let checkVersion = versionHolder[1]; const ensureVersion = (nextCheckVersion = ++versionHolder[1]) => { if (checkVersion !== nextCheckVersion && !listeners.size) { checkVersion = nextCheckVersion; propProxyStates.forEach(([propProxyState]) => { const propVersion = propProxyState[1](nextCheckVersion); if (propVersion > version) { version = propVersion; } }); } return version; }; const createPropListener = (prop) => (op, nextVersion) => { const newOp = [...op]; newOp[1] = [prop, ...newOp[1]]; notifyUpdate(newOp, nextVersion); }; const propProxyStates = /* @__PURE__ */ new Map(); const addPropListener = (prop, propProxyState) => { if ((import.meta.env ? import.meta.env.MODE : void 0) !== "production" && propProxyStates.has(prop)) { throw new Error("prop listener already exists"); } if (listeners.size) { const remove = propProxyState[3](createPropListener(prop)); propProxyStates.set(prop, [propProxyState, remove]); } else { propProxyStates.set(prop, [propProxyState]); } }; const removePropListener = (prop) => { var _a; const entry = propProxyStates.get(prop); if (entry) { propProxyStates.delete(prop); (_a = entry[1]) == null ? void 0 : _a.call(entry); } }; const addListener = (listener) => { listeners.add(listener); if (listeners.size === 1) { propProxyStates.forEach(([propProxyState, prevRemove], prop) => { if ((import.meta.env ? import.meta.env.MODE : void 0) !== "production" && prevRemove) { throw new Error("remove already exists"); } const remove = propProxyState[3](createPropListener(prop)); propProxyStates.set(prop, [propProxyState, remove]); }); } const removeListener = () => { listeners.delete(listener); if (listeners.size === 0) { propProxyStates.forEach(([propProxyState, remove], prop) => { if (remove) { remove(); propProxyStates.set(prop, [propProxyState]); } }); } }; return removeListener; }; const baseObject = Array.isArray(initialObject) ? [] : Object.create(Object.getPrototypeOf(initialObject)); const handler = { deleteProperty(target, prop) { const prevValue = Reflect.get(target, prop); removePropListener(prop); const deleted = Reflect.deleteProperty(target, prop); if (deleted) { notifyUpdate(["delete", [prop], prevValue]); } return deleted; }, set(target, prop, value, receiver) { const hasPrevValue = Reflect.has(target, prop); const prevValue = Reflect.get(target, prop, receiver); if (hasPrevValue && (objectIs(prevValue, value) || proxyCache.has(value) && objectIs(prevValue, proxyCache.get(value)))) { return true; } removePropListener(prop); if (isObject(value)) { value = y(value) || value; } let nextValue = value; if (value instanceof Promise) { value.then((v) => { value.status = "fulfilled"; value.value = v; notifyUpdate(["resolve", [prop], v]); }).catch((e2) => { value.status = "rejected"; value.reason = e2; notifyUpdate(["reject", [prop], e2]); }); } else { if (!proxyStateMap.has(value) && canProxy(value)) { nextValue = proxyFunction(value); } const childProxyState = !refSet.has(nextValue) && proxyStateMap.get(nextValue); if (childProxyState) { addPropListener(prop, childProxyState); } } Reflect.set(target, prop, nextValue, receiver); notifyUpdate(["set", [prop], value, prevValue]); return true; } }; const proxyObject = newProxy(baseObject, handler); proxyCache.set(initialObject, proxyObject); const proxyState = [ baseObject, ensureVersion, createSnapshot, addListener ]; proxyStateMap.set(proxyObject, proxyState); Reflect.ownKeys(initialObject).forEach((key) => { const desc = Object.getOwnPropertyDescriptor( initialObject, key ); if ("value" in desc) { proxyObject[key] = initialObject[key]; delete desc.value; delete desc.writable; } Object.defineProperty(baseObject, key, desc); }); return proxyObject; }) => [ // public functions proxyFunction, // shared state proxyStateMap, refSet, // internal things objectIs, newProxy, canProxy, defaultHandlePromise, snapCache, createSnapshot, proxyCache, versionHolder ]; var [defaultProxyFunction] = buildProxyFunction(); function proxy(initialObject = {}) { return defaultProxyFunction(initialObject); } function subscribe(proxyObject, callback, notifyInSync) { const proxyState = proxyStateMap.get(proxyObject); if ((import.meta.env ? import.meta.env.MODE : void 0) !== "production" && !proxyState) { console.warn("Please use proxy object"); } let promise; const ops = []; const addListener = proxyState[3]; let isListenerActive = false; const listener = (op) => { ops.push(op); if (notifyInSync) { callback(ops.splice(0)); return; } if (!promise) { promise = Promise.resolve().then(() => { promise = void 0; if (isListenerActive) { callback(ops.splice(0)); } }); } }; const removeListener = addListener(listener); isListenerActive = true; return () => { isListenerActive = false; removeListener(); }; } function snapshot(proxyObject, handlePromise) { const proxyState = proxyStateMap.get(proxyObject); if ((import.meta.env ? import.meta.env.MODE : void 0) !== "production" && !proxyState) { console.warn("Please use proxy object"); } const [target, ensureVersion, createSnapshot] = proxyState; return createSnapshot(target, ensureVersion(), handlePromise); } // node_modules/@walletconnect/modal-core/dist/index.js var state$7 = proxy({ history: ["ConnectWallet"], view: "ConnectWallet", data: void 0 }); var RouterCtrl = { state: state$7, subscribe(callback) { return subscribe(state$7, () => callback(state$7)); }, push(view, data) { if (view !== state$7.view) { state$7.view = view; if (data) { state$7.data = data; } state$7.history.push(view); } }, reset(view) { state$7.view = view; state$7.history = [view]; }, replace(view) { if (state$7.history.length > 1) { state$7.history[state$7.history.length - 1] = view; state$7.view = view; } }, goBack() { if (state$7.history.length > 1) { state$7.history.pop(); const [last] = state$7.history.slice(-1); state$7.view = last; } }, setData(data) { state$7.data = data; } }; var CoreUtil = { WALLETCONNECT_DEEPLINK_CHOICE: "WALLETCONNECT_DEEPLINK_CHOICE", WCM_VERSION: "WCM_VERSION", RECOMMENDED_WALLET_AMOUNT: 9, isMobile() { if (typeof window !== "undefined") { return Boolean( window.matchMedia("(pointer:coarse)").matches || /Android|webOS|iPhone|iPad|iPod|BlackBerry|Opera Mini/u.test(navigator.userAgent) ); } return false; }, isAndroid() { return CoreUtil.isMobile() && navigator.userAgent.toLowerCase().includes("android"); }, isIos() { const ua = navigator.userAgent.toLowerCase(); return CoreUtil.isMobile() && (ua.includes("iphone") || ua.includes("ipad")); }, isHttpUrl(url) { return url.startsWith("http://") || url.startsWith("https://"); }, isArray(data) { return Array.isArray(data) && data.length > 0; }, isTelegram() { return typeof window !== "undefined" && // eslint-disable-next-line @typescript-eslint/no-explicit-any (Boolean(window.TelegramWebviewProxy) || // eslint-disable-next-line @typescript-eslint/no-explicit-any Boolean(window.Telegram) || // eslint-disable-next-line @typescript-eslint/no-explicit-any Boolean(window.TelegramWebviewProxyProto)); }, formatNativeUrl(appUrl, wcUri, name) { if (CoreUtil.isHttpUrl(appUrl)) { return this.formatUniversalUrl(appUrl, wcUri, name); } let safeAppUrl = appUrl; if (!safeAppUrl.includes("://")) { safeAppUrl = appUrl.replaceAll("/", "").replaceAll(":", ""); safeAppUrl = `${safeAppUrl}://`; } if (!safeAppUrl.endsWith("/")) { safeAppUrl = `${safeAppUrl}/`; } this.setWalletConnectDeepLink(safeAppUrl, name); const encodedWcUrl = encodeURIComponent(wcUri); return `${safeAppUrl}wc?uri=${encodedWcUrl}`; }, formatUniversalUrl(appUrl, wcUri, name) { if (!CoreUtil.isHttpUrl(appUrl)) { return this.formatNativeUrl(appUrl, wcUri, name); } let safeAppUrl = appUrl; if (safeAppUrl.startsWith("https://t.me")) { const formattedUri = Buffer.from(wcUri).toString("base64").replace(/[=]/g, ""); if (safeAppUrl.endsWith("/")) { safeAppUrl = safeAppUrl.slice(0, -1); } this.setWalletConnectDeepLink(safeAppUrl, name); const url = new URL(safeAppUrl); url.searchParams.set("startapp", formattedUri); const link = url.toString(); return link; } if (!safeAppUrl.endsWith("/")) { safeAppUrl = `${safeAppUrl}/`; } this.setWalletConnectDeepLink(safeAppUrl, name); const encodedWcUrl = encodeURIComponent(wcUri); return `${safeAppUrl}wc?uri=${encodedWcUrl}`; }, async wait(miliseconds) { return new Promise((resolve) => { setTimeout(resolve, miliseconds); }); }, openHref(href, target) { const adjustedTarget = this.isTelegram() ? "_blank" : target; window.open(href, adjustedTarget, "noreferrer noopener"); }, setWalletConnectDeepLink(href, name) { try { localStorage.setItem(CoreUtil.WALLETCONNECT_DEEPLINK_CHOICE, JSON.stringify({ href, name })); } catch (e2) { console.info("Unable to set WalletConnect deep link"); } }, setWalletConnectAndroidDeepLink(wcUri) { try { const [href] = wcUri.split("?"); localStorage.setItem( CoreUtil.WALLETCONNECT_DEEPLINK_CHOICE, JSON.stringify({ href, name: "Android" }) ); } catch (e2) { console.info("Unable to set WalletConnect android deep link"); } }, removeWalletConnectDeepLink() { try { localStorage.removeItem(CoreUtil.WALLETCONNECT_DEEPLINK_CHOICE); } catch (e2) { console.info("Unable to remove WalletConnect deep link"); } }, setModalVersionInStorage() { try { if (typeof localStorage !== "undefined") { localStorage.setItem(CoreUtil.WCM_VERSION, "2.7.0"); } } catch (e2) { console.info("Unable to set Web3Modal version in storage"); } }, getWalletRouterData() { var _a; const routerData = (_a = RouterCtrl.state.data) == null ? void 0 : _a.Wallet; if (!routerData) { throw new Error('Missing "Wallet" view data'); } return routerData; } }; var isEnabled = typeof location !== "undefined" && (location.hostname.includes("localhost") || location.protocol.includes("https")); var state$6 = proxy({ enabled: isEnabled, userSessionId: "", events: [], connectedWalletId: void 0 }); var EventsCtrl = { state: state$6, subscribe(callback) { return subscribe(state$6.events, () => callback(snapshot(state$6.events[state$6.events.length - 1]))); }, initialize() { if (state$6.enabled && typeof (crypto == null ? void 0 : crypto.randomUUID) !== "undefined") { state$6.userSessionId = crypto.randomUUID(); } }, setConnectedWalletId(connectedWalletId) { state$6.connectedWalletId = connectedWalletId; }, click(data) { if (state$6.enabled) { const event = { type: "CLICK", name: data.name, userSessionId: state$6.userSessionId, timestamp: Date.now(), data }; state$6.events.push(event); } }, track(data) { if (state$6.enabled) { const event = { type: "TRACK", name: data.name, userSessionId: state$6.userSessionId, timestamp: Date.now(), data }; state$6.events.push(event); } }, view(data) { if (state$6.enabled) { const event = { type: "VIEW", name: data.name, userSessionId: state$6.userSessionId, timestamp: Date.now(), data }; state$6.events.push(event); } } }; var state$5 = proxy({ chains: void 0, walletConnectUri: void 0, isAuth: false, isCustomDesktop: false, isCustomMobile: false, isDataLoaded: false, isUiLoaded: false }); var OptionsCtrl = { state: state$5, subscribe(callback) { return subscribe(state$5, () => callback(state$5)); }, setChains(chains) { state$5.chains = chains; }, setWalletConnectUri(walletConnectUri) { state$5.walletConnectUri = walletConnectUri; }, setIsCustomDesktop(isCustomDesktop) { state$5.isCustomDesktop = isCustomDesktop; }, setIsCustomMobile(isCustomMobile) { state$5.isCustomMobile = isCustomMobile; }, setIsDataLoaded(isDataLoaded) { state$5.isDataLoaded = isDataLoaded; }, setIsUiLoaded(isUiLoaded) { state$5.isUiLoaded = isUiLoaded; }, setIsAuth(isAuth) { state$5.isAuth = isAuth; } }; var state$4 = proxy({ projectId: "", mobileWallets: void 0, desktopWallets: void 0, walletImages: void 0, chains: void 0, enableAuthMode: false, enableExplorer: true, explorerExcludedWalletIds: void 0, explorerRecommendedWalletIds: void 0, termsOfServiceUrl: void 0, privacyPolicyUrl: void 0 }); var ConfigCtrl = { state: state$4, subscribe(callback) { return subscribe(state$4, () => callback(state$4)); }, setConfig(config) { var _a, _b; EventsCtrl.initialize(); OptionsCtrl.setChains(config.chains); OptionsCtrl.setIsAuth(Boolean(config.enableAuthMode)); OptionsCtrl.setIsCustomMobile(Boolean((_a = config.mobileWallets) == null ? void 0 : _a.length)); OptionsCtrl.setIsCustomDesktop(Boolean((_b = config.desktopWallets) == null ? void 0 : _b.length)); CoreUtil.setModalVersionInStorage(); Object.assign(state$4, config); } }; var __defProp$2 = Object.defineProperty; var __getOwnPropSymbols$2 = Object.getOwnPropertySymbols; var __hasOwnProp$2 = Object.prototype.hasOwnProperty; var __propIsEnum$2 = Object.prototype.propertyIsEnumerable; var __defNormalProp$2 = (obj, key, value) => key in obj ? __defProp$2(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value; var __spreadValues$2 = (a, b) => { for (var prop in b || (b = {})) if (__hasOwnProp$2.call(b, prop)) __defNormalProp$2(a, prop, b[prop]); if (__getOwnPropSymbols$2) for (var prop of __getOwnPropSymbols$2(b)) { if (__propIsEnum$2.call(b, prop)) __defNormalProp$2(a, prop, b[prop]); } return a; }; var W3M_API = "https://explorer-api.walletconnect.com"; var SDK_TYPE = "wcm"; var SDK_VERSION = `js-${"2.7.0"}`; async function fetchListings(endpoint, params) { const allParams = __spreadValues$2({ sdkType: SDK_TYPE, sdkVersion: SDK_VERSION }, params); const url = new URL(endpoint, W3M_API); url.searchParams.append("projectId", ConfigCtrl.state.projectId); Object.entries(allParams).forEach(([key, value]) => { if (value) { url.searchParams.append(key, String(value)); } }); const request = await fetch(url); return request.json(); } var ExplorerUtil = { async getDesktopListings(params) { return fetchListings("/w3m/v1/getDesktopListings", params); }, async getMobileListings(params) { return fetchListings("/w3m/v1/getMobileListings", params); }, async getInjectedListings(params) { return fetchListings("/w3m/v1/getInjectedListings", params); }, async getAllListings(params) { return fetchListings("/w3m/v1/getAllListings", params); }, getWalletImageUrl(imageId) { return `${W3M_API}/w3m/v1/getWalletImage/${imageId}?projectId=${ConfigCtrl.state.projectId}&sdkType=${SDK_TYPE}&sdkVersion=${SDK_VERSION}`; }, getAssetImageUrl(imageId) { return `${W3M_API}/w3m/v1/getAssetImage/${imageId}?projectId=${ConfigCtrl.state.projectId}&sdkType=${SDK_TYPE}&sdkVersion=${SDK_VERSION}`; } }; var __defProp$1 = Object.defineProperty; var __getOwnPropSymbols$1 = Object.getOwnPropertySymbols; var __hasOwnProp$1 = Object.prototype.hasOwnProperty; var __propIsEnum$1 = Object.prototype.propertyIsEnumerable; var __defNormalProp$1 = (obj, key, value) => key in obj ? __defProp$1(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value; var __spreadValues$1 = (a, b) => { for (var prop in b || (b = {})) if (__hasOwnProp$1.call(b, prop)) __defNormalProp$1(a, prop, b[prop]); if (__getOwnPropSymbols$1) for (var prop of __getOwnPropSymbols$1(b)) { if (__propIsEnum$1.call(b, prop)) __defNormalProp$1(a, prop, b[prop]); } return a; }; var isMobile = CoreUtil.isMobile(); var state$3 = proxy({ wallets: { listings: [], total: 0, page: 1 }, search: { listings: [], total: 0, page: 1 }, recomendedWallets: [] }); var ExplorerCtrl = { state: state$3, async getRecomendedWallets() { const { explorerRecommendedWalletIds, explorerExcludedWalletIds } = ConfigCtrl.state; if (explorerRecommendedWalletIds === "NONE" || explorerExcludedWalletIds === "ALL" && !explorerRecommendedWalletIds) { return state$3.recomendedWallets; } if (CoreUtil.isArray(explorerRecommendedWalletIds)) { const recommendedIds = explorerRecommendedWalletIds.join(","); const params = { recommendedIds }; const { listings } = await ExplorerUtil.getAllListings(params); const listingsArr = Object.values(listings); listingsArr.sort((a, b) => { const aIndex = explorerRecommendedWalletIds.indexOf(a.id); const bIndex = explorerRecommendedWalletIds.indexOf(b.id); return aIndex - bIndex; }); state$3.recomendedWallets = listingsArr; } else { const { chains, isAuth } = OptionsCtrl.state; const chainsFilter = chains == null ? void 0 : chains.join(","); const isExcluded = CoreUtil.isArray(explorerExcludedWalletIds); const params = { page: 1, sdks: isAuth ? "auth_v1" : void 0, entries: CoreUtil.RECOMMENDED_WALLET_AMOUNT, chains: chainsFilter, version: 2, excludedIds: isExcluded ? explorerExcludedWalletIds.join(",") : void 0 }; const { listings } = isMobile ? await ExplorerUtil.getMobileListings(params) : await ExplorerUtil.getDesktopListings(params); state$3.recomendedWallets = Object.values(listings); } return state$3.recomendedWallets; }, async getWallets(params) { const extendedParams = __spreadValues$1({}, params); const { explorerRecommendedWalletIds, explorerExcludedWalletIds } = ConfigCtrl.state; const { recomendedWallets } = state$3; if (explorerExcludedWalletIds === "ALL") { return state$3.wallets; } if (recomendedWallets.length) { extendedParams.excludedIds = recomendedWallets.map((wallet) => wallet.id).join(","); } else if (CoreUtil.isArray(explorerRecommendedWalletIds)) { extendedParams.excludedIds = explorerRecommendedWalletIds.join(","); } if (CoreUtil.isArray(explorerExcludedWalletIds)) { extendedParams.excludedIds = [extendedParams.excludedIds, explorerExcludedWalletIds].filter(Boolean).join(","); } if (OptionsCtrl.state.isAuth) { extendedParams.sdks = "auth_v1"; } const { page, search } = params; const { listings: listingsObj, total } = isMobile ? await ExplorerUtil.getMobileListings(extendedParams) : await ExplorerUtil.getDesktopListings(extendedParams); const listings = Object.values(listingsObj); const type = search ? "search" : "wallets"; state$3[type] = { listings: [...state$3[type].listings, ...listings], total, page: page != null ? page : 1 }; return { listings, total }; }, getWalletImageUrl(imageId) { return ExplorerUtil.getWalletImageUrl(imageId); }, getAssetImageUrl(imageId) { return ExplorerUtil.getAssetImageUrl(imageId); }, resetSearch() { state$3.search = { listings: [], total: 0, page: 1 }; } }; var state$2 = proxy({ open: false }); var ModalCtrl = { state: state$2, subscribe(callback) { return subscribe(state$2, () => callback(state$2)); }, async open(options) { return new Promise((resolve) => { const { isUiLoaded, isDataLoaded } = OptionsCtrl.state; CoreUtil.removeWalletConnectDeepLink(); OptionsCtrl.setWalletConnectUri(options == null ? void 0 : options.uri); OptionsCtrl.setChains(options == null ? void 0 : options.chains); RouterCtrl.reset("ConnectWallet"); if (isUiLoaded && isDataLoaded) { state$2.open = true; resolve(); } else { const interval = setInterval(() => { const opts = OptionsCtrl.state; if (opts.isUiLoaded && opts.isDataLoaded) { clearInterval(interval); state$2.open = true; resolve(); } }, 200); } }); }, close() { state$2.open = false; } }; var __defProp = Object.defineProperty; var __getOwnPropSymbols = Object.getOwnPropertySymbols; var __hasOwnProp = Object.prototype.hasOwnProperty; var __propIsEnum = Object.prototype.propertyIsEnumerable; var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value; var __spreadValues = (a, b) => { for (var prop in b || (b = {})) if (__hasOwnProp.call(b, prop)) __defNormalProp(a, prop, b[prop]); if (__getOwnPropSymbols) for (var prop of __getOwnPropSymbols(b)) { if (__propIsEnum.call(b, prop)) __defNormalProp(a, prop, b[prop]); } return a; }; function isDarkMode() { return typeof matchMedia !== "undefined" && matchMedia("(prefers-color-scheme: dark)").matches; } var state$1 = proxy({ themeMode: isDarkMode() ? "dark" : "light" }); var ThemeCtrl = { state: state$1, subscribe(callback) { return subscribe(state$1, () => callback(state$1)); }, setThemeConfig(theme) { const { themeMode, themeVariables } = theme; if (themeMode) { state$1.themeMode = themeMode; } if (themeVariables) { state$1.themeVariables = __spreadValues({}, themeVariables); } } }; var state = proxy({ open: false, message: "", variant: "success" }); var ToastCtrl = { state, subscribe(callback) { return subscribe(state, () => callback(state)); }, openToast(message, variant) { state.open = true; state.message = message; state.variant = variant; }, closeToast() { state.open = false; } }; export { RouterCtrl, CoreUtil, EventsCtrl, OptionsCtrl, ConfigCtrl, ExplorerCtrl, ModalCtrl, ThemeCtrl, ToastCtrl }; //# sourceMappingURL=chunk-35YKZJSE.js.map ================================================ FILE: 17-Crowd-Funding-Dapp/Frontend/.vite/deps_temp_6cf5ba4c/chunk-36FW3ZLE.js ================================================ import { fetchTokenMetadata } from "./chunk-4U2YWK76.js"; import { parseNFT } from "./chunk-NOA36MVL.js"; import { detectMethod } from "./chunk-PK5NRJAC.js"; import { readContract } from "./chunk-AG4NO6K6.js"; // node_modules/thirdweb/dist/esm/extensions/erc721/__generated__/IERC721A/read/tokenURI.js var FN_SELECTOR = "0xc87b56dd"; var FN_INPUTS = [ { type: "uint256", name: "_tokenId" } ]; var FN_OUTPUTS = [ { type: "string" } ]; function isTokenURISupported(availableSelectors) { return detectMethod({ availableSelectors, method: [FN_SELECTOR, FN_INPUTS, FN_OUTPUTS] }); } async function tokenURI(options) { return readContract({ contract: options.contract, method: [FN_SELECTOR, FN_INPUTS, FN_OUTPUTS], params: [options.tokenId] }); } // node_modules/thirdweb/dist/esm/extensions/erc721/read/getNFT.js async function getNFT(options) { const [uri, owner] = await Promise.all([ tokenURI(options).catch(() => null), options.includeOwner ? import("./ownerOf-JJ32SN7R.js").then((m) => m.ownerOf(options)).catch(() => null) : null ]); if (!(uri == null ? void 0 : uri.trim())) { return parseNFT({ id: options.tokenId, type: "ERC721", uri: "" }, { tokenId: options.tokenId, tokenUri: "", type: "ERC721", owner }); } return parseNFT(await fetchTokenMetadata({ client: options.contract.client, tokenId: options.tokenId, tokenUri: uri }).catch(() => ({ id: options.tokenId, type: "ERC721", uri })), { tokenId: options.tokenId, tokenUri: uri, type: "ERC721", owner }); } export { isTokenURISupported, getNFT }; //# sourceMappingURL=chunk-36FW3ZLE.js.map ================================================ FILE: 17-Crowd-Funding-Dapp/Frontend/.vite/deps_temp_6cf5ba4c/chunk-3DBHE3NE.js ================================================ // node_modules/thirdweb/dist/esm/reactive/store.js function createStore(initialValue) { const listeners = /* @__PURE__ */ new Set(); let value = initialValue; const notify = () => { for (const listener of listeners) { listener(); } }; return { getValue() { return value; }, setValue(newValue) { if (newValue === value) { return; } value = newValue; notify(); }, subscribe(listener) { listeners.add(listener); return () => { listeners.delete(listener); }; } }; } // node_modules/thirdweb/dist/esm/transaction/transaction-store.js var transactionsByAddress = /* @__PURE__ */ new Map(); function getTransactionStore(address) { const existingStore = transactionsByAddress.get(address); if (existingStore) { return existingStore; } const newStore = createStore([]); transactionsByAddress.set(address, newStore); return newStore; } function addTransactionToStore(options) { const { address, transactionHash, chainId } = options; const tranasctionStore = getTransactionStore(address); tranasctionStore.setValue([ ...tranasctionStore.getValue(), { transactionHash, chainId } ]); transactionsByAddress.set(address, tranasctionStore); } export { createStore, getTransactionStore, addTransactionToStore }; //# sourceMappingURL=chunk-3DBHE3NE.js.map ================================================ FILE: 17-Crowd-Funding-Dapp/Frontend/.vite/deps_temp_6cf5ba4c/chunk-3GSJ2FQJ.js ================================================ import { detectOS, detectPlatform } from "./chunk-P7ZDTV2E.js"; import { LruMap } from "./chunk-SNQ54XRM.js"; // node_modules/thirdweb/dist/esm/version.js var version = "5.68.0"; // node_modules/thirdweb/dist/esm/utils/jwt/is-jwt.js function isJWT(str) { return str.split(".").length === 3; } // node_modules/thirdweb/dist/esm/utils/process.js var IS_DEV = ( // biome-ignore lint/nursery/noProcessEnv: ok in this file true ); // node_modules/thirdweb/dist/esm/utils/fetch.js var DEFAULT_REQUEST_TIMEOUT = 6e4; function getClientFetch(client, ecosystem) { async function fetchWithHeaders(url, init) { const { requestTimeoutMs = DEFAULT_REQUEST_TIMEOUT, ...restInit } = init || {}; let headers = restInit.headers ? new Headers(restInit.headers) : void 0; if (isThirdwebUrl(url)) { if (!headers) { headers = new Headers(); } const authToken = client.secretKey && isJWT(client.secretKey) ? client.secretKey : void 0; const secretKey = client.secretKey && !isJWT(client.secretKey) ? client.secretKey : void 0; const clientId = client.clientId; if (authToken && !isPayUrl(url) && !isInAppWalletUrl(url) && !isBundlerUrl(url)) { headers.set("authorization", `Bearer ${authToken}`); } else if (secretKey) { headers.set("x-secret-key", secretKey); } else if (clientId) { headers.set("x-client-id", clientId); } if (ecosystem) { headers.set("x-ecosystem-id", ecosystem.id); if (ecosystem.partnerId) { headers.set("x-ecosystem-partner-id", ecosystem.partnerId); } } for (const [key, value] of getPlatformHeaders()) { headers.set(key, value); } } let controller; let abortTimeout; if (requestTimeoutMs) { controller = new AbortController(); abortTimeout = setTimeout(() => { controller == null ? void 0 : controller.abort("timeout"); }, requestTimeoutMs); } return fetch(url, { ...restInit, headers, signal: controller == null ? void 0 : controller.signal }).finally(() => { if (abortTimeout) { clearTimeout(abortTimeout); } }); } return fetchWithHeaders; } var THIRDWEB_DOMAINS = [ ".thirdweb.com", ".ipfscdn.io", // dev domains ".thirdweb.dev", ".thirdweb-dev.com" ]; var IS_THIRDWEB_URL_CACHE = new LruMap(4096); function isThirdwebUrl(url) { if (IS_THIRDWEB_URL_CACHE.has(url)) { return IS_THIRDWEB_URL_CACHE.get(url); } try { const { hostname } = new URL(url); try { if (IS_DEV) { if (hostname === "localhost") { IS_THIRDWEB_URL_CACHE.set(url, true); return true; } } } catch { } const is = THIRDWEB_DOMAINS.some((domain) => hostname.endsWith(domain)); IS_THIRDWEB_URL_CACHE.set(url, is); return is; } catch { IS_THIRDWEB_URL_CACHE.set(url, false); return false; } } function isPayUrl(url) { try { const { hostname } = new URL(url); return hostname.startsWith("pay."); } catch { return false; } } function isInAppWalletUrl(url) { try { const { hostname } = new URL(url); return hostname.startsWith("in-app-wallet.") || hostname.startsWith("embedded-wallet."); } catch { return false; } } function isBundlerUrl(url) { try { const { hostname } = new URL(url); return hostname.endsWith(".bundler.thirdweb.com") || hostname.endsWith(".bundler.thirdweb-dev.com"); } catch { return false; } } var SDK_NAME = "unified-sdk"; var previousPlatform; function getPlatformHeaders() { if (previousPlatform) { return previousPlatform; } let os = null; if (typeof navigator !== "undefined") { os = detectOS(navigator.userAgent); } let bundleId = void 0; if (typeof globalThis !== "undefined" && "Application" in globalThis) { bundleId = globalThis.Application.applicationId; } previousPlatform = Object.entries({ "x-sdk-platform": detectPlatform(), "x-sdk-version": version, "x-sdk-os": os ? parseOs(os) : "unknown", "x-sdk-name": SDK_NAME, ...bundleId ? { "x-bundle-id": bundleId } : {} }); return previousPlatform; } function parseOs(os) { const osLowerCased = os.toLowerCase(); if (osLowerCased.startsWith("win")) { return "win"; } switch (os) { case "Mac OS": return "mac"; case "iOS": return "ios"; case "Android OS": return "android"; default: return osLowerCased.replace(/\s/gi, "_"); } } export { isJWT, IS_DEV, getClientFetch, isThirdwebUrl }; //# sourceMappingURL=chunk-3GSJ2FQJ.js.map ================================================ FILE: 17-Crowd-Funding-Dapp/Frontend/.vite/deps_temp_6cf5ba4c/chunk-3ZOYRTTJ.js ================================================ // node_modules/thirdweb/dist/esm/utils/type-guards.js function isObject(value) { return typeof value === "object" && value !== null; } function isObjectWithKeys(value, keys = []) { return isObject(value) && keys.every((key) => key in value); } export { isObjectWithKeys }; //# sourceMappingURL=chunk-3ZOYRTTJ.js.map ================================================ FILE: 17-Crowd-Funding-Dapp/Frontend/.vite/deps_temp_6cf5ba4c/chunk-4BCIASJM.js ================================================ import { concat } from "./chunk-Y3WKETHV.js"; // node_modules/thirdweb/dist/esm/utils/encoding/helpers/concat-hex.js function concatHex(values) { return concat(...values); } export { concatHex }; //# sourceMappingURL=chunk-4BCIASJM.js.map ================================================ FILE: 17-Crowd-Funding-Dapp/Frontend/.vite/deps_temp_6cf5ba4c/chunk-4OCU6WGG.js ================================================ // node_modules/thirdweb/dist/esm/utils/sleep.js function sleep(ms) { return new Promise((resolve) => setTimeout(resolve, ms)); } export { sleep }; //# sourceMappingURL=chunk-4OCU6WGG.js.map ================================================ FILE: 17-Crowd-Funding-Dapp/Frontend/.vite/deps_temp_6cf5ba4c/chunk-4PEUWIWY.js ================================================ import { hexToBigInt } from "./chunk-BBNNHC5G.js"; // node_modules/thirdweb/dist/esm/rpc/actions/eth_getBalance.js async function eth_getBalance(request, params) { const hexBalance = await request({ method: "eth_getBalance", params: [params.address, params.blockTag || "latest"] }); return hexToBigInt(hexBalance); } export { eth_getBalance }; //# sourceMappingURL=chunk-4PEUWIWY.js.map ================================================ FILE: 17-Crowd-Funding-Dapp/Frontend/.vite/deps_temp_6cf5ba4c/chunk-4RRAU5V7.js ================================================ import { decimals } from "./chunk-QVNJVROL.js"; import { withCache } from "./chunk-GOA7IGSB.js"; // node_modules/thirdweb/dist/esm/extensions/erc20/read/decimals.js async function decimals2(options) { return withCache(() => decimals(options), { cacheKey: `${options.contract.chain.id}:${options.contract.address}:decimals`, // can never change, so cache forever cacheTime: Number.POSITIVE_INFINITY }); } export { decimals2 as decimals }; //# sourceMappingURL=chunk-4RRAU5V7.js.map ================================================ FILE: 17-Crowd-Funding-Dapp/Frontend/.vite/deps_temp_6cf5ba4c/chunk-4U2YWK76.js ================================================ import { isBase64JSON, parseBase64String } from "./chunk-VJFQPB47.js"; import { numberToHex } from "./chunk-BBNNHC5G.js"; // node_modules/thirdweb/dist/esm/utils/nft/fetchTokenMetadata.js async function fetchTokenMetadata(options) { const { client, tokenId, tokenUri } = options; if (isBase64JSON(tokenUri)) { try { return JSON.parse(parseBase64String(tokenUri)); } catch (e) { console.error("Failed to fetch base64 encoded NFT", { tokenId, tokenUri }, e); throw e; } } const { download } = await import("./download-F3MJUB7B.js"); try { if (!tokenUri.includes("{id}")) { return await (await download({ client, uri: tokenUri })).json(); } } catch (e) { console.error("Failed to fetch non-dynamic NFT", { tokenId, tokenUri }, e); throw e; } try { try { return await (await download({ client, uri: tokenUri.replace("{id}", numberToHex(tokenId, { size: 32 }).slice(2)) })).json(); } catch { return await (await download({ client, uri: tokenUri.replace("{id}", tokenId.toString()) })).json(); } } catch (e) { console.error("Failed to fetch dynamic NFT", { tokenId, tokenUri }, e); throw e; } } export { fetchTokenMetadata }; //# sourceMappingURL=chunk-4U2YWK76.js.map ================================================ FILE: 17-Crowd-Funding-Dapp/Frontend/.vite/deps_temp_6cf5ba4c/chunk-5CO5G7XZ.js ================================================ import { resolveScheme } from "./chunk-ZNEQLT5Q.js"; import { getClientFetch } from "./chunk-3GSJ2FQJ.js"; // node_modules/thirdweb/dist/esm/storage/download.js async function download(options) { var _a, _b, _c, _d, _e, _f, _g, _h, _i, _j; let url; if (options.uri.startsWith("ar://")) { const { resolveArweaveScheme } = await import("./arweave-57OCWZ5C.js"); url = resolveArweaveScheme(options); } else { url = resolveScheme(options); } const res = await getClientFetch(options.client)(url, { keepalive: (_c = (_b = (_a = options.client.config) == null ? void 0 : _a.storage) == null ? void 0 : _b.fetch) == null ? void 0 : _c.keepalive, headers: (_f = (_e = (_d = options.client.config) == null ? void 0 : _d.storage) == null ? void 0 : _e.fetch) == null ? void 0 : _f.headers, requestTimeoutMs: options.requestTimeoutMs ?? ((_i = (_h = (_g = options.client.config) == null ? void 0 : _g.storage) == null ? void 0 : _h.fetch) == null ? void 0 : _i.requestTimeoutMs) ?? 6e4 }); if (!res.ok) { (_j = res.body) == null ? void 0 : _j.cancel(); throw new Error(`Failed to download file: ${res.statusText}`); } return res; } export { download }; //# sourceMappingURL=chunk-5CO5G7XZ.js.map ================================================ FILE: 17-Crowd-Funding-Dapp/Frontend/.vite/deps_temp_6cf5ba4c/chunk-5EFACFVF.js ================================================ import { eth_sendRawTransaction } from "./chunk-MWAIX6LF.js"; import { toSerializableTransaction } from "./chunk-JZC47WAY.js"; import { resolvePromisedValue } from "./chunk-QC3K2OKT.js"; import { encode } from "./chunk-7QDK5KLB.js"; import { concatHex as concatHex2 } from "./chunk-4BCIASJM.js"; import { defineBlock, defineChain, defineTransaction, defineTransactionReceipt, formatLog, serializeTransaction, sha256, toRlp } from "./chunk-LO5SQBMX.js"; import { getAddress } from "./chunk-EIVAOYE5.js"; import { BaseError, InvalidAddressError, InvalidChainIdError, concatHex, defineTransactionRequest, hexToBigInt, hexToBytes, hexToNumber, isAddress, maxUint16, pad, toBytes, toHex as toHex2 } from "./chunk-GINVHONX.js"; import { getRpcClient } from "./chunk-I5DK3TWY.js"; import { toHex, uint8ArrayToHex } from "./chunk-BBNNHC5G.js"; // node_modules/thirdweb/dist/esm/utils/bigint.js function toBigInt(value) { if (["string", "number"].includes(typeof value) && !Number.isInteger(Number(value))) { throw new Error(`Expected value to be an integer to convert to a bigint, got ${value} of type ${typeof value}`); } if (value instanceof Uint8Array) { return BigInt(uint8ArrayToHex(value)); } return BigInt(value); } var replaceBigInts = (obj, replacer) => { if (typeof obj === "bigint") return replacer(obj); if (Array.isArray(obj)) return obj.map((x) => replaceBigInts(x, replacer)); if (obj && typeof obj === "object") return Object.fromEntries(Object.entries(obj).map(([k, v]) => [k, replaceBigInts(v, replacer)])); return obj; }; // node_modules/viem/_esm/zksync/constants/number.js var gasPerPubdataDefault = 50000n; var maxBytecodeSize = maxUint16 * 32n; // node_modules/viem/_esm/zksync/errors/transaction.js var InvalidEip712TransactionError = class extends BaseError { constructor() { super([ "Transaction is not an EIP712 transaction.", "", "Transaction must:", ' - include `type: "eip712"`', " - include one of the following: `customSignature`, `paymaster`, `paymasterInput`, `gasPerPubdata`, `factoryDeps`" ].join("\n"), { name: "InvalidEip712TransactionError" }); } }; // node_modules/viem/_esm/zksync/utils/isEip712Transaction.js function isEIP712Transaction(transaction) { if (transaction.type === "eip712") return true; if ("customSignature" in transaction && transaction.customSignature || "paymaster" in transaction && transaction.paymaster || "paymasterInput" in transaction && transaction.paymasterInput || "gasPerPubdata" in transaction && typeof transaction.gasPerPubdata === "bigint" || "factoryDeps" in transaction && transaction.factoryDeps) return true; return false; } // node_modules/viem/_esm/zksync/utils/assertEip712Transaction.js function assertEip712Transaction(transaction) { const { chainId, to, from, paymaster, paymasterInput } = transaction; if (!isEIP712Transaction(transaction)) throw new InvalidEip712TransactionError(); if (!chainId || chainId <= 0) throw new InvalidChainIdError({ chainId }); if (to && !isAddress(to)) throw new InvalidAddressError({ address: to }); if (from && !isAddress(from)) throw new InvalidAddressError({ address: from }); if (paymaster && !isAddress(paymaster)) throw new InvalidAddressError({ address: paymaster }); if (paymaster && !paymasterInput) { throw new BaseError("`paymasterInput` must be provided when `paymaster` is defined"); } if (!paymaster && paymasterInput) { throw new BaseError("`paymaster` must be provided when `paymasterInput` is defined"); } } // node_modules/viem/_esm/zksync/serializers.js function serializeTransaction2(transaction, signature) { if (isEIP712Transaction(transaction)) return serializeTransactionEIP712(transaction); return serializeTransaction(transaction, signature); } var serializers = { transaction: serializeTransaction2 }; function serializeTransactionEIP712(transaction) { const { chainId, gas, nonce, to, from, value, maxFeePerGas, maxPriorityFeePerGas, customSignature, factoryDeps, paymaster, paymasterInput, gasPerPubdata, data } = transaction; assertEip712Transaction(transaction); const serializedTransaction = [ nonce ? toHex2(nonce) : "0x", maxPriorityFeePerGas ? toHex2(maxPriorityFeePerGas) : "0x", maxFeePerGas ? toHex2(maxFeePerGas) : "0x", gas ? toHex2(gas) : "0x", to ?? "0x", value ? toHex2(value) : "0x", data ?? "0x0", toHex2(chainId), toHex2(""), toHex2(""), toHex2(chainId), from ?? "0x", gasPerPubdata ? toHex2(gasPerPubdata) : toHex2(gasPerPubdataDefault), factoryDeps ?? [], customSignature ?? "0x", // EIP712 signature paymaster && paymasterInput ? [paymaster, paymasterInput] : [] ]; return concatHex([ "0x71", toRlp(serializedTransaction) ]); } // node_modules/viem/_esm/zksync/errors/bytecode.js var BytecodeLengthExceedsMaxSizeError = class extends BaseError { constructor({ givenLength, maxBytecodeSize: maxBytecodeSize2 }) { super(`Bytecode cannot be longer than ${maxBytecodeSize2} bytes. Given length: ${givenLength}`, { name: "BytecodeLengthExceedsMaxSizeError" }); } }; var BytecodeLengthInWordsMustBeOddError = class extends BaseError { constructor({ givenLengthInWords }) { super(`Bytecode length in 32-byte words must be odd. Given length in words: ${givenLengthInWords}`, { name: "BytecodeLengthInWordsMustBeOddError" }); } }; var BytecodeLengthMustBeDivisibleBy32Error = class extends BaseError { constructor({ givenLength }) { super(`The bytecode length in bytes must be divisible by 32. Given length: ${givenLength}`, { name: "BytecodeLengthMustBeDivisibleBy32Error" }); } }; // node_modules/viem/_esm/zksync/utils/hashBytecode.js function hashBytecode(bytecode) { const bytecodeBytes = toBytes(bytecode); if (bytecodeBytes.length % 32 !== 0) throw new BytecodeLengthMustBeDivisibleBy32Error({ givenLength: bytecodeBytes.length }); if (bytecodeBytes.length > maxBytecodeSize) throw new BytecodeLengthExceedsMaxSizeError({ givenLength: bytecodeBytes.length, maxBytecodeSize }); const hashStr = sha256(bytecodeBytes); const hash = toBytes(hashStr); const bytecodeLengthInWords = bytecodeBytes.length / 32; if (bytecodeLengthInWords % 2 === 0) { throw new BytecodeLengthInWordsMustBeOddError({ givenLengthInWords: bytecodeLengthInWords }); } const bytecodeLength = toBytes(bytecodeLengthInWords); const bytecodeLengthPadded = pad(bytecodeLength, { size: 2 }); const codeHashVersion = new Uint8Array([1, 0]); hash.set(codeHashVersion, 0); hash.set(bytecodeLengthPadded, 2); return hash; } // node_modules/viem/_esm/zksync/formatters.js var formatters = { block: defineBlock({ format(args) { var _a; const transactions = (_a = args.transactions) == null ? void 0 : _a.map((transaction) => { var _a2; if (typeof transaction === "string") return transaction; const formatted = (_a2 = formatters.transaction) == null ? void 0 : _a2.format(transaction); if (formatted.typeHex === "0x71") formatted.type = "eip712"; else if (formatted.typeHex === "0xff") formatted.type = "priority"; return formatted; }); return { l1BatchNumber: args.l1BatchNumber ? hexToBigInt(args.l1BatchNumber) : null, l1BatchTimestamp: args.l1BatchTimestamp ? hexToBigInt(args.l1BatchTimestamp) : null, transactions }; } }), transaction: defineTransaction({ format(args) { const transaction = {}; if (args.type === "0x71") transaction.type = "eip712"; else if (args.type === "0xff") transaction.type = "priority"; return { ...transaction, l1BatchNumber: args.l1BatchNumber ? hexToBigInt(args.l1BatchNumber) : null, l1BatchTxIndex: args.l1BatchTxIndex ? hexToBigInt(args.l1BatchTxIndex) : null }; } }), transactionReceipt: defineTransactionReceipt({ format(args) { return { l1BatchNumber: args.l1BatchNumber ? hexToBigInt(args.l1BatchNumber) : null, l1BatchTxIndex: args.l1BatchTxIndex ? hexToBigInt(args.l1BatchTxIndex) : null, logs: args.logs.map((log) => { return { ...formatLog(log), l1BatchNumber: log.l1BatchNumber ? hexToBigInt(log.l1BatchNumber) : null, transactionLogIndex: hexToNumber(log.transactionLogIndex), logType: log.logType }; }), l2ToL1Logs: args.l2ToL1Logs.map((l2ToL1Log) => { return { blockNumber: hexToBigInt(l2ToL1Log.blockHash), blockHash: l2ToL1Log.blockHash, l1BatchNumber: hexToBigInt(l2ToL1Log.l1BatchNumber), transactionIndex: hexToBigInt(l2ToL1Log.transactionIndex), shardId: hexToBigInt(l2ToL1Log.shardId), isService: l2ToL1Log.isService, sender: l2ToL1Log.sender, key: l2ToL1Log.key, value: l2ToL1Log.value, transactionHash: l2ToL1Log.transactionHash, logIndex: hexToBigInt(l2ToL1Log.logIndex) }; }) }; } }), transactionRequest: defineTransactionRequest({ exclude: [ "customSignature", "factoryDeps", "gasPerPubdata", "paymaster", "paymasterInput" ], format(args) { if (args.gasPerPubdata || args.paymaster && args.paymasterInput || args.factoryDeps || args.customSignature) return { eip712Meta: { ...args.gasPerPubdata ? { gasPerPubdata: toHex2(args.gasPerPubdata) } : { gasPerPubdata: toHex2(gasPerPubdataDefault) }, ...args.paymaster && args.paymasterInput ? { paymasterParams: { paymaster: args.paymaster, paymasterInput: Array.from(hexToBytes(args.paymasterInput)) } } : {}, ...args.factoryDeps ? { factoryDeps: args.factoryDeps.map((dep) => Array.from(hexToBytes(dep))) } : {}, ...args.customSignature ? { customSignature: Array.from(hexToBytes(args.customSignature)) } : {} }, type: "0x71" }; return {}; } }) }; // node_modules/viem/_esm/zksync/utils/getEip712Domain.js var getEip712Domain2 = (transaction) => { assertEip712Transaction(transaction); const message = transactionToMessage(transaction); return { domain: { name: "zkSync", version: "2", chainId: transaction.chainId }, types: { Transaction: [ { name: "txType", type: "uint256" }, { name: "from", type: "uint256" }, { name: "to", type: "uint256" }, { name: "gasLimit", type: "uint256" }, { name: "gasPerPubdataByteLimit", type: "uint256" }, { name: "maxFeePerGas", type: "uint256" }, { name: "maxPriorityFeePerGas", type: "uint256" }, { name: "paymaster", type: "uint256" }, { name: "nonce", type: "uint256" }, { name: "value", type: "uint256" }, { name: "data", type: "bytes" }, { name: "factoryDeps", type: "bytes32[]" }, { name: "paymasterInput", type: "bytes" } ] }, primaryType: "Transaction", message }; }; function transactionToMessage(transaction) { const { gas, nonce, to, from, value, maxFeePerGas, maxPriorityFeePerGas, factoryDeps, paymaster, paymasterInput, gasPerPubdata, data } = transaction; return { txType: 113n, from: BigInt(from), to: to ? BigInt(to) : 0n, gasLimit: gas ?? 0n, gasPerPubdataByteLimit: gasPerPubdata ?? gasPerPubdataDefault, maxFeePerGas: maxFeePerGas ?? 0n, maxPriorityFeePerGas: maxPriorityFeePerGas ?? 0n, paymaster: paymaster ? BigInt(paymaster) : 0n, nonce: nonce ? BigInt(nonce) : 0n, value: value ?? 0n, data: data ? data : "0x0", factoryDeps: (factoryDeps == null ? void 0 : factoryDeps.map((dep) => toHex2(hashBytecode(dep)))) ?? [], paymasterInput: paymasterInput ? paymasterInput : "0x" }; } // node_modules/viem/_esm/zksync/chainConfig.js var chainConfig = { formatters, serializers, custom: { getEip712Domain: getEip712Domain2 } }; // node_modules/viem/_esm/chains/definitions/zksync.js var zksync = defineChain({ ...chainConfig, id: 324, name: "ZKsync Era", network: "zksync-era", nativeCurrency: { decimals: 18, name: "Ether", symbol: "ETH" }, rpcUrls: { default: { http: ["https://mainnet.era.zksync.io"], webSocket: ["wss://mainnet.era.zksync.io/ws"] } }, blockExplorers: { default: { name: "Etherscan", url: "https://era.zksync.network/", apiUrl: "https://api-era.zksync.network/api" }, native: { name: "ZKsync Explorer", url: "https://explorer.zksync.io/", apiUrl: "https://block-explorer-api.mainnet.zksync.io/api" } }, contracts: { multicall3: { address: "0xF9cda624FBC7e059355ce98a31693d299FACd963" }, universalSignatureVerifier: { address: "0xfB688330379976DA81eB64Fe4BF50d7401763B9C", blockCreated: 45659388 } } }); // node_modules/viem/_esm/chains/definitions/zksyncInMemoryNode.js var zksyncInMemoryNode = defineChain({ ...chainConfig, id: 260, name: "ZKsync InMemory Node", network: "zksync-in-memory-node", nativeCurrency: { name: "Ether", symbol: "ETH", decimals: 18 }, rpcUrls: { default: { http: ["http://localhost:8011"] } }, testnet: true }); // node_modules/viem/_esm/chains/definitions/zksyncLocalNode.js var zksyncLocalNode = defineChain({ ...chainConfig, id: 270, name: "ZKsync CLI Local Node", network: "zksync-cli-local-node", nativeCurrency: { name: "Ether", symbol: "ETH", decimals: 18 }, rpcUrls: { default: { http: ["http://localhost:3050"] } }, testnet: true }); // node_modules/viem/_esm/chains/definitions/zksyncSepoliaTestnet.js var zksyncSepoliaTestnet = defineChain({ ...chainConfig, id: 300, name: "ZKsync Sepolia Testnet", network: "zksync-sepolia-testnet", nativeCurrency: { name: "Ether", symbol: "ETH", decimals: 18 }, rpcUrls: { default: { http: ["https://sepolia.era.zksync.dev"], webSocket: ["wss://sepolia.era.zksync.dev/ws"] } }, blockExplorers: { default: { name: "Etherscan", url: "https://sepolia-era.zksync.network/", apiUrl: "https://api-sepolia-era.zksync.network/api" }, native: { name: "ZKsync Explorer", url: "https://sepolia.explorer.zksync.io/", blockExplorerApi: "https://block-explorer-api.sepolia.zksync.dev/api" } }, contracts: { multicall3: { address: "0xF9cda624FBC7e059355ce98a31693d299FACd963" }, universalSignatureVerifier: { address: "0xfB688330379976DA81eB64Fe4BF50d7401763B9C", blockCreated: 3855712 } }, testnet: true }); // node_modules/thirdweb/dist/esm/transaction/actions/zksync/getEip721Domain.js var gasPerPubdataDefault2 = 50000n; var getEip712Domain3 = (transaction) => { const message = transactionToMessage2(transaction); return { domain: { name: "zkSync", version: "2", chainId: transaction.chainId }, types: { Transaction: [ { name: "txType", type: "uint256" }, { name: "from", type: "uint256" }, { name: "to", type: "uint256" }, { name: "gasLimit", type: "uint256" }, { name: "gasPerPubdataByteLimit", type: "uint256" }, { name: "maxFeePerGas", type: "uint256" }, { name: "maxPriorityFeePerGas", type: "uint256" }, { name: "paymaster", type: "uint256" }, { name: "nonce", type: "uint256" }, { name: "value", type: "uint256" }, { name: "data", type: "bytes" }, { name: "factoryDeps", type: "bytes32[]" }, { name: "paymasterInput", type: "bytes" } ] }, primaryType: "Transaction", message }; }; function transactionToMessage2(transaction) { const { gas, nonce, to, from, value, maxFeePerGas, maxPriorityFeePerGas, paymaster, paymasterInput, gasPerPubdata, data, factoryDeps } = transaction; return { txType: 113n, from: BigInt(from), to: to ? BigInt(to) : 0n, gasLimit: gas ?? 0n, gasPerPubdataByteLimit: gasPerPubdata ?? gasPerPubdataDefault2, maxFeePerGas: maxFeePerGas ?? 0n, maxPriorityFeePerGas: maxPriorityFeePerGas ?? 0n, paymaster: paymaster ? BigInt(paymaster) : 0n, nonce: nonce ? BigInt(nonce) : 0n, value: value ?? 0n, data: data ? data : "0x0", factoryDeps: (factoryDeps == null ? void 0 : factoryDeps.map((dep) => toHex(hashBytecode(dep)))) ?? [], paymasterInput: paymasterInput ? paymasterInput : "0x" }; } // node_modules/thirdweb/dist/esm/transaction/actions/zksync/send-eip712-transaction.js async function sendEip712Transaction2(options) { const { account, transaction } = options; const eip712Transaction = await populateEip712Transaction(options); const hash = await signEip712Transaction2({ account, eip712Transaction, chainId: transaction.chain.id }); const rpc = getRpcClient(transaction); const result = await eth_sendRawTransaction(rpc, hash); return { transactionHash: result, chain: transaction.chain, client: transaction.client }; } async function signEip712Transaction2(options) { const { account, eip712Transaction, chainId } = options; const eip712Domain = getEip712Domain3(eip712Transaction); const customSignature = await account.signTypedData({ // biome-ignore lint/suspicious/noExplicitAny: TODO type properly ...eip712Domain }); return serializeTransactionEIP7122({ ...eip712Transaction, chainId, customSignature }); } async function populateEip712Transaction(options) { const { account, transaction } = options; const { gas, maxFeePerGas, maxPriorityFeePerGas, gasPerPubdata } = await getZkGasFees({ transaction, from: getAddress(account.address) }); const serializableTransaction = await toSerializableTransaction({ transaction: { ...transaction, gas, maxFeePerGas, maxPriorityFeePerGas }, from: account.address }); return { ...serializableTransaction, ...transaction.eip712, gasPerPubdata, from: account.address }; } function serializeTransactionEIP7122(transaction) { const { chainId, gas, nonce, to, from, value, maxFeePerGas, maxPriorityFeePerGas, customSignature, factoryDeps, paymaster, paymasterInput, gasPerPubdata, data } = transaction; const serializedTransaction = [ nonce ? toHex(nonce) : "0x", maxPriorityFeePerGas ? toHex(maxPriorityFeePerGas) : "0x", maxFeePerGas ? toHex(maxFeePerGas) : "0x", gas ? toHex(gas) : "0x", to ?? "0x", value ? toHex(value) : "0x", data ?? "0x0", toHex(chainId), toHex(""), toHex(""), toHex(chainId), from ?? "0x", gasPerPubdata ? toHex(gasPerPubdata) : toHex(gasPerPubdataDefault2), factoryDeps ?? [], customSignature ?? "0x", // EIP712 signature paymaster && paymasterInput ? [paymaster, paymasterInput] : [] ]; return concatHex2(["0x71", toRlp(serializedTransaction)]); } async function getZkGasFees(args) { const { transaction, from } = args; let [gas, maxFeePerGas, maxPriorityFeePerGas, eip712] = await Promise.all([ resolvePromisedValue(transaction.gas), resolvePromisedValue(transaction.maxFeePerGas), resolvePromisedValue(transaction.maxPriorityFeePerGas), resolvePromisedValue(transaction.eip712) ]); let gasPerPubdata = eip712 == null ? void 0 : eip712.gasPerPubdata; if (!gas || !maxFeePerGas || !maxPriorityFeePerGas) { const rpc = getRpcClient(transaction); const params = await formatTransaction({ transaction, from }); const result = await rpc({ // biome-ignore lint/suspicious/noExplicitAny: TODO add to RPC method types method: "zks_estimateFee", // biome-ignore lint/suspicious/noExplicitAny: TODO add to RPC method types params: [replaceBigInts(params, toHex)] }); gas = toBigInt(result.gas_limit) * 2n; const baseFee = toBigInt(result.max_fee_per_gas); maxFeePerGas = baseFee * 2n; maxPriorityFeePerGas = toBigInt(result.max_priority_fee_per_gas) || 1n; gasPerPubdata = toBigInt(result.gas_per_pubdata_limit) * 2n; if (gasPerPubdata < 50000n) { gasPerPubdata = 50000n; } } return { gas, maxFeePerGas, maxPriorityFeePerGas, gasPerPubdata }; } async function formatTransaction(args) { var _a; const { transaction, from } = args; const [data, to, value, eip712] = await Promise.all([ encode(transaction), resolvePromisedValue(transaction.to), resolvePromisedValue(transaction.value), resolvePromisedValue(transaction.eip712) ]); const gasPerPubdata = eip712 == null ? void 0 : eip712.gasPerPubdata; return { from, to, data, value, gasPerPubdata, eip712Meta: { ...eip712, gasPerPubdata: gasPerPubdata || 50000n, factoryDeps: (_a = eip712 == null ? void 0 : eip712.factoryDeps) == null ? void 0 : _a.map((dep) => Array.from(hexToBytes(dep))) }, type: "0x71" }; } export { sendEip712Transaction2 as sendEip712Transaction, signEip712Transaction2 as signEip712Transaction, populateEip712Transaction, getZkGasFees }; //# sourceMappingURL=chunk-5EFACFVF.js.map ================================================ FILE: 17-Crowd-Funding-Dapp/Frontend/.vite/deps_temp_6cf5ba4c/chunk-5THTWD2M.js ================================================ import { sendTransaction } from "./chunk-JTR2PIFP.js"; import { prepareTransaction } from "./chunk-CNLOA7AS.js"; import { checksumAddress } from "./chunk-EIVAOYE5.js"; import { getCachedChain } from "./chunk-TFBEDS4S.js"; import { hexToBigInt, hexToNumber } from "./chunk-BBNNHC5G.js"; // node_modules/thirdweb/dist/esm/wallets/wallet-connect/receiver/request-handlers/send-raw-transaction.js async function handleSendRawTransactionRequest(options) { const { account, chainId, params: [rawTransaction] } = options; if (!account.sendRawTransaction) { throw new Error("The current account does not support sending raw transactions"); } const txResult = await account.sendRawTransaction({ rawTransaction, chainId }); return txResult.transactionHash; } // node_modules/thirdweb/dist/esm/wallets/wallet-connect/receiver/utils.js function validateAccountAddress(account, address) { if (checksumAddress(account.address) !== checksumAddress(address)) { throw new Error(`Failed to validate account address (${account.address}), differs from ${address}`); } } function parseEip155ChainId(chainId) { const chainIdParts = chainId.split(":"); const chainIdAsNumber = Number.parseInt(chainIdParts[1] ?? "0"); if (chainIdParts.length !== 2 || chainIdParts[0] !== "eip155" || chainIdAsNumber === 0 || !chainIdAsNumber) { throw new Error(`Invalid chainId ${chainId}, should have the format 'eip155:1'`); } return chainIdAsNumber; } // node_modules/thirdweb/dist/esm/wallets/wallet-connect/receiver/request-handlers/send-transaction.js async function handleSendTransactionRequest(options) { const { account, chainId, thirdwebClient, params: [transaction] } = options; if (transaction.from !== void 0) { validateAccountAddress(account, transaction.from); } const preparedTransaction = prepareTransaction({ gas: transaction.gas ? hexToBigInt(transaction.gas) : void 0, gasPrice: transaction.gasPrice ? hexToBigInt(transaction.gasPrice) : void 0, value: transaction.value ? hexToBigInt(transaction.value) : void 0, to: transaction.to, data: transaction.data, chain: getCachedChain(chainId), client: thirdwebClient }); const txResult = await sendTransaction({ transaction: preparedTransaction, account }); return txResult.transactionHash; } // node_modules/thirdweb/dist/esm/wallets/wallet-connect/receiver/request-handlers/sign-transaction.js async function handleSignTransactionRequest(options) { const { account, params: [transaction] } = options; if (!account.signTransaction) { throw new Error("The current account does not support signing transactions"); } if (transaction.from !== void 0) { validateAccountAddress(account, transaction.from); } return account.signTransaction({ gas: transaction.gas ? hexToBigInt(transaction.gas) : void 0, gasPrice: transaction.gasPrice ? hexToBigInt(transaction.gasPrice) : void 0, value: transaction.value ? hexToBigInt(transaction.value) : void 0, nonce: transaction.nonce ? hexToNumber(transaction.nonce) : void 0, to: transaction.to, data: transaction.data }); } // node_modules/thirdweb/dist/esm/wallets/wallet-connect/receiver/request-handlers/sign-typed-data.js async function handleSignTypedDataRequest(options) { const { account, params } = options; validateAccountAddress(account, params[0]); return account.signTypedData( // The data could be sent to us as a string or object, depending on the level of parsing on the client side typeof params[1] === "string" ? JSON.parse(params[1]) : params[1] ); } // node_modules/thirdweb/dist/esm/wallets/wallet-connect/receiver/request-handlers/sign.js async function handleSignRequest(options) { const { account, params } = options; validateAccountAddress(account, params[1]); return account.signMessage({ message: { raw: params[0] } }); } export { handleSendRawTransactionRequest, parseEip155ChainId, handleSendTransactionRequest, handleSignTransactionRequest, handleSignTypedDataRequest, handleSignRequest }; //# sourceMappingURL=chunk-5THTWD2M.js.map ================================================ FILE: 17-Crowd-Funding-Dapp/Frontend/.vite/deps_temp_6cf5ba4c/chunk-5U5XBS6S.js ================================================ // node_modules/thirdweb/dist/esm/utils/url.js function isHttpUrl(url) { return url.startsWith("http://") || url.startsWith("https://"); } function formatUniversalUrl(appUrl, wcUri) { if (!isHttpUrl(appUrl)) { return formatNativeUrl(appUrl, wcUri); } let safeAppUrl = appUrl; if (!safeAppUrl.endsWith("/")) { safeAppUrl = `${safeAppUrl}/`; } const encodedWcUrl = encodeURIComponent(wcUri); return { redirect: `${safeAppUrl}wc?uri=${encodedWcUrl}`, href: safeAppUrl }; } function formatNativeUrl(appUrl, wcUri) { if (isHttpUrl(appUrl)) { return formatUniversalUrl(appUrl, wcUri); } let safeAppUrl = appUrl; if (!safeAppUrl.includes("://")) { safeAppUrl = appUrl.replaceAll("/", "").replaceAll(":", ""); safeAppUrl = `${safeAppUrl}://`; } if (!safeAppUrl.endsWith("/")) { safeAppUrl = `${safeAppUrl}/`; } const encodedWcUrl = encodeURIComponent(wcUri); return { redirect: `${safeAppUrl}wc?uri=${encodedWcUrl}`, href: safeAppUrl }; } function formatWalletConnectUrl(appUrl, wcUri) { return isHttpUrl(appUrl) ? formatUniversalUrl(appUrl, wcUri) : formatNativeUrl(appUrl, wcUri); } function formatExplorerTxUrl(explorerUrl, txHash) { return `${explorerUrl.endsWith("/") ? explorerUrl : `${explorerUrl}/`}tx/${txHash}`; } function formatExplorerAddressUrl(explorerUrl, address) { return `${explorerUrl.endsWith("/") ? explorerUrl : `${explorerUrl}/`}address/${address}`; } export { formatWalletConnectUrl, formatExplorerTxUrl, formatExplorerAddressUrl }; //# sourceMappingURL=chunk-5U5XBS6S.js.map ================================================ FILE: 17-Crowd-Funding-Dapp/Frontend/.vite/deps_temp_6cf5ba4c/chunk-65EUCVOP.js ================================================ import { getOrCreateInAppWalletConnector } from "./chunk-6WNCTW75.js"; // node_modules/thirdweb/dist/esm/wallets/in-app/web/lib/auth/index.js async function getInAppWalletConnector(client, ecosystem) { return getOrCreateInAppWalletConnector(client, async (client2) => { const { InAppWebConnector } = await import("./web-connector-5CMXT4ED.js"); return new InAppWebConnector({ client: client2, ecosystem }); }, ecosystem); } async function getAuthenticatedUser(options) { const { client, ecosystem } = options; const connector = await getInAppWalletConnector(client, ecosystem); const user = await connector.getUser(); switch (user.status) { case "Logged In, Wallet Initialized": { return user; } } return void 0; } async function getUserEmail(options) { const user = await getAuthenticatedUser(options); if (user && "email" in user.authDetails) { return user.authDetails.email; } return void 0; } async function getUserPhoneNumber(options) { const user = await getAuthenticatedUser(options); if (user && "phoneNumber" in user.authDetails) { return user.authDetails.phoneNumber; } return void 0; } async function preAuthenticate(args) { const connector = await getInAppWalletConnector(args.client, args.ecosystem); return connector.preAuthenticate(args); } async function authenticate(args) { const connector = await getInAppWalletConnector(args.client, args.ecosystem); return connector.authenticate(args); } async function authenticateWithRedirect(args) { const connector = await getInAppWalletConnector(args.client, args.ecosystem); if (!connector.authenticateWithRedirect) { throw new Error("authenticateWithRedirect is not supported on this platform"); } return connector.authenticateWithRedirect(args.strategy, args.mode, args.redirectUrl); } async function linkProfile(args) { const connector = await getInAppWalletConnector(args.client, args.ecosystem); return await connector.linkProfile(args); } async function getProfiles(args) { const connector = await getInAppWalletConnector(args.client, args.ecosystem); return connector.getProfiles(); } export { getUserEmail, getUserPhoneNumber, preAuthenticate, authenticate, authenticateWithRedirect, linkProfile, getProfiles }; //# sourceMappingURL=chunk-65EUCVOP.js.map ================================================ FILE: 17-Crowd-Funding-Dapp/Frontend/.vite/deps_temp_6cf5ba4c/chunk-673YCYST.js ================================================ // node_modules/thirdweb/dist/esm/constants/addresses.js var NATIVE_TOKEN_ADDRESS = "0xeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee"; function isNativeTokenAddress(address) { return address.toLowerCase() === NATIVE_TOKEN_ADDRESS; } var ZERO_ADDRESS = "0x0000000000000000000000000000000000000000"; export { NATIVE_TOKEN_ADDRESS, isNativeTokenAddress, ZERO_ADDRESS }; //# sourceMappingURL=chunk-673YCYST.js.map ================================================ FILE: 17-Crowd-Funding-Dapp/Frontend/.vite/deps_temp_6cf5ba4c/chunk-67BSOYLQ.js ================================================ import { keccak_256 } from "./chunk-O6LGEXJ4.js"; import { hexToUint8Array, isHex, uint8ArrayToHex } from "./chunk-BBNNHC5G.js"; // node_modules/thirdweb/dist/esm/utils/hashing/keccak256.js function keccak256(value, to) { const bytes = keccak_256(isHex(value, { strict: false }) ? hexToUint8Array(value) : value); if (to === "bytes") { return bytes; } return uint8ArrayToHex(bytes); } export { keccak256 }; //# sourceMappingURL=chunk-67BSOYLQ.js.map ================================================ FILE: 17-Crowd-Funding-Dapp/Frontend/.vite/deps_temp_6cf5ba4c/chunk-6FLJU7W7.js ================================================ // node_modules/thirdweb/dist/esm/utils/arweave.js var DEFAULT_GATEWAY = "https://arweave.net/{fileId}"; function resolveArweaveScheme(options) { if (options.uri.startsWith("ar://")) { const fileId = options.uri.replace("ar://", ""); if (options.gatewayUrl) { const separator = options.gatewayUrl.endsWith("/") ? "" : "/"; return `${options.gatewayUrl}${separator}${fileId}`; } return DEFAULT_GATEWAY.replace("{fileId}", fileId); } if (options.uri.startsWith("http")) { return options.uri; } throw new Error(`Invalid URI scheme, expected "ar://" or "http(s)://"`); } export { resolveArweaveScheme }; //# sourceMappingURL=chunk-6FLJU7W7.js.map ================================================ FILE: 17-Crowd-Funding-Dapp/Frontend/.vite/deps_temp_6cf5ba4c/chunk-6LAJV43E.js ================================================ // node_modules/@lit/reactive-element/development/css-tag.js var NODE_MODE = false; var global = NODE_MODE ? globalThis : window; var supportsAdoptingStyleSheets = global.ShadowRoot && (global.ShadyCSS === void 0 || global.ShadyCSS.nativeShadow) && "adoptedStyleSheets" in Document.prototype && "replace" in CSSStyleSheet.prototype; var constructionToken = Symbol(); var cssTagCache = /* @__PURE__ */ new WeakMap(); var CSSResult = class { constructor(cssText, strings, safeToken) { this["_$cssResult$"] = true; if (safeToken !== constructionToken) { throw new Error("CSSResult is not constructable. Use `unsafeCSS` or `css` instead."); } this.cssText = cssText; this._strings = strings; } // This is a getter so that it's lazy. In practice, this means stylesheets // are not created until the first element instance is made. get styleSheet() { let styleSheet = this._styleSheet; const strings = this._strings; if (supportsAdoptingStyleSheets && styleSheet === void 0) { const cacheable = strings !== void 0 && strings.length === 1; if (cacheable) { styleSheet = cssTagCache.get(strings); } if (styleSheet === void 0) { (this._styleSheet = styleSheet = new CSSStyleSheet()).replaceSync(this.cssText); if (cacheable) { cssTagCache.set(strings, styleSheet); } } } return styleSheet; } toString() { return this.cssText; } }; var textFromCSSResult = (value) => { if (value["_$cssResult$"] === true) { return value.cssText; } else if (typeof value === "number") { return value; } else { throw new Error(`Value passed to 'css' function must be a 'css' function result: ${value}. Use 'unsafeCSS' to pass non-literal values, but take care to ensure page security.`); } }; var unsafeCSS = (value) => new CSSResult(typeof value === "string" ? value : String(value), void 0, constructionToken); var css = (strings, ...values) => { const cssText = strings.length === 1 ? strings[0] : values.reduce((acc, v, idx) => acc + textFromCSSResult(v) + strings[idx + 1], strings[0]); return new CSSResult(cssText, strings, constructionToken); }; var adoptStyles = (renderRoot, styles) => { if (supportsAdoptingStyleSheets) { renderRoot.adoptedStyleSheets = styles.map((s) => s instanceof CSSStyleSheet ? s : s.styleSheet); } else { styles.forEach((s) => { const style = document.createElement("style"); const nonce = global["litNonce"]; if (nonce !== void 0) { style.setAttribute("nonce", nonce); } style.textContent = s.cssText; renderRoot.appendChild(style); }); } }; var cssResultFromStyleSheet = (sheet) => { let cssText = ""; for (const rule of sheet.cssRules) { cssText += rule.cssText; } return unsafeCSS(cssText); }; var getCompatibleStyle = supportsAdoptingStyleSheets || NODE_MODE && global.CSSStyleSheet === void 0 ? (s) => s : (s) => s instanceof CSSStyleSheet ? cssResultFromStyleSheet(s) : s; // node_modules/lit-html/development/lit-html.js var _a; var _b; var _c; var _d; var DEV_MODE = true; var ENABLE_EXTRA_SECURITY_HOOKS = true; var ENABLE_SHADYDOM_NOPATCH = true; var NODE_MODE2 = false; var global2 = NODE_MODE2 ? globalThis : window; var debugLogEvent = DEV_MODE ? (event) => { const shouldEmit = global2.emitLitDebugLogEvents; if (!shouldEmit) { return; } global2.dispatchEvent(new CustomEvent("lit-debug", { detail: event })); } : void 0; var debugLogRenderId = 0; var issueWarning; if (DEV_MODE) { (_a = global2.litIssuedWarnings) !== null && _a !== void 0 ? _a : global2.litIssuedWarnings = /* @__PURE__ */ new Set(); issueWarning = (code, warning) => { warning += code ? ` See https://lit.dev/msg/${code} for more information.` : ""; if (!global2.litIssuedWarnings.has(warning)) { console.warn(warning); global2.litIssuedWarnings.add(warning); } }; issueWarning("dev-mode", `Lit is in dev mode. Not recommended for production!`); } var wrap = ENABLE_SHADYDOM_NOPATCH && ((_b = global2.ShadyDOM) === null || _b === void 0 ? void 0 : _b.inUse) && ((_c = global2.ShadyDOM) === null || _c === void 0 ? void 0 : _c.noPatch) === true ? global2.ShadyDOM.wrap : (node) => node; var trustedTypes = global2.trustedTypes; var policy = trustedTypes ? trustedTypes.createPolicy("lit-html", { createHTML: (s) => s }) : void 0; var identityFunction = (value) => value; var noopSanitizer = (_node, _name, _type) => identityFunction; var setSanitizer = (newSanitizer) => { if (!ENABLE_EXTRA_SECURITY_HOOKS) { return; } if (sanitizerFactoryInternal !== noopSanitizer) { throw new Error(`Attempted to overwrite existing lit-html security policy. setSanitizeDOMValueFactory should be called at most once.`); } sanitizerFactoryInternal = newSanitizer; }; var _testOnlyClearSanitizerFactoryDoNotCallOrElse = () => { sanitizerFactoryInternal = noopSanitizer; }; var createSanitizer = (node, name, type) => { return sanitizerFactoryInternal(node, name, type); }; var boundAttributeSuffix = "$lit$"; var marker = `lit$${String(Math.random()).slice(9)}$`; var markerMatch = "?" + marker; var nodeMarker = `<${markerMatch}>`; var d = NODE_MODE2 && global2.document === void 0 ? { createTreeWalker() { return {}; } } : document; var createMarker = () => d.createComment(""); var isPrimitive = (value) => value === null || typeof value != "object" && typeof value != "function"; var isArray = Array.isArray; var isIterable = (value) => isArray(value) || // eslint-disable-next-line @typescript-eslint/no-explicit-any typeof (value === null || value === void 0 ? void 0 : value[Symbol.iterator]) === "function"; var SPACE_CHAR = `[ \f\r]`; var ATTR_VALUE_CHAR = `[^ \f\r"'\`<>=]`; var NAME_CHAR = `[^\\s"'>=/]`; var textEndRegex = /<(?:(!--|\/[^a-zA-Z])|(\/?[a-zA-Z][^>\s]*)|(\/?$))/g; var COMMENT_START = 1; var TAG_NAME = 2; var DYNAMIC_TAG_NAME = 3; var commentEndRegex = /-->/g; var comment2EndRegex = />/g; var tagEndRegex = new RegExp(`>|${SPACE_CHAR}(?:(${NAME_CHAR}+)(${SPACE_CHAR}*=${SPACE_CHAR}*(?:${ATTR_VALUE_CHAR}|("|')|))|$)`, "g"); var ENTIRE_MATCH = 0; var ATTRIBUTE_NAME = 1; var SPACES_AND_EQUALS = 2; var QUOTE_CHAR = 3; var singleQuoteAttrEndRegex = /'/g; var doubleQuoteAttrEndRegex = /"/g; var rawTextElement = /^(?:script|style|textarea|title)$/i; var HTML_RESULT = 1; var SVG_RESULT = 2; var ATTRIBUTE_PART = 1; var CHILD_PART = 2; var PROPERTY_PART = 3; var BOOLEAN_ATTRIBUTE_PART = 4; var EVENT_PART = 5; var ELEMENT_PART = 6; var COMMENT_PART = 7; var tag = (type) => (strings, ...values) => { if (DEV_MODE && strings.some((s) => s === void 0)) { console.warn("Some template strings are undefined.\nThis is probably caused by illegal octal escape sequences."); } return { // This property needs to remain unminified. ["_$litType$"]: type, strings, values }; }; var html = tag(HTML_RESULT); var svg = tag(SVG_RESULT); var noChange = Symbol.for("lit-noChange"); var nothing = Symbol.for("lit-nothing"); var templateCache = /* @__PURE__ */ new WeakMap(); var walker = d.createTreeWalker(d, 129, null, false); var sanitizerFactoryInternal = noopSanitizer; function trustFromTemplateString(tsa, stringFromTSA) { if (!Array.isArray(tsa) || !tsa.hasOwnProperty("raw")) { let message = "invalid template strings array"; if (DEV_MODE) { message = ` Internal Error: expected template strings to be an array with a 'raw' field. Faking a template strings array by calling html or svg like an ordinary function is effectively the same as calling unsafeHtml and can lead to major security issues, e.g. opening your code up to XSS attacks. If you're using the html or svg tagged template functions normally and still seeing this error, please file a bug at https://github.com/lit/lit/issues/new?template=bug_report.md and include information about your build tooling, if any. `.trim().replace(/\n */g, "\n"); } throw new Error(message); } return policy !== void 0 ? policy.createHTML(stringFromTSA) : stringFromTSA; } var getTemplateHtml = (strings, type) => { const l = strings.length - 1; const attrNames = []; let html2 = type === SVG_RESULT ? "" : ""; let rawTextEndRegex; let regex = textEndRegex; for (let i = 0; i < l; i++) { const s = strings[i]; let attrNameEndIndex = -1; let attrName; let lastIndex = 0; let match; while (lastIndex < s.length) { regex.lastIndex = lastIndex; match = regex.exec(s); if (match === null) { break; } lastIndex = regex.lastIndex; if (regex === textEndRegex) { if (match[COMMENT_START] === "!--") { regex = commentEndRegex; } else if (match[COMMENT_START] !== void 0) { regex = comment2EndRegex; } else if (match[TAG_NAME] !== void 0) { if (rawTextElement.test(match[TAG_NAME])) { rawTextEndRegex = new RegExp(`") { regex = rawTextEndRegex !== null && rawTextEndRegex !== void 0 ? rawTextEndRegex : textEndRegex; attrNameEndIndex = -1; } else if (match[ATTRIBUTE_NAME] === void 0) { attrNameEndIndex = -2; } else { attrNameEndIndex = regex.lastIndex - match[SPACES_AND_EQUALS].length; attrName = match[ATTRIBUTE_NAME]; regex = match[QUOTE_CHAR] === void 0 ? tagEndRegex : match[QUOTE_CHAR] === '"' ? doubleQuoteAttrEndRegex : singleQuoteAttrEndRegex; } } else if (regex === doubleQuoteAttrEndRegex || regex === singleQuoteAttrEndRegex) { regex = tagEndRegex; } else if (regex === commentEndRegex || regex === comment2EndRegex) { regex = textEndRegex; } else { regex = tagEndRegex; rawTextEndRegex = void 0; } } if (DEV_MODE) { console.assert(attrNameEndIndex === -1 || regex === tagEndRegex || regex === singleQuoteAttrEndRegex || regex === doubleQuoteAttrEndRegex, "unexpected parse state B"); } const end = regex === tagEndRegex && strings[i + 1].startsWith("/>") ? " " : ""; html2 += regex === textEndRegex ? s + nodeMarker : attrNameEndIndex >= 0 ? (attrNames.push(attrName), s.slice(0, attrNameEndIndex) + boundAttributeSuffix + s.slice(attrNameEndIndex)) + marker + end : s + marker + (attrNameEndIndex === -2 ? (attrNames.push(void 0), i) : end); } const htmlResult = html2 + (strings[l] || "") + (type === SVG_RESULT ? "" : ""); return [trustFromTemplateString(strings, htmlResult), attrNames]; }; var Template = class _Template { constructor({ strings, ["_$litType$"]: type }, options) { this.parts = []; let node; let nodeIndex = 0; let attrNameIndex = 0; const partCount = strings.length - 1; const parts = this.parts; const [html2, attrNames] = getTemplateHtml(strings, type); this.el = _Template.createElement(html2, options); walker.currentNode = this.el.content; if (type === SVG_RESULT) { const content = this.el.content; const svgElement = content.firstChild; svgElement.remove(); content.append(...svgElement.childNodes); } while ((node = walker.nextNode()) !== null && parts.length < partCount) { if (node.nodeType === 1) { if (DEV_MODE) { const tag2 = node.localName; if (/^(?:textarea|template)$/i.test(tag2) && node.innerHTML.includes(marker)) { const m = `Expressions are not supported inside \`${tag2}\` elements. See https://lit.dev/msg/expression-in-${tag2} for more information.`; if (tag2 === "template") { throw new Error(m); } else issueWarning("", m); } } if (node.hasAttributes()) { const attrsToRemove = []; for (const name of node.getAttributeNames()) { if (name.endsWith(boundAttributeSuffix) || name.startsWith(marker)) { const realName = attrNames[attrNameIndex++]; attrsToRemove.push(name); if (realName !== void 0) { const value = node.getAttribute(realName.toLowerCase() + boundAttributeSuffix); const statics = value.split(marker); const m = /([.?@])?(.*)/.exec(realName); parts.push({ type: ATTRIBUTE_PART, index: nodeIndex, name: m[2], strings: statics, ctor: m[1] === "." ? PropertyPart : m[1] === "?" ? BooleanAttributePart : m[1] === "@" ? EventPart : AttributePart }); } else { parts.push({ type: ELEMENT_PART, index: nodeIndex }); } } } for (const name of attrsToRemove) { node.removeAttribute(name); } } if (rawTextElement.test(node.tagName)) { const strings2 = node.textContent.split(marker); const lastIndex = strings2.length - 1; if (lastIndex > 0) { node.textContent = trustedTypes ? trustedTypes.emptyScript : ""; for (let i = 0; i < lastIndex; i++) { node.append(strings2[i], createMarker()); walker.nextNode(); parts.push({ type: CHILD_PART, index: ++nodeIndex }); } node.append(strings2[lastIndex], createMarker()); } } } else if (node.nodeType === 8) { const data = node.data; if (data === markerMatch) { parts.push({ type: CHILD_PART, index: nodeIndex }); } else { let i = -1; while ((i = node.data.indexOf(marker, i + 1)) !== -1) { parts.push({ type: COMMENT_PART, index: nodeIndex }); i += marker.length - 1; } } } nodeIndex++; } debugLogEvent === null || debugLogEvent === void 0 ? void 0 : debugLogEvent({ kind: "template prep", template: this, clonableTemplate: this.el, parts: this.parts, strings }); } // Overridden via `litHtmlPolyfillSupport` to provide platform support. /** @nocollapse */ static createElement(html2, _options) { const el = d.createElement("template"); el.innerHTML = html2; return el; } }; function resolveDirective(part, value, parent = part, attributeIndex) { var _a5, _b4, _c4; var _d3; if (value === noChange) { return value; } let currentDirective = attributeIndex !== void 0 ? (_a5 = parent.__directives) === null || _a5 === void 0 ? void 0 : _a5[attributeIndex] : parent.__directive; const nextDirectiveConstructor = isPrimitive(value) ? void 0 : ( // This property needs to remain unminified. value["_$litDirective$"] ); if ((currentDirective === null || currentDirective === void 0 ? void 0 : currentDirective.constructor) !== nextDirectiveConstructor) { (_b4 = currentDirective === null || currentDirective === void 0 ? void 0 : currentDirective["_$notifyDirectiveConnectionChanged"]) === null || _b4 === void 0 ? void 0 : _b4.call(currentDirective, false); if (nextDirectiveConstructor === void 0) { currentDirective = void 0; } else { currentDirective = new nextDirectiveConstructor(part); currentDirective._$initialize(part, parent, attributeIndex); } if (attributeIndex !== void 0) { ((_c4 = (_d3 = parent).__directives) !== null && _c4 !== void 0 ? _c4 : _d3.__directives = [])[attributeIndex] = currentDirective; } else { parent.__directive = currentDirective; } } if (currentDirective !== void 0) { value = resolveDirective(part, currentDirective._$resolve(part, value.values), currentDirective, attributeIndex); } return value; } var TemplateInstance = class { constructor(template, parent) { this._$parts = []; this._$disconnectableChildren = void 0; this._$template = template; this._$parent = parent; } // Called by ChildPart parentNode getter get parentNode() { return this._$parent.parentNode; } // See comment in Disconnectable interface for why this is a getter get _$isConnected() { return this._$parent._$isConnected; } // This method is separate from the constructor because we need to return a // DocumentFragment and we don't want to hold onto it with an instance field. _clone(options) { var _a5; const { el: { content }, parts } = this._$template; const fragment = ((_a5 = options === null || options === void 0 ? void 0 : options.creationScope) !== null && _a5 !== void 0 ? _a5 : d).importNode(content, true); walker.currentNode = fragment; let node = walker.nextNode(); let nodeIndex = 0; let partIndex = 0; let templatePart = parts[0]; while (templatePart !== void 0) { if (nodeIndex === templatePart.index) { let part; if (templatePart.type === CHILD_PART) { part = new ChildPart(node, node.nextSibling, this, options); } else if (templatePart.type === ATTRIBUTE_PART) { part = new templatePart.ctor(node, templatePart.name, templatePart.strings, this, options); } else if (templatePart.type === ELEMENT_PART) { part = new ElementPart(node, this, options); } this._$parts.push(part); templatePart = parts[++partIndex]; } if (nodeIndex !== (templatePart === null || templatePart === void 0 ? void 0 : templatePart.index)) { node = walker.nextNode(); nodeIndex++; } } walker.currentNode = d; return fragment; } _update(values) { let i = 0; for (const part of this._$parts) { if (part !== void 0) { debugLogEvent === null || debugLogEvent === void 0 ? void 0 : debugLogEvent({ kind: "set part", part, value: values[i], valueIndex: i, values, templateInstance: this }); if (part.strings !== void 0) { part._$setValue(values, part, i); i += part.strings.length - 2; } else { part._$setValue(values[i]); } } i++; } } }; var ChildPart = class _ChildPart { constructor(startNode, endNode, parent, options) { var _a5; this.type = CHILD_PART; this._$committedValue = nothing; this._$disconnectableChildren = void 0; this._$startNode = startNode; this._$endNode = endNode; this._$parent = parent; this.options = options; this.__isConnected = (_a5 = options === null || options === void 0 ? void 0 : options.isConnected) !== null && _a5 !== void 0 ? _a5 : true; if (ENABLE_EXTRA_SECURITY_HOOKS) { this._textSanitizer = void 0; } } // See comment in Disconnectable interface for why this is a getter get _$isConnected() { var _a5, _b4; return (_b4 = (_a5 = this._$parent) === null || _a5 === void 0 ? void 0 : _a5._$isConnected) !== null && _b4 !== void 0 ? _b4 : this.__isConnected; } /** * The parent node into which the part renders its content. * * A ChildPart's content consists of a range of adjacent child nodes of * `.parentNode`, possibly bordered by 'marker nodes' (`.startNode` and * `.endNode`). * * - If both `.startNode` and `.endNode` are non-null, then the part's content * consists of all siblings between `.startNode` and `.endNode`, exclusively. * * - If `.startNode` is non-null but `.endNode` is null, then the part's * content consists of all siblings following `.startNode`, up to and * including the last child of `.parentNode`. If `.endNode` is non-null, then * `.startNode` will always be non-null. * * - If both `.endNode` and `.startNode` are null, then the part's content * consists of all child nodes of `.parentNode`. */ get parentNode() { let parentNode = wrap(this._$startNode).parentNode; const parent = this._$parent; if (parent !== void 0 && (parentNode === null || parentNode === void 0 ? void 0 : parentNode.nodeType) === 11) { parentNode = parent.parentNode; } return parentNode; } /** * The part's leading marker node, if any. See `.parentNode` for more * information. */ get startNode() { return this._$startNode; } /** * The part's trailing marker node, if any. See `.parentNode` for more * information. */ get endNode() { return this._$endNode; } _$setValue(value, directiveParent = this) { var _a5; if (DEV_MODE && this.parentNode === null) { throw new Error(`This \`ChildPart\` has no \`parentNode\` and therefore cannot accept a value. This likely means the element containing the part was manipulated in an unsupported way outside of Lit's control such that the part's marker nodes were ejected from DOM. For example, setting the element's \`innerHTML\` or \`textContent\` can do this.`); } value = resolveDirective(this, value, directiveParent); if (isPrimitive(value)) { if (value === nothing || value == null || value === "") { if (this._$committedValue !== nothing) { debugLogEvent === null || debugLogEvent === void 0 ? void 0 : debugLogEvent({ kind: "commit nothing to child", start: this._$startNode, end: this._$endNode, parent: this._$parent, options: this.options }); this._$clear(); } this._$committedValue = nothing; } else if (value !== this._$committedValue && value !== noChange) { this._commitText(value); } } else if (value["_$litType$"] !== void 0) { this._commitTemplateResult(value); } else if (value.nodeType !== void 0) { if (DEV_MODE && ((_a5 = this.options) === null || _a5 === void 0 ? void 0 : _a5.host) === value) { this._commitText(`[probable mistake: rendered a template's host in itself (commonly caused by writing \${this} in a template]`); console.warn(`Attempted to render the template host`, value, `inside itself. This is almost always a mistake, and in dev mode `, `we render some warning text. In production however, we'll `, `render it, which will usually result in an error, and sometimes `, `in the element disappearing from the DOM.`); return; } this._commitNode(value); } else if (isIterable(value)) { this._commitIterable(value); } else { this._commitText(value); } } _insert(node) { return wrap(wrap(this._$startNode).parentNode).insertBefore(node, this._$endNode); } _commitNode(value) { var _a5; if (this._$committedValue !== value) { this._$clear(); if (ENABLE_EXTRA_SECURITY_HOOKS && sanitizerFactoryInternal !== noopSanitizer) { const parentNodeName = (_a5 = this._$startNode.parentNode) === null || _a5 === void 0 ? void 0 : _a5.nodeName; if (parentNodeName === "STYLE" || parentNodeName === "SCRIPT") { let message = "Forbidden"; if (DEV_MODE) { if (parentNodeName === "STYLE") { message = `Lit does not support binding inside style nodes. This is a security risk, as style injection attacks can exfiltrate data and spoof UIs. Consider instead using css\`...\` literals to compose styles, and make do dynamic styling with css custom properties, ::parts, s, and by mutating the DOM rather than stylesheets.`; } else { message = `Lit does not support binding inside script nodes. This is a security risk, as it could allow arbitrary code execution.`; } } throw new Error(message); } } debugLogEvent === null || debugLogEvent === void 0 ? void 0 : debugLogEvent({ kind: "commit node", start: this._$startNode, parent: this._$parent, value, options: this.options }); this._$committedValue = this._insert(value); } } _commitText(value) { if (this._$committedValue !== nothing && isPrimitive(this._$committedValue)) { const node = wrap(this._$startNode).nextSibling; if (ENABLE_EXTRA_SECURITY_HOOKS) { if (this._textSanitizer === void 0) { this._textSanitizer = createSanitizer(node, "data", "property"); } value = this._textSanitizer(value); } debugLogEvent === null || debugLogEvent === void 0 ? void 0 : debugLogEvent({ kind: "commit text", node, value, options: this.options }); node.data = value; } else { if (ENABLE_EXTRA_SECURITY_HOOKS) { const textNode = d.createTextNode(""); this._commitNode(textNode); if (this._textSanitizer === void 0) { this._textSanitizer = createSanitizer(textNode, "data", "property"); } value = this._textSanitizer(value); debugLogEvent === null || debugLogEvent === void 0 ? void 0 : debugLogEvent({ kind: "commit text", node: textNode, value, options: this.options }); textNode.data = value; } else { this._commitNode(d.createTextNode(value)); debugLogEvent === null || debugLogEvent === void 0 ? void 0 : debugLogEvent({ kind: "commit text", node: wrap(this._$startNode).nextSibling, value, options: this.options }); } } this._$committedValue = value; } _commitTemplateResult(result) { var _a5; const { values, ["_$litType$"]: type } = result; const template = typeof type === "number" ? this._$getTemplate(result) : (type.el === void 0 && (type.el = Template.createElement(trustFromTemplateString(type.h, type.h[0]), this.options)), type); if (((_a5 = this._$committedValue) === null || _a5 === void 0 ? void 0 : _a5._$template) === template) { debugLogEvent === null || debugLogEvent === void 0 ? void 0 : debugLogEvent({ kind: "template updating", template, instance: this._$committedValue, parts: this._$committedValue._$parts, options: this.options, values }); this._$committedValue._update(values); } else { const instance = new TemplateInstance(template, this); const fragment = instance._clone(this.options); debugLogEvent === null || debugLogEvent === void 0 ? void 0 : debugLogEvent({ kind: "template instantiated", template, instance, parts: instance._$parts, options: this.options, fragment, values }); instance._update(values); debugLogEvent === null || debugLogEvent === void 0 ? void 0 : debugLogEvent({ kind: "template instantiated and updated", template, instance, parts: instance._$parts, options: this.options, fragment, values }); this._commitNode(fragment); this._$committedValue = instance; } } // Overridden via `litHtmlPolyfillSupport` to provide platform support. /** @internal */ _$getTemplate(result) { let template = templateCache.get(result.strings); if (template === void 0) { templateCache.set(result.strings, template = new Template(result)); } return template; } _commitIterable(value) { if (!isArray(this._$committedValue)) { this._$committedValue = []; this._$clear(); } const itemParts = this._$committedValue; let partIndex = 0; let itemPart; for (const item of value) { if (partIndex === itemParts.length) { itemParts.push(itemPart = new _ChildPart(this._insert(createMarker()), this._insert(createMarker()), this, this.options)); } else { itemPart = itemParts[partIndex]; } itemPart._$setValue(item); partIndex++; } if (partIndex < itemParts.length) { this._$clear(itemPart && wrap(itemPart._$endNode).nextSibling, partIndex); itemParts.length = partIndex; } } /** * Removes the nodes contained within this Part from the DOM. * * @param start Start node to clear from, for clearing a subset of the part's * DOM (used when truncating iterables) * @param from When `start` is specified, the index within the iterable from * which ChildParts are being removed, used for disconnecting directives in * those Parts. * * @internal */ _$clear(start = wrap(this._$startNode).nextSibling, from) { var _a5; (_a5 = this._$notifyConnectionChanged) === null || _a5 === void 0 ? void 0 : _a5.call(this, false, true, from); while (start && start !== this._$endNode) { const n = wrap(start).nextSibling; wrap(start).remove(); start = n; } } /** * Implementation of RootPart's `isConnected`. Note that this metod * should only be called on `RootPart`s (the `ChildPart` returned from a * top-level `render()` call). It has no effect on non-root ChildParts. * @param isConnected Whether to set * @internal */ setConnected(isConnected) { var _a5; if (this._$parent === void 0) { this.__isConnected = isConnected; (_a5 = this._$notifyConnectionChanged) === null || _a5 === void 0 ? void 0 : _a5.call(this, isConnected); } else if (DEV_MODE) { throw new Error("part.setConnected() may only be called on a RootPart returned from render()."); } } }; var AttributePart = class { constructor(element, name, strings, parent, options) { this.type = ATTRIBUTE_PART; this._$committedValue = nothing; this._$disconnectableChildren = void 0; this.element = element; this.name = name; this._$parent = parent; this.options = options; if (strings.length > 2 || strings[0] !== "" || strings[1] !== "") { this._$committedValue = new Array(strings.length - 1).fill(new String()); this.strings = strings; } else { this._$committedValue = nothing; } if (ENABLE_EXTRA_SECURITY_HOOKS) { this._sanitizer = void 0; } } get tagName() { return this.element.tagName; } // See comment in Disconnectable interface for why this is a getter get _$isConnected() { return this._$parent._$isConnected; } /** * Sets the value of this part by resolving the value from possibly multiple * values and static strings and committing it to the DOM. * If this part is single-valued, `this._strings` will be undefined, and the * method will be called with a single value argument. If this part is * multi-value, `this._strings` will be defined, and the method is called * with the value array of the part's owning TemplateInstance, and an offset * into the value array from which the values should be read. * This method is overloaded this way to eliminate short-lived array slices * of the template instance values, and allow a fast-path for single-valued * parts. * * @param value The part value, or an array of values for multi-valued parts * @param valueIndex the index to start reading values from. `undefined` for * single-valued parts * @param noCommit causes the part to not commit its value to the DOM. Used * in hydration to prime attribute parts with their first-rendered value, * but not set the attribute, and in SSR to no-op the DOM operation and * capture the value for serialization. * * @internal */ _$setValue(value, directiveParent = this, valueIndex, noCommit) { const strings = this.strings; let change = false; if (strings === void 0) { value = resolveDirective(this, value, directiveParent, 0); change = !isPrimitive(value) || value !== this._$committedValue && value !== noChange; if (change) { this._$committedValue = value; } } else { const values = value; value = strings[0]; let i, v; for (i = 0; i < strings.length - 1; i++) { v = resolveDirective(this, values[valueIndex + i], directiveParent, i); if (v === noChange) { v = this._$committedValue[i]; } change || (change = !isPrimitive(v) || v !== this._$committedValue[i]); if (v === nothing) { value = nothing; } else if (value !== nothing) { value += (v !== null && v !== void 0 ? v : "") + strings[i + 1]; } this._$committedValue[i] = v; } } if (change && !noCommit) { this._commitValue(value); } } /** @internal */ _commitValue(value) { if (value === nothing) { wrap(this.element).removeAttribute(this.name); } else { if (ENABLE_EXTRA_SECURITY_HOOKS) { if (this._sanitizer === void 0) { this._sanitizer = sanitizerFactoryInternal(this.element, this.name, "attribute"); } value = this._sanitizer(value !== null && value !== void 0 ? value : ""); } debugLogEvent === null || debugLogEvent === void 0 ? void 0 : debugLogEvent({ kind: "commit attribute", element: this.element, name: this.name, value, options: this.options }); wrap(this.element).setAttribute(this.name, value !== null && value !== void 0 ? value : ""); } } }; var PropertyPart = class extends AttributePart { constructor() { super(...arguments); this.type = PROPERTY_PART; } /** @internal */ _commitValue(value) { if (ENABLE_EXTRA_SECURITY_HOOKS) { if (this._sanitizer === void 0) { this._sanitizer = sanitizerFactoryInternal(this.element, this.name, "property"); } value = this._sanitizer(value); } debugLogEvent === null || debugLogEvent === void 0 ? void 0 : debugLogEvent({ kind: "commit property", element: this.element, name: this.name, value, options: this.options }); this.element[this.name] = value === nothing ? void 0 : value; } }; var emptyStringForBooleanAttribute = trustedTypes ? trustedTypes.emptyScript : ""; var BooleanAttributePart = class extends AttributePart { constructor() { super(...arguments); this.type = BOOLEAN_ATTRIBUTE_PART; } /** @internal */ _commitValue(value) { debugLogEvent === null || debugLogEvent === void 0 ? void 0 : debugLogEvent({ kind: "commit boolean attribute", element: this.element, name: this.name, value: !!(value && value !== nothing), options: this.options }); if (value && value !== nothing) { wrap(this.element).setAttribute(this.name, emptyStringForBooleanAttribute); } else { wrap(this.element).removeAttribute(this.name); } } }; var EventPart = class extends AttributePart { constructor(element, name, strings, parent, options) { super(element, name, strings, parent, options); this.type = EVENT_PART; if (DEV_MODE && this.strings !== void 0) { throw new Error(`A \`<${element.localName}>\` has a \`@${name}=...\` listener with invalid content. Event listeners in templates must have exactly one expression and no surrounding text.`); } } // EventPart does not use the base _$setValue/_resolveValue implementation // since the dirty checking is more complex /** @internal */ _$setValue(newListener, directiveParent = this) { var _a5; newListener = (_a5 = resolveDirective(this, newListener, directiveParent, 0)) !== null && _a5 !== void 0 ? _a5 : nothing; if (newListener === noChange) { return; } const oldListener = this._$committedValue; const shouldRemoveListener = newListener === nothing && oldListener !== nothing || newListener.capture !== oldListener.capture || newListener.once !== oldListener.once || newListener.passive !== oldListener.passive; const shouldAddListener = newListener !== nothing && (oldListener === nothing || shouldRemoveListener); debugLogEvent === null || debugLogEvent === void 0 ? void 0 : debugLogEvent({ kind: "commit event listener", element: this.element, name: this.name, value: newListener, options: this.options, removeListener: shouldRemoveListener, addListener: shouldAddListener, oldListener }); if (shouldRemoveListener) { this.element.removeEventListener(this.name, this, oldListener); } if (shouldAddListener) { this.element.addEventListener(this.name, this, newListener); } this._$committedValue = newListener; } handleEvent(event) { var _a5, _b4; if (typeof this._$committedValue === "function") { this._$committedValue.call((_b4 = (_a5 = this.options) === null || _a5 === void 0 ? void 0 : _a5.host) !== null && _b4 !== void 0 ? _b4 : this.element, event); } else { this._$committedValue.handleEvent(event); } } }; var ElementPart = class { constructor(element, parent, options) { this.element = element; this.type = ELEMENT_PART; this._$disconnectableChildren = void 0; this._$parent = parent; this.options = options; } // See comment in Disconnectable interface for why this is a getter get _$isConnected() { return this._$parent._$isConnected; } _$setValue(value) { debugLogEvent === null || debugLogEvent === void 0 ? void 0 : debugLogEvent({ kind: "commit to element binding", element: this.element, value, options: this.options }); resolveDirective(this, value); } }; var polyfillSupport = DEV_MODE ? global2.litHtmlPolyfillSupportDevMode : global2.litHtmlPolyfillSupport; polyfillSupport === null || polyfillSupport === void 0 ? void 0 : polyfillSupport(Template, ChildPart); ((_d = global2.litHtmlVersions) !== null && _d !== void 0 ? _d : global2.litHtmlVersions = []).push("2.8.0"); if (DEV_MODE && global2.litHtmlVersions.length > 1) { issueWarning("multiple-versions", `Multiple versions of Lit loaded. Loading multiple versions is not recommended.`); } var render = (value, container, options) => { var _a5, _b4; if (DEV_MODE && container == null) { throw new TypeError(`The container to render into may not be ${container}`); } const renderId = DEV_MODE ? debugLogRenderId++ : 0; const partOwnerNode = (_a5 = options === null || options === void 0 ? void 0 : options.renderBefore) !== null && _a5 !== void 0 ? _a5 : container; let part = partOwnerNode["_$litPart$"]; debugLogEvent === null || debugLogEvent === void 0 ? void 0 : debugLogEvent({ kind: "begin render", id: renderId, value, container, options, part }); if (part === void 0) { const endNode = (_b4 = options === null || options === void 0 ? void 0 : options.renderBefore) !== null && _b4 !== void 0 ? _b4 : null; partOwnerNode["_$litPart$"] = part = new ChildPart(container.insertBefore(createMarker(), endNode), endNode, void 0, options !== null && options !== void 0 ? options : {}); } part._$setValue(value); debugLogEvent === null || debugLogEvent === void 0 ? void 0 : debugLogEvent({ kind: "end render", id: renderId, value, container, options, part }); return part; }; if (ENABLE_EXTRA_SECURITY_HOOKS) { render.setSanitizer = setSanitizer; render.createSanitizer = createSanitizer; if (DEV_MODE) { render._testOnlyClearSanitizerFactoryDoNotCallOrElse = _testOnlyClearSanitizerFactoryDoNotCallOrElse; } } // node_modules/@lit/reactive-element/development/reactive-element.js var _a2; var _b2; var _c2; var _d2; var _e; var NODE_MODE3 = false; var global3 = NODE_MODE3 ? globalThis : window; if (NODE_MODE3) { (_a2 = global3.customElements) !== null && _a2 !== void 0 ? _a2 : global3.customElements = customElements; } var DEV_MODE2 = true; var requestUpdateThenable; var issueWarning2; var trustedTypes2 = global3.trustedTypes; var emptyStringForBooleanAttribute2 = trustedTypes2 ? trustedTypes2.emptyScript : ""; var polyfillSupport2 = DEV_MODE2 ? global3.reactiveElementPolyfillSupportDevMode : global3.reactiveElementPolyfillSupport; if (DEV_MODE2) { const issuedWarnings = (_b2 = global3.litIssuedWarnings) !== null && _b2 !== void 0 ? _b2 : global3.litIssuedWarnings = /* @__PURE__ */ new Set(); issueWarning2 = (code, warning) => { warning += ` See https://lit.dev/msg/${code} for more information.`; if (!issuedWarnings.has(warning)) { console.warn(warning); issuedWarnings.add(warning); } }; issueWarning2("dev-mode", `Lit is in dev mode. Not recommended for production!`); if (((_c2 = global3.ShadyDOM) === null || _c2 === void 0 ? void 0 : _c2.inUse) && polyfillSupport2 === void 0) { issueWarning2("polyfill-support-missing", `Shadow DOM is being polyfilled via \`ShadyDOM\` but the \`polyfill-support\` module has not been loaded.`); } requestUpdateThenable = (name) => ({ then: (onfulfilled, _onrejected) => { issueWarning2("request-update-promise", `The \`requestUpdate\` method should no longer return a Promise but does so on \`${name}\`. Use \`updateComplete\` instead.`); if (onfulfilled !== void 0) { onfulfilled(false); } } }); } var debugLogEvent2 = DEV_MODE2 ? (event) => { const shouldEmit = global3.emitLitDebugLogEvents; if (!shouldEmit) { return; } global3.dispatchEvent(new CustomEvent("lit-debug", { detail: event })); } : void 0; var JSCompiler_renameProperty = (prop, _obj) => prop; var defaultConverter = { toAttribute(value, type) { switch (type) { case Boolean: value = value ? emptyStringForBooleanAttribute2 : null; break; case Object: case Array: value = value == null ? value : JSON.stringify(value); break; } return value; }, fromAttribute(value, type) { let fromValue = value; switch (type) { case Boolean: fromValue = value !== null; break; case Number: fromValue = value === null ? null : Number(value); break; case Object: case Array: try { fromValue = JSON.parse(value); } catch (e) { fromValue = null; } break; } return fromValue; } }; var notEqual = (value, old) => { return old !== value && (old === old || value === value); }; var defaultPropertyDeclaration = { attribute: true, type: String, converter: defaultConverter, reflect: false, hasChanged: notEqual }; var finalized = "finalized"; var ReactiveElement = class extends HTMLElement { constructor() { super(); this.__instanceProperties = /* @__PURE__ */ new Map(); this.isUpdatePending = false; this.hasUpdated = false; this.__reflectingProperty = null; this.__initialize(); } /** * Adds an initializer function to the class that is called during instance * construction. * * This is useful for code that runs against a `ReactiveElement` * subclass, such as a decorator, that needs to do work for each * instance, such as setting up a `ReactiveController`. * * ```ts * const myDecorator = (target: typeof ReactiveElement, key: string) => { * target.addInitializer((instance: ReactiveElement) => { * // This is run during construction of the element * new MyController(instance); * }); * } * ``` * * Decorating a field will then cause each instance to run an initializer * that adds a controller: * * ```ts * class MyElement extends LitElement { * @myDecorator foo; * } * ``` * * Initializers are stored per-constructor. Adding an initializer to a * subclass does not add it to a superclass. Since initializers are run in * constructors, initializers will run in order of the class hierarchy, * starting with superclasses and progressing to the instance's class. * * @nocollapse */ static addInitializer(initializer) { var _a5; this.finalize(); ((_a5 = this._initializers) !== null && _a5 !== void 0 ? _a5 : this._initializers = []).push(initializer); } /** * Returns a list of attributes corresponding to the registered properties. * @nocollapse * @category attributes */ static get observedAttributes() { this.finalize(); const attributes = []; this.elementProperties.forEach((v, p) => { const attr = this.__attributeNameForProperty(p, v); if (attr !== void 0) { this.__attributeToPropertyMap.set(attr, p); attributes.push(attr); } }); return attributes; } /** * Creates a property accessor on the element prototype if one does not exist * and stores a {@linkcode PropertyDeclaration} for the property with the * given options. The property setter calls the property's `hasChanged` * property option or uses a strict identity check to determine whether or not * to request an update. * * This method may be overridden to customize properties; however, * when doing so, it's important to call `super.createProperty` to ensure * the property is setup correctly. This method calls * `getPropertyDescriptor` internally to get a descriptor to install. * To customize what properties do when they are get or set, override * `getPropertyDescriptor`. To customize the options for a property, * implement `createProperty` like this: * * ```ts * static createProperty(name, options) { * options = Object.assign(options, {myOption: true}); * super.createProperty(name, options); * } * ``` * * @nocollapse * @category properties */ static createProperty(name, options = defaultPropertyDeclaration) { var _a5; if (options.state) { options.attribute = false; } this.finalize(); this.elementProperties.set(name, options); if (!options.noAccessor && !this.prototype.hasOwnProperty(name)) { const key = typeof name === "symbol" ? Symbol() : `__${name}`; const descriptor = this.getPropertyDescriptor(name, key, options); if (descriptor !== void 0) { Object.defineProperty(this.prototype, name, descriptor); if (DEV_MODE2) { if (!this.hasOwnProperty("__reactivePropertyKeys")) { this.__reactivePropertyKeys = new Set((_a5 = this.__reactivePropertyKeys) !== null && _a5 !== void 0 ? _a5 : []); } this.__reactivePropertyKeys.add(name); } } } } /** * Returns a property descriptor to be defined on the given named property. * If no descriptor is returned, the property will not become an accessor. * For example, * * ```ts * class MyElement extends LitElement { * static getPropertyDescriptor(name, key, options) { * const defaultDescriptor = * super.getPropertyDescriptor(name, key, options); * const setter = defaultDescriptor.set; * return { * get: defaultDescriptor.get, * set(value) { * setter.call(this, value); * // custom action. * }, * configurable: true, * enumerable: true * } * } * } * ``` * * @nocollapse * @category properties */ static getPropertyDescriptor(name, key, options) { return { // eslint-disable-next-line @typescript-eslint/no-explicit-any get() { return this[key]; }, set(value) { const oldValue = this[name]; this[key] = value; this.requestUpdate(name, oldValue, options); }, configurable: true, enumerable: true }; } /** * Returns the property options associated with the given property. * These options are defined with a `PropertyDeclaration` via the `properties` * object or the `@property` decorator and are registered in * `createProperty(...)`. * * Note, this method should be considered "final" and not overridden. To * customize the options for a given property, override * {@linkcode createProperty}. * * @nocollapse * @final * @category properties */ static getPropertyOptions(name) { return this.elementProperties.get(name) || defaultPropertyDeclaration; } /** * Creates property accessors for registered properties, sets up element * styling, and ensures any superclasses are also finalized. Returns true if * the element was finalized. * @nocollapse */ static finalize() { if (this.hasOwnProperty(finalized)) { return false; } this[finalized] = true; const superCtor = Object.getPrototypeOf(this); superCtor.finalize(); if (superCtor._initializers !== void 0) { this._initializers = [...superCtor._initializers]; } this.elementProperties = new Map(superCtor.elementProperties); this.__attributeToPropertyMap = /* @__PURE__ */ new Map(); if (this.hasOwnProperty(JSCompiler_renameProperty("properties", this))) { const props = this.properties; const propKeys = [ ...Object.getOwnPropertyNames(props), ...Object.getOwnPropertySymbols(props) ]; for (const p of propKeys) { this.createProperty(p, props[p]); } } this.elementStyles = this.finalizeStyles(this.styles); if (DEV_MODE2) { const warnRemovedOrRenamed = (name, renamed = false) => { if (this.prototype.hasOwnProperty(name)) { issueWarning2(renamed ? "renamed-api" : "removed-api", `\`${name}\` is implemented on class ${this.name}. It has been ${renamed ? "renamed" : "removed"} in this version of LitElement.`); } }; warnRemovedOrRenamed("initialize"); warnRemovedOrRenamed("requestUpdateInternal"); warnRemovedOrRenamed("_getUpdateComplete", true); } return true; } /** * Takes the styles the user supplied via the `static styles` property and * returns the array of styles to apply to the element. * Override this method to integrate into a style management system. * * Styles are deduplicated preserving the _last_ instance in the list. This * is a performance optimization to avoid duplicated styles that can occur * especially when composing via subclassing. The last item is kept to try * to preserve the cascade order with the assumption that it's most important * that last added styles override previous styles. * * @nocollapse * @category styles */ static finalizeStyles(styles) { const elementStyles = []; if (Array.isArray(styles)) { const set = new Set(styles.flat(Infinity).reverse()); for (const s of set) { elementStyles.unshift(getCompatibleStyle(s)); } } else if (styles !== void 0) { elementStyles.push(getCompatibleStyle(styles)); } return elementStyles; } /** * Returns the property name for the given attribute `name`. * @nocollapse */ static __attributeNameForProperty(name, options) { const attribute = options.attribute; return attribute === false ? void 0 : typeof attribute === "string" ? attribute : typeof name === "string" ? name.toLowerCase() : void 0; } /** * Internal only override point for customizing work done when elements * are constructed. */ __initialize() { var _a5; this.__updatePromise = new Promise((res) => this.enableUpdating = res); this._$changedProperties = /* @__PURE__ */ new Map(); this.__saveInstanceProperties(); this.requestUpdate(); (_a5 = this.constructor._initializers) === null || _a5 === void 0 ? void 0 : _a5.forEach((i) => i(this)); } /** * Registers a `ReactiveController` to participate in the element's reactive * update cycle. The element automatically calls into any registered * controllers during its lifecycle callbacks. * * If the element is connected when `addController()` is called, the * controller's `hostConnected()` callback will be immediately called. * @category controllers */ addController(controller) { var _a5, _b4; ((_a5 = this.__controllers) !== null && _a5 !== void 0 ? _a5 : this.__controllers = []).push(controller); if (this.renderRoot !== void 0 && this.isConnected) { (_b4 = controller.hostConnected) === null || _b4 === void 0 ? void 0 : _b4.call(controller); } } /** * Removes a `ReactiveController` from the element. * @category controllers */ removeController(controller) { var _a5; (_a5 = this.__controllers) === null || _a5 === void 0 ? void 0 : _a5.splice(this.__controllers.indexOf(controller) >>> 0, 1); } /** * Fixes any properties set on the instance before upgrade time. * Otherwise these would shadow the accessor and break these properties. * The properties are stored in a Map which is played back after the * constructor runs. Note, on very old versions of Safari (<=9) or Chrome * (<=41), properties created for native platform properties like (`id` or * `name`) may not have default values set in the element constructor. On * these browsers native properties appear on instances and therefore their * default value will overwrite any element default (e.g. if the element sets * this.id = 'id' in the constructor, the 'id' will become '' since this is * the native platform default). */ __saveInstanceProperties() { this.constructor.elementProperties.forEach((_v, p) => { if (this.hasOwnProperty(p)) { this.__instanceProperties.set(p, this[p]); delete this[p]; } }); } /** * Returns the node into which the element should render and by default * creates and returns an open shadowRoot. Implement to customize where the * element's DOM is rendered. For example, to render into the element's * childNodes, return `this`. * * @return Returns a node into which to render. * @category rendering */ createRenderRoot() { var _a5; const renderRoot = (_a5 = this.shadowRoot) !== null && _a5 !== void 0 ? _a5 : this.attachShadow(this.constructor.shadowRootOptions); adoptStyles(renderRoot, this.constructor.elementStyles); return renderRoot; } /** * On first connection, creates the element's renderRoot, sets up * element styling, and enables updating. * @category lifecycle */ connectedCallback() { var _a5; if (this.renderRoot === void 0) { this.renderRoot = this.createRenderRoot(); } this.enableUpdating(true); (_a5 = this.__controllers) === null || _a5 === void 0 ? void 0 : _a5.forEach((c) => { var _a6; return (_a6 = c.hostConnected) === null || _a6 === void 0 ? void 0 : _a6.call(c); }); } /** * Note, this method should be considered final and not overridden. It is * overridden on the element instance with a function that triggers the first * update. * @category updates */ enableUpdating(_requestedUpdate) { } /** * Allows for `super.disconnectedCallback()` in extensions while * reserving the possibility of making non-breaking feature additions * when disconnecting at some point in the future. * @category lifecycle */ disconnectedCallback() { var _a5; (_a5 = this.__controllers) === null || _a5 === void 0 ? void 0 : _a5.forEach((c) => { var _a6; return (_a6 = c.hostDisconnected) === null || _a6 === void 0 ? void 0 : _a6.call(c); }); } /** * Synchronizes property values when attributes change. * * Specifically, when an attribute is set, the corresponding property is set. * You should rarely need to implement this callback. If this method is * overridden, `super.attributeChangedCallback(name, _old, value)` must be * called. * * See [using the lifecycle callbacks](https://developer.mozilla.org/en-US/docs/Web/Web_Components/Using_custom_elements#using_the_lifecycle_callbacks) * on MDN for more information about the `attributeChangedCallback`. * @category attributes */ attributeChangedCallback(name, _old, value) { this._$attributeToProperty(name, value); } __propertyToAttribute(name, value, options = defaultPropertyDeclaration) { var _a5; const attr = this.constructor.__attributeNameForProperty(name, options); if (attr !== void 0 && options.reflect === true) { const converter = ((_a5 = options.converter) === null || _a5 === void 0 ? void 0 : _a5.toAttribute) !== void 0 ? options.converter : defaultConverter; const attrValue = converter.toAttribute(value, options.type); if (DEV_MODE2 && this.constructor.enabledWarnings.indexOf("migration") >= 0 && attrValue === void 0) { issueWarning2("undefined-attribute-value", `The attribute value for the ${name} property is undefined on element ${this.localName}. The attribute will be removed, but in the previous version of \`ReactiveElement\`, the attribute would not have changed.`); } this.__reflectingProperty = name; if (attrValue == null) { this.removeAttribute(attr); } else { this.setAttribute(attr, attrValue); } this.__reflectingProperty = null; } } /** @internal */ _$attributeToProperty(name, value) { var _a5; const ctor = this.constructor; const propName = ctor.__attributeToPropertyMap.get(name); if (propName !== void 0 && this.__reflectingProperty !== propName) { const options = ctor.getPropertyOptions(propName); const converter = typeof options.converter === "function" ? { fromAttribute: options.converter } : ((_a5 = options.converter) === null || _a5 === void 0 ? void 0 : _a5.fromAttribute) !== void 0 ? options.converter : defaultConverter; this.__reflectingProperty = propName; this[propName] = converter.fromAttribute( value, options.type // eslint-disable-next-line @typescript-eslint/no-explicit-any ); this.__reflectingProperty = null; } } /** * Requests an update which is processed asynchronously. This should be called * when an element should update based on some state not triggered by setting * a reactive property. In this case, pass no arguments. It should also be * called when manually implementing a property setter. In this case, pass the * property `name` and `oldValue` to ensure that any configured property * options are honored. * * @param name name of requesting property * @param oldValue old value of requesting property * @param options property options to use instead of the previously * configured options * @category updates */ requestUpdate(name, oldValue, options) { let shouldRequestUpdate = true; if (name !== void 0) { options = options || this.constructor.getPropertyOptions(name); const hasChanged = options.hasChanged || notEqual; if (hasChanged(this[name], oldValue)) { if (!this._$changedProperties.has(name)) { this._$changedProperties.set(name, oldValue); } if (options.reflect === true && this.__reflectingProperty !== name) { if (this.__reflectingProperties === void 0) { this.__reflectingProperties = /* @__PURE__ */ new Map(); } this.__reflectingProperties.set(name, options); } } else { shouldRequestUpdate = false; } } if (!this.isUpdatePending && shouldRequestUpdate) { this.__updatePromise = this.__enqueueUpdate(); } return DEV_MODE2 ? requestUpdateThenable(this.localName) : void 0; } /** * Sets up the element to asynchronously update. */ async __enqueueUpdate() { this.isUpdatePending = true; try { await this.__updatePromise; } catch (e) { Promise.reject(e); } const result = this.scheduleUpdate(); if (result != null) { await result; } return !this.isUpdatePending; } /** * Schedules an element update. You can override this method to change the * timing of updates by returning a Promise. The update will await the * returned Promise, and you should resolve the Promise to allow the update * to proceed. If this method is overridden, `super.scheduleUpdate()` * must be called. * * For instance, to schedule updates to occur just before the next frame: * * ```ts * override protected async scheduleUpdate(): Promise { * await new Promise((resolve) => requestAnimationFrame(() => resolve())); * super.scheduleUpdate(); * } * ``` * @category updates */ scheduleUpdate() { return this.performUpdate(); } /** * Performs an element update. Note, if an exception is thrown during the * update, `firstUpdated` and `updated` will not be called. * * Call `performUpdate()` to immediately process a pending update. This should * generally not be needed, but it can be done in rare cases when you need to * update synchronously. * * Note: To ensure `performUpdate()` synchronously completes a pending update, * it should not be overridden. In LitElement 2.x it was suggested to override * `performUpdate()` to also customizing update scheduling. Instead, you should now * override `scheduleUpdate()`. For backwards compatibility with LitElement 2.x, * scheduling updates via `performUpdate()` continues to work, but will make * also calling `performUpdate()` to synchronously process updates difficult. * * @category updates */ performUpdate() { var _a5, _b4; if (!this.isUpdatePending) { return; } debugLogEvent2 === null || debugLogEvent2 === void 0 ? void 0 : debugLogEvent2({ kind: "update" }); if (!this.hasUpdated) { if (DEV_MODE2) { const shadowedProperties = []; (_a5 = this.constructor.__reactivePropertyKeys) === null || _a5 === void 0 ? void 0 : _a5.forEach((p) => { var _a6; if (this.hasOwnProperty(p) && !((_a6 = this.__instanceProperties) === null || _a6 === void 0 ? void 0 : _a6.has(p))) { shadowedProperties.push(p); } }); if (shadowedProperties.length) { throw new Error(`The following properties on element ${this.localName} will not trigger updates as expected because they are set using class fields: ${shadowedProperties.join(", ")}. Native class fields and some compiled output will overwrite accessors used for detecting changes. See https://lit.dev/msg/class-field-shadowing for more information.`); } } } if (this.__instanceProperties) { this.__instanceProperties.forEach((v, p) => this[p] = v); this.__instanceProperties = void 0; } let shouldUpdate = false; const changedProperties = this._$changedProperties; try { shouldUpdate = this.shouldUpdate(changedProperties); if (shouldUpdate) { this.willUpdate(changedProperties); (_b4 = this.__controllers) === null || _b4 === void 0 ? void 0 : _b4.forEach((c) => { var _a6; return (_a6 = c.hostUpdate) === null || _a6 === void 0 ? void 0 : _a6.call(c); }); this.update(changedProperties); } else { this.__markUpdated(); } } catch (e) { shouldUpdate = false; this.__markUpdated(); throw e; } if (shouldUpdate) { this._$didUpdate(changedProperties); } } /** * Invoked before `update()` to compute values needed during the update. * * Implement `willUpdate` to compute property values that depend on other * properties and are used in the rest of the update process. * * ```ts * willUpdate(changedProperties) { * // only need to check changed properties for an expensive computation. * if (changedProperties.has('firstName') || changedProperties.has('lastName')) { * this.sha = computeSHA(`${this.firstName} ${this.lastName}`); * } * } * * render() { * return html`SHA: ${this.sha}`; * } * ``` * * @category updates */ willUpdate(_changedProperties) { } // Note, this is an override point for polyfill-support. // @internal _$didUpdate(changedProperties) { var _a5; (_a5 = this.__controllers) === null || _a5 === void 0 ? void 0 : _a5.forEach((c) => { var _a6; return (_a6 = c.hostUpdated) === null || _a6 === void 0 ? void 0 : _a6.call(c); }); if (!this.hasUpdated) { this.hasUpdated = true; this.firstUpdated(changedProperties); } this.updated(changedProperties); if (DEV_MODE2 && this.isUpdatePending && this.constructor.enabledWarnings.indexOf("change-in-update") >= 0) { issueWarning2("change-in-update", `Element ${this.localName} scheduled an update (generally because a property was set) after an update completed, causing a new update to be scheduled. This is inefficient and should be avoided unless the next update can only be scheduled as a side effect of the previous update.`); } } __markUpdated() { this._$changedProperties = /* @__PURE__ */ new Map(); this.isUpdatePending = false; } /** * Returns a Promise that resolves when the element has completed updating. * The Promise value is a boolean that is `true` if the element completed the * update without triggering another update. The Promise result is `false` if * a property was set inside `updated()`. If the Promise is rejected, an * exception was thrown during the update. * * To await additional asynchronous work, override the `getUpdateComplete` * method. For example, it is sometimes useful to await a rendered element * before fulfilling this Promise. To do this, first await * `super.getUpdateComplete()`, then any subsequent state. * * @return A promise of a boolean that resolves to true if the update completed * without triggering another update. * @category updates */ get updateComplete() { return this.getUpdateComplete(); } /** * Override point for the `updateComplete` promise. * * It is not safe to override the `updateComplete` getter directly due to a * limitation in TypeScript which means it is not possible to call a * superclass getter (e.g. `super.updateComplete.then(...)`) when the target * language is ES5 (https://github.com/microsoft/TypeScript/issues/338). * This method should be overridden instead. For example: * * ```ts * class MyElement extends LitElement { * override async getUpdateComplete() { * const result = await super.getUpdateComplete(); * await this._myChild.updateComplete; * return result; * } * } * ``` * * @return A promise of a boolean that resolves to true if the update completed * without triggering another update. * @category updates */ getUpdateComplete() { return this.__updatePromise; } /** * Controls whether or not `update()` should be called when the element requests * an update. By default, this method always returns `true`, but this can be * customized to control when to update. * * @param _changedProperties Map of changed properties with old values * @category updates */ shouldUpdate(_changedProperties) { return true; } /** * Updates the element. This method reflects property values to attributes. * It can be overridden to render and keep updated element DOM. * Setting properties inside this method will *not* trigger * another update. * * @param _changedProperties Map of changed properties with old values * @category updates */ update(_changedProperties) { if (this.__reflectingProperties !== void 0) { this.__reflectingProperties.forEach((v, k) => this.__propertyToAttribute(k, this[k], v)); this.__reflectingProperties = void 0; } this.__markUpdated(); } /** * Invoked whenever the element is updated. Implement to perform * post-updating tasks via DOM APIs, for example, focusing an element. * * Setting properties inside this method will trigger the element to update * again after this update cycle completes. * * @param _changedProperties Map of changed properties with old values * @category updates */ updated(_changedProperties) { } /** * Invoked when the element is first updated. Implement to perform one time * work on the element after update. * * ```ts * firstUpdated() { * this.renderRoot.getElementById('my-text-area').focus(); * } * ``` * * Setting properties inside this method will trigger the element to update * again after this update cycle completes. * * @param _changedProperties Map of changed properties with old values * @category updates */ firstUpdated(_changedProperties) { } }; _e = finalized; ReactiveElement[_e] = true; ReactiveElement.elementProperties = /* @__PURE__ */ new Map(); ReactiveElement.elementStyles = []; ReactiveElement.shadowRootOptions = { mode: "open" }; polyfillSupport2 === null || polyfillSupport2 === void 0 ? void 0 : polyfillSupport2({ ReactiveElement }); if (DEV_MODE2) { ReactiveElement.enabledWarnings = ["change-in-update"]; const ensureOwnWarnings = function(ctor) { if (!ctor.hasOwnProperty(JSCompiler_renameProperty("enabledWarnings", ctor))) { ctor.enabledWarnings = ctor.enabledWarnings.slice(); } }; ReactiveElement.enableWarning = function(warning) { ensureOwnWarnings(this); if (this.enabledWarnings.indexOf(warning) < 0) { this.enabledWarnings.push(warning); } }; ReactiveElement.disableWarning = function(warning) { ensureOwnWarnings(this); const i = this.enabledWarnings.indexOf(warning); if (i >= 0) { this.enabledWarnings.splice(i, 1); } }; } ((_d2 = global3.reactiveElementVersions) !== null && _d2 !== void 0 ? _d2 : global3.reactiveElementVersions = []).push("1.6.3"); if (DEV_MODE2 && global3.reactiveElementVersions.length > 1) { issueWarning2("multiple-versions", `Multiple versions of Lit loaded. Loading multiple versions is not recommended.`); } // node_modules/lit-element/development/lit-element.js var _a3; var _b3; var _c3; var DEV_MODE3 = true; var issueWarning3; if (DEV_MODE3) { const issuedWarnings = (_a3 = globalThis.litIssuedWarnings) !== null && _a3 !== void 0 ? _a3 : globalThis.litIssuedWarnings = /* @__PURE__ */ new Set(); issueWarning3 = (code, warning) => { warning += ` See https://lit.dev/msg/${code} for more information.`; if (!issuedWarnings.has(warning)) { console.warn(warning); issuedWarnings.add(warning); } }; } var LitElement = class extends ReactiveElement { constructor() { super(...arguments); this.renderOptions = { host: this }; this.__childPart = void 0; } /** * @category rendering */ createRenderRoot() { var _a5; var _b4; const renderRoot = super.createRenderRoot(); (_a5 = (_b4 = this.renderOptions).renderBefore) !== null && _a5 !== void 0 ? _a5 : _b4.renderBefore = renderRoot.firstChild; return renderRoot; } /** * Updates the element. This method reflects property values to attributes * and calls `render` to render DOM via lit-html. Setting properties inside * this method will *not* trigger another update. * @param changedProperties Map of changed properties with old values * @category updates */ update(changedProperties) { const value = this.render(); if (!this.hasUpdated) { this.renderOptions.isConnected = this.isConnected; } super.update(changedProperties); this.__childPart = render(value, this.renderRoot, this.renderOptions); } /** * Invoked when the component is added to the document's DOM. * * In `connectedCallback()` you should setup tasks that should only occur when * the element is connected to the document. The most common of these is * adding event listeners to nodes external to the element, like a keydown * event handler added to the window. * * ```ts * connectedCallback() { * super.connectedCallback(); * addEventListener('keydown', this._handleKeydown); * } * ``` * * Typically, anything done in `connectedCallback()` should be undone when the * element is disconnected, in `disconnectedCallback()`. * * @category lifecycle */ connectedCallback() { var _a5; super.connectedCallback(); (_a5 = this.__childPart) === null || _a5 === void 0 ? void 0 : _a5.setConnected(true); } /** * Invoked when the component is removed from the document's DOM. * * This callback is the main signal to the element that it may no longer be * used. `disconnectedCallback()` should ensure that nothing is holding a * reference to the element (such as event listeners added to nodes external * to the element), so that it is free to be garbage collected. * * ```ts * disconnectedCallback() { * super.disconnectedCallback(); * window.removeEventListener('keydown', this._handleKeydown); * } * ``` * * An element may be re-connected after being disconnected. * * @category lifecycle */ disconnectedCallback() { var _a5; super.disconnectedCallback(); (_a5 = this.__childPart) === null || _a5 === void 0 ? void 0 : _a5.setConnected(false); } /** * Invoked on each update to perform rendering tasks. This method may return * any value renderable by lit-html's `ChildPart` - typically a * `TemplateResult`. Setting properties inside this method will *not* trigger * the element to update. * @category rendering */ render() { return noChange; } }; LitElement["finalized"] = true; LitElement["_$litElement$"] = true; (_b3 = globalThis.litElementHydrateSupport) === null || _b3 === void 0 ? void 0 : _b3.call(globalThis, { LitElement }); var polyfillSupport3 = DEV_MODE3 ? globalThis.litElementPolyfillSupportDevMode : globalThis.litElementPolyfillSupport; polyfillSupport3 === null || polyfillSupport3 === void 0 ? void 0 : polyfillSupport3({ LitElement }); if (DEV_MODE3) { LitElement["finalize"] = function() { const finalized2 = ReactiveElement.finalize.call(this); if (!finalized2) { return false; } const warnRemovedOrRenamed = (obj, name, renamed = false) => { if (obj.hasOwnProperty(name)) { const ctorName = (typeof obj === "function" ? obj : obj.constructor).name; issueWarning3(renamed ? "renamed-api" : "removed-api", `\`${name}\` is implemented on class ${ctorName}. It has been ${renamed ? "renamed" : "removed"} in this version of LitElement.`); } }; warnRemovedOrRenamed(this, "render"); warnRemovedOrRenamed(this, "getStyles", true); warnRemovedOrRenamed(this.prototype, "adoptStyles"); return true; }; } ((_c3 = globalThis.litElementVersions) !== null && _c3 !== void 0 ? _c3 : globalThis.litElementVersions = []).push("3.3.3"); if (DEV_MODE3 && globalThis.litElementVersions.length > 1) { issueWarning3("multiple-versions", `Multiple versions of Lit loaded. Loading multiple versions is not recommended.`); } // node_modules/@lit/reactive-element/development/decorators/custom-element.js var legacyCustomElement = (tagName, clazz) => { customElements.define(tagName, clazz); return clazz; }; var standardCustomElement = (tagName, descriptor) => { const { kind, elements } = descriptor; return { kind, elements, // This callback is called once the class is otherwise fully defined finisher(clazz) { customElements.define(tagName, clazz); } }; }; var customElement = (tagName) => (classOrDescriptor) => typeof classOrDescriptor === "function" ? legacyCustomElement(tagName, classOrDescriptor) : standardCustomElement(tagName, classOrDescriptor); // node_modules/@lit/reactive-element/development/decorators/property.js var standardProperty = (options, element) => { if (element.kind === "method" && element.descriptor && !("value" in element.descriptor)) { return { ...element, finisher(clazz) { clazz.createProperty(element.key, options); } }; } else { return { kind: "field", key: Symbol(), placement: "own", descriptor: {}, // store the original key so subsequent decorators have access to it. originalKey: element.key, // When @babel/plugin-proposal-decorators implements initializers, // do this instead of the initializer below. See: // https://github.com/babel/babel/issues/9260 extras: [ // { // kind: 'initializer', // placement: 'own', // initializer: descriptor.initializer, // } // ], initializer() { if (typeof element.initializer === "function") { this[element.key] = element.initializer.call(this); } }, finisher(clazz) { clazz.createProperty(element.key, options); } }; } }; var legacyProperty = (options, proto, name) => { proto.constructor.createProperty(name, options); }; function property(options) { return (protoOrDescriptor, name) => name !== void 0 ? legacyProperty(options, protoOrDescriptor, name) : standardProperty(options, protoOrDescriptor); } // node_modules/@lit/reactive-element/development/decorators/state.js function state(options) { return property({ ...options, state: true }); } // node_modules/@lit/reactive-element/development/decorators/query-assigned-elements.js var _a4; var NODE_MODE4 = false; var global4 = NODE_MODE4 ? globalThis : window; var slotAssignedElements = ((_a4 = global4.HTMLSlotElement) === null || _a4 === void 0 ? void 0 : _a4.prototype.assignedElements) != null ? (slot, opts) => slot.assignedElements(opts) : (slot, opts) => slot.assignedNodes(opts).filter((node) => node.nodeType === Node.ELEMENT_NODE); export { css, ReactiveElement, html, svg, noChange, nothing, render, LitElement, customElement, property, state }; /*! Bundled license information: @lit/reactive-element/development/css-tag.js: (** * @license * Copyright 2019 Google LLC * SPDX-License-Identifier: BSD-3-Clause *) lit-html/development/lit-html.js: (** * @license * Copyright 2017 Google LLC * SPDX-License-Identifier: BSD-3-Clause *) @lit/reactive-element/development/reactive-element.js: (** * @license * Copyright 2017 Google LLC * SPDX-License-Identifier: BSD-3-Clause *) lit-element/development/lit-element.js: (** * @license * Copyright 2017 Google LLC * SPDX-License-Identifier: BSD-3-Clause *) lit-html/development/is-server.js: (** * @license * Copyright 2022 Google LLC * SPDX-License-Identifier: BSD-3-Clause *) @lit/reactive-element/development/decorators/custom-element.js: (** * @license * Copyright 2017 Google LLC * SPDX-License-Identifier: BSD-3-Clause *) @lit/reactive-element/development/decorators/property.js: (** * @license * Copyright 2017 Google LLC * SPDX-License-Identifier: BSD-3-Clause *) @lit/reactive-element/development/decorators/state.js: (** * @license * Copyright 2017 Google LLC * SPDX-License-Identifier: BSD-3-Clause *) @lit/reactive-element/development/decorators/base.js: (** * @license * Copyright 2017 Google LLC * SPDX-License-Identifier: BSD-3-Clause *) @lit/reactive-element/development/decorators/event-options.js: (** * @license * Copyright 2017 Google LLC * SPDX-License-Identifier: BSD-3-Clause *) @lit/reactive-element/development/decorators/query.js: (** * @license * Copyright 2017 Google LLC * SPDX-License-Identifier: BSD-3-Clause *) @lit/reactive-element/development/decorators/query-all.js: (** * @license * Copyright 2017 Google LLC * SPDX-License-Identifier: BSD-3-Clause *) @lit/reactive-element/development/decorators/query-async.js: (** * @license * Copyright 2017 Google LLC * SPDX-License-Identifier: BSD-3-Clause *) @lit/reactive-element/development/decorators/query-assigned-elements.js: (** * @license * Copyright 2021 Google LLC * SPDX-License-Identifier: BSD-3-Clause *) @lit/reactive-element/development/decorators/query-assigned-nodes.js: (** * @license * Copyright 2017 Google LLC * SPDX-License-Identifier: BSD-3-Clause *) */ //# sourceMappingURL=chunk-6LAJV43E.js.map ================================================ FILE: 17-Crowd-Funding-Dapp/Frontend/.vite/deps_temp_6cf5ba4c/chunk-6RU56BH7.js ================================================ import { readContract } from "./chunk-AG4NO6K6.js"; import { withCache } from "./chunk-GOA7IGSB.js"; // node_modules/thirdweb/dist/esm/extensions/common/__generated__/IContractMetadata/read/name.js var FN_SELECTOR = "0x06fdde03"; var FN_INPUTS = []; var FN_OUTPUTS = [ { type: "string" } ]; async function name(options) { return readContract({ contract: options.contract, method: [FN_SELECTOR, FN_INPUTS, FN_OUTPUTS], params: [] }); } // node_modules/thirdweb/dist/esm/extensions/common/read/name.js async function name2(options) { return withCache(() => name(options), { cacheKey: `${options.contract.chain.id}:${options.contract.address}:name`, // can never change, so cache forever cacheTime: Number.POSITIVE_INFINITY }); } // node_modules/thirdweb/dist/esm/extensions/common/__generated__/IContractMetadata/read/symbol.js var FN_SELECTOR2 = "0x95d89b41"; var FN_INPUTS2 = []; var FN_OUTPUTS2 = [ { type: "string" } ]; async function symbol(options) { return readContract({ contract: options.contract, method: [FN_SELECTOR2, FN_INPUTS2, FN_OUTPUTS2], params: [] }); } // node_modules/thirdweb/dist/esm/extensions/common/read/symbol.js async function symbol2(options) { return withCache(() => symbol(options), { cacheKey: `${options.contract.chain.id}:${options.contract.address}:symbol`, // can never change, so cache forever cacheTime: Number.POSITIVE_INFINITY }); } export { name2 as name, symbol2 as symbol }; //# sourceMappingURL=chunk-6RU56BH7.js.map ================================================ FILE: 17-Crowd-Funding-Dapp/Frontend/.vite/deps_temp_6cf5ba4c/chunk-6WNCTW75.js ================================================ import { getEcosystemInfo } from "./chunk-QLJVAXYD.js"; import { createWalletEmitter, trackConnect } from "./chunk-CLN3QXW2.js"; import { stringify } from "./chunk-NJUWOGZE.js"; import { getCachedChainIfExists } from "./chunk-TFBEDS4S.js"; // node_modules/thirdweb/dist/esm/wallets/in-app/core/wallet/in-app-core.js var connectorCache = /* @__PURE__ */ new Map(); async function getOrCreateInAppWalletConnector(client, connectorFactory, ecosystem) { const key = stringify({ clientId: client.clientId, ecosystem }); if (connectorCache.has(key)) { return connectorCache.get(key); } const connector = await connectorFactory(client); connectorCache.set(key, connector); return connector; } function createInAppWallet(args) { const { createOptions: _createOptions, connectorFactory, ecosystem } = args; const walletId = ecosystem ? ecosystem.id : "inApp"; const emitter = createWalletEmitter(); let createOptions = _createOptions; let account = void 0; let chain = void 0; let client; return { id: walletId, subscribe: emitter.subscribe, getChain() { if (!chain) { return void 0; } chain = getCachedChainIfExists(chain.id) || chain; return chain; }, getConfig: () => createOptions, getAccount: () => account, autoConnect: async (options) => { const { autoConnectInAppWallet } = await import("./wallet-ZUZOMGPE.js"); const connector = await getOrCreateInAppWalletConnector(options.client, connectorFactory, ecosystem); if (ecosystem) { const ecosystemOptions = await getEcosystemInfo(ecosystem.id); const smartAccountOptions = ecosystemOptions == null ? void 0 : ecosystemOptions.smartAccountOptions; if (smartAccountOptions) { const preferredChain = options.chain; if (!preferredChain) { throw new Error("Chain is required for ecosystem smart accounts, pass it via connect() or via UI components"); } createOptions = { ...createOptions, smartAccount: { chain: preferredChain, sponsorGas: smartAccountOptions.sponsorGas, factoryAddress: smartAccountOptions.accountFactoryAddress } }; } } const [connectedAccount, connectedChain] = await autoConnectInAppWallet(options, createOptions, connector); client = options.client; account = connectedAccount; chain = connectedChain; trackConnect({ client: options.client, ecosystem, walletType: walletId, walletAddress: account.address, chainId: chain.id }); return account; }, connect: async (options) => { const { connectInAppWallet } = await import("./wallet-ZUZOMGPE.js"); const connector = await getOrCreateInAppWalletConnector(options.client, connectorFactory, ecosystem); if (ecosystem) { const ecosystemOptions = await getEcosystemInfo(ecosystem.id); const smartAccountOptions = ecosystemOptions == null ? void 0 : ecosystemOptions.smartAccountOptions; if (smartAccountOptions) { const preferredChain = options.chain; if (!preferredChain) { throw new Error("Chain is required for ecosystem smart accounts, pass it via connect() or via UI components"); } createOptions = { ...createOptions, smartAccount: { chain: preferredChain, sponsorGas: smartAccountOptions.sponsorGas, factoryAddress: smartAccountOptions.accountFactoryAddress } }; } } const [connectedAccount, connectedChain] = await connectInAppWallet(options, createOptions, connector); client = options.client; account = connectedAccount; chain = connectedChain; trackConnect({ client: options.client, ecosystem, walletType: walletId, walletAddress: account.address, chainId: chain.id }); return account; }, disconnect: async () => { if (client) { const connector = await getOrCreateInAppWalletConnector(client, connectorFactory, ecosystem); const result = await connector.logout(); if (!result.success) { throw new Error("Failed to logout"); } } account = void 0; chain = void 0; emitter.emit("disconnect", void 0); }, switchChain: async (newChain) => { if ((createOptions == null ? void 0 : createOptions.smartAccount) && client && account) { const { autoConnectInAppWallet } = await import("./wallet-ZUZOMGPE.js"); const connector = await getOrCreateInAppWalletConnector(client, connectorFactory, ecosystem); if (ecosystem) { const ecosystemOptions = await getEcosystemInfo(ecosystem.id); const smartAccountOptions = ecosystemOptions == null ? void 0 : ecosystemOptions.smartAccountOptions; if (smartAccountOptions) { createOptions = { ...createOptions, smartAccount: { chain: newChain, sponsorGas: smartAccountOptions.sponsorGas, factoryAddress: smartAccountOptions.accountFactoryAddress } }; } } const [connectedAccount, connectedChain] = await autoConnectInAppWallet({ chain: newChain, client }, createOptions, connector); account = connectedAccount; chain = connectedChain; } else { chain = newChain; } emitter.emit("chainChanged", newChain); } }; } export { getOrCreateInAppWalletConnector, createInAppWallet }; //# sourceMappingURL=chunk-6WNCTW75.js.map ================================================ FILE: 17-Crowd-Funding-Dapp/Frontend/.vite/deps_temp_6cf5ba4c/chunk-6XF6HOWC.js ================================================ import { resolvePromisedValue } from "./chunk-QC3K2OKT.js"; import { prepareTransaction } from "./chunk-CNLOA7AS.js"; import { isAbiFunction, prepareMethod } from "./chunk-NPJBMLFY.js"; import { encodeAbiParameters } from "./chunk-U7TO6S3N.js"; import { parseAbiItem } from "./chunk-GINVHONX.js"; // node_modules/thirdweb/dist/esm/transaction/prepare-contract-call.js function prepareContractCall(options) { const { contract, method, params, ...rest } = options; const preparedMethodPromise = () => (async () => { var _a, _b; if (Array.isArray(method)) { return method; } if (isAbiFunction(method)) { return prepareMethod(method); } if (typeof method === "function") { return prepareMethod( // @ts-expect-error - method *is* function in this case await method(contract) ); } if (typeof method === "string" && method.startsWith("function ")) { const abiItem = parseAbiItem(method); if (abiItem.type === "function") { return prepareMethod(abiItem); } throw new Error(`"method" passed is not of type "function"`); } if (contract.abi && ((_a = contract.abi) == null ? void 0 : _a.length) > 0) { const abiFunction = (_b = contract.abi) == null ? void 0 : _b.find((item) => item.type === "function" && item.name === method); if (abiFunction) { return prepareMethod(abiFunction); } } throw new Error(`Could not resolve method "${method}".`); })(); return prepareTransaction({ ...rest, // these always inferred from the contract to: contract.address, chain: contract.chain, client: contract.client, data: async () => { let preparedM; if (Array.isArray(method)) { preparedM = method; } else { preparedM = await preparedMethodPromise(); } if (preparedM[1].length === 0) { return preparedM[0]; } return preparedM[0] + encodeAbiParameters( preparedM[1], // @ts-expect-error - TODO: fix this type issue await resolvePromisedValue(params ?? []) ).slice(2); } }, { preparedMethod: preparedMethodPromise, contract }); } // node_modules/thirdweb/dist/esm/utils/promise/once.js function once(fn) { let result; return () => { if (!result) { result = fn(); } return result; }; } export { prepareContractCall, once }; //# sourceMappingURL=chunk-6XF6HOWC.js.map ================================================ FILE: 17-Crowd-Funding-Dapp/Frontend/.vite/deps_temp_6cf5ba4c/chunk-7AY3QZZV.js ================================================ import { hexToNumber, isHex } from "./chunk-BBNNHC5G.js"; // node_modules/thirdweb/dist/esm/wallets/utils/chains.js function getValidPublicRPCUrl(chain) { return getValidChainRPCs(chain).map((rpc) => { try { const url = new URL(rpc); if (url.hostname.endsWith(".thirdweb.com")) { url.pathname = ""; url.search = ""; } return url.toString(); } catch { return rpc; } }); } function getValidChainRPCs(chain, clientId, mode = "http") { const processedRPCs = []; for (const rpc of chain.rpc) { if (mode === "http" && !rpc.startsWith("http")) { continue; } if (mode === "ws" && !rpc.startsWith("ws")) { continue; } if (rpc.includes("${THIRDWEB_API_KEY}")) { if (clientId) { processedRPCs.push(rpc.replace("${THIRDWEB_API_KEY}", clientId) + (typeof globalThis !== "undefined" && "APP_BUNDLE_ID" in globalThis ? ( // @ts-expect-error `/?bundleId=${globalThis.APP_BUNDLE_ID}` ) : "")); } else { processedRPCs.push(rpc.replace("${THIRDWEB_API_KEY}", "")); } } else if (rpc.includes("${")) { } else { processedRPCs.push(rpc); } } if (processedRPCs.length === 0) { throw new Error(`No RPC available for chainId "${chain.chainId}" with mode ${mode}`); } return processedRPCs; } // node_modules/thirdweb/dist/esm/wallets/utils/normalizeChainId.js function normalizeChainId(chainId) { if (typeof chainId === "number") { return chainId; } if (isHex(chainId)) { return hexToNumber(chainId); } if (typeof chainId === "bigint") { return Number(chainId); } return Number.parseInt(chainId, 10); } export { getValidPublicRPCUrl, normalizeChainId }; //# sourceMappingURL=chunk-7AY3QZZV.js.map ================================================ FILE: 17-Crowd-Funding-Dapp/Frontend/.vite/deps_temp_6cf5ba4c/chunk-7ETS5GH6.js ================================================ import { fetchTokenMetadata } from "./chunk-4U2YWK76.js"; import { parseNFT } from "./chunk-NOA36MVL.js"; import { detectMethod } from "./chunk-PK5NRJAC.js"; import { readContract } from "./chunk-AG4NO6K6.js"; // node_modules/thirdweb/dist/esm/extensions/erc1155/__generated__/IERC1155/read/totalSupply.js var FN_SELECTOR = "0xbd85b039"; var FN_INPUTS = [ { type: "uint256", name: "id" } ]; var FN_OUTPUTS = [ { type: "uint256" } ]; async function totalSupply(options) { return readContract({ contract: options.contract, method: [FN_SELECTOR, FN_INPUTS, FN_OUTPUTS], params: [options.id] }); } // node_modules/thirdweb/dist/esm/extensions/erc1155/__generated__/IERC1155/read/uri.js var FN_SELECTOR2 = "0x0e89341c"; var FN_INPUTS2 = [ { type: "uint256", name: "tokenId" } ]; var FN_OUTPUTS2 = [ { type: "string" } ]; function isUriSupported(availableSelectors) { return detectMethod({ availableSelectors, method: [FN_SELECTOR2, FN_INPUTS2, FN_OUTPUTS2] }); } async function uri(options) { return readContract({ contract: options.contract, method: [FN_SELECTOR2, FN_INPUTS2, FN_OUTPUTS2], params: [options.tokenId] }); } // node_modules/thirdweb/dist/esm/extensions/erc1155/read/getNFT.js async function getNFT(options) { const [tokenUri, supply] = await Promise.all([ uri({ contract: options.contract, tokenId: options.tokenId }), totalSupply({ contract: options.contract, id: options.tokenId // in cases where the supply is not available -> fall back to 0 }).catch(() => 0n) ]); return parseNFT(await fetchTokenMetadata({ client: options.contract.client, tokenId: options.tokenId, tokenUri }).catch(() => ({ id: options.tokenId, type: "ERC1155", uri: tokenUri })), { tokenId: options.tokenId, tokenUri, type: "ERC1155", owner: null, supply }); } export { isUriSupported, getNFT }; //# sourceMappingURL=chunk-7ETS5GH6.js.map ================================================ FILE: 17-Crowd-Funding-Dapp/Frontend/.vite/deps_temp_6cf5ba4c/chunk-7EY5MWB2.js ================================================ import { sha256 } from "./chunk-O6UZ65WN.js"; import { Hash, bytes, concatBytes as concatBytes2, exists, hash, randomBytes, toBytes } from "./chunk-ME5GAE4N.js"; import { aInRange, abool, abytes, bitLen, bitMask, bytesToHex, bytesToNumberBE, bytesToNumberLE, concatBytes, createHmacDrbg, ensureBytes, hexToBytes, inRange, isBytes, memoized, numberToBytesBE, numberToBytesLE, numberToHexUnpadded, utf8ToBytes, utils_exports, validateObject } from "./chunk-SPELR2RL.js"; // node_modules/@noble/hashes/esm/hmac.js var HMAC = class extends Hash { constructor(hash2, _key) { super(); this.finished = false; this.destroyed = false; hash(hash2); const key = toBytes(_key); this.iHash = hash2.create(); if (typeof this.iHash.update !== "function") throw new Error("Expected instance of class which extends utils.Hash"); this.blockLen = this.iHash.blockLen; this.outputLen = this.iHash.outputLen; const blockLen = this.blockLen; const pad = new Uint8Array(blockLen); pad.set(key.length > blockLen ? hash2.create().update(key).digest() : key); for (let i = 0; i < pad.length; i++) pad[i] ^= 54; this.iHash.update(pad); this.oHash = hash2.create(); for (let i = 0; i < pad.length; i++) pad[i] ^= 54 ^ 92; this.oHash.update(pad); pad.fill(0); } update(buf) { exists(this); this.iHash.update(buf); return this; } digestInto(out) { exists(this); bytes(out, this.outputLen); this.finished = true; this.iHash.digestInto(out); this.oHash.update(out); this.oHash.digestInto(out); this.destroy(); } digest() { const out = new Uint8Array(this.oHash.outputLen); this.digestInto(out); return out; } _cloneInto(to) { to || (to = Object.create(Object.getPrototypeOf(this), {})); const { oHash, iHash, finished, destroyed, blockLen, outputLen } = this; to = to; to.finished = finished; to.destroyed = destroyed; to.blockLen = blockLen; to.outputLen = outputLen; to.oHash = oHash._cloneInto(to.oHash); to.iHash = iHash._cloneInto(to.iHash); return to; } destroy() { this.destroyed = true; this.oHash.destroy(); this.iHash.destroy(); } }; var hmac = (hash2, key, message) => new HMAC(hash2, key).update(message).digest(); hmac.create = (hash2, key) => new HMAC(hash2, key); // node_modules/@noble/curves/esm/abstract/modular.js var _0n = BigInt(0); var _1n = BigInt(1); var _2n = BigInt(2); var _3n = BigInt(3); var _4n = BigInt(4); var _5n = BigInt(5); var _8n = BigInt(8); var _9n = BigInt(9); var _16n = BigInt(16); function mod(a, b) { const result = a % b; return result >= _0n ? result : b + result; } function pow(num2, power, modulo) { if (modulo <= _0n || power < _0n) throw new Error("Expected power/modulo > 0"); if (modulo === _1n) return _0n; let res = _1n; while (power > _0n) { if (power & _1n) res = res * num2 % modulo; num2 = num2 * num2 % modulo; power >>= _1n; } return res; } function pow2(x, power, modulo) { let res = x; while (power-- > _0n) { res *= res; res %= modulo; } return res; } function invert(number, modulo) { if (number === _0n || modulo <= _0n) { throw new Error(`invert: expected positive integers, got n=${number} mod=${modulo}`); } let a = mod(number, modulo); let b = modulo; let x = _0n, y = _1n, u = _1n, v = _0n; while (a !== _0n) { const q = b / a; const r = b % a; const m = x - u * q; const n = y - v * q; b = a, a = r, x = u, y = v, u = m, v = n; } const gcd = b; if (gcd !== _1n) throw new Error("invert: does not exist"); return mod(x, modulo); } function tonelliShanks(P) { const legendreC = (P - _1n) / _2n; let Q, S, Z; for (Q = P - _1n, S = 0; Q % _2n === _0n; Q /= _2n, S++) ; for (Z = _2n; Z < P && pow(Z, legendreC, P) !== P - _1n; Z++) ; if (S === 1) { const p1div4 = (P + _1n) / _4n; return function tonelliFast(Fp2, n) { const root = Fp2.pow(n, p1div4); if (!Fp2.eql(Fp2.sqr(root), n)) throw new Error("Cannot find square root"); return root; }; } const Q1div2 = (Q + _1n) / _2n; return function tonelliSlow(Fp2, n) { if (Fp2.pow(n, legendreC) === Fp2.neg(Fp2.ONE)) throw new Error("Cannot find square root"); let r = S; let g = Fp2.pow(Fp2.mul(Fp2.ONE, Z), Q); let x = Fp2.pow(n, Q1div2); let b = Fp2.pow(n, Q); while (!Fp2.eql(b, Fp2.ONE)) { if (Fp2.eql(b, Fp2.ZERO)) return Fp2.ZERO; let m = 1; for (let t2 = Fp2.sqr(b); m < r; m++) { if (Fp2.eql(t2, Fp2.ONE)) break; t2 = Fp2.sqr(t2); } const ge = Fp2.pow(g, _1n << BigInt(r - m - 1)); g = Fp2.sqr(ge); x = Fp2.mul(x, ge); b = Fp2.mul(b, g); r = m; } return x; }; } function FpSqrt(P) { if (P % _4n === _3n) { const p1div4 = (P + _1n) / _4n; return function sqrt3mod4(Fp2, n) { const root = Fp2.pow(n, p1div4); if (!Fp2.eql(Fp2.sqr(root), n)) throw new Error("Cannot find square root"); return root; }; } if (P % _8n === _5n) { const c1 = (P - _5n) / _8n; return function sqrt5mod8(Fp2, n) { const n2 = Fp2.mul(n, _2n); const v = Fp2.pow(n2, c1); const nv = Fp2.mul(n, v); const i = Fp2.mul(Fp2.mul(nv, _2n), v); const root = Fp2.mul(nv, Fp2.sub(i, Fp2.ONE)); if (!Fp2.eql(Fp2.sqr(root), n)) throw new Error("Cannot find square root"); return root; }; } if (P % _16n === _9n) { } return tonelliShanks(P); } var FIELD_FIELDS = [ "create", "isValid", "is0", "neg", "inv", "sqrt", "sqr", "eql", "add", "sub", "mul", "pow", "div", "addN", "subN", "mulN", "sqrN" ]; function validateField(field) { const initial = { ORDER: "bigint", MASK: "bigint", BYTES: "isSafeInteger", BITS: "isSafeInteger" }; const opts = FIELD_FIELDS.reduce((map, val) => { map[val] = "function"; return map; }, initial); return validateObject(field, opts); } function FpPow(f, num2, power) { if (power < _0n) throw new Error("Expected power > 0"); if (power === _0n) return f.ONE; if (power === _1n) return num2; let p = f.ONE; let d = num2; while (power > _0n) { if (power & _1n) p = f.mul(p, d); d = f.sqr(d); power >>= _1n; } return p; } function FpInvertBatch(f, nums) { const tmp = new Array(nums.length); const lastMultiplied = nums.reduce((acc, num2, i) => { if (f.is0(num2)) return acc; tmp[i] = acc; return f.mul(acc, num2); }, f.ONE); const inverted = f.inv(lastMultiplied); nums.reduceRight((acc, num2, i) => { if (f.is0(num2)) return acc; tmp[i] = f.mul(acc, tmp[i]); return f.mul(acc, num2); }, inverted); return tmp; } function nLength(n, nBitLength) { const _nBitLength = nBitLength !== void 0 ? nBitLength : n.toString(2).length; const nByteLength = Math.ceil(_nBitLength / 8); return { nBitLength: _nBitLength, nByteLength }; } function Field(ORDER, bitLen2, isLE = false, redef = {}) { if (ORDER <= _0n) throw new Error(`Expected Field ORDER > 0, got ${ORDER}`); const { nBitLength: BITS, nByteLength: BYTES } = nLength(ORDER, bitLen2); if (BYTES > 2048) throw new Error("Field lengths over 2048 bytes are not supported"); const sqrtP = FpSqrt(ORDER); const f = Object.freeze({ ORDER, BITS, BYTES, MASK: bitMask(BITS), ZERO: _0n, ONE: _1n, create: (num2) => mod(num2, ORDER), isValid: (num2) => { if (typeof num2 !== "bigint") throw new Error(`Invalid field element: expected bigint, got ${typeof num2}`); return _0n <= num2 && num2 < ORDER; }, is0: (num2) => num2 === _0n, isOdd: (num2) => (num2 & _1n) === _1n, neg: (num2) => mod(-num2, ORDER), eql: (lhs, rhs) => lhs === rhs, sqr: (num2) => mod(num2 * num2, ORDER), add: (lhs, rhs) => mod(lhs + rhs, ORDER), sub: (lhs, rhs) => mod(lhs - rhs, ORDER), mul: (lhs, rhs) => mod(lhs * rhs, ORDER), pow: (num2, power) => FpPow(f, num2, power), div: (lhs, rhs) => mod(lhs * invert(rhs, ORDER), ORDER), // Same as above, but doesn't normalize sqrN: (num2) => num2 * num2, addN: (lhs, rhs) => lhs + rhs, subN: (lhs, rhs) => lhs - rhs, mulN: (lhs, rhs) => lhs * rhs, inv: (num2) => invert(num2, ORDER), sqrt: redef.sqrt || ((n) => sqrtP(f, n)), invertBatch: (lst) => FpInvertBatch(f, lst), // TODO: do we really need constant cmov? // We don't have const-time bigints anyway, so probably will be not very useful cmov: (a, b, c) => c ? b : a, toBytes: (num2) => isLE ? numberToBytesLE(num2, BYTES) : numberToBytesBE(num2, BYTES), fromBytes: (bytes2) => { if (bytes2.length !== BYTES) throw new Error(`Fp.fromBytes: expected ${BYTES}, got ${bytes2.length}`); return isLE ? bytesToNumberLE(bytes2) : bytesToNumberBE(bytes2); } }); return Object.freeze(f); } function getFieldBytesLength(fieldOrder) { if (typeof fieldOrder !== "bigint") throw new Error("field order must be bigint"); const bitLength = fieldOrder.toString(2).length; return Math.ceil(bitLength / 8); } function getMinHashLength(fieldOrder) { const length = getFieldBytesLength(fieldOrder); return length + Math.ceil(length / 2); } function mapHashToField(key, fieldOrder, isLE = false) { const len = key.length; const fieldLen = getFieldBytesLength(fieldOrder); const minLen = getMinHashLength(fieldOrder); if (len < 16 || len < minLen || len > 1024) throw new Error(`expected ${minLen}-1024 bytes of input, got ${len}`); const num2 = isLE ? bytesToNumberBE(key) : bytesToNumberLE(key); const reduced = mod(num2, fieldOrder - _1n) + _1n; return isLE ? numberToBytesLE(reduced, fieldLen) : numberToBytesBE(reduced, fieldLen); } // node_modules/@noble/curves/esm/abstract/curve.js var _0n2 = BigInt(0); var _1n2 = BigInt(1); var pointPrecomputes = /* @__PURE__ */ new WeakMap(); var pointWindowSizes = /* @__PURE__ */ new WeakMap(); function wNAF(c, bits) { const constTimeNegate = (condition, item) => { const neg = item.negate(); return condition ? neg : item; }; const validateW = (W) => { if (!Number.isSafeInteger(W) || W <= 0 || W > bits) throw new Error(`Wrong window size=${W}, should be [1..${bits}]`); }; const opts = (W) => { validateW(W); const windows = Math.ceil(bits / W) + 1; const windowSize = 2 ** (W - 1); return { windows, windowSize }; }; return { constTimeNegate, // non-const time multiplication ladder unsafeLadder(elm, n) { let p = c.ZERO; let d = elm; while (n > _0n2) { if (n & _1n2) p = p.add(d); d = d.double(); n >>= _1n2; } return p; }, /** * Creates a wNAF precomputation window. Used for caching. * Default window size is set by `utils.precompute()` and is equal to 8. * Number of precomputed points depends on the curve size: * 2^(𝑊−1) * (Math.ceil(𝑛 / 𝑊) + 1), where: * - 𝑊 is the window size * - 𝑛 is the bitlength of the curve order. * For a 256-bit curve and window size 8, the number of precomputed points is 128 * 33 = 4224. * @returns precomputed point tables flattened to a single array */ precomputeWindow(elm, W) { const { windows, windowSize } = opts(W); const points = []; let p = elm; let base = p; for (let window = 0; window < windows; window++) { base = p; points.push(base); for (let i = 1; i < windowSize; i++) { base = base.add(p); points.push(base); } p = base.double(); } return points; }, /** * Implements ec multiplication using precomputed tables and w-ary non-adjacent form. * @param W window size * @param precomputes precomputed tables * @param n scalar (we don't check here, but should be less than curve order) * @returns real and fake (for const-time) points */ wNAF(W, precomputes, n) { const { windows, windowSize } = opts(W); let p = c.ZERO; let f = c.BASE; const mask = BigInt(2 ** W - 1); const maxNumber = 2 ** W; const shiftBy = BigInt(W); for (let window = 0; window < windows; window++) { const offset = window * windowSize; let wbits = Number(n & mask); n >>= shiftBy; if (wbits > windowSize) { wbits -= maxNumber; n += _1n2; } const offset1 = offset; const offset2 = offset + Math.abs(wbits) - 1; const cond1 = window % 2 !== 0; const cond2 = wbits < 0; if (wbits === 0) { f = f.add(constTimeNegate(cond1, precomputes[offset1])); } else { p = p.add(constTimeNegate(cond2, precomputes[offset2])); } } return { p, f }; }, wNAFCached(P, n, transform) { const W = pointWindowSizes.get(P) || 1; let comp = pointPrecomputes.get(P); if (!comp) { comp = this.precomputeWindow(P, W); if (W !== 1) pointPrecomputes.set(P, transform(comp)); } return this.wNAF(W, comp, n); }, // We calculate precomputes for elliptic curve point multiplication // using windowed method. This specifies window size and // stores precomputed values. Usually only base point would be precomputed. setWindowSize(P, W) { validateW(W); pointWindowSizes.set(P, W); pointPrecomputes.delete(P); } }; } function pippenger(c, field, points, scalars) { if (!Array.isArray(points) || !Array.isArray(scalars) || scalars.length !== points.length) throw new Error("arrays of points and scalars must have equal length"); scalars.forEach((s, i) => { if (!field.isValid(s)) throw new Error(`wrong scalar at index ${i}`); }); points.forEach((p, i) => { if (!(p instanceof c)) throw new Error(`wrong point at index ${i}`); }); const wbits = bitLen(BigInt(points.length)); const windowSize = wbits > 12 ? wbits - 3 : wbits > 4 ? wbits - 2 : wbits ? 2 : 1; const MASK = (1 << windowSize) - 1; const buckets = new Array(MASK + 1).fill(c.ZERO); const lastBits = Math.floor((field.BITS - 1) / windowSize) * windowSize; let sum = c.ZERO; for (let i = lastBits; i >= 0; i -= windowSize) { buckets.fill(c.ZERO); for (let j = 0; j < scalars.length; j++) { const scalar = scalars[j]; const wbits2 = Number(scalar >> BigInt(i) & BigInt(MASK)); buckets[wbits2] = buckets[wbits2].add(points[j]); } let resI = c.ZERO; for (let j = buckets.length - 1, sumI = c.ZERO; j > 0; j--) { sumI = sumI.add(buckets[j]); resI = resI.add(sumI); } sum = sum.add(resI); if (i !== 0) for (let j = 0; j < windowSize; j++) sum = sum.double(); } return sum; } function validateBasic(curve) { validateField(curve.Fp); validateObject(curve, { n: "bigint", h: "bigint", Gx: "field", Gy: "field" }, { nBitLength: "isSafeInteger", nByteLength: "isSafeInteger" }); return Object.freeze({ ...nLength(curve.n, curve.nBitLength), ...curve, ...{ p: curve.Fp.ORDER } }); } // node_modules/@noble/curves/esm/abstract/weierstrass.js function validateSigVerOpts(opts) { if (opts.lowS !== void 0) abool("lowS", opts.lowS); if (opts.prehash !== void 0) abool("prehash", opts.prehash); } function validatePointOpts(curve) { const opts = validateBasic(curve); validateObject(opts, { a: "field", b: "field" }, { allowedPrivateKeyLengths: "array", wrapPrivateKey: "boolean", isTorsionFree: "function", clearCofactor: "function", allowInfinityPoint: "boolean", fromBytes: "function", toBytes: "function" }); const { endo, Fp: Fp2, a } = opts; if (endo) { if (!Fp2.eql(a, Fp2.ZERO)) { throw new Error("Endomorphism can only be defined for Koblitz curves that have a=0"); } if (typeof endo !== "object" || typeof endo.beta !== "bigint" || typeof endo.splitScalar !== "function") { throw new Error("Expected endomorphism with beta: bigint and splitScalar: function"); } } return Object.freeze({ ...opts }); } var { bytesToNumberBE: b2n, hexToBytes: h2b } = utils_exports; var DER = { // asn.1 DER encoding utils Err: class DERErr extends Error { constructor(m = "") { super(m); } }, // Basic building block is TLV (Tag-Length-Value) _tlv: { encode: (tag, data) => { const { Err: E } = DER; if (tag < 0 || tag > 256) throw new E("tlv.encode: wrong tag"); if (data.length & 1) throw new E("tlv.encode: unpadded data"); const dataLen = data.length / 2; const len = numberToHexUnpadded(dataLen); if (len.length / 2 & 128) throw new E("tlv.encode: long form length too big"); const lenLen = dataLen > 127 ? numberToHexUnpadded(len.length / 2 | 128) : ""; return `${numberToHexUnpadded(tag)}${lenLen}${len}${data}`; }, // v - value, l - left bytes (unparsed) decode(tag, data) { const { Err: E } = DER; let pos = 0; if (tag < 0 || tag > 256) throw new E("tlv.encode: wrong tag"); if (data.length < 2 || data[pos++] !== tag) throw new E("tlv.decode: wrong tlv"); const first = data[pos++]; const isLong = !!(first & 128); let length = 0; if (!isLong) length = first; else { const lenLen = first & 127; if (!lenLen) throw new E("tlv.decode(long): indefinite length not supported"); if (lenLen > 4) throw new E("tlv.decode(long): byte length is too big"); const lengthBytes = data.subarray(pos, pos + lenLen); if (lengthBytes.length !== lenLen) throw new E("tlv.decode: length bytes not complete"); if (lengthBytes[0] === 0) throw new E("tlv.decode(long): zero leftmost byte"); for (const b of lengthBytes) length = length << 8 | b; pos += lenLen; if (length < 128) throw new E("tlv.decode(long): not minimal encoding"); } const v = data.subarray(pos, pos + length); if (v.length !== length) throw new E("tlv.decode: wrong value length"); return { v, l: data.subarray(pos + length) }; } }, // https://crypto.stackexchange.com/a/57734 Leftmost bit of first byte is 'negative' flag, // since we always use positive integers here. It must always be empty: // - add zero byte if exists // - if next byte doesn't have a flag, leading zero is not allowed (minimal encoding) _int: { encode(num2) { const { Err: E } = DER; if (num2 < _0n3) throw new E("integer: negative integers are not allowed"); let hex = numberToHexUnpadded(num2); if (Number.parseInt(hex[0], 16) & 8) hex = "00" + hex; if (hex.length & 1) throw new E("unexpected assertion"); return hex; }, decode(data) { const { Err: E } = DER; if (data[0] & 128) throw new E("Invalid signature integer: negative"); if (data[0] === 0 && !(data[1] & 128)) throw new E("Invalid signature integer: unnecessary leading zero"); return b2n(data); } }, toSig(hex) { const { Err: E, _int: int, _tlv: tlv } = DER; const data = typeof hex === "string" ? h2b(hex) : hex; abytes(data); const { v: seqBytes, l: seqLeftBytes } = tlv.decode(48, data); if (seqLeftBytes.length) throw new E("Invalid signature: left bytes after parsing"); const { v: rBytes, l: rLeftBytes } = tlv.decode(2, seqBytes); const { v: sBytes, l: sLeftBytes } = tlv.decode(2, rLeftBytes); if (sLeftBytes.length) throw new E("Invalid signature: left bytes after parsing"); return { r: int.decode(rBytes), s: int.decode(sBytes) }; }, hexFromSig(sig) { const { _tlv: tlv, _int: int } = DER; const seq = `${tlv.encode(2, int.encode(sig.r))}${tlv.encode(2, int.encode(sig.s))}`; return tlv.encode(48, seq); } }; var _0n3 = BigInt(0); var _1n3 = BigInt(1); var _2n2 = BigInt(2); var _3n2 = BigInt(3); var _4n2 = BigInt(4); function weierstrassPoints(opts) { const CURVE = validatePointOpts(opts); const { Fp: Fp2 } = CURVE; const Fn = Field(CURVE.n, CURVE.nBitLength); const toBytes2 = CURVE.toBytes || ((_c, point, _isCompressed) => { const a = point.toAffine(); return concatBytes(Uint8Array.from([4]), Fp2.toBytes(a.x), Fp2.toBytes(a.y)); }); const fromBytes = CURVE.fromBytes || ((bytes2) => { const tail = bytes2.subarray(1); const x = Fp2.fromBytes(tail.subarray(0, Fp2.BYTES)); const y = Fp2.fromBytes(tail.subarray(Fp2.BYTES, 2 * Fp2.BYTES)); return { x, y }; }); function weierstrassEquation(x) { const { a, b } = CURVE; const x2 = Fp2.sqr(x); const x3 = Fp2.mul(x2, x); return Fp2.add(Fp2.add(x3, Fp2.mul(x, a)), b); } if (!Fp2.eql(Fp2.sqr(CURVE.Gy), weierstrassEquation(CURVE.Gx))) throw new Error("bad generator point: equation left != right"); function isWithinCurveOrder(num2) { return inRange(num2, _1n3, CURVE.n); } function normPrivateKeyToScalar(key) { const { allowedPrivateKeyLengths: lengths, nByteLength, wrapPrivateKey, n: N } = CURVE; if (lengths && typeof key !== "bigint") { if (isBytes(key)) key = bytesToHex(key); if (typeof key !== "string" || !lengths.includes(key.length)) throw new Error("Invalid key"); key = key.padStart(nByteLength * 2, "0"); } let num2; try { num2 = typeof key === "bigint" ? key : bytesToNumberBE(ensureBytes("private key", key, nByteLength)); } catch (error) { throw new Error(`private key must be ${nByteLength} bytes, hex or bigint, not ${typeof key}`); } if (wrapPrivateKey) num2 = mod(num2, N); aInRange("private key", num2, _1n3, N); return num2; } function assertPrjPoint(other) { if (!(other instanceof Point2)) throw new Error("ProjectivePoint expected"); } const toAffineMemo = memoized((p, iz) => { const { px: x, py: y, pz: z } = p; if (Fp2.eql(z, Fp2.ONE)) return { x, y }; const is0 = p.is0(); if (iz == null) iz = is0 ? Fp2.ONE : Fp2.inv(z); const ax = Fp2.mul(x, iz); const ay = Fp2.mul(y, iz); const zz = Fp2.mul(z, iz); if (is0) return { x: Fp2.ZERO, y: Fp2.ZERO }; if (!Fp2.eql(zz, Fp2.ONE)) throw new Error("invZ was invalid"); return { x: ax, y: ay }; }); const assertValidMemo = memoized((p) => { if (p.is0()) { if (CURVE.allowInfinityPoint && !Fp2.is0(p.py)) return; throw new Error("bad point: ZERO"); } const { x, y } = p.toAffine(); if (!Fp2.isValid(x) || !Fp2.isValid(y)) throw new Error("bad point: x or y not FE"); const left = Fp2.sqr(y); const right = weierstrassEquation(x); if (!Fp2.eql(left, right)) throw new Error("bad point: equation left != right"); if (!p.isTorsionFree()) throw new Error("bad point: not in prime-order subgroup"); return true; }); class Point2 { constructor(px, py, pz) { this.px = px; this.py = py; this.pz = pz; if (px == null || !Fp2.isValid(px)) throw new Error("x required"); if (py == null || !Fp2.isValid(py)) throw new Error("y required"); if (pz == null || !Fp2.isValid(pz)) throw new Error("z required"); Object.freeze(this); } // Does not validate if the point is on-curve. // Use fromHex instead, or call assertValidity() later. static fromAffine(p) { const { x, y } = p || {}; if (!p || !Fp2.isValid(x) || !Fp2.isValid(y)) throw new Error("invalid affine point"); if (p instanceof Point2) throw new Error("projective point not allowed"); const is0 = (i) => Fp2.eql(i, Fp2.ZERO); if (is0(x) && is0(y)) return Point2.ZERO; return new Point2(x, y, Fp2.ONE); } get x() { return this.toAffine().x; } get y() { return this.toAffine().y; } /** * Takes a bunch of Projective Points but executes only one * inversion on all of them. Inversion is very slow operation, * so this improves performance massively. * Optimization: converts a list of projective points to a list of identical points with Z=1. */ static normalizeZ(points) { const toInv = Fp2.invertBatch(points.map((p) => p.pz)); return points.map((p, i) => p.toAffine(toInv[i])).map(Point2.fromAffine); } /** * Converts hash string or Uint8Array to Point. * @param hex short/long ECDSA hex */ static fromHex(hex) { const P = Point2.fromAffine(fromBytes(ensureBytes("pointHex", hex))); P.assertValidity(); return P; } // Multiplies generator point by privateKey. static fromPrivateKey(privateKey) { return Point2.BASE.multiply(normPrivateKeyToScalar(privateKey)); } // Multiscalar Multiplication static msm(points, scalars) { return pippenger(Point2, Fn, points, scalars); } // "Private method", don't use it directly _setWindowSize(windowSize) { wnaf.setWindowSize(this, windowSize); } // A point on curve is valid if it conforms to equation. assertValidity() { assertValidMemo(this); } hasEvenY() { const { y } = this.toAffine(); if (Fp2.isOdd) return !Fp2.isOdd(y); throw new Error("Field doesn't support isOdd"); } /** * Compare one point to another. */ equals(other) { assertPrjPoint(other); const { px: X1, py: Y1, pz: Z1 } = this; const { px: X2, py: Y2, pz: Z2 } = other; const U1 = Fp2.eql(Fp2.mul(X1, Z2), Fp2.mul(X2, Z1)); const U2 = Fp2.eql(Fp2.mul(Y1, Z2), Fp2.mul(Y2, Z1)); return U1 && U2; } /** * Flips point to one corresponding to (x, -y) in Affine coordinates. */ negate() { return new Point2(this.px, Fp2.neg(this.py), this.pz); } // Renes-Costello-Batina exception-free doubling formula. // There is 30% faster Jacobian formula, but it is not complete. // https://eprint.iacr.org/2015/1060, algorithm 3 // Cost: 8M + 3S + 3*a + 2*b3 + 15add. double() { const { a, b } = CURVE; const b3 = Fp2.mul(b, _3n2); const { px: X1, py: Y1, pz: Z1 } = this; let X3 = Fp2.ZERO, Y3 = Fp2.ZERO, Z3 = Fp2.ZERO; let t0 = Fp2.mul(X1, X1); let t1 = Fp2.mul(Y1, Y1); let t2 = Fp2.mul(Z1, Z1); let t3 = Fp2.mul(X1, Y1); t3 = Fp2.add(t3, t3); Z3 = Fp2.mul(X1, Z1); Z3 = Fp2.add(Z3, Z3); X3 = Fp2.mul(a, Z3); Y3 = Fp2.mul(b3, t2); Y3 = Fp2.add(X3, Y3); X3 = Fp2.sub(t1, Y3); Y3 = Fp2.add(t1, Y3); Y3 = Fp2.mul(X3, Y3); X3 = Fp2.mul(t3, X3); Z3 = Fp2.mul(b3, Z3); t2 = Fp2.mul(a, t2); t3 = Fp2.sub(t0, t2); t3 = Fp2.mul(a, t3); t3 = Fp2.add(t3, Z3); Z3 = Fp2.add(t0, t0); t0 = Fp2.add(Z3, t0); t0 = Fp2.add(t0, t2); t0 = Fp2.mul(t0, t3); Y3 = Fp2.add(Y3, t0); t2 = Fp2.mul(Y1, Z1); t2 = Fp2.add(t2, t2); t0 = Fp2.mul(t2, t3); X3 = Fp2.sub(X3, t0); Z3 = Fp2.mul(t2, t1); Z3 = Fp2.add(Z3, Z3); Z3 = Fp2.add(Z3, Z3); return new Point2(X3, Y3, Z3); } // Renes-Costello-Batina exception-free addition formula. // There is 30% faster Jacobian formula, but it is not complete. // https://eprint.iacr.org/2015/1060, algorithm 1 // Cost: 12M + 0S + 3*a + 3*b3 + 23add. add(other) { assertPrjPoint(other); const { px: X1, py: Y1, pz: Z1 } = this; const { px: X2, py: Y2, pz: Z2 } = other; let X3 = Fp2.ZERO, Y3 = Fp2.ZERO, Z3 = Fp2.ZERO; const a = CURVE.a; const b3 = Fp2.mul(CURVE.b, _3n2); let t0 = Fp2.mul(X1, X2); let t1 = Fp2.mul(Y1, Y2); let t2 = Fp2.mul(Z1, Z2); let t3 = Fp2.add(X1, Y1); let t4 = Fp2.add(X2, Y2); t3 = Fp2.mul(t3, t4); t4 = Fp2.add(t0, t1); t3 = Fp2.sub(t3, t4); t4 = Fp2.add(X1, Z1); let t5 = Fp2.add(X2, Z2); t4 = Fp2.mul(t4, t5); t5 = Fp2.add(t0, t2); t4 = Fp2.sub(t4, t5); t5 = Fp2.add(Y1, Z1); X3 = Fp2.add(Y2, Z2); t5 = Fp2.mul(t5, X3); X3 = Fp2.add(t1, t2); t5 = Fp2.sub(t5, X3); Z3 = Fp2.mul(a, t4); X3 = Fp2.mul(b3, t2); Z3 = Fp2.add(X3, Z3); X3 = Fp2.sub(t1, Z3); Z3 = Fp2.add(t1, Z3); Y3 = Fp2.mul(X3, Z3); t1 = Fp2.add(t0, t0); t1 = Fp2.add(t1, t0); t2 = Fp2.mul(a, t2); t4 = Fp2.mul(b3, t4); t1 = Fp2.add(t1, t2); t2 = Fp2.sub(t0, t2); t2 = Fp2.mul(a, t2); t4 = Fp2.add(t4, t2); t0 = Fp2.mul(t1, t4); Y3 = Fp2.add(Y3, t0); t0 = Fp2.mul(t5, t4); X3 = Fp2.mul(t3, X3); X3 = Fp2.sub(X3, t0); t0 = Fp2.mul(t3, t1); Z3 = Fp2.mul(t5, Z3); Z3 = Fp2.add(Z3, t0); return new Point2(X3, Y3, Z3); } subtract(other) { return this.add(other.negate()); } is0() { return this.equals(Point2.ZERO); } wNAF(n) { return wnaf.wNAFCached(this, n, Point2.normalizeZ); } /** * Non-constant-time multiplication. Uses double-and-add algorithm. * It's faster, but should only be used when you don't care about * an exposed private key e.g. sig verification, which works over *public* keys. */ multiplyUnsafe(sc) { aInRange("scalar", sc, _0n3, CURVE.n); const I = Point2.ZERO; if (sc === _0n3) return I; if (sc === _1n3) return this; const { endo } = CURVE; if (!endo) return wnaf.unsafeLadder(this, sc); let { k1neg, k1, k2neg, k2 } = endo.splitScalar(sc); let k1p = I; let k2p = I; let d = this; while (k1 > _0n3 || k2 > _0n3) { if (k1 & _1n3) k1p = k1p.add(d); if (k2 & _1n3) k2p = k2p.add(d); d = d.double(); k1 >>= _1n3; k2 >>= _1n3; } if (k1neg) k1p = k1p.negate(); if (k2neg) k2p = k2p.negate(); k2p = new Point2(Fp2.mul(k2p.px, endo.beta), k2p.py, k2p.pz); return k1p.add(k2p); } /** * Constant time multiplication. * Uses wNAF method. Windowed method may be 10% faster, * but takes 2x longer to generate and consumes 2x memory. * Uses precomputes when available. * Uses endomorphism for Koblitz curves. * @param scalar by which the point would be multiplied * @returns New point */ multiply(scalar) { const { endo, n: N } = CURVE; aInRange("scalar", scalar, _1n3, N); let point, fake; if (endo) { const { k1neg, k1, k2neg, k2 } = endo.splitScalar(scalar); let { p: k1p, f: f1p } = this.wNAF(k1); let { p: k2p, f: f2p } = this.wNAF(k2); k1p = wnaf.constTimeNegate(k1neg, k1p); k2p = wnaf.constTimeNegate(k2neg, k2p); k2p = new Point2(Fp2.mul(k2p.px, endo.beta), k2p.py, k2p.pz); point = k1p.add(k2p); fake = f1p.add(f2p); } else { const { p, f } = this.wNAF(scalar); point = p; fake = f; } return Point2.normalizeZ([point, fake])[0]; } /** * Efficiently calculate `aP + bQ`. Unsafe, can expose private key, if used incorrectly. * Not using Strauss-Shamir trick: precomputation tables are faster. * The trick could be useful if both P and Q are not G (not in our case). * @returns non-zero affine point */ multiplyAndAddUnsafe(Q, a, b) { const G = Point2.BASE; const mul = (P, a2) => a2 === _0n3 || a2 === _1n3 || !P.equals(G) ? P.multiplyUnsafe(a2) : P.multiply(a2); const sum = mul(this, a).add(mul(Q, b)); return sum.is0() ? void 0 : sum; } // Converts Projective point to affine (x, y) coordinates. // Can accept precomputed Z^-1 - for example, from invertBatch. // (x, y, z) ∋ (x=x/z, y=y/z) toAffine(iz) { return toAffineMemo(this, iz); } isTorsionFree() { const { h: cofactor, isTorsionFree } = CURVE; if (cofactor === _1n3) return true; if (isTorsionFree) return isTorsionFree(Point2, this); throw new Error("isTorsionFree() has not been declared for the elliptic curve"); } clearCofactor() { const { h: cofactor, clearCofactor } = CURVE; if (cofactor === _1n3) return this; if (clearCofactor) return clearCofactor(Point2, this); return this.multiplyUnsafe(CURVE.h); } toRawBytes(isCompressed = true) { abool("isCompressed", isCompressed); this.assertValidity(); return toBytes2(Point2, this, isCompressed); } toHex(isCompressed = true) { abool("isCompressed", isCompressed); return bytesToHex(this.toRawBytes(isCompressed)); } } Point2.BASE = new Point2(CURVE.Gx, CURVE.Gy, Fp2.ONE); Point2.ZERO = new Point2(Fp2.ZERO, Fp2.ONE, Fp2.ZERO); const _bits = CURVE.nBitLength; const wnaf = wNAF(Point2, CURVE.endo ? Math.ceil(_bits / 2) : _bits); return { CURVE, ProjectivePoint: Point2, normPrivateKeyToScalar, weierstrassEquation, isWithinCurveOrder }; } function validateOpts(curve) { const opts = validateBasic(curve); validateObject(opts, { hash: "hash", hmac: "function", randomBytes: "function" }, { bits2int: "function", bits2int_modN: "function", lowS: "boolean" }); return Object.freeze({ lowS: true, ...opts }); } function weierstrass(curveDef) { const CURVE = validateOpts(curveDef); const { Fp: Fp2, n: CURVE_ORDER } = CURVE; const compressedLen = Fp2.BYTES + 1; const uncompressedLen = 2 * Fp2.BYTES + 1; function modN2(a) { return mod(a, CURVE_ORDER); } function invN(a) { return invert(a, CURVE_ORDER); } const { ProjectivePoint: Point2, normPrivateKeyToScalar, weierstrassEquation, isWithinCurveOrder } = weierstrassPoints({ ...CURVE, toBytes(_c, point, isCompressed) { const a = point.toAffine(); const x = Fp2.toBytes(a.x); const cat = concatBytes; abool("isCompressed", isCompressed); if (isCompressed) { return cat(Uint8Array.from([point.hasEvenY() ? 2 : 3]), x); } else { return cat(Uint8Array.from([4]), x, Fp2.toBytes(a.y)); } }, fromBytes(bytes2) { const len = bytes2.length; const head = bytes2[0]; const tail = bytes2.subarray(1); if (len === compressedLen && (head === 2 || head === 3)) { const x = bytesToNumberBE(tail); if (!inRange(x, _1n3, Fp2.ORDER)) throw new Error("Point is not on curve"); const y2 = weierstrassEquation(x); let y; try { y = Fp2.sqrt(y2); } catch (sqrtError) { const suffix = sqrtError instanceof Error ? ": " + sqrtError.message : ""; throw new Error("Point is not on curve" + suffix); } const isYOdd = (y & _1n3) === _1n3; const isHeadOdd = (head & 1) === 1; if (isHeadOdd !== isYOdd) y = Fp2.neg(y); return { x, y }; } else if (len === uncompressedLen && head === 4) { const x = Fp2.fromBytes(tail.subarray(0, Fp2.BYTES)); const y = Fp2.fromBytes(tail.subarray(Fp2.BYTES, 2 * Fp2.BYTES)); return { x, y }; } else { throw new Error(`Point of length ${len} was invalid. Expected ${compressedLen} compressed bytes or ${uncompressedLen} uncompressed bytes`); } } }); const numToNByteStr = (num2) => bytesToHex(numberToBytesBE(num2, CURVE.nByteLength)); function isBiggerThanHalfOrder(number) { const HALF = CURVE_ORDER >> _1n3; return number > HALF; } function normalizeS(s) { return isBiggerThanHalfOrder(s) ? modN2(-s) : s; } const slcNum = (b, from, to) => bytesToNumberBE(b.slice(from, to)); class Signature { constructor(r, s, recovery) { this.r = r; this.s = s; this.recovery = recovery; this.assertValidity(); } // pair (bytes of r, bytes of s) static fromCompact(hex) { const l = CURVE.nByteLength; hex = ensureBytes("compactSignature", hex, l * 2); return new Signature(slcNum(hex, 0, l), slcNum(hex, l, 2 * l)); } // DER encoded ECDSA signature // https://bitcoin.stackexchange.com/questions/57644/what-are-the-parts-of-a-bitcoin-transaction-input-script static fromDER(hex) { const { r, s } = DER.toSig(ensureBytes("DER", hex)); return new Signature(r, s); } assertValidity() { aInRange("r", this.r, _1n3, CURVE_ORDER); aInRange("s", this.s, _1n3, CURVE_ORDER); } addRecoveryBit(recovery) { return new Signature(this.r, this.s, recovery); } recoverPublicKey(msgHash) { const { r, s, recovery: rec } = this; const h = bits2int_modN(ensureBytes("msgHash", msgHash)); if (rec == null || ![0, 1, 2, 3].includes(rec)) throw new Error("recovery id invalid"); const radj = rec === 2 || rec === 3 ? r + CURVE.n : r; if (radj >= Fp2.ORDER) throw new Error("recovery id 2 or 3 invalid"); const prefix = (rec & 1) === 0 ? "02" : "03"; const R = Point2.fromHex(prefix + numToNByteStr(radj)); const ir = invN(radj); const u1 = modN2(-h * ir); const u2 = modN2(s * ir); const Q = Point2.BASE.multiplyAndAddUnsafe(R, u1, u2); if (!Q) throw new Error("point at infinify"); Q.assertValidity(); return Q; } // Signatures should be low-s, to prevent malleability. hasHighS() { return isBiggerThanHalfOrder(this.s); } normalizeS() { return this.hasHighS() ? new Signature(this.r, modN2(-this.s), this.recovery) : this; } // DER-encoded toDERRawBytes() { return hexToBytes(this.toDERHex()); } toDERHex() { return DER.hexFromSig({ r: this.r, s: this.s }); } // padded bytes of r, then padded bytes of s toCompactRawBytes() { return hexToBytes(this.toCompactHex()); } toCompactHex() { return numToNByteStr(this.r) + numToNByteStr(this.s); } } const utils = { isValidPrivateKey(privateKey) { try { normPrivateKeyToScalar(privateKey); return true; } catch (error) { return false; } }, normPrivateKeyToScalar, /** * Produces cryptographically secure private key from random of size * (groupLen + ceil(groupLen / 2)) with modulo bias being negligible. */ randomPrivateKey: () => { const length = getMinHashLength(CURVE.n); return mapHashToField(CURVE.randomBytes(length), CURVE.n); }, /** * Creates precompute table for an arbitrary EC point. Makes point "cached". * Allows to massively speed-up `point.multiply(scalar)`. * @returns cached point * @example * const fast = utils.precompute(8, ProjectivePoint.fromHex(someonesPubKey)); * fast.multiply(privKey); // much faster ECDH now */ precompute(windowSize = 8, point = Point2.BASE) { point._setWindowSize(windowSize); point.multiply(BigInt(3)); return point; } }; function getPublicKey(privateKey, isCompressed = true) { return Point2.fromPrivateKey(privateKey).toRawBytes(isCompressed); } function isProbPub(item) { const arr = isBytes(item); const str = typeof item === "string"; const len = (arr || str) && item.length; if (arr) return len === compressedLen || len === uncompressedLen; if (str) return len === 2 * compressedLen || len === 2 * uncompressedLen; if (item instanceof Point2) return true; return false; } function getSharedSecret(privateA, publicB, isCompressed = true) { if (isProbPub(privateA)) throw new Error("first arg must be private key"); if (!isProbPub(publicB)) throw new Error("second arg must be public key"); const b = Point2.fromHex(publicB); return b.multiply(normPrivateKeyToScalar(privateA)).toRawBytes(isCompressed); } const bits2int = CURVE.bits2int || function(bytes2) { const num2 = bytesToNumberBE(bytes2); const delta = bytes2.length * 8 - CURVE.nBitLength; return delta > 0 ? num2 >> BigInt(delta) : num2; }; const bits2int_modN = CURVE.bits2int_modN || function(bytes2) { return modN2(bits2int(bytes2)); }; const ORDER_MASK = bitMask(CURVE.nBitLength); function int2octets(num2) { aInRange(`num < 2^${CURVE.nBitLength}`, num2, _0n3, ORDER_MASK); return numberToBytesBE(num2, CURVE.nByteLength); } function prepSig(msgHash, privateKey, opts = defaultSigOpts) { if (["recovered", "canonical"].some((k) => k in opts)) throw new Error("sign() legacy options not supported"); const { hash: hash2, randomBytes: randomBytes2 } = CURVE; let { lowS, prehash, extraEntropy: ent } = opts; if (lowS == null) lowS = true; msgHash = ensureBytes("msgHash", msgHash); validateSigVerOpts(opts); if (prehash) msgHash = ensureBytes("prehashed msgHash", hash2(msgHash)); const h1int = bits2int_modN(msgHash); const d = normPrivateKeyToScalar(privateKey); const seedArgs = [int2octets(d), int2octets(h1int)]; if (ent != null && ent !== false) { const e = ent === true ? randomBytes2(Fp2.BYTES) : ent; seedArgs.push(ensureBytes("extraEntropy", e)); } const seed = concatBytes(...seedArgs); const m = h1int; function k2sig(kBytes) { const k = bits2int(kBytes); if (!isWithinCurveOrder(k)) return; const ik = invN(k); const q = Point2.BASE.multiply(k).toAffine(); const r = modN2(q.x); if (r === _0n3) return; const s = modN2(ik * modN2(m + r * d)); if (s === _0n3) return; let recovery = (q.x === r ? 0 : 2) | Number(q.y & _1n3); let normS = s; if (lowS && isBiggerThanHalfOrder(s)) { normS = normalizeS(s); recovery ^= 1; } return new Signature(r, normS, recovery); } return { seed, k2sig }; } const defaultSigOpts = { lowS: CURVE.lowS, prehash: false }; const defaultVerOpts = { lowS: CURVE.lowS, prehash: false }; function sign(msgHash, privKey, opts = defaultSigOpts) { const { seed, k2sig } = prepSig(msgHash, privKey, opts); const C = CURVE; const drbg = createHmacDrbg(C.hash.outputLen, C.nByteLength, C.hmac); return drbg(seed, k2sig); } Point2.BASE._setWindowSize(8); function verify(signature, msgHash, publicKey, opts = defaultVerOpts) { var _a; const sg = signature; msgHash = ensureBytes("msgHash", msgHash); publicKey = ensureBytes("publicKey", publicKey); if ("strict" in opts) throw new Error("options.strict was renamed to lowS"); validateSigVerOpts(opts); const { lowS, prehash } = opts; let _sig = void 0; let P; try { if (typeof sg === "string" || isBytes(sg)) { try { _sig = Signature.fromDER(sg); } catch (derError) { if (!(derError instanceof DER.Err)) throw derError; _sig = Signature.fromCompact(sg); } } else if (typeof sg === "object" && typeof sg.r === "bigint" && typeof sg.s === "bigint") { const { r: r2, s: s2 } = sg; _sig = new Signature(r2, s2); } else { throw new Error("PARSE"); } P = Point2.fromHex(publicKey); } catch (error) { if (error.message === "PARSE") throw new Error(`signature must be Signature instance, Uint8Array or hex string`); return false; } if (lowS && _sig.hasHighS()) return false; if (prehash) msgHash = CURVE.hash(msgHash); const { r, s } = _sig; const h = bits2int_modN(msgHash); const is = invN(s); const u1 = modN2(h * is); const u2 = modN2(r * is); const R = (_a = Point2.BASE.multiplyAndAddUnsafe(P, u1, u2)) == null ? void 0 : _a.toAffine(); if (!R) return false; const v = modN2(R.x); return v === r; } return { CURVE, getPublicKey, getSharedSecret, sign, verify, ProjectivePoint: Point2, Signature, utils }; } function SWUFpSqrtRatio(Fp2, Z) { const q = Fp2.ORDER; let l = _0n3; for (let o = q - _1n3; o % _2n2 === _0n3; o /= _2n2) l += _1n3; const c1 = l; const _2n_pow_c1_1 = _2n2 << c1 - _1n3 - _1n3; const _2n_pow_c1 = _2n_pow_c1_1 * _2n2; const c2 = (q - _1n3) / _2n_pow_c1; const c3 = (c2 - _1n3) / _2n2; const c4 = _2n_pow_c1 - _1n3; const c5 = _2n_pow_c1_1; const c6 = Fp2.pow(Z, c2); const c7 = Fp2.pow(Z, (c2 + _1n3) / _2n2); let sqrtRatio = (u, v) => { let tv1 = c6; let tv2 = Fp2.pow(v, c4); let tv3 = Fp2.sqr(tv2); tv3 = Fp2.mul(tv3, v); let tv5 = Fp2.mul(u, tv3); tv5 = Fp2.pow(tv5, c3); tv5 = Fp2.mul(tv5, tv2); tv2 = Fp2.mul(tv5, v); tv3 = Fp2.mul(tv5, u); let tv4 = Fp2.mul(tv3, tv2); tv5 = Fp2.pow(tv4, c5); let isQR = Fp2.eql(tv5, Fp2.ONE); tv2 = Fp2.mul(tv3, c7); tv5 = Fp2.mul(tv4, tv1); tv3 = Fp2.cmov(tv2, tv3, isQR); tv4 = Fp2.cmov(tv5, tv4, isQR); for (let i = c1; i > _1n3; i--) { let tv52 = i - _2n2; tv52 = _2n2 << tv52 - _1n3; let tvv5 = Fp2.pow(tv4, tv52); const e1 = Fp2.eql(tvv5, Fp2.ONE); tv2 = Fp2.mul(tv3, tv1); tv1 = Fp2.mul(tv1, tv1); tvv5 = Fp2.mul(tv4, tv1); tv3 = Fp2.cmov(tv2, tv3, e1); tv4 = Fp2.cmov(tvv5, tv4, e1); } return { isValid: isQR, value: tv3 }; }; if (Fp2.ORDER % _4n2 === _3n2) { const c12 = (Fp2.ORDER - _3n2) / _4n2; const c22 = Fp2.sqrt(Fp2.neg(Z)); sqrtRatio = (u, v) => { let tv1 = Fp2.sqr(v); const tv2 = Fp2.mul(u, v); tv1 = Fp2.mul(tv1, tv2); let y1 = Fp2.pow(tv1, c12); y1 = Fp2.mul(y1, tv2); const y2 = Fp2.mul(y1, c22); const tv3 = Fp2.mul(Fp2.sqr(y1), v); const isQR = Fp2.eql(tv3, u); let y = Fp2.cmov(y2, y1, isQR); return { isValid: isQR, value: y }; }; } return sqrtRatio; } function mapToCurveSimpleSWU(Fp2, opts) { validateField(Fp2); if (!Fp2.isValid(opts.A) || !Fp2.isValid(opts.B) || !Fp2.isValid(opts.Z)) throw new Error("mapToCurveSimpleSWU: invalid opts"); const sqrtRatio = SWUFpSqrtRatio(Fp2, opts.Z); if (!Fp2.isOdd) throw new Error("Fp.isOdd is not implemented!"); return (u) => { let tv1, tv2, tv3, tv4, tv5, tv6, x, y; tv1 = Fp2.sqr(u); tv1 = Fp2.mul(tv1, opts.Z); tv2 = Fp2.sqr(tv1); tv2 = Fp2.add(tv2, tv1); tv3 = Fp2.add(tv2, Fp2.ONE); tv3 = Fp2.mul(tv3, opts.B); tv4 = Fp2.cmov(opts.Z, Fp2.neg(tv2), !Fp2.eql(tv2, Fp2.ZERO)); tv4 = Fp2.mul(tv4, opts.A); tv2 = Fp2.sqr(tv3); tv6 = Fp2.sqr(tv4); tv5 = Fp2.mul(tv6, opts.A); tv2 = Fp2.add(tv2, tv5); tv2 = Fp2.mul(tv2, tv3); tv6 = Fp2.mul(tv6, tv4); tv5 = Fp2.mul(tv6, opts.B); tv2 = Fp2.add(tv2, tv5); x = Fp2.mul(tv1, tv3); const { isValid, value } = sqrtRatio(tv2, tv6); y = Fp2.mul(tv1, u); y = Fp2.mul(y, value); x = Fp2.cmov(x, tv3, isValid); y = Fp2.cmov(y, value, isValid); const e1 = Fp2.isOdd(u) === Fp2.isOdd(y); y = Fp2.cmov(Fp2.neg(y), y, e1); x = Fp2.div(x, tv4); return { x, y }; }; } // node_modules/@noble/curves/esm/_shortw_utils.js function getHash(hash2) { return { hash: hash2, hmac: (key, ...msgs) => hmac(hash2, key, concatBytes2(...msgs)), randomBytes }; } function createCurve(curveDef, defHash) { const create = (hash2) => weierstrass({ ...curveDef, ...getHash(hash2) }); return Object.freeze({ ...create(defHash), create }); } // node_modules/@noble/curves/esm/abstract/hash-to-curve.js var os2ip = bytesToNumberBE; function i2osp(value, length) { anum(value); anum(length); if (value < 0 || value >= 1 << 8 * length) { throw new Error(`bad I2OSP call: value=${value} length=${length}`); } const res = Array.from({ length }).fill(0); for (let i = length - 1; i >= 0; i--) { res[i] = value & 255; value >>>= 8; } return new Uint8Array(res); } function strxor(a, b) { const arr = new Uint8Array(a.length); for (let i = 0; i < a.length; i++) { arr[i] = a[i] ^ b[i]; } return arr; } function anum(item) { if (!Number.isSafeInteger(item)) throw new Error("number expected"); } function expand_message_xmd(msg, DST, lenInBytes, H) { abytes(msg); abytes(DST); anum(lenInBytes); if (DST.length > 255) DST = H(concatBytes(utf8ToBytes("H2C-OVERSIZE-DST-"), DST)); const { outputLen: b_in_bytes, blockLen: r_in_bytes } = H; const ell = Math.ceil(lenInBytes / b_in_bytes); if (lenInBytes > 65535 || ell > 255) throw new Error("expand_message_xmd: invalid lenInBytes"); const DST_prime = concatBytes(DST, i2osp(DST.length, 1)); const Z_pad = i2osp(0, r_in_bytes); const l_i_b_str = i2osp(lenInBytes, 2); const b = new Array(ell); const b_0 = H(concatBytes(Z_pad, msg, l_i_b_str, i2osp(0, 1), DST_prime)); b[0] = H(concatBytes(b_0, i2osp(1, 1), DST_prime)); for (let i = 1; i <= ell; i++) { const args = [strxor(b_0, b[i - 1]), i2osp(i + 1, 1), DST_prime]; b[i] = H(concatBytes(...args)); } const pseudo_random_bytes = concatBytes(...b); return pseudo_random_bytes.slice(0, lenInBytes); } function expand_message_xof(msg, DST, lenInBytes, k, H) { abytes(msg); abytes(DST); anum(lenInBytes); if (DST.length > 255) { const dkLen = Math.ceil(2 * k / 8); DST = H.create({ dkLen }).update(utf8ToBytes("H2C-OVERSIZE-DST-")).update(DST).digest(); } if (lenInBytes > 65535 || DST.length > 255) throw new Error("expand_message_xof: invalid lenInBytes"); return H.create({ dkLen: lenInBytes }).update(msg).update(i2osp(lenInBytes, 2)).update(DST).update(i2osp(DST.length, 1)).digest(); } function hash_to_field(msg, count, options) { validateObject(options, { DST: "stringOrUint8Array", p: "bigint", m: "isSafeInteger", k: "isSafeInteger", hash: "hash" }); const { p, k, m, hash: hash2, expand, DST: _DST } = options; abytes(msg); anum(count); const DST = typeof _DST === "string" ? utf8ToBytes(_DST) : _DST; const log2p = p.toString(2).length; const L = Math.ceil((log2p + k) / 8); const len_in_bytes = count * m * L; let prb; if (expand === "xmd") { prb = expand_message_xmd(msg, DST, len_in_bytes, hash2); } else if (expand === "xof") { prb = expand_message_xof(msg, DST, len_in_bytes, k, hash2); } else if (expand === "_internal_pass") { prb = msg; } else { throw new Error('expand must be "xmd" or "xof"'); } const u = new Array(count); for (let i = 0; i < count; i++) { const e = new Array(m); for (let j = 0; j < m; j++) { const elm_offset = L * (j + i * m); const tv = prb.subarray(elm_offset, elm_offset + L); e[j] = mod(os2ip(tv), p); } u[i] = e; } return u; } function isogenyMap(field, map) { const COEFF = map.map((i) => Array.from(i).reverse()); return (x, y) => { const [xNum, xDen, yNum, yDen] = COEFF.map((val) => val.reduce((acc, i) => field.add(field.mul(acc, x), i))); x = field.div(xNum, xDen); y = field.mul(y, field.div(yNum, yDen)); return { x, y }; }; } function createHasher(Point2, mapToCurve, def) { if (typeof mapToCurve !== "function") throw new Error("mapToCurve() must be defined"); return { // Encodes byte string to elliptic curve. // hash_to_curve from https://www.rfc-editor.org/rfc/rfc9380#section-3 hashToCurve(msg, options) { const u = hash_to_field(msg, 2, { ...def, DST: def.DST, ...options }); const u0 = Point2.fromAffine(mapToCurve(u[0])); const u1 = Point2.fromAffine(mapToCurve(u[1])); const P = u0.add(u1).clearCofactor(); P.assertValidity(); return P; }, // Encodes byte string to elliptic curve. // encode_to_curve from https://www.rfc-editor.org/rfc/rfc9380#section-3 encodeToCurve(msg, options) { const u = hash_to_field(msg, 1, { ...def, DST: def.encodeDST, ...options }); const P = Point2.fromAffine(mapToCurve(u[0])).clearCofactor(); P.assertValidity(); return P; }, // Same as encodeToCurve, but without hash mapToCurve(scalars) { if (!Array.isArray(scalars)) throw new Error("mapToCurve: expected array of bigints"); for (const i of scalars) if (typeof i !== "bigint") throw new Error(`mapToCurve: expected array of bigints, got ${i} in array`); const P = Point2.fromAffine(mapToCurve(scalars)).clearCofactor(); P.assertValidity(); return P; } }; } // node_modules/@noble/curves/esm/secp256k1.js var secp256k1P = BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"); var secp256k1N = BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"); var _1n4 = BigInt(1); var _2n3 = BigInt(2); var divNearest = (a, b) => (a + b / _2n3) / b; function sqrtMod(y) { const P = secp256k1P; const _3n3 = BigInt(3), _6n = BigInt(6), _11n = BigInt(11), _22n = BigInt(22); const _23n = BigInt(23), _44n = BigInt(44), _88n = BigInt(88); const b2 = y * y * y % P; const b3 = b2 * b2 * y % P; const b6 = pow2(b3, _3n3, P) * b3 % P; const b9 = pow2(b6, _3n3, P) * b3 % P; const b11 = pow2(b9, _2n3, P) * b2 % P; const b22 = pow2(b11, _11n, P) * b11 % P; const b44 = pow2(b22, _22n, P) * b22 % P; const b88 = pow2(b44, _44n, P) * b44 % P; const b176 = pow2(b88, _88n, P) * b88 % P; const b220 = pow2(b176, _44n, P) * b44 % P; const b223 = pow2(b220, _3n3, P) * b3 % P; const t1 = pow2(b223, _23n, P) * b22 % P; const t2 = pow2(t1, _6n, P) * b2 % P; const root = pow2(t2, _2n3, P); if (!Fp.eql(Fp.sqr(root), y)) throw new Error("Cannot find square root"); return root; } var Fp = Field(secp256k1P, void 0, void 0, { sqrt: sqrtMod }); var secp256k1 = createCurve({ a: BigInt(0), // equation params: a, b b: BigInt(7), // Seem to be rigid: bitcointalk.org/index.php?topic=289795.msg3183975#msg3183975 Fp, // Field's prime: 2n**256n - 2n**32n - 2n**9n - 2n**8n - 2n**7n - 2n**6n - 2n**4n - 1n n: secp256k1N, // Curve order, total count of valid points in the field // Base point (x, y) aka generator point Gx: BigInt("55066263022277343669578718895168534326250603453777594175500187360389116729240"), Gy: BigInt("32670510020758816978083085130507043184471273380659243275938904335757337482424"), h: BigInt(1), // Cofactor lowS: true, // Allow only low-S signatures by default in sign() and verify() /** * secp256k1 belongs to Koblitz curves: it has efficiently computable endomorphism. * Endomorphism uses 2x less RAM, speeds up precomputation by 2x and ECDH / key recovery by 20%. * For precomputed wNAF it trades off 1/2 init time & 1/3 ram for 20% perf hit. * Explanation: https://gist.github.com/paulmillr/eb670806793e84df628a7c434a873066 */ endo: { beta: BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"), splitScalar: (k) => { const n = secp256k1N; const a1 = BigInt("0x3086d221a7d46bcde86c90e49284eb15"); const b1 = -_1n4 * BigInt("0xe4437ed6010e88286f547fa90abfe4c3"); const a2 = BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"); const b2 = a1; const POW_2_128 = BigInt("0x100000000000000000000000000000000"); const c1 = divNearest(b2 * k, n); const c2 = divNearest(-b1 * k, n); let k1 = mod(k - c1 * a1 - c2 * a2, n); let k2 = mod(-c1 * b1 - c2 * b2, n); const k1neg = k1 > POW_2_128; const k2neg = k2 > POW_2_128; if (k1neg) k1 = n - k1; if (k2neg) k2 = n - k2; if (k1 > POW_2_128 || k2 > POW_2_128) { throw new Error("splitScalar: Endomorphism failed, k=" + k); } return { k1neg, k1, k2neg, k2 }; } } }, sha256); var _0n4 = BigInt(0); var TAGGED_HASH_PREFIXES = {}; function taggedHash(tag, ...messages) { let tagP = TAGGED_HASH_PREFIXES[tag]; if (tagP === void 0) { const tagH = sha256(Uint8Array.from(tag, (c) => c.charCodeAt(0))); tagP = concatBytes(tagH, tagH); TAGGED_HASH_PREFIXES[tag] = tagP; } return sha256(concatBytes(tagP, ...messages)); } var pointToBytes = (point) => point.toRawBytes(true).slice(1); var numTo32b = (n) => numberToBytesBE(n, 32); var modP = (x) => mod(x, secp256k1P); var modN = (x) => mod(x, secp256k1N); var Point = secp256k1.ProjectivePoint; var GmulAdd = (Q, a, b) => Point.BASE.multiplyAndAddUnsafe(Q, a, b); function schnorrGetExtPubKey(priv) { let d_ = secp256k1.utils.normPrivateKeyToScalar(priv); let p = Point.fromPrivateKey(d_); const scalar = p.hasEvenY() ? d_ : modN(-d_); return { scalar, bytes: pointToBytes(p) }; } function lift_x(x) { aInRange("x", x, _1n4, secp256k1P); const xx = modP(x * x); const c = modP(xx * x + BigInt(7)); let y = sqrtMod(c); if (y % _2n3 !== _0n4) y = modP(-y); const p = new Point(x, y, _1n4); p.assertValidity(); return p; } var num = bytesToNumberBE; function challenge(...args) { return modN(num(taggedHash("BIP0340/challenge", ...args))); } function schnorrGetPublicKey(privateKey) { return schnorrGetExtPubKey(privateKey).bytes; } function schnorrSign(message, privateKey, auxRand = randomBytes(32)) { const m = ensureBytes("message", message); const { bytes: px, scalar: d } = schnorrGetExtPubKey(privateKey); const a = ensureBytes("auxRand", auxRand, 32); const t = numTo32b(d ^ num(taggedHash("BIP0340/aux", a))); const rand = taggedHash("BIP0340/nonce", t, px, m); const k_ = modN(num(rand)); if (k_ === _0n4) throw new Error("sign failed: k is zero"); const { bytes: rx, scalar: k } = schnorrGetExtPubKey(k_); const e = challenge(rx, px, m); const sig = new Uint8Array(64); sig.set(rx, 0); sig.set(numTo32b(modN(k + e * d)), 32); if (!schnorrVerify(sig, m, px)) throw new Error("sign: Invalid signature produced"); return sig; } function schnorrVerify(signature, message, publicKey) { const sig = ensureBytes("signature", signature, 64); const m = ensureBytes("message", message); const pub = ensureBytes("publicKey", publicKey, 32); try { const P = lift_x(num(pub)); const r = num(sig.subarray(0, 32)); if (!inRange(r, _1n4, secp256k1P)) return false; const s = num(sig.subarray(32, 64)); if (!inRange(s, _1n4, secp256k1N)) return false; const e = challenge(numTo32b(r), pointToBytes(P), m); const R = GmulAdd(P, s, modN(-e)); if (!R || !R.hasEvenY() || R.toAffine().x !== r) return false; return true; } catch (error) { return false; } } var schnorr = (() => ({ getPublicKey: schnorrGetPublicKey, sign: schnorrSign, verify: schnorrVerify, utils: { randomPrivateKey: secp256k1.utils.randomPrivateKey, lift_x, pointToBytes, numberToBytesBE, bytesToNumberBE, taggedHash, mod } }))(); var isoMap = (() => isogenyMap(Fp, [ // xNum [ "0x8e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38daaaaa8c7", "0x7d3d4c80bc321d5b9f315cea7fd44c5d595d2fc0bf63b92dfff1044f17c6581", "0x534c328d23f234e6e2a413deca25caece4506144037c40314ecbd0b53d9dd262", "0x8e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38daaaaa88c" ], // xDen [ "0xd35771193d94918a9ca34ccbb7b640dd86cd409542f8487d9fe6b745781eb49b", "0xedadc6f64383dc1df7c4b2d51b54225406d36b641f5e41bbc52a56612a8c6d14", "0x0000000000000000000000000000000000000000000000000000000000000001" // LAST 1 ], // yNum [ "0x4bda12f684bda12f684bda12f684bda12f684bda12f684bda12f684b8e38e23c", "0xc75e0c32d5cb7c0fa9d0a54b12a0a6d5647ab046d686da6fdffc90fc201d71a3", "0x29a6194691f91a73715209ef6512e576722830a201be2018a765e85a9ecee931", "0x2f684bda12f684bda12f684bda12f684bda12f684bda12f684bda12f38e38d84" ], // yDen [ "0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffff93b", "0x7a06534bb8bdb49fd5e9e6632722c2989467c1bfc8e8d978dfb425d2685c2573", "0x6484aa716545ca2cf3a70c3fa8fe337e0a3d21162f0d6299a7bf8192bfd2a76f", "0x0000000000000000000000000000000000000000000000000000000000000001" // LAST 1 ] ].map((i) => i.map((j) => BigInt(j)))))(); var mapSWU = (() => mapToCurveSimpleSWU(Fp, { A: BigInt("0x3f8731abdd661adca08a5558f0f5d272e953d363cb6f0e5d405447c01a444533"), B: BigInt("1771"), Z: Fp.create(BigInt("-11")) }))(); var htf = (() => createHasher(secp256k1.ProjectivePoint, (scalars) => { const { x, y } = mapSWU(Fp.create(scalars[0])); return isoMap(x, y); }, { DST: "secp256k1_XMD:SHA-256_SSWU_RO_", encodeDST: "secp256k1_XMD:SHA-256_SSWU_NU_", p: Fp.ORDER, m: 1, k: 128, expand: "xmd", hash: sha256 }))(); var hashToCurve = (() => htf.hashToCurve)(); var encodeToCurve = (() => htf.encodeToCurve)(); export { secp256k1, schnorr, hashToCurve, encodeToCurve }; /*! Bundled license information: @noble/curves/esm/abstract/modular.js: (*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) *) @noble/curves/esm/abstract/curve.js: (*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) *) @noble/curves/esm/abstract/weierstrass.js: (*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) *) @noble/curves/esm/_shortw_utils.js: (*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) *) @noble/curves/esm/secp256k1.js: (*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) *) */ //# sourceMappingURL=chunk-7EY5MWB2.js.map ================================================ FILE: 17-Crowd-Funding-Dapp/Frontend/.vite/deps_temp_6cf5ba4c/chunk-7QDK5KLB.js ================================================ // node_modules/thirdweb/dist/esm/transaction/actions/encode.js var encodeWeakMap = /* @__PURE__ */ new WeakMap(); async function encode(transaction) { if (encodeWeakMap.has(transaction)) { return encodeWeakMap.get(transaction); } const promise = (async () => { const [data, extraData, { concatHex }] = await Promise.all([ getDataFromTx(transaction), getExtraCallDataFromTx(transaction), import("./concat-hex-2F4R6DIF.js") ]); if (extraData) { return concatHex([data, extraData]); } return data; })(); encodeWeakMap.set(transaction, promise); return promise; } async function getDataFromTx(transaction) { if (transaction.data === void 0) { return "0x"; } if (typeof transaction.data === "function") { const data = await transaction.data(); if (!data) { return "0x"; } return data; } return transaction.data; } async function getExtraCallDataFromTx(transaction) { if (!transaction.extraCallData) { return void 0; } if (typeof transaction.extraCallData === "function") { const extraData = await transaction.extraCallData(); if (!extraData) return void 0; if (!extraData.startsWith("0x")) { throw Error("Invalid extra calldata - must be a hex string"); } if (extraData === "0x") { return void 0; } return extraData; } if (!transaction.extraCallData.startsWith("0x")) { throw Error("Invalid extra calldata - must be a hex string"); } return transaction.extraCallData; } export { encode, getDataFromTx, getExtraCallDataFromTx }; //# sourceMappingURL=chunk-7QDK5KLB.js.map ================================================ FILE: 17-Crowd-Funding-Dapp/Frontend/.vite/deps_temp_6cf5ba4c/chunk-7VZHRFCE.js ================================================ // node_modules/thirdweb/dist/esm/contract/contract.js function getContract(options) { return options; } export { getContract }; //# sourceMappingURL=chunk-7VZHRFCE.js.map ================================================ FILE: 17-Crowd-Funding-Dapp/Frontend/.vite/deps_temp_6cf5ba4c/chunk-7ZCK2FX5.js ================================================ // node_modules/thirdweb/dist/esm/utils/any-evm/zksync/isZkSyncChain.js async function isZkSyncChain(chain) { if (chain.id === 1337 || chain.id === 31337) { return false; } if (chain.id === 324 || chain.id === 300 || chain.id === 302 || chain.id === 11124 || chain.id === 282 || chain.id === 388 || chain.id === 4654 || chain.id === 333271 || chain.id === 37111 || chain.id === 978658 || chain.id === 531050104 || chain.id === 4457845 || chain.id === 2741) { return true; } try { const { getChainMetadata } = await import("./utils-RIDKW7H5.js"); const chainMetadata = await getChainMetadata(chain); return chainMetadata.stackType === "zksync_stack"; } catch { return false; } } export { isZkSyncChain }; //# sourceMappingURL=chunk-7ZCK2FX5.js.map ================================================ FILE: 17-Crowd-Funding-Dapp/Frontend/.vite/deps_temp_6cf5ba4c/chunk-7ZNEOXS2.js ================================================ import { LoadingScreen, TextDivider, WalletTypeRowButton, compactModalMaxHeight, openOauthSignInWindow, useScreenContext } from "./chunk-KWA5PGSC.js"; import { ConnectingScreen } from "./chunk-MGEBXLXC.js"; import { linkProfile, preAuthenticate } from "./chunk-65EUCVOP.js"; import { AllWalletsUI_default, createWallet, isAndroid, isIOS, isMobile, openWindow, sortWallets } from "./chunk-HO57TQQM.js"; import { Spinner, WalletButtonEl, WalletEntryButton, useSetSelectionData } from "./chunk-AARWH2GQ.js"; import { Button, ButtonLink, CheckIcon, ChevronLeftIcon, Container, CopyIcon, ExclamationTriangleIcon, ExternalLinkIcon, FingerPrintIcon, IconButton, Img, Line, Link, ModalHeader, ModalTitle, OutlineWalletIcon, ScreenBottomContainer, Spacer, StyledButton, StyledDiv, StyledUl, Text, WalletImage, fadeInAnimation, fontSize, iconSize, keyframes, noScrollBar, radius, setLastAuthProvider, spacing, useConnectionManager, useConnectionManagerCtx, useCustomTheme, useQuery, useWalletInfo } from "./chunk-HI6IFF64.js"; import { require_jsx_runtime } from "./chunk-U3QNWT4A.js"; import { formatWalletConnectUrl } from "./chunk-5U5XBS6S.js"; import { isEcosystemWallet } from "./chunk-XC5J5ANL.js"; import { getInstalledWalletProviders } from "./chunk-PWFRCBEK.js"; import { COINBASE, METAMASK, RAINBOW, ZERION } from "./chunk-BZXRHH4X.js"; import { hasStoredPasskey } from "./chunk-XTOEMUZK.js"; import { loginWithOauthRedirect } from "./chunk-J7FYPWA5.js"; import { webLocalStorage } from "./chunk-VIBS7Y3M.js"; import { require_react } from "./chunk-2MTJELC7.js"; import { defineChain } from "./chunk-TFBEDS4S.js"; import { __toESM } from "./chunk-SEVZ5PBP.js"; // node_modules/thirdweb/dist/esm/react/web/wallets/shared/GuestLogin.js var import_jsx_runtime = __toESM(require_jsx_runtime(), 1); var import_react = __toESM(require_react(), 1); function GuestLogin(props) { var _a; const ewLocale = props.locale; const locale = ewLocale.socialLoginScreen; const [authError, setAuthError] = (0, import_react.useState)(void 0); const { done, wallet } = props; const [status, setStatus] = (0, import_react.useState)("connecting"); const handleGuestLogin = async () => { var _a2, _b; const connectOptions = { client: props.client, ecosystem: isEcosystemWallet(wallet) ? { id: wallet.id, partnerId: (_a2 = wallet.getConfig()) == null ? void 0 : _a2.partnerId } : void 0, strategy: "guest" }; try { await wallet.connect(connectOptions); await setLastAuthProvider("guest", webLocalStorage); setStatus("connected"); done(); } catch (e) { setStatus("error"); if (e instanceof Error && ((_b = e == null ? void 0 : e.message) == null ? void 0 : _b.includes("PAYMENT_METHOD_REQUIRED"))) { setAuthError(ewLocale.maxAccountsExceeded); } console.error("Error generating guest account", e); } }; const guestLogin = (_a = props.state) == null ? void 0 : _a.guestLogin; const socialLoginStarted = (0, import_react.useRef)(false); (0, import_react.useEffect)(() => { if (socialLoginStarted.current) { return; } if (guestLogin) { socialLoginStarted.current = true; setStatus("connecting"); guestLogin.connectionPromise.then(() => { done(); setStatus("connected"); }).catch((e) => { setAuthError(e.message); setStatus("error"); }); } }, [done, guestLogin]); return (0, import_jsx_runtime.jsx)(Container, { animate: "fadein", flex: "column", fullHeight: true, children: (0, import_jsx_runtime.jsxs)(Container, { flex: "column", expand: true, p: "lg", style: { paddingBottom: 0 }, children: [props.goBack && (0, import_jsx_runtime.jsx)(ModalHeader, { title: locale.title, onBack: props.goBack }), props.size === "compact" ? (0, import_jsx_runtime.jsx)(Spacer, { y: "xl" }) : null, (0, import_jsx_runtime.jsxs)(Container, { flex: "column", center: "both", expand: true, style: { textAlign: "center", minHeight: "250px" }, children: [status !== "error" && (0, import_jsx_runtime.jsxs)(Container, { animate: "fadein", children: [(0, import_jsx_runtime.jsx)(Text, { color: "primaryText", center: true, multiline: true, style: { maxWidth: "250px" }, children: "Generating your guest account" }), (0, import_jsx_runtime.jsx)(Spacer, { y: "xl" }), (0, import_jsx_runtime.jsx)(Container, { center: "x", flex: "row", children: (0, import_jsx_runtime.jsx)(Spinner, { size: "lg", color: "accentText" }) }), (0, import_jsx_runtime.jsx)(Spacer, { y: "xxl" })] }), status === "error" && (0, import_jsx_runtime.jsxs)(Container, { animate: "fadein", children: [authError ? (0, import_jsx_runtime.jsx)(Text, { center: true, color: "danger", children: authError }) : (0, import_jsx_runtime.jsx)(Text, { color: "danger", children: locale.failed }), (0, import_jsx_runtime.jsx)(Spacer, { y: "lg" }), (0, import_jsx_runtime.jsx)(Button, { variant: "primary", onClick: handleGuestLogin, children: locale.retry }), (0, import_jsx_runtime.jsx)(Spacer, { y: "xxl" })] })] })] }) }); } // node_modules/thirdweb/dist/esm/react/web/wallets/shared/OTPLoginUI.js var import_jsx_runtime3 = __toESM(require_jsx_runtime(), 1); var import_react3 = __toESM(require_react(), 1); // node_modules/thirdweb/dist/esm/react/web/ui/components/FadeIn.js var FadeIn = StyledDiv({ animation: `${fadeInAnimation} 0.15s ease-in` }); // node_modules/thirdweb/dist/esm/react/web/ui/components/OTPInput.js var import_jsx_runtime2 = __toESM(require_jsx_runtime(), 1); // node_modules/input-otp/dist/index.mjs var n = __toESM(require_react(), 1); var U = __toESM(require_react(), 1); var S = __toESM(require_react(), 1); var Bt = Object.defineProperty; var At = Object.defineProperties; var kt = Object.getOwnPropertyDescriptors; var Y = Object.getOwnPropertySymbols; var gt = Object.prototype.hasOwnProperty; var Et = Object.prototype.propertyIsEnumerable; var vt = (r, s, e) => s in r ? Bt(r, s, { enumerable: true, configurable: true, writable: true, value: e }) : r[s] = e; var St = (r, s) => { for (var e in s || (s = {})) gt.call(s, e) && vt(r, e, s[e]); if (Y) for (var e of Y(s)) Et.call(s, e) && vt(r, e, s[e]); return r; }; var bt = (r, s) => At(r, kt(s)); var Pt = (r, s) => { var e = {}; for (var u in r) gt.call(r, u) && s.indexOf(u) < 0 && (e[u] = r[u]); if (r != null && Y) for (var u of Y(r)) s.indexOf(u) < 0 && Et.call(r, u) && (e[u] = r[u]); return e; }; function ht(r) { let s = setTimeout(r, 0), e = setTimeout(r, 10), u = setTimeout(r, 50); return [s, e, u]; } function _t(r) { let s = U.useRef(); return U.useEffect(() => { s.current = r; }), s.current; } var Ot = 18; var wt = 40; var Gt = `${wt}px`; var xt = ["[data-lastpass-icon-root]", "com-1password-button", "[data-dashlanecreated]", '[style$="2147483647 !important;"]'].join(","); function Tt({ containerRef: r, inputRef: s, pushPasswordManagerStrategy: e, isFocused: u }) { let [P, D] = S.useState(false), [G, H] = S.useState(false), [F, W] = S.useState(false), Z = S.useMemo(() => e === "none" ? false : (e === "increase-width" || e === "experimental-no-flickering") && P && G, [P, G, e]), T = S.useCallback(() => { let f = r.current, h = s.current; if (!f || !h || F || e === "none") return; let a = f, B = a.getBoundingClientRect().left + a.offsetWidth, A = a.getBoundingClientRect().top + a.offsetHeight / 2, z = B - Ot, q = A; document.querySelectorAll(xt).length === 0 && document.elementFromPoint(z, q) === f || (D(true), W(true)); }, [r, s, F, e]); return S.useEffect(() => { let f = r.current; if (!f || e === "none") return; function h() { let A = window.innerWidth - f.getBoundingClientRect().right; H(A >= wt); } h(); let a = setInterval(h, 1e3); return () => { clearInterval(a); }; }, [r, e]), S.useEffect(() => { let f = u || document.activeElement === s.current; if (e === "none" || !f) return; let h = setTimeout(T, 0), a = setTimeout(T, 2e3), B = setTimeout(T, 5e3), A = setTimeout(() => { W(true); }, 6e3); return () => { clearTimeout(h), clearTimeout(a), clearTimeout(B), clearTimeout(A); }; }, [s, u, e, T]), { hasPWMBadge: P, willPushPWMBadge: Z, PWM_BADGE_SPACE_WIDTH: Gt }; } var jt = n.createContext({}); var Lt = n.forwardRef((A, B) => { var z = A, { value: r, onChange: s, maxLength: e, textAlign: u = "left", pattern: P, placeholder: D, inputMode: G = "numeric", onComplete: H, pushPasswordManagerStrategy: F = "increase-width", pasteTransformer: W, containerClassName: Z, noScriptCSSFallback: T = Nt, render: f, children: h } = z, a = Pt(z, ["value", "onChange", "maxLength", "textAlign", "pattern", "placeholder", "inputMode", "onComplete", "pushPasswordManagerStrategy", "pasteTransformer", "containerClassName", "noScriptCSSFallback", "render", "children"]); var X, lt, ut, dt, ft; let [q, nt] = n.useState(typeof a.defaultValue == "string" ? a.defaultValue : ""), i = r != null ? r : q, I = _t(i), x = n.useCallback((t) => { s == null || s(t), nt(t); }, [s]), m = n.useMemo(() => P ? typeof P == "string" ? new RegExp(P) : P : null, [P]), l = n.useRef(null), K = n.useRef(null), J = n.useRef({ value: i, onChange: x, isIOS: typeof window != "undefined" && ((lt = (X = window == null ? void 0 : window.CSS) == null ? void 0 : X.supports) == null ? void 0 : lt.call(X, "-webkit-touch-callout", "none")) }), V = n.useRef({ prev: [(ut = l.current) == null ? void 0 : ut.selectionStart, (dt = l.current) == null ? void 0 : dt.selectionEnd, (ft = l.current) == null ? void 0 : ft.selectionDirection] }); n.useImperativeHandle(B, () => l.current, []), n.useEffect(() => { let t = l.current, o = K.current; if (!t || !o) return; J.current.value !== t.value && J.current.onChange(t.value), V.current.prev = [t.selectionStart, t.selectionEnd, t.selectionDirection]; function d() { if (document.activeElement !== t) { L(null), N(null); return; } let c = t.selectionStart, b = t.selectionEnd, mt = t.selectionDirection, v = t.maxLength, C = t.value, _ = V.current.prev, g = -1, E = -1, w; if (C.length !== 0 && c !== null && b !== null) { let Dt = c === b, Ht = c === C.length && C.length < v; if (Dt && !Ht) { let y = c; if (y === 0) g = 0, E = 1, w = "forward"; else if (y === v) g = y - 1, E = y, w = "backward"; else if (v > 1 && C.length > 1) { let et = 0; if (_[0] !== null && _[1] !== null) { w = y < _[1] ? "backward" : "forward"; let Wt = _[0] === _[1] && _[0] < v; w === "backward" && !Wt && (et = -1); } g = et + y, E = et + y + 1; } } g !== -1 && E !== -1 && g !== E && l.current.setSelectionRange(g, E, w); } let pt = g !== -1 ? g : c, Rt = E !== -1 ? E : b, yt = w != null ? w : mt; L(pt), N(Rt), V.current.prev = [pt, Rt, yt]; } if (document.addEventListener("selectionchange", d, { capture: true }), d(), document.activeElement === t && Q(true), !document.getElementById("input-otp-style")) { let c = document.createElement("style"); if (c.id = "input-otp-style", document.head.appendChild(c), c.sheet) { let b = "background: transparent !important; color: transparent !important; border-color: transparent !important; opacity: 0 !important; box-shadow: none !important; -webkit-box-shadow: none !important; -webkit-text-fill-color: transparent !important;"; $(c.sheet, "[data-input-otp]::selection { background: transparent !important; color: transparent !important; }"), $(c.sheet, `[data-input-otp]:autofill { ${b} }`), $(c.sheet, `[data-input-otp]:-webkit-autofill { ${b} }`), $(c.sheet, "@supports (-webkit-touch-callout: none) { [data-input-otp] { letter-spacing: -.6em !important; font-weight: 100 !important; font-stretch: ultra-condensed; font-optical-sizing: none !important; left: -1px !important; right: 1px !important; } }"), $(c.sheet, "[data-input-otp] + * { pointer-events: all !important; }"); } } let p = () => { o && o.style.setProperty("--root-height", `${t.clientHeight}px`); }; p(); let R = new ResizeObserver(p); return R.observe(t), () => { document.removeEventListener("selectionchange", d, { capture: true }), R.disconnect(); }; }, []); let [ot, rt] = n.useState(false), [j, Q] = n.useState(false), [M, L] = n.useState(null), [k, N] = n.useState(null); n.useEffect(() => { ht(() => { var p, R, c, b; (p = l.current) == null || p.dispatchEvent(new Event("input")); let t = (R = l.current) == null ? void 0 : R.selectionStart, o = (c = l.current) == null ? void 0 : c.selectionEnd, d = (b = l.current) == null ? void 0 : b.selectionDirection; t !== null && o !== null && (L(t), N(o), V.current.prev = [t, o, d]); }); }, [i, j]), n.useEffect(() => { I !== void 0 && i !== I && I.length < e && i.length === e && (H == null || H(i)); }, [e, H, I, i]); let O = Tt({ containerRef: K, inputRef: l, pushPasswordManagerStrategy: F, isFocused: j }), st = n.useCallback((t) => { let o = t.currentTarget.value.slice(0, e); if (o.length > 0 && m && !m.test(o)) { t.preventDefault(); return; } typeof I == "string" && o.length < I.length && document.dispatchEvent(new Event("selectionchange")), x(o); }, [e, x, I, m]), at = n.useCallback(() => { var t; if (l.current) { let o = Math.min(l.current.value.length, e - 1), d = l.current.value.length; (t = l.current) == null || t.setSelectionRange(o, d), L(o), N(d); } Q(true); }, [e]), ct = n.useCallback((t) => { var g, E; let o = l.current; if (!W && (!J.current.isIOS || !t.clipboardData || !o)) return; let d = t.clipboardData.getData("text/plain"), p = W ? W(d) : d; console.log({ _content: d, content: p }), t.preventDefault(); let R = (g = l.current) == null ? void 0 : g.selectionStart, c = (E = l.current) == null ? void 0 : E.selectionEnd, v = (R !== c ? i.slice(0, R) + p + i.slice(c) : i.slice(0, R) + p + i.slice(R)).slice(0, e); if (v.length > 0 && m && !m.test(v)) return; o.value = v, x(v); let C = Math.min(v.length, e - 1), _ = v.length; o.setSelectionRange(C, _), L(C), N(_); }, [e, x, m, i]), It = n.useMemo(() => ({ position: "relative", cursor: a.disabled ? "default" : "text", userSelect: "none", WebkitUserSelect: "none", pointerEvents: "none" }), [a.disabled]), it = n.useMemo(() => ({ position: "absolute", inset: 0, width: O.willPushPWMBadge ? `calc(100% + ${O.PWM_BADGE_SPACE_WIDTH})` : "100%", clipPath: O.willPushPWMBadge ? `inset(0 ${O.PWM_BADGE_SPACE_WIDTH} 0 0)` : void 0, height: "100%", display: "flex", textAlign: u, opacity: "1", color: "transparent", pointerEvents: "all", background: "transparent", caretColor: "transparent", border: "0 solid transparent", outline: "0 solid transparent", boxShadow: "none", lineHeight: "1", letterSpacing: "-.5em", fontSize: "var(--root-height)", fontFamily: "monospace", fontVariantNumeric: "tabular-nums" }), [O.PWM_BADGE_SPACE_WIDTH, O.willPushPWMBadge, u]), Mt = n.useMemo(() => n.createElement("input", bt(St({ autoComplete: a.autoComplete || "one-time-code" }, a), { "data-input-otp": true, "data-input-otp-placeholder-shown": i.length === 0 || void 0, "data-input-otp-mss": M, "data-input-otp-mse": k, inputMode: G, pattern: m == null ? void 0 : m.source, "aria-placeholder": D, style: it, maxLength: e, value: i, ref: l, onPaste: (t) => { var o; ct(t), (o = a.onPaste) == null || o.call(a, t); }, onChange: st, onMouseOver: (t) => { var o; rt(true), (o = a.onMouseOver) == null || o.call(a, t); }, onMouseLeave: (t) => { var o; rt(false), (o = a.onMouseLeave) == null || o.call(a, t); }, onFocus: (t) => { var o; at(), (o = a.onFocus) == null || o.call(a, t); }, onBlur: (t) => { var o; Q(false), (o = a.onBlur) == null || o.call(a, t); } })), [st, at, ct, G, it, e, k, M, a, m == null ? void 0 : m.source, i]), tt = n.useMemo(() => ({ slots: Array.from({ length: e }).map((t, o) => { var c; let d = j && M !== null && k !== null && (M === k && o === M || o >= M && o < k), p = i[o] !== void 0 ? i[o] : null, R = i[0] !== void 0 ? null : (c = D == null ? void 0 : D[o]) != null ? c : null; return { char: p, placeholderChar: R, isActive: d, hasFakeCaret: d && p === null }; }), isFocused: j, isHovering: !a.disabled && ot }), [j, ot, e, k, M, a.disabled, i]), Ct = n.useMemo(() => f ? f(tt) : n.createElement(jt.Provider, { value: tt }, h), [h, tt, f]); return n.createElement(n.Fragment, null, T !== null && n.createElement("noscript", null, n.createElement("style", null, T)), n.createElement("div", { ref: K, "data-input-otp-container": true, style: It, className: Z }, Ct, n.createElement("div", { style: { position: "absolute", inset: 0, pointerEvents: "none" } }, Mt))); }); Lt.displayName = "Input"; function $(r, s) { try { r.insertRule(s); } catch (e) { console.error("input-otp could not insert CSS rule:", s); } } var Nt = ` [data-input-otp] { --nojs-bg: white !important; --nojs-fg: black !important; background-color: var(--nojs-bg) !important; color: var(--nojs-fg) !important; caret-color: var(--nojs-fg) !important; letter-spacing: .25em !important; text-align: center !important; border: 1px solid var(--nojs-fg) !important; border-radius: 4px !important; width: 100% !important; } @media (prefers-color-scheme: dark) { [data-input-otp] { --nojs-bg: black !important; --nojs-fg: white !important; } }`; // node_modules/thirdweb/dist/esm/react/web/ui/components/OTPInput.js function OTPInput(props) { return (0, import_jsx_runtime2.jsx)(OTPInputContainer, { children: (0, import_jsx_runtime2.jsx)(Lt, { onComplete: () => { props.onEnter(); }, maxLength: 6, value: props.value, render: ({ slots }) => (0, import_jsx_runtime2.jsx)(Container, { flex: "row", gap: "xs", center: "both", children: slots.map((slot, idx) => ( // biome-ignore lint/suspicious/noArrayIndexKey: index is the only valid key here (0, import_jsx_runtime2.jsx)(Slot, { ...slot, isInvalid: props.isInvalid }, idx) )) }), onChange: (newValue) => { props.setValue(newValue); } }) }); } var OTPInputContainer = StyledDiv({ "& input": { maxWidth: "100%" } }); function Slot(props) { return (0, import_jsx_runtime2.jsxs)(OTPInputBox, { "data-active": props.isActive, "data-error": props.isInvalid, children: [props.char !== null && (0, import_jsx_runtime2.jsx)("div", { children: props.char }), props.hasFakeCaret && (0, import_jsx_runtime2.jsx)(FakeCaret, {})] }); } var caretBlink = keyframes` 0%, 100% { opacity: 0; }, 50% { opacity: 1; } `; var FakeCaret = StyledDiv((_) => { const theme = useCustomTheme(); return { position: "absolute", pointerEvents: "none", inset: 0, display: "flex", alignItems: "center", justifyContent: "center", animation: `${caretBlink} 1s infinite`, "&::before": { content: "''", display: "block", width: "1.5px", height: "1em", backgroundColor: theme.colors.primaryText } }; }); var OTPInputBox = StyledDiv((_) => { const theme = useCustomTheme(); return { position: "relative", width: "40px", height: "40px", textAlign: "center", display: "flex", alignItems: "center", justifyContent: "center", fontSize: fontSize.md, padding: spacing.xs, boxSizing: "border-box", transition: "color 200ms ease", border: `2px solid ${theme.colors.borderColor}`, "&[data-active='true']": { borderColor: theme.colors.accentText }, color: theme.colors.primaryText, borderRadius: radius.lg, "&[data-error='true']": { borderColor: theme.colors.danger } }; }); // node_modules/thirdweb/dist/esm/react/web/wallets/shared/OTPLoginUI.js function OTPLoginUI(props) { var _a; const { wallet, done, goBack, userInfo } = props; const isWideModal = props.size === "wide"; const locale = props.locale; const [otpInput, setOtpInput] = (0, import_react3.useState)(""); const [verifyStatus, setVerifyStatus] = (0, import_react3.useState)("idle"); const [error, setError] = (0, import_react3.useState)(); const [accountStatus, setAccountStatus] = (0, import_react3.useState)("sending"); const ecosystem = isEcosystemWallet(wallet) ? { id: wallet.id, partnerId: (_a = wallet.getConfig()) == null ? void 0 : _a.partnerId } : void 0; const [screen] = (0, import_react3.useState)("base"); const sendEmailOrSms = (0, import_react3.useCallback)(async () => { setOtpInput(""); setVerifyStatus("idle"); setAccountStatus("sending"); try { if ("email" in userInfo) { await preAuthenticate({ ecosystem, email: userInfo.email, strategy: "email", client: props.client }); setAccountStatus("sent"); } else if ("phone" in userInfo) { await preAuthenticate({ ecosystem, phoneNumber: userInfo.phone, strategy: "phone", client: props.client }); setAccountStatus("sent"); } else { throw new Error("Invalid userInfo"); } } catch (e) { console.error(e); setVerifyStatus("idle"); setAccountStatus("error"); } }, [props.client, userInfo, ecosystem]); async function connect(otp) { if ("email" in userInfo) { await wallet.connect({ chain: props.chain, strategy: "email", email: userInfo.email, verificationCode: otp, client: props.client }); await setLastAuthProvider("email", webLocalStorage); } else if ("phone" in userInfo) { await wallet.connect({ chain: props.chain, strategy: "phone", phoneNumber: userInfo.phone, verificationCode: otp, client: props.client }); await setLastAuthProvider("phone", webLocalStorage); } else { throw new Error("Invalid userInfo"); } } async function link(otp) { if ("email" in userInfo) { await linkProfile({ client: props.client, strategy: "email", email: userInfo.email, verificationCode: otp, ecosystem }); } else if ("phone" in userInfo) { await linkProfile({ client: props.client, strategy: "phone", phoneNumber: userInfo.phone, verificationCode: otp, ecosystem }); } } const verify = async (otp) => { var _a2; if (otp.length !== 6) { return; } setVerifyStatus("verifying"); try { if (props.isLinking) { await link(otp); } else { await connect(otp); } done(); setVerifyStatus("valid"); } catch (e) { if (e instanceof Error && ((_a2 = e == null ? void 0 : e.message) == null ? void 0 : _a2.includes("PAYMENT_METHOD_REQUIRED"))) { setVerifyStatus("payment_required"); } else if (e instanceof Error && (e.message.toLowerCase().includes("link") || e.message.toLowerCase().includes("profile"))) { setVerifyStatus("linking_error"); setError(e.message); } else { setVerifyStatus("invalid"); } console.error("Authentication Error", e); } }; const emailSentOnMount = (0, import_react3.useRef)(false); (0, import_react3.useEffect)(() => { if (!emailSentOnMount.current) { emailSentOnMount.current = true; sendEmailOrSms(); } }, [sendEmailOrSms]); if (screen === "base") { return (0, import_jsx_runtime3.jsxs)(Container, { fullHeight: true, flex: "column", animate: "fadein", children: [(0, import_jsx_runtime3.jsx)(Container, { p: "lg", children: (0, import_jsx_runtime3.jsx)(ModalHeader, { title: locale.signIn, onBack: goBack }) }), (0, import_jsx_runtime3.jsx)(Container, { expand: true, flex: "column", center: "y", children: (0, import_jsx_runtime3.jsxs)("form", { onSubmit: (e) => { e.preventDefault(); }, children: [(0, import_jsx_runtime3.jsxs)(Container, { flex: "column", center: "x", px: "lg", children: [!isWideModal && (0, import_jsx_runtime3.jsx)(Spacer, { y: "xl" }), (0, import_jsx_runtime3.jsx)(Text, { children: locale.emailLoginScreen.enterCodeSendTo }), (0, import_jsx_runtime3.jsx)(Spacer, { y: "sm" }), (0, import_jsx_runtime3.jsx)(Text, { color: "primaryText", children: "email" in userInfo ? userInfo.email : userInfo.phone }), (0, import_jsx_runtime3.jsx)(Spacer, { y: "xl" })] }), (0, import_jsx_runtime3.jsx)(OTPInput, { isInvalid: verifyStatus === "invalid", digits: 6, value: otpInput, setValue: (value) => { setOtpInput(value); setVerifyStatus("idle"); }, onEnter: () => { verify(otpInput); } }), verifyStatus === "invalid" && (0, import_jsx_runtime3.jsxs)(FadeIn, { children: [(0, import_jsx_runtime3.jsx)(Spacer, { y: "md" }), (0, import_jsx_runtime3.jsx)(Text, { size: "sm", color: "danger", center: true, children: locale.emailLoginScreen.invalidCode })] }), verifyStatus === "linking_error" && (0, import_jsx_runtime3.jsxs)(FadeIn, { children: [(0, import_jsx_runtime3.jsx)(Spacer, { y: "md" }), (0, import_jsx_runtime3.jsx)(Text, { size: "sm", color: "danger", center: true, children: error || "Failed to verify code" })] }), verifyStatus === "payment_required" && (0, import_jsx_runtime3.jsxs)(FadeIn, { children: [(0, import_jsx_runtime3.jsx)(Spacer, { y: "md" }), (0, import_jsx_runtime3.jsx)(Text, { size: "sm", color: "danger", center: true, children: locale.maxAccountsExceeded })] }), (0, import_jsx_runtime3.jsx)(Spacer, { y: "xl" }), (0, import_jsx_runtime3.jsx)(Container, { px: isWideModal ? "xxl" : "lg", children: verifyStatus === "verifying" ? (0, import_jsx_runtime3.jsx)(import_jsx_runtime3.Fragment, { children: (0, import_jsx_runtime3.jsx)(Container, { flex: "row", center: "x", animate: "fadein", children: (0, import_jsx_runtime3.jsx)(Spinner, { size: "lg", color: "accentText" }) }) }) : (0, import_jsx_runtime3.jsx)(Container, { animate: "fadein", children: (0, import_jsx_runtime3.jsx)(Button, { onClick: () => verify(otpInput), variant: "accent", type: "submit", style: { width: "100%" }, children: locale.emailLoginScreen.verify }) }, "btn-container") }), (0, import_jsx_runtime3.jsx)(Spacer, { y: "xl" }), !isWideModal && (0, import_jsx_runtime3.jsx)(Line, {}), (0, import_jsx_runtime3.jsxs)(Container, { p: isWideModal ? void 0 : "lg", children: [accountStatus === "error" && (0, import_jsx_runtime3.jsx)(Text, { size: "sm", center: true, color: "danger", children: locale.emailLoginScreen.failedToSendCode }), accountStatus === "sending" && (0, import_jsx_runtime3.jsxs)(Container, { flex: "row", center: "both", gap: "xs", style: { textAlign: "center" }, children: [(0, import_jsx_runtime3.jsx)(Text, { size: "sm", children: locale.emailLoginScreen.sendingCode }), (0, import_jsx_runtime3.jsx)(Spinner, { size: "xs", color: "secondaryText" })] }), accountStatus === "sent" && (0, import_jsx_runtime3.jsx)(LinkButton, { onClick: sendEmailOrSms, type: "button", children: locale.emailLoginScreen.resendCode })] })] }) })] }); } return null; } var LinkButton = StyledButton((_) => { const theme = useCustomTheme(); return { all: "unset", color: theme.colors.accentText, fontSize: fontSize.sm, cursor: "pointer", textAlign: "center", fontWeight: 500, width: "100%", "&:hover": { color: theme.colors.primaryText } }; }); // node_modules/thirdweb/dist/esm/react/web/wallets/shared/PassKeyLogin.js var import_jsx_runtime7 = __toESM(require_jsx_runtime(), 1); var import_react4 = __toESM(require_react(), 1); // node_modules/thirdweb/dist/esm/react/web/wallets/shared/ErrorState.js var import_jsx_runtime5 = __toESM(require_jsx_runtime(), 1); // node_modules/thirdweb/dist/esm/react/web/ui/ConnectWallet/icons/AccentFailIcon.js var import_jsx_runtime4 = __toESM(require_jsx_runtime(), 1); var AccentFailIcon = (props) => { return (0, import_jsx_runtime4.jsxs)("svg", { width: props.size, height: props.size, viewBox: "0 0 109 109", fill: "none", xmlns: "http://www.w3.org/2000/svg", role: "presentation", children: [(0, import_jsx_runtime4.jsxs)("g", { clipPath: "url(#clip0_4036_4155)", children: [(0, import_jsx_runtime4.jsx)("path", { d: "M54.5 109C84.5995 109 109 84.5995 109 54.5C109 24.4005 84.5995 0 54.5 0C24.4005 0 0 24.4005 0 54.5C0 84.5995 24.4005 109 54.5 109Z", fill: "#4BABFF" }), (0, import_jsx_runtime4.jsx)("path", { d: "M55 96C77.6437 96 96 77.6437 96 55C96 32.3563 77.6437 14 55 14C32.3563 14 14 32.3563 14 55C14 77.6437 32.3563 96 55 96Z", fill: "#1C85FF" }), (0, import_jsx_runtime4.jsx)("path", { d: "M73.2352 69.389C73.7459 69.8997 74.0329 70.5924 74.0329 71.3147C74.0329 72.037 73.7459 72.7298 73.2352 73.2405C72.7244 73.7513 72.0317 74.0382 71.3094 74.0382C70.5871 74.0382 69.8944 73.7513 69.3836 73.2405L54.9992 58.8515L40.6102 73.236C40.0994 73.7467 39.4067 74.0337 38.6844 74.0337C37.9621 74.0337 37.2694 73.7467 36.7586 73.236C36.2479 72.7252 35.9609 72.0325 35.9609 71.3102C35.9609 70.5879 36.2479 69.8952 36.7586 69.3844L51.1476 55L36.7632 40.611C36.2524 40.1002 35.9655 39.4075 35.9655 38.6852C35.9655 37.9629 36.2524 37.2702 36.7632 36.7594C37.2739 36.2487 37.9666 35.9617 38.6889 35.9617C39.4112 35.9617 40.104 36.2487 40.6147 36.7594L54.9992 51.1484L69.3881 36.7572C69.8989 36.2464 70.5916 35.9595 71.3139 35.9595C72.0362 35.9595 72.729 36.2464 73.2397 36.7572C73.7505 37.2679 74.0374 37.9606 74.0374 38.6829C74.0374 39.4052 73.7505 40.098 73.2397 40.6087L58.8507 55L73.2352 69.389Z", fill: "url(#paint0_linear_4036_4155)" })] }), (0, import_jsx_runtime4.jsxs)("defs", { children: [(0, import_jsx_runtime4.jsxs)("linearGradient", { id: "paint0_linear_4036_4155", x1: "54.9992", y1: "35.9595", x2: "54.9992", y2: "74.0382", gradientUnits: "userSpaceOnUse", children: [(0, import_jsx_runtime4.jsx)("stop", { stopColor: "white" }), (0, import_jsx_runtime4.jsx)("stop", { offset: "1", stopColor: "#90CBFF" })] }), (0, import_jsx_runtime4.jsx)("clipPath", { id: "clip0_4036_4155", children: (0, import_jsx_runtime4.jsx)("rect", { width: "109", height: "109", fill: "white" }) })] })] }); }; // node_modules/thirdweb/dist/esm/react/web/wallets/shared/ErrorState.js function ErrorState(props) { return (0, import_jsx_runtime5.jsxs)(Container, { animate: "fadein", children: [(0, import_jsx_runtime5.jsx)(Spacer, { y: "xxl" }), (0, import_jsx_runtime5.jsx)(Container, { flex: "row", center: "x", children: (0, import_jsx_runtime5.jsx)(AccentFailIcon, { size: iconSize["3xl"] }) }), (0, import_jsx_runtime5.jsx)(Spacer, { y: "lg" }), (0, import_jsx_runtime5.jsx)(Text, { center: true, color: "primaryText", size: "md", children: props.title }), (0, import_jsx_runtime5.jsx)(Spacer, { y: "xl" }), (0, import_jsx_runtime5.jsx)(Spacer, { y: "xxl" }), (0, import_jsx_runtime5.jsx)(Button, { variant: "accent", fullWidth: true, onClick: props.onTryAgain, children: "Try Again" })] }); } // node_modules/thirdweb/dist/esm/react/web/wallets/shared/LoadingState.js var import_jsx_runtime6 = __toESM(require_jsx_runtime(), 1); function LoadingState(props) { return (0, import_jsx_runtime6.jsxs)(Container, { animate: "fadein", children: [(0, import_jsx_runtime6.jsx)(Spacer, { y: "xxl" }), (0, import_jsx_runtime6.jsxs)(Container, { flex: "row", center: "x", style: { position: "relative" }, children: [(0, import_jsx_runtime6.jsx)(Spinner, { size: "4xl", color: "accentText" }), (0, import_jsx_runtime6.jsx)(Container, { color: "accentText", style: { position: "absolute", top: "50%", left: "50%", transform: "translate(-50%, -50%)" }, children: props.icon })] }), (0, import_jsx_runtime6.jsx)(Spacer, { y: "xl" }), (0, import_jsx_runtime6.jsx)(Text, { center: true, color: "primaryText", size: "lg", children: props.title }), (0, import_jsx_runtime6.jsx)(Spacer, { y: "md" }), (0, import_jsx_runtime6.jsx)(Text, { multiline: true, center: true, children: props.subtitle }), (0, import_jsx_runtime6.jsx)(Spacer, { y: "xxl" }), (0, import_jsx_runtime6.jsx)(Spacer, { y: "xxl" })] }); } // node_modules/thirdweb/dist/esm/react/web/wallets/shared/PassKeyLogin.js function PassKeyLogin(props) { const { wallet, done, client, chain, size, locale } = props; const [screen, setScreen] = (0, import_react4.useState)("loading"); const triggered = (0, import_react4.useRef)(false); (0, import_react4.useEffect)(() => { if (triggered.current) { return; } triggered.current = true; hasStoredPasskey(client, isEcosystemWallet(wallet.id) ? wallet.id : void 0).then((isStored) => { if (isStored) { setScreen("login"); } else { setScreen("select"); } }).catch(() => { setScreen("select"); }); }, [client, wallet.id]); return (0, import_jsx_runtime7.jsxs)(Container, { animate: "fadein", fullHeight: true, flex: "column", children: [(0, import_jsx_runtime7.jsx)(Container, { p: "lg", children: (0, import_jsx_runtime7.jsx)(ModalHeader, { title: props.isLinking ? locale.passkeys.linkPasskey : locale.passkeys.title, onBack: props.onBack }) }), (0, import_jsx_runtime7.jsx)(Container, { px: size === "wide" ? "xxl" : "lg", expand: true, flex: "column", center: "y", children: (0, import_jsx_runtime7.jsxs)("div", { children: [screen === "loading" && (0, import_jsx_runtime7.jsxs)(import_jsx_runtime7.Fragment, { children: [(0, import_jsx_runtime7.jsx)(LoadingScreen, {}), (0, import_jsx_runtime7.jsx)(Spacer, { y: "xxl" })] }), screen === "select" && (0, import_jsx_runtime7.jsx)(SelectLoginMethod, { onSignin: () => { setScreen("login"); }, onSignup: () => { setScreen("signup"); } }), screen === "login" && (0, import_jsx_runtime7.jsx)(LoginScreen, { wallet, client, done, onCreate: () => { setScreen("signup"); }, chain, isLinking: props.isLinking }), screen === "signup" && (0, import_jsx_runtime7.jsx)(SignupScreen, { wallet, client, done, chain, isLinking: props.isLinking })] }) })] }); } function LoginScreen(props) { const { wallet, done, client, chain } = props; const [status, setStatus] = (0, import_react4.useState)("loading"); const [error, setError] = (0, import_react4.useState)(); async function login() { setStatus("loading"); try { if (props.isLinking) { await linkProfile({ client, strategy: "passkey", type: "sign-in" }).catch((e) => { setError(e.message); throw e; }); } else { await wallet.connect({ client, strategy: "passkey", type: "sign-in", chain }); await setLastAuthProvider("passkey", webLocalStorage); } done(); } catch (e) { console.error("Failed to login with passkey", e); setStatus("error"); } } const triggered = (0, import_react4.useRef)(false); (0, import_react4.useEffect)(() => { if (triggered.current) { return; } triggered.current = true; login(); }); if (status === "loading") { return (0, import_jsx_runtime7.jsx)(LoadingState, { title: "Requesting Passkey", subtitle: "A pop-up prompt will appear to sign-in and verify your passkey", icon: (0, import_jsx_runtime7.jsx)(FingerPrintIcon, { size: iconSize.xxl }) }); } if (status === "error") { return (0, import_jsx_runtime7.jsxs)(import_jsx_runtime7.Fragment, { children: [(0, import_jsx_runtime7.jsx)(ErrorState, { onTryAgain: login, title: error || "Failed to Login" }), (0, import_jsx_runtime7.jsx)(Spacer, { y: "sm" }), (0, import_jsx_runtime7.jsx)(Button, { variant: "outline", fullWidth: true, onClick: props.onCreate, children: "Create a new Passkey" }), (0, import_jsx_runtime7.jsx)(Spacer, { y: "lg" })] }); } return null; } function SignupScreen(props) { var _a; const { wallet, done, client, chain } = props; const [error, setError] = (0, import_react4.useState)(); const [status, setStatus] = (0, import_react4.useState)("loading"); const ecosystem = isEcosystemWallet(wallet) ? { id: wallet.id, partnerId: (_a = wallet.getConfig()) == null ? void 0 : _a.partnerId } : void 0; async function signup() { setStatus("loading"); try { if (props.isLinking) { await linkProfile({ client, strategy: "passkey", type: "sign-up", ecosystem }); } else { await wallet.connect({ client, strategy: "passkey", type: "sign-up", chain }); await setLastAuthProvider("passkey", webLocalStorage); } done(); } catch (e) { console.error(e); if (e instanceof Error) { setError(`Error creating passkey: ${e.message}`); } setStatus("error"); } } const triggered = (0, import_react4.useRef)(false); (0, import_react4.useEffect)(() => { if (triggered.current) { return; } triggered.current = true; signup(); }); if (status === "loading") { return (0, import_jsx_runtime7.jsx)(LoadingState, { title: "Creating Passkey", subtitle: "A pop-up prompt will appear to sign-in and verify your passkey", icon: (0, import_jsx_runtime7.jsx)(FingerPrintIcon, { size: iconSize.xxl }) }); } if (status === "error") { return (0, import_jsx_runtime7.jsxs)(import_jsx_runtime7.Fragment, { children: [(0, import_jsx_runtime7.jsx)(ErrorState, { onTryAgain: signup, title: error || "Failed to create passkey" }), (0, import_jsx_runtime7.jsx)(Spacer, { y: "lg" })] }); } return null; } function SelectLoginMethod(props) { return (0, import_jsx_runtime7.jsxs)(Container, { children: [(0, import_jsx_runtime7.jsx)(Spacer, { y: "xxl" }), (0, import_jsx_runtime7.jsx)(Container, { flex: "row", center: "x", color: "accentText", children: (0, import_jsx_runtime7.jsx)(FingerPrintIcon, { size: iconSize["4xl"] }) }), (0, import_jsx_runtime7.jsx)(Spacer, { y: "xl" }), (0, import_jsx_runtime7.jsx)(Spacer, { y: "xxl" }), (0, import_jsx_runtime7.jsx)(Button, { variant: "accent", onClick: props.onSignup, fullWidth: true, children: "Create a Passkey" }), (0, import_jsx_runtime7.jsx)(Spacer, { y: "sm" }), (0, import_jsx_runtime7.jsx)(Button, { variant: "outline", onClick: props.onSignin, fullWidth: true, children: "I have a Passkey" }), (0, import_jsx_runtime7.jsx)(Spacer, { y: "lg" })] }); } // node_modules/thirdweb/dist/esm/react/web/wallets/shared/SocialLogin.js var import_jsx_runtime8 = __toESM(require_jsx_runtime(), 1); var import_react5 = __toESM(require_react(), 1); function SocialLogin(props) { var _a, _b; const ewLocale = props.locale; const locale = ewLocale.socialLoginScreen; const themeObj = useCustomTheme(); const ecosystem = isEcosystemWallet(props.wallet) ? { id: props.wallet.id, partnerId: (_a = props.wallet.getConfig()) == null ? void 0 : _a.partnerId } : void 0; const [authError, setAuthError] = (0, import_react5.useState)(void 0); const { done, wallet } = props; const [status, setStatus] = (0, import_react5.useState)("connecting"); const handleSocialLogin = async () => { var _a2, _b2, _c, _d; const walletConfig = wallet.getConfig(); const authMode = walletConfig && "auth" in walletConfig ? ((_a2 = walletConfig == null ? void 0 : walletConfig.auth) == null ? void 0 : _a2.mode) ?? "popup" : "popup"; if (walletConfig && "auth" in walletConfig && authMode !== "popup" && !props.isLinking) { return loginWithOauthRedirect({ authOption: props.socialAuth, client: props.client, ecosystem, redirectUrl: (_b2 = walletConfig == null ? void 0 : walletConfig.auth) == null ? void 0 : _b2.redirectUrl, mode: (_c = walletConfig == null ? void 0 : walletConfig.auth) == null ? void 0 : _c.mode }); } try { const socialWindow = openOauthSignInWindow({ authOption: props.socialAuth, themeObj, client: props.client, ecosystem }); if (!socialWindow) { throw new Error(`Failed to open ${props.socialAuth} login window`); } setStatus("connecting"); if (props.isLinking) { await linkProfile({ client: props.client, strategy: props.socialAuth, openedWindow: socialWindow, closeOpenedWindow: (openedWindow) => { openedWindow.close(); }, ecosystem }).catch((e) => { setAuthError(e.message); throw e; }); } else { await wallet.connect({ chain: props.chain, strategy: props.socialAuth, openedWindow: socialWindow, closeOpenedWindow: (openedWindow) => { openedWindow.close(); }, client: props.client }); } await setLastAuthProvider(props.socialAuth, webLocalStorage); setStatus("connected"); done(); } catch (e) { setStatus("error"); if (e instanceof Error && ((_d = e == null ? void 0 : e.message) == null ? void 0 : _d.includes("PAYMENT_METHOD_REQUIRED"))) { setAuthError(ewLocale.maxAccountsExceeded); } console.error(`Error sign in with ${props.socialAuth}`, e); } }; const socialLogin = (_b = props.state) == null ? void 0 : _b.socialLogin; const socialLoginStarted = (0, import_react5.useRef)(false); (0, import_react5.useEffect)(() => { if (socialLoginStarted.current) { return; } if (socialLogin) { socialLoginStarted.current = true; setStatus("connecting"); socialLogin.connectionPromise.then(() => { done(); setStatus("connected"); }).catch((e) => { setAuthError(e.message); setStatus("error"); }); } }, [done, socialLogin]); return (0, import_jsx_runtime8.jsx)(Container, { animate: "fadein", flex: "column", fullHeight: true, children: (0, import_jsx_runtime8.jsxs)(Container, { flex: "column", expand: true, p: "lg", style: { paddingBottom: 0 }, children: [props.goBack && (0, import_jsx_runtime8.jsx)(ModalHeader, { title: props.isLinking ? props.connectLocale.manageWallet.linkProfile : locale.title, onBack: props.goBack }), props.size === "compact" ? (0, import_jsx_runtime8.jsx)(Spacer, { y: "xl" }) : null, (0, import_jsx_runtime8.jsxs)(Container, { flex: "column", center: "both", expand: true, style: { textAlign: "center", minHeight: "250px" }, children: [status !== "error" && (0, import_jsx_runtime8.jsxs)(Container, { animate: "fadein", children: [(0, import_jsx_runtime8.jsx)(Text, { color: "primaryText", center: true, multiline: true, style: { maxWidth: "250px" }, children: locale.instruction }), (0, import_jsx_runtime8.jsx)(Spacer, { y: "xl" }), (0, import_jsx_runtime8.jsx)(Container, { center: "x", flex: "row", children: (0, import_jsx_runtime8.jsx)(Spinner, { size: "lg", color: "accentText" }) }), (0, import_jsx_runtime8.jsx)(Spacer, { y: "xxl" })] }), status === "error" && (0, import_jsx_runtime8.jsxs)(Container, { animate: "fadein", children: [authError ? (0, import_jsx_runtime8.jsx)(Text, { center: true, color: "danger", children: authError }) : (0, import_jsx_runtime8.jsx)(Text, { color: "danger", children: locale.failed }), (0, import_jsx_runtime8.jsx)(Spacer, { y: "lg" }), (0, import_jsx_runtime8.jsx)(Button, { variant: "primary", onClick: handleSocialLogin, children: locale.retry }), (0, import_jsx_runtime8.jsx)(Spacer, { y: "xxl" })] })] })] }) }); } // node_modules/thirdweb/dist/esm/react/web/wallets/in-app/WalletAuth.js var import_jsx_runtime24 = __toESM(require_jsx_runtime(), 1); var import_react16 = __toESM(require_react(), 1); // node_modules/thirdweb/dist/esm/react/core/hooks/wallets/useAddConnectedWallet.js function useAddConnectedWallet() { const manager = useConnectionManagerCtx("useAddConnectedWallet"); return manager.handleConnection; } // node_modules/thirdweb/dist/esm/react/web/ui/ConnectWallet/WalletSelector.js var import_jsx_runtime23 = __toESM(require_jsx_runtime(), 1); var import_react15 = __toESM(require_react(), 1); // node_modules/thirdweb/dist/esm/react/web/ui/ConnectWallet/Modal/SmartWalletConnectUI.js var import_jsx_runtime19 = __toESM(require_jsx_runtime(), 1); var import_react14 = __toESM(require_react(), 1); // node_modules/thirdweb/dist/esm/react/web/wallets/smartWallet/locale/getSmartWalletLocale.js async function getSmartWalletLocale(localeId) { switch (localeId) { case "es_ES": return (await import("./es-UEK7RLXG.js")).default; case "ja_JP": return (await import("./ja-6MH4WP2Z.js")).default; case "tl_PH": return (await import("./tl-DDFVDALG.js")).default; case "vi_VN": return (await import("./vi-4HLVRM5V.js")).default; case "de_DE": return (await import("./de-OKZ4QL64.js")).default; case "ko_KR": return (await import("./kr-LSVS4UQW.js")).default; case "fr_FR": return (await import("./fr-HCZLKSNB.js")).default; default: return (await import("./en-SB77EPNW.js")).default; } } // node_modules/thirdweb/dist/esm/react/web/ui/ConnectWallet/Modal/AnyWalletConnectUI.js var import_jsx_runtime18 = __toESM(require_jsx_runtime(), 1); var import_react13 = __toESM(require_react(), 1); // node_modules/thirdweb/dist/esm/react/web/wallets/injected/locale/getInjectedWalletLocale.js async function getInjectedWalletLocale(locale) { switch (locale) { case "es_ES": return (await import("./es-7RULN4RE.js")).default; case "ja_JP": return (await import("./ja-HG2757OL.js")).default; case "tl_PH": return (await import("./tl-AVOH7Y5Z.js")).default; case "vi_VN": return (await import("./vi-JLTPQX3P.js")).default; case "de_DE": return (await import("./de-WT7ZYIRL.js")).default; case "ko_KR": return (await import("./kr-XDCZ7IIG.js")).default; case "fr_FR": return (await import("./fr-2PO34MSK.js")).default; default: return (await import("./en-GF35UFXC.js")).default; } } // node_modules/thirdweb/dist/esm/react/web/wallets/shared/GetStartedScreen.js var import_jsx_runtime13 = __toESM(require_jsx_runtime(), 1); var import_react8 = __toESM(require_react(), 1); // node_modules/thirdweb/dist/esm/react/web/ui/ConnectWallet/icons/AppleIcon.js var import_jsx_runtime9 = __toESM(require_jsx_runtime(), 1); var AppleIcon = (props) => { return (0, import_jsx_runtime9.jsx)("svg", { xmlns: "http://www.w3.org/2000/svg", width: props.size, height: props.size, viewBox: "0 0 23 28", fill: "none", role: "presentation", children: (0, import_jsx_runtime9.jsx)("path", { d: "M22.4181 21.6041C22.008 22.5506 21.5224 23.422 20.9599 24.223C20.1931 25.3151 19.5652 26.0711 19.0814 26.4908C18.3313 27.1799 17.5277 27.5327 16.6671 27.5528C16.0493 27.5528 15.3043 27.3772 14.437 27.021C13.5669 26.6664 12.7673 26.4908 12.0362 26.4908C11.2694 26.4908 10.447 26.6664 9.56734 27.021C8.68636 27.3772 7.97665 27.5628 7.43403 27.5812C6.60879 27.6164 5.78624 27.2534 4.96519 26.4908C4.44116 26.0343 3.78569 25.2516 3.00047 24.1428C2.15799 22.9587 1.46536 21.5857 0.92274 20.0203C0.341611 18.3295 0.050293 16.6922 0.050293 15.1071C0.050293 13.2914 0.44307 11.7253 1.2298 10.413C1.84809 9.35886 2.67065 8.52734 3.70014 7.91691C4.72963 7.30648 5.84199 6.99541 7.03991 6.97551C7.69538 6.97551 8.55493 7.17804 9.6231 7.57607C10.6882 7.97544 11.3722 8.17797 11.672 8.17797C11.8962 8.17797 12.656 7.94116 13.944 7.46904C15.162 7.0312 16.19 6.84991 17.0321 6.92133C19.3141 7.10529 21.0285 8.00387 22.1687 9.62276C20.1278 10.858 19.1182 12.5881 19.1383 14.8076C19.1567 16.5363 19.7846 17.9749 21.0185 19.1172C21.5777 19.6473 22.2022 20.0571 22.897 20.3481C22.7463 20.7846 22.5872 21.2027 22.4181 21.6041ZM17.1845 1.03178C17.1845 2.38678 16.6889 3.65194 15.7011 4.82296C14.509 6.21507 13.0672 7.0195 11.5036 6.89256C11.4837 6.73 11.4721 6.55892 11.4721 6.37913C11.4721 5.07833 12.039 3.68622 13.0457 2.54798C13.5484 1.97167 14.1876 1.49247 14.9628 1.11021C15.7363 0.733653 16.4679 0.525407 17.156 0.489746C17.1761 0.670889 17.1845 0.85206 17.1845 1.03178Z", fill: "#959CA0" }) }); }; // node_modules/thirdweb/dist/esm/react/web/ui/ConnectWallet/icons/ChromeIcon.js var import_jsx_runtime10 = __toESM(require_jsx_runtime(), 1); var ChromeIcon = (props) => { return (0, import_jsx_runtime10.jsx)("svg", { xmlns: "http://www.w3.org/2000/svg", width: props.size, height: props.size, viewBox: "0 0 190.5 190.5", role: "presentation", children: (0, import_jsx_runtime10.jsxs)("g", { transform: "translate(90.669 -507.469)", children: [(0, import_jsx_runtime10.jsx)("path", { d: "M4.583 650.342c26.304 0 47.627-21.324 47.627-47.628s-21.323-47.628-47.627-47.628-47.627 21.324-47.627 47.628 21.323 47.628 47.627 47.628z", fill: "#fff", clipPath: "none", mask: "none" }), (0, import_jsx_runtime10.jsx)("path", { d: "M-36.664 626.539l-41.24-71.43c-8.362 14.479-12.765 30.904-12.765 47.625s4.401 33.146 12.762 47.625 20.387 26.503 34.868 34.86 30.908 12.755 47.628 12.75l41.24-71.43v-.011c-4.177 7.244-10.188 13.26-17.428 17.443a47.62 47.62 0 0 1-47.632.007 47.62 47.62 0 0 1-17.433-17.437z", fill: "#229342", clipPath: "none", mask: "none" }), (0, import_jsx_runtime10.jsx)("path", { d: "M45.826 626.536l-41.239 71.43c16.72.003 33.146-4.398 47.626-12.757s26.504-20.384 34.863-34.865a95.24 95.24 0 0 0 12.755-47.627c-.003-16.72-4.408-33.145-12.772-47.623H4.58l-.01.007a47.62 47.62 0 0 1 23.819 6.372c7.243 4.179 13.257 10.19 17.439 17.431a47.62 47.62 0 0 1-.001 47.633z", fill: "#fbc116", clipPath: "none", mask: "none" }), (0, import_jsx_runtime10.jsx)("path", { d: "M4.583 640.43c20.824 0 37.705-16.881 37.705-37.706s-16.881-37.705-37.705-37.705-37.705 16.881-37.705 37.705 16.881 37.706 37.705 37.706z", fill: "#1a73e8", clipPath: "none", mask: "none" }), (0, import_jsx_runtime10.jsx)("path", { d: "M4.583 555.097h82.479c-8.358-14.481-20.381-26.507-34.861-34.868a95.23 95.23 0 0 0-47.625-12.76c-16.72.001-33.145 4.404-47.623 12.767a95.23 95.23 0 0 0-34.856 34.872l41.24 71.43.011.006a47.62 47.62 0 0 1-.015-47.633c4.179-7.242 10.193-13.256 17.434-17.436s15.456-6.381 23.818-6.379z", fill: "#e33b2e", clipPath: "none", mask: "none" })] }) }); }; // node_modules/thirdweb/dist/esm/react/web/ui/ConnectWallet/icons/PlayStoreIcon.js var import_jsx_runtime11 = __toESM(require_jsx_runtime(), 1); var PlayStoreIcon = (props) => { return (0, import_jsx_runtime11.jsxs)("svg", { xmlns: "http://www.w3.org/2000/svg", width: props.size, height: props.size, viewBox: "0 0 23 26", fill: "none", role: "presentation", children: [(0, import_jsx_runtime11.jsx)("path", { d: "M10.5832 12.0978L0.0976562 23.2275C0.0980507 23.2298 0.0988382 23.2317 0.0992076 23.2341C0.420793 24.4427 1.52467 25.3326 2.83473 25.3326C3.35844 25.3326 3.85012 25.191 4.27179 24.9424L4.30528 24.9228L16.1087 18.1117L10.5838 12.0977", fill: "#EB3131" }), (0, import_jsx_runtime11.jsx)("path", { d: "M21.1922 10.2046L21.1821 10.1977L16.0862 7.2435L10.345 12.3523L16.1061 18.1127L21.1752 15.1879C22.0639 14.7081 22.6672 13.7712 22.6672 12.6908C22.6672 11.6182 22.072 10.6859 21.1922 10.2046Z", fill: "#F6B60B" }), (0, import_jsx_runtime11.jsx)("path", { d: "M0.0961678 2.10416C0.0331317 2.33661 0 2.58009 0 2.83292V22.5002C0 22.7526 0.0327407 22.9969 0.0965672 23.2285L10.9441 12.3832L0.0965672 2.10444", fill: "#5778C5" }), (0, import_jsx_runtime11.jsx)("path", { d: "M10.6603 12.6667L16.088 7.24061L4.29785 0.404818C3.8693 0.148138 3.36912 0 2.83391 0C1.52384 0 0.418474 0.891502 0.0968301 2.10147C0.0964356 2.10265 0.0964355 2.10347 0.0964355 2.1045L10.6603 12.6669", fill: "#3BAD49" })] }); }; // node_modules/thirdweb/dist/esm/react/web/ui/components/QRCode.js var import_jsx_runtime12 = __toESM(require_jsx_runtime(), 1); var import_react7 = __toESM(require_react(), 1); var QRCodeRenderer = (0, import_react7.lazy)(() => import("./QRCodeRenderer-ZNSMXL36.js")); var QRCode = (props) => { const size = props.size || 310; const placeholder = (0, import_jsx_runtime12.jsxs)(QRPlaceholder, { style: { width: `${size}px`, height: `${size}px` }, children: [(0, import_jsx_runtime12.jsx)("span", { "data-v1": true }), (0, import_jsx_runtime12.jsx)("span", { "data-v2": true }), (0, import_jsx_runtime12.jsx)("span", { "data-v3": true }), (0, import_jsx_runtime12.jsx)("div", {})] }); return (0, import_jsx_runtime12.jsxs)("div", { style: { position: "relative", display: "flex", justifyContent: "center" }, children: [props.qrCodeUri ? (0, import_jsx_runtime12.jsx)(import_react7.Suspense, { fallback: placeholder, children: (0, import_jsx_runtime12.jsx)(QRCodeContainer, { children: (0, import_jsx_runtime12.jsx)(QRCodeRenderer, { uri: props.qrCodeUri, size: size + 20, ecl: "M", clearSize: props.QRIcon ? 70 : void 0 }) }) }) : placeholder, props.QRIcon && (0, import_jsx_runtime12.jsx)(IconContainer, { children: props.QRIcon })] }); }; var IconContainer = StyledDiv({ position: "absolute", top: "50%", left: "50%", transform: "translate(-50%, -50%)", display: "flex", justifyContent: "center", alignContent: "center", zIndex: 1e3 }); var QRCodeContainer = StyledDiv(() => { const theme = useCustomTheme(); return { animation: `${fadeInAnimation} 600ms ease`, "--ck-qr-dot-color": theme.colors.primaryText, "--ck-body-background": theme.colors.modalBg, "--ck-qr-background": theme.colors.modalBg }; }); var PlaceholderKeyframes = keyframes` 0%{ background-position: 100% 0; } 100%{ background-position: -100% 0; } `; var QRPlaceholder = StyledDiv((_) => { const theme = useCustomTheme(); return { "--color": theme.colors.skeletonBg, "--bg": theme.colors.modalBg, overflow: "hidden", position: "relative", display: "flex", alignItems: "center", justifyContent: "center", borderRadius: radius.md, "> div": { zIndex: 4, position: "relative", width: "28%", height: "28%", borderRadius: "5px", background: "var(--bg)", boxShadow: "0 0 0 7px var(--bg)" }, "> span": { zIndex: 4, position: "absolute", background: "var(--color)", borderRadius: "12px", width: "13.25%", height: "13.25%", boxShadow: "0 0 0 4px var(--bg)", "&:before": { content: '""', position: "absolute", inset: "9px", borderRadius: "3px", boxShadow: "0 0 0 4px var(--bg)" }, "&[data-v1]": { top: 0, left: 0 }, "&[data-v2]": { top: 0, right: 0 }, "&[data-v3]": { bottom: 0, left: 0 } }, "&:before": { zIndex: 3, content: '""', position: "absolute", inset: 0, background: "repeat", backgroundSize: "1.888% 1.888%", backgroundImage: "radial-gradient(var(--color) 41%, transparent 41%)" }, "&::after": { zIndex: 100, content: '""', position: "absolute", inset: 0, transform: "scale(1.5) rotate(45deg)", background: "linear-gradient(90deg, transparent 50%, var(--color), transparent)", backgroundSize: "200% 100%", animation: `${PlaceholderKeyframes} 1000ms linear infinite both` } }; }); // node_modules/thirdweb/dist/esm/react/web/wallets/shared/GetStartedScreen.js var GetStartedScreen = ({ wallet, walletInfo, header, footer, onBack, locale, client }) => { const [showScreen, setShowScreen] = (0, import_react8.useState)("base"); const isScanScreen = showScreen === "android-scan" || showScreen === "ios-scan"; const handleBack = onBack ? () => { if (showScreen === "base") { onBack(); } else { setShowScreen("base"); } } : void 0; return (0, import_jsx_runtime13.jsx)(Container, { fullHeight: true, flex: "column", animate: "fadein", children: (0, import_jsx_runtime13.jsxs)(Container, { expand: true, flex: "column", p: "lg", children: [showScreen === "android-scan" && walletInfo.app.android && (0, import_jsx_runtime13.jsx)(InstallScanScreen, { platformIcon: (0, import_jsx_runtime13.jsx)(PlayStoreIcon, { size: iconSize.md }), url: walletInfo.app.android, platform: "Google Play", walletName: walletInfo.name, walletId: wallet.id, onBack: handleBack, locale: { scanToDownload: locale.getStartedScreen.instruction }, client }), showScreen === "ios-scan" && walletInfo.app.ios && (0, import_jsx_runtime13.jsx)(InstallScanScreen, { platformIcon: (0, import_jsx_runtime13.jsx)(AppleIcon, { size: iconSize.md }), url: walletInfo.app.ios, platform: "App Store", walletName: walletInfo.name, walletId: wallet.id, onBack: handleBack, locale: { scanToDownload: locale.getStartedScreen.instruction }, client }), showScreen === "base" && (0, import_jsx_runtime13.jsxs)(Container, { expand: true, flex: "column", children: [header || (0, import_jsx_runtime13.jsx)(ModalHeader, { onBack: handleBack, title: walletInfo.name }), (0, import_jsx_runtime13.jsx)(Spacer, { y: "xl" }), (0, import_jsx_runtime13.jsx)(Container, { expand: true, animate: "fadein", flex: "column", center: "y", style: { minHeight: "250px" }, children: (0, import_jsx_runtime13.jsxs)(Container, { flex: "column", gap: "xs", children: [walletInfo.app.chrome && (0, import_jsx_runtime13.jsxs)(ButtonLink2, { onClick: () => { openWindow(walletInfo.app.chrome || ""); }, children: [(0, import_jsx_runtime13.jsx)(ChromeIcon, { size: iconSize.lg }), (0, import_jsx_runtime13.jsx)("span", { children: locale.download.chrome })] }), walletInfo.app.android && (0, import_jsx_runtime13.jsxs)(ButtonLink2, { as: "button", onClick: () => { if (isMobile()) { openWindow(walletInfo.app.android || ""); } else { setShowScreen("android-scan"); } }, children: [(0, import_jsx_runtime13.jsx)(PlayStoreIcon, { size: iconSize.lg }), (0, import_jsx_runtime13.jsx)("span", { children: locale.download.android })] }), walletInfo.app.ios && (0, import_jsx_runtime13.jsxs)(ButtonLink2, { as: "button", onClick: () => { if (isMobile()) { openWindow(walletInfo.app.ios || ""); } else { setShowScreen("ios-scan"); } }, children: [(0, import_jsx_runtime13.jsx)(AppleIcon, { size: iconSize.lg }), (0, import_jsx_runtime13.jsx)("span", { children: locale.download.iOS })] })] }) })] }), !isScanScreen && footer] }) }); }; var InstallScanScreen = (props) => { return (0, import_jsx_runtime13.jsxs)(Container, { animate: "fadein", expand: true, children: [(0, import_jsx_runtime13.jsx)(ModalHeader, { title: props.walletName, onBack: props.onBack }), (0, import_jsx_runtime13.jsx)(Spacer, { y: "xl" }), (0, import_jsx_runtime13.jsxs)(Container, { flex: "column", expand: true, center: "both", style: { textAlign: "center" }, children: [(0, import_jsx_runtime13.jsx)(QRCode, { qrCodeUri: props.url, QRIcon: (0, import_jsx_runtime13.jsx)(WalletImage, { id: props.walletId, size: iconSize.xxl, client: props.client }) }), (0, import_jsx_runtime13.jsx)(Spacer, { y: "xl" }), (0, import_jsx_runtime13.jsx)(Text, { multiline: true, center: true, balance: true, children: props.locale.scanToDownload }), (0, import_jsx_runtime13.jsx)(Spacer, { y: "xs" })] })] }); }; var ButtonLink2 = StyledButton((_) => { const theme = useCustomTheme(); return { all: "unset", textDecoration: "none", padding: `${spacing.sm} ${spacing.md}`, borderRadius: radius.sm, display: "flex", alignItems: "center", gap: spacing.md, cursor: "pointer", boxSizing: "border-box", width: "100%", fontWeight: 500, color: theme.colors.secondaryButtonText, background: theme.colors.secondaryButtonBg, transition: "100ms ease", "&:hover": { background: theme.colors.secondaryButtonHoverBg, textDecoration: "none", color: theme.colors.primaryText } }; }); // node_modules/thirdweb/dist/esm/react/web/wallets/shared/WalletConnectConnection.js var import_jsx_runtime15 = __toESM(require_jsx_runtime(), 1); var import_react10 = __toESM(require_react(), 1); // node_modules/thirdweb/dist/esm/utils/promise/wait.js function wait(ms) { return new Promise((resolve) => { setTimeout(resolve, ms); }); } // node_modules/thirdweb/dist/esm/react/web/wallets/shared/ScanScreen.js var import_jsx_runtime14 = __toESM(require_jsx_runtime(), 1); var import_react9 = __toESM(require_react(), 1); var ScanScreen = (props) => { const { connectModalSize, client } = props; const [linkCopied, setLinkCopied] = (0, import_react9.useState)(false); return (0, import_jsx_runtime14.jsxs)(Container, { fullHeight: true, flex: "column", animate: "fadein", children: [(0, import_jsx_runtime14.jsx)(Container, { p: "lg", children: (0, import_jsx_runtime14.jsx)(ModalHeader, { onBack: props.onBack, title: props.walletName }) }), (0, import_jsx_runtime14.jsx)(Spacer, { y: "sm" }), (0, import_jsx_runtime14.jsxs)(Container, { expand: true, flex: "column", px: "lg", center: "both", children: [!props.error && (0, import_jsx_runtime14.jsxs)("div", { style: { textAlign: "center" }, children: [(0, import_jsx_runtime14.jsx)(QRCode, { qrCodeUri: props.qrCodeUri, QRIcon: (0, import_jsx_runtime14.jsx)(WalletImage, { size: iconSize.xxl, id: props.walletId, client }) }), (0, import_jsx_runtime14.jsx)(Spacer, { y: "xs" }), (0, import_jsx_runtime14.jsxs)(Button, { disabled: props.qrCodeUri === void 0, variant: "link", style: { fontSize: "12px", opacity: props.qrCodeUri === void 0 ? 0.5 : 1, cursor: props.qrCodeUri === void 0 ? "default" : "pointer" }, onClick: () => { navigator.clipboard.writeText(props.qrCodeUri).then(() => { setLinkCopied(true); setTimeout(() => setLinkCopied(false), 3e3); }).catch((err) => { console.error("Failed to copy link to clipboard", err); }); }, children: [linkCopied ? (0, import_jsx_runtime14.jsx)(CheckIcon, { width: 14, height: 14 }) : (0, import_jsx_runtime14.jsx)(CopyIcon, { width: 14, height: 14 }), (0, import_jsx_runtime14.jsx)("span", { style: { padding: "0 4px" }, children: "Copy Link" })] }), (0, import_jsx_runtime14.jsx)(Spacer, { y: "lg" }), (0, import_jsx_runtime14.jsx)(Text, { center: true, multiline: true, balance: true, style: { paddingInline: spacing.lg }, children: props.qrScanInstruction })] }), props.error && (0, import_jsx_runtime14.jsxs)(Container, { animate: "fadein", style: { width: "100%" }, children: [(0, import_jsx_runtime14.jsx)(Spacer, { y: "xxl" }), (0, import_jsx_runtime14.jsx)(Container, { flex: "row", center: "x", children: (0, import_jsx_runtime14.jsx)(AccentFailIcon, { size: iconSize["3xl"] }) }), (0, import_jsx_runtime14.jsx)(Spacer, { y: "lg" }), (0, import_jsx_runtime14.jsx)(Text, { center: true, size: "lg", color: "primaryText", children: "Connection Failed" }), (0, import_jsx_runtime14.jsx)(Spacer, { y: "3xl" }), (0, import_jsx_runtime14.jsx)(Button, { fullWidth: true, variant: "accent", onClick: props.onRetry, children: "Try again" })] })] }), (0, import_jsx_runtime14.jsx)(Spacer, { y: "lg" }), props.onGetStarted && (0, import_jsx_runtime14.jsx)(ScreenBottomContainer, { style: { border: connectModalSize === "compact" ? void 0 : "none" }, children: (0, import_jsx_runtime14.jsx)(Button, { variant: "link", onClick: props.onGetStarted, style: { fontSize: fontSize.sm, textAlign: "center" }, children: props.getStartedLink }) })] }); }; // node_modules/thirdweb/dist/esm/react/web/wallets/shared/WalletConnectConnection.js var WalletConnectConnection = (props) => { const { onBack, onGetStarted, wallet, walletInfo, locale, done } = props; const [qrCodeUri, setQrCodeUri] = (0, import_react10.useState)(); const [errorConnecting, setErrorConnecting] = (0, import_react10.useState)(false); const connect = (0, import_react10.useCallback)(() => { var _a; setErrorConnecting(false); wallet.connect({ chain: props.chain, client: props.client, walletConnect: { projectId: (_a = props.walletConnect) == null ? void 0 : _a.projectId, showQrModal: false, onDisplayUri(uri) { const preferNative = walletInfo.mobile.native || walletInfo.mobile.universal; try { if (isMobile()) { if (isAndroid()) { if (preferNative) { openWindow(formatWalletConnectUrl(preferNative, uri).redirect); } } else if (isIOS()) { if (preferNative) { openWindow(formatWalletConnectUrl(preferNative, uri).redirect); } } else { const preferUniversal = walletInfo.mobile.universal || walletInfo.mobile.native; if (preferUniversal) { openWindow(formatWalletConnectUrl(preferUniversal, uri).redirect); } } } else { setQrCodeUri(uri); } } catch { setErrorConnecting(true); } }, optionalChains: props.chains } }).then(() => { done(); }).catch((e) => { setErrorConnecting(true); console.error(e); }); }, [ props.walletConnect, walletInfo.mobile.native, walletInfo.mobile.universal, wallet, props.chain, props.client, props.chains, done ]); const scanStarted = (0, import_react10.useRef)(false); (0, import_react10.useEffect)(() => { if (scanStarted.current) { return; } scanStarted.current = true; connect(); }, [connect]); if (isMobile()) { return (0, import_jsx_runtime15.jsx)(ConnectingScreen, { locale: { getStartedLink: locale.getStartedLink, instruction: locale.connectionScreen.instruction, tryAgain: locale.connectionScreen.retry, inProgress: locale.connectionScreen.inProgress, failed: locale.connectionScreen.failed }, onBack, walletName: walletInfo.name, walletId: wallet.id, errorConnecting, onRetry: connect, onGetStarted, client: props.client, size: props.size }); } return (0, import_jsx_runtime15.jsx)(ScanScreen, { qrScanInstruction: locale.scanScreen.instruction, onBack, onGetStarted, qrCodeUri, walletName: walletInfo.name, walletId: wallet.id, getStartedLink: locale.getStartedLink, error: errorConnecting, onRetry: connect, client: props.client, connectModalSize: props.size }); }; var WalletConnectStandaloneConnection = (props) => { const { onBack, wallet, walletInfo, locale, done, setModalVisibility } = props; const [qrCodeUri, setQrCodeUri] = (0, import_react10.useState)(); const [errorConnecting, setErrorConnecting] = (0, import_react10.useState)(false); const connect = (0, import_react10.useCallback)(() => { var _a, _b; setErrorConnecting(false); if (isMobile()) { let wcModalClosed = false; wait(2e3).then(() => { if (!wcModalClosed) { setModalVisibility(false); } }); wallet.connect({ chain: props.chain, client: props.client, projectId: (_a = props.walletConnect) == null ? void 0 : _a.projectId, showQrModal: true, optionalChains: props.chains }).then(() => { wcModalClosed = true; setModalVisibility(true); done(); }).catch((e) => { wcModalClosed = true; setModalVisibility(true); setErrorConnecting(true); console.error(e); }); } else { wallet.connect({ chain: props.chain, client: props.client, projectId: (_b = props.walletConnect) == null ? void 0 : _b.projectId, showQrModal: false, onDisplayUri(uri) { const platformUris = { ios: walletInfo.mobile.native || "", android: walletInfo.mobile.universal || "", other: walletInfo.mobile.universal || "" }; setQrCodeUri(uri); if (isMobile()) { if (isAndroid()) { openWindow(`${platformUris.android}wc?uri=${encodeURIComponent(uri)}`); } else if (isIOS()) { openWindow(`${platformUris.ios}wc?uri=${encodeURIComponent(uri)}`); } else { openWindow(`${platformUris.other}wc?uri=${encodeURIComponent(uri)}`); } } }, optionalChains: props.chains }).then(() => { done(); }).catch((e) => { setErrorConnecting(true); console.error(e); }); } }, [ props.walletConnect, walletInfo.mobile.native, walletInfo.mobile.universal, wallet, props.chain, props.client, props.chains, done, setModalVisibility ]); const scanStarted = (0, import_react10.useRef)(false); (0, import_react10.useEffect)(() => { if (scanStarted.current) { return; } scanStarted.current = true; connect(); }, [connect]); if (isMobile()) { return (0, import_jsx_runtime15.jsx)(ConnectingScreen, { locale: { getStartedLink: locale.getStartedLink, instruction: locale.connectionScreen.instruction, tryAgain: locale.connectionScreen.retry, inProgress: locale.connectionScreen.inProgress, failed: locale.connectionScreen.failed }, onBack, walletName: walletInfo.name, walletId: wallet.id, errorConnecting, onRetry: connect, client: props.client, size: props.size }); } return (0, import_jsx_runtime15.jsx)(ScanScreen, { qrScanInstruction: locale.scanScreen.instruction, onBack, qrCodeUri, walletName: walletInfo.name, walletId: wallet.id, getStartedLink: locale.getStartedLink, error: errorConnecting, onRetry: connect, client: props.client, connectModalSize: props.size }); }; // node_modules/thirdweb/dist/esm/react/web/ui/ConnectWallet/Modal/DeepLinkConnectUI.js var import_jsx_runtime16 = __toESM(require_jsx_runtime(), 1); var DeepLinkConnectUI = (props) => { return (0, import_jsx_runtime16.jsxs)(Container, { animate: "fadein", children: [(0, import_jsx_runtime16.jsx)(Container, { p: "lg", children: (0, import_jsx_runtime16.jsx)(ModalHeader, { onBack: props.onBack, title: props.walletInfo.name }) }), (0, import_jsx_runtime16.jsx)(Container, { flex: "row", center: "x", animate: "fadein", py: "3xl", children: (0, import_jsx_runtime16.jsx)(PulsatingContainer, { children: (0, import_jsx_runtime16.jsx)(WalletImage, { id: props.wallet.id, client: props.client, size: "80" }) }) }), (0, import_jsx_runtime16.jsx)(Container, { p: "lg", children: (0, import_jsx_runtime16.jsxs)(ButtonLink, { fullWidth: true, variant: "accent", href: `${props.deepLinkPrefix}${window.location.toString().replace("https://", "")}`, gap: "xs", children: ["Continue in ", props.walletInfo.name, (0, import_jsx_runtime16.jsx)(ExternalLinkIcon, { width: iconSize.sm, height: iconSize.sm })] }) })] }); }; var pulseAnimation = keyframes` 0% { transform: scale(0.9); } 100% { opacity: 0; transform: scale(1.4); } `; var PulsatingContainer = StyledDiv((_) => { const theme = useCustomTheme(); return { position: "relative", "&::before": { content: '""', display: "block", position: "absolute", left: 0, top: 0, bottom: 0, right: 0, background: theme.colors.accentText, animation: `${pulseAnimation} 2s cubic-bezier(0.175, 0.885, 0.32, 1.1) infinite`, zIndex: -1, borderRadius: radius.xl } }; }); // node_modules/thirdweb/dist/esm/react/web/ui/ConnectWallet/Modal/InjectedConnectUI.js var import_jsx_runtime17 = __toESM(require_jsx_runtime(), 1); var import_react12 = __toESM(require_react(), 1); // node_modules/thirdweb/dist/esm/react/core/utils/wait.js var wait2 = (ms) => new Promise((resolve) => setTimeout(resolve, ms)); // node_modules/thirdweb/dist/esm/react/web/ui/ConnectWallet/Modal/InjectedConnectUI.js var InjectedConnectUI = (props) => { const { wallet, done } = props; const [errorConnecting, setErrorConnecting] = (0, import_react12.useState)(false); const locale = props.locale; const connectToExtension = (0, import_react12.useCallback)(async () => { try { connectPrompted.current = true; setErrorConnecting(false); await wait2(1e3); await wallet.connect({ client: props.client, chain: props.chain }); done(); } catch (e) { setErrorConnecting(true); console.error(e); } }, [props.client, props.chain, done, wallet]); const connectPrompted = (0, import_react12.useRef)(false); (0, import_react12.useEffect)(() => { if (connectPrompted.current) { return; } connectToExtension(); }, [connectToExtension]); return (0, import_jsx_runtime17.jsx)(ConnectingScreen, { locale: { getStartedLink: locale.getStartedLink, instruction: locale.connectionScreen.instruction, tryAgain: locale.connectionScreen.retry, inProgress: locale.connectionScreen.inProgress, failed: locale.connectionScreen.failed }, onBack: props.onBack, walletName: props.walletName, onGetStarted: props.onGetStarted, walletId: props.wallet.id, onRetry: () => { connectToExtension(); }, errorConnecting, client: props.client, size: props.size }); }; // node_modules/thirdweb/dist/esm/react/web/ui/ConnectWallet/Modal/AnyWalletConnectUI.js var CoinbaseSDKWalletConnectUI = (0, import_react13.lazy)(() => import("./CoinbaseSDKConnection-PPK2JHPJ.js")); var InAppWalletConnectUI = (0, import_react13.lazy)(() => import("./InAppWalletConnectUI-IYEPIHHJ.js")); var EcosystemWalletConnectUI = (0, import_react13.lazy)(() => import("./EcosystemWalletConnectUI-ANAXYA53.js")); function AnyWalletConnectUI(props) { var _a, _b; const [screen, setScreen] = (0, import_react13.useState)("main"); const { wallet } = props; const walletInfo = useWalletInfo(props.wallet.id); const localeId = props.connectLocale.id; const localeFnQuery = useQuery({ queryKey: ["injectedWalletLocale", localeId, (_a = walletInfo.data) == null ? void 0 : _a.name], queryFn: async () => { return getInjectedWalletLocale(localeId); }, refetchOnWindowFocus: false, refetchOnMount: false }); if (walletInfo.isLoading || !localeFnQuery.data) { return (0, import_jsx_runtime18.jsx)(LoadingScreen, {}); } const localeFn = localeFnQuery.data; if (!walletInfo.data) { const injectedProvider = getInstalledWalletProviders().find((w) => w.info.rdns === wallet.id); if (injectedProvider) { return (0, import_jsx_runtime18.jsx)(InjectedConnectUI, { wallet: props.wallet, walletName: injectedProvider.info.name, done: props.done, locale: localeFn(injectedProvider.info.name), onBack: props.onBack, chain: props.chain, client: props.client, size: props.size }); } return (0, import_jsx_runtime18.jsxs)(Container, { animate: "fadein", fullHeight: true, flex: "column", children: [(0, import_jsx_runtime18.jsx)(Container, { p: "lg", children: (0, import_jsx_runtime18.jsx)(ModalHeader, { title: "Not Supported", onBack: props.onBack }) }), (0, import_jsx_runtime18.jsxs)(Container, { flex: "column", expand: true, center: "both", p: "lg", style: { minHeight: "300px" }, children: [(0, import_jsx_runtime18.jsx)(AccentFailIcon, { size: iconSize["3xl"] }), (0, import_jsx_runtime18.jsx)(Spacer, { y: "lg" }), (0, import_jsx_runtime18.jsx)(Text, { color: "primaryText", center: true, children: "Wallet is not supported" }), (0, import_jsx_runtime18.jsx)(Spacer, { y: "xxl" })] })] }); } const locale = localeFn(walletInfo.data.name); const isInstalled = getInstalledWalletProviders().find((w) => w.info.rdns === walletInfo.data.rdns); if (screen === "get-started") { return (0, import_jsx_runtime18.jsx)(GetStartedScreen, { locale, wallet: props.wallet, walletInfo: walletInfo.data, onBack: () => { setScreen("main"); }, client: props.client }); } if (walletInfo.data.deepLink && !isInstalled && ((_b = wallet.getConfig()) == null ? void 0 : _b.preferDeepLink) && isMobile()) { return (0, import_jsx_runtime18.jsx)(DeepLinkConnectUI, { wallet: props.wallet, walletInfo: walletInfo.data, deepLinkPrefix: walletInfo.data.deepLink.mobile, locale, onGetStarted: () => { setScreen("get-started"); }, onBack: props.onBack, client: props.client }); } if (walletInfo.data.rdns && isInstalled) { return (0, import_jsx_runtime18.jsx)(InjectedConnectUI, { wallet: props.wallet, walletName: walletInfo.data.name, done: props.done, locale, onGetStarted: () => { setScreen("get-started"); }, onBack: props.onBack, chain: props.chain, client: props.client, size: props.size }); } if (walletInfo.data.mobile.native || walletInfo.data.mobile.universal) { return (0, import_jsx_runtime18.jsx)(WalletConnectConnection, { locale, onGetStarted: () => { setScreen("get-started"); }, onBack: props.onBack, done: props.done, wallet: props.wallet, walletInfo: walletInfo.data, chain: props.chain, chains: props.chains, client: props.client, size: props.size, walletConnect: props.walletConnect }); } if (props.wallet.id === "walletConnect") { return (0, import_jsx_runtime18.jsx)(WalletConnectStandaloneConnection, { locale, onBack: props.onBack, done: props.done, wallet: props.wallet, walletInfo: walletInfo.data, setModalVisibility: props.setModalVisibility, chain: props.chain, chains: props.chains, client: props.client, size: props.size, walletConnect: props.walletConnect }); } if (props.wallet.id === "inApp" || props.wallet.id === "embedded") { return (0, import_jsx_runtime18.jsx)(import_react13.Suspense, { fallback: (0, import_jsx_runtime18.jsx)(LoadingScreen, {}), children: (0, import_jsx_runtime18.jsx)(InAppWalletConnectUI, { wallet: props.wallet, done: props.done, goBack: props.onBack, chain: props.chain, client: props.client, size: props.size, walletConnect: props.walletConnect, connectLocale: props.connectLocale, meta: props.meta }) }); } if (isEcosystemWallet(props.wallet.id)) { return (0, import_jsx_runtime18.jsx)(import_react13.Suspense, { fallback: (0, import_jsx_runtime18.jsx)(LoadingScreen, {}), children: (0, import_jsx_runtime18.jsx)(EcosystemWalletConnectUI, { wallet: props.wallet, done: props.done, goBack: props.onBack, chain: props.chain, client: props.client, size: props.size, meta: props.meta, walletConnect: props.walletConnect, connectLocale: props.connectLocale }) }); } if (props.wallet.id) { return (0, import_jsx_runtime18.jsx)(import_react13.Suspense, { fallback: (0, import_jsx_runtime18.jsx)(LoadingScreen, {}), children: (0, import_jsx_runtime18.jsx)(CoinbaseSDKWalletConnectUI, { locale, onGetStarted: () => { setScreen("get-started"); }, onBack: props.onBack, done: props.done, wallet: props.wallet, walletInfo: walletInfo.data, chain: props.chain, client: props.client, size: props.size }) }); } return (0, import_jsx_runtime18.jsx)(GetStartedScreen, { locale, wallet: props.wallet, walletInfo: walletInfo.data, onBack: props.onBack, client: props.client }); } // node_modules/thirdweb/dist/esm/react/web/ui/ConnectWallet/Modal/SmartWalletConnectUI.js function SmartConnectUI(props) { const personalWalletInfo = useWalletInfo(props.personalWallet.id); const [keyConnected, setKeyConnected] = (0, import_react14.useState)(false); if (!personalWalletInfo.data) { return (0, import_jsx_runtime19.jsx)(LoadingScreen, {}); } if (!keyConnected) { return (0, import_jsx_runtime19.jsx)(AnyWalletConnectUI, { wallet: props.personalWallet, done: () => { setKeyConnected(true); }, onBack: props.onBack, setModalVisibility: props.setModalVisibility, chain: props.chain, chains: props.chains, client: props.client, meta: props.meta, size: props.size, walletConnect: props.walletConnect, connectLocale: props.connectLocale }); } return (0, import_jsx_runtime19.jsx)(SmartWalletConnecting, { done: props.done, personalWallet: props.personalWallet, accountAbstraction: props.accountAbstraction, onBack: props.onBack, personalWalletInfo: personalWalletInfo.data, localeId: props.connectLocale.id, size: props.size, client: props.client }); } function SmartWalletConnecting(props) { var _a; const localeQuery = useQuery({ queryKey: ["getSmartWalletLocale", props.localeId], queryFn: () => getSmartWalletLocale(props.localeId) }); const { chain: smartWalletChain } = props.accountAbstraction; const { personalWallet } = props; const { done } = props; const [personalWalletChainId, setPersonalWalletChainId] = (0, import_react14.useState)((_a = personalWallet.getChain()) == null ? void 0 : _a.id); (0, import_react14.useEffect)(() => { const unsubChainChanged = personalWallet.subscribe("chainChanged", (chain) => setPersonalWalletChainId(chain.id)); return () => { unsubChainChanged(); }; }, [personalWallet]); const wrongNetwork = personalWalletChainId !== smartWalletChain.id; const [smartWalletConnectionStatus, setSmartWalletConnectionStatus] = (0, import_react14.useState)("idle"); const [personalWalletChainSwitchStatus, setPersonalWalletChainSwitchStatus] = (0, import_react14.useState)("idle"); const connectionManager = useConnectionManager(); const handleConnect = (0, import_react14.useCallback)(async () => { if (!personalWallet) { throw new Error("No personal wallet"); } setSmartWalletConnectionStatus("connecting"); try { const connected = await connectionManager.handleConnection(personalWallet, { accountAbstraction: props.accountAbstraction, client: props.client }); done(connected); setSmartWalletConnectionStatus("idle"); } catch (e) { console.error(e); setSmartWalletConnectionStatus("connect-error"); } }, [ done, personalWallet, props.client, props.accountAbstraction, connectionManager ]); const connectStarted = (0, import_react14.useRef)(false); (0, import_react14.useEffect)(() => { if (!wrongNetwork && !connectStarted.current) { handleConnect(); connectStarted.current = true; } }, [handleConnect, wrongNetwork]); if (!localeQuery.data) { return (0, import_jsx_runtime19.jsx)(LoadingScreen, {}); } if (wrongNetwork) { return (0, import_jsx_runtime19.jsxs)(Container, { fullHeight: true, animate: "fadein", flex: "column", children: [(0, import_jsx_runtime19.jsx)(Container, { p: "lg", children: (0, import_jsx_runtime19.jsx)(ModalHeader, { title: props.personalWalletInfo.name, onBack: props.onBack }) }), props.size === "compact" && (0, import_jsx_runtime19.jsx)(Spacer, { y: "lg" }), (0, import_jsx_runtime19.jsx)(Container, { expand: true, flex: "column", center: "both", p: "lg", children: (0, import_jsx_runtime19.jsxs)(Container, { p: props.size === "wide" ? "lg" : void 0, children: [(0, import_jsx_runtime19.jsx)(Container, { flex: "row", center: "x", color: "danger", children: (0, import_jsx_runtime19.jsx)(ExclamationTriangleIcon, { width: iconSize.lg, height: iconSize.lg }) }), (0, import_jsx_runtime19.jsx)(Spacer, { y: "md" }), (0, import_jsx_runtime19.jsx)(Text, { size: "lg", color: "primaryText", center: true, weight: 500, children: localeQuery.data.wrongNetworkScreen.title }), (0, import_jsx_runtime19.jsx)(Spacer, { y: "lg" }), (0, import_jsx_runtime19.jsx)(Text, { multiline: true, center: true, children: localeQuery.data.wrongNetworkScreen.subtitle }), (0, import_jsx_runtime19.jsx)(Spacer, { y: "xl" }), (0, import_jsx_runtime19.jsxs)(Container, { flex: "column", gap: "md", children: [(0, import_jsx_runtime19.jsxs)(Button, { type: "button", fullWidth: true, variant: "accent", style: { display: "flex", alignItems: "center", gap: spacing.sm }, onClick: async () => { if (!personalWallet.switchChain) { setPersonalWalletChainSwitchStatus("switch-error"); throw new Error("No switchChain method"); } try { setPersonalWalletChainSwitchStatus("switching"); await personalWallet.switchChain(smartWalletChain); const newChain = personalWallet.getChain(); if (newChain) { setPersonalWalletChainId(newChain.id); } setPersonalWalletChainSwitchStatus("idle"); } catch (e) { console.error(e); setPersonalWalletChainSwitchStatus("switch-error"); } }, children: [personalWalletChainSwitchStatus === "switching" ? "Switching" : "Switch Network", personalWalletChainSwitchStatus === "switching" && (0, import_jsx_runtime19.jsx)(Spinner, { size: "sm", color: "accentButtonText" })] }), (0, import_jsx_runtime19.jsxs)(Container, { flex: "row", gap: "sm", center: "both", color: "danger", style: { textAlign: "center", fontSize: fontSize.sm, opacity: personalWalletChainSwitchStatus === "switch-error" ? 1 : 0, transition: "opacity 200ms ease" }, children: [(0, import_jsx_runtime19.jsx)(ExclamationTriangleIcon, { width: iconSize.sm, height: iconSize.sm }), (0, import_jsx_runtime19.jsx)("span", { children: localeQuery.data.wrongNetworkScreen.failedToSwitch })] })] })] }) })] }); } if (smartWalletConnectionStatus === "connect-error") { return (0, import_jsx_runtime19.jsx)(Container, { fullHeight: true, animate: "fadein", flex: "column", center: "both", p: "lg", style: { minHeight: "300px" }, children: (0, import_jsx_runtime19.jsx)(Text, { color: "danger", children: localeQuery.data.failedToConnect }) }); } return (0, import_jsx_runtime19.jsxs)(Container, { fullHeight: true, flex: "column", center: "both", style: { minHeight: "300px" }, children: [(0, import_jsx_runtime19.jsx)(Text, { color: "primaryText", multiline: true, center: true, children: localeQuery.data.connecting }), (0, import_jsx_runtime19.jsx)(Spacer, { y: "lg" }), (0, import_jsx_runtime19.jsx)(Spinner, { color: "accentText", size: "lg" })] }); } // node_modules/thirdweb/dist/esm/react/web/ui/ConnectWallet/Modal/TOS.js var import_jsx_runtime20 = __toESM(require_jsx_runtime(), 1); function TOS(props) { const { termsOfServiceUrl, privacyPolicyUrl, locale, requireApproval } = props; if (!termsOfServiceUrl && !privacyPolicyUrl && !requireApproval) { return null; } const bothGiven = termsOfServiceUrl && privacyPolicyUrl; return (0, import_jsx_runtime20.jsx)(Container, { flex: "row", center: "x", children: (0, import_jsx_runtime20.jsxs)(Text, { size: "xs", multiline: true, balance: true, inline: true, center: true, style: { maxWidth: "250px" }, children: [requireApproval && (0, import_jsx_runtime20.jsx)("input", { style: { transform: "translateY(3px)", marginRight: spacing["3xs"] }, type: "checkbox", onChange: props.onApprove, checked: props.isApproved, disabled: !requireApproval }), locale.prefix, " ", termsOfServiceUrl && (0, import_jsx_runtime20.jsxs)(Link, { inline: true, size: "xs", href: termsOfServiceUrl, target: "_blank", style: { whiteSpace: "nowrap" }, children: [" ", locale.termsOfService, " "] }), bothGiven && `${locale.and} `, privacyPolicyUrl && (0, import_jsx_runtime20.jsx)(Link, { inline: true, size: "xs", href: privacyPolicyUrl, target: "_blank", children: locale.privacyPolicy }), !privacyPolicyUrl && !termsOfServiceUrl && (0, import_jsx_runtime20.jsx)(Text, { inline: true, size: "xs", children: "Terms of Service and Privacy Policy" })] }) }); } // node_modules/thirdweb/dist/esm/react/web/ui/ConnectWallet/PoweredByTW.js var import_jsx_runtime22 = __toESM(require_jsx_runtime(), 1); // node_modules/thirdweb/dist/esm/react/web/ui/ConnectWallet/icons/ThirdwebTextIcon.js var import_jsx_runtime21 = __toESM(require_jsx_runtime(), 1); var ThirdwebTextIcon = (props) => { return (0, import_jsx_runtime21.jsxs)("svg", { width: props.height * 74 / 11, height: props.height, viewBox: "0 0 74 11", fill: "none", xmlns: "http://www.w3.org/2000/svg", role: "presentation", children: [(0, import_jsx_runtime21.jsx)("path", { fillRule: "evenodd", clipRule: "evenodd", d: "M34.1489 0.373291C33.5297 0.373291 33.022 0.874761 33.022 1.51414C33.022 2.14097 33.5297 2.64244 34.1489 2.64244C34.7681 2.64244 35.2758 2.14097 35.2758 1.51414C35.2758 0.874761 34.7681 0.373291 34.1489 0.373291ZM35.1396 3.21913H33.1706V9.97644H35.1396V3.21913ZM21.6787 0.624035H23.5982V3.21914H25.0718V5.02444H23.5982V7.40642C23.5982 7.75745 23.8706 8.03326 24.205 8.03326H25.0594V9.95138H24.205C22.818 9.95138 21.6787 8.81054 21.6787 7.39389V5.0119H20.7871V3.20661H21.6787V0.624035ZM29.7652 3.0687C28.8736 3.0687 28.1677 3.44481 27.8953 4.03403V0.624035H25.9263V9.96392H27.8953V6.17782C27.8953 5.388 28.403 4.83639 29.1213 4.83639C29.8519 4.83639 30.2605 5.31278 30.2605 6.11514V9.97646H32.2295V5.8644C32.2295 4.10925 31.3379 3.0687 29.7652 3.0687ZM37.9507 3.2066V4.13432C38.2479 3.45734 38.9661 3.0687 39.8701 3.05616C40.0063 3.05616 40.1797 3.0687 40.3902 3.09377V4.97429C40.1921 4.93668 39.9692 4.9116 39.7339 4.9116C38.607 4.9116 37.9507 5.55098 37.9507 6.66675V9.96392H35.9817V3.2066H37.9507ZM45.9257 4.09672C45.7275 3.50749 44.9474 3.09378 43.9443 3.09378C43.0032 3.09378 42.2106 3.43227 41.5791 4.10926C40.9599 4.7737 40.6379 5.61367 40.6379 6.59154C40.6379 7.5694 40.9599 8.39683 41.5791 9.08635C42.2106 9.7508 43.0032 10.0893 43.9443 10.0893C44.9474 10.0893 45.7275 9.67558 45.9257 9.08635V9.97646H47.8946V0.624035H45.9257V4.09672ZM45.5294 7.79506C45.195 8.12102 44.7864 8.27146 44.3034 8.27146C43.8329 8.27146 43.4242 8.10848 43.1022 7.79506C42.7679 7.45657 42.6069 7.0554 42.6069 6.59154C42.6069 6.12767 42.7679 5.7265 43.1022 5.40054C43.4366 5.06205 43.8329 4.89907 44.3034 4.89907C44.7988 4.89907 45.2074 5.06205 45.5294 5.40054C45.8761 5.7265 46.0495 6.12767 46.0495 6.59154C46.0495 7.0554 45.8761 7.45657 45.5294 7.79506ZM53.5787 3.2442L55.3619 6.45361L56.5631 3.21913H58.4949L55.7458 10.3651L53.5787 6.47868L51.4115 10.3651L48.6748 3.21913H50.6066L51.7954 6.45361L53.5787 3.2442ZM61.7394 3.05616C60.7239 3.05616 59.8694 3.38212 59.2007 4.03403C58.5444 4.6734 58.2101 5.5259 58.2101 6.57899V6.64167C58.2101 7.69476 58.5444 8.54726 59.2007 9.18664C59.8818 9.81347 60.7487 10.1394 61.8384 10.1394C62.8539 10.1394 63.6836 9.93884 64.3151 9.52513V7.78252C63.6959 8.22131 62.9034 8.43443 61.9499 8.43443C60.9097 8.43443 60.2286 7.92042 60.1914 7.11807H65.0829C65.1077 6.91748 65.12 6.69182 65.12 6.46616C65.12 5.50083 64.7981 4.69848 64.1789 4.04657C63.5597 3.38212 62.73 3.05616 61.7394 3.05616ZM60.1914 5.82679C60.2038 5.51337 60.3648 5.25009 60.662 5.03697C60.9716 4.82385 61.3183 4.71101 61.7394 4.71101C62.5195 4.71101 63.1263 5.22502 63.1263 5.82679H60.1914ZM69.8135 3.09378C70.7546 3.09378 71.5472 3.43227 72.1663 4.10925C72.7979 4.78624 73.1199 5.60113 73.1199 6.579C73.1199 7.55686 72.7979 8.38429 72.1663 9.07381C71.5472 9.73826 70.7546 10.0768 69.8135 10.0768C68.8104 10.0768 68.0302 9.66304 67.8321 9.07381V9.96392H65.8631V0.624035H67.8321V4.09672C68.0302 3.50749 68.8104 3.09378 69.8135 3.09378ZM69.4543 8.27146C69.9249 8.27146 70.3212 8.12102 70.6555 7.79506C70.9899 7.45657 71.1509 7.05539 71.1509 6.59153C71.1509 6.12767 70.9899 5.7265 70.6555 5.40054C70.3336 5.06205 69.9249 4.89907 69.4543 4.89907C68.9714 4.89907 68.5627 5.06205 68.216 5.40054C67.8816 5.7265 67.7083 6.12767 67.7083 6.59153C67.7083 7.05539 67.8816 7.45657 68.216 7.79506C68.5503 8.10848 68.959 8.27146 69.4543 8.27146Z", fill: "currentColor" }), (0, import_jsx_runtime21.jsx)("g", { clipPath: "url(#clip0_5017_2727)", children: (0, import_jsx_runtime21.jsx)("path", { fillRule: "evenodd", clipRule: "evenodd", d: "M0.045011 0.900694C-0.126602 0.467742 0.193222 0 0.661257 0H3.56697C3.83999 0 4.08181 0.162357 4.18322 0.413623L6.49609 6.18115C6.55849 6.33578 6.55849 6.50973 6.49609 6.66822L5.04128 10.2903C4.81896 10.8431 4.03111 10.8431 3.80879 10.2903L0.045011 0.900694ZM5.65759 0.881366C5.50158 0.45228 5.8214 0 6.28164 0H8.81292C9.09374 0 9.34336 0.173954 9.43697 0.432951L11.5392 6.20048C11.5899 6.34351 11.5899 6.502 11.5392 6.6489L10.2755 10.1164C10.0649 10.6962 9.23805 10.6962 9.02744 10.1164L5.65759 0.881366ZM11.3404 0C10.8724 0 10.5525 0.467742 10.7241 0.900694L14.4879 10.2903C14.7102 10.8431 15.4981 10.8431 15.7204 10.2903L17.1752 6.66822C17.2376 6.50973 17.2376 6.33578 17.1752 6.18115L14.8623 0.413623C14.7609 0.162357 14.5191 0 14.2461 0H11.3404Z", fill: "currentColor" }) }), (0, import_jsx_runtime21.jsx)("defs", { children: (0, import_jsx_runtime21.jsx)("clipPath", { id: "clip0_5017_2727", children: (0, import_jsx_runtime21.jsx)("rect", { width: "17.219", height: "10.7049", fill: "white" }) }) })] }); }; // node_modules/thirdweb/dist/esm/react/web/ui/ConnectWallet/PoweredByTW.js function PoweredByThirdweb() { return (0, import_jsx_runtime22.jsx)(Link, { color: "secondaryText", hoverColor: "primaryText", target: "_blank", href: "https://thirdweb.com/connect?utm_source=cw_text", children: (0, import_jsx_runtime22.jsxs)(Container, { flex: "row", center: "both", style: { color: "currentColor", gap: 4 }, children: [(0, import_jsx_runtime22.jsx)(Text, { size: "sm", weight: 600, style: { color: "currentColor" }, children: "Powered by" }), (0, import_jsx_runtime22.jsx)(ThirdwebTextIcon, { height: 13 })] }) }); } // node_modules/thirdweb/dist/esm/react/web/ui/ConnectWallet/WalletSelector.js var InAppWalletSelectionUI = (0, import_react15.lazy)(() => import("./InAppWalletSelectionUI-QJ7CQPJG.js")); var inAppWalletId = "inApp"; function WalletSelector(props) { const [personalWallet, setPersonalWallet] = (0, import_react15.useState)(null); if (!props.accountAbstraction) { return (0, import_jsx_runtime23.jsx)(WalletSelectorInner, { ...props }); } if (personalWallet) { return (0, import_jsx_runtime23.jsx)(SmartConnectUI, { accountAbstraction: props.accountAbstraction, done: props.done, personalWallet, setModalVisibility: props.setModalVisibility, onBack: props.goBack, meta: props.meta, size: props.size, chain: props.chain, chains: props.chains, client: props.client, walletConnect: props.walletConnect, connectLocale: props.connectLocale }); } return (0, import_jsx_runtime23.jsx)(WalletSelectorInner, { ...props, done: (w) => { setPersonalWallet(w); } }); } var WalletSelectorInner = (props) => { const { walletIdsToHide } = props; const isCompact = props.size === "compact"; const [isWalletGroupExpanded, setIsWalletGroupExpanded] = (0, import_react15.useState)(false); const [approvedTOS, setApprovedTOS] = (0, import_react15.useState)(false); const installedWallets = getInstalledWallets(); const propsWallets = props.wallets; let _wallets = [...propsWallets]; for (const iW of installedWallets) { if (!propsWallets.find((w) => w.id === iW.id)) { _wallets.push(iW); } } if (walletIdsToHide) { _wallets = _wallets.filter((w) => !(walletIdsToHide == null ? void 0 : walletIdsToHide.includes(w.id))); } const localWalletConfig = false; const nonLocalWalletConfigs = _wallets; const socialWallets = nonLocalWalletConfigs.filter((w) => w.id === inAppWalletId); const eoaWallets = sortWallets(nonLocalWalletConfigs.filter((w) => w.id !== inAppWalletId), props.recommendedWallets); const continueAsGuest = localWalletConfig && (0, import_jsx_runtime23.jsx)(Button, { fullWidth: true, variant: isCompact ? "outline" : "link", style: !isCompact ? { textAlign: "left", justifyContent: "flex-start" } : void 0, onClick: () => { props.selectWallet(localWalletConfig); }, "data-test": "continue-as-guest-button", children: props.connectLocale.continueAsGuest }); const enableTWIconLink = (0, import_react15.useRef)(false); (0, import_react15.useEffect)(() => { setTimeout(() => { enableTWIconLink.current = true; }, 1e3); }, []); const twTitle = props.modalHeader ? (0, import_jsx_runtime23.jsx)(ModalHeader, { title: props.modalHeader.title, onBack: props.modalHeader.onBack }) : (0, import_jsx_runtime23.jsxs)(Container, { gap: "xxs", center: "y", flex: "row", children: [!props.meta.titleIconUrl ? null : (0, import_jsx_runtime23.jsx)(Img, { src: props.meta.titleIconUrl, width: iconSize.md, height: iconSize.md, client: props.client }), (0, import_jsx_runtime23.jsxs)(ModalTitle, { children: [" ", props.title, " "] })] }); const handleSelect = async (wallet) => { props.selectWallet(wallet); }; const connectAWallet = (0, import_jsx_runtime23.jsx)(WalletTypeRowButton, { client: props.client, icon: OutlineWalletIcon, onClick: () => { setIsWalletGroupExpanded(true); }, title: props.connectLocale.connectAWallet }); const newToWallets = (0, import_jsx_runtime23.jsxs)(Container, { flex: "row", style: { justifyContent: "space-between" }, children: [(0, import_jsx_runtime23.jsx)(Text, { color: "secondaryText", size: "sm", weight: 500, children: props.connectLocale.newToWallets }), (0, import_jsx_runtime23.jsx)(Link, { weight: 500, size: "sm", target: "_blank", href: "https://blog.thirdweb.com/web3-wallet/", children: props.connectLocale.getStarted })] }); const tos = props.meta.requireApproval || props.meta.termsOfServiceUrl || props.meta.privacyPolicyUrl ? (0, import_jsx_runtime23.jsx)(TOS, { termsOfServiceUrl: props.meta.termsOfServiceUrl, privacyPolicyUrl: props.meta.privacyPolicyUrl, locale: props.connectLocale.agreement, requireApproval: props.meta.requireApproval, isApproved: approvedTOS, onApprove: () => setApprovedTOS(!approvedTOS) }) : void 0; let topSection; let bottomSection; if (!isCompact) { topSection = (0, import_jsx_runtime23.jsx)(WalletSelection, { wallets: nonLocalWalletConfigs, selectWallet: handleSelect, done: props.done, goBack: props.goBack, onShowAll: props.onShowAll, client: props.client, connectLocale: props.connectLocale, size: props.size, recommendedWallets: props.recommendedWallets, chain: props.chain, showAllWallets: props.showAllWallets, diableSelectionDataReset: props.disableSelectionDataReset, disabled: props.meta.requireApproval && !approvedTOS }); if (continueAsGuest) { bottomSection = (0, import_jsx_runtime23.jsx)(ScreenBottomContainer, { children: continueAsGuest }); } } else { if (socialWallets.length === 0) { topSection = (0, import_jsx_runtime23.jsx)(WalletSelection, { wallets: nonLocalWalletConfigs, selectWallet: handleSelect, done: props.done, goBack: props.goBack, onShowAll: props.onShowAll, client: props.client, connectLocale: props.connectLocale, size: props.size, recommendedWallets: props.recommendedWallets, chain: props.chain, showAllWallets: props.showAllWallets, diableSelectionDataReset: props.disableSelectionDataReset, disabled: props.meta.requireApproval && !approvedTOS }); bottomSection = (0, import_jsx_runtime23.jsxs)(import_jsx_runtime23.Fragment, { children: [(0, import_jsx_runtime23.jsx)(Line, {}), (0, import_jsx_runtime23.jsxs)(Container, { flex: "column", p: "md", gap: "md", children: [newToWallets, continueAsGuest] }), !continueAsGuest && (0, import_jsx_runtime23.jsx)(Line, {}), tos && (0, import_jsx_runtime23.jsx)(Container, { px: "md", style: { paddingBottom: spacing.md, paddingTop: continueAsGuest ? 0 : spacing.md }, children: tos })] }); } else { if (!isWalletGroupExpanded) { topSection = (0, import_jsx_runtime23.jsxs)(Container, { px: "xs", children: [(0, import_jsx_runtime23.jsx)(WalletSelection, { wallets: socialWallets, selectWallet: handleSelect, done: props.done, goBack: props.goBack, client: props.client, connectLocale: props.connectLocale, size: props.size, recommendedWallets: props.recommendedWallets, chain: props.chain, showAllWallets: props.showAllWallets, diableSelectionDataReset: props.disableSelectionDataReset, disabled: props.meta.requireApproval && !approvedTOS }), eoaWallets.length > 0 && (0, import_jsx_runtime23.jsxs)(import_jsx_runtime23.Fragment, { children: [(0, import_jsx_runtime23.jsx)(TextDivider, { text: props.connectLocale.or }), (0, import_jsx_runtime23.jsx)(Spacer, { y: "lg" })] })] }); if (eoaWallets.length === 0) { bottomSection = tos || continueAsGuest ? (0, import_jsx_runtime23.jsxs)(import_jsx_runtime23.Fragment, { children: [(0, import_jsx_runtime23.jsx)(Spacer, { y: "md" }), (0, import_jsx_runtime23.jsx)(Line, {}), continueAsGuest && (0, import_jsx_runtime23.jsxs)(Container, { p: "lg", children: [" ", continueAsGuest] }), tos && (0, import_jsx_runtime23.jsxs)(Container, { p: "md", children: [" ", tos, " "] })] }) : (0, import_jsx_runtime23.jsx)(Spacer, { y: "sm" }); } else { if (eoaWallets.length > 1) { bottomSection = (0, import_jsx_runtime23.jsxs)(Container, { flex: "column", style: { position: "relative" }, gap: "sm", children: [(0, import_jsx_runtime23.jsx)(GradientDiv, {}), (0, import_jsx_runtime23.jsxs)(Container, { px: "lg", flex: "column", gap: "md", children: [connectAWallet, continueAsGuest] }), tos ? (0, import_jsx_runtime23.jsxs)(Container, { p: "md", children: [" ", tos, " "] }) : (0, import_jsx_runtime23.jsx)(Spacer, { y: "xxs" })] }); } else { bottomSection = (0, import_jsx_runtime23.jsxs)(import_jsx_runtime23.Fragment, { children: [(0, import_jsx_runtime23.jsx)(Container, { px: "lg", children: (0, import_jsx_runtime23.jsx)(WalletSelection, { wallets: eoaWallets, selectWallet: handleSelect, done: props.done, goBack: props.goBack, onShowAll: props.onShowAll, client: props.client, connectLocale: props.connectLocale, size: props.size, recommendedWallets: props.recommendedWallets, chain: props.chain, showAllWallets: props.showAllWallets, diableSelectionDataReset: props.disableSelectionDataReset, disabled: props.meta.requireApproval && !approvedTOS }) }), continueAsGuest && (0, import_jsx_runtime23.jsx)(Container, { flex: "column", px: "lg", gap: "lg", children: continueAsGuest }), tos ? (0, import_jsx_runtime23.jsxs)(import_jsx_runtime23.Fragment, { children: [continueAsGuest ? (0, import_jsx_runtime23.jsx)(Spacer, { y: "md" }) : (0, import_jsx_runtime23.jsx)(Line, {}), (0, import_jsx_runtime23.jsxs)(Container, { p: "md", children: [" ", tos, " "] })] }) : (0, import_jsx_runtime23.jsx)(import_jsx_runtime23.Fragment, { children: continueAsGuest && (0, import_jsx_runtime23.jsx)(Spacer, { y: "xl" }) })] }); } } } else { topSection = (0, import_jsx_runtime23.jsx)(WalletSelection, { wallets: eoaWallets, selectWallet: handleSelect, done: props.done, goBack: props.goBack, onShowAll: props.onShowAll, client: props.client, connectLocale: props.connectLocale, size: props.size, recommendedWallets: props.recommendedWallets, chain: props.chain, showAllWallets: props.showAllWallets, diableSelectionDataReset: props.disableSelectionDataReset, disabled: props.meta.requireApproval && !approvedTOS }); bottomSection = (0, import_jsx_runtime23.jsx)(ScreenBottomContainer, { children: newToWallets }); } } } const showHeader = !props.hideHeader || props.modalHeader; return (0, import_jsx_runtime23.jsxs)(Container, { scrollY: true, flex: "column", animate: "fadein", fullHeight: true, style: { maxHeight: props.size === "compact" ? compactModalMaxHeight : void 0 }, children: [showHeader && (0, import_jsx_runtime23.jsx)(Container, { p: "lg", children: isWalletGroupExpanded ? (0, import_jsx_runtime23.jsx)(ModalHeader, { title: twTitle, onBack: () => { setIsWalletGroupExpanded(false); } }) : twTitle }), (0, import_jsx_runtime23.jsxs)(Container, { expand: true, scrollY: true, px: "md", style: !showHeader ? { paddingTop: spacing.lg } : { paddingTop: "2px" }, children: [!showHeader && isWalletGroupExpanded && (0, import_jsx_runtime23.jsx)(Container, { flex: "row", center: "y", style: { padding: spacing.sm, paddingTop: 0 }, children: (0, import_jsx_runtime23.jsxs)(IconButton, { onClick: () => { setIsWalletGroupExpanded(false); }, style: { gap: spacing.xxs, transform: `translateX(-${spacing.xs})`, paddingBlock: spacing.xxs, paddingRight: spacing.xs }, children: [(0, import_jsx_runtime23.jsx)(ChevronLeftIcon, { width: iconSize.sm, height: iconSize.sm }), props.connectLocale.goBackButton] }) }), topSection] }), bottomSection, isCompact && props.meta.showThirdwebBranding !== false && (0, import_jsx_runtime23.jsx)(Container, { py: "md", children: (0, import_jsx_runtime23.jsx)(PoweredByThirdweb, {}) })] }); }; var _installedWallets = []; function getInstalledWallets() { if (_installedWallets.length === 0) { const providers = getInstalledWalletProviders(); const walletIds = providers.map((provider) => provider.info.rdns); _installedWallets = walletIds.map((w) => createWallet(w)); } return _installedWallets; } var WalletSelection = (props) => { const wallets = sortWallets(props.wallets, props.recommendedWallets); const { screen } = useScreenContext(); const setSelectionData = useSetSelectionData(); return (0, import_jsx_runtime23.jsxs)(WalletList, { style: { minHeight: "100%", maxHeight: "370px" }, children: [wallets.map((wallet) => { const isActive = screen ? typeof screen === "object" && screen.id === wallet.id : false; return (0, import_jsx_runtime23.jsx)("li", { children: wallet.id === "inApp" && props.size === "compact" ? (0, import_jsx_runtime23.jsx)(import_react15.Suspense, { fallback: (0, import_jsx_runtime23.jsx)(LoadingScreen, { height: "195px" }), children: (0, import_jsx_runtime23.jsx)(InAppWalletSelectionUI, { done: () => props.done(wallet), select: () => props.selectWallet(wallet), wallet, goBack: props.goBack, client: props.client, connectLocale: props.connectLocale, size: props.size, recommendedWallets: props.recommendedWallets, chain: props.chain, disabled: props.disabled }) }) : (0, import_jsx_runtime23.jsx)(WalletEntryButton, { walletId: wallet.id, selectWallet: () => { if (!props.diableSelectionDataReset) { setSelectionData({}); } props.selectWallet(wallet); }, connectLocale: props.connectLocale, client: props.client, recommendedWallets: props.recommendedWallets, isActive, badge: void 0 }) }, wallet.id); }), props.onShowAll && props.showAllWallets !== false && (0, import_jsx_runtime23.jsx)(ButtonContainer, { children: (0, import_jsx_runtime23.jsxs)(WalletButtonEl, { onClick: props.onShowAll, children: [(0, import_jsx_runtime23.jsxs)(ShowAllWalletsIcon, { children: [(0, import_jsx_runtime23.jsx)("div", { "data-dot": true }), (0, import_jsx_runtime23.jsx)("div", { "data-dot": true }), (0, import_jsx_runtime23.jsx)("div", { "data-dot": true }), (0, import_jsx_runtime23.jsx)("div", { "data-dot": true })] }), (0, import_jsx_runtime23.jsxs)(Container, { flex: "row", gap: "xs", children: [(0, import_jsx_runtime23.jsx)(Text, { color: "primaryText", children: "All Wallets" }), (0, import_jsx_runtime23.jsx)(BadgeText, { children: " 350+ " })] })] }) })] }); }; var BadgeText = StyledDiv(() => { const theme = useCustomTheme(); return { backgroundColor: theme.colors.secondaryButtonBg, paddingBlock: "3px", paddingInline: spacing.xxs, fontSize: fontSize.xs, borderRadius: radius.sm, color: theme.colors.secondaryText }; }); var ButtonContainer = StyledDiv(() => { const theme = useCustomTheme(); return { "&:hover [data-dot]": { background: theme.colors.primaryText } }; }); var ShowAllWalletsIcon = StyledDiv(() => { const theme = useCustomTheme(); return { width: `${iconSize.xl}px`, height: `${iconSize.xl}px`, backgroundColor: theme.colors.tertiaryBg, border: `2px solid ${theme.colors.borderColor}`, borderRadius: radius.md, display: "grid", gridTemplateColumns: "1fr 1fr", justifyItems: "center", alignItems: "center", padding: spacing.xs, "& div": { transition: "background 200ms ease", background: theme.colors.secondaryText, borderRadius: "50%", width: "10px", height: "10px" } }; }); var WalletList = StyledUl({ all: "unset", listStyleType: "none", display: "flex", flexDirection: "column", gap: "2px", boxSizing: "border-box", overflowY: "auto", flex: 1, ...noScrollBar, // to show the box-shadow of inputs that overflows padding: "2px", margin: "-2px", marginBottom: 0, paddingBottom: spacing.lg }); var GradientDiv = StyledDiv((_) => { const theme = useCustomTheme(); theme.colors.modalBg; return { height: spacing.lg, position: "absolute", top: `-${spacing.lg}`, left: 0, width: "100%", background: `linear-gradient(to bottom, transparent 0%, ${theme.colors.modalBg} 80%)`, pointerEvents: "none" }; }); // node_modules/thirdweb/dist/esm/react/web/wallets/defaultWallets.js function getDefaultWallets(options) { return [ createWallet("inApp"), createWallet(METAMASK), createWallet(COINBASE, { appMetadata: options == null ? void 0 : options.appMetadata, chains: options == null ? void 0 : options.chains }), createWallet(RAINBOW), createWallet("io.rabby"), createWallet(ZERION) ]; } // node_modules/thirdweb/dist/esm/react/web/wallets/in-app/WalletAuth.js function WalletAuth(props) { var _a; const { wallet, done } = props; const addConnectedWallet = useAddConnectedWallet(); const walletToConnect = (0, import_react16.useRef)(void 0); const [status, setStatus] = (0, import_react16.useState)("selecting"); const [error, setError] = (0, import_react16.useState)(); const [showAll, setShowAll] = (0, import_react16.useState)(false); const ecosystem = isEcosystemWallet(wallet) ? { id: wallet.id, partnerId: (_a = wallet.getConfig()) == null ? void 0 : _a.partnerId } : void 0; const back = () => { setStatus("selecting"); walletToConnect.current = void 0; props.onBack(); }; async function login(walletToLink) { setStatus("loading"); walletToConnect.current = walletToLink; try { if (props.isLinking) { await linkProfile({ client: props.client, strategy: "wallet", wallet: walletToLink, chain: wallet.getChain() || defineChain(1), ecosystem }).catch((e) => { setError(e.message); throw e; }); } else { await wallet.connect({ client: props.client, strategy: "wallet", wallet: walletToLink, chain: walletToLink.getChain() || defineChain(1) }); } addConnectedWallet(walletToLink); done(); } catch { setStatus("error"); } } if (!walletToConnect.current) { if (showAll) { return (0, import_jsx_runtime24.jsx)(import_react16.Suspense, { fallback: (0, import_jsx_runtime24.jsx)(LoadingScreen, {}), children: (0, import_jsx_runtime24.jsx)(AllWalletsUI_default, { onBack: () => setShowAll(false), onSelect: async (newWallet) => { login(newWallet); setShowAll(false); }, client: props.client, connectLocale: props.locale, recommendedWallets: void 0, specifiedWallets: [], size: props.size, disableSelectionDataReset: true }) }); } return (0, import_jsx_runtime24.jsx)(WalletSelector, { title: props.locale.connectAWallet, wallets: getDefaultWallets(), selectWallet: async (newWallet) => { login(newWallet); }, onShowAll: () => { setShowAll(true); }, done: () => { }, goBack: back, setModalVisibility: () => { }, client: props.client, connectLocale: props.locale, hideHeader: false, recommendedWallets: void 0, chain: wallet.getChain(), showAllWallets: true, chains: [], size: props.size, meta: props.meta || {}, walletConnect: props.walletConnect, modalHeader: { title: props.isLinking ? props.inAppLocale.linkWallet : props.inAppLocale.signInWithWallet, onBack: back }, walletIdsToHide: ["inApp"], disableSelectionDataReset: true }); } return (0, import_jsx_runtime24.jsxs)(Container, { animate: "fadein", fullHeight: true, flex: "column", children: [(0, import_jsx_runtime24.jsx)(Container, { p: "lg", children: (0, import_jsx_runtime24.jsx)(ModalHeader, { title: props.isLinking ? props.inAppLocale.linkWallet : props.inAppLocale.signInWithWallet, onBack: back }) }), (0, import_jsx_runtime24.jsx)(Container, { px: props.size === "wide" ? "xxl" : "lg", expand: true, flex: "column", center: "y", children: (0, import_jsx_runtime24.jsx)("div", { children: status === "error" ? (0, import_jsx_runtime24.jsxs)(import_jsx_runtime24.Fragment, { children: [(0, import_jsx_runtime24.jsx)(ErrorState, { onTryAgain: () => { if (!walletToConnect.current) { throw new Error("Failed to connect to unknown wallet"); } login(walletToConnect.current); }, title: error || "Failed to Login" }), (0, import_jsx_runtime24.jsx)(Spacer, { y: "lg" })] }) : (0, import_jsx_runtime24.jsx)(import_jsx_runtime24.Fragment, { children: (0, import_jsx_runtime24.jsx)(LoadingState, { title: "Sign in with your wallet", subtitle: "A pop-up prompt will appear to sign-in and verify your wallet", icon: (0, import_jsx_runtime24.jsx)(WalletImage, { id: walletToConnect.current.id ?? "", size: iconSize.xl, client: props.client }) }) }) }) })] }); } export { getDefaultWallets, AccentFailIcon, QRCode, wait2 as wait, GuestLogin, OTPLoginUI, PassKeyLogin, SocialLogin, TOS, PoweredByThirdweb, WalletAuth, AnyWalletConnectUI, SmartConnectUI, WalletSelector }; //# sourceMappingURL=chunk-7ZNEOXS2.js.map ================================================ FILE: 17-Crowd-Funding-Dapp/Frontend/.vite/deps_temp_6cf5ba4c/chunk-AARWH2GQ.js ================================================ import { Container, CustomThemeProvider, Skeleton, StyledButton, StyledCircle, StyledDiv, StyledInput, StyledLabel, StyledSvg, Text, WalletImage, fontSize, iconSize, keyframes, radius, spacing, useCustomTheme, useWalletInfo } from "./chunk-HI6IFF64.js"; import { require_jsx_runtime } from "./chunk-U3QNWT4A.js"; import { getInstalledWalletProviders } from "./chunk-PWFRCBEK.js"; import { require_react } from "./chunk-2MTJELC7.js"; import { __toESM } from "./chunk-SEVZ5PBP.js"; // node_modules/thirdweb/dist/esm/react/web/providers/wallet-ui-states-provider.js var import_jsx_runtime = __toESM(require_jsx_runtime(), 1); var import_react = __toESM(require_react(), 1); var WalletModalOpen = (0, import_react.createContext)(false); var SetWalletModalOpen = (0, import_react.createContext)(() => { }); var SelectionUIDataCtx = (0, import_react.createContext)({}); var SetSelectionUIDataCtx = (0, import_react.createContext)(() => { }); var WalletUIStatesProvider = (props) => { const [isWalletModalOpen, setIsWalletModalOpen] = (0, import_react.useState)(props.isOpen); const [selectionUIData, setSelectionUIData] = (0, import_react.useState)({}); return (0, import_jsx_runtime.jsx)(WalletModalOpen.Provider, { value: isWalletModalOpen, children: (0, import_jsx_runtime.jsx)(SetWalletModalOpen.Provider, { value: setIsWalletModalOpen, children: (0, import_jsx_runtime.jsx)(SelectionUIDataCtx.Provider, { value: selectionUIData, children: (0, import_jsx_runtime.jsx)(SetSelectionUIDataCtx.Provider, { value: setSelectionUIData, children: (0, import_jsx_runtime.jsx)(CustomThemeProvider, { theme: props.theme, children: props.children }) }) }) }) }); }; var useIsWalletModalOpen = () => { return (0, import_react.useContext)(WalletModalOpen); }; var useSetIsWalletModalOpen = () => { const context = (0, import_react.useContext)(SetWalletModalOpen); if (context === void 0) { throw new Error("useSetWalletModalOpen must be used within a ThirdwebProvider"); } return context; }; function useSetSelectionData() { return (0, import_react.useContext)(SetSelectionUIDataCtx); } function useSelectionData() { return (0, import_react.useContext)(SelectionUIDataCtx); } // node_modules/thirdweb/dist/esm/react/web/ui/components/Spinner.js var import_jsx_runtime2 = __toESM(require_jsx_runtime(), 1); var Spinner = (props) => { const theme = useCustomTheme(); return (0, import_jsx_runtime2.jsx)(Svg, { style: { width: `${iconSize[props.size]}px`, height: `${iconSize[props.size]}px` }, viewBox: "0 0 50 50", children: (0, import_jsx_runtime2.jsx)(Circle, { cx: "25", cy: "25", r: "20", fill: "none", stroke: theme.colors[props.color], strokeWidth: Number(iconSize[props.size]) > 64 ? "2" : "4" }) }); }; var dashAnimation = keyframes` 0% { stroke-dasharray: 1, 150; stroke-dashoffset: 0; } 50% { stroke-dasharray: 90, 150; stroke-dashoffset: -35; } 100% { stroke-dasharray: 90, 150; stroke-dashoffset: -124; } `; var rotateAnimation = keyframes` 100% { transform: rotate(360deg); } `; var Svg = StyledSvg({ animation: `${rotateAnimation} 2s linear infinite`, width: "1em", height: "1em" }); var Circle = StyledCircle({ strokeLinecap: "round", animation: `${dashAnimation} 1.5s ease-in-out infinite` }); // node_modules/thirdweb/dist/esm/react/web/ui/components/formElements.js var Label = StyledLabel((props) => { const theme = useCustomTheme(); return { fontSize: fontSize.sm, color: theme.colors[props.color || "primaryText"], display: "block", fontWeight: 500 }; }); var Input = StyledInput((props) => { const theme = useCustomTheme(); return { fontSize: fontSize.md, fontFamily: "inherit", display: "block", padding: props.sm ? spacing.sm : fontSize.sm, boxSizing: "border-box", width: "100%", outline: "none", border: "none", borderRadius: radius.md, color: theme.colors.primaryText, WebkitAppearance: "none", appearance: "none", background: "transparent", "&::placeholder": { color: theme.colors.secondaryText }, boxShadow: `0 0 0 1.5px ${props.variant === "outline" ? theme.colors.borderColor : "transparent"}`, "&:-webkit-autofill": { WebkitTextFillColor: theme.colors.primaryText, WebkitBoxShadow: `0 0 0px 1000px ${theme.colors.inputAutofillBg} inset !important`, boxShadow: `0 0 0px 1000px ${theme.colors.inputAutofillBg} inset !important`, transition: "background-color 5000s ease-in-out 0s" }, "&:-webkit-autofill:focus": { WebkitBoxShadow: `0 0 0px 1000px ${theme.colors.inputAutofillBg} inset, 0 0 0 2px ${props.variant === "outline" ? theme.colors.accentText : "transparent"} !important`, boxShadow: `0 0 0px 1000px ${theme.colors.inputAutofillBg} inset, 0 0 0 2px ${props.variant === "outline" ? theme.colors.accentText : "transparent"} !important` }, "&[data-placeholder='true']": { color: theme.colors.secondaryText }, "&:focus": { boxShadow: `0 0 0 2px ${theme.colors.accentText}` }, "&[data-focus='false']:focus": { boxShadow: "none" }, "&:not([type='password'])": { overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }, "&[data-error='true']": { boxShadow: `0 0 0 2px ${theme.colors.danger} !important` }, "&[disabled]": { cursor: "not-allowed" }, "&[type='number']::-webkit-outer-spin-button, &[type='number']::-webkit-inner-spin-button": { WebkitAppearance: "none", margin: 0 }, "&[type='number']": { appearance: "none", MozAppearance: "textfield" } }; }); var InputContainer = StyledDiv(() => { const theme = useCustomTheme(); return { display: "flex", borderRadius: radius.md, boxShadow: `0 0 0px 1px ${theme.colors.borderColor}`, "&:focus-within": { boxShadow: `0 0 0px 1px ${theme.colors.accentText}` }, "input:focus": { boxShadow: "none" }, // show error ring on container instead of input "&[data-error='true']": { boxShadow: `0 0 0px 1px ${theme.colors.danger}` } }; }); // node_modules/thirdweb/dist/esm/react/web/ui/ConnectWallet/WalletEntryButton.js var import_jsx_runtime3 = __toESM(require_jsx_runtime(), 1); function WalletEntryButton(props) { var _a, _b, _c; const { walletId, selectWallet } = props; const isRecommended = (_a = props.recommendedWallets) == null ? void 0 : _a.find((w) => w.id === walletId); const walletInfo = useWalletInfo(walletId); const walletName = ((_b = getInstalledWalletProviders().find((p) => p.info.rdns === walletId)) == null ? void 0 : _b.info.name) || ((_c = walletInfo.data) == null ? void 0 : _c.name); const isInstalled = getInstalledWalletProviders().find((p) => p.info.rdns === walletId); return (0, import_jsx_runtime3.jsxs)(WalletButtonEl, { type: "button", onClick: selectWallet, "data-active": props.isActive, children: [(0, import_jsx_runtime3.jsx)(WalletImage, { id: walletId, size: iconSize.xl, client: props.client }), (0, import_jsx_runtime3.jsxs)(Container, { flex: "column", gap: "xxs", expand: true, children: [walletName ? (0, import_jsx_runtime3.jsx)(Text, { color: "primaryText", weight: 600, children: walletName }) : (0, import_jsx_runtime3.jsx)(Skeleton, { width: "100px", height: fontSize.md }), props.badge ? (0, import_jsx_runtime3.jsx)(Text, { size: "sm", children: props.badge }) : isRecommended ? (0, import_jsx_runtime3.jsx)(Text, { size: "sm", children: props.connectLocale.recommended }) : isInstalled ? (0, import_jsx_runtime3.jsx)(Text, { size: "sm", children: props.connectLocale.installed }) : null] })] }); } var WalletButtonEl = StyledButton((_) => { const theme = useCustomTheme(); return { all: "unset", display: "flex", alignItems: "center", gap: spacing.sm, cursor: "pointer", boxSizing: "border-box", width: "100%", color: theme.colors.secondaryText, position: "relative", borderRadius: radius.md, padding: `${spacing.xs} ${spacing.xs}`, "&:hover": { backgroundColor: theme.colors.tertiaryBg, transform: "scale(1.01)" }, '&[data-active="true"]': { backgroundColor: theme.colors.tertiaryBg }, transition: "background-color 200ms ease, transform 200ms ease" }; }); export { WalletUIStatesProvider, useIsWalletModalOpen, useSetIsWalletModalOpen, useSetSelectionData, useSelectionData, Spinner, Label, Input, InputContainer, WalletEntryButton, WalletButtonEl }; //# sourceMappingURL=chunk-AARWH2GQ.js.map ================================================ FILE: 17-Crowd-Funding-Dapp/Frontend/.vite/deps_temp_6cf5ba4c/chunk-ADIC4TC2.js ================================================ import { sendTransaction } from "./chunk-JTR2PIFP.js"; import { waitForReceipt } from "./chunk-JBQP4JIV.js"; // node_modules/thirdweb/dist/esm/transaction/actions/send-and-confirm-transaction.js async function sendAndConfirmTransaction(options) { const submittedTx = await sendTransaction(options); return waitForReceipt(submittedTx); } export { sendAndConfirmTransaction }; //# sourceMappingURL=chunk-ADIC4TC2.js.map ================================================ FILE: 17-Crowd-Funding-Dapp/Frontend/.vite/deps_temp_6cf5ba4c/chunk-AG4NO6K6.js ================================================ import { isAbiFunction, prepareMethod } from "./chunk-NPJBMLFY.js"; import { encodeAbiParameters } from "./chunk-U7TO6S3N.js"; import { decodeAbiParameters, parseAbiItem } from "./chunk-GINVHONX.js"; import { getRpcClient } from "./chunk-I5DK3TWY.js"; import { numberToHex } from "./chunk-BBNNHC5G.js"; // node_modules/thirdweb/dist/esm/rpc/actions/eth_call.js function encodeStateOverrides(overrides) { return Object.fromEntries(Object.entries(overrides).map(([address, override]) => { return [ address, { balance: override.balance ? numberToHex(override.balance) : void 0, nonce: override.nonce ? numberToHex(override.nonce) : void 0, code: override.code, state: override.state, stateDiff: override.stateDiff } ]; })); } async function eth_call(request, params) { const { blockNumber, blockTag, ...txRequest } = params; const blockNumberHex = blockNumber ? numberToHex(blockNumber) : void 0; const block = blockNumberHex || blockTag || "latest"; return await request({ method: "eth_call", params: params.stateOverrides ? [ txRequest, block, encodeStateOverrides(params.stateOverrides) ] : [txRequest, block] }); } // node_modules/thirdweb/dist/esm/transaction/read-contract.js async function readContract(options) { const { contract, method, params } = options; const resolvePreparedMethod = async () => { var _a, _b; if (Array.isArray(method)) { return method; } if (isAbiFunction(method)) { return prepareMethod(method); } if (typeof method === "function") { return prepareMethod( // @ts-expect-error - we're sure it's a function await method(contract) ); } if (typeof method === "string" && method.startsWith("function ")) { const abiItem = parseAbiItem(method); if (abiItem.type === "function") { return prepareMethod(abiItem); } throw new Error(`"method" passed is not of type "function"`); } if (contract.abi && ((_a = contract.abi) == null ? void 0 : _a.length) > 0) { const abiFunction = (_b = contract.abi) == null ? void 0 : _b.find((item) => item.type === "function" && item.name === method); if (abiFunction) { return prepareMethod(abiFunction); } } throw new Error(`Could not resolve method "${method}".`); }; const [resolvedPreparedMethod, resolvedParams] = await Promise.all([ resolvePreparedMethod(), typeof params === "function" ? params() : params ]); let encodedData; if (resolvedPreparedMethod[1].length === 0) { encodedData = resolvedPreparedMethod[0]; } else { encodedData = resolvedPreparedMethod[0] + encodeAbiParameters( resolvedPreparedMethod[1], // @ts-expect-error - TODO: fix this type issue resolvedParams ).slice(2); } const rpcRequest = getRpcClient({ chain: contract.chain, client: contract.client }); const result = await eth_call(rpcRequest, { data: encodedData, to: contract.address, from: options.from }); const decoded = decodeAbiParameters(resolvedPreparedMethod[2], result); if (Array.isArray(decoded) && decoded.length === 1) { return decoded[0]; } return decoded; } export { eth_call, readContract }; //# sourceMappingURL=chunk-AG4NO6K6.js.map ================================================ FILE: 17-Crowd-Funding-Dapp/Frontend/.vite/deps_temp_6cf5ba4c/chunk-AWMNEQRO.js ================================================ import { once, prepareContractCall } from "./chunk-6XF6HOWC.js"; // node_modules/thirdweb/dist/esm/extensions/erc20/__generated__/IERC20/write/approve.js var FN_SELECTOR = "0x095ea7b3"; var FN_INPUTS = [ { type: "address", name: "spender" }, { type: "uint256", name: "value" } ]; var FN_OUTPUTS = [ { type: "bool" } ]; function approve(options) { const asyncOptions = once(async () => { return "asyncParams" in options ? await options.asyncParams() : options; }); return prepareContractCall({ contract: options.contract, method: [FN_SELECTOR, FN_INPUTS, FN_OUTPUTS], params: async () => { const resolvedOptions = await asyncOptions(); return [resolvedOptions.spender, resolvedOptions.value]; }, value: async () => { var _a; return (_a = (await asyncOptions()).overrides) == null ? void 0 : _a.value; }, accessList: async () => { var _a; return (_a = (await asyncOptions()).overrides) == null ? void 0 : _a.accessList; }, gas: async () => { var _a; return (_a = (await asyncOptions()).overrides) == null ? void 0 : _a.gas; }, gasPrice: async () => { var _a; return (_a = (await asyncOptions()).overrides) == null ? void 0 : _a.gasPrice; }, maxFeePerGas: async () => { var _a; return (_a = (await asyncOptions()).overrides) == null ? void 0 : _a.maxFeePerGas; }, maxPriorityFeePerGas: async () => { var _a; return (_a = (await asyncOptions()).overrides) == null ? void 0 : _a.maxPriorityFeePerGas; }, nonce: async () => { var _a; return (_a = (await asyncOptions()).overrides) == null ? void 0 : _a.nonce; }, extraGas: async () => { var _a; return (_a = (await asyncOptions()).overrides) == null ? void 0 : _a.extraGas; }, erc20Value: async () => { var _a; return (_a = (await asyncOptions()).overrides) == null ? void 0 : _a.erc20Value; } }); } export { approve }; //# sourceMappingURL=chunk-AWMNEQRO.js.map ================================================ FILE: 17-Crowd-Funding-Dapp/Frontend/.vite/deps_temp_6cf5ba4c/chunk-B7XHB4Z2.js ================================================ import { isHex } from "./chunk-BBNNHC5G.js"; import { fromBoolean2 as fromBoolean, fromHex, fromNumber2 as fromNumber, fromString2 as fromString } from "./chunk-Y3WKETHV.js"; // node_modules/thirdweb/dist/esm/utils/encoding/to-bytes.js function toBytes(value, opts = {}) { switch (typeof value) { case "number": case "bigint": return numberToBytes(value, opts); case "boolean": return boolToBytes(value, opts); default: if (isHex(value)) { return hexToBytes(value, opts); } return stringToBytes(value, opts); } } function boolToBytes(value, opts = {}) { return fromBoolean(value, opts); } function hexToBytes(hex_, opts = {}) { return fromHex(hex_, opts); } function numberToBytes(value, opts) { return fromNumber(value, opts); } function stringToBytes(value, opts = {}) { return fromString(value, opts); } export { toBytes, boolToBytes, hexToBytes, numberToBytes, stringToBytes }; //# sourceMappingURL=chunk-B7XHB4Z2.js.map ================================================ FILE: 17-Crowd-Funding-Dapp/Frontend/.vite/deps_temp_6cf5ba4c/chunk-BBNNHC5G.js ================================================ import { fromBoolean, fromBytes, fromNumber, fromString, padLeft, padRight, toBigInt, toBoolean, toBytes, toNumber, toString, validate } from "./chunk-Y3WKETHV.js"; // node_modules/thirdweb/dist/esm/utils/encoding/helpers/is-hex.js function isHex(value, options = {}) { return validate(value, options); } // node_modules/thirdweb/dist/esm/utils/encoding/hex.js function padHex(hex_, options = {}) { const { dir, size = 32 } = options; if (size === null) { return hex_; } if (dir === "right") { return padRight(hex_, size); } return padLeft(hex_, size); } function hexToString(hex, opts = {}) { return toString(hex, opts); } function hexToBigInt(hex, opts = {}) { return toBigInt(hex, opts); } function hexToNumber(hex, opts = {}) { return toNumber(hex, opts); } function hexToBool(hex, opts = {}) { return toBoolean(hex, opts); } function hexToUint8Array(hex, opts = {}) { return toBytes(hex, opts); } function fromHex(hex, toOrOpts) { const opts = typeof toOrOpts === "string" ? { to: toOrOpts } : toOrOpts; switch (opts.to) { case "number": return hexToNumber(hex, opts); case "bigint": return hexToBigInt(hex, opts); case "string": return hexToString(hex, opts); case "boolean": return hexToBool(hex, opts); default: return hexToUint8Array(hex, opts); } } function boolToHex(value, opts = {}) { return fromBoolean(value, opts); } function uint8ArrayToHex(value, opts = {}) { return fromBytes(value, opts); } function numberToHex(value_, opts = {}) { return fromNumber(value_, opts); } function stringToHex(value_, opts = {}) { return fromString(value_, opts); } function toHex(value, opts = {}) { switch (typeof value) { case "number": case "bigint": return numberToHex(value, opts); case "string": return stringToHex(value, opts); case "boolean": return boolToHex(value, opts); default: return uint8ArrayToHex(value, opts); } } export { isHex, padHex, hexToString, hexToBigInt, hexToNumber, hexToBool, hexToUint8Array, fromHex, boolToHex, uint8ArrayToHex, numberToHex, stringToHex, toHex }; //# sourceMappingURL=chunk-BBNNHC5G.js.map ================================================ FILE: 17-Crowd-Funding-Dapp/Frontend/.vite/deps_temp_6cf5ba4c/chunk-BZXRHH4X.js ================================================ // node_modules/thirdweb/dist/esm/wallets/constants.js var COINBASE = "com.coinbase.wallet"; var METAMASK = "io.metamask"; var RAINBOW = "me.rainbow"; var ZERION = "io.zerion.wallet"; export { COINBASE, METAMASK, RAINBOW, ZERION }; //# sourceMappingURL=chunk-BZXRHH4X.js.map ================================================ FILE: 17-Crowd-Funding-Dapp/Frontend/.vite/deps_temp_6cf5ba4c/chunk-CLN3QXW2.js ================================================ import { track } from "./chunk-N24CESYN.js"; // node_modules/thirdweb/dist/esm/analytics/track/connect.js async function trackConnect(args) { const { client, ecosystem, walletType, walletAddress, chainId } = args; return track({ client, ecosystem, data: { source: "connectWallet", action: "connect", walletType, walletAddress, chainId } }); } // node_modules/thirdweb/dist/esm/utils/tiny-emitter.js function createEmitter() { const subsribers = /* @__PURE__ */ new Map(); return { subscribe(event, cb) { var _a; if (!subsribers.has(event)) { subsribers.set(event, /* @__PURE__ */ new Set([cb])); } else { (_a = subsribers.get(event)) == null ? void 0 : _a.add(cb); } return () => { const subscribers = subsribers.get(event); if (subscribers) { subscribers.delete(cb); } }; }, emit(event, data) { const subscribers = subsribers.get(event); if (subscribers) { for (const cb of subscribers) { cb(data); } } } }; } // node_modules/thirdweb/dist/esm/wallets/wallet-emitter.js function createWalletEmitter() { return createEmitter(); } export { trackConnect, createWalletEmitter }; //# sourceMappingURL=chunk-CLN3QXW2.js.map ================================================ FILE: 17-Crowd-Funding-Dapp/Frontend/.vite/deps_temp_6cf5ba4c/chunk-CNLOA7AS.js ================================================ // node_modules/thirdweb/dist/esm/transaction/prepare-transaction.js function prepareTransaction(options, info) { if (info) { options.__preparedMethod = info.preparedMethod; options.__contract = info.contract; } return options; } export { prepareTransaction }; //# sourceMappingURL=chunk-CNLOA7AS.js.map ================================================ FILE: 17-Crowd-Funding-Dapp/Frontend/.vite/deps_temp_6cf5ba4c/chunk-CXAZLQ2Z.js ================================================ import { formatBlock } from "./chunk-LO5SQBMX.js"; import { numberToHex } from "./chunk-BBNNHC5G.js"; // node_modules/thirdweb/dist/esm/rpc/actions/eth_getBlockByNumber.js async function eth_getBlockByNumber(request, params) { const blockTag = params.blockTag ?? "latest"; const includeTransactions = params.includeTransactions ?? false; const blockNumberHex = params.blockNumber !== void 0 ? numberToHex(params.blockNumber) : void 0; const block = await request({ method: "eth_getBlockByNumber", params: [blockNumberHex || blockTag, includeTransactions] }); if (!block) { throw new Error("Block not found"); } return formatBlock(block); } export { eth_getBlockByNumber }; //# sourceMappingURL=chunk-CXAZLQ2Z.js.map ================================================ FILE: 17-Crowd-Funding-Dapp/Frontend/.vite/deps_temp_6cf5ba4c/chunk-CYVKJMZE.js ================================================ // node_modules/thirdweb/dist/esm/wallets/in-app/core/constants/settings.js var IN_APP_WALLET_PATH = "/sdk/2022-08-12/embedded-wallet"; var WALLET_USER_ID_LOCAL_STORAGE_NAME = (cliekeytId) => `thirdwebEwsWalletUserId-${cliekeytId}`; var AUTH_TOKEN_LOCAL_STORAGE_PREFIX = "walletToken"; var AUTH_TOKEN_LOCAL_STORAGE_NAME = (key) => { return `${AUTH_TOKEN_LOCAL_STORAGE_PREFIX}-${key}`; }; var PASSKEY_CREDENTIAL_ID_LOCAL_STORAGE_NAME = (key) => { return `passkey-credential-id-${key}`; }; var DEVICE_SHARE_LOCAL_STORAGE_PREFIX = "a"; var DEVICE_SHARE_LOCAL_STORAGE_NAME = (key, userId) => `${DEVICE_SHARE_LOCAL_STORAGE_PREFIX}-${key}-${userId}`; var WALLET_CONNECT_SESSIONS_LOCAL_STORAGE_NAME = (key) => `walletConnectSessions-${key}`; var GUEST_SESSION_LOCAL_STORAGE_NAME = (key) => `thirdweb_guest_session_id_${key}`; // node_modules/thirdweb/dist/esm/wallets/in-app/core/authentication/client-scoped-storage.js var data = /* @__PURE__ */ new Map(); var ClientScopedStorage = class { /** * @internal */ constructor({ storage, clientId, ecosystem }) { Object.defineProperty(this, "key", { enumerable: true, configurable: true, writable: true, value: void 0 }); Object.defineProperty(this, "storage", { enumerable: true, configurable: true, writable: true, value: void 0 }); Object.defineProperty(this, "ecosystem", { enumerable: true, configurable: true, writable: true, value: void 0 }); this.storage = storage; this.key = getLocalStorageKey(clientId, ecosystem == null ? void 0 : ecosystem.id); this.ecosystem = ecosystem; } async getItem(key) { if (this.storage) { return this.storage.getItem(key); } return data.get(key) ?? null; } async setItem(key, value) { if (this.storage) { return this.storage.setItem(key, value); } data.set(key, value); } async removeItem(key) { const item = await this.getItem(key); if (this.storage && item) { this.storage.removeItem(key); return true; } return false; } /** * @internal */ async getWalletConnectSessions() { return this.getItem(WALLET_CONNECT_SESSIONS_LOCAL_STORAGE_NAME(this.key)); } /** * @internal */ async saveWalletConnectSessions(stringifiedSessions) { await this.setItem(WALLET_CONNECT_SESSIONS_LOCAL_STORAGE_NAME(this.key), stringifiedSessions); } /** * @internal */ async savePasskeyCredentialId(id) { await this.setItem(PASSKEY_CREDENTIAL_ID_LOCAL_STORAGE_NAME(this.key), id); } /** * @internal */ async getPasskeyCredentialId() { return this.getItem(PASSKEY_CREDENTIAL_ID_LOCAL_STORAGE_NAME(this.key)); } /** * @internal */ async saveAuthCookie(cookie) { await this.setItem(AUTH_TOKEN_LOCAL_STORAGE_NAME(this.key), cookie); } /** * @internal */ async getAuthCookie() { return this.getItem(AUTH_TOKEN_LOCAL_STORAGE_NAME(this.key)); } /** * @internal */ async removeAuthCookie() { return this.removeItem(AUTH_TOKEN_LOCAL_STORAGE_NAME(this.key)); } /** * @internal */ async saveDeviceShare(share, userId) { await this.saveWalletUserId(userId); await this.setItem(DEVICE_SHARE_LOCAL_STORAGE_NAME(this.key, userId), share); } /** * @internal */ async getDeviceShare() { const userId = await this.getWalletUserId(); if (userId) { return this.getItem(DEVICE_SHARE_LOCAL_STORAGE_NAME(this.key, userId)); } return null; } /** * @internal */ async removeDeviceShare() { const userId = await this.getWalletUserId(); if (userId) { return this.removeItem(DEVICE_SHARE_LOCAL_STORAGE_NAME(this.key, userId)); } return false; } /** * @internal */ async getWalletUserId() { return this.getItem(WALLET_USER_ID_LOCAL_STORAGE_NAME(this.key)); } /** * @internal */ async saveWalletUserId(userId) { await this.setItem(WALLET_USER_ID_LOCAL_STORAGE_NAME(this.key), userId); } /** * @internal */ async removeWalletUserId() { return this.removeItem(WALLET_USER_ID_LOCAL_STORAGE_NAME(this.key)); } /** * @internal */ async getGuestSessionId() { return this.getItem(GUEST_SESSION_LOCAL_STORAGE_NAME(this.key)); } /** * @internal */ async saveGuestSessionId(sessionId) { await this.setItem(GUEST_SESSION_LOCAL_STORAGE_NAME(this.key), sessionId); } }; var getLocalStorageKey = (clientId, ecosystemId) => { return `${clientId}${ecosystemId ? `-${ecosystemId}` : ""}`; }; export { IN_APP_WALLET_PATH, ClientScopedStorage }; //# sourceMappingURL=chunk-CYVKJMZE.js.map ================================================ FILE: 17-Crowd-Funding-Dapp/Frontend/.vite/deps_temp_6cf5ba4c/chunk-DYKFWRMQ.js ================================================ import { encodeEventTopics, parseEventLogs } from "./chunk-LO5SQBMX.js"; import { parseAbiItem, toSignatureHash } from "./chunk-GINVHONX.js"; // node_modules/thirdweb/dist/esm/event/utils.js function isAbiEvent(item) { return !!(item && typeof item === "object" && "type" in item && item.type === "event"); } // node_modules/thirdweb/dist/esm/event/prepare-event.js function prepareEvent(options) { const { signature } = options; let resolvedSignature; if (isAbiEvent(signature)) { resolvedSignature = signature; } else { resolvedSignature = parseAbiItem(signature); } return { abiEvent: resolvedSignature, hash: toSignatureHash(resolvedSignature), // @ts-expect-error - TODO: investiagte why this complains, it works fine however topics: encodeEventTopics({ abi: [resolvedSignature], args: options.filters }) }; } // node_modules/thirdweb/dist/esm/event/actions/parse-logs.js function parseEventLogs2(options) { const { logs, events, strict } = options; return parseEventLogs({ logs, abi: events.map((e) => e.abiEvent), strict }); } export { isAbiEvent, prepareEvent, parseEventLogs2 as parseEventLogs }; //# sourceMappingURL=chunk-DYKFWRMQ.js.map ================================================ FILE: 17-Crowd-Funding-Dapp/Frontend/.vite/deps_temp_6cf5ba4c/chunk-EGJT3UEX.js ================================================ import { GuestLogin, OTPLoginUI, PassKeyLogin, PoweredByThirdweb, SocialLogin, TOS, WalletAuth } from "./chunk-7ZNEOXS2.js"; import { ConnectWalletSocialOptions, LoadingScreen, useInAppWalletLocale, useScreenContext } from "./chunk-KWA5PGSC.js"; import { useSelectionData, useSetSelectionData } from "./chunk-AARWH2GQ.js"; import { Container, Img, ModalHeader, ModalTitle, Skeleton, Spacer, iconSize, radius, useWalletInfo } from "./chunk-HI6IFF64.js"; import { require_jsx_runtime } from "./chunk-U3QNWT4A.js"; import { require_react } from "./chunk-2MTJELC7.js"; import { __toESM } from "./chunk-SEVZ5PBP.js"; // node_modules/thirdweb/dist/esm/react/web/wallets/ecosystem/EcosystemWalletConnectUI.js var import_jsx_runtime3 = __toESM(require_jsx_runtime(), 1); // node_modules/thirdweb/dist/esm/react/web/wallets/ecosystem/EcosystemWalletFormUI.js var import_jsx_runtime2 = __toESM(require_jsx_runtime(), 1); var import_react = __toESM(require_react(), 1); // node_modules/thirdweb/dist/esm/react/web/wallets/ecosystem/EcosystemWalletHeader.js var import_jsx_runtime = __toESM(require_jsx_runtime(), 1); function EcosystemWalletHeader(props) { var _a, _b, _c; const walletInfo = useWalletInfo(props.wallet.id); return (0, import_jsx_runtime.jsx)(ModalHeader, { onBack: props.onBack, title: walletInfo.isLoading ? (0, import_jsx_runtime.jsx)(Skeleton, { height: "24px", width: "200px" }) : (0, import_jsx_runtime.jsxs)(import_jsx_runtime.Fragment, { children: [!((_a = walletInfo.data) == null ? void 0 : _a.image_id) ? null : (0, import_jsx_runtime.jsx)(Img, { src: (_b = walletInfo.data) == null ? void 0 : _b.image_id, style: { borderRadius: radius.sm }, width: iconSize.md, height: iconSize.md, client: props.client }), (0, import_jsx_runtime.jsx)(ModalTitle, { children: (_c = walletInfo.data) == null ? void 0 : _c.name })] }), leftAligned: true }); } // node_modules/thirdweb/dist/esm/react/web/wallets/ecosystem/EcosystemWalletFormUI.js function EcosystemWalletFormUIScreen(props) { const isCompact = props.size === "compact"; const { initialScreen, screen } = useScreenContext(); const [isApproved, setIsApproved] = (0, import_react.useState)(false); const onBack = screen === props.wallet && initialScreen === props.wallet ? void 0 : props.goBack; return (0, import_jsx_runtime2.jsxs)(Container, { fullHeight: true, flex: "column", p: "lg", animate: "fadein", style: { minHeight: "250px" }, children: [props.isLinking ? (0, import_jsx_runtime2.jsx)(ModalHeader, { title: props.connectLocale.manageWallet.linkProfile, onBack }) : (0, import_jsx_runtime2.jsx)(EcosystemWalletHeader, { client: props.client, onBack: isCompact ? onBack : void 0, wallet: props.wallet }), (0, import_jsx_runtime2.jsx)(Spacer, { y: "lg" }), (0, import_jsx_runtime2.jsx)(Container, { expand: true, flex: "column", center: "y", p: isCompact ? void 0 : "lg", children: (0, import_jsx_runtime2.jsx)(ConnectWalletSocialOptions, { disabled: props.meta.requireApproval && !isApproved, ...props }) }), isCompact && (props.meta.showThirdwebBranding !== false || props.meta.termsOfServiceUrl || props.meta.privacyPolicyUrl) && (0, import_jsx_runtime2.jsx)(Spacer, { y: "xl" }), (0, import_jsx_runtime2.jsxs)(Container, { flex: "column", gap: "lg", children: [(0, import_jsx_runtime2.jsx)(TOS, { termsOfServiceUrl: props.meta.termsOfServiceUrl, privacyPolicyUrl: props.meta.privacyPolicyUrl, locale: props.connectLocale.agreement, requireApproval: props.meta.requireApproval, onApprove: () => { setIsApproved(!isApproved); }, isApproved }), props.meta.showThirdwebBranding !== false && (0, import_jsx_runtime2.jsx)(PoweredByThirdweb, {})] })] }); } // node_modules/thirdweb/dist/esm/react/web/wallets/ecosystem/EcosystemWalletConnectUI.js function EcosystemWalletConnectUI(props) { const data = useSelectionData(); const setSelectionData = useSetSelectionData(); const state = data; const localeId = props.connectLocale.id; const locale = useInAppWalletLocale(localeId); if (!locale) { return (0, import_jsx_runtime3.jsx)(LoadingScreen, {}); } const goBackToMain = () => { var _a; if (props.size === "compact") { (_a = props.goBack) == null ? void 0 : _a.call(props); } setSelectionData({}); }; const done = () => { props.done(); setSelectionData({}); }; const otpUserInfo = (state == null ? void 0 : state.emailLogin) ? { email: state.emailLogin } : (state == null ? void 0 : state.phoneLogin) ? { phone: state.phoneLogin } : void 0; if (otpUserInfo) { return (0, import_jsx_runtime3.jsx)(OTPLoginUI, { userInfo: otpUserInfo, locale, done, goBack: goBackToMain, wallet: props.wallet, chain: props.chain, client: props.client, size: props.size, isLinking: props.isLinking }); } if (state == null ? void 0 : state.passkeyLogin) { return (0, import_jsx_runtime3.jsx)(PassKeyLogin, { locale: props.connectLocale, wallet: props.wallet, done, onBack: goBackToMain, chain: props.chain, client: props.client, size: props.size, isLinking: props.isLinking }); } if (state == null ? void 0 : state.socialLogin) { return (0, import_jsx_runtime3.jsx)(SocialLogin, { socialAuth: state.socialLogin.type, locale, done, goBack: goBackToMain, wallet: props.wallet, state, chain: props.chain, client: props.client, size: props.size, connectLocale: props.connectLocale, isLinking: props.isLinking }); } if (state == null ? void 0 : state.walletLogin) { return (0, import_jsx_runtime3.jsx)(WalletAuth, { meta: props.meta, inAppLocale: locale, walletConnect: props.walletConnect, wallet: props.wallet, client: props.client, size: props.size, done, onBack: goBackToMain || (() => setSelectionData({})), locale: props.connectLocale, isLinking: state.walletLogin.linking }); } if (state == null ? void 0 : state.guestLogin) { return (0, import_jsx_runtime3.jsx)(GuestLogin, { locale, done, goBack: goBackToMain, wallet: props.wallet, state, client: props.client, size: props.size, connectLocale: props.connectLocale }); } return (0, import_jsx_runtime3.jsx)(EcosystemWalletFormUIScreen, { select: () => { }, locale, done, goBack: props.goBack, wallet: props.wallet, chain: props.chain, client: props.client, size: props.size, connectLocale: props.connectLocale, meta: props.meta, isLinking: props.isLinking }); } var EcosystemWalletConnectUI_default = EcosystemWalletConnectUI; export { EcosystemWalletConnectUI_default }; //# sourceMappingURL=chunk-EGJT3UEX.js.map ================================================ FILE: 17-Crowd-Funding-Dapp/Frontend/.vite/deps_temp_6cf5ba4c/chunk-EHYTL2NA.js ================================================ import { __commonJS, __esm, __export, __reExport, __require, __toCommonJS, __toESM } from "./chunk-SEVZ5PBP.js"; // node_modules/events/events.js var require_events = __commonJS({ "node_modules/events/events.js"(exports, module) { "use strict"; var R2 = typeof Reflect === "object" ? Reflect : null; var ReflectApply = R2 && typeof R2.apply === "function" ? R2.apply : function ReflectApply2(target, receiver, args) { return Function.prototype.apply.call(target, receiver, args); }; var ReflectOwnKeys; if (R2 && typeof R2.ownKeys === "function") { ReflectOwnKeys = R2.ownKeys; } else if (Object.getOwnPropertySymbols) { ReflectOwnKeys = function ReflectOwnKeys2(target) { return Object.getOwnPropertyNames(target).concat(Object.getOwnPropertySymbols(target)); }; } else { ReflectOwnKeys = function ReflectOwnKeys2(target) { return Object.getOwnPropertyNames(target); }; } function ProcessEmitWarning(warning) { if (console && console.warn) console.warn(warning); } var NumberIsNaN = Number.isNaN || function NumberIsNaN2(value) { return value !== value; }; function EventEmitter() { EventEmitter.init.call(this); } module.exports = EventEmitter; module.exports.once = once; EventEmitter.EventEmitter = EventEmitter; EventEmitter.prototype._events = void 0; EventEmitter.prototype._eventsCount = 0; EventEmitter.prototype._maxListeners = void 0; var defaultMaxListeners = 10; function checkListener(listener) { if (typeof listener !== "function") { throw new TypeError('The "listener" argument must be of type Function. Received type ' + typeof listener); } } Object.defineProperty(EventEmitter, "defaultMaxListeners", { enumerable: true, get: function() { return defaultMaxListeners; }, set: function(arg) { if (typeof arg !== "number" || arg < 0 || NumberIsNaN(arg)) { throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received ' + arg + "."); } defaultMaxListeners = arg; } }); EventEmitter.init = function() { if (this._events === void 0 || this._events === Object.getPrototypeOf(this)._events) { this._events = /* @__PURE__ */ Object.create(null); this._eventsCount = 0; } this._maxListeners = this._maxListeners || void 0; }; EventEmitter.prototype.setMaxListeners = function setMaxListeners(n5) { if (typeof n5 !== "number" || n5 < 0 || NumberIsNaN(n5)) { throw new RangeError('The value of "n" is out of range. It must be a non-negative number. Received ' + n5 + "."); } this._maxListeners = n5; return this; }; function _getMaxListeners(that) { if (that._maxListeners === void 0) return EventEmitter.defaultMaxListeners; return that._maxListeners; } EventEmitter.prototype.getMaxListeners = function getMaxListeners() { return _getMaxListeners(this); }; EventEmitter.prototype.emit = function emit(type) { var args = []; for (var i4 = 1; i4 < arguments.length; i4++) args.push(arguments[i4]); var doError = type === "error"; var events = this._events; if (events !== void 0) doError = doError && events.error === void 0; else if (!doError) return false; if (doError) { var er3; if (args.length > 0) er3 = args[0]; if (er3 instanceof Error) { throw er3; } var err = new Error("Unhandled error." + (er3 ? " (" + er3.message + ")" : "")); err.context = er3; throw err; } var handler = events[type]; if (handler === void 0) return false; if (typeof handler === "function") { ReflectApply(handler, this, args); } else { var len = handler.length; var listeners = arrayClone(handler, len); for (var i4 = 0; i4 < len; ++i4) ReflectApply(listeners[i4], this, args); } return true; }; function _addListener(target, type, listener, prepend) { var m2; var events; var existing; checkListener(listener); events = target._events; if (events === void 0) { events = target._events = /* @__PURE__ */ Object.create(null); target._eventsCount = 0; } else { if (events.newListener !== void 0) { target.emit( "newListener", type, listener.listener ? listener.listener : listener ); events = target._events; } existing = events[type]; } if (existing === void 0) { existing = events[type] = listener; ++target._eventsCount; } else { if (typeof existing === "function") { existing = events[type] = prepend ? [listener, existing] : [existing, listener]; } else if (prepend) { existing.unshift(listener); } else { existing.push(listener); } m2 = _getMaxListeners(target); if (m2 > 0 && existing.length > m2 && !existing.warned) { existing.warned = true; var w4 = new Error("Possible EventEmitter memory leak detected. " + existing.length + " " + String(type) + " listeners added. Use emitter.setMaxListeners() to increase limit"); w4.name = "MaxListenersExceededWarning"; w4.emitter = target; w4.type = type; w4.count = existing.length; ProcessEmitWarning(w4); } } return target; } EventEmitter.prototype.addListener = function addListener(type, listener) { return _addListener(this, type, listener, false); }; EventEmitter.prototype.on = EventEmitter.prototype.addListener; EventEmitter.prototype.prependListener = function prependListener(type, listener) { return _addListener(this, type, listener, true); }; function onceWrapper() { if (!this.fired) { this.target.removeListener(this.type, this.wrapFn); this.fired = true; if (arguments.length === 0) return this.listener.call(this.target); return this.listener.apply(this.target, arguments); } } function _onceWrap(target, type, listener) { var state = { fired: false, wrapFn: void 0, target, type, listener }; var wrapped = onceWrapper.bind(state); wrapped.listener = listener; state.wrapFn = wrapped; return wrapped; } EventEmitter.prototype.once = function once2(type, listener) { checkListener(listener); this.on(type, _onceWrap(this, type, listener)); return this; }; EventEmitter.prototype.prependOnceListener = function prependOnceListener(type, listener) { checkListener(listener); this.prependListener(type, _onceWrap(this, type, listener)); return this; }; EventEmitter.prototype.removeListener = function removeListener(type, listener) { var list, events, position, i4, originalListener; checkListener(listener); events = this._events; if (events === void 0) return this; list = events[type]; if (list === void 0) return this; if (list === listener || list.listener === listener) { if (--this._eventsCount === 0) this._events = /* @__PURE__ */ Object.create(null); else { delete events[type]; if (events.removeListener) this.emit("removeListener", type, list.listener || listener); } } else if (typeof list !== "function") { position = -1; for (i4 = list.length - 1; i4 >= 0; i4--) { if (list[i4] === listener || list[i4].listener === listener) { originalListener = list[i4].listener; position = i4; break; } } if (position < 0) return this; if (position === 0) list.shift(); else { spliceOne(list, position); } if (list.length === 1) events[type] = list[0]; if (events.removeListener !== void 0) this.emit("removeListener", type, originalListener || listener); } return this; }; EventEmitter.prototype.off = EventEmitter.prototype.removeListener; EventEmitter.prototype.removeAllListeners = function removeAllListeners(type) { var listeners, events, i4; events = this._events; if (events === void 0) return this; if (events.removeListener === void 0) { if (arguments.length === 0) { this._events = /* @__PURE__ */ Object.create(null); this._eventsCount = 0; } else if (events[type] !== void 0) { if (--this._eventsCount === 0) this._events = /* @__PURE__ */ Object.create(null); else delete events[type]; } return this; } if (arguments.length === 0) { var keys2 = Object.keys(events); var key2; for (i4 = 0; i4 < keys2.length; ++i4) { key2 = keys2[i4]; if (key2 === "removeListener") continue; this.removeAllListeners(key2); } this.removeAllListeners("removeListener"); this._events = /* @__PURE__ */ Object.create(null); this._eventsCount = 0; return this; } listeners = events[type]; if (typeof listeners === "function") { this.removeListener(type, listeners); } else if (listeners !== void 0) { for (i4 = listeners.length - 1; i4 >= 0; i4--) { this.removeListener(type, listeners[i4]); } } return this; }; function _listeners(target, type, unwrap) { var events = target._events; if (events === void 0) return []; var evlistener = events[type]; if (evlistener === void 0) return []; if (typeof evlistener === "function") return unwrap ? [evlistener.listener || evlistener] : [evlistener]; return unwrap ? unwrapListeners(evlistener) : arrayClone(evlistener, evlistener.length); } EventEmitter.prototype.listeners = function listeners(type) { return _listeners(this, type, true); }; EventEmitter.prototype.rawListeners = function rawListeners(type) { return _listeners(this, type, false); }; EventEmitter.listenerCount = function(emitter, type) { if (typeof emitter.listenerCount === "function") { return emitter.listenerCount(type); } else { return listenerCount.call(emitter, type); } }; EventEmitter.prototype.listenerCount = listenerCount; function listenerCount(type) { var events = this._events; if (events !== void 0) { var evlistener = events[type]; if (typeof evlistener === "function") { return 1; } else if (evlistener !== void 0) { return evlistener.length; } } return 0; } EventEmitter.prototype.eventNames = function eventNames() { return this._eventsCount > 0 ? ReflectOwnKeys(this._events) : []; }; function arrayClone(arr, n5) { var copy = new Array(n5); for (var i4 = 0; i4 < n5; ++i4) copy[i4] = arr[i4]; return copy; } function spliceOne(list, index) { for (; index + 1 < list.length; index++) list[index] = list[index + 1]; list.pop(); } function unwrapListeners(arr) { var ret = new Array(arr.length); for (var i4 = 0; i4 < ret.length; ++i4) { ret[i4] = arr[i4].listener || arr[i4]; } return ret; } function once(emitter, name2) { return new Promise(function(resolve, reject) { function errorListener(err) { emitter.removeListener(name2, resolver); reject(err); } function resolver() { if (typeof emitter.removeListener === "function") { emitter.removeListener("error", errorListener); } resolve([].slice.call(arguments)); } ; eventTargetAgnosticAddListener(emitter, name2, resolver, { once: true }); if (name2 !== "error") { addErrorHandlerIfEventEmitter(emitter, errorListener, { once: true }); } }); } function addErrorHandlerIfEventEmitter(emitter, handler, flags) { if (typeof emitter.on === "function") { eventTargetAgnosticAddListener(emitter, "error", handler, flags); } } function eventTargetAgnosticAddListener(emitter, name2, listener, flags) { if (typeof emitter.on === "function") { if (flags.once) { emitter.once(name2, listener); } else { emitter.on(name2, listener); } } else if (typeof emitter.addEventListener === "function") { emitter.addEventListener(name2, function wrapListener(arg) { if (flags.once) { emitter.removeEventListener(name2, wrapListener); } listener(arg); }); } else { throw new TypeError('The "emitter" argument must be of type EventEmitter. Received type ' + typeof emitter); } } } }); // node_modules/tslib/tslib.es6.js var tslib_es6_exports = {}; __export(tslib_es6_exports, { __assign: () => __assign, __asyncDelegator: () => __asyncDelegator, __asyncGenerator: () => __asyncGenerator, __asyncValues: () => __asyncValues, __await: () => __await, __awaiter: () => __awaiter, __classPrivateFieldGet: () => __classPrivateFieldGet, __classPrivateFieldSet: () => __classPrivateFieldSet, __createBinding: () => __createBinding, __decorate: () => __decorate, __exportStar: () => __exportStar, __extends: () => __extends, __generator: () => __generator, __importDefault: () => __importDefault, __importStar: () => __importStar, __makeTemplateObject: () => __makeTemplateObject, __metadata: () => __metadata, __param: () => __param, __read: () => __read, __rest: () => __rest, __spread: () => __spread, __spreadArrays: () => __spreadArrays, __values: () => __values }); function __extends(d3, b5) { extendStatics(d3, b5); function __() { this.constructor = d3; } d3.prototype = b5 === null ? Object.create(b5) : (__.prototype = b5.prototype, new __()); } function __rest(s3, e2) { var t = {}; for (var p3 in s3) if (Object.prototype.hasOwnProperty.call(s3, p3) && e2.indexOf(p3) < 0) t[p3] = s3[p3]; if (s3 != null && typeof Object.getOwnPropertySymbols === "function") for (var i4 = 0, p3 = Object.getOwnPropertySymbols(s3); i4 < p3.length; i4++) { if (e2.indexOf(p3[i4]) < 0 && Object.prototype.propertyIsEnumerable.call(s3, p3[i4])) t[p3[i4]] = s3[p3[i4]]; } return t; } function __decorate(decorators, target, key2, desc) { var c5 = arguments.length, r4 = c5 < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key2) : desc, d3; if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r4 = Reflect.decorate(decorators, target, key2, desc); else for (var i4 = decorators.length - 1; i4 >= 0; i4--) if (d3 = decorators[i4]) r4 = (c5 < 3 ? d3(r4) : c5 > 3 ? d3(target, key2, r4) : d3(target, key2)) || r4; return c5 > 3 && r4 && Object.defineProperty(target, key2, r4), r4; } function __param(paramIndex, decorator) { return function(target, key2) { decorator(target, key2, paramIndex); }; } function __metadata(metadataKey, metadataValue) { if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(metadataKey, metadataValue); } function __awaiter(thisArg, _arguments, P3, generator) { function adopt(value) { return value instanceof P3 ? value : new P3(function(resolve) { resolve(value); }); } return new (P3 || (P3 = Promise))(function(resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e2) { reject(e2); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e2) { reject(e2); } } function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); } function __generator(thisArg, body) { var _4 = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f4, y6, t, g4; return g4 = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g4[Symbol.iterator] = function() { return this; }), g4; function verb(n5) { return function(v5) { return step([n5, v5]); }; } function step(op) { if (f4) throw new TypeError("Generator is already executing."); while (_4) try { if (f4 = 1, y6 && (t = op[0] & 2 ? y6["return"] : op[0] ? y6["throw"] || ((t = y6["return"]) && t.call(y6), 0) : y6.next) && !(t = t.call(y6, op[1])).done) return t; if (y6 = 0, t) op = [op[0] & 2, t.value]; switch (op[0]) { case 0: case 1: t = op; break; case 4: _4.label++; return { value: op[1], done: false }; case 5: _4.label++; y6 = op[1]; op = [0]; continue; case 7: op = _4.ops.pop(); _4.trys.pop(); continue; default: if (!(t = _4.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _4 = 0; continue; } if (op[0] === 3 && (!t || op[1] > t[0] && op[1] < t[3])) { _4.label = op[1]; break; } if (op[0] === 6 && _4.label < t[1]) { _4.label = t[1]; t = op; break; } if (t && _4.label < t[2]) { _4.label = t[2]; _4.ops.push(op); break; } if (t[2]) _4.ops.pop(); _4.trys.pop(); continue; } op = body.call(thisArg, _4); } catch (e2) { op = [6, e2]; y6 = 0; } finally { f4 = t = 0; } if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; } } function __createBinding(o4, m2, k4, k22) { if (k22 === void 0) k22 = k4; o4[k22] = m2[k4]; } function __exportStar(m2, exports) { for (var p3 in m2) if (p3 !== "default" && !exports.hasOwnProperty(p3)) exports[p3] = m2[p3]; } function __values(o4) { var s3 = typeof Symbol === "function" && Symbol.iterator, m2 = s3 && o4[s3], i4 = 0; if (m2) return m2.call(o4); if (o4 && typeof o4.length === "number") return { next: function() { if (o4 && i4 >= o4.length) o4 = void 0; return { value: o4 && o4[i4++], done: !o4 }; } }; throw new TypeError(s3 ? "Object is not iterable." : "Symbol.iterator is not defined."); } function __read(o4, n5) { var m2 = typeof Symbol === "function" && o4[Symbol.iterator]; if (!m2) return o4; var i4 = m2.call(o4), r4, ar3 = [], e2; try { while ((n5 === void 0 || n5-- > 0) && !(r4 = i4.next()).done) ar3.push(r4.value); } catch (error) { e2 = { error }; } finally { try { if (r4 && !r4.done && (m2 = i4["return"])) m2.call(i4); } finally { if (e2) throw e2.error; } } return ar3; } function __spread() { for (var ar3 = [], i4 = 0; i4 < arguments.length; i4++) ar3 = ar3.concat(__read(arguments[i4])); return ar3; } function __spreadArrays() { for (var s3 = 0, i4 = 0, il = arguments.length; i4 < il; i4++) s3 += arguments[i4].length; for (var r4 = Array(s3), k4 = 0, i4 = 0; i4 < il; i4++) for (var a4 = arguments[i4], j2 = 0, jl = a4.length; j2 < jl; j2++, k4++) r4[k4] = a4[j2]; return r4; } function __await(v5) { return this instanceof __await ? (this.v = v5, this) : new __await(v5); } function __asyncGenerator(thisArg, _arguments, generator) { if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); var g4 = generator.apply(thisArg, _arguments || []), i4, q3 = []; return i4 = {}, verb("next"), verb("throw"), verb("return"), i4[Symbol.asyncIterator] = function() { return this; }, i4; function verb(n5) { if (g4[n5]) i4[n5] = function(v5) { return new Promise(function(a4, b5) { q3.push([n5, v5, a4, b5]) > 1 || resume(n5, v5); }); }; } function resume(n5, v5) { try { step(g4[n5](v5)); } catch (e2) { settle(q3[0][3], e2); } } function step(r4) { r4.value instanceof __await ? Promise.resolve(r4.value.v).then(fulfill, reject) : settle(q3[0][2], r4); } function fulfill(value) { resume("next", value); } function reject(value) { resume("throw", value); } function settle(f4, v5) { if (f4(v5), q3.shift(), q3.length) resume(q3[0][0], q3[0][1]); } } function __asyncDelegator(o4) { var i4, p3; return i4 = {}, verb("next"), verb("throw", function(e2) { throw e2; }), verb("return"), i4[Symbol.iterator] = function() { return this; }, i4; function verb(n5, f4) { i4[n5] = o4[n5] ? function(v5) { return (p3 = !p3) ? { value: __await(o4[n5](v5)), done: n5 === "return" } : f4 ? f4(v5) : v5; } : f4; } } function __asyncValues(o4) { if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); var m2 = o4[Symbol.asyncIterator], i4; return m2 ? m2.call(o4) : (o4 = typeof __values === "function" ? __values(o4) : o4[Symbol.iterator](), i4 = {}, verb("next"), verb("throw"), verb("return"), i4[Symbol.asyncIterator] = function() { return this; }, i4); function verb(n5) { i4[n5] = o4[n5] && function(v5) { return new Promise(function(resolve, reject) { v5 = o4[n5](v5), settle(resolve, reject, v5.done, v5.value); }); }; } function settle(resolve, reject, d3, v5) { Promise.resolve(v5).then(function(v6) { resolve({ value: v6, done: d3 }); }, reject); } } function __makeTemplateObject(cooked, raw) { if (Object.defineProperty) { Object.defineProperty(cooked, "raw", { value: raw }); } else { cooked.raw = raw; } return cooked; } function __importStar(mod) { if (mod && mod.__esModule) return mod; var result = {}; if (mod != null) { for (var k4 in mod) if (Object.hasOwnProperty.call(mod, k4)) result[k4] = mod[k4]; } result.default = mod; return result; } function __importDefault(mod) { return mod && mod.__esModule ? mod : { default: mod }; } function __classPrivateFieldGet(receiver, privateMap) { if (!privateMap.has(receiver)) { throw new TypeError("attempted to get private field on non-instance"); } return privateMap.get(receiver); } function __classPrivateFieldSet(receiver, privateMap, value) { if (!privateMap.has(receiver)) { throw new TypeError("attempted to set private field on non-instance"); } privateMap.set(receiver, value); return value; } var extendStatics, __assign; var init_tslib_es6 = __esm({ "node_modules/tslib/tslib.es6.js"() { extendStatics = function(d3, b5) { extendStatics = Object.setPrototypeOf || { __proto__: [] } instanceof Array && function(d4, b6) { d4.__proto__ = b6; } || function(d4, b6) { for (var p3 in b6) if (b6.hasOwnProperty(p3)) d4[p3] = b6[p3]; }; return extendStatics(d3, b5); }; __assign = function() { __assign = Object.assign || function __assign2(t) { for (var s3, i4 = 1, n5 = arguments.length; i4 < n5; i4++) { s3 = arguments[i4]; for (var p3 in s3) if (Object.prototype.hasOwnProperty.call(s3, p3)) t[p3] = s3[p3]; } return t; }; return __assign.apply(this, arguments); }; } }); // node_modules/@walletconnect/time/dist/cjs/utils/delay.js var require_delay = __commonJS({ "node_modules/@walletconnect/time/dist/cjs/utils/delay.js"(exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.delay = void 0; function delay(timeout) { return new Promise((resolve) => { setTimeout(() => { resolve(true); }, timeout); }); } exports.delay = delay; } }); // node_modules/@walletconnect/time/dist/cjs/constants/misc.js var require_misc = __commonJS({ "node_modules/@walletconnect/time/dist/cjs/constants/misc.js"(exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.ONE_THOUSAND = exports.ONE_HUNDRED = void 0; exports.ONE_HUNDRED = 100; exports.ONE_THOUSAND = 1e3; } }); // node_modules/@walletconnect/time/dist/cjs/constants/time.js var require_time = __commonJS({ "node_modules/@walletconnect/time/dist/cjs/constants/time.js"(exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.ONE_YEAR = exports.FOUR_WEEKS = exports.THREE_WEEKS = exports.TWO_WEEKS = exports.ONE_WEEK = exports.THIRTY_DAYS = exports.SEVEN_DAYS = exports.FIVE_DAYS = exports.THREE_DAYS = exports.ONE_DAY = exports.TWENTY_FOUR_HOURS = exports.TWELVE_HOURS = exports.SIX_HOURS = exports.THREE_HOURS = exports.ONE_HOUR = exports.SIXTY_MINUTES = exports.THIRTY_MINUTES = exports.TEN_MINUTES = exports.FIVE_MINUTES = exports.ONE_MINUTE = exports.SIXTY_SECONDS = exports.THIRTY_SECONDS = exports.TEN_SECONDS = exports.FIVE_SECONDS = exports.ONE_SECOND = void 0; exports.ONE_SECOND = 1; exports.FIVE_SECONDS = 5; exports.TEN_SECONDS = 10; exports.THIRTY_SECONDS = 30; exports.SIXTY_SECONDS = 60; exports.ONE_MINUTE = exports.SIXTY_SECONDS; exports.FIVE_MINUTES = exports.ONE_MINUTE * 5; exports.TEN_MINUTES = exports.ONE_MINUTE * 10; exports.THIRTY_MINUTES = exports.ONE_MINUTE * 30; exports.SIXTY_MINUTES = exports.ONE_MINUTE * 60; exports.ONE_HOUR = exports.SIXTY_MINUTES; exports.THREE_HOURS = exports.ONE_HOUR * 3; exports.SIX_HOURS = exports.ONE_HOUR * 6; exports.TWELVE_HOURS = exports.ONE_HOUR * 12; exports.TWENTY_FOUR_HOURS = exports.ONE_HOUR * 24; exports.ONE_DAY = exports.TWENTY_FOUR_HOURS; exports.THREE_DAYS = exports.ONE_DAY * 3; exports.FIVE_DAYS = exports.ONE_DAY * 5; exports.SEVEN_DAYS = exports.ONE_DAY * 7; exports.THIRTY_DAYS = exports.ONE_DAY * 30; exports.ONE_WEEK = exports.SEVEN_DAYS; exports.TWO_WEEKS = exports.ONE_WEEK * 2; exports.THREE_WEEKS = exports.ONE_WEEK * 3; exports.FOUR_WEEKS = exports.ONE_WEEK * 4; exports.ONE_YEAR = exports.ONE_DAY * 365; } }); // node_modules/@walletconnect/time/dist/cjs/constants/index.js var require_constants = __commonJS({ "node_modules/@walletconnect/time/dist/cjs/constants/index.js"(exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var tslib_1 = (init_tslib_es6(), __toCommonJS(tslib_es6_exports)); tslib_1.__exportStar(require_misc(), exports); tslib_1.__exportStar(require_time(), exports); } }); // node_modules/@walletconnect/time/dist/cjs/utils/convert.js var require_convert = __commonJS({ "node_modules/@walletconnect/time/dist/cjs/utils/convert.js"(exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.fromMiliseconds = exports.toMiliseconds = void 0; var constants_1 = require_constants(); function toMiliseconds(seconds) { return seconds * constants_1.ONE_THOUSAND; } exports.toMiliseconds = toMiliseconds; function fromMiliseconds2(miliseconds) { return Math.floor(miliseconds / constants_1.ONE_THOUSAND); } exports.fromMiliseconds = fromMiliseconds2; } }); // node_modules/@walletconnect/time/dist/cjs/utils/index.js var require_utils = __commonJS({ "node_modules/@walletconnect/time/dist/cjs/utils/index.js"(exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var tslib_1 = (init_tslib_es6(), __toCommonJS(tslib_es6_exports)); tslib_1.__exportStar(require_delay(), exports); tslib_1.__exportStar(require_convert(), exports); } }); // node_modules/@walletconnect/time/dist/cjs/watch.js var require_watch = __commonJS({ "node_modules/@walletconnect/time/dist/cjs/watch.js"(exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.Watch = void 0; var Watch = class { constructor() { this.timestamps = /* @__PURE__ */ new Map(); } start(label) { if (this.timestamps.has(label)) { throw new Error(`Watch already started for label: ${label}`); } this.timestamps.set(label, { started: Date.now() }); } stop(label) { const timestamp = this.get(label); if (typeof timestamp.elapsed !== "undefined") { throw new Error(`Watch already stopped for label: ${label}`); } const elapsed = Date.now() - timestamp.started; this.timestamps.set(label, { started: timestamp.started, elapsed }); } get(label) { const timestamp = this.timestamps.get(label); if (typeof timestamp === "undefined") { throw new Error(`No timestamp found for label: ${label}`); } return timestamp; } elapsed(label) { const timestamp = this.get(label); const elapsed = timestamp.elapsed || Date.now() - timestamp.started; return elapsed; } }; exports.Watch = Watch; exports.default = Watch; } }); // node_modules/@walletconnect/time/dist/cjs/types/watch.js var require_watch2 = __commonJS({ "node_modules/@walletconnect/time/dist/cjs/types/watch.js"(exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.IWatch = void 0; var IWatch = class { }; exports.IWatch = IWatch; } }); // node_modules/@walletconnect/time/dist/cjs/types/index.js var require_types = __commonJS({ "node_modules/@walletconnect/time/dist/cjs/types/index.js"(exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var tslib_1 = (init_tslib_es6(), __toCommonJS(tslib_es6_exports)); tslib_1.__exportStar(require_watch2(), exports); } }); // node_modules/@walletconnect/time/dist/cjs/index.js var require_cjs = __commonJS({ "node_modules/@walletconnect/time/dist/cjs/index.js"(exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var tslib_1 = (init_tslib_es6(), __toCommonJS(tslib_es6_exports)); tslib_1.__exportStar(require_utils(), exports); tslib_1.__exportStar(require_watch(), exports); tslib_1.__exportStar(require_types(), exports); tslib_1.__exportStar(require_constants(), exports); } }); // node_modules/@walletconnect/window-getters/dist/cjs/index.js var require_cjs2 = __commonJS({ "node_modules/@walletconnect/window-getters/dist/cjs/index.js"(exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.getLocalStorage = exports.getLocalStorageOrThrow = exports.getCrypto = exports.getCryptoOrThrow = exports.getLocation = exports.getLocationOrThrow = exports.getNavigator = exports.getNavigatorOrThrow = exports.getDocument = exports.getDocumentOrThrow = exports.getFromWindowOrThrow = exports.getFromWindow = void 0; function getFromWindow(name2) { let res = void 0; if (typeof window !== "undefined" && typeof window[name2] !== "undefined") { res = window[name2]; } return res; } exports.getFromWindow = getFromWindow; function getFromWindowOrThrow(name2) { const res = getFromWindow(name2); if (!res) { throw new Error(`${name2} is not defined in Window`); } return res; } exports.getFromWindowOrThrow = getFromWindowOrThrow; function getDocumentOrThrow() { return getFromWindowOrThrow("document"); } exports.getDocumentOrThrow = getDocumentOrThrow; function getDocument() { return getFromWindow("document"); } exports.getDocument = getDocument; function getNavigatorOrThrow() { return getFromWindowOrThrow("navigator"); } exports.getNavigatorOrThrow = getNavigatorOrThrow; function getNavigator() { return getFromWindow("navigator"); } exports.getNavigator = getNavigator; function getLocationOrThrow() { return getFromWindowOrThrow("location"); } exports.getLocationOrThrow = getLocationOrThrow; function getLocation() { return getFromWindow("location"); } exports.getLocation = getLocation; function getCryptoOrThrow() { return getFromWindowOrThrow("crypto"); } exports.getCryptoOrThrow = getCryptoOrThrow; function getCrypto() { return getFromWindow("crypto"); } exports.getCrypto = getCrypto; function getLocalStorageOrThrow() { return getFromWindowOrThrow("localStorage"); } exports.getLocalStorageOrThrow = getLocalStorageOrThrow; function getLocalStorage() { return getFromWindow("localStorage"); } exports.getLocalStorage = getLocalStorage; } }); // node_modules/@walletconnect/window-metadata/dist/cjs/index.js var require_cjs3 = __commonJS({ "node_modules/@walletconnect/window-metadata/dist/cjs/index.js"(exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.getWindowMetadata = void 0; var window_getters_1 = require_cjs2(); function getWindowMetadata() { let doc; let loc; try { doc = window_getters_1.getDocumentOrThrow(); loc = window_getters_1.getLocationOrThrow(); } catch (e2) { return null; } function getIcons() { const links = doc.getElementsByTagName("link"); const icons2 = []; for (let i4 = 0; i4 < links.length; i4++) { const link = links[i4]; const rel = link.getAttribute("rel"); if (rel) { if (rel.toLowerCase().indexOf("icon") > -1) { const href = link.getAttribute("href"); if (href) { if (href.toLowerCase().indexOf("https:") === -1 && href.toLowerCase().indexOf("http:") === -1 && href.indexOf("//") !== 0) { let absoluteHref = loc.protocol + "//" + loc.host; if (href.indexOf("/") === 0) { absoluteHref += href; } else { const path = loc.pathname.split("/"); path.pop(); const finalPath = path.join("/"); absoluteHref += finalPath + "/" + href; } icons2.push(absoluteHref); } else if (href.indexOf("//") === 0) { const absoluteUrl = loc.protocol + href; icons2.push(absoluteUrl); } else { icons2.push(href); } } } } } return icons2; } function getWindowMetadataOfAny(...args) { const metaTags = doc.getElementsByTagName("meta"); for (let i4 = 0; i4 < metaTags.length; i4++) { const tag = metaTags[i4]; const attributes = ["itemprop", "property", "name"].map((target) => tag.getAttribute(target)).filter((attr) => { if (attr) { return args.includes(attr); } return false; }); if (attributes.length && attributes) { const content = tag.getAttribute("content"); if (content) { return content; } } } return ""; } function getName() { let name3 = getWindowMetadataOfAny("name", "og:site_name", "og:title", "twitter:title"); if (!name3) { name3 = doc.title; } return name3; } function getDescription() { const description2 = getWindowMetadataOfAny("description", "og:description", "twitter:description", "keywords"); return description2; } const name2 = getName(); const description = getDescription(); const url = loc.origin; const icons = getIcons(); const meta = { description, url, icons, name: name2 }; return meta; } exports.getWindowMetadata = getWindowMetadata; } }); // node_modules/strict-uri-encode/index.js var require_strict_uri_encode = __commonJS({ "node_modules/strict-uri-encode/index.js"(exports, module) { "use strict"; module.exports = (str) => encodeURIComponent(str).replace(/[!'()*]/g, (x6) => `%${x6.charCodeAt(0).toString(16).toUpperCase()}`); } }); // node_modules/decode-uri-component/index.js var require_decode_uri_component = __commonJS({ "node_modules/decode-uri-component/index.js"(exports, module) { "use strict"; var token = "%[a-f0-9]{2}"; var singleMatcher = new RegExp("(" + token + ")|([^%]+?)", "gi"); var multiMatcher = new RegExp("(" + token + ")+", "gi"); function decodeComponents(components, split) { try { return [decodeURIComponent(components.join(""))]; } catch (err) { } if (components.length === 1) { return components; } split = split || 1; var left = components.slice(0, split); var right = components.slice(split); return Array.prototype.concat.call([], decodeComponents(left), decodeComponents(right)); } function decode8(input) { try { return decodeURIComponent(input); } catch (err) { var tokens = input.match(singleMatcher) || []; for (var i4 = 1; i4 < tokens.length; i4++) { input = decodeComponents(tokens, i4).join(""); tokens = input.match(singleMatcher) || []; } return input; } } function customDecodeURIComponent(input) { var replaceMap = { "%FE%FF": "��", "%FF%FE": "��" }; var match = multiMatcher.exec(input); while (match) { try { replaceMap[match[0]] = decodeURIComponent(match[0]); } catch (err) { var result = decode8(match[0]); if (result !== match[0]) { replaceMap[match[0]] = result; } } match = multiMatcher.exec(input); } replaceMap["%C2"] = "�"; var entries = Object.keys(replaceMap); for (var i4 = 0; i4 < entries.length; i4++) { var key2 = entries[i4]; input = input.replace(new RegExp(key2, "g"), replaceMap[key2]); } return input; } module.exports = function(encodedURI) { if (typeof encodedURI !== "string") { throw new TypeError("Expected `encodedURI` to be of type `string`, got `" + typeof encodedURI + "`"); } try { encodedURI = encodedURI.replace(/\+/g, " "); return decodeURIComponent(encodedURI); } catch (err) { return customDecodeURIComponent(encodedURI); } }; } }); // node_modules/split-on-first/index.js var require_split_on_first = __commonJS({ "node_modules/split-on-first/index.js"(exports, module) { "use strict"; module.exports = (string2, separator) => { if (!(typeof string2 === "string" && typeof separator === "string")) { throw new TypeError("Expected the arguments to be of type `string`"); } if (separator === "") { return [string2]; } const separatorIndex = string2.indexOf(separator); if (separatorIndex === -1) { return [string2]; } return [ string2.slice(0, separatorIndex), string2.slice(separatorIndex + separator.length) ]; }; } }); // node_modules/filter-obj/index.js var require_filter_obj = __commonJS({ "node_modules/filter-obj/index.js"(exports, module) { "use strict"; module.exports = function(obj, predicate) { var ret = {}; var keys2 = Object.keys(obj); var isArr = Array.isArray(predicate); for (var i4 = 0; i4 < keys2.length; i4++) { var key2 = keys2[i4]; var val = obj[key2]; if (isArr ? predicate.indexOf(key2) !== -1 : predicate(key2, val, obj)) { ret[key2] = val; } } return ret; }; } }); // node_modules/query-string/index.js var require_query_string = __commonJS({ "node_modules/query-string/index.js"(exports) { "use strict"; var strictUriEncode = require_strict_uri_encode(); var decodeComponent = require_decode_uri_component(); var splitOnFirst = require_split_on_first(); var filterObject = require_filter_obj(); var isNullOrUndefined = (value) => value === null || value === void 0; var encodeFragmentIdentifier = Symbol("encodeFragmentIdentifier"); function encoderForArrayFormat(options) { switch (options.arrayFormat) { case "index": return (key2) => (result, value) => { const index = result.length; if (value === void 0 || options.skipNull && value === null || options.skipEmptyString && value === "") { return result; } if (value === null) { return [...result, [encode8(key2, options), "[", index, "]"].join("")]; } return [ ...result, [encode8(key2, options), "[", encode8(index, options), "]=", encode8(value, options)].join("") ]; }; case "bracket": return (key2) => (result, value) => { if (value === void 0 || options.skipNull && value === null || options.skipEmptyString && value === "") { return result; } if (value === null) { return [...result, [encode8(key2, options), "[]"].join("")]; } return [...result, [encode8(key2, options), "[]=", encode8(value, options)].join("")]; }; case "colon-list-separator": return (key2) => (result, value) => { if (value === void 0 || options.skipNull && value === null || options.skipEmptyString && value === "") { return result; } if (value === null) { return [...result, [encode8(key2, options), ":list="].join("")]; } return [...result, [encode8(key2, options), ":list=", encode8(value, options)].join("")]; }; case "comma": case "separator": case "bracket-separator": { const keyValueSep = options.arrayFormat === "bracket-separator" ? "[]=" : "="; return (key2) => (result, value) => { if (value === void 0 || options.skipNull && value === null || options.skipEmptyString && value === "") { return result; } value = value === null ? "" : value; if (result.length === 0) { return [[encode8(key2, options), keyValueSep, encode8(value, options)].join("")]; } return [[result, encode8(value, options)].join(options.arrayFormatSeparator)]; }; } default: return (key2) => (result, value) => { if (value === void 0 || options.skipNull && value === null || options.skipEmptyString && value === "") { return result; } if (value === null) { return [...result, encode8(key2, options)]; } return [...result, [encode8(key2, options), "=", encode8(value, options)].join("")]; }; } } function parserForArrayFormat(options) { let result; switch (options.arrayFormat) { case "index": return (key2, value, accumulator) => { result = /\[(\d*)\]$/.exec(key2); key2 = key2.replace(/\[\d*\]$/, ""); if (!result) { accumulator[key2] = value; return; } if (accumulator[key2] === void 0) { accumulator[key2] = {}; } accumulator[key2][result[1]] = value; }; case "bracket": return (key2, value, accumulator) => { result = /(\[\])$/.exec(key2); key2 = key2.replace(/\[\]$/, ""); if (!result) { accumulator[key2] = value; return; } if (accumulator[key2] === void 0) { accumulator[key2] = [value]; return; } accumulator[key2] = [].concat(accumulator[key2], value); }; case "colon-list-separator": return (key2, value, accumulator) => { result = /(:list)$/.exec(key2); key2 = key2.replace(/:list$/, ""); if (!result) { accumulator[key2] = value; return; } if (accumulator[key2] === void 0) { accumulator[key2] = [value]; return; } accumulator[key2] = [].concat(accumulator[key2], value); }; case "comma": case "separator": return (key2, value, accumulator) => { const isArray = typeof value === "string" && value.includes(options.arrayFormatSeparator); const isEncodedArray = typeof value === "string" && !isArray && decode8(value, options).includes(options.arrayFormatSeparator); value = isEncodedArray ? decode8(value, options) : value; const newValue = isArray || isEncodedArray ? value.split(options.arrayFormatSeparator).map((item) => decode8(item, options)) : value === null ? value : decode8(value, options); accumulator[key2] = newValue; }; case "bracket-separator": return (key2, value, accumulator) => { const isArray = /(\[\])$/.test(key2); key2 = key2.replace(/\[\]$/, ""); if (!isArray) { accumulator[key2] = value ? decode8(value, options) : value; return; } const arrayValue = value === null ? [] : value.split(options.arrayFormatSeparator).map((item) => decode8(item, options)); if (accumulator[key2] === void 0) { accumulator[key2] = arrayValue; return; } accumulator[key2] = [].concat(accumulator[key2], arrayValue); }; default: return (key2, value, accumulator) => { if (accumulator[key2] === void 0) { accumulator[key2] = value; return; } accumulator[key2] = [].concat(accumulator[key2], value); }; } } function validateArrayFormatSeparator(value) { if (typeof value !== "string" || value.length !== 1) { throw new TypeError("arrayFormatSeparator must be single character string"); } } function encode8(value, options) { if (options.encode) { return options.strict ? strictUriEncode(value) : encodeURIComponent(value); } return value; } function decode8(value, options) { if (options.decode) { return decodeComponent(value); } return value; } function keysSorter(input) { if (Array.isArray(input)) { return input.sort(); } if (typeof input === "object") { return keysSorter(Object.keys(input)).sort((a4, b5) => Number(a4) - Number(b5)).map((key2) => input[key2]); } return input; } function removeHash(input) { const hashStart = input.indexOf("#"); if (hashStart !== -1) { input = input.slice(0, hashStart); } return input; } function getHash(url) { let hash2 = ""; const hashStart = url.indexOf("#"); if (hashStart !== -1) { hash2 = url.slice(hashStart); } return hash2; } function extract(input) { input = removeHash(input); const queryStart = input.indexOf("?"); if (queryStart === -1) { return ""; } return input.slice(queryStart + 1); } function parseValue(value, options) { if (options.parseNumbers && !Number.isNaN(Number(value)) && (typeof value === "string" && value.trim() !== "")) { value = Number(value); } else if (options.parseBooleans && value !== null && (value.toLowerCase() === "true" || value.toLowerCase() === "false")) { value = value.toLowerCase() === "true"; } return value; } function parse2(query, options) { options = Object.assign({ decode: true, sort: true, arrayFormat: "none", arrayFormatSeparator: ",", parseNumbers: false, parseBooleans: false }, options); validateArrayFormatSeparator(options.arrayFormatSeparator); const formatter = parserForArrayFormat(options); const ret = /* @__PURE__ */ Object.create(null); if (typeof query !== "string") { return ret; } query = query.trim().replace(/^[?#&]/, ""); if (!query) { return ret; } for (const param of query.split("&")) { if (param === "") { continue; } let [key2, value] = splitOnFirst(options.decode ? param.replace(/\+/g, " ") : param, "="); value = value === void 0 ? null : ["comma", "separator", "bracket-separator"].includes(options.arrayFormat) ? value : decode8(value, options); formatter(decode8(key2, options), value, ret); } for (const key2 of Object.keys(ret)) { const value = ret[key2]; if (typeof value === "object" && value !== null) { for (const k4 of Object.keys(value)) { value[k4] = parseValue(value[k4], options); } } else { ret[key2] = parseValue(value, options); } } if (options.sort === false) { return ret; } return (options.sort === true ? Object.keys(ret).sort() : Object.keys(ret).sort(options.sort)).reduce((result, key2) => { const value = ret[key2]; if (Boolean(value) && typeof value === "object" && !Array.isArray(value)) { result[key2] = keysSorter(value); } else { result[key2] = value; } return result; }, /* @__PURE__ */ Object.create(null)); } exports.extract = extract; exports.parse = parse2; exports.stringify = (object, options) => { if (!object) { return ""; } options = Object.assign({ encode: true, strict: true, arrayFormat: "none", arrayFormatSeparator: "," }, options); validateArrayFormatSeparator(options.arrayFormatSeparator); const shouldFilter = (key2) => options.skipNull && isNullOrUndefined(object[key2]) || options.skipEmptyString && object[key2] === ""; const formatter = encoderForArrayFormat(options); const objectCopy = {}; for (const key2 of Object.keys(object)) { if (!shouldFilter(key2)) { objectCopy[key2] = object[key2]; } } const keys2 = Object.keys(objectCopy); if (options.sort !== false) { keys2.sort(options.sort); } return keys2.map((key2) => { const value = object[key2]; if (value === void 0) { return ""; } if (value === null) { return encode8(key2, options); } if (Array.isArray(value)) { if (value.length === 0 && options.arrayFormat === "bracket-separator") { return encode8(key2, options) + "[]"; } return value.reduce(formatter(key2), []).join("&"); } return encode8(key2, options) + "=" + encode8(value, options); }).filter((x6) => x6.length > 0).join("&"); }; exports.parseUrl = (url, options) => { options = Object.assign({ decode: true }, options); const [url_, hash2] = splitOnFirst(url, "#"); return Object.assign( { url: url_.split("?")[0] || "", query: parse2(extract(url), options) }, options && options.parseFragmentIdentifier && hash2 ? { fragmentIdentifier: decode8(hash2, options) } : {} ); }; exports.stringifyUrl = (object, options) => { options = Object.assign({ encode: true, strict: true, [encodeFragmentIdentifier]: true }, options); const url = removeHash(object.url).split("?")[0] || ""; const queryFromUrl = exports.extract(object.url); const parsedQueryFromUrl = exports.parse(queryFromUrl, { sort: false }); const query = Object.assign(parsedQueryFromUrl, object.query); let queryString = exports.stringify(query, options); if (queryString) { queryString = `?${queryString}`; } let hash2 = getHash(object.url); if (object.fragmentIdentifier) { hash2 = `#${options[encodeFragmentIdentifier] ? encode8(object.fragmentIdentifier, options) : object.fragmentIdentifier}`; } return `${url}${queryString}${hash2}`; }; exports.pick = (input, filter, options) => { options = Object.assign({ parseFragmentIdentifier: true, [encodeFragmentIdentifier]: false }, options); const { url, query, fragmentIdentifier } = exports.parseUrl(input, options); return exports.stringifyUrl({ url, query: filterObject(query, filter), fragmentIdentifier }, options); }; exports.exclude = (input, filter, options) => { const exclusionFilter = Array.isArray(filter) ? (key2) => !filter.includes(key2) : (key2, value) => !filter(key2, value); return exports.pick(input, exclusionFilter, options); }; } }); // node_modules/js-sha3/src/sha3.js var require_sha3 = __commonJS({ "node_modules/js-sha3/src/sha3.js"(exports, module) { (function() { "use strict"; var INPUT_ERROR = "input is invalid type"; var FINALIZE_ERROR = "finalize already called"; var WINDOW = typeof window === "object"; var root = WINDOW ? window : {}; if (root.JS_SHA3_NO_WINDOW) { WINDOW = false; } var WEB_WORKER = !WINDOW && typeof self === "object"; var NODE_JS = !root.JS_SHA3_NO_NODE_JS && typeof process === "object" && process.versions && process.versions.node; if (NODE_JS) { root = global; } else if (WEB_WORKER) { root = self; } var COMMON_JS = !root.JS_SHA3_NO_COMMON_JS && typeof module === "object" && module.exports; var AMD = typeof define === "function" && define.amd; var ARRAY_BUFFER = !root.JS_SHA3_NO_ARRAY_BUFFER && typeof ArrayBuffer !== "undefined"; var HEX_CHARS = "0123456789abcdef".split(""); var SHAKE_PADDING = [31, 7936, 2031616, 520093696]; var CSHAKE_PADDING = [4, 1024, 262144, 67108864]; var KECCAK_PADDING = [1, 256, 65536, 16777216]; var PADDING = [6, 1536, 393216, 100663296]; var SHIFT = [0, 8, 16, 24]; var RC = [ 1, 0, 32898, 0, 32906, 2147483648, 2147516416, 2147483648, 32907, 0, 2147483649, 0, 2147516545, 2147483648, 32777, 2147483648, 138, 0, 136, 0, 2147516425, 0, 2147483658, 0, 2147516555, 0, 139, 2147483648, 32905, 2147483648, 32771, 2147483648, 32770, 2147483648, 128, 2147483648, 32778, 0, 2147483658, 2147483648, 2147516545, 2147483648, 32896, 2147483648, 2147483649, 0, 2147516424, 2147483648 ]; var BITS = [224, 256, 384, 512]; var SHAKE_BITS = [128, 256]; var OUTPUT_TYPES = ["hex", "buffer", "arrayBuffer", "array", "digest"]; var CSHAKE_BYTEPAD = { "128": 168, "256": 136 }; if (root.JS_SHA3_NO_NODE_JS || !Array.isArray) { Array.isArray = function(obj) { return Object.prototype.toString.call(obj) === "[object Array]"; }; } if (ARRAY_BUFFER && (root.JS_SHA3_NO_ARRAY_BUFFER_IS_VIEW || !ArrayBuffer.isView)) { ArrayBuffer.isView = function(obj) { return typeof obj === "object" && obj.buffer && obj.buffer.constructor === ArrayBuffer; }; } var createOutputMethod = function(bits2, padding2, outputType) { return function(message) { return new Keccak(bits2, padding2, bits2).update(message)[outputType](); }; }; var createShakeOutputMethod = function(bits2, padding2, outputType) { return function(message, outputBits) { return new Keccak(bits2, padding2, outputBits).update(message)[outputType](); }; }; var createCshakeOutputMethod = function(bits2, padding2, outputType) { return function(message, outputBits, n5, s3) { return methods["cshake" + bits2].update(message, outputBits, n5, s3)[outputType](); }; }; var createKmacOutputMethod = function(bits2, padding2, outputType) { return function(key2, message, outputBits, s3) { return methods["kmac" + bits2].update(key2, message, outputBits, s3)[outputType](); }; }; var createOutputMethods = function(method, createMethod2, bits2, padding2) { for (var i5 = 0; i5 < OUTPUT_TYPES.length; ++i5) { var type = OUTPUT_TYPES[i5]; method[type] = createMethod2(bits2, padding2, type); } return method; }; var createMethod = function(bits2, padding2) { var method = createOutputMethod(bits2, padding2, "hex"); method.create = function() { return new Keccak(bits2, padding2, bits2); }; method.update = function(message) { return method.create().update(message); }; return createOutputMethods(method, createOutputMethod, bits2, padding2); }; var createShakeMethod = function(bits2, padding2) { var method = createShakeOutputMethod(bits2, padding2, "hex"); method.create = function(outputBits) { return new Keccak(bits2, padding2, outputBits); }; method.update = function(message, outputBits) { return method.create(outputBits).update(message); }; return createOutputMethods(method, createShakeOutputMethod, bits2, padding2); }; var createCshakeMethod = function(bits2, padding2) { var w4 = CSHAKE_BYTEPAD[bits2]; var method = createCshakeOutputMethod(bits2, padding2, "hex"); method.create = function(outputBits, n5, s3) { if (!n5 && !s3) { return methods["shake" + bits2].create(outputBits); } else { return new Keccak(bits2, padding2, outputBits).bytepad([n5, s3], w4); } }; method.update = function(message, outputBits, n5, s3) { return method.create(outputBits, n5, s3).update(message); }; return createOutputMethods(method, createCshakeOutputMethod, bits2, padding2); }; var createKmacMethod = function(bits2, padding2) { var w4 = CSHAKE_BYTEPAD[bits2]; var method = createKmacOutputMethod(bits2, padding2, "hex"); method.create = function(key2, outputBits, s3) { return new Kmac(bits2, padding2, outputBits).bytepad(["KMAC", s3], w4).bytepad([key2], w4); }; method.update = function(key2, message, outputBits, s3) { return method.create(key2, outputBits, s3).update(message); }; return createOutputMethods(method, createKmacOutputMethod, bits2, padding2); }; var algorithms = [ { name: "keccak", padding: KECCAK_PADDING, bits: BITS, createMethod }, { name: "sha3", padding: PADDING, bits: BITS, createMethod }, { name: "shake", padding: SHAKE_PADDING, bits: SHAKE_BITS, createMethod: createShakeMethod }, { name: "cshake", padding: CSHAKE_PADDING, bits: SHAKE_BITS, createMethod: createCshakeMethod }, { name: "kmac", padding: CSHAKE_PADDING, bits: SHAKE_BITS, createMethod: createKmacMethod } ]; var methods = {}, methodNames = []; for (var i4 = 0; i4 < algorithms.length; ++i4) { var algorithm = algorithms[i4]; var bits = algorithm.bits; for (var j2 = 0; j2 < bits.length; ++j2) { var methodName = algorithm.name + "_" + bits[j2]; methodNames.push(methodName); methods[methodName] = algorithm.createMethod(bits[j2], algorithm.padding); if (algorithm.name !== "sha3") { var newMethodName = algorithm.name + bits[j2]; methodNames.push(newMethodName); methods[newMethodName] = methods[methodName]; } } } function Keccak(bits2, padding2, outputBits) { this.blocks = []; this.s = []; this.padding = padding2; this.outputBits = outputBits; this.reset = true; this.finalized = false; this.block = 0; this.start = 0; this.blockCount = 1600 - (bits2 << 1) >> 5; this.byteCount = this.blockCount << 2; this.outputBlocks = outputBits >> 5; this.extraBytes = (outputBits & 31) >> 3; for (var i5 = 0; i5 < 50; ++i5) { this.s[i5] = 0; } } Keccak.prototype.update = function(message) { if (this.finalized) { throw new Error(FINALIZE_ERROR); } var notString, type = typeof message; if (type !== "string") { if (type === "object") { if (message === null) { throw new Error(INPUT_ERROR); } else if (ARRAY_BUFFER && message.constructor === ArrayBuffer) { message = new Uint8Array(message); } else if (!Array.isArray(message)) { if (!ARRAY_BUFFER || !ArrayBuffer.isView(message)) { throw new Error(INPUT_ERROR); } } } else { throw new Error(INPUT_ERROR); } notString = true; } var blocks = this.blocks, byteCount = this.byteCount, length2 = message.length, blockCount = this.blockCount, index = 0, s3 = this.s, i5, code2; while (index < length2) { if (this.reset) { this.reset = false; blocks[0] = this.block; for (i5 = 1; i5 < blockCount + 1; ++i5) { blocks[i5] = 0; } } if (notString) { for (i5 = this.start; index < length2 && i5 < byteCount; ++index) { blocks[i5 >> 2] |= message[index] << SHIFT[i5++ & 3]; } } else { for (i5 = this.start; index < length2 && i5 < byteCount; ++index) { code2 = message.charCodeAt(index); if (code2 < 128) { blocks[i5 >> 2] |= code2 << SHIFT[i5++ & 3]; } else if (code2 < 2048) { blocks[i5 >> 2] |= (192 | code2 >> 6) << SHIFT[i5++ & 3]; blocks[i5 >> 2] |= (128 | code2 & 63) << SHIFT[i5++ & 3]; } else if (code2 < 55296 || code2 >= 57344) { blocks[i5 >> 2] |= (224 | code2 >> 12) << SHIFT[i5++ & 3]; blocks[i5 >> 2] |= (128 | code2 >> 6 & 63) << SHIFT[i5++ & 3]; blocks[i5 >> 2] |= (128 | code2 & 63) << SHIFT[i5++ & 3]; } else { code2 = 65536 + ((code2 & 1023) << 10 | message.charCodeAt(++index) & 1023); blocks[i5 >> 2] |= (240 | code2 >> 18) << SHIFT[i5++ & 3]; blocks[i5 >> 2] |= (128 | code2 >> 12 & 63) << SHIFT[i5++ & 3]; blocks[i5 >> 2] |= (128 | code2 >> 6 & 63) << SHIFT[i5++ & 3]; blocks[i5 >> 2] |= (128 | code2 & 63) << SHIFT[i5++ & 3]; } } } this.lastByteIndex = i5; if (i5 >= byteCount) { this.start = i5 - byteCount; this.block = blocks[blockCount]; for (i5 = 0; i5 < blockCount; ++i5) { s3[i5] ^= blocks[i5]; } f4(s3); this.reset = true; } else { this.start = i5; } } return this; }; Keccak.prototype.encode = function(x6, right) { var o4 = x6 & 255, n5 = 1; var bytes = [o4]; x6 = x6 >> 8; o4 = x6 & 255; while (o4 > 0) { bytes.unshift(o4); x6 = x6 >> 8; o4 = x6 & 255; ++n5; } if (right) { bytes.push(n5); } else { bytes.unshift(n5); } this.update(bytes); return bytes.length; }; Keccak.prototype.encodeString = function(str) { var notString, type = typeof str; if (type !== "string") { if (type === "object") { if (str === null) { throw new Error(INPUT_ERROR); } else if (ARRAY_BUFFER && str.constructor === ArrayBuffer) { str = new Uint8Array(str); } else if (!Array.isArray(str)) { if (!ARRAY_BUFFER || !ArrayBuffer.isView(str)) { throw new Error(INPUT_ERROR); } } } else { throw new Error(INPUT_ERROR); } notString = true; } var bytes = 0, length2 = str.length; if (notString) { bytes = length2; } else { for (var i5 = 0; i5 < str.length; ++i5) { var code2 = str.charCodeAt(i5); if (code2 < 128) { bytes += 1; } else if (code2 < 2048) { bytes += 2; } else if (code2 < 55296 || code2 >= 57344) { bytes += 3; } else { code2 = 65536 + ((code2 & 1023) << 10 | str.charCodeAt(++i5) & 1023); bytes += 4; } } } bytes += this.encode(bytes * 8); this.update(str); return bytes; }; Keccak.prototype.bytepad = function(strs, w4) { var bytes = this.encode(w4); for (var i5 = 0; i5 < strs.length; ++i5) { bytes += this.encodeString(strs[i5]); } var paddingBytes = w4 - bytes % w4; var zeros2 = []; zeros2.length = paddingBytes; this.update(zeros2); return this; }; Keccak.prototype.finalize = function() { if (this.finalized) { return; } this.finalized = true; var blocks = this.blocks, i5 = this.lastByteIndex, blockCount = this.blockCount, s3 = this.s; blocks[i5 >> 2] |= this.padding[i5 & 3]; if (this.lastByteIndex === this.byteCount) { blocks[0] = blocks[blockCount]; for (i5 = 1; i5 < blockCount + 1; ++i5) { blocks[i5] = 0; } } blocks[blockCount - 1] |= 2147483648; for (i5 = 0; i5 < blockCount; ++i5) { s3[i5] ^= blocks[i5]; } f4(s3); }; Keccak.prototype.toString = Keccak.prototype.hex = function() { this.finalize(); var blockCount = this.blockCount, s3 = this.s, outputBlocks = this.outputBlocks, extraBytes = this.extraBytes, i5 = 0, j3 = 0; var hex = "", block; while (j3 < outputBlocks) { for (i5 = 0; i5 < blockCount && j3 < outputBlocks; ++i5, ++j3) { block = s3[i5]; hex += HEX_CHARS[block >> 4 & 15] + HEX_CHARS[block & 15] + HEX_CHARS[block >> 12 & 15] + HEX_CHARS[block >> 8 & 15] + HEX_CHARS[block >> 20 & 15] + HEX_CHARS[block >> 16 & 15] + HEX_CHARS[block >> 28 & 15] + HEX_CHARS[block >> 24 & 15]; } if (j3 % blockCount === 0) { f4(s3); i5 = 0; } } if (extraBytes) { block = s3[i5]; hex += HEX_CHARS[block >> 4 & 15] + HEX_CHARS[block & 15]; if (extraBytes > 1) { hex += HEX_CHARS[block >> 12 & 15] + HEX_CHARS[block >> 8 & 15]; } if (extraBytes > 2) { hex += HEX_CHARS[block >> 20 & 15] + HEX_CHARS[block >> 16 & 15]; } } return hex; }; Keccak.prototype.arrayBuffer = function() { this.finalize(); var blockCount = this.blockCount, s3 = this.s, outputBlocks = this.outputBlocks, extraBytes = this.extraBytes, i5 = 0, j3 = 0; var bytes = this.outputBits >> 3; var buffer; if (extraBytes) { buffer = new ArrayBuffer(outputBlocks + 1 << 2); } else { buffer = new ArrayBuffer(bytes); } var array = new Uint32Array(buffer); while (j3 < outputBlocks) { for (i5 = 0; i5 < blockCount && j3 < outputBlocks; ++i5, ++j3) { array[j3] = s3[i5]; } if (j3 % blockCount === 0) { f4(s3); } } if (extraBytes) { array[i5] = s3[i5]; buffer = buffer.slice(0, bytes); } return buffer; }; Keccak.prototype.buffer = Keccak.prototype.arrayBuffer; Keccak.prototype.digest = Keccak.prototype.array = function() { this.finalize(); var blockCount = this.blockCount, s3 = this.s, outputBlocks = this.outputBlocks, extraBytes = this.extraBytes, i5 = 0, j3 = 0; var array = [], offset, block; while (j3 < outputBlocks) { for (i5 = 0; i5 < blockCount && j3 < outputBlocks; ++i5, ++j3) { offset = j3 << 2; block = s3[i5]; array[offset] = block & 255; array[offset + 1] = block >> 8 & 255; array[offset + 2] = block >> 16 & 255; array[offset + 3] = block >> 24 & 255; } if (j3 % blockCount === 0) { f4(s3); } } if (extraBytes) { offset = j3 << 2; block = s3[i5]; array[offset] = block & 255; if (extraBytes > 1) { array[offset + 1] = block >> 8 & 255; } if (extraBytes > 2) { array[offset + 2] = block >> 16 & 255; } } return array; }; function Kmac(bits2, padding2, outputBits) { Keccak.call(this, bits2, padding2, outputBits); } Kmac.prototype = new Keccak(); Kmac.prototype.finalize = function() { this.encode(this.outputBits, true); return Keccak.prototype.finalize.call(this); }; var f4 = function(s3) { var h5, l4, n5, c0, c1, c22, c32, c42, c5, c6, c7, c8, c9, b0, b1, b22, b32, b42, b5, b6, b7, b8, b9, b10, b11, b12, b13, b14, b15, b16, b17, b18, b19, b20, b21, b222, b23, b24, b25, b26, b27, b28, b29, b30, b31, b322, b33, b34, b35, b36, b37, b38, b39, b40, b41, b422, b43, b44, b45, b46, b47, b48, b49; for (n5 = 0; n5 < 48; n5 += 2) { c0 = s3[0] ^ s3[10] ^ s3[20] ^ s3[30] ^ s3[40]; c1 = s3[1] ^ s3[11] ^ s3[21] ^ s3[31] ^ s3[41]; c22 = s3[2] ^ s3[12] ^ s3[22] ^ s3[32] ^ s3[42]; c32 = s3[3] ^ s3[13] ^ s3[23] ^ s3[33] ^ s3[43]; c42 = s3[4] ^ s3[14] ^ s3[24] ^ s3[34] ^ s3[44]; c5 = s3[5] ^ s3[15] ^ s3[25] ^ s3[35] ^ s3[45]; c6 = s3[6] ^ s3[16] ^ s3[26] ^ s3[36] ^ s3[46]; c7 = s3[7] ^ s3[17] ^ s3[27] ^ s3[37] ^ s3[47]; c8 = s3[8] ^ s3[18] ^ s3[28] ^ s3[38] ^ s3[48]; c9 = s3[9] ^ s3[19] ^ s3[29] ^ s3[39] ^ s3[49]; h5 = c8 ^ (c22 << 1 | c32 >>> 31); l4 = c9 ^ (c32 << 1 | c22 >>> 31); s3[0] ^= h5; s3[1] ^= l4; s3[10] ^= h5; s3[11] ^= l4; s3[20] ^= h5; s3[21] ^= l4; s3[30] ^= h5; s3[31] ^= l4; s3[40] ^= h5; s3[41] ^= l4; h5 = c0 ^ (c42 << 1 | c5 >>> 31); l4 = c1 ^ (c5 << 1 | c42 >>> 31); s3[2] ^= h5; s3[3] ^= l4; s3[12] ^= h5; s3[13] ^= l4; s3[22] ^= h5; s3[23] ^= l4; s3[32] ^= h5; s3[33] ^= l4; s3[42] ^= h5; s3[43] ^= l4; h5 = c22 ^ (c6 << 1 | c7 >>> 31); l4 = c32 ^ (c7 << 1 | c6 >>> 31); s3[4] ^= h5; s3[5] ^= l4; s3[14] ^= h5; s3[15] ^= l4; s3[24] ^= h5; s3[25] ^= l4; s3[34] ^= h5; s3[35] ^= l4; s3[44] ^= h5; s3[45] ^= l4; h5 = c42 ^ (c8 << 1 | c9 >>> 31); l4 = c5 ^ (c9 << 1 | c8 >>> 31); s3[6] ^= h5; s3[7] ^= l4; s3[16] ^= h5; s3[17] ^= l4; s3[26] ^= h5; s3[27] ^= l4; s3[36] ^= h5; s3[37] ^= l4; s3[46] ^= h5; s3[47] ^= l4; h5 = c6 ^ (c0 << 1 | c1 >>> 31); l4 = c7 ^ (c1 << 1 | c0 >>> 31); s3[8] ^= h5; s3[9] ^= l4; s3[18] ^= h5; s3[19] ^= l4; s3[28] ^= h5; s3[29] ^= l4; s3[38] ^= h5; s3[39] ^= l4; s3[48] ^= h5; s3[49] ^= l4; b0 = s3[0]; b1 = s3[1]; b322 = s3[11] << 4 | s3[10] >>> 28; b33 = s3[10] << 4 | s3[11] >>> 28; b14 = s3[20] << 3 | s3[21] >>> 29; b15 = s3[21] << 3 | s3[20] >>> 29; b46 = s3[31] << 9 | s3[30] >>> 23; b47 = s3[30] << 9 | s3[31] >>> 23; b28 = s3[40] << 18 | s3[41] >>> 14; b29 = s3[41] << 18 | s3[40] >>> 14; b20 = s3[2] << 1 | s3[3] >>> 31; b21 = s3[3] << 1 | s3[2] >>> 31; b22 = s3[13] << 12 | s3[12] >>> 20; b32 = s3[12] << 12 | s3[13] >>> 20; b34 = s3[22] << 10 | s3[23] >>> 22; b35 = s3[23] << 10 | s3[22] >>> 22; b16 = s3[33] << 13 | s3[32] >>> 19; b17 = s3[32] << 13 | s3[33] >>> 19; b48 = s3[42] << 2 | s3[43] >>> 30; b49 = s3[43] << 2 | s3[42] >>> 30; b40 = s3[5] << 30 | s3[4] >>> 2; b41 = s3[4] << 30 | s3[5] >>> 2; b222 = s3[14] << 6 | s3[15] >>> 26; b23 = s3[15] << 6 | s3[14] >>> 26; b42 = s3[25] << 11 | s3[24] >>> 21; b5 = s3[24] << 11 | s3[25] >>> 21; b36 = s3[34] << 15 | s3[35] >>> 17; b37 = s3[35] << 15 | s3[34] >>> 17; b18 = s3[45] << 29 | s3[44] >>> 3; b19 = s3[44] << 29 | s3[45] >>> 3; b10 = s3[6] << 28 | s3[7] >>> 4; b11 = s3[7] << 28 | s3[6] >>> 4; b422 = s3[17] << 23 | s3[16] >>> 9; b43 = s3[16] << 23 | s3[17] >>> 9; b24 = s3[26] << 25 | s3[27] >>> 7; b25 = s3[27] << 25 | s3[26] >>> 7; b6 = s3[36] << 21 | s3[37] >>> 11; b7 = s3[37] << 21 | s3[36] >>> 11; b38 = s3[47] << 24 | s3[46] >>> 8; b39 = s3[46] << 24 | s3[47] >>> 8; b30 = s3[8] << 27 | s3[9] >>> 5; b31 = s3[9] << 27 | s3[8] >>> 5; b12 = s3[18] << 20 | s3[19] >>> 12; b13 = s3[19] << 20 | s3[18] >>> 12; b44 = s3[29] << 7 | s3[28] >>> 25; b45 = s3[28] << 7 | s3[29] >>> 25; b26 = s3[38] << 8 | s3[39] >>> 24; b27 = s3[39] << 8 | s3[38] >>> 24; b8 = s3[48] << 14 | s3[49] >>> 18; b9 = s3[49] << 14 | s3[48] >>> 18; s3[0] = b0 ^ ~b22 & b42; s3[1] = b1 ^ ~b32 & b5; s3[10] = b10 ^ ~b12 & b14; s3[11] = b11 ^ ~b13 & b15; s3[20] = b20 ^ ~b222 & b24; s3[21] = b21 ^ ~b23 & b25; s3[30] = b30 ^ ~b322 & b34; s3[31] = b31 ^ ~b33 & b35; s3[40] = b40 ^ ~b422 & b44; s3[41] = b41 ^ ~b43 & b45; s3[2] = b22 ^ ~b42 & b6; s3[3] = b32 ^ ~b5 & b7; s3[12] = b12 ^ ~b14 & b16; s3[13] = b13 ^ ~b15 & b17; s3[22] = b222 ^ ~b24 & b26; s3[23] = b23 ^ ~b25 & b27; s3[32] = b322 ^ ~b34 & b36; s3[33] = b33 ^ ~b35 & b37; s3[42] = b422 ^ ~b44 & b46; s3[43] = b43 ^ ~b45 & b47; s3[4] = b42 ^ ~b6 & b8; s3[5] = b5 ^ ~b7 & b9; s3[14] = b14 ^ ~b16 & b18; s3[15] = b15 ^ ~b17 & b19; s3[24] = b24 ^ ~b26 & b28; s3[25] = b25 ^ ~b27 & b29; s3[34] = b34 ^ ~b36 & b38; s3[35] = b35 ^ ~b37 & b39; s3[44] = b44 ^ ~b46 & b48; s3[45] = b45 ^ ~b47 & b49; s3[6] = b6 ^ ~b8 & b0; s3[7] = b7 ^ ~b9 & b1; s3[16] = b16 ^ ~b18 & b10; s3[17] = b17 ^ ~b19 & b11; s3[26] = b26 ^ ~b28 & b20; s3[27] = b27 ^ ~b29 & b21; s3[36] = b36 ^ ~b38 & b30; s3[37] = b37 ^ ~b39 & b31; s3[46] = b46 ^ ~b48 & b40; s3[47] = b47 ^ ~b49 & b41; s3[8] = b8 ^ ~b0 & b22; s3[9] = b9 ^ ~b1 & b32; s3[18] = b18 ^ ~b10 & b12; s3[19] = b19 ^ ~b11 & b13; s3[28] = b28 ^ ~b20 & b222; s3[29] = b29 ^ ~b21 & b23; s3[38] = b38 ^ ~b30 & b322; s3[39] = b39 ^ ~b31 & b33; s3[48] = b48 ^ ~b40 & b422; s3[49] = b49 ^ ~b41 & b43; s3[0] ^= RC[n5]; s3[1] ^= RC[n5 + 1]; } }; if (COMMON_JS) { module.exports = methods; } else { for (i4 = 0; i4 < methodNames.length; ++i4) { root[methodNames[i4]] = methods[methodNames[i4]]; } if (AMD) { define(function() { return methods; }); } } })(); } }); // browser-external:buffer var require_buffer = __commonJS({ "browser-external:buffer"(exports, module) { module.exports = Object.create(new Proxy({}, { get(_4, key2) { if (key2 !== "__esModule" && key2 !== "__proto__" && key2 !== "constructor" && key2 !== "splice") { console.warn(`Module "buffer" has been externalized for browser compatibility. Cannot access "buffer.${key2}" in client code. See http://vitejs.dev/guide/troubleshooting.html#module-externalized-for-browser-compatibility for more details.`); } } })); } }); // node_modules/bn.js/lib/bn.js var require_bn = __commonJS({ "node_modules/bn.js/lib/bn.js"(exports, module) { (function(module2, exports2) { "use strict"; function assert2(val, msg) { if (!val) throw new Error(msg || "Assertion failed"); } function inherits(ctor, superCtor) { ctor.super_ = superCtor; var TempCtor = function() { }; TempCtor.prototype = superCtor.prototype; ctor.prototype = new TempCtor(); ctor.prototype.constructor = ctor; } function BN3(number, base3, endian) { if (BN3.isBN(number)) { return number; } this.negative = 0; this.words = null; this.length = 0; this.red = null; if (number !== null) { if (base3 === "le" || base3 === "be") { endian = base3; base3 = 10; } this._init(number || 0, base3 || 10, endian || "be"); } } if (typeof module2 === "object") { module2.exports = BN3; } else { exports2.BN = BN3; } BN3.BN = BN3; BN3.wordSize = 26; var Buffer2; try { if (typeof window !== "undefined" && typeof window.Buffer !== "undefined") { Buffer2 = window.Buffer; } else { Buffer2 = require_buffer().Buffer; } } catch (e2) { } BN3.isBN = function isBN(num) { if (num instanceof BN3) { return true; } return num !== null && typeof num === "object" && num.constructor.wordSize === BN3.wordSize && Array.isArray(num.words); }; BN3.max = function max(left, right) { if (left.cmp(right) > 0) return left; return right; }; BN3.min = function min(left, right) { if (left.cmp(right) < 0) return left; return right; }; BN3.prototype._init = function init2(number, base3, endian) { if (typeof number === "number") { return this._initNumber(number, base3, endian); } if (typeof number === "object") { return this._initArray(number, base3, endian); } if (base3 === "hex") { base3 = 16; } assert2(base3 === (base3 | 0) && base3 >= 2 && base3 <= 36); number = number.toString().replace(/\s+/g, ""); var start = 0; if (number[0] === "-") { start++; this.negative = 1; } if (start < number.length) { if (base3 === 16) { this._parseHex(number, start, endian); } else { this._parseBase(number, base3, start); if (endian === "le") { this._initArray(this.toArray(), base3, endian); } } } }; BN3.prototype._initNumber = function _initNumber(number, base3, endian) { if (number < 0) { this.negative = 1; number = -number; } if (number < 67108864) { this.words = [number & 67108863]; this.length = 1; } else if (number < 4503599627370496) { this.words = [ number & 67108863, number / 67108864 & 67108863 ]; this.length = 2; } else { assert2(number < 9007199254740992); this.words = [ number & 67108863, number / 67108864 & 67108863, 1 ]; this.length = 3; } if (endian !== "le") return; this._initArray(this.toArray(), base3, endian); }; BN3.prototype._initArray = function _initArray(number, base3, endian) { assert2(typeof number.length === "number"); if (number.length <= 0) { this.words = [0]; this.length = 1; return this; } this.length = Math.ceil(number.length / 3); this.words = new Array(this.length); for (var i4 = 0; i4 < this.length; i4++) { this.words[i4] = 0; } var j2, w4; var off = 0; if (endian === "be") { for (i4 = number.length - 1, j2 = 0; i4 >= 0; i4 -= 3) { w4 = number[i4] | number[i4 - 1] << 8 | number[i4 - 2] << 16; this.words[j2] |= w4 << off & 67108863; this.words[j2 + 1] = w4 >>> 26 - off & 67108863; off += 24; if (off >= 26) { off -= 26; j2++; } } } else if (endian === "le") { for (i4 = 0, j2 = 0; i4 < number.length; i4 += 3) { w4 = number[i4] | number[i4 + 1] << 8 | number[i4 + 2] << 16; this.words[j2] |= w4 << off & 67108863; this.words[j2 + 1] = w4 >>> 26 - off & 67108863; off += 24; if (off >= 26) { off -= 26; j2++; } } } return this._strip(); }; function parseHex4Bits(string2, index) { var c5 = string2.charCodeAt(index); if (c5 >= 48 && c5 <= 57) { return c5 - 48; } else if (c5 >= 65 && c5 <= 70) { return c5 - 55; } else if (c5 >= 97 && c5 <= 102) { return c5 - 87; } else { assert2(false, "Invalid character in " + string2); } } function parseHexByte(string2, lowerBound, index) { var r4 = parseHex4Bits(string2, index); if (index - 1 >= lowerBound) { r4 |= parseHex4Bits(string2, index - 1) << 4; } return r4; } BN3.prototype._parseHex = function _parseHex(number, start, endian) { this.length = Math.ceil((number.length - start) / 6); this.words = new Array(this.length); for (var i4 = 0; i4 < this.length; i4++) { this.words[i4] = 0; } var off = 0; var j2 = 0; var w4; if (endian === "be") { for (i4 = number.length - 1; i4 >= start; i4 -= 2) { w4 = parseHexByte(number, start, i4) << off; this.words[j2] |= w4 & 67108863; if (off >= 18) { off -= 18; j2 += 1; this.words[j2] |= w4 >>> 26; } else { off += 8; } } } else { var parseLength = number.length - start; for (i4 = parseLength % 2 === 0 ? start + 1 : start; i4 < number.length; i4 += 2) { w4 = parseHexByte(number, start, i4) << off; this.words[j2] |= w4 & 67108863; if (off >= 18) { off -= 18; j2 += 1; this.words[j2] |= w4 >>> 26; } else { off += 8; } } } this._strip(); }; function parseBase(str, start, end, mul3) { var r4 = 0; var b5 = 0; var len = Math.min(str.length, end); for (var i4 = start; i4 < len; i4++) { var c5 = str.charCodeAt(i4) - 48; r4 *= mul3; if (c5 >= 49) { b5 = c5 - 49 + 10; } else if (c5 >= 17) { b5 = c5 - 17 + 10; } else { b5 = c5; } assert2(c5 >= 0 && b5 < mul3, "Invalid character"); r4 += b5; } return r4; } BN3.prototype._parseBase = function _parseBase(number, base3, start) { this.words = [0]; this.length = 1; for (var limbLen = 0, limbPow = 1; limbPow <= 67108863; limbPow *= base3) { limbLen++; } limbLen--; limbPow = limbPow / base3 | 0; var total = number.length - start; var mod = total % limbLen; var end = Math.min(total, total - mod) + start; var word = 0; for (var i4 = start; i4 < end; i4 += limbLen) { word = parseBase(number, i4, i4 + limbLen, base3); this.imuln(limbPow); if (this.words[0] + word < 67108864) { this.words[0] += word; } else { this._iaddn(word); } } if (mod !== 0) { var pow = 1; word = parseBase(number, i4, number.length, base3); for (i4 = 0; i4 < mod; i4++) { pow *= base3; } this.imuln(pow); if (this.words[0] + word < 67108864) { this.words[0] += word; } else { this._iaddn(word); } } this._strip(); }; BN3.prototype.copy = function copy(dest) { dest.words = new Array(this.length); for (var i4 = 0; i4 < this.length; i4++) { dest.words[i4] = this.words[i4]; } dest.length = this.length; dest.negative = this.negative; dest.red = this.red; }; function move(dest, src2) { dest.words = src2.words; dest.length = src2.length; dest.negative = src2.negative; dest.red = src2.red; } BN3.prototype._move = function _move(dest) { move(dest, this); }; BN3.prototype.clone = function clone() { var r4 = new BN3(null); this.copy(r4); return r4; }; BN3.prototype._expand = function _expand(size) { while (this.length < size) { this.words[this.length++] = 0; } return this; }; BN3.prototype._strip = function strip() { while (this.length > 1 && this.words[this.length - 1] === 0) { this.length--; } return this._normSign(); }; BN3.prototype._normSign = function _normSign() { if (this.length === 1 && this.words[0] === 0) { this.negative = 0; } return this; }; if (typeof Symbol !== "undefined" && typeof Symbol.for === "function") { try { BN3.prototype[Symbol.for("nodejs.util.inspect.custom")] = inspect4; } catch (e2) { BN3.prototype.inspect = inspect4; } } else { BN3.prototype.inspect = inspect4; } function inspect4() { return (this.red ? ""; } var zeros2 = [ "", "0", "00", "000", "0000", "00000", "000000", "0000000", "00000000", "000000000", "0000000000", "00000000000", "000000000000", "0000000000000", "00000000000000", "000000000000000", "0000000000000000", "00000000000000000", "000000000000000000", "0000000000000000000", "00000000000000000000", "000000000000000000000", "0000000000000000000000", "00000000000000000000000", "000000000000000000000000", "0000000000000000000000000" ]; var groupSizes = [ 0, 0, 25, 16, 12, 11, 10, 9, 8, 8, 7, 7, 7, 7, 6, 6, 6, 6, 6, 6, 6, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5 ]; var groupBases = [ 0, 0, 33554432, 43046721, 16777216, 48828125, 60466176, 40353607, 16777216, 43046721, 1e7, 19487171, 35831808, 62748517, 7529536, 11390625, 16777216, 24137569, 34012224, 47045881, 64e6, 4084101, 5153632, 6436343, 7962624, 9765625, 11881376, 14348907, 17210368, 20511149, 243e5, 28629151, 33554432, 39135393, 45435424, 52521875, 60466176 ]; BN3.prototype.toString = function toString3(base3, padding2) { base3 = base3 || 10; padding2 = padding2 | 0 || 1; var out; if (base3 === 16 || base3 === "hex") { out = ""; var off = 0; var carry = 0; for (var i4 = 0; i4 < this.length; i4++) { var w4 = this.words[i4]; var word = ((w4 << off | carry) & 16777215).toString(16); carry = w4 >>> 24 - off & 16777215; off += 2; if (off >= 26) { off -= 26; i4--; } if (carry !== 0 || i4 !== this.length - 1) { out = zeros2[6 - word.length] + word + out; } else { out = word + out; } } if (carry !== 0) { out = carry.toString(16) + out; } while (out.length % padding2 !== 0) { out = "0" + out; } if (this.negative !== 0) { out = "-" + out; } return out; } if (base3 === (base3 | 0) && base3 >= 2 && base3 <= 36) { var groupSize = groupSizes[base3]; var groupBase = groupBases[base3]; out = ""; var c5 = this.clone(); c5.negative = 0; while (!c5.isZero()) { var r4 = c5.modrn(groupBase).toString(base3); c5 = c5.idivn(groupBase); if (!c5.isZero()) { out = zeros2[groupSize - r4.length] + r4 + out; } else { out = r4 + out; } } if (this.isZero()) { out = "0" + out; } while (out.length % padding2 !== 0) { out = "0" + out; } if (this.negative !== 0) { out = "-" + out; } return out; } assert2(false, "Base should be between 2 and 36"); }; BN3.prototype.toNumber = function toNumber() { var ret = this.words[0]; if (this.length === 2) { ret += this.words[1] * 67108864; } else if (this.length === 3 && this.words[2] === 1) { ret += 4503599627370496 + this.words[1] * 67108864; } else if (this.length > 2) { assert2(false, "Number can only safely store up to 53 bits"); } return this.negative !== 0 ? -ret : ret; }; BN3.prototype.toJSON = function toJSON2() { return this.toString(16, 2); }; if (Buffer2) { BN3.prototype.toBuffer = function toBuffer(endian, length2) { return this.toArrayLike(Buffer2, endian, length2); }; } BN3.prototype.toArray = function toArray(endian, length2) { return this.toArrayLike(Array, endian, length2); }; var allocate = function allocate2(ArrayType, size) { if (ArrayType.allocUnsafe) { return ArrayType.allocUnsafe(size); } return new ArrayType(size); }; BN3.prototype.toArrayLike = function toArrayLike(ArrayType, endian, length2) { this._strip(); var byteLength = this.byteLength(); var reqLength = length2 || Math.max(1, byteLength); assert2(byteLength <= reqLength, "byte array longer than desired length"); assert2(reqLength > 0, "Requested array length <= 0"); var res = allocate(ArrayType, reqLength); var postfix = endian === "le" ? "LE" : "BE"; this["_toArrayLike" + postfix](res, byteLength); return res; }; BN3.prototype._toArrayLikeLE = function _toArrayLikeLE(res, byteLength) { var position = 0; var carry = 0; for (var i4 = 0, shift = 0; i4 < this.length; i4++) { var word = this.words[i4] << shift | carry; res[position++] = word & 255; if (position < res.length) { res[position++] = word >> 8 & 255; } if (position < res.length) { res[position++] = word >> 16 & 255; } if (shift === 6) { if (position < res.length) { res[position++] = word >> 24 & 255; } carry = 0; shift = 0; } else { carry = word >>> 24; shift += 2; } } if (position < res.length) { res[position++] = carry; while (position < res.length) { res[position++] = 0; } } }; BN3.prototype._toArrayLikeBE = function _toArrayLikeBE(res, byteLength) { var position = res.length - 1; var carry = 0; for (var i4 = 0, shift = 0; i4 < this.length; i4++) { var word = this.words[i4] << shift | carry; res[position--] = word & 255; if (position >= 0) { res[position--] = word >> 8 & 255; } if (position >= 0) { res[position--] = word >> 16 & 255; } if (shift === 6) { if (position >= 0) { res[position--] = word >> 24 & 255; } carry = 0; shift = 0; } else { carry = word >>> 24; shift += 2; } } if (position >= 0) { res[position--] = carry; while (position >= 0) { res[position--] = 0; } } }; if (Math.clz32) { BN3.prototype._countBits = function _countBits(w4) { return 32 - Math.clz32(w4); }; } else { BN3.prototype._countBits = function _countBits(w4) { var t = w4; var r4 = 0; if (t >= 4096) { r4 += 13; t >>>= 13; } if (t >= 64) { r4 += 7; t >>>= 7; } if (t >= 8) { r4 += 4; t >>>= 4; } if (t >= 2) { r4 += 2; t >>>= 2; } return r4 + t; }; } BN3.prototype._zeroBits = function _zeroBits(w4) { if (w4 === 0) return 26; var t = w4; var r4 = 0; if ((t & 8191) === 0) { r4 += 13; t >>>= 13; } if ((t & 127) === 0) { r4 += 7; t >>>= 7; } if ((t & 15) === 0) { r4 += 4; t >>>= 4; } if ((t & 3) === 0) { r4 += 2; t >>>= 2; } if ((t & 1) === 0) { r4++; } return r4; }; BN3.prototype.bitLength = function bitLength() { var w4 = this.words[this.length - 1]; var hi2 = this._countBits(w4); return (this.length - 1) * 26 + hi2; }; function toBitArray(num) { var w4 = new Array(num.bitLength()); for (var bit = 0; bit < w4.length; bit++) { var off = bit / 26 | 0; var wbit = bit % 26; w4[bit] = num.words[off] >>> wbit & 1; } return w4; } BN3.prototype.zeroBits = function zeroBits() { if (this.isZero()) return 0; var r4 = 0; for (var i4 = 0; i4 < this.length; i4++) { var b5 = this._zeroBits(this.words[i4]); r4 += b5; if (b5 !== 26) break; } return r4; }; BN3.prototype.byteLength = function byteLength() { return Math.ceil(this.bitLength() / 8); }; BN3.prototype.toTwos = function toTwos(width) { if (this.negative !== 0) { return this.abs().inotn(width).iaddn(1); } return this.clone(); }; BN3.prototype.fromTwos = function fromTwos(width) { if (this.testn(width - 1)) { return this.notn(width).iaddn(1).ineg(); } return this.clone(); }; BN3.prototype.isNeg = function isNeg() { return this.negative !== 0; }; BN3.prototype.neg = function neg3() { return this.clone().ineg(); }; BN3.prototype.ineg = function ineg() { if (!this.isZero()) { this.negative ^= 1; } return this; }; BN3.prototype.iuor = function iuor(num) { while (this.length < num.length) { this.words[this.length++] = 0; } for (var i4 = 0; i4 < num.length; i4++) { this.words[i4] = this.words[i4] | num.words[i4]; } return this._strip(); }; BN3.prototype.ior = function ior(num) { assert2((this.negative | num.negative) === 0); return this.iuor(num); }; BN3.prototype.or = function or3(num) { if (this.length > num.length) return this.clone().ior(num); return num.clone().ior(this); }; BN3.prototype.uor = function uor(num) { if (this.length > num.length) return this.clone().iuor(num); return num.clone().iuor(this); }; BN3.prototype.iuand = function iuand(num) { var b5; if (this.length > num.length) { b5 = num; } else { b5 = this; } for (var i4 = 0; i4 < b5.length; i4++) { this.words[i4] = this.words[i4] & num.words[i4]; } this.length = b5.length; return this._strip(); }; BN3.prototype.iand = function iand(num) { assert2((this.negative | num.negative) === 0); return this.iuand(num); }; BN3.prototype.and = function and(num) { if (this.length > num.length) return this.clone().iand(num); return num.clone().iand(this); }; BN3.prototype.uand = function uand(num) { if (this.length > num.length) return this.clone().iuand(num); return num.clone().iuand(this); }; BN3.prototype.iuxor = function iuxor(num) { var a4; var b5; if (this.length > num.length) { a4 = this; b5 = num; } else { a4 = num; b5 = this; } for (var i4 = 0; i4 < b5.length; i4++) { this.words[i4] = a4.words[i4] ^ b5.words[i4]; } if (this !== a4) { for (; i4 < a4.length; i4++) { this.words[i4] = a4.words[i4]; } } this.length = a4.length; return this._strip(); }; BN3.prototype.ixor = function ixor(num) { assert2((this.negative | num.negative) === 0); return this.iuxor(num); }; BN3.prototype.xor = function xor2(num) { if (this.length > num.length) return this.clone().ixor(num); return num.clone().ixor(this); }; BN3.prototype.uxor = function uxor(num) { if (this.length > num.length) return this.clone().iuxor(num); return num.clone().iuxor(this); }; BN3.prototype.inotn = function inotn(width) { assert2(typeof width === "number" && width >= 0); var bytesNeeded = Math.ceil(width / 26) | 0; var bitsLeft = width % 26; this._expand(bytesNeeded); if (bitsLeft > 0) { bytesNeeded--; } for (var i4 = 0; i4 < bytesNeeded; i4++) { this.words[i4] = ~this.words[i4] & 67108863; } if (bitsLeft > 0) { this.words[i4] = ~this.words[i4] & 67108863 >> 26 - bitsLeft; } return this._strip(); }; BN3.prototype.notn = function notn(width) { return this.clone().inotn(width); }; BN3.prototype.setn = function setn(bit, val) { assert2(typeof bit === "number" && bit >= 0); var off = bit / 26 | 0; var wbit = bit % 26; this._expand(off + 1); if (val) { this.words[off] = this.words[off] | 1 << wbit; } else { this.words[off] = this.words[off] & ~(1 << wbit); } return this._strip(); }; BN3.prototype.iadd = function iadd(num) { var r4; if (this.negative !== 0 && num.negative === 0) { this.negative = 0; r4 = this.isub(num); this.negative ^= 1; return this._normSign(); } else if (this.negative === 0 && num.negative !== 0) { num.negative = 0; r4 = this.isub(num); num.negative = 1; return r4._normSign(); } var a4, b5; if (this.length > num.length) { a4 = this; b5 = num; } else { a4 = num; b5 = this; } var carry = 0; for (var i4 = 0; i4 < b5.length; i4++) { r4 = (a4.words[i4] | 0) + (b5.words[i4] | 0) + carry; this.words[i4] = r4 & 67108863; carry = r4 >>> 26; } for (; carry !== 0 && i4 < a4.length; i4++) { r4 = (a4.words[i4] | 0) + carry; this.words[i4] = r4 & 67108863; carry = r4 >>> 26; } this.length = a4.length; if (carry !== 0) { this.words[this.length] = carry; this.length++; } else if (a4 !== this) { for (; i4 < a4.length; i4++) { this.words[i4] = a4.words[i4]; } } return this; }; BN3.prototype.add = function add3(num) { var res; if (num.negative !== 0 && this.negative === 0) { num.negative = 0; res = this.sub(num); num.negative ^= 1; return res; } else if (num.negative === 0 && this.negative !== 0) { this.negative = 0; res = num.sub(this); this.negative = 1; return res; } if (this.length > num.length) return this.clone().iadd(num); return num.clone().iadd(this); }; BN3.prototype.isub = function isub(num) { if (num.negative !== 0) { num.negative = 0; var r4 = this.iadd(num); num.negative = 1; return r4._normSign(); } else if (this.negative !== 0) { this.negative = 0; this.iadd(num); this.negative = 1; return this._normSign(); } var cmp = this.cmp(num); if (cmp === 0) { this.negative = 0; this.length = 1; this.words[0] = 0; return this; } var a4, b5; if (cmp > 0) { a4 = this; b5 = num; } else { a4 = num; b5 = this; } var carry = 0; for (var i4 = 0; i4 < b5.length; i4++) { r4 = (a4.words[i4] | 0) - (b5.words[i4] | 0) + carry; carry = r4 >> 26; this.words[i4] = r4 & 67108863; } for (; carry !== 0 && i4 < a4.length; i4++) { r4 = (a4.words[i4] | 0) + carry; carry = r4 >> 26; this.words[i4] = r4 & 67108863; } if (carry === 0 && i4 < a4.length && a4 !== this) { for (; i4 < a4.length; i4++) { this.words[i4] = a4.words[i4]; } } this.length = Math.max(this.length, i4); if (a4 !== this) { this.negative = 1; } return this._strip(); }; BN3.prototype.sub = function sub(num) { return this.clone().isub(num); }; function smallMulTo(self2, num, out) { out.negative = num.negative ^ self2.negative; var len = self2.length + num.length | 0; out.length = len; len = len - 1 | 0; var a4 = self2.words[0] | 0; var b5 = num.words[0] | 0; var r4 = a4 * b5; var lo2 = r4 & 67108863; var carry = r4 / 67108864 | 0; out.words[0] = lo2; for (var k4 = 1; k4 < len; k4++) { var ncarry = carry >>> 26; var rword = carry & 67108863; var maxJ = Math.min(k4, num.length - 1); for (var j2 = Math.max(0, k4 - self2.length + 1); j2 <= maxJ; j2++) { var i4 = k4 - j2 | 0; a4 = self2.words[i4] | 0; b5 = num.words[j2] | 0; r4 = a4 * b5 + rword; ncarry += r4 / 67108864 | 0; rword = r4 & 67108863; } out.words[k4] = rword | 0; carry = ncarry | 0; } if (carry !== 0) { out.words[k4] = carry | 0; } else { out.length--; } return out._strip(); } var comb10MulTo = function comb10MulTo2(self2, num, out) { var a4 = self2.words; var b5 = num.words; var o4 = out.words; var c5 = 0; var lo2; var mid; var hi2; var a0 = a4[0] | 0; var al0 = a0 & 8191; var ah0 = a0 >>> 13; var a1 = a4[1] | 0; var al1 = a1 & 8191; var ah1 = a1 >>> 13; var a22 = a4[2] | 0; var al2 = a22 & 8191; var ah2 = a22 >>> 13; var a32 = a4[3] | 0; var al3 = a32 & 8191; var ah3 = a32 >>> 13; var a42 = a4[4] | 0; var al4 = a42 & 8191; var ah4 = a42 >>> 13; var a5 = a4[5] | 0; var al5 = a5 & 8191; var ah5 = a5 >>> 13; var a6 = a4[6] | 0; var al6 = a6 & 8191; var ah6 = a6 >>> 13; var a7 = a4[7] | 0; var al7 = a7 & 8191; var ah7 = a7 >>> 13; var a8 = a4[8] | 0; var al8 = a8 & 8191; var ah8 = a8 >>> 13; var a9 = a4[9] | 0; var al9 = a9 & 8191; var ah9 = a9 >>> 13; var b0 = b5[0] | 0; var bl0 = b0 & 8191; var bh0 = b0 >>> 13; var b1 = b5[1] | 0; var bl1 = b1 & 8191; var bh1 = b1 >>> 13; var b22 = b5[2] | 0; var bl2 = b22 & 8191; var bh2 = b22 >>> 13; var b32 = b5[3] | 0; var bl3 = b32 & 8191; var bh3 = b32 >>> 13; var b42 = b5[4] | 0; var bl4 = b42 & 8191; var bh4 = b42 >>> 13; var b52 = b5[5] | 0; var bl5 = b52 & 8191; var bh5 = b52 >>> 13; var b6 = b5[6] | 0; var bl6 = b6 & 8191; var bh6 = b6 >>> 13; var b7 = b5[7] | 0; var bl7 = b7 & 8191; var bh7 = b7 >>> 13; var b8 = b5[8] | 0; var bl8 = b8 & 8191; var bh8 = b8 >>> 13; var b9 = b5[9] | 0; var bl9 = b9 & 8191; var bh9 = b9 >>> 13; out.negative = self2.negative ^ num.negative; out.length = 19; lo2 = Math.imul(al0, bl0); mid = Math.imul(al0, bh0); mid = mid + Math.imul(ah0, bl0) | 0; hi2 = Math.imul(ah0, bh0); var w0 = (c5 + lo2 | 0) + ((mid & 8191) << 13) | 0; c5 = (hi2 + (mid >>> 13) | 0) + (w0 >>> 26) | 0; w0 &= 67108863; lo2 = Math.imul(al1, bl0); mid = Math.imul(al1, bh0); mid = mid + Math.imul(ah1, bl0) | 0; hi2 = Math.imul(ah1, bh0); lo2 = lo2 + Math.imul(al0, bl1) | 0; mid = mid + Math.imul(al0, bh1) | 0; mid = mid + Math.imul(ah0, bl1) | 0; hi2 = hi2 + Math.imul(ah0, bh1) | 0; var w1 = (c5 + lo2 | 0) + ((mid & 8191) << 13) | 0; c5 = (hi2 + (mid >>> 13) | 0) + (w1 >>> 26) | 0; w1 &= 67108863; lo2 = Math.imul(al2, bl0); mid = Math.imul(al2, bh0); mid = mid + Math.imul(ah2, bl0) | 0; hi2 = Math.imul(ah2, bh0); lo2 = lo2 + Math.imul(al1, bl1) | 0; mid = mid + Math.imul(al1, bh1) | 0; mid = mid + Math.imul(ah1, bl1) | 0; hi2 = hi2 + Math.imul(ah1, bh1) | 0; lo2 = lo2 + Math.imul(al0, bl2) | 0; mid = mid + Math.imul(al0, bh2) | 0; mid = mid + Math.imul(ah0, bl2) | 0; hi2 = hi2 + Math.imul(ah0, bh2) | 0; var w22 = (c5 + lo2 | 0) + ((mid & 8191) << 13) | 0; c5 = (hi2 + (mid >>> 13) | 0) + (w22 >>> 26) | 0; w22 &= 67108863; lo2 = Math.imul(al3, bl0); mid = Math.imul(al3, bh0); mid = mid + Math.imul(ah3, bl0) | 0; hi2 = Math.imul(ah3, bh0); lo2 = lo2 + Math.imul(al2, bl1) | 0; mid = mid + Math.imul(al2, bh1) | 0; mid = mid + Math.imul(ah2, bl1) | 0; hi2 = hi2 + Math.imul(ah2, bh1) | 0; lo2 = lo2 + Math.imul(al1, bl2) | 0; mid = mid + Math.imul(al1, bh2) | 0; mid = mid + Math.imul(ah1, bl2) | 0; hi2 = hi2 + Math.imul(ah1, bh2) | 0; lo2 = lo2 + Math.imul(al0, bl3) | 0; mid = mid + Math.imul(al0, bh3) | 0; mid = mid + Math.imul(ah0, bl3) | 0; hi2 = hi2 + Math.imul(ah0, bh3) | 0; var w32 = (c5 + lo2 | 0) + ((mid & 8191) << 13) | 0; c5 = (hi2 + (mid >>> 13) | 0) + (w32 >>> 26) | 0; w32 &= 67108863; lo2 = Math.imul(al4, bl0); mid = Math.imul(al4, bh0); mid = mid + Math.imul(ah4, bl0) | 0; hi2 = Math.imul(ah4, bh0); lo2 = lo2 + Math.imul(al3, bl1) | 0; mid = mid + Math.imul(al3, bh1) | 0; mid = mid + Math.imul(ah3, bl1) | 0; hi2 = hi2 + Math.imul(ah3, bh1) | 0; lo2 = lo2 + Math.imul(al2, bl2) | 0; mid = mid + Math.imul(al2, bh2) | 0; mid = mid + Math.imul(ah2, bl2) | 0; hi2 = hi2 + Math.imul(ah2, bh2) | 0; lo2 = lo2 + Math.imul(al1, bl3) | 0; mid = mid + Math.imul(al1, bh3) | 0; mid = mid + Math.imul(ah1, bl3) | 0; hi2 = hi2 + Math.imul(ah1, bh3) | 0; lo2 = lo2 + Math.imul(al0, bl4) | 0; mid = mid + Math.imul(al0, bh4) | 0; mid = mid + Math.imul(ah0, bl4) | 0; hi2 = hi2 + Math.imul(ah0, bh4) | 0; var w4 = (c5 + lo2 | 0) + ((mid & 8191) << 13) | 0; c5 = (hi2 + (mid >>> 13) | 0) + (w4 >>> 26) | 0; w4 &= 67108863; lo2 = Math.imul(al5, bl0); mid = Math.imul(al5, bh0); mid = mid + Math.imul(ah5, bl0) | 0; hi2 = Math.imul(ah5, bh0); lo2 = lo2 + Math.imul(al4, bl1) | 0; mid = mid + Math.imul(al4, bh1) | 0; mid = mid + Math.imul(ah4, bl1) | 0; hi2 = hi2 + Math.imul(ah4, bh1) | 0; lo2 = lo2 + Math.imul(al3, bl2) | 0; mid = mid + Math.imul(al3, bh2) | 0; mid = mid + Math.imul(ah3, bl2) | 0; hi2 = hi2 + Math.imul(ah3, bh2) | 0; lo2 = lo2 + Math.imul(al2, bl3) | 0; mid = mid + Math.imul(al2, bh3) | 0; mid = mid + Math.imul(ah2, bl3) | 0; hi2 = hi2 + Math.imul(ah2, bh3) | 0; lo2 = lo2 + Math.imul(al1, bl4) | 0; mid = mid + Math.imul(al1, bh4) | 0; mid = mid + Math.imul(ah1, bl4) | 0; hi2 = hi2 + Math.imul(ah1, bh4) | 0; lo2 = lo2 + Math.imul(al0, bl5) | 0; mid = mid + Math.imul(al0, bh5) | 0; mid = mid + Math.imul(ah0, bl5) | 0; hi2 = hi2 + Math.imul(ah0, bh5) | 0; var w5 = (c5 + lo2 | 0) + ((mid & 8191) << 13) | 0; c5 = (hi2 + (mid >>> 13) | 0) + (w5 >>> 26) | 0; w5 &= 67108863; lo2 = Math.imul(al6, bl0); mid = Math.imul(al6, bh0); mid = mid + Math.imul(ah6, bl0) | 0; hi2 = Math.imul(ah6, bh0); lo2 = lo2 + Math.imul(al5, bl1) | 0; mid = mid + Math.imul(al5, bh1) | 0; mid = mid + Math.imul(ah5, bl1) | 0; hi2 = hi2 + Math.imul(ah5, bh1) | 0; lo2 = lo2 + Math.imul(al4, bl2) | 0; mid = mid + Math.imul(al4, bh2) | 0; mid = mid + Math.imul(ah4, bl2) | 0; hi2 = hi2 + Math.imul(ah4, bh2) | 0; lo2 = lo2 + Math.imul(al3, bl3) | 0; mid = mid + Math.imul(al3, bh3) | 0; mid = mid + Math.imul(ah3, bl3) | 0; hi2 = hi2 + Math.imul(ah3, bh3) | 0; lo2 = lo2 + Math.imul(al2, bl4) | 0; mid = mid + Math.imul(al2, bh4) | 0; mid = mid + Math.imul(ah2, bl4) | 0; hi2 = hi2 + Math.imul(ah2, bh4) | 0; lo2 = lo2 + Math.imul(al1, bl5) | 0; mid = mid + Math.imul(al1, bh5) | 0; mid = mid + Math.imul(ah1, bl5) | 0; hi2 = hi2 + Math.imul(ah1, bh5) | 0; lo2 = lo2 + Math.imul(al0, bl6) | 0; mid = mid + Math.imul(al0, bh6) | 0; mid = mid + Math.imul(ah0, bl6) | 0; hi2 = hi2 + Math.imul(ah0, bh6) | 0; var w6 = (c5 + lo2 | 0) + ((mid & 8191) << 13) | 0; c5 = (hi2 + (mid >>> 13) | 0) + (w6 >>> 26) | 0; w6 &= 67108863; lo2 = Math.imul(al7, bl0); mid = Math.imul(al7, bh0); mid = mid + Math.imul(ah7, bl0) | 0; hi2 = Math.imul(ah7, bh0); lo2 = lo2 + Math.imul(al6, bl1) | 0; mid = mid + Math.imul(al6, bh1) | 0; mid = mid + Math.imul(ah6, bl1) | 0; hi2 = hi2 + Math.imul(ah6, bh1) | 0; lo2 = lo2 + Math.imul(al5, bl2) | 0; mid = mid + Math.imul(al5, bh2) | 0; mid = mid + Math.imul(ah5, bl2) | 0; hi2 = hi2 + Math.imul(ah5, bh2) | 0; lo2 = lo2 + Math.imul(al4, bl3) | 0; mid = mid + Math.imul(al4, bh3) | 0; mid = mid + Math.imul(ah4, bl3) | 0; hi2 = hi2 + Math.imul(ah4, bh3) | 0; lo2 = lo2 + Math.imul(al3, bl4) | 0; mid = mid + Math.imul(al3, bh4) | 0; mid = mid + Math.imul(ah3, bl4) | 0; hi2 = hi2 + Math.imul(ah3, bh4) | 0; lo2 = lo2 + Math.imul(al2, bl5) | 0; mid = mid + Math.imul(al2, bh5) | 0; mid = mid + Math.imul(ah2, bl5) | 0; hi2 = hi2 + Math.imul(ah2, bh5) | 0; lo2 = lo2 + Math.imul(al1, bl6) | 0; mid = mid + Math.imul(al1, bh6) | 0; mid = mid + Math.imul(ah1, bl6) | 0; hi2 = hi2 + Math.imul(ah1, bh6) | 0; lo2 = lo2 + Math.imul(al0, bl7) | 0; mid = mid + Math.imul(al0, bh7) | 0; mid = mid + Math.imul(ah0, bl7) | 0; hi2 = hi2 + Math.imul(ah0, bh7) | 0; var w7 = (c5 + lo2 | 0) + ((mid & 8191) << 13) | 0; c5 = (hi2 + (mid >>> 13) | 0) + (w7 >>> 26) | 0; w7 &= 67108863; lo2 = Math.imul(al8, bl0); mid = Math.imul(al8, bh0); mid = mid + Math.imul(ah8, bl0) | 0; hi2 = Math.imul(ah8, bh0); lo2 = lo2 + Math.imul(al7, bl1) | 0; mid = mid + Math.imul(al7, bh1) | 0; mid = mid + Math.imul(ah7, bl1) | 0; hi2 = hi2 + Math.imul(ah7, bh1) | 0; lo2 = lo2 + Math.imul(al6, bl2) | 0; mid = mid + Math.imul(al6, bh2) | 0; mid = mid + Math.imul(ah6, bl2) | 0; hi2 = hi2 + Math.imul(ah6, bh2) | 0; lo2 = lo2 + Math.imul(al5, bl3) | 0; mid = mid + Math.imul(al5, bh3) | 0; mid = mid + Math.imul(ah5, bl3) | 0; hi2 = hi2 + Math.imul(ah5, bh3) | 0; lo2 = lo2 + Math.imul(al4, bl4) | 0; mid = mid + Math.imul(al4, bh4) | 0; mid = mid + Math.imul(ah4, bl4) | 0; hi2 = hi2 + Math.imul(ah4, bh4) | 0; lo2 = lo2 + Math.imul(al3, bl5) | 0; mid = mid + Math.imul(al3, bh5) | 0; mid = mid + Math.imul(ah3, bl5) | 0; hi2 = hi2 + Math.imul(ah3, bh5) | 0; lo2 = lo2 + Math.imul(al2, bl6) | 0; mid = mid + Math.imul(al2, bh6) | 0; mid = mid + Math.imul(ah2, bl6) | 0; hi2 = hi2 + Math.imul(ah2, bh6) | 0; lo2 = lo2 + Math.imul(al1, bl7) | 0; mid = mid + Math.imul(al1, bh7) | 0; mid = mid + Math.imul(ah1, bl7) | 0; hi2 = hi2 + Math.imul(ah1, bh7) | 0; lo2 = lo2 + Math.imul(al0, bl8) | 0; mid = mid + Math.imul(al0, bh8) | 0; mid = mid + Math.imul(ah0, bl8) | 0; hi2 = hi2 + Math.imul(ah0, bh8) | 0; var w8 = (c5 + lo2 | 0) + ((mid & 8191) << 13) | 0; c5 = (hi2 + (mid >>> 13) | 0) + (w8 >>> 26) | 0; w8 &= 67108863; lo2 = Math.imul(al9, bl0); mid = Math.imul(al9, bh0); mid = mid + Math.imul(ah9, bl0) | 0; hi2 = Math.imul(ah9, bh0); lo2 = lo2 + Math.imul(al8, bl1) | 0; mid = mid + Math.imul(al8, bh1) | 0; mid = mid + Math.imul(ah8, bl1) | 0; hi2 = hi2 + Math.imul(ah8, bh1) | 0; lo2 = lo2 + Math.imul(al7, bl2) | 0; mid = mid + Math.imul(al7, bh2) | 0; mid = mid + Math.imul(ah7, bl2) | 0; hi2 = hi2 + Math.imul(ah7, bh2) | 0; lo2 = lo2 + Math.imul(al6, bl3) | 0; mid = mid + Math.imul(al6, bh3) | 0; mid = mid + Math.imul(ah6, bl3) | 0; hi2 = hi2 + Math.imul(ah6, bh3) | 0; lo2 = lo2 + Math.imul(al5, bl4) | 0; mid = mid + Math.imul(al5, bh4) | 0; mid = mid + Math.imul(ah5, bl4) | 0; hi2 = hi2 + Math.imul(ah5, bh4) | 0; lo2 = lo2 + Math.imul(al4, bl5) | 0; mid = mid + Math.imul(al4, bh5) | 0; mid = mid + Math.imul(ah4, bl5) | 0; hi2 = hi2 + Math.imul(ah4, bh5) | 0; lo2 = lo2 + Math.imul(al3, bl6) | 0; mid = mid + Math.imul(al3, bh6) | 0; mid = mid + Math.imul(ah3, bl6) | 0; hi2 = hi2 + Math.imul(ah3, bh6) | 0; lo2 = lo2 + Math.imul(al2, bl7) | 0; mid = mid + Math.imul(al2, bh7) | 0; mid = mid + Math.imul(ah2, bl7) | 0; hi2 = hi2 + Math.imul(ah2, bh7) | 0; lo2 = lo2 + Math.imul(al1, bl8) | 0; mid = mid + Math.imul(al1, bh8) | 0; mid = mid + Math.imul(ah1, bl8) | 0; hi2 = hi2 + Math.imul(ah1, bh8) | 0; lo2 = lo2 + Math.imul(al0, bl9) | 0; mid = mid + Math.imul(al0, bh9) | 0; mid = mid + Math.imul(ah0, bl9) | 0; hi2 = hi2 + Math.imul(ah0, bh9) | 0; var w9 = (c5 + lo2 | 0) + ((mid & 8191) << 13) | 0; c5 = (hi2 + (mid >>> 13) | 0) + (w9 >>> 26) | 0; w9 &= 67108863; lo2 = Math.imul(al9, bl1); mid = Math.imul(al9, bh1); mid = mid + Math.imul(ah9, bl1) | 0; hi2 = Math.imul(ah9, bh1); lo2 = lo2 + Math.imul(al8, bl2) | 0; mid = mid + Math.imul(al8, bh2) | 0; mid = mid + Math.imul(ah8, bl2) | 0; hi2 = hi2 + Math.imul(ah8, bh2) | 0; lo2 = lo2 + Math.imul(al7, bl3) | 0; mid = mid + Math.imul(al7, bh3) | 0; mid = mid + Math.imul(ah7, bl3) | 0; hi2 = hi2 + Math.imul(ah7, bh3) | 0; lo2 = lo2 + Math.imul(al6, bl4) | 0; mid = mid + Math.imul(al6, bh4) | 0; mid = mid + Math.imul(ah6, bl4) | 0; hi2 = hi2 + Math.imul(ah6, bh4) | 0; lo2 = lo2 + Math.imul(al5, bl5) | 0; mid = mid + Math.imul(al5, bh5) | 0; mid = mid + Math.imul(ah5, bl5) | 0; hi2 = hi2 + Math.imul(ah5, bh5) | 0; lo2 = lo2 + Math.imul(al4, bl6) | 0; mid = mid + Math.imul(al4, bh6) | 0; mid = mid + Math.imul(ah4, bl6) | 0; hi2 = hi2 + Math.imul(ah4, bh6) | 0; lo2 = lo2 + Math.imul(al3, bl7) | 0; mid = mid + Math.imul(al3, bh7) | 0; mid = mid + Math.imul(ah3, bl7) | 0; hi2 = hi2 + Math.imul(ah3, bh7) | 0; lo2 = lo2 + Math.imul(al2, bl8) | 0; mid = mid + Math.imul(al2, bh8) | 0; mid = mid + Math.imul(ah2, bl8) | 0; hi2 = hi2 + Math.imul(ah2, bh8) | 0; lo2 = lo2 + Math.imul(al1, bl9) | 0; mid = mid + Math.imul(al1, bh9) | 0; mid = mid + Math.imul(ah1, bl9) | 0; hi2 = hi2 + Math.imul(ah1, bh9) | 0; var w10 = (c5 + lo2 | 0) + ((mid & 8191) << 13) | 0; c5 = (hi2 + (mid >>> 13) | 0) + (w10 >>> 26) | 0; w10 &= 67108863; lo2 = Math.imul(al9, bl2); mid = Math.imul(al9, bh2); mid = mid + Math.imul(ah9, bl2) | 0; hi2 = Math.imul(ah9, bh2); lo2 = lo2 + Math.imul(al8, bl3) | 0; mid = mid + Math.imul(al8, bh3) | 0; mid = mid + Math.imul(ah8, bl3) | 0; hi2 = hi2 + Math.imul(ah8, bh3) | 0; lo2 = lo2 + Math.imul(al7, bl4) | 0; mid = mid + Math.imul(al7, bh4) | 0; mid = mid + Math.imul(ah7, bl4) | 0; hi2 = hi2 + Math.imul(ah7, bh4) | 0; lo2 = lo2 + Math.imul(al6, bl5) | 0; mid = mid + Math.imul(al6, bh5) | 0; mid = mid + Math.imul(ah6, bl5) | 0; hi2 = hi2 + Math.imul(ah6, bh5) | 0; lo2 = lo2 + Math.imul(al5, bl6) | 0; mid = mid + Math.imul(al5, bh6) | 0; mid = mid + Math.imul(ah5, bl6) | 0; hi2 = hi2 + Math.imul(ah5, bh6) | 0; lo2 = lo2 + Math.imul(al4, bl7) | 0; mid = mid + Math.imul(al4, bh7) | 0; mid = mid + Math.imul(ah4, bl7) | 0; hi2 = hi2 + Math.imul(ah4, bh7) | 0; lo2 = lo2 + Math.imul(al3, bl8) | 0; mid = mid + Math.imul(al3, bh8) | 0; mid = mid + Math.imul(ah3, bl8) | 0; hi2 = hi2 + Math.imul(ah3, bh8) | 0; lo2 = lo2 + Math.imul(al2, bl9) | 0; mid = mid + Math.imul(al2, bh9) | 0; mid = mid + Math.imul(ah2, bl9) | 0; hi2 = hi2 + Math.imul(ah2, bh9) | 0; var w11 = (c5 + lo2 | 0) + ((mid & 8191) << 13) | 0; c5 = (hi2 + (mid >>> 13) | 0) + (w11 >>> 26) | 0; w11 &= 67108863; lo2 = Math.imul(al9, bl3); mid = Math.imul(al9, bh3); mid = mid + Math.imul(ah9, bl3) | 0; hi2 = Math.imul(ah9, bh3); lo2 = lo2 + Math.imul(al8, bl4) | 0; mid = mid + Math.imul(al8, bh4) | 0; mid = mid + Math.imul(ah8, bl4) | 0; hi2 = hi2 + Math.imul(ah8, bh4) | 0; lo2 = lo2 + Math.imul(al7, bl5) | 0; mid = mid + Math.imul(al7, bh5) | 0; mid = mid + Math.imul(ah7, bl5) | 0; hi2 = hi2 + Math.imul(ah7, bh5) | 0; lo2 = lo2 + Math.imul(al6, bl6) | 0; mid = mid + Math.imul(al6, bh6) | 0; mid = mid + Math.imul(ah6, bl6) | 0; hi2 = hi2 + Math.imul(ah6, bh6) | 0; lo2 = lo2 + Math.imul(al5, bl7) | 0; mid = mid + Math.imul(al5, bh7) | 0; mid = mid + Math.imul(ah5, bl7) | 0; hi2 = hi2 + Math.imul(ah5, bh7) | 0; lo2 = lo2 + Math.imul(al4, bl8) | 0; mid = mid + Math.imul(al4, bh8) | 0; mid = mid + Math.imul(ah4, bl8) | 0; hi2 = hi2 + Math.imul(ah4, bh8) | 0; lo2 = lo2 + Math.imul(al3, bl9) | 0; mid = mid + Math.imul(al3, bh9) | 0; mid = mid + Math.imul(ah3, bl9) | 0; hi2 = hi2 + Math.imul(ah3, bh9) | 0; var w12 = (c5 + lo2 | 0) + ((mid & 8191) << 13) | 0; c5 = (hi2 + (mid >>> 13) | 0) + (w12 >>> 26) | 0; w12 &= 67108863; lo2 = Math.imul(al9, bl4); mid = Math.imul(al9, bh4); mid = mid + Math.imul(ah9, bl4) | 0; hi2 = Math.imul(ah9, bh4); lo2 = lo2 + Math.imul(al8, bl5) | 0; mid = mid + Math.imul(al8, bh5) | 0; mid = mid + Math.imul(ah8, bl5) | 0; hi2 = hi2 + Math.imul(ah8, bh5) | 0; lo2 = lo2 + Math.imul(al7, bl6) | 0; mid = mid + Math.imul(al7, bh6) | 0; mid = mid + Math.imul(ah7, bl6) | 0; hi2 = hi2 + Math.imul(ah7, bh6) | 0; lo2 = lo2 + Math.imul(al6, bl7) | 0; mid = mid + Math.imul(al6, bh7) | 0; mid = mid + Math.imul(ah6, bl7) | 0; hi2 = hi2 + Math.imul(ah6, bh7) | 0; lo2 = lo2 + Math.imul(al5, bl8) | 0; mid = mid + Math.imul(al5, bh8) | 0; mid = mid + Math.imul(ah5, bl8) | 0; hi2 = hi2 + Math.imul(ah5, bh8) | 0; lo2 = lo2 + Math.imul(al4, bl9) | 0; mid = mid + Math.imul(al4, bh9) | 0; mid = mid + Math.imul(ah4, bl9) | 0; hi2 = hi2 + Math.imul(ah4, bh9) | 0; var w13 = (c5 + lo2 | 0) + ((mid & 8191) << 13) | 0; c5 = (hi2 + (mid >>> 13) | 0) + (w13 >>> 26) | 0; w13 &= 67108863; lo2 = Math.imul(al9, bl5); mid = Math.imul(al9, bh5); mid = mid + Math.imul(ah9, bl5) | 0; hi2 = Math.imul(ah9, bh5); lo2 = lo2 + Math.imul(al8, bl6) | 0; mid = mid + Math.imul(al8, bh6) | 0; mid = mid + Math.imul(ah8, bl6) | 0; hi2 = hi2 + Math.imul(ah8, bh6) | 0; lo2 = lo2 + Math.imul(al7, bl7) | 0; mid = mid + Math.imul(al7, bh7) | 0; mid = mid + Math.imul(ah7, bl7) | 0; hi2 = hi2 + Math.imul(ah7, bh7) | 0; lo2 = lo2 + Math.imul(al6, bl8) | 0; mid = mid + Math.imul(al6, bh8) | 0; mid = mid + Math.imul(ah6, bl8) | 0; hi2 = hi2 + Math.imul(ah6, bh8) | 0; lo2 = lo2 + Math.imul(al5, bl9) | 0; mid = mid + Math.imul(al5, bh9) | 0; mid = mid + Math.imul(ah5, bl9) | 0; hi2 = hi2 + Math.imul(ah5, bh9) | 0; var w14 = (c5 + lo2 | 0) + ((mid & 8191) << 13) | 0; c5 = (hi2 + (mid >>> 13) | 0) + (w14 >>> 26) | 0; w14 &= 67108863; lo2 = Math.imul(al9, bl6); mid = Math.imul(al9, bh6); mid = mid + Math.imul(ah9, bl6) | 0; hi2 = Math.imul(ah9, bh6); lo2 = lo2 + Math.imul(al8, bl7) | 0; mid = mid + Math.imul(al8, bh7) | 0; mid = mid + Math.imul(ah8, bl7) | 0; hi2 = hi2 + Math.imul(ah8, bh7) | 0; lo2 = lo2 + Math.imul(al7, bl8) | 0; mid = mid + Math.imul(al7, bh8) | 0; mid = mid + Math.imul(ah7, bl8) | 0; hi2 = hi2 + Math.imul(ah7, bh8) | 0; lo2 = lo2 + Math.imul(al6, bl9) | 0; mid = mid + Math.imul(al6, bh9) | 0; mid = mid + Math.imul(ah6, bl9) | 0; hi2 = hi2 + Math.imul(ah6, bh9) | 0; var w15 = (c5 + lo2 | 0) + ((mid & 8191) << 13) | 0; c5 = (hi2 + (mid >>> 13) | 0) + (w15 >>> 26) | 0; w15 &= 67108863; lo2 = Math.imul(al9, bl7); mid = Math.imul(al9, bh7); mid = mid + Math.imul(ah9, bl7) | 0; hi2 = Math.imul(ah9, bh7); lo2 = lo2 + Math.imul(al8, bl8) | 0; mid = mid + Math.imul(al8, bh8) | 0; mid = mid + Math.imul(ah8, bl8) | 0; hi2 = hi2 + Math.imul(ah8, bh8) | 0; lo2 = lo2 + Math.imul(al7, bl9) | 0; mid = mid + Math.imul(al7, bh9) | 0; mid = mid + Math.imul(ah7, bl9) | 0; hi2 = hi2 + Math.imul(ah7, bh9) | 0; var w16 = (c5 + lo2 | 0) + ((mid & 8191) << 13) | 0; c5 = (hi2 + (mid >>> 13) | 0) + (w16 >>> 26) | 0; w16 &= 67108863; lo2 = Math.imul(al9, bl8); mid = Math.imul(al9, bh8); mid = mid + Math.imul(ah9, bl8) | 0; hi2 = Math.imul(ah9, bh8); lo2 = lo2 + Math.imul(al8, bl9) | 0; mid = mid + Math.imul(al8, bh9) | 0; mid = mid + Math.imul(ah8, bl9) | 0; hi2 = hi2 + Math.imul(ah8, bh9) | 0; var w17 = (c5 + lo2 | 0) + ((mid & 8191) << 13) | 0; c5 = (hi2 + (mid >>> 13) | 0) + (w17 >>> 26) | 0; w17 &= 67108863; lo2 = Math.imul(al9, bl9); mid = Math.imul(al9, bh9); mid = mid + Math.imul(ah9, bl9) | 0; hi2 = Math.imul(ah9, bh9); var w18 = (c5 + lo2 | 0) + ((mid & 8191) << 13) | 0; c5 = (hi2 + (mid >>> 13) | 0) + (w18 >>> 26) | 0; w18 &= 67108863; o4[0] = w0; o4[1] = w1; o4[2] = w22; o4[3] = w32; o4[4] = w4; o4[5] = w5; o4[6] = w6; o4[7] = w7; o4[8] = w8; o4[9] = w9; o4[10] = w10; o4[11] = w11; o4[12] = w12; o4[13] = w13; o4[14] = w14; o4[15] = w15; o4[16] = w16; o4[17] = w17; o4[18] = w18; if (c5 !== 0) { o4[19] = c5; out.length++; } return out; }; if (!Math.imul) { comb10MulTo = smallMulTo; } function bigMulTo(self2, num, out) { out.negative = num.negative ^ self2.negative; out.length = self2.length + num.length; var carry = 0; var hncarry = 0; for (var k4 = 0; k4 < out.length - 1; k4++) { var ncarry = hncarry; hncarry = 0; var rword = carry & 67108863; var maxJ = Math.min(k4, num.length - 1); for (var j2 = Math.max(0, k4 - self2.length + 1); j2 <= maxJ; j2++) { var i4 = k4 - j2; var a4 = self2.words[i4] | 0; var b5 = num.words[j2] | 0; var r4 = a4 * b5; var lo2 = r4 & 67108863; ncarry = ncarry + (r4 / 67108864 | 0) | 0; lo2 = lo2 + rword | 0; rword = lo2 & 67108863; ncarry = ncarry + (lo2 >>> 26) | 0; hncarry += ncarry >>> 26; ncarry &= 67108863; } out.words[k4] = rword; carry = ncarry; ncarry = hncarry; } if (carry !== 0) { out.words[k4] = carry; } else { out.length--; } return out._strip(); } function jumboMulTo(self2, num, out) { return bigMulTo(self2, num, out); } BN3.prototype.mulTo = function mulTo(num, out) { var res; var len = this.length + num.length; if (this.length === 10 && num.length === 10) { res = comb10MulTo(this, num, out); } else if (len < 63) { res = smallMulTo(this, num, out); } else if (len < 1024) { res = bigMulTo(this, num, out); } else { res = jumboMulTo(this, num, out); } return res; }; function FFTM(x6, y6) { this.x = x6; this.y = y6; } FFTM.prototype.makeRBT = function makeRBT(N11) { var t = new Array(N11); var l4 = BN3.prototype._countBits(N11) - 1; for (var i4 = 0; i4 < N11; i4++) { t[i4] = this.revBin(i4, l4, N11); } return t; }; FFTM.prototype.revBin = function revBin(x6, l4, N11) { if (x6 === 0 || x6 === N11 - 1) return x6; var rb = 0; for (var i4 = 0; i4 < l4; i4++) { rb |= (x6 & 1) << l4 - i4 - 1; x6 >>= 1; } return rb; }; FFTM.prototype.permute = function permute(rbt, rws, iws, rtws, itws, N11) { for (var i4 = 0; i4 < N11; i4++) { rtws[i4] = rws[rbt[i4]]; itws[i4] = iws[rbt[i4]]; } }; FFTM.prototype.transform = function transform(rws, iws, rtws, itws, N11, rbt) { this.permute(rbt, rws, iws, rtws, itws, N11); for (var s3 = 1; s3 < N11; s3 <<= 1) { var l4 = s3 << 1; var rtwdf = Math.cos(2 * Math.PI / l4); var itwdf = Math.sin(2 * Math.PI / l4); for (var p3 = 0; p3 < N11; p3 += l4) { var rtwdf_ = rtwdf; var itwdf_ = itwdf; for (var j2 = 0; j2 < s3; j2++) { var re3 = rtws[p3 + j2]; var ie2 = itws[p3 + j2]; var ro2 = rtws[p3 + j2 + s3]; var io2 = itws[p3 + j2 + s3]; var rx = rtwdf_ * ro2 - itwdf_ * io2; io2 = rtwdf_ * io2 + itwdf_ * ro2; ro2 = rx; rtws[p3 + j2] = re3 + ro2; itws[p3 + j2] = ie2 + io2; rtws[p3 + j2 + s3] = re3 - ro2; itws[p3 + j2 + s3] = ie2 - io2; if (j2 !== l4) { rx = rtwdf * rtwdf_ - itwdf * itwdf_; itwdf_ = rtwdf * itwdf_ + itwdf * rtwdf_; rtwdf_ = rx; } } } } }; FFTM.prototype.guessLen13b = function guessLen13b(n5, m2) { var N11 = Math.max(m2, n5) | 1; var odd = N11 & 1; var i4 = 0; for (N11 = N11 / 2 | 0; N11; N11 = N11 >>> 1) { i4++; } return 1 << i4 + 1 + odd; }; FFTM.prototype.conjugate = function conjugate(rws, iws, N11) { if (N11 <= 1) return; for (var i4 = 0; i4 < N11 / 2; i4++) { var t = rws[i4]; rws[i4] = rws[N11 - i4 - 1]; rws[N11 - i4 - 1] = t; t = iws[i4]; iws[i4] = -iws[N11 - i4 - 1]; iws[N11 - i4 - 1] = -t; } }; FFTM.prototype.normalize13b = function normalize13b(ws2, N11) { var carry = 0; for (var i4 = 0; i4 < N11 / 2; i4++) { var w4 = Math.round(ws2[2 * i4 + 1] / N11) * 8192 + Math.round(ws2[2 * i4] / N11) + carry; ws2[i4] = w4 & 67108863; if (w4 < 67108864) { carry = 0; } else { carry = w4 / 67108864 | 0; } } return ws2; }; FFTM.prototype.convert13b = function convert13b(ws2, len, rws, N11) { var carry = 0; for (var i4 = 0; i4 < len; i4++) { carry = carry + (ws2[i4] | 0); rws[2 * i4] = carry & 8191; carry = carry >>> 13; rws[2 * i4 + 1] = carry & 8191; carry = carry >>> 13; } for (i4 = 2 * len; i4 < N11; ++i4) { rws[i4] = 0; } assert2(carry === 0); assert2((carry & ~8191) === 0); }; FFTM.prototype.stub = function stub(N11) { var ph = new Array(N11); for (var i4 = 0; i4 < N11; i4++) { ph[i4] = 0; } return ph; }; FFTM.prototype.mulp = function mulp(x6, y6, out) { var N11 = 2 * this.guessLen13b(x6.length, y6.length); var rbt = this.makeRBT(N11); var _4 = this.stub(N11); var rws = new Array(N11); var rwst = new Array(N11); var iwst = new Array(N11); var nrws = new Array(N11); var nrwst = new Array(N11); var niwst = new Array(N11); var rmws = out.words; rmws.length = N11; this.convert13b(x6.words, x6.length, rws, N11); this.convert13b(y6.words, y6.length, nrws, N11); this.transform(rws, _4, rwst, iwst, N11, rbt); this.transform(nrws, _4, nrwst, niwst, N11, rbt); for (var i4 = 0; i4 < N11; i4++) { var rx = rwst[i4] * nrwst[i4] - iwst[i4] * niwst[i4]; iwst[i4] = rwst[i4] * niwst[i4] + iwst[i4] * nrwst[i4]; rwst[i4] = rx; } this.conjugate(rwst, iwst, N11); this.transform(rwst, iwst, rmws, _4, N11, rbt); this.conjugate(rmws, _4, N11); this.normalize13b(rmws, N11); out.negative = x6.negative ^ y6.negative; out.length = x6.length + y6.length; return out._strip(); }; BN3.prototype.mul = function mul3(num) { var out = new BN3(null); out.words = new Array(this.length + num.length); return this.mulTo(num, out); }; BN3.prototype.mulf = function mulf(num) { var out = new BN3(null); out.words = new Array(this.length + num.length); return jumboMulTo(this, num, out); }; BN3.prototype.imul = function imul(num) { return this.clone().mulTo(num, this); }; BN3.prototype.imuln = function imuln(num) { var isNegNum = num < 0; if (isNegNum) num = -num; assert2(typeof num === "number"); assert2(num < 67108864); var carry = 0; for (var i4 = 0; i4 < this.length; i4++) { var w4 = (this.words[i4] | 0) * num; var lo2 = (w4 & 67108863) + (carry & 67108863); carry >>= 26; carry += w4 / 67108864 | 0; carry += lo2 >>> 26; this.words[i4] = lo2 & 67108863; } if (carry !== 0) { this.words[i4] = carry; this.length++; } return isNegNum ? this.ineg() : this; }; BN3.prototype.muln = function muln(num) { return this.clone().imuln(num); }; BN3.prototype.sqr = function sqr() { return this.mul(this); }; BN3.prototype.isqr = function isqr() { return this.imul(this.clone()); }; BN3.prototype.pow = function pow(num) { var w4 = toBitArray(num); if (w4.length === 0) return new BN3(1); var res = this; for (var i4 = 0; i4 < w4.length; i4++, res = res.sqr()) { if (w4[i4] !== 0) break; } if (++i4 < w4.length) { for (var q3 = res.sqr(); i4 < w4.length; i4++, q3 = q3.sqr()) { if (w4[i4] === 0) continue; res = res.mul(q3); } } return res; }; BN3.prototype.iushln = function iushln(bits) { assert2(typeof bits === "number" && bits >= 0); var r4 = bits % 26; var s3 = (bits - r4) / 26; var carryMask = 67108863 >>> 26 - r4 << 26 - r4; var i4; if (r4 !== 0) { var carry = 0; for (i4 = 0; i4 < this.length; i4++) { var newCarry = this.words[i4] & carryMask; var c5 = (this.words[i4] | 0) - newCarry << r4; this.words[i4] = c5 | carry; carry = newCarry >>> 26 - r4; } if (carry) { this.words[i4] = carry; this.length++; } } if (s3 !== 0) { for (i4 = this.length - 1; i4 >= 0; i4--) { this.words[i4 + s3] = this.words[i4]; } for (i4 = 0; i4 < s3; i4++) { this.words[i4] = 0; } this.length += s3; } return this._strip(); }; BN3.prototype.ishln = function ishln(bits) { assert2(this.negative === 0); return this.iushln(bits); }; BN3.prototype.iushrn = function iushrn(bits, hint, extended) { assert2(typeof bits === "number" && bits >= 0); var h5; if (hint) { h5 = (hint - hint % 26) / 26; } else { h5 = 0; } var r4 = bits % 26; var s3 = Math.min((bits - r4) / 26, this.length); var mask = 67108863 ^ 67108863 >>> r4 << r4; var maskedWords = extended; h5 -= s3; h5 = Math.max(0, h5); if (maskedWords) { for (var i4 = 0; i4 < s3; i4++) { maskedWords.words[i4] = this.words[i4]; } maskedWords.length = s3; } if (s3 === 0) { } else if (this.length > s3) { this.length -= s3; for (i4 = 0; i4 < this.length; i4++) { this.words[i4] = this.words[i4 + s3]; } } else { this.words[0] = 0; this.length = 1; } var carry = 0; for (i4 = this.length - 1; i4 >= 0 && (carry !== 0 || i4 >= h5); i4--) { var word = this.words[i4] | 0; this.words[i4] = carry << 26 - r4 | word >>> r4; carry = word & mask; } if (maskedWords && carry !== 0) { maskedWords.words[maskedWords.length++] = carry; } if (this.length === 0) { this.words[0] = 0; this.length = 1; } return this._strip(); }; BN3.prototype.ishrn = function ishrn(bits, hint, extended) { assert2(this.negative === 0); return this.iushrn(bits, hint, extended); }; BN3.prototype.shln = function shln(bits) { return this.clone().ishln(bits); }; BN3.prototype.ushln = function ushln(bits) { return this.clone().iushln(bits); }; BN3.prototype.shrn = function shrn(bits) { return this.clone().ishrn(bits); }; BN3.prototype.ushrn = function ushrn(bits) { return this.clone().iushrn(bits); }; BN3.prototype.testn = function testn(bit) { assert2(typeof bit === "number" && bit >= 0); var r4 = bit % 26; var s3 = (bit - r4) / 26; var q3 = 1 << r4; if (this.length <= s3) return false; var w4 = this.words[s3]; return !!(w4 & q3); }; BN3.prototype.imaskn = function imaskn(bits) { assert2(typeof bits === "number" && bits >= 0); var r4 = bits % 26; var s3 = (bits - r4) / 26; assert2(this.negative === 0, "imaskn works only with positive numbers"); if (this.length <= s3) { return this; } if (r4 !== 0) { s3++; } this.length = Math.min(s3, this.length); if (r4 !== 0) { var mask = 67108863 ^ 67108863 >>> r4 << r4; this.words[this.length - 1] &= mask; } return this._strip(); }; BN3.prototype.maskn = function maskn(bits) { return this.clone().imaskn(bits); }; BN3.prototype.iaddn = function iaddn(num) { assert2(typeof num === "number"); assert2(num < 67108864); if (num < 0) return this.isubn(-num); if (this.negative !== 0) { if (this.length === 1 && (this.words[0] | 0) <= num) { this.words[0] = num - (this.words[0] | 0); this.negative = 0; return this; } this.negative = 0; this.isubn(num); this.negative = 1; return this; } return this._iaddn(num); }; BN3.prototype._iaddn = function _iaddn(num) { this.words[0] += num; for (var i4 = 0; i4 < this.length && this.words[i4] >= 67108864; i4++) { this.words[i4] -= 67108864; if (i4 === this.length - 1) { this.words[i4 + 1] = 1; } else { this.words[i4 + 1]++; } } this.length = Math.max(this.length, i4 + 1); return this; }; BN3.prototype.isubn = function isubn(num) { assert2(typeof num === "number"); assert2(num < 67108864); if (num < 0) return this.iaddn(-num); if (this.negative !== 0) { this.negative = 0; this.iaddn(num); this.negative = 1; return this; } this.words[0] -= num; if (this.length === 1 && this.words[0] < 0) { this.words[0] = -this.words[0]; this.negative = 1; } else { for (var i4 = 0; i4 < this.length && this.words[i4] < 0; i4++) { this.words[i4] += 67108864; this.words[i4 + 1] -= 1; } } return this._strip(); }; BN3.prototype.addn = function addn(num) { return this.clone().iaddn(num); }; BN3.prototype.subn = function subn(num) { return this.clone().isubn(num); }; BN3.prototype.iabs = function iabs() { this.negative = 0; return this; }; BN3.prototype.abs = function abs() { return this.clone().iabs(); }; BN3.prototype._ishlnsubmul = function _ishlnsubmul(num, mul3, shift) { var len = num.length + shift; var i4; this._expand(len); var w4; var carry = 0; for (i4 = 0; i4 < num.length; i4++) { w4 = (this.words[i4 + shift] | 0) + carry; var right = (num.words[i4] | 0) * mul3; w4 -= right & 67108863; carry = (w4 >> 26) - (right / 67108864 | 0); this.words[i4 + shift] = w4 & 67108863; } for (; i4 < this.length - shift; i4++) { w4 = (this.words[i4 + shift] | 0) + carry; carry = w4 >> 26; this.words[i4 + shift] = w4 & 67108863; } if (carry === 0) return this._strip(); assert2(carry === -1); carry = 0; for (i4 = 0; i4 < this.length; i4++) { w4 = -(this.words[i4] | 0) + carry; carry = w4 >> 26; this.words[i4] = w4 & 67108863; } this.negative = 1; return this._strip(); }; BN3.prototype._wordDiv = function _wordDiv(num, mode) { var shift = this.length - num.length; var a4 = this.clone(); var b5 = num; var bhi = b5.words[b5.length - 1] | 0; var bhiBits = this._countBits(bhi); shift = 26 - bhiBits; if (shift !== 0) { b5 = b5.ushln(shift); a4.iushln(shift); bhi = b5.words[b5.length - 1] | 0; } var m2 = a4.length - b5.length; var q3; if (mode !== "mod") { q3 = new BN3(null); q3.length = m2 + 1; q3.words = new Array(q3.length); for (var i4 = 0; i4 < q3.length; i4++) { q3.words[i4] = 0; } } var diff = a4.clone()._ishlnsubmul(b5, 1, m2); if (diff.negative === 0) { a4 = diff; if (q3) { q3.words[m2] = 1; } } for (var j2 = m2 - 1; j2 >= 0; j2--) { var qj = (a4.words[b5.length + j2] | 0) * 67108864 + (a4.words[b5.length + j2 - 1] | 0); qj = Math.min(qj / bhi | 0, 67108863); a4._ishlnsubmul(b5, qj, j2); while (a4.negative !== 0) { qj--; a4.negative = 0; a4._ishlnsubmul(b5, 1, j2); if (!a4.isZero()) { a4.negative ^= 1; } } if (q3) { q3.words[j2] = qj; } } if (q3) { q3._strip(); } a4._strip(); if (mode !== "div" && shift !== 0) { a4.iushrn(shift); } return { div: q3 || null, mod: a4 }; }; BN3.prototype.divmod = function divmod(num, mode, positive) { assert2(!num.isZero()); if (this.isZero()) { return { div: new BN3(0), mod: new BN3(0) }; } var div, mod, res; if (this.negative !== 0 && num.negative === 0) { res = this.neg().divmod(num, mode); if (mode !== "mod") { div = res.div.neg(); } if (mode !== "div") { mod = res.mod.neg(); if (positive && mod.negative !== 0) { mod.iadd(num); } } return { div, mod }; } if (this.negative === 0 && num.negative !== 0) { res = this.divmod(num.neg(), mode); if (mode !== "mod") { div = res.div.neg(); } return { div, mod: res.mod }; } if ((this.negative & num.negative) !== 0) { res = this.neg().divmod(num.neg(), mode); if (mode !== "div") { mod = res.mod.neg(); if (positive && mod.negative !== 0) { mod.isub(num); } } return { div: res.div, mod }; } if (num.length > this.length || this.cmp(num) < 0) { return { div: new BN3(0), mod: this }; } if (num.length === 1) { if (mode === "div") { return { div: this.divn(num.words[0]), mod: null }; } if (mode === "mod") { return { div: null, mod: new BN3(this.modrn(num.words[0])) }; } return { div: this.divn(num.words[0]), mod: new BN3(this.modrn(num.words[0])) }; } return this._wordDiv(num, mode); }; BN3.prototype.div = function div(num) { return this.divmod(num, "div", false).div; }; BN3.prototype.mod = function mod(num) { return this.divmod(num, "mod", false).mod; }; BN3.prototype.umod = function umod(num) { return this.divmod(num, "mod", true).mod; }; BN3.prototype.divRound = function divRound(num) { var dm = this.divmod(num); if (dm.mod.isZero()) return dm.div; var mod = dm.div.negative !== 0 ? dm.mod.isub(num) : dm.mod; var half = num.ushrn(1); var r22 = num.andln(1); var cmp = mod.cmp(half); if (cmp < 0 || r22 === 1 && cmp === 0) return dm.div; return dm.div.negative !== 0 ? dm.div.isubn(1) : dm.div.iaddn(1); }; BN3.prototype.modrn = function modrn(num) { var isNegNum = num < 0; if (isNegNum) num = -num; assert2(num <= 67108863); var p3 = (1 << 26) % num; var acc = 0; for (var i4 = this.length - 1; i4 >= 0; i4--) { acc = (p3 * acc + (this.words[i4] | 0)) % num; } return isNegNum ? -acc : acc; }; BN3.prototype.modn = function modn(num) { return this.modrn(num); }; BN3.prototype.idivn = function idivn(num) { var isNegNum = num < 0; if (isNegNum) num = -num; assert2(num <= 67108863); var carry = 0; for (var i4 = this.length - 1; i4 >= 0; i4--) { var w4 = (this.words[i4] | 0) + carry * 67108864; this.words[i4] = w4 / num | 0; carry = w4 % num; } this._strip(); return isNegNum ? this.ineg() : this; }; BN3.prototype.divn = function divn(num) { return this.clone().idivn(num); }; BN3.prototype.egcd = function egcd(p3) { assert2(p3.negative === 0); assert2(!p3.isZero()); var x6 = this; var y6 = p3.clone(); if (x6.negative !== 0) { x6 = x6.umod(p3); } else { x6 = x6.clone(); } var A3 = new BN3(1); var B4 = new BN3(0); var C5 = new BN3(0); var D4 = new BN3(1); var g4 = 0; while (x6.isEven() && y6.isEven()) { x6.iushrn(1); y6.iushrn(1); ++g4; } var yp = y6.clone(); var xp = x6.clone(); while (!x6.isZero()) { for (var i4 = 0, im = 1; (x6.words[0] & im) === 0 && i4 < 26; ++i4, im <<= 1) ; if (i4 > 0) { x6.iushrn(i4); while (i4-- > 0) { if (A3.isOdd() || B4.isOdd()) { A3.iadd(yp); B4.isub(xp); } A3.iushrn(1); B4.iushrn(1); } } for (var j2 = 0, jm = 1; (y6.words[0] & jm) === 0 && j2 < 26; ++j2, jm <<= 1) ; if (j2 > 0) { y6.iushrn(j2); while (j2-- > 0) { if (C5.isOdd() || D4.isOdd()) { C5.iadd(yp); D4.isub(xp); } C5.iushrn(1); D4.iushrn(1); } } if (x6.cmp(y6) >= 0) { x6.isub(y6); A3.isub(C5); B4.isub(D4); } else { y6.isub(x6); C5.isub(A3); D4.isub(B4); } } return { a: C5, b: D4, gcd: y6.iushln(g4) }; }; BN3.prototype._invmp = function _invmp(p3) { assert2(p3.negative === 0); assert2(!p3.isZero()); var a4 = this; var b5 = p3.clone(); if (a4.negative !== 0) { a4 = a4.umod(p3); } else { a4 = a4.clone(); } var x1 = new BN3(1); var x22 = new BN3(0); var delta = b5.clone(); while (a4.cmpn(1) > 0 && b5.cmpn(1) > 0) { for (var i4 = 0, im = 1; (a4.words[0] & im) === 0 && i4 < 26; ++i4, im <<= 1) ; if (i4 > 0) { a4.iushrn(i4); while (i4-- > 0) { if (x1.isOdd()) { x1.iadd(delta); } x1.iushrn(1); } } for (var j2 = 0, jm = 1; (b5.words[0] & jm) === 0 && j2 < 26; ++j2, jm <<= 1) ; if (j2 > 0) { b5.iushrn(j2); while (j2-- > 0) { if (x22.isOdd()) { x22.iadd(delta); } x22.iushrn(1); } } if (a4.cmp(b5) >= 0) { a4.isub(b5); x1.isub(x22); } else { b5.isub(a4); x22.isub(x1); } } var res; if (a4.cmpn(1) === 0) { res = x1; } else { res = x22; } if (res.cmpn(0) < 0) { res.iadd(p3); } return res; }; BN3.prototype.gcd = function gcd(num) { if (this.isZero()) return num.abs(); if (num.isZero()) return this.abs(); var a4 = this.clone(); var b5 = num.clone(); a4.negative = 0; b5.negative = 0; for (var shift = 0; a4.isEven() && b5.isEven(); shift++) { a4.iushrn(1); b5.iushrn(1); } do { while (a4.isEven()) { a4.iushrn(1); } while (b5.isEven()) { b5.iushrn(1); } var r4 = a4.cmp(b5); if (r4 < 0) { var t = a4; a4 = b5; b5 = t; } else if (r4 === 0 || b5.cmpn(1) === 0) { break; } a4.isub(b5); } while (true); return b5.iushln(shift); }; BN3.prototype.invm = function invm(num) { return this.egcd(num).a.umod(num); }; BN3.prototype.isEven = function isEven() { return (this.words[0] & 1) === 0; }; BN3.prototype.isOdd = function isOdd() { return (this.words[0] & 1) === 1; }; BN3.prototype.andln = function andln(num) { return this.words[0] & num; }; BN3.prototype.bincn = function bincn(bit) { assert2(typeof bit === "number"); var r4 = bit % 26; var s3 = (bit - r4) / 26; var q3 = 1 << r4; if (this.length <= s3) { this._expand(s3 + 1); this.words[s3] |= q3; return this; } var carry = q3; for (var i4 = s3; carry !== 0 && i4 < this.length; i4++) { var w4 = this.words[i4] | 0; w4 += carry; carry = w4 >>> 26; w4 &= 67108863; this.words[i4] = w4; } if (carry !== 0) { this.words[i4] = carry; this.length++; } return this; }; BN3.prototype.isZero = function isZero() { return this.length === 1 && this.words[0] === 0; }; BN3.prototype.cmpn = function cmpn(num) { var negative = num < 0; if (this.negative !== 0 && !negative) return -1; if (this.negative === 0 && negative) return 1; this._strip(); var res; if (this.length > 1) { res = 1; } else { if (negative) { num = -num; } assert2(num <= 67108863, "Number is too big"); var w4 = this.words[0] | 0; res = w4 === num ? 0 : w4 < num ? -1 : 1; } if (this.negative !== 0) return -res | 0; return res; }; BN3.prototype.cmp = function cmp(num) { if (this.negative !== 0 && num.negative === 0) return -1; if (this.negative === 0 && num.negative !== 0) return 1; var res = this.ucmp(num); if (this.negative !== 0) return -res | 0; return res; }; BN3.prototype.ucmp = function ucmp(num) { if (this.length > num.length) return 1; if (this.length < num.length) return -1; var res = 0; for (var i4 = this.length - 1; i4 >= 0; i4--) { var a4 = this.words[i4] | 0; var b5 = num.words[i4] | 0; if (a4 === b5) continue; if (a4 < b5) { res = -1; } else if (a4 > b5) { res = 1; } break; } return res; }; BN3.prototype.gtn = function gtn(num) { return this.cmpn(num) === 1; }; BN3.prototype.gt = function gt4(num) { return this.cmp(num) === 1; }; BN3.prototype.gten = function gten(num) { return this.cmpn(num) >= 0; }; BN3.prototype.gte = function gte(num) { return this.cmp(num) >= 0; }; BN3.prototype.ltn = function ltn(num) { return this.cmpn(num) === -1; }; BN3.prototype.lt = function lt3(num) { return this.cmp(num) === -1; }; BN3.prototype.lten = function lten(num) { return this.cmpn(num) <= 0; }; BN3.prototype.lte = function lte(num) { return this.cmp(num) <= 0; }; BN3.prototype.eqn = function eqn(num) { return this.cmpn(num) === 0; }; BN3.prototype.eq = function eq4(num) { return this.cmp(num) === 0; }; BN3.red = function red(num) { return new Red(num); }; BN3.prototype.toRed = function toRed(ctx) { assert2(!this.red, "Already a number in reduction context"); assert2(this.negative === 0, "red works only with positives"); return ctx.convertTo(this)._forceRed(ctx); }; BN3.prototype.fromRed = function fromRed() { assert2(this.red, "fromRed works only with numbers in reduction context"); return this.red.convertFrom(this); }; BN3.prototype._forceRed = function _forceRed(ctx) { this.red = ctx; return this; }; BN3.prototype.forceRed = function forceRed(ctx) { assert2(!this.red, "Already a number in reduction context"); return this._forceRed(ctx); }; BN3.prototype.redAdd = function redAdd(num) { assert2(this.red, "redAdd works only with red numbers"); return this.red.add(this, num); }; BN3.prototype.redIAdd = function redIAdd(num) { assert2(this.red, "redIAdd works only with red numbers"); return this.red.iadd(this, num); }; BN3.prototype.redSub = function redSub(num) { assert2(this.red, "redSub works only with red numbers"); return this.red.sub(this, num); }; BN3.prototype.redISub = function redISub(num) { assert2(this.red, "redISub works only with red numbers"); return this.red.isub(this, num); }; BN3.prototype.redShl = function redShl(num) { assert2(this.red, "redShl works only with red numbers"); return this.red.shl(this, num); }; BN3.prototype.redMul = function redMul(num) { assert2(this.red, "redMul works only with red numbers"); this.red._verify2(this, num); return this.red.mul(this, num); }; BN3.prototype.redIMul = function redIMul(num) { assert2(this.red, "redMul works only with red numbers"); this.red._verify2(this, num); return this.red.imul(this, num); }; BN3.prototype.redSqr = function redSqr() { assert2(this.red, "redSqr works only with red numbers"); this.red._verify1(this); return this.red.sqr(this); }; BN3.prototype.redISqr = function redISqr() { assert2(this.red, "redISqr works only with red numbers"); this.red._verify1(this); return this.red.isqr(this); }; BN3.prototype.redSqrt = function redSqrt() { assert2(this.red, "redSqrt works only with red numbers"); this.red._verify1(this); return this.red.sqrt(this); }; BN3.prototype.redInvm = function redInvm() { assert2(this.red, "redInvm works only with red numbers"); this.red._verify1(this); return this.red.invm(this); }; BN3.prototype.redNeg = function redNeg() { assert2(this.red, "redNeg works only with red numbers"); this.red._verify1(this); return this.red.neg(this); }; BN3.prototype.redPow = function redPow(num) { assert2(this.red && !num.red, "redPow(normalNum)"); this.red._verify1(this); return this.red.pow(this, num); }; var primes = { k256: null, p224: null, p192: null, p25519: null }; function MPrime(name2, p3) { this.name = name2; this.p = new BN3(p3, 16); this.n = this.p.bitLength(); this.k = new BN3(1).iushln(this.n).isub(this.p); this.tmp = this._tmp(); } MPrime.prototype._tmp = function _tmp() { var tmp = new BN3(null); tmp.words = new Array(Math.ceil(this.n / 13)); return tmp; }; MPrime.prototype.ireduce = function ireduce(num) { var r4 = num; var rlen; do { this.split(r4, this.tmp); r4 = this.imulK(r4); r4 = r4.iadd(this.tmp); rlen = r4.bitLength(); } while (rlen > this.n); var cmp = rlen < this.n ? -1 : r4.ucmp(this.p); if (cmp === 0) { r4.words[0] = 0; r4.length = 1; } else if (cmp > 0) { r4.isub(this.p); } else { if (r4.strip !== void 0) { r4.strip(); } else { r4._strip(); } } return r4; }; MPrime.prototype.split = function split(input, out) { input.iushrn(this.n, 0, out); }; MPrime.prototype.imulK = function imulK(num) { return num.imul(this.k); }; function K256() { MPrime.call( this, "k256", "ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffe fffffc2f" ); } inherits(K256, MPrime); K256.prototype.split = function split(input, output) { var mask = 4194303; var outLen = Math.min(input.length, 9); for (var i4 = 0; i4 < outLen; i4++) { output.words[i4] = input.words[i4]; } output.length = outLen; if (input.length <= 9) { input.words[0] = 0; input.length = 1; return; } var prev = input.words[9]; output.words[output.length++] = prev & mask; for (i4 = 10; i4 < input.length; i4++) { var next = input.words[i4] | 0; input.words[i4 - 10] = (next & mask) << 4 | prev >>> 22; prev = next; } prev >>>= 22; input.words[i4 - 10] = prev; if (prev === 0 && input.length > 10) { input.length -= 10; } else { input.length -= 9; } }; K256.prototype.imulK = function imulK(num) { num.words[num.length] = 0; num.words[num.length + 1] = 0; num.length += 2; var lo2 = 0; for (var i4 = 0; i4 < num.length; i4++) { var w4 = num.words[i4] | 0; lo2 += w4 * 977; num.words[i4] = lo2 & 67108863; lo2 = w4 * 64 + (lo2 / 67108864 | 0); } if (num.words[num.length - 1] === 0) { num.length--; if (num.words[num.length - 1] === 0) { num.length--; } } return num; }; function P224() { MPrime.call( this, "p224", "ffffffff ffffffff ffffffff ffffffff 00000000 00000000 00000001" ); } inherits(P224, MPrime); function P192() { MPrime.call( this, "p192", "ffffffff ffffffff ffffffff fffffffe ffffffff ffffffff" ); } inherits(P192, MPrime); function P25519() { MPrime.call( this, "25519", "7fffffffffffffff ffffffffffffffff ffffffffffffffff ffffffffffffffed" ); } inherits(P25519, MPrime); P25519.prototype.imulK = function imulK(num) { var carry = 0; for (var i4 = 0; i4 < num.length; i4++) { var hi2 = (num.words[i4] | 0) * 19 + carry; var lo2 = hi2 & 67108863; hi2 >>>= 26; num.words[i4] = lo2; carry = hi2; } if (carry !== 0) { num.words[num.length++] = carry; } return num; }; BN3._prime = function prime(name2) { if (primes[name2]) return primes[name2]; var prime2; if (name2 === "k256") { prime2 = new K256(); } else if (name2 === "p224") { prime2 = new P224(); } else if (name2 === "p192") { prime2 = new P192(); } else if (name2 === "p25519") { prime2 = new P25519(); } else { throw new Error("Unknown prime " + name2); } primes[name2] = prime2; return prime2; }; function Red(m2) { if (typeof m2 === "string") { var prime = BN3._prime(m2); this.m = prime.p; this.prime = prime; } else { assert2(m2.gtn(1), "modulus must be greater than 1"); this.m = m2; this.prime = null; } } Red.prototype._verify1 = function _verify1(a4) { assert2(a4.negative === 0, "red works only with positives"); assert2(a4.red, "red works only with red numbers"); }; Red.prototype._verify2 = function _verify2(a4, b5) { assert2((a4.negative | b5.negative) === 0, "red works only with positives"); assert2( a4.red && a4.red === b5.red, "red works only with red numbers" ); }; Red.prototype.imod = function imod(a4) { if (this.prime) return this.prime.ireduce(a4)._forceRed(this); move(a4, a4.umod(this.m)._forceRed(this)); return a4; }; Red.prototype.neg = function neg3(a4) { if (a4.isZero()) { return a4.clone(); } return this.m.sub(a4)._forceRed(this); }; Red.prototype.add = function add3(a4, b5) { this._verify2(a4, b5); var res = a4.add(b5); if (res.cmp(this.m) >= 0) { res.isub(this.m); } return res._forceRed(this); }; Red.prototype.iadd = function iadd(a4, b5) { this._verify2(a4, b5); var res = a4.iadd(b5); if (res.cmp(this.m) >= 0) { res.isub(this.m); } return res; }; Red.prototype.sub = function sub(a4, b5) { this._verify2(a4, b5); var res = a4.sub(b5); if (res.cmpn(0) < 0) { res.iadd(this.m); } return res._forceRed(this); }; Red.prototype.isub = function isub(a4, b5) { this._verify2(a4, b5); var res = a4.isub(b5); if (res.cmpn(0) < 0) { res.iadd(this.m); } return res; }; Red.prototype.shl = function shl(a4, num) { this._verify1(a4); return this.imod(a4.ushln(num)); }; Red.prototype.imul = function imul(a4, b5) { this._verify2(a4, b5); return this.imod(a4.imul(b5)); }; Red.prototype.mul = function mul3(a4, b5) { this._verify2(a4, b5); return this.imod(a4.mul(b5)); }; Red.prototype.isqr = function isqr(a4) { return this.imul(a4, a4.clone()); }; Red.prototype.sqr = function sqr(a4) { return this.mul(a4, a4); }; Red.prototype.sqrt = function sqrt(a4) { if (a4.isZero()) return a4.clone(); var mod3 = this.m.andln(3); assert2(mod3 % 2 === 1); if (mod3 === 3) { var pow = this.m.add(new BN3(1)).iushrn(2); return this.pow(a4, pow); } var q3 = this.m.subn(1); var s3 = 0; while (!q3.isZero() && q3.andln(1) === 0) { s3++; q3.iushrn(1); } assert2(!q3.isZero()); var one = new BN3(1).toRed(this); var nOne = one.redNeg(); var lpow = this.m.subn(1).iushrn(1); var z6 = this.m.bitLength(); z6 = new BN3(2 * z6 * z6).toRed(this); while (this.pow(z6, lpow).cmp(nOne) !== 0) { z6.redIAdd(nOne); } var c5 = this.pow(z6, q3); var r4 = this.pow(a4, q3.addn(1).iushrn(1)); var t = this.pow(a4, q3); var m2 = s3; while (t.cmp(one) !== 0) { var tmp = t; for (var i4 = 0; tmp.cmp(one) !== 0; i4++) { tmp = tmp.redSqr(); } assert2(i4 < m2); var b5 = this.pow(c5, new BN3(1).iushln(m2 - i4 - 1)); r4 = r4.redMul(b5); c5 = b5.redSqr(); t = t.redMul(c5); m2 = i4; } return r4; }; Red.prototype.invm = function invm(a4) { var inv = a4._invmp(this.m); if (inv.negative !== 0) { inv.negative = 0; return this.imod(inv).redNeg(); } else { return this.imod(inv); } }; Red.prototype.pow = function pow(a4, num) { if (num.isZero()) return new BN3(1).toRed(this); if (num.cmpn(1) === 0) return a4.clone(); var windowSize = 4; var wnd = new Array(1 << windowSize); wnd[0] = new BN3(1).toRed(this); wnd[1] = a4; for (var i4 = 2; i4 < wnd.length; i4++) { wnd[i4] = this.mul(wnd[i4 - 1], a4); } var res = wnd[0]; var current = 0; var currentLen = 0; var start = num.bitLength() % 26; if (start === 0) { start = 26; } for (i4 = num.length - 1; i4 >= 0; i4--) { var word = num.words[i4]; for (var j2 = start - 1; j2 >= 0; j2--) { var bit = word >> j2 & 1; if (res !== wnd[0]) { res = this.sqr(res); } if (bit === 0 && current === 0) { currentLen = 0; continue; } current <<= 1; current |= bit; currentLen++; if (currentLen !== windowSize && (i4 !== 0 || j2 !== 0)) continue; res = this.mul(res, wnd[current]); currentLen = 0; current = 0; } start = 26; } return res; }; Red.prototype.convertTo = function convertTo(num) { var r4 = num.umod(this.m); return r4 === num ? r4.clone() : r4; }; Red.prototype.convertFrom = function convertFrom(num) { var res = num.clone(); res.red = null; return res; }; BN3.mont = function mont(num) { return new Mont(num); }; function Mont(m2) { Red.call(this, m2); this.shift = this.m.bitLength(); if (this.shift % 26 !== 0) { this.shift += 26 - this.shift % 26; } this.r = new BN3(1).iushln(this.shift); this.r2 = this.imod(this.r.sqr()); this.rinv = this.r._invmp(this.m); this.minv = this.rinv.mul(this.r).isubn(1).div(this.m); this.minv = this.minv.umod(this.r); this.minv = this.r.sub(this.minv); } inherits(Mont, Red); Mont.prototype.convertTo = function convertTo(num) { return this.imod(num.ushln(this.shift)); }; Mont.prototype.convertFrom = function convertFrom(num) { var r4 = this.imod(num.mul(this.rinv)); r4.red = null; return r4; }; Mont.prototype.imul = function imul(a4, b5) { if (a4.isZero() || b5.isZero()) { a4.words[0] = 0; a4.length = 1; return a4; } var t = a4.imul(b5); var c5 = t.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m); var u3 = t.isub(c5).iushrn(this.shift); var res = u3; if (u3.cmp(this.m) >= 0) { res = u3.isub(this.m); } else if (u3.cmpn(0) < 0) { res = u3.iadd(this.m); } return res._forceRed(this); }; Mont.prototype.mul = function mul3(a4, b5) { if (a4.isZero() || b5.isZero()) return new BN3(0)._forceRed(this); var t = a4.mul(b5); var c5 = t.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m); var u3 = t.isub(c5).iushrn(this.shift); var res = u3; if (u3.cmp(this.m) >= 0) { res = u3.isub(this.m); } else if (u3.cmpn(0) < 0) { res = u3.iadd(this.m); } return res._forceRed(this); }; Mont.prototype.invm = function invm(a4) { var res = this.imod(a4._invmp(this.m).mul(this.r2)); return res._forceRed(this); }; })(typeof module === "undefined" || module, exports); } }); // node_modules/minimalistic-assert/index.js var require_minimalistic_assert = __commonJS({ "node_modules/minimalistic-assert/index.js"(exports, module) { module.exports = assert2; function assert2(val, msg) { if (!val) throw new Error(msg || "Assertion failed"); } assert2.equal = function assertEqual2(l4, r4, msg) { if (l4 != r4) throw new Error(msg || "Assertion failed: " + l4 + " != " + r4); }; } }); // node_modules/inherits/inherits_browser.js var require_inherits_browser = __commonJS({ "node_modules/inherits/inherits_browser.js"(exports, module) { if (typeof Object.create === "function") { module.exports = function inherits(ctor, superCtor) { if (superCtor) { ctor.super_ = superCtor; ctor.prototype = Object.create(superCtor.prototype, { constructor: { value: ctor, enumerable: false, writable: true, configurable: true } }); } }; } else { module.exports = function inherits(ctor, superCtor) { if (superCtor) { ctor.super_ = superCtor; var TempCtor = function() { }; TempCtor.prototype = superCtor.prototype; ctor.prototype = new TempCtor(); ctor.prototype.constructor = ctor; } }; } } }); // node_modules/hash.js/lib/hash/utils.js var require_utils2 = __commonJS({ "node_modules/hash.js/lib/hash/utils.js"(exports) { "use strict"; var assert2 = require_minimalistic_assert(); var inherits = require_inherits_browser(); exports.inherits = inherits; function isSurrogatePair(msg, i4) { if ((msg.charCodeAt(i4) & 64512) !== 55296) { return false; } if (i4 < 0 || i4 + 1 >= msg.length) { return false; } return (msg.charCodeAt(i4 + 1) & 64512) === 56320; } function toArray(msg, enc) { if (Array.isArray(msg)) return msg.slice(); if (!msg) return []; var res = []; if (typeof msg === "string") { if (!enc) { var p3 = 0; for (var i4 = 0; i4 < msg.length; i4++) { var c5 = msg.charCodeAt(i4); if (c5 < 128) { res[p3++] = c5; } else if (c5 < 2048) { res[p3++] = c5 >> 6 | 192; res[p3++] = c5 & 63 | 128; } else if (isSurrogatePair(msg, i4)) { c5 = 65536 + ((c5 & 1023) << 10) + (msg.charCodeAt(++i4) & 1023); res[p3++] = c5 >> 18 | 240; res[p3++] = c5 >> 12 & 63 | 128; res[p3++] = c5 >> 6 & 63 | 128; res[p3++] = c5 & 63 | 128; } else { res[p3++] = c5 >> 12 | 224; res[p3++] = c5 >> 6 & 63 | 128; res[p3++] = c5 & 63 | 128; } } } else if (enc === "hex") { msg = msg.replace(/[^a-z0-9]+/ig, ""); if (msg.length % 2 !== 0) msg = "0" + msg; for (i4 = 0; i4 < msg.length; i4 += 2) res.push(parseInt(msg[i4] + msg[i4 + 1], 16)); } } else { for (i4 = 0; i4 < msg.length; i4++) res[i4] = msg[i4] | 0; } return res; } exports.toArray = toArray; function toHex2(msg) { var res = ""; for (var i4 = 0; i4 < msg.length; i4++) res += zero2(msg[i4].toString(16)); return res; } exports.toHex = toHex2; function htonl(w4) { var res = w4 >>> 24 | w4 >>> 8 & 65280 | w4 << 8 & 16711680 | (w4 & 255) << 24; return res >>> 0; } exports.htonl = htonl; function toHex32(msg, endian) { var res = ""; for (var i4 = 0; i4 < msg.length; i4++) { var w4 = msg[i4]; if (endian === "little") w4 = htonl(w4); res += zero8(w4.toString(16)); } return res; } exports.toHex32 = toHex32; function zero2(word) { if (word.length === 1) return "0" + word; else return word; } exports.zero2 = zero2; function zero8(word) { if (word.length === 7) return "0" + word; else if (word.length === 6) return "00" + word; else if (word.length === 5) return "000" + word; else if (word.length === 4) return "0000" + word; else if (word.length === 3) return "00000" + word; else if (word.length === 2) return "000000" + word; else if (word.length === 1) return "0000000" + word; else return word; } exports.zero8 = zero8; function join32(msg, start, end, endian) { var len = end - start; assert2(len % 4 === 0); var res = new Array(len / 4); for (var i4 = 0, k4 = start; i4 < res.length; i4++, k4 += 4) { var w4; if (endian === "big") w4 = msg[k4] << 24 | msg[k4 + 1] << 16 | msg[k4 + 2] << 8 | msg[k4 + 3]; else w4 = msg[k4 + 3] << 24 | msg[k4 + 2] << 16 | msg[k4 + 1] << 8 | msg[k4]; res[i4] = w4 >>> 0; } return res; } exports.join32 = join32; function split32(msg, endian) { var res = new Array(msg.length * 4); for (var i4 = 0, k4 = 0; i4 < msg.length; i4++, k4 += 4) { var m2 = msg[i4]; if (endian === "big") { res[k4] = m2 >>> 24; res[k4 + 1] = m2 >>> 16 & 255; res[k4 + 2] = m2 >>> 8 & 255; res[k4 + 3] = m2 & 255; } else { res[k4 + 3] = m2 >>> 24; res[k4 + 2] = m2 >>> 16 & 255; res[k4 + 1] = m2 >>> 8 & 255; res[k4] = m2 & 255; } } return res; } exports.split32 = split32; function rotr32(w4, b5) { return w4 >>> b5 | w4 << 32 - b5; } exports.rotr32 = rotr32; function rotl32(w4, b5) { return w4 << b5 | w4 >>> 32 - b5; } exports.rotl32 = rotl32; function sum32(a4, b5) { return a4 + b5 >>> 0; } exports.sum32 = sum32; function sum32_3(a4, b5, c5) { return a4 + b5 + c5 >>> 0; } exports.sum32_3 = sum32_3; function sum32_4(a4, b5, c5, d3) { return a4 + b5 + c5 + d3 >>> 0; } exports.sum32_4 = sum32_4; function sum32_5(a4, b5, c5, d3, e2) { return a4 + b5 + c5 + d3 + e2 >>> 0; } exports.sum32_5 = sum32_5; function sum64(buf, pos, ah, al) { var bh = buf[pos]; var bl = buf[pos + 1]; var lo2 = al + bl >>> 0; var hi2 = (lo2 < al ? 1 : 0) + ah + bh; buf[pos] = hi2 >>> 0; buf[pos + 1] = lo2; } exports.sum64 = sum64; function sum64_hi(ah, al, bh, bl) { var lo2 = al + bl >>> 0; var hi2 = (lo2 < al ? 1 : 0) + ah + bh; return hi2 >>> 0; } exports.sum64_hi = sum64_hi; function sum64_lo(ah, al, bh, bl) { var lo2 = al + bl; return lo2 >>> 0; } exports.sum64_lo = sum64_lo; function sum64_4_hi(ah, al, bh, bl, ch, cl, dh, dl) { var carry = 0; var lo2 = al; lo2 = lo2 + bl >>> 0; carry += lo2 < al ? 1 : 0; lo2 = lo2 + cl >>> 0; carry += lo2 < cl ? 1 : 0; lo2 = lo2 + dl >>> 0; carry += lo2 < dl ? 1 : 0; var hi2 = ah + bh + ch + dh + carry; return hi2 >>> 0; } exports.sum64_4_hi = sum64_4_hi; function sum64_4_lo(ah, al, bh, bl, ch, cl, dh, dl) { var lo2 = al + bl + cl + dl; return lo2 >>> 0; } exports.sum64_4_lo = sum64_4_lo; function sum64_5_hi(ah, al, bh, bl, ch, cl, dh, dl, eh, el) { var carry = 0; var lo2 = al; lo2 = lo2 + bl >>> 0; carry += lo2 < al ? 1 : 0; lo2 = lo2 + cl >>> 0; carry += lo2 < cl ? 1 : 0; lo2 = lo2 + dl >>> 0; carry += lo2 < dl ? 1 : 0; lo2 = lo2 + el >>> 0; carry += lo2 < el ? 1 : 0; var hi2 = ah + bh + ch + dh + eh + carry; return hi2 >>> 0; } exports.sum64_5_hi = sum64_5_hi; function sum64_5_lo(ah, al, bh, bl, ch, cl, dh, dl, eh, el) { var lo2 = al + bl + cl + dl + el; return lo2 >>> 0; } exports.sum64_5_lo = sum64_5_lo; function rotr64_hi(ah, al, num) { var r4 = al << 32 - num | ah >>> num; return r4 >>> 0; } exports.rotr64_hi = rotr64_hi; function rotr64_lo(ah, al, num) { var r4 = ah << 32 - num | al >>> num; return r4 >>> 0; } exports.rotr64_lo = rotr64_lo; function shr64_hi(ah, al, num) { return ah >>> num; } exports.shr64_hi = shr64_hi; function shr64_lo(ah, al, num) { var r4 = ah << 32 - num | al >>> num; return r4 >>> 0; } exports.shr64_lo = shr64_lo; } }); // node_modules/hash.js/lib/hash/common.js var require_common = __commonJS({ "node_modules/hash.js/lib/hash/common.js"(exports) { "use strict"; var utils = require_utils2(); var assert2 = require_minimalistic_assert(); function BlockHash() { this.pending = null; this.pendingTotal = 0; this.blockSize = this.constructor.blockSize; this.outSize = this.constructor.outSize; this.hmacStrength = this.constructor.hmacStrength; this.padLength = this.constructor.padLength / 8; this.endian = "big"; this._delta8 = this.blockSize / 8; this._delta32 = this.blockSize / 32; } exports.BlockHash = BlockHash; BlockHash.prototype.update = function update2(msg, enc) { msg = utils.toArray(msg, enc); if (!this.pending) this.pending = msg; else this.pending = this.pending.concat(msg); this.pendingTotal += msg.length; if (this.pending.length >= this._delta8) { msg = this.pending; var r4 = msg.length % this._delta8; this.pending = msg.slice(msg.length - r4, msg.length); if (this.pending.length === 0) this.pending = null; msg = utils.join32(msg, 0, msg.length - r4, this.endian); for (var i4 = 0; i4 < msg.length; i4 += this._delta32) this._update(msg, i4, i4 + this._delta32); } return this; }; BlockHash.prototype.digest = function digest2(enc) { this.update(this._pad()); assert2(this.pending === null); return this._digest(enc); }; BlockHash.prototype._pad = function pad() { var len = this.pendingTotal; var bytes = this._delta8; var k4 = bytes - (len + this.padLength) % bytes; var res = new Array(k4 + this.padLength); res[0] = 128; for (var i4 = 1; i4 < k4; i4++) res[i4] = 0; len <<= 3; if (this.endian === "big") { for (var t = 8; t < this.padLength; t++) res[i4++] = 0; res[i4++] = 0; res[i4++] = 0; res[i4++] = 0; res[i4++] = 0; res[i4++] = len >>> 24 & 255; res[i4++] = len >>> 16 & 255; res[i4++] = len >>> 8 & 255; res[i4++] = len & 255; } else { res[i4++] = len & 255; res[i4++] = len >>> 8 & 255; res[i4++] = len >>> 16 & 255; res[i4++] = len >>> 24 & 255; res[i4++] = 0; res[i4++] = 0; res[i4++] = 0; res[i4++] = 0; for (t = 8; t < this.padLength; t++) res[i4++] = 0; } return res; }; } }); // node_modules/hash.js/lib/hash/sha/common.js var require_common2 = __commonJS({ "node_modules/hash.js/lib/hash/sha/common.js"(exports) { "use strict"; var utils = require_utils2(); var rotr32 = utils.rotr32; function ft_1(s3, x6, y6, z6) { if (s3 === 0) return ch32(x6, y6, z6); if (s3 === 1 || s3 === 3) return p32(x6, y6, z6); if (s3 === 2) return maj32(x6, y6, z6); } exports.ft_1 = ft_1; function ch32(x6, y6, z6) { return x6 & y6 ^ ~x6 & z6; } exports.ch32 = ch32; function maj32(x6, y6, z6) { return x6 & y6 ^ x6 & z6 ^ y6 & z6; } exports.maj32 = maj32; function p32(x6, y6, z6) { return x6 ^ y6 ^ z6; } exports.p32 = p32; function s0_256(x6) { return rotr32(x6, 2) ^ rotr32(x6, 13) ^ rotr32(x6, 22); } exports.s0_256 = s0_256; function s1_256(x6) { return rotr32(x6, 6) ^ rotr32(x6, 11) ^ rotr32(x6, 25); } exports.s1_256 = s1_256; function g0_256(x6) { return rotr32(x6, 7) ^ rotr32(x6, 18) ^ x6 >>> 3; } exports.g0_256 = g0_256; function g1_256(x6) { return rotr32(x6, 17) ^ rotr32(x6, 19) ^ x6 >>> 10; } exports.g1_256 = g1_256; } }); // node_modules/hash.js/lib/hash/sha/1.js var require__ = __commonJS({ "node_modules/hash.js/lib/hash/sha/1.js"(exports, module) { "use strict"; var utils = require_utils2(); var common = require_common(); var shaCommon = require_common2(); var rotl32 = utils.rotl32; var sum32 = utils.sum32; var sum32_5 = utils.sum32_5; var ft_1 = shaCommon.ft_1; var BlockHash = common.BlockHash; var sha1_K = [ 1518500249, 1859775393, 2400959708, 3395469782 ]; function SHA1() { if (!(this instanceof SHA1)) return new SHA1(); BlockHash.call(this); this.h = [ 1732584193, 4023233417, 2562383102, 271733878, 3285377520 ]; this.W = new Array(80); } utils.inherits(SHA1, BlockHash); module.exports = SHA1; SHA1.blockSize = 512; SHA1.outSize = 160; SHA1.hmacStrength = 80; SHA1.padLength = 64; SHA1.prototype._update = function _update(msg, start) { var W3 = this.W; for (var i4 = 0; i4 < 16; i4++) W3[i4] = msg[start + i4]; for (; i4 < W3.length; i4++) W3[i4] = rotl32(W3[i4 - 3] ^ W3[i4 - 8] ^ W3[i4 - 14] ^ W3[i4 - 16], 1); var a4 = this.h[0]; var b5 = this.h[1]; var c5 = this.h[2]; var d3 = this.h[3]; var e2 = this.h[4]; for (i4 = 0; i4 < W3.length; i4++) { var s3 = ~~(i4 / 20); var t = sum32_5(rotl32(a4, 5), ft_1(s3, b5, c5, d3), e2, W3[i4], sha1_K[s3]); e2 = d3; d3 = c5; c5 = rotl32(b5, 30); b5 = a4; a4 = t; } this.h[0] = sum32(this.h[0], a4); this.h[1] = sum32(this.h[1], b5); this.h[2] = sum32(this.h[2], c5); this.h[3] = sum32(this.h[3], d3); this.h[4] = sum32(this.h[4], e2); }; SHA1.prototype._digest = function digest2(enc) { if (enc === "hex") return utils.toHex32(this.h, "big"); else return utils.split32(this.h, "big"); }; } }); // node_modules/hash.js/lib/hash/sha/256.js var require__2 = __commonJS({ "node_modules/hash.js/lib/hash/sha/256.js"(exports, module) { "use strict"; var utils = require_utils2(); var common = require_common(); var shaCommon = require_common2(); var assert2 = require_minimalistic_assert(); var sum32 = utils.sum32; var sum32_4 = utils.sum32_4; var sum32_5 = utils.sum32_5; var ch32 = shaCommon.ch32; var maj32 = shaCommon.maj32; var s0_256 = shaCommon.s0_256; var s1_256 = shaCommon.s1_256; var g0_256 = shaCommon.g0_256; var g1_256 = shaCommon.g1_256; var BlockHash = common.BlockHash; var sha256_K = [ 1116352408, 1899447441, 3049323471, 3921009573, 961987163, 1508970993, 2453635748, 2870763221, 3624381080, 310598401, 607225278, 1426881987, 1925078388, 2162078206, 2614888103, 3248222580, 3835390401, 4022224774, 264347078, 604807628, 770255983, 1249150122, 1555081692, 1996064986, 2554220882, 2821834349, 2952996808, 3210313671, 3336571891, 3584528711, 113926993, 338241895, 666307205, 773529912, 1294757372, 1396182291, 1695183700, 1986661051, 2177026350, 2456956037, 2730485921, 2820302411, 3259730800, 3345764771, 3516065817, 3600352804, 4094571909, 275423344, 430227734, 506948616, 659060556, 883997877, 958139571, 1322822218, 1537002063, 1747873779, 1955562222, 2024104815, 2227730452, 2361852424, 2428436474, 2756734187, 3204031479, 3329325298 ]; function SHA256() { if (!(this instanceof SHA256)) return new SHA256(); BlockHash.call(this); this.h = [ 1779033703, 3144134277, 1013904242, 2773480762, 1359893119, 2600822924, 528734635, 1541459225 ]; this.k = sha256_K; this.W = new Array(64); } utils.inherits(SHA256, BlockHash); module.exports = SHA256; SHA256.blockSize = 512; SHA256.outSize = 256; SHA256.hmacStrength = 192; SHA256.padLength = 64; SHA256.prototype._update = function _update(msg, start) { var W3 = this.W; for (var i4 = 0; i4 < 16; i4++) W3[i4] = msg[start + i4]; for (; i4 < W3.length; i4++) W3[i4] = sum32_4(g1_256(W3[i4 - 2]), W3[i4 - 7], g0_256(W3[i4 - 15]), W3[i4 - 16]); var a4 = this.h[0]; var b5 = this.h[1]; var c5 = this.h[2]; var d3 = this.h[3]; var e2 = this.h[4]; var f4 = this.h[5]; var g4 = this.h[6]; var h5 = this.h[7]; assert2(this.k.length === W3.length); for (i4 = 0; i4 < W3.length; i4++) { var T1 = sum32_5(h5, s1_256(e2), ch32(e2, f4, g4), this.k[i4], W3[i4]); var T2 = sum32(s0_256(a4), maj32(a4, b5, c5)); h5 = g4; g4 = f4; f4 = e2; e2 = sum32(d3, T1); d3 = c5; c5 = b5; b5 = a4; a4 = sum32(T1, T2); } this.h[0] = sum32(this.h[0], a4); this.h[1] = sum32(this.h[1], b5); this.h[2] = sum32(this.h[2], c5); this.h[3] = sum32(this.h[3], d3); this.h[4] = sum32(this.h[4], e2); this.h[5] = sum32(this.h[5], f4); this.h[6] = sum32(this.h[6], g4); this.h[7] = sum32(this.h[7], h5); }; SHA256.prototype._digest = function digest2(enc) { if (enc === "hex") return utils.toHex32(this.h, "big"); else return utils.split32(this.h, "big"); }; } }); // node_modules/hash.js/lib/hash/sha/224.js var require__3 = __commonJS({ "node_modules/hash.js/lib/hash/sha/224.js"(exports, module) { "use strict"; var utils = require_utils2(); var SHA256 = require__2(); function SHA224() { if (!(this instanceof SHA224)) return new SHA224(); SHA256.call(this); this.h = [ 3238371032, 914150663, 812702999, 4144912697, 4290775857, 1750603025, 1694076839, 3204075428 ]; } utils.inherits(SHA224, SHA256); module.exports = SHA224; SHA224.blockSize = 512; SHA224.outSize = 224; SHA224.hmacStrength = 192; SHA224.padLength = 64; SHA224.prototype._digest = function digest2(enc) { if (enc === "hex") return utils.toHex32(this.h.slice(0, 7), "big"); else return utils.split32(this.h.slice(0, 7), "big"); }; } }); // node_modules/hash.js/lib/hash/sha/512.js var require__4 = __commonJS({ "node_modules/hash.js/lib/hash/sha/512.js"(exports, module) { "use strict"; var utils = require_utils2(); var common = require_common(); var assert2 = require_minimalistic_assert(); var rotr64_hi = utils.rotr64_hi; var rotr64_lo = utils.rotr64_lo; var shr64_hi = utils.shr64_hi; var shr64_lo = utils.shr64_lo; var sum64 = utils.sum64; var sum64_hi = utils.sum64_hi; var sum64_lo = utils.sum64_lo; var sum64_4_hi = utils.sum64_4_hi; var sum64_4_lo = utils.sum64_4_lo; var sum64_5_hi = utils.sum64_5_hi; var sum64_5_lo = utils.sum64_5_lo; var BlockHash = common.BlockHash; var sha512_K = [ 1116352408, 3609767458, 1899447441, 602891725, 3049323471, 3964484399, 3921009573, 2173295548, 961987163, 4081628472, 1508970993, 3053834265, 2453635748, 2937671579, 2870763221, 3664609560, 3624381080, 2734883394, 310598401, 1164996542, 607225278, 1323610764, 1426881987, 3590304994, 1925078388, 4068182383, 2162078206, 991336113, 2614888103, 633803317, 3248222580, 3479774868, 3835390401, 2666613458, 4022224774, 944711139, 264347078, 2341262773, 604807628, 2007800933, 770255983, 1495990901, 1249150122, 1856431235, 1555081692, 3175218132, 1996064986, 2198950837, 2554220882, 3999719339, 2821834349, 766784016, 2952996808, 2566594879, 3210313671, 3203337956, 3336571891, 1034457026, 3584528711, 2466948901, 113926993, 3758326383, 338241895, 168717936, 666307205, 1188179964, 773529912, 1546045734, 1294757372, 1522805485, 1396182291, 2643833823, 1695183700, 2343527390, 1986661051, 1014477480, 2177026350, 1206759142, 2456956037, 344077627, 2730485921, 1290863460, 2820302411, 3158454273, 3259730800, 3505952657, 3345764771, 106217008, 3516065817, 3606008344, 3600352804, 1432725776, 4094571909, 1467031594, 275423344, 851169720, 430227734, 3100823752, 506948616, 1363258195, 659060556, 3750685593, 883997877, 3785050280, 958139571, 3318307427, 1322822218, 3812723403, 1537002063, 2003034995, 1747873779, 3602036899, 1955562222, 1575990012, 2024104815, 1125592928, 2227730452, 2716904306, 2361852424, 442776044, 2428436474, 593698344, 2756734187, 3733110249, 3204031479, 2999351573, 3329325298, 3815920427, 3391569614, 3928383900, 3515267271, 566280711, 3940187606, 3454069534, 4118630271, 4000239992, 116418474, 1914138554, 174292421, 2731055270, 289380356, 3203993006, 460393269, 320620315, 685471733, 587496836, 852142971, 1086792851, 1017036298, 365543100, 1126000580, 2618297676, 1288033470, 3409855158, 1501505948, 4234509866, 1607167915, 987167468, 1816402316, 1246189591 ]; function SHA512() { if (!(this instanceof SHA512)) return new SHA512(); BlockHash.call(this); this.h = [ 1779033703, 4089235720, 3144134277, 2227873595, 1013904242, 4271175723, 2773480762, 1595750129, 1359893119, 2917565137, 2600822924, 725511199, 528734635, 4215389547, 1541459225, 327033209 ]; this.k = sha512_K; this.W = new Array(160); } utils.inherits(SHA512, BlockHash); module.exports = SHA512; SHA512.blockSize = 1024; SHA512.outSize = 512; SHA512.hmacStrength = 192; SHA512.padLength = 128; SHA512.prototype._prepareBlock = function _prepareBlock(msg, start) { var W3 = this.W; for (var i4 = 0; i4 < 32; i4++) W3[i4] = msg[start + i4]; for (; i4 < W3.length; i4 += 2) { var c0_hi = g1_512_hi(W3[i4 - 4], W3[i4 - 3]); var c0_lo = g1_512_lo(W3[i4 - 4], W3[i4 - 3]); var c1_hi = W3[i4 - 14]; var c1_lo = W3[i4 - 13]; var c2_hi = g0_512_hi(W3[i4 - 30], W3[i4 - 29]); var c2_lo = g0_512_lo(W3[i4 - 30], W3[i4 - 29]); var c3_hi = W3[i4 - 32]; var c3_lo = W3[i4 - 31]; W3[i4] = sum64_4_hi( c0_hi, c0_lo, c1_hi, c1_lo, c2_hi, c2_lo, c3_hi, c3_lo ); W3[i4 + 1] = sum64_4_lo( c0_hi, c0_lo, c1_hi, c1_lo, c2_hi, c2_lo, c3_hi, c3_lo ); } }; SHA512.prototype._update = function _update(msg, start) { this._prepareBlock(msg, start); var W3 = this.W; var ah = this.h[0]; var al = this.h[1]; var bh = this.h[2]; var bl = this.h[3]; var ch = this.h[4]; var cl = this.h[5]; var dh = this.h[6]; var dl = this.h[7]; var eh = this.h[8]; var el = this.h[9]; var fh = this.h[10]; var fl = this.h[11]; var gh = this.h[12]; var gl = this.h[13]; var hh = this.h[14]; var hl = this.h[15]; assert2(this.k.length === W3.length); for (var i4 = 0; i4 < W3.length; i4 += 2) { var c0_hi = hh; var c0_lo = hl; var c1_hi = s1_512_hi(eh, el); var c1_lo = s1_512_lo(eh, el); var c2_hi = ch64_hi(eh, el, fh, fl, gh, gl); var c2_lo = ch64_lo(eh, el, fh, fl, gh, gl); var c3_hi = this.k[i4]; var c3_lo = this.k[i4 + 1]; var c4_hi = W3[i4]; var c4_lo = W3[i4 + 1]; var T1_hi = sum64_5_hi( c0_hi, c0_lo, c1_hi, c1_lo, c2_hi, c2_lo, c3_hi, c3_lo, c4_hi, c4_lo ); var T1_lo = sum64_5_lo( c0_hi, c0_lo, c1_hi, c1_lo, c2_hi, c2_lo, c3_hi, c3_lo, c4_hi, c4_lo ); c0_hi = s0_512_hi(ah, al); c0_lo = s0_512_lo(ah, al); c1_hi = maj64_hi(ah, al, bh, bl, ch, cl); c1_lo = maj64_lo(ah, al, bh, bl, ch, cl); var T2_hi = sum64_hi(c0_hi, c0_lo, c1_hi, c1_lo); var T2_lo = sum64_lo(c0_hi, c0_lo, c1_hi, c1_lo); hh = gh; hl = gl; gh = fh; gl = fl; fh = eh; fl = el; eh = sum64_hi(dh, dl, T1_hi, T1_lo); el = sum64_lo(dl, dl, T1_hi, T1_lo); dh = ch; dl = cl; ch = bh; cl = bl; bh = ah; bl = al; ah = sum64_hi(T1_hi, T1_lo, T2_hi, T2_lo); al = sum64_lo(T1_hi, T1_lo, T2_hi, T2_lo); } sum64(this.h, 0, ah, al); sum64(this.h, 2, bh, bl); sum64(this.h, 4, ch, cl); sum64(this.h, 6, dh, dl); sum64(this.h, 8, eh, el); sum64(this.h, 10, fh, fl); sum64(this.h, 12, gh, gl); sum64(this.h, 14, hh, hl); }; SHA512.prototype._digest = function digest2(enc) { if (enc === "hex") return utils.toHex32(this.h, "big"); else return utils.split32(this.h, "big"); }; function ch64_hi(xh, xl, yh, yl, zh) { var r4 = xh & yh ^ ~xh & zh; if (r4 < 0) r4 += 4294967296; return r4; } function ch64_lo(xh, xl, yh, yl, zh, zl) { var r4 = xl & yl ^ ~xl & zl; if (r4 < 0) r4 += 4294967296; return r4; } function maj64_hi(xh, xl, yh, yl, zh) { var r4 = xh & yh ^ xh & zh ^ yh & zh; if (r4 < 0) r4 += 4294967296; return r4; } function maj64_lo(xh, xl, yh, yl, zh, zl) { var r4 = xl & yl ^ xl & zl ^ yl & zl; if (r4 < 0) r4 += 4294967296; return r4; } function s0_512_hi(xh, xl) { var c0_hi = rotr64_hi(xh, xl, 28); var c1_hi = rotr64_hi(xl, xh, 2); var c2_hi = rotr64_hi(xl, xh, 7); var r4 = c0_hi ^ c1_hi ^ c2_hi; if (r4 < 0) r4 += 4294967296; return r4; } function s0_512_lo(xh, xl) { var c0_lo = rotr64_lo(xh, xl, 28); var c1_lo = rotr64_lo(xl, xh, 2); var c2_lo = rotr64_lo(xl, xh, 7); var r4 = c0_lo ^ c1_lo ^ c2_lo; if (r4 < 0) r4 += 4294967296; return r4; } function s1_512_hi(xh, xl) { var c0_hi = rotr64_hi(xh, xl, 14); var c1_hi = rotr64_hi(xh, xl, 18); var c2_hi = rotr64_hi(xl, xh, 9); var r4 = c0_hi ^ c1_hi ^ c2_hi; if (r4 < 0) r4 += 4294967296; return r4; } function s1_512_lo(xh, xl) { var c0_lo = rotr64_lo(xh, xl, 14); var c1_lo = rotr64_lo(xh, xl, 18); var c2_lo = rotr64_lo(xl, xh, 9); var r4 = c0_lo ^ c1_lo ^ c2_lo; if (r4 < 0) r4 += 4294967296; return r4; } function g0_512_hi(xh, xl) { var c0_hi = rotr64_hi(xh, xl, 1); var c1_hi = rotr64_hi(xh, xl, 8); var c2_hi = shr64_hi(xh, xl, 7); var r4 = c0_hi ^ c1_hi ^ c2_hi; if (r4 < 0) r4 += 4294967296; return r4; } function g0_512_lo(xh, xl) { var c0_lo = rotr64_lo(xh, xl, 1); var c1_lo = rotr64_lo(xh, xl, 8); var c2_lo = shr64_lo(xh, xl, 7); var r4 = c0_lo ^ c1_lo ^ c2_lo; if (r4 < 0) r4 += 4294967296; return r4; } function g1_512_hi(xh, xl) { var c0_hi = rotr64_hi(xh, xl, 19); var c1_hi = rotr64_hi(xl, xh, 29); var c2_hi = shr64_hi(xh, xl, 6); var r4 = c0_hi ^ c1_hi ^ c2_hi; if (r4 < 0) r4 += 4294967296; return r4; } function g1_512_lo(xh, xl) { var c0_lo = rotr64_lo(xh, xl, 19); var c1_lo = rotr64_lo(xl, xh, 29); var c2_lo = shr64_lo(xh, xl, 6); var r4 = c0_lo ^ c1_lo ^ c2_lo; if (r4 < 0) r4 += 4294967296; return r4; } } }); // node_modules/hash.js/lib/hash/sha/384.js var require__5 = __commonJS({ "node_modules/hash.js/lib/hash/sha/384.js"(exports, module) { "use strict"; var utils = require_utils2(); var SHA512 = require__4(); function SHA384() { if (!(this instanceof SHA384)) return new SHA384(); SHA512.call(this); this.h = [ 3418070365, 3238371032, 1654270250, 914150663, 2438529370, 812702999, 355462360, 4144912697, 1731405415, 4290775857, 2394180231, 1750603025, 3675008525, 1694076839, 1203062813, 3204075428 ]; } utils.inherits(SHA384, SHA512); module.exports = SHA384; SHA384.blockSize = 1024; SHA384.outSize = 384; SHA384.hmacStrength = 192; SHA384.padLength = 128; SHA384.prototype._digest = function digest2(enc) { if (enc === "hex") return utils.toHex32(this.h.slice(0, 12), "big"); else return utils.split32(this.h.slice(0, 12), "big"); }; } }); // node_modules/hash.js/lib/hash/sha.js var require_sha = __commonJS({ "node_modules/hash.js/lib/hash/sha.js"(exports) { "use strict"; exports.sha1 = require__(); exports.sha224 = require__3(); exports.sha256 = require__2(); exports.sha384 = require__5(); exports.sha512 = require__4(); } }); // node_modules/hash.js/lib/hash/ripemd.js var require_ripemd = __commonJS({ "node_modules/hash.js/lib/hash/ripemd.js"(exports) { "use strict"; var utils = require_utils2(); var common = require_common(); var rotl32 = utils.rotl32; var sum32 = utils.sum32; var sum32_3 = utils.sum32_3; var sum32_4 = utils.sum32_4; var BlockHash = common.BlockHash; function RIPEMD160() { if (!(this instanceof RIPEMD160)) return new RIPEMD160(); BlockHash.call(this); this.h = [1732584193, 4023233417, 2562383102, 271733878, 3285377520]; this.endian = "little"; } utils.inherits(RIPEMD160, BlockHash); exports.ripemd160 = RIPEMD160; RIPEMD160.blockSize = 512; RIPEMD160.outSize = 160; RIPEMD160.hmacStrength = 192; RIPEMD160.padLength = 64; RIPEMD160.prototype._update = function update2(msg, start) { var A3 = this.h[0]; var B4 = this.h[1]; var C5 = this.h[2]; var D4 = this.h[3]; var E3 = this.h[4]; var Ah = A3; var Bh = B4; var Ch = C5; var Dh = D4; var Eh = E3; for (var j2 = 0; j2 < 80; j2++) { var T2 = sum32( rotl32( sum32_4(A3, f4(j2, B4, C5, D4), msg[r4[j2] + start], K3(j2)), s3[j2] ), E3 ); A3 = E3; E3 = D4; D4 = rotl32(C5, 10); C5 = B4; B4 = T2; T2 = sum32( rotl32( sum32_4(Ah, f4(79 - j2, Bh, Ch, Dh), msg[rh[j2] + start], Kh(j2)), sh[j2] ), Eh ); Ah = Eh; Eh = Dh; Dh = rotl32(Ch, 10); Ch = Bh; Bh = T2; } T2 = sum32_3(this.h[1], C5, Dh); this.h[1] = sum32_3(this.h[2], D4, Eh); this.h[2] = sum32_3(this.h[3], E3, Ah); this.h[3] = sum32_3(this.h[4], A3, Bh); this.h[4] = sum32_3(this.h[0], B4, Ch); this.h[0] = T2; }; RIPEMD160.prototype._digest = function digest2(enc) { if (enc === "hex") return utils.toHex32(this.h, "little"); else return utils.split32(this.h, "little"); }; function f4(j2, x6, y6, z6) { if (j2 <= 15) return x6 ^ y6 ^ z6; else if (j2 <= 31) return x6 & y6 | ~x6 & z6; else if (j2 <= 47) return (x6 | ~y6) ^ z6; else if (j2 <= 63) return x6 & z6 | y6 & ~z6; else return x6 ^ (y6 | ~z6); } function K3(j2) { if (j2 <= 15) return 0; else if (j2 <= 31) return 1518500249; else if (j2 <= 47) return 1859775393; else if (j2 <= 63) return 2400959708; else return 2840853838; } function Kh(j2) { if (j2 <= 15) return 1352829926; else if (j2 <= 31) return 1548603684; else if (j2 <= 47) return 1836072691; else if (j2 <= 63) return 2053994217; else return 0; } var r4 = [ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 7, 4, 13, 1, 10, 6, 15, 3, 12, 0, 9, 5, 2, 14, 11, 8, 3, 10, 14, 4, 9, 15, 8, 1, 2, 7, 0, 6, 13, 11, 5, 12, 1, 9, 11, 10, 0, 8, 12, 4, 13, 3, 7, 15, 14, 5, 6, 2, 4, 0, 5, 9, 7, 12, 2, 10, 14, 1, 3, 8, 11, 6, 15, 13 ]; var rh = [ 5, 14, 7, 0, 9, 2, 11, 4, 13, 6, 15, 8, 1, 10, 3, 12, 6, 11, 3, 7, 0, 13, 5, 10, 14, 15, 8, 12, 4, 9, 1, 2, 15, 5, 1, 3, 7, 14, 6, 9, 11, 8, 12, 2, 10, 0, 4, 13, 8, 6, 4, 1, 3, 11, 15, 0, 5, 12, 2, 13, 9, 7, 10, 14, 12, 15, 10, 4, 1, 5, 8, 7, 6, 2, 13, 14, 0, 3, 9, 11 ]; var s3 = [ 11, 14, 15, 12, 5, 8, 7, 9, 11, 13, 14, 15, 6, 7, 9, 8, 7, 6, 8, 13, 11, 9, 7, 15, 7, 12, 15, 9, 11, 7, 13, 12, 11, 13, 6, 7, 14, 9, 13, 15, 14, 8, 13, 6, 5, 12, 7, 5, 11, 12, 14, 15, 14, 15, 9, 8, 9, 14, 5, 6, 8, 6, 5, 12, 9, 15, 5, 11, 6, 8, 13, 12, 5, 12, 13, 14, 11, 8, 5, 6 ]; var sh = [ 8, 9, 9, 11, 13, 15, 15, 5, 7, 7, 8, 11, 14, 14, 12, 6, 9, 13, 15, 7, 12, 8, 9, 11, 7, 7, 12, 7, 6, 15, 13, 11, 9, 7, 15, 11, 8, 6, 6, 14, 12, 13, 5, 14, 13, 13, 7, 5, 15, 5, 8, 11, 14, 14, 6, 14, 6, 9, 12, 9, 12, 5, 15, 8, 8, 5, 12, 9, 12, 5, 14, 6, 8, 13, 6, 5, 15, 13, 11, 11 ]; } }); // node_modules/hash.js/lib/hash/hmac.js var require_hmac = __commonJS({ "node_modules/hash.js/lib/hash/hmac.js"(exports, module) { "use strict"; var utils = require_utils2(); var assert2 = require_minimalistic_assert(); function Hmac(hash2, key2, enc) { if (!(this instanceof Hmac)) return new Hmac(hash2, key2, enc); this.Hash = hash2; this.blockSize = hash2.blockSize / 8; this.outSize = hash2.outSize / 8; this.inner = null; this.outer = null; this._init(utils.toArray(key2, enc)); } module.exports = Hmac; Hmac.prototype._init = function init2(key2) { if (key2.length > this.blockSize) key2 = new this.Hash().update(key2).digest(); assert2(key2.length <= this.blockSize); for (var i4 = key2.length; i4 < this.blockSize; i4++) key2.push(0); for (i4 = 0; i4 < key2.length; i4++) key2[i4] ^= 54; this.inner = new this.Hash().update(key2); for (i4 = 0; i4 < key2.length; i4++) key2[i4] ^= 106; this.outer = new this.Hash().update(key2); }; Hmac.prototype.update = function update2(msg, enc) { this.inner.update(msg, enc); return this; }; Hmac.prototype.digest = function digest2(enc) { this.outer.update(this.inner.digest()); return this.outer.digest(enc); }; } }); // node_modules/hash.js/lib/hash.js var require_hash = __commonJS({ "node_modules/hash.js/lib/hash.js"(exports) { var hash2 = exports; hash2.utils = require_utils2(); hash2.common = require_common(); hash2.sha = require_sha(); hash2.ripemd = require_ripemd(); hash2.hmac = require_hmac(); hash2.sha1 = hash2.sha.sha1; hash2.sha256 = hash2.sha.sha256; hash2.sha224 = hash2.sha.sha224; hash2.sha384 = hash2.sha.sha384; hash2.sha512 = hash2.sha.sha512; hash2.ripemd160 = hash2.ripemd.ripemd160; } }); // node_modules/@stablelib/int/lib/int.js var require_int = __commonJS({ "node_modules/@stablelib/int/lib/int.js"(exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); function imulShim(a4, b5) { var ah = a4 >>> 16 & 65535, al = a4 & 65535; var bh = b5 >>> 16 & 65535, bl = b5 & 65535; return al * bl + (ah * bl + al * bh << 16 >>> 0) | 0; } exports.mul = Math.imul || imulShim; function add3(a4, b5) { return a4 + b5 | 0; } exports.add = add3; function sub(a4, b5) { return a4 - b5 | 0; } exports.sub = sub; function rotl(x6, n5) { return x6 << n5 | x6 >>> 32 - n5; } exports.rotl = rotl; function rotr(x6, n5) { return x6 << 32 - n5 | x6 >>> n5; } exports.rotr = rotr; function isIntegerShim(n5) { return typeof n5 === "number" && isFinite(n5) && Math.floor(n5) === n5; } exports.isInteger = Number.isInteger || isIntegerShim; exports.MAX_SAFE_INTEGER = 9007199254740991; exports.isSafeInteger = function(n5) { return exports.isInteger(n5) && (n5 >= -exports.MAX_SAFE_INTEGER && n5 <= exports.MAX_SAFE_INTEGER); }; } }); // node_modules/@stablelib/binary/lib/binary.js var require_binary = __commonJS({ "node_modules/@stablelib/binary/lib/binary.js"(exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var int_1 = require_int(); function readInt16BE(array, offset) { if (offset === void 0) { offset = 0; } return (array[offset + 0] << 8 | array[offset + 1]) << 16 >> 16; } exports.readInt16BE = readInt16BE; function readUint16BE(array, offset) { if (offset === void 0) { offset = 0; } return (array[offset + 0] << 8 | array[offset + 1]) >>> 0; } exports.readUint16BE = readUint16BE; function readInt16LE(array, offset) { if (offset === void 0) { offset = 0; } return (array[offset + 1] << 8 | array[offset]) << 16 >> 16; } exports.readInt16LE = readInt16LE; function readUint16LE(array, offset) { if (offset === void 0) { offset = 0; } return (array[offset + 1] << 8 | array[offset]) >>> 0; } exports.readUint16LE = readUint16LE; function writeUint16BE(value, out, offset) { if (out === void 0) { out = new Uint8Array(2); } if (offset === void 0) { offset = 0; } out[offset + 0] = value >>> 8; out[offset + 1] = value >>> 0; return out; } exports.writeUint16BE = writeUint16BE; exports.writeInt16BE = writeUint16BE; function writeUint16LE(value, out, offset) { if (out === void 0) { out = new Uint8Array(2); } if (offset === void 0) { offset = 0; } out[offset + 0] = value >>> 0; out[offset + 1] = value >>> 8; return out; } exports.writeUint16LE = writeUint16LE; exports.writeInt16LE = writeUint16LE; function readInt32BE(array, offset) { if (offset === void 0) { offset = 0; } return array[offset] << 24 | array[offset + 1] << 16 | array[offset + 2] << 8 | array[offset + 3]; } exports.readInt32BE = readInt32BE; function readUint32BE(array, offset) { if (offset === void 0) { offset = 0; } return (array[offset] << 24 | array[offset + 1] << 16 | array[offset + 2] << 8 | array[offset + 3]) >>> 0; } exports.readUint32BE = readUint32BE; function readInt32LE(array, offset) { if (offset === void 0) { offset = 0; } return array[offset + 3] << 24 | array[offset + 2] << 16 | array[offset + 1] << 8 | array[offset]; } exports.readInt32LE = readInt32LE; function readUint32LE(array, offset) { if (offset === void 0) { offset = 0; } return (array[offset + 3] << 24 | array[offset + 2] << 16 | array[offset + 1] << 8 | array[offset]) >>> 0; } exports.readUint32LE = readUint32LE; function writeUint32BE(value, out, offset) { if (out === void 0) { out = new Uint8Array(4); } if (offset === void 0) { offset = 0; } out[offset + 0] = value >>> 24; out[offset + 1] = value >>> 16; out[offset + 2] = value >>> 8; out[offset + 3] = value >>> 0; return out; } exports.writeUint32BE = writeUint32BE; exports.writeInt32BE = writeUint32BE; function writeUint32LE(value, out, offset) { if (out === void 0) { out = new Uint8Array(4); } if (offset === void 0) { offset = 0; } out[offset + 0] = value >>> 0; out[offset + 1] = value >>> 8; out[offset + 2] = value >>> 16; out[offset + 3] = value >>> 24; return out; } exports.writeUint32LE = writeUint32LE; exports.writeInt32LE = writeUint32LE; function readInt64BE(array, offset) { if (offset === void 0) { offset = 0; } var hi2 = readInt32BE(array, offset); var lo2 = readInt32BE(array, offset + 4); return hi2 * 4294967296 + lo2 - (lo2 >> 31) * 4294967296; } exports.readInt64BE = readInt64BE; function readUint64BE(array, offset) { if (offset === void 0) { offset = 0; } var hi2 = readUint32BE(array, offset); var lo2 = readUint32BE(array, offset + 4); return hi2 * 4294967296 + lo2; } exports.readUint64BE = readUint64BE; function readInt64LE(array, offset) { if (offset === void 0) { offset = 0; } var lo2 = readInt32LE(array, offset); var hi2 = readInt32LE(array, offset + 4); return hi2 * 4294967296 + lo2 - (lo2 >> 31) * 4294967296; } exports.readInt64LE = readInt64LE; function readUint64LE(array, offset) { if (offset === void 0) { offset = 0; } var lo2 = readUint32LE(array, offset); var hi2 = readUint32LE(array, offset + 4); return hi2 * 4294967296 + lo2; } exports.readUint64LE = readUint64LE; function writeUint64BE(value, out, offset) { if (out === void 0) { out = new Uint8Array(8); } if (offset === void 0) { offset = 0; } writeUint32BE(value / 4294967296 >>> 0, out, offset); writeUint32BE(value >>> 0, out, offset + 4); return out; } exports.writeUint64BE = writeUint64BE; exports.writeInt64BE = writeUint64BE; function writeUint64LE(value, out, offset) { if (out === void 0) { out = new Uint8Array(8); } if (offset === void 0) { offset = 0; } writeUint32LE(value >>> 0, out, offset); writeUint32LE(value / 4294967296 >>> 0, out, offset + 4); return out; } exports.writeUint64LE = writeUint64LE; exports.writeInt64LE = writeUint64LE; function readUintBE(bitLength, array, offset) { if (offset === void 0) { offset = 0; } if (bitLength % 8 !== 0) { throw new Error("readUintBE supports only bitLengths divisible by 8"); } if (bitLength / 8 > array.length - offset) { throw new Error("readUintBE: array is too short for the given bitLength"); } var result = 0; var mul3 = 1; for (var i4 = bitLength / 8 + offset - 1; i4 >= offset; i4--) { result += array[i4] * mul3; mul3 *= 256; } return result; } exports.readUintBE = readUintBE; function readUintLE(bitLength, array, offset) { if (offset === void 0) { offset = 0; } if (bitLength % 8 !== 0) { throw new Error("readUintLE supports only bitLengths divisible by 8"); } if (bitLength / 8 > array.length - offset) { throw new Error("readUintLE: array is too short for the given bitLength"); } var result = 0; var mul3 = 1; for (var i4 = offset; i4 < offset + bitLength / 8; i4++) { result += array[i4] * mul3; mul3 *= 256; } return result; } exports.readUintLE = readUintLE; function writeUintBE(bitLength, value, out, offset) { if (out === void 0) { out = new Uint8Array(bitLength / 8); } if (offset === void 0) { offset = 0; } if (bitLength % 8 !== 0) { throw new Error("writeUintBE supports only bitLengths divisible by 8"); } if (!int_1.isSafeInteger(value)) { throw new Error("writeUintBE value must be an integer"); } var div = 1; for (var i4 = bitLength / 8 + offset - 1; i4 >= offset; i4--) { out[i4] = value / div & 255; div *= 256; } return out; } exports.writeUintBE = writeUintBE; function writeUintLE(bitLength, value, out, offset) { if (out === void 0) { out = new Uint8Array(bitLength / 8); } if (offset === void 0) { offset = 0; } if (bitLength % 8 !== 0) { throw new Error("writeUintLE supports only bitLengths divisible by 8"); } if (!int_1.isSafeInteger(value)) { throw new Error("writeUintLE value must be an integer"); } var div = 1; for (var i4 = offset; i4 < offset + bitLength / 8; i4++) { out[i4] = value / div & 255; div *= 256; } return out; } exports.writeUintLE = writeUintLE; function readFloat32BE(array, offset) { if (offset === void 0) { offset = 0; } var view = new DataView(array.buffer, array.byteOffset, array.byteLength); return view.getFloat32(offset); } exports.readFloat32BE = readFloat32BE; function readFloat32LE(array, offset) { if (offset === void 0) { offset = 0; } var view = new DataView(array.buffer, array.byteOffset, array.byteLength); return view.getFloat32(offset, true); } exports.readFloat32LE = readFloat32LE; function readFloat64BE(array, offset) { if (offset === void 0) { offset = 0; } var view = new DataView(array.buffer, array.byteOffset, array.byteLength); return view.getFloat64(offset); } exports.readFloat64BE = readFloat64BE; function readFloat64LE(array, offset) { if (offset === void 0) { offset = 0; } var view = new DataView(array.buffer, array.byteOffset, array.byteLength); return view.getFloat64(offset, true); } exports.readFloat64LE = readFloat64LE; function writeFloat32BE(value, out, offset) { if (out === void 0) { out = new Uint8Array(4); } if (offset === void 0) { offset = 0; } var view = new DataView(out.buffer, out.byteOffset, out.byteLength); view.setFloat32(offset, value); return out; } exports.writeFloat32BE = writeFloat32BE; function writeFloat32LE(value, out, offset) { if (out === void 0) { out = new Uint8Array(4); } if (offset === void 0) { offset = 0; } var view = new DataView(out.buffer, out.byteOffset, out.byteLength); view.setFloat32(offset, value, true); return out; } exports.writeFloat32LE = writeFloat32LE; function writeFloat64BE(value, out, offset) { if (out === void 0) { out = new Uint8Array(8); } if (offset === void 0) { offset = 0; } var view = new DataView(out.buffer, out.byteOffset, out.byteLength); view.setFloat64(offset, value); return out; } exports.writeFloat64BE = writeFloat64BE; function writeFloat64LE(value, out, offset) { if (out === void 0) { out = new Uint8Array(8); } if (offset === void 0) { offset = 0; } var view = new DataView(out.buffer, out.byteOffset, out.byteLength); view.setFloat64(offset, value, true); return out; } exports.writeFloat64LE = writeFloat64LE; } }); // node_modules/@stablelib/wipe/lib/wipe.js var require_wipe = __commonJS({ "node_modules/@stablelib/wipe/lib/wipe.js"(exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); function wipe(array) { for (var i4 = 0; i4 < array.length; i4++) { array[i4] = 0; } return array; } exports.wipe = wipe; } }); // node_modules/@stablelib/chacha/lib/chacha.js var require_chacha = __commonJS({ "node_modules/@stablelib/chacha/lib/chacha.js"(exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var binary_1 = require_binary(); var wipe_1 = require_wipe(); var ROUNDS = 20; function core(out, input, key2) { var j0 = 1634760805; var j1 = 857760878; var j2 = 2036477234; var j3 = 1797285236; var j4 = key2[3] << 24 | key2[2] << 16 | key2[1] << 8 | key2[0]; var j5 = key2[7] << 24 | key2[6] << 16 | key2[5] << 8 | key2[4]; var j6 = key2[11] << 24 | key2[10] << 16 | key2[9] << 8 | key2[8]; var j7 = key2[15] << 24 | key2[14] << 16 | key2[13] << 8 | key2[12]; var j8 = key2[19] << 24 | key2[18] << 16 | key2[17] << 8 | key2[16]; var j9 = key2[23] << 24 | key2[22] << 16 | key2[21] << 8 | key2[20]; var j10 = key2[27] << 24 | key2[26] << 16 | key2[25] << 8 | key2[24]; var j11 = key2[31] << 24 | key2[30] << 16 | key2[29] << 8 | key2[28]; var j12 = input[3] << 24 | input[2] << 16 | input[1] << 8 | input[0]; var j13 = input[7] << 24 | input[6] << 16 | input[5] << 8 | input[4]; var j14 = input[11] << 24 | input[10] << 16 | input[9] << 8 | input[8]; var j15 = input[15] << 24 | input[14] << 16 | input[13] << 8 | input[12]; var x0 = j0; var x1 = j1; var x22 = j2; var x32 = j3; var x42 = j4; var x52 = j5; var x6 = j6; var x7 = j7; var x8 = j8; var x9 = j9; var x10 = j10; var x11 = j11; var x12 = j12; var x13 = j13; var x14 = j14; var x15 = j15; for (var i4 = 0; i4 < ROUNDS; i4 += 2) { x0 = x0 + x42 | 0; x12 ^= x0; x12 = x12 >>> 32 - 16 | x12 << 16; x8 = x8 + x12 | 0; x42 ^= x8; x42 = x42 >>> 32 - 12 | x42 << 12; x1 = x1 + x52 | 0; x13 ^= x1; x13 = x13 >>> 32 - 16 | x13 << 16; x9 = x9 + x13 | 0; x52 ^= x9; x52 = x52 >>> 32 - 12 | x52 << 12; x22 = x22 + x6 | 0; x14 ^= x22; x14 = x14 >>> 32 - 16 | x14 << 16; x10 = x10 + x14 | 0; x6 ^= x10; x6 = x6 >>> 32 - 12 | x6 << 12; x32 = x32 + x7 | 0; x15 ^= x32; x15 = x15 >>> 32 - 16 | x15 << 16; x11 = x11 + x15 | 0; x7 ^= x11; x7 = x7 >>> 32 - 12 | x7 << 12; x22 = x22 + x6 | 0; x14 ^= x22; x14 = x14 >>> 32 - 8 | x14 << 8; x10 = x10 + x14 | 0; x6 ^= x10; x6 = x6 >>> 32 - 7 | x6 << 7; x32 = x32 + x7 | 0; x15 ^= x32; x15 = x15 >>> 32 - 8 | x15 << 8; x11 = x11 + x15 | 0; x7 ^= x11; x7 = x7 >>> 32 - 7 | x7 << 7; x1 = x1 + x52 | 0; x13 ^= x1; x13 = x13 >>> 32 - 8 | x13 << 8; x9 = x9 + x13 | 0; x52 ^= x9; x52 = x52 >>> 32 - 7 | x52 << 7; x0 = x0 + x42 | 0; x12 ^= x0; x12 = x12 >>> 32 - 8 | x12 << 8; x8 = x8 + x12 | 0; x42 ^= x8; x42 = x42 >>> 32 - 7 | x42 << 7; x0 = x0 + x52 | 0; x15 ^= x0; x15 = x15 >>> 32 - 16 | x15 << 16; x10 = x10 + x15 | 0; x52 ^= x10; x52 = x52 >>> 32 - 12 | x52 << 12; x1 = x1 + x6 | 0; x12 ^= x1; x12 = x12 >>> 32 - 16 | x12 << 16; x11 = x11 + x12 | 0; x6 ^= x11; x6 = x6 >>> 32 - 12 | x6 << 12; x22 = x22 + x7 | 0; x13 ^= x22; x13 = x13 >>> 32 - 16 | x13 << 16; x8 = x8 + x13 | 0; x7 ^= x8; x7 = x7 >>> 32 - 12 | x7 << 12; x32 = x32 + x42 | 0; x14 ^= x32; x14 = x14 >>> 32 - 16 | x14 << 16; x9 = x9 + x14 | 0; x42 ^= x9; x42 = x42 >>> 32 - 12 | x42 << 12; x22 = x22 + x7 | 0; x13 ^= x22; x13 = x13 >>> 32 - 8 | x13 << 8; x8 = x8 + x13 | 0; x7 ^= x8; x7 = x7 >>> 32 - 7 | x7 << 7; x32 = x32 + x42 | 0; x14 ^= x32; x14 = x14 >>> 32 - 8 | x14 << 8; x9 = x9 + x14 | 0; x42 ^= x9; x42 = x42 >>> 32 - 7 | x42 << 7; x1 = x1 + x6 | 0; x12 ^= x1; x12 = x12 >>> 32 - 8 | x12 << 8; x11 = x11 + x12 | 0; x6 ^= x11; x6 = x6 >>> 32 - 7 | x6 << 7; x0 = x0 + x52 | 0; x15 ^= x0; x15 = x15 >>> 32 - 8 | x15 << 8; x10 = x10 + x15 | 0; x52 ^= x10; x52 = x52 >>> 32 - 7 | x52 << 7; } binary_1.writeUint32LE(x0 + j0 | 0, out, 0); binary_1.writeUint32LE(x1 + j1 | 0, out, 4); binary_1.writeUint32LE(x22 + j2 | 0, out, 8); binary_1.writeUint32LE(x32 + j3 | 0, out, 12); binary_1.writeUint32LE(x42 + j4 | 0, out, 16); binary_1.writeUint32LE(x52 + j5 | 0, out, 20); binary_1.writeUint32LE(x6 + j6 | 0, out, 24); binary_1.writeUint32LE(x7 + j7 | 0, out, 28); binary_1.writeUint32LE(x8 + j8 | 0, out, 32); binary_1.writeUint32LE(x9 + j9 | 0, out, 36); binary_1.writeUint32LE(x10 + j10 | 0, out, 40); binary_1.writeUint32LE(x11 + j11 | 0, out, 44); binary_1.writeUint32LE(x12 + j12 | 0, out, 48); binary_1.writeUint32LE(x13 + j13 | 0, out, 52); binary_1.writeUint32LE(x14 + j14 | 0, out, 56); binary_1.writeUint32LE(x15 + j15 | 0, out, 60); } function streamXOR(key2, nonce, src2, dst, nonceInplaceCounterLength) { if (nonceInplaceCounterLength === void 0) { nonceInplaceCounterLength = 0; } if (key2.length !== 32) { throw new Error("ChaCha: key size must be 32 bytes"); } if (dst.length < src2.length) { throw new Error("ChaCha: destination is shorter than source"); } var nc; var counterLength; if (nonceInplaceCounterLength === 0) { if (nonce.length !== 8 && nonce.length !== 12) { throw new Error("ChaCha nonce must be 8 or 12 bytes"); } nc = new Uint8Array(16); counterLength = nc.length - nonce.length; nc.set(nonce, counterLength); } else { if (nonce.length !== 16) { throw new Error("ChaCha nonce with counter must be 16 bytes"); } nc = nonce; counterLength = nonceInplaceCounterLength; } var block = new Uint8Array(64); for (var i4 = 0; i4 < src2.length; i4 += 64) { core(block, nc, key2); for (var j2 = i4; j2 < i4 + 64 && j2 < src2.length; j2++) { dst[j2] = src2[j2] ^ block[j2 - i4]; } incrementCounter(nc, 0, counterLength); } wipe_1.wipe(block); if (nonceInplaceCounterLength === 0) { wipe_1.wipe(nc); } return dst; } exports.streamXOR = streamXOR; function stream(key2, nonce, dst, nonceInplaceCounterLength) { if (nonceInplaceCounterLength === void 0) { nonceInplaceCounterLength = 0; } wipe_1.wipe(dst); return streamXOR(key2, nonce, dst, dst, nonceInplaceCounterLength); } exports.stream = stream; function incrementCounter(counter, pos, len) { var carry = 1; while (len--) { carry = carry + (counter[pos] & 255) | 0; counter[pos] = carry & 255; carry >>>= 8; pos++; } if (carry > 0) { throw new Error("ChaCha: counter overflow"); } } } }); // node_modules/@stablelib/constant-time/lib/constant-time.js var require_constant_time = __commonJS({ "node_modules/@stablelib/constant-time/lib/constant-time.js"(exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); function select(subject, resultIfOne, resultIfZero) { return ~(subject - 1) & resultIfOne | subject - 1 & resultIfZero; } exports.select = select; function lessOrEqual(a4, b5) { return (a4 | 0) - (b5 | 0) - 1 >>> 31 & 1; } exports.lessOrEqual = lessOrEqual; function compare2(a4, b5) { if (a4.length !== b5.length) { return 0; } var result = 0; for (var i4 = 0; i4 < a4.length; i4++) { result |= a4[i4] ^ b5[i4]; } return 1 & result - 1 >>> 8; } exports.compare = compare2; function equal(a4, b5) { if (a4.length === 0 || b5.length === 0) { return false; } return compare2(a4, b5) !== 0; } exports.equal = equal; } }); // node_modules/@stablelib/poly1305/lib/poly1305.js var require_poly1305 = __commonJS({ "node_modules/@stablelib/poly1305/lib/poly1305.js"(exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var constant_time_1 = require_constant_time(); var wipe_1 = require_wipe(); exports.DIGEST_LENGTH = 16; var Poly1305 = ( /** @class */ function() { function Poly13052(key2) { this.digestLength = exports.DIGEST_LENGTH; this._buffer = new Uint8Array(16); this._r = new Uint16Array(10); this._h = new Uint16Array(10); this._pad = new Uint16Array(8); this._leftover = 0; this._fin = 0; this._finished = false; var t0 = key2[0] | key2[1] << 8; this._r[0] = t0 & 8191; var t1 = key2[2] | key2[3] << 8; this._r[1] = (t0 >>> 13 | t1 << 3) & 8191; var t2 = key2[4] | key2[5] << 8; this._r[2] = (t1 >>> 10 | t2 << 6) & 7939; var t3 = key2[6] | key2[7] << 8; this._r[3] = (t2 >>> 7 | t3 << 9) & 8191; var t4 = key2[8] | key2[9] << 8; this._r[4] = (t3 >>> 4 | t4 << 12) & 255; this._r[5] = t4 >>> 1 & 8190; var t5 = key2[10] | key2[11] << 8; this._r[6] = (t4 >>> 14 | t5 << 2) & 8191; var t6 = key2[12] | key2[13] << 8; this._r[7] = (t5 >>> 11 | t6 << 5) & 8065; var t7 = key2[14] | key2[15] << 8; this._r[8] = (t6 >>> 8 | t7 << 8) & 8191; this._r[9] = t7 >>> 5 & 127; this._pad[0] = key2[16] | key2[17] << 8; this._pad[1] = key2[18] | key2[19] << 8; this._pad[2] = key2[20] | key2[21] << 8; this._pad[3] = key2[22] | key2[23] << 8; this._pad[4] = key2[24] | key2[25] << 8; this._pad[5] = key2[26] | key2[27] << 8; this._pad[6] = key2[28] | key2[29] << 8; this._pad[7] = key2[30] | key2[31] << 8; } Poly13052.prototype._blocks = function(m2, mpos, bytes) { var hibit = this._fin ? 0 : 1 << 11; var h0 = this._h[0], h1 = this._h[1], h22 = this._h[2], h32 = this._h[3], h42 = this._h[4], h5 = this._h[5], h6 = this._h[6], h7 = this._h[7], h8 = this._h[8], h9 = this._h[9]; var r0 = this._r[0], r1 = this._r[1], r22 = this._r[2], r32 = this._r[3], r4 = this._r[4], r5 = this._r[5], r6 = this._r[6], r7 = this._r[7], r8 = this._r[8], r9 = this._r[9]; while (bytes >= 16) { var t0 = m2[mpos + 0] | m2[mpos + 1] << 8; h0 += t0 & 8191; var t1 = m2[mpos + 2] | m2[mpos + 3] << 8; h1 += (t0 >>> 13 | t1 << 3) & 8191; var t2 = m2[mpos + 4] | m2[mpos + 5] << 8; h22 += (t1 >>> 10 | t2 << 6) & 8191; var t3 = m2[mpos + 6] | m2[mpos + 7] << 8; h32 += (t2 >>> 7 | t3 << 9) & 8191; var t4 = m2[mpos + 8] | m2[mpos + 9] << 8; h42 += (t3 >>> 4 | t4 << 12) & 8191; h5 += t4 >>> 1 & 8191; var t5 = m2[mpos + 10] | m2[mpos + 11] << 8; h6 += (t4 >>> 14 | t5 << 2) & 8191; var t6 = m2[mpos + 12] | m2[mpos + 13] << 8; h7 += (t5 >>> 11 | t6 << 5) & 8191; var t7 = m2[mpos + 14] | m2[mpos + 15] << 8; h8 += (t6 >>> 8 | t7 << 8) & 8191; h9 += t7 >>> 5 | hibit; var c5 = 0; var d0 = c5; d0 += h0 * r0; d0 += h1 * (5 * r9); d0 += h22 * (5 * r8); d0 += h32 * (5 * r7); d0 += h42 * (5 * r6); c5 = d0 >>> 13; d0 &= 8191; d0 += h5 * (5 * r5); d0 += h6 * (5 * r4); d0 += h7 * (5 * r32); d0 += h8 * (5 * r22); d0 += h9 * (5 * r1); c5 += d0 >>> 13; d0 &= 8191; var d1 = c5; d1 += h0 * r1; d1 += h1 * r0; d1 += h22 * (5 * r9); d1 += h32 * (5 * r8); d1 += h42 * (5 * r7); c5 = d1 >>> 13; d1 &= 8191; d1 += h5 * (5 * r6); d1 += h6 * (5 * r5); d1 += h7 * (5 * r4); d1 += h8 * (5 * r32); d1 += h9 * (5 * r22); c5 += d1 >>> 13; d1 &= 8191; var d22 = c5; d22 += h0 * r22; d22 += h1 * r1; d22 += h22 * r0; d22 += h32 * (5 * r9); d22 += h42 * (5 * r8); c5 = d22 >>> 13; d22 &= 8191; d22 += h5 * (5 * r7); d22 += h6 * (5 * r6); d22 += h7 * (5 * r5); d22 += h8 * (5 * r4); d22 += h9 * (5 * r32); c5 += d22 >>> 13; d22 &= 8191; var d3 = c5; d3 += h0 * r32; d3 += h1 * r22; d3 += h22 * r1; d3 += h32 * r0; d3 += h42 * (5 * r9); c5 = d3 >>> 13; d3 &= 8191; d3 += h5 * (5 * r8); d3 += h6 * (5 * r7); d3 += h7 * (5 * r6); d3 += h8 * (5 * r5); d3 += h9 * (5 * r4); c5 += d3 >>> 13; d3 &= 8191; var d4 = c5; d4 += h0 * r4; d4 += h1 * r32; d4 += h22 * r22; d4 += h32 * r1; d4 += h42 * r0; c5 = d4 >>> 13; d4 &= 8191; d4 += h5 * (5 * r9); d4 += h6 * (5 * r8); d4 += h7 * (5 * r7); d4 += h8 * (5 * r6); d4 += h9 * (5 * r5); c5 += d4 >>> 13; d4 &= 8191; var d5 = c5; d5 += h0 * r5; d5 += h1 * r4; d5 += h22 * r32; d5 += h32 * r22; d5 += h42 * r1; c5 = d5 >>> 13; d5 &= 8191; d5 += h5 * r0; d5 += h6 * (5 * r9); d5 += h7 * (5 * r8); d5 += h8 * (5 * r7); d5 += h9 * (5 * r6); c5 += d5 >>> 13; d5 &= 8191; var d6 = c5; d6 += h0 * r6; d6 += h1 * r5; d6 += h22 * r4; d6 += h32 * r32; d6 += h42 * r22; c5 = d6 >>> 13; d6 &= 8191; d6 += h5 * r1; d6 += h6 * r0; d6 += h7 * (5 * r9); d6 += h8 * (5 * r8); d6 += h9 * (5 * r7); c5 += d6 >>> 13; d6 &= 8191; var d7 = c5; d7 += h0 * r7; d7 += h1 * r6; d7 += h22 * r5; d7 += h32 * r4; d7 += h42 * r32; c5 = d7 >>> 13; d7 &= 8191; d7 += h5 * r22; d7 += h6 * r1; d7 += h7 * r0; d7 += h8 * (5 * r9); d7 += h9 * (5 * r8); c5 += d7 >>> 13; d7 &= 8191; var d8 = c5; d8 += h0 * r8; d8 += h1 * r7; d8 += h22 * r6; d8 += h32 * r5; d8 += h42 * r4; c5 = d8 >>> 13; d8 &= 8191; d8 += h5 * r32; d8 += h6 * r22; d8 += h7 * r1; d8 += h8 * r0; d8 += h9 * (5 * r9); c5 += d8 >>> 13; d8 &= 8191; var d9 = c5; d9 += h0 * r9; d9 += h1 * r8; d9 += h22 * r7; d9 += h32 * r6; d9 += h42 * r5; c5 = d9 >>> 13; d9 &= 8191; d9 += h5 * r4; d9 += h6 * r32; d9 += h7 * r22; d9 += h8 * r1; d9 += h9 * r0; c5 += d9 >>> 13; d9 &= 8191; c5 = (c5 << 2) + c5 | 0; c5 = c5 + d0 | 0; d0 = c5 & 8191; c5 = c5 >>> 13; d1 += c5; h0 = d0; h1 = d1; h22 = d22; h32 = d3; h42 = d4; h5 = d5; h6 = d6; h7 = d7; h8 = d8; h9 = d9; mpos += 16; bytes -= 16; } this._h[0] = h0; this._h[1] = h1; this._h[2] = h22; this._h[3] = h32; this._h[4] = h42; this._h[5] = h5; this._h[6] = h6; this._h[7] = h7; this._h[8] = h8; this._h[9] = h9; }; Poly13052.prototype.finish = function(mac, macpos) { if (macpos === void 0) { macpos = 0; } var g4 = new Uint16Array(10); var c5; var mask; var f4; var i4; if (this._leftover) { i4 = this._leftover; this._buffer[i4++] = 1; for (; i4 < 16; i4++) { this._buffer[i4] = 0; } this._fin = 1; this._blocks(this._buffer, 0, 16); } c5 = this._h[1] >>> 13; this._h[1] &= 8191; for (i4 = 2; i4 < 10; i4++) { this._h[i4] += c5; c5 = this._h[i4] >>> 13; this._h[i4] &= 8191; } this._h[0] += c5 * 5; c5 = this._h[0] >>> 13; this._h[0] &= 8191; this._h[1] += c5; c5 = this._h[1] >>> 13; this._h[1] &= 8191; this._h[2] += c5; g4[0] = this._h[0] + 5; c5 = g4[0] >>> 13; g4[0] &= 8191; for (i4 = 1; i4 < 10; i4++) { g4[i4] = this._h[i4] + c5; c5 = g4[i4] >>> 13; g4[i4] &= 8191; } g4[9] -= 1 << 13; mask = (c5 ^ 1) - 1; for (i4 = 0; i4 < 10; i4++) { g4[i4] &= mask; } mask = ~mask; for (i4 = 0; i4 < 10; i4++) { this._h[i4] = this._h[i4] & mask | g4[i4]; } this._h[0] = (this._h[0] | this._h[1] << 13) & 65535; this._h[1] = (this._h[1] >>> 3 | this._h[2] << 10) & 65535; this._h[2] = (this._h[2] >>> 6 | this._h[3] << 7) & 65535; this._h[3] = (this._h[3] >>> 9 | this._h[4] << 4) & 65535; this._h[4] = (this._h[4] >>> 12 | this._h[5] << 1 | this._h[6] << 14) & 65535; this._h[5] = (this._h[6] >>> 2 | this._h[7] << 11) & 65535; this._h[6] = (this._h[7] >>> 5 | this._h[8] << 8) & 65535; this._h[7] = (this._h[8] >>> 8 | this._h[9] << 5) & 65535; f4 = this._h[0] + this._pad[0]; this._h[0] = f4 & 65535; for (i4 = 1; i4 < 8; i4++) { f4 = (this._h[i4] + this._pad[i4] | 0) + (f4 >>> 16) | 0; this._h[i4] = f4 & 65535; } mac[macpos + 0] = this._h[0] >>> 0; mac[macpos + 1] = this._h[0] >>> 8; mac[macpos + 2] = this._h[1] >>> 0; mac[macpos + 3] = this._h[1] >>> 8; mac[macpos + 4] = this._h[2] >>> 0; mac[macpos + 5] = this._h[2] >>> 8; mac[macpos + 6] = this._h[3] >>> 0; mac[macpos + 7] = this._h[3] >>> 8; mac[macpos + 8] = this._h[4] >>> 0; mac[macpos + 9] = this._h[4] >>> 8; mac[macpos + 10] = this._h[5] >>> 0; mac[macpos + 11] = this._h[5] >>> 8; mac[macpos + 12] = this._h[6] >>> 0; mac[macpos + 13] = this._h[6] >>> 8; mac[macpos + 14] = this._h[7] >>> 0; mac[macpos + 15] = this._h[7] >>> 8; this._finished = true; return this; }; Poly13052.prototype.update = function(m2) { var mpos = 0; var bytes = m2.length; var want; if (this._leftover) { want = 16 - this._leftover; if (want > bytes) { want = bytes; } for (var i4 = 0; i4 < want; i4++) { this._buffer[this._leftover + i4] = m2[mpos + i4]; } bytes -= want; mpos += want; this._leftover += want; if (this._leftover < 16) { return this; } this._blocks(this._buffer, 0, 16); this._leftover = 0; } if (bytes >= 16) { want = bytes - bytes % 16; this._blocks(m2, mpos, want); mpos += want; bytes -= want; } if (bytes) { for (var i4 = 0; i4 < bytes; i4++) { this._buffer[this._leftover + i4] = m2[mpos + i4]; } this._leftover += bytes; } return this; }; Poly13052.prototype.digest = function() { if (this._finished) { throw new Error("Poly1305 was finished"); } var mac = new Uint8Array(16); this.finish(mac); return mac; }; Poly13052.prototype.clean = function() { wipe_1.wipe(this._buffer); wipe_1.wipe(this._r); wipe_1.wipe(this._h); wipe_1.wipe(this._pad); this._leftover = 0; this._fin = 0; this._finished = true; return this; }; return Poly13052; }() ); exports.Poly1305 = Poly1305; function oneTimeAuth(key2, data) { var h5 = new Poly1305(key2); h5.update(data); var digest2 = h5.digest(); h5.clean(); return digest2; } exports.oneTimeAuth = oneTimeAuth; function equal(a4, b5) { if (a4.length !== exports.DIGEST_LENGTH || b5.length !== exports.DIGEST_LENGTH) { return false; } return constant_time_1.equal(a4, b5); } exports.equal = equal; } }); // node_modules/@stablelib/chacha20poly1305/lib/chacha20poly1305.js var require_chacha20poly1305 = __commonJS({ "node_modules/@stablelib/chacha20poly1305/lib/chacha20poly1305.js"(exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var chacha_1 = require_chacha(); var poly1305_1 = require_poly1305(); var wipe_1 = require_wipe(); var binary_1 = require_binary(); var constant_time_1 = require_constant_time(); exports.KEY_LENGTH = 32; exports.NONCE_LENGTH = 12; exports.TAG_LENGTH = 16; var ZEROS = new Uint8Array(16); var ChaCha20Poly1305 = ( /** @class */ function() { function ChaCha20Poly13052(key2) { this.nonceLength = exports.NONCE_LENGTH; this.tagLength = exports.TAG_LENGTH; if (key2.length !== exports.KEY_LENGTH) { throw new Error("ChaCha20Poly1305 needs 32-byte key"); } this._key = new Uint8Array(key2); } ChaCha20Poly13052.prototype.seal = function(nonce, plaintext, associatedData, dst) { if (nonce.length > 16) { throw new Error("ChaCha20Poly1305: incorrect nonce length"); } var counter = new Uint8Array(16); counter.set(nonce, counter.length - nonce.length); var authKey = new Uint8Array(32); chacha_1.stream(this._key, counter, authKey, 4); var resultLength = plaintext.length + this.tagLength; var result; if (dst) { if (dst.length !== resultLength) { throw new Error("ChaCha20Poly1305: incorrect destination length"); } result = dst; } else { result = new Uint8Array(resultLength); } chacha_1.streamXOR(this._key, counter, plaintext, result, 4); this._authenticate(result.subarray(result.length - this.tagLength, result.length), authKey, result.subarray(0, result.length - this.tagLength), associatedData); wipe_1.wipe(counter); return result; }; ChaCha20Poly13052.prototype.open = function(nonce, sealed, associatedData, dst) { if (nonce.length > 16) { throw new Error("ChaCha20Poly1305: incorrect nonce length"); } if (sealed.length < this.tagLength) { return null; } var counter = new Uint8Array(16); counter.set(nonce, counter.length - nonce.length); var authKey = new Uint8Array(32); chacha_1.stream(this._key, counter, authKey, 4); var calculatedTag = new Uint8Array(this.tagLength); this._authenticate(calculatedTag, authKey, sealed.subarray(0, sealed.length - this.tagLength), associatedData); if (!constant_time_1.equal(calculatedTag, sealed.subarray(sealed.length - this.tagLength, sealed.length))) { return null; } var resultLength = sealed.length - this.tagLength; var result; if (dst) { if (dst.length !== resultLength) { throw new Error("ChaCha20Poly1305: incorrect destination length"); } result = dst; } else { result = new Uint8Array(resultLength); } chacha_1.streamXOR(this._key, counter, sealed.subarray(0, sealed.length - this.tagLength), result, 4); wipe_1.wipe(counter); return result; }; ChaCha20Poly13052.prototype.clean = function() { wipe_1.wipe(this._key); return this; }; ChaCha20Poly13052.prototype._authenticate = function(tagOut, authKey, ciphertext, associatedData) { var h5 = new poly1305_1.Poly1305(authKey); if (associatedData) { h5.update(associatedData); if (associatedData.length % 16 > 0) { h5.update(ZEROS.subarray(associatedData.length % 16)); } } h5.update(ciphertext); if (ciphertext.length % 16 > 0) { h5.update(ZEROS.subarray(ciphertext.length % 16)); } var length2 = new Uint8Array(8); if (associatedData) { binary_1.writeUint64LE(associatedData.length, length2); } h5.update(length2); binary_1.writeUint64LE(ciphertext.length, length2); h5.update(length2); var tag = h5.digest(); for (var i4 = 0; i4 < tag.length; i4++) { tagOut[i4] = tag[i4]; } h5.clean(); wipe_1.wipe(tag); wipe_1.wipe(length2); }; return ChaCha20Poly13052; }() ); exports.ChaCha20Poly1305 = ChaCha20Poly1305; } }); // node_modules/@stablelib/hash/lib/hash.js var require_hash2 = __commonJS({ "node_modules/@stablelib/hash/lib/hash.js"(exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); function isSerializableHash(h5) { return typeof h5.saveState !== "undefined" && typeof h5.restoreState !== "undefined" && typeof h5.cleanSavedState !== "undefined"; } exports.isSerializableHash = isSerializableHash; } }); // node_modules/@stablelib/hmac/lib/hmac.js var require_hmac2 = __commonJS({ "node_modules/@stablelib/hmac/lib/hmac.js"(exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var hash_1 = require_hash2(); var constant_time_1 = require_constant_time(); var wipe_1 = require_wipe(); var HMAC = ( /** @class */ function() { function HMAC2(hash2, key2) { this._finished = false; this._inner = new hash2(); this._outer = new hash2(); this.blockSize = this._outer.blockSize; this.digestLength = this._outer.digestLength; var pad = new Uint8Array(this.blockSize); if (key2.length > this.blockSize) { this._inner.update(key2).finish(pad).clean(); } else { pad.set(key2); } for (var i4 = 0; i4 < pad.length; i4++) { pad[i4] ^= 54; } this._inner.update(pad); for (var i4 = 0; i4 < pad.length; i4++) { pad[i4] ^= 54 ^ 92; } this._outer.update(pad); if (hash_1.isSerializableHash(this._inner) && hash_1.isSerializableHash(this._outer)) { this._innerKeyedState = this._inner.saveState(); this._outerKeyedState = this._outer.saveState(); } wipe_1.wipe(pad); } HMAC2.prototype.reset = function() { if (!hash_1.isSerializableHash(this._inner) || !hash_1.isSerializableHash(this._outer)) { throw new Error("hmac: can't reset() because hash doesn't implement restoreState()"); } this._inner.restoreState(this._innerKeyedState); this._outer.restoreState(this._outerKeyedState); this._finished = false; return this; }; HMAC2.prototype.clean = function() { if (hash_1.isSerializableHash(this._inner)) { this._inner.cleanSavedState(this._innerKeyedState); } if (hash_1.isSerializableHash(this._outer)) { this._outer.cleanSavedState(this._outerKeyedState); } this._inner.clean(); this._outer.clean(); }; HMAC2.prototype.update = function(data) { this._inner.update(data); return this; }; HMAC2.prototype.finish = function(out) { if (this._finished) { this._outer.finish(out); return this; } this._inner.finish(out); this._outer.update(out.subarray(0, this.digestLength)).finish(out); this._finished = true; return this; }; HMAC2.prototype.digest = function() { var out = new Uint8Array(this.digestLength); this.finish(out); return out; }; HMAC2.prototype.saveState = function() { if (!hash_1.isSerializableHash(this._inner)) { throw new Error("hmac: can't saveState() because hash doesn't implement it"); } return this._inner.saveState(); }; HMAC2.prototype.restoreState = function(savedState) { if (!hash_1.isSerializableHash(this._inner) || !hash_1.isSerializableHash(this._outer)) { throw new Error("hmac: can't restoreState() because hash doesn't implement it"); } this._inner.restoreState(savedState); this._outer.restoreState(this._outerKeyedState); this._finished = false; return this; }; HMAC2.prototype.cleanSavedState = function(savedState) { if (!hash_1.isSerializableHash(this._inner)) { throw new Error("hmac: can't cleanSavedState() because hash doesn't implement it"); } this._inner.cleanSavedState(savedState); }; return HMAC2; }() ); exports.HMAC = HMAC; function hmac2(hash2, key2, data) { var h5 = new HMAC(hash2, key2); h5.update(data); var digest2 = h5.digest(); h5.clean(); return digest2; } exports.hmac = hmac2; exports.equal = constant_time_1.equal; } }); // node_modules/@stablelib/hkdf/lib/hkdf.js var require_hkdf = __commonJS({ "node_modules/@stablelib/hkdf/lib/hkdf.js"(exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var hmac_1 = require_hmac2(); var wipe_1 = require_wipe(); var HKDF = ( /** @class */ function() { function HKDF2(hash2, key2, salt, info) { if (salt === void 0) { salt = new Uint8Array(0); } this._counter = new Uint8Array(1); this._hash = hash2; this._info = info; var okm = hmac_1.hmac(this._hash, salt, key2); this._hmac = new hmac_1.HMAC(hash2, okm); this._buffer = new Uint8Array(this._hmac.digestLength); this._bufpos = this._buffer.length; } HKDF2.prototype._fillBuffer = function() { this._counter[0]++; var ctr = this._counter[0]; if (ctr === 0) { throw new Error("hkdf: cannot expand more"); } this._hmac.reset(); if (ctr > 1) { this._hmac.update(this._buffer); } if (this._info) { this._hmac.update(this._info); } this._hmac.update(this._counter); this._hmac.finish(this._buffer); this._bufpos = 0; }; HKDF2.prototype.expand = function(length2) { var out = new Uint8Array(length2); for (var i4 = 0; i4 < out.length; i4++) { if (this._bufpos === this._buffer.length) { this._fillBuffer(); } out[i4] = this._buffer[this._bufpos++]; } return out; }; HKDF2.prototype.clean = function() { this._hmac.clean(); wipe_1.wipe(this._buffer); wipe_1.wipe(this._counter); this._bufpos = 0; }; return HKDF2; }() ); exports.HKDF = HKDF; } }); // node_modules/@stablelib/random/lib/source/browser.js var require_browser = __commonJS({ "node_modules/@stablelib/random/lib/source/browser.js"(exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.BrowserRandomSource = void 0; var QUOTA = 65536; var BrowserRandomSource = class { constructor() { this.isAvailable = false; this.isInstantiated = false; const browserCrypto = typeof self !== "undefined" ? self.crypto || self.msCrypto : null; if (browserCrypto && browserCrypto.getRandomValues !== void 0) { this._crypto = browserCrypto; this.isAvailable = true; this.isInstantiated = true; } } randomBytes(length2) { if (!this.isAvailable || !this._crypto) { throw new Error("Browser random byte generator is not available."); } const out = new Uint8Array(length2); for (let i4 = 0; i4 < out.length; i4 += QUOTA) { this._crypto.getRandomValues(out.subarray(i4, i4 + Math.min(out.length - i4, QUOTA))); } return out; } }; exports.BrowserRandomSource = BrowserRandomSource; } }); // browser-external:crypto var require_crypto = __commonJS({ "browser-external:crypto"(exports, module) { module.exports = Object.create(new Proxy({}, { get(_4, key2) { if (key2 !== "__esModule" && key2 !== "__proto__" && key2 !== "constructor" && key2 !== "splice") { console.warn(`Module "crypto" has been externalized for browser compatibility. Cannot access "crypto.${key2}" in client code. See http://vitejs.dev/guide/troubleshooting.html#module-externalized-for-browser-compatibility for more details.`); } } })); } }); // node_modules/@stablelib/random/lib/source/node.js var require_node = __commonJS({ "node_modules/@stablelib/random/lib/source/node.js"(exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.NodeRandomSource = void 0; var wipe_1 = require_wipe(); var NodeRandomSource = class { constructor() { this.isAvailable = false; this.isInstantiated = false; if (typeof __require !== "undefined") { const nodeCrypto = require_crypto(); if (nodeCrypto && nodeCrypto.randomBytes) { this._crypto = nodeCrypto; this.isAvailable = true; this.isInstantiated = true; } } } randomBytes(length2) { if (!this.isAvailable || !this._crypto) { throw new Error("Node.js random byte generator is not available."); } let buffer = this._crypto.randomBytes(length2); if (buffer.length !== length2) { throw new Error("NodeRandomSource: got fewer bytes than requested"); } const out = new Uint8Array(length2); for (let i4 = 0; i4 < out.length; i4++) { out[i4] = buffer[i4]; } (0, wipe_1.wipe)(buffer); return out; } }; exports.NodeRandomSource = NodeRandomSource; } }); // node_modules/@stablelib/random/lib/source/system.js var require_system = __commonJS({ "node_modules/@stablelib/random/lib/source/system.js"(exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.SystemRandomSource = void 0; var browser_1 = require_browser(); var node_1 = require_node(); var SystemRandomSource = class { constructor() { this.isAvailable = false; this.name = ""; this._source = new browser_1.BrowserRandomSource(); if (this._source.isAvailable) { this.isAvailable = true; this.name = "Browser"; return; } this._source = new node_1.NodeRandomSource(); if (this._source.isAvailable) { this.isAvailable = true; this.name = "Node"; return; } } randomBytes(length2) { if (!this.isAvailable) { throw new Error("System random byte generator is not available."); } return this._source.randomBytes(length2); } }; exports.SystemRandomSource = SystemRandomSource; } }); // node_modules/@stablelib/random/lib/random.js var require_random = __commonJS({ "node_modules/@stablelib/random/lib/random.js"(exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.randomStringForEntropy = exports.randomString = exports.randomUint32 = exports.randomBytes = exports.defaultRandomSource = void 0; var system_1 = require_system(); var binary_1 = require_binary(); var wipe_1 = require_wipe(); exports.defaultRandomSource = new system_1.SystemRandomSource(); function randomBytes2(length2, prng = exports.defaultRandomSource) { return prng.randomBytes(length2); } exports.randomBytes = randomBytes2; function randomUint32(prng = exports.defaultRandomSource) { const buf = randomBytes2(4, prng); const result = (0, binary_1.readUint32LE)(buf); (0, wipe_1.wipe)(buf); return result; } exports.randomUint32 = randomUint32; var ALPHANUMERIC = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"; function randomString(length2, charset = ALPHANUMERIC, prng = exports.defaultRandomSource) { if (charset.length < 2) { throw new Error("randomString charset is too short"); } if (charset.length > 256) { throw new Error("randomString charset is too long"); } let out = ""; const charsLen = charset.length; const maxByte = 256 - 256 % charsLen; while (length2 > 0) { const buf = randomBytes2(Math.ceil(length2 * 256 / maxByte), prng); for (let i4 = 0; i4 < buf.length && length2 > 0; i4++) { const randomByte = buf[i4]; if (randomByte < maxByte) { out += charset.charAt(randomByte % charsLen); length2--; } } (0, wipe_1.wipe)(buf); } return out; } exports.randomString = randomString; function randomStringForEntropy(bits, charset = ALPHANUMERIC, prng = exports.defaultRandomSource) { const length2 = Math.ceil(bits / (Math.log(charset.length) / Math.LN2)); return randomString(length2, charset, prng); } exports.randomStringForEntropy = randomStringForEntropy; } }); // node_modules/@stablelib/sha256/lib/sha256.js var require_sha256 = __commonJS({ "node_modules/@stablelib/sha256/lib/sha256.js"(exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var binary_1 = require_binary(); var wipe_1 = require_wipe(); exports.DIGEST_LENGTH = 32; exports.BLOCK_SIZE = 64; var SHA256 = ( /** @class */ function() { function SHA2562() { this.digestLength = exports.DIGEST_LENGTH; this.blockSize = exports.BLOCK_SIZE; this._state = new Int32Array(8); this._temp = new Int32Array(64); this._buffer = new Uint8Array(128); this._bufferLength = 0; this._bytesHashed = 0; this._finished = false; this.reset(); } SHA2562.prototype._initState = function() { this._state[0] = 1779033703; this._state[1] = 3144134277; this._state[2] = 1013904242; this._state[3] = 2773480762; this._state[4] = 1359893119; this._state[5] = 2600822924; this._state[6] = 528734635; this._state[7] = 1541459225; }; SHA2562.prototype.reset = function() { this._initState(); this._bufferLength = 0; this._bytesHashed = 0; this._finished = false; return this; }; SHA2562.prototype.clean = function() { wipe_1.wipe(this._buffer); wipe_1.wipe(this._temp); this.reset(); }; SHA2562.prototype.update = function(data, dataLength) { if (dataLength === void 0) { dataLength = data.length; } if (this._finished) { throw new Error("SHA256: can't update because hash was finished."); } var dataPos = 0; this._bytesHashed += dataLength; if (this._bufferLength > 0) { while (this._bufferLength < this.blockSize && dataLength > 0) { this._buffer[this._bufferLength++] = data[dataPos++]; dataLength--; } if (this._bufferLength === this.blockSize) { hashBlocks(this._temp, this._state, this._buffer, 0, this.blockSize); this._bufferLength = 0; } } if (dataLength >= this.blockSize) { dataPos = hashBlocks(this._temp, this._state, data, dataPos, dataLength); dataLength %= this.blockSize; } while (dataLength > 0) { this._buffer[this._bufferLength++] = data[dataPos++]; dataLength--; } return this; }; SHA2562.prototype.finish = function(out) { if (!this._finished) { var bytesHashed = this._bytesHashed; var left = this._bufferLength; var bitLenHi = bytesHashed / 536870912 | 0; var bitLenLo = bytesHashed << 3; var padLength = bytesHashed % 64 < 56 ? 64 : 128; this._buffer[left] = 128; for (var i4 = left + 1; i4 < padLength - 8; i4++) { this._buffer[i4] = 0; } binary_1.writeUint32BE(bitLenHi, this._buffer, padLength - 8); binary_1.writeUint32BE(bitLenLo, this._buffer, padLength - 4); hashBlocks(this._temp, this._state, this._buffer, 0, padLength); this._finished = true; } for (var i4 = 0; i4 < this.digestLength / 4; i4++) { binary_1.writeUint32BE(this._state[i4], out, i4 * 4); } return this; }; SHA2562.prototype.digest = function() { var out = new Uint8Array(this.digestLength); this.finish(out); return out; }; SHA2562.prototype.saveState = function() { if (this._finished) { throw new Error("SHA256: cannot save finished state"); } return { state: new Int32Array(this._state), buffer: this._bufferLength > 0 ? new Uint8Array(this._buffer) : void 0, bufferLength: this._bufferLength, bytesHashed: this._bytesHashed }; }; SHA2562.prototype.restoreState = function(savedState) { this._state.set(savedState.state); this._bufferLength = savedState.bufferLength; if (savedState.buffer) { this._buffer.set(savedState.buffer); } this._bytesHashed = savedState.bytesHashed; this._finished = false; return this; }; SHA2562.prototype.cleanSavedState = function(savedState) { wipe_1.wipe(savedState.state); if (savedState.buffer) { wipe_1.wipe(savedState.buffer); } savedState.bufferLength = 0; savedState.bytesHashed = 0; }; return SHA2562; }() ); exports.SHA256 = SHA256; var K3 = new Int32Array([ 1116352408, 1899447441, 3049323471, 3921009573, 961987163, 1508970993, 2453635748, 2870763221, 3624381080, 310598401, 607225278, 1426881987, 1925078388, 2162078206, 2614888103, 3248222580, 3835390401, 4022224774, 264347078, 604807628, 770255983, 1249150122, 1555081692, 1996064986, 2554220882, 2821834349, 2952996808, 3210313671, 3336571891, 3584528711, 113926993, 338241895, 666307205, 773529912, 1294757372, 1396182291, 1695183700, 1986661051, 2177026350, 2456956037, 2730485921, 2820302411, 3259730800, 3345764771, 3516065817, 3600352804, 4094571909, 275423344, 430227734, 506948616, 659060556, 883997877, 958139571, 1322822218, 1537002063, 1747873779, 1955562222, 2024104815, 2227730452, 2361852424, 2428436474, 2756734187, 3204031479, 3329325298 ]); function hashBlocks(w4, v5, p3, pos, len) { while (len >= 64) { var a4 = v5[0]; var b5 = v5[1]; var c5 = v5[2]; var d3 = v5[3]; var e2 = v5[4]; var f4 = v5[5]; var g4 = v5[6]; var h5 = v5[7]; for (var i4 = 0; i4 < 16; i4++) { var j2 = pos + i4 * 4; w4[i4] = binary_1.readUint32BE(p3, j2); } for (var i4 = 16; i4 < 64; i4++) { var u3 = w4[i4 - 2]; var t1 = (u3 >>> 17 | u3 << 32 - 17) ^ (u3 >>> 19 | u3 << 32 - 19) ^ u3 >>> 10; u3 = w4[i4 - 15]; var t2 = (u3 >>> 7 | u3 << 32 - 7) ^ (u3 >>> 18 | u3 << 32 - 18) ^ u3 >>> 3; w4[i4] = (t1 + w4[i4 - 7] | 0) + (t2 + w4[i4 - 16] | 0); } for (var i4 = 0; i4 < 64; i4++) { var t1 = (((e2 >>> 6 | e2 << 32 - 6) ^ (e2 >>> 11 | e2 << 32 - 11) ^ (e2 >>> 25 | e2 << 32 - 25)) + (e2 & f4 ^ ~e2 & g4) | 0) + (h5 + (K3[i4] + w4[i4] | 0) | 0) | 0; var t2 = ((a4 >>> 2 | a4 << 32 - 2) ^ (a4 >>> 13 | a4 << 32 - 13) ^ (a4 >>> 22 | a4 << 32 - 22)) + (a4 & b5 ^ a4 & c5 ^ b5 & c5) | 0; h5 = g4; g4 = f4; f4 = e2; e2 = d3 + t1 | 0; d3 = c5; c5 = b5; b5 = a4; a4 = t1 + t2 | 0; } v5[0] += a4; v5[1] += b5; v5[2] += c5; v5[3] += d3; v5[4] += e2; v5[5] += f4; v5[6] += g4; v5[7] += h5; pos += 64; len -= 64; } return pos; } function hash2(data) { var h5 = new SHA256(); h5.update(data); var digest2 = h5.digest(); h5.clean(); return digest2; } exports.hash = hash2; } }); // node_modules/@stablelib/x25519/lib/x25519.js var require_x25519 = __commonJS({ "node_modules/@stablelib/x25519/lib/x25519.js"(exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.sharedKey = exports.generateKeyPair = exports.generateKeyPairFromSeed = exports.scalarMultBase = exports.scalarMult = exports.SHARED_KEY_LENGTH = exports.SECRET_KEY_LENGTH = exports.PUBLIC_KEY_LENGTH = void 0; var random_1 = require_random(); var wipe_1 = require_wipe(); exports.PUBLIC_KEY_LENGTH = 32; exports.SECRET_KEY_LENGTH = 32; exports.SHARED_KEY_LENGTH = 32; function gf(init2) { const r4 = new Float64Array(16); if (init2) { for (let i4 = 0; i4 < init2.length; i4++) { r4[i4] = init2[i4]; } } return r4; } var _9 = new Uint8Array(32); _9[0] = 9; var _121665 = gf([56129, 1]); function car25519(o4) { let c5 = 1; for (let i4 = 0; i4 < 16; i4++) { let v5 = o4[i4] + c5 + 65535; c5 = Math.floor(v5 / 65536); o4[i4] = v5 - c5 * 65536; } o4[0] += c5 - 1 + 37 * (c5 - 1); } function sel25519(p3, q3, b5) { const c5 = ~(b5 - 1); for (let i4 = 0; i4 < 16; i4++) { const t = c5 & (p3[i4] ^ q3[i4]); p3[i4] ^= t; q3[i4] ^= t; } } function pack25519(o4, n5) { const m2 = gf(); const t = gf(); for (let i4 = 0; i4 < 16; i4++) { t[i4] = n5[i4]; } car25519(t); car25519(t); car25519(t); for (let j2 = 0; j2 < 2; j2++) { m2[0] = t[0] - 65517; for (let i4 = 1; i4 < 15; i4++) { m2[i4] = t[i4] - 65535 - (m2[i4 - 1] >> 16 & 1); m2[i4 - 1] &= 65535; } m2[15] = t[15] - 32767 - (m2[14] >> 16 & 1); const b5 = m2[15] >> 16 & 1; m2[14] &= 65535; sel25519(t, m2, 1 - b5); } for (let i4 = 0; i4 < 16; i4++) { o4[2 * i4] = t[i4] & 255; o4[2 * i4 + 1] = t[i4] >> 8; } } function unpack25519(o4, n5) { for (let i4 = 0; i4 < 16; i4++) { o4[i4] = n5[2 * i4] + (n5[2 * i4 + 1] << 8); } o4[15] &= 32767; } function add3(o4, a4, b5) { for (let i4 = 0; i4 < 16; i4++) { o4[i4] = a4[i4] + b5[i4]; } } function sub(o4, a4, b5) { for (let i4 = 0; i4 < 16; i4++) { o4[i4] = a4[i4] - b5[i4]; } } function mul3(o4, a4, b5) { let v5, c5, t0 = 0, t1 = 0, t2 = 0, t3 = 0, t4 = 0, t5 = 0, t6 = 0, t7 = 0, t8 = 0, t9 = 0, t10 = 0, t11 = 0, t12 = 0, t13 = 0, t14 = 0, t15 = 0, t16 = 0, t17 = 0, t18 = 0, t19 = 0, t20 = 0, t21 = 0, t22 = 0, t23 = 0, t24 = 0, t25 = 0, t26 = 0, t27 = 0, t28 = 0, t29 = 0, t30 = 0, b0 = b5[0], b1 = b5[1], b22 = b5[2], b32 = b5[3], b42 = b5[4], b52 = b5[5], b6 = b5[6], b7 = b5[7], b8 = b5[8], b9 = b5[9], b10 = b5[10], b11 = b5[11], b12 = b5[12], b13 = b5[13], b14 = b5[14], b15 = b5[15]; v5 = a4[0]; t0 += v5 * b0; t1 += v5 * b1; t2 += v5 * b22; t3 += v5 * b32; t4 += v5 * b42; t5 += v5 * b52; t6 += v5 * b6; t7 += v5 * b7; t8 += v5 * b8; t9 += v5 * b9; t10 += v5 * b10; t11 += v5 * b11; t12 += v5 * b12; t13 += v5 * b13; t14 += v5 * b14; t15 += v5 * b15; v5 = a4[1]; t1 += v5 * b0; t2 += v5 * b1; t3 += v5 * b22; t4 += v5 * b32; t5 += v5 * b42; t6 += v5 * b52; t7 += v5 * b6; t8 += v5 * b7; t9 += v5 * b8; t10 += v5 * b9; t11 += v5 * b10; t12 += v5 * b11; t13 += v5 * b12; t14 += v5 * b13; t15 += v5 * b14; t16 += v5 * b15; v5 = a4[2]; t2 += v5 * b0; t3 += v5 * b1; t4 += v5 * b22; t5 += v5 * b32; t6 += v5 * b42; t7 += v5 * b52; t8 += v5 * b6; t9 += v5 * b7; t10 += v5 * b8; t11 += v5 * b9; t12 += v5 * b10; t13 += v5 * b11; t14 += v5 * b12; t15 += v5 * b13; t16 += v5 * b14; t17 += v5 * b15; v5 = a4[3]; t3 += v5 * b0; t4 += v5 * b1; t5 += v5 * b22; t6 += v5 * b32; t7 += v5 * b42; t8 += v5 * b52; t9 += v5 * b6; t10 += v5 * b7; t11 += v5 * b8; t12 += v5 * b9; t13 += v5 * b10; t14 += v5 * b11; t15 += v5 * b12; t16 += v5 * b13; t17 += v5 * b14; t18 += v5 * b15; v5 = a4[4]; t4 += v5 * b0; t5 += v5 * b1; t6 += v5 * b22; t7 += v5 * b32; t8 += v5 * b42; t9 += v5 * b52; t10 += v5 * b6; t11 += v5 * b7; t12 += v5 * b8; t13 += v5 * b9; t14 += v5 * b10; t15 += v5 * b11; t16 += v5 * b12; t17 += v5 * b13; t18 += v5 * b14; t19 += v5 * b15; v5 = a4[5]; t5 += v5 * b0; t6 += v5 * b1; t7 += v5 * b22; t8 += v5 * b32; t9 += v5 * b42; t10 += v5 * b52; t11 += v5 * b6; t12 += v5 * b7; t13 += v5 * b8; t14 += v5 * b9; t15 += v5 * b10; t16 += v5 * b11; t17 += v5 * b12; t18 += v5 * b13; t19 += v5 * b14; t20 += v5 * b15; v5 = a4[6]; t6 += v5 * b0; t7 += v5 * b1; t8 += v5 * b22; t9 += v5 * b32; t10 += v5 * b42; t11 += v5 * b52; t12 += v5 * b6; t13 += v5 * b7; t14 += v5 * b8; t15 += v5 * b9; t16 += v5 * b10; t17 += v5 * b11; t18 += v5 * b12; t19 += v5 * b13; t20 += v5 * b14; t21 += v5 * b15; v5 = a4[7]; t7 += v5 * b0; t8 += v5 * b1; t9 += v5 * b22; t10 += v5 * b32; t11 += v5 * b42; t12 += v5 * b52; t13 += v5 * b6; t14 += v5 * b7; t15 += v5 * b8; t16 += v5 * b9; t17 += v5 * b10; t18 += v5 * b11; t19 += v5 * b12; t20 += v5 * b13; t21 += v5 * b14; t22 += v5 * b15; v5 = a4[8]; t8 += v5 * b0; t9 += v5 * b1; t10 += v5 * b22; t11 += v5 * b32; t12 += v5 * b42; t13 += v5 * b52; t14 += v5 * b6; t15 += v5 * b7; t16 += v5 * b8; t17 += v5 * b9; t18 += v5 * b10; t19 += v5 * b11; t20 += v5 * b12; t21 += v5 * b13; t22 += v5 * b14; t23 += v5 * b15; v5 = a4[9]; t9 += v5 * b0; t10 += v5 * b1; t11 += v5 * b22; t12 += v5 * b32; t13 += v5 * b42; t14 += v5 * b52; t15 += v5 * b6; t16 += v5 * b7; t17 += v5 * b8; t18 += v5 * b9; t19 += v5 * b10; t20 += v5 * b11; t21 += v5 * b12; t22 += v5 * b13; t23 += v5 * b14; t24 += v5 * b15; v5 = a4[10]; t10 += v5 * b0; t11 += v5 * b1; t12 += v5 * b22; t13 += v5 * b32; t14 += v5 * b42; t15 += v5 * b52; t16 += v5 * b6; t17 += v5 * b7; t18 += v5 * b8; t19 += v5 * b9; t20 += v5 * b10; t21 += v5 * b11; t22 += v5 * b12; t23 += v5 * b13; t24 += v5 * b14; t25 += v5 * b15; v5 = a4[11]; t11 += v5 * b0; t12 += v5 * b1; t13 += v5 * b22; t14 += v5 * b32; t15 += v5 * b42; t16 += v5 * b52; t17 += v5 * b6; t18 += v5 * b7; t19 += v5 * b8; t20 += v5 * b9; t21 += v5 * b10; t22 += v5 * b11; t23 += v5 * b12; t24 += v5 * b13; t25 += v5 * b14; t26 += v5 * b15; v5 = a4[12]; t12 += v5 * b0; t13 += v5 * b1; t14 += v5 * b22; t15 += v5 * b32; t16 += v5 * b42; t17 += v5 * b52; t18 += v5 * b6; t19 += v5 * b7; t20 += v5 * b8; t21 += v5 * b9; t22 += v5 * b10; t23 += v5 * b11; t24 += v5 * b12; t25 += v5 * b13; t26 += v5 * b14; t27 += v5 * b15; v5 = a4[13]; t13 += v5 * b0; t14 += v5 * b1; t15 += v5 * b22; t16 += v5 * b32; t17 += v5 * b42; t18 += v5 * b52; t19 += v5 * b6; t20 += v5 * b7; t21 += v5 * b8; t22 += v5 * b9; t23 += v5 * b10; t24 += v5 * b11; t25 += v5 * b12; t26 += v5 * b13; t27 += v5 * b14; t28 += v5 * b15; v5 = a4[14]; t14 += v5 * b0; t15 += v5 * b1; t16 += v5 * b22; t17 += v5 * b32; t18 += v5 * b42; t19 += v5 * b52; t20 += v5 * b6; t21 += v5 * b7; t22 += v5 * b8; t23 += v5 * b9; t24 += v5 * b10; t25 += v5 * b11; t26 += v5 * b12; t27 += v5 * b13; t28 += v5 * b14; t29 += v5 * b15; v5 = a4[15]; t15 += v5 * b0; t16 += v5 * b1; t17 += v5 * b22; t18 += v5 * b32; t19 += v5 * b42; t20 += v5 * b52; t21 += v5 * b6; t22 += v5 * b7; t23 += v5 * b8; t24 += v5 * b9; t25 += v5 * b10; t26 += v5 * b11; t27 += v5 * b12; t28 += v5 * b13; t29 += v5 * b14; t30 += v5 * b15; t0 += 38 * t16; t1 += 38 * t17; t2 += 38 * t18; t3 += 38 * t19; t4 += 38 * t20; t5 += 38 * t21; t6 += 38 * t22; t7 += 38 * t23; t8 += 38 * t24; t9 += 38 * t25; t10 += 38 * t26; t11 += 38 * t27; t12 += 38 * t28; t13 += 38 * t29; t14 += 38 * t30; c5 = 1; v5 = t0 + c5 + 65535; c5 = Math.floor(v5 / 65536); t0 = v5 - c5 * 65536; v5 = t1 + c5 + 65535; c5 = Math.floor(v5 / 65536); t1 = v5 - c5 * 65536; v5 = t2 + c5 + 65535; c5 = Math.floor(v5 / 65536); t2 = v5 - c5 * 65536; v5 = t3 + c5 + 65535; c5 = Math.floor(v5 / 65536); t3 = v5 - c5 * 65536; v5 = t4 + c5 + 65535; c5 = Math.floor(v5 / 65536); t4 = v5 - c5 * 65536; v5 = t5 + c5 + 65535; c5 = Math.floor(v5 / 65536); t5 = v5 - c5 * 65536; v5 = t6 + c5 + 65535; c5 = Math.floor(v5 / 65536); t6 = v5 - c5 * 65536; v5 = t7 + c5 + 65535; c5 = Math.floor(v5 / 65536); t7 = v5 - c5 * 65536; v5 = t8 + c5 + 65535; c5 = Math.floor(v5 / 65536); t8 = v5 - c5 * 65536; v5 = t9 + c5 + 65535; c5 = Math.floor(v5 / 65536); t9 = v5 - c5 * 65536; v5 = t10 + c5 + 65535; c5 = Math.floor(v5 / 65536); t10 = v5 - c5 * 65536; v5 = t11 + c5 + 65535; c5 = Math.floor(v5 / 65536); t11 = v5 - c5 * 65536; v5 = t12 + c5 + 65535; c5 = Math.floor(v5 / 65536); t12 = v5 - c5 * 65536; v5 = t13 + c5 + 65535; c5 = Math.floor(v5 / 65536); t13 = v5 - c5 * 65536; v5 = t14 + c5 + 65535; c5 = Math.floor(v5 / 65536); t14 = v5 - c5 * 65536; v5 = t15 + c5 + 65535; c5 = Math.floor(v5 / 65536); t15 = v5 - c5 * 65536; t0 += c5 - 1 + 37 * (c5 - 1); c5 = 1; v5 = t0 + c5 + 65535; c5 = Math.floor(v5 / 65536); t0 = v5 - c5 * 65536; v5 = t1 + c5 + 65535; c5 = Math.floor(v5 / 65536); t1 = v5 - c5 * 65536; v5 = t2 + c5 + 65535; c5 = Math.floor(v5 / 65536); t2 = v5 - c5 * 65536; v5 = t3 + c5 + 65535; c5 = Math.floor(v5 / 65536); t3 = v5 - c5 * 65536; v5 = t4 + c5 + 65535; c5 = Math.floor(v5 / 65536); t4 = v5 - c5 * 65536; v5 = t5 + c5 + 65535; c5 = Math.floor(v5 / 65536); t5 = v5 - c5 * 65536; v5 = t6 + c5 + 65535; c5 = Math.floor(v5 / 65536); t6 = v5 - c5 * 65536; v5 = t7 + c5 + 65535; c5 = Math.floor(v5 / 65536); t7 = v5 - c5 * 65536; v5 = t8 + c5 + 65535; c5 = Math.floor(v5 / 65536); t8 = v5 - c5 * 65536; v5 = t9 + c5 + 65535; c5 = Math.floor(v5 / 65536); t9 = v5 - c5 * 65536; v5 = t10 + c5 + 65535; c5 = Math.floor(v5 / 65536); t10 = v5 - c5 * 65536; v5 = t11 + c5 + 65535; c5 = Math.floor(v5 / 65536); t11 = v5 - c5 * 65536; v5 = t12 + c5 + 65535; c5 = Math.floor(v5 / 65536); t12 = v5 - c5 * 65536; v5 = t13 + c5 + 65535; c5 = Math.floor(v5 / 65536); t13 = v5 - c5 * 65536; v5 = t14 + c5 + 65535; c5 = Math.floor(v5 / 65536); t14 = v5 - c5 * 65536; v5 = t15 + c5 + 65535; c5 = Math.floor(v5 / 65536); t15 = v5 - c5 * 65536; t0 += c5 - 1 + 37 * (c5 - 1); o4[0] = t0; o4[1] = t1; o4[2] = t2; o4[3] = t3; o4[4] = t4; o4[5] = t5; o4[6] = t6; o4[7] = t7; o4[8] = t8; o4[9] = t9; o4[10] = t10; o4[11] = t11; o4[12] = t12; o4[13] = t13; o4[14] = t14; o4[15] = t15; } function square(o4, a4) { mul3(o4, a4, a4); } function inv25519(o4, inp) { const c5 = gf(); for (let i4 = 0; i4 < 16; i4++) { c5[i4] = inp[i4]; } for (let i4 = 253; i4 >= 0; i4--) { square(c5, c5); if (i4 !== 2 && i4 !== 4) { mul3(c5, c5, inp); } } for (let i4 = 0; i4 < 16; i4++) { o4[i4] = c5[i4]; } } function scalarMult(n5, p3) { const z6 = new Uint8Array(32); const x6 = new Float64Array(80); const a4 = gf(), b5 = gf(), c5 = gf(), d3 = gf(), e2 = gf(), f4 = gf(); for (let i4 = 0; i4 < 31; i4++) { z6[i4] = n5[i4]; } z6[31] = n5[31] & 127 | 64; z6[0] &= 248; unpack25519(x6, p3); for (let i4 = 0; i4 < 16; i4++) { b5[i4] = x6[i4]; } a4[0] = d3[0] = 1; for (let i4 = 254; i4 >= 0; --i4) { const r4 = z6[i4 >>> 3] >>> (i4 & 7) & 1; sel25519(a4, b5, r4); sel25519(c5, d3, r4); add3(e2, a4, c5); sub(a4, a4, c5); add3(c5, b5, d3); sub(b5, b5, d3); square(d3, e2); square(f4, a4); mul3(a4, c5, a4); mul3(c5, b5, e2); add3(e2, a4, c5); sub(a4, a4, c5); square(b5, a4); sub(c5, d3, f4); mul3(a4, c5, _121665); add3(a4, a4, d3); mul3(c5, c5, a4); mul3(a4, d3, f4); mul3(d3, b5, x6); square(b5, e2); sel25519(a4, b5, r4); sel25519(c5, d3, r4); } for (let i4 = 0; i4 < 16; i4++) { x6[i4 + 16] = a4[i4]; x6[i4 + 32] = c5[i4]; x6[i4 + 48] = b5[i4]; x6[i4 + 64] = d3[i4]; } const x32 = x6.subarray(32); const x16 = x6.subarray(16); inv25519(x32, x32); mul3(x16, x16, x32); const q3 = new Uint8Array(32); pack25519(q3, x16); return q3; } exports.scalarMult = scalarMult; function scalarMultBase(n5) { return scalarMult(n5, _9); } exports.scalarMultBase = scalarMultBase; function generateKeyPairFromSeed2(seed) { if (seed.length !== exports.SECRET_KEY_LENGTH) { throw new Error(`x25519: seed must be ${exports.SECRET_KEY_LENGTH} bytes`); } const secretKey = new Uint8Array(seed); const publicKey = scalarMultBase(secretKey); return { publicKey, secretKey }; } exports.generateKeyPairFromSeed = generateKeyPairFromSeed2; function generateKeyPair3(prng) { const seed = (0, random_1.randomBytes)(32, prng); const result = generateKeyPairFromSeed2(seed); (0, wipe_1.wipe)(seed); return result; } exports.generateKeyPair = generateKeyPair3; function sharedKey2(mySecretKey, theirPublicKey, rejectZero = false) { if (mySecretKey.length !== exports.PUBLIC_KEY_LENGTH) { throw new Error("X25519: incorrect secret key length"); } if (theirPublicKey.length !== exports.PUBLIC_KEY_LENGTH) { throw new Error("X25519: incorrect public key length"); } const result = scalarMult(mySecretKey, theirPublicKey); if (rejectZero) { let zeros2 = 0; for (let i4 = 0; i4 < result.length; i4++) { zeros2 |= result[i4]; } if (zeros2 === 0) { throw new Error("X25519: invalid shared key"); } } return result; } exports.sharedKey = sharedKey2; } }); // node_modules/elliptic/package.json var require_package = __commonJS({ "node_modules/elliptic/package.json"(exports, module) { module.exports = { name: "elliptic", version: "6.6.0", description: "EC cryptography", main: "lib/elliptic.js", files: [ "lib" ], scripts: { lint: "eslint lib test", "lint:fix": "npm run lint -- --fix", unit: "istanbul test _mocha --reporter=spec test/index.js", test: "npm run lint && npm run unit", version: "grunt dist && git add dist/" }, repository: { type: "git", url: "git@github.com:indutny/elliptic" }, keywords: [ "EC", "Elliptic", "curve", "Cryptography" ], author: "Fedor Indutny ", license: "MIT", bugs: { url: "https://github.com/indutny/elliptic/issues" }, homepage: "https://github.com/indutny/elliptic", devDependencies: { brfs: "^2.0.2", coveralls: "^3.1.0", eslint: "^7.6.0", grunt: "^1.2.1", "grunt-browserify": "^5.3.0", "grunt-cli": "^1.3.2", "grunt-contrib-connect": "^3.0.0", "grunt-contrib-copy": "^1.0.0", "grunt-contrib-uglify": "^5.0.0", "grunt-mocha-istanbul": "^5.0.2", "grunt-saucelabs": "^9.0.1", istanbul: "^0.4.5", mocha: "^8.0.1" }, dependencies: { "bn.js": "^4.11.9", brorand: "^1.1.0", "hash.js": "^1.0.0", "hmac-drbg": "^1.0.1", inherits: "^2.0.4", "minimalistic-assert": "^1.0.1", "minimalistic-crypto-utils": "^1.0.1" } }; } }); // node_modules/elliptic/node_modules/bn.js/lib/bn.js var require_bn2 = __commonJS({ "node_modules/elliptic/node_modules/bn.js/lib/bn.js"(exports, module) { (function(module2, exports2) { "use strict"; function assert2(val, msg) { if (!val) throw new Error(msg || "Assertion failed"); } function inherits(ctor, superCtor) { ctor.super_ = superCtor; var TempCtor = function() { }; TempCtor.prototype = superCtor.prototype; ctor.prototype = new TempCtor(); ctor.prototype.constructor = ctor; } function BN3(number, base3, endian) { if (BN3.isBN(number)) { return number; } this.negative = 0; this.words = null; this.length = 0; this.red = null; if (number !== null) { if (base3 === "le" || base3 === "be") { endian = base3; base3 = 10; } this._init(number || 0, base3 || 10, endian || "be"); } } if (typeof module2 === "object") { module2.exports = BN3; } else { exports2.BN = BN3; } BN3.BN = BN3; BN3.wordSize = 26; var Buffer2; try { if (typeof window !== "undefined" && typeof window.Buffer !== "undefined") { Buffer2 = window.Buffer; } else { Buffer2 = require_buffer().Buffer; } } catch (e2) { } BN3.isBN = function isBN(num) { if (num instanceof BN3) { return true; } return num !== null && typeof num === "object" && num.constructor.wordSize === BN3.wordSize && Array.isArray(num.words); }; BN3.max = function max(left, right) { if (left.cmp(right) > 0) return left; return right; }; BN3.min = function min(left, right) { if (left.cmp(right) < 0) return left; return right; }; BN3.prototype._init = function init2(number, base3, endian) { if (typeof number === "number") { return this._initNumber(number, base3, endian); } if (typeof number === "object") { return this._initArray(number, base3, endian); } if (base3 === "hex") { base3 = 16; } assert2(base3 === (base3 | 0) && base3 >= 2 && base3 <= 36); number = number.toString().replace(/\s+/g, ""); var start = 0; if (number[0] === "-") { start++; this.negative = 1; } if (start < number.length) { if (base3 === 16) { this._parseHex(number, start, endian); } else { this._parseBase(number, base3, start); if (endian === "le") { this._initArray(this.toArray(), base3, endian); } } } }; BN3.prototype._initNumber = function _initNumber(number, base3, endian) { if (number < 0) { this.negative = 1; number = -number; } if (number < 67108864) { this.words = [number & 67108863]; this.length = 1; } else if (number < 4503599627370496) { this.words = [ number & 67108863, number / 67108864 & 67108863 ]; this.length = 2; } else { assert2(number < 9007199254740992); this.words = [ number & 67108863, number / 67108864 & 67108863, 1 ]; this.length = 3; } if (endian !== "le") return; this._initArray(this.toArray(), base3, endian); }; BN3.prototype._initArray = function _initArray(number, base3, endian) { assert2(typeof number.length === "number"); if (number.length <= 0) { this.words = [0]; this.length = 1; return this; } this.length = Math.ceil(number.length / 3); this.words = new Array(this.length); for (var i4 = 0; i4 < this.length; i4++) { this.words[i4] = 0; } var j2, w4; var off = 0; if (endian === "be") { for (i4 = number.length - 1, j2 = 0; i4 >= 0; i4 -= 3) { w4 = number[i4] | number[i4 - 1] << 8 | number[i4 - 2] << 16; this.words[j2] |= w4 << off & 67108863; this.words[j2 + 1] = w4 >>> 26 - off & 67108863; off += 24; if (off >= 26) { off -= 26; j2++; } } } else if (endian === "le") { for (i4 = 0, j2 = 0; i4 < number.length; i4 += 3) { w4 = number[i4] | number[i4 + 1] << 8 | number[i4 + 2] << 16; this.words[j2] |= w4 << off & 67108863; this.words[j2 + 1] = w4 >>> 26 - off & 67108863; off += 24; if (off >= 26) { off -= 26; j2++; } } } return this.strip(); }; function parseHex4Bits(string2, index) { var c5 = string2.charCodeAt(index); if (c5 >= 65 && c5 <= 70) { return c5 - 55; } else if (c5 >= 97 && c5 <= 102) { return c5 - 87; } else { return c5 - 48 & 15; } } function parseHexByte(string2, lowerBound, index) { var r4 = parseHex4Bits(string2, index); if (index - 1 >= lowerBound) { r4 |= parseHex4Bits(string2, index - 1) << 4; } return r4; } BN3.prototype._parseHex = function _parseHex(number, start, endian) { this.length = Math.ceil((number.length - start) / 6); this.words = new Array(this.length); for (var i4 = 0; i4 < this.length; i4++) { this.words[i4] = 0; } var off = 0; var j2 = 0; var w4; if (endian === "be") { for (i4 = number.length - 1; i4 >= start; i4 -= 2) { w4 = parseHexByte(number, start, i4) << off; this.words[j2] |= w4 & 67108863; if (off >= 18) { off -= 18; j2 += 1; this.words[j2] |= w4 >>> 26; } else { off += 8; } } } else { var parseLength = number.length - start; for (i4 = parseLength % 2 === 0 ? start + 1 : start; i4 < number.length; i4 += 2) { w4 = parseHexByte(number, start, i4) << off; this.words[j2] |= w4 & 67108863; if (off >= 18) { off -= 18; j2 += 1; this.words[j2] |= w4 >>> 26; } else { off += 8; } } } this.strip(); }; function parseBase(str, start, end, mul3) { var r4 = 0; var len = Math.min(str.length, end); for (var i4 = start; i4 < len; i4++) { var c5 = str.charCodeAt(i4) - 48; r4 *= mul3; if (c5 >= 49) { r4 += c5 - 49 + 10; } else if (c5 >= 17) { r4 += c5 - 17 + 10; } else { r4 += c5; } } return r4; } BN3.prototype._parseBase = function _parseBase(number, base3, start) { this.words = [0]; this.length = 1; for (var limbLen = 0, limbPow = 1; limbPow <= 67108863; limbPow *= base3) { limbLen++; } limbLen--; limbPow = limbPow / base3 | 0; var total = number.length - start; var mod = total % limbLen; var end = Math.min(total, total - mod) + start; var word = 0; for (var i4 = start; i4 < end; i4 += limbLen) { word = parseBase(number, i4, i4 + limbLen, base3); this.imuln(limbPow); if (this.words[0] + word < 67108864) { this.words[0] += word; } else { this._iaddn(word); } } if (mod !== 0) { var pow = 1; word = parseBase(number, i4, number.length, base3); for (i4 = 0; i4 < mod; i4++) { pow *= base3; } this.imuln(pow); if (this.words[0] + word < 67108864) { this.words[0] += word; } else { this._iaddn(word); } } this.strip(); }; BN3.prototype.copy = function copy(dest) { dest.words = new Array(this.length); for (var i4 = 0; i4 < this.length; i4++) { dest.words[i4] = this.words[i4]; } dest.length = this.length; dest.negative = this.negative; dest.red = this.red; }; BN3.prototype.clone = function clone() { var r4 = new BN3(null); this.copy(r4); return r4; }; BN3.prototype._expand = function _expand(size) { while (this.length < size) { this.words[this.length++] = 0; } return this; }; BN3.prototype.strip = function strip() { while (this.length > 1 && this.words[this.length - 1] === 0) { this.length--; } return this._normSign(); }; BN3.prototype._normSign = function _normSign() { if (this.length === 1 && this.words[0] === 0) { this.negative = 0; } return this; }; BN3.prototype.inspect = function inspect4() { return (this.red ? ""; }; var zeros2 = [ "", "0", "00", "000", "0000", "00000", "000000", "0000000", "00000000", "000000000", "0000000000", "00000000000", "000000000000", "0000000000000", "00000000000000", "000000000000000", "0000000000000000", "00000000000000000", "000000000000000000", "0000000000000000000", "00000000000000000000", "000000000000000000000", "0000000000000000000000", "00000000000000000000000", "000000000000000000000000", "0000000000000000000000000" ]; var groupSizes = [ 0, 0, 25, 16, 12, 11, 10, 9, 8, 8, 7, 7, 7, 7, 6, 6, 6, 6, 6, 6, 6, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5 ]; var groupBases = [ 0, 0, 33554432, 43046721, 16777216, 48828125, 60466176, 40353607, 16777216, 43046721, 1e7, 19487171, 35831808, 62748517, 7529536, 11390625, 16777216, 24137569, 34012224, 47045881, 64e6, 4084101, 5153632, 6436343, 7962624, 9765625, 11881376, 14348907, 17210368, 20511149, 243e5, 28629151, 33554432, 39135393, 45435424, 52521875, 60466176 ]; BN3.prototype.toString = function toString3(base3, padding2) { base3 = base3 || 10; padding2 = padding2 | 0 || 1; var out; if (base3 === 16 || base3 === "hex") { out = ""; var off = 0; var carry = 0; for (var i4 = 0; i4 < this.length; i4++) { var w4 = this.words[i4]; var word = ((w4 << off | carry) & 16777215).toString(16); carry = w4 >>> 24 - off & 16777215; off += 2; if (off >= 26) { off -= 26; i4--; } if (carry !== 0 || i4 !== this.length - 1) { out = zeros2[6 - word.length] + word + out; } else { out = word + out; } } if (carry !== 0) { out = carry.toString(16) + out; } while (out.length % padding2 !== 0) { out = "0" + out; } if (this.negative !== 0) { out = "-" + out; } return out; } if (base3 === (base3 | 0) && base3 >= 2 && base3 <= 36) { var groupSize = groupSizes[base3]; var groupBase = groupBases[base3]; out = ""; var c5 = this.clone(); c5.negative = 0; while (!c5.isZero()) { var r4 = c5.modn(groupBase).toString(base3); c5 = c5.idivn(groupBase); if (!c5.isZero()) { out = zeros2[groupSize - r4.length] + r4 + out; } else { out = r4 + out; } } if (this.isZero()) { out = "0" + out; } while (out.length % padding2 !== 0) { out = "0" + out; } if (this.negative !== 0) { out = "-" + out; } return out; } assert2(false, "Base should be between 2 and 36"); }; BN3.prototype.toNumber = function toNumber() { var ret = this.words[0]; if (this.length === 2) { ret += this.words[1] * 67108864; } else if (this.length === 3 && this.words[2] === 1) { ret += 4503599627370496 + this.words[1] * 67108864; } else if (this.length > 2) { assert2(false, "Number can only safely store up to 53 bits"); } return this.negative !== 0 ? -ret : ret; }; BN3.prototype.toJSON = function toJSON2() { return this.toString(16); }; BN3.prototype.toBuffer = function toBuffer(endian, length2) { assert2(typeof Buffer2 !== "undefined"); return this.toArrayLike(Buffer2, endian, length2); }; BN3.prototype.toArray = function toArray(endian, length2) { return this.toArrayLike(Array, endian, length2); }; BN3.prototype.toArrayLike = function toArrayLike(ArrayType, endian, length2) { var byteLength = this.byteLength(); var reqLength = length2 || Math.max(1, byteLength); assert2(byteLength <= reqLength, "byte array longer than desired length"); assert2(reqLength > 0, "Requested array length <= 0"); this.strip(); var littleEndian = endian === "le"; var res = new ArrayType(reqLength); var b5, i4; var q3 = this.clone(); if (!littleEndian) { for (i4 = 0; i4 < reqLength - byteLength; i4++) { res[i4] = 0; } for (i4 = 0; !q3.isZero(); i4++) { b5 = q3.andln(255); q3.iushrn(8); res[reqLength - i4 - 1] = b5; } } else { for (i4 = 0; !q3.isZero(); i4++) { b5 = q3.andln(255); q3.iushrn(8); res[i4] = b5; } for (; i4 < reqLength; i4++) { res[i4] = 0; } } return res; }; if (Math.clz32) { BN3.prototype._countBits = function _countBits(w4) { return 32 - Math.clz32(w4); }; } else { BN3.prototype._countBits = function _countBits(w4) { var t = w4; var r4 = 0; if (t >= 4096) { r4 += 13; t >>>= 13; } if (t >= 64) { r4 += 7; t >>>= 7; } if (t >= 8) { r4 += 4; t >>>= 4; } if (t >= 2) { r4 += 2; t >>>= 2; } return r4 + t; }; } BN3.prototype._zeroBits = function _zeroBits(w4) { if (w4 === 0) return 26; var t = w4; var r4 = 0; if ((t & 8191) === 0) { r4 += 13; t >>>= 13; } if ((t & 127) === 0) { r4 += 7; t >>>= 7; } if ((t & 15) === 0) { r4 += 4; t >>>= 4; } if ((t & 3) === 0) { r4 += 2; t >>>= 2; } if ((t & 1) === 0) { r4++; } return r4; }; BN3.prototype.bitLength = function bitLength() { var w4 = this.words[this.length - 1]; var hi2 = this._countBits(w4); return (this.length - 1) * 26 + hi2; }; function toBitArray(num) { var w4 = new Array(num.bitLength()); for (var bit = 0; bit < w4.length; bit++) { var off = bit / 26 | 0; var wbit = bit % 26; w4[bit] = (num.words[off] & 1 << wbit) >>> wbit; } return w4; } BN3.prototype.zeroBits = function zeroBits() { if (this.isZero()) return 0; var r4 = 0; for (var i4 = 0; i4 < this.length; i4++) { var b5 = this._zeroBits(this.words[i4]); r4 += b5; if (b5 !== 26) break; } return r4; }; BN3.prototype.byteLength = function byteLength() { return Math.ceil(this.bitLength() / 8); }; BN3.prototype.toTwos = function toTwos(width) { if (this.negative !== 0) { return this.abs().inotn(width).iaddn(1); } return this.clone(); }; BN3.prototype.fromTwos = function fromTwos(width) { if (this.testn(width - 1)) { return this.notn(width).iaddn(1).ineg(); } return this.clone(); }; BN3.prototype.isNeg = function isNeg() { return this.negative !== 0; }; BN3.prototype.neg = function neg3() { return this.clone().ineg(); }; BN3.prototype.ineg = function ineg() { if (!this.isZero()) { this.negative ^= 1; } return this; }; BN3.prototype.iuor = function iuor(num) { while (this.length < num.length) { this.words[this.length++] = 0; } for (var i4 = 0; i4 < num.length; i4++) { this.words[i4] = this.words[i4] | num.words[i4]; } return this.strip(); }; BN3.prototype.ior = function ior(num) { assert2((this.negative | num.negative) === 0); return this.iuor(num); }; BN3.prototype.or = function or3(num) { if (this.length > num.length) return this.clone().ior(num); return num.clone().ior(this); }; BN3.prototype.uor = function uor(num) { if (this.length > num.length) return this.clone().iuor(num); return num.clone().iuor(this); }; BN3.prototype.iuand = function iuand(num) { var b5; if (this.length > num.length) { b5 = num; } else { b5 = this; } for (var i4 = 0; i4 < b5.length; i4++) { this.words[i4] = this.words[i4] & num.words[i4]; } this.length = b5.length; return this.strip(); }; BN3.prototype.iand = function iand(num) { assert2((this.negative | num.negative) === 0); return this.iuand(num); }; BN3.prototype.and = function and(num) { if (this.length > num.length) return this.clone().iand(num); return num.clone().iand(this); }; BN3.prototype.uand = function uand(num) { if (this.length > num.length) return this.clone().iuand(num); return num.clone().iuand(this); }; BN3.prototype.iuxor = function iuxor(num) { var a4; var b5; if (this.length > num.length) { a4 = this; b5 = num; } else { a4 = num; b5 = this; } for (var i4 = 0; i4 < b5.length; i4++) { this.words[i4] = a4.words[i4] ^ b5.words[i4]; } if (this !== a4) { for (; i4 < a4.length; i4++) { this.words[i4] = a4.words[i4]; } } this.length = a4.length; return this.strip(); }; BN3.prototype.ixor = function ixor(num) { assert2((this.negative | num.negative) === 0); return this.iuxor(num); }; BN3.prototype.xor = function xor2(num) { if (this.length > num.length) return this.clone().ixor(num); return num.clone().ixor(this); }; BN3.prototype.uxor = function uxor(num) { if (this.length > num.length) return this.clone().iuxor(num); return num.clone().iuxor(this); }; BN3.prototype.inotn = function inotn(width) { assert2(typeof width === "number" && width >= 0); var bytesNeeded = Math.ceil(width / 26) | 0; var bitsLeft = width % 26; this._expand(bytesNeeded); if (bitsLeft > 0) { bytesNeeded--; } for (var i4 = 0; i4 < bytesNeeded; i4++) { this.words[i4] = ~this.words[i4] & 67108863; } if (bitsLeft > 0) { this.words[i4] = ~this.words[i4] & 67108863 >> 26 - bitsLeft; } return this.strip(); }; BN3.prototype.notn = function notn(width) { return this.clone().inotn(width); }; BN3.prototype.setn = function setn(bit, val) { assert2(typeof bit === "number" && bit >= 0); var off = bit / 26 | 0; var wbit = bit % 26; this._expand(off + 1); if (val) { this.words[off] = this.words[off] | 1 << wbit; } else { this.words[off] = this.words[off] & ~(1 << wbit); } return this.strip(); }; BN3.prototype.iadd = function iadd(num) { var r4; if (this.negative !== 0 && num.negative === 0) { this.negative = 0; r4 = this.isub(num); this.negative ^= 1; return this._normSign(); } else if (this.negative === 0 && num.negative !== 0) { num.negative = 0; r4 = this.isub(num); num.negative = 1; return r4._normSign(); } var a4, b5; if (this.length > num.length) { a4 = this; b5 = num; } else { a4 = num; b5 = this; } var carry = 0; for (var i4 = 0; i4 < b5.length; i4++) { r4 = (a4.words[i4] | 0) + (b5.words[i4] | 0) + carry; this.words[i4] = r4 & 67108863; carry = r4 >>> 26; } for (; carry !== 0 && i4 < a4.length; i4++) { r4 = (a4.words[i4] | 0) + carry; this.words[i4] = r4 & 67108863; carry = r4 >>> 26; } this.length = a4.length; if (carry !== 0) { this.words[this.length] = carry; this.length++; } else if (a4 !== this) { for (; i4 < a4.length; i4++) { this.words[i4] = a4.words[i4]; } } return this; }; BN3.prototype.add = function add3(num) { var res; if (num.negative !== 0 && this.negative === 0) { num.negative = 0; res = this.sub(num); num.negative ^= 1; return res; } else if (num.negative === 0 && this.negative !== 0) { this.negative = 0; res = num.sub(this); this.negative = 1; return res; } if (this.length > num.length) return this.clone().iadd(num); return num.clone().iadd(this); }; BN3.prototype.isub = function isub(num) { if (num.negative !== 0) { num.negative = 0; var r4 = this.iadd(num); num.negative = 1; return r4._normSign(); } else if (this.negative !== 0) { this.negative = 0; this.iadd(num); this.negative = 1; return this._normSign(); } var cmp = this.cmp(num); if (cmp === 0) { this.negative = 0; this.length = 1; this.words[0] = 0; return this; } var a4, b5; if (cmp > 0) { a4 = this; b5 = num; } else { a4 = num; b5 = this; } var carry = 0; for (var i4 = 0; i4 < b5.length; i4++) { r4 = (a4.words[i4] | 0) - (b5.words[i4] | 0) + carry; carry = r4 >> 26; this.words[i4] = r4 & 67108863; } for (; carry !== 0 && i4 < a4.length; i4++) { r4 = (a4.words[i4] | 0) + carry; carry = r4 >> 26; this.words[i4] = r4 & 67108863; } if (carry === 0 && i4 < a4.length && a4 !== this) { for (; i4 < a4.length; i4++) { this.words[i4] = a4.words[i4]; } } this.length = Math.max(this.length, i4); if (a4 !== this) { this.negative = 1; } return this.strip(); }; BN3.prototype.sub = function sub(num) { return this.clone().isub(num); }; function smallMulTo(self2, num, out) { out.negative = num.negative ^ self2.negative; var len = self2.length + num.length | 0; out.length = len; len = len - 1 | 0; var a4 = self2.words[0] | 0; var b5 = num.words[0] | 0; var r4 = a4 * b5; var lo2 = r4 & 67108863; var carry = r4 / 67108864 | 0; out.words[0] = lo2; for (var k4 = 1; k4 < len; k4++) { var ncarry = carry >>> 26; var rword = carry & 67108863; var maxJ = Math.min(k4, num.length - 1); for (var j2 = Math.max(0, k4 - self2.length + 1); j2 <= maxJ; j2++) { var i4 = k4 - j2 | 0; a4 = self2.words[i4] | 0; b5 = num.words[j2] | 0; r4 = a4 * b5 + rword; ncarry += r4 / 67108864 | 0; rword = r4 & 67108863; } out.words[k4] = rword | 0; carry = ncarry | 0; } if (carry !== 0) { out.words[k4] = carry | 0; } else { out.length--; } return out.strip(); } var comb10MulTo = function comb10MulTo2(self2, num, out) { var a4 = self2.words; var b5 = num.words; var o4 = out.words; var c5 = 0; var lo2; var mid; var hi2; var a0 = a4[0] | 0; var al0 = a0 & 8191; var ah0 = a0 >>> 13; var a1 = a4[1] | 0; var al1 = a1 & 8191; var ah1 = a1 >>> 13; var a22 = a4[2] | 0; var al2 = a22 & 8191; var ah2 = a22 >>> 13; var a32 = a4[3] | 0; var al3 = a32 & 8191; var ah3 = a32 >>> 13; var a42 = a4[4] | 0; var al4 = a42 & 8191; var ah4 = a42 >>> 13; var a5 = a4[5] | 0; var al5 = a5 & 8191; var ah5 = a5 >>> 13; var a6 = a4[6] | 0; var al6 = a6 & 8191; var ah6 = a6 >>> 13; var a7 = a4[7] | 0; var al7 = a7 & 8191; var ah7 = a7 >>> 13; var a8 = a4[8] | 0; var al8 = a8 & 8191; var ah8 = a8 >>> 13; var a9 = a4[9] | 0; var al9 = a9 & 8191; var ah9 = a9 >>> 13; var b0 = b5[0] | 0; var bl0 = b0 & 8191; var bh0 = b0 >>> 13; var b1 = b5[1] | 0; var bl1 = b1 & 8191; var bh1 = b1 >>> 13; var b22 = b5[2] | 0; var bl2 = b22 & 8191; var bh2 = b22 >>> 13; var b32 = b5[3] | 0; var bl3 = b32 & 8191; var bh3 = b32 >>> 13; var b42 = b5[4] | 0; var bl4 = b42 & 8191; var bh4 = b42 >>> 13; var b52 = b5[5] | 0; var bl5 = b52 & 8191; var bh5 = b52 >>> 13; var b6 = b5[6] | 0; var bl6 = b6 & 8191; var bh6 = b6 >>> 13; var b7 = b5[7] | 0; var bl7 = b7 & 8191; var bh7 = b7 >>> 13; var b8 = b5[8] | 0; var bl8 = b8 & 8191; var bh8 = b8 >>> 13; var b9 = b5[9] | 0; var bl9 = b9 & 8191; var bh9 = b9 >>> 13; out.negative = self2.negative ^ num.negative; out.length = 19; lo2 = Math.imul(al0, bl0); mid = Math.imul(al0, bh0); mid = mid + Math.imul(ah0, bl0) | 0; hi2 = Math.imul(ah0, bh0); var w0 = (c5 + lo2 | 0) + ((mid & 8191) << 13) | 0; c5 = (hi2 + (mid >>> 13) | 0) + (w0 >>> 26) | 0; w0 &= 67108863; lo2 = Math.imul(al1, bl0); mid = Math.imul(al1, bh0); mid = mid + Math.imul(ah1, bl0) | 0; hi2 = Math.imul(ah1, bh0); lo2 = lo2 + Math.imul(al0, bl1) | 0; mid = mid + Math.imul(al0, bh1) | 0; mid = mid + Math.imul(ah0, bl1) | 0; hi2 = hi2 + Math.imul(ah0, bh1) | 0; var w1 = (c5 + lo2 | 0) + ((mid & 8191) << 13) | 0; c5 = (hi2 + (mid >>> 13) | 0) + (w1 >>> 26) | 0; w1 &= 67108863; lo2 = Math.imul(al2, bl0); mid = Math.imul(al2, bh0); mid = mid + Math.imul(ah2, bl0) | 0; hi2 = Math.imul(ah2, bh0); lo2 = lo2 + Math.imul(al1, bl1) | 0; mid = mid + Math.imul(al1, bh1) | 0; mid = mid + Math.imul(ah1, bl1) | 0; hi2 = hi2 + Math.imul(ah1, bh1) | 0; lo2 = lo2 + Math.imul(al0, bl2) | 0; mid = mid + Math.imul(al0, bh2) | 0; mid = mid + Math.imul(ah0, bl2) | 0; hi2 = hi2 + Math.imul(ah0, bh2) | 0; var w22 = (c5 + lo2 | 0) + ((mid & 8191) << 13) | 0; c5 = (hi2 + (mid >>> 13) | 0) + (w22 >>> 26) | 0; w22 &= 67108863; lo2 = Math.imul(al3, bl0); mid = Math.imul(al3, bh0); mid = mid + Math.imul(ah3, bl0) | 0; hi2 = Math.imul(ah3, bh0); lo2 = lo2 + Math.imul(al2, bl1) | 0; mid = mid + Math.imul(al2, bh1) | 0; mid = mid + Math.imul(ah2, bl1) | 0; hi2 = hi2 + Math.imul(ah2, bh1) | 0; lo2 = lo2 + Math.imul(al1, bl2) | 0; mid = mid + Math.imul(al1, bh2) | 0; mid = mid + Math.imul(ah1, bl2) | 0; hi2 = hi2 + Math.imul(ah1, bh2) | 0; lo2 = lo2 + Math.imul(al0, bl3) | 0; mid = mid + Math.imul(al0, bh3) | 0; mid = mid + Math.imul(ah0, bl3) | 0; hi2 = hi2 + Math.imul(ah0, bh3) | 0; var w32 = (c5 + lo2 | 0) + ((mid & 8191) << 13) | 0; c5 = (hi2 + (mid >>> 13) | 0) + (w32 >>> 26) | 0; w32 &= 67108863; lo2 = Math.imul(al4, bl0); mid = Math.imul(al4, bh0); mid = mid + Math.imul(ah4, bl0) | 0; hi2 = Math.imul(ah4, bh0); lo2 = lo2 + Math.imul(al3, bl1) | 0; mid = mid + Math.imul(al3, bh1) | 0; mid = mid + Math.imul(ah3, bl1) | 0; hi2 = hi2 + Math.imul(ah3, bh1) | 0; lo2 = lo2 + Math.imul(al2, bl2) | 0; mid = mid + Math.imul(al2, bh2) | 0; mid = mid + Math.imul(ah2, bl2) | 0; hi2 = hi2 + Math.imul(ah2, bh2) | 0; lo2 = lo2 + Math.imul(al1, bl3) | 0; mid = mid + Math.imul(al1, bh3) | 0; mid = mid + Math.imul(ah1, bl3) | 0; hi2 = hi2 + Math.imul(ah1, bh3) | 0; lo2 = lo2 + Math.imul(al0, bl4) | 0; mid = mid + Math.imul(al0, bh4) | 0; mid = mid + Math.imul(ah0, bl4) | 0; hi2 = hi2 + Math.imul(ah0, bh4) | 0; var w4 = (c5 + lo2 | 0) + ((mid & 8191) << 13) | 0; c5 = (hi2 + (mid >>> 13) | 0) + (w4 >>> 26) | 0; w4 &= 67108863; lo2 = Math.imul(al5, bl0); mid = Math.imul(al5, bh0); mid = mid + Math.imul(ah5, bl0) | 0; hi2 = Math.imul(ah5, bh0); lo2 = lo2 + Math.imul(al4, bl1) | 0; mid = mid + Math.imul(al4, bh1) | 0; mid = mid + Math.imul(ah4, bl1) | 0; hi2 = hi2 + Math.imul(ah4, bh1) | 0; lo2 = lo2 + Math.imul(al3, bl2) | 0; mid = mid + Math.imul(al3, bh2) | 0; mid = mid + Math.imul(ah3, bl2) | 0; hi2 = hi2 + Math.imul(ah3, bh2) | 0; lo2 = lo2 + Math.imul(al2, bl3) | 0; mid = mid + Math.imul(al2, bh3) | 0; mid = mid + Math.imul(ah2, bl3) | 0; hi2 = hi2 + Math.imul(ah2, bh3) | 0; lo2 = lo2 + Math.imul(al1, bl4) | 0; mid = mid + Math.imul(al1, bh4) | 0; mid = mid + Math.imul(ah1, bl4) | 0; hi2 = hi2 + Math.imul(ah1, bh4) | 0; lo2 = lo2 + Math.imul(al0, bl5) | 0; mid = mid + Math.imul(al0, bh5) | 0; mid = mid + Math.imul(ah0, bl5) | 0; hi2 = hi2 + Math.imul(ah0, bh5) | 0; var w5 = (c5 + lo2 | 0) + ((mid & 8191) << 13) | 0; c5 = (hi2 + (mid >>> 13) | 0) + (w5 >>> 26) | 0; w5 &= 67108863; lo2 = Math.imul(al6, bl0); mid = Math.imul(al6, bh0); mid = mid + Math.imul(ah6, bl0) | 0; hi2 = Math.imul(ah6, bh0); lo2 = lo2 + Math.imul(al5, bl1) | 0; mid = mid + Math.imul(al5, bh1) | 0; mid = mid + Math.imul(ah5, bl1) | 0; hi2 = hi2 + Math.imul(ah5, bh1) | 0; lo2 = lo2 + Math.imul(al4, bl2) | 0; mid = mid + Math.imul(al4, bh2) | 0; mid = mid + Math.imul(ah4, bl2) | 0; hi2 = hi2 + Math.imul(ah4, bh2) | 0; lo2 = lo2 + Math.imul(al3, bl3) | 0; mid = mid + Math.imul(al3, bh3) | 0; mid = mid + Math.imul(ah3, bl3) | 0; hi2 = hi2 + Math.imul(ah3, bh3) | 0; lo2 = lo2 + Math.imul(al2, bl4) | 0; mid = mid + Math.imul(al2, bh4) | 0; mid = mid + Math.imul(ah2, bl4) | 0; hi2 = hi2 + Math.imul(ah2, bh4) | 0; lo2 = lo2 + Math.imul(al1, bl5) | 0; mid = mid + Math.imul(al1, bh5) | 0; mid = mid + Math.imul(ah1, bl5) | 0; hi2 = hi2 + Math.imul(ah1, bh5) | 0; lo2 = lo2 + Math.imul(al0, bl6) | 0; mid = mid + Math.imul(al0, bh6) | 0; mid = mid + Math.imul(ah0, bl6) | 0; hi2 = hi2 + Math.imul(ah0, bh6) | 0; var w6 = (c5 + lo2 | 0) + ((mid & 8191) << 13) | 0; c5 = (hi2 + (mid >>> 13) | 0) + (w6 >>> 26) | 0; w6 &= 67108863; lo2 = Math.imul(al7, bl0); mid = Math.imul(al7, bh0); mid = mid + Math.imul(ah7, bl0) | 0; hi2 = Math.imul(ah7, bh0); lo2 = lo2 + Math.imul(al6, bl1) | 0; mid = mid + Math.imul(al6, bh1) | 0; mid = mid + Math.imul(ah6, bl1) | 0; hi2 = hi2 + Math.imul(ah6, bh1) | 0; lo2 = lo2 + Math.imul(al5, bl2) | 0; mid = mid + Math.imul(al5, bh2) | 0; mid = mid + Math.imul(ah5, bl2) | 0; hi2 = hi2 + Math.imul(ah5, bh2) | 0; lo2 = lo2 + Math.imul(al4, bl3) | 0; mid = mid + Math.imul(al4, bh3) | 0; mid = mid + Math.imul(ah4, bl3) | 0; hi2 = hi2 + Math.imul(ah4, bh3) | 0; lo2 = lo2 + Math.imul(al3, bl4) | 0; mid = mid + Math.imul(al3, bh4) | 0; mid = mid + Math.imul(ah3, bl4) | 0; hi2 = hi2 + Math.imul(ah3, bh4) | 0; lo2 = lo2 + Math.imul(al2, bl5) | 0; mid = mid + Math.imul(al2, bh5) | 0; mid = mid + Math.imul(ah2, bl5) | 0; hi2 = hi2 + Math.imul(ah2, bh5) | 0; lo2 = lo2 + Math.imul(al1, bl6) | 0; mid = mid + Math.imul(al1, bh6) | 0; mid = mid + Math.imul(ah1, bl6) | 0; hi2 = hi2 + Math.imul(ah1, bh6) | 0; lo2 = lo2 + Math.imul(al0, bl7) | 0; mid = mid + Math.imul(al0, bh7) | 0; mid = mid + Math.imul(ah0, bl7) | 0; hi2 = hi2 + Math.imul(ah0, bh7) | 0; var w7 = (c5 + lo2 | 0) + ((mid & 8191) << 13) | 0; c5 = (hi2 + (mid >>> 13) | 0) + (w7 >>> 26) | 0; w7 &= 67108863; lo2 = Math.imul(al8, bl0); mid = Math.imul(al8, bh0); mid = mid + Math.imul(ah8, bl0) | 0; hi2 = Math.imul(ah8, bh0); lo2 = lo2 + Math.imul(al7, bl1) | 0; mid = mid + Math.imul(al7, bh1) | 0; mid = mid + Math.imul(ah7, bl1) | 0; hi2 = hi2 + Math.imul(ah7, bh1) | 0; lo2 = lo2 + Math.imul(al6, bl2) | 0; mid = mid + Math.imul(al6, bh2) | 0; mid = mid + Math.imul(ah6, bl2) | 0; hi2 = hi2 + Math.imul(ah6, bh2) | 0; lo2 = lo2 + Math.imul(al5, bl3) | 0; mid = mid + Math.imul(al5, bh3) | 0; mid = mid + Math.imul(ah5, bl3) | 0; hi2 = hi2 + Math.imul(ah5, bh3) | 0; lo2 = lo2 + Math.imul(al4, bl4) | 0; mid = mid + Math.imul(al4, bh4) | 0; mid = mid + Math.imul(ah4, bl4) | 0; hi2 = hi2 + Math.imul(ah4, bh4) | 0; lo2 = lo2 + Math.imul(al3, bl5) | 0; mid = mid + Math.imul(al3, bh5) | 0; mid = mid + Math.imul(ah3, bl5) | 0; hi2 = hi2 + Math.imul(ah3, bh5) | 0; lo2 = lo2 + Math.imul(al2, bl6) | 0; mid = mid + Math.imul(al2, bh6) | 0; mid = mid + Math.imul(ah2, bl6) | 0; hi2 = hi2 + Math.imul(ah2, bh6) | 0; lo2 = lo2 + Math.imul(al1, bl7) | 0; mid = mid + Math.imul(al1, bh7) | 0; mid = mid + Math.imul(ah1, bl7) | 0; hi2 = hi2 + Math.imul(ah1, bh7) | 0; lo2 = lo2 + Math.imul(al0, bl8) | 0; mid = mid + Math.imul(al0, bh8) | 0; mid = mid + Math.imul(ah0, bl8) | 0; hi2 = hi2 + Math.imul(ah0, bh8) | 0; var w8 = (c5 + lo2 | 0) + ((mid & 8191) << 13) | 0; c5 = (hi2 + (mid >>> 13) | 0) + (w8 >>> 26) | 0; w8 &= 67108863; lo2 = Math.imul(al9, bl0); mid = Math.imul(al9, bh0); mid = mid + Math.imul(ah9, bl0) | 0; hi2 = Math.imul(ah9, bh0); lo2 = lo2 + Math.imul(al8, bl1) | 0; mid = mid + Math.imul(al8, bh1) | 0; mid = mid + Math.imul(ah8, bl1) | 0; hi2 = hi2 + Math.imul(ah8, bh1) | 0; lo2 = lo2 + Math.imul(al7, bl2) | 0; mid = mid + Math.imul(al7, bh2) | 0; mid = mid + Math.imul(ah7, bl2) | 0; hi2 = hi2 + Math.imul(ah7, bh2) | 0; lo2 = lo2 + Math.imul(al6, bl3) | 0; mid = mid + Math.imul(al6, bh3) | 0; mid = mid + Math.imul(ah6, bl3) | 0; hi2 = hi2 + Math.imul(ah6, bh3) | 0; lo2 = lo2 + Math.imul(al5, bl4) | 0; mid = mid + Math.imul(al5, bh4) | 0; mid = mid + Math.imul(ah5, bl4) | 0; hi2 = hi2 + Math.imul(ah5, bh4) | 0; lo2 = lo2 + Math.imul(al4, bl5) | 0; mid = mid + Math.imul(al4, bh5) | 0; mid = mid + Math.imul(ah4, bl5) | 0; hi2 = hi2 + Math.imul(ah4, bh5) | 0; lo2 = lo2 + Math.imul(al3, bl6) | 0; mid = mid + Math.imul(al3, bh6) | 0; mid = mid + Math.imul(ah3, bl6) | 0; hi2 = hi2 + Math.imul(ah3, bh6) | 0; lo2 = lo2 + Math.imul(al2, bl7) | 0; mid = mid + Math.imul(al2, bh7) | 0; mid = mid + Math.imul(ah2, bl7) | 0; hi2 = hi2 + Math.imul(ah2, bh7) | 0; lo2 = lo2 + Math.imul(al1, bl8) | 0; mid = mid + Math.imul(al1, bh8) | 0; mid = mid + Math.imul(ah1, bl8) | 0; hi2 = hi2 + Math.imul(ah1, bh8) | 0; lo2 = lo2 + Math.imul(al0, bl9) | 0; mid = mid + Math.imul(al0, bh9) | 0; mid = mid + Math.imul(ah0, bl9) | 0; hi2 = hi2 + Math.imul(ah0, bh9) | 0; var w9 = (c5 + lo2 | 0) + ((mid & 8191) << 13) | 0; c5 = (hi2 + (mid >>> 13) | 0) + (w9 >>> 26) | 0; w9 &= 67108863; lo2 = Math.imul(al9, bl1); mid = Math.imul(al9, bh1); mid = mid + Math.imul(ah9, bl1) | 0; hi2 = Math.imul(ah9, bh1); lo2 = lo2 + Math.imul(al8, bl2) | 0; mid = mid + Math.imul(al8, bh2) | 0; mid = mid + Math.imul(ah8, bl2) | 0; hi2 = hi2 + Math.imul(ah8, bh2) | 0; lo2 = lo2 + Math.imul(al7, bl3) | 0; mid = mid + Math.imul(al7, bh3) | 0; mid = mid + Math.imul(ah7, bl3) | 0; hi2 = hi2 + Math.imul(ah7, bh3) | 0; lo2 = lo2 + Math.imul(al6, bl4) | 0; mid = mid + Math.imul(al6, bh4) | 0; mid = mid + Math.imul(ah6, bl4) | 0; hi2 = hi2 + Math.imul(ah6, bh4) | 0; lo2 = lo2 + Math.imul(al5, bl5) | 0; mid = mid + Math.imul(al5, bh5) | 0; mid = mid + Math.imul(ah5, bl5) | 0; hi2 = hi2 + Math.imul(ah5, bh5) | 0; lo2 = lo2 + Math.imul(al4, bl6) | 0; mid = mid + Math.imul(al4, bh6) | 0; mid = mid + Math.imul(ah4, bl6) | 0; hi2 = hi2 + Math.imul(ah4, bh6) | 0; lo2 = lo2 + Math.imul(al3, bl7) | 0; mid = mid + Math.imul(al3, bh7) | 0; mid = mid + Math.imul(ah3, bl7) | 0; hi2 = hi2 + Math.imul(ah3, bh7) | 0; lo2 = lo2 + Math.imul(al2, bl8) | 0; mid = mid + Math.imul(al2, bh8) | 0; mid = mid + Math.imul(ah2, bl8) | 0; hi2 = hi2 + Math.imul(ah2, bh8) | 0; lo2 = lo2 + Math.imul(al1, bl9) | 0; mid = mid + Math.imul(al1, bh9) | 0; mid = mid + Math.imul(ah1, bl9) | 0; hi2 = hi2 + Math.imul(ah1, bh9) | 0; var w10 = (c5 + lo2 | 0) + ((mid & 8191) << 13) | 0; c5 = (hi2 + (mid >>> 13) | 0) + (w10 >>> 26) | 0; w10 &= 67108863; lo2 = Math.imul(al9, bl2); mid = Math.imul(al9, bh2); mid = mid + Math.imul(ah9, bl2) | 0; hi2 = Math.imul(ah9, bh2); lo2 = lo2 + Math.imul(al8, bl3) | 0; mid = mid + Math.imul(al8, bh3) | 0; mid = mid + Math.imul(ah8, bl3) | 0; hi2 = hi2 + Math.imul(ah8, bh3) | 0; lo2 = lo2 + Math.imul(al7, bl4) | 0; mid = mid + Math.imul(al7, bh4) | 0; mid = mid + Math.imul(ah7, bl4) | 0; hi2 = hi2 + Math.imul(ah7, bh4) | 0; lo2 = lo2 + Math.imul(al6, bl5) | 0; mid = mid + Math.imul(al6, bh5) | 0; mid = mid + Math.imul(ah6, bl5) | 0; hi2 = hi2 + Math.imul(ah6, bh5) | 0; lo2 = lo2 + Math.imul(al5, bl6) | 0; mid = mid + Math.imul(al5, bh6) | 0; mid = mid + Math.imul(ah5, bl6) | 0; hi2 = hi2 + Math.imul(ah5, bh6) | 0; lo2 = lo2 + Math.imul(al4, bl7) | 0; mid = mid + Math.imul(al4, bh7) | 0; mid = mid + Math.imul(ah4, bl7) | 0; hi2 = hi2 + Math.imul(ah4, bh7) | 0; lo2 = lo2 + Math.imul(al3, bl8) | 0; mid = mid + Math.imul(al3, bh8) | 0; mid = mid + Math.imul(ah3, bl8) | 0; hi2 = hi2 + Math.imul(ah3, bh8) | 0; lo2 = lo2 + Math.imul(al2, bl9) | 0; mid = mid + Math.imul(al2, bh9) | 0; mid = mid + Math.imul(ah2, bl9) | 0; hi2 = hi2 + Math.imul(ah2, bh9) | 0; var w11 = (c5 + lo2 | 0) + ((mid & 8191) << 13) | 0; c5 = (hi2 + (mid >>> 13) | 0) + (w11 >>> 26) | 0; w11 &= 67108863; lo2 = Math.imul(al9, bl3); mid = Math.imul(al9, bh3); mid = mid + Math.imul(ah9, bl3) | 0; hi2 = Math.imul(ah9, bh3); lo2 = lo2 + Math.imul(al8, bl4) | 0; mid = mid + Math.imul(al8, bh4) | 0; mid = mid + Math.imul(ah8, bl4) | 0; hi2 = hi2 + Math.imul(ah8, bh4) | 0; lo2 = lo2 + Math.imul(al7, bl5) | 0; mid = mid + Math.imul(al7, bh5) | 0; mid = mid + Math.imul(ah7, bl5) | 0; hi2 = hi2 + Math.imul(ah7, bh5) | 0; lo2 = lo2 + Math.imul(al6, bl6) | 0; mid = mid + Math.imul(al6, bh6) | 0; mid = mid + Math.imul(ah6, bl6) | 0; hi2 = hi2 + Math.imul(ah6, bh6) | 0; lo2 = lo2 + Math.imul(al5, bl7) | 0; mid = mid + Math.imul(al5, bh7) | 0; mid = mid + Math.imul(ah5, bl7) | 0; hi2 = hi2 + Math.imul(ah5, bh7) | 0; lo2 = lo2 + Math.imul(al4, bl8) | 0; mid = mid + Math.imul(al4, bh8) | 0; mid = mid + Math.imul(ah4, bl8) | 0; hi2 = hi2 + Math.imul(ah4, bh8) | 0; lo2 = lo2 + Math.imul(al3, bl9) | 0; mid = mid + Math.imul(al3, bh9) | 0; mid = mid + Math.imul(ah3, bl9) | 0; hi2 = hi2 + Math.imul(ah3, bh9) | 0; var w12 = (c5 + lo2 | 0) + ((mid & 8191) << 13) | 0; c5 = (hi2 + (mid >>> 13) | 0) + (w12 >>> 26) | 0; w12 &= 67108863; lo2 = Math.imul(al9, bl4); mid = Math.imul(al9, bh4); mid = mid + Math.imul(ah9, bl4) | 0; hi2 = Math.imul(ah9, bh4); lo2 = lo2 + Math.imul(al8, bl5) | 0; mid = mid + Math.imul(al8, bh5) | 0; mid = mid + Math.imul(ah8, bl5) | 0; hi2 = hi2 + Math.imul(ah8, bh5) | 0; lo2 = lo2 + Math.imul(al7, bl6) | 0; mid = mid + Math.imul(al7, bh6) | 0; mid = mid + Math.imul(ah7, bl6) | 0; hi2 = hi2 + Math.imul(ah7, bh6) | 0; lo2 = lo2 + Math.imul(al6, bl7) | 0; mid = mid + Math.imul(al6, bh7) | 0; mid = mid + Math.imul(ah6, bl7) | 0; hi2 = hi2 + Math.imul(ah6, bh7) | 0; lo2 = lo2 + Math.imul(al5, bl8) | 0; mid = mid + Math.imul(al5, bh8) | 0; mid = mid + Math.imul(ah5, bl8) | 0; hi2 = hi2 + Math.imul(ah5, bh8) | 0; lo2 = lo2 + Math.imul(al4, bl9) | 0; mid = mid + Math.imul(al4, bh9) | 0; mid = mid + Math.imul(ah4, bl9) | 0; hi2 = hi2 + Math.imul(ah4, bh9) | 0; var w13 = (c5 + lo2 | 0) + ((mid & 8191) << 13) | 0; c5 = (hi2 + (mid >>> 13) | 0) + (w13 >>> 26) | 0; w13 &= 67108863; lo2 = Math.imul(al9, bl5); mid = Math.imul(al9, bh5); mid = mid + Math.imul(ah9, bl5) | 0; hi2 = Math.imul(ah9, bh5); lo2 = lo2 + Math.imul(al8, bl6) | 0; mid = mid + Math.imul(al8, bh6) | 0; mid = mid + Math.imul(ah8, bl6) | 0; hi2 = hi2 + Math.imul(ah8, bh6) | 0; lo2 = lo2 + Math.imul(al7, bl7) | 0; mid = mid + Math.imul(al7, bh7) | 0; mid = mid + Math.imul(ah7, bl7) | 0; hi2 = hi2 + Math.imul(ah7, bh7) | 0; lo2 = lo2 + Math.imul(al6, bl8) | 0; mid = mid + Math.imul(al6, bh8) | 0; mid = mid + Math.imul(ah6, bl8) | 0; hi2 = hi2 + Math.imul(ah6, bh8) | 0; lo2 = lo2 + Math.imul(al5, bl9) | 0; mid = mid + Math.imul(al5, bh9) | 0; mid = mid + Math.imul(ah5, bl9) | 0; hi2 = hi2 + Math.imul(ah5, bh9) | 0; var w14 = (c5 + lo2 | 0) + ((mid & 8191) << 13) | 0; c5 = (hi2 + (mid >>> 13) | 0) + (w14 >>> 26) | 0; w14 &= 67108863; lo2 = Math.imul(al9, bl6); mid = Math.imul(al9, bh6); mid = mid + Math.imul(ah9, bl6) | 0; hi2 = Math.imul(ah9, bh6); lo2 = lo2 + Math.imul(al8, bl7) | 0; mid = mid + Math.imul(al8, bh7) | 0; mid = mid + Math.imul(ah8, bl7) | 0; hi2 = hi2 + Math.imul(ah8, bh7) | 0; lo2 = lo2 + Math.imul(al7, bl8) | 0; mid = mid + Math.imul(al7, bh8) | 0; mid = mid + Math.imul(ah7, bl8) | 0; hi2 = hi2 + Math.imul(ah7, bh8) | 0; lo2 = lo2 + Math.imul(al6, bl9) | 0; mid = mid + Math.imul(al6, bh9) | 0; mid = mid + Math.imul(ah6, bl9) | 0; hi2 = hi2 + Math.imul(ah6, bh9) | 0; var w15 = (c5 + lo2 | 0) + ((mid & 8191) << 13) | 0; c5 = (hi2 + (mid >>> 13) | 0) + (w15 >>> 26) | 0; w15 &= 67108863; lo2 = Math.imul(al9, bl7); mid = Math.imul(al9, bh7); mid = mid + Math.imul(ah9, bl7) | 0; hi2 = Math.imul(ah9, bh7); lo2 = lo2 + Math.imul(al8, bl8) | 0; mid = mid + Math.imul(al8, bh8) | 0; mid = mid + Math.imul(ah8, bl8) | 0; hi2 = hi2 + Math.imul(ah8, bh8) | 0; lo2 = lo2 + Math.imul(al7, bl9) | 0; mid = mid + Math.imul(al7, bh9) | 0; mid = mid + Math.imul(ah7, bl9) | 0; hi2 = hi2 + Math.imul(ah7, bh9) | 0; var w16 = (c5 + lo2 | 0) + ((mid & 8191) << 13) | 0; c5 = (hi2 + (mid >>> 13) | 0) + (w16 >>> 26) | 0; w16 &= 67108863; lo2 = Math.imul(al9, bl8); mid = Math.imul(al9, bh8); mid = mid + Math.imul(ah9, bl8) | 0; hi2 = Math.imul(ah9, bh8); lo2 = lo2 + Math.imul(al8, bl9) | 0; mid = mid + Math.imul(al8, bh9) | 0; mid = mid + Math.imul(ah8, bl9) | 0; hi2 = hi2 + Math.imul(ah8, bh9) | 0; var w17 = (c5 + lo2 | 0) + ((mid & 8191) << 13) | 0; c5 = (hi2 + (mid >>> 13) | 0) + (w17 >>> 26) | 0; w17 &= 67108863; lo2 = Math.imul(al9, bl9); mid = Math.imul(al9, bh9); mid = mid + Math.imul(ah9, bl9) | 0; hi2 = Math.imul(ah9, bh9); var w18 = (c5 + lo2 | 0) + ((mid & 8191) << 13) | 0; c5 = (hi2 + (mid >>> 13) | 0) + (w18 >>> 26) | 0; w18 &= 67108863; o4[0] = w0; o4[1] = w1; o4[2] = w22; o4[3] = w32; o4[4] = w4; o4[5] = w5; o4[6] = w6; o4[7] = w7; o4[8] = w8; o4[9] = w9; o4[10] = w10; o4[11] = w11; o4[12] = w12; o4[13] = w13; o4[14] = w14; o4[15] = w15; o4[16] = w16; o4[17] = w17; o4[18] = w18; if (c5 !== 0) { o4[19] = c5; out.length++; } return out; }; if (!Math.imul) { comb10MulTo = smallMulTo; } function bigMulTo(self2, num, out) { out.negative = num.negative ^ self2.negative; out.length = self2.length + num.length; var carry = 0; var hncarry = 0; for (var k4 = 0; k4 < out.length - 1; k4++) { var ncarry = hncarry; hncarry = 0; var rword = carry & 67108863; var maxJ = Math.min(k4, num.length - 1); for (var j2 = Math.max(0, k4 - self2.length + 1); j2 <= maxJ; j2++) { var i4 = k4 - j2; var a4 = self2.words[i4] | 0; var b5 = num.words[j2] | 0; var r4 = a4 * b5; var lo2 = r4 & 67108863; ncarry = ncarry + (r4 / 67108864 | 0) | 0; lo2 = lo2 + rword | 0; rword = lo2 & 67108863; ncarry = ncarry + (lo2 >>> 26) | 0; hncarry += ncarry >>> 26; ncarry &= 67108863; } out.words[k4] = rword; carry = ncarry; ncarry = hncarry; } if (carry !== 0) { out.words[k4] = carry; } else { out.length--; } return out.strip(); } function jumboMulTo(self2, num, out) { var fftm = new FFTM(); return fftm.mulp(self2, num, out); } BN3.prototype.mulTo = function mulTo(num, out) { var res; var len = this.length + num.length; if (this.length === 10 && num.length === 10) { res = comb10MulTo(this, num, out); } else if (len < 63) { res = smallMulTo(this, num, out); } else if (len < 1024) { res = bigMulTo(this, num, out); } else { res = jumboMulTo(this, num, out); } return res; }; function FFTM(x6, y6) { this.x = x6; this.y = y6; } FFTM.prototype.makeRBT = function makeRBT(N11) { var t = new Array(N11); var l4 = BN3.prototype._countBits(N11) - 1; for (var i4 = 0; i4 < N11; i4++) { t[i4] = this.revBin(i4, l4, N11); } return t; }; FFTM.prototype.revBin = function revBin(x6, l4, N11) { if (x6 === 0 || x6 === N11 - 1) return x6; var rb = 0; for (var i4 = 0; i4 < l4; i4++) { rb |= (x6 & 1) << l4 - i4 - 1; x6 >>= 1; } return rb; }; FFTM.prototype.permute = function permute(rbt, rws, iws, rtws, itws, N11) { for (var i4 = 0; i4 < N11; i4++) { rtws[i4] = rws[rbt[i4]]; itws[i4] = iws[rbt[i4]]; } }; FFTM.prototype.transform = function transform(rws, iws, rtws, itws, N11, rbt) { this.permute(rbt, rws, iws, rtws, itws, N11); for (var s3 = 1; s3 < N11; s3 <<= 1) { var l4 = s3 << 1; var rtwdf = Math.cos(2 * Math.PI / l4); var itwdf = Math.sin(2 * Math.PI / l4); for (var p3 = 0; p3 < N11; p3 += l4) { var rtwdf_ = rtwdf; var itwdf_ = itwdf; for (var j2 = 0; j2 < s3; j2++) { var re3 = rtws[p3 + j2]; var ie2 = itws[p3 + j2]; var ro2 = rtws[p3 + j2 + s3]; var io2 = itws[p3 + j2 + s3]; var rx = rtwdf_ * ro2 - itwdf_ * io2; io2 = rtwdf_ * io2 + itwdf_ * ro2; ro2 = rx; rtws[p3 + j2] = re3 + ro2; itws[p3 + j2] = ie2 + io2; rtws[p3 + j2 + s3] = re3 - ro2; itws[p3 + j2 + s3] = ie2 - io2; if (j2 !== l4) { rx = rtwdf * rtwdf_ - itwdf * itwdf_; itwdf_ = rtwdf * itwdf_ + itwdf * rtwdf_; rtwdf_ = rx; } } } } }; FFTM.prototype.guessLen13b = function guessLen13b(n5, m2) { var N11 = Math.max(m2, n5) | 1; var odd = N11 & 1; var i4 = 0; for (N11 = N11 / 2 | 0; N11; N11 = N11 >>> 1) { i4++; } return 1 << i4 + 1 + odd; }; FFTM.prototype.conjugate = function conjugate(rws, iws, N11) { if (N11 <= 1) return; for (var i4 = 0; i4 < N11 / 2; i4++) { var t = rws[i4]; rws[i4] = rws[N11 - i4 - 1]; rws[N11 - i4 - 1] = t; t = iws[i4]; iws[i4] = -iws[N11 - i4 - 1]; iws[N11 - i4 - 1] = -t; } }; FFTM.prototype.normalize13b = function normalize13b(ws2, N11) { var carry = 0; for (var i4 = 0; i4 < N11 / 2; i4++) { var w4 = Math.round(ws2[2 * i4 + 1] / N11) * 8192 + Math.round(ws2[2 * i4] / N11) + carry; ws2[i4] = w4 & 67108863; if (w4 < 67108864) { carry = 0; } else { carry = w4 / 67108864 | 0; } } return ws2; }; FFTM.prototype.convert13b = function convert13b(ws2, len, rws, N11) { var carry = 0; for (var i4 = 0; i4 < len; i4++) { carry = carry + (ws2[i4] | 0); rws[2 * i4] = carry & 8191; carry = carry >>> 13; rws[2 * i4 + 1] = carry & 8191; carry = carry >>> 13; } for (i4 = 2 * len; i4 < N11; ++i4) { rws[i4] = 0; } assert2(carry === 0); assert2((carry & ~8191) === 0); }; FFTM.prototype.stub = function stub(N11) { var ph = new Array(N11); for (var i4 = 0; i4 < N11; i4++) { ph[i4] = 0; } return ph; }; FFTM.prototype.mulp = function mulp(x6, y6, out) { var N11 = 2 * this.guessLen13b(x6.length, y6.length); var rbt = this.makeRBT(N11); var _4 = this.stub(N11); var rws = new Array(N11); var rwst = new Array(N11); var iwst = new Array(N11); var nrws = new Array(N11); var nrwst = new Array(N11); var niwst = new Array(N11); var rmws = out.words; rmws.length = N11; this.convert13b(x6.words, x6.length, rws, N11); this.convert13b(y6.words, y6.length, nrws, N11); this.transform(rws, _4, rwst, iwst, N11, rbt); this.transform(nrws, _4, nrwst, niwst, N11, rbt); for (var i4 = 0; i4 < N11; i4++) { var rx = rwst[i4] * nrwst[i4] - iwst[i4] * niwst[i4]; iwst[i4] = rwst[i4] * niwst[i4] + iwst[i4] * nrwst[i4]; rwst[i4] = rx; } this.conjugate(rwst, iwst, N11); this.transform(rwst, iwst, rmws, _4, N11, rbt); this.conjugate(rmws, _4, N11); this.normalize13b(rmws, N11); out.negative = x6.negative ^ y6.negative; out.length = x6.length + y6.length; return out.strip(); }; BN3.prototype.mul = function mul3(num) { var out = new BN3(null); out.words = new Array(this.length + num.length); return this.mulTo(num, out); }; BN3.prototype.mulf = function mulf(num) { var out = new BN3(null); out.words = new Array(this.length + num.length); return jumboMulTo(this, num, out); }; BN3.prototype.imul = function imul(num) { return this.clone().mulTo(num, this); }; BN3.prototype.imuln = function imuln(num) { assert2(typeof num === "number"); assert2(num < 67108864); var carry = 0; for (var i4 = 0; i4 < this.length; i4++) { var w4 = (this.words[i4] | 0) * num; var lo2 = (w4 & 67108863) + (carry & 67108863); carry >>= 26; carry += w4 / 67108864 | 0; carry += lo2 >>> 26; this.words[i4] = lo2 & 67108863; } if (carry !== 0) { this.words[i4] = carry; this.length++; } return this; }; BN3.prototype.muln = function muln(num) { return this.clone().imuln(num); }; BN3.prototype.sqr = function sqr() { return this.mul(this); }; BN3.prototype.isqr = function isqr() { return this.imul(this.clone()); }; BN3.prototype.pow = function pow(num) { var w4 = toBitArray(num); if (w4.length === 0) return new BN3(1); var res = this; for (var i4 = 0; i4 < w4.length; i4++, res = res.sqr()) { if (w4[i4] !== 0) break; } if (++i4 < w4.length) { for (var q3 = res.sqr(); i4 < w4.length; i4++, q3 = q3.sqr()) { if (w4[i4] === 0) continue; res = res.mul(q3); } } return res; }; BN3.prototype.iushln = function iushln(bits) { assert2(typeof bits === "number" && bits >= 0); var r4 = bits % 26; var s3 = (bits - r4) / 26; var carryMask = 67108863 >>> 26 - r4 << 26 - r4; var i4; if (r4 !== 0) { var carry = 0; for (i4 = 0; i4 < this.length; i4++) { var newCarry = this.words[i4] & carryMask; var c5 = (this.words[i4] | 0) - newCarry << r4; this.words[i4] = c5 | carry; carry = newCarry >>> 26 - r4; } if (carry) { this.words[i4] = carry; this.length++; } } if (s3 !== 0) { for (i4 = this.length - 1; i4 >= 0; i4--) { this.words[i4 + s3] = this.words[i4]; } for (i4 = 0; i4 < s3; i4++) { this.words[i4] = 0; } this.length += s3; } return this.strip(); }; BN3.prototype.ishln = function ishln(bits) { assert2(this.negative === 0); return this.iushln(bits); }; BN3.prototype.iushrn = function iushrn(bits, hint, extended) { assert2(typeof bits === "number" && bits >= 0); var h5; if (hint) { h5 = (hint - hint % 26) / 26; } else { h5 = 0; } var r4 = bits % 26; var s3 = Math.min((bits - r4) / 26, this.length); var mask = 67108863 ^ 67108863 >>> r4 << r4; var maskedWords = extended; h5 -= s3; h5 = Math.max(0, h5); if (maskedWords) { for (var i4 = 0; i4 < s3; i4++) { maskedWords.words[i4] = this.words[i4]; } maskedWords.length = s3; } if (s3 === 0) { } else if (this.length > s3) { this.length -= s3; for (i4 = 0; i4 < this.length; i4++) { this.words[i4] = this.words[i4 + s3]; } } else { this.words[0] = 0; this.length = 1; } var carry = 0; for (i4 = this.length - 1; i4 >= 0 && (carry !== 0 || i4 >= h5); i4--) { var word = this.words[i4] | 0; this.words[i4] = carry << 26 - r4 | word >>> r4; carry = word & mask; } if (maskedWords && carry !== 0) { maskedWords.words[maskedWords.length++] = carry; } if (this.length === 0) { this.words[0] = 0; this.length = 1; } return this.strip(); }; BN3.prototype.ishrn = function ishrn(bits, hint, extended) { assert2(this.negative === 0); return this.iushrn(bits, hint, extended); }; BN3.prototype.shln = function shln(bits) { return this.clone().ishln(bits); }; BN3.prototype.ushln = function ushln(bits) { return this.clone().iushln(bits); }; BN3.prototype.shrn = function shrn(bits) { return this.clone().ishrn(bits); }; BN3.prototype.ushrn = function ushrn(bits) { return this.clone().iushrn(bits); }; BN3.prototype.testn = function testn(bit) { assert2(typeof bit === "number" && bit >= 0); var r4 = bit % 26; var s3 = (bit - r4) / 26; var q3 = 1 << r4; if (this.length <= s3) return false; var w4 = this.words[s3]; return !!(w4 & q3); }; BN3.prototype.imaskn = function imaskn(bits) { assert2(typeof bits === "number" && bits >= 0); var r4 = bits % 26; var s3 = (bits - r4) / 26; assert2(this.negative === 0, "imaskn works only with positive numbers"); if (this.length <= s3) { return this; } if (r4 !== 0) { s3++; } this.length = Math.min(s3, this.length); if (r4 !== 0) { var mask = 67108863 ^ 67108863 >>> r4 << r4; this.words[this.length - 1] &= mask; } return this.strip(); }; BN3.prototype.maskn = function maskn(bits) { return this.clone().imaskn(bits); }; BN3.prototype.iaddn = function iaddn(num) { assert2(typeof num === "number"); assert2(num < 67108864); if (num < 0) return this.isubn(-num); if (this.negative !== 0) { if (this.length === 1 && (this.words[0] | 0) < num) { this.words[0] = num - (this.words[0] | 0); this.negative = 0; return this; } this.negative = 0; this.isubn(num); this.negative = 1; return this; } return this._iaddn(num); }; BN3.prototype._iaddn = function _iaddn(num) { this.words[0] += num; for (var i4 = 0; i4 < this.length && this.words[i4] >= 67108864; i4++) { this.words[i4] -= 67108864; if (i4 === this.length - 1) { this.words[i4 + 1] = 1; } else { this.words[i4 + 1]++; } } this.length = Math.max(this.length, i4 + 1); return this; }; BN3.prototype.isubn = function isubn(num) { assert2(typeof num === "number"); assert2(num < 67108864); if (num < 0) return this.iaddn(-num); if (this.negative !== 0) { this.negative = 0; this.iaddn(num); this.negative = 1; return this; } this.words[0] -= num; if (this.length === 1 && this.words[0] < 0) { this.words[0] = -this.words[0]; this.negative = 1; } else { for (var i4 = 0; i4 < this.length && this.words[i4] < 0; i4++) { this.words[i4] += 67108864; this.words[i4 + 1] -= 1; } } return this.strip(); }; BN3.prototype.addn = function addn(num) { return this.clone().iaddn(num); }; BN3.prototype.subn = function subn(num) { return this.clone().isubn(num); }; BN3.prototype.iabs = function iabs() { this.negative = 0; return this; }; BN3.prototype.abs = function abs() { return this.clone().iabs(); }; BN3.prototype._ishlnsubmul = function _ishlnsubmul(num, mul3, shift) { var len = num.length + shift; var i4; this._expand(len); var w4; var carry = 0; for (i4 = 0; i4 < num.length; i4++) { w4 = (this.words[i4 + shift] | 0) + carry; var right = (num.words[i4] | 0) * mul3; w4 -= right & 67108863; carry = (w4 >> 26) - (right / 67108864 | 0); this.words[i4 + shift] = w4 & 67108863; } for (; i4 < this.length - shift; i4++) { w4 = (this.words[i4 + shift] | 0) + carry; carry = w4 >> 26; this.words[i4 + shift] = w4 & 67108863; } if (carry === 0) return this.strip(); assert2(carry === -1); carry = 0; for (i4 = 0; i4 < this.length; i4++) { w4 = -(this.words[i4] | 0) + carry; carry = w4 >> 26; this.words[i4] = w4 & 67108863; } this.negative = 1; return this.strip(); }; BN3.prototype._wordDiv = function _wordDiv(num, mode) { var shift = this.length - num.length; var a4 = this.clone(); var b5 = num; var bhi = b5.words[b5.length - 1] | 0; var bhiBits = this._countBits(bhi); shift = 26 - bhiBits; if (shift !== 0) { b5 = b5.ushln(shift); a4.iushln(shift); bhi = b5.words[b5.length - 1] | 0; } var m2 = a4.length - b5.length; var q3; if (mode !== "mod") { q3 = new BN3(null); q3.length = m2 + 1; q3.words = new Array(q3.length); for (var i4 = 0; i4 < q3.length; i4++) { q3.words[i4] = 0; } } var diff = a4.clone()._ishlnsubmul(b5, 1, m2); if (diff.negative === 0) { a4 = diff; if (q3) { q3.words[m2] = 1; } } for (var j2 = m2 - 1; j2 >= 0; j2--) { var qj = (a4.words[b5.length + j2] | 0) * 67108864 + (a4.words[b5.length + j2 - 1] | 0); qj = Math.min(qj / bhi | 0, 67108863); a4._ishlnsubmul(b5, qj, j2); while (a4.negative !== 0) { qj--; a4.negative = 0; a4._ishlnsubmul(b5, 1, j2); if (!a4.isZero()) { a4.negative ^= 1; } } if (q3) { q3.words[j2] = qj; } } if (q3) { q3.strip(); } a4.strip(); if (mode !== "div" && shift !== 0) { a4.iushrn(shift); } return { div: q3 || null, mod: a4 }; }; BN3.prototype.divmod = function divmod(num, mode, positive) { assert2(!num.isZero()); if (this.isZero()) { return { div: new BN3(0), mod: new BN3(0) }; } var div, mod, res; if (this.negative !== 0 && num.negative === 0) { res = this.neg().divmod(num, mode); if (mode !== "mod") { div = res.div.neg(); } if (mode !== "div") { mod = res.mod.neg(); if (positive && mod.negative !== 0) { mod.iadd(num); } } return { div, mod }; } if (this.negative === 0 && num.negative !== 0) { res = this.divmod(num.neg(), mode); if (mode !== "mod") { div = res.div.neg(); } return { div, mod: res.mod }; } if ((this.negative & num.negative) !== 0) { res = this.neg().divmod(num.neg(), mode); if (mode !== "div") { mod = res.mod.neg(); if (positive && mod.negative !== 0) { mod.isub(num); } } return { div: res.div, mod }; } if (num.length > this.length || this.cmp(num) < 0) { return { div: new BN3(0), mod: this }; } if (num.length === 1) { if (mode === "div") { return { div: this.divn(num.words[0]), mod: null }; } if (mode === "mod") { return { div: null, mod: new BN3(this.modn(num.words[0])) }; } return { div: this.divn(num.words[0]), mod: new BN3(this.modn(num.words[0])) }; } return this._wordDiv(num, mode); }; BN3.prototype.div = function div(num) { return this.divmod(num, "div", false).div; }; BN3.prototype.mod = function mod(num) { return this.divmod(num, "mod", false).mod; }; BN3.prototype.umod = function umod(num) { return this.divmod(num, "mod", true).mod; }; BN3.prototype.divRound = function divRound(num) { var dm = this.divmod(num); if (dm.mod.isZero()) return dm.div; var mod = dm.div.negative !== 0 ? dm.mod.isub(num) : dm.mod; var half = num.ushrn(1); var r22 = num.andln(1); var cmp = mod.cmp(half); if (cmp < 0 || r22 === 1 && cmp === 0) return dm.div; return dm.div.negative !== 0 ? dm.div.isubn(1) : dm.div.iaddn(1); }; BN3.prototype.modn = function modn(num) { assert2(num <= 67108863); var p3 = (1 << 26) % num; var acc = 0; for (var i4 = this.length - 1; i4 >= 0; i4--) { acc = (p3 * acc + (this.words[i4] | 0)) % num; } return acc; }; BN3.prototype.idivn = function idivn(num) { assert2(num <= 67108863); var carry = 0; for (var i4 = this.length - 1; i4 >= 0; i4--) { var w4 = (this.words[i4] | 0) + carry * 67108864; this.words[i4] = w4 / num | 0; carry = w4 % num; } return this.strip(); }; BN3.prototype.divn = function divn(num) { return this.clone().idivn(num); }; BN3.prototype.egcd = function egcd(p3) { assert2(p3.negative === 0); assert2(!p3.isZero()); var x6 = this; var y6 = p3.clone(); if (x6.negative !== 0) { x6 = x6.umod(p3); } else { x6 = x6.clone(); } var A3 = new BN3(1); var B4 = new BN3(0); var C5 = new BN3(0); var D4 = new BN3(1); var g4 = 0; while (x6.isEven() && y6.isEven()) { x6.iushrn(1); y6.iushrn(1); ++g4; } var yp = y6.clone(); var xp = x6.clone(); while (!x6.isZero()) { for (var i4 = 0, im = 1; (x6.words[0] & im) === 0 && i4 < 26; ++i4, im <<= 1) ; if (i4 > 0) { x6.iushrn(i4); while (i4-- > 0) { if (A3.isOdd() || B4.isOdd()) { A3.iadd(yp); B4.isub(xp); } A3.iushrn(1); B4.iushrn(1); } } for (var j2 = 0, jm = 1; (y6.words[0] & jm) === 0 && j2 < 26; ++j2, jm <<= 1) ; if (j2 > 0) { y6.iushrn(j2); while (j2-- > 0) { if (C5.isOdd() || D4.isOdd()) { C5.iadd(yp); D4.isub(xp); } C5.iushrn(1); D4.iushrn(1); } } if (x6.cmp(y6) >= 0) { x6.isub(y6); A3.isub(C5); B4.isub(D4); } else { y6.isub(x6); C5.isub(A3); D4.isub(B4); } } return { a: C5, b: D4, gcd: y6.iushln(g4) }; }; BN3.prototype._invmp = function _invmp(p3) { assert2(p3.negative === 0); assert2(!p3.isZero()); var a4 = this; var b5 = p3.clone(); if (a4.negative !== 0) { a4 = a4.umod(p3); } else { a4 = a4.clone(); } var x1 = new BN3(1); var x22 = new BN3(0); var delta = b5.clone(); while (a4.cmpn(1) > 0 && b5.cmpn(1) > 0) { for (var i4 = 0, im = 1; (a4.words[0] & im) === 0 && i4 < 26; ++i4, im <<= 1) ; if (i4 > 0) { a4.iushrn(i4); while (i4-- > 0) { if (x1.isOdd()) { x1.iadd(delta); } x1.iushrn(1); } } for (var j2 = 0, jm = 1; (b5.words[0] & jm) === 0 && j2 < 26; ++j2, jm <<= 1) ; if (j2 > 0) { b5.iushrn(j2); while (j2-- > 0) { if (x22.isOdd()) { x22.iadd(delta); } x22.iushrn(1); } } if (a4.cmp(b5) >= 0) { a4.isub(b5); x1.isub(x22); } else { b5.isub(a4); x22.isub(x1); } } var res; if (a4.cmpn(1) === 0) { res = x1; } else { res = x22; } if (res.cmpn(0) < 0) { res.iadd(p3); } return res; }; BN3.prototype.gcd = function gcd(num) { if (this.isZero()) return num.abs(); if (num.isZero()) return this.abs(); var a4 = this.clone(); var b5 = num.clone(); a4.negative = 0; b5.negative = 0; for (var shift = 0; a4.isEven() && b5.isEven(); shift++) { a4.iushrn(1); b5.iushrn(1); } do { while (a4.isEven()) { a4.iushrn(1); } while (b5.isEven()) { b5.iushrn(1); } var r4 = a4.cmp(b5); if (r4 < 0) { var t = a4; a4 = b5; b5 = t; } else if (r4 === 0 || b5.cmpn(1) === 0) { break; } a4.isub(b5); } while (true); return b5.iushln(shift); }; BN3.prototype.invm = function invm(num) { return this.egcd(num).a.umod(num); }; BN3.prototype.isEven = function isEven() { return (this.words[0] & 1) === 0; }; BN3.prototype.isOdd = function isOdd() { return (this.words[0] & 1) === 1; }; BN3.prototype.andln = function andln(num) { return this.words[0] & num; }; BN3.prototype.bincn = function bincn(bit) { assert2(typeof bit === "number"); var r4 = bit % 26; var s3 = (bit - r4) / 26; var q3 = 1 << r4; if (this.length <= s3) { this._expand(s3 + 1); this.words[s3] |= q3; return this; } var carry = q3; for (var i4 = s3; carry !== 0 && i4 < this.length; i4++) { var w4 = this.words[i4] | 0; w4 += carry; carry = w4 >>> 26; w4 &= 67108863; this.words[i4] = w4; } if (carry !== 0) { this.words[i4] = carry; this.length++; } return this; }; BN3.prototype.isZero = function isZero() { return this.length === 1 && this.words[0] === 0; }; BN3.prototype.cmpn = function cmpn(num) { var negative = num < 0; if (this.negative !== 0 && !negative) return -1; if (this.negative === 0 && negative) return 1; this.strip(); var res; if (this.length > 1) { res = 1; } else { if (negative) { num = -num; } assert2(num <= 67108863, "Number is too big"); var w4 = this.words[0] | 0; res = w4 === num ? 0 : w4 < num ? -1 : 1; } if (this.negative !== 0) return -res | 0; return res; }; BN3.prototype.cmp = function cmp(num) { if (this.negative !== 0 && num.negative === 0) return -1; if (this.negative === 0 && num.negative !== 0) return 1; var res = this.ucmp(num); if (this.negative !== 0) return -res | 0; return res; }; BN3.prototype.ucmp = function ucmp(num) { if (this.length > num.length) return 1; if (this.length < num.length) return -1; var res = 0; for (var i4 = this.length - 1; i4 >= 0; i4--) { var a4 = this.words[i4] | 0; var b5 = num.words[i4] | 0; if (a4 === b5) continue; if (a4 < b5) { res = -1; } else if (a4 > b5) { res = 1; } break; } return res; }; BN3.prototype.gtn = function gtn(num) { return this.cmpn(num) === 1; }; BN3.prototype.gt = function gt4(num) { return this.cmp(num) === 1; }; BN3.prototype.gten = function gten(num) { return this.cmpn(num) >= 0; }; BN3.prototype.gte = function gte(num) { return this.cmp(num) >= 0; }; BN3.prototype.ltn = function ltn(num) { return this.cmpn(num) === -1; }; BN3.prototype.lt = function lt3(num) { return this.cmp(num) === -1; }; BN3.prototype.lten = function lten(num) { return this.cmpn(num) <= 0; }; BN3.prototype.lte = function lte(num) { return this.cmp(num) <= 0; }; BN3.prototype.eqn = function eqn(num) { return this.cmpn(num) === 0; }; BN3.prototype.eq = function eq4(num) { return this.cmp(num) === 0; }; BN3.red = function red(num) { return new Red(num); }; BN3.prototype.toRed = function toRed(ctx) { assert2(!this.red, "Already a number in reduction context"); assert2(this.negative === 0, "red works only with positives"); return ctx.convertTo(this)._forceRed(ctx); }; BN3.prototype.fromRed = function fromRed() { assert2(this.red, "fromRed works only with numbers in reduction context"); return this.red.convertFrom(this); }; BN3.prototype._forceRed = function _forceRed(ctx) { this.red = ctx; return this; }; BN3.prototype.forceRed = function forceRed(ctx) { assert2(!this.red, "Already a number in reduction context"); return this._forceRed(ctx); }; BN3.prototype.redAdd = function redAdd(num) { assert2(this.red, "redAdd works only with red numbers"); return this.red.add(this, num); }; BN3.prototype.redIAdd = function redIAdd(num) { assert2(this.red, "redIAdd works only with red numbers"); return this.red.iadd(this, num); }; BN3.prototype.redSub = function redSub(num) { assert2(this.red, "redSub works only with red numbers"); return this.red.sub(this, num); }; BN3.prototype.redISub = function redISub(num) { assert2(this.red, "redISub works only with red numbers"); return this.red.isub(this, num); }; BN3.prototype.redShl = function redShl(num) { assert2(this.red, "redShl works only with red numbers"); return this.red.shl(this, num); }; BN3.prototype.redMul = function redMul(num) { assert2(this.red, "redMul works only with red numbers"); this.red._verify2(this, num); return this.red.mul(this, num); }; BN3.prototype.redIMul = function redIMul(num) { assert2(this.red, "redMul works only with red numbers"); this.red._verify2(this, num); return this.red.imul(this, num); }; BN3.prototype.redSqr = function redSqr() { assert2(this.red, "redSqr works only with red numbers"); this.red._verify1(this); return this.red.sqr(this); }; BN3.prototype.redISqr = function redISqr() { assert2(this.red, "redISqr works only with red numbers"); this.red._verify1(this); return this.red.isqr(this); }; BN3.prototype.redSqrt = function redSqrt() { assert2(this.red, "redSqrt works only with red numbers"); this.red._verify1(this); return this.red.sqrt(this); }; BN3.prototype.redInvm = function redInvm() { assert2(this.red, "redInvm works only with red numbers"); this.red._verify1(this); return this.red.invm(this); }; BN3.prototype.redNeg = function redNeg() { assert2(this.red, "redNeg works only with red numbers"); this.red._verify1(this); return this.red.neg(this); }; BN3.prototype.redPow = function redPow(num) { assert2(this.red && !num.red, "redPow(normalNum)"); this.red._verify1(this); return this.red.pow(this, num); }; var primes = { k256: null, p224: null, p192: null, p25519: null }; function MPrime(name2, p3) { this.name = name2; this.p = new BN3(p3, 16); this.n = this.p.bitLength(); this.k = new BN3(1).iushln(this.n).isub(this.p); this.tmp = this._tmp(); } MPrime.prototype._tmp = function _tmp() { var tmp = new BN3(null); tmp.words = new Array(Math.ceil(this.n / 13)); return tmp; }; MPrime.prototype.ireduce = function ireduce(num) { var r4 = num; var rlen; do { this.split(r4, this.tmp); r4 = this.imulK(r4); r4 = r4.iadd(this.tmp); rlen = r4.bitLength(); } while (rlen > this.n); var cmp = rlen < this.n ? -1 : r4.ucmp(this.p); if (cmp === 0) { r4.words[0] = 0; r4.length = 1; } else if (cmp > 0) { r4.isub(this.p); } else { if (r4.strip !== void 0) { r4.strip(); } else { r4._strip(); } } return r4; }; MPrime.prototype.split = function split(input, out) { input.iushrn(this.n, 0, out); }; MPrime.prototype.imulK = function imulK(num) { return num.imul(this.k); }; function K256() { MPrime.call( this, "k256", "ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffe fffffc2f" ); } inherits(K256, MPrime); K256.prototype.split = function split(input, output) { var mask = 4194303; var outLen = Math.min(input.length, 9); for (var i4 = 0; i4 < outLen; i4++) { output.words[i4] = input.words[i4]; } output.length = outLen; if (input.length <= 9) { input.words[0] = 0; input.length = 1; return; } var prev = input.words[9]; output.words[output.length++] = prev & mask; for (i4 = 10; i4 < input.length; i4++) { var next = input.words[i4] | 0; input.words[i4 - 10] = (next & mask) << 4 | prev >>> 22; prev = next; } prev >>>= 22; input.words[i4 - 10] = prev; if (prev === 0 && input.length > 10) { input.length -= 10; } else { input.length -= 9; } }; K256.prototype.imulK = function imulK(num) { num.words[num.length] = 0; num.words[num.length + 1] = 0; num.length += 2; var lo2 = 0; for (var i4 = 0; i4 < num.length; i4++) { var w4 = num.words[i4] | 0; lo2 += w4 * 977; num.words[i4] = lo2 & 67108863; lo2 = w4 * 64 + (lo2 / 67108864 | 0); } if (num.words[num.length - 1] === 0) { num.length--; if (num.words[num.length - 1] === 0) { num.length--; } } return num; }; function P224() { MPrime.call( this, "p224", "ffffffff ffffffff ffffffff ffffffff 00000000 00000000 00000001" ); } inherits(P224, MPrime); function P192() { MPrime.call( this, "p192", "ffffffff ffffffff ffffffff fffffffe ffffffff ffffffff" ); } inherits(P192, MPrime); function P25519() { MPrime.call( this, "25519", "7fffffffffffffff ffffffffffffffff ffffffffffffffff ffffffffffffffed" ); } inherits(P25519, MPrime); P25519.prototype.imulK = function imulK(num) { var carry = 0; for (var i4 = 0; i4 < num.length; i4++) { var hi2 = (num.words[i4] | 0) * 19 + carry; var lo2 = hi2 & 67108863; hi2 >>>= 26; num.words[i4] = lo2; carry = hi2; } if (carry !== 0) { num.words[num.length++] = carry; } return num; }; BN3._prime = function prime(name2) { if (primes[name2]) return primes[name2]; var prime2; if (name2 === "k256") { prime2 = new K256(); } else if (name2 === "p224") { prime2 = new P224(); } else if (name2 === "p192") { prime2 = new P192(); } else if (name2 === "p25519") { prime2 = new P25519(); } else { throw new Error("Unknown prime " + name2); } primes[name2] = prime2; return prime2; }; function Red(m2) { if (typeof m2 === "string") { var prime = BN3._prime(m2); this.m = prime.p; this.prime = prime; } else { assert2(m2.gtn(1), "modulus must be greater than 1"); this.m = m2; this.prime = null; } } Red.prototype._verify1 = function _verify1(a4) { assert2(a4.negative === 0, "red works only with positives"); assert2(a4.red, "red works only with red numbers"); }; Red.prototype._verify2 = function _verify2(a4, b5) { assert2((a4.negative | b5.negative) === 0, "red works only with positives"); assert2( a4.red && a4.red === b5.red, "red works only with red numbers" ); }; Red.prototype.imod = function imod(a4) { if (this.prime) return this.prime.ireduce(a4)._forceRed(this); return a4.umod(this.m)._forceRed(this); }; Red.prototype.neg = function neg3(a4) { if (a4.isZero()) { return a4.clone(); } return this.m.sub(a4)._forceRed(this); }; Red.prototype.add = function add3(a4, b5) { this._verify2(a4, b5); var res = a4.add(b5); if (res.cmp(this.m) >= 0) { res.isub(this.m); } return res._forceRed(this); }; Red.prototype.iadd = function iadd(a4, b5) { this._verify2(a4, b5); var res = a4.iadd(b5); if (res.cmp(this.m) >= 0) { res.isub(this.m); } return res; }; Red.prototype.sub = function sub(a4, b5) { this._verify2(a4, b5); var res = a4.sub(b5); if (res.cmpn(0) < 0) { res.iadd(this.m); } return res._forceRed(this); }; Red.prototype.isub = function isub(a4, b5) { this._verify2(a4, b5); var res = a4.isub(b5); if (res.cmpn(0) < 0) { res.iadd(this.m); } return res; }; Red.prototype.shl = function shl(a4, num) { this._verify1(a4); return this.imod(a4.ushln(num)); }; Red.prototype.imul = function imul(a4, b5) { this._verify2(a4, b5); return this.imod(a4.imul(b5)); }; Red.prototype.mul = function mul3(a4, b5) { this._verify2(a4, b5); return this.imod(a4.mul(b5)); }; Red.prototype.isqr = function isqr(a4) { return this.imul(a4, a4.clone()); }; Red.prototype.sqr = function sqr(a4) { return this.mul(a4, a4); }; Red.prototype.sqrt = function sqrt(a4) { if (a4.isZero()) return a4.clone(); var mod3 = this.m.andln(3); assert2(mod3 % 2 === 1); if (mod3 === 3) { var pow = this.m.add(new BN3(1)).iushrn(2); return this.pow(a4, pow); } var q3 = this.m.subn(1); var s3 = 0; while (!q3.isZero() && q3.andln(1) === 0) { s3++; q3.iushrn(1); } assert2(!q3.isZero()); var one = new BN3(1).toRed(this); var nOne = one.redNeg(); var lpow = this.m.subn(1).iushrn(1); var z6 = this.m.bitLength(); z6 = new BN3(2 * z6 * z6).toRed(this); while (this.pow(z6, lpow).cmp(nOne) !== 0) { z6.redIAdd(nOne); } var c5 = this.pow(z6, q3); var r4 = this.pow(a4, q3.addn(1).iushrn(1)); var t = this.pow(a4, q3); var m2 = s3; while (t.cmp(one) !== 0) { var tmp = t; for (var i4 = 0; tmp.cmp(one) !== 0; i4++) { tmp = tmp.redSqr(); } assert2(i4 < m2); var b5 = this.pow(c5, new BN3(1).iushln(m2 - i4 - 1)); r4 = r4.redMul(b5); c5 = b5.redSqr(); t = t.redMul(c5); m2 = i4; } return r4; }; Red.prototype.invm = function invm(a4) { var inv = a4._invmp(this.m); if (inv.negative !== 0) { inv.negative = 0; return this.imod(inv).redNeg(); } else { return this.imod(inv); } }; Red.prototype.pow = function pow(a4, num) { if (num.isZero()) return new BN3(1).toRed(this); if (num.cmpn(1) === 0) return a4.clone(); var windowSize = 4; var wnd = new Array(1 << windowSize); wnd[0] = new BN3(1).toRed(this); wnd[1] = a4; for (var i4 = 2; i4 < wnd.length; i4++) { wnd[i4] = this.mul(wnd[i4 - 1], a4); } var res = wnd[0]; var current = 0; var currentLen = 0; var start = num.bitLength() % 26; if (start === 0) { start = 26; } for (i4 = num.length - 1; i4 >= 0; i4--) { var word = num.words[i4]; for (var j2 = start - 1; j2 >= 0; j2--) { var bit = word >> j2 & 1; if (res !== wnd[0]) { res = this.sqr(res); } if (bit === 0 && current === 0) { currentLen = 0; continue; } current <<= 1; current |= bit; currentLen++; if (currentLen !== windowSize && (i4 !== 0 || j2 !== 0)) continue; res = this.mul(res, wnd[current]); currentLen = 0; current = 0; } start = 26; } return res; }; Red.prototype.convertTo = function convertTo(num) { var r4 = num.umod(this.m); return r4 === num ? r4.clone() : r4; }; Red.prototype.convertFrom = function convertFrom(num) { var res = num.clone(); res.red = null; return res; }; BN3.mont = function mont(num) { return new Mont(num); }; function Mont(m2) { Red.call(this, m2); this.shift = this.m.bitLength(); if (this.shift % 26 !== 0) { this.shift += 26 - this.shift % 26; } this.r = new BN3(1).iushln(this.shift); this.r2 = this.imod(this.r.sqr()); this.rinv = this.r._invmp(this.m); this.minv = this.rinv.mul(this.r).isubn(1).div(this.m); this.minv = this.minv.umod(this.r); this.minv = this.r.sub(this.minv); } inherits(Mont, Red); Mont.prototype.convertTo = function convertTo(num) { return this.imod(num.ushln(this.shift)); }; Mont.prototype.convertFrom = function convertFrom(num) { var r4 = this.imod(num.mul(this.rinv)); r4.red = null; return r4; }; Mont.prototype.imul = function imul(a4, b5) { if (a4.isZero() || b5.isZero()) { a4.words[0] = 0; a4.length = 1; return a4; } var t = a4.imul(b5); var c5 = t.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m); var u3 = t.isub(c5).iushrn(this.shift); var res = u3; if (u3.cmp(this.m) >= 0) { res = u3.isub(this.m); } else if (u3.cmpn(0) < 0) { res = u3.iadd(this.m); } return res._forceRed(this); }; Mont.prototype.mul = function mul3(a4, b5) { if (a4.isZero() || b5.isZero()) return new BN3(0)._forceRed(this); var t = a4.mul(b5); var c5 = t.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m); var u3 = t.isub(c5).iushrn(this.shift); var res = u3; if (u3.cmp(this.m) >= 0) { res = u3.isub(this.m); } else if (u3.cmpn(0) < 0) { res = u3.iadd(this.m); } return res._forceRed(this); }; Mont.prototype.invm = function invm(a4) { var res = this.imod(a4._invmp(this.m).mul(this.r2)); return res._forceRed(this); }; })(typeof module === "undefined" || module, exports); } }); // node_modules/minimalistic-crypto-utils/lib/utils.js var require_utils3 = __commonJS({ "node_modules/minimalistic-crypto-utils/lib/utils.js"(exports) { "use strict"; var utils = exports; function toArray(msg, enc) { if (Array.isArray(msg)) return msg.slice(); if (!msg) return []; var res = []; if (typeof msg !== "string") { for (var i4 = 0; i4 < msg.length; i4++) res[i4] = msg[i4] | 0; return res; } if (enc === "hex") { msg = msg.replace(/[^a-z0-9]+/ig, ""); if (msg.length % 2 !== 0) msg = "0" + msg; for (var i4 = 0; i4 < msg.length; i4 += 2) res.push(parseInt(msg[i4] + msg[i4 + 1], 16)); } else { for (var i4 = 0; i4 < msg.length; i4++) { var c5 = msg.charCodeAt(i4); var hi2 = c5 >> 8; var lo2 = c5 & 255; if (hi2) res.push(hi2, lo2); else res.push(lo2); } } return res; } utils.toArray = toArray; function zero2(word) { if (word.length === 1) return "0" + word; else return word; } utils.zero2 = zero2; function toHex2(msg) { var res = ""; for (var i4 = 0; i4 < msg.length; i4++) res += zero2(msg[i4].toString(16)); return res; } utils.toHex = toHex2; utils.encode = function encode8(arr, enc) { if (enc === "hex") return toHex2(arr); else return arr; }; } }); // node_modules/elliptic/lib/elliptic/utils.js var require_utils4 = __commonJS({ "node_modules/elliptic/lib/elliptic/utils.js"(exports) { "use strict"; var utils = exports; var BN3 = require_bn2(); var minAssert = require_minimalistic_assert(); var minUtils = require_utils3(); utils.assert = minAssert; utils.toArray = minUtils.toArray; utils.zero2 = minUtils.zero2; utils.toHex = minUtils.toHex; utils.encode = minUtils.encode; function getNAF2(num, w4, bits) { var naf = new Array(Math.max(num.bitLength(), bits) + 1); var i4; for (i4 = 0; i4 < naf.length; i4 += 1) { naf[i4] = 0; } var ws2 = 1 << w4 + 1; var k4 = num.clone(); for (i4 = 0; i4 < naf.length; i4++) { var z6; var mod = k4.andln(ws2 - 1); if (k4.isOdd()) { if (mod > (ws2 >> 1) - 1) z6 = (ws2 >> 1) - mod; else z6 = mod; k4.isubn(z6); } else { z6 = 0; } naf[i4] = z6; k4.iushrn(1); } return naf; } utils.getNAF = getNAF2; function getJSF2(k1, k22) { var jsf = [ [], [] ]; k1 = k1.clone(); k22 = k22.clone(); var d1 = 0; var d22 = 0; var m8; while (k1.cmpn(-d1) > 0 || k22.cmpn(-d22) > 0) { var m14 = k1.andln(3) + d1 & 3; var m24 = k22.andln(3) + d22 & 3; if (m14 === 3) m14 = -1; if (m24 === 3) m24 = -1; var u1; if ((m14 & 1) === 0) { u1 = 0; } else { m8 = k1.andln(7) + d1 & 7; if ((m8 === 3 || m8 === 5) && m24 === 2) u1 = -m14; else u1 = m14; } jsf[0].push(u1); var u22; if ((m24 & 1) === 0) { u22 = 0; } else { m8 = k22.andln(7) + d22 & 7; if ((m8 === 3 || m8 === 5) && m14 === 2) u22 = -m24; else u22 = m24; } jsf[1].push(u22); if (2 * d1 === u1 + 1) d1 = 1 - d1; if (2 * d22 === u22 + 1) d22 = 1 - d22; k1.iushrn(1); k22.iushrn(1); } return jsf; } utils.getJSF = getJSF2; function cachedProperty(obj, name2, computer) { var key2 = "_" + name2; obj.prototype[name2] = function cachedProperty2() { return this[key2] !== void 0 ? this[key2] : this[key2] = computer.call(this); }; } utils.cachedProperty = cachedProperty; function parseBytes(bytes) { return typeof bytes === "string" ? utils.toArray(bytes, "hex") : bytes; } utils.parseBytes = parseBytes; function intFromLE(bytes) { return new BN3(bytes, "hex", "le"); } utils.intFromLE = intFromLE; } }); // node_modules/brorand/index.js var require_brorand = __commonJS({ "node_modules/brorand/index.js"(exports, module) { var r4; module.exports = function rand2(len) { if (!r4) r4 = new Rand(null); return r4.generate(len); }; function Rand(rand2) { this.rand = rand2; } module.exports.Rand = Rand; Rand.prototype.generate = function generate2(len) { return this._rand(len); }; Rand.prototype._rand = function _rand(n5) { if (this.rand.getBytes) return this.rand.getBytes(n5); var res = new Uint8Array(n5); for (var i4 = 0; i4 < res.length; i4++) res[i4] = this.rand.getByte(); return res; }; if (typeof self === "object") { if (self.crypto && self.crypto.getRandomValues) { Rand.prototype._rand = function _rand(n5) { var arr = new Uint8Array(n5); self.crypto.getRandomValues(arr); return arr; }; } else if (self.msCrypto && self.msCrypto.getRandomValues) { Rand.prototype._rand = function _rand(n5) { var arr = new Uint8Array(n5); self.msCrypto.getRandomValues(arr); return arr; }; } else if (typeof window === "object") { Rand.prototype._rand = function() { throw new Error("Not implemented yet"); }; } } else { try { crypto2 = require_crypto(); if (typeof crypto2.randomBytes !== "function") throw new Error("Not supported"); Rand.prototype._rand = function _rand(n5) { return crypto2.randomBytes(n5); }; } catch (e2) { } } var crypto2; } }); // node_modules/elliptic/lib/elliptic/curve/base.js var require_base = __commonJS({ "node_modules/elliptic/lib/elliptic/curve/base.js"(exports, module) { "use strict"; var BN3 = require_bn2(); var utils = require_utils4(); var getNAF2 = utils.getNAF; var getJSF2 = utils.getJSF; var assert2 = utils.assert; function BaseCurve2(type, conf) { this.type = type; this.p = new BN3(conf.p, 16); this.red = conf.prime ? BN3.red(conf.prime) : BN3.mont(this.p); this.zero = new BN3(0).toRed(this.red); this.one = new BN3(1).toRed(this.red); this.two = new BN3(2).toRed(this.red); this.n = conf.n && new BN3(conf.n, 16); this.g = conf.g && this.pointFromJSON(conf.g, conf.gRed); this._wnafT1 = new Array(4); this._wnafT2 = new Array(4); this._wnafT3 = new Array(4); this._wnafT4 = new Array(4); this._bitLength = this.n ? this.n.bitLength() : 0; var adjustCount = this.n && this.p.div(this.n); if (!adjustCount || adjustCount.cmpn(100) > 0) { this.redN = null; } else { this._maxwellTrick = true; this.redN = this.n.toRed(this.red); } } module.exports = BaseCurve2; BaseCurve2.prototype.point = function point3() { throw new Error("Not implemented"); }; BaseCurve2.prototype.validate = function validate5() { throw new Error("Not implemented"); }; BaseCurve2.prototype._fixedNafMul = function _fixedNafMul2(p3, k4) { assert2(p3.precomputed); var doubles = p3._getDoubles(); var naf = getNAF2(k4, 1, this._bitLength); var I5 = (1 << doubles.step + 1) - (doubles.step % 2 === 0 ? 2 : 1); I5 /= 3; var repr = []; var j2; var nafW; for (j2 = 0; j2 < naf.length; j2 += doubles.step) { nafW = 0; for (var l4 = j2 + doubles.step - 1; l4 >= j2; l4--) nafW = (nafW << 1) + naf[l4]; repr.push(nafW); } var a4 = this.jpoint(null, null, null); var b5 = this.jpoint(null, null, null); for (var i4 = I5; i4 > 0; i4--) { for (j2 = 0; j2 < repr.length; j2++) { nafW = repr[j2]; if (nafW === i4) b5 = b5.mixedAdd(doubles.points[j2]); else if (nafW === -i4) b5 = b5.mixedAdd(doubles.points[j2].neg()); } a4 = a4.add(b5); } return a4.toP(); }; BaseCurve2.prototype._wnafMul = function _wnafMul2(p3, k4) { var w4 = 4; var nafPoints = p3._getNAFPoints(w4); w4 = nafPoints.wnd; var wnd = nafPoints.points; var naf = getNAF2(k4, w4, this._bitLength); var acc = this.jpoint(null, null, null); for (var i4 = naf.length - 1; i4 >= 0; i4--) { for (var l4 = 0; i4 >= 0 && naf[i4] === 0; i4--) l4++; if (i4 >= 0) l4++; acc = acc.dblp(l4); if (i4 < 0) break; var z6 = naf[i4]; assert2(z6 !== 0); if (p3.type === "affine") { if (z6 > 0) acc = acc.mixedAdd(wnd[z6 - 1 >> 1]); else acc = acc.mixedAdd(wnd[-z6 - 1 >> 1].neg()); } else { if (z6 > 0) acc = acc.add(wnd[z6 - 1 >> 1]); else acc = acc.add(wnd[-z6 - 1 >> 1].neg()); } } return p3.type === "affine" ? acc.toP() : acc; }; BaseCurve2.prototype._wnafMulAdd = function _wnafMulAdd2(defW, points, coeffs, len, jacobianResult) { var wndWidth = this._wnafT1; var wnd = this._wnafT2; var naf = this._wnafT3; var max = 0; var i4; var j2; var p3; for (i4 = 0; i4 < len; i4++) { p3 = points[i4]; var nafPoints = p3._getNAFPoints(defW); wndWidth[i4] = nafPoints.wnd; wnd[i4] = nafPoints.points; } for (i4 = len - 1; i4 >= 1; i4 -= 2) { var a4 = i4 - 1; var b5 = i4; if (wndWidth[a4] !== 1 || wndWidth[b5] !== 1) { naf[a4] = getNAF2(coeffs[a4], wndWidth[a4], this._bitLength); naf[b5] = getNAF2(coeffs[b5], wndWidth[b5], this._bitLength); max = Math.max(naf[a4].length, max); max = Math.max(naf[b5].length, max); continue; } var comb = [ points[a4], /* 1 */ null, /* 3 */ null, /* 5 */ points[b5] /* 7 */ ]; if (points[a4].y.cmp(points[b5].y) === 0) { comb[1] = points[a4].add(points[b5]); comb[2] = points[a4].toJ().mixedAdd(points[b5].neg()); } else if (points[a4].y.cmp(points[b5].y.redNeg()) === 0) { comb[1] = points[a4].toJ().mixedAdd(points[b5]); comb[2] = points[a4].add(points[b5].neg()); } else { comb[1] = points[a4].toJ().mixedAdd(points[b5]); comb[2] = points[a4].toJ().mixedAdd(points[b5].neg()); } var index = [ -3, /* -1 -1 */ -1, /* -1 0 */ -5, /* -1 1 */ -7, /* 0 -1 */ 0, /* 0 0 */ 7, /* 0 1 */ 5, /* 1 -1 */ 1, /* 1 0 */ 3 /* 1 1 */ ]; var jsf = getJSF2(coeffs[a4], coeffs[b5]); max = Math.max(jsf[0].length, max); naf[a4] = new Array(max); naf[b5] = new Array(max); for (j2 = 0; j2 < max; j2++) { var ja = jsf[0][j2] | 0; var jb = jsf[1][j2] | 0; naf[a4][j2] = index[(ja + 1) * 3 + (jb + 1)]; naf[b5][j2] = 0; wnd[a4] = comb; } } var acc = this.jpoint(null, null, null); var tmp = this._wnafT4; for (i4 = max; i4 >= 0; i4--) { var k4 = 0; while (i4 >= 0) { var zero = true; for (j2 = 0; j2 < len; j2++) { tmp[j2] = naf[j2][i4] | 0; if (tmp[j2] !== 0) zero = false; } if (!zero) break; k4++; i4--; } if (i4 >= 0) k4++; acc = acc.dblp(k4); if (i4 < 0) break; for (j2 = 0; j2 < len; j2++) { var z6 = tmp[j2]; p3; if (z6 === 0) continue; else if (z6 > 0) p3 = wnd[j2][z6 - 1 >> 1]; else if (z6 < 0) p3 = wnd[j2][-z6 - 1 >> 1].neg(); if (p3.type === "affine") acc = acc.mixedAdd(p3); else acc = acc.add(p3); } } for (i4 = 0; i4 < len; i4++) wnd[i4] = null; if (jacobianResult) return acc; else return acc.toP(); }; function BasePoint2(curve, type) { this.curve = curve; this.type = type; this.precomputed = null; } BaseCurve2.BasePoint = BasePoint2; BasePoint2.prototype.eq = function eq4() { throw new Error("Not implemented"); }; BasePoint2.prototype.validate = function validate5() { return this.curve.validate(this); }; BaseCurve2.prototype.decodePoint = function decodePoint2(bytes, enc) { bytes = utils.toArray(bytes, enc); var len = this.p.byteLength(); if ((bytes[0] === 4 || bytes[0] === 6 || bytes[0] === 7) && bytes.length - 1 === 2 * len) { if (bytes[0] === 6) assert2(bytes[bytes.length - 1] % 2 === 0); else if (bytes[0] === 7) assert2(bytes[bytes.length - 1] % 2 === 1); var res = this.point( bytes.slice(1, 1 + len), bytes.slice(1 + len, 1 + 2 * len) ); return res; } else if ((bytes[0] === 2 || bytes[0] === 3) && bytes.length - 1 === len) { return this.pointFromX(bytes.slice(1, 1 + len), bytes[0] === 3); } throw new Error("Unknown point format"); }; BasePoint2.prototype.encodeCompressed = function encodeCompressed2(enc) { return this.encode(enc, true); }; BasePoint2.prototype._encode = function _encode2(compact) { var len = this.curve.p.byteLength(); var x6 = this.getX().toArray("be", len); if (compact) return [this.getY().isEven() ? 2 : 3].concat(x6); return [4].concat(x6, this.getY().toArray("be", len)); }; BasePoint2.prototype.encode = function encode8(enc, compact) { return utils.encode(this._encode(compact), enc); }; BasePoint2.prototype.precompute = function precompute2(power) { if (this.precomputed) return this; var precomputed = { doubles: null, naf: null, beta: null }; precomputed.naf = this._getNAFPoints(8); precomputed.doubles = this._getDoubles(4, power); precomputed.beta = this._getBeta(); this.precomputed = precomputed; return this; }; BasePoint2.prototype._hasDoubles = function _hasDoubles2(k4) { if (!this.precomputed) return false; var doubles = this.precomputed.doubles; if (!doubles) return false; return doubles.points.length >= Math.ceil((k4.bitLength() + 1) / doubles.step); }; BasePoint2.prototype._getDoubles = function _getDoubles2(step, power) { if (this.precomputed && this.precomputed.doubles) return this.precomputed.doubles; var doubles = [this]; var acc = this; for (var i4 = 0; i4 < power; i4 += step) { for (var j2 = 0; j2 < step; j2++) acc = acc.dbl(); doubles.push(acc); } return { step, points: doubles }; }; BasePoint2.prototype._getNAFPoints = function _getNAFPoints2(wnd) { if (this.precomputed && this.precomputed.naf) return this.precomputed.naf; var res = [this]; var max = (1 << wnd) - 1; var dbl3 = max === 1 ? null : this.dbl(); for (var i4 = 1; i4 < max; i4++) res[i4] = res[i4 - 1].add(dbl3); return { wnd, points: res }; }; BasePoint2.prototype._getBeta = function _getBeta3() { return null; }; BasePoint2.prototype.dblp = function dblp3(k4) { var r4 = this; for (var i4 = 0; i4 < k4; i4++) r4 = r4.dbl(); return r4; }; } }); // node_modules/elliptic/lib/elliptic/curve/short.js var require_short = __commonJS({ "node_modules/elliptic/lib/elliptic/curve/short.js"(exports, module) { "use strict"; var utils = require_utils4(); var BN3 = require_bn2(); var inherits = require_inherits_browser(); var Base = require_base(); var assert2 = utils.assert; function ShortCurve2(conf) { Base.call(this, "short", conf); this.a = new BN3(conf.a, 16).toRed(this.red); this.b = new BN3(conf.b, 16).toRed(this.red); this.tinv = this.two.redInvm(); this.zeroA = this.a.fromRed().cmpn(0) === 0; this.threeA = this.a.fromRed().sub(this.p).cmpn(-3) === 0; this.endo = this._getEndomorphism(conf); this._endoWnafT1 = new Array(4); this._endoWnafT2 = new Array(4); } inherits(ShortCurve2, Base); module.exports = ShortCurve2; ShortCurve2.prototype._getEndomorphism = function _getEndomorphism2(conf) { if (!this.zeroA || !this.g || !this.n || this.p.modn(3) !== 1) return; var beta; var lambda; if (conf.beta) { beta = new BN3(conf.beta, 16).toRed(this.red); } else { var betas = this._getEndoRoots(this.p); beta = betas[0].cmp(betas[1]) < 0 ? betas[0] : betas[1]; beta = beta.toRed(this.red); } if (conf.lambda) { lambda = new BN3(conf.lambda, 16); } else { var lambdas = this._getEndoRoots(this.n); if (this.g.mul(lambdas[0]).x.cmp(this.g.x.redMul(beta)) === 0) { lambda = lambdas[0]; } else { lambda = lambdas[1]; assert2(this.g.mul(lambda).x.cmp(this.g.x.redMul(beta)) === 0); } } var basis; if (conf.basis) { basis = conf.basis.map(function(vec) { return { a: new BN3(vec.a, 16), b: new BN3(vec.b, 16) }; }); } else { basis = this._getEndoBasis(lambda); } return { beta, lambda, basis }; }; ShortCurve2.prototype._getEndoRoots = function _getEndoRoots2(num) { var red = num === this.p ? this.red : BN3.mont(num); var tinv = new BN3(2).toRed(red).redInvm(); var ntinv = tinv.redNeg(); var s3 = new BN3(3).toRed(red).redNeg().redSqrt().redMul(tinv); var l1 = ntinv.redAdd(s3).fromRed(); var l22 = ntinv.redSub(s3).fromRed(); return [l1, l22]; }; ShortCurve2.prototype._getEndoBasis = function _getEndoBasis2(lambda) { var aprxSqrt = this.n.ushrn(Math.floor(this.n.bitLength() / 2)); var u3 = lambda; var v5 = this.n.clone(); var x1 = new BN3(1); var y1 = new BN3(0); var x22 = new BN3(0); var y22 = new BN3(1); var a0; var b0; var a1; var b1; var a22; var b22; var prevR; var i4 = 0; var r4; var x6; while (u3.cmpn(0) !== 0) { var q3 = v5.div(u3); r4 = v5.sub(q3.mul(u3)); x6 = x22.sub(q3.mul(x1)); var y6 = y22.sub(q3.mul(y1)); if (!a1 && r4.cmp(aprxSqrt) < 0) { a0 = prevR.neg(); b0 = x1; a1 = r4.neg(); b1 = x6; } else if (a1 && ++i4 === 2) { break; } prevR = r4; v5 = u3; u3 = r4; x22 = x1; x1 = x6; y22 = y1; y1 = y6; } a22 = r4.neg(); b22 = x6; var len1 = a1.sqr().add(b1.sqr()); var len2 = a22.sqr().add(b22.sqr()); if (len2.cmp(len1) >= 0) { a22 = a0; b22 = b0; } if (a1.negative) { a1 = a1.neg(); b1 = b1.neg(); } if (a22.negative) { a22 = a22.neg(); b22 = b22.neg(); } return [ { a: a1, b: b1 }, { a: a22, b: b22 } ]; }; ShortCurve2.prototype._endoSplit = function _endoSplit2(k4) { var basis = this.endo.basis; var v1 = basis[0]; var v22 = basis[1]; var c1 = v22.b.mul(k4).divRound(this.n); var c22 = v1.b.neg().mul(k4).divRound(this.n); var p1 = c1.mul(v1.a); var p22 = c22.mul(v22.a); var q1 = c1.mul(v1.b); var q22 = c22.mul(v22.b); var k1 = k4.sub(p1).sub(p22); var k22 = q1.add(q22).neg(); return { k1, k2: k22 }; }; ShortCurve2.prototype.pointFromX = function pointFromX2(x6, odd) { x6 = new BN3(x6, 16); if (!x6.red) x6 = x6.toRed(this.red); var y22 = x6.redSqr().redMul(x6).redIAdd(x6.redMul(this.a)).redIAdd(this.b); var y6 = y22.redSqrt(); if (y6.redSqr().redSub(y22).cmp(this.zero) !== 0) throw new Error("invalid point"); var isOdd = y6.fromRed().isOdd(); if (odd && !isOdd || !odd && isOdd) y6 = y6.redNeg(); return this.point(x6, y6); }; ShortCurve2.prototype.validate = function validate5(point3) { if (point3.inf) return true; var x6 = point3.x; var y6 = point3.y; var ax = this.a.redMul(x6); var rhs = x6.redSqr().redMul(x6).redIAdd(ax).redIAdd(this.b); return y6.redSqr().redISub(rhs).cmpn(0) === 0; }; ShortCurve2.prototype._endoWnafMulAdd = function _endoWnafMulAdd2(points, coeffs, jacobianResult) { var npoints = this._endoWnafT1; var ncoeffs = this._endoWnafT2; for (var i4 = 0; i4 < points.length; i4++) { var split = this._endoSplit(coeffs[i4]); var p3 = points[i4]; var beta = p3._getBeta(); if (split.k1.negative) { split.k1.ineg(); p3 = p3.neg(true); } if (split.k2.negative) { split.k2.ineg(); beta = beta.neg(true); } npoints[i4 * 2] = p3; npoints[i4 * 2 + 1] = beta; ncoeffs[i4 * 2] = split.k1; ncoeffs[i4 * 2 + 1] = split.k2; } var res = this._wnafMulAdd(1, npoints, ncoeffs, i4 * 2, jacobianResult); for (var j2 = 0; j2 < i4 * 2; j2++) { npoints[j2] = null; ncoeffs[j2] = null; } return res; }; function Point2(curve, x6, y6, isRed) { Base.BasePoint.call(this, curve, "affine"); if (x6 === null && y6 === null) { this.x = null; this.y = null; this.inf = true; } else { this.x = new BN3(x6, 16); this.y = new BN3(y6, 16); if (isRed) { this.x.forceRed(this.curve.red); this.y.forceRed(this.curve.red); } if (!this.x.red) this.x = this.x.toRed(this.curve.red); if (!this.y.red) this.y = this.y.toRed(this.curve.red); this.inf = false; } } inherits(Point2, Base.BasePoint); ShortCurve2.prototype.point = function point3(x6, y6, isRed) { return new Point2(this, x6, y6, isRed); }; ShortCurve2.prototype.pointFromJSON = function pointFromJSON2(obj, red) { return Point2.fromJSON(this, obj, red); }; Point2.prototype._getBeta = function _getBeta3() { if (!this.curve.endo) return; var pre = this.precomputed; if (pre && pre.beta) return pre.beta; var beta = this.curve.point(this.x.redMul(this.curve.endo.beta), this.y); if (pre) { var curve = this.curve; var endoMul = function(p3) { return curve.point(p3.x.redMul(curve.endo.beta), p3.y); }; pre.beta = beta; beta.precomputed = { beta: null, naf: pre.naf && { wnd: pre.naf.wnd, points: pre.naf.points.map(endoMul) }, doubles: pre.doubles && { step: pre.doubles.step, points: pre.doubles.points.map(endoMul) } }; } return beta; }; Point2.prototype.toJSON = function toJSON2() { if (!this.precomputed) return [this.x, this.y]; return [this.x, this.y, this.precomputed && { doubles: this.precomputed.doubles && { step: this.precomputed.doubles.step, points: this.precomputed.doubles.points.slice(1) }, naf: this.precomputed.naf && { wnd: this.precomputed.naf.wnd, points: this.precomputed.naf.points.slice(1) } }]; }; Point2.fromJSON = function fromJSON2(curve, obj, red) { if (typeof obj === "string") obj = JSON.parse(obj); var res = curve.point(obj[0], obj[1], red); if (!obj[2]) return res; function obj2point(obj2) { return curve.point(obj2[0], obj2[1], red); } var pre = obj[2]; res.precomputed = { beta: null, doubles: pre.doubles && { step: pre.doubles.step, points: [res].concat(pre.doubles.points.map(obj2point)) }, naf: pre.naf && { wnd: pre.naf.wnd, points: [res].concat(pre.naf.points.map(obj2point)) } }; return res; }; Point2.prototype.inspect = function inspect4() { if (this.isInfinity()) return ""; return ""; }; Point2.prototype.isInfinity = function isInfinity3() { return this.inf; }; Point2.prototype.add = function add3(p3) { if (this.inf) return p3; if (p3.inf) return this; if (this.eq(p3)) return this.dbl(); if (this.neg().eq(p3)) return this.curve.point(null, null); if (this.x.cmp(p3.x) === 0) return this.curve.point(null, null); var c5 = this.y.redSub(p3.y); if (c5.cmpn(0) !== 0) c5 = c5.redMul(this.x.redSub(p3.x).redInvm()); var nx = c5.redSqr().redISub(this.x).redISub(p3.x); var ny = c5.redMul(this.x.redSub(nx)).redISub(this.y); return this.curve.point(nx, ny); }; Point2.prototype.dbl = function dbl3() { if (this.inf) return this; var ys1 = this.y.redAdd(this.y); if (ys1.cmpn(0) === 0) return this.curve.point(null, null); var a4 = this.curve.a; var x22 = this.x.redSqr(); var dyinv = ys1.redInvm(); var c5 = x22.redAdd(x22).redIAdd(x22).redIAdd(a4).redMul(dyinv); var nx = c5.redSqr().redISub(this.x.redAdd(this.x)); var ny = c5.redMul(this.x.redSub(nx)).redISub(this.y); return this.curve.point(nx, ny); }; Point2.prototype.getX = function getX2() { return this.x.fromRed(); }; Point2.prototype.getY = function getY2() { return this.y.fromRed(); }; Point2.prototype.mul = function mul3(k4) { k4 = new BN3(k4, 16); if (this.isInfinity()) return this; else if (this._hasDoubles(k4)) return this.curve._fixedNafMul(this, k4); else if (this.curve.endo) return this.curve._endoWnafMulAdd([this], [k4]); else return this.curve._wnafMul(this, k4); }; Point2.prototype.mulAdd = function mulAdd2(k1, p22, k22) { var points = [this, p22]; var coeffs = [k1, k22]; if (this.curve.endo) return this.curve._endoWnafMulAdd(points, coeffs); else return this.curve._wnafMulAdd(1, points, coeffs, 2); }; Point2.prototype.jmulAdd = function jmulAdd2(k1, p22, k22) { var points = [this, p22]; var coeffs = [k1, k22]; if (this.curve.endo) return this.curve._endoWnafMulAdd(points, coeffs, true); else return this.curve._wnafMulAdd(1, points, coeffs, 2, true); }; Point2.prototype.eq = function eq4(p3) { return this === p3 || this.inf === p3.inf && (this.inf || this.x.cmp(p3.x) === 0 && this.y.cmp(p3.y) === 0); }; Point2.prototype.neg = function neg3(_precompute) { if (this.inf) return this; var res = this.curve.point(this.x, this.y.redNeg()); if (_precompute && this.precomputed) { var pre = this.precomputed; var negate = function(p3) { return p3.neg(); }; res.precomputed = { naf: pre.naf && { wnd: pre.naf.wnd, points: pre.naf.points.map(negate) }, doubles: pre.doubles && { step: pre.doubles.step, points: pre.doubles.points.map(negate) } }; } return res; }; Point2.prototype.toJ = function toJ2() { if (this.inf) return this.curve.jpoint(null, null, null); var res = this.curve.jpoint(this.x, this.y, this.curve.one); return res; }; function JPoint2(curve, x6, y6, z6) { Base.BasePoint.call(this, curve, "jacobian"); if (x6 === null && y6 === null && z6 === null) { this.x = this.curve.one; this.y = this.curve.one; this.z = new BN3(0); } else { this.x = new BN3(x6, 16); this.y = new BN3(y6, 16); this.z = new BN3(z6, 16); } if (!this.x.red) this.x = this.x.toRed(this.curve.red); if (!this.y.red) this.y = this.y.toRed(this.curve.red); if (!this.z.red) this.z = this.z.toRed(this.curve.red); this.zOne = this.z === this.curve.one; } inherits(JPoint2, Base.BasePoint); ShortCurve2.prototype.jpoint = function jpoint2(x6, y6, z6) { return new JPoint2(this, x6, y6, z6); }; JPoint2.prototype.toP = function toP2() { if (this.isInfinity()) return this.curve.point(null, null); var zinv = this.z.redInvm(); var zinv2 = zinv.redSqr(); var ax = this.x.redMul(zinv2); var ay = this.y.redMul(zinv2).redMul(zinv); return this.curve.point(ax, ay); }; JPoint2.prototype.neg = function neg3() { return this.curve.jpoint(this.x, this.y.redNeg(), this.z); }; JPoint2.prototype.add = function add3(p3) { if (this.isInfinity()) return p3; if (p3.isInfinity()) return this; var pz2 = p3.z.redSqr(); var z22 = this.z.redSqr(); var u1 = this.x.redMul(pz2); var u22 = p3.x.redMul(z22); var s1 = this.y.redMul(pz2.redMul(p3.z)); var s22 = p3.y.redMul(z22.redMul(this.z)); var h5 = u1.redSub(u22); var r4 = s1.redSub(s22); if (h5.cmpn(0) === 0) { if (r4.cmpn(0) !== 0) return this.curve.jpoint(null, null, null); else return this.dbl(); } var h22 = h5.redSqr(); var h32 = h22.redMul(h5); var v5 = u1.redMul(h22); var nx = r4.redSqr().redIAdd(h32).redISub(v5).redISub(v5); var ny = r4.redMul(v5.redISub(nx)).redISub(s1.redMul(h32)); var nz = this.z.redMul(p3.z).redMul(h5); return this.curve.jpoint(nx, ny, nz); }; JPoint2.prototype.mixedAdd = function mixedAdd2(p3) { if (this.isInfinity()) return p3.toJ(); if (p3.isInfinity()) return this; var z22 = this.z.redSqr(); var u1 = this.x; var u22 = p3.x.redMul(z22); var s1 = this.y; var s22 = p3.y.redMul(z22).redMul(this.z); var h5 = u1.redSub(u22); var r4 = s1.redSub(s22); if (h5.cmpn(0) === 0) { if (r4.cmpn(0) !== 0) return this.curve.jpoint(null, null, null); else return this.dbl(); } var h22 = h5.redSqr(); var h32 = h22.redMul(h5); var v5 = u1.redMul(h22); var nx = r4.redSqr().redIAdd(h32).redISub(v5).redISub(v5); var ny = r4.redMul(v5.redISub(nx)).redISub(s1.redMul(h32)); var nz = this.z.redMul(h5); return this.curve.jpoint(nx, ny, nz); }; JPoint2.prototype.dblp = function dblp3(pow) { if (pow === 0) return this; if (this.isInfinity()) return this; if (!pow) return this.dbl(); var i4; if (this.curve.zeroA || this.curve.threeA) { var r4 = this; for (i4 = 0; i4 < pow; i4++) r4 = r4.dbl(); return r4; } var a4 = this.curve.a; var tinv = this.curve.tinv; var jx = this.x; var jy = this.y; var jz = this.z; var jz4 = jz.redSqr().redSqr(); var jyd = jy.redAdd(jy); for (i4 = 0; i4 < pow; i4++) { var jx2 = jx.redSqr(); var jyd2 = jyd.redSqr(); var jyd4 = jyd2.redSqr(); var c5 = jx2.redAdd(jx2).redIAdd(jx2).redIAdd(a4.redMul(jz4)); var t1 = jx.redMul(jyd2); var nx = c5.redSqr().redISub(t1.redAdd(t1)); var t2 = t1.redISub(nx); var dny = c5.redMul(t2); dny = dny.redIAdd(dny).redISub(jyd4); var nz = jyd.redMul(jz); if (i4 + 1 < pow) jz4 = jz4.redMul(jyd4); jx = nx; jz = nz; jyd = dny; } return this.curve.jpoint(jx, jyd.redMul(tinv), jz); }; JPoint2.prototype.dbl = function dbl3() { if (this.isInfinity()) return this; if (this.curve.zeroA) return this._zeroDbl(); else if (this.curve.threeA) return this._threeDbl(); else return this._dbl(); }; JPoint2.prototype._zeroDbl = function _zeroDbl2() { var nx; var ny; var nz; if (this.zOne) { var xx = this.x.redSqr(); var yy = this.y.redSqr(); var yyyy = yy.redSqr(); var s3 = this.x.redAdd(yy).redSqr().redISub(xx).redISub(yyyy); s3 = s3.redIAdd(s3); var m2 = xx.redAdd(xx).redIAdd(xx); var t = m2.redSqr().redISub(s3).redISub(s3); var yyyy8 = yyyy.redIAdd(yyyy); yyyy8 = yyyy8.redIAdd(yyyy8); yyyy8 = yyyy8.redIAdd(yyyy8); nx = t; ny = m2.redMul(s3.redISub(t)).redISub(yyyy8); nz = this.y.redAdd(this.y); } else { var a4 = this.x.redSqr(); var b5 = this.y.redSqr(); var c5 = b5.redSqr(); var d3 = this.x.redAdd(b5).redSqr().redISub(a4).redISub(c5); d3 = d3.redIAdd(d3); var e2 = a4.redAdd(a4).redIAdd(a4); var f4 = e2.redSqr(); var c8 = c5.redIAdd(c5); c8 = c8.redIAdd(c8); c8 = c8.redIAdd(c8); nx = f4.redISub(d3).redISub(d3); ny = e2.redMul(d3.redISub(nx)).redISub(c8); nz = this.y.redMul(this.z); nz = nz.redIAdd(nz); } return this.curve.jpoint(nx, ny, nz); }; JPoint2.prototype._threeDbl = function _threeDbl2() { var nx; var ny; var nz; if (this.zOne) { var xx = this.x.redSqr(); var yy = this.y.redSqr(); var yyyy = yy.redSqr(); var s3 = this.x.redAdd(yy).redSqr().redISub(xx).redISub(yyyy); s3 = s3.redIAdd(s3); var m2 = xx.redAdd(xx).redIAdd(xx).redIAdd(this.curve.a); var t = m2.redSqr().redISub(s3).redISub(s3); nx = t; var yyyy8 = yyyy.redIAdd(yyyy); yyyy8 = yyyy8.redIAdd(yyyy8); yyyy8 = yyyy8.redIAdd(yyyy8); ny = m2.redMul(s3.redISub(t)).redISub(yyyy8); nz = this.y.redAdd(this.y); } else { var delta = this.z.redSqr(); var gamma = this.y.redSqr(); var beta = this.x.redMul(gamma); var alpha = this.x.redSub(delta).redMul(this.x.redAdd(delta)); alpha = alpha.redAdd(alpha).redIAdd(alpha); var beta4 = beta.redIAdd(beta); beta4 = beta4.redIAdd(beta4); var beta8 = beta4.redAdd(beta4); nx = alpha.redSqr().redISub(beta8); nz = this.y.redAdd(this.z).redSqr().redISub(gamma).redISub(delta); var ggamma8 = gamma.redSqr(); ggamma8 = ggamma8.redIAdd(ggamma8); ggamma8 = ggamma8.redIAdd(ggamma8); ggamma8 = ggamma8.redIAdd(ggamma8); ny = alpha.redMul(beta4.redISub(nx)).redISub(ggamma8); } return this.curve.jpoint(nx, ny, nz); }; JPoint2.prototype._dbl = function _dbl2() { var a4 = this.curve.a; var jx = this.x; var jy = this.y; var jz = this.z; var jz4 = jz.redSqr().redSqr(); var jx2 = jx.redSqr(); var jy2 = jy.redSqr(); var c5 = jx2.redAdd(jx2).redIAdd(jx2).redIAdd(a4.redMul(jz4)); var jxd4 = jx.redAdd(jx); jxd4 = jxd4.redIAdd(jxd4); var t1 = jxd4.redMul(jy2); var nx = c5.redSqr().redISub(t1.redAdd(t1)); var t2 = t1.redISub(nx); var jyd8 = jy2.redSqr(); jyd8 = jyd8.redIAdd(jyd8); jyd8 = jyd8.redIAdd(jyd8); jyd8 = jyd8.redIAdd(jyd8); var ny = c5.redMul(t2).redISub(jyd8); var nz = jy.redAdd(jy).redMul(jz); return this.curve.jpoint(nx, ny, nz); }; JPoint2.prototype.trpl = function trpl2() { if (!this.curve.zeroA) return this.dbl().add(this); var xx = this.x.redSqr(); var yy = this.y.redSqr(); var zz = this.z.redSqr(); var yyyy = yy.redSqr(); var m2 = xx.redAdd(xx).redIAdd(xx); var mm = m2.redSqr(); var e2 = this.x.redAdd(yy).redSqr().redISub(xx).redISub(yyyy); e2 = e2.redIAdd(e2); e2 = e2.redAdd(e2).redIAdd(e2); e2 = e2.redISub(mm); var ee3 = e2.redSqr(); var t = yyyy.redIAdd(yyyy); t = t.redIAdd(t); t = t.redIAdd(t); t = t.redIAdd(t); var u3 = m2.redIAdd(e2).redSqr().redISub(mm).redISub(ee3).redISub(t); var yyu4 = yy.redMul(u3); yyu4 = yyu4.redIAdd(yyu4); yyu4 = yyu4.redIAdd(yyu4); var nx = this.x.redMul(ee3).redISub(yyu4); nx = nx.redIAdd(nx); nx = nx.redIAdd(nx); var ny = this.y.redMul(u3.redMul(t.redISub(u3)).redISub(e2.redMul(ee3))); ny = ny.redIAdd(ny); ny = ny.redIAdd(ny); ny = ny.redIAdd(ny); var nz = this.z.redAdd(e2).redSqr().redISub(zz).redISub(ee3); return this.curve.jpoint(nx, ny, nz); }; JPoint2.prototype.mul = function mul3(k4, kbase) { k4 = new BN3(k4, kbase); return this.curve._wnafMul(this, k4); }; JPoint2.prototype.eq = function eq4(p3) { if (p3.type === "affine") return this.eq(p3.toJ()); if (this === p3) return true; var z22 = this.z.redSqr(); var pz2 = p3.z.redSqr(); if (this.x.redMul(pz2).redISub(p3.x.redMul(z22)).cmpn(0) !== 0) return false; var z32 = z22.redMul(this.z); var pz3 = pz2.redMul(p3.z); return this.y.redMul(pz3).redISub(p3.y.redMul(z32)).cmpn(0) === 0; }; JPoint2.prototype.eqXToP = function eqXToP2(x6) { var zs2 = this.z.redSqr(); var rx = x6.toRed(this.curve.red).redMul(zs2); if (this.x.cmp(rx) === 0) return true; var xc = x6.clone(); var t = this.curve.redN.redMul(zs2); for (; ; ) { xc.iadd(this.curve.n); if (xc.cmp(this.curve.p) >= 0) return false; rx.redIAdd(t); if (this.x.cmp(rx) === 0) return true; } }; JPoint2.prototype.inspect = function inspect4() { if (this.isInfinity()) return ""; return ""; }; JPoint2.prototype.isInfinity = function isInfinity3() { return this.z.cmpn(0) === 0; }; } }); // node_modules/elliptic/lib/elliptic/curve/mont.js var require_mont = __commonJS({ "node_modules/elliptic/lib/elliptic/curve/mont.js"(exports, module) { "use strict"; var BN3 = require_bn2(); var inherits = require_inherits_browser(); var Base = require_base(); var utils = require_utils4(); function MontCurve(conf) { Base.call(this, "mont", conf); this.a = new BN3(conf.a, 16).toRed(this.red); this.b = new BN3(conf.b, 16).toRed(this.red); this.i4 = new BN3(4).toRed(this.red).redInvm(); this.two = new BN3(2).toRed(this.red); this.a24 = this.i4.redMul(this.a.redAdd(this.two)); } inherits(MontCurve, Base); module.exports = MontCurve; MontCurve.prototype.validate = function validate5(point3) { var x6 = point3.normalize().x; var x22 = x6.redSqr(); var rhs = x22.redMul(x6).redAdd(x22.redMul(this.a)).redAdd(x6); var y6 = rhs.redSqrt(); return y6.redSqr().cmp(rhs) === 0; }; function Point2(curve, x6, z6) { Base.BasePoint.call(this, curve, "projective"); if (x6 === null && z6 === null) { this.x = this.curve.one; this.z = this.curve.zero; } else { this.x = new BN3(x6, 16); this.z = new BN3(z6, 16); if (!this.x.red) this.x = this.x.toRed(this.curve.red); if (!this.z.red) this.z = this.z.toRed(this.curve.red); } } inherits(Point2, Base.BasePoint); MontCurve.prototype.decodePoint = function decodePoint2(bytes, enc) { return this.point(utils.toArray(bytes, enc), 1); }; MontCurve.prototype.point = function point3(x6, z6) { return new Point2(this, x6, z6); }; MontCurve.prototype.pointFromJSON = function pointFromJSON2(obj) { return Point2.fromJSON(this, obj); }; Point2.prototype.precompute = function precompute2() { }; Point2.prototype._encode = function _encode2() { return this.getX().toArray("be", this.curve.p.byteLength()); }; Point2.fromJSON = function fromJSON2(curve, obj) { return new Point2(curve, obj[0], obj[1] || curve.one); }; Point2.prototype.inspect = function inspect4() { if (this.isInfinity()) return ""; return ""; }; Point2.prototype.isInfinity = function isInfinity3() { return this.z.cmpn(0) === 0; }; Point2.prototype.dbl = function dbl3() { var a4 = this.x.redAdd(this.z); var aa = a4.redSqr(); var b5 = this.x.redSub(this.z); var bb = b5.redSqr(); var c5 = aa.redSub(bb); var nx = aa.redMul(bb); var nz = c5.redMul(bb.redAdd(this.curve.a24.redMul(c5))); return this.curve.point(nx, nz); }; Point2.prototype.add = function add3() { throw new Error("Not supported on Montgomery curve"); }; Point2.prototype.diffAdd = function diffAdd(p3, diff) { var a4 = this.x.redAdd(this.z); var b5 = this.x.redSub(this.z); var c5 = p3.x.redAdd(p3.z); var d3 = p3.x.redSub(p3.z); var da = d3.redMul(a4); var cb = c5.redMul(b5); var nx = diff.z.redMul(da.redAdd(cb).redSqr()); var nz = diff.x.redMul(da.redISub(cb).redSqr()); return this.curve.point(nx, nz); }; Point2.prototype.mul = function mul3(k4) { var t = k4.clone(); var a4 = this; var b5 = this.curve.point(null, null); var c5 = this; for (var bits = []; t.cmpn(0) !== 0; t.iushrn(1)) bits.push(t.andln(1)); for (var i4 = bits.length - 1; i4 >= 0; i4--) { if (bits[i4] === 0) { a4 = a4.diffAdd(b5, c5); b5 = b5.dbl(); } else { b5 = a4.diffAdd(b5, c5); a4 = a4.dbl(); } } return b5; }; Point2.prototype.mulAdd = function mulAdd2() { throw new Error("Not supported on Montgomery curve"); }; Point2.prototype.jumlAdd = function jumlAdd() { throw new Error("Not supported on Montgomery curve"); }; Point2.prototype.eq = function eq4(other) { return this.getX().cmp(other.getX()) === 0; }; Point2.prototype.normalize = function normalize() { this.x = this.x.redMul(this.z.redInvm()); this.z = this.curve.one; return this; }; Point2.prototype.getX = function getX2() { this.normalize(); return this.x.fromRed(); }; } }); // node_modules/elliptic/lib/elliptic/curve/edwards.js var require_edwards = __commonJS({ "node_modules/elliptic/lib/elliptic/curve/edwards.js"(exports, module) { "use strict"; var utils = require_utils4(); var BN3 = require_bn2(); var inherits = require_inherits_browser(); var Base = require_base(); var assert2 = utils.assert; function EdwardsCurve(conf) { this.twisted = (conf.a | 0) !== 1; this.mOneA = this.twisted && (conf.a | 0) === -1; this.extended = this.mOneA; Base.call(this, "edwards", conf); this.a = new BN3(conf.a, 16).umod(this.red.m); this.a = this.a.toRed(this.red); this.c = new BN3(conf.c, 16).toRed(this.red); this.c2 = this.c.redSqr(); this.d = new BN3(conf.d, 16).toRed(this.red); this.dd = this.d.redAdd(this.d); assert2(!this.twisted || this.c.fromRed().cmpn(1) === 0); this.oneC = (conf.c | 0) === 1; } inherits(EdwardsCurve, Base); module.exports = EdwardsCurve; EdwardsCurve.prototype._mulA = function _mulA(num) { if (this.mOneA) return num.redNeg(); else return this.a.redMul(num); }; EdwardsCurve.prototype._mulC = function _mulC(num) { if (this.oneC) return num; else return this.c.redMul(num); }; EdwardsCurve.prototype.jpoint = function jpoint2(x6, y6, z6, t) { return this.point(x6, y6, z6, t); }; EdwardsCurve.prototype.pointFromX = function pointFromX2(x6, odd) { x6 = new BN3(x6, 16); if (!x6.red) x6 = x6.toRed(this.red); var x22 = x6.redSqr(); var rhs = this.c2.redSub(this.a.redMul(x22)); var lhs = this.one.redSub(this.c2.redMul(this.d).redMul(x22)); var y22 = rhs.redMul(lhs.redInvm()); var y6 = y22.redSqrt(); if (y6.redSqr().redSub(y22).cmp(this.zero) !== 0) throw new Error("invalid point"); var isOdd = y6.fromRed().isOdd(); if (odd && !isOdd || !odd && isOdd) y6 = y6.redNeg(); return this.point(x6, y6); }; EdwardsCurve.prototype.pointFromY = function pointFromY(y6, odd) { y6 = new BN3(y6, 16); if (!y6.red) y6 = y6.toRed(this.red); var y22 = y6.redSqr(); var lhs = y22.redSub(this.c2); var rhs = y22.redMul(this.d).redMul(this.c2).redSub(this.a); var x22 = lhs.redMul(rhs.redInvm()); if (x22.cmp(this.zero) === 0) { if (odd) throw new Error("invalid point"); else return this.point(this.zero, y6); } var x6 = x22.redSqrt(); if (x6.redSqr().redSub(x22).cmp(this.zero) !== 0) throw new Error("invalid point"); if (x6.fromRed().isOdd() !== odd) x6 = x6.redNeg(); return this.point(x6, y6); }; EdwardsCurve.prototype.validate = function validate5(point3) { if (point3.isInfinity()) return true; point3.normalize(); var x22 = point3.x.redSqr(); var y22 = point3.y.redSqr(); var lhs = x22.redMul(this.a).redAdd(y22); var rhs = this.c2.redMul(this.one.redAdd(this.d.redMul(x22).redMul(y22))); return lhs.cmp(rhs) === 0; }; function Point2(curve, x6, y6, z6, t) { Base.BasePoint.call(this, curve, "projective"); if (x6 === null && y6 === null && z6 === null) { this.x = this.curve.zero; this.y = this.curve.one; this.z = this.curve.one; this.t = this.curve.zero; this.zOne = true; } else { this.x = new BN3(x6, 16); this.y = new BN3(y6, 16); this.z = z6 ? new BN3(z6, 16) : this.curve.one; this.t = t && new BN3(t, 16); if (!this.x.red) this.x = this.x.toRed(this.curve.red); if (!this.y.red) this.y = this.y.toRed(this.curve.red); if (!this.z.red) this.z = this.z.toRed(this.curve.red); if (this.t && !this.t.red) this.t = this.t.toRed(this.curve.red); this.zOne = this.z === this.curve.one; if (this.curve.extended && !this.t) { this.t = this.x.redMul(this.y); if (!this.zOne) this.t = this.t.redMul(this.z.redInvm()); } } } inherits(Point2, Base.BasePoint); EdwardsCurve.prototype.pointFromJSON = function pointFromJSON2(obj) { return Point2.fromJSON(this, obj); }; EdwardsCurve.prototype.point = function point3(x6, y6, z6, t) { return new Point2(this, x6, y6, z6, t); }; Point2.fromJSON = function fromJSON2(curve, obj) { return new Point2(curve, obj[0], obj[1], obj[2]); }; Point2.prototype.inspect = function inspect4() { if (this.isInfinity()) return ""; return ""; }; Point2.prototype.isInfinity = function isInfinity3() { return this.x.cmpn(0) === 0 && (this.y.cmp(this.z) === 0 || this.zOne && this.y.cmp(this.curve.c) === 0); }; Point2.prototype._extDbl = function _extDbl() { var a4 = this.x.redSqr(); var b5 = this.y.redSqr(); var c5 = this.z.redSqr(); c5 = c5.redIAdd(c5); var d3 = this.curve._mulA(a4); var e2 = this.x.redAdd(this.y).redSqr().redISub(a4).redISub(b5); var g4 = d3.redAdd(b5); var f4 = g4.redSub(c5); var h5 = d3.redSub(b5); var nx = e2.redMul(f4); var ny = g4.redMul(h5); var nt3 = e2.redMul(h5); var nz = f4.redMul(g4); return this.curve.point(nx, ny, nz, nt3); }; Point2.prototype._projDbl = function _projDbl() { var b5 = this.x.redAdd(this.y).redSqr(); var c5 = this.x.redSqr(); var d3 = this.y.redSqr(); var nx; var ny; var nz; var e2; var h5; var j2; if (this.curve.twisted) { e2 = this.curve._mulA(c5); var f4 = e2.redAdd(d3); if (this.zOne) { nx = b5.redSub(c5).redSub(d3).redMul(f4.redSub(this.curve.two)); ny = f4.redMul(e2.redSub(d3)); nz = f4.redSqr().redSub(f4).redSub(f4); } else { h5 = this.z.redSqr(); j2 = f4.redSub(h5).redISub(h5); nx = b5.redSub(c5).redISub(d3).redMul(j2); ny = f4.redMul(e2.redSub(d3)); nz = f4.redMul(j2); } } else { e2 = c5.redAdd(d3); h5 = this.curve._mulC(this.z).redSqr(); j2 = e2.redSub(h5).redSub(h5); nx = this.curve._mulC(b5.redISub(e2)).redMul(j2); ny = this.curve._mulC(e2).redMul(c5.redISub(d3)); nz = e2.redMul(j2); } return this.curve.point(nx, ny, nz); }; Point2.prototype.dbl = function dbl3() { if (this.isInfinity()) return this; if (this.curve.extended) return this._extDbl(); else return this._projDbl(); }; Point2.prototype._extAdd = function _extAdd(p3) { var a4 = this.y.redSub(this.x).redMul(p3.y.redSub(p3.x)); var b5 = this.y.redAdd(this.x).redMul(p3.y.redAdd(p3.x)); var c5 = this.t.redMul(this.curve.dd).redMul(p3.t); var d3 = this.z.redMul(p3.z.redAdd(p3.z)); var e2 = b5.redSub(a4); var f4 = d3.redSub(c5); var g4 = d3.redAdd(c5); var h5 = b5.redAdd(a4); var nx = e2.redMul(f4); var ny = g4.redMul(h5); var nt3 = e2.redMul(h5); var nz = f4.redMul(g4); return this.curve.point(nx, ny, nz, nt3); }; Point2.prototype._projAdd = function _projAdd(p3) { var a4 = this.z.redMul(p3.z); var b5 = a4.redSqr(); var c5 = this.x.redMul(p3.x); var d3 = this.y.redMul(p3.y); var e2 = this.curve.d.redMul(c5).redMul(d3); var f4 = b5.redSub(e2); var g4 = b5.redAdd(e2); var tmp = this.x.redAdd(this.y).redMul(p3.x.redAdd(p3.y)).redISub(c5).redISub(d3); var nx = a4.redMul(f4).redMul(tmp); var ny; var nz; if (this.curve.twisted) { ny = a4.redMul(g4).redMul(d3.redSub(this.curve._mulA(c5))); nz = f4.redMul(g4); } else { ny = a4.redMul(g4).redMul(d3.redSub(c5)); nz = this.curve._mulC(f4).redMul(g4); } return this.curve.point(nx, ny, nz); }; Point2.prototype.add = function add3(p3) { if (this.isInfinity()) return p3; if (p3.isInfinity()) return this; if (this.curve.extended) return this._extAdd(p3); else return this._projAdd(p3); }; Point2.prototype.mul = function mul3(k4) { if (this._hasDoubles(k4)) return this.curve._fixedNafMul(this, k4); else return this.curve._wnafMul(this, k4); }; Point2.prototype.mulAdd = function mulAdd2(k1, p3, k22) { return this.curve._wnafMulAdd(1, [this, p3], [k1, k22], 2, false); }; Point2.prototype.jmulAdd = function jmulAdd2(k1, p3, k22) { return this.curve._wnafMulAdd(1, [this, p3], [k1, k22], 2, true); }; Point2.prototype.normalize = function normalize() { if (this.zOne) return this; var zi2 = this.z.redInvm(); this.x = this.x.redMul(zi2); this.y = this.y.redMul(zi2); if (this.t) this.t = this.t.redMul(zi2); this.z = this.curve.one; this.zOne = true; return this; }; Point2.prototype.neg = function neg3() { return this.curve.point( this.x.redNeg(), this.y, this.z, this.t && this.t.redNeg() ); }; Point2.prototype.getX = function getX2() { this.normalize(); return this.x.fromRed(); }; Point2.prototype.getY = function getY2() { this.normalize(); return this.y.fromRed(); }; Point2.prototype.eq = function eq4(other) { return this === other || this.getX().cmp(other.getX()) === 0 && this.getY().cmp(other.getY()) === 0; }; Point2.prototype.eqXToP = function eqXToP2(x6) { var rx = x6.toRed(this.curve.red).redMul(this.z); if (this.x.cmp(rx) === 0) return true; var xc = x6.clone(); var t = this.curve.redN.redMul(this.z); for (; ; ) { xc.iadd(this.curve.n); if (xc.cmp(this.curve.p) >= 0) return false; rx.redIAdd(t); if (this.x.cmp(rx) === 0) return true; } }; Point2.prototype.toP = Point2.prototype.normalize; Point2.prototype.mixedAdd = Point2.prototype.add; } }); // node_modules/elliptic/lib/elliptic/curve/index.js var require_curve = __commonJS({ "node_modules/elliptic/lib/elliptic/curve/index.js"(exports) { "use strict"; var curve = exports; curve.base = require_base(); curve.short = require_short(); curve.mont = require_mont(); curve.edwards = require_edwards(); } }); // node_modules/elliptic/lib/elliptic/precomputed/secp256k1.js var require_secp256k1 = __commonJS({ "node_modules/elliptic/lib/elliptic/precomputed/secp256k1.js"(exports, module) { module.exports = { doubles: { step: 4, points: [ [ "e60fce93b59e9ec53011aabc21c23e97b2a31369b87a5ae9c44ee89e2a6dec0a", "f7e3507399e595929db99f34f57937101296891e44d23f0be1f32cce69616821" ], [ "8282263212c609d9ea2a6e3e172de238d8c39cabd5ac1ca10646e23fd5f51508", "11f8a8098557dfe45e8256e830b60ace62d613ac2f7b17bed31b6eaff6e26caf" ], [ "175e159f728b865a72f99cc6c6fc846de0b93833fd2222ed73fce5b551e5b739", "d3506e0d9e3c79eba4ef97a51ff71f5eacb5955add24345c6efa6ffee9fed695" ], [ "363d90d447b00c9c99ceac05b6262ee053441c7e55552ffe526bad8f83ff4640", "4e273adfc732221953b445397f3363145b9a89008199ecb62003c7f3bee9de9" ], [ "8b4b5f165df3c2be8c6244b5b745638843e4a781a15bcd1b69f79a55dffdf80c", "4aad0a6f68d308b4b3fbd7813ab0da04f9e336546162ee56b3eff0c65fd4fd36" ], [ "723cbaa6e5db996d6bf771c00bd548c7b700dbffa6c0e77bcb6115925232fcda", "96e867b5595cc498a921137488824d6e2660a0653779494801dc069d9eb39f5f" ], [ "eebfa4d493bebf98ba5feec812c2d3b50947961237a919839a533eca0e7dd7fa", "5d9a8ca3970ef0f269ee7edaf178089d9ae4cdc3a711f712ddfd4fdae1de8999" ], [ "100f44da696e71672791d0a09b7bde459f1215a29b3c03bfefd7835b39a48db0", "cdd9e13192a00b772ec8f3300c090666b7ff4a18ff5195ac0fbd5cd62bc65a09" ], [ "e1031be262c7ed1b1dc9227a4a04c017a77f8d4464f3b3852c8acde6e534fd2d", "9d7061928940405e6bb6a4176597535af292dd419e1ced79a44f18f29456a00d" ], [ "feea6cae46d55b530ac2839f143bd7ec5cf8b266a41d6af52d5e688d9094696d", "e57c6b6c97dce1bab06e4e12bf3ecd5c981c8957cc41442d3155debf18090088" ], [ "da67a91d91049cdcb367be4be6ffca3cfeed657d808583de33fa978bc1ec6cb1", "9bacaa35481642bc41f463f7ec9780e5dec7adc508f740a17e9ea8e27a68be1d" ], [ "53904faa0b334cdda6e000935ef22151ec08d0f7bb11069f57545ccc1a37b7c0", "5bc087d0bc80106d88c9eccac20d3c1c13999981e14434699dcb096b022771c8" ], [ "8e7bcd0bd35983a7719cca7764ca906779b53a043a9b8bcaeff959f43ad86047", "10b7770b2a3da4b3940310420ca9514579e88e2e47fd68b3ea10047e8460372a" ], [ "385eed34c1cdff21e6d0818689b81bde71a7f4f18397e6690a841e1599c43862", "283bebc3e8ea23f56701de19e9ebf4576b304eec2086dc8cc0458fe5542e5453" ], [ "6f9d9b803ecf191637c73a4413dfa180fddf84a5947fbc9c606ed86c3fac3a7", "7c80c68e603059ba69b8e2a30e45c4d47ea4dd2f5c281002d86890603a842160" ], [ "3322d401243c4e2582a2147c104d6ecbf774d163db0f5e5313b7e0e742d0e6bd", "56e70797e9664ef5bfb019bc4ddaf9b72805f63ea2873af624f3a2e96c28b2a0" ], [ "85672c7d2de0b7da2bd1770d89665868741b3f9af7643397721d74d28134ab83", "7c481b9b5b43b2eb6374049bfa62c2e5e77f17fcc5298f44c8e3094f790313a6" ], [ "948bf809b1988a46b06c9f1919413b10f9226c60f668832ffd959af60c82a0a", "53a562856dcb6646dc6b74c5d1c3418c6d4dff08c97cd2bed4cb7f88d8c8e589" ], [ "6260ce7f461801c34f067ce0f02873a8f1b0e44dfc69752accecd819f38fd8e8", "bc2da82b6fa5b571a7f09049776a1ef7ecd292238051c198c1a84e95b2b4ae17" ], [ "e5037de0afc1d8d43d8348414bbf4103043ec8f575bfdc432953cc8d2037fa2d", "4571534baa94d3b5f9f98d09fb990bddbd5f5b03ec481f10e0e5dc841d755bda" ], [ "e06372b0f4a207adf5ea905e8f1771b4e7e8dbd1c6a6c5b725866a0ae4fce725", "7a908974bce18cfe12a27bb2ad5a488cd7484a7787104870b27034f94eee31dd" ], [ "213c7a715cd5d45358d0bbf9dc0ce02204b10bdde2a3f58540ad6908d0559754", "4b6dad0b5ae462507013ad06245ba190bb4850f5f36a7eeddff2c27534b458f2" ], [ "4e7c272a7af4b34e8dbb9352a5419a87e2838c70adc62cddf0cc3a3b08fbd53c", "17749c766c9d0b18e16fd09f6def681b530b9614bff7dd33e0b3941817dcaae6" ], [ "fea74e3dbe778b1b10f238ad61686aa5c76e3db2be43057632427e2840fb27b6", "6e0568db9b0b13297cf674deccb6af93126b596b973f7b77701d3db7f23cb96f" ], [ "76e64113f677cf0e10a2570d599968d31544e179b760432952c02a4417bdde39", "c90ddf8dee4e95cf577066d70681f0d35e2a33d2b56d2032b4b1752d1901ac01" ], [ "c738c56b03b2abe1e8281baa743f8f9a8f7cc643df26cbee3ab150242bcbb891", "893fb578951ad2537f718f2eacbfbbbb82314eef7880cfe917e735d9699a84c3" ], [ "d895626548b65b81e264c7637c972877d1d72e5f3a925014372e9f6588f6c14b", "febfaa38f2bc7eae728ec60818c340eb03428d632bb067e179363ed75d7d991f" ], [ "b8da94032a957518eb0f6433571e8761ceffc73693e84edd49150a564f676e03", "2804dfa44805a1e4d7c99cc9762808b092cc584d95ff3b511488e4e74efdf6e7" ], [ "e80fea14441fb33a7d8adab9475d7fab2019effb5156a792f1a11778e3c0df5d", "eed1de7f638e00771e89768ca3ca94472d155e80af322ea9fcb4291b6ac9ec78" ], [ "a301697bdfcd704313ba48e51d567543f2a182031efd6915ddc07bbcc4e16070", "7370f91cfb67e4f5081809fa25d40f9b1735dbf7c0a11a130c0d1a041e177ea1" ], [ "90ad85b389d6b936463f9d0512678de208cc330b11307fffab7ac63e3fb04ed4", "e507a3620a38261affdcbd9427222b839aefabe1582894d991d4d48cb6ef150" ], [ "8f68b9d2f63b5f339239c1ad981f162ee88c5678723ea3351b7b444c9ec4c0da", "662a9f2dba063986de1d90c2b6be215dbbea2cfe95510bfdf23cbf79501fff82" ], [ "e4f3fb0176af85d65ff99ff9198c36091f48e86503681e3e6686fd5053231e11", "1e63633ad0ef4f1c1661a6d0ea02b7286cc7e74ec951d1c9822c38576feb73bc" ], [ "8c00fa9b18ebf331eb961537a45a4266c7034f2f0d4e1d0716fb6eae20eae29e", "efa47267fea521a1a9dc343a3736c974c2fadafa81e36c54e7d2a4c66702414b" ], [ "e7a26ce69dd4829f3e10cec0a9e98ed3143d084f308b92c0997fddfc60cb3e41", "2a758e300fa7984b471b006a1aafbb18d0a6b2c0420e83e20e8a9421cf2cfd51" ], [ "b6459e0ee3662ec8d23540c223bcbdc571cbcb967d79424f3cf29eb3de6b80ef", "67c876d06f3e06de1dadf16e5661db3c4b3ae6d48e35b2ff30bf0b61a71ba45" ], [ "d68a80c8280bb840793234aa118f06231d6f1fc67e73c5a5deda0f5b496943e8", "db8ba9fff4b586d00c4b1f9177b0e28b5b0e7b8f7845295a294c84266b133120" ], [ "324aed7df65c804252dc0270907a30b09612aeb973449cea4095980fc28d3d5d", "648a365774b61f2ff130c0c35aec1f4f19213b0c7e332843967224af96ab7c84" ], [ "4df9c14919cde61f6d51dfdbe5fee5dceec4143ba8d1ca888e8bd373fd054c96", "35ec51092d8728050974c23a1d85d4b5d506cdc288490192ebac06cad10d5d" ], [ "9c3919a84a474870faed8a9c1cc66021523489054d7f0308cbfc99c8ac1f98cd", "ddb84f0f4a4ddd57584f044bf260e641905326f76c64c8e6be7e5e03d4fc599d" ], [ "6057170b1dd12fdf8de05f281d8e06bb91e1493a8b91d4cc5a21382120a959e5", "9a1af0b26a6a4807add9a2daf71df262465152bc3ee24c65e899be932385a2a8" ], [ "a576df8e23a08411421439a4518da31880cef0fba7d4df12b1a6973eecb94266", "40a6bf20e76640b2c92b97afe58cd82c432e10a7f514d9f3ee8be11ae1b28ec8" ], [ "7778a78c28dec3e30a05fe9629de8c38bb30d1f5cf9a3a208f763889be58ad71", "34626d9ab5a5b22ff7098e12f2ff580087b38411ff24ac563b513fc1fd9f43ac" ], [ "928955ee637a84463729fd30e7afd2ed5f96274e5ad7e5cb09eda9c06d903ac", "c25621003d3f42a827b78a13093a95eeac3d26efa8a8d83fc5180e935bcd091f" ], [ "85d0fef3ec6db109399064f3a0e3b2855645b4a907ad354527aae75163d82751", "1f03648413a38c0be29d496e582cf5663e8751e96877331582c237a24eb1f962" ], [ "ff2b0dce97eece97c1c9b6041798b85dfdfb6d8882da20308f5404824526087e", "493d13fef524ba188af4c4dc54d07936c7b7ed6fb90e2ceb2c951e01f0c29907" ], [ "827fbbe4b1e880ea9ed2b2e6301b212b57f1ee148cd6dd28780e5e2cf856e241", "c60f9c923c727b0b71bef2c67d1d12687ff7a63186903166d605b68baec293ec" ], [ "eaa649f21f51bdbae7be4ae34ce6e5217a58fdce7f47f9aa7f3b58fa2120e2b3", "be3279ed5bbbb03ac69a80f89879aa5a01a6b965f13f7e59d47a5305ba5ad93d" ], [ "e4a42d43c5cf169d9391df6decf42ee541b6d8f0c9a137401e23632dda34d24f", "4d9f92e716d1c73526fc99ccfb8ad34ce886eedfa8d8e4f13a7f7131deba9414" ], [ "1ec80fef360cbdd954160fadab352b6b92b53576a88fea4947173b9d4300bf19", "aeefe93756b5340d2f3a4958a7abbf5e0146e77f6295a07b671cdc1cc107cefd" ], [ "146a778c04670c2f91b00af4680dfa8bce3490717d58ba889ddb5928366642be", "b318e0ec3354028add669827f9d4b2870aaa971d2f7e5ed1d0b297483d83efd0" ], [ "fa50c0f61d22e5f07e3acebb1aa07b128d0012209a28b9776d76a8793180eef9", "6b84c6922397eba9b72cd2872281a68a5e683293a57a213b38cd8d7d3f4f2811" ], [ "da1d61d0ca721a11b1a5bf6b7d88e8421a288ab5d5bba5220e53d32b5f067ec2", "8157f55a7c99306c79c0766161c91e2966a73899d279b48a655fba0f1ad836f1" ], [ "a8e282ff0c9706907215ff98e8fd416615311de0446f1e062a73b0610d064e13", "7f97355b8db81c09abfb7f3c5b2515888b679a3e50dd6bd6cef7c73111f4cc0c" ], [ "174a53b9c9a285872d39e56e6913cab15d59b1fa512508c022f382de8319497c", "ccc9dc37abfc9c1657b4155f2c47f9e6646b3a1d8cb9854383da13ac079afa73" ], [ "959396981943785c3d3e57edf5018cdbe039e730e4918b3d884fdff09475b7ba", "2e7e552888c331dd8ba0386a4b9cd6849c653f64c8709385e9b8abf87524f2fd" ], [ "d2a63a50ae401e56d645a1153b109a8fcca0a43d561fba2dbb51340c9d82b151", "e82d86fb6443fcb7565aee58b2948220a70f750af484ca52d4142174dcf89405" ], [ "64587e2335471eb890ee7896d7cfdc866bacbdbd3839317b3436f9b45617e073", "d99fcdd5bf6902e2ae96dd6447c299a185b90a39133aeab358299e5e9faf6589" ], [ "8481bde0e4e4d885b3a546d3e549de042f0aa6cea250e7fd358d6c86dd45e458", "38ee7b8cba5404dd84a25bf39cecb2ca900a79c42b262e556d64b1b59779057e" ], [ "13464a57a78102aa62b6979ae817f4637ffcfed3c4b1ce30bcd6303f6caf666b", "69be159004614580ef7e433453ccb0ca48f300a81d0942e13f495a907f6ecc27" ], [ "bc4a9df5b713fe2e9aef430bcc1dc97a0cd9ccede2f28588cada3a0d2d83f366", "d3a81ca6e785c06383937adf4b798caa6e8a9fbfa547b16d758d666581f33c1" ], [ "8c28a97bf8298bc0d23d8c749452a32e694b65e30a9472a3954ab30fe5324caa", "40a30463a3305193378fedf31f7cc0eb7ae784f0451cb9459e71dc73cbef9482" ], [ "8ea9666139527a8c1dd94ce4f071fd23c8b350c5a4bb33748c4ba111faccae0", "620efabbc8ee2782e24e7c0cfb95c5d735b783be9cf0f8e955af34a30e62b945" ], [ "dd3625faef5ba06074669716bbd3788d89bdde815959968092f76cc4eb9a9787", "7a188fa3520e30d461da2501045731ca941461982883395937f68d00c644a573" ], [ "f710d79d9eb962297e4f6232b40e8f7feb2bc63814614d692c12de752408221e", "ea98e67232d3b3295d3b535532115ccac8612c721851617526ae47a9c77bfc82" ] ] }, naf: { wnd: 7, points: [ [ "f9308a019258c31049344f85f89d5229b531c845836f99b08601f113bce036f9", "388f7b0f632de8140fe337e62a37f3566500a99934c2231b6cb9fd7584b8e672" ], [ "2f8bde4d1a07209355b4a7250a5c5128e88b84bddc619ab7cba8d569b240efe4", "d8ac222636e5e3d6d4dba9dda6c9c426f788271bab0d6840dca87d3aa6ac62d6" ], [ "5cbdf0646e5db4eaa398f365f2ea7a0e3d419b7e0330e39ce92bddedcac4f9bc", "6aebca40ba255960a3178d6d861a54dba813d0b813fde7b5a5082628087264da" ], [ "acd484e2f0c7f65309ad178a9f559abde09796974c57e714c35f110dfc27ccbe", "cc338921b0a7d9fd64380971763b61e9add888a4375f8e0f05cc262ac64f9c37" ], [ "774ae7f858a9411e5ef4246b70c65aac5649980be5c17891bbec17895da008cb", "d984a032eb6b5e190243dd56d7b7b365372db1e2dff9d6a8301d74c9c953c61b" ], [ "f28773c2d975288bc7d1d205c3748651b075fbc6610e58cddeeddf8f19405aa8", "ab0902e8d880a89758212eb65cdaf473a1a06da521fa91f29b5cb52db03ed81" ], [ "d7924d4f7d43ea965a465ae3095ff41131e5946f3c85f79e44adbcf8e27e080e", "581e2872a86c72a683842ec228cc6defea40af2bd896d3a5c504dc9ff6a26b58" ], [ "defdea4cdb677750a420fee807eacf21eb9898ae79b9768766e4faa04a2d4a34", "4211ab0694635168e997b0ead2a93daeced1f4a04a95c0f6cfb199f69e56eb77" ], [ "2b4ea0a797a443d293ef5cff444f4979f06acfebd7e86d277475656138385b6c", "85e89bc037945d93b343083b5a1c86131a01f60c50269763b570c854e5c09b7a" ], [ "352bbf4a4cdd12564f93fa332ce333301d9ad40271f8107181340aef25be59d5", "321eb4075348f534d59c18259dda3e1f4a1b3b2e71b1039c67bd3d8bcf81998c" ], [ "2fa2104d6b38d11b0230010559879124e42ab8dfeff5ff29dc9cdadd4ecacc3f", "2de1068295dd865b64569335bd5dd80181d70ecfc882648423ba76b532b7d67" ], [ "9248279b09b4d68dab21a9b066edda83263c3d84e09572e269ca0cd7f5453714", "73016f7bf234aade5d1aa71bdea2b1ff3fc0de2a887912ffe54a32ce97cb3402" ], [ "daed4f2be3a8bf278e70132fb0beb7522f570e144bf615c07e996d443dee8729", "a69dce4a7d6c98e8d4a1aca87ef8d7003f83c230f3afa726ab40e52290be1c55" ], [ "c44d12c7065d812e8acf28d7cbb19f9011ecd9e9fdf281b0e6a3b5e87d22e7db", "2119a460ce326cdc76c45926c982fdac0e106e861edf61c5a039063f0e0e6482" ], [ "6a245bf6dc698504c89a20cfded60853152b695336c28063b61c65cbd269e6b4", "e022cf42c2bd4a708b3f5126f16a24ad8b33ba48d0423b6efd5e6348100d8a82" ], [ "1697ffa6fd9de627c077e3d2fe541084ce13300b0bec1146f95ae57f0d0bd6a5", "b9c398f186806f5d27561506e4557433a2cf15009e498ae7adee9d63d01b2396" ], [ "605bdb019981718b986d0f07e834cb0d9deb8360ffb7f61df982345ef27a7479", "2972d2de4f8d20681a78d93ec96fe23c26bfae84fb14db43b01e1e9056b8c49" ], [ "62d14dab4150bf497402fdc45a215e10dcb01c354959b10cfe31c7e9d87ff33d", "80fc06bd8cc5b01098088a1950eed0db01aa132967ab472235f5642483b25eaf" ], [ "80c60ad0040f27dade5b4b06c408e56b2c50e9f56b9b8b425e555c2f86308b6f", "1c38303f1cc5c30f26e66bad7fe72f70a65eed4cbe7024eb1aa01f56430bd57a" ], [ "7a9375ad6167ad54aa74c6348cc54d344cc5dc9487d847049d5eabb0fa03c8fb", "d0e3fa9eca8726909559e0d79269046bdc59ea10c70ce2b02d499ec224dc7f7" ], [ "d528ecd9b696b54c907a9ed045447a79bb408ec39b68df504bb51f459bc3ffc9", "eecf41253136e5f99966f21881fd656ebc4345405c520dbc063465b521409933" ], [ "49370a4b5f43412ea25f514e8ecdad05266115e4a7ecb1387231808f8b45963", "758f3f41afd6ed428b3081b0512fd62a54c3f3afbb5b6764b653052a12949c9a" ], [ "77f230936ee88cbbd73df930d64702ef881d811e0e1498e2f1c13eb1fc345d74", "958ef42a7886b6400a08266e9ba1b37896c95330d97077cbbe8eb3c7671c60d6" ], [ "f2dac991cc4ce4b9ea44887e5c7c0bce58c80074ab9d4dbaeb28531b7739f530", "e0dedc9b3b2f8dad4da1f32dec2531df9eb5fbeb0598e4fd1a117dba703a3c37" ], [ "463b3d9f662621fb1b4be8fbbe2520125a216cdfc9dae3debcba4850c690d45b", "5ed430d78c296c3543114306dd8622d7c622e27c970a1de31cb377b01af7307e" ], [ "f16f804244e46e2a09232d4aff3b59976b98fac14328a2d1a32496b49998f247", "cedabd9b82203f7e13d206fcdf4e33d92a6c53c26e5cce26d6579962c4e31df6" ], [ "caf754272dc84563b0352b7a14311af55d245315ace27c65369e15f7151d41d1", "cb474660ef35f5f2a41b643fa5e460575f4fa9b7962232a5c32f908318a04476" ], [ "2600ca4b282cb986f85d0f1709979d8b44a09c07cb86d7c124497bc86f082120", "4119b88753c15bd6a693b03fcddbb45d5ac6be74ab5f0ef44b0be9475a7e4b40" ], [ "7635ca72d7e8432c338ec53cd12220bc01c48685e24f7dc8c602a7746998e435", "91b649609489d613d1d5e590f78e6d74ecfc061d57048bad9e76f302c5b9c61" ], [ "754e3239f325570cdbbf4a87deee8a66b7f2b33479d468fbc1a50743bf56cc18", "673fb86e5bda30fb3cd0ed304ea49a023ee33d0197a695d0c5d98093c536683" ], [ "e3e6bd1071a1e96aff57859c82d570f0330800661d1c952f9fe2694691d9b9e8", "59c9e0bba394e76f40c0aa58379a3cb6a5a2283993e90c4167002af4920e37f5" ], [ "186b483d056a033826ae73d88f732985c4ccb1f32ba35f4b4cc47fdcf04aa6eb", "3b952d32c67cf77e2e17446e204180ab21fb8090895138b4a4a797f86e80888b" ], [ "df9d70a6b9876ce544c98561f4be4f725442e6d2b737d9c91a8321724ce0963f", "55eb2dafd84d6ccd5f862b785dc39d4ab157222720ef9da217b8c45cf2ba2417" ], [ "5edd5cc23c51e87a497ca815d5dce0f8ab52554f849ed8995de64c5f34ce7143", "efae9c8dbc14130661e8cec030c89ad0c13c66c0d17a2905cdc706ab7399a868" ], [ "290798c2b6476830da12fe02287e9e777aa3fba1c355b17a722d362f84614fba", "e38da76dcd440621988d00bcf79af25d5b29c094db2a23146d003afd41943e7a" ], [ "af3c423a95d9f5b3054754efa150ac39cd29552fe360257362dfdecef4053b45", "f98a3fd831eb2b749a93b0e6f35cfb40c8cd5aa667a15581bc2feded498fd9c6" ], [ "766dbb24d134e745cccaa28c99bf274906bb66b26dcf98df8d2fed50d884249a", "744b1152eacbe5e38dcc887980da38b897584a65fa06cedd2c924f97cbac5996" ], [ "59dbf46f8c94759ba21277c33784f41645f7b44f6c596a58ce92e666191abe3e", "c534ad44175fbc300f4ea6ce648309a042ce739a7919798cd85e216c4a307f6e" ], [ "f13ada95103c4537305e691e74e9a4a8dd647e711a95e73cb62dc6018cfd87b8", "e13817b44ee14de663bf4bc808341f326949e21a6a75c2570778419bdaf5733d" ], [ "7754b4fa0e8aced06d4167a2c59cca4cda1869c06ebadfb6488550015a88522c", "30e93e864e669d82224b967c3020b8fa8d1e4e350b6cbcc537a48b57841163a2" ], [ "948dcadf5990e048aa3874d46abef9d701858f95de8041d2a6828c99e2262519", "e491a42537f6e597d5d28a3224b1bc25df9154efbd2ef1d2cbba2cae5347d57e" ], [ "7962414450c76c1689c7b48f8202ec37fb224cf5ac0bfa1570328a8a3d7c77ab", "100b610ec4ffb4760d5c1fc133ef6f6b12507a051f04ac5760afa5b29db83437" ], [ "3514087834964b54b15b160644d915485a16977225b8847bb0dd085137ec47ca", "ef0afbb2056205448e1652c48e8127fc6039e77c15c2378b7e7d15a0de293311" ], [ "d3cc30ad6b483e4bc79ce2c9dd8bc54993e947eb8df787b442943d3f7b527eaf", "8b378a22d827278d89c5e9be8f9508ae3c2ad46290358630afb34db04eede0a4" ], [ "1624d84780732860ce1c78fcbfefe08b2b29823db913f6493975ba0ff4847610", "68651cf9b6da903e0914448c6cd9d4ca896878f5282be4c8cc06e2a404078575" ], [ "733ce80da955a8a26902c95633e62a985192474b5af207da6df7b4fd5fc61cd4", "f5435a2bd2badf7d485a4d8b8db9fcce3e1ef8e0201e4578c54673bc1dc5ea1d" ], [ "15d9441254945064cf1a1c33bbd3b49f8966c5092171e699ef258dfab81c045c", "d56eb30b69463e7234f5137b73b84177434800bacebfc685fc37bbe9efe4070d" ], [ "a1d0fcf2ec9de675b612136e5ce70d271c21417c9d2b8aaaac138599d0717940", "edd77f50bcb5a3cab2e90737309667f2641462a54070f3d519212d39c197a629" ], [ "e22fbe15c0af8ccc5780c0735f84dbe9a790badee8245c06c7ca37331cb36980", "a855babad5cd60c88b430a69f53a1a7a38289154964799be43d06d77d31da06" ], [ "311091dd9860e8e20ee13473c1155f5f69635e394704eaa74009452246cfa9b3", "66db656f87d1f04fffd1f04788c06830871ec5a64feee685bd80f0b1286d8374" ], [ "34c1fd04d301be89b31c0442d3e6ac24883928b45a9340781867d4232ec2dbdf", "9414685e97b1b5954bd46f730174136d57f1ceeb487443dc5321857ba73abee" ], [ "f219ea5d6b54701c1c14de5b557eb42a8d13f3abbcd08affcc2a5e6b049b8d63", "4cb95957e83d40b0f73af4544cccf6b1f4b08d3c07b27fb8d8c2962a400766d1" ], [ "d7b8740f74a8fbaab1f683db8f45de26543a5490bca627087236912469a0b448", "fa77968128d9c92ee1010f337ad4717eff15db5ed3c049b3411e0315eaa4593b" ], [ "32d31c222f8f6f0ef86f7c98d3a3335ead5bcd32abdd94289fe4d3091aa824bf", "5f3032f5892156e39ccd3d7915b9e1da2e6dac9e6f26e961118d14b8462e1661" ], [ "7461f371914ab32671045a155d9831ea8793d77cd59592c4340f86cbc18347b5", "8ec0ba238b96bec0cbdddcae0aa442542eee1ff50c986ea6b39847b3cc092ff6" ], [ "ee079adb1df1860074356a25aa38206a6d716b2c3e67453d287698bad7b2b2d6", "8dc2412aafe3be5c4c5f37e0ecc5f9f6a446989af04c4e25ebaac479ec1c8c1e" ], [ "16ec93e447ec83f0467b18302ee620f7e65de331874c9dc72bfd8616ba9da6b5", "5e4631150e62fb40d0e8c2a7ca5804a39d58186a50e497139626778e25b0674d" ], [ "eaa5f980c245f6f038978290afa70b6bd8855897f98b6aa485b96065d537bd99", "f65f5d3e292c2e0819a528391c994624d784869d7e6ea67fb18041024edc07dc" ], [ "78c9407544ac132692ee1910a02439958ae04877151342ea96c4b6b35a49f51", "f3e0319169eb9b85d5404795539a5e68fa1fbd583c064d2462b675f194a3ddb4" ], [ "494f4be219a1a77016dcd838431aea0001cdc8ae7a6fc688726578d9702857a5", "42242a969283a5f339ba7f075e36ba2af925ce30d767ed6e55f4b031880d562c" ], [ "a598a8030da6d86c6bc7f2f5144ea549d28211ea58faa70ebf4c1e665c1fe9b5", "204b5d6f84822c307e4b4a7140737aec23fc63b65b35f86a10026dbd2d864e6b" ], [ "c41916365abb2b5d09192f5f2dbeafec208f020f12570a184dbadc3e58595997", "4f14351d0087efa49d245b328984989d5caf9450f34bfc0ed16e96b58fa9913" ], [ "841d6063a586fa475a724604da03bc5b92a2e0d2e0a36acfe4c73a5514742881", "73867f59c0659e81904f9a1c7543698e62562d6744c169ce7a36de01a8d6154" ], [ "5e95bb399a6971d376026947f89bde2f282b33810928be4ded112ac4d70e20d5", "39f23f366809085beebfc71181313775a99c9aed7d8ba38b161384c746012865" ], [ "36e4641a53948fd476c39f8a99fd974e5ec07564b5315d8bf99471bca0ef2f66", "d2424b1b1abe4eb8164227b085c9aa9456ea13493fd563e06fd51cf5694c78fc" ], [ "336581ea7bfbbb290c191a2f507a41cf5643842170e914faeab27c2c579f726", "ead12168595fe1be99252129b6e56b3391f7ab1410cd1e0ef3dcdcabd2fda224" ], [ "8ab89816dadfd6b6a1f2634fcf00ec8403781025ed6890c4849742706bd43ede", "6fdcef09f2f6d0a044e654aef624136f503d459c3e89845858a47a9129cdd24e" ], [ "1e33f1a746c9c5778133344d9299fcaa20b0938e8acff2544bb40284b8c5fb94", "60660257dd11b3aa9c8ed618d24edff2306d320f1d03010e33a7d2057f3b3b6" ], [ "85b7c1dcb3cec1b7ee7f30ded79dd20a0ed1f4cc18cbcfcfa410361fd8f08f31", "3d98a9cdd026dd43f39048f25a8847f4fcafad1895d7a633c6fed3c35e999511" ], [ "29df9fbd8d9e46509275f4b125d6d45d7fbe9a3b878a7af872a2800661ac5f51", "b4c4fe99c775a606e2d8862179139ffda61dc861c019e55cd2876eb2a27d84b" ], [ "a0b1cae06b0a847a3fea6e671aaf8adfdfe58ca2f768105c8082b2e449fce252", "ae434102edde0958ec4b19d917a6a28e6b72da1834aff0e650f049503a296cf2" ], [ "4e8ceafb9b3e9a136dc7ff67e840295b499dfb3b2133e4ba113f2e4c0e121e5", "cf2174118c8b6d7a4b48f6d534ce5c79422c086a63460502b827ce62a326683c" ], [ "d24a44e047e19b6f5afb81c7ca2f69080a5076689a010919f42725c2b789a33b", "6fb8d5591b466f8fc63db50f1c0f1c69013f996887b8244d2cdec417afea8fa3" ], [ "ea01606a7a6c9cdd249fdfcfacb99584001edd28abbab77b5104e98e8e3b35d4", "322af4908c7312b0cfbfe369f7a7b3cdb7d4494bc2823700cfd652188a3ea98d" ], [ "af8addbf2b661c8a6c6328655eb96651252007d8c5ea31be4ad196de8ce2131f", "6749e67c029b85f52a034eafd096836b2520818680e26ac8f3dfbcdb71749700" ], [ "e3ae1974566ca06cc516d47e0fb165a674a3dabcfca15e722f0e3450f45889", "2aeabe7e4531510116217f07bf4d07300de97e4874f81f533420a72eeb0bd6a4" ], [ "591ee355313d99721cf6993ffed1e3e301993ff3ed258802075ea8ced397e246", "b0ea558a113c30bea60fc4775460c7901ff0b053d25ca2bdeee98f1a4be5d196" ], [ "11396d55fda54c49f19aa97318d8da61fa8584e47b084945077cf03255b52984", "998c74a8cd45ac01289d5833a7beb4744ff536b01b257be4c5767bea93ea57a4" ], [ "3c5d2a1ba39c5a1790000738c9e0c40b8dcdfd5468754b6405540157e017aa7a", "b2284279995a34e2f9d4de7396fc18b80f9b8b9fdd270f6661f79ca4c81bd257" ], [ "cc8704b8a60a0defa3a99a7299f2e9c3fbc395afb04ac078425ef8a1793cc030", "bdd46039feed17881d1e0862db347f8cf395b74fc4bcdc4e940b74e3ac1f1b13" ], [ "c533e4f7ea8555aacd9777ac5cad29b97dd4defccc53ee7ea204119b2889b197", "6f0a256bc5efdf429a2fb6242f1a43a2d9b925bb4a4b3a26bb8e0f45eb596096" ], [ "c14f8f2ccb27d6f109f6d08d03cc96a69ba8c34eec07bbcf566d48e33da6593", "c359d6923bb398f7fd4473e16fe1c28475b740dd098075e6c0e8649113dc3a38" ], [ "a6cbc3046bc6a450bac24789fa17115a4c9739ed75f8f21ce441f72e0b90e6ef", "21ae7f4680e889bb130619e2c0f95a360ceb573c70603139862afd617fa9b9f" ], [ "347d6d9a02c48927ebfb86c1359b1caf130a3c0267d11ce6344b39f99d43cc38", "60ea7f61a353524d1c987f6ecec92f086d565ab687870cb12689ff1e31c74448" ], [ "da6545d2181db8d983f7dcb375ef5866d47c67b1bf31c8cf855ef7437b72656a", "49b96715ab6878a79e78f07ce5680c5d6673051b4935bd897fea824b77dc208a" ], [ "c40747cc9d012cb1a13b8148309c6de7ec25d6945d657146b9d5994b8feb1111", "5ca560753be2a12fc6de6caf2cb489565db936156b9514e1bb5e83037e0fa2d4" ], [ "4e42c8ec82c99798ccf3a610be870e78338c7f713348bd34c8203ef4037f3502", "7571d74ee5e0fb92a7a8b33a07783341a5492144cc54bcc40a94473693606437" ], [ "3775ab7089bc6af823aba2e1af70b236d251cadb0c86743287522a1b3b0dedea", "be52d107bcfa09d8bcb9736a828cfa7fac8db17bf7a76a2c42ad961409018cf7" ], [ "cee31cbf7e34ec379d94fb814d3d775ad954595d1314ba8846959e3e82f74e26", "8fd64a14c06b589c26b947ae2bcf6bfa0149ef0be14ed4d80f448a01c43b1c6d" ], [ "b4f9eaea09b6917619f6ea6a4eb5464efddb58fd45b1ebefcdc1a01d08b47986", "39e5c9925b5a54b07433a4f18c61726f8bb131c012ca542eb24a8ac07200682a" ], [ "d4263dfc3d2df923a0179a48966d30ce84e2515afc3dccc1b77907792ebcc60e", "62dfaf07a0f78feb30e30d6295853ce189e127760ad6cf7fae164e122a208d54" ], [ "48457524820fa65a4f8d35eb6930857c0032acc0a4a2de422233eeda897612c4", "25a748ab367979d98733c38a1fa1c2e7dc6cc07db2d60a9ae7a76aaa49bd0f77" ], [ "dfeeef1881101f2cb11644f3a2afdfc2045e19919152923f367a1767c11cceda", "ecfb7056cf1de042f9420bab396793c0c390bde74b4bbdff16a83ae09a9a7517" ], [ "6d7ef6b17543f8373c573f44e1f389835d89bcbc6062ced36c82df83b8fae859", "cd450ec335438986dfefa10c57fea9bcc521a0959b2d80bbf74b190dca712d10" ], [ "e75605d59102a5a2684500d3b991f2e3f3c88b93225547035af25af66e04541f", "f5c54754a8f71ee540b9b48728473e314f729ac5308b06938360990e2bfad125" ], [ "eb98660f4c4dfaa06a2be453d5020bc99a0c2e60abe388457dd43fefb1ed620c", "6cb9a8876d9cb8520609af3add26cd20a0a7cd8a9411131ce85f44100099223e" ], [ "13e87b027d8514d35939f2e6892b19922154596941888336dc3563e3b8dba942", "fef5a3c68059a6dec5d624114bf1e91aac2b9da568d6abeb2570d55646b8adf1" ], [ "ee163026e9fd6fe017c38f06a5be6fc125424b371ce2708e7bf4491691e5764a", "1acb250f255dd61c43d94ccc670d0f58f49ae3fa15b96623e5430da0ad6c62b2" ], [ "b268f5ef9ad51e4d78de3a750c2dc89b1e626d43505867999932e5db33af3d80", "5f310d4b3c99b9ebb19f77d41c1dee018cf0d34fd4191614003e945a1216e423" ], [ "ff07f3118a9df035e9fad85eb6c7bfe42b02f01ca99ceea3bf7ffdba93c4750d", "438136d603e858a3a5c440c38eccbaddc1d2942114e2eddd4740d098ced1f0d8" ], [ "8d8b9855c7c052a34146fd20ffb658bea4b9f69e0d825ebec16e8c3ce2b526a1", "cdb559eedc2d79f926baf44fb84ea4d44bcf50fee51d7ceb30e2e7f463036758" ], [ "52db0b5384dfbf05bfa9d472d7ae26dfe4b851ceca91b1eba54263180da32b63", "c3b997d050ee5d423ebaf66a6db9f57b3180c902875679de924b69d84a7b375" ], [ "e62f9490d3d51da6395efd24e80919cc7d0f29c3f3fa48c6fff543becbd43352", "6d89ad7ba4876b0b22c2ca280c682862f342c8591f1daf5170e07bfd9ccafa7d" ], [ "7f30ea2476b399b4957509c88f77d0191afa2ff5cb7b14fd6d8e7d65aaab1193", "ca5ef7d4b231c94c3b15389a5f6311e9daff7bb67b103e9880ef4bff637acaec" ], [ "5098ff1e1d9f14fb46a210fada6c903fef0fb7b4a1dd1d9ac60a0361800b7a00", "9731141d81fc8f8084d37c6e7542006b3ee1b40d60dfe5362a5b132fd17ddc0" ], [ "32b78c7de9ee512a72895be6b9cbefa6e2f3c4ccce445c96b9f2c81e2778ad58", "ee1849f513df71e32efc3896ee28260c73bb80547ae2275ba497237794c8753c" ], [ "e2cb74fddc8e9fbcd076eef2a7c72b0ce37d50f08269dfc074b581550547a4f7", "d3aa2ed71c9dd2247a62df062736eb0baddea9e36122d2be8641abcb005cc4a4" ], [ "8438447566d4d7bedadc299496ab357426009a35f235cb141be0d99cd10ae3a8", "c4e1020916980a4da5d01ac5e6ad330734ef0d7906631c4f2390426b2edd791f" ], [ "4162d488b89402039b584c6fc6c308870587d9c46f660b878ab65c82c711d67e", "67163e903236289f776f22c25fb8a3afc1732f2b84b4e95dbda47ae5a0852649" ], [ "3fad3fa84caf0f34f0f89bfd2dcf54fc175d767aec3e50684f3ba4a4bf5f683d", "cd1bc7cb6cc407bb2f0ca647c718a730cf71872e7d0d2a53fa20efcdfe61826" ], [ "674f2600a3007a00568c1a7ce05d0816c1fb84bf1370798f1c69532faeb1a86b", "299d21f9413f33b3edf43b257004580b70db57da0b182259e09eecc69e0d38a5" ], [ "d32f4da54ade74abb81b815ad1fb3b263d82d6c692714bcff87d29bd5ee9f08f", "f9429e738b8e53b968e99016c059707782e14f4535359d582fc416910b3eea87" ], [ "30e4e670435385556e593657135845d36fbb6931f72b08cb1ed954f1e3ce3ff6", "462f9bce619898638499350113bbc9b10a878d35da70740dc695a559eb88db7b" ], [ "be2062003c51cc3004682904330e4dee7f3dcd10b01e580bf1971b04d4cad297", "62188bc49d61e5428573d48a74e1c655b1c61090905682a0d5558ed72dccb9bc" ], [ "93144423ace3451ed29e0fb9ac2af211cb6e84a601df5993c419859fff5df04a", "7c10dfb164c3425f5c71a3f9d7992038f1065224f72bb9d1d902a6d13037b47c" ], [ "b015f8044f5fcbdcf21ca26d6c34fb8197829205c7b7d2a7cb66418c157b112c", "ab8c1e086d04e813744a655b2df8d5f83b3cdc6faa3088c1d3aea1454e3a1d5f" ], [ "d5e9e1da649d97d89e4868117a465a3a4f8a18de57a140d36b3f2af341a21b52", "4cb04437f391ed73111a13cc1d4dd0db1693465c2240480d8955e8592f27447a" ], [ "d3ae41047dd7ca065dbf8ed77b992439983005cd72e16d6f996a5316d36966bb", "bd1aeb21ad22ebb22a10f0303417c6d964f8cdd7df0aca614b10dc14d125ac46" ], [ "463e2763d885f958fc66cdd22800f0a487197d0a82e377b49f80af87c897b065", "bfefacdb0e5d0fd7df3a311a94de062b26b80c61fbc97508b79992671ef7ca7f" ], [ "7985fdfd127c0567c6f53ec1bb63ec3158e597c40bfe747c83cddfc910641917", "603c12daf3d9862ef2b25fe1de289aed24ed291e0ec6708703a5bd567f32ed03" ], [ "74a1ad6b5f76e39db2dd249410eac7f99e74c59cb83d2d0ed5ff1543da7703e9", "cc6157ef18c9c63cd6193d83631bbea0093e0968942e8c33d5737fd790e0db08" ], [ "30682a50703375f602d416664ba19b7fc9bab42c72747463a71d0896b22f6da3", "553e04f6b018b4fa6c8f39e7f311d3176290d0e0f19ca73f17714d9977a22ff8" ], [ "9e2158f0d7c0d5f26c3791efefa79597654e7a2b2464f52b1ee6c1347769ef57", "712fcdd1b9053f09003a3481fa7762e9ffd7c8ef35a38509e2fbf2629008373" ], [ "176e26989a43c9cfeba4029c202538c28172e566e3c4fce7322857f3be327d66", "ed8cc9d04b29eb877d270b4878dc43c19aefd31f4eee09ee7b47834c1fa4b1c3" ], [ "75d46efea3771e6e68abb89a13ad747ecf1892393dfc4f1b7004788c50374da8", "9852390a99507679fd0b86fd2b39a868d7efc22151346e1a3ca4726586a6bed8" ], [ "809a20c67d64900ffb698c4c825f6d5f2310fb0451c869345b7319f645605721", "9e994980d9917e22b76b061927fa04143d096ccc54963e6a5ebfa5f3f8e286c1" ], [ "1b38903a43f7f114ed4500b4eac7083fdefece1cf29c63528d563446f972c180", "4036edc931a60ae889353f77fd53de4a2708b26b6f5da72ad3394119daf408f9" ] ] } }; } }); // node_modules/elliptic/lib/elliptic/curves.js var require_curves = __commonJS({ "node_modules/elliptic/lib/elliptic/curves.js"(exports) { "use strict"; var curves = exports; var hash2 = require_hash(); var curve = require_curve(); var utils = require_utils4(); var assert2 = utils.assert; function PresetCurve(options) { if (options.type === "short") this.curve = new curve.short(options); else if (options.type === "edwards") this.curve = new curve.edwards(options); else this.curve = new curve.mont(options); this.g = this.curve.g; this.n = this.curve.n; this.hash = options.hash; assert2(this.g.validate(), "Invalid curve"); assert2(this.g.mul(this.n).isInfinity(), "Invalid curve, G*N != O"); } curves.PresetCurve = PresetCurve; function defineCurve(name2, options) { Object.defineProperty(curves, name2, { configurable: true, enumerable: true, get: function() { var curve2 = new PresetCurve(options); Object.defineProperty(curves, name2, { configurable: true, enumerable: true, value: curve2 }); return curve2; } }); } defineCurve("p192", { type: "short", prime: "p192", p: "ffffffff ffffffff ffffffff fffffffe ffffffff ffffffff", a: "ffffffff ffffffff ffffffff fffffffe ffffffff fffffffc", b: "64210519 e59c80e7 0fa7e9ab 72243049 feb8deec c146b9b1", n: "ffffffff ffffffff ffffffff 99def836 146bc9b1 b4d22831", hash: hash2.sha256, gRed: false, g: [ "188da80e b03090f6 7cbf20eb 43a18800 f4ff0afd 82ff1012", "07192b95 ffc8da78 631011ed 6b24cdd5 73f977a1 1e794811" ] }); defineCurve("p224", { type: "short", prime: "p224", p: "ffffffff ffffffff ffffffff ffffffff 00000000 00000000 00000001", a: "ffffffff ffffffff ffffffff fffffffe ffffffff ffffffff fffffffe", b: "b4050a85 0c04b3ab f5413256 5044b0b7 d7bfd8ba 270b3943 2355ffb4", n: "ffffffff ffffffff ffffffff ffff16a2 e0b8f03e 13dd2945 5c5c2a3d", hash: hash2.sha256, gRed: false, g: [ "b70e0cbd 6bb4bf7f 321390b9 4a03c1d3 56c21122 343280d6 115c1d21", "bd376388 b5f723fb 4c22dfe6 cd4375a0 5a074764 44d58199 85007e34" ] }); defineCurve("p256", { type: "short", prime: null, p: "ffffffff 00000001 00000000 00000000 00000000 ffffffff ffffffff ffffffff", a: "ffffffff 00000001 00000000 00000000 00000000 ffffffff ffffffff fffffffc", b: "5ac635d8 aa3a93e7 b3ebbd55 769886bc 651d06b0 cc53b0f6 3bce3c3e 27d2604b", n: "ffffffff 00000000 ffffffff ffffffff bce6faad a7179e84 f3b9cac2 fc632551", hash: hash2.sha256, gRed: false, g: [ "6b17d1f2 e12c4247 f8bce6e5 63a440f2 77037d81 2deb33a0 f4a13945 d898c296", "4fe342e2 fe1a7f9b 8ee7eb4a 7c0f9e16 2bce3357 6b315ece cbb64068 37bf51f5" ] }); defineCurve("p384", { type: "short", prime: null, p: "ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffe ffffffff 00000000 00000000 ffffffff", a: "ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffe ffffffff 00000000 00000000 fffffffc", b: "b3312fa7 e23ee7e4 988e056b e3f82d19 181d9c6e fe814112 0314088f 5013875a c656398d 8a2ed19d 2a85c8ed d3ec2aef", n: "ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff c7634d81 f4372ddf 581a0db2 48b0a77a ecec196a ccc52973", hash: hash2.sha384, gRed: false, g: [ "aa87ca22 be8b0537 8eb1c71e f320ad74 6e1d3b62 8ba79b98 59f741e0 82542a38 5502f25d bf55296c 3a545e38 72760ab7", "3617de4a 96262c6f 5d9e98bf 9292dc29 f8f41dbd 289a147c e9da3113 b5f0b8c0 0a60b1ce 1d7e819d 7a431d7c 90ea0e5f" ] }); defineCurve("p521", { type: "short", prime: null, p: "000001ff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff", a: "000001ff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffc", b: "00000051 953eb961 8e1c9a1f 929a21a0 b68540ee a2da725b 99b315f3 b8b48991 8ef109e1 56193951 ec7e937b 1652c0bd 3bb1bf07 3573df88 3d2c34f1 ef451fd4 6b503f00", n: "000001ff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffa 51868783 bf2f966b 7fcc0148 f709a5d0 3bb5c9b8 899c47ae bb6fb71e 91386409", hash: hash2.sha512, gRed: false, g: [ "000000c6 858e06b7 0404e9cd 9e3ecb66 2395b442 9c648139 053fb521 f828af60 6b4d3dba a14b5e77 efe75928 fe1dc127 a2ffa8de 3348b3c1 856a429b f97e7e31 c2e5bd66", "00000118 39296a78 9a3bc004 5c8a5fb4 2c7d1bd9 98f54449 579b4468 17afbd17 273e662c 97ee7299 5ef42640 c550b901 3fad0761 353c7086 a272c240 88be9476 9fd16650" ] }); defineCurve("curve25519", { type: "mont", prime: "p25519", p: "7fffffffffffffff ffffffffffffffff ffffffffffffffff ffffffffffffffed", a: "76d06", b: "1", n: "1000000000000000 0000000000000000 14def9dea2f79cd6 5812631a5cf5d3ed", hash: hash2.sha256, gRed: false, g: [ "9" ] }); defineCurve("ed25519", { type: "edwards", prime: "p25519", p: "7fffffffffffffff ffffffffffffffff ffffffffffffffff ffffffffffffffed", a: "-1", c: "1", // -121665 * (121666^(-1)) (mod P) d: "52036cee2b6ffe73 8cc740797779e898 00700a4d4141d8ab 75eb4dca135978a3", n: "1000000000000000 0000000000000000 14def9dea2f79cd6 5812631a5cf5d3ed", hash: hash2.sha256, gRed: false, g: [ "216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51a", // 4/5 "6666666666666666666666666666666666666666666666666666666666666658" ] }); var pre; try { pre = require_secp256k1(); } catch (e2) { pre = void 0; } defineCurve("secp256k1", { type: "short", prime: "k256", p: "ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffe fffffc2f", a: "0", b: "7", n: "ffffffff ffffffff ffffffff fffffffe baaedce6 af48a03b bfd25e8c d0364141", h: "1", hash: hash2.sha256, // Precomputed endomorphism beta: "7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee", lambda: "5363ad4cc05c30e0a5261c028812645a122e22ea20816678df02967c1b23bd72", basis: [ { a: "3086d221a7d46bcde86c90e49284eb15", b: "-e4437ed6010e88286f547fa90abfe4c3" }, { a: "114ca50f7a8e2f3f657c1108d9d44cfd8", b: "3086d221a7d46bcde86c90e49284eb15" } ], gRed: false, g: [ "79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798", "483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8", pre ] }); } }); // node_modules/hmac-drbg/lib/hmac-drbg.js var require_hmac_drbg = __commonJS({ "node_modules/hmac-drbg/lib/hmac-drbg.js"(exports, module) { "use strict"; var hash2 = require_hash(); var utils = require_utils3(); var assert2 = require_minimalistic_assert(); function HmacDRBG2(options) { if (!(this instanceof HmacDRBG2)) return new HmacDRBG2(options); this.hash = options.hash; this.predResist = !!options.predResist; this.outLen = this.hash.outSize; this.minEntropy = options.minEntropy || this.hash.hmacStrength; this._reseed = null; this.reseedInterval = null; this.K = null; this.V = null; var entropy = utils.toArray(options.entropy, options.entropyEnc || "hex"); var nonce = utils.toArray(options.nonce, options.nonceEnc || "hex"); var pers = utils.toArray(options.pers, options.persEnc || "hex"); assert2( entropy.length >= this.minEntropy / 8, "Not enough entropy. Minimum is: " + this.minEntropy + " bits" ); this._init(entropy, nonce, pers); } module.exports = HmacDRBG2; HmacDRBG2.prototype._init = function init2(entropy, nonce, pers) { var seed = entropy.concat(nonce).concat(pers); this.K = new Array(this.outLen / 8); this.V = new Array(this.outLen / 8); for (var i4 = 0; i4 < this.V.length; i4++) { this.K[i4] = 0; this.V[i4] = 1; } this._update(seed); this._reseed = 1; this.reseedInterval = 281474976710656; }; HmacDRBG2.prototype._hmac = function hmac2() { return new hash2.hmac(this.hash, this.K); }; HmacDRBG2.prototype._update = function update2(seed) { var kmac = this._hmac().update(this.V).update([0]); if (seed) kmac = kmac.update(seed); this.K = kmac.digest(); this.V = this._hmac().update(this.V).digest(); if (!seed) return; this.K = this._hmac().update(this.V).update([1]).update(seed).digest(); this.V = this._hmac().update(this.V).digest(); }; HmacDRBG2.prototype.reseed = function reseed2(entropy, entropyEnc, add3, addEnc) { if (typeof entropyEnc !== "string") { addEnc = add3; add3 = entropyEnc; entropyEnc = null; } entropy = utils.toArray(entropy, entropyEnc); add3 = utils.toArray(add3, addEnc); assert2( entropy.length >= this.minEntropy / 8, "Not enough entropy. Minimum is: " + this.minEntropy + " bits" ); this._update(entropy.concat(add3 || [])); this._reseed = 1; }; HmacDRBG2.prototype.generate = function generate2(len, enc, add3, addEnc) { if (this._reseed > this.reseedInterval) throw new Error("Reseed is required"); if (typeof enc !== "string") { addEnc = add3; add3 = enc; enc = null; } if (add3) { add3 = utils.toArray(add3, addEnc || "hex"); this._update(add3); } var temp = []; while (temp.length < len) { this.V = this._hmac().update(this.V).digest(); temp = temp.concat(this.V); } var res = temp.slice(0, len); this._update(add3); this._reseed++; return utils.encode(res, enc); }; } }); // node_modules/elliptic/lib/elliptic/ec/key.js var require_key = __commonJS({ "node_modules/elliptic/lib/elliptic/ec/key.js"(exports, module) { "use strict"; var BN3 = require_bn2(); var utils = require_utils4(); var assert2 = utils.assert; function KeyPair2(ec2, options) { this.ec = ec2; this.priv = null; this.pub = null; if (options.priv) this._importPrivate(options.priv, options.privEnc); if (options.pub) this._importPublic(options.pub, options.pubEnc); } module.exports = KeyPair2; KeyPair2.fromPublic = function fromPublic2(ec2, pub, enc) { if (pub instanceof KeyPair2) return pub; return new KeyPair2(ec2, { pub, pubEnc: enc }); }; KeyPair2.fromPrivate = function fromPrivate2(ec2, priv, enc) { if (priv instanceof KeyPair2) return priv; return new KeyPair2(ec2, { priv, privEnc: enc }); }; KeyPair2.prototype.validate = function validate5() { var pub = this.getPublic(); if (pub.isInfinity()) return { result: false, reason: "Invalid public key" }; if (!pub.validate()) return { result: false, reason: "Public key is not a point" }; if (!pub.mul(this.ec.curve.n).isInfinity()) return { result: false, reason: "Public key * N != O" }; return { result: true, reason: null }; }; KeyPair2.prototype.getPublic = function getPublic2(compact, enc) { if (typeof compact === "string") { enc = compact; compact = null; } if (!this.pub) this.pub = this.ec.g.mul(this.priv); if (!enc) return this.pub; return this.pub.encode(enc, compact); }; KeyPair2.prototype.getPrivate = function getPrivate2(enc) { if (enc === "hex") return this.priv.toString(16, 2); else return this.priv; }; KeyPair2.prototype._importPrivate = function _importPrivate2(key2, enc) { this.priv = new BN3(key2, enc || 16); this.priv = this.priv.umod(this.ec.curve.n); }; KeyPair2.prototype._importPublic = function _importPublic2(key2, enc) { if (key2.x || key2.y) { if (this.ec.curve.type === "mont") { assert2(key2.x, "Need x coordinate"); } else if (this.ec.curve.type === "short" || this.ec.curve.type === "edwards") { assert2(key2.x && key2.y, "Need both x and y coordinate"); } this.pub = this.ec.curve.point(key2.x, key2.y); return; } this.pub = this.ec.curve.decodePoint(key2, enc); }; KeyPair2.prototype.derive = function derive2(pub) { if (!pub.validate()) { assert2(pub.validate(), "public point not validated"); } return pub.mul(this.priv).getX(); }; KeyPair2.prototype.sign = function sign4(msg, enc, options) { return this.ec.sign(msg, this, enc, options); }; KeyPair2.prototype.verify = function verify4(msg, signature2, options) { return this.ec.verify(msg, signature2, this, void 0, options); }; KeyPair2.prototype.inspect = function inspect4() { return ""; }; } }); // node_modules/elliptic/lib/elliptic/ec/signature.js var require_signature = __commonJS({ "node_modules/elliptic/lib/elliptic/ec/signature.js"(exports, module) { "use strict"; var BN3 = require_bn2(); var utils = require_utils4(); var assert2 = utils.assert; function Signature2(options, enc) { if (options instanceof Signature2) return options; if (this._importDER(options, enc)) return; assert2(options.r && options.s, "Signature without r or s"); this.r = new BN3(options.r, 16); this.s = new BN3(options.s, 16); if (options.recoveryParam === void 0) this.recoveryParam = null; else this.recoveryParam = options.recoveryParam; } module.exports = Signature2; function Position2() { this.place = 0; } function getLength2(buf, p3) { var initial = buf[p3.place++]; if (!(initial & 128)) { return initial; } var octetLen = initial & 15; if (octetLen === 0 || octetLen > 4) { return false; } if (buf[p3.place] === 0) { return false; } var val = 0; for (var i4 = 0, off = p3.place; i4 < octetLen; i4++, off++) { val <<= 8; val |= buf[off]; val >>>= 0; } if (val <= 127) { return false; } p3.place = off; return val; } function rmPadding2(buf) { var i4 = 0; var len = buf.length - 1; while (!buf[i4] && !(buf[i4 + 1] & 128) && i4 < len) { i4++; } if (i4 === 0) { return buf; } return buf.slice(i4); } Signature2.prototype._importDER = function _importDER2(data, enc) { data = utils.toArray(data, enc); var p3 = new Position2(); if (data[p3.place++] !== 48) { return false; } var len = getLength2(data, p3); if (len === false) { return false; } if (len + p3.place !== data.length) { return false; } if (data[p3.place++] !== 2) { return false; } var rlen = getLength2(data, p3); if (rlen === false) { return false; } if ((data[p3.place] & 128) !== 0) { return false; } var r4 = data.slice(p3.place, rlen + p3.place); p3.place += rlen; if (data[p3.place++] !== 2) { return false; } var slen = getLength2(data, p3); if (slen === false) { return false; } if (data.length !== slen + p3.place) { return false; } if ((data[p3.place] & 128) !== 0) { return false; } var s3 = data.slice(p3.place, slen + p3.place); if (r4[0] === 0) { if (r4[1] & 128) { r4 = r4.slice(1); } else { return false; } } if (s3[0] === 0) { if (s3[1] & 128) { s3 = s3.slice(1); } else { return false; } } this.r = new BN3(r4); this.s = new BN3(s3); this.recoveryParam = null; return true; }; function constructLength2(arr, len) { if (len < 128) { arr.push(len); return; } var octets = 1 + (Math.log(len) / Math.LN2 >>> 3); arr.push(octets | 128); while (--octets) { arr.push(len >>> (octets << 3) & 255); } arr.push(len); } Signature2.prototype.toDER = function toDER2(enc) { var r4 = this.r.toArray(); var s3 = this.s.toArray(); if (r4[0] & 128) r4 = [0].concat(r4); if (s3[0] & 128) s3 = [0].concat(s3); r4 = rmPadding2(r4); s3 = rmPadding2(s3); while (!s3[0] && !(s3[1] & 128)) { s3 = s3.slice(1); } var arr = [2]; constructLength2(arr, r4.length); arr = arr.concat(r4); arr.push(2); constructLength2(arr, s3.length); var backHalf = arr.concat(s3); var res = [48]; constructLength2(res, backHalf.length); res = res.concat(backHalf); return utils.encode(res, enc); }; } }); // node_modules/elliptic/lib/elliptic/ec/index.js var require_ec = __commonJS({ "node_modules/elliptic/lib/elliptic/ec/index.js"(exports, module) { "use strict"; var BN3 = require_bn2(); var HmacDRBG2 = require_hmac_drbg(); var utils = require_utils4(); var curves = require_curves(); var rand2 = require_brorand(); var assert2 = utils.assert; var KeyPair2 = require_key(); var Signature2 = require_signature(); function EC2(options) { if (!(this instanceof EC2)) return new EC2(options); if (typeof options === "string") { assert2( Object.prototype.hasOwnProperty.call(curves, options), "Unknown curve " + options ); options = curves[options]; } if (options instanceof curves.PresetCurve) options = { curve: options }; this.curve = options.curve.curve; this.n = this.curve.n; this.nh = this.n.ushrn(1); this.g = this.curve.g; this.g = options.curve.g; this.g.precompute(options.curve.n.bitLength() + 1); this.hash = options.hash || options.curve.hash; } module.exports = EC2; EC2.prototype.keyPair = function keyPair2(options) { return new KeyPair2(this, options); }; EC2.prototype.keyFromPrivate = function keyFromPrivate2(priv, enc) { return KeyPair2.fromPrivate(this, priv, enc); }; EC2.prototype.keyFromPublic = function keyFromPublic2(pub, enc) { return KeyPair2.fromPublic(this, pub, enc); }; EC2.prototype.genKeyPair = function genKeyPair2(options) { if (!options) options = {}; var drbg = new HmacDRBG2({ hash: this.hash, pers: options.pers, persEnc: options.persEnc || "utf8", entropy: options.entropy || rand2(this.hash.hmacStrength), entropyEnc: options.entropy && options.entropyEnc || "utf8", nonce: this.n.toArray() }); var bytes = this.n.byteLength(); var ns2 = this.n.sub(new BN3(2)); for (; ; ) { var priv = new BN3(drbg.generate(bytes)); if (priv.cmp(ns2) > 0) continue; priv.iaddn(1); return this.keyFromPrivate(priv); } }; EC2.prototype._truncateToN = function _truncateToN2(msg, truncOnly, bitLength) { var byteLength; if (BN3.isBN(msg) || typeof msg === "number") { msg = new BN3(msg, 16); byteLength = msg.byteLength(); } else if (typeof msg === "object") { byteLength = msg.length; msg = new BN3(msg, 16); } else { var str = msg.toString(); byteLength = str.length + 1 >>> 1; msg = new BN3(str, 16); } if (typeof bitLength !== "number") { bitLength = byteLength * 8; } var delta = bitLength - this.n.bitLength(); if (delta > 0) msg = msg.ushrn(delta); if (!truncOnly && msg.cmp(this.n) >= 0) return msg.sub(this.n); else return msg; }; EC2.prototype.sign = function sign4(msg, key2, enc, options) { if (typeof enc === "object") { options = enc; enc = null; } if (!options) options = {}; key2 = this.keyFromPrivate(key2, enc); msg = this._truncateToN(msg, false, options.msgBitLength); var bytes = this.n.byteLength(); var bkey = key2.getPrivate().toArray("be", bytes); var nonce = msg.toArray("be", bytes); var drbg = new HmacDRBG2({ hash: this.hash, entropy: bkey, nonce, pers: options.pers, persEnc: options.persEnc || "utf8" }); var ns1 = this.n.sub(new BN3(1)); for (var iter = 0; ; iter++) { var k4 = options.k ? options.k(iter) : new BN3(drbg.generate(this.n.byteLength())); k4 = this._truncateToN(k4, true); if (k4.cmpn(1) <= 0 || k4.cmp(ns1) >= 0) continue; var kp = this.g.mul(k4); if (kp.isInfinity()) continue; var kpX = kp.getX(); var r4 = kpX.umod(this.n); if (r4.cmpn(0) === 0) continue; var s3 = k4.invm(this.n).mul(r4.mul(key2.getPrivate()).iadd(msg)); s3 = s3.umod(this.n); if (s3.cmpn(0) === 0) continue; var recoveryParam = (kp.getY().isOdd() ? 1 : 0) | (kpX.cmp(r4) !== 0 ? 2 : 0); if (options.canonical && s3.cmp(this.nh) > 0) { s3 = this.n.sub(s3); recoveryParam ^= 1; } return new Signature2({ r: r4, s: s3, recoveryParam }); } }; EC2.prototype.verify = function verify4(msg, signature2, key2, enc, options) { if (!options) options = {}; msg = this._truncateToN(msg, false, options.msgBitLength); key2 = this.keyFromPublic(key2, enc); signature2 = new Signature2(signature2, "hex"); var r4 = signature2.r; var s3 = signature2.s; if (r4.cmpn(1) < 0 || r4.cmp(this.n) >= 0) return false; if (s3.cmpn(1) < 0 || s3.cmp(this.n) >= 0) return false; var sinv = s3.invm(this.n); var u1 = sinv.mul(msg).umod(this.n); var u22 = sinv.mul(r4).umod(this.n); var p3; if (!this.curve._maxwellTrick) { p3 = this.g.mulAdd(u1, key2.getPublic(), u22); if (p3.isInfinity()) return false; return p3.getX().umod(this.n).cmp(r4) === 0; } p3 = this.g.jmulAdd(u1, key2.getPublic(), u22); if (p3.isInfinity()) return false; return p3.eqXToP(r4); }; EC2.prototype.recoverPubKey = function(msg, signature2, j2, enc) { assert2((3 & j2) === j2, "The recovery param is more than two bits"); signature2 = new Signature2(signature2, enc); var n5 = this.n; var e2 = new BN3(msg); var r4 = signature2.r; var s3 = signature2.s; var isYOdd = j2 & 1; var isSecondKey = j2 >> 1; if (r4.cmp(this.curve.p.umod(this.curve.n)) >= 0 && isSecondKey) throw new Error("Unable to find sencond key candinate"); if (isSecondKey) r4 = this.curve.pointFromX(r4.add(this.curve.n), isYOdd); else r4 = this.curve.pointFromX(r4, isYOdd); var rInv = signature2.r.invm(n5); var s1 = n5.sub(e2).mul(rInv).umod(n5); var s22 = s3.mul(rInv).umod(n5); return this.g.mulAdd(s1, r4, s22); }; EC2.prototype.getKeyRecoveryParam = function(e2, signature2, Q2, enc) { signature2 = new Signature2(signature2, enc); if (signature2.recoveryParam !== null) return signature2.recoveryParam; for (var i4 = 0; i4 < 4; i4++) { var Qprime; try { Qprime = this.recoverPubKey(e2, signature2, i4); } catch (e3) { continue; } if (Qprime.eq(Q2)) return i4; } throw new Error("Unable to find valid recovery factor"); }; } }); // node_modules/elliptic/lib/elliptic/eddsa/key.js var require_key2 = __commonJS({ "node_modules/elliptic/lib/elliptic/eddsa/key.js"(exports, module) { "use strict"; var utils = require_utils4(); var assert2 = utils.assert; var parseBytes = utils.parseBytes; var cachedProperty = utils.cachedProperty; function KeyPair2(eddsa, params) { this.eddsa = eddsa; this._secret = parseBytes(params.secret); if (eddsa.isPoint(params.pub)) this._pub = params.pub; else this._pubBytes = parseBytes(params.pub); } KeyPair2.fromPublic = function fromPublic2(eddsa, pub) { if (pub instanceof KeyPair2) return pub; return new KeyPair2(eddsa, { pub }); }; KeyPair2.fromSecret = function fromSecret(eddsa, secret) { if (secret instanceof KeyPair2) return secret; return new KeyPair2(eddsa, { secret }); }; KeyPair2.prototype.secret = function secret() { return this._secret; }; cachedProperty(KeyPair2, "pubBytes", function pubBytes() { return this.eddsa.encodePoint(this.pub()); }); cachedProperty(KeyPair2, "pub", function pub() { if (this._pubBytes) return this.eddsa.decodePoint(this._pubBytes); return this.eddsa.g.mul(this.priv()); }); cachedProperty(KeyPair2, "privBytes", function privBytes() { var eddsa = this.eddsa; var hash2 = this.hash(); var lastIx = eddsa.encodingLength - 1; var a4 = hash2.slice(0, eddsa.encodingLength); a4[0] &= 248; a4[lastIx] &= 127; a4[lastIx] |= 64; return a4; }); cachedProperty(KeyPair2, "priv", function priv() { return this.eddsa.decodeInt(this.privBytes()); }); cachedProperty(KeyPair2, "hash", function hash2() { return this.eddsa.hash().update(this.secret()).digest(); }); cachedProperty(KeyPair2, "messagePrefix", function messagePrefix2() { return this.hash().slice(this.eddsa.encodingLength); }); KeyPair2.prototype.sign = function sign4(message) { assert2(this._secret, "KeyPair can only verify"); return this.eddsa.sign(message, this); }; KeyPair2.prototype.verify = function verify4(message, sig) { return this.eddsa.verify(message, sig, this); }; KeyPair2.prototype.getSecret = function getSecret(enc) { assert2(this._secret, "KeyPair is public only"); return utils.encode(this.secret(), enc); }; KeyPair2.prototype.getPublic = function getPublic2(enc) { return utils.encode(this.pubBytes(), enc); }; module.exports = KeyPair2; } }); // node_modules/elliptic/lib/elliptic/eddsa/signature.js var require_signature2 = __commonJS({ "node_modules/elliptic/lib/elliptic/eddsa/signature.js"(exports, module) { "use strict"; var BN3 = require_bn2(); var utils = require_utils4(); var assert2 = utils.assert; var cachedProperty = utils.cachedProperty; var parseBytes = utils.parseBytes; function Signature2(eddsa, sig) { this.eddsa = eddsa; if (typeof sig !== "object") sig = parseBytes(sig); if (Array.isArray(sig)) { assert2(sig.length === eddsa.encodingLength * 2, "Signature has invalid size"); sig = { R: sig.slice(0, eddsa.encodingLength), S: sig.slice(eddsa.encodingLength) }; } assert2(sig.R && sig.S, "Signature without R or S"); if (eddsa.isPoint(sig.R)) this._R = sig.R; if (sig.S instanceof BN3) this._S = sig.S; this._Rencoded = Array.isArray(sig.R) ? sig.R : sig.Rencoded; this._Sencoded = Array.isArray(sig.S) ? sig.S : sig.Sencoded; } cachedProperty(Signature2, "S", function S6() { return this.eddsa.decodeInt(this.Sencoded()); }); cachedProperty(Signature2, "R", function R2() { return this.eddsa.decodePoint(this.Rencoded()); }); cachedProperty(Signature2, "Rencoded", function Rencoded() { return this.eddsa.encodePoint(this.R()); }); cachedProperty(Signature2, "Sencoded", function Sencoded() { return this.eddsa.encodeInt(this.S()); }); Signature2.prototype.toBytes = function toBytes() { return this.Rencoded().concat(this.Sencoded()); }; Signature2.prototype.toHex = function toHex2() { return utils.encode(this.toBytes(), "hex").toUpperCase(); }; module.exports = Signature2; } }); // node_modules/elliptic/lib/elliptic/eddsa/index.js var require_eddsa = __commonJS({ "node_modules/elliptic/lib/elliptic/eddsa/index.js"(exports, module) { "use strict"; var hash2 = require_hash(); var curves = require_curves(); var utils = require_utils4(); var assert2 = utils.assert; var parseBytes = utils.parseBytes; var KeyPair2 = require_key2(); var Signature2 = require_signature2(); function EDDSA(curve) { assert2(curve === "ed25519", "only tested with ed25519 so far"); if (!(this instanceof EDDSA)) return new EDDSA(curve); curve = curves[curve].curve; this.curve = curve; this.g = curve.g; this.g.precompute(curve.n.bitLength() + 1); this.pointClass = curve.point().constructor; this.encodingLength = Math.ceil(curve.n.bitLength() / 8); this.hash = hash2.sha512; } module.exports = EDDSA; EDDSA.prototype.sign = function sign4(message, secret) { message = parseBytes(message); var key2 = this.keyFromSecret(secret); var r4 = this.hashInt(key2.messagePrefix(), message); var R2 = this.g.mul(r4); var Rencoded = this.encodePoint(R2); var s_ = this.hashInt(Rencoded, key2.pubBytes(), message).mul(key2.priv()); var S6 = r4.add(s_).umod(this.curve.n); return this.makeSignature({ R: R2, S: S6, Rencoded }); }; EDDSA.prototype.verify = function verify4(message, sig, pub) { message = parseBytes(message); sig = this.makeSignature(sig); if (sig.S().gte(sig.eddsa.curve.n) || sig.S().isNeg()) { return false; } var key2 = this.keyFromPublic(pub); var h5 = this.hashInt(sig.Rencoded(), key2.pubBytes(), message); var SG = this.g.mul(sig.S()); var RplusAh = sig.R().add(key2.pub().mul(h5)); return RplusAh.eq(SG); }; EDDSA.prototype.hashInt = function hashInt() { var hash3 = this.hash(); for (var i4 = 0; i4 < arguments.length; i4++) hash3.update(arguments[i4]); return utils.intFromLE(hash3.digest()).umod(this.curve.n); }; EDDSA.prototype.keyFromPublic = function keyFromPublic2(pub) { return KeyPair2.fromPublic(this, pub); }; EDDSA.prototype.keyFromSecret = function keyFromSecret(secret) { return KeyPair2.fromSecret(this, secret); }; EDDSA.prototype.makeSignature = function makeSignature(sig) { if (sig instanceof Signature2) return sig; return new Signature2(this, sig); }; EDDSA.prototype.encodePoint = function encodePoint(point3) { var enc = point3.getY().toArray("le", this.encodingLength); enc[this.encodingLength - 1] |= point3.getX().isOdd() ? 128 : 0; return enc; }; EDDSA.prototype.decodePoint = function decodePoint2(bytes) { bytes = utils.parseBytes(bytes); var lastIx = bytes.length - 1; var normed = bytes.slice(0, lastIx).concat(bytes[lastIx] & ~128); var xIsOdd = (bytes[lastIx] & 128) !== 0; var y6 = utils.intFromLE(normed); return this.curve.pointFromY(y6, xIsOdd); }; EDDSA.prototype.encodeInt = function encodeInt(num) { return num.toArray("le", this.encodingLength); }; EDDSA.prototype.decodeInt = function decodeInt(bytes) { return utils.intFromLE(bytes); }; EDDSA.prototype.isPoint = function isPoint(val) { return val instanceof this.pointClass; }; } }); // node_modules/elliptic/lib/elliptic.js var require_elliptic = __commonJS({ "node_modules/elliptic/lib/elliptic.js"(exports) { "use strict"; var elliptic = exports; elliptic.version = require_package().version; elliptic.utils = require_utils4(); elliptic.rand = require_brorand(); elliptic.curve = require_curve(); elliptic.curves = require_curves(); elliptic.ec = require_ec(); elliptic.eddsa = require_eddsa(); } }); // node_modules/@stablelib/sha512/lib/sha512.js var require_sha512 = __commonJS({ "node_modules/@stablelib/sha512/lib/sha512.js"(exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var binary_1 = require_binary(); var wipe_1 = require_wipe(); exports.DIGEST_LENGTH = 64; exports.BLOCK_SIZE = 128; var SHA512 = ( /** @class */ function() { function SHA5122() { this.digestLength = exports.DIGEST_LENGTH; this.blockSize = exports.BLOCK_SIZE; this._stateHi = new Int32Array(8); this._stateLo = new Int32Array(8); this._tempHi = new Int32Array(16); this._tempLo = new Int32Array(16); this._buffer = new Uint8Array(256); this._bufferLength = 0; this._bytesHashed = 0; this._finished = false; this.reset(); } SHA5122.prototype._initState = function() { this._stateHi[0] = 1779033703; this._stateHi[1] = 3144134277; this._stateHi[2] = 1013904242; this._stateHi[3] = 2773480762; this._stateHi[4] = 1359893119; this._stateHi[5] = 2600822924; this._stateHi[6] = 528734635; this._stateHi[7] = 1541459225; this._stateLo[0] = 4089235720; this._stateLo[1] = 2227873595; this._stateLo[2] = 4271175723; this._stateLo[3] = 1595750129; this._stateLo[4] = 2917565137; this._stateLo[5] = 725511199; this._stateLo[6] = 4215389547; this._stateLo[7] = 327033209; }; SHA5122.prototype.reset = function() { this._initState(); this._bufferLength = 0; this._bytesHashed = 0; this._finished = false; return this; }; SHA5122.prototype.clean = function() { wipe_1.wipe(this._buffer); wipe_1.wipe(this._tempHi); wipe_1.wipe(this._tempLo); this.reset(); }; SHA5122.prototype.update = function(data, dataLength) { if (dataLength === void 0) { dataLength = data.length; } if (this._finished) { throw new Error("SHA512: can't update because hash was finished."); } var dataPos = 0; this._bytesHashed += dataLength; if (this._bufferLength > 0) { while (this._bufferLength < exports.BLOCK_SIZE && dataLength > 0) { this._buffer[this._bufferLength++] = data[dataPos++]; dataLength--; } if (this._bufferLength === this.blockSize) { hashBlocks(this._tempHi, this._tempLo, this._stateHi, this._stateLo, this._buffer, 0, this.blockSize); this._bufferLength = 0; } } if (dataLength >= this.blockSize) { dataPos = hashBlocks(this._tempHi, this._tempLo, this._stateHi, this._stateLo, data, dataPos, dataLength); dataLength %= this.blockSize; } while (dataLength > 0) { this._buffer[this._bufferLength++] = data[dataPos++]; dataLength--; } return this; }; SHA5122.prototype.finish = function(out) { if (!this._finished) { var bytesHashed = this._bytesHashed; var left = this._bufferLength; var bitLenHi = bytesHashed / 536870912 | 0; var bitLenLo = bytesHashed << 3; var padLength = bytesHashed % 128 < 112 ? 128 : 256; this._buffer[left] = 128; for (var i4 = left + 1; i4 < padLength - 8; i4++) { this._buffer[i4] = 0; } binary_1.writeUint32BE(bitLenHi, this._buffer, padLength - 8); binary_1.writeUint32BE(bitLenLo, this._buffer, padLength - 4); hashBlocks(this._tempHi, this._tempLo, this._stateHi, this._stateLo, this._buffer, 0, padLength); this._finished = true; } for (var i4 = 0; i4 < this.digestLength / 8; i4++) { binary_1.writeUint32BE(this._stateHi[i4], out, i4 * 8); binary_1.writeUint32BE(this._stateLo[i4], out, i4 * 8 + 4); } return this; }; SHA5122.prototype.digest = function() { var out = new Uint8Array(this.digestLength); this.finish(out); return out; }; SHA5122.prototype.saveState = function() { if (this._finished) { throw new Error("SHA256: cannot save finished state"); } return { stateHi: new Int32Array(this._stateHi), stateLo: new Int32Array(this._stateLo), buffer: this._bufferLength > 0 ? new Uint8Array(this._buffer) : void 0, bufferLength: this._bufferLength, bytesHashed: this._bytesHashed }; }; SHA5122.prototype.restoreState = function(savedState) { this._stateHi.set(savedState.stateHi); this._stateLo.set(savedState.stateLo); this._bufferLength = savedState.bufferLength; if (savedState.buffer) { this._buffer.set(savedState.buffer); } this._bytesHashed = savedState.bytesHashed; this._finished = false; return this; }; SHA5122.prototype.cleanSavedState = function(savedState) { wipe_1.wipe(savedState.stateHi); wipe_1.wipe(savedState.stateLo); if (savedState.buffer) { wipe_1.wipe(savedState.buffer); } savedState.bufferLength = 0; savedState.bytesHashed = 0; }; return SHA5122; }() ); exports.SHA512 = SHA512; var K3 = new Int32Array([ 1116352408, 3609767458, 1899447441, 602891725, 3049323471, 3964484399, 3921009573, 2173295548, 961987163, 4081628472, 1508970993, 3053834265, 2453635748, 2937671579, 2870763221, 3664609560, 3624381080, 2734883394, 310598401, 1164996542, 607225278, 1323610764, 1426881987, 3590304994, 1925078388, 4068182383, 2162078206, 991336113, 2614888103, 633803317, 3248222580, 3479774868, 3835390401, 2666613458, 4022224774, 944711139, 264347078, 2341262773, 604807628, 2007800933, 770255983, 1495990901, 1249150122, 1856431235, 1555081692, 3175218132, 1996064986, 2198950837, 2554220882, 3999719339, 2821834349, 766784016, 2952996808, 2566594879, 3210313671, 3203337956, 3336571891, 1034457026, 3584528711, 2466948901, 113926993, 3758326383, 338241895, 168717936, 666307205, 1188179964, 773529912, 1546045734, 1294757372, 1522805485, 1396182291, 2643833823, 1695183700, 2343527390, 1986661051, 1014477480, 2177026350, 1206759142, 2456956037, 344077627, 2730485921, 1290863460, 2820302411, 3158454273, 3259730800, 3505952657, 3345764771, 106217008, 3516065817, 3606008344, 3600352804, 1432725776, 4094571909, 1467031594, 275423344, 851169720, 430227734, 3100823752, 506948616, 1363258195, 659060556, 3750685593, 883997877, 3785050280, 958139571, 3318307427, 1322822218, 3812723403, 1537002063, 2003034995, 1747873779, 3602036899, 1955562222, 1575990012, 2024104815, 1125592928, 2227730452, 2716904306, 2361852424, 442776044, 2428436474, 593698344, 2756734187, 3733110249, 3204031479, 2999351573, 3329325298, 3815920427, 3391569614, 3928383900, 3515267271, 566280711, 3940187606, 3454069534, 4118630271, 4000239992, 116418474, 1914138554, 174292421, 2731055270, 289380356, 3203993006, 460393269, 320620315, 685471733, 587496836, 852142971, 1086792851, 1017036298, 365543100, 1126000580, 2618297676, 1288033470, 3409855158, 1501505948, 4234509866, 1607167915, 987167468, 1816402316, 1246189591 ]); function hashBlocks(wh, wl, hh, hl, m2, pos, len) { var ah0 = hh[0], ah1 = hh[1], ah2 = hh[2], ah3 = hh[3], ah4 = hh[4], ah5 = hh[5], ah6 = hh[6], ah7 = hh[7], al0 = hl[0], al1 = hl[1], al2 = hl[2], al3 = hl[3], al4 = hl[4], al5 = hl[5], al6 = hl[6], al7 = hl[7]; var h5, l4; var th, tl; var a4, b5, c5, d3; while (len >= 128) { for (var i4 = 0; i4 < 16; i4++) { var j2 = 8 * i4 + pos; wh[i4] = binary_1.readUint32BE(m2, j2); wl[i4] = binary_1.readUint32BE(m2, j2 + 4); } for (var i4 = 0; i4 < 80; i4++) { var bh0 = ah0; var bh1 = ah1; var bh2 = ah2; var bh3 = ah3; var bh4 = ah4; var bh5 = ah5; var bh6 = ah6; var bh7 = ah7; var bl0 = al0; var bl1 = al1; var bl2 = al2; var bl3 = al3; var bl4 = al4; var bl5 = al5; var bl6 = al6; var bl7 = al7; h5 = ah7; l4 = al7; a4 = l4 & 65535; b5 = l4 >>> 16; c5 = h5 & 65535; d3 = h5 >>> 16; h5 = (ah4 >>> 14 | al4 << 32 - 14) ^ (ah4 >>> 18 | al4 << 32 - 18) ^ (al4 >>> 41 - 32 | ah4 << 32 - (41 - 32)); l4 = (al4 >>> 14 | ah4 << 32 - 14) ^ (al4 >>> 18 | ah4 << 32 - 18) ^ (ah4 >>> 41 - 32 | al4 << 32 - (41 - 32)); a4 += l4 & 65535; b5 += l4 >>> 16; c5 += h5 & 65535; d3 += h5 >>> 16; h5 = ah4 & ah5 ^ ~ah4 & ah6; l4 = al4 & al5 ^ ~al4 & al6; a4 += l4 & 65535; b5 += l4 >>> 16; c5 += h5 & 65535; d3 += h5 >>> 16; h5 = K3[i4 * 2]; l4 = K3[i4 * 2 + 1]; a4 += l4 & 65535; b5 += l4 >>> 16; c5 += h5 & 65535; d3 += h5 >>> 16; h5 = wh[i4 % 16]; l4 = wl[i4 % 16]; a4 += l4 & 65535; b5 += l4 >>> 16; c5 += h5 & 65535; d3 += h5 >>> 16; b5 += a4 >>> 16; c5 += b5 >>> 16; d3 += c5 >>> 16; th = c5 & 65535 | d3 << 16; tl = a4 & 65535 | b5 << 16; h5 = th; l4 = tl; a4 = l4 & 65535; b5 = l4 >>> 16; c5 = h5 & 65535; d3 = h5 >>> 16; h5 = (ah0 >>> 28 | al0 << 32 - 28) ^ (al0 >>> 34 - 32 | ah0 << 32 - (34 - 32)) ^ (al0 >>> 39 - 32 | ah0 << 32 - (39 - 32)); l4 = (al0 >>> 28 | ah0 << 32 - 28) ^ (ah0 >>> 34 - 32 | al0 << 32 - (34 - 32)) ^ (ah0 >>> 39 - 32 | al0 << 32 - (39 - 32)); a4 += l4 & 65535; b5 += l4 >>> 16; c5 += h5 & 65535; d3 += h5 >>> 16; h5 = ah0 & ah1 ^ ah0 & ah2 ^ ah1 & ah2; l4 = al0 & al1 ^ al0 & al2 ^ al1 & al2; a4 += l4 & 65535; b5 += l4 >>> 16; c5 += h5 & 65535; d3 += h5 >>> 16; b5 += a4 >>> 16; c5 += b5 >>> 16; d3 += c5 >>> 16; bh7 = c5 & 65535 | d3 << 16; bl7 = a4 & 65535 | b5 << 16; h5 = bh3; l4 = bl3; a4 = l4 & 65535; b5 = l4 >>> 16; c5 = h5 & 65535; d3 = h5 >>> 16; h5 = th; l4 = tl; a4 += l4 & 65535; b5 += l4 >>> 16; c5 += h5 & 65535; d3 += h5 >>> 16; b5 += a4 >>> 16; c5 += b5 >>> 16; d3 += c5 >>> 16; bh3 = c5 & 65535 | d3 << 16; bl3 = a4 & 65535 | b5 << 16; ah1 = bh0; ah2 = bh1; ah3 = bh2; ah4 = bh3; ah5 = bh4; ah6 = bh5; ah7 = bh6; ah0 = bh7; al1 = bl0; al2 = bl1; al3 = bl2; al4 = bl3; al5 = bl4; al6 = bl5; al7 = bl6; al0 = bl7; if (i4 % 16 === 15) { for (var j2 = 0; j2 < 16; j2++) { h5 = wh[j2]; l4 = wl[j2]; a4 = l4 & 65535; b5 = l4 >>> 16; c5 = h5 & 65535; d3 = h5 >>> 16; h5 = wh[(j2 + 9) % 16]; l4 = wl[(j2 + 9) % 16]; a4 += l4 & 65535; b5 += l4 >>> 16; c5 += h5 & 65535; d3 += h5 >>> 16; th = wh[(j2 + 1) % 16]; tl = wl[(j2 + 1) % 16]; h5 = (th >>> 1 | tl << 32 - 1) ^ (th >>> 8 | tl << 32 - 8) ^ th >>> 7; l4 = (tl >>> 1 | th << 32 - 1) ^ (tl >>> 8 | th << 32 - 8) ^ (tl >>> 7 | th << 32 - 7); a4 += l4 & 65535; b5 += l4 >>> 16; c5 += h5 & 65535; d3 += h5 >>> 16; th = wh[(j2 + 14) % 16]; tl = wl[(j2 + 14) % 16]; h5 = (th >>> 19 | tl << 32 - 19) ^ (tl >>> 61 - 32 | th << 32 - (61 - 32)) ^ th >>> 6; l4 = (tl >>> 19 | th << 32 - 19) ^ (th >>> 61 - 32 | tl << 32 - (61 - 32)) ^ (tl >>> 6 | th << 32 - 6); a4 += l4 & 65535; b5 += l4 >>> 16; c5 += h5 & 65535; d3 += h5 >>> 16; b5 += a4 >>> 16; c5 += b5 >>> 16; d3 += c5 >>> 16; wh[j2] = c5 & 65535 | d3 << 16; wl[j2] = a4 & 65535 | b5 << 16; } } } h5 = ah0; l4 = al0; a4 = l4 & 65535; b5 = l4 >>> 16; c5 = h5 & 65535; d3 = h5 >>> 16; h5 = hh[0]; l4 = hl[0]; a4 += l4 & 65535; b5 += l4 >>> 16; c5 += h5 & 65535; d3 += h5 >>> 16; b5 += a4 >>> 16; c5 += b5 >>> 16; d3 += c5 >>> 16; hh[0] = ah0 = c5 & 65535 | d3 << 16; hl[0] = al0 = a4 & 65535 | b5 << 16; h5 = ah1; l4 = al1; a4 = l4 & 65535; b5 = l4 >>> 16; c5 = h5 & 65535; d3 = h5 >>> 16; h5 = hh[1]; l4 = hl[1]; a4 += l4 & 65535; b5 += l4 >>> 16; c5 += h5 & 65535; d3 += h5 >>> 16; b5 += a4 >>> 16; c5 += b5 >>> 16; d3 += c5 >>> 16; hh[1] = ah1 = c5 & 65535 | d3 << 16; hl[1] = al1 = a4 & 65535 | b5 << 16; h5 = ah2; l4 = al2; a4 = l4 & 65535; b5 = l4 >>> 16; c5 = h5 & 65535; d3 = h5 >>> 16; h5 = hh[2]; l4 = hl[2]; a4 += l4 & 65535; b5 += l4 >>> 16; c5 += h5 & 65535; d3 += h5 >>> 16; b5 += a4 >>> 16; c5 += b5 >>> 16; d3 += c5 >>> 16; hh[2] = ah2 = c5 & 65535 | d3 << 16; hl[2] = al2 = a4 & 65535 | b5 << 16; h5 = ah3; l4 = al3; a4 = l4 & 65535; b5 = l4 >>> 16; c5 = h5 & 65535; d3 = h5 >>> 16; h5 = hh[3]; l4 = hl[3]; a4 += l4 & 65535; b5 += l4 >>> 16; c5 += h5 & 65535; d3 += h5 >>> 16; b5 += a4 >>> 16; c5 += b5 >>> 16; d3 += c5 >>> 16; hh[3] = ah3 = c5 & 65535 | d3 << 16; hl[3] = al3 = a4 & 65535 | b5 << 16; h5 = ah4; l4 = al4; a4 = l4 & 65535; b5 = l4 >>> 16; c5 = h5 & 65535; d3 = h5 >>> 16; h5 = hh[4]; l4 = hl[4]; a4 += l4 & 65535; b5 += l4 >>> 16; c5 += h5 & 65535; d3 += h5 >>> 16; b5 += a4 >>> 16; c5 += b5 >>> 16; d3 += c5 >>> 16; hh[4] = ah4 = c5 & 65535 | d3 << 16; hl[4] = al4 = a4 & 65535 | b5 << 16; h5 = ah5; l4 = al5; a4 = l4 & 65535; b5 = l4 >>> 16; c5 = h5 & 65535; d3 = h5 >>> 16; h5 = hh[5]; l4 = hl[5]; a4 += l4 & 65535; b5 += l4 >>> 16; c5 += h5 & 65535; d3 += h5 >>> 16; b5 += a4 >>> 16; c5 += b5 >>> 16; d3 += c5 >>> 16; hh[5] = ah5 = c5 & 65535 | d3 << 16; hl[5] = al5 = a4 & 65535 | b5 << 16; h5 = ah6; l4 = al6; a4 = l4 & 65535; b5 = l4 >>> 16; c5 = h5 & 65535; d3 = h5 >>> 16; h5 = hh[6]; l4 = hl[6]; a4 += l4 & 65535; b5 += l4 >>> 16; c5 += h5 & 65535; d3 += h5 >>> 16; b5 += a4 >>> 16; c5 += b5 >>> 16; d3 += c5 >>> 16; hh[6] = ah6 = c5 & 65535 | d3 << 16; hl[6] = al6 = a4 & 65535 | b5 << 16; h5 = ah7; l4 = al7; a4 = l4 & 65535; b5 = l4 >>> 16; c5 = h5 & 65535; d3 = h5 >>> 16; h5 = hh[7]; l4 = hl[7]; a4 += l4 & 65535; b5 += l4 >>> 16; c5 += h5 & 65535; d3 += h5 >>> 16; b5 += a4 >>> 16; c5 += b5 >>> 16; d3 += c5 >>> 16; hh[7] = ah7 = c5 & 65535 | d3 << 16; hl[7] = al7 = a4 & 65535 | b5 << 16; pos += 128; len -= 128; } return pos; } function hash2(data) { var h5 = new SHA512(); h5.update(data); var digest2 = h5.digest(); h5.clean(); return digest2; } exports.hash = hash2; } }); // node_modules/@stablelib/ed25519/lib/ed25519.js var require_ed25519 = __commonJS({ "node_modules/@stablelib/ed25519/lib/ed25519.js"(exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.convertSecretKeyToX25519 = exports.convertPublicKeyToX25519 = exports.verify = exports.sign = exports.extractPublicKeyFromSecretKey = exports.generateKeyPair = exports.generateKeyPairFromSeed = exports.SEED_LENGTH = exports.SECRET_KEY_LENGTH = exports.PUBLIC_KEY_LENGTH = exports.SIGNATURE_LENGTH = void 0; var random_1 = require_random(); var sha512_1 = require_sha512(); var wipe_1 = require_wipe(); exports.SIGNATURE_LENGTH = 64; exports.PUBLIC_KEY_LENGTH = 32; exports.SECRET_KEY_LENGTH = 64; exports.SEED_LENGTH = 32; function gf(init2) { const r4 = new Float64Array(16); if (init2) { for (let i4 = 0; i4 < init2.length; i4++) { r4[i4] = init2[i4]; } } return r4; } var _9 = new Uint8Array(32); _9[0] = 9; var gf0 = gf(); var gf1 = gf([1]); var D4 = gf([ 30883, 4953, 19914, 30187, 55467, 16705, 2637, 112, 59544, 30585, 16505, 36039, 65139, 11119, 27886, 20995 ]); var D22 = gf([ 61785, 9906, 39828, 60374, 45398, 33411, 5274, 224, 53552, 61171, 33010, 6542, 64743, 22239, 55772, 9222 ]); var X3 = gf([ 54554, 36645, 11616, 51542, 42930, 38181, 51040, 26924, 56412, 64982, 57905, 49316, 21502, 52590, 14035, 8553 ]); var Y2 = gf([ 26200, 26214, 26214, 26214, 26214, 26214, 26214, 26214, 26214, 26214, 26214, 26214, 26214, 26214, 26214, 26214 ]); var I5 = gf([ 41136, 18958, 6951, 50414, 58488, 44335, 6150, 12099, 55207, 15867, 153, 11085, 57099, 20417, 9344, 11139 ]); function set25519(r4, a4) { for (let i4 = 0; i4 < 16; i4++) { r4[i4] = a4[i4] | 0; } } function car25519(o4) { let c5 = 1; for (let i4 = 0; i4 < 16; i4++) { let v5 = o4[i4] + c5 + 65535; c5 = Math.floor(v5 / 65536); o4[i4] = v5 - c5 * 65536; } o4[0] += c5 - 1 + 37 * (c5 - 1); } function sel25519(p3, q3, b5) { const c5 = ~(b5 - 1); for (let i4 = 0; i4 < 16; i4++) { const t = c5 & (p3[i4] ^ q3[i4]); p3[i4] ^= t; q3[i4] ^= t; } } function pack25519(o4, n5) { const m2 = gf(); const t = gf(); for (let i4 = 0; i4 < 16; i4++) { t[i4] = n5[i4]; } car25519(t); car25519(t); car25519(t); for (let j2 = 0; j2 < 2; j2++) { m2[0] = t[0] - 65517; for (let i4 = 1; i4 < 15; i4++) { m2[i4] = t[i4] - 65535 - (m2[i4 - 1] >> 16 & 1); m2[i4 - 1] &= 65535; } m2[15] = t[15] - 32767 - (m2[14] >> 16 & 1); const b5 = m2[15] >> 16 & 1; m2[14] &= 65535; sel25519(t, m2, 1 - b5); } for (let i4 = 0; i4 < 16; i4++) { o4[2 * i4] = t[i4] & 255; o4[2 * i4 + 1] = t[i4] >> 8; } } function verify32(x6, y6) { let d3 = 0; for (let i4 = 0; i4 < 32; i4++) { d3 |= x6[i4] ^ y6[i4]; } return (1 & d3 - 1 >>> 8) - 1; } function neq25519(a4, b5) { const c5 = new Uint8Array(32); const d3 = new Uint8Array(32); pack25519(c5, a4); pack25519(d3, b5); return verify32(c5, d3); } function par25519(a4) { const d3 = new Uint8Array(32); pack25519(d3, a4); return d3[0] & 1; } function unpack25519(o4, n5) { for (let i4 = 0; i4 < 16; i4++) { o4[i4] = n5[2 * i4] + (n5[2 * i4 + 1] << 8); } o4[15] &= 32767; } function add3(o4, a4, b5) { for (let i4 = 0; i4 < 16; i4++) { o4[i4] = a4[i4] + b5[i4]; } } function sub(o4, a4, b5) { for (let i4 = 0; i4 < 16; i4++) { o4[i4] = a4[i4] - b5[i4]; } } function mul3(o4, a4, b5) { let v5, c5, t0 = 0, t1 = 0, t2 = 0, t3 = 0, t4 = 0, t5 = 0, t6 = 0, t7 = 0, t8 = 0, t9 = 0, t10 = 0, t11 = 0, t12 = 0, t13 = 0, t14 = 0, t15 = 0, t16 = 0, t17 = 0, t18 = 0, t19 = 0, t20 = 0, t21 = 0, t22 = 0, t23 = 0, t24 = 0, t25 = 0, t26 = 0, t27 = 0, t28 = 0, t29 = 0, t30 = 0, b0 = b5[0], b1 = b5[1], b22 = b5[2], b32 = b5[3], b42 = b5[4], b52 = b5[5], b6 = b5[6], b7 = b5[7], b8 = b5[8], b9 = b5[9], b10 = b5[10], b11 = b5[11], b12 = b5[12], b13 = b5[13], b14 = b5[14], b15 = b5[15]; v5 = a4[0]; t0 += v5 * b0; t1 += v5 * b1; t2 += v5 * b22; t3 += v5 * b32; t4 += v5 * b42; t5 += v5 * b52; t6 += v5 * b6; t7 += v5 * b7; t8 += v5 * b8; t9 += v5 * b9; t10 += v5 * b10; t11 += v5 * b11; t12 += v5 * b12; t13 += v5 * b13; t14 += v5 * b14; t15 += v5 * b15; v5 = a4[1]; t1 += v5 * b0; t2 += v5 * b1; t3 += v5 * b22; t4 += v5 * b32; t5 += v5 * b42; t6 += v5 * b52; t7 += v5 * b6; t8 += v5 * b7; t9 += v5 * b8; t10 += v5 * b9; t11 += v5 * b10; t12 += v5 * b11; t13 += v5 * b12; t14 += v5 * b13; t15 += v5 * b14; t16 += v5 * b15; v5 = a4[2]; t2 += v5 * b0; t3 += v5 * b1; t4 += v5 * b22; t5 += v5 * b32; t6 += v5 * b42; t7 += v5 * b52; t8 += v5 * b6; t9 += v5 * b7; t10 += v5 * b8; t11 += v5 * b9; t12 += v5 * b10; t13 += v5 * b11; t14 += v5 * b12; t15 += v5 * b13; t16 += v5 * b14; t17 += v5 * b15; v5 = a4[3]; t3 += v5 * b0; t4 += v5 * b1; t5 += v5 * b22; t6 += v5 * b32; t7 += v5 * b42; t8 += v5 * b52; t9 += v5 * b6; t10 += v5 * b7; t11 += v5 * b8; t12 += v5 * b9; t13 += v5 * b10; t14 += v5 * b11; t15 += v5 * b12; t16 += v5 * b13; t17 += v5 * b14; t18 += v5 * b15; v5 = a4[4]; t4 += v5 * b0; t5 += v5 * b1; t6 += v5 * b22; t7 += v5 * b32; t8 += v5 * b42; t9 += v5 * b52; t10 += v5 * b6; t11 += v5 * b7; t12 += v5 * b8; t13 += v5 * b9; t14 += v5 * b10; t15 += v5 * b11; t16 += v5 * b12; t17 += v5 * b13; t18 += v5 * b14; t19 += v5 * b15; v5 = a4[5]; t5 += v5 * b0; t6 += v5 * b1; t7 += v5 * b22; t8 += v5 * b32; t9 += v5 * b42; t10 += v5 * b52; t11 += v5 * b6; t12 += v5 * b7; t13 += v5 * b8; t14 += v5 * b9; t15 += v5 * b10; t16 += v5 * b11; t17 += v5 * b12; t18 += v5 * b13; t19 += v5 * b14; t20 += v5 * b15; v5 = a4[6]; t6 += v5 * b0; t7 += v5 * b1; t8 += v5 * b22; t9 += v5 * b32; t10 += v5 * b42; t11 += v5 * b52; t12 += v5 * b6; t13 += v5 * b7; t14 += v5 * b8; t15 += v5 * b9; t16 += v5 * b10; t17 += v5 * b11; t18 += v5 * b12; t19 += v5 * b13; t20 += v5 * b14; t21 += v5 * b15; v5 = a4[7]; t7 += v5 * b0; t8 += v5 * b1; t9 += v5 * b22; t10 += v5 * b32; t11 += v5 * b42; t12 += v5 * b52; t13 += v5 * b6; t14 += v5 * b7; t15 += v5 * b8; t16 += v5 * b9; t17 += v5 * b10; t18 += v5 * b11; t19 += v5 * b12; t20 += v5 * b13; t21 += v5 * b14; t22 += v5 * b15; v5 = a4[8]; t8 += v5 * b0; t9 += v5 * b1; t10 += v5 * b22; t11 += v5 * b32; t12 += v5 * b42; t13 += v5 * b52; t14 += v5 * b6; t15 += v5 * b7; t16 += v5 * b8; t17 += v5 * b9; t18 += v5 * b10; t19 += v5 * b11; t20 += v5 * b12; t21 += v5 * b13; t22 += v5 * b14; t23 += v5 * b15; v5 = a4[9]; t9 += v5 * b0; t10 += v5 * b1; t11 += v5 * b22; t12 += v5 * b32; t13 += v5 * b42; t14 += v5 * b52; t15 += v5 * b6; t16 += v5 * b7; t17 += v5 * b8; t18 += v5 * b9; t19 += v5 * b10; t20 += v5 * b11; t21 += v5 * b12; t22 += v5 * b13; t23 += v5 * b14; t24 += v5 * b15; v5 = a4[10]; t10 += v5 * b0; t11 += v5 * b1; t12 += v5 * b22; t13 += v5 * b32; t14 += v5 * b42; t15 += v5 * b52; t16 += v5 * b6; t17 += v5 * b7; t18 += v5 * b8; t19 += v5 * b9; t20 += v5 * b10; t21 += v5 * b11; t22 += v5 * b12; t23 += v5 * b13; t24 += v5 * b14; t25 += v5 * b15; v5 = a4[11]; t11 += v5 * b0; t12 += v5 * b1; t13 += v5 * b22; t14 += v5 * b32; t15 += v5 * b42; t16 += v5 * b52; t17 += v5 * b6; t18 += v5 * b7; t19 += v5 * b8; t20 += v5 * b9; t21 += v5 * b10; t22 += v5 * b11; t23 += v5 * b12; t24 += v5 * b13; t25 += v5 * b14; t26 += v5 * b15; v5 = a4[12]; t12 += v5 * b0; t13 += v5 * b1; t14 += v5 * b22; t15 += v5 * b32; t16 += v5 * b42; t17 += v5 * b52; t18 += v5 * b6; t19 += v5 * b7; t20 += v5 * b8; t21 += v5 * b9; t22 += v5 * b10; t23 += v5 * b11; t24 += v5 * b12; t25 += v5 * b13; t26 += v5 * b14; t27 += v5 * b15; v5 = a4[13]; t13 += v5 * b0; t14 += v5 * b1; t15 += v5 * b22; t16 += v5 * b32; t17 += v5 * b42; t18 += v5 * b52; t19 += v5 * b6; t20 += v5 * b7; t21 += v5 * b8; t22 += v5 * b9; t23 += v5 * b10; t24 += v5 * b11; t25 += v5 * b12; t26 += v5 * b13; t27 += v5 * b14; t28 += v5 * b15; v5 = a4[14]; t14 += v5 * b0; t15 += v5 * b1; t16 += v5 * b22; t17 += v5 * b32; t18 += v5 * b42; t19 += v5 * b52; t20 += v5 * b6; t21 += v5 * b7; t22 += v5 * b8; t23 += v5 * b9; t24 += v5 * b10; t25 += v5 * b11; t26 += v5 * b12; t27 += v5 * b13; t28 += v5 * b14; t29 += v5 * b15; v5 = a4[15]; t15 += v5 * b0; t16 += v5 * b1; t17 += v5 * b22; t18 += v5 * b32; t19 += v5 * b42; t20 += v5 * b52; t21 += v5 * b6; t22 += v5 * b7; t23 += v5 * b8; t24 += v5 * b9; t25 += v5 * b10; t26 += v5 * b11; t27 += v5 * b12; t28 += v5 * b13; t29 += v5 * b14; t30 += v5 * b15; t0 += 38 * t16; t1 += 38 * t17; t2 += 38 * t18; t3 += 38 * t19; t4 += 38 * t20; t5 += 38 * t21; t6 += 38 * t22; t7 += 38 * t23; t8 += 38 * t24; t9 += 38 * t25; t10 += 38 * t26; t11 += 38 * t27; t12 += 38 * t28; t13 += 38 * t29; t14 += 38 * t30; c5 = 1; v5 = t0 + c5 + 65535; c5 = Math.floor(v5 / 65536); t0 = v5 - c5 * 65536; v5 = t1 + c5 + 65535; c5 = Math.floor(v5 / 65536); t1 = v5 - c5 * 65536; v5 = t2 + c5 + 65535; c5 = Math.floor(v5 / 65536); t2 = v5 - c5 * 65536; v5 = t3 + c5 + 65535; c5 = Math.floor(v5 / 65536); t3 = v5 - c5 * 65536; v5 = t4 + c5 + 65535; c5 = Math.floor(v5 / 65536); t4 = v5 - c5 * 65536; v5 = t5 + c5 + 65535; c5 = Math.floor(v5 / 65536); t5 = v5 - c5 * 65536; v5 = t6 + c5 + 65535; c5 = Math.floor(v5 / 65536); t6 = v5 - c5 * 65536; v5 = t7 + c5 + 65535; c5 = Math.floor(v5 / 65536); t7 = v5 - c5 * 65536; v5 = t8 + c5 + 65535; c5 = Math.floor(v5 / 65536); t8 = v5 - c5 * 65536; v5 = t9 + c5 + 65535; c5 = Math.floor(v5 / 65536); t9 = v5 - c5 * 65536; v5 = t10 + c5 + 65535; c5 = Math.floor(v5 / 65536); t10 = v5 - c5 * 65536; v5 = t11 + c5 + 65535; c5 = Math.floor(v5 / 65536); t11 = v5 - c5 * 65536; v5 = t12 + c5 + 65535; c5 = Math.floor(v5 / 65536); t12 = v5 - c5 * 65536; v5 = t13 + c5 + 65535; c5 = Math.floor(v5 / 65536); t13 = v5 - c5 * 65536; v5 = t14 + c5 + 65535; c5 = Math.floor(v5 / 65536); t14 = v5 - c5 * 65536; v5 = t15 + c5 + 65535; c5 = Math.floor(v5 / 65536); t15 = v5 - c5 * 65536; t0 += c5 - 1 + 37 * (c5 - 1); c5 = 1; v5 = t0 + c5 + 65535; c5 = Math.floor(v5 / 65536); t0 = v5 - c5 * 65536; v5 = t1 + c5 + 65535; c5 = Math.floor(v5 / 65536); t1 = v5 - c5 * 65536; v5 = t2 + c5 + 65535; c5 = Math.floor(v5 / 65536); t2 = v5 - c5 * 65536; v5 = t3 + c5 + 65535; c5 = Math.floor(v5 / 65536); t3 = v5 - c5 * 65536; v5 = t4 + c5 + 65535; c5 = Math.floor(v5 / 65536); t4 = v5 - c5 * 65536; v5 = t5 + c5 + 65535; c5 = Math.floor(v5 / 65536); t5 = v5 - c5 * 65536; v5 = t6 + c5 + 65535; c5 = Math.floor(v5 / 65536); t6 = v5 - c5 * 65536; v5 = t7 + c5 + 65535; c5 = Math.floor(v5 / 65536); t7 = v5 - c5 * 65536; v5 = t8 + c5 + 65535; c5 = Math.floor(v5 / 65536); t8 = v5 - c5 * 65536; v5 = t9 + c5 + 65535; c5 = Math.floor(v5 / 65536); t9 = v5 - c5 * 65536; v5 = t10 + c5 + 65535; c5 = Math.floor(v5 / 65536); t10 = v5 - c5 * 65536; v5 = t11 + c5 + 65535; c5 = Math.floor(v5 / 65536); t11 = v5 - c5 * 65536; v5 = t12 + c5 + 65535; c5 = Math.floor(v5 / 65536); t12 = v5 - c5 * 65536; v5 = t13 + c5 + 65535; c5 = Math.floor(v5 / 65536); t13 = v5 - c5 * 65536; v5 = t14 + c5 + 65535; c5 = Math.floor(v5 / 65536); t14 = v5 - c5 * 65536; v5 = t15 + c5 + 65535; c5 = Math.floor(v5 / 65536); t15 = v5 - c5 * 65536; t0 += c5 - 1 + 37 * (c5 - 1); o4[0] = t0; o4[1] = t1; o4[2] = t2; o4[3] = t3; o4[4] = t4; o4[5] = t5; o4[6] = t6; o4[7] = t7; o4[8] = t8; o4[9] = t9; o4[10] = t10; o4[11] = t11; o4[12] = t12; o4[13] = t13; o4[14] = t14; o4[15] = t15; } function square(o4, a4) { mul3(o4, a4, a4); } function inv25519(o4, i4) { const c5 = gf(); let a4; for (a4 = 0; a4 < 16; a4++) { c5[a4] = i4[a4]; } for (a4 = 253; a4 >= 0; a4--) { square(c5, c5); if (a4 !== 2 && a4 !== 4) { mul3(c5, c5, i4); } } for (a4 = 0; a4 < 16; a4++) { o4[a4] = c5[a4]; } } function pow2523(o4, i4) { const c5 = gf(); let a4; for (a4 = 0; a4 < 16; a4++) { c5[a4] = i4[a4]; } for (a4 = 250; a4 >= 0; a4--) { square(c5, c5); if (a4 !== 1) { mul3(c5, c5, i4); } } for (a4 = 0; a4 < 16; a4++) { o4[a4] = c5[a4]; } } function edadd(p3, q3) { const a4 = gf(), b5 = gf(), c5 = gf(), d3 = gf(), e2 = gf(), f4 = gf(), g4 = gf(), h5 = gf(), t = gf(); sub(a4, p3[1], p3[0]); sub(t, q3[1], q3[0]); mul3(a4, a4, t); add3(b5, p3[0], p3[1]); add3(t, q3[0], q3[1]); mul3(b5, b5, t); mul3(c5, p3[3], q3[3]); mul3(c5, c5, D22); mul3(d3, p3[2], q3[2]); add3(d3, d3, d3); sub(e2, b5, a4); sub(f4, d3, c5); add3(g4, d3, c5); add3(h5, b5, a4); mul3(p3[0], e2, f4); mul3(p3[1], h5, g4); mul3(p3[2], g4, f4); mul3(p3[3], e2, h5); } function cswap(p3, q3, b5) { for (let i4 = 0; i4 < 4; i4++) { sel25519(p3[i4], q3[i4], b5); } } function pack(r4, p3) { const tx = gf(), ty = gf(), zi2 = gf(); inv25519(zi2, p3[2]); mul3(tx, p3[0], zi2); mul3(ty, p3[1], zi2); pack25519(r4, ty); r4[31] ^= par25519(tx) << 7; } function scalarmult(p3, q3, s3) { set25519(p3[0], gf0); set25519(p3[1], gf1); set25519(p3[2], gf1); set25519(p3[3], gf0); for (let i4 = 255; i4 >= 0; --i4) { const b5 = s3[i4 / 8 | 0] >> (i4 & 7) & 1; cswap(p3, q3, b5); edadd(q3, p3); edadd(p3, p3); cswap(p3, q3, b5); } } function scalarbase(p3, s3) { const q3 = [gf(), gf(), gf(), gf()]; set25519(q3[0], X3); set25519(q3[1], Y2); set25519(q3[2], gf1); mul3(q3[3], X3, Y2); scalarmult(p3, q3, s3); } function generateKeyPairFromSeed2(seed) { if (seed.length !== exports.SEED_LENGTH) { throw new Error(`ed25519: seed must be ${exports.SEED_LENGTH} bytes`); } const d3 = (0, sha512_1.hash)(seed); d3[0] &= 248; d3[31] &= 127; d3[31] |= 64; const publicKey = new Uint8Array(32); const p3 = [gf(), gf(), gf(), gf()]; scalarbase(p3, d3); pack(publicKey, p3); const secretKey = new Uint8Array(64); secretKey.set(seed); secretKey.set(publicKey, 32); return { publicKey, secretKey }; } exports.generateKeyPairFromSeed = generateKeyPairFromSeed2; function generateKeyPair3(prng) { const seed = (0, random_1.randomBytes)(32, prng); const result = generateKeyPairFromSeed2(seed); (0, wipe_1.wipe)(seed); return result; } exports.generateKeyPair = generateKeyPair3; function extractPublicKeyFromSecretKey(secretKey) { if (secretKey.length !== exports.SECRET_KEY_LENGTH) { throw new Error(`ed25519: secret key must be ${exports.SECRET_KEY_LENGTH} bytes`); } return new Uint8Array(secretKey.subarray(32)); } exports.extractPublicKeyFromSecretKey = extractPublicKeyFromSecretKey; var L3 = new Float64Array([ 237, 211, 245, 92, 26, 99, 18, 88, 214, 156, 247, 162, 222, 249, 222, 20, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 16 ]); function modL(r4, x6) { let carry; let i4; let j2; let k4; for (i4 = 63; i4 >= 32; --i4) { carry = 0; for (j2 = i4 - 32, k4 = i4 - 12; j2 < k4; ++j2) { x6[j2] += carry - 16 * x6[i4] * L3[j2 - (i4 - 32)]; carry = Math.floor((x6[j2] + 128) / 256); x6[j2] -= carry * 256; } x6[j2] += carry; x6[i4] = 0; } carry = 0; for (j2 = 0; j2 < 32; j2++) { x6[j2] += carry - (x6[31] >> 4) * L3[j2]; carry = x6[j2] >> 8; x6[j2] &= 255; } for (j2 = 0; j2 < 32; j2++) { x6[j2] -= carry * L3[j2]; } for (i4 = 0; i4 < 32; i4++) { x6[i4 + 1] += x6[i4] >> 8; r4[i4] = x6[i4] & 255; } } function reduce(r4) { const x6 = new Float64Array(64); for (let i4 = 0; i4 < 64; i4++) { x6[i4] = r4[i4]; } for (let i4 = 0; i4 < 64; i4++) { r4[i4] = 0; } modL(r4, x6); } function sign4(secretKey, message) { const x6 = new Float64Array(64); const p3 = [gf(), gf(), gf(), gf()]; const d3 = (0, sha512_1.hash)(secretKey.subarray(0, 32)); d3[0] &= 248; d3[31] &= 127; d3[31] |= 64; const signature2 = new Uint8Array(64); signature2.set(d3.subarray(32), 32); const hs = new sha512_1.SHA512(); hs.update(signature2.subarray(32)); hs.update(message); const r4 = hs.digest(); hs.clean(); reduce(r4); scalarbase(p3, r4); pack(signature2, p3); hs.reset(); hs.update(signature2.subarray(0, 32)); hs.update(secretKey.subarray(32)); hs.update(message); const h5 = hs.digest(); reduce(h5); for (let i4 = 0; i4 < 32; i4++) { x6[i4] = r4[i4]; } for (let i4 = 0; i4 < 32; i4++) { for (let j2 = 0; j2 < 32; j2++) { x6[i4 + j2] += h5[i4] * d3[j2]; } } modL(signature2.subarray(32), x6); return signature2; } exports.sign = sign4; function unpackneg(r4, p3) { const t = gf(), chk = gf(), num = gf(), den = gf(), den2 = gf(), den4 = gf(), den6 = gf(); set25519(r4[2], gf1); unpack25519(r4[1], p3); square(num, r4[1]); mul3(den, num, D4); sub(num, num, r4[2]); add3(den, r4[2], den); square(den2, den); square(den4, den2); mul3(den6, den4, den2); mul3(t, den6, num); mul3(t, t, den); pow2523(t, t); mul3(t, t, num); mul3(t, t, den); mul3(t, t, den); mul3(r4[0], t, den); square(chk, r4[0]); mul3(chk, chk, den); if (neq25519(chk, num)) { mul3(r4[0], r4[0], I5); } square(chk, r4[0]); mul3(chk, chk, den); if (neq25519(chk, num)) { return -1; } if (par25519(r4[0]) === p3[31] >> 7) { sub(r4[0], gf0, r4[0]); } mul3(r4[3], r4[0], r4[1]); return 0; } function verify4(publicKey, message, signature2) { const t = new Uint8Array(32); const p3 = [gf(), gf(), gf(), gf()]; const q3 = [gf(), gf(), gf(), gf()]; if (signature2.length !== exports.SIGNATURE_LENGTH) { throw new Error(`ed25519: signature must be ${exports.SIGNATURE_LENGTH} bytes`); } if (unpackneg(q3, publicKey)) { return false; } const hs = new sha512_1.SHA512(); hs.update(signature2.subarray(0, 32)); hs.update(publicKey); hs.update(message); const h5 = hs.digest(); reduce(h5); scalarmult(p3, q3, h5); scalarbase(q3, signature2.subarray(32)); edadd(p3, q3); pack(t, p3); if (verify32(signature2, t)) { return false; } return true; } exports.verify = verify4; function convertPublicKeyToX25519(publicKey) { let q3 = [gf(), gf(), gf(), gf()]; if (unpackneg(q3, publicKey)) { throw new Error("Ed25519: invalid public key"); } let a4 = gf(); let b5 = gf(); let y6 = q3[1]; add3(a4, gf1, y6); sub(b5, gf1, y6); inv25519(b5, b5); mul3(a4, a4, b5); let z6 = new Uint8Array(32); pack25519(z6, a4); return z6; } exports.convertPublicKeyToX25519 = convertPublicKeyToX25519; function convertSecretKeyToX25519(secretKey) { const d3 = (0, sha512_1.hash)(secretKey.subarray(0, 32)); d3[0] &= 248; d3[31] &= 127; d3[31] |= 64; const o4 = new Uint8Array(d3.subarray(0, 32)); (0, wipe_1.wipe)(d3); return o4; } exports.convertSecretKeyToX25519 = convertSecretKeyToX25519; } }); // node_modules/quick-format-unescaped/index.js var require_quick_format_unescaped = __commonJS({ "node_modules/quick-format-unescaped/index.js"(exports, module) { "use strict"; function tryStringify(o4) { try { return JSON.stringify(o4); } catch (e2) { return '"[Circular]"'; } } module.exports = format; function format(f4, args, opts) { var ss2 = opts && opts.stringify || tryStringify; var offset = 1; if (typeof f4 === "object" && f4 !== null) { var len = args.length + offset; if (len === 1) return f4; var objects = new Array(len); objects[0] = ss2(f4); for (var index = 1; index < len; index++) { objects[index] = ss2(args[index]); } return objects.join(" "); } if (typeof f4 !== "string") { return f4; } var argLen = args.length; if (argLen === 0) return f4; var str = ""; var a4 = 1 - offset; var lastPos = -1; var flen = f4 && f4.length || 0; for (var i4 = 0; i4 < flen; ) { if (f4.charCodeAt(i4) === 37 && i4 + 1 < flen) { lastPos = lastPos > -1 ? lastPos : 0; switch (f4.charCodeAt(i4 + 1)) { case 100: case 102: if (a4 >= argLen) break; if (args[a4] == null) break; if (lastPos < i4) str += f4.slice(lastPos, i4); str += Number(args[a4]); lastPos = i4 + 2; i4++; break; case 105: if (a4 >= argLen) break; if (args[a4] == null) break; if (lastPos < i4) str += f4.slice(lastPos, i4); str += Math.floor(Number(args[a4])); lastPos = i4 + 2; i4++; break; case 79: case 111: case 106: if (a4 >= argLen) break; if (args[a4] === void 0) break; if (lastPos < i4) str += f4.slice(lastPos, i4); var type = typeof args[a4]; if (type === "string") { str += "'" + args[a4] + "'"; lastPos = i4 + 2; i4++; break; } if (type === "function") { str += args[a4].name || ""; lastPos = i4 + 2; i4++; break; } str += ss2(args[a4]); lastPos = i4 + 2; i4++; break; case 115: if (a4 >= argLen) break; if (lastPos < i4) str += f4.slice(lastPos, i4); str += String(args[a4]); lastPos = i4 + 2; i4++; break; case 37: if (lastPos < i4) str += f4.slice(lastPos, i4); str += "%"; lastPos = i4 + 2; i4++; a4--; break; } ++a4; } ++i4; } if (lastPos === -1) return f4; else if (lastPos < flen) { str += f4.slice(lastPos); } return str; } } }); // node_modules/pino/browser.js var require_browser2 = __commonJS({ "node_modules/pino/browser.js"(exports, module) { "use strict"; var format = require_quick_format_unescaped(); module.exports = pino; var _console = pfGlobalThisOrFallback().console || {}; var stdSerializers = { mapHttpRequest: mock, mapHttpResponse: mock, wrapRequestSerializer: passthrough, wrapResponseSerializer: passthrough, wrapErrorSerializer: passthrough, req: mock, res: mock, err: asErrValue }; function shouldSerialize(serialize, serializers) { if (Array.isArray(serialize)) { const hasToFilter = serialize.filter(function(k4) { return k4 !== "!stdSerializers.err"; }); return hasToFilter; } else if (serialize === true) { return Object.keys(serializers); } return false; } function pino(opts) { opts = opts || {}; opts.browser = opts.browser || {}; const transmit2 = opts.browser.transmit; if (transmit2 && typeof transmit2.send !== "function") { throw Error("pino: transmit option must have a send function"); } const proto = opts.browser.write || _console; if (opts.browser.write) opts.browser.asObject = true; const serializers = opts.serializers || {}; const serialize = shouldSerialize(opts.browser.serialize, serializers); let stdErrSerialize = opts.browser.serialize; if (Array.isArray(opts.browser.serialize) && opts.browser.serialize.indexOf("!stdSerializers.err") > -1) stdErrSerialize = false; const levels = ["error", "fatal", "warn", "info", "debug", "trace"]; if (typeof proto === "function") { proto.error = proto.fatal = proto.warn = proto.info = proto.debug = proto.trace = proto; } if (opts.enabled === false) opts.level = "silent"; const level = opts.level || "info"; const logger12 = Object.create(proto); if (!logger12.log) logger12.log = noop; Object.defineProperty(logger12, "levelVal", { get: getLevelVal }); Object.defineProperty(logger12, "level", { get: getLevel, set: setLevel }); const setOpts = { transmit: transmit2, serialize, asObject: opts.browser.asObject, levels, timestamp: getTimeFunction(opts) }; logger12.levels = pino.levels; logger12.level = level; logger12.setMaxListeners = logger12.getMaxListeners = logger12.emit = logger12.addListener = logger12.on = logger12.prependListener = logger12.once = logger12.prependOnceListener = logger12.removeListener = logger12.removeAllListeners = logger12.listeners = logger12.listenerCount = logger12.eventNames = logger12.write = logger12.flush = noop; logger12.serializers = serializers; logger12._serialize = serialize; logger12._stdErrSerialize = stdErrSerialize; logger12.child = child; if (transmit2) logger12._logEvent = createLogEventShape(); function getLevelVal() { return this.level === "silent" ? Infinity : this.levels.values[this.level]; } function getLevel() { return this._level; } function setLevel(level2) { if (level2 !== "silent" && !this.levels.values[level2]) { throw Error("unknown level " + level2); } this._level = level2; set2(setOpts, logger12, "error", "log"); set2(setOpts, logger12, "fatal", "error"); set2(setOpts, logger12, "warn", "error"); set2(setOpts, logger12, "info", "log"); set2(setOpts, logger12, "debug", "log"); set2(setOpts, logger12, "trace", "log"); } function child(bindings, childOptions) { if (!bindings) { throw new Error("missing bindings for child Pino"); } childOptions = childOptions || {}; if (serialize && bindings.serializers) { childOptions.serializers = bindings.serializers; } const childOptionsSerializers = childOptions.serializers; if (serialize && childOptionsSerializers) { var childSerializers = Object.assign({}, serializers, childOptionsSerializers); var childSerialize = opts.browser.serialize === true ? Object.keys(childSerializers) : serialize; delete bindings.serializers; applySerializers([bindings], childSerialize, childSerializers, this._stdErrSerialize); } function Child(parent) { this._childLevel = (parent._childLevel | 0) + 1; this.error = bind(parent, bindings, "error"); this.fatal = bind(parent, bindings, "fatal"); this.warn = bind(parent, bindings, "warn"); this.info = bind(parent, bindings, "info"); this.debug = bind(parent, bindings, "debug"); this.trace = bind(parent, bindings, "trace"); if (childSerializers) { this.serializers = childSerializers; this._serialize = childSerialize; } if (transmit2) { this._logEvent = createLogEventShape( [].concat(parent._logEvent.bindings, bindings) ); } } Child.prototype = this; return new Child(this); } return logger12; } pino.levels = { values: { fatal: 60, error: 50, warn: 40, info: 30, debug: 20, trace: 10 }, labels: { 10: "trace", 20: "debug", 30: "info", 40: "warn", 50: "error", 60: "fatal" } }; pino.stdSerializers = stdSerializers; pino.stdTimeFunctions = Object.assign({}, { nullTime, epochTime, unixTime, isoTime }); function set2(opts, logger12, level, fallback) { const proto = Object.getPrototypeOf(logger12); logger12[level] = logger12.levelVal > logger12.levels.values[level] ? noop : proto[level] ? proto[level] : _console[level] || _console[fallback] || noop; wrap(opts, logger12, level); } function wrap(opts, logger12, level) { if (!opts.transmit && logger12[level] === noop) return; logger12[level] = function(write) { return function LOG() { const ts2 = opts.timestamp(); const args = new Array(arguments.length); const proto = Object.getPrototypeOf && Object.getPrototypeOf(this) === _console ? _console : this; for (var i4 = 0; i4 < args.length; i4++) args[i4] = arguments[i4]; if (opts.serialize && !opts.asObject) { applySerializers(args, this._serialize, this.serializers, this._stdErrSerialize); } if (opts.asObject) write.call(proto, asObject(this, level, args, ts2)); else write.apply(proto, args); if (opts.transmit) { const transmitLevel = opts.transmit.level || logger12.level; const transmitValue = pino.levels.values[transmitLevel]; const methodValue = pino.levels.values[level]; if (methodValue < transmitValue) return; transmit(this, { ts: ts2, methodLevel: level, methodValue, transmitLevel, transmitValue: pino.levels.values[opts.transmit.level || logger12.level], send: opts.transmit.send, val: logger12.levelVal }, args); } }; }(logger12[level]); } function asObject(logger12, level, args, ts2) { if (logger12._serialize) applySerializers(args, logger12._serialize, logger12.serializers, logger12._stdErrSerialize); const argsCloned = args.slice(); let msg = argsCloned[0]; const o4 = {}; if (ts2) { o4.time = ts2; } o4.level = pino.levels.values[level]; let lvl = (logger12._childLevel | 0) + 1; if (lvl < 1) lvl = 1; if (msg !== null && typeof msg === "object") { while (lvl-- && typeof argsCloned[0] === "object") { Object.assign(o4, argsCloned.shift()); } msg = argsCloned.length ? format(argsCloned.shift(), argsCloned) : void 0; } else if (typeof msg === "string") msg = format(argsCloned.shift(), argsCloned); if (msg !== void 0) o4.msg = msg; return o4; } function applySerializers(args, serialize, serializers, stdErrSerialize) { for (const i4 in args) { if (stdErrSerialize && args[i4] instanceof Error) { args[i4] = pino.stdSerializers.err(args[i4]); } else if (typeof args[i4] === "object" && !Array.isArray(args[i4])) { for (const k4 in args[i4]) { if (serialize && serialize.indexOf(k4) > -1 && k4 in serializers) { args[i4][k4] = serializers[k4](args[i4][k4]); } } } } } function bind(parent, bindings, level) { return function() { const args = new Array(1 + arguments.length); args[0] = bindings; for (var i4 = 1; i4 < args.length; i4++) { args[i4] = arguments[i4 - 1]; } return parent[level].apply(this, args); }; } function transmit(logger12, opts, args) { const send = opts.send; const ts2 = opts.ts; const methodLevel = opts.methodLevel; const methodValue = opts.methodValue; const val = opts.val; const bindings = logger12._logEvent.bindings; applySerializers( args, logger12._serialize || Object.keys(logger12.serializers), logger12.serializers, logger12._stdErrSerialize === void 0 ? true : logger12._stdErrSerialize ); logger12._logEvent.ts = ts2; logger12._logEvent.messages = args.filter(function(arg) { return bindings.indexOf(arg) === -1; }); logger12._logEvent.level.label = methodLevel; logger12._logEvent.level.value = methodValue; send(methodLevel, logger12._logEvent, val); logger12._logEvent = createLogEventShape(bindings); } function createLogEventShape(bindings) { return { ts: 0, messages: [], bindings: bindings || [], level: { label: "", value: 0 } }; } function asErrValue(err) { const obj = { type: err.constructor.name, msg: err.message, stack: err.stack }; for (const key2 in err) { if (obj[key2] === void 0) { obj[key2] = err[key2]; } } return obj; } function getTimeFunction(opts) { if (typeof opts.timestamp === "function") { return opts.timestamp; } if (opts.timestamp === false) { return nullTime; } return epochTime; } function mock() { return {}; } function passthrough(a4) { return a4; } function noop() { } function nullTime() { return false; } function epochTime() { return Date.now(); } function unixTime() { return Math.round(Date.now() / 1e3); } function isoTime() { return new Date(Date.now()).toISOString(); } function pfGlobalThisOrFallback() { function defd(o4) { return typeof o4 !== "undefined" && o4; } try { if (typeof globalThis !== "undefined") return globalThis; Object.defineProperty(Object.prototype, "globalThis", { get: function() { delete Object.prototype.globalThis; return this.globalThis = this; }, configurable: true }); return globalThis; } catch (e2) { return defd(self) || defd(window) || defd(this) || {}; } } } }); // node_modules/@walletconnect/environment/dist/cjs/crypto.js var require_crypto2 = __commonJS({ "node_modules/@walletconnect/environment/dist/cjs/crypto.js"(exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.isBrowserCryptoAvailable = exports.getSubtleCrypto = exports.getBrowerCrypto = void 0; function getBrowerCrypto() { return (global === null || global === void 0 ? void 0 : global.crypto) || (global === null || global === void 0 ? void 0 : global.msCrypto) || {}; } exports.getBrowerCrypto = getBrowerCrypto; function getSubtleCrypto() { const browserCrypto = getBrowerCrypto(); return browserCrypto.subtle || browserCrypto.webkitSubtle; } exports.getSubtleCrypto = getSubtleCrypto; function isBrowserCryptoAvailable() { return !!getBrowerCrypto() && !!getSubtleCrypto(); } exports.isBrowserCryptoAvailable = isBrowserCryptoAvailable; } }); // node_modules/@walletconnect/environment/dist/cjs/env.js var require_env = __commonJS({ "node_modules/@walletconnect/environment/dist/cjs/env.js"(exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.isBrowser = exports.isNode = exports.isReactNative = void 0; function isReactNative() { return typeof document === "undefined" && typeof navigator !== "undefined" && navigator.product === "ReactNative"; } exports.isReactNative = isReactNative; function isNode2() { return typeof process !== "undefined" && typeof process.versions !== "undefined" && typeof process.versions.node !== "undefined"; } exports.isNode = isNode2; function isBrowser() { return !isReactNative() && !isNode2(); } exports.isBrowser = isBrowser; } }); // node_modules/@walletconnect/environment/dist/cjs/index.js var require_cjs4 = __commonJS({ "node_modules/@walletconnect/environment/dist/cjs/index.js"(exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var tslib_1 = (init_tslib_es6(), __toCommonJS(tslib_es6_exports)); tslib_1.__exportStar(require_crypto2(), exports); tslib_1.__exportStar(require_env(), exports); } }); // node_modules/ws/browser.js var require_browser3 = __commonJS({ "node_modules/ws/browser.js"(exports, module) { "use strict"; module.exports = function() { throw new Error( "ws does not work in the browser. Browser clients must use the native WebSocket object" ); }; } }); // node_modules/lodash.isequal/index.js var require_lodash = __commonJS({ "node_modules/lodash.isequal/index.js"(exports, module) { var LARGE_ARRAY_SIZE = 200; var HASH_UNDEFINED = "__lodash_hash_undefined__"; var COMPARE_PARTIAL_FLAG = 1; var COMPARE_UNORDERED_FLAG = 2; var MAX_SAFE_INTEGER2 = 9007199254740991; var argsTag = "[object Arguments]"; var arrayTag = "[object Array]"; var asyncTag = "[object AsyncFunction]"; var boolTag = "[object Boolean]"; var dateTag = "[object Date]"; var errorTag = "[object Error]"; var funcTag = "[object Function]"; var genTag = "[object GeneratorFunction]"; var mapTag = "[object Map]"; var numberTag = "[object Number]"; var nullTag = "[object Null]"; var objectTag = "[object Object]"; var promiseTag = "[object Promise]"; var proxyTag = "[object Proxy]"; var regexpTag = "[object RegExp]"; var setTag = "[object Set]"; var stringTag = "[object String]"; var symbolTag = "[object Symbol]"; var undefinedTag = "[object Undefined]"; var weakMapTag = "[object WeakMap]"; var arrayBufferTag = "[object ArrayBuffer]"; var dataViewTag = "[object DataView]"; var float32Tag = "[object Float32Array]"; var float64Tag = "[object Float64Array]"; var int8Tag = "[object Int8Array]"; var int16Tag = "[object Int16Array]"; var int32Tag = "[object Int32Array]"; var uint8Tag = "[object Uint8Array]"; var uint8ClampedTag = "[object Uint8ClampedArray]"; var uint16Tag = "[object Uint16Array]"; var uint32Tag = "[object Uint32Array]"; var reRegExpChar = /[\\^$.*+?()[\]{}|]/g; var reIsHostCtor = /^\[object .+?Constructor\]$/; var reIsUint = /^(?:0|[1-9]\d*)$/; var typedArrayTags = {}; typedArrayTags[float32Tag] = typedArrayTags[float64Tag] = typedArrayTags[int8Tag] = typedArrayTags[int16Tag] = typedArrayTags[int32Tag] = typedArrayTags[uint8Tag] = typedArrayTags[uint8ClampedTag] = typedArrayTags[uint16Tag] = typedArrayTags[uint32Tag] = true; typedArrayTags[argsTag] = typedArrayTags[arrayTag] = typedArrayTags[arrayBufferTag] = typedArrayTags[boolTag] = typedArrayTags[dataViewTag] = typedArrayTags[dateTag] = typedArrayTags[errorTag] = typedArrayTags[funcTag] = typedArrayTags[mapTag] = typedArrayTags[numberTag] = typedArrayTags[objectTag] = typedArrayTags[regexpTag] = typedArrayTags[setTag] = typedArrayTags[stringTag] = typedArrayTags[weakMapTag] = false; var freeGlobal = typeof global == "object" && global && global.Object === Object && global; var freeSelf = typeof self == "object" && self && self.Object === Object && self; var root = freeGlobal || freeSelf || Function("return this")(); var freeExports = typeof exports == "object" && exports && !exports.nodeType && exports; var freeModule = freeExports && typeof module == "object" && module && !module.nodeType && module; var moduleExports = freeModule && freeModule.exports === freeExports; var freeProcess = moduleExports && freeGlobal.process; var nodeUtil = function() { try { return freeProcess && freeProcess.binding && freeProcess.binding("util"); } catch (e2) { } }(); var nodeIsTypedArray = nodeUtil && nodeUtil.isTypedArray; function arrayFilter(array, predicate) { var index = -1, length2 = array == null ? 0 : array.length, resIndex = 0, result = []; while (++index < length2) { var value = array[index]; if (predicate(value, index, array)) { result[resIndex++] = value; } } return result; } function arrayPush(array, values) { var index = -1, length2 = values.length, offset = array.length; while (++index < length2) { array[offset + index] = values[index]; } return array; } function arraySome(array, predicate) { var index = -1, length2 = array == null ? 0 : array.length; while (++index < length2) { if (predicate(array[index], index, array)) { return true; } } return false; } function baseTimes(n5, iteratee) { var index = -1, result = Array(n5); while (++index < n5) { result[index] = iteratee(index); } return result; } function baseUnary(func) { return function(value) { return func(value); }; } function cacheHas(cache, key2) { return cache.has(key2); } function getValue(object, key2) { return object == null ? void 0 : object[key2]; } function mapToArray(map) { var index = -1, result = Array(map.size); map.forEach(function(value, key2) { result[++index] = [key2, value]; }); return result; } function overArg(func, transform) { return function(arg) { return func(transform(arg)); }; } function setToArray(set2) { var index = -1, result = Array(set2.size); set2.forEach(function(value) { result[++index] = value; }); return result; } var arrayProto = Array.prototype; var funcProto = Function.prototype; var objectProto = Object.prototype; var coreJsData = root["__core-js_shared__"]; var funcToString = funcProto.toString; var hasOwnProperty = objectProto.hasOwnProperty; var maskSrcKey = function() { var uid = /[^.]+$/.exec(coreJsData && coreJsData.keys && coreJsData.keys.IE_PROTO || ""); return uid ? "Symbol(src)_1." + uid : ""; }(); var nativeObjectToString = objectProto.toString; var reIsNative = RegExp( "^" + funcToString.call(hasOwnProperty).replace(reRegExpChar, "\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g, "$1.*?") + "$" ); var Buffer2 = moduleExports ? root.Buffer : void 0; var Symbol2 = root.Symbol; var Uint8Array2 = root.Uint8Array; var propertyIsEnumerable = objectProto.propertyIsEnumerable; var splice = arrayProto.splice; var symToStringTag = Symbol2 ? Symbol2.toStringTag : void 0; var nativeGetSymbols = Object.getOwnPropertySymbols; var nativeIsBuffer = Buffer2 ? Buffer2.isBuffer : void 0; var nativeKeys = overArg(Object.keys, Object); var DataView2 = getNative(root, "DataView"); var Map2 = getNative(root, "Map"); var Promise2 = getNative(root, "Promise"); var Set2 = getNative(root, "Set"); var WeakMap = getNative(root, "WeakMap"); var nativeCreate = getNative(Object, "create"); var dataViewCtorString = toSource(DataView2); var mapCtorString = toSource(Map2); var promiseCtorString = toSource(Promise2); var setCtorString = toSource(Set2); var weakMapCtorString = toSource(WeakMap); var symbolProto = Symbol2 ? Symbol2.prototype : void 0; var symbolValueOf = symbolProto ? symbolProto.valueOf : void 0; function Hash(entries) { var index = -1, length2 = entries == null ? 0 : entries.length; this.clear(); while (++index < length2) { var entry = entries[index]; this.set(entry[0], entry[1]); } } function hashClear() { this.__data__ = nativeCreate ? nativeCreate(null) : {}; this.size = 0; } function hashDelete(key2) { var result = this.has(key2) && delete this.__data__[key2]; this.size -= result ? 1 : 0; return result; } function hashGet(key2) { var data = this.__data__; if (nativeCreate) { var result = data[key2]; return result === HASH_UNDEFINED ? void 0 : result; } return hasOwnProperty.call(data, key2) ? data[key2] : void 0; } function hashHas(key2) { var data = this.__data__; return nativeCreate ? data[key2] !== void 0 : hasOwnProperty.call(data, key2); } function hashSet(key2, value) { var data = this.__data__; this.size += this.has(key2) ? 0 : 1; data[key2] = nativeCreate && value === void 0 ? HASH_UNDEFINED : value; return this; } Hash.prototype.clear = hashClear; Hash.prototype["delete"] = hashDelete; Hash.prototype.get = hashGet; Hash.prototype.has = hashHas; Hash.prototype.set = hashSet; function ListCache(entries) { var index = -1, length2 = entries == null ? 0 : entries.length; this.clear(); while (++index < length2) { var entry = entries[index]; this.set(entry[0], entry[1]); } } function listCacheClear() { this.__data__ = []; this.size = 0; } function listCacheDelete(key2) { var data = this.__data__, index = assocIndexOf(data, key2); if (index < 0) { return false; } var lastIndex = data.length - 1; if (index == lastIndex) { data.pop(); } else { splice.call(data, index, 1); } --this.size; return true; } function listCacheGet(key2) { var data = this.__data__, index = assocIndexOf(data, key2); return index < 0 ? void 0 : data[index][1]; } function listCacheHas(key2) { return assocIndexOf(this.__data__, key2) > -1; } function listCacheSet(key2, value) { var data = this.__data__, index = assocIndexOf(data, key2); if (index < 0) { ++this.size; data.push([key2, value]); } else { data[index][1] = value; } return this; } ListCache.prototype.clear = listCacheClear; ListCache.prototype["delete"] = listCacheDelete; ListCache.prototype.get = listCacheGet; ListCache.prototype.has = listCacheHas; ListCache.prototype.set = listCacheSet; function MapCache(entries) { var index = -1, length2 = entries == null ? 0 : entries.length; this.clear(); while (++index < length2) { var entry = entries[index]; this.set(entry[0], entry[1]); } } function mapCacheClear() { this.size = 0; this.__data__ = { "hash": new Hash(), "map": new (Map2 || ListCache)(), "string": new Hash() }; } function mapCacheDelete(key2) { var result = getMapData(this, key2)["delete"](key2); this.size -= result ? 1 : 0; return result; } function mapCacheGet(key2) { return getMapData(this, key2).get(key2); } function mapCacheHas(key2) { return getMapData(this, key2).has(key2); } function mapCacheSet(key2, value) { var data = getMapData(this, key2), size = data.size; data.set(key2, value); this.size += data.size == size ? 0 : 1; return this; } MapCache.prototype.clear = mapCacheClear; MapCache.prototype["delete"] = mapCacheDelete; MapCache.prototype.get = mapCacheGet; MapCache.prototype.has = mapCacheHas; MapCache.prototype.set = mapCacheSet; function SetCache(values) { var index = -1, length2 = values == null ? 0 : values.length; this.__data__ = new MapCache(); while (++index < length2) { this.add(values[index]); } } function setCacheAdd(value) { this.__data__.set(value, HASH_UNDEFINED); return this; } function setCacheHas(value) { return this.__data__.has(value); } SetCache.prototype.add = SetCache.prototype.push = setCacheAdd; SetCache.prototype.has = setCacheHas; function Stack(entries) { var data = this.__data__ = new ListCache(entries); this.size = data.size; } function stackClear() { this.__data__ = new ListCache(); this.size = 0; } function stackDelete(key2) { var data = this.__data__, result = data["delete"](key2); this.size = data.size; return result; } function stackGet(key2) { return this.__data__.get(key2); } function stackHas(key2) { return this.__data__.has(key2); } function stackSet(key2, value) { var data = this.__data__; if (data instanceof ListCache) { var pairs = data.__data__; if (!Map2 || pairs.length < LARGE_ARRAY_SIZE - 1) { pairs.push([key2, value]); this.size = ++data.size; return this; } data = this.__data__ = new MapCache(pairs); } data.set(key2, value); this.size = data.size; return this; } Stack.prototype.clear = stackClear; Stack.prototype["delete"] = stackDelete; Stack.prototype.get = stackGet; Stack.prototype.has = stackHas; Stack.prototype.set = stackSet; function arrayLikeKeys(value, inherited) { var isArr = isArray(value), isArg = !isArr && isArguments(value), isBuff = !isArr && !isArg && isBuffer(value), isType = !isArr && !isArg && !isBuff && isTypedArray(value), skipIndexes = isArr || isArg || isBuff || isType, result = skipIndexes ? baseTimes(value.length, String) : [], length2 = result.length; for (var key2 in value) { if ((inherited || hasOwnProperty.call(value, key2)) && !(skipIndexes && // Safari 9 has enumerable `arguments.length` in strict mode. (key2 == "length" || // Node.js 0.10 has enumerable non-index properties on buffers. isBuff && (key2 == "offset" || key2 == "parent") || // PhantomJS 2 has enumerable non-index properties on typed arrays. isType && (key2 == "buffer" || key2 == "byteLength" || key2 == "byteOffset") || // Skip index properties. isIndex(key2, length2)))) { result.push(key2); } } return result; } function assocIndexOf(array, key2) { var length2 = array.length; while (length2--) { if (eq4(array[length2][0], key2)) { return length2; } } return -1; } function baseGetAllKeys(object, keysFunc, symbolsFunc) { var result = keysFunc(object); return isArray(object) ? result : arrayPush(result, symbolsFunc(object)); } function baseGetTag(value) { if (value == null) { return value === void 0 ? undefinedTag : nullTag; } return symToStringTag && symToStringTag in Object(value) ? getRawTag(value) : objectToString(value); } function baseIsArguments(value) { return isObjectLike(value) && baseGetTag(value) == argsTag; } function baseIsEqual(value, other, bitmask, customizer, stack) { if (value === other) { return true; } if (value == null || other == null || !isObjectLike(value) && !isObjectLike(other)) { return value !== value && other !== other; } return baseIsEqualDeep(value, other, bitmask, customizer, baseIsEqual, stack); } function baseIsEqualDeep(object, other, bitmask, customizer, equalFunc, stack) { var objIsArr = isArray(object), othIsArr = isArray(other), objTag = objIsArr ? arrayTag : getTag(object), othTag = othIsArr ? arrayTag : getTag(other); objTag = objTag == argsTag ? objectTag : objTag; othTag = othTag == argsTag ? objectTag : othTag; var objIsObj = objTag == objectTag, othIsObj = othTag == objectTag, isSameTag = objTag == othTag; if (isSameTag && isBuffer(object)) { if (!isBuffer(other)) { return false; } objIsArr = true; objIsObj = false; } if (isSameTag && !objIsObj) { stack || (stack = new Stack()); return objIsArr || isTypedArray(object) ? equalArrays(object, other, bitmask, customizer, equalFunc, stack) : equalByTag(object, other, objTag, bitmask, customizer, equalFunc, stack); } if (!(bitmask & COMPARE_PARTIAL_FLAG)) { var objIsWrapped = objIsObj && hasOwnProperty.call(object, "__wrapped__"), othIsWrapped = othIsObj && hasOwnProperty.call(other, "__wrapped__"); if (objIsWrapped || othIsWrapped) { var objUnwrapped = objIsWrapped ? object.value() : object, othUnwrapped = othIsWrapped ? other.value() : other; stack || (stack = new Stack()); return equalFunc(objUnwrapped, othUnwrapped, bitmask, customizer, stack); } } if (!isSameTag) { return false; } stack || (stack = new Stack()); return equalObjects(object, other, bitmask, customizer, equalFunc, stack); } function baseIsNative(value) { if (!isObject(value) || isMasked(value)) { return false; } var pattern = isFunction(value) ? reIsNative : reIsHostCtor; return pattern.test(toSource(value)); } function baseIsTypedArray(value) { return isObjectLike(value) && isLength(value.length) && !!typedArrayTags[baseGetTag(value)]; } function baseKeys(object) { if (!isPrototype(object)) { return nativeKeys(object); } var result = []; for (var key2 in Object(object)) { if (hasOwnProperty.call(object, key2) && key2 != "constructor") { result.push(key2); } } return result; } function equalArrays(array, other, bitmask, customizer, equalFunc, stack) { var isPartial = bitmask & COMPARE_PARTIAL_FLAG, arrLength = array.length, othLength = other.length; if (arrLength != othLength && !(isPartial && othLength > arrLength)) { return false; } var stacked = stack.get(array); if (stacked && stack.get(other)) { return stacked == other; } var index = -1, result = true, seen = bitmask & COMPARE_UNORDERED_FLAG ? new SetCache() : void 0; stack.set(array, other); stack.set(other, array); while (++index < arrLength) { var arrValue = array[index], othValue = other[index]; if (customizer) { var compared = isPartial ? customizer(othValue, arrValue, index, other, array, stack) : customizer(arrValue, othValue, index, array, other, stack); } if (compared !== void 0) { if (compared) { continue; } result = false; break; } if (seen) { if (!arraySome(other, function(othValue2, othIndex) { if (!cacheHas(seen, othIndex) && (arrValue === othValue2 || equalFunc(arrValue, othValue2, bitmask, customizer, stack))) { return seen.push(othIndex); } })) { result = false; break; } } else if (!(arrValue === othValue || equalFunc(arrValue, othValue, bitmask, customizer, stack))) { result = false; break; } } stack["delete"](array); stack["delete"](other); return result; } function equalByTag(object, other, tag, bitmask, customizer, equalFunc, stack) { switch (tag) { case dataViewTag: if (object.byteLength != other.byteLength || object.byteOffset != other.byteOffset) { return false; } object = object.buffer; other = other.buffer; case arrayBufferTag: if (object.byteLength != other.byteLength || !equalFunc(new Uint8Array2(object), new Uint8Array2(other))) { return false; } return true; case boolTag: case dateTag: case numberTag: return eq4(+object, +other); case errorTag: return object.name == other.name && object.message == other.message; case regexpTag: case stringTag: return object == other + ""; case mapTag: var convert = mapToArray; case setTag: var isPartial = bitmask & COMPARE_PARTIAL_FLAG; convert || (convert = setToArray); if (object.size != other.size && !isPartial) { return false; } var stacked = stack.get(object); if (stacked) { return stacked == other; } bitmask |= COMPARE_UNORDERED_FLAG; stack.set(object, other); var result = equalArrays(convert(object), convert(other), bitmask, customizer, equalFunc, stack); stack["delete"](object); return result; case symbolTag: if (symbolValueOf) { return symbolValueOf.call(object) == symbolValueOf.call(other); } } return false; } function equalObjects(object, other, bitmask, customizer, equalFunc, stack) { var isPartial = bitmask & COMPARE_PARTIAL_FLAG, objProps = getAllKeys(object), objLength = objProps.length, othProps = getAllKeys(other), othLength = othProps.length; if (objLength != othLength && !isPartial) { return false; } var index = objLength; while (index--) { var key2 = objProps[index]; if (!(isPartial ? key2 in other : hasOwnProperty.call(other, key2))) { return false; } } var stacked = stack.get(object); if (stacked && stack.get(other)) { return stacked == other; } var result = true; stack.set(object, other); stack.set(other, object); var skipCtor = isPartial; while (++index < objLength) { key2 = objProps[index]; var objValue = object[key2], othValue = other[key2]; if (customizer) { var compared = isPartial ? customizer(othValue, objValue, key2, other, object, stack) : customizer(objValue, othValue, key2, object, other, stack); } if (!(compared === void 0 ? objValue === othValue || equalFunc(objValue, othValue, bitmask, customizer, stack) : compared)) { result = false; break; } skipCtor || (skipCtor = key2 == "constructor"); } if (result && !skipCtor) { var objCtor = object.constructor, othCtor = other.constructor; if (objCtor != othCtor && ("constructor" in object && "constructor" in other) && !(typeof objCtor == "function" && objCtor instanceof objCtor && typeof othCtor == "function" && othCtor instanceof othCtor)) { result = false; } } stack["delete"](object); stack["delete"](other); return result; } function getAllKeys(object) { return baseGetAllKeys(object, keys2, getSymbols); } function getMapData(map, key2) { var data = map.__data__; return isKeyable(key2) ? data[typeof key2 == "string" ? "string" : "hash"] : data.map; } function getNative(object, key2) { var value = getValue(object, key2); return baseIsNative(value) ? value : void 0; } function getRawTag(value) { var isOwn = hasOwnProperty.call(value, symToStringTag), tag = value[symToStringTag]; try { value[symToStringTag] = void 0; var unmasked = true; } catch (e2) { } var result = nativeObjectToString.call(value); if (unmasked) { if (isOwn) { value[symToStringTag] = tag; } else { delete value[symToStringTag]; } } return result; } var getSymbols = !nativeGetSymbols ? stubArray : function(object) { if (object == null) { return []; } object = Object(object); return arrayFilter(nativeGetSymbols(object), function(symbol) { return propertyIsEnumerable.call(object, symbol); }); }; var getTag = baseGetTag; if (DataView2 && getTag(new DataView2(new ArrayBuffer(1))) != dataViewTag || Map2 && getTag(new Map2()) != mapTag || Promise2 && getTag(Promise2.resolve()) != promiseTag || Set2 && getTag(new Set2()) != setTag || WeakMap && getTag(new WeakMap()) != weakMapTag) { getTag = function(value) { var result = baseGetTag(value), Ctor = result == objectTag ? value.constructor : void 0, ctorString = Ctor ? toSource(Ctor) : ""; if (ctorString) { switch (ctorString) { case dataViewCtorString: return dataViewTag; case mapCtorString: return mapTag; case promiseCtorString: return promiseTag; case setCtorString: return setTag; case weakMapCtorString: return weakMapTag; } } return result; }; } function isIndex(value, length2) { length2 = length2 == null ? MAX_SAFE_INTEGER2 : length2; return !!length2 && (typeof value == "number" || reIsUint.test(value)) && (value > -1 && value % 1 == 0 && value < length2); } function isKeyable(value) { var type = typeof value; return type == "string" || type == "number" || type == "symbol" || type == "boolean" ? value !== "__proto__" : value === null; } function isMasked(func) { return !!maskSrcKey && maskSrcKey in func; } function isPrototype(value) { var Ctor = value && value.constructor, proto = typeof Ctor == "function" && Ctor.prototype || objectProto; return value === proto; } function objectToString(value) { return nativeObjectToString.call(value); } function toSource(func) { if (func != null) { try { return funcToString.call(func); } catch (e2) { } try { return func + ""; } catch (e2) { } } return ""; } function eq4(value, other) { return value === other || value !== value && other !== other; } var isArguments = baseIsArguments(function() { return arguments; }()) ? baseIsArguments : function(value) { return isObjectLike(value) && hasOwnProperty.call(value, "callee") && !propertyIsEnumerable.call(value, "callee"); }; var isArray = Array.isArray; function isArrayLike(value) { return value != null && isLength(value.length) && !isFunction(value); } var isBuffer = nativeIsBuffer || stubFalse; function isEqual(value, other) { return baseIsEqual(value, other); } function isFunction(value) { if (!isObject(value)) { return false; } var tag = baseGetTag(value); return tag == funcTag || tag == genTag || tag == asyncTag || tag == proxyTag; } function isLength(value) { return typeof value == "number" && value > -1 && value % 1 == 0 && value <= MAX_SAFE_INTEGER2; } function isObject(value) { var type = typeof value; return value != null && (type == "object" || type == "function"); } function isObjectLike(value) { return value != null && typeof value == "object"; } var isTypedArray = nodeIsTypedArray ? baseUnary(nodeIsTypedArray) : baseIsTypedArray; function keys2(object) { return isArrayLike(object) ? arrayLikeKeys(object) : baseKeys(object); } function stubArray() { return []; } function stubFalse() { return false; } module.exports = isEqual; } }); // node_modules/detect-browser/es/index.js var __spreadArray = function(to2, from3, pack) { if (pack || arguments.length === 2) for (var i4 = 0, l4 = from3.length, ar3; i4 < l4; i4++) { if (ar3 || !(i4 in from3)) { if (!ar3) ar3 = Array.prototype.slice.call(from3, 0, i4); ar3[i4] = from3[i4]; } } return to2.concat(ar3 || Array.prototype.slice.call(from3)); }; var BrowserInfo = ( /** @class */ function() { function BrowserInfo2(name2, version12, os) { this.name = name2; this.version = version12; this.os = os; this.type = "browser"; } return BrowserInfo2; }() ); var NodeInfo = ( /** @class */ function() { function NodeInfo2(version12) { this.version = version12; this.type = "node"; this.name = "node"; this.os = process.platform; } return NodeInfo2; }() ); var SearchBotDeviceInfo = ( /** @class */ function() { function SearchBotDeviceInfo2(name2, version12, os, bot) { this.name = name2; this.version = version12; this.os = os; this.bot = bot; this.type = "bot-device"; } return SearchBotDeviceInfo2; }() ); var BotInfo = ( /** @class */ function() { function BotInfo2() { this.type = "bot"; this.bot = true; this.name = "bot"; this.version = null; this.os = null; } return BotInfo2; }() ); var ReactNativeInfo = ( /** @class */ function() { function ReactNativeInfo2() { this.type = "react-native"; this.name = "react-native"; this.version = null; this.os = null; } return ReactNativeInfo2; }() ); var SEARCHBOX_UA_REGEX = /alexa|bot|crawl(er|ing)|facebookexternalhit|feedburner|google web preview|nagios|postrank|pingdom|slurp|spider|yahoo!|yandex/; var SEARCHBOT_OS_REGEX = /(nuhk|curl|Googlebot|Yammybot|Openbot|Slurp|MSNBot|Ask\ Jeeves\/Teoma|ia_archiver)/; var REQUIRED_VERSION_PARTS = 3; var userAgentRules = [ ["aol", /AOLShield\/([0-9\._]+)/], ["edge", /Edge\/([0-9\._]+)/], ["edge-ios", /EdgiOS\/([0-9\._]+)/], ["yandexbrowser", /YaBrowser\/([0-9\._]+)/], ["kakaotalk", /KAKAOTALK\s([0-9\.]+)/], ["samsung", /SamsungBrowser\/([0-9\.]+)/], ["silk", /\bSilk\/([0-9._-]+)\b/], ["miui", /MiuiBrowser\/([0-9\.]+)$/], ["beaker", /BeakerBrowser\/([0-9\.]+)/], ["edge-chromium", /EdgA?\/([0-9\.]+)/], [ "chromium-webview", /(?!Chrom.*OPR)wv\).*Chrom(?:e|ium)\/([0-9\.]+)(:?\s|$)/ ], ["chrome", /(?!Chrom.*OPR)Chrom(?:e|ium)\/([0-9\.]+)(:?\s|$)/], ["phantomjs", /PhantomJS\/([0-9\.]+)(:?\s|$)/], ["crios", /CriOS\/([0-9\.]+)(:?\s|$)/], ["firefox", /Firefox\/([0-9\.]+)(?:\s|$)/], ["fxios", /FxiOS\/([0-9\.]+)/], ["opera-mini", /Opera Mini.*Version\/([0-9\.]+)/], ["opera", /Opera\/([0-9\.]+)(?:\s|$)/], ["opera", /OPR\/([0-9\.]+)(:?\s|$)/], ["pie", /^Microsoft Pocket Internet Explorer\/(\d+\.\d+)$/], ["pie", /^Mozilla\/\d\.\d+\s\(compatible;\s(?:MSP?IE|MSInternet Explorer) (\d+\.\d+);.*Windows CE.*\)$/], ["netfront", /^Mozilla\/\d\.\d+.*NetFront\/(\d.\d)/], ["ie", /Trident\/7\.0.*rv\:([0-9\.]+).*\).*Gecko$/], ["ie", /MSIE\s([0-9\.]+);.*Trident\/[4-7].0/], ["ie", /MSIE\s(7\.0)/], ["bb10", /BB10;\sTouch.*Version\/([0-9\.]+)/], ["android", /Android\s([0-9\.]+)/], ["ios", /Version\/([0-9\._]+).*Mobile.*Safari.*/], ["safari", /Version\/([0-9\._]+).*Safari/], ["facebook", /FB[AS]V\/([0-9\.]+)/], ["instagram", /Instagram\s([0-9\.]+)/], ["ios-webview", /AppleWebKit\/([0-9\.]+).*Mobile/], ["ios-webview", /AppleWebKit\/([0-9\.]+).*Gecko\)$/], ["curl", /^curl\/([0-9\.]+)$/], ["searchbot", SEARCHBOX_UA_REGEX] ]; var operatingSystemRules = [ ["iOS", /iP(hone|od|ad)/], ["Android OS", /Android/], ["BlackBerry OS", /BlackBerry|BB10/], ["Windows Mobile", /IEMobile/], ["Amazon OS", /Kindle/], ["Windows 3.11", /Win16/], ["Windows 95", /(Windows 95)|(Win95)|(Windows_95)/], ["Windows 98", /(Windows 98)|(Win98)/], ["Windows 2000", /(Windows NT 5.0)|(Windows 2000)/], ["Windows XP", /(Windows NT 5.1)|(Windows XP)/], ["Windows Server 2003", /(Windows NT 5.2)/], ["Windows Vista", /(Windows NT 6.0)/], ["Windows 7", /(Windows NT 6.1)/], ["Windows 8", /(Windows NT 6.2)/], ["Windows 8.1", /(Windows NT 6.3)/], ["Windows 10", /(Windows NT 10.0)/], ["Windows ME", /Windows ME/], ["Windows CE", /Windows CE|WinCE|Microsoft Pocket Internet Explorer/], ["Open BSD", /OpenBSD/], ["Sun OS", /SunOS/], ["Chrome OS", /CrOS/], ["Linux", /(Linux)|(X11)/], ["Mac OS", /(Mac_PowerPC)|(Macintosh)/], ["QNX", /QNX/], ["BeOS", /BeOS/], ["OS/2", /OS\/2/] ]; function detect(userAgent) { if (!!userAgent) { return parseUserAgent(userAgent); } if (typeof document === "undefined" && typeof navigator !== "undefined" && navigator.product === "ReactNative") { return new ReactNativeInfo(); } if (typeof navigator !== "undefined") { return parseUserAgent(navigator.userAgent); } return getNodeVersion(); } function matchUserAgent(ua) { return ua !== "" && userAgentRules.reduce(function(matched, _a) { var browser = _a[0], regex = _a[1]; if (matched) { return matched; } var uaMatch = regex.exec(ua); return !!uaMatch && [browser, uaMatch]; }, false); } function parseUserAgent(ua) { var matchedRule = matchUserAgent(ua); if (!matchedRule) { return null; } var name2 = matchedRule[0], match = matchedRule[1]; if (name2 === "searchbot") { return new BotInfo(); } var versionParts = match[1] && match[1].split(".").join("_").split("_").slice(0, 3); if (versionParts) { if (versionParts.length < REQUIRED_VERSION_PARTS) { versionParts = __spreadArray(__spreadArray([], versionParts, true), createVersionParts(REQUIRED_VERSION_PARTS - versionParts.length), true); } } else { versionParts = []; } var version12 = versionParts.join("."); var os = detectOS(ua); var searchBotMatch = SEARCHBOT_OS_REGEX.exec(ua); if (searchBotMatch && searchBotMatch[1]) { return new SearchBotDeviceInfo(name2, version12, os, searchBotMatch[1]); } return new BrowserInfo(name2, version12, os); } function detectOS(ua) { for (var ii2 = 0, count = operatingSystemRules.length; ii2 < count; ii2++) { var _a = operatingSystemRules[ii2], os = _a[0], regex = _a[1]; var match = regex.exec(ua); if (match) { return os; } } return null; } function getNodeVersion() { var isNode2 = typeof process !== "undefined" && process.version; return isNode2 ? new NodeInfo(process.version.slice(1)) : null; } function createVersionParts(count) { var output = []; for (var ii2 = 0; ii2 < count; ii2++) { output.push("0"); } return output; } // node_modules/@walletconnect/utils/dist/index.es.js var import_time2 = __toESM(require_cjs()); var import_window_getters = __toESM(require_cjs2()); var import_window_metadata = __toESM(require_cjs3()); var q = __toESM(require_query_string()); // node_modules/@ethersproject/keccak256/lib.esm/index.js var import_js_sha3 = __toESM(require_sha3()); // node_modules/@ethersproject/logger/lib.esm/_version.js var version = "logger/5.7.0"; // node_modules/@ethersproject/logger/lib.esm/index.js var _permanentCensorErrors = false; var _censorErrors = false; var LogLevels = { debug: 1, "default": 2, info: 2, warning: 3, error: 4, off: 5 }; var _logLevel = LogLevels["default"]; var _globalLogger = null; function _checkNormalize() { try { const missing = []; ["NFD", "NFC", "NFKD", "NFKC"].forEach((form) => { try { if ("test".normalize(form) !== "test") { throw new Error("bad normalize"); } ; } catch (error) { missing.push(form); } }); if (missing.length) { throw new Error("missing " + missing.join(", ")); } if (String.fromCharCode(233).normalize("NFD") !== String.fromCharCode(101, 769)) { throw new Error("broken implementation"); } } catch (error) { return error.message; } return null; } var _normalizeError = _checkNormalize(); var LogLevel; (function(LogLevel2) { LogLevel2["DEBUG"] = "DEBUG"; LogLevel2["INFO"] = "INFO"; LogLevel2["WARNING"] = "WARNING"; LogLevel2["ERROR"] = "ERROR"; LogLevel2["OFF"] = "OFF"; })(LogLevel || (LogLevel = {})); var ErrorCode; (function(ErrorCode2) { ErrorCode2["UNKNOWN_ERROR"] = "UNKNOWN_ERROR"; ErrorCode2["NOT_IMPLEMENTED"] = "NOT_IMPLEMENTED"; ErrorCode2["UNSUPPORTED_OPERATION"] = "UNSUPPORTED_OPERATION"; ErrorCode2["NETWORK_ERROR"] = "NETWORK_ERROR"; ErrorCode2["SERVER_ERROR"] = "SERVER_ERROR"; ErrorCode2["TIMEOUT"] = "TIMEOUT"; ErrorCode2["BUFFER_OVERRUN"] = "BUFFER_OVERRUN"; ErrorCode2["NUMERIC_FAULT"] = "NUMERIC_FAULT"; ErrorCode2["MISSING_NEW"] = "MISSING_NEW"; ErrorCode2["INVALID_ARGUMENT"] = "INVALID_ARGUMENT"; ErrorCode2["MISSING_ARGUMENT"] = "MISSING_ARGUMENT"; ErrorCode2["UNEXPECTED_ARGUMENT"] = "UNEXPECTED_ARGUMENT"; ErrorCode2["CALL_EXCEPTION"] = "CALL_EXCEPTION"; ErrorCode2["INSUFFICIENT_FUNDS"] = "INSUFFICIENT_FUNDS"; ErrorCode2["NONCE_EXPIRED"] = "NONCE_EXPIRED"; ErrorCode2["REPLACEMENT_UNDERPRICED"] = "REPLACEMENT_UNDERPRICED"; ErrorCode2["UNPREDICTABLE_GAS_LIMIT"] = "UNPREDICTABLE_GAS_LIMIT"; ErrorCode2["TRANSACTION_REPLACED"] = "TRANSACTION_REPLACED"; ErrorCode2["ACTION_REJECTED"] = "ACTION_REJECTED"; })(ErrorCode || (ErrorCode = {})); var HEX = "0123456789abcdef"; var Logger = class _Logger { constructor(version12) { Object.defineProperty(this, "version", { enumerable: true, value: version12, writable: false }); } _log(logLevel, args) { const level = logLevel.toLowerCase(); if (LogLevels[level] == null) { this.throwArgumentError("invalid log level name", "logLevel", logLevel); } if (_logLevel > LogLevels[level]) { return; } console.log.apply(console, args); } debug(...args) { this._log(_Logger.levels.DEBUG, args); } info(...args) { this._log(_Logger.levels.INFO, args); } warn(...args) { this._log(_Logger.levels.WARNING, args); } makeError(message, code2, params) { if (_censorErrors) { return this.makeError("censored error", code2, {}); } if (!code2) { code2 = _Logger.errors.UNKNOWN_ERROR; } if (!params) { params = {}; } const messageDetails = []; Object.keys(params).forEach((key2) => { const value = params[key2]; try { if (value instanceof Uint8Array) { let hex = ""; for (let i4 = 0; i4 < value.length; i4++) { hex += HEX[value[i4] >> 4]; hex += HEX[value[i4] & 15]; } messageDetails.push(key2 + "=Uint8Array(0x" + hex + ")"); } else { messageDetails.push(key2 + "=" + JSON.stringify(value)); } } catch (error2) { messageDetails.push(key2 + "=" + JSON.stringify(params[key2].toString())); } }); messageDetails.push(`code=${code2}`); messageDetails.push(`version=${this.version}`); const reason = message; let url = ""; switch (code2) { case ErrorCode.NUMERIC_FAULT: { url = "NUMERIC_FAULT"; const fault = message; switch (fault) { case "overflow": case "underflow": case "division-by-zero": url += "-" + fault; break; case "negative-power": case "negative-width": url += "-unsupported"; break; case "unbound-bitwise-result": url += "-unbound-result"; break; } break; } case ErrorCode.CALL_EXCEPTION: case ErrorCode.INSUFFICIENT_FUNDS: case ErrorCode.MISSING_NEW: case ErrorCode.NONCE_EXPIRED: case ErrorCode.REPLACEMENT_UNDERPRICED: case ErrorCode.TRANSACTION_REPLACED: case ErrorCode.UNPREDICTABLE_GAS_LIMIT: url = code2; break; } if (url) { message += " [ See: https://links.ethers.org/v5-errors-" + url + " ]"; } if (messageDetails.length) { message += " (" + messageDetails.join(", ") + ")"; } const error = new Error(message); error.reason = reason; error.code = code2; Object.keys(params).forEach(function(key2) { error[key2] = params[key2]; }); return error; } throwError(message, code2, params) { throw this.makeError(message, code2, params); } throwArgumentError(message, name2, value) { return this.throwError(message, _Logger.errors.INVALID_ARGUMENT, { argument: name2, value }); } assert(condition, message, code2, params) { if (!!condition) { return; } this.throwError(message, code2, params); } assertArgument(condition, message, name2, value) { if (!!condition) { return; } this.throwArgumentError(message, name2, value); } checkNormalize(message) { if (message == null) { message = "platform missing String.prototype.normalize"; } if (_normalizeError) { this.throwError("platform missing String.prototype.normalize", _Logger.errors.UNSUPPORTED_OPERATION, { operation: "String.prototype.normalize", form: _normalizeError }); } } checkSafeUint53(value, message) { if (typeof value !== "number") { return; } if (message == null) { message = "value not safe"; } if (value < 0 || value >= 9007199254740991) { this.throwError(message, _Logger.errors.NUMERIC_FAULT, { operation: "checkSafeInteger", fault: "out-of-safe-range", value }); } if (value % 1) { this.throwError(message, _Logger.errors.NUMERIC_FAULT, { operation: "checkSafeInteger", fault: "non-integer", value }); } } checkArgumentCount(count, expectedCount, message) { if (message) { message = ": " + message; } else { message = ""; } if (count < expectedCount) { this.throwError("missing argument" + message, _Logger.errors.MISSING_ARGUMENT, { count, expectedCount }); } if (count > expectedCount) { this.throwError("too many arguments" + message, _Logger.errors.UNEXPECTED_ARGUMENT, { count, expectedCount }); } } checkNew(target, kind) { if (target === Object || target == null) { this.throwError("missing new", _Logger.errors.MISSING_NEW, { name: kind.name }); } } checkAbstract(target, kind) { if (target === kind) { this.throwError("cannot instantiate abstract class " + JSON.stringify(kind.name) + " directly; use a sub-class", _Logger.errors.UNSUPPORTED_OPERATION, { name: target.name, operation: "new" }); } else if (target === Object || target == null) { this.throwError("missing new", _Logger.errors.MISSING_NEW, { name: kind.name }); } } static globalLogger() { if (!_globalLogger) { _globalLogger = new _Logger(version); } return _globalLogger; } static setCensorship(censorship, permanent) { if (!censorship && permanent) { this.globalLogger().throwError("cannot permanently disable censorship", _Logger.errors.UNSUPPORTED_OPERATION, { operation: "setCensorship" }); } if (_permanentCensorErrors) { if (!censorship) { return; } this.globalLogger().throwError("error censorship permanent", _Logger.errors.UNSUPPORTED_OPERATION, { operation: "setCensorship" }); } _censorErrors = !!censorship; _permanentCensorErrors = !!permanent; } static setLogLevel(logLevel) { const level = LogLevels[logLevel.toLowerCase()]; if (level == null) { _Logger.globalLogger().warn("invalid log level - " + logLevel); return; } _logLevel = level; } static from(version12) { return new _Logger(version12); } }; Logger.errors = ErrorCode; Logger.levels = LogLevel; // node_modules/@ethersproject/bytes/lib.esm/_version.js var version2 = "bytes/5.7.0"; // node_modules/@ethersproject/bytes/lib.esm/index.js var logger = new Logger(version2); function isHexable(value) { return !!value.toHexString; } function addSlice(array) { if (array.slice) { return array; } array.slice = function() { const args = Array.prototype.slice.call(arguments); return addSlice(new Uint8Array(Array.prototype.slice.apply(array, args))); }; return array; } function isBytesLike(value) { return isHexString(value) && !(value.length % 2) || isBytes(value); } function isInteger(value) { return typeof value === "number" && value == value && value % 1 === 0; } function isBytes(value) { if (value == null) { return false; } if (value.constructor === Uint8Array) { return true; } if (typeof value === "string") { return false; } if (!isInteger(value.length) || value.length < 0) { return false; } for (let i4 = 0; i4 < value.length; i4++) { const v5 = value[i4]; if (!isInteger(v5) || v5 < 0 || v5 >= 256) { return false; } } return true; } function arrayify(value, options) { if (!options) { options = {}; } if (typeof value === "number") { logger.checkSafeUint53(value, "invalid arrayify value"); const result = []; while (value) { result.unshift(value & 255); value = parseInt(String(value / 256)); } if (result.length === 0) { result.push(0); } return addSlice(new Uint8Array(result)); } if (options.allowMissingPrefix && typeof value === "string" && value.substring(0, 2) !== "0x") { value = "0x" + value; } if (isHexable(value)) { value = value.toHexString(); } if (isHexString(value)) { let hex = value.substring(2); if (hex.length % 2) { if (options.hexPad === "left") { hex = "0" + hex; } else if (options.hexPad === "right") { hex += "0"; } else { logger.throwArgumentError("hex data is odd-length", "value", value); } } const result = []; for (let i4 = 0; i4 < hex.length; i4 += 2) { result.push(parseInt(hex.substring(i4, i4 + 2), 16)); } return addSlice(new Uint8Array(result)); } if (isBytes(value)) { return addSlice(new Uint8Array(value)); } return logger.throwArgumentError("invalid arrayify value", "value", value); } function concat(items) { const objects = items.map((item) => arrayify(item)); const length2 = objects.reduce((accum, item) => accum + item.length, 0); const result = new Uint8Array(length2); objects.reduce((offset, object) => { result.set(object, offset); return offset + object.length; }, 0); return addSlice(result); } function zeroPad(value, length2) { value = arrayify(value); if (value.length > length2) { logger.throwArgumentError("value out of range", "value", arguments[0]); } const result = new Uint8Array(length2); result.set(value, length2 - value.length); return addSlice(result); } function isHexString(value, length2) { if (typeof value !== "string" || !value.match(/^0x[0-9A-Fa-f]*$/)) { return false; } if (length2 && value.length !== 2 + 2 * length2) { return false; } return true; } var HexCharacters = "0123456789abcdef"; function hexlify(value, options) { if (!options) { options = {}; } if (typeof value === "number") { logger.checkSafeUint53(value, "invalid hexlify value"); let hex = ""; while (value) { hex = HexCharacters[value & 15] + hex; value = Math.floor(value / 16); } if (hex.length) { if (hex.length % 2) { hex = "0" + hex; } return "0x" + hex; } return "0x00"; } if (typeof value === "bigint") { value = value.toString(16); if (value.length % 2) { return "0x0" + value; } return "0x" + value; } if (options.allowMissingPrefix && typeof value === "string" && value.substring(0, 2) !== "0x") { value = "0x" + value; } if (isHexable(value)) { return value.toHexString(); } if (isHexString(value)) { if (value.length % 2) { if (options.hexPad === "left") { value = "0x0" + value.substring(2); } else if (options.hexPad === "right") { value += "0"; } else { logger.throwArgumentError("hex data is odd-length", "value", value); } } return value.toLowerCase(); } if (isBytes(value)) { let result = "0x"; for (let i4 = 0; i4 < value.length; i4++) { let v5 = value[i4]; result += HexCharacters[(v5 & 240) >> 4] + HexCharacters[v5 & 15]; } return result; } return logger.throwArgumentError("invalid hexlify value", "value", value); } function hexDataLength(data) { if (typeof data !== "string") { data = hexlify(data); } else if (!isHexString(data) || data.length % 2) { return null; } return (data.length - 2) / 2; } function hexDataSlice(data, offset, endOffset) { if (typeof data !== "string") { data = hexlify(data); } else if (!isHexString(data) || data.length % 2) { logger.throwArgumentError("invalid hexData", "value", data); } offset = 2 + 2 * offset; if (endOffset != null) { return "0x" + data.substring(offset, 2 + 2 * endOffset); } return "0x" + data.substring(offset); } function hexZeroPad(value, length2) { if (typeof value !== "string") { value = hexlify(value); } else if (!isHexString(value)) { logger.throwArgumentError("invalid hex string", "value", value); } if (value.length > 2 * length2 + 2) { logger.throwArgumentError("value out of range", "value", arguments[1]); } while (value.length < 2 * length2 + 2) { value = "0x0" + value.substring(2); } return value; } function splitSignature(signature2) { const result = { r: "0x", s: "0x", _vs: "0x", recoveryParam: 0, v: 0, yParityAndS: "0x", compact: "0x" }; if (isBytesLike(signature2)) { let bytes = arrayify(signature2); if (bytes.length === 64) { result.v = 27 + (bytes[32] >> 7); bytes[32] &= 127; result.r = hexlify(bytes.slice(0, 32)); result.s = hexlify(bytes.slice(32, 64)); } else if (bytes.length === 65) { result.r = hexlify(bytes.slice(0, 32)); result.s = hexlify(bytes.slice(32, 64)); result.v = bytes[64]; } else { logger.throwArgumentError("invalid signature string", "signature", signature2); } if (result.v < 27) { if (result.v === 0 || result.v === 1) { result.v += 27; } else { logger.throwArgumentError("signature invalid v byte", "signature", signature2); } } result.recoveryParam = 1 - result.v % 2; if (result.recoveryParam) { bytes[32] |= 128; } result._vs = hexlify(bytes.slice(32, 64)); } else { result.r = signature2.r; result.s = signature2.s; result.v = signature2.v; result.recoveryParam = signature2.recoveryParam; result._vs = signature2._vs; if (result._vs != null) { const vs4 = zeroPad(arrayify(result._vs), 32); result._vs = hexlify(vs4); const recoveryParam = vs4[0] >= 128 ? 1 : 0; if (result.recoveryParam == null) { result.recoveryParam = recoveryParam; } else if (result.recoveryParam !== recoveryParam) { logger.throwArgumentError("signature recoveryParam mismatch _vs", "signature", signature2); } vs4[0] &= 127; const s3 = hexlify(vs4); if (result.s == null) { result.s = s3; } else if (result.s !== s3) { logger.throwArgumentError("signature v mismatch _vs", "signature", signature2); } } if (result.recoveryParam == null) { if (result.v == null) { logger.throwArgumentError("signature missing v and recoveryParam", "signature", signature2); } else if (result.v === 0 || result.v === 1) { result.recoveryParam = result.v; } else { result.recoveryParam = 1 - result.v % 2; } } else { if (result.v == null) { result.v = 27 + result.recoveryParam; } else { const recId = result.v === 0 || result.v === 1 ? result.v : 1 - result.v % 2; if (result.recoveryParam !== recId) { logger.throwArgumentError("signature recoveryParam mismatch v", "signature", signature2); } } } if (result.r == null || !isHexString(result.r)) { logger.throwArgumentError("signature missing or invalid r", "signature", signature2); } else { result.r = hexZeroPad(result.r, 32); } if (result.s == null || !isHexString(result.s)) { logger.throwArgumentError("signature missing or invalid s", "signature", signature2); } else { result.s = hexZeroPad(result.s, 32); } const vs3 = arrayify(result.s); if (vs3[0] >= 128) { logger.throwArgumentError("signature s out of range", "signature", signature2); } if (result.recoveryParam) { vs3[0] |= 128; } const _vs = hexlify(vs3); if (result._vs) { if (!isHexString(result._vs)) { logger.throwArgumentError("signature invalid _vs", "signature", signature2); } result._vs = hexZeroPad(result._vs, 32); } if (result._vs == null) { result._vs = _vs; } else if (result._vs !== _vs) { logger.throwArgumentError("signature _vs mismatch v and s", "signature", signature2); } } result.yParityAndS = result._vs; result.compact = result.r + result.yParityAndS.substring(2); return result; } // node_modules/@ethersproject/keccak256/lib.esm/index.js function keccak256(data) { return "0x" + import_js_sha3.default.keccak_256(arrayify(data)); } // node_modules/@ethersproject/bignumber/lib.esm/bignumber.js var import_bn = __toESM(require_bn()); // node_modules/@ethersproject/bignumber/lib.esm/_version.js var version3 = "bignumber/5.7.0"; // node_modules/@ethersproject/bignumber/lib.esm/bignumber.js var BN = import_bn.default.BN; var logger2 = new Logger(version3); var _constructorGuard = {}; var MAX_SAFE = 9007199254740991; function isBigNumberish(value) { return value != null && (BigNumber.isBigNumber(value) || typeof value === "number" && value % 1 === 0 || typeof value === "string" && !!value.match(/^-?[0-9]+$/) || isHexString(value) || typeof value === "bigint" || isBytes(value)); } var _warnedToStringRadix = false; var BigNumber = class _BigNumber { constructor(constructorGuard, hex) { if (constructorGuard !== _constructorGuard) { logger2.throwError("cannot call constructor directly; use BigNumber.from", Logger.errors.UNSUPPORTED_OPERATION, { operation: "new (BigNumber)" }); } this._hex = hex; this._isBigNumber = true; Object.freeze(this); } fromTwos(value) { return toBigNumber(toBN(this).fromTwos(value)); } toTwos(value) { return toBigNumber(toBN(this).toTwos(value)); } abs() { if (this._hex[0] === "-") { return _BigNumber.from(this._hex.substring(1)); } return this; } add(other) { return toBigNumber(toBN(this).add(toBN(other))); } sub(other) { return toBigNumber(toBN(this).sub(toBN(other))); } div(other) { const o4 = _BigNumber.from(other); if (o4.isZero()) { throwFault("division-by-zero", "div"); } return toBigNumber(toBN(this).div(toBN(other))); } mul(other) { return toBigNumber(toBN(this).mul(toBN(other))); } mod(other) { const value = toBN(other); if (value.isNeg()) { throwFault("division-by-zero", "mod"); } return toBigNumber(toBN(this).umod(value)); } pow(other) { const value = toBN(other); if (value.isNeg()) { throwFault("negative-power", "pow"); } return toBigNumber(toBN(this).pow(value)); } and(other) { const value = toBN(other); if (this.isNegative() || value.isNeg()) { throwFault("unbound-bitwise-result", "and"); } return toBigNumber(toBN(this).and(value)); } or(other) { const value = toBN(other); if (this.isNegative() || value.isNeg()) { throwFault("unbound-bitwise-result", "or"); } return toBigNumber(toBN(this).or(value)); } xor(other) { const value = toBN(other); if (this.isNegative() || value.isNeg()) { throwFault("unbound-bitwise-result", "xor"); } return toBigNumber(toBN(this).xor(value)); } mask(value) { if (this.isNegative() || value < 0) { throwFault("negative-width", "mask"); } return toBigNumber(toBN(this).maskn(value)); } shl(value) { if (this.isNegative() || value < 0) { throwFault("negative-width", "shl"); } return toBigNumber(toBN(this).shln(value)); } shr(value) { if (this.isNegative() || value < 0) { throwFault("negative-width", "shr"); } return toBigNumber(toBN(this).shrn(value)); } eq(other) { return toBN(this).eq(toBN(other)); } lt(other) { return toBN(this).lt(toBN(other)); } lte(other) { return toBN(this).lte(toBN(other)); } gt(other) { return toBN(this).gt(toBN(other)); } gte(other) { return toBN(this).gte(toBN(other)); } isNegative() { return this._hex[0] === "-"; } isZero() { return toBN(this).isZero(); } toNumber() { try { return toBN(this).toNumber(); } catch (error) { throwFault("overflow", "toNumber", this.toString()); } return null; } toBigInt() { try { return BigInt(this.toString()); } catch (e2) { } return logger2.throwError("this platform does not support BigInt", Logger.errors.UNSUPPORTED_OPERATION, { value: this.toString() }); } toString() { if (arguments.length > 0) { if (arguments[0] === 10) { if (!_warnedToStringRadix) { _warnedToStringRadix = true; logger2.warn("BigNumber.toString does not accept any parameters; base-10 is assumed"); } } else if (arguments[0] === 16) { logger2.throwError("BigNumber.toString does not accept any parameters; use bigNumber.toHexString()", Logger.errors.UNEXPECTED_ARGUMENT, {}); } else { logger2.throwError("BigNumber.toString does not accept parameters", Logger.errors.UNEXPECTED_ARGUMENT, {}); } } return toBN(this).toString(10); } toHexString() { return this._hex; } toJSON(key2) { return { type: "BigNumber", hex: this.toHexString() }; } static from(value) { if (value instanceof _BigNumber) { return value; } if (typeof value === "string") { if (value.match(/^-?0x[0-9a-f]+$/i)) { return new _BigNumber(_constructorGuard, toHex(value)); } if (value.match(/^-?[0-9]+$/)) { return new _BigNumber(_constructorGuard, toHex(new BN(value))); } return logger2.throwArgumentError("invalid BigNumber string", "value", value); } if (typeof value === "number") { if (value % 1) { throwFault("underflow", "BigNumber.from", value); } if (value >= MAX_SAFE || value <= -MAX_SAFE) { throwFault("overflow", "BigNumber.from", value); } return _BigNumber.from(String(value)); } const anyValue = value; if (typeof anyValue === "bigint") { return _BigNumber.from(anyValue.toString()); } if (isBytes(anyValue)) { return _BigNumber.from(hexlify(anyValue)); } if (anyValue) { if (anyValue.toHexString) { const hex = anyValue.toHexString(); if (typeof hex === "string") { return _BigNumber.from(hex); } } else { let hex = anyValue._hex; if (hex == null && anyValue.type === "BigNumber") { hex = anyValue.hex; } if (typeof hex === "string") { if (isHexString(hex) || hex[0] === "-" && isHexString(hex.substring(1))) { return _BigNumber.from(hex); } } } } return logger2.throwArgumentError("invalid BigNumber value", "value", value); } static isBigNumber(value) { return !!(value && value._isBigNumber); } }; function toHex(value) { if (typeof value !== "string") { return toHex(value.toString(16)); } if (value[0] === "-") { value = value.substring(1); if (value[0] === "-") { logger2.throwArgumentError("invalid hex", "value", value); } value = toHex(value); if (value === "0x00") { return value; } return "-" + value; } if (value.substring(0, 2) !== "0x") { value = "0x" + value; } if (value === "0x") { return "0x00"; } if (value.length % 2) { value = "0x0" + value.substring(2); } while (value.length > 4 && value.substring(0, 4) === "0x00") { value = "0x" + value.substring(4); } return value; } function toBigNumber(value) { return BigNumber.from(toHex(value)); } function toBN(value) { const hex = BigNumber.from(value).toHexString(); if (hex[0] === "-") { return new BN("-" + hex.substring(3), 16); } return new BN(hex.substring(2), 16); } function throwFault(fault, operation, value) { const params = { fault, operation }; if (value != null) { params.value = value; } return logger2.throwError(fault, Logger.errors.NUMERIC_FAULT, params); } function _base36To16(value) { return new BN(value, 36).toString(16); } // node_modules/@ethersproject/bignumber/lib.esm/fixednumber.js var logger3 = new Logger(version3); var _constructorGuard2 = {}; var Zero = BigNumber.from(0); var NegativeOne = BigNumber.from(-1); function throwFault2(message, fault, operation, value) { const params = { fault, operation }; if (value !== void 0) { params.value = value; } return logger3.throwError(message, Logger.errors.NUMERIC_FAULT, params); } var zeros = "0"; while (zeros.length < 256) { zeros += zeros; } function getMultiplier(decimals) { if (typeof decimals !== "number") { try { decimals = BigNumber.from(decimals).toNumber(); } catch (e2) { } } if (typeof decimals === "number" && decimals >= 0 && decimals <= 256 && !(decimals % 1)) { return "1" + zeros.substring(0, decimals); } return logger3.throwArgumentError("invalid decimal size", "decimals", decimals); } function formatFixed(value, decimals) { if (decimals == null) { decimals = 0; } const multiplier = getMultiplier(decimals); value = BigNumber.from(value); const negative = value.lt(Zero); if (negative) { value = value.mul(NegativeOne); } let fraction = value.mod(multiplier).toString(); while (fraction.length < multiplier.length - 1) { fraction = "0" + fraction; } fraction = fraction.match(/^([0-9]*[1-9]|0)(0*)/)[1]; const whole = value.div(multiplier).toString(); if (multiplier.length === 1) { value = whole; } else { value = whole + "." + fraction; } if (negative) { value = "-" + value; } return value; } function parseFixed(value, decimals) { if (decimals == null) { decimals = 0; } const multiplier = getMultiplier(decimals); if (typeof value !== "string" || !value.match(/^-?[0-9.]+$/)) { logger3.throwArgumentError("invalid decimal value", "value", value); } const negative = value.substring(0, 1) === "-"; if (negative) { value = value.substring(1); } if (value === ".") { logger3.throwArgumentError("missing value", "value", value); } const comps = value.split("."); if (comps.length > 2) { logger3.throwArgumentError("too many decimal points", "value", value); } let whole = comps[0], fraction = comps[1]; if (!whole) { whole = "0"; } if (!fraction) { fraction = "0"; } while (fraction[fraction.length - 1] === "0") { fraction = fraction.substring(0, fraction.length - 1); } if (fraction.length > multiplier.length - 1) { throwFault2("fractional component exceeds decimals", "underflow", "parseFixed"); } if (fraction === "") { fraction = "0"; } while (fraction.length < multiplier.length - 1) { fraction += "0"; } const wholeValue = BigNumber.from(whole); const fractionValue = BigNumber.from(fraction); let wei = wholeValue.mul(multiplier).add(fractionValue); if (negative) { wei = wei.mul(NegativeOne); } return wei; } var FixedFormat = class _FixedFormat { constructor(constructorGuard, signed2, width, decimals) { if (constructorGuard !== _constructorGuard2) { logger3.throwError("cannot use FixedFormat constructor; use FixedFormat.from", Logger.errors.UNSUPPORTED_OPERATION, { operation: "new FixedFormat" }); } this.signed = signed2; this.width = width; this.decimals = decimals; this.name = (signed2 ? "" : "u") + "fixed" + String(width) + "x" + String(decimals); this._multiplier = getMultiplier(decimals); Object.freeze(this); } static from(value) { if (value instanceof _FixedFormat) { return value; } if (typeof value === "number") { value = `fixed128x${value}`; } let signed2 = true; let width = 128; let decimals = 18; if (typeof value === "string") { if (value === "fixed") { } else if (value === "ufixed") { signed2 = false; } else { const match = value.match(/^(u?)fixed([0-9]+)x([0-9]+)$/); if (!match) { logger3.throwArgumentError("invalid fixed format", "format", value); } signed2 = match[1] !== "u"; width = parseInt(match[2]); decimals = parseInt(match[3]); } } else if (value) { const check = (key2, type, defaultValue) => { if (value[key2] == null) { return defaultValue; } if (typeof value[key2] !== type) { logger3.throwArgumentError("invalid fixed format (" + key2 + " not " + type + ")", "format." + key2, value[key2]); } return value[key2]; }; signed2 = check("signed", "boolean", signed2); width = check("width", "number", width); decimals = check("decimals", "number", decimals); } if (width % 8) { logger3.throwArgumentError("invalid fixed format width (not byte aligned)", "format.width", width); } if (decimals > 80) { logger3.throwArgumentError("invalid fixed format (decimals too large)", "format.decimals", decimals); } return new _FixedFormat(_constructorGuard2, signed2, width, decimals); } }; var FixedNumber = class _FixedNumber { constructor(constructorGuard, hex, value, format) { if (constructorGuard !== _constructorGuard2) { logger3.throwError("cannot use FixedNumber constructor; use FixedNumber.from", Logger.errors.UNSUPPORTED_OPERATION, { operation: "new FixedFormat" }); } this.format = format; this._hex = hex; this._value = value; this._isFixedNumber = true; Object.freeze(this); } _checkFormat(other) { if (this.format.name !== other.format.name) { logger3.throwArgumentError("incompatible format; use fixedNumber.toFormat", "other", other); } } addUnsafe(other) { this._checkFormat(other); const a4 = parseFixed(this._value, this.format.decimals); const b5 = parseFixed(other._value, other.format.decimals); return _FixedNumber.fromValue(a4.add(b5), this.format.decimals, this.format); } subUnsafe(other) { this._checkFormat(other); const a4 = parseFixed(this._value, this.format.decimals); const b5 = parseFixed(other._value, other.format.decimals); return _FixedNumber.fromValue(a4.sub(b5), this.format.decimals, this.format); } mulUnsafe(other) { this._checkFormat(other); const a4 = parseFixed(this._value, this.format.decimals); const b5 = parseFixed(other._value, other.format.decimals); return _FixedNumber.fromValue(a4.mul(b5).div(this.format._multiplier), this.format.decimals, this.format); } divUnsafe(other) { this._checkFormat(other); const a4 = parseFixed(this._value, this.format.decimals); const b5 = parseFixed(other._value, other.format.decimals); return _FixedNumber.fromValue(a4.mul(this.format._multiplier).div(b5), this.format.decimals, this.format); } floor() { const comps = this.toString().split("."); if (comps.length === 1) { comps.push("0"); } let result = _FixedNumber.from(comps[0], this.format); const hasFraction = !comps[1].match(/^(0*)$/); if (this.isNegative() && hasFraction) { result = result.subUnsafe(ONE.toFormat(result.format)); } return result; } ceiling() { const comps = this.toString().split("."); if (comps.length === 1) { comps.push("0"); } let result = _FixedNumber.from(comps[0], this.format); const hasFraction = !comps[1].match(/^(0*)$/); if (!this.isNegative() && hasFraction) { result = result.addUnsafe(ONE.toFormat(result.format)); } return result; } // @TODO: Support other rounding algorithms round(decimals) { if (decimals == null) { decimals = 0; } const comps = this.toString().split("."); if (comps.length === 1) { comps.push("0"); } if (decimals < 0 || decimals > 80 || decimals % 1) { logger3.throwArgumentError("invalid decimal count", "decimals", decimals); } if (comps[1].length <= decimals) { return this; } const factor = _FixedNumber.from("1" + zeros.substring(0, decimals), this.format); const bump = BUMP.toFormat(this.format); return this.mulUnsafe(factor).addUnsafe(bump).floor().divUnsafe(factor); } isZero() { return this._value === "0.0" || this._value === "0"; } isNegative() { return this._value[0] === "-"; } toString() { return this._value; } toHexString(width) { if (width == null) { return this._hex; } if (width % 8) { logger3.throwArgumentError("invalid byte width", "width", width); } const hex = BigNumber.from(this._hex).fromTwos(this.format.width).toTwos(width).toHexString(); return hexZeroPad(hex, width / 8); } toUnsafeFloat() { return parseFloat(this.toString()); } toFormat(format) { return _FixedNumber.fromString(this._value, format); } static fromValue(value, decimals, format) { if (format == null && decimals != null && !isBigNumberish(decimals)) { format = decimals; decimals = null; } if (decimals == null) { decimals = 0; } if (format == null) { format = "fixed"; } return _FixedNumber.fromString(formatFixed(value, decimals), FixedFormat.from(format)); } static fromString(value, format) { if (format == null) { format = "fixed"; } const fixedFormat = FixedFormat.from(format); const numeric = parseFixed(value, fixedFormat.decimals); if (!fixedFormat.signed && numeric.lt(Zero)) { throwFault2("unsigned value cannot be negative", "overflow", "value", value); } let hex = null; if (fixedFormat.signed) { hex = numeric.toTwos(fixedFormat.width).toHexString(); } else { hex = numeric.toHexString(); hex = hexZeroPad(hex, fixedFormat.width / 8); } const decimal = formatFixed(numeric, fixedFormat.decimals); return new _FixedNumber(_constructorGuard2, hex, decimal, fixedFormat); } static fromBytes(value, format) { if (format == null) { format = "fixed"; } const fixedFormat = FixedFormat.from(format); if (arrayify(value).length > fixedFormat.width / 8) { throw new Error("overflow"); } let numeric = BigNumber.from(value); if (fixedFormat.signed) { numeric = numeric.fromTwos(fixedFormat.width); } const hex = numeric.toTwos((fixedFormat.signed ? 0 : 1) + fixedFormat.width).toHexString(); const decimal = formatFixed(numeric, fixedFormat.decimals); return new _FixedNumber(_constructorGuard2, hex, decimal, fixedFormat); } static from(value, format) { if (typeof value === "string") { return _FixedNumber.fromString(value, format); } if (isBytes(value)) { return _FixedNumber.fromBytes(value, format); } try { return _FixedNumber.fromValue(value, 0, format); } catch (error) { if (error.code !== Logger.errors.INVALID_ARGUMENT) { throw error; } } return logger3.throwArgumentError("invalid FixedNumber value", "value", value); } static isFixedNumber(value) { return !!(value && value._isFixedNumber); } }; var ONE = FixedNumber.from(1); var BUMP = FixedNumber.from("0.5"); // node_modules/@ethersproject/constants/lib.esm/bignumbers.js var NegativeOne2 = BigNumber.from(-1); var Zero2 = BigNumber.from(0); var One = BigNumber.from(1); var Two = BigNumber.from(2); var WeiPerEther = BigNumber.from("1000000000000000000"); var MaxUint256 = BigNumber.from("0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"); var MinInt256 = BigNumber.from("-0x8000000000000000000000000000000000000000000000000000000000000000"); var MaxInt256 = BigNumber.from("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"); // node_modules/@ethersproject/strings/lib.esm/_version.js var version4 = "strings/5.7.0"; // node_modules/@ethersproject/strings/lib.esm/utf8.js var logger4 = new Logger(version4); var UnicodeNormalizationForm; (function(UnicodeNormalizationForm2) { UnicodeNormalizationForm2["current"] = ""; UnicodeNormalizationForm2["NFC"] = "NFC"; UnicodeNormalizationForm2["NFD"] = "NFD"; UnicodeNormalizationForm2["NFKC"] = "NFKC"; UnicodeNormalizationForm2["NFKD"] = "NFKD"; })(UnicodeNormalizationForm || (UnicodeNormalizationForm = {})); var Utf8ErrorReason; (function(Utf8ErrorReason2) { Utf8ErrorReason2["UNEXPECTED_CONTINUE"] = "unexpected continuation byte"; Utf8ErrorReason2["BAD_PREFIX"] = "bad codepoint prefix"; Utf8ErrorReason2["OVERRUN"] = "string overrun"; Utf8ErrorReason2["MISSING_CONTINUE"] = "missing continuation byte"; Utf8ErrorReason2["OUT_OF_RANGE"] = "out of UTF-8 range"; Utf8ErrorReason2["UTF16_SURROGATE"] = "UTF-16 surrogate"; Utf8ErrorReason2["OVERLONG"] = "overlong representation"; })(Utf8ErrorReason || (Utf8ErrorReason = {})); function errorFunc(reason, offset, bytes, output, badCodepoint) { return logger4.throwArgumentError(`invalid codepoint at offset ${offset}; ${reason}`, "bytes", bytes); } function ignoreFunc(reason, offset, bytes, output, badCodepoint) { if (reason === Utf8ErrorReason.BAD_PREFIX || reason === Utf8ErrorReason.UNEXPECTED_CONTINUE) { let i4 = 0; for (let o4 = offset + 1; o4 < bytes.length; o4++) { if (bytes[o4] >> 6 !== 2) { break; } i4++; } return i4; } if (reason === Utf8ErrorReason.OVERRUN) { return bytes.length - offset - 1; } return 0; } function replaceFunc(reason, offset, bytes, output, badCodepoint) { if (reason === Utf8ErrorReason.OVERLONG) { output.push(badCodepoint); return 0; } output.push(65533); return ignoreFunc(reason, offset, bytes, output, badCodepoint); } var Utf8ErrorFuncs = Object.freeze({ error: errorFunc, ignore: ignoreFunc, replace: replaceFunc }); function toUtf8Bytes(str, form = UnicodeNormalizationForm.current) { if (form != UnicodeNormalizationForm.current) { logger4.checkNormalize(); str = str.normalize(form); } let result = []; for (let i4 = 0; i4 < str.length; i4++) { const c5 = str.charCodeAt(i4); if (c5 < 128) { result.push(c5); } else if (c5 < 2048) { result.push(c5 >> 6 | 192); result.push(c5 & 63 | 128); } else if ((c5 & 64512) == 55296) { i4++; const c22 = str.charCodeAt(i4); if (i4 >= str.length || (c22 & 64512) !== 56320) { throw new Error("invalid utf-8 string"); } const pair = 65536 + ((c5 & 1023) << 10) + (c22 & 1023); result.push(pair >> 18 | 240); result.push(pair >> 12 & 63 | 128); result.push(pair >> 6 & 63 | 128); result.push(pair & 63 | 128); } else { result.push(c5 >> 12 | 224); result.push(c5 >> 6 & 63 | 128); result.push(c5 & 63 | 128); } } return arrayify(result); } // node_modules/@ethersproject/strings/lib.esm/idna.js function bytes2(data) { if (data.length % 4 !== 0) { throw new Error("bad data"); } let result = []; for (let i4 = 0; i4 < data.length; i4 += 4) { result.push(parseInt(data.substring(i4, i4 + 4), 16)); } return result; } function createTable(data, func) { if (!func) { func = function(value) { return [parseInt(value, 16)]; }; } let lo2 = 0; let result = {}; data.split(",").forEach((pair) => { let comps = pair.split(":"); lo2 += parseInt(comps[0], 16); result[lo2] = func(comps[1]); }); return result; } function createRangeTable(data) { let hi2 = 0; return data.split(",").map((v5) => { let comps = v5.split("-"); if (comps.length === 1) { comps[1] = "0"; } else if (comps[1] === "") { comps[1] = "1"; } let lo2 = hi2 + parseInt(comps[0], 16); hi2 = parseInt(comps[1], 16); return { l: lo2, h: hi2 }; }); } var Table_A_1_ranges = createRangeTable("221,13-1b,5f-,40-10,51-f,11-3,3-3,2-2,2-4,8,2,15,2d,28-8,88,48,27-,3-5,11-20,27-,8,28,3-5,12,18,b-a,1c-4,6-16,2-d,2-2,2,1b-4,17-9,8f-,10,f,1f-2,1c-34,33-14e,4,36-,13-,6-2,1a-f,4,9-,3-,17,8,2-2,5-,2,8-,3-,4-8,2-3,3,6-,16-6,2-,7-3,3-,17,8,3,3,3-,2,6-3,3-,4-a,5,2-6,10-b,4,8,2,4,17,8,3,6-,b,4,4-,2-e,2-4,b-10,4,9-,3-,17,8,3-,5-,9-2,3-,4-7,3-3,3,4-3,c-10,3,7-2,4,5-2,3,2,3-2,3-2,4-2,9,4-3,6-2,4,5-8,2-e,d-d,4,9,4,18,b,6-3,8,4,5-6,3-8,3-3,b-11,3,9,4,18,b,6-3,8,4,5-6,3-6,2,3-3,b-11,3,9,4,18,11-3,7-,4,5-8,2-7,3-3,b-11,3,13-2,19,a,2-,8-2,2-3,7,2,9-11,4-b,3b-3,1e-24,3,2-,3,2-,2-5,5,8,4,2,2-,3,e,4-,6,2,7-,b-,3-21,49,23-5,1c-3,9,25,10-,2-2f,23,6,3,8-2,5-5,1b-45,27-9,2a-,2-3,5b-4,45-4,53-5,8,40,2,5-,8,2,5-,28,2,5-,20,2,5-,8,2,5-,8,8,18,20,2,5-,8,28,14-5,1d-22,56-b,277-8,1e-2,52-e,e,8-a,18-8,15-b,e,4,3-b,5e-2,b-15,10,b-5,59-7,2b-555,9d-3,5b-5,17-,7-,27-,7-,9,2,2,2,20-,36,10,f-,7,14-,4,a,54-3,2-6,6-5,9-,1c-10,13-1d,1c-14,3c-,10-6,32-b,240-30,28-18,c-14,a0,115-,3,66-,b-76,5,5-,1d,24,2,5-2,2,8-,35-2,19,f-10,1d-3,311-37f,1b,5a-b,d7-19,d-3,41,57-,68-4,29-3,5f,29-37,2e-2,25-c,2c-2,4e-3,30,78-3,64-,20,19b7-49,51a7-59,48e-2,38-738,2ba5-5b,222f-,3c-94,8-b,6-4,1b,6,2,3,3,6d-20,16e-f,41-,37-7,2e-2,11-f,5-b,18-,b,14,5-3,6,88-,2,bf-2,7-,7-,7-,4-2,8,8-9,8-2ff,20,5-b,1c-b4,27-,27-cbb1,f7-9,28-2,b5-221,56,48,3-,2-,3-,5,d,2,5,3,42,5-,9,8,1d,5,6,2-2,8,153-3,123-3,33-27fd,a6da-5128,21f-5df,3-fffd,3-fffd,3-fffd,3-fffd,3-fffd,3-fffd,3-fffd,3-fffd,3-fffd,3-fffd,3-fffd,3,2-1d,61-ff7d"); var Table_B_1_flags = "ad,34f,1806,180b,180c,180d,200b,200c,200d,2060,feff".split(",").map((v5) => parseInt(v5, 16)); var Table_B_2_lut_abs = createTable("b5:3bc,c3:ff,7:73,2:253,5:254,3:256,1:257,5:259,1:25b,3:260,1:263,2:269,1:268,5:26f,1:272,2:275,7:280,3:283,5:288,3:28a,1:28b,5:292,3f:195,1:1bf,29:19e,125:3b9,8b:3b2,1:3b8,1:3c5,3:3c6,1:3c0,1a:3ba,1:3c1,1:3c3,2:3b8,1:3b5,1bc9:3b9,1c:1f76,1:1f77,f:1f7a,1:1f7b,d:1f78,1:1f79,1:1f7c,1:1f7d,107:63,5:25b,4:68,1:68,1:68,3:69,1:69,1:6c,3:6e,4:70,1:71,1:72,1:72,1:72,7:7a,2:3c9,2:7a,2:6b,1:e5,1:62,1:63,3:65,1:66,2:6d,b:3b3,1:3c0,6:64,1b574:3b8,1a:3c3,20:3b8,1a:3c3,20:3b8,1a:3c3,20:3b8,1a:3c3,20:3b8,1a:3c3"); var Table_B_2_lut_rel = createTable("179:1,2:1,2:1,5:1,2:1,a:4f,a:1,8:1,2:1,2:1,3:1,5:1,3:1,4:1,2:1,3:1,4:1,8:2,1:1,2:2,1:1,2:2,27:2,195:26,2:25,1:25,1:25,2:40,2:3f,1:3f,33:1,11:-6,1:-9,1ac7:-3a,6d:-8,1:-8,1:-8,1:-8,1:-8,1:-8,1:-8,1:-8,9:-8,1:-8,1:-8,1:-8,1:-8,1:-8,b:-8,1:-8,1:-8,1:-8,1:-8,1:-8,1:-8,1:-8,9:-8,1:-8,1:-8,1:-8,1:-8,1:-8,1:-8,1:-8,9:-8,1:-8,1:-8,1:-8,1:-8,1:-8,c:-8,2:-8,2:-8,2:-8,9:-8,1:-8,1:-8,1:-8,1:-8,1:-8,1:-8,1:-8,49:-8,1:-8,1:-4a,1:-4a,d:-56,1:-56,1:-56,1:-56,d:-8,1:-8,f:-8,1:-8,3:-7"); var Table_B_2_complex = createTable("df:00730073,51:00690307,19:02BC006E,a7:006A030C,18a:002003B9,16:03B903080301,20:03C503080301,1d7:05650582,190f:00680331,1:00740308,1:0077030A,1:0079030A,1:006102BE,b6:03C50313,2:03C503130300,2:03C503130301,2:03C503130342,2a:1F0003B9,1:1F0103B9,1:1F0203B9,1:1F0303B9,1:1F0403B9,1:1F0503B9,1:1F0603B9,1:1F0703B9,1:1F0003B9,1:1F0103B9,1:1F0203B9,1:1F0303B9,1:1F0403B9,1:1F0503B9,1:1F0603B9,1:1F0703B9,1:1F2003B9,1:1F2103B9,1:1F2203B9,1:1F2303B9,1:1F2403B9,1:1F2503B9,1:1F2603B9,1:1F2703B9,1:1F2003B9,1:1F2103B9,1:1F2203B9,1:1F2303B9,1:1F2403B9,1:1F2503B9,1:1F2603B9,1:1F2703B9,1:1F6003B9,1:1F6103B9,1:1F6203B9,1:1F6303B9,1:1F6403B9,1:1F6503B9,1:1F6603B9,1:1F6703B9,1:1F6003B9,1:1F6103B9,1:1F6203B9,1:1F6303B9,1:1F6403B9,1:1F6503B9,1:1F6603B9,1:1F6703B9,3:1F7003B9,1:03B103B9,1:03AC03B9,2:03B10342,1:03B1034203B9,5:03B103B9,6:1F7403B9,1:03B703B9,1:03AE03B9,2:03B70342,1:03B7034203B9,5:03B703B9,6:03B903080300,1:03B903080301,3:03B90342,1:03B903080342,b:03C503080300,1:03C503080301,1:03C10313,2:03C50342,1:03C503080342,b:1F7C03B9,1:03C903B9,1:03CE03B9,2:03C90342,1:03C9034203B9,5:03C903B9,ac:00720073,5b:00B00063,6:00B00066,d:006E006F,a:0073006D,1:00740065006C,1:0074006D,124f:006800700061,2:00610075,2:006F0076,b:00700061,1:006E0061,1:03BC0061,1:006D0061,1:006B0061,1:006B0062,1:006D0062,1:00670062,3:00700066,1:006E0066,1:03BC0066,4:0068007A,1:006B0068007A,1:006D0068007A,1:00670068007A,1:00740068007A,15:00700061,1:006B00700061,1:006D00700061,1:006700700061,8:00700076,1:006E0076,1:03BC0076,1:006D0076,1:006B0076,1:006D0076,1:00700077,1:006E0077,1:03BC0077,1:006D0077,1:006B0077,1:006D0077,1:006B03C9,1:006D03C9,2:00620071,3:00632215006B0067,1:0063006F002E,1:00640062,1:00670079,2:00680070,2:006B006B,1:006B006D,9:00700068,2:00700070006D,1:00700072,2:00730076,1:00770062,c723:00660066,1:00660069,1:0066006C,1:006600660069,1:00660066006C,1:00730074,1:00730074,d:05740576,1:05740565,1:0574056B,1:057E0576,1:0574056D", bytes2); var Table_C_ranges = createRangeTable("80-20,2a0-,39c,32,f71,18e,7f2-f,19-7,30-4,7-5,f81-b,5,a800-20ff,4d1-1f,110,fa-6,d174-7,2e84-,ffff-,ffff-,ffff-,ffff-,ffff-,ffff-,ffff-,ffff-,ffff-,ffff-,ffff-,ffff-,2,1f-5f,ff7f-20001"); // node_modules/@ethersproject/hash/lib.esm/_version.js var version5 = "hash/5.7.0"; // node_modules/@ethersproject/base64/lib.esm/base64.js function decode(textData) { textData = atob(textData); const data = []; for (let i4 = 0; i4 < textData.length; i4++) { data.push(textData.charCodeAt(i4)); } return arrayify(data); } // node_modules/@ethersproject/hash/lib.esm/ens-normalize/decoder.js function flat(array, depth) { if (depth == null) { depth = 1; } const result = []; const forEach = result.forEach; const flatDeep = function(arr, depth2) { forEach.call(arr, function(val) { if (depth2 > 0 && Array.isArray(val)) { flatDeep(val, depth2 - 1); } else { result.push(val); } }); }; flatDeep(array, depth); return result; } function fromEntries(array) { const result = {}; for (let i4 = 0; i4 < array.length; i4++) { const value = array[i4]; result[value[0]] = value[1]; } return result; } function decode_arithmetic(bytes) { let pos = 0; function u16() { return bytes[pos++] << 8 | bytes[pos++]; } let symbol_count = u16(); let total = 1; let acc = [0, 1]; for (let i4 = 1; i4 < symbol_count; i4++) { acc.push(total += u16()); } let skip = u16(); let pos_payload = pos; pos += skip; let read_width = 0; let read_buffer = 0; function read_bit() { if (read_width == 0) { read_buffer = read_buffer << 8 | bytes[pos++]; read_width = 8; } return read_buffer >> --read_width & 1; } const N11 = 31; const FULL = Math.pow(2, N11); const HALF = FULL >>> 1; const QRTR = HALF >> 1; const MASK = FULL - 1; let register = 0; for (let i4 = 0; i4 < N11; i4++) register = register << 1 | read_bit(); let symbols = []; let low = 0; let range = FULL; while (true) { let value = Math.floor(((register - low + 1) * total - 1) / range); let start = 0; let end = symbol_count; while (end - start > 1) { let mid = start + end >>> 1; if (value < acc[mid]) { end = mid; } else { start = mid; } } if (start == 0) break; symbols.push(start); let a4 = low + Math.floor(range * acc[start] / total); let b5 = low + Math.floor(range * acc[start + 1] / total) - 1; while (((a4 ^ b5) & HALF) == 0) { register = register << 1 & MASK | read_bit(); a4 = a4 << 1 & MASK; b5 = b5 << 1 & MASK | 1; } while (a4 & ~b5 & QRTR) { register = register & HALF | register << 1 & MASK >>> 1 | read_bit(); a4 = a4 << 1 ^ HALF; b5 = (b5 ^ HALF) << 1 | HALF | 1; } low = a4; range = 1 + b5 - a4; } let offset = symbol_count - 4; return symbols.map((x6) => { switch (x6 - offset) { case 3: return offset + 65792 + (bytes[pos_payload++] << 16 | bytes[pos_payload++] << 8 | bytes[pos_payload++]); case 2: return offset + 256 + (bytes[pos_payload++] << 8 | bytes[pos_payload++]); case 1: return offset + bytes[pos_payload++]; default: return x6 - 1; } }); } function read_payload(v5) { let pos = 0; return () => v5[pos++]; } function read_compressed_payload(bytes) { return read_payload(decode_arithmetic(bytes)); } function signed(i4) { return i4 & 1 ? ~i4 >> 1 : i4 >> 1; } function read_counts(n5, next) { let v5 = Array(n5); for (let i4 = 0; i4 < n5; i4++) v5[i4] = 1 + next(); return v5; } function read_ascending(n5, next) { let v5 = Array(n5); for (let i4 = 0, x6 = -1; i4 < n5; i4++) v5[i4] = x6 += 1 + next(); return v5; } function read_deltas(n5, next) { let v5 = Array(n5); for (let i4 = 0, x6 = 0; i4 < n5; i4++) v5[i4] = x6 += signed(next()); return v5; } function read_member_array(next, lookup) { let v5 = read_ascending(next(), next); let n5 = next(); let vX = read_ascending(n5, next); let vN = read_counts(n5, next); for (let i4 = 0; i4 < n5; i4++) { for (let j2 = 0; j2 < vN[i4]; j2++) { v5.push(vX[i4] + j2); } } return lookup ? v5.map((x6) => lookup[x6]) : v5; } function read_mapped_map(next) { let ret = []; while (true) { let w4 = next(); if (w4 == 0) break; ret.push(read_linear_table(w4, next)); } while (true) { let w4 = next() - 1; if (w4 < 0) break; ret.push(read_replacement_table(w4, next)); } return fromEntries(flat(ret)); } function read_zero_terminated_array(next) { let v5 = []; while (true) { let i4 = next(); if (i4 == 0) break; v5.push(i4); } return v5; } function read_transposed(n5, w4, next) { let m2 = Array(n5).fill(void 0).map(() => []); for (let i4 = 0; i4 < w4; i4++) { read_deltas(n5, next).forEach((x6, j2) => m2[j2].push(x6)); } return m2; } function read_linear_table(w4, next) { let dx = 1 + next(); let dy = next(); let vN = read_zero_terminated_array(next); let m2 = read_transposed(vN.length, 1 + w4, next); return flat(m2.map((v5, i4) => { const x6 = v5[0], ys3 = v5.slice(1); return Array(vN[i4]).fill(void 0).map((_4, j2) => { let j_dy = j2 * dy; return [x6 + j2 * dx, ys3.map((y6) => y6 + j_dy)]; }); })); } function read_replacement_table(w4, next) { let n5 = 1 + next(); let m2 = read_transposed(n5, 1 + w4, next); return m2.map((v5) => [v5[0], v5.slice(1)]); } function read_emoji_trie(next) { let sorted = read_member_array(next).sort((a4, b5) => a4 - b5); return read2(); function read2() { let branches = []; while (true) { let keys2 = read_member_array(next, sorted); if (keys2.length == 0) break; branches.push({ set: new Set(keys2), node: read2() }); } branches.sort((a4, b5) => b5.set.size - a4.set.size); let temp = next(); let valid = temp % 3; temp = temp / 3 | 0; let fe0f = !!(temp & 1); temp >>= 1; let save = temp == 1; let check = temp == 2; return { branches, valid, fe0f, save, check }; } } // node_modules/@ethersproject/hash/lib.esm/ens-normalize/include.js function getData() { return read_compressed_payload(decode("AEQF2AO2DEsA2wIrAGsBRABxAN8AZwCcAEwAqgA0AGwAUgByADcATAAVAFYAIQAyACEAKAAYAFgAGwAjABQAMAAmADIAFAAfABQAKwATACoADgAbAA8AHQAYABoAGQAxADgALAAoADwAEwA9ABMAGgARAA4ADwAWABMAFgAIAA8AHgQXBYMA5BHJAS8JtAYoAe4AExozi0UAH21tAaMnBT8CrnIyhrMDhRgDygIBUAEHcoFHUPe8AXBjAewCjgDQR8IICIcEcQLwATXCDgzvHwBmBoHNAqsBdBcUAykgDhAMShskMgo8AY8jqAQfAUAfHw8BDw87MioGlCIPBwZCa4ELatMAAMspJVgsDl8AIhckSg8XAHdvTwBcIQEiDT4OPhUqbyECAEoAS34Aej8Ybx83JgT/Xw8gHxZ/7w8RICxPHA9vBw+Pfw8PHwAPFv+fAsAvCc8vEr8ivwD/EQ8Bol8OEBa/A78hrwAPCU8vESNvvwWfHwNfAVoDHr+ZAAED34YaAdJPAK7PLwSEgDLHAGo1Pz8Pvx9fUwMrpb8O/58VTzAPIBoXIyQJNF8hpwIVAT8YGAUADDNBaX3RAMomJCg9EhUeA29MABsZBTMNJipjOhc19gcIDR8bBwQHEggCWi6DIgLuAQYA+BAFCha3A5XiAEsqM7UFFgFLhAMjFTMYE1Klnw74nRVBG/ASCm0BYRN/BrsU3VoWy+S0vV8LQx+vN8gF2AC2AK5EAWwApgYDKmAAroQ0NDQ0AT+OCg7wAAIHRAbpNgVcBV0APTA5BfbPFgMLzcYL/QqqA82eBALKCjQCjqYCht0/k2+OAsXQAoP3ASTKDgDw6ACKAUYCMpIKJpRaAE4A5womABzZvs0REEKiACIQAd5QdAECAj4Ywg/wGqY2AVgAYADYvAoCGAEubA0gvAY2ALAAbpbvqpyEAGAEpgQAJgAG7gAgAEACmghUFwCqAMpAINQIwC4DthRAAPcycKgApoIdABwBfCisABoATwBqASIAvhnSBP8aH/ECeAKXAq40NjgDBTwFYQU6AXs3oABgAD4XNgmcCY1eCl5tIFZeUqGgyoNHABgAEQAaABNwWQAmABMATPMa3T34ADldyprmM1M2XociUQgLzvwAXT3xABgAEQAaABNwIGFAnADD8AAgAD4BBJWzaCcIAIEBFMAWwKoAAdq9BWAF5wLQpALEtQAKUSGkahR4GnJM+gsAwCgeFAiUAECQ0BQuL8AAIAAAADKeIheclvFqQAAETr4iAMxIARMgAMIoHhQIAn0E0pDQFC4HhznoAAAAIAI2C0/4lvFqQAAETgBJJwYCAy4ABgYAFAA8MBKYEH4eRhTkAjYeFcgACAYAeABsOqyQ5gRwDayqugEgaIIAtgoACgDmEABmBAWGme5OBJJA2m4cDeoAmITWAXwrMgOgAGwBCh6CBXYF1Tzg1wKAAFdiuABRAFwAXQBsAG8AdgBrAHYAbwCEAHEwfxQBVE5TEQADVFhTBwBDANILAqcCzgLTApQCrQL6vAAMAL8APLhNBKkE6glGKTAU4Dr4N2EYEwBCkABKk8rHAbYBmwIoAiU4Ajf/Aq4CowCAANIChzgaNBsCsTgeODcFXrgClQKdAqQBiQGYAqsCsjTsNHsfNPA0ixsAWTWiOAMFPDQSNCk2BDZHNow2TTZUNhk28Jk9VzI3QkEoAoICoQKwAqcAQAAxBV4FXbS9BW47YkIXP1ciUqs05DS/FwABUwJW11e6nHuYZmSh/RAYA8oMKvZ8KASoUAJYWAJ6ILAsAZSoqjpgA0ocBIhmDgDWAAawRDQoAAcuAj5iAHABZiR2AIgiHgCaAU68ACxuHAG0ygM8MiZIAlgBdF4GagJqAPZOHAMuBgoATkYAsABiAHgAMLoGDPj0HpKEBAAOJgAuALggTAHWAeAMEDbd20Uege0ADwAWADkAQgA9OHd+2MUQZBBhBgNNDkxxPxUQArEPqwvqERoM1irQ090ANK4H8ANYB/ADWANYB/AH8ANYB/ADWANYA1gDWBwP8B/YxRBkD00EcgWTBZAE2wiIJk4RhgctCNdUEnQjHEwDSgEBIypJITuYMxAlR0wRTQgIATZHbKx9PQNMMbBU+pCnA9AyVDlxBgMedhKlAC8PeCE1uk6DekxxpQpQT7NX9wBFBgASqwAS5gBJDSgAUCwGPQBI4zTYABNGAE2bAE3KAExdGABKaAbgAFBXAFCOAFBJABI2SWdObALDOq0//QomCZhvwHdTBkIQHCemEPgMNAG2ATwN7kvZBPIGPATKH34ZGg/OlZ0Ipi3eDO4m5C6igFsj9iqEBe5L9TzeC05RaQ9aC2YJ5DpkgU8DIgEOIowK3g06CG4Q9ArKbA3mEUYHOgPWSZsApgcCCxIdNhW2JhFirQsKOXgG/Br3C5AmsBMqev0F1BoiBk4BKhsAANAu6IWxWjJcHU9gBgQLJiPIFKlQIQ0mQLh4SRocBxYlqgKSQ3FKiFE3HpQh9zw+DWcuFFF9B/Y8BhlQC4I8n0asRQ8R0z6OPUkiSkwtBDaALDAnjAnQD4YMunxzAVoJIgmyDHITMhEYN8YIOgcaLpclJxYIIkaWYJsE+KAD9BPSAwwFQAlCBxQDthwuEy8VKgUOgSXYAvQ21i60ApBWgQEYBcwPJh/gEFFH4Q7qCJwCZgOEJewALhUiABginAhEZABgj9lTBi7MCMhqbSN1A2gU6GIRdAeSDlgHqBw0FcAc4nDJXgyGCSiksAlcAXYJmgFgBOQICjVcjKEgQmdUi1kYnCBiQUBd/QIyDGYVoES+h3kCjA9sEhwBNgF0BzoNAgJ4Ee4RbBCWCOyGBTW2M/k6JgRQIYQgEgooA1BszwsoJvoM+WoBpBJjAw00PnfvZ6xgtyUX/gcaMsZBYSHyC5NPzgydGsIYQ1QvGeUHwAP0GvQn60FYBgADpAQUOk4z7wS+C2oIjAlAAEoOpBgH2BhrCnKM0QEyjAG4mgNYkoQCcJAGOAcMAGgMiAV65gAeAqgIpAAGANADWAA6Aq4HngAaAIZCAT4DKDABIuYCkAOUCDLMAZYwAfQqBBzEDBYA+DhuSwLDsgKAa2ajBd5ZAo8CSjYBTiYEBk9IUgOwcuIA3ABMBhTgSAEWrEvMG+REAeBwLADIAPwABjYHBkIBzgH0bgC4AWALMgmjtLYBTuoqAIQAFmwB2AKKAN4ANgCA8gFUAE4FWvoF1AJQSgESMhksWGIBvAMgATQBDgB6BsyOpsoIIARuB9QCEBwV4gLvLwe2AgMi4BPOQsYCvd9WADIXUu5eZwqoCqdeaAC0YTQHMnM9UQAPH6k+yAdy/BZIiQImSwBQ5gBQQzSaNTFWSTYBpwGqKQK38AFtqwBI/wK37gK3rQK3sAK6280C0gK33AK3zxAAUEIAUD9SklKDArekArw5AEQAzAHCO147WTteO1k7XjtZO147WTteO1kDmChYI03AVU0oJqkKbV9GYewMpw3VRMk6ShPcYFJgMxPJLbgUwhXPJVcZPhq9JwYl5VUKDwUt1GYxCC00dhe9AEApaYNCY4ceMQpMHOhTklT5LRwAskujM7ANrRsWREEFSHXuYisWDwojAmSCAmJDXE6wXDchAqH4AmiZAmYKAp+FOBwMAmY8AmYnBG8EgAN/FAN+kzkHOXgYOYM6JCQCbB4CMjc4CwJtyAJtr/CLADRoRiwBaADfAOIASwYHmQyOAP8MwwAOtgJ3MAJ2o0ACeUxEAni7Hl3cRa9G9AJ8QAJ6yQJ9CgJ88UgBSH5kJQAsFklZSlwWGErNAtECAtDNSygDiFADh+dExpEzAvKiXQQDA69Lz0wuJgTQTU1NsAKLQAKK2cIcCB5EaAa4Ao44Ao5dQZiCAo7aAo5deVG1UzYLUtVUhgKT/AKTDQDqAB1VH1WwVdEHLBwplocy4nhnRTw6ApegAu+zWCKpAFomApaQApZ9nQCqWa1aCoJOADwClrYClk9cRVzSApnMApllXMtdCBoCnJw5wzqeApwXAp+cAp65iwAeEDIrEAKd8gKekwC2PmE1YfACntQCoG8BqgKeoCACnk+mY8lkKCYsAiewAiZ/AqD8AqBN2AKmMAKlzwKoAAB+AqfzaH1osgAESmodatICrOQCrK8CrWgCrQMCVx4CVd0CseLYAx9PbJgCsr4OArLpGGzhbWRtSWADJc4Ctl08QG6RAylGArhfArlIFgK5K3hwN3DiAr0aAy2zAzISAr6JcgMDM3ICvhtzI3NQAsPMAsMFc4N0TDZGdOEDPKgDPJsDPcACxX0CxkgCxhGKAshqUgLIRQLJUALJLwJkngLd03h6YniveSZL0QMYpGcDAmH1GfSVJXsMXpNevBICz2wCz20wTFTT9BSgAMeuAs90ASrrA04TfkwGAtwoAtuLAtJQA1JdA1NgAQIDVY2AikABzBfuYUZ2AILPg44C2sgC2d+EEYRKpz0DhqYAMANkD4ZyWvoAVgLfZgLeuXR4AuIw7RUB8zEoAfScAfLTiALr9ALpcXoAAur6AurlAPpIAboC7ooC652Wq5cEAu5AA4XhmHpw4XGiAvMEAGoDjheZlAL3FAORbwOSiAL3mQL52gL4Z5odmqy8OJsfA52EAv77ARwAOp8dn7QDBY4DpmsDptoA0sYDBmuhiaIGCgMMSgFgASACtgNGAJwEgLpoBgC8BGzAEowcggCEDC6kdjoAJAM0C5IKRoABZCgiAIzw3AYBLACkfng9ogigkgNmWAN6AEQCvrkEVqTGAwCsBRbAA+4iQkMCHR072jI2PTbUNsk2RjY5NvA23TZKNiU3EDcZN5I+RTxDRTBCJkK5VBYKFhZfwQCWygU3AJBRHpu+OytgNxa61A40GMsYjsn7BVwFXQVcBV0FaAVdBVwFXQVcBV0FXAVdBVwFXUsaCNyKAK4AAQUHBwKU7oICoW1e7jAEzgPxA+YDwgCkBFDAwADABKzAAOxFLhitA1UFTDeyPkM+bj51QkRCuwTQWWQ8X+0AWBYzsACNA8xwzAGm7EZ/QisoCTAbLDs6fnLfb8H2GccsbgFw13M1HAVkBW/Jxsm9CNRO8E8FDD0FBQw9FkcClOYCoMFegpDfADgcMiA2AJQACB8AsigKAIzIEAJKeBIApY5yPZQIAKQiHb4fvj5BKSRPQrZCOz0oXyxgOywfKAnGbgMClQaCAkILXgdeCD9IIGUgQj5fPoY+dT52Ao5CM0dAX9BTVG9SDzFwWTQAbxBzJF/lOEIQQglCCkKJIAls5AcClQICoKPMODEFxhi6KSAbiyfIRrMjtCgdWCAkPlFBIitCsEJRzAbMAV/OEyQzDg0OAQQEJ36i328/Mk9AybDJsQlq3tDRApUKAkFzXf1d/j9uALYP6hCoFgCTGD8kPsFKQiobrm0+zj0KSD8kPnVCRBwMDyJRTHFgMTJa5rwXQiQ2YfI/JD7BMEJEHGINTw4TOFlIRzwJO0icMQpyPyQ+wzJCRBv6DVgnKB01NgUKj2bwYzMqCoBkznBgEF+zYDIocwRIX+NgHj4HICNfh2C4CwdwFWpTG/lgUhYGAwRfv2Ts8mAaXzVgml/XYIJfuWC4HI1gUF9pYJZgMR6ilQHMAOwLAlDRefC0in4AXAEJA6PjCwc0IamOANMMCAECRQDFNRTZBgd+CwQlRA+r6+gLBDEFBnwUBXgKATIArwAGRAAHA3cDdAN2A3kDdwN9A3oDdQN7A30DfAN4A3oDfQAYEAAlAtYASwMAUAFsAHcKAHcAmgB3AHUAdQB2AHVu8UgAygDAAHcAdQB1AHYAdQALCgB3AAsAmgB3AAsCOwB3AAtu8UgAygDAAHgKAJoAdwB3AHUAdQB2AHUAeAB1AHUAdgB1bvFIAMoAwAALCgCaAHcACwB3AAsCOwB3AAtu8UgAygDAAH4ACwGgALcBpwC6AahdAu0COwLtbvFIAMoAwAALCgCaAu0ACwLtAAsCOwLtAAtu8UgAygDAA24ACwNvAAu0VsQAAzsAABCkjUIpAAsAUIusOggWcgMeBxVsGwL67U/2HlzmWOEeOgALASvuAAseAfpKUpnpGgYJDCIZM6YyARUE9ThqAD5iXQgnAJYJPnOzw0ZAEZxEKsIAkA4DhAHnTAIDxxUDK0lxCQlPYgIvIQVYJQBVqE1GakUAKGYiDToSBA1EtAYAXQJYAIF8GgMHRyAAIAjOe9YncekRAA0KACUrjwE7Ayc6AAYWAqaiKG4McEcqANoN3+Mg9TwCBhIkuCny+JwUQ29L008JluRxu3K+oAdqiHOqFH0AG5SUIfUJ5SxCGfxdipRzqTmT4V5Zb+r1Uo4Vm+NqSSEl2mNvR2JhIa8SpYO6ntdwFXHCWTCK8f2+Hxo7uiG3drDycAuKIMP5bhi06ACnqArH1rz4Rqg//lm6SgJGEVbF9xJHISaR6HxqxSnkw6shDnelHKNEfGUXSJRJ1GcsmtJw25xrZMDK9gXSm1/YMkdX4/6NKYOdtk/NQ3/NnDASjTc3fPjIjW/5sVfVObX2oTDWkr1dF9f3kxBsD3/3aQO8hPfRz+e0uEiJqt1161griu7gz8hDDwtpy+F+BWtefnKHZPAxcZoWbnznhJpy0e842j36bcNzGnIEusgGX0a8ZxsnjcSsPDZ09yZ36fCQbriHeQ72JRMILNl6ePPf2HWoVwgWAm1fb3V2sAY0+B6rAXqSwPBgseVmoqsBTSrm91+XasMYYySI8eeRxH3ZvHkMz3BQ5aJ3iUVbYPNM3/7emRtjlsMgv/9VyTsyt/mK+8fgWeT6SoFaclXqn42dAIsvAarF5vNNWHzKSkKQ/8Hfk5ZWK7r9yliOsooyBjRhfkHP4Q2DkWXQi6FG/9r/IwbmkV5T7JSopHKn1pJwm9tb5Ot0oyN1Z2mPpKXHTxx2nlK08fKk1hEYA8WgVVWL5lgx0iTv+KdojJeU23ZDjmiubXOxVXJKKi2Wjuh2HLZOFLiSC7Tls5SMh4f+Pj6xUSrNjFqLGehRNB8lC0QSLNmkJJx/wSG3MnjE9T1CkPwJI0wH2lfzwETIiVqUxg0dfu5q39Gt+hwdcxkhhNvQ4TyrBceof3Mhs/IxFci1HmHr4FMZgXEEczPiGCx0HRwzAqDq2j9AVm1kwN0mRVLWLylgtoPNapF5cY4Y1wJh/e0BBwZj44YgZrDNqvD/9Hv7GFYdUQeDJuQ3EWI4HaKqavU1XjC/n41kT4L79kqGq0kLhdTZvgP3TA3fS0ozVz+5piZsoOtIvBUFoMKbNcmBL6YxxaUAusHB38XrS8dQMnQwJfUUkpRoGr5AUeWicvBTzyK9g77+yCkf5PAysL7r/JjcZgrbvRpMW9iyaxZvKO6ceZN2EwIxKwVFPuvFuiEPGCoagbMo+SpydLrXqBzNCDGFCrO/rkcwa2xhokQZ5CdZ0AsU3JfSqJ6n5I14YA+P/uAgfhPU84Tlw7cEFfp7AEE8ey4sP12PTt4Cods1GRgDOB5xvyiR5m+Bx8O5nBCNctU8BevfV5A08x6RHd5jcwPTMDSZJOedIZ1cGQ704lxbAzqZOP05ZxaOghzSdvFBHYqomATARyAADK4elP8Ly3IrUZKfWh23Xy20uBUmLS4Pfagu9+oyVa2iPgqRP3F2CTUsvJ7+RYnN8fFZbU/HVvxvcFFDKkiTqV5UBZ3Gz54JAKByi9hkKMZJvuGgcSYXFmw08UyoQyVdfTD1/dMkCHXcTGAKeROgArsvmRrQTLUOXioOHGK2QkjHuoYFgXciZoTJd6Fs5q1QX1G+p/e26hYsEf7QZD1nnIyl/SFkNtYYmmBhpBrxl9WbY0YpHWRuw2Ll/tj9mD8P4snVzJl4F9J+1arVeTb9E5r2ILH04qStjxQNwn3m4YNqxmaNbLAqW2TN6LidwuJRqS+NXbtqxoeDXpxeGWmxzSkWxjkyCkX4NQRme6q5SAcC+M7+9ETfA/EwrzQajKakCwYyeunP6ZFlxU2oMEn1Pz31zeStW74G406ZJFCl1wAXIoUKkWotYEpOuXB1uVNxJ63dpJEqfxBeptwIHNrPz8BllZoIcBoXwgfJ+8VAUnVPvRvexnw0Ma/WiGYuJO5y8QTvEYBigFmhUxY5RqzE8OcywN/8m4UYrlaniJO75XQ6KSo9+tWHlu+hMi0UVdiKQp7NelnoZUzNaIyBPVeOwK6GNp+FfHuPOoyhaWuNvTYFkvxscMQWDh+zeFCFkgwbXftiV23ywJ4+uwRqmg9k3KzwIQpzppt8DBBOMbrqwQM5Gb05sEwdKzMiAqOloaA/lr0KA+1pr0/+HiWoiIjHA/wir2nIuS3PeU/ji3O6ZwoxcR1SZ9FhtLC5S0FIzFhbBWcGVP/KpxOPSiUoAdWUpqKH++6Scz507iCcxYI6rdMBICPJZea7OcmeFw5mObJSiqpjg2UoWNIs+cFhyDSt6geV5qgi3FunmwwDoGSMgerFOZGX1m0dMCYo5XOruxO063dwENK9DbnVM9wYFREzh4vyU1WYYJ/LRRp6oxgjqP/X5a8/4Af6p6NWkQferzBmXme0zY/4nwMJm/wd1tIqSwGz+E3xPEAOoZlJit3XddD7/BT1pllzOx+8bmQtANQ/S6fZexc6qi3W+Q2xcmXTUhuS5mpHQRvcxZUN0S5+PL9lXWUAaRZhEH8hTdAcuNMMCuVNKTEGtSUKNi3O6KhSaTzck8csZ2vWRZ+d7mW8c4IKwXIYd25S/zIftPkwPzufjEvOHWVD1m+FjpDVUTV0DGDuHj6QnaEwLu/dEgdLQOg9E1Sro9XHJ8ykLAwtPu+pxqKDuFexqON1sKQm7rwbE1E68UCfA/erovrTCG+DBSNg0l4goDQvZN6uNlbyLpcZAwj2UclycvLpIZMgv4yRlpb3YuMftozorbcGVHt/VeDV3+Fdf1TP0iuaCsPi2G4XeGhsyF1ubVDxkoJhmniQ0/jSg/eYML9KLfnCFgISWkp91eauR3IQvED0nAPXK+6hPCYs+n3+hCZbiskmVMG2da+0EsZPonUeIY8EbfusQXjsK/eFDaosbPjEfQS0RKG7yj5GG69M7MeO1HmiUYocgygJHL6M1qzUDDwUSmr99V7Sdr2F3JjQAJY+F0yH33Iv3+C9M38eML7gTgmNu/r2bUMiPvpYbZ6v1/IaESirBHNa7mPKn4dEmYg7v/+HQgPN1G79jBQ1+soydfDC2r+h2Bl/KIc5KjMK7OH6nb1jLsNf0EHVe2KBiE51ox636uyG6Lho0t3J34L5QY/ilE3mikaF4HKXG1mG1rCevT1Vv6GavltxoQe/bMrpZvRggnBxSEPEeEzkEdOxTnPXHVjUYdw8JYvjB/o7Eegc3Ma+NUxLLnsK0kJlinPmUHzHGtrk5+CAbVzFOBqpyy3QVUnzTDfC/0XD94/okH+OB+i7g9lolhWIjSnfIb+Eq43ZXOWmwvjyV/qqD+t0e+7mTEM74qP/Ozt8nmC7mRpyu63OB4KnUzFc074SqoyPUAgM+/TJGFo6T44EHnQU4X4z6qannVqgw/U7zCpwcmXV1AubIrvOmkKHazJAR55ePjp5tLBsN8vAqs3NAHdcEHOR2xQ0lsNAFzSUuxFQCFYvXLZJdOj9p4fNq6p0HBGUik2YzaI4xySy91KzhQ0+q1hjxvImRwPRf76tChlRkhRCi74NXZ9qUNeIwP+s5p+3m5nwPdNOHgSLD79n7O9m1n1uDHiMntq4nkYwV5OZ1ENbXxFd4PgrlvavZsyUO4MqYlqqn1O8W/I1dEZq5dXhrbETLaZIbC2Kj/Aa/QM+fqUOHdf0tXAQ1huZ3cmWECWSXy/43j35+Mvq9xws7JKseriZ1pEWKc8qlzNrGPUGcVgOa9cPJYIJsGnJTAUsEcDOEVULO5x0rXBijc1lgXEzQQKhROf8zIV82w8eswc78YX11KYLWQRcgHNJElBxfXr72lS2RBSl07qTKorO2uUDZr3sFhYsvnhLZn0A94KRzJ/7DEGIAhW5ZWFpL8gEwu1aLA9MuWZzNwl8Oze9Y+bX+v9gywRVnoB5I/8kXTXU3141yRLYrIOOz6SOnyHNy4SieqzkBXharjfjqq1q6tklaEbA8Qfm2DaIPs7OTq/nvJBjKfO2H9bH2cCMh1+5gspfycu8f/cuuRmtDjyqZ7uCIMyjdV3a+p3fqmXsRx4C8lujezIFHnQiVTXLXuI1XrwN3+siYYj2HHTvESUx8DlOTXpak9qFRK+L3mgJ1WsD7F4cu1aJoFoYQnu+wGDMOjJM3kiBQWHCcvhJ/HRdxodOQp45YZaOTA22Nb4XKCVxqkbwMYFhzYQYIAnCW8FW14uf98jhUG2zrKhQQ0q0CEq0t5nXyvUyvR8DvD69LU+g3i+HFWQMQ8PqZuHD+sNKAV0+M6EJC0szq7rEr7B5bQ8BcNHzvDMc9eqB5ZCQdTf80Obn4uzjwpYU7SISdtV0QGa9D3Wrh2BDQtpBKxaNFV+/Cy2P/Sv+8s7Ud0Fd74X4+o/TNztWgETUapy+majNQ68Lq3ee0ZO48VEbTZYiH1Co4OlfWef82RWeyUXo7woM03PyapGfikTnQinoNq5z5veLpeMV3HCAMTaZmA1oGLAn7XS3XYsz+XK7VMQsc4XKrmDXOLU/pSXVNUq8dIqTba///3x6LiLS6xs1xuCAYSfcQ3+rQgmu7uvf3THKt5Ooo97TqcbRqxx7EASizaQCBQllG/rYxVapMLgtLbZS64w1MDBMXX+PQpBKNwqUKOf2DDRDUXQf9EhOS0Qj4nTmlA8dzSLz/G1d+Ud8MTy/6ghhdiLpeerGY/UlDOfiuqFsMUU5/UYlP+BAmgRLuNpvrUaLlVkrqDievNVEAwF+4CoM1MZTmjxjJMsKJq+u8Zd7tNCUFy6LiyYXRJQ4VyvEQFFaCGKsxIwQkk7EzZ6LTJq2hUuPhvAW+gQnSG6J+MszC+7QCRHcnqDdyNRJ6T9xyS87A6MDutbzKGvGktpbXqtzWtXb9HsfK2cBMomjN9a4y+TaJLnXxAeX/HWzmf4cR4vALt/P4w4qgKY04ml4ZdLOinFYS6cup3G/1ie4+t1eOnpBNlqGqs75ilzkT4+DsZQxNvaSKJ//6zIbbk/M7LOhFmRc/1R+kBtz7JFGdZm/COotIdvQoXpTqP/1uqEUmCb/QWoGLMwO5ANcHzxdY48IGP5+J+zKOTBFZ4Pid+GTM+Wq12MV/H86xEJptBa6T+p3kgpwLedManBHC2GgNrFpoN2xnrMz9WFWX/8/ygSBkavq2Uv7FdCsLEYLu9LLIvAU0bNRDtzYl+/vXmjpIvuJFYjmI0im6QEYqnIeMsNjXG4vIutIGHijeAG/9EDBozKV5cldkHbLxHh25vT+ZEzbhXlqvpzKJwcEgfNwLAKFeo0/pvEE10XDB+EXRTXtSzJozQKFFAJhMxYkVaCW+E9AL7tMeU8acxidHqzb6lX4691UsDpy/LLRmT+epgW56+5Cw8tB4kMUv6s9lh3eRKbyGs+H/4mQMaYzPTf2OOdokEn+zzgvoD3FqNKk8QqGAXVsqcGdXrT62fSPkR2vROFi68A6se86UxRUk4cajfPyCC4G5wDhD+zNq4jodQ4u4n/m37Lr36n4LIAAsVr02dFi9AiwA81MYs2rm4eDlDNmdMRvEKRHfBwW5DdMNp0jPFZMeARqF/wL4XBfd+EMLBfMzpH5GH6NaW+1vrvMdg+VxDzatk3MXgO3ro3P/DpcC6+Mo4MySJhKJhSR01SGGGp5hPWmrrUgrv3lDnP+HhcI3nt3YqBoVAVTBAQT5iuhTg8nvPtd8ZeYj6w1x6RqGUBrSku7+N1+BaasZvjTk64RoIDlL8brpEcJx3OmY7jLoZsswdtmhfC/G21llXhITOwmvRDDeTTPbyASOa16cF5/A1fZAidJpqju3wYAy9avPR1ya6eNp9K8XYrrtuxlqi+bDKwlfrYdR0RRiKRVTLOH85+ZY7XSmzRpfZBJjaTa81VDcJHpZnZnSQLASGYW9l51ZV/h7eVzTi3Hv6hUsgc/51AqJRTkpbFVLXXszoBL8nBX0u/0jBLT8nH+fJePbrwURT58OY+UieRjd1vs04w0VG5VN2U6MoGZkQzKN/ptz0Q366dxoTGmj7i1NQGHi9GgnquXFYdrCfZBmeb7s0T6yrdlZH5cZuwHFyIJ/kAtGsTg0xH5taAAq44BAk1CPk9KVVbqQzrCUiFdF/6gtlPQ8bHHc1G1W92MXGZ5HEHftyLYs8mbD/9xYRUWkHmlM0zC2ilJlnNgV4bfALpQghxOUoZL7VTqtCHIaQSXm+YUMnpkXybnV+A6xlm2CVy8fn0Xlm2XRa0+zzOa21JWWmixfiPMSCZ7qA4rS93VN3pkpF1s5TonQjisHf7iU9ZGvUPOAKZcR1pbeVf/Ul7OhepGCaId9wOtqo7pJ7yLcBZ0pFkOF28y4zEI/kcUNmutBHaQpBdNM8vjCS6HZRokkeo88TBAjGyG7SR+6vUgTcyK9Imalj0kuxz0wmK+byQU11AiJFk/ya5dNduRClcnU64yGu/ieWSeOos1t3ep+RPIWQ2pyTYVbZltTbsb7NiwSi3AV+8KLWk7LxCnfZUetEM8ThnsSoGH38/nyAwFguJp8FjvlHtcWZuU4hPva0rHfr0UhOOJ/F6vS62FW7KzkmRll2HEc7oUq4fyi5T70Vl7YVIfsPHUCdHesf9Lk7WNVWO75JDkYbMI8TOW8JKVtLY9d6UJRITO8oKo0xS+o99Yy04iniGHAaGj88kEWgwv0OrHdY/nr76DOGNS59hXCGXzTKUvDl9iKpLSWYN1lxIeyywdNpTkhay74w2jFT6NS8qkjo5CxA1yfSYwp6AJIZNKIeEK5PJAW7ORgWgwp0VgzYpqovMrWxbu+DGZ6Lhie1RAqpzm8VUzKJOH3mCzWuTOLsN3VT/dv2eeYe9UjbR8YTBsLz7q60VN1sU51k+um1f8JxD5pPhbhSC8rRaB454tmh6YUWrJI3+GWY0qeWioj/tbkYITOkJaeuGt4JrJvHA+l0Gu7kY7XOaa05alMnRWVCXqFgLIwSY4uF59Ue5SU4QKuc/HamDxbr0x6csCetXGoP7Qn1Bk/J9DsynO/UD6iZ1Hyrz+jit0hDCwi/E9OjgKTbB3ZQKQ/0ZOvevfNHG0NK4Aj3Cp7NpRk07RT1i/S0EL93Ag8GRgKI9CfpajKyK6+Jj/PI1KO5/85VAwz2AwzP8FTBb075IxCXv6T9RVvWT2tUaqxDS92zrGUbWzUYk9mSs82pECH+fkqsDt93VW++4YsR/dHCYcQSYTO/KaBMDj9LSD/J/+z20Kq8XvZUAIHtm9hRPP3ItbuAu2Hm5lkPs92pd7kCxgRs0xOVBnZ13ccdA0aunrwv9SdqElJRC3g+oCu+nXyCgmXUs9yMjTMAIHfxZV+aPKcZeUBWt057Xo85Ks1Ir5gzEHCWqZEhrLZMuF11ziGtFQUds/EESajhagzcKsxamcSZxGth4UII+adPhQkUnx2WyN+4YWR+r3f8MnkyGFuR4zjzxJS8WsQYR5PTyRaD9ixa6Mh741nBHbzfjXHskGDq179xaRNrCIB1z1xRfWfjqw2pHc1zk9xlPpL8sQWAIuETZZhbnmL54rceXVNRvUiKrrqIkeogsl0XXb17ylNb0f4GA9Wd44vffEG8FSZGHEL2fbaTGRcSiCeA8PmA/f6Hz8HCS76fXUHwgwkzSwlI71ekZ7Fapmlk/KC+Hs8hUcw3N2LN5LhkVYyizYFl/uPeVP5lsoJHhhfWvvSWruCUW1ZcJOeuTbrDgywJ/qG07gZJplnTvLcYdNaH0KMYOYMGX+rB4NGPFmQsNaIwlWrfCezxre8zXBrsMT+edVLbLqN1BqB76JH4BvZTqUIMfGwPGEn+EnmTV86fPBaYbFL3DFEhjB45CewkXEAtJxk4/Ms2pPXnaRqdky0HOYdcUcE2zcXq4vaIvW2/v0nHFJH2XXe22ueDmq/18XGtELSq85j9X8q0tcNSSKJIX8FTuJF/Pf8j5PhqG2u+osvsLxYrvvfeVJL+4tkcXcr9JV7v0ERmj/X6fM3NC4j6dS1+9Umr2oPavqiAydTZPLMNRGY23LO9zAVDly7jD+70G5TPPLdhRIl4WxcYjLnM+SNcJ26FOrkrISUtPObIz5Zb3AG612krnpy15RMW+1cQjlnWFI6538qky9axd2oJmHIHP08KyP0ubGO+TQNOYuv2uh17yCIvR8VcStw7o1g0NM60sk+8Tq7YfIBJrtp53GkvzXH7OA0p8/n/u1satf/VJhtR1l8Wa6Gmaug7haSpaCaYQax6ta0mkutlb+eAOSG1aobM81D9A4iS1RRlzBBoVX6tU1S6WE2N9ORY6DfeLRC4l9Rvr5h95XDWB2mR1d4WFudpsgVYwiTwT31ljskD8ZyDOlm5DkGh9N/UB/0AI5Xvb8ZBmai2hQ4BWMqFwYnzxwB26YHSOv9WgY3JXnvoN+2R4rqGVh/LLDMtpFP+SpMGJNWvbIl5SOodbCczW2RKleksPoUeGEzrjtKHVdtZA+kfqO+rVx/iclCqwoopepvJpSTDjT+b9GWylGRF8EDbGlw6eUzmJM95Ovoz+kwLX3c2fTjFeYEsE7vUZm3mqdGJuKh2w9/QGSaqRHs99aScGOdDqkFcACoqdbBoQqqjamhH6Q9ng39JCg3lrGJwd50Qk9ovnqBTr8MME7Ps2wiVfygUmPoUBJJfJWX5Nda0nuncbFkA==")); } // node_modules/@ethersproject/hash/lib.esm/ens-normalize/lib.js var r = getData(); var VALID = new Set(read_member_array(r)); var IGNORED = new Set(read_member_array(r)); var MAPPED = read_mapped_map(r); var EMOJI_ROOT = read_emoji_trie(r); // node_modules/@ethersproject/hash/lib.esm/namehash.js var logger5 = new Logger(version5); var Zeros = new Uint8Array(32); Zeros.fill(0); // node_modules/@ethersproject/hash/lib.esm/message.js var messagePrefix = "Ethereum Signed Message:\n"; function hashMessage(message) { if (typeof message === "string") { message = toUtf8Bytes(message); } return keccak256(concat([ toUtf8Bytes(messagePrefix), toUtf8Bytes(String(message.length)), message ])); } // node_modules/@ethersproject/rlp/lib.esm/_version.js var version6 = "rlp/5.7.0"; // node_modules/@ethersproject/rlp/lib.esm/index.js var logger6 = new Logger(version6); // node_modules/@ethersproject/address/lib.esm/_version.js var version7 = "address/5.7.0"; // node_modules/@ethersproject/address/lib.esm/index.js var logger7 = new Logger(version7); function getChecksumAddress(address) { if (!isHexString(address, 20)) { logger7.throwArgumentError("invalid address", "address", address); } address = address.toLowerCase(); const chars = address.substring(2).split(""); const expanded = new Uint8Array(40); for (let i4 = 0; i4 < 40; i4++) { expanded[i4] = chars[i4].charCodeAt(0); } const hashed = arrayify(keccak256(expanded)); for (let i4 = 0; i4 < 40; i4 += 2) { if (hashed[i4 >> 1] >> 4 >= 8) { chars[i4] = chars[i4].toUpperCase(); } if ((hashed[i4 >> 1] & 15) >= 8) { chars[i4 + 1] = chars[i4 + 1].toUpperCase(); } } return "0x" + chars.join(""); } var MAX_SAFE_INTEGER = 9007199254740991; function log10(x6) { if (Math.log10) { return Math.log10(x6); } return Math.log(x6) / Math.LN10; } var ibanLookup = {}; for (let i4 = 0; i4 < 10; i4++) { ibanLookup[String(i4)] = String(i4); } for (let i4 = 0; i4 < 26; i4++) { ibanLookup[String.fromCharCode(65 + i4)] = String(10 + i4); } var safeDigits = Math.floor(log10(MAX_SAFE_INTEGER)); function ibanChecksum(address) { address = address.toUpperCase(); address = address.substring(4) + address.substring(0, 2) + "00"; let expanded = address.split("").map((c5) => { return ibanLookup[c5]; }).join(""); while (expanded.length >= safeDigits) { let block = expanded.substring(0, safeDigits); expanded = parseInt(block, 10) % 97 + expanded.substring(block.length); } let checksum = String(98 - parseInt(expanded, 10) % 97); while (checksum.length < 2) { checksum = "0" + checksum; } return checksum; } function getAddress(address) { let result = null; if (typeof address !== "string") { logger7.throwArgumentError("invalid address", "address", address); } if (address.match(/^(0x)?[0-9a-fA-F]{40}$/)) { if (address.substring(0, 2) !== "0x") { address = "0x" + address; } result = getChecksumAddress(address); if (address.match(/([A-F].*[a-f])|([a-f].*[A-F])/) && result !== address) { logger7.throwArgumentError("bad address checksum", "address", address); } } else if (address.match(/^XE[0-9]{2}[0-9A-Za-z]{30,31}$/)) { if (address.substring(2, 4) !== ibanChecksum(address)) { logger7.throwArgumentError("bad icap checksum", "address", address); } result = _base36To16(address.substring(4)); while (result.length < 40) { result = "0" + result; } result = getChecksumAddress("0x" + result); } else { logger7.throwArgumentError("invalid address", "address", address); } return result; } // node_modules/@ethersproject/properties/lib.esm/_version.js var version8 = "properties/5.7.0"; // node_modules/@ethersproject/properties/lib.esm/index.js var logger8 = new Logger(version8); function defineReadOnly(object, name2, value) { Object.defineProperty(object, name2, { enumerable: true, value, writable: false }); } // node_modules/@ethersproject/hash/lib.esm/typed-data.js var logger9 = new Logger(version5); var padding = new Uint8Array(32); padding.fill(0); var NegativeOne3 = BigNumber.from(-1); var Zero3 = BigNumber.from(0); var One2 = BigNumber.from(1); var MaxUint2562 = BigNumber.from("0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"); var hexTrue = hexZeroPad(One2.toHexString(), 32); var hexFalse = hexZeroPad(Zero3.toHexString(), 32); function checkString(key2) { return function(value) { if (typeof value !== "string") { logger9.throwArgumentError(`invalid domain value for ${JSON.stringify(key2)}`, `domain.${key2}`, value); } return value; }; } var domainChecks = { name: checkString("name"), version: checkString("version"), chainId: function(value) { try { return BigNumber.from(value).toString(); } catch (error) { } return logger9.throwArgumentError(`invalid domain value for "chainId"`, "domain.chainId", value); }, verifyingContract: function(value) { try { return getAddress(value).toLowerCase(); } catch (error) { } return logger9.throwArgumentError(`invalid domain value "verifyingContract"`, "domain.verifyingContract", value); }, salt: function(value) { try { const bytes = arrayify(value); if (bytes.length !== 32) { throw new Error("bad length"); } return hexlify(bytes); } catch (error) { } return logger9.throwArgumentError(`invalid domain value "salt"`, "domain.salt", value); } }; // node_modules/@ethersproject/signing-key/lib.esm/elliptic.js var import_bn2 = __toESM(require_bn()); var import_hash = __toESM(require_hash()); function createCommonjsModule(fn, basedir, module) { return module = { path: basedir, exports: {}, require: function(path, base3) { return commonjsRequire(path, base3 === void 0 || base3 === null ? module.path : base3); } }, fn(module, module.exports), module.exports; } function commonjsRequire() { throw new Error("Dynamic requires are not currently supported by @rollup/plugin-commonjs"); } var minimalisticAssert = assert; function assert(val, msg) { if (!val) throw new Error(msg || "Assertion failed"); } assert.equal = function assertEqual(l4, r4, msg) { if (l4 != r4) throw new Error(msg || "Assertion failed: " + l4 + " != " + r4); }; var utils_1 = createCommonjsModule(function(module, exports) { "use strict"; var utils = exports; function toArray(msg, enc) { if (Array.isArray(msg)) return msg.slice(); if (!msg) return []; var res = []; if (typeof msg !== "string") { for (var i4 = 0; i4 < msg.length; i4++) res[i4] = msg[i4] | 0; return res; } if (enc === "hex") { msg = msg.replace(/[^a-z0-9]+/ig, ""); if (msg.length % 2 !== 0) msg = "0" + msg; for (var i4 = 0; i4 < msg.length; i4 += 2) res.push(parseInt(msg[i4] + msg[i4 + 1], 16)); } else { for (var i4 = 0; i4 < msg.length; i4++) { var c5 = msg.charCodeAt(i4); var hi2 = c5 >> 8; var lo2 = c5 & 255; if (hi2) res.push(hi2, lo2); else res.push(lo2); } } return res; } utils.toArray = toArray; function zero2(word) { if (word.length === 1) return "0" + word; else return word; } utils.zero2 = zero2; function toHex2(msg) { var res = ""; for (var i4 = 0; i4 < msg.length; i4++) res += zero2(msg[i4].toString(16)); return res; } utils.toHex = toHex2; utils.encode = function encode8(arr, enc) { if (enc === "hex") return toHex2(arr); else return arr; }; }); var utils_1$1 = createCommonjsModule(function(module, exports) { "use strict"; var utils = exports; utils.assert = minimalisticAssert; utils.toArray = utils_1.toArray; utils.zero2 = utils_1.zero2; utils.toHex = utils_1.toHex; utils.encode = utils_1.encode; function getNAF2(num, w4, bits) { var naf = new Array(Math.max(num.bitLength(), bits) + 1); naf.fill(0); var ws2 = 1 << w4 + 1; var k4 = num.clone(); for (var i4 = 0; i4 < naf.length; i4++) { var z6; var mod = k4.andln(ws2 - 1); if (k4.isOdd()) { if (mod > (ws2 >> 1) - 1) z6 = (ws2 >> 1) - mod; else z6 = mod; k4.isubn(z6); } else { z6 = 0; } naf[i4] = z6; k4.iushrn(1); } return naf; } utils.getNAF = getNAF2; function getJSF2(k1, k22) { var jsf = [ [], [] ]; k1 = k1.clone(); k22 = k22.clone(); var d1 = 0; var d22 = 0; var m8; while (k1.cmpn(-d1) > 0 || k22.cmpn(-d22) > 0) { var m14 = k1.andln(3) + d1 & 3; var m24 = k22.andln(3) + d22 & 3; if (m14 === 3) m14 = -1; if (m24 === 3) m24 = -1; var u1; if ((m14 & 1) === 0) { u1 = 0; } else { m8 = k1.andln(7) + d1 & 7; if ((m8 === 3 || m8 === 5) && m24 === 2) u1 = -m14; else u1 = m14; } jsf[0].push(u1); var u22; if ((m24 & 1) === 0) { u22 = 0; } else { m8 = k22.andln(7) + d22 & 7; if ((m8 === 3 || m8 === 5) && m14 === 2) u22 = -m24; else u22 = m24; } jsf[1].push(u22); if (2 * d1 === u1 + 1) d1 = 1 - d1; if (2 * d22 === u22 + 1) d22 = 1 - d22; k1.iushrn(1); k22.iushrn(1); } return jsf; } utils.getJSF = getJSF2; function cachedProperty(obj, name2, computer) { var key2 = "_" + name2; obj.prototype[name2] = function cachedProperty2() { return this[key2] !== void 0 ? this[key2] : this[key2] = computer.call(this); }; } utils.cachedProperty = cachedProperty; function parseBytes(bytes) { return typeof bytes === "string" ? utils.toArray(bytes, "hex") : bytes; } utils.parseBytes = parseBytes; function intFromLE(bytes) { return new import_bn2.default(bytes, "hex", "le"); } utils.intFromLE = intFromLE; }); var getNAF = utils_1$1.getNAF; var getJSF = utils_1$1.getJSF; var assert$1 = utils_1$1.assert; function BaseCurve(type, conf) { this.type = type; this.p = new import_bn2.default(conf.p, 16); this.red = conf.prime ? import_bn2.default.red(conf.prime) : import_bn2.default.mont(this.p); this.zero = new import_bn2.default(0).toRed(this.red); this.one = new import_bn2.default(1).toRed(this.red); this.two = new import_bn2.default(2).toRed(this.red); this.n = conf.n && new import_bn2.default(conf.n, 16); this.g = conf.g && this.pointFromJSON(conf.g, conf.gRed); this._wnafT1 = new Array(4); this._wnafT2 = new Array(4); this._wnafT3 = new Array(4); this._wnafT4 = new Array(4); this._bitLength = this.n ? this.n.bitLength() : 0; var adjustCount = this.n && this.p.div(this.n); if (!adjustCount || adjustCount.cmpn(100) > 0) { this.redN = null; } else { this._maxwellTrick = true; this.redN = this.n.toRed(this.red); } } var base = BaseCurve; BaseCurve.prototype.point = function point() { throw new Error("Not implemented"); }; BaseCurve.prototype.validate = function validate() { throw new Error("Not implemented"); }; BaseCurve.prototype._fixedNafMul = function _fixedNafMul(p3, k4) { assert$1(p3.precomputed); var doubles = p3._getDoubles(); var naf = getNAF(k4, 1, this._bitLength); var I5 = (1 << doubles.step + 1) - (doubles.step % 2 === 0 ? 2 : 1); I5 /= 3; var repr = []; var j2; var nafW; for (j2 = 0; j2 < naf.length; j2 += doubles.step) { nafW = 0; for (var l4 = j2 + doubles.step - 1; l4 >= j2; l4--) nafW = (nafW << 1) + naf[l4]; repr.push(nafW); } var a4 = this.jpoint(null, null, null); var b5 = this.jpoint(null, null, null); for (var i4 = I5; i4 > 0; i4--) { for (j2 = 0; j2 < repr.length; j2++) { nafW = repr[j2]; if (nafW === i4) b5 = b5.mixedAdd(doubles.points[j2]); else if (nafW === -i4) b5 = b5.mixedAdd(doubles.points[j2].neg()); } a4 = a4.add(b5); } return a4.toP(); }; BaseCurve.prototype._wnafMul = function _wnafMul(p3, k4) { var w4 = 4; var nafPoints = p3._getNAFPoints(w4); w4 = nafPoints.wnd; var wnd = nafPoints.points; var naf = getNAF(k4, w4, this._bitLength); var acc = this.jpoint(null, null, null); for (var i4 = naf.length - 1; i4 >= 0; i4--) { for (var l4 = 0; i4 >= 0 && naf[i4] === 0; i4--) l4++; if (i4 >= 0) l4++; acc = acc.dblp(l4); if (i4 < 0) break; var z6 = naf[i4]; assert$1(z6 !== 0); if (p3.type === "affine") { if (z6 > 0) acc = acc.mixedAdd(wnd[z6 - 1 >> 1]); else acc = acc.mixedAdd(wnd[-z6 - 1 >> 1].neg()); } else { if (z6 > 0) acc = acc.add(wnd[z6 - 1 >> 1]); else acc = acc.add(wnd[-z6 - 1 >> 1].neg()); } } return p3.type === "affine" ? acc.toP() : acc; }; BaseCurve.prototype._wnafMulAdd = function _wnafMulAdd(defW, points, coeffs, len, jacobianResult) { var wndWidth = this._wnafT1; var wnd = this._wnafT2; var naf = this._wnafT3; var max = 0; var i4; var j2; var p3; for (i4 = 0; i4 < len; i4++) { p3 = points[i4]; var nafPoints = p3._getNAFPoints(defW); wndWidth[i4] = nafPoints.wnd; wnd[i4] = nafPoints.points; } for (i4 = len - 1; i4 >= 1; i4 -= 2) { var a4 = i4 - 1; var b5 = i4; if (wndWidth[a4] !== 1 || wndWidth[b5] !== 1) { naf[a4] = getNAF(coeffs[a4], wndWidth[a4], this._bitLength); naf[b5] = getNAF(coeffs[b5], wndWidth[b5], this._bitLength); max = Math.max(naf[a4].length, max); max = Math.max(naf[b5].length, max); continue; } var comb = [ points[a4], /* 1 */ null, /* 3 */ null, /* 5 */ points[b5] /* 7 */ ]; if (points[a4].y.cmp(points[b5].y) === 0) { comb[1] = points[a4].add(points[b5]); comb[2] = points[a4].toJ().mixedAdd(points[b5].neg()); } else if (points[a4].y.cmp(points[b5].y.redNeg()) === 0) { comb[1] = points[a4].toJ().mixedAdd(points[b5]); comb[2] = points[a4].add(points[b5].neg()); } else { comb[1] = points[a4].toJ().mixedAdd(points[b5]); comb[2] = points[a4].toJ().mixedAdd(points[b5].neg()); } var index = [ -3, /* -1 -1 */ -1, /* -1 0 */ -5, /* -1 1 */ -7, /* 0 -1 */ 0, /* 0 0 */ 7, /* 0 1 */ 5, /* 1 -1 */ 1, /* 1 0 */ 3 /* 1 1 */ ]; var jsf = getJSF(coeffs[a4], coeffs[b5]); max = Math.max(jsf[0].length, max); naf[a4] = new Array(max); naf[b5] = new Array(max); for (j2 = 0; j2 < max; j2++) { var ja = jsf[0][j2] | 0; var jb = jsf[1][j2] | 0; naf[a4][j2] = index[(ja + 1) * 3 + (jb + 1)]; naf[b5][j2] = 0; wnd[a4] = comb; } } var acc = this.jpoint(null, null, null); var tmp = this._wnafT4; for (i4 = max; i4 >= 0; i4--) { var k4 = 0; while (i4 >= 0) { var zero = true; for (j2 = 0; j2 < len; j2++) { tmp[j2] = naf[j2][i4] | 0; if (tmp[j2] !== 0) zero = false; } if (!zero) break; k4++; i4--; } if (i4 >= 0) k4++; acc = acc.dblp(k4); if (i4 < 0) break; for (j2 = 0; j2 < len; j2++) { var z6 = tmp[j2]; p3; if (z6 === 0) continue; else if (z6 > 0) p3 = wnd[j2][z6 - 1 >> 1]; else if (z6 < 0) p3 = wnd[j2][-z6 - 1 >> 1].neg(); if (p3.type === "affine") acc = acc.mixedAdd(p3); else acc = acc.add(p3); } } for (i4 = 0; i4 < len; i4++) wnd[i4] = null; if (jacobianResult) return acc; else return acc.toP(); }; function BasePoint(curve, type) { this.curve = curve; this.type = type; this.precomputed = null; } BaseCurve.BasePoint = BasePoint; BasePoint.prototype.eq = function eq() { throw new Error("Not implemented"); }; BasePoint.prototype.validate = function validate2() { return this.curve.validate(this); }; BaseCurve.prototype.decodePoint = function decodePoint(bytes, enc) { bytes = utils_1$1.toArray(bytes, enc); var len = this.p.byteLength(); if ((bytes[0] === 4 || bytes[0] === 6 || bytes[0] === 7) && bytes.length - 1 === 2 * len) { if (bytes[0] === 6) assert$1(bytes[bytes.length - 1] % 2 === 0); else if (bytes[0] === 7) assert$1(bytes[bytes.length - 1] % 2 === 1); var res = this.point( bytes.slice(1, 1 + len), bytes.slice(1 + len, 1 + 2 * len) ); return res; } else if ((bytes[0] === 2 || bytes[0] === 3) && bytes.length - 1 === len) { return this.pointFromX(bytes.slice(1, 1 + len), bytes[0] === 3); } throw new Error("Unknown point format"); }; BasePoint.prototype.encodeCompressed = function encodeCompressed(enc) { return this.encode(enc, true); }; BasePoint.prototype._encode = function _encode(compact) { var len = this.curve.p.byteLength(); var x6 = this.getX().toArray("be", len); if (compact) return [this.getY().isEven() ? 2 : 3].concat(x6); return [4].concat(x6, this.getY().toArray("be", len)); }; BasePoint.prototype.encode = function encode3(enc, compact) { return utils_1$1.encode(this._encode(compact), enc); }; BasePoint.prototype.precompute = function precompute(power) { if (this.precomputed) return this; var precomputed = { doubles: null, naf: null, beta: null }; precomputed.naf = this._getNAFPoints(8); precomputed.doubles = this._getDoubles(4, power); precomputed.beta = this._getBeta(); this.precomputed = precomputed; return this; }; BasePoint.prototype._hasDoubles = function _hasDoubles(k4) { if (!this.precomputed) return false; var doubles = this.precomputed.doubles; if (!doubles) return false; return doubles.points.length >= Math.ceil((k4.bitLength() + 1) / doubles.step); }; BasePoint.prototype._getDoubles = function _getDoubles(step, power) { if (this.precomputed && this.precomputed.doubles) return this.precomputed.doubles; var doubles = [this]; var acc = this; for (var i4 = 0; i4 < power; i4 += step) { for (var j2 = 0; j2 < step; j2++) acc = acc.dbl(); doubles.push(acc); } return { step, points: doubles }; }; BasePoint.prototype._getNAFPoints = function _getNAFPoints(wnd) { if (this.precomputed && this.precomputed.naf) return this.precomputed.naf; var res = [this]; var max = (1 << wnd) - 1; var dbl3 = max === 1 ? null : this.dbl(); for (var i4 = 1; i4 < max; i4++) res[i4] = res[i4 - 1].add(dbl3); return { wnd, points: res }; }; BasePoint.prototype._getBeta = function _getBeta() { return null; }; BasePoint.prototype.dblp = function dblp(k4) { var r4 = this; for (var i4 = 0; i4 < k4; i4++) r4 = r4.dbl(); return r4; }; var inherits_browser = createCommonjsModule(function(module) { if (typeof Object.create === "function") { module.exports = function inherits(ctor, superCtor) { if (superCtor) { ctor.super_ = superCtor; ctor.prototype = Object.create(superCtor.prototype, { constructor: { value: ctor, enumerable: false, writable: true, configurable: true } }); } }; } else { module.exports = function inherits(ctor, superCtor) { if (superCtor) { ctor.super_ = superCtor; var TempCtor = function() { }; TempCtor.prototype = superCtor.prototype; ctor.prototype = new TempCtor(); ctor.prototype.constructor = ctor; } }; } }); var assert$2 = utils_1$1.assert; function ShortCurve(conf) { base.call(this, "short", conf); this.a = new import_bn2.default(conf.a, 16).toRed(this.red); this.b = new import_bn2.default(conf.b, 16).toRed(this.red); this.tinv = this.two.redInvm(); this.zeroA = this.a.fromRed().cmpn(0) === 0; this.threeA = this.a.fromRed().sub(this.p).cmpn(-3) === 0; this.endo = this._getEndomorphism(conf); this._endoWnafT1 = new Array(4); this._endoWnafT2 = new Array(4); } inherits_browser(ShortCurve, base); var short_1 = ShortCurve; ShortCurve.prototype._getEndomorphism = function _getEndomorphism(conf) { if (!this.zeroA || !this.g || !this.n || this.p.modn(3) !== 1) return; var beta; var lambda; if (conf.beta) { beta = new import_bn2.default(conf.beta, 16).toRed(this.red); } else { var betas = this._getEndoRoots(this.p); beta = betas[0].cmp(betas[1]) < 0 ? betas[0] : betas[1]; beta = beta.toRed(this.red); } if (conf.lambda) { lambda = new import_bn2.default(conf.lambda, 16); } else { var lambdas = this._getEndoRoots(this.n); if (this.g.mul(lambdas[0]).x.cmp(this.g.x.redMul(beta)) === 0) { lambda = lambdas[0]; } else { lambda = lambdas[1]; assert$2(this.g.mul(lambda).x.cmp(this.g.x.redMul(beta)) === 0); } } var basis; if (conf.basis) { basis = conf.basis.map(function(vec) { return { a: new import_bn2.default(vec.a, 16), b: new import_bn2.default(vec.b, 16) }; }); } else { basis = this._getEndoBasis(lambda); } return { beta, lambda, basis }; }; ShortCurve.prototype._getEndoRoots = function _getEndoRoots(num) { var red = num === this.p ? this.red : import_bn2.default.mont(num); var tinv = new import_bn2.default(2).toRed(red).redInvm(); var ntinv = tinv.redNeg(); var s3 = new import_bn2.default(3).toRed(red).redNeg().redSqrt().redMul(tinv); var l1 = ntinv.redAdd(s3).fromRed(); var l22 = ntinv.redSub(s3).fromRed(); return [l1, l22]; }; ShortCurve.prototype._getEndoBasis = function _getEndoBasis(lambda) { var aprxSqrt = this.n.ushrn(Math.floor(this.n.bitLength() / 2)); var u3 = lambda; var v5 = this.n.clone(); var x1 = new import_bn2.default(1); var y1 = new import_bn2.default(0); var x22 = new import_bn2.default(0); var y22 = new import_bn2.default(1); var a0; var b0; var a1; var b1; var a22; var b22; var prevR; var i4 = 0; var r4; var x6; while (u3.cmpn(0) !== 0) { var q3 = v5.div(u3); r4 = v5.sub(q3.mul(u3)); x6 = x22.sub(q3.mul(x1)); var y6 = y22.sub(q3.mul(y1)); if (!a1 && r4.cmp(aprxSqrt) < 0) { a0 = prevR.neg(); b0 = x1; a1 = r4.neg(); b1 = x6; } else if (a1 && ++i4 === 2) { break; } prevR = r4; v5 = u3; u3 = r4; x22 = x1; x1 = x6; y22 = y1; y1 = y6; } a22 = r4.neg(); b22 = x6; var len1 = a1.sqr().add(b1.sqr()); var len2 = a22.sqr().add(b22.sqr()); if (len2.cmp(len1) >= 0) { a22 = a0; b22 = b0; } if (a1.negative) { a1 = a1.neg(); b1 = b1.neg(); } if (a22.negative) { a22 = a22.neg(); b22 = b22.neg(); } return [ { a: a1, b: b1 }, { a: a22, b: b22 } ]; }; ShortCurve.prototype._endoSplit = function _endoSplit(k4) { var basis = this.endo.basis; var v1 = basis[0]; var v22 = basis[1]; var c1 = v22.b.mul(k4).divRound(this.n); var c22 = v1.b.neg().mul(k4).divRound(this.n); var p1 = c1.mul(v1.a); var p22 = c22.mul(v22.a); var q1 = c1.mul(v1.b); var q22 = c22.mul(v22.b); var k1 = k4.sub(p1).sub(p22); var k22 = q1.add(q22).neg(); return { k1, k2: k22 }; }; ShortCurve.prototype.pointFromX = function pointFromX(x6, odd) { x6 = new import_bn2.default(x6, 16); if (!x6.red) x6 = x6.toRed(this.red); var y22 = x6.redSqr().redMul(x6).redIAdd(x6.redMul(this.a)).redIAdd(this.b); var y6 = y22.redSqrt(); if (y6.redSqr().redSub(y22).cmp(this.zero) !== 0) throw new Error("invalid point"); var isOdd = y6.fromRed().isOdd(); if (odd && !isOdd || !odd && isOdd) y6 = y6.redNeg(); return this.point(x6, y6); }; ShortCurve.prototype.validate = function validate3(point3) { if (point3.inf) return true; var x6 = point3.x; var y6 = point3.y; var ax = this.a.redMul(x6); var rhs = x6.redSqr().redMul(x6).redIAdd(ax).redIAdd(this.b); return y6.redSqr().redISub(rhs).cmpn(0) === 0; }; ShortCurve.prototype._endoWnafMulAdd = function _endoWnafMulAdd(points, coeffs, jacobianResult) { var npoints = this._endoWnafT1; var ncoeffs = this._endoWnafT2; for (var i4 = 0; i4 < points.length; i4++) { var split = this._endoSplit(coeffs[i4]); var p3 = points[i4]; var beta = p3._getBeta(); if (split.k1.negative) { split.k1.ineg(); p3 = p3.neg(true); } if (split.k2.negative) { split.k2.ineg(); beta = beta.neg(true); } npoints[i4 * 2] = p3; npoints[i4 * 2 + 1] = beta; ncoeffs[i4 * 2] = split.k1; ncoeffs[i4 * 2 + 1] = split.k2; } var res = this._wnafMulAdd(1, npoints, ncoeffs, i4 * 2, jacobianResult); for (var j2 = 0; j2 < i4 * 2; j2++) { npoints[j2] = null; ncoeffs[j2] = null; } return res; }; function Point(curve, x6, y6, isRed) { base.BasePoint.call(this, curve, "affine"); if (x6 === null && y6 === null) { this.x = null; this.y = null; this.inf = true; } else { this.x = new import_bn2.default(x6, 16); this.y = new import_bn2.default(y6, 16); if (isRed) { this.x.forceRed(this.curve.red); this.y.forceRed(this.curve.red); } if (!this.x.red) this.x = this.x.toRed(this.curve.red); if (!this.y.red) this.y = this.y.toRed(this.curve.red); this.inf = false; } } inherits_browser(Point, base.BasePoint); ShortCurve.prototype.point = function point2(x6, y6, isRed) { return new Point(this, x6, y6, isRed); }; ShortCurve.prototype.pointFromJSON = function pointFromJSON(obj, red) { return Point.fromJSON(this, obj, red); }; Point.prototype._getBeta = function _getBeta2() { if (!this.curve.endo) return; var pre = this.precomputed; if (pre && pre.beta) return pre.beta; var beta = this.curve.point(this.x.redMul(this.curve.endo.beta), this.y); if (pre) { var curve = this.curve; var endoMul = function(p3) { return curve.point(p3.x.redMul(curve.endo.beta), p3.y); }; pre.beta = beta; beta.precomputed = { beta: null, naf: pre.naf && { wnd: pre.naf.wnd, points: pre.naf.points.map(endoMul) }, doubles: pre.doubles && { step: pre.doubles.step, points: pre.doubles.points.map(endoMul) } }; } return beta; }; Point.prototype.toJSON = function toJSON() { if (!this.precomputed) return [this.x, this.y]; return [this.x, this.y, this.precomputed && { doubles: this.precomputed.doubles && { step: this.precomputed.doubles.step, points: this.precomputed.doubles.points.slice(1) }, naf: this.precomputed.naf && { wnd: this.precomputed.naf.wnd, points: this.precomputed.naf.points.slice(1) } }]; }; Point.fromJSON = function fromJSON(curve, obj, red) { if (typeof obj === "string") obj = JSON.parse(obj); var res = curve.point(obj[0], obj[1], red); if (!obj[2]) return res; function obj2point(obj2) { return curve.point(obj2[0], obj2[1], red); } var pre = obj[2]; res.precomputed = { beta: null, doubles: pre.doubles && { step: pre.doubles.step, points: [res].concat(pre.doubles.points.map(obj2point)) }, naf: pre.naf && { wnd: pre.naf.wnd, points: [res].concat(pre.naf.points.map(obj2point)) } }; return res; }; Point.prototype.inspect = function inspect() { if (this.isInfinity()) return ""; return ""; }; Point.prototype.isInfinity = function isInfinity() { return this.inf; }; Point.prototype.add = function add(p3) { if (this.inf) return p3; if (p3.inf) return this; if (this.eq(p3)) return this.dbl(); if (this.neg().eq(p3)) return this.curve.point(null, null); if (this.x.cmp(p3.x) === 0) return this.curve.point(null, null); var c5 = this.y.redSub(p3.y); if (c5.cmpn(0) !== 0) c5 = c5.redMul(this.x.redSub(p3.x).redInvm()); var nx = c5.redSqr().redISub(this.x).redISub(p3.x); var ny = c5.redMul(this.x.redSub(nx)).redISub(this.y); return this.curve.point(nx, ny); }; Point.prototype.dbl = function dbl() { if (this.inf) return this; var ys1 = this.y.redAdd(this.y); if (ys1.cmpn(0) === 0) return this.curve.point(null, null); var a4 = this.curve.a; var x22 = this.x.redSqr(); var dyinv = ys1.redInvm(); var c5 = x22.redAdd(x22).redIAdd(x22).redIAdd(a4).redMul(dyinv); var nx = c5.redSqr().redISub(this.x.redAdd(this.x)); var ny = c5.redMul(this.x.redSub(nx)).redISub(this.y); return this.curve.point(nx, ny); }; Point.prototype.getX = function getX() { return this.x.fromRed(); }; Point.prototype.getY = function getY() { return this.y.fromRed(); }; Point.prototype.mul = function mul(k4) { k4 = new import_bn2.default(k4, 16); if (this.isInfinity()) return this; else if (this._hasDoubles(k4)) return this.curve._fixedNafMul(this, k4); else if (this.curve.endo) return this.curve._endoWnafMulAdd([this], [k4]); else return this.curve._wnafMul(this, k4); }; Point.prototype.mulAdd = function mulAdd(k1, p22, k22) { var points = [this, p22]; var coeffs = [k1, k22]; if (this.curve.endo) return this.curve._endoWnafMulAdd(points, coeffs); else return this.curve._wnafMulAdd(1, points, coeffs, 2); }; Point.prototype.jmulAdd = function jmulAdd(k1, p22, k22) { var points = [this, p22]; var coeffs = [k1, k22]; if (this.curve.endo) return this.curve._endoWnafMulAdd(points, coeffs, true); else return this.curve._wnafMulAdd(1, points, coeffs, 2, true); }; Point.prototype.eq = function eq2(p3) { return this === p3 || this.inf === p3.inf && (this.inf || this.x.cmp(p3.x) === 0 && this.y.cmp(p3.y) === 0); }; Point.prototype.neg = function neg(_precompute) { if (this.inf) return this; var res = this.curve.point(this.x, this.y.redNeg()); if (_precompute && this.precomputed) { var pre = this.precomputed; var negate = function(p3) { return p3.neg(); }; res.precomputed = { naf: pre.naf && { wnd: pre.naf.wnd, points: pre.naf.points.map(negate) }, doubles: pre.doubles && { step: pre.doubles.step, points: pre.doubles.points.map(negate) } }; } return res; }; Point.prototype.toJ = function toJ() { if (this.inf) return this.curve.jpoint(null, null, null); var res = this.curve.jpoint(this.x, this.y, this.curve.one); return res; }; function JPoint(curve, x6, y6, z6) { base.BasePoint.call(this, curve, "jacobian"); if (x6 === null && y6 === null && z6 === null) { this.x = this.curve.one; this.y = this.curve.one; this.z = new import_bn2.default(0); } else { this.x = new import_bn2.default(x6, 16); this.y = new import_bn2.default(y6, 16); this.z = new import_bn2.default(z6, 16); } if (!this.x.red) this.x = this.x.toRed(this.curve.red); if (!this.y.red) this.y = this.y.toRed(this.curve.red); if (!this.z.red) this.z = this.z.toRed(this.curve.red); this.zOne = this.z === this.curve.one; } inherits_browser(JPoint, base.BasePoint); ShortCurve.prototype.jpoint = function jpoint(x6, y6, z6) { return new JPoint(this, x6, y6, z6); }; JPoint.prototype.toP = function toP() { if (this.isInfinity()) return this.curve.point(null, null); var zinv = this.z.redInvm(); var zinv2 = zinv.redSqr(); var ax = this.x.redMul(zinv2); var ay = this.y.redMul(zinv2).redMul(zinv); return this.curve.point(ax, ay); }; JPoint.prototype.neg = function neg2() { return this.curve.jpoint(this.x, this.y.redNeg(), this.z); }; JPoint.prototype.add = function add2(p3) { if (this.isInfinity()) return p3; if (p3.isInfinity()) return this; var pz2 = p3.z.redSqr(); var z22 = this.z.redSqr(); var u1 = this.x.redMul(pz2); var u22 = p3.x.redMul(z22); var s1 = this.y.redMul(pz2.redMul(p3.z)); var s22 = p3.y.redMul(z22.redMul(this.z)); var h5 = u1.redSub(u22); var r4 = s1.redSub(s22); if (h5.cmpn(0) === 0) { if (r4.cmpn(0) !== 0) return this.curve.jpoint(null, null, null); else return this.dbl(); } var h22 = h5.redSqr(); var h32 = h22.redMul(h5); var v5 = u1.redMul(h22); var nx = r4.redSqr().redIAdd(h32).redISub(v5).redISub(v5); var ny = r4.redMul(v5.redISub(nx)).redISub(s1.redMul(h32)); var nz = this.z.redMul(p3.z).redMul(h5); return this.curve.jpoint(nx, ny, nz); }; JPoint.prototype.mixedAdd = function mixedAdd(p3) { if (this.isInfinity()) return p3.toJ(); if (p3.isInfinity()) return this; var z22 = this.z.redSqr(); var u1 = this.x; var u22 = p3.x.redMul(z22); var s1 = this.y; var s22 = p3.y.redMul(z22).redMul(this.z); var h5 = u1.redSub(u22); var r4 = s1.redSub(s22); if (h5.cmpn(0) === 0) { if (r4.cmpn(0) !== 0) return this.curve.jpoint(null, null, null); else return this.dbl(); } var h22 = h5.redSqr(); var h32 = h22.redMul(h5); var v5 = u1.redMul(h22); var nx = r4.redSqr().redIAdd(h32).redISub(v5).redISub(v5); var ny = r4.redMul(v5.redISub(nx)).redISub(s1.redMul(h32)); var nz = this.z.redMul(h5); return this.curve.jpoint(nx, ny, nz); }; JPoint.prototype.dblp = function dblp2(pow) { if (pow === 0) return this; if (this.isInfinity()) return this; if (!pow) return this.dbl(); var i4; if (this.curve.zeroA || this.curve.threeA) { var r4 = this; for (i4 = 0; i4 < pow; i4++) r4 = r4.dbl(); return r4; } var a4 = this.curve.a; var tinv = this.curve.tinv; var jx = this.x; var jy = this.y; var jz = this.z; var jz4 = jz.redSqr().redSqr(); var jyd = jy.redAdd(jy); for (i4 = 0; i4 < pow; i4++) { var jx2 = jx.redSqr(); var jyd2 = jyd.redSqr(); var jyd4 = jyd2.redSqr(); var c5 = jx2.redAdd(jx2).redIAdd(jx2).redIAdd(a4.redMul(jz4)); var t1 = jx.redMul(jyd2); var nx = c5.redSqr().redISub(t1.redAdd(t1)); var t2 = t1.redISub(nx); var dny = c5.redMul(t2); dny = dny.redIAdd(dny).redISub(jyd4); var nz = jyd.redMul(jz); if (i4 + 1 < pow) jz4 = jz4.redMul(jyd4); jx = nx; jz = nz; jyd = dny; } return this.curve.jpoint(jx, jyd.redMul(tinv), jz); }; JPoint.prototype.dbl = function dbl2() { if (this.isInfinity()) return this; if (this.curve.zeroA) return this._zeroDbl(); else if (this.curve.threeA) return this._threeDbl(); else return this._dbl(); }; JPoint.prototype._zeroDbl = function _zeroDbl() { var nx; var ny; var nz; if (this.zOne) { var xx = this.x.redSqr(); var yy = this.y.redSqr(); var yyyy = yy.redSqr(); var s3 = this.x.redAdd(yy).redSqr().redISub(xx).redISub(yyyy); s3 = s3.redIAdd(s3); var m2 = xx.redAdd(xx).redIAdd(xx); var t = m2.redSqr().redISub(s3).redISub(s3); var yyyy8 = yyyy.redIAdd(yyyy); yyyy8 = yyyy8.redIAdd(yyyy8); yyyy8 = yyyy8.redIAdd(yyyy8); nx = t; ny = m2.redMul(s3.redISub(t)).redISub(yyyy8); nz = this.y.redAdd(this.y); } else { var a4 = this.x.redSqr(); var b5 = this.y.redSqr(); var c5 = b5.redSqr(); var d3 = this.x.redAdd(b5).redSqr().redISub(a4).redISub(c5); d3 = d3.redIAdd(d3); var e2 = a4.redAdd(a4).redIAdd(a4); var f4 = e2.redSqr(); var c8 = c5.redIAdd(c5); c8 = c8.redIAdd(c8); c8 = c8.redIAdd(c8); nx = f4.redISub(d3).redISub(d3); ny = e2.redMul(d3.redISub(nx)).redISub(c8); nz = this.y.redMul(this.z); nz = nz.redIAdd(nz); } return this.curve.jpoint(nx, ny, nz); }; JPoint.prototype._threeDbl = function _threeDbl() { var nx; var ny; var nz; if (this.zOne) { var xx = this.x.redSqr(); var yy = this.y.redSqr(); var yyyy = yy.redSqr(); var s3 = this.x.redAdd(yy).redSqr().redISub(xx).redISub(yyyy); s3 = s3.redIAdd(s3); var m2 = xx.redAdd(xx).redIAdd(xx).redIAdd(this.curve.a); var t = m2.redSqr().redISub(s3).redISub(s3); nx = t; var yyyy8 = yyyy.redIAdd(yyyy); yyyy8 = yyyy8.redIAdd(yyyy8); yyyy8 = yyyy8.redIAdd(yyyy8); ny = m2.redMul(s3.redISub(t)).redISub(yyyy8); nz = this.y.redAdd(this.y); } else { var delta = this.z.redSqr(); var gamma = this.y.redSqr(); var beta = this.x.redMul(gamma); var alpha = this.x.redSub(delta).redMul(this.x.redAdd(delta)); alpha = alpha.redAdd(alpha).redIAdd(alpha); var beta4 = beta.redIAdd(beta); beta4 = beta4.redIAdd(beta4); var beta8 = beta4.redAdd(beta4); nx = alpha.redSqr().redISub(beta8); nz = this.y.redAdd(this.z).redSqr().redISub(gamma).redISub(delta); var ggamma8 = gamma.redSqr(); ggamma8 = ggamma8.redIAdd(ggamma8); ggamma8 = ggamma8.redIAdd(ggamma8); ggamma8 = ggamma8.redIAdd(ggamma8); ny = alpha.redMul(beta4.redISub(nx)).redISub(ggamma8); } return this.curve.jpoint(nx, ny, nz); }; JPoint.prototype._dbl = function _dbl() { var a4 = this.curve.a; var jx = this.x; var jy = this.y; var jz = this.z; var jz4 = jz.redSqr().redSqr(); var jx2 = jx.redSqr(); var jy2 = jy.redSqr(); var c5 = jx2.redAdd(jx2).redIAdd(jx2).redIAdd(a4.redMul(jz4)); var jxd4 = jx.redAdd(jx); jxd4 = jxd4.redIAdd(jxd4); var t1 = jxd4.redMul(jy2); var nx = c5.redSqr().redISub(t1.redAdd(t1)); var t2 = t1.redISub(nx); var jyd8 = jy2.redSqr(); jyd8 = jyd8.redIAdd(jyd8); jyd8 = jyd8.redIAdd(jyd8); jyd8 = jyd8.redIAdd(jyd8); var ny = c5.redMul(t2).redISub(jyd8); var nz = jy.redAdd(jy).redMul(jz); return this.curve.jpoint(nx, ny, nz); }; JPoint.prototype.trpl = function trpl() { if (!this.curve.zeroA) return this.dbl().add(this); var xx = this.x.redSqr(); var yy = this.y.redSqr(); var zz = this.z.redSqr(); var yyyy = yy.redSqr(); var m2 = xx.redAdd(xx).redIAdd(xx); var mm = m2.redSqr(); var e2 = this.x.redAdd(yy).redSqr().redISub(xx).redISub(yyyy); e2 = e2.redIAdd(e2); e2 = e2.redAdd(e2).redIAdd(e2); e2 = e2.redISub(mm); var ee3 = e2.redSqr(); var t = yyyy.redIAdd(yyyy); t = t.redIAdd(t); t = t.redIAdd(t); t = t.redIAdd(t); var u3 = m2.redIAdd(e2).redSqr().redISub(mm).redISub(ee3).redISub(t); var yyu4 = yy.redMul(u3); yyu4 = yyu4.redIAdd(yyu4); yyu4 = yyu4.redIAdd(yyu4); var nx = this.x.redMul(ee3).redISub(yyu4); nx = nx.redIAdd(nx); nx = nx.redIAdd(nx); var ny = this.y.redMul(u3.redMul(t.redISub(u3)).redISub(e2.redMul(ee3))); ny = ny.redIAdd(ny); ny = ny.redIAdd(ny); ny = ny.redIAdd(ny); var nz = this.z.redAdd(e2).redSqr().redISub(zz).redISub(ee3); return this.curve.jpoint(nx, ny, nz); }; JPoint.prototype.mul = function mul2(k4, kbase) { k4 = new import_bn2.default(k4, kbase); return this.curve._wnafMul(this, k4); }; JPoint.prototype.eq = function eq3(p3) { if (p3.type === "affine") return this.eq(p3.toJ()); if (this === p3) return true; var z22 = this.z.redSqr(); var pz2 = p3.z.redSqr(); if (this.x.redMul(pz2).redISub(p3.x.redMul(z22)).cmpn(0) !== 0) return false; var z32 = z22.redMul(this.z); var pz3 = pz2.redMul(p3.z); return this.y.redMul(pz3).redISub(p3.y.redMul(z32)).cmpn(0) === 0; }; JPoint.prototype.eqXToP = function eqXToP(x6) { var zs2 = this.z.redSqr(); var rx = x6.toRed(this.curve.red).redMul(zs2); if (this.x.cmp(rx) === 0) return true; var xc = x6.clone(); var t = this.curve.redN.redMul(zs2); for (; ; ) { xc.iadd(this.curve.n); if (xc.cmp(this.curve.p) >= 0) return false; rx.redIAdd(t); if (this.x.cmp(rx) === 0) return true; } }; JPoint.prototype.inspect = function inspect2() { if (this.isInfinity()) return ""; return ""; }; JPoint.prototype.isInfinity = function isInfinity2() { return this.z.cmpn(0) === 0; }; var curve_1 = createCommonjsModule(function(module, exports) { "use strict"; var curve = exports; curve.base = base; curve.short = short_1; curve.mont = /*RicMoo:ethers:require(./mont)*/ null; curve.edwards = /*RicMoo:ethers:require(./edwards)*/ null; }); var curves_1 = createCommonjsModule(function(module, exports) { "use strict"; var curves = exports; var assert2 = utils_1$1.assert; function PresetCurve(options) { if (options.type === "short") this.curve = new curve_1.short(options); else if (options.type === "edwards") this.curve = new curve_1.edwards(options); else this.curve = new curve_1.mont(options); this.g = this.curve.g; this.n = this.curve.n; this.hash = options.hash; assert2(this.g.validate(), "Invalid curve"); assert2(this.g.mul(this.n).isInfinity(), "Invalid curve, G*N != O"); } curves.PresetCurve = PresetCurve; function defineCurve(name2, options) { Object.defineProperty(curves, name2, { configurable: true, enumerable: true, get: function() { var curve = new PresetCurve(options); Object.defineProperty(curves, name2, { configurable: true, enumerable: true, value: curve }); return curve; } }); } defineCurve("p192", { type: "short", prime: "p192", p: "ffffffff ffffffff ffffffff fffffffe ffffffff ffffffff", a: "ffffffff ffffffff ffffffff fffffffe ffffffff fffffffc", b: "64210519 e59c80e7 0fa7e9ab 72243049 feb8deec c146b9b1", n: "ffffffff ffffffff ffffffff 99def836 146bc9b1 b4d22831", hash: import_hash.default.sha256, gRed: false, g: [ "188da80e b03090f6 7cbf20eb 43a18800 f4ff0afd 82ff1012", "07192b95 ffc8da78 631011ed 6b24cdd5 73f977a1 1e794811" ] }); defineCurve("p224", { type: "short", prime: "p224", p: "ffffffff ffffffff ffffffff ffffffff 00000000 00000000 00000001", a: "ffffffff ffffffff ffffffff fffffffe ffffffff ffffffff fffffffe", b: "b4050a85 0c04b3ab f5413256 5044b0b7 d7bfd8ba 270b3943 2355ffb4", n: "ffffffff ffffffff ffffffff ffff16a2 e0b8f03e 13dd2945 5c5c2a3d", hash: import_hash.default.sha256, gRed: false, g: [ "b70e0cbd 6bb4bf7f 321390b9 4a03c1d3 56c21122 343280d6 115c1d21", "bd376388 b5f723fb 4c22dfe6 cd4375a0 5a074764 44d58199 85007e34" ] }); defineCurve("p256", { type: "short", prime: null, p: "ffffffff 00000001 00000000 00000000 00000000 ffffffff ffffffff ffffffff", a: "ffffffff 00000001 00000000 00000000 00000000 ffffffff ffffffff fffffffc", b: "5ac635d8 aa3a93e7 b3ebbd55 769886bc 651d06b0 cc53b0f6 3bce3c3e 27d2604b", n: "ffffffff 00000000 ffffffff ffffffff bce6faad a7179e84 f3b9cac2 fc632551", hash: import_hash.default.sha256, gRed: false, g: [ "6b17d1f2 e12c4247 f8bce6e5 63a440f2 77037d81 2deb33a0 f4a13945 d898c296", "4fe342e2 fe1a7f9b 8ee7eb4a 7c0f9e16 2bce3357 6b315ece cbb64068 37bf51f5" ] }); defineCurve("p384", { type: "short", prime: null, p: "ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffe ffffffff 00000000 00000000 ffffffff", a: "ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffe ffffffff 00000000 00000000 fffffffc", b: "b3312fa7 e23ee7e4 988e056b e3f82d19 181d9c6e fe814112 0314088f 5013875a c656398d 8a2ed19d 2a85c8ed d3ec2aef", n: "ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff c7634d81 f4372ddf 581a0db2 48b0a77a ecec196a ccc52973", hash: import_hash.default.sha384, gRed: false, g: [ "aa87ca22 be8b0537 8eb1c71e f320ad74 6e1d3b62 8ba79b98 59f741e0 82542a38 5502f25d bf55296c 3a545e38 72760ab7", "3617de4a 96262c6f 5d9e98bf 9292dc29 f8f41dbd 289a147c e9da3113 b5f0b8c0 0a60b1ce 1d7e819d 7a431d7c 90ea0e5f" ] }); defineCurve("p521", { type: "short", prime: null, p: "000001ff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff", a: "000001ff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffc", b: "00000051 953eb961 8e1c9a1f 929a21a0 b68540ee a2da725b 99b315f3 b8b48991 8ef109e1 56193951 ec7e937b 1652c0bd 3bb1bf07 3573df88 3d2c34f1 ef451fd4 6b503f00", n: "000001ff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffa 51868783 bf2f966b 7fcc0148 f709a5d0 3bb5c9b8 899c47ae bb6fb71e 91386409", hash: import_hash.default.sha512, gRed: false, g: [ "000000c6 858e06b7 0404e9cd 9e3ecb66 2395b442 9c648139 053fb521 f828af60 6b4d3dba a14b5e77 efe75928 fe1dc127 a2ffa8de 3348b3c1 856a429b f97e7e31 c2e5bd66", "00000118 39296a78 9a3bc004 5c8a5fb4 2c7d1bd9 98f54449 579b4468 17afbd17 273e662c 97ee7299 5ef42640 c550b901 3fad0761 353c7086 a272c240 88be9476 9fd16650" ] }); defineCurve("curve25519", { type: "mont", prime: "p25519", p: "7fffffffffffffff ffffffffffffffff ffffffffffffffff ffffffffffffffed", a: "76d06", b: "1", n: "1000000000000000 0000000000000000 14def9dea2f79cd6 5812631a5cf5d3ed", hash: import_hash.default.sha256, gRed: false, g: [ "9" ] }); defineCurve("ed25519", { type: "edwards", prime: "p25519", p: "7fffffffffffffff ffffffffffffffff ffffffffffffffff ffffffffffffffed", a: "-1", c: "1", // -121665 * (121666^(-1)) (mod P) d: "52036cee2b6ffe73 8cc740797779e898 00700a4d4141d8ab 75eb4dca135978a3", n: "1000000000000000 0000000000000000 14def9dea2f79cd6 5812631a5cf5d3ed", hash: import_hash.default.sha256, gRed: false, g: [ "216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51a", // 4/5 "6666666666666666666666666666666666666666666666666666666666666658" ] }); var pre; try { pre = /*RicMoo:ethers:require(./precomputed/secp256k1)*/ null.crash(); } catch (e2) { pre = void 0; } defineCurve("secp256k1", { type: "short", prime: "k256", p: "ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffe fffffc2f", a: "0", b: "7", n: "ffffffff ffffffff ffffffff fffffffe baaedce6 af48a03b bfd25e8c d0364141", h: "1", hash: import_hash.default.sha256, // Precomputed endomorphism beta: "7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee", lambda: "5363ad4cc05c30e0a5261c028812645a122e22ea20816678df02967c1b23bd72", basis: [ { a: "3086d221a7d46bcde86c90e49284eb15", b: "-e4437ed6010e88286f547fa90abfe4c3" }, { a: "114ca50f7a8e2f3f657c1108d9d44cfd8", b: "3086d221a7d46bcde86c90e49284eb15" } ], gRed: false, g: [ "79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798", "483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8", pre ] }); }); function HmacDRBG(options) { if (!(this instanceof HmacDRBG)) return new HmacDRBG(options); this.hash = options.hash; this.predResist = !!options.predResist; this.outLen = this.hash.outSize; this.minEntropy = options.minEntropy || this.hash.hmacStrength; this._reseed = null; this.reseedInterval = null; this.K = null; this.V = null; var entropy = utils_1.toArray(options.entropy, options.entropyEnc || "hex"); var nonce = utils_1.toArray(options.nonce, options.nonceEnc || "hex"); var pers = utils_1.toArray(options.pers, options.persEnc || "hex"); minimalisticAssert( entropy.length >= this.minEntropy / 8, "Not enough entropy. Minimum is: " + this.minEntropy + " bits" ); this._init(entropy, nonce, pers); } var hmacDrbg = HmacDRBG; HmacDRBG.prototype._init = function init(entropy, nonce, pers) { var seed = entropy.concat(nonce).concat(pers); this.K = new Array(this.outLen / 8); this.V = new Array(this.outLen / 8); for (var i4 = 0; i4 < this.V.length; i4++) { this.K[i4] = 0; this.V[i4] = 1; } this._update(seed); this._reseed = 1; this.reseedInterval = 281474976710656; }; HmacDRBG.prototype._hmac = function hmac() { return new import_hash.default.hmac(this.hash, this.K); }; HmacDRBG.prototype._update = function update(seed) { var kmac = this._hmac().update(this.V).update([0]); if (seed) kmac = kmac.update(seed); this.K = kmac.digest(); this.V = this._hmac().update(this.V).digest(); if (!seed) return; this.K = this._hmac().update(this.V).update([1]).update(seed).digest(); this.V = this._hmac().update(this.V).digest(); }; HmacDRBG.prototype.reseed = function reseed(entropy, entropyEnc, add3, addEnc) { if (typeof entropyEnc !== "string") { addEnc = add3; add3 = entropyEnc; entropyEnc = null; } entropy = utils_1.toArray(entropy, entropyEnc); add3 = utils_1.toArray(add3, addEnc); minimalisticAssert( entropy.length >= this.minEntropy / 8, "Not enough entropy. Minimum is: " + this.minEntropy + " bits" ); this._update(entropy.concat(add3 || [])); this._reseed = 1; }; HmacDRBG.prototype.generate = function generate(len, enc, add3, addEnc) { if (this._reseed > this.reseedInterval) throw new Error("Reseed is required"); if (typeof enc !== "string") { addEnc = add3; add3 = enc; enc = null; } if (add3) { add3 = utils_1.toArray(add3, addEnc || "hex"); this._update(add3); } var temp = []; while (temp.length < len) { this.V = this._hmac().update(this.V).digest(); temp = temp.concat(this.V); } var res = temp.slice(0, len); this._update(add3); this._reseed++; return utils_1.encode(res, enc); }; var assert$3 = utils_1$1.assert; function KeyPair(ec2, options) { this.ec = ec2; this.priv = null; this.pub = null; if (options.priv) this._importPrivate(options.priv, options.privEnc); if (options.pub) this._importPublic(options.pub, options.pubEnc); } var key = KeyPair; KeyPair.fromPublic = function fromPublic(ec2, pub, enc) { if (pub instanceof KeyPair) return pub; return new KeyPair(ec2, { pub, pubEnc: enc }); }; KeyPair.fromPrivate = function fromPrivate(ec2, priv, enc) { if (priv instanceof KeyPair) return priv; return new KeyPair(ec2, { priv, privEnc: enc }); }; KeyPair.prototype.validate = function validate4() { var pub = this.getPublic(); if (pub.isInfinity()) return { result: false, reason: "Invalid public key" }; if (!pub.validate()) return { result: false, reason: "Public key is not a point" }; if (!pub.mul(this.ec.curve.n).isInfinity()) return { result: false, reason: "Public key * N != O" }; return { result: true, reason: null }; }; KeyPair.prototype.getPublic = function getPublic(compact, enc) { if (typeof compact === "string") { enc = compact; compact = null; } if (!this.pub) this.pub = this.ec.g.mul(this.priv); if (!enc) return this.pub; return this.pub.encode(enc, compact); }; KeyPair.prototype.getPrivate = function getPrivate(enc) { if (enc === "hex") return this.priv.toString(16, 2); else return this.priv; }; KeyPair.prototype._importPrivate = function _importPrivate(key2, enc) { this.priv = new import_bn2.default(key2, enc || 16); this.priv = this.priv.umod(this.ec.curve.n); }; KeyPair.prototype._importPublic = function _importPublic(key2, enc) { if (key2.x || key2.y) { if (this.ec.curve.type === "mont") { assert$3(key2.x, "Need x coordinate"); } else if (this.ec.curve.type === "short" || this.ec.curve.type === "edwards") { assert$3(key2.x && key2.y, "Need both x and y coordinate"); } this.pub = this.ec.curve.point(key2.x, key2.y); return; } this.pub = this.ec.curve.decodePoint(key2, enc); }; KeyPair.prototype.derive = function derive(pub) { if (!pub.validate()) { assert$3(pub.validate(), "public point not validated"); } return pub.mul(this.priv).getX(); }; KeyPair.prototype.sign = function sign(msg, enc, options) { return this.ec.sign(msg, this, enc, options); }; KeyPair.prototype.verify = function verify(msg, signature2) { return this.ec.verify(msg, signature2, this); }; KeyPair.prototype.inspect = function inspect3() { return ""; }; var assert$4 = utils_1$1.assert; function Signature(options, enc) { if (options instanceof Signature) return options; if (this._importDER(options, enc)) return; assert$4(options.r && options.s, "Signature without r or s"); this.r = new import_bn2.default(options.r, 16); this.s = new import_bn2.default(options.s, 16); if (options.recoveryParam === void 0) this.recoveryParam = null; else this.recoveryParam = options.recoveryParam; } var signature = Signature; function Position() { this.place = 0; } function getLength(buf, p3) { var initial = buf[p3.place++]; if (!(initial & 128)) { return initial; } var octetLen = initial & 15; if (octetLen === 0 || octetLen > 4) { return false; } var val = 0; for (var i4 = 0, off = p3.place; i4 < octetLen; i4++, off++) { val <<= 8; val |= buf[off]; val >>>= 0; } if (val <= 127) { return false; } p3.place = off; return val; } function rmPadding(buf) { var i4 = 0; var len = buf.length - 1; while (!buf[i4] && !(buf[i4 + 1] & 128) && i4 < len) { i4++; } if (i4 === 0) { return buf; } return buf.slice(i4); } Signature.prototype._importDER = function _importDER(data, enc) { data = utils_1$1.toArray(data, enc); var p3 = new Position(); if (data[p3.place++] !== 48) { return false; } var len = getLength(data, p3); if (len === false) { return false; } if (len + p3.place !== data.length) { return false; } if (data[p3.place++] !== 2) { return false; } var rlen = getLength(data, p3); if (rlen === false) { return false; } var r4 = data.slice(p3.place, rlen + p3.place); p3.place += rlen; if (data[p3.place++] !== 2) { return false; } var slen = getLength(data, p3); if (slen === false) { return false; } if (data.length !== slen + p3.place) { return false; } var s3 = data.slice(p3.place, slen + p3.place); if (r4[0] === 0) { if (r4[1] & 128) { r4 = r4.slice(1); } else { return false; } } if (s3[0] === 0) { if (s3[1] & 128) { s3 = s3.slice(1); } else { return false; } } this.r = new import_bn2.default(r4); this.s = new import_bn2.default(s3); this.recoveryParam = null; return true; }; function constructLength(arr, len) { if (len < 128) { arr.push(len); return; } var octets = 1 + (Math.log(len) / Math.LN2 >>> 3); arr.push(octets | 128); while (--octets) { arr.push(len >>> (octets << 3) & 255); } arr.push(len); } Signature.prototype.toDER = function toDER(enc) { var r4 = this.r.toArray(); var s3 = this.s.toArray(); if (r4[0] & 128) r4 = [0].concat(r4); if (s3[0] & 128) s3 = [0].concat(s3); r4 = rmPadding(r4); s3 = rmPadding(s3); while (!s3[0] && !(s3[1] & 128)) { s3 = s3.slice(1); } var arr = [2]; constructLength(arr, r4.length); arr = arr.concat(r4); arr.push(2); constructLength(arr, s3.length); var backHalf = arr.concat(s3); var res = [48]; constructLength(res, backHalf.length); res = res.concat(backHalf); return utils_1$1.encode(res, enc); }; var rand = ( /*RicMoo:ethers:require(brorand)*/ function() { throw new Error("unsupported"); } ); var assert$5 = utils_1$1.assert; function EC(options) { if (!(this instanceof EC)) return new EC(options); if (typeof options === "string") { assert$5( Object.prototype.hasOwnProperty.call(curves_1, options), "Unknown curve " + options ); options = curves_1[options]; } if (options instanceof curves_1.PresetCurve) options = { curve: options }; this.curve = options.curve.curve; this.n = this.curve.n; this.nh = this.n.ushrn(1); this.g = this.curve.g; this.g = options.curve.g; this.g.precompute(options.curve.n.bitLength() + 1); this.hash = options.hash || options.curve.hash; } var ec = EC; EC.prototype.keyPair = function keyPair(options) { return new key(this, options); }; EC.prototype.keyFromPrivate = function keyFromPrivate(priv, enc) { return key.fromPrivate(this, priv, enc); }; EC.prototype.keyFromPublic = function keyFromPublic(pub, enc) { return key.fromPublic(this, pub, enc); }; EC.prototype.genKeyPair = function genKeyPair(options) { if (!options) options = {}; var drbg = new hmacDrbg({ hash: this.hash, pers: options.pers, persEnc: options.persEnc || "utf8", entropy: options.entropy || rand(this.hash.hmacStrength), entropyEnc: options.entropy && options.entropyEnc || "utf8", nonce: this.n.toArray() }); var bytes = this.n.byteLength(); var ns2 = this.n.sub(new import_bn2.default(2)); for (; ; ) { var priv = new import_bn2.default(drbg.generate(bytes)); if (priv.cmp(ns2) > 0) continue; priv.iaddn(1); return this.keyFromPrivate(priv); } }; EC.prototype._truncateToN = function _truncateToN(msg, truncOnly) { var delta = msg.byteLength() * 8 - this.n.bitLength(); if (delta > 0) msg = msg.ushrn(delta); if (!truncOnly && msg.cmp(this.n) >= 0) return msg.sub(this.n); else return msg; }; EC.prototype.sign = function sign2(msg, key2, enc, options) { if (typeof enc === "object") { options = enc; enc = null; } if (!options) options = {}; key2 = this.keyFromPrivate(key2, enc); msg = this._truncateToN(new import_bn2.default(msg, 16)); var bytes = this.n.byteLength(); var bkey = key2.getPrivate().toArray("be", bytes); var nonce = msg.toArray("be", bytes); var drbg = new hmacDrbg({ hash: this.hash, entropy: bkey, nonce, pers: options.pers, persEnc: options.persEnc || "utf8" }); var ns1 = this.n.sub(new import_bn2.default(1)); for (var iter = 0; ; iter++) { var k4 = options.k ? options.k(iter) : new import_bn2.default(drbg.generate(this.n.byteLength())); k4 = this._truncateToN(k4, true); if (k4.cmpn(1) <= 0 || k4.cmp(ns1) >= 0) continue; var kp = this.g.mul(k4); if (kp.isInfinity()) continue; var kpX = kp.getX(); var r4 = kpX.umod(this.n); if (r4.cmpn(0) === 0) continue; var s3 = k4.invm(this.n).mul(r4.mul(key2.getPrivate()).iadd(msg)); s3 = s3.umod(this.n); if (s3.cmpn(0) === 0) continue; var recoveryParam = (kp.getY().isOdd() ? 1 : 0) | (kpX.cmp(r4) !== 0 ? 2 : 0); if (options.canonical && s3.cmp(this.nh) > 0) { s3 = this.n.sub(s3); recoveryParam ^= 1; } return new signature({ r: r4, s: s3, recoveryParam }); } }; EC.prototype.verify = function verify2(msg, signature$1, key2, enc) { msg = this._truncateToN(new import_bn2.default(msg, 16)); key2 = this.keyFromPublic(key2, enc); signature$1 = new signature(signature$1, "hex"); var r4 = signature$1.r; var s3 = signature$1.s; if (r4.cmpn(1) < 0 || r4.cmp(this.n) >= 0) return false; if (s3.cmpn(1) < 0 || s3.cmp(this.n) >= 0) return false; var sinv = s3.invm(this.n); var u1 = sinv.mul(msg).umod(this.n); var u22 = sinv.mul(r4).umod(this.n); var p3; if (!this.curve._maxwellTrick) { p3 = this.g.mulAdd(u1, key2.getPublic(), u22); if (p3.isInfinity()) return false; return p3.getX().umod(this.n).cmp(r4) === 0; } p3 = this.g.jmulAdd(u1, key2.getPublic(), u22); if (p3.isInfinity()) return false; return p3.eqXToP(r4); }; EC.prototype.recoverPubKey = function(msg, signature$1, j2, enc) { assert$5((3 & j2) === j2, "The recovery param is more than two bits"); signature$1 = new signature(signature$1, enc); var n5 = this.n; var e2 = new import_bn2.default(msg); var r4 = signature$1.r; var s3 = signature$1.s; var isYOdd = j2 & 1; var isSecondKey = j2 >> 1; if (r4.cmp(this.curve.p.umod(this.curve.n)) >= 0 && isSecondKey) throw new Error("Unable to find sencond key candinate"); if (isSecondKey) r4 = this.curve.pointFromX(r4.add(this.curve.n), isYOdd); else r4 = this.curve.pointFromX(r4, isYOdd); var rInv = signature$1.r.invm(n5); var s1 = n5.sub(e2).mul(rInv).umod(n5); var s22 = s3.mul(rInv).umod(n5); return this.g.mulAdd(s1, r4, s22); }; EC.prototype.getKeyRecoveryParam = function(e2, signature$1, Q2, enc) { signature$1 = new signature(signature$1, enc); if (signature$1.recoveryParam !== null) return signature$1.recoveryParam; for (var i4 = 0; i4 < 4; i4++) { var Qprime; try { Qprime = this.recoverPubKey(e2, signature$1, i4); } catch (e3) { continue; } if (Qprime.eq(Q2)) return i4; } throw new Error("Unable to find valid recovery factor"); }; var elliptic_1 = createCommonjsModule(function(module, exports) { "use strict"; var elliptic = exports; elliptic.version = /*RicMoo:ethers*/ { version: "6.5.4" }.version; elliptic.utils = utils_1$1; elliptic.rand = /*RicMoo:ethers:require(brorand)*/ function() { throw new Error("unsupported"); }; elliptic.curve = curve_1; elliptic.curves = curves_1; elliptic.ec = ec; elliptic.eddsa = /*RicMoo:ethers:require(./elliptic/eddsa)*/ null; }); var EC$1 = elliptic_1.ec; // node_modules/@ethersproject/signing-key/lib.esm/_version.js var version9 = "signing-key/5.7.0"; // node_modules/@ethersproject/signing-key/lib.esm/index.js var logger10 = new Logger(version9); var _curve = null; function getCurve() { if (!_curve) { _curve = new EC$1("secp256k1"); } return _curve; } var SigningKey = class { constructor(privateKey) { defineReadOnly(this, "curve", "secp256k1"); defineReadOnly(this, "privateKey", hexlify(privateKey)); if (hexDataLength(this.privateKey) !== 32) { logger10.throwArgumentError("invalid private key", "privateKey", "[[ REDACTED ]]"); } const keyPair2 = getCurve().keyFromPrivate(arrayify(this.privateKey)); defineReadOnly(this, "publicKey", "0x" + keyPair2.getPublic(false, "hex")); defineReadOnly(this, "compressedPublicKey", "0x" + keyPair2.getPublic(true, "hex")); defineReadOnly(this, "_isSigningKey", true); } _addPoint(other) { const p0 = getCurve().keyFromPublic(arrayify(this.publicKey)); const p1 = getCurve().keyFromPublic(arrayify(other)); return "0x" + p0.pub.add(p1.pub).encodeCompressed("hex"); } signDigest(digest2) { const keyPair2 = getCurve().keyFromPrivate(arrayify(this.privateKey)); const digestBytes = arrayify(digest2); if (digestBytes.length !== 32) { logger10.throwArgumentError("bad digest length", "digest", digest2); } const signature2 = keyPair2.sign(digestBytes, { canonical: true }); return splitSignature({ recoveryParam: signature2.recoveryParam, r: hexZeroPad("0x" + signature2.r.toString(16), 32), s: hexZeroPad("0x" + signature2.s.toString(16), 32) }); } computeSharedSecret(otherKey) { const keyPair2 = getCurve().keyFromPrivate(arrayify(this.privateKey)); const otherKeyPair = getCurve().keyFromPublic(arrayify(computePublicKey(otherKey))); return hexZeroPad("0x" + keyPair2.derive(otherKeyPair.getPublic()).toString(16), 32); } static isSigningKey(value) { return !!(value && value._isSigningKey); } }; function recoverPublicKey(digest2, signature2) { const sig = splitSignature(signature2); const rs = { r: arrayify(sig.r), s: arrayify(sig.s) }; return "0x" + getCurve().recoverPubKey(arrayify(digest2), rs, sig.recoveryParam).encode("hex", false); } function computePublicKey(key2, compressed) { const bytes = arrayify(key2); if (bytes.length === 32) { const signingKey = new SigningKey(bytes); if (compressed) { return "0x" + getCurve().keyFromPrivate(bytes).getPublic(true, "hex"); } return signingKey.publicKey; } else if (bytes.length === 33) { if (compressed) { return hexlify(bytes); } return "0x" + getCurve().keyFromPublic(bytes).getPublic(false, "hex"); } else if (bytes.length === 65) { if (!compressed) { return hexlify(bytes); } return "0x" + getCurve().keyFromPublic(bytes).getPublic(true, "hex"); } return logger10.throwArgumentError("invalid public or private key", "key", "[REDACTED]"); } // node_modules/@ethersproject/transactions/lib.esm/_version.js var version10 = "transactions/5.7.0"; // node_modules/@ethersproject/transactions/lib.esm/index.js var logger11 = new Logger(version10); var TransactionTypes; (function(TransactionTypes2) { TransactionTypes2[TransactionTypes2["legacy"] = 0] = "legacy"; TransactionTypes2[TransactionTypes2["eip2930"] = 1] = "eip2930"; TransactionTypes2[TransactionTypes2["eip1559"] = 2] = "eip1559"; })(TransactionTypes || (TransactionTypes = {})); function computeAddress(key2) { const publicKey = computePublicKey(key2); return getAddress(hexDataSlice(keccak256(hexDataSlice(publicKey, 1)), 12)); } function recoverAddress(digest2, signature2) { return computeAddress(recoverPublicKey(arrayify(digest2), signature2)); } // node_modules/@walletconnect/utils/dist/index.es.js var import_chacha20poly1305 = __toESM(require_chacha20poly1305()); var import_hkdf = __toESM(require_hkdf()); var import_random2 = __toESM(require_random()); var import_sha256 = __toESM(require_sha256()); var _e = __toESM(require_x25519()); // node_modules/uint8arrays/esm/src/alloc.js function allocUnsafe(size = 0) { if (globalThis.Buffer != null && globalThis.Buffer.allocUnsafe != null) { return globalThis.Buffer.allocUnsafe(size); } return new Uint8Array(size); } // node_modules/uint8arrays/esm/src/concat.js function concat2(arrays, length2) { if (!length2) { length2 = arrays.reduce((acc, curr) => acc + curr.length, 0); } const output = allocUnsafe(length2); let offset = 0; for (const arr of arrays) { output.set(arr, offset); offset += arr.length; } return output; } // node_modules/multiformats/esm/src/bases/identity.js var identity_exports = {}; __export(identity_exports, { identity: () => identity }); // node_modules/multiformats/esm/vendor/base-x.js function base2(ALPHABET, name2) { if (ALPHABET.length >= 255) { throw new TypeError("Alphabet too long"); } var BASE_MAP = new Uint8Array(256); for (var j2 = 0; j2 < BASE_MAP.length; j2++) { BASE_MAP[j2] = 255; } for (var i4 = 0; i4 < ALPHABET.length; i4++) { var x6 = ALPHABET.charAt(i4); var xc = x6.charCodeAt(0); if (BASE_MAP[xc] !== 255) { throw new TypeError(x6 + " is ambiguous"); } BASE_MAP[xc] = i4; } var BASE = ALPHABET.length; var LEADER = ALPHABET.charAt(0); var FACTOR = Math.log(BASE) / Math.log(256); var iFACTOR = Math.log(256) / Math.log(BASE); function encode8(source) { if (source instanceof Uint8Array) ; else if (ArrayBuffer.isView(source)) { source = new Uint8Array(source.buffer, source.byteOffset, source.byteLength); } else if (Array.isArray(source)) { source = Uint8Array.from(source); } if (!(source instanceof Uint8Array)) { throw new TypeError("Expected Uint8Array"); } if (source.length === 0) { return ""; } var zeroes = 0; var length2 = 0; var pbegin = 0; var pend = source.length; while (pbegin !== pend && source[pbegin] === 0) { pbegin++; zeroes++; } var size = (pend - pbegin) * iFACTOR + 1 >>> 0; var b58 = new Uint8Array(size); while (pbegin !== pend) { var carry = source[pbegin]; var i5 = 0; for (var it1 = size - 1; (carry !== 0 || i5 < length2) && it1 !== -1; it1--, i5++) { carry += 256 * b58[it1] >>> 0; b58[it1] = carry % BASE >>> 0; carry = carry / BASE >>> 0; } if (carry !== 0) { throw new Error("Non-zero carry"); } length2 = i5; pbegin++; } var it22 = size - length2; while (it22 !== size && b58[it22] === 0) { it22++; } var str = LEADER.repeat(zeroes); for (; it22 < size; ++it22) { str += ALPHABET.charAt(b58[it22]); } return str; } function decodeUnsafe(source) { if (typeof source !== "string") { throw new TypeError("Expected String"); } if (source.length === 0) { return new Uint8Array(); } var psz = 0; if (source[psz] === " ") { return; } var zeroes = 0; var length2 = 0; while (source[psz] === LEADER) { zeroes++; psz++; } var size = (source.length - psz) * FACTOR + 1 >>> 0; var b256 = new Uint8Array(size); while (source[psz]) { var carry = BASE_MAP[source.charCodeAt(psz)]; if (carry === 255) { return; } var i5 = 0; for (var it32 = size - 1; (carry !== 0 || i5 < length2) && it32 !== -1; it32--, i5++) { carry += BASE * b256[it32] >>> 0; b256[it32] = carry % 256 >>> 0; carry = carry / 256 >>> 0; } if (carry !== 0) { throw new Error("Non-zero carry"); } length2 = i5; psz++; } if (source[psz] === " ") { return; } var it4 = size - length2; while (it4 !== size && b256[it4] === 0) { it4++; } var vch = new Uint8Array(zeroes + (size - it4)); var j3 = zeroes; while (it4 !== size) { vch[j3++] = b256[it4++]; } return vch; } function decode8(string2) { var buffer = decodeUnsafe(string2); if (buffer) { return buffer; } throw new Error(`Non-${name2} character`); } return { encode: encode8, decodeUnsafe, decode: decode8 }; } var src = base2; var _brrp__multiformats_scope_baseX = src; var base_x_default = _brrp__multiformats_scope_baseX; // node_modules/multiformats/esm/src/bytes.js var empty = new Uint8Array(0); var equals = (aa, bb) => { if (aa === bb) return true; if (aa.byteLength !== bb.byteLength) { return false; } for (let ii2 = 0; ii2 < aa.byteLength; ii2++) { if (aa[ii2] !== bb[ii2]) { return false; } } return true; }; var coerce = (o4) => { if (o4 instanceof Uint8Array && o4.constructor.name === "Uint8Array") return o4; if (o4 instanceof ArrayBuffer) return new Uint8Array(o4); if (ArrayBuffer.isView(o4)) { return new Uint8Array(o4.buffer, o4.byteOffset, o4.byteLength); } throw new Error("Unknown type, must be binary type"); }; var fromString = (str) => new TextEncoder().encode(str); var toString = (b5) => new TextDecoder().decode(b5); // node_modules/multiformats/esm/src/bases/base.js var Encoder = class { constructor(name2, prefix, baseEncode) { this.name = name2; this.prefix = prefix; this.baseEncode = baseEncode; } encode(bytes) { if (bytes instanceof Uint8Array) { return `${this.prefix}${this.baseEncode(bytes)}`; } else { throw Error("Unknown type, must be binary type"); } } }; var Decoder = class { constructor(name2, prefix, baseDecode) { this.name = name2; this.prefix = prefix; if (prefix.codePointAt(0) === void 0) { throw new Error("Invalid prefix character"); } this.prefixCodePoint = prefix.codePointAt(0); this.baseDecode = baseDecode; } decode(text) { if (typeof text === "string") { if (text.codePointAt(0) !== this.prefixCodePoint) { throw Error(`Unable to decode multibase string ${JSON.stringify(text)}, ${this.name} decoder only supports inputs prefixed with ${this.prefix}`); } return this.baseDecode(text.slice(this.prefix.length)); } else { throw Error("Can only multibase decode strings"); } } or(decoder) { return or(this, decoder); } }; var ComposedDecoder = class { constructor(decoders) { this.decoders = decoders; } or(decoder) { return or(this, decoder); } decode(input) { const prefix = input[0]; const decoder = this.decoders[prefix]; if (decoder) { return decoder.decode(input); } else { throw RangeError(`Unable to decode multibase string ${JSON.stringify(input)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`); } } }; var or = (left, right) => new ComposedDecoder({ ...left.decoders || { [left.prefix]: left }, ...right.decoders || { [right.prefix]: right } }); var Codec = class { constructor(name2, prefix, baseEncode, baseDecode) { this.name = name2; this.prefix = prefix; this.baseEncode = baseEncode; this.baseDecode = baseDecode; this.encoder = new Encoder(name2, prefix, baseEncode); this.decoder = new Decoder(name2, prefix, baseDecode); } encode(input) { return this.encoder.encode(input); } decode(input) { return this.decoder.decode(input); } }; var from = ({ name: name2, prefix, encode: encode8, decode: decode8 }) => new Codec(name2, prefix, encode8, decode8); var baseX = ({ prefix, name: name2, alphabet: alphabet2 }) => { const { encode: encode8, decode: decode8 } = base_x_default(alphabet2, name2); return from({ prefix, name: name2, encode: encode8, decode: (text) => coerce(decode8(text)) }); }; var decode3 = (string2, alphabet2, bitsPerChar, name2) => { const codes = {}; for (let i4 = 0; i4 < alphabet2.length; ++i4) { codes[alphabet2[i4]] = i4; } let end = string2.length; while (string2[end - 1] === "=") { --end; } const out = new Uint8Array(end * bitsPerChar / 8 | 0); let bits = 0; let buffer = 0; let written = 0; for (let i4 = 0; i4 < end; ++i4) { const value = codes[string2[i4]]; if (value === void 0) { throw new SyntaxError(`Non-${name2} character`); } buffer = buffer << bitsPerChar | value; bits += bitsPerChar; if (bits >= 8) { bits -= 8; out[written++] = 255 & buffer >> bits; } } if (bits >= bitsPerChar || 255 & buffer << 8 - bits) { throw new SyntaxError("Unexpected end of data"); } return out; }; var encode4 = (data, alphabet2, bitsPerChar) => { const pad = alphabet2[alphabet2.length - 1] === "="; const mask = (1 << bitsPerChar) - 1; let out = ""; let bits = 0; let buffer = 0; for (let i4 = 0; i4 < data.length; ++i4) { buffer = buffer << 8 | data[i4]; bits += 8; while (bits > bitsPerChar) { bits -= bitsPerChar; out += alphabet2[mask & buffer >> bits]; } } if (bits) { out += alphabet2[mask & buffer << bitsPerChar - bits]; } if (pad) { while (out.length * bitsPerChar & 7) { out += "="; } } return out; }; var rfc4648 = ({ name: name2, prefix, bitsPerChar, alphabet: alphabet2 }) => { return from({ prefix, name: name2, encode(input) { return encode4(input, alphabet2, bitsPerChar); }, decode(input) { return decode3(input, alphabet2, bitsPerChar, name2); } }); }; // node_modules/multiformats/esm/src/bases/identity.js var identity = from({ prefix: "\0", name: "identity", encode: (buf) => toString(buf), decode: (str) => fromString(str) }); // node_modules/multiformats/esm/src/bases/base2.js var base2_exports = {}; __export(base2_exports, { base2: () => base22 }); var base22 = rfc4648({ prefix: "0", name: "base2", alphabet: "01", bitsPerChar: 1 }); // node_modules/multiformats/esm/src/bases/base8.js var base8_exports = {}; __export(base8_exports, { base8: () => base8 }); var base8 = rfc4648({ prefix: "7", name: "base8", alphabet: "01234567", bitsPerChar: 3 }); // node_modules/multiformats/esm/src/bases/base10.js var base10_exports = {}; __export(base10_exports, { base10: () => base10 }); var base10 = baseX({ prefix: "9", name: "base10", alphabet: "0123456789" }); // node_modules/multiformats/esm/src/bases/base16.js var base16_exports = {}; __export(base16_exports, { base16: () => base16, base16upper: () => base16upper }); var base16 = rfc4648({ prefix: "f", name: "base16", alphabet: "0123456789abcdef", bitsPerChar: 4 }); var base16upper = rfc4648({ prefix: "F", name: "base16upper", alphabet: "0123456789ABCDEF", bitsPerChar: 4 }); // node_modules/multiformats/esm/src/bases/base32.js var base32_exports = {}; __export(base32_exports, { base32: () => base32, base32hex: () => base32hex, base32hexpad: () => base32hexpad, base32hexpadupper: () => base32hexpadupper, base32hexupper: () => base32hexupper, base32pad: () => base32pad, base32padupper: () => base32padupper, base32upper: () => base32upper, base32z: () => base32z }); var base32 = rfc4648({ prefix: "b", name: "base32", alphabet: "abcdefghijklmnopqrstuvwxyz234567", bitsPerChar: 5 }); var base32upper = rfc4648({ prefix: "B", name: "base32upper", alphabet: "ABCDEFGHIJKLMNOPQRSTUVWXYZ234567", bitsPerChar: 5 }); var base32pad = rfc4648({ prefix: "c", name: "base32pad", alphabet: "abcdefghijklmnopqrstuvwxyz234567=", bitsPerChar: 5 }); var base32padupper = rfc4648({ prefix: "C", name: "base32padupper", alphabet: "ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=", bitsPerChar: 5 }); var base32hex = rfc4648({ prefix: "v", name: "base32hex", alphabet: "0123456789abcdefghijklmnopqrstuv", bitsPerChar: 5 }); var base32hexupper = rfc4648({ prefix: "V", name: "base32hexupper", alphabet: "0123456789ABCDEFGHIJKLMNOPQRSTUV", bitsPerChar: 5 }); var base32hexpad = rfc4648({ prefix: "t", name: "base32hexpad", alphabet: "0123456789abcdefghijklmnopqrstuv=", bitsPerChar: 5 }); var base32hexpadupper = rfc4648({ prefix: "T", name: "base32hexpadupper", alphabet: "0123456789ABCDEFGHIJKLMNOPQRSTUV=", bitsPerChar: 5 }); var base32z = rfc4648({ prefix: "h", name: "base32z", alphabet: "ybndrfg8ejkmcpqxot1uwisza345h769", bitsPerChar: 5 }); // node_modules/multiformats/esm/src/bases/base36.js var base36_exports = {}; __export(base36_exports, { base36: () => base36, base36upper: () => base36upper }); var base36 = baseX({ prefix: "k", name: "base36", alphabet: "0123456789abcdefghijklmnopqrstuvwxyz" }); var base36upper = baseX({ prefix: "K", name: "base36upper", alphabet: "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ" }); // node_modules/multiformats/esm/src/bases/base58.js var base58_exports = {}; __export(base58_exports, { base58btc: () => base58btc, base58flickr: () => base58flickr }); var base58btc = baseX({ name: "base58btc", prefix: "z", alphabet: "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz" }); var base58flickr = baseX({ name: "base58flickr", prefix: "Z", alphabet: "123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ" }); // node_modules/multiformats/esm/src/bases/base64.js var base64_exports = {}; __export(base64_exports, { base64: () => base64, base64pad: () => base64pad, base64url: () => base64url, base64urlpad: () => base64urlpad }); var base64 = rfc4648({ prefix: "m", name: "base64", alphabet: "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/", bitsPerChar: 6 }); var base64pad = rfc4648({ prefix: "M", name: "base64pad", alphabet: "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=", bitsPerChar: 6 }); var base64url = rfc4648({ prefix: "u", name: "base64url", alphabet: "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_", bitsPerChar: 6 }); var base64urlpad = rfc4648({ prefix: "U", name: "base64urlpad", alphabet: "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=", bitsPerChar: 6 }); // node_modules/multiformats/esm/src/bases/base256emoji.js var base256emoji_exports = {}; __export(base256emoji_exports, { base256emoji: () => base256emoji }); var alphabet = Array.from("🚀🪐☄🛰🌌🌑🌒🌓🌔🌕🌖🌗🌘🌍🌏🌎🐉☀💻🖥💾💿😂❤😍🤣😊🙏💕😭😘👍😅👏😁🔥🥰💔💖💙😢🤔😆🙄💪😉☺👌🤗💜😔😎😇🌹🤦🎉💞✌✨🤷😱😌🌸🙌😋💗💚😏💛🙂💓🤩😄😀🖤😃💯🙈👇🎶😒🤭❣😜💋👀😪😑💥🙋😞😩😡🤪👊🥳😥🤤👉💃😳✋😚😝😴🌟😬🙃🍀🌷😻😓⭐✅🥺🌈😈🤘💦✔😣🏃💐☹🎊💘😠☝😕🌺🎂🌻😐🖕💝🙊😹🗣💫💀👑🎵🤞😛🔴😤🌼😫⚽🤙☕🏆🤫👈😮🙆🍻🍃🐶💁😲🌿🧡🎁⚡🌞🎈❌✊👋😰🤨😶🤝🚶💰🍓💢🤟🙁🚨💨🤬✈🎀🍺🤓😙💟🌱😖👶🥴▶➡❓💎💸⬇😨🌚🦋😷🕺⚠🙅😟😵👎🤲🤠🤧📌🔵💅🧐🐾🍒😗🤑🌊🤯🐷☎💧😯💆👆🎤🙇🍑❄🌴💣🐸💌📍🥀🤢👅💡💩👐📸👻🤐🤮🎼🥵🚩🍎🍊👼💍📣🥂"); var alphabetBytesToChars = alphabet.reduce((p3, c5, i4) => { p3[i4] = c5; return p3; }, []); var alphabetCharsToBytes = alphabet.reduce((p3, c5, i4) => { p3[c5.codePointAt(0)] = i4; return p3; }, []); function encode5(data) { return data.reduce((p3, c5) => { p3 += alphabetBytesToChars[c5]; return p3; }, ""); } function decode4(str) { const byts = []; for (const char of str) { const byt = alphabetCharsToBytes[char.codePointAt(0)]; if (byt === void 0) { throw new Error(`Non-base256emoji character: ${char}`); } byts.push(byt); } return new Uint8Array(byts); } var base256emoji = from({ prefix: "🚀", name: "base256emoji", encode: encode5, decode: decode4 }); // node_modules/multiformats/esm/src/hashes/sha2-browser.js var sha2_browser_exports = {}; __export(sha2_browser_exports, { sha256: () => sha256, sha512: () => sha512 }); // node_modules/multiformats/esm/vendor/varint.js var encode_1 = encode6; var MSB = 128; var REST = 127; var MSBALL = ~REST; var INT = Math.pow(2, 31); function encode6(num, out, offset) { out = out || []; offset = offset || 0; var oldOffset = offset; while (num >= INT) { out[offset++] = num & 255 | MSB; num /= 128; } while (num & MSBALL) { out[offset++] = num & 255 | MSB; num >>>= 7; } out[offset] = num | 0; encode6.bytes = offset - oldOffset + 1; return out; } var decode5 = read; var MSB$1 = 128; var REST$1 = 127; function read(buf, offset) { var res = 0, offset = offset || 0, shift = 0, counter = offset, b5, l4 = buf.length; do { if (counter >= l4) { read.bytes = 0; throw new RangeError("Could not decode varint"); } b5 = buf[counter++]; res += shift < 28 ? (b5 & REST$1) << shift : (b5 & REST$1) * Math.pow(2, shift); shift += 7; } while (b5 >= MSB$1); read.bytes = counter - offset; return res; } var N1 = Math.pow(2, 7); var N2 = Math.pow(2, 14); var N3 = Math.pow(2, 21); var N4 = Math.pow(2, 28); var N5 = Math.pow(2, 35); var N6 = Math.pow(2, 42); var N7 = Math.pow(2, 49); var N8 = Math.pow(2, 56); var N9 = Math.pow(2, 63); var length = function(value) { return value < N1 ? 1 : value < N2 ? 2 : value < N3 ? 3 : value < N4 ? 4 : value < N5 ? 5 : value < N6 ? 6 : value < N7 ? 7 : value < N8 ? 8 : value < N9 ? 9 : 10; }; var varint = { encode: encode_1, decode: decode5, encodingLength: length }; var _brrp_varint = varint; var varint_default = _brrp_varint; // node_modules/multiformats/esm/src/varint.js var decode6 = (data, offset = 0) => { const code2 = varint_default.decode(data, offset); return [ code2, varint_default.decode.bytes ]; }; var encodeTo = (int, target, offset = 0) => { varint_default.encode(int, target, offset); return target; }; var encodingLength = (int) => { return varint_default.encodingLength(int); }; // node_modules/multiformats/esm/src/hashes/digest.js var create = (code2, digest2) => { const size = digest2.byteLength; const sizeOffset = encodingLength(code2); const digestOffset = sizeOffset + encodingLength(size); const bytes = new Uint8Array(digestOffset + size); encodeTo(code2, bytes, 0); encodeTo(size, bytes, sizeOffset); bytes.set(digest2, digestOffset); return new Digest(code2, size, digest2, bytes); }; var decode7 = (multihash) => { const bytes = coerce(multihash); const [code2, sizeOffset] = decode6(bytes); const [size, digestOffset] = decode6(bytes.subarray(sizeOffset)); const digest2 = bytes.subarray(sizeOffset + digestOffset); if (digest2.byteLength !== size) { throw new Error("Incorrect length"); } return new Digest(code2, size, digest2, bytes); }; var equals2 = (a4, b5) => { if (a4 === b5) { return true; } else { return a4.code === b5.code && a4.size === b5.size && equals(a4.bytes, b5.bytes); } }; var Digest = class { constructor(code2, size, digest2, bytes) { this.code = code2; this.size = size; this.digest = digest2; this.bytes = bytes; } }; // node_modules/multiformats/esm/src/hashes/hasher.js var from2 = ({ name: name2, code: code2, encode: encode8 }) => new Hasher(name2, code2, encode8); var Hasher = class { constructor(name2, code2, encode8) { this.name = name2; this.code = code2; this.encode = encode8; } digest(input) { if (input instanceof Uint8Array) { const result = this.encode(input); return result instanceof Uint8Array ? create(this.code, result) : result.then((digest2) => create(this.code, digest2)); } else { throw Error("Unknown type, must be binary type"); } } }; // node_modules/multiformats/esm/src/hashes/sha2-browser.js var sha = (name2) => async (data) => new Uint8Array(await crypto.subtle.digest(name2, data)); var sha256 = from2({ name: "sha2-256", code: 18, encode: sha("SHA-256") }); var sha512 = from2({ name: "sha2-512", code: 19, encode: sha("SHA-512") }); // node_modules/multiformats/esm/src/hashes/identity.js var identity_exports2 = {}; __export(identity_exports2, { identity: () => identity2 }); var code = 0; var name = "identity"; var encode7 = coerce; var digest = (input) => create(code, encode7(input)); var identity2 = { code, name, encode: encode7, digest }; // node_modules/multiformats/esm/src/codecs/json.js var textEncoder = new TextEncoder(); var textDecoder = new TextDecoder(); // node_modules/multiformats/esm/src/cid.js var CID = class _CID { constructor(version12, code2, multihash, bytes) { this.code = code2; this.version = version12; this.multihash = multihash; this.bytes = bytes; this.byteOffset = bytes.byteOffset; this.byteLength = bytes.byteLength; this.asCID = this; this._baseCache = /* @__PURE__ */ new Map(); Object.defineProperties(this, { byteOffset: hidden, byteLength: hidden, code: readonly, version: readonly, multihash: readonly, bytes: readonly, _baseCache: hidden, asCID: hidden }); } toV0() { switch (this.version) { case 0: { return this; } default: { const { code: code2, multihash } = this; if (code2 !== DAG_PB_CODE) { throw new Error("Cannot convert a non dag-pb CID to CIDv0"); } if (multihash.code !== SHA_256_CODE) { throw new Error("Cannot convert non sha2-256 multihash CID to CIDv0"); } return _CID.createV0(multihash); } } } toV1() { switch (this.version) { case 0: { const { code: code2, digest: digest2 } = this.multihash; const multihash = create(code2, digest2); return _CID.createV1(this.code, multihash); } case 1: { return this; } default: { throw Error(`Can not convert CID version ${this.version} to version 0. This is a bug please report`); } } } equals(other) { return other && this.code === other.code && this.version === other.version && equals2(this.multihash, other.multihash); } toString(base3) { const { bytes, version: version12, _baseCache } = this; switch (version12) { case 0: return toStringV0(bytes, _baseCache, base3 || base58btc.encoder); default: return toStringV1(bytes, _baseCache, base3 || base32.encoder); } } toJSON() { return { code: this.code, version: this.version, hash: this.multihash.bytes }; } get [Symbol.toStringTag]() { return "CID"; } [Symbol.for("nodejs.util.inspect.custom")]() { return "CID(" + this.toString() + ")"; } static isCID(value) { deprecate(/^0\.0/, IS_CID_DEPRECATION); return !!(value && (value[cidSymbol] || value.asCID === value)); } get toBaseEncodedString() { throw new Error("Deprecated, use .toString()"); } get codec() { throw new Error('"codec" property is deprecated, use integer "code" property instead'); } get buffer() { throw new Error("Deprecated .buffer property, use .bytes to get Uint8Array instead"); } get multibaseName() { throw new Error('"multibaseName" property is deprecated'); } get prefix() { throw new Error('"prefix" property is deprecated'); } static asCID(value) { if (value instanceof _CID) { return value; } else if (value != null && value.asCID === value) { const { version: version12, code: code2, multihash, bytes } = value; return new _CID(version12, code2, multihash, bytes || encodeCID(version12, code2, multihash.bytes)); } else if (value != null && value[cidSymbol] === true) { const { version: version12, multihash, code: code2 } = value; const digest2 = decode7(multihash); return _CID.create(version12, code2, digest2); } else { return null; } } static create(version12, code2, digest2) { if (typeof code2 !== "number") { throw new Error("String codecs are no longer supported"); } switch (version12) { case 0: { if (code2 !== DAG_PB_CODE) { throw new Error(`Version 0 CID must use dag-pb (code: ${DAG_PB_CODE}) block encoding`); } else { return new _CID(version12, code2, digest2, digest2.bytes); } } case 1: { const bytes = encodeCID(version12, code2, digest2.bytes); return new _CID(version12, code2, digest2, bytes); } default: { throw new Error("Invalid version"); } } } static createV0(digest2) { return _CID.create(0, DAG_PB_CODE, digest2); } static createV1(code2, digest2) { return _CID.create(1, code2, digest2); } static decode(bytes) { const [cid, remainder] = _CID.decodeFirst(bytes); if (remainder.length) { throw new Error("Incorrect length"); } return cid; } static decodeFirst(bytes) { const specs = _CID.inspectBytes(bytes); const prefixSize = specs.size - specs.multihashSize; const multihashBytes = coerce(bytes.subarray(prefixSize, prefixSize + specs.multihashSize)); if (multihashBytes.byteLength !== specs.multihashSize) { throw new Error("Incorrect length"); } const digestBytes = multihashBytes.subarray(specs.multihashSize - specs.digestSize); const digest2 = new Digest(specs.multihashCode, specs.digestSize, digestBytes, multihashBytes); const cid = specs.version === 0 ? _CID.createV0(digest2) : _CID.createV1(specs.codec, digest2); return [ cid, bytes.subarray(specs.size) ]; } static inspectBytes(initialBytes) { let offset = 0; const next = () => { const [i4, length2] = decode6(initialBytes.subarray(offset)); offset += length2; return i4; }; let version12 = next(); let codec = DAG_PB_CODE; if (version12 === 18) { version12 = 0; offset = 0; } else if (version12 === 1) { codec = next(); } if (version12 !== 0 && version12 !== 1) { throw new RangeError(`Invalid CID version ${version12}`); } const prefixSize = offset; const multihashCode = next(); const digestSize = next(); const size = offset + digestSize; const multihashSize = size - prefixSize; return { version: version12, codec, multihashCode, digestSize, multihashSize, size }; } static parse(source, base3) { const [prefix, bytes] = parseCIDtoBytes(source, base3); const cid = _CID.decode(bytes); cid._baseCache.set(prefix, source); return cid; } }; var parseCIDtoBytes = (source, base3) => { switch (source[0]) { case "Q": { const decoder = base3 || base58btc; return [ base58btc.prefix, decoder.decode(`${base58btc.prefix}${source}`) ]; } case base58btc.prefix: { const decoder = base3 || base58btc; return [ base58btc.prefix, decoder.decode(source) ]; } case base32.prefix: { const decoder = base3 || base32; return [ base32.prefix, decoder.decode(source) ]; } default: { if (base3 == null) { throw Error("To parse non base32 or base58btc encoded CID multibase decoder must be provided"); } return [ source[0], base3.decode(source) ]; } } }; var toStringV0 = (bytes, cache, base3) => { const { prefix } = base3; if (prefix !== base58btc.prefix) { throw Error(`Cannot string encode V0 in ${base3.name} encoding`); } const cid = cache.get(prefix); if (cid == null) { const cid2 = base3.encode(bytes).slice(1); cache.set(prefix, cid2); return cid2; } else { return cid; } }; var toStringV1 = (bytes, cache, base3) => { const { prefix } = base3; const cid = cache.get(prefix); if (cid == null) { const cid2 = base3.encode(bytes); cache.set(prefix, cid2); return cid2; } else { return cid; } }; var DAG_PB_CODE = 112; var SHA_256_CODE = 18; var encodeCID = (version12, code2, multihash) => { const codeOffset = encodingLength(version12); const hashOffset = codeOffset + encodingLength(code2); const bytes = new Uint8Array(hashOffset + multihash.byteLength); encodeTo(version12, bytes, 0); encodeTo(code2, bytes, codeOffset); bytes.set(multihash, hashOffset); return bytes; }; var cidSymbol = Symbol.for("@ipld/js-cid/CID"); var readonly = { writable: false, configurable: false, enumerable: true }; var hidden = { writable: false, enumerable: false, configurable: false }; var version11 = "0.0.0-dev"; var deprecate = (range, message) => { if (range.test(version11)) { console.warn(message); } else { throw new Error(message); } }; var IS_CID_DEPRECATION = `CID.isCID(v) is deprecated and will be removed in the next major release. Following code pattern: if (CID.isCID(value)) { doSomethingWithCID(value) } Is replaced with: const cid = CID.asCID(value) if (cid) { // Make sure to use cid instead of value doSomethingWithCID(cid) } `; // node_modules/multiformats/esm/src/basics.js var bases = { ...identity_exports, ...base2_exports, ...base8_exports, ...base10_exports, ...base16_exports, ...base32_exports, ...base36_exports, ...base58_exports, ...base64_exports, ...base256emoji_exports }; var hashes = { ...sha2_browser_exports, ...identity_exports2 }; // node_modules/uint8arrays/esm/src/util/bases.js function createCodec(name2, prefix, encode8, decode8) { return { name: name2, prefix, encoder: { name: name2, prefix, encode: encode8 }, decoder: { decode: decode8 } }; } var string = createCodec("utf8", "u", (buf) => { const decoder = new TextDecoder("utf8"); return "u" + decoder.decode(buf); }, (str) => { const encoder = new TextEncoder(); return encoder.encode(str.substring(1)); }); var ascii = createCodec("ascii", "a", (buf) => { let string2 = "a"; for (let i4 = 0; i4 < buf.length; i4++) { string2 += String.fromCharCode(buf[i4]); } return string2; }, (str) => { str = str.substring(1); const buf = allocUnsafe(str.length); for (let i4 = 0; i4 < str.length; i4++) { buf[i4] = str.charCodeAt(i4); } return buf; }); var BASES = { utf8: string, "utf-8": string, hex: bases.base16, latin1: ascii, ascii, binary: ascii, ...bases }; var bases_default = BASES; // node_modules/uint8arrays/esm/src/from-string.js function fromString2(string2, encoding = "utf8") { const base3 = bases_default[encoding]; if (!base3) { throw new Error(`Unsupported encoding "${encoding}"`); } if ((encoding === "utf8" || encoding === "utf-8") && globalThis.Buffer != null && globalThis.Buffer.from != null) { return globalThis.Buffer.from(string2, "utf8"); } return base3.decoder.decode(`${base3.prefix}${string2}`); } // node_modules/uint8arrays/esm/src/to-string.js function toString2(array, encoding = "utf8") { const base3 = bases_default[encoding]; if (!base3) { throw new Error(`Unsupported encoding "${encoding}"`); } if ((encoding === "utf8" || encoding === "utf-8") && globalThis.Buffer != null && globalThis.Buffer.from != null) { return globalThis.Buffer.from(array.buffer, array.byteOffset, array.byteLength).toString("utf8"); } return base3.encoder.encode(array).substring(1); } // node_modules/@walletconnect/utils/dist/index.es.js var import_elliptic2 = __toESM(require_elliptic()); // node_modules/@walletconnect/relay-auth/dist/esm/api.js var ed25519 = __toESM(require_ed25519()); var import_random = __toESM(require_random()); var import_time = __toESM(require_cjs()); // node_modules/@walletconnect/relay-auth/dist/esm/constants.js var JWT_IRIDIUM_ALG = "EdDSA"; var JWT_IRIDIUM_TYP = "JWT"; var JWT_DELIMITER = "."; var JWT_ENCODING = "base64url"; var JSON_ENCODING = "utf8"; var DATA_ENCODING = "utf8"; var DID_DELIMITER = ":"; var DID_PREFIX = "did"; var DID_METHOD = "key"; var MULTICODEC_ED25519_ENCODING = "base58btc"; var MULTICODEC_ED25519_BASE = "z"; var MULTICODEC_ED25519_HEADER = "K36"; var KEY_PAIR_SEED_LENGTH = 32; // node_modules/@walletconnect/safe-json/dist/esm/index.js var JSONStringify = (data) => JSON.stringify(data, (_4, value) => typeof value === "bigint" ? value.toString() + "n" : value); var JSONParse = (json) => { const numbersBiggerThanMaxInt = /([\[:])?(\d{17,}|(?:[9](?:[1-9]07199254740991|0[1-9]7199254740991|00[8-9]199254740991|007[2-9]99254740991|007199[3-9]54740991|0071992[6-9]4740991|00719925[5-9]740991|007199254[8-9]40991|0071992547[5-9]0991|00719925474[1-9]991|00719925474099[2-9])))([,\}\]])/g; const serializedData = json.replace(numbersBiggerThanMaxInt, '$1"$2n"$3'); return JSON.parse(serializedData, (_4, value) => { const isCustomFormatBigInt = typeof value === "string" && value.match(/^\d+n$/); if (isCustomFormatBigInt) return BigInt(value.substring(0, value.length - 1)); return value; }); }; function safeJsonParse(value) { if (typeof value !== "string") { throw new Error(`Cannot safe json parse value of type ${typeof value}`); } try { return JSONParse(value); } catch (_a) { return value; } } function safeJsonStringify(value) { return typeof value === "string" ? value : JSONStringify(value) || ""; } // node_modules/@walletconnect/relay-auth/dist/esm/utils.js function decodeJSON(str) { return safeJsonParse(toString2(fromString2(str, JWT_ENCODING), JSON_ENCODING)); } function encodeJSON(val) { return toString2(fromString2(safeJsonStringify(val), JSON_ENCODING), JWT_ENCODING); } function encodeIss(publicKey) { const header = fromString2(MULTICODEC_ED25519_HEADER, MULTICODEC_ED25519_ENCODING); const multicodec = MULTICODEC_ED25519_BASE + toString2(concat2([header, publicKey]), MULTICODEC_ED25519_ENCODING); return [DID_PREFIX, DID_METHOD, multicodec].join(DID_DELIMITER); } function encodeSig(bytes) { return toString2(bytes, JWT_ENCODING); } function decodeSig(encoded) { return fromString2(encoded, JWT_ENCODING); } function encodeData(params) { return fromString2([encodeJSON(params.header), encodeJSON(params.payload)].join(JWT_DELIMITER), DATA_ENCODING); } function encodeJWT(params) { return [ encodeJSON(params.header), encodeJSON(params.payload), encodeSig(params.signature) ].join(JWT_DELIMITER); } function decodeJWT(jwt) { const params = jwt.split(JWT_DELIMITER); const header = decodeJSON(params[0]); const payload = decodeJSON(params[1]); const signature2 = decodeSig(params[2]); const data = fromString2(params.slice(0, 2).join(JWT_DELIMITER), DATA_ENCODING); return { header, payload, signature: signature2, data }; } // node_modules/@walletconnect/relay-auth/dist/esm/api.js function generateKeyPair(seed = (0, import_random.randomBytes)(KEY_PAIR_SEED_LENGTH)) { return ed25519.generateKeyPairFromSeed(seed); } async function signJWT(sub, aud, ttl, keyPair2, iat = (0, import_time.fromMiliseconds)(Date.now())) { const header = { alg: JWT_IRIDIUM_ALG, typ: JWT_IRIDIUM_TYP }; const iss = encodeIss(keyPair2.publicKey); const exp = iat + ttl; const payload = { iss, sub, aud, iat, exp }; const data = encodeData({ header, payload }); const signature2 = ed25519.sign(keyPair2.secretKey, data); return encodeJWT({ header, payload, signature: signature2 }); } // node_modules/@walletconnect/relay-api/dist/index.es.js var C = { waku: { publish: "waku_publish", batchPublish: "waku_batchPublish", subscribe: "waku_subscribe", batchSubscribe: "waku_batchSubscribe", subscription: "waku_subscription", unsubscribe: "waku_unsubscribe", batchUnsubscribe: "waku_batchUnsubscribe", batchFetchMessages: "waku_batchFetchMessages" }, irn: { publish: "irn_publish", batchPublish: "irn_batchPublish", subscribe: "irn_subscribe", batchSubscribe: "irn_batchSubscribe", subscription: "irn_subscription", unsubscribe: "irn_unsubscribe", batchUnsubscribe: "irn_batchUnsubscribe", batchFetchMessages: "irn_batchFetchMessages" }, iridium: { publish: "iridium_publish", batchPublish: "iridium_batchPublish", subscribe: "iridium_subscribe", batchSubscribe: "iridium_batchSubscribe", subscription: "iridium_subscription", unsubscribe: "iridium_unsubscribe", batchUnsubscribe: "iridium_batchUnsubscribe", batchFetchMessages: "iridium_batchFetchMessages" } }; // node_modules/@walletconnect/utils/dist/index.es.js var H = ":"; function re(e2) { const [n5, t] = e2.split(H); return { namespace: n5, reference: t }; } function mt(e2, n5 = []) { const t = []; return Object.keys(e2).forEach((r4) => { if (n5.length && !n5.includes(r4)) return; const o4 = e2[r4]; t.push(...o4.accounts); }), t; } function W(e2, n5) { return e2.includes(":") ? [e2] : n5.chains || []; } var gt = Object.defineProperty; var Ke = Object.getOwnPropertySymbols; var vt = Object.prototype.hasOwnProperty; var bt = Object.prototype.propertyIsEnumerable; var Le = (e2, n5, t) => n5 in e2 ? gt(e2, n5, { enumerable: true, configurable: true, writable: true, value: t }) : e2[n5] = t; var Fe = (e2, n5) => { for (var t in n5 || (n5 = {})) vt.call(n5, t) && Le(e2, t, n5[t]); if (Ke) for (var t of Ke(n5)) bt.call(n5, t) && Le(e2, t, n5[t]); return e2; }; var qe = "ReactNative"; var y = { reactNative: "react-native", node: "node", browser: "browser", unknown: "unknown" }; var He = "js"; function ce() { return typeof process < "u" && typeof process.versions < "u" && typeof process.versions.node < "u"; } function _() { return !(0, import_window_getters.getDocument)() && !!(0, import_window_getters.getNavigator)() && navigator.product === qe; } function V() { return !ce() && !!(0, import_window_getters.getNavigator)() && !!(0, import_window_getters.getDocument)(); } function P() { return _() ? y.reactNative : ce() ? y.node : V() ? y.browser : y.unknown; } function Ot() { var e2; try { return _() && typeof global < "u" && typeof (global == null ? void 0 : global.Application) < "u" ? (e2 = global.Application) == null ? void 0 : e2.applicationId : void 0; } catch { return; } } function We(e2, n5) { let t = q.parse(e2); return t = Fe(Fe({}, t), n5), e2 = q.stringify(t), e2; } function Nt() { return (0, import_window_metadata.getWindowMetadata)() || { name: "", description: "", url: "", icons: [""] }; } function Je() { if (P() === y.reactNative && typeof global < "u" && typeof (global == null ? void 0 : global.Platform) < "u") { const { OS: t, Version: r4 } = global.Platform; return [t, r4].join("-"); } const e2 = detect(); if (e2 === null) return "unknown"; const n5 = e2.os ? e2.os.replace(" ", "").toLowerCase() : "unknown"; return e2.type === "browser" ? [n5, e2.name, e2.version].join("-") : [n5, e2.version].join("-"); } function ze() { var e2; const n5 = P(); return n5 === y.browser ? [n5, ((e2 = (0, import_window_getters.getLocation)()) == null ? void 0 : e2.host) || "unknown"].join(":") : n5; } function Ge(e2, n5, t) { const r4 = Je(), o4 = ze(); return [[e2, n5].join("-"), [He, t].join("-"), r4, o4].join("/"); } function $t({ protocol: e2, version: n5, relayUrl: t, sdkVersion: r4, auth: o4, projectId: s3, useOnCloseEvent: i4, bundleId: u3 }) { const l4 = t.split("?"), c5 = Ge(e2, n5, r4), d3 = { auth: o4, ua: c5, projectId: s3, useOnCloseEvent: i4 || void 0, origin: u3 || void 0 }, a4 = We(l4[1] || "", d3); return l4[0] + "?" + a4; } function $(e2, n5) { return e2.filter((t) => n5.includes(t)).length === e2.length; } function Tt(e2) { return Object.fromEntries(e2.entries()); } function Pt(e2) { return new Map(Object.entries(e2)); } function _t(e2 = import_time2.FIVE_MINUTES, n5) { const t = (0, import_time2.toMiliseconds)(e2 || import_time2.FIVE_MINUTES); let r4, o4, s3; return { resolve: (i4) => { s3 && r4 && (clearTimeout(s3), r4(i4)); }, reject: (i4) => { s3 && o4 && (clearTimeout(s3), o4(i4)); }, done: () => new Promise((i4, u3) => { s3 = setTimeout(() => { u3(new Error(n5)); }, t), r4 = i4, o4 = u3; }) }; } function kt(e2, n5, t) { return new Promise(async (r4, o4) => { const s3 = setTimeout(() => o4(new Error(t)), n5); try { const i4 = await e2; r4(i4); } catch (i4) { o4(i4); } clearTimeout(s3); }); } function ae(e2, n5) { if (typeof n5 == "string" && n5.startsWith(`${e2}:`)) return n5; if (e2.toLowerCase() === "topic") { if (typeof n5 != "string") throw new Error('Value must be "string" for expirer target type: topic'); return `topic:${n5}`; } else if (e2.toLowerCase() === "id") { if (typeof n5 != "number") throw new Error('Value must be "number" for expirer target type: id'); return `id:${n5}`; } throw new Error(`Unknown expirer target type: ${e2}`); } function Dt(e2) { return ae("topic", e2); } function xt(e2) { return ae("id", e2); } function Vt(e2) { const [n5, t] = e2.split(":"), r4 = { id: void 0, topic: void 0 }; if (n5 === "topic" && typeof t == "string") r4.topic = t; else if (n5 === "id" && Number.isInteger(Number(t))) r4.id = Number(t); else throw new Error(`Invalid target, expected id:number or topic:string, got ${n5}:${t}`); return r4; } function Mt(e2, n5) { return (0, import_time2.fromMiliseconds)((n5 || Date.now()) + (0, import_time2.toMiliseconds)(e2)); } function Kt(e2) { return Date.now() >= (0, import_time2.toMiliseconds)(e2); } function Lt(e2, n5) { return `${e2}${n5 ? `:${n5}` : ""}`; } function N(e2 = [], n5 = []) { return [.../* @__PURE__ */ new Set([...e2, ...n5])]; } async function Ft({ id: e2, topic: n5, wcDeepLink: t }) { var r4; try { if (!t) return; const o4 = typeof t == "string" ? JSON.parse(t) : t, s3 = o4 == null ? void 0 : o4.href; if (typeof s3 != "string") return; const i4 = Xe(s3, e2, n5), u3 = P(); if (u3 === y.browser) { if (!((r4 = (0, import_window_getters.getDocument)()) != null && r4.hasFocus())) { console.warn("Document does not have focus, skipping deeplink."); return; } i4.startsWith("https://") || i4.startsWith("http://") ? window.open(i4, "_blank", "noreferrer noopener") : window.open(i4, en() ? "_blank" : "_self", "noreferrer noopener"); } else u3 === y.reactNative && typeof (global == null ? void 0 : global.Linking) < "u" && await global.Linking.openURL(i4); } catch (o4) { console.error(o4); } } function Xe(e2, n5, t) { const r4 = `requestId=${n5}&sessionTopic=${t}`; e2.endsWith("/") && (e2 = e2.slice(0, -1)); let o4 = `${e2}`; if (e2.startsWith("https://t.me")) { const s3 = e2.includes("?") ? "&startapp=" : "?startapp="; o4 = `${o4}${s3}${nn(r4, true)}`; } else o4 = `${o4}/wc?${r4}`; return o4; } async function qt(e2, n5) { let t = ""; try { if (V() && (t = localStorage.getItem(n5), t)) return t; t = await e2.getItem(n5); } catch (r4) { console.error(r4); } return t; } function Bt(e2, n5) { if (!e2.includes(n5)) return null; const t = e2.split(/([&,?,=])/), r4 = t.indexOf(n5); return t[r4 + 2]; } function Ht() { return typeof crypto < "u" && crypto != null && crypto.randomUUID ? crypto.randomUUID() : "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/gu, (e2) => { const n5 = Math.random() * 16 | 0; return (e2 === "x" ? n5 : n5 & 3 | 8).toString(16); }); } function Wt() { return typeof process < "u" && process.env.IS_VITEST === "true"; } function en() { return typeof window < "u" && (!!window.TelegramWebviewProxy || !!window.Telegram || !!window.TelegramWebviewProxyProto); } function nn(e2, n5 = false) { const t = Buffer.from(e2).toString("base64"); return n5 ? t.replace(/[=]/g, "") : t; } function le(e2) { return Buffer.from(e2, "base64").toString("utf-8"); } var Jt = "https://rpc.walletconnect.org/v1"; async function tn(e2, n5, t, r4, o4, s3) { switch (t.t) { case "eip191": return rn(e2, n5, t.s); case "eip1271": return await on(e2, n5, t.s, r4, o4, s3); default: throw new Error(`verifySignature failed: Attempted to verify CacaoSignature with unknown type: ${t.t}`); } } function rn(e2, n5, t) { return recoverAddress(hashMessage(n5), t).toLowerCase() === e2.toLowerCase(); } async function on(e2, n5, t, r4, o4, s3) { const i4 = re(r4); if (!i4.namespace || !i4.reference) throw new Error(`isValidEip1271Signature failed: chainId must be in CAIP-2 format, received: ${r4}`); try { const u3 = "0x1626ba7e", l4 = "0000000000000000000000000000000000000000000000000000000000000040", c5 = "0000000000000000000000000000000000000000000000000000000000000041", d3 = t.substring(2), a4 = hashMessage(n5).substring(2), f4 = u3 + a4 + l4 + c5 + d3, h5 = await fetch(`${s3 || Jt}/?chainId=${r4}&projectId=${o4}`, { method: "POST", body: JSON.stringify({ id: zt(), jsonrpc: "2.0", method: "eth_call", params: [{ to: e2, data: f4 }, "latest"] }) }), { result: p3 } = await h5.json(); return p3 ? p3.slice(0, u3.length).toLowerCase() === u3.toLowerCase() : false; } catch (u3) { return console.error("isValidEip1271Signature: ", u3), false; } } function zt() { return Date.now() + Math.floor(Math.random() * 1e3); } var Gt = Object.defineProperty; var Yt = Object.defineProperties; var Qt = Object.getOwnPropertyDescriptors; var sn = Object.getOwnPropertySymbols; var Zt = Object.prototype.hasOwnProperty; var Xt = Object.prototype.propertyIsEnumerable; var cn = (e2, n5, t) => n5 in e2 ? Gt(e2, n5, { enumerable: true, configurable: true, writable: true, value: t }) : e2[n5] = t; var de = (e2, n5) => { for (var t in n5 || (n5 = {})) Zt.call(n5, t) && cn(e2, t, n5[t]); if (sn) for (var t of sn(n5)) Xt.call(n5, t) && cn(e2, t, n5[t]); return e2; }; var an = (e2, n5) => Yt(e2, Qt(n5)); var er = "did:pkh:"; var z = (e2) => e2 == null ? void 0 : e2.split(":"); var un = (e2) => { const n5 = e2 && z(e2); if (n5) return e2.includes(er) ? n5[3] : n5[1]; }; var ln = (e2) => { const n5 = e2 && z(e2); if (n5) return n5[2] + ":" + n5[3]; }; var fe = (e2) => { const n5 = e2 && z(e2); if (n5) return n5.pop(); }; async function nr(e2) { const { cacao: n5, projectId: t } = e2, { s: r4, p: o4 } = n5, s3 = dn(o4, o4.iss), i4 = fe(o4.iss); return await tn(i4, s3, r4, ln(o4.iss), t); } var dn = (e2, n5) => { const t = `${e2.domain} wants you to sign in with your Ethereum account:`, r4 = fe(n5); if (!e2.aud && !e2.uri) throw new Error("Either `aud` or `uri` is required to construct the message"); let o4 = e2.statement || void 0; const s3 = `URI: ${e2.aud || e2.uri}`, i4 = `Version: ${e2.version}`, u3 = `Chain ID: ${un(n5)}`, l4 = `Nonce: ${e2.nonce}`, c5 = `Issued At: ${e2.iat}`, d3 = e2.exp ? `Expiration Time: ${e2.exp}` : void 0, a4 = e2.nbf ? `Not Before: ${e2.nbf}` : void 0, f4 = e2.requestId ? `Request ID: ${e2.requestId}` : void 0, h5 = e2.resources ? `Resources:${e2.resources.map((m2) => ` - ${m2}`).join("")}` : void 0, p3 = Y(e2.resources); if (p3) { const m2 = R(p3); o4 = he(o4, m2); } return [t, r4, "", o4, "", s3, i4, u3, l4, c5, d3, a4, f4, h5].filter((m2) => m2 != null).join(` `); }; function hn(e2) { return Buffer.from(JSON.stringify(e2)).toString("base64"); } function yn(e2) { return JSON.parse(Buffer.from(e2, "base64").toString("utf-8")); } function O(e2) { if (!e2) throw new Error("No recap provided, value is undefined"); if (!e2.att) throw new Error("No `att` property found"); const n5 = Object.keys(e2.att); if (!(n5 != null && n5.length)) throw new Error("No resources found in `att` property"); n5.forEach((t) => { const r4 = e2.att[t]; if (Array.isArray(r4)) throw new Error(`Resource must be an object: ${t}`); if (typeof r4 != "object") throw new Error(`Resource must be an object: ${t}`); if (!Object.keys(r4).length) throw new Error(`Resource object is empty: ${t}`); Object.keys(r4).forEach((o4) => { const s3 = r4[o4]; if (!Array.isArray(s3)) throw new Error(`Ability limits ${o4} must be an array of objects, found: ${s3}`); if (!s3.length) throw new Error(`Value of ${o4} is empty array, must be an array with objects`); s3.forEach((i4) => { if (typeof i4 != "object") throw new Error(`Ability limits (${o4}) must be an array of objects, found: ${i4}`); }); }); }); } function gn(e2, n5, t, r4 = {}) { return t == null ? void 0 : t.sort((o4, s3) => o4.localeCompare(s3)), { att: { [e2]: pe(n5, t, r4) } }; } function pe(e2, n5, t = {}) { n5 = n5 == null ? void 0 : n5.sort((o4, s3) => o4.localeCompare(s3)); const r4 = n5.map((o4) => ({ [`${e2}/${o4}`]: [t] })); return Object.assign({}, ...r4); } function G(e2) { return O(e2), `urn:recap:${hn(e2).replace(/=/g, "")}`; } function R(e2) { const n5 = yn(e2.replace("urn:recap:", "")); return O(n5), n5; } function ir(e2, n5, t) { const r4 = gn(e2, n5, t); return G(r4); } function me(e2) { return e2 && e2.includes("urn:recap:"); } function cr(e2, n5) { const t = R(e2), r4 = R(n5), o4 = bn(t, r4); return G(o4); } function bn(e2, n5) { O(e2), O(n5); const t = Object.keys(e2.att).concat(Object.keys(n5.att)).sort((o4, s3) => o4.localeCompare(s3)), r4 = { att: {} }; return t.forEach((o4) => { var s3, i4; Object.keys(((s3 = e2.att) == null ? void 0 : s3[o4]) || {}).concat(Object.keys(((i4 = n5.att) == null ? void 0 : i4[o4]) || {})).sort((u3, l4) => u3.localeCompare(l4)).forEach((u3) => { var l4, c5; r4.att[o4] = an(de({}, r4.att[o4]), { [u3]: ((l4 = e2.att[o4]) == null ? void 0 : l4[u3]) || ((c5 = n5.att[o4]) == null ? void 0 : c5[u3]) }); }); }), r4; } function he(e2 = "", n5) { O(n5); const t = "I further authorize the stated URI to perform the following actions on my behalf: "; if (e2.includes(t)) return e2; const r4 = []; let o4 = 0; Object.keys(n5.att).forEach((u3) => { const l4 = Object.keys(n5.att[u3]).map((a4) => ({ ability: a4.split("/")[0], action: a4.split("/")[1] })); l4.sort((a4, f4) => a4.action.localeCompare(f4.action)); const c5 = {}; l4.forEach((a4) => { c5[a4.ability] || (c5[a4.ability] = []), c5[a4.ability].push(a4.action); }); const d3 = Object.keys(c5).map((a4) => (o4++, `(${o4}) '${a4}': '${c5[a4].join("', '")}' for '${u3}'.`)); r4.push(d3.join(", ").replace(".,", ".")); }); const s3 = r4.join(" "), i4 = `${t}${s3}`; return `${e2 ? e2 + " " : ""}${i4}`; } function ar(e2) { var n5; const t = R(e2); O(t); const r4 = (n5 = t.att) == null ? void 0 : n5.eip155; return r4 ? Object.keys(r4).map((o4) => o4.split("/")[1]) : []; } function ur(e2) { const n5 = R(e2); O(n5); const t = []; return Object.values(n5.att).forEach((r4) => { Object.values(r4).forEach((o4) => { var s3; (s3 = o4 == null ? void 0 : o4[0]) != null && s3.chains && t.push(o4[0].chains); }); }), [...new Set(t.flat())]; } function Y(e2) { if (!e2) return; const n5 = e2 == null ? void 0 : e2[e2.length - 1]; return me(n5) ? n5 : void 0; } var ye = "base10"; var g = "base16"; var ge = "base64pad"; var lr = "base64url"; var k = "utf8"; var ve = 0; var D = 1; var M = 2; var dr = 0; var wn = 1; var K = 12; var be = 32; function fr() { const e2 = _e.generateKeyPair(); return { privateKey: toString2(e2.secretKey, g), publicKey: toString2(e2.publicKey, g) }; } function pr() { const e2 = (0, import_random2.randomBytes)(be); return toString2(e2, g); } function mr(e2, n5) { const t = _e.sharedKey(fromString2(e2, g), fromString2(n5, g), true), r4 = new import_hkdf.HKDF(import_sha256.SHA256, t).expand(be); return toString2(r4, g); } function hr(e2) { const n5 = (0, import_sha256.hash)(fromString2(e2, g)); return toString2(n5, g); } function yr(e2) { const n5 = (0, import_sha256.hash)(fromString2(e2, k)); return toString2(n5, g); } function Ee(e2) { return fromString2(`${e2}`, ye); } function A(e2) { return Number(toString2(e2, ye)); } function gr(e2) { const n5 = Ee(typeof e2.type < "u" ? e2.type : ve); if (A(n5) === D && typeof e2.senderPublicKey > "u") throw new Error("Missing sender public key for type 1 envelope"); const t = typeof e2.senderPublicKey < "u" ? fromString2(e2.senderPublicKey, g) : void 0, r4 = typeof e2.iv < "u" ? fromString2(e2.iv, g) : (0, import_random2.randomBytes)(K), o4 = new import_chacha20poly1305.ChaCha20Poly1305(fromString2(e2.symKey, g)).seal(r4, fromString2(e2.message, k)); return we({ type: n5, sealed: o4, iv: r4, senderPublicKey: t, encoding: e2.encoding }); } function vr(e2, n5) { const t = Ee(M), r4 = (0, import_random2.randomBytes)(K), o4 = fromString2(e2, k); return we({ type: t, sealed: o4, iv: r4, encoding: n5 }); } function br(e2) { const n5 = new import_chacha20poly1305.ChaCha20Poly1305(fromString2(e2.symKey, g)), { sealed: t, iv: r4 } = Q({ encoded: e2.encoded, encoding: e2 == null ? void 0 : e2.encoding }), o4 = n5.open(r4, t); if (o4 === null) throw new Error("Failed to decrypt"); return toString2(o4, k); } function Er(e2, n5) { const { sealed: t } = Q({ encoded: e2, encoding: n5 }); return toString2(t, k); } function we(e2) { const { encoding: n5 = ge } = e2; if (A(e2.type) === M) return toString2(concat2([e2.type, e2.sealed]), n5); if (A(e2.type) === D) { if (typeof e2.senderPublicKey > "u") throw new Error("Missing sender public key for type 1 envelope"); return toString2(concat2([e2.type, e2.senderPublicKey, e2.iv, e2.sealed]), n5); } return toString2(concat2([e2.type, e2.iv, e2.sealed]), n5); } function Q(e2) { const { encoded: n5, encoding: t = ge } = e2, r4 = fromString2(n5, t), o4 = r4.slice(dr, wn), s3 = wn; if (A(o4) === D) { const c5 = s3 + be, d3 = c5 + K, a4 = r4.slice(s3, c5), f4 = r4.slice(c5, d3), h5 = r4.slice(d3); return { type: o4, sealed: h5, iv: f4, senderPublicKey: a4 }; } if (A(o4) === M) { const c5 = r4.slice(s3), d3 = (0, import_random2.randomBytes)(K); return { type: o4, sealed: c5, iv: d3 }; } const i4 = s3 + K, u3 = r4.slice(s3, i4), l4 = r4.slice(i4); return { type: o4, sealed: l4, iv: u3 }; } function wr(e2, n5) { const t = Q({ encoded: e2, encoding: n5 == null ? void 0 : n5.encoding }); return On({ type: A(t.type), senderPublicKey: typeof t.senderPublicKey < "u" ? toString2(t.senderPublicKey, g) : void 0, receiverPublicKey: n5 == null ? void 0 : n5.receiverPublicKey }); } function On(e2) { const n5 = (e2 == null ? void 0 : e2.type) || ve; if (n5 === D) { if (typeof (e2 == null ? void 0 : e2.senderPublicKey) > "u") throw new Error("missing sender public key"); if (typeof (e2 == null ? void 0 : e2.receiverPublicKey) > "u") throw new Error("missing receiver public key"); } return { type: n5, senderPublicKey: e2 == null ? void 0 : e2.senderPublicKey, receiverPublicKey: e2 == null ? void 0 : e2.receiverPublicKey }; } function Or(e2) { return e2.type === D && typeof e2.senderPublicKey == "string" && typeof e2.receiverPublicKey == "string"; } function Nr(e2) { return e2.type === M; } function Nn(e2) { return new import_elliptic2.ec("p256").keyFromPublic({ x: Buffer.from(e2.x, "base64").toString("hex"), y: Buffer.from(e2.y, "base64").toString("hex") }, "hex"); } function Sr(e2) { let n5 = e2.replace(/-/g, "+").replace(/_/g, "/"); const t = n5.length % 4; return t > 0 && (n5 += "=".repeat(4 - t)), n5; } function $r(e2) { return Buffer.from(Sr(e2), "base64"); } function Rr(e2, n5) { const [t, r4, o4] = e2.split("."), s3 = $r(o4); if (s3.length !== 64) throw new Error("Invalid signature length"); const i4 = s3.slice(0, 32).toString("hex"), u3 = s3.slice(32, 64).toString("hex"), l4 = `${t}.${r4}`, c5 = new import_sha256.SHA256().update(Buffer.from(l4)).digest(), d3 = Nn(n5), a4 = Buffer.from(c5).toString("hex"); if (!d3.verify(a4, { r: i4, s: u3 })) throw new Error("Invalid signature"); return decodeJWT(e2).payload; } var Sn = "irn"; function Ir(e2) { return (e2 == null ? void 0 : e2.relay) || { protocol: Sn }; } function jr(e2) { const n5 = C[e2]; if (typeof n5 > "u") throw new Error(`Relay Protocol not supported: ${e2}`); return n5; } var Tr = Object.defineProperty; var Pr = Object.defineProperties; var Ar = Object.getOwnPropertyDescriptors; var $n = Object.getOwnPropertySymbols; var Cr = Object.prototype.hasOwnProperty; var Ur = Object.prototype.propertyIsEnumerable; var Rn = (e2, n5, t) => n5 in e2 ? Tr(e2, n5, { enumerable: true, configurable: true, writable: true, value: t }) : e2[n5] = t; var In = (e2, n5) => { for (var t in n5 || (n5 = {})) Cr.call(n5, t) && Rn(e2, t, n5[t]); if ($n) for (var t of $n(n5)) Ur.call(n5, t) && Rn(e2, t, n5[t]); return e2; }; var _r = (e2, n5) => Pr(e2, Ar(n5)); function jn(e2, n5 = "-") { const t = {}, r4 = "relay" + n5; return Object.keys(e2).forEach((o4) => { if (o4.startsWith(r4)) { const s3 = o4.replace(r4, ""), i4 = e2[o4]; t[s3] = i4; } }), t; } function kr(e2) { if (!e2.includes("wc:")) { const l4 = le(e2); l4 != null && l4.includes("wc:") && (e2 = l4); } e2 = e2.includes("wc://") ? e2.replace("wc://", "") : e2, e2 = e2.includes("wc:") ? e2.replace("wc:", "") : e2; const n5 = e2.indexOf(":"), t = e2.indexOf("?") !== -1 ? e2.indexOf("?") : void 0, r4 = e2.substring(0, n5), o4 = e2.substring(n5 + 1, t).split("@"), s3 = typeof t < "u" ? e2.substring(t) : "", i4 = q.parse(s3), u3 = typeof i4.methods == "string" ? i4.methods.split(",") : void 0; return { protocol: r4, topic: Tn(o4[0]), version: parseInt(o4[1], 10), symKey: i4.symKey, relay: jn(i4), methods: u3, expiryTimestamp: i4.expiryTimestamp ? parseInt(i4.expiryTimestamp, 10) : void 0 }; } function Tn(e2) { return e2.startsWith("//") ? e2.substring(2) : e2; } function Pn(e2, n5 = "-") { const t = "relay", r4 = {}; return Object.keys(e2).forEach((o4) => { const s3 = t + n5 + o4; e2[o4] && (r4[s3] = e2[o4]); }), r4; } function Dr(e2) { return `${e2.protocol}:${e2.topic}@${e2.version}?` + q.stringify(In(_r(In({ symKey: e2.symKey }, Pn(e2.relay)), { expiryTimestamp: e2.expiryTimestamp }), e2.methods ? { methods: e2.methods.join(",") } : {})); } function xr(e2, n5, t) { return `${e2}?wc_ev=${t}&topic=${n5}`; } function C2(e2) { const n5 = []; return e2.forEach((t) => { const [r4, o4] = t.split(":"); n5.push(`${r4}:${o4}`); }), n5; } function Un(e2) { const n5 = []; return Object.values(e2).forEach((t) => { n5.push(...C2(t.accounts)); }), n5; } function _n(e2, n5) { const t = []; return Object.values(e2).forEach((r4) => { C2(r4.accounts).includes(n5) && t.push(...r4.methods); }), t; } function kn(e2, n5) { const t = []; return Object.values(e2).forEach((r4) => { C2(r4.accounts).includes(n5) && t.push(...r4.events); }), t; } function Oe(e2) { return e2.includes(":"); } function Dn(e2) { return Oe(e2) ? e2.split(":")[0] : e2; } function xn(e2) { const n5 = {}; return e2 == null ? void 0 : e2.forEach((t) => { const [r4, o4] = t.split(":"); n5[r4] || (n5[r4] = { accounts: [], chains: [], events: [] }), n5[r4].accounts.push(t), n5[r4].chains.push(`${r4}:${o4}`); }), n5; } function Jr(e2, n5) { n5 = n5.map((r4) => r4.replace("did:pkh:", "")); const t = xn(n5); for (const [r4, o4] of Object.entries(t)) o4.methods ? o4.methods = N(o4.methods, e2) : o4.methods = e2, o4.events = ["chainChanged", "accountsChanged"]; return t; } var Vn = { INVALID_METHOD: { message: "Invalid method.", code: 1001 }, INVALID_EVENT: { message: "Invalid event.", code: 1002 }, INVALID_UPDATE_REQUEST: { message: "Invalid update request.", code: 1003 }, INVALID_EXTEND_REQUEST: { message: "Invalid extend request.", code: 1004 }, INVALID_SESSION_SETTLE_REQUEST: { message: "Invalid session settle request.", code: 1005 }, UNAUTHORIZED_METHOD: { message: "Unauthorized method.", code: 3001 }, UNAUTHORIZED_EVENT: { message: "Unauthorized event.", code: 3002 }, UNAUTHORIZED_UPDATE_REQUEST: { message: "Unauthorized update request.", code: 3003 }, UNAUTHORIZED_EXTEND_REQUEST: { message: "Unauthorized extend request.", code: 3004 }, USER_REJECTED: { message: "User rejected.", code: 5e3 }, USER_REJECTED_CHAINS: { message: "User rejected chains.", code: 5001 }, USER_REJECTED_METHODS: { message: "User rejected methods.", code: 5002 }, USER_REJECTED_EVENTS: { message: "User rejected events.", code: 5003 }, UNSUPPORTED_CHAINS: { message: "Unsupported chains.", code: 5100 }, UNSUPPORTED_METHODS: { message: "Unsupported methods.", code: 5101 }, UNSUPPORTED_EVENTS: { message: "Unsupported events.", code: 5102 }, UNSUPPORTED_ACCOUNTS: { message: "Unsupported accounts.", code: 5103 }, UNSUPPORTED_NAMESPACE_KEY: { message: "Unsupported namespace key.", code: 5104 }, USER_DISCONNECTED: { message: "User disconnected.", code: 6e3 }, SESSION_SETTLEMENT_FAILED: { message: "Session settlement failed.", code: 7e3 }, WC_METHOD_UNSUPPORTED: { message: "Unsupported wc_ method.", code: 10001 } }; var Mn = { NOT_INITIALIZED: { message: "Not initialized.", code: 1 }, NO_MATCHING_KEY: { message: "No matching key.", code: 2 }, RESTORE_WILL_OVERRIDE: { message: "Restore will override.", code: 3 }, RESUBSCRIBED: { message: "Resubscribed.", code: 4 }, MISSING_OR_INVALID: { message: "Missing or invalid.", code: 5 }, EXPIRED: { message: "Expired.", code: 6 }, UNKNOWN_TYPE: { message: "Unknown type.", code: 7 }, MISMATCHED_TOPIC: { message: "Mismatched topic.", code: 8 }, NON_CONFORMING_NAMESPACES: { message: "Non conforming namespaces.", code: 9 } }; function S(e2, n5) { const { message: t, code: r4 } = Mn[e2]; return { message: n5 ? `${t} ${n5}` : t, code: r4 }; } function U(e2, n5) { const { message: t, code: r4 } = Vn[e2]; return { message: n5 ? `${t} ${n5}` : t, code: r4 }; } function L(e2, n5) { return Array.isArray(e2) ? typeof n5 < "u" && e2.length ? e2.every(n5) : true : false; } function Z(e2) { return Object.getPrototypeOf(e2) === Object.prototype && Object.keys(e2).length; } function I(e2) { return typeof e2 > "u"; } function b(e2, n5) { return n5 && I(e2) ? true : typeof e2 == "string" && !!e2.trim().length; } function X(e2, n5) { return n5 && I(e2) ? true : typeof e2 == "number" && !isNaN(e2); } function zr(e2, n5) { const { requiredNamespaces: t } = n5, r4 = Object.keys(e2.namespaces), o4 = Object.keys(t); let s3 = true; return $(o4, r4) ? (r4.forEach((i4) => { const { accounts: u3, methods: l4, events: c5 } = e2.namespaces[i4], d3 = C2(u3), a4 = t[i4]; (!$(W(i4, a4), d3) || !$(a4.methods, l4) || !$(a4.events, c5)) && (s3 = false); }), s3) : false; } function F(e2) { return b(e2, false) && e2.includes(":") ? e2.split(":").length === 2 : false; } function Kn(e2) { if (b(e2, false) && e2.includes(":")) { const n5 = e2.split(":"); if (n5.length === 3) { const t = n5[0] + ":" + n5[1]; return !!n5[2] && F(t); } } return false; } function Gr(e2) { function n5(t) { try { return typeof new URL(t) < "u"; } catch { return false; } } try { if (b(e2, false)) { if (n5(e2)) return true; const t = le(e2); return n5(t); } } catch { } return false; } function Yr(e2) { var n5; return (n5 = e2 == null ? void 0 : e2.proposer) == null ? void 0 : n5.publicKey; } function Qr(e2) { return e2 == null ? void 0 : e2.topic; } function Zr(e2, n5) { let t = null; return b(e2 == null ? void 0 : e2.publicKey, false) || (t = S("MISSING_OR_INVALID", `${n5} controller public key should be a string`)), t; } function Se(e2) { let n5 = true; return L(e2) ? e2.length && (n5 = e2.every((t) => b(t, false))) : n5 = false, n5; } function Ln(e2, n5, t) { let r4 = null; return L(n5) && n5.length ? n5.forEach((o4) => { r4 || F(o4) || (r4 = U("UNSUPPORTED_CHAINS", `${t}, chain ${o4} should be a string and conform to "namespace:chainId" format`)); }) : F(e2) || (r4 = U("UNSUPPORTED_CHAINS", `${t}, chains must be defined as "namespace:chainId" e.g. "eip155:1": {...} in the namespace key OR as an array of CAIP-2 chainIds e.g. eip155: { chains: ["eip155:1", "eip155:5"] }`)), r4; } function Fn(e2, n5, t) { let r4 = null; return Object.entries(e2).forEach(([o4, s3]) => { if (r4) return; const i4 = Ln(o4, W(o4, s3), `${n5} ${t}`); i4 && (r4 = i4); }), r4; } function qn(e2, n5) { let t = null; return L(e2) ? e2.forEach((r4) => { t || Kn(r4) || (t = U("UNSUPPORTED_ACCOUNTS", `${n5}, account ${r4} should be a string and conform to "namespace:chainId:address" format`)); }) : t = U("UNSUPPORTED_ACCOUNTS", `${n5}, accounts should be an array of strings conforming to "namespace:chainId:address" format`), t; } function Bn(e2, n5) { let t = null; return Object.values(e2).forEach((r4) => { if (t) return; const o4 = qn(r4 == null ? void 0 : r4.accounts, `${n5} namespace`); o4 && (t = o4); }), t; } function Hn(e2, n5) { let t = null; return Se(e2 == null ? void 0 : e2.methods) ? Se(e2 == null ? void 0 : e2.events) || (t = U("UNSUPPORTED_EVENTS", `${n5}, events should be an array of strings or empty array for no events`)) : t = U("UNSUPPORTED_METHODS", `${n5}, methods should be an array of strings or empty array for no methods`), t; } function $e(e2, n5) { let t = null; return Object.values(e2).forEach((r4) => { if (t) return; const o4 = Hn(r4, `${n5}, namespace`); o4 && (t = o4); }), t; } function Xr(e2, n5, t) { let r4 = null; if (e2 && Z(e2)) { const o4 = $e(e2, n5); o4 && (r4 = o4); const s3 = Fn(e2, n5, t); s3 && (r4 = s3); } else r4 = S("MISSING_OR_INVALID", `${n5}, ${t} should be an object with data`); return r4; } function Wn(e2, n5) { let t = null; if (e2 && Z(e2)) { const r4 = $e(e2, n5); r4 && (t = r4); const o4 = Bn(e2, n5); o4 && (t = o4); } else t = S("MISSING_OR_INVALID", `${n5}, namespaces should be an object with data`); return t; } function Jn(e2) { return b(e2.protocol, true); } function eo(e2, n5) { let t = false; return n5 && !e2 ? t = true : e2 && L(e2) && e2.length && e2.forEach((r4) => { t = Jn(r4); }), t; } function no(e2) { return typeof e2 == "number"; } function to(e2) { return typeof e2 < "u" && typeof e2 !== null; } function ro(e2) { return !(!e2 || typeof e2 != "object" || !e2.code || !X(e2.code, false) || !e2.message || !b(e2.message, false)); } function oo(e2) { return !(I(e2) || !b(e2.method, false)); } function so(e2) { return !(I(e2) || I(e2.result) && I(e2.error) || !X(e2.id, false) || !b(e2.jsonrpc, false)); } function io(e2) { return !(I(e2) || !b(e2.name, false)); } function co(e2, n5) { return !(!F(n5) || !Un(e2).includes(n5)); } function ao(e2, n5, t) { return b(t, false) ? _n(e2, n5).includes(t) : false; } function uo(e2, n5, t) { return b(t, false) ? kn(e2, n5).includes(t) : false; } function zn(e2, n5, t) { let r4 = null; const o4 = lo(e2), s3 = fo(n5), i4 = Object.keys(o4), u3 = Object.keys(s3), l4 = Gn(Object.keys(e2)), c5 = Gn(Object.keys(n5)), d3 = l4.filter((a4) => !c5.includes(a4)); return d3.length && (r4 = S("NON_CONFORMING_NAMESPACES", `${t} namespaces keys don't satisfy requiredNamespaces. Required: ${d3.toString()} Received: ${Object.keys(n5).toString()}`)), $(i4, u3) || (r4 = S("NON_CONFORMING_NAMESPACES", `${t} namespaces chains don't satisfy required namespaces. Required: ${i4.toString()} Approved: ${u3.toString()}`)), Object.keys(n5).forEach((a4) => { if (!a4.includes(":") || r4) return; const f4 = C2(n5[a4].accounts); f4.includes(a4) || (r4 = S("NON_CONFORMING_NAMESPACES", `${t} namespaces accounts don't satisfy namespace accounts for ${a4} Required: ${a4} Approved: ${f4.toString()}`)); }), i4.forEach((a4) => { r4 || ($(o4[a4].methods, s3[a4].methods) ? $(o4[a4].events, s3[a4].events) || (r4 = S("NON_CONFORMING_NAMESPACES", `${t} namespaces events don't satisfy namespace events for ${a4}`)) : r4 = S("NON_CONFORMING_NAMESPACES", `${t} namespaces methods don't satisfy namespace methods for ${a4}`)); }), r4; } function lo(e2) { const n5 = {}; return Object.keys(e2).forEach((t) => { var r4; t.includes(":") ? n5[t] = e2[t] : (r4 = e2[t].chains) == null || r4.forEach((o4) => { n5[o4] = { methods: e2[t].methods, events: e2[t].events }; }); }), n5; } function Gn(e2) { return [...new Set(e2.map((n5) => n5.includes(":") ? n5.split(":")[0] : n5))]; } function fo(e2) { const n5 = {}; return Object.keys(e2).forEach((t) => { if (t.includes(":")) n5[t] = e2[t]; else { const r4 = C2(e2[t].accounts); r4 == null ? void 0 : r4.forEach((o4) => { n5[o4] = { accounts: e2[t].accounts.filter((s3) => s3.includes(`${o4}:`)), methods: e2[t].methods, events: e2[t].events }; }); } }), n5; } function po(e2, n5) { return X(e2, false) && e2 <= n5.max && e2 >= n5.min; } function mo() { const e2 = P(); return new Promise((n5) => { switch (e2) { case y.browser: n5(Yn()); break; case y.reactNative: n5(Qn()); break; case y.node: n5(Zn()); break; default: n5(true); } }); } function Yn() { return V() && (navigator == null ? void 0 : navigator.onLine); } async function Qn() { if (_() && typeof global < "u" && global != null && global.NetInfo) { const e2 = await (global == null ? void 0 : global.NetInfo.fetch()); return e2 == null ? void 0 : e2.isConnected; } return true; } function Zn() { return true; } function ho(e2) { switch (P()) { case y.browser: Xn(e2); break; case y.reactNative: et(e2); break; case y.node: break; } } function Xn(e2) { !_() && V() && (window.addEventListener("online", () => e2(true)), window.addEventListener("offline", () => e2(false))); } function et(e2) { _() && typeof global < "u" && global != null && global.NetInfo && (global == null ? void 0 : global.NetInfo.addEventListener((n5) => e2(n5 == null ? void 0 : n5.isConnected))); } var Re = {}; var yo = class { static get(n5) { return Re[n5]; } static set(n5, t) { Re[n5] = t; } static delete(n5) { delete Re[n5]; } }; // node_modules/@walletconnect/logger/dist/index.es.js var import_pino = __toESM(require_browser2()); var import_pino2 = __toESM(require_browser2()); var c = { level: "info" }; var n = "custom_context"; var l = 1e3 * 1024; var O2 = class { constructor(e2) { this.nodeValue = e2, this.sizeInBytes = new TextEncoder().encode(this.nodeValue).length, this.next = null; } get value() { return this.nodeValue; } get size() { return this.sizeInBytes; } }; var d = class { constructor(e2) { this.head = null, this.tail = null, this.lengthInNodes = 0, this.maxSizeInBytes = e2, this.sizeInBytes = 0; } append(e2) { const t = new O2(e2); if (t.size > this.maxSizeInBytes) throw new Error(`[LinkedList] Value too big to insert into list: ${e2} with size ${t.size}`); for (; this.size + t.size > this.maxSizeInBytes; ) this.shift(); this.head ? (this.tail && (this.tail.next = t), this.tail = t) : (this.head = t, this.tail = t), this.lengthInNodes++, this.sizeInBytes += t.size; } shift() { if (!this.head) return; const e2 = this.head; this.head = this.head.next, this.head || (this.tail = null), this.lengthInNodes--, this.sizeInBytes -= e2.size; } toArray() { const e2 = []; let t = this.head; for (; t !== null; ) e2.push(t.value), t = t.next; return e2; } get length() { return this.lengthInNodes; } get size() { return this.sizeInBytes; } toOrderedArray() { return Array.from(this); } [Symbol.iterator]() { let e2 = this.head; return { next: () => { if (!e2) return { done: true, value: null }; const t = e2.value; return e2 = e2.next, { done: false, value: t }; } }; } }; var L2 = class { constructor(e2, t = l) { this.level = e2 ?? "error", this.levelValue = import_pino.levels.values[this.level], this.MAX_LOG_SIZE_IN_BYTES = t, this.logs = new d(this.MAX_LOG_SIZE_IN_BYTES); } forwardToConsole(e2, t) { t === import_pino.levels.values.error ? console.error(e2) : t === import_pino.levels.values.warn ? console.warn(e2) : t === import_pino.levels.values.debug ? console.debug(e2) : t === import_pino.levels.values.trace ? console.trace(e2) : console.log(e2); } appendToLogs(e2) { this.logs.append(safeJsonStringify({ timestamp: (/* @__PURE__ */ new Date()).toISOString(), log: e2 })); const t = typeof e2 == "string" ? JSON.parse(e2).level : e2.level; t >= this.levelValue && this.forwardToConsole(e2, t); } getLogs() { return this.logs; } clearLogs() { this.logs = new d(this.MAX_LOG_SIZE_IN_BYTES); } getLogArray() { return Array.from(this.logs); } logsToBlob(e2) { const t = this.getLogArray(); return t.push(safeJsonStringify({ extraMetadata: e2 })), new Blob(t, { type: "application/json" }); } }; var m = class { constructor(e2, t = l) { this.baseChunkLogger = new L2(e2, t); } write(e2) { this.baseChunkLogger.appendToLogs(e2); } getLogs() { return this.baseChunkLogger.getLogs(); } clearLogs() { this.baseChunkLogger.clearLogs(); } getLogArray() { return this.baseChunkLogger.getLogArray(); } logsToBlob(e2) { return this.baseChunkLogger.logsToBlob(e2); } downloadLogsBlobInBrowser(e2) { const t = URL.createObjectURL(this.logsToBlob(e2)), o4 = document.createElement("a"); o4.href = t, o4.download = `walletconnect-logs-${(/* @__PURE__ */ new Date()).toISOString()}.txt`, document.body.appendChild(o4), o4.click(), document.body.removeChild(o4), URL.revokeObjectURL(t); } }; var B2 = class { constructor(e2, t = l) { this.baseChunkLogger = new L2(e2, t); } write(e2) { this.baseChunkLogger.appendToLogs(e2); } getLogs() { return this.baseChunkLogger.getLogs(); } clearLogs() { this.baseChunkLogger.clearLogs(); } getLogArray() { return this.baseChunkLogger.getLogArray(); } logsToBlob(e2) { return this.baseChunkLogger.logsToBlob(e2); } }; var x = Object.defineProperty; var S2 = Object.defineProperties; var _2 = Object.getOwnPropertyDescriptors; var p = Object.getOwnPropertySymbols; var T = Object.prototype.hasOwnProperty; var z2 = Object.prototype.propertyIsEnumerable; var f = (r4, e2, t) => e2 in r4 ? x(r4, e2, { enumerable: true, configurable: true, writable: true, value: t }) : r4[e2] = t; var i = (r4, e2) => { for (var t in e2 || (e2 = {})) T.call(e2, t) && f(r4, t, e2[t]); if (p) for (var t of p(e2)) z2.call(e2, t) && f(r4, t, e2[t]); return r4; }; var g2 = (r4, e2) => S2(r4, _2(e2)); function k2(r4) { return g2(i({}, r4), { level: (r4 == null ? void 0 : r4.level) || c.level }); } function v(r4, e2 = n) { return r4[e2] || ""; } function b2(r4, e2, t = n) { return r4[t] = e2, r4; } function y2(r4, e2 = n) { let t = ""; return typeof r4.bindings > "u" ? t = v(r4, e2) : t = r4.bindings().context || "", t; } function w(r4, e2, t = n) { const o4 = y2(r4, t); return o4.trim() ? `${o4}/${e2}` : e2; } function E(r4, e2, t = n) { const o4 = w(r4, e2, t), a4 = r4.child({ context: o4 }); return b2(a4, o4, t); } function C3(r4) { var e2, t; const o4 = new m((e2 = r4.opts) == null ? void 0 : e2.level, r4.maxSizeInBytes); return { logger: (0, import_pino.default)(g2(i({}, r4.opts), { level: "trace", browser: g2(i({}, (t = r4.opts) == null ? void 0 : t.browser), { write: (a4) => o4.write(a4) }) })), chunkLoggerController: o4 }; } function I2(r4) { var e2; const t = new B2((e2 = r4.opts) == null ? void 0 : e2.level, r4.maxSizeInBytes); return { logger: (0, import_pino.default)(g2(i({}, r4.opts), { level: "trace" }), t), chunkLoggerController: t }; } function A2(r4) { return typeof r4.loggerOverride < "u" && typeof r4.loggerOverride != "string" ? { logger: r4.loggerOverride, chunkLoggerController: null } : typeof window < "u" ? C3(r4) : I2(r4); } // node_modules/@walletconnect/jsonrpc-utils/dist/esm/constants.js var PARSE_ERROR = "PARSE_ERROR"; var INVALID_REQUEST = "INVALID_REQUEST"; var METHOD_NOT_FOUND = "METHOD_NOT_FOUND"; var INVALID_PARAMS = "INVALID_PARAMS"; var INTERNAL_ERROR = "INTERNAL_ERROR"; var SERVER_ERROR = "SERVER_ERROR"; var RESERVED_ERROR_CODES = [-32700, -32600, -32601, -32602, -32603]; var SERVER_ERROR_CODE_RANGE = [-32e3, -32099]; var STANDARD_ERROR_MAP = { [PARSE_ERROR]: { code: -32700, message: "Parse error" }, [INVALID_REQUEST]: { code: -32600, message: "Invalid Request" }, [METHOD_NOT_FOUND]: { code: -32601, message: "Method not found" }, [INVALID_PARAMS]: { code: -32602, message: "Invalid params" }, [INTERNAL_ERROR]: { code: -32603, message: "Internal error" }, [SERVER_ERROR]: { code: -32e3, message: "Server error" } }; var DEFAULT_ERROR = SERVER_ERROR; // node_modules/@walletconnect/jsonrpc-utils/dist/esm/error.js function isServerErrorCode(code2) { return code2 <= SERVER_ERROR_CODE_RANGE[0] && code2 >= SERVER_ERROR_CODE_RANGE[1]; } function isReservedErrorCode(code2) { return RESERVED_ERROR_CODES.includes(code2); } function isValidErrorCode(code2) { return typeof code2 === "number"; } function getError(type) { if (!Object.keys(STANDARD_ERROR_MAP).includes(type)) { return STANDARD_ERROR_MAP[DEFAULT_ERROR]; } return STANDARD_ERROR_MAP[type]; } function getErrorByCode(code2) { const match = Object.values(STANDARD_ERROR_MAP).find((e2) => e2.code === code2); if (!match) { return STANDARD_ERROR_MAP[DEFAULT_ERROR]; } return match; } function validateJsonRpcError(response) { if (typeof response.error.code === "undefined") { return { valid: false, error: "Missing code for JSON-RPC error" }; } if (typeof response.error.message === "undefined") { return { valid: false, error: "Missing message for JSON-RPC error" }; } if (!isValidErrorCode(response.error.code)) { return { valid: false, error: `Invalid error code type for JSON-RPC: ${response.error.code}` }; } if (isReservedErrorCode(response.error.code)) { const error = getErrorByCode(response.error.code); if (error.message !== STANDARD_ERROR_MAP[DEFAULT_ERROR].message && response.error.message === error.message) { return { valid: false, error: `Invalid error code message for JSON-RPC: ${response.error.code}` }; } } return { valid: true }; } function parseConnectionError(e2, url, type) { return e2.message.includes("getaddrinfo ENOTFOUND") || e2.message.includes("connect ECONNREFUSED") ? new Error(`Unavailable ${type} RPC url at ${url}`) : e2; } // node_modules/@walletconnect/jsonrpc-utils/dist/esm/format.js function payloadId(entropy = 3) { const date = Date.now() * Math.pow(10, entropy); const extra = Math.floor(Math.random() * Math.pow(10, entropy)); return date + extra; } function getBigIntRpcId(entropy = 6) { return BigInt(payloadId(entropy)); } function formatJsonRpcRequest(method, params, id2) { return { id: id2 || payloadId(), jsonrpc: "2.0", method, params }; } function formatJsonRpcResult(id2, result) { return { id: id2, jsonrpc: "2.0", result }; } function formatJsonRpcError(id2, error, data) { return { id: id2, jsonrpc: "2.0", error: formatErrorMessage(error, data) }; } function formatErrorMessage(error, data) { if (typeof error === "undefined") { return getError(INTERNAL_ERROR); } if (typeof error === "string") { error = Object.assign(Object.assign({}, getError(SERVER_ERROR)), { message: error }); } if (typeof data !== "undefined") { error.data = data; } if (isReservedErrorCode(error.code)) { error = getErrorByCode(error.code); } return error; } // node_modules/@walletconnect/jsonrpc-utils/dist/esm/index.js var esm_exports = {}; __export(esm_exports, { DEFAULT_ERROR: () => DEFAULT_ERROR, IBaseJsonRpcProvider: () => n2, IEvents: () => e, IJsonRpcConnection: () => o, IJsonRpcProvider: () => r2, INTERNAL_ERROR: () => INTERNAL_ERROR, INVALID_PARAMS: () => INVALID_PARAMS, INVALID_REQUEST: () => INVALID_REQUEST, METHOD_NOT_FOUND: () => METHOD_NOT_FOUND, PARSE_ERROR: () => PARSE_ERROR, RESERVED_ERROR_CODES: () => RESERVED_ERROR_CODES, SERVER_ERROR: () => SERVER_ERROR, SERVER_ERROR_CODE_RANGE: () => SERVER_ERROR_CODE_RANGE, STANDARD_ERROR_MAP: () => STANDARD_ERROR_MAP, formatErrorMessage: () => formatErrorMessage, formatJsonRpcError: () => formatJsonRpcError, formatJsonRpcRequest: () => formatJsonRpcRequest, formatJsonRpcResult: () => formatJsonRpcResult, getBigIntRpcId: () => getBigIntRpcId, getError: () => getError, getErrorByCode: () => getErrorByCode, isHttpUrl: () => isHttpUrl, isJsonRpcError: () => isJsonRpcError, isJsonRpcPayload: () => isJsonRpcPayload, isJsonRpcRequest: () => isJsonRpcRequest, isJsonRpcResponse: () => isJsonRpcResponse, isJsonRpcResult: () => isJsonRpcResult, isJsonRpcValidationInvalid: () => isJsonRpcValidationInvalid, isLocalhostUrl: () => isLocalhostUrl, isNodeJs: () => isNodeJs, isReservedErrorCode: () => isReservedErrorCode, isServerErrorCode: () => isServerErrorCode, isValidDefaultRoute: () => isValidDefaultRoute, isValidErrorCode: () => isValidErrorCode, isValidLeadingWildcardRoute: () => isValidLeadingWildcardRoute, isValidRoute: () => isValidRoute, isValidTrailingWildcardRoute: () => isValidTrailingWildcardRoute, isValidWildcardRoute: () => isValidWildcardRoute, isWsUrl: () => isWsUrl, parseConnectionError: () => parseConnectionError, payloadId: () => payloadId, validateJsonRpcError: () => validateJsonRpcError }); // node_modules/@walletconnect/jsonrpc-utils/dist/esm/env.js var env_exports = {}; __export(env_exports, { isNodeJs: () => isNodeJs }); var import_environment = __toESM(require_cjs4()); __reExport(env_exports, __toESM(require_cjs4())); var isNodeJs = import_environment.isNode; // node_modules/@walletconnect/jsonrpc-utils/dist/esm/index.js __reExport(esm_exports, env_exports); // node_modules/@walletconnect/jsonrpc-utils/dist/esm/routing.js function isValidRoute(route) { if (route.includes("*")) { return isValidWildcardRoute(route); } if (/\W/g.test(route)) { return false; } return true; } function isValidDefaultRoute(route) { return route === "*"; } function isValidWildcardRoute(route) { if (isValidDefaultRoute(route)) { return true; } if (!route.includes("*")) { return false; } if (route.split("*").length !== 2) { return false; } if (route.split("*").filter((x6) => x6.trim() === "").length !== 1) { return false; } return true; } function isValidLeadingWildcardRoute(route) { return !isValidDefaultRoute(route) && isValidWildcardRoute(route) && !route.split("*")[0].trim(); } function isValidTrailingWildcardRoute(route) { return !isValidDefaultRoute(route) && isValidWildcardRoute(route) && !route.split("*")[1].trim(); } // node_modules/@walletconnect/jsonrpc-types/dist/index.es.js var e = class { }; var o = class extends e { constructor(c5) { super(); } }; var n2 = class extends e { constructor() { super(); } }; var r2 = class extends n2 { constructor(c5) { super(); } }; // node_modules/@walletconnect/jsonrpc-utils/dist/esm/url.js var HTTP_REGEX = "^https?:"; var WS_REGEX = "^wss?:"; function getUrlProtocol(url) { const matches = url.match(new RegExp(/^\w+:/, "gi")); if (!matches || !matches.length) return; return matches[0]; } function matchRegexProtocol(url, regex) { const protocol = getUrlProtocol(url); if (typeof protocol === "undefined") return false; return new RegExp(regex).test(protocol); } function isHttpUrl(url) { return matchRegexProtocol(url, HTTP_REGEX); } function isWsUrl(url) { return matchRegexProtocol(url, WS_REGEX); } function isLocalhostUrl(url) { return new RegExp("wss?://localhost(:d{2,5})?").test(url); } // node_modules/@walletconnect/jsonrpc-utils/dist/esm/validators.js function isJsonRpcPayload(payload) { return typeof payload === "object" && "id" in payload && "jsonrpc" in payload && payload.jsonrpc === "2.0"; } function isJsonRpcRequest(payload) { return isJsonRpcPayload(payload) && "method" in payload; } function isJsonRpcResponse(payload) { return isJsonRpcPayload(payload) && (isJsonRpcResult(payload) || isJsonRpcError(payload)); } function isJsonRpcResult(payload) { return "result" in payload; } function isJsonRpcError(payload) { return "error" in payload; } function isJsonRpcValidationInvalid(validation) { return "error" in validation && validation.valid === false; } // node_modules/@walletconnect/jsonrpc-provider/dist/index.es.js var import_events = __toESM(require_events()); var o2 = class extends r2 { constructor(t) { super(t), this.events = new import_events.EventEmitter(), this.hasRegisteredEventListeners = false, this.connection = this.setConnection(t), this.connection.connected && this.registerEventListeners(); } async connect(t = this.connection) { await this.open(t); } async disconnect() { await this.close(); } on(t, e2) { this.events.on(t, e2); } once(t, e2) { this.events.once(t, e2); } off(t, e2) { this.events.off(t, e2); } removeListener(t, e2) { this.events.removeListener(t, e2); } async request(t, e2) { return this.requestStrict(formatJsonRpcRequest(t.method, t.params || [], t.id || getBigIntRpcId().toString()), e2); } async requestStrict(t, e2) { return new Promise(async (i4, s3) => { if (!this.connection.connected) try { await this.open(); } catch (n5) { s3(n5); } this.events.on(`${t.id}`, (n5) => { isJsonRpcError(n5) ? s3(n5.error) : i4(n5.result); }); try { await this.connection.send(t, e2); } catch (n5) { s3(n5); } }); } setConnection(t = this.connection) { return t; } onPayload(t) { this.events.emit("payload", t), isJsonRpcResponse(t) ? this.events.emit(`${t.id}`, t) : this.events.emit("message", { type: t.method, data: t.params }); } onClose(t) { t && t.code === 3e3 && this.events.emit("error", new Error(`WebSocket connection closed abnormally with code: ${t.code} ${t.reason ? `(${t.reason})` : ""}`)), this.events.emit("disconnect"); } async open(t = this.connection) { this.connection === t && this.connection.connected || (this.connection.connected && this.close(), typeof t == "string" && (await this.connection.open(t), t = this.connection), this.connection = this.setConnection(t), await this.connection.open(), this.registerEventListeners(), this.events.emit("connect")); } async close() { await this.connection.close(); } registerEventListeners() { this.hasRegisteredEventListeners || (this.connection.on("payload", (t) => this.onPayload(t)), this.connection.on("close", (t) => this.onClose(t)), this.connection.on("error", (t) => this.events.emit("error", t)), this.connection.on("register_error", (t) => this.onClose()), this.hasRegisteredEventListeners = true); } }; // node_modules/@walletconnect/core/dist/index.es.js var import_events7 = __toESM(require_events()); // node_modules/@walletconnect/heartbeat/dist/index.es.js var import_events2 = __toESM(require_events()); var import_time3 = __toESM(require_cjs()); // node_modules/@walletconnect/events/dist/esm/events.js var IEvents = class { }; // node_modules/@walletconnect/heartbeat/dist/index.es.js var n3 = class extends IEvents { constructor(e2) { super(); } }; var s2 = import_time3.FIVE_SECONDS; var r3 = { pulse: "heartbeat_pulse" }; var i2 = class _i extends n3 { constructor(e2) { super(e2), this.events = new import_events2.EventEmitter(), this.interval = s2, this.interval = (e2 == null ? void 0 : e2.interval) || s2; } static async init(e2) { const t = new _i(e2); return await t.init(), t; } async init() { await this.initialize(); } stop() { clearInterval(this.intervalRef); } on(e2, t) { this.events.on(e2, t); } once(e2, t) { this.events.once(e2, t); } off(e2, t) { this.events.off(e2, t); } removeListener(e2, t) { this.events.removeListener(e2, t); } async initialize() { this.intervalRef = setInterval(() => this.pulse(), (0, import_time3.toMiliseconds)(this.interval)); } pulse() { this.events.emit(r3.pulse); } }; // node_modules/destr/dist/index.mjs var suspectProtoRx = /"(?:_|\\u0{2}5[Ff]){2}(?:p|\\u0{2}70)(?:r|\\u0{2}72)(?:o|\\u0{2}6[Ff])(?:t|\\u0{2}74)(?:o|\\u0{2}6[Ff])(?:_|\\u0{2}5[Ff]){2}"\s*:/; var suspectConstructorRx = /"(?:c|\\u0063)(?:o|\\u006[Ff])(?:n|\\u006[Ee])(?:s|\\u0073)(?:t|\\u0074)(?:r|\\u0072)(?:u|\\u0075)(?:c|\\u0063)(?:t|\\u0074)(?:o|\\u006[Ff])(?:r|\\u0072)"\s*:/; var JsonSigRx = /^\s*["[{]|^\s*-?\d{1,16}(\.\d{1,17})?([Ee][+-]?\d+)?\s*$/; function jsonParseTransform(key2, value) { if (key2 === "__proto__" || key2 === "constructor" && value && typeof value === "object" && "prototype" in value) { warnKeyDropped(key2); return; } return value; } function warnKeyDropped(key2) { console.warn(`[destr] Dropping "${key2}" key to prevent prototype pollution.`); } function destr(value, options = {}) { if (typeof value !== "string") { return value; } const _value = value.trim(); if ( // eslint-disable-next-line unicorn/prefer-at value[0] === '"' && value.endsWith('"') && !value.includes("\\") ) { return _value.slice(1, -1); } if (_value.length <= 9) { const _lval = _value.toLowerCase(); if (_lval === "true") { return true; } if (_lval === "false") { return false; } if (_lval === "undefined") { return void 0; } if (_lval === "null") { return null; } if (_lval === "nan") { return Number.NaN; } if (_lval === "infinity") { return Number.POSITIVE_INFINITY; } if (_lval === "-infinity") { return Number.NEGATIVE_INFINITY; } } if (!JsonSigRx.test(value)) { if (options.strict) { throw new SyntaxError("[destr] Invalid JSON"); } return value; } try { if (suspectProtoRx.test(value) || suspectConstructorRx.test(value)) { if (options.strict) { throw new Error("[destr] Possible prototype pollution"); } return JSON.parse(value, jsonParseTransform); } return JSON.parse(value); } catch (error) { if (options.strict) { throw error; } return value; } } // node_modules/unstorage/dist/shared/unstorage.d569726e.mjs function wrapToPromise(value) { if (!value || typeof value.then !== "function") { return Promise.resolve(value); } return value; } function asyncCall(function_, ...arguments_) { try { return wrapToPromise(function_(...arguments_)); } catch (error) { return Promise.reject(error); } } function isPrimitive(value) { const type = typeof value; return value === null || type !== "object" && type !== "function"; } function isPureObject(value) { const proto = Object.getPrototypeOf(value); return !proto || proto.isPrototypeOf(Object); } function stringify2(value) { if (isPrimitive(value)) { return String(value); } if (isPureObject(value) || Array.isArray(value)) { return JSON.stringify(value); } if (typeof value.toJSON === "function") { return stringify2(value.toJSON()); } throw new Error("[unstorage] Cannot stringify value!"); } function checkBufferSupport() { if (typeof Buffer === "undefined") { throw new TypeError("[unstorage] Buffer is not supported!"); } } var BASE64_PREFIX = "base64:"; function serializeRaw(value) { if (typeof value === "string") { return value; } checkBufferSupport(); const base642 = Buffer.from(value).toString("base64"); return BASE64_PREFIX + base642; } function deserializeRaw(value) { if (typeof value !== "string") { return value; } if (!value.startsWith(BASE64_PREFIX)) { return value; } checkBufferSupport(); return Buffer.from(value.slice(BASE64_PREFIX.length), "base64"); } function normalizeKey(key2) { if (!key2) { return ""; } return key2.split("?")[0].replace(/[/\\]/g, ":").replace(/:+/g, ":").replace(/^:|:$/g, ""); } function joinKeys(...keys2) { return normalizeKey(keys2.join(":")); } function normalizeBaseKey(base3) { base3 = normalizeKey(base3); return base3 ? base3 + ":" : ""; } // node_modules/unstorage/dist/index.mjs function defineDriver(factory) { return factory; } var DRIVER_NAME = "memory"; var memory = defineDriver(() => { const data = /* @__PURE__ */ new Map(); return { name: DRIVER_NAME, getInstance: () => data, hasItem(key2) { return data.has(key2); }, getItem(key2) { return data.get(key2) ?? null; }, getItemRaw(key2) { return data.get(key2) ?? null; }, setItem(key2, value) { data.set(key2, value); }, setItemRaw(key2, value) { data.set(key2, value); }, removeItem(key2) { data.delete(key2); }, getKeys() { return [...data.keys()]; }, clear() { data.clear(); }, dispose() { data.clear(); } }; }); function createStorage(options = {}) { const context = { mounts: { "": options.driver || memory() }, mountpoints: [""], watching: false, watchListeners: [], unwatch: {} }; const getMount = (key2) => { for (const base3 of context.mountpoints) { if (key2.startsWith(base3)) { return { base: base3, relativeKey: key2.slice(base3.length), driver: context.mounts[base3] }; } } return { base: "", relativeKey: key2, driver: context.mounts[""] }; }; const getMounts = (base3, includeParent) => { return context.mountpoints.filter( (mountpoint) => mountpoint.startsWith(base3) || includeParent && base3.startsWith(mountpoint) ).map((mountpoint) => ({ relativeBase: base3.length > mountpoint.length ? base3.slice(mountpoint.length) : void 0, mountpoint, driver: context.mounts[mountpoint] })); }; const onChange = (event, key2) => { if (!context.watching) { return; } key2 = normalizeKey(key2); for (const listener of context.watchListeners) { listener(event, key2); } }; const startWatch = async () => { if (context.watching) { return; } context.watching = true; for (const mountpoint in context.mounts) { context.unwatch[mountpoint] = await watch( context.mounts[mountpoint], onChange, mountpoint ); } }; const stopWatch = async () => { if (!context.watching) { return; } for (const mountpoint in context.unwatch) { await context.unwatch[mountpoint](); } context.unwatch = {}; context.watching = false; }; const runBatch = (items, commonOptions, cb) => { const batches = /* @__PURE__ */ new Map(); const getBatch = (mount) => { let batch = batches.get(mount.base); if (!batch) { batch = { driver: mount.driver, base: mount.base, items: [] }; batches.set(mount.base, batch); } return batch; }; for (const item of items) { const isStringItem = typeof item === "string"; const key2 = normalizeKey(isStringItem ? item : item.key); const value = isStringItem ? void 0 : item.value; const options2 = isStringItem || !item.options ? commonOptions : { ...commonOptions, ...item.options }; const mount = getMount(key2); getBatch(mount).items.push({ key: key2, value, relativeKey: mount.relativeKey, options: options2 }); } return Promise.all([...batches.values()].map((batch) => cb(batch))).then( (r4) => r4.flat() ); }; const storage = { // Item hasItem(key2, opts = {}) { key2 = normalizeKey(key2); const { relativeKey, driver } = getMount(key2); return asyncCall(driver.hasItem, relativeKey, opts); }, getItem(key2, opts = {}) { key2 = normalizeKey(key2); const { relativeKey, driver } = getMount(key2); return asyncCall(driver.getItem, relativeKey, opts).then( (value) => destr(value) ); }, getItems(items, commonOptions) { return runBatch(items, commonOptions, (batch) => { if (batch.driver.getItems) { return asyncCall( batch.driver.getItems, batch.items.map((item) => ({ key: item.relativeKey, options: item.options })), commonOptions ).then( (r4) => r4.map((item) => ({ key: joinKeys(batch.base, item.key), value: destr(item.value) })) ); } return Promise.all( batch.items.map((item) => { return asyncCall( batch.driver.getItem, item.relativeKey, item.options ).then((value) => ({ key: item.key, value: destr(value) })); }) ); }); }, getItemRaw(key2, opts = {}) { key2 = normalizeKey(key2); const { relativeKey, driver } = getMount(key2); if (driver.getItemRaw) { return asyncCall(driver.getItemRaw, relativeKey, opts); } return asyncCall(driver.getItem, relativeKey, opts).then( (value) => deserializeRaw(value) ); }, async setItem(key2, value, opts = {}) { if (value === void 0) { return storage.removeItem(key2); } key2 = normalizeKey(key2); const { relativeKey, driver } = getMount(key2); if (!driver.setItem) { return; } await asyncCall(driver.setItem, relativeKey, stringify2(value), opts); if (!driver.watch) { onChange("update", key2); } }, async setItems(items, commonOptions) { await runBatch(items, commonOptions, async (batch) => { if (batch.driver.setItems) { return asyncCall( batch.driver.setItems, batch.items.map((item) => ({ key: item.relativeKey, value: stringify2(item.value), options: item.options })), commonOptions ); } if (!batch.driver.setItem) { return; } await Promise.all( batch.items.map((item) => { return asyncCall( batch.driver.setItem, item.relativeKey, stringify2(item.value), item.options ); }) ); }); }, async setItemRaw(key2, value, opts = {}) { if (value === void 0) { return storage.removeItem(key2, opts); } key2 = normalizeKey(key2); const { relativeKey, driver } = getMount(key2); if (driver.setItemRaw) { await asyncCall(driver.setItemRaw, relativeKey, value, opts); } else if (driver.setItem) { await asyncCall(driver.setItem, relativeKey, serializeRaw(value), opts); } else { return; } if (!driver.watch) { onChange("update", key2); } }, async removeItem(key2, opts = {}) { if (typeof opts === "boolean") { opts = { removeMeta: opts }; } key2 = normalizeKey(key2); const { relativeKey, driver } = getMount(key2); if (!driver.removeItem) { return; } await asyncCall(driver.removeItem, relativeKey, opts); if (opts.removeMeta || opts.removeMata) { await asyncCall(driver.removeItem, relativeKey + "$", opts); } if (!driver.watch) { onChange("remove", key2); } }, // Meta async getMeta(key2, opts = {}) { if (typeof opts === "boolean") { opts = { nativeOnly: opts }; } key2 = normalizeKey(key2); const { relativeKey, driver } = getMount(key2); const meta = /* @__PURE__ */ Object.create(null); if (driver.getMeta) { Object.assign(meta, await asyncCall(driver.getMeta, relativeKey, opts)); } if (!opts.nativeOnly) { const value = await asyncCall( driver.getItem, relativeKey + "$", opts ).then((value_) => destr(value_)); if (value && typeof value === "object") { if (typeof value.atime === "string") { value.atime = new Date(value.atime); } if (typeof value.mtime === "string") { value.mtime = new Date(value.mtime); } Object.assign(meta, value); } } return meta; }, setMeta(key2, value, opts = {}) { return this.setItem(key2 + "$", value, opts); }, removeMeta(key2, opts = {}) { return this.removeItem(key2 + "$", opts); }, // Keys async getKeys(base3, opts = {}) { base3 = normalizeBaseKey(base3); const mounts = getMounts(base3, true); let maskedMounts = []; const allKeys = []; for (const mount of mounts) { const rawKeys = await asyncCall( mount.driver.getKeys, mount.relativeBase, opts ); for (const key2 of rawKeys) { const fullKey = mount.mountpoint + normalizeKey(key2); if (!maskedMounts.some((p3) => fullKey.startsWith(p3))) { allKeys.push(fullKey); } } maskedMounts = [ mount.mountpoint, ...maskedMounts.filter((p3) => !p3.startsWith(mount.mountpoint)) ]; } return base3 ? allKeys.filter( (key2) => key2.startsWith(base3) && key2[key2.length - 1] !== "$" ) : allKeys.filter((key2) => key2[key2.length - 1] !== "$"); }, // Utils async clear(base3, opts = {}) { base3 = normalizeBaseKey(base3); await Promise.all( getMounts(base3, false).map(async (m2) => { if (m2.driver.clear) { return asyncCall(m2.driver.clear, m2.relativeBase, opts); } if (m2.driver.removeItem) { const keys2 = await m2.driver.getKeys(m2.relativeBase || "", opts); return Promise.all( keys2.map((key2) => m2.driver.removeItem(key2, opts)) ); } }) ); }, async dispose() { await Promise.all( Object.values(context.mounts).map((driver) => dispose(driver)) ); }, async watch(callback) { await startWatch(); context.watchListeners.push(callback); return async () => { context.watchListeners = context.watchListeners.filter( (listener) => listener !== callback ); if (context.watchListeners.length === 0) { await stopWatch(); } }; }, async unwatch() { context.watchListeners = []; await stopWatch(); }, // Mount mount(base3, driver) { base3 = normalizeBaseKey(base3); if (base3 && context.mounts[base3]) { throw new Error(`already mounted at ${base3}`); } if (base3) { context.mountpoints.push(base3); context.mountpoints.sort((a4, b5) => b5.length - a4.length); } context.mounts[base3] = driver; if (context.watching) { Promise.resolve(watch(driver, onChange, base3)).then((unwatcher) => { context.unwatch[base3] = unwatcher; }).catch(console.error); } return storage; }, async unmount(base3, _dispose = true) { base3 = normalizeBaseKey(base3); if (!base3 || !context.mounts[base3]) { return; } if (context.watching && base3 in context.unwatch) { context.unwatch[base3](); delete context.unwatch[base3]; } if (_dispose) { await dispose(context.mounts[base3]); } context.mountpoints = context.mountpoints.filter((key2) => key2 !== base3); delete context.mounts[base3]; }, getMount(key2 = "") { key2 = normalizeKey(key2) + ":"; const m2 = getMount(key2); return { driver: m2.driver, base: m2.base }; }, getMounts(base3 = "", opts = {}) { base3 = normalizeKey(base3); const mounts = getMounts(base3, opts.parents); return mounts.map((m2) => ({ driver: m2.driver, base: m2.mountpoint })); }, // Aliases keys: (base3, opts = {}) => storage.getKeys(base3, opts), get: (key2, opts = {}) => storage.getItem(key2, opts), set: (key2, value, opts = {}) => storage.setItem(key2, value, opts), has: (key2, opts = {}) => storage.hasItem(key2, opts), del: (key2, opts = {}) => storage.removeItem(key2, opts), remove: (key2, opts = {}) => storage.removeItem(key2, opts) }; return storage; } function watch(driver, onChange, base3) { return driver.watch ? driver.watch((event, key2) => onChange(event, base3 + key2)) : () => { }; } async function dispose(driver) { if (typeof driver.dispose === "function") { await asyncCall(driver.dispose); } } // node_modules/idb-keyval/dist/index.js function promisifyRequest(request) { return new Promise((resolve, reject) => { request.oncomplete = request.onsuccess = () => resolve(request.result); request.onabort = request.onerror = () => reject(request.error); }); } function createStore(dbName, storeName) { const request = indexedDB.open(dbName); request.onupgradeneeded = () => request.result.createObjectStore(storeName); const dbp = promisifyRequest(request); return (txMode, callback) => dbp.then((db) => callback(db.transaction(storeName, txMode).objectStore(storeName))); } var defaultGetStoreFunc; function defaultGetStore() { if (!defaultGetStoreFunc) { defaultGetStoreFunc = createStore("keyval-store", "keyval"); } return defaultGetStoreFunc; } function get(key2, customStore = defaultGetStore()) { return customStore("readonly", (store) => promisifyRequest(store.get(key2))); } function set(key2, value, customStore = defaultGetStore()) { return customStore("readwrite", (store) => { store.put(value, key2); return promisifyRequest(store.transaction); }); } function del(key2, customStore = defaultGetStore()) { return customStore("readwrite", (store) => { store.delete(key2); return promisifyRequest(store.transaction); }); } function clear(customStore = defaultGetStore()) { return customStore("readwrite", (store) => { store.clear(); return promisifyRequest(store.transaction); }); } function eachCursor(store, callback) { store.openCursor().onsuccess = function() { if (!this.result) return; callback(this.result); this.result.continue(); }; return promisifyRequest(store.transaction); } function keys(customStore = defaultGetStore()) { return customStore("readonly", (store) => { if (store.getAllKeys) { return promisifyRequest(store.getAllKeys()); } const items = []; return eachCursor(store, (cursor) => items.push(cursor.key)).then(() => items); }); } // node_modules/@walletconnect/keyvaluestorage/dist/index.es.js var x2 = "idb-keyval"; var z3 = (i4 = {}) => { const t = i4.base && i4.base.length > 0 ? `${i4.base}:` : "", e2 = (s3) => t + s3; let n5; return i4.dbName && i4.storeName && (n5 = createStore(i4.dbName, i4.storeName)), { name: x2, options: i4, async hasItem(s3) { return !(typeof await get(e2(s3), n5) > "u"); }, async getItem(s3) { return await get(e2(s3), n5) ?? null; }, setItem(s3, a4) { return set(e2(s3), a4, n5); }, removeItem(s3) { return del(e2(s3), n5); }, getKeys() { return keys(n5); }, clear() { return clear(n5); } }; }; var D2 = "WALLET_CONNECT_V2_INDEXED_DB"; var E2 = "keyvaluestorage"; var _3 = class { constructor() { this.indexedDb = createStorage({ driver: z3({ dbName: D2, storeName: E2 }) }); } async getKeys() { return this.indexedDb.getKeys(); } async getEntries() { return (await this.indexedDb.getItems(await this.indexedDb.getKeys())).map((t) => [t.key, t.value]); } async getItem(t) { const e2 = await this.indexedDb.getItem(t); if (e2 !== null) return e2; } async setItem(t, e2) { await this.indexedDb.setItem(t, safeJsonStringify(e2)); } async removeItem(t) { await this.indexedDb.removeItem(t); } }; var l3 = typeof globalThis < "u" ? globalThis : typeof window < "u" ? window : typeof global < "u" ? global : typeof self < "u" ? self : {}; var c3 = { exports: {} }; (function() { let i4; function t() { } i4 = t, i4.prototype.getItem = function(e2) { return this.hasOwnProperty(e2) ? String(this[e2]) : null; }, i4.prototype.setItem = function(e2, n5) { this[e2] = String(n5); }, i4.prototype.removeItem = function(e2) { delete this[e2]; }, i4.prototype.clear = function() { const e2 = this; Object.keys(e2).forEach(function(n5) { e2[n5] = void 0, delete e2[n5]; }); }, i4.prototype.key = function(e2) { return e2 = e2 || 0, Object.keys(this)[e2]; }, i4.prototype.__defineGetter__("length", function() { return Object.keys(this).length; }), typeof l3 < "u" && l3.localStorage ? c3.exports = l3.localStorage : typeof window < "u" && window.localStorage ? c3.exports = window.localStorage : c3.exports = new t(); })(); function k3(i4) { var t; return [i4[0], safeJsonParse((t = i4[1]) != null ? t : "")]; } var K2 = class { constructor() { this.localStorage = c3.exports; } async getKeys() { return Object.keys(this.localStorage); } async getEntries() { return Object.entries(this.localStorage).map(k3); } async getItem(t) { const e2 = this.localStorage.getItem(t); if (e2 !== null) return safeJsonParse(e2); } async setItem(t, e2) { this.localStorage.setItem(t, safeJsonStringify(e2)); } async removeItem(t) { this.localStorage.removeItem(t); } }; var N10 = "wc_storage_version"; var y3 = 1; var O3 = async (i4, t, e2) => { const n5 = N10, s3 = await t.getItem(n5); if (s3 && s3 >= y3) { e2(t); return; } const a4 = await i4.getKeys(); if (!a4.length) { e2(t); return; } const m2 = []; for (; a4.length; ) { const r4 = a4.shift(); if (!r4) continue; const o4 = r4.toLowerCase(); if (o4.includes("wc@") || o4.includes("walletconnect") || o4.includes("wc_") || o4.includes("wallet_connect")) { const f4 = await i4.getItem(r4); await t.setItem(r4, f4), m2.push(r4); } } await t.setItem(n5, y3), e2(t), j(i4, m2); }; var j = async (i4, t) => { t.length && t.forEach(async (e2) => { await i4.removeItem(e2); }); }; var h2 = class { constructor() { this.initialized = false, this.setInitialized = (e2) => { this.storage = e2, this.initialized = true; }; const t = new K2(); this.storage = t; try { const e2 = new _3(); O3(t, e2, this.setInitialized); } catch { this.initialized = true; } } async getKeys() { return await this.initialize(), this.storage.getKeys(); } async getEntries() { return await this.initialize(), this.storage.getEntries(); } async getItem(t) { return await this.initialize(), this.storage.getItem(t); } async setItem(t, e2) { return await this.initialize(), this.storage.setItem(t, e2); } async removeItem(t) { return await this.initialize(), this.storage.removeItem(t); } async initialize() { this.initialized || await new Promise((t) => { const e2 = setInterval(() => { this.initialized && (clearInterval(e2), t()); }, 20); }); } }; // node_modules/@walletconnect/types/dist/index.es.js var import_events5 = __toESM(require_events()); var n4 = class extends IEvents { constructor(s3) { super(), this.opts = s3, this.protocol = "wc", this.version = 2; } }; var h3 = class extends IEvents { constructor(s3, t) { super(), this.core = s3, this.logger = t, this.records = /* @__PURE__ */ new Map(); } }; var a2 = class { constructor(s3, t) { this.logger = s3, this.core = t; } }; var g3 = class extends IEvents { constructor(s3, t) { super(), this.relayer = s3, this.logger = t; } }; var u = class extends IEvents { constructor(s3) { super(); } }; var p2 = class { constructor(s3, t, e2, f4) { this.core = s3, this.logger = t, this.name = e2; } }; var d2 = class extends IEvents { constructor(s3, t) { super(), this.relayer = s3, this.logger = t; } }; var x3 = class extends IEvents { constructor(s3, t) { super(), this.core = s3, this.logger = t; } }; var y4 = class { constructor(s3, t, e2) { this.core = s3, this.logger = t, this.store = e2; } }; var v2 = class { constructor(s3, t) { this.projectId = s3, this.logger = t; } }; var C4 = class { constructor(s3, t, e2) { this.core = s3, this.logger = t, this.telemetryEnabled = e2; } }; var S3 = class { constructor(s3) { this.opts = s3, this.protocol = "wc", this.version = 2; } }; var M2 = class { constructor(s3) { this.client = s3; } }; // node_modules/@walletconnect/core/dist/index.es.js var import_time4 = __toESM(require_cjs()); // node_modules/@walletconnect/jsonrpc-ws-connection/dist/index.es.js var import_events6 = __toESM(require_events()); var w2 = () => typeof WebSocket < "u" ? WebSocket : typeof global < "u" && typeof global.WebSocket < "u" ? global.WebSocket : typeof window < "u" && typeof window.WebSocket < "u" ? window.WebSocket : typeof self < "u" && typeof self.WebSocket < "u" ? self.WebSocket : require_browser3(); var b3 = () => typeof WebSocket < "u" || typeof global < "u" && typeof global.WebSocket < "u" || typeof window < "u" && typeof window.WebSocket < "u" || typeof self < "u" && typeof self.WebSocket < "u"; var a3 = (c5) => c5.split("?")[0]; var h4 = 10; var S4 = w2(); var f2 = class { constructor(e2) { if (this.url = e2, this.events = new import_events6.EventEmitter(), this.registering = false, !isWsUrl(e2)) throw new Error(`Provided URL is not compatible with WebSocket connection: ${e2}`); this.url = e2; } get connected() { return typeof this.socket < "u"; } get connecting() { return this.registering; } on(e2, t) { this.events.on(e2, t); } once(e2, t) { this.events.once(e2, t); } off(e2, t) { this.events.off(e2, t); } removeListener(e2, t) { this.events.removeListener(e2, t); } async open(e2 = this.url) { await this.register(e2); } async close() { return new Promise((e2, t) => { if (typeof this.socket > "u") { t(new Error("Connection already closed")); return; } this.socket.onclose = (n5) => { this.onClose(n5), e2(); }, this.socket.close(); }); } async send(e2) { typeof this.socket > "u" && (this.socket = await this.register()); try { this.socket.send(safeJsonStringify(e2)); } catch (t) { this.onError(e2.id, t); } } register(e2 = this.url) { if (!isWsUrl(e2)) throw new Error(`Provided URL is not compatible with WebSocket connection: ${e2}`); if (this.registering) { const t = this.events.getMaxListeners(); return (this.events.listenerCount("register_error") >= t || this.events.listenerCount("open") >= t) && this.events.setMaxListeners(t + 1), new Promise((n5, o4) => { this.events.once("register_error", (s3) => { this.resetMaxListeners(), o4(s3); }), this.events.once("open", () => { if (this.resetMaxListeners(), typeof this.socket > "u") return o4(new Error("WebSocket connection is missing or invalid")); n5(this.socket); }); }); } return this.url = e2, this.registering = true, new Promise((t, n5) => { const o4 = new URLSearchParams(e2).get("origin"), s3 = (0, esm_exports.isReactNative)() ? { headers: { origin: o4 } } : { rejectUnauthorized: !isLocalhostUrl(e2) }, i4 = new S4(e2, [], s3); b3() ? i4.onerror = (r4) => { const l4 = r4; n5(this.emitError(l4.error)); } : i4.on("error", (r4) => { n5(this.emitError(r4)); }), i4.onopen = () => { this.onOpen(i4), t(i4); }; }); } onOpen(e2) { e2.onmessage = (t) => this.onPayload(t), e2.onclose = (t) => this.onClose(t), this.socket = e2, this.registering = false, this.events.emit("open"); } onClose(e2) { this.socket = void 0, this.registering = false, this.events.emit("close", e2); } onPayload(e2) { if (typeof e2.data > "u") return; const t = typeof e2.data == "string" ? safeJsonParse(e2.data) : e2.data; this.events.emit("payload", t); } onError(e2, t) { const n5 = this.parseError(t), o4 = n5.message || n5.toString(), s3 = formatJsonRpcError(e2, o4); this.events.emit("payload", s3); } parseError(e2, t = this.url) { return parseConnectionError(e2, a3(t), "WS"); } resetMaxListeners() { this.events.getMaxListeners() > h4 && this.events.setMaxListeners(h4); } emitError(e2) { const t = this.parseError(new Error((e2 == null ? void 0 : e2.message) || `WebSocket connection failed for host: ${a3(this.url)}`)); return this.events.emit("register_error", t), t; } }; // node_modules/@walletconnect/core/dist/index.es.js var import_lodash = __toESM(require_lodash()); var import_window_getters2 = __toESM(require_cjs2()); var ye2 = "wc"; var De = 2; var ie = "core"; var x4 = `${ye2}@2:${ie}:`; var Ye = { name: ie, logger: "error" }; var Je2 = { database: ":memory:" }; var Xe2 = "crypto"; var me2 = "client_ed25519_seed"; var We2 = import_time4.ONE_DAY; var Ze = "keychain"; var Qe = "0.3"; var et2 = "messages"; var tt = "0.3"; var it2 = import_time4.SIX_HOURS; var st2 = "publisher"; var rt = "irn"; var nt = "error"; var be2 = "wss://relay.walletconnect.org"; var ot = "relayer"; var v3 = { message: "relayer_message", message_ack: "relayer_message_ack", connect: "relayer_connect", disconnect: "relayer_disconnect", error: "relayer_error", connection_stalled: "relayer_connection_stalled", transport_closed: "relayer_transport_closed", publish: "relayer_publish" }; var at2 = "_subscription"; var I3 = { payload: "payload", connect: "connect", disconnect: "disconnect", error: "error" }; var ht = 0.1; var se = "2.17.2"; var M3 = { link_mode: "link_mode", relay: "relay" }; var ct = "0.3"; var lt = "WALLETCONNECT_CLIENT_ID"; var fe2 = "WALLETCONNECT_LINK_MODE_APPS"; var O4 = { created: "subscription_created", deleted: "subscription_deleted", expired: "subscription_expired", disabled: "subscription_disabled", sync: "subscription_sync", resubscribed: "subscription_resubscribed" }; var ut2 = "subscription"; var dt = "0.3"; var pt = import_time4.FIVE_SECONDS * 1e3; var gt2 = "pairing"; var yt = "0.3"; var B3 = { wc_pairingDelete: { req: { ttl: import_time4.ONE_DAY, prompt: false, tag: 1e3 }, res: { ttl: import_time4.ONE_DAY, prompt: false, tag: 1001 } }, wc_pairingPing: { req: { ttl: import_time4.THIRTY_SECONDS, prompt: false, tag: 1002 }, res: { ttl: import_time4.THIRTY_SECONDS, prompt: false, tag: 1003 } }, unregistered_method: { req: { ttl: import_time4.ONE_DAY, prompt: false, tag: 0 }, res: { ttl: import_time4.ONE_DAY, prompt: false, tag: 0 } } }; var V2 = { create: "pairing_create", expire: "pairing_expire", delete: "pairing_delete", ping: "pairing_ping" }; var P2 = { created: "history_created", updated: "history_updated", deleted: "history_deleted", sync: "history_sync" }; var Dt2 = "history"; var mt2 = "0.3"; var bt2 = "expirer"; var S5 = { created: "expirer_created", deleted: "expirer_deleted", expired: "expirer_expired", sync: "expirer_sync" }; var ft = "0.3"; var _t2 = "verify-api"; var vs = "https://verify.walletconnect.com"; var Et = "https://verify.walletconnect.org"; var J = Et; var vt2 = `${J}/v3`; var wt = [vs, Et]; var It = "echo"; var Tt2 = "https://echo.walletconnect.com"; var z4 = { pairing_started: "pairing_started", pairing_uri_validation_success: "pairing_uri_validation_success", pairing_uri_not_expired: "pairing_uri_not_expired", store_new_pairing: "store_new_pairing", subscribing_pairing_topic: "subscribing_pairing_topic", subscribe_pairing_topic_success: "subscribe_pairing_topic_success", existing_pairing: "existing_pairing", pairing_not_expired: "pairing_not_expired", emit_inactive_pairing: "emit_inactive_pairing", emit_session_proposal: "emit_session_proposal", subscribing_to_pairing_topic: "subscribing_to_pairing_topic" }; var $2 = { no_wss_connection: "no_wss_connection", no_internet_connection: "no_internet_connection", malformed_pairing_uri: "malformed_pairing_uri", active_pairing_already_exists: "active_pairing_already_exists", subscribe_pairing_topic_failure: "subscribe_pairing_topic_failure", pairing_expired: "pairing_expired", proposal_expired: "proposal_expired", proposal_listener_not_found: "proposal_listener_not_found" }; var Is = { session_approve_started: "session_approve_started", proposal_not_expired: "proposal_not_expired", session_namespaces_validation_success: "session_namespaces_validation_success", create_session_topic: "create_session_topic", subscribing_session_topic: "subscribing_session_topic", subscribe_session_topic_success: "subscribe_session_topic_success", publishing_session_approve: "publishing_session_approve", session_approve_publish_success: "session_approve_publish_success", store_session: "store_session", publishing_session_settle: "publishing_session_settle", session_settle_publish_success: "session_settle_publish_success" }; var Ts = { no_internet_connection: "no_internet_connection", no_wss_connection: "no_wss_connection", proposal_expired: "proposal_expired", subscribe_session_topic_failure: "subscribe_session_topic_failure", session_approve_publish_failure: "session_approve_publish_failure", session_settle_publish_failure: "session_settle_publish_failure", session_approve_namespace_validation_failure: "session_approve_namespace_validation_failure", proposal_not_found: "proposal_not_found" }; var Cs = { authenticated_session_approve_started: "authenticated_session_approve_started", authenticated_session_not_expired: "authenticated_session_not_expired", chains_caip2_compliant: "chains_caip2_compliant", chains_evm_compliant: "chains_evm_compliant", create_authenticated_session_topic: "create_authenticated_session_topic", cacaos_verified: "cacaos_verified", store_authenticated_session: "store_authenticated_session", subscribing_authenticated_session_topic: "subscribing_authenticated_session_topic", subscribe_authenticated_session_topic_success: "subscribe_authenticated_session_topic_success", publishing_authenticated_session_approve: "publishing_authenticated_session_approve", authenticated_session_approve_publish_success: "authenticated_session_approve_publish_success" }; var Ps = { no_internet_connection: "no_internet_connection", no_wss_connection: "no_wss_connection", missing_session_authenticate_request: "missing_session_authenticate_request", session_authenticate_request_expired: "session_authenticate_request_expired", chains_caip2_compliant_failure: "chains_caip2_compliant_failure", chains_evm_compliant_failure: "chains_evm_compliant_failure", invalid_cacao: "invalid_cacao", subscribe_authenticated_session_topic_failure: "subscribe_authenticated_session_topic_failure", authenticated_session_approve_publish_failure: "authenticated_session_approve_publish_failure", authenticated_session_pending_request_not_found: "authenticated_session_pending_request_not_found" }; var Ct = 0.1; var Pt2 = "event-client"; var St = 86400; var Rt = "https://pulse.walletconnect.org/batch"; function Ss(o4, e2) { if (o4.length >= 255) throw new TypeError("Alphabet too long"); for (var t = new Uint8Array(256), s3 = 0; s3 < t.length; s3++) t[s3] = 255; for (var i4 = 0; i4 < o4.length; i4++) { var r4 = o4.charAt(i4), n5 = r4.charCodeAt(0); if (t[n5] !== 255) throw new TypeError(r4 + " is ambiguous"); t[n5] = i4; } var a4 = o4.length, h5 = o4.charAt(0), c5 = Math.log(a4) / Math.log(256), l4 = Math.log(256) / Math.log(a4); function p3(u3) { if (u3 instanceof Uint8Array || (ArrayBuffer.isView(u3) ? u3 = new Uint8Array(u3.buffer, u3.byteOffset, u3.byteLength) : Array.isArray(u3) && (u3 = Uint8Array.from(u3))), !(u3 instanceof Uint8Array)) throw new TypeError("Expected Uint8Array"); if (u3.length === 0) return ""; for (var g4 = 0, _4 = 0, y6 = 0, b5 = u3.length; y6 !== b5 && u3[y6] === 0; ) y6++, g4++; for (var A3 = (b5 - y6) * l4 + 1 >>> 0, T2 = new Uint8Array(A3); y6 !== b5; ) { for (var N11 = u3[y6], k4 = 0, R2 = A3 - 1; (N11 !== 0 || k4 < _4) && R2 !== -1; R2--, k4++) N11 += 256 * T2[R2] >>> 0, T2[R2] = N11 % a4 >>> 0, N11 = N11 / a4 >>> 0; if (N11 !== 0) throw new Error("Non-zero carry"); _4 = k4, y6++; } for (var L3 = A3 - _4; L3 !== A3 && T2[L3] === 0; ) L3++; for (var Q2 = h5.repeat(g4); L3 < A3; ++L3) Q2 += o4.charAt(T2[L3]); return Q2; } function D4(u3) { if (typeof u3 != "string") throw new TypeError("Expected String"); if (u3.length === 0) return new Uint8Array(); var g4 = 0; if (u3[g4] !== " ") { for (var _4 = 0, y6 = 0; u3[g4] === h5; ) _4++, g4++; for (var b5 = (u3.length - g4) * c5 + 1 >>> 0, A3 = new Uint8Array(b5); u3[g4]; ) { var T2 = t[u3.charCodeAt(g4)]; if (T2 === 255) return; for (var N11 = 0, k4 = b5 - 1; (T2 !== 0 || N11 < y6) && k4 !== -1; k4--, N11++) T2 += a4 * A3[k4] >>> 0, A3[k4] = T2 % 256 >>> 0, T2 = T2 / 256 >>> 0; if (T2 !== 0) throw new Error("Non-zero carry"); y6 = N11, g4++; } if (u3[g4] !== " ") { for (var R2 = b5 - y6; R2 !== b5 && A3[R2] === 0; ) R2++; for (var L3 = new Uint8Array(_4 + (b5 - R2)), Q2 = _4; R2 !== b5; ) L3[Q2++] = A3[R2++]; return L3; } } } function m2(u3) { var g4 = D4(u3); if (g4) return g4; throw new Error(`Non-${e2} character`); } return { encode: p3, decodeUnsafe: D4, decode: m2 }; } var Rs = Ss; var xs = Rs; var xt2 = (o4) => { if (o4 instanceof Uint8Array && o4.constructor.name === "Uint8Array") return o4; if (o4 instanceof ArrayBuffer) return new Uint8Array(o4); if (ArrayBuffer.isView(o4)) return new Uint8Array(o4.buffer, o4.byteOffset, o4.byteLength); throw new Error("Unknown type, must be binary type"); }; var Os = (o4) => new TextEncoder().encode(o4); var As = (o4) => new TextDecoder().decode(o4); var Ns = class { constructor(e2, t, s3) { this.name = e2, this.prefix = t, this.baseEncode = s3; } encode(e2) { if (e2 instanceof Uint8Array) return `${this.prefix}${this.baseEncode(e2)}`; throw Error("Unknown type, must be binary type"); } }; var zs = class { constructor(e2, t, s3) { if (this.name = e2, this.prefix = t, t.codePointAt(0) === void 0) throw new Error("Invalid prefix character"); this.prefixCodePoint = t.codePointAt(0), this.baseDecode = s3; } decode(e2) { if (typeof e2 == "string") { if (e2.codePointAt(0) !== this.prefixCodePoint) throw Error(`Unable to decode multibase string ${JSON.stringify(e2)}, ${this.name} decoder only supports inputs prefixed with ${this.prefix}`); return this.baseDecode(e2.slice(this.prefix.length)); } else throw Error("Can only multibase decode strings"); } or(e2) { return Ot2(this, e2); } }; var Ls = class { constructor(e2) { this.decoders = e2; } or(e2) { return Ot2(this, e2); } decode(e2) { const t = e2[0], s3 = this.decoders[t]; if (s3) return s3.decode(e2); throw RangeError(`Unable to decode multibase string ${JSON.stringify(e2)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`); } }; var Ot2 = (o4, e2) => new Ls({ ...o4.decoders || { [o4.prefix]: o4 }, ...e2.decoders || { [e2.prefix]: e2 } }); var $s = class { constructor(e2, t, s3, i4) { this.name = e2, this.prefix = t, this.baseEncode = s3, this.baseDecode = i4, this.encoder = new Ns(e2, t, s3), this.decoder = new zs(e2, t, i4); } encode(e2) { return this.encoder.encode(e2); } decode(e2) { return this.decoder.decode(e2); } }; var re2 = ({ name: o4, prefix: e2, encode: t, decode: s3 }) => new $s(o4, e2, t, s3); var X2 = ({ prefix: o4, name: e2, alphabet: t }) => { const { encode: s3, decode: i4 } = xs(t, e2); return re2({ prefix: o4, name: e2, encode: s3, decode: (r4) => xt2(i4(r4)) }); }; var ks = (o4, e2, t, s3) => { const i4 = {}; for (let l4 = 0; l4 < e2.length; ++l4) i4[e2[l4]] = l4; let r4 = o4.length; for (; o4[r4 - 1] === "="; ) --r4; const n5 = new Uint8Array(r4 * t / 8 | 0); let a4 = 0, h5 = 0, c5 = 0; for (let l4 = 0; l4 < r4; ++l4) { const p3 = i4[o4[l4]]; if (p3 === void 0) throw new SyntaxError(`Non-${s3} character`); h5 = h5 << t | p3, a4 += t, a4 >= 8 && (a4 -= 8, n5[c5++] = 255 & h5 >> a4); } if (a4 >= t || 255 & h5 << 8 - a4) throw new SyntaxError("Unexpected end of data"); return n5; }; var Ms = (o4, e2, t) => { const s3 = e2[e2.length - 1] === "=", i4 = (1 << t) - 1; let r4 = "", n5 = 0, a4 = 0; for (let h5 = 0; h5 < o4.length; ++h5) for (a4 = a4 << 8 | o4[h5], n5 += 8; n5 > t; ) n5 -= t, r4 += e2[i4 & a4 >> n5]; if (n5 && (r4 += e2[i4 & a4 << t - n5]), s3) for (; r4.length * t & 7; ) r4 += "="; return r4; }; var f3 = ({ name: o4, prefix: e2, bitsPerChar: t, alphabet: s3 }) => re2({ prefix: e2, name: o4, encode(i4) { return Ms(i4, s3, t); }, decode(i4) { return ks(i4, s3, t, o4); } }); var Us = re2({ prefix: "\0", name: "identity", encode: (o4) => As(o4), decode: (o4) => Os(o4) }); var Fs = Object.freeze({ __proto__: null, identity: Us }); var Ks = f3({ prefix: "0", name: "base2", alphabet: "01", bitsPerChar: 1 }); var Bs = Object.freeze({ __proto__: null, base2: Ks }); var Vs = f3({ prefix: "7", name: "base8", alphabet: "01234567", bitsPerChar: 3 }); var js = Object.freeze({ __proto__: null, base8: Vs }); var qs = X2({ prefix: "9", name: "base10", alphabet: "0123456789" }); var Gs = Object.freeze({ __proto__: null, base10: qs }); var Hs = f3({ prefix: "f", name: "base16", alphabet: "0123456789abcdef", bitsPerChar: 4 }); var Ys = f3({ prefix: "F", name: "base16upper", alphabet: "0123456789ABCDEF", bitsPerChar: 4 }); var Js = Object.freeze({ __proto__: null, base16: Hs, base16upper: Ys }); var Xs = f3({ prefix: "b", name: "base32", alphabet: "abcdefghijklmnopqrstuvwxyz234567", bitsPerChar: 5 }); var Ws = f3({ prefix: "B", name: "base32upper", alphabet: "ABCDEFGHIJKLMNOPQRSTUVWXYZ234567", bitsPerChar: 5 }); var Zs = f3({ prefix: "c", name: "base32pad", alphabet: "abcdefghijklmnopqrstuvwxyz234567=", bitsPerChar: 5 }); var Qs = f3({ prefix: "C", name: "base32padupper", alphabet: "ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=", bitsPerChar: 5 }); var er2 = f3({ prefix: "v", name: "base32hex", alphabet: "0123456789abcdefghijklmnopqrstuv", bitsPerChar: 5 }); var tr = f3({ prefix: "V", name: "base32hexupper", alphabet: "0123456789ABCDEFGHIJKLMNOPQRSTUV", bitsPerChar: 5 }); var ir2 = f3({ prefix: "t", name: "base32hexpad", alphabet: "0123456789abcdefghijklmnopqrstuv=", bitsPerChar: 5 }); var sr = f3({ prefix: "T", name: "base32hexpadupper", alphabet: "0123456789ABCDEFGHIJKLMNOPQRSTUV=", bitsPerChar: 5 }); var rr = f3({ prefix: "h", name: "base32z", alphabet: "ybndrfg8ejkmcpqxot1uwisza345h769", bitsPerChar: 5 }); var nr2 = Object.freeze({ __proto__: null, base32: Xs, base32upper: Ws, base32pad: Zs, base32padupper: Qs, base32hex: er2, base32hexupper: tr, base32hexpad: ir2, base32hexpadupper: sr, base32z: rr }); var or2 = X2({ prefix: "k", name: "base36", alphabet: "0123456789abcdefghijklmnopqrstuvwxyz" }); var ar2 = X2({ prefix: "K", name: "base36upper", alphabet: "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ" }); var hr2 = Object.freeze({ __proto__: null, base36: or2, base36upper: ar2 }); var cr2 = X2({ name: "base58btc", prefix: "z", alphabet: "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz" }); var lr2 = X2({ name: "base58flickr", prefix: "Z", alphabet: "123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ" }); var ur2 = Object.freeze({ __proto__: null, base58btc: cr2, base58flickr: lr2 }); var dr2 = f3({ prefix: "m", name: "base64", alphabet: "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/", bitsPerChar: 6 }); var pr2 = f3({ prefix: "M", name: "base64pad", alphabet: "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=", bitsPerChar: 6 }); var gr2 = f3({ prefix: "u", name: "base64url", alphabet: "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_", bitsPerChar: 6 }); var yr2 = f3({ prefix: "U", name: "base64urlpad", alphabet: "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=", bitsPerChar: 6 }); var Dr2 = Object.freeze({ __proto__: null, base64: dr2, base64pad: pr2, base64url: gr2, base64urlpad: yr2 }); var At = Array.from("🚀🪐☄🛰🌌🌑🌒🌓🌔🌕🌖🌗🌘🌍🌏🌎🐉☀💻🖥💾💿😂❤😍🤣😊🙏💕😭😘👍😅👏😁🔥🥰💔💖💙😢🤔😆🙄💪😉☺👌🤗💜😔😎😇🌹🤦🎉💞✌✨🤷😱😌🌸🙌😋💗💚😏💛🙂💓🤩😄😀🖤😃💯🙈👇🎶😒🤭❣😜💋👀😪😑💥🙋😞😩😡🤪👊🥳😥🤤👉💃😳✋😚😝😴🌟😬🙃🍀🌷😻😓⭐✅🥺🌈😈🤘💦✔😣🏃💐☹🎊💘😠☝😕🌺🎂🌻😐🖕💝🙊😹🗣💫💀👑🎵🤞😛🔴😤🌼😫⚽🤙☕🏆🤫👈😮🙆🍻🍃🐶💁😲🌿🧡🎁⚡🌞🎈❌✊👋😰🤨😶🤝🚶💰🍓💢🤟🙁🚨💨🤬✈🎀🍺🤓😙💟🌱😖👶🥴▶➡❓💎💸⬇😨🌚🦋😷🕺⚠🙅😟😵👎🤲🤠🤧📌🔵💅🧐🐾🍒😗🤑🌊🤯🐷☎💧😯💆👆🎤🙇🍑❄🌴💣🐸💌📍🥀🤢👅💡💩👐📸👻🤐🤮🎼🥵🚩🍎🍊👼💍📣🥂"); var mr2 = At.reduce((o4, e2, t) => (o4[t] = e2, o4), []); var br2 = At.reduce((o4, e2, t) => (o4[e2.codePointAt(0)] = t, o4), []); function fr2(o4) { return o4.reduce((e2, t) => (e2 += mr2[t], e2), ""); } function _r2(o4) { const e2 = []; for (const t of o4) { const s3 = br2[t.codePointAt(0)]; if (s3 === void 0) throw new Error(`Non-base256emoji character: ${t}`); e2.push(s3); } return new Uint8Array(e2); } var Er2 = re2({ prefix: "🚀", name: "base256emoji", encode: fr2, decode: _r2 }); var vr2 = Object.freeze({ __proto__: null, base256emoji: Er2 }); var wr2 = zt2; var Nt2 = 128; var Ir2 = 127; var Tr2 = ~Ir2; var Cr2 = Math.pow(2, 31); function zt2(o4, e2, t) { e2 = e2 || [], t = t || 0; for (var s3 = t; o4 >= Cr2; ) e2[t++] = o4 & 255 | Nt2, o4 /= 128; for (; o4 & Tr2; ) e2[t++] = o4 & 255 | Nt2, o4 >>>= 7; return e2[t] = o4 | 0, zt2.bytes = t - s3 + 1, e2; } var Pr2 = _e2; var Sr2 = 128; var Lt2 = 127; function _e2(o4, s3) { var t = 0, s3 = s3 || 0, i4 = 0, r4 = s3, n5, a4 = o4.length; do { if (r4 >= a4) throw _e2.bytes = 0, new RangeError("Could not decode varint"); n5 = o4[r4++], t += i4 < 28 ? (n5 & Lt2) << i4 : (n5 & Lt2) * Math.pow(2, i4), i4 += 7; } while (n5 >= Sr2); return _e2.bytes = r4 - s3, t; } var Rr2 = Math.pow(2, 7); var xr2 = Math.pow(2, 14); var Or2 = Math.pow(2, 21); var Ar2 = Math.pow(2, 28); var Nr2 = Math.pow(2, 35); var zr2 = Math.pow(2, 42); var Lr = Math.pow(2, 49); var $r2 = Math.pow(2, 56); var kr2 = Math.pow(2, 63); var Mr = function(o4) { return o4 < Rr2 ? 1 : o4 < xr2 ? 2 : o4 < Or2 ? 3 : o4 < Ar2 ? 4 : o4 < Nr2 ? 5 : o4 < zr2 ? 6 : o4 < Lr ? 7 : o4 < $r2 ? 8 : o4 < kr2 ? 9 : 10; }; var Ur2 = { encode: wr2, decode: Pr2, encodingLength: Mr }; var $t2 = Ur2; var kt2 = (o4, e2, t = 0) => ($t2.encode(o4, e2, t), e2); var Mt2 = (o4) => $t2.encodingLength(o4); var Ee2 = (o4, e2) => { const t = e2.byteLength, s3 = Mt2(o4), i4 = s3 + Mt2(t), r4 = new Uint8Array(i4 + t); return kt2(o4, r4, 0), kt2(t, r4, s3), r4.set(e2, i4), new Fr(o4, t, e2, r4); }; var Fr = class { constructor(e2, t, s3, i4) { this.code = e2, this.size = t, this.digest = s3, this.bytes = i4; } }; var Ut = ({ name: o4, code: e2, encode: t }) => new Kr(o4, e2, t); var Kr = class { constructor(e2, t, s3) { this.name = e2, this.code = t, this.encode = s3; } digest(e2) { if (e2 instanceof Uint8Array) { const t = this.encode(e2); return t instanceof Uint8Array ? Ee2(this.code, t) : t.then((s3) => Ee2(this.code, s3)); } else throw Error("Unknown type, must be binary type"); } }; var Ft2 = (o4) => async (e2) => new Uint8Array(await crypto.subtle.digest(o4, e2)); var Br = Ut({ name: "sha2-256", code: 18, encode: Ft2("SHA-256") }); var Vr = Ut({ name: "sha2-512", code: 19, encode: Ft2("SHA-512") }); var jr2 = Object.freeze({ __proto__: null, sha256: Br, sha512: Vr }); var Kt2 = 0; var qr = "identity"; var Bt2 = xt2; var Gr2 = (o4) => Ee2(Kt2, Bt2(o4)); var Hr = { code: Kt2, name: qr, encode: Bt2, digest: Gr2 }; var Yr2 = Object.freeze({ __proto__: null, identity: Hr }); new TextEncoder(), new TextDecoder(); var Vt2 = { ...Fs, ...Bs, ...js, ...Gs, ...Js, ...nr2, ...hr2, ...ur2, ...Dr2, ...vr2 }; ({ ...jr2, ...Yr2 }); function Jr2(o4 = 0) { return globalThis.Buffer != null && globalThis.Buffer.allocUnsafe != null ? globalThis.Buffer.allocUnsafe(o4) : new Uint8Array(o4); } function jt(o4, e2, t, s3) { return { name: o4, prefix: e2, encoder: { name: o4, prefix: e2, encode: t }, decoder: { decode: s3 } }; } var qt2 = jt("utf8", "u", (o4) => "u" + new TextDecoder("utf8").decode(o4), (o4) => new TextEncoder().encode(o4.substring(1))); var ve2 = jt("ascii", "a", (o4) => { let e2 = "a"; for (let t = 0; t < o4.length; t++) e2 += String.fromCharCode(o4[t]); return e2; }, (o4) => { o4 = o4.substring(1); const e2 = Jr2(o4.length); for (let t = 0; t < o4.length; t++) e2[t] = o4.charCodeAt(t); return e2; }); var Xr2 = { utf8: qt2, "utf-8": qt2, hex: Vt2.base16, latin1: ve2, ascii: ve2, binary: ve2, ...Vt2 }; function Wr(o4, e2 = "utf8") { const t = Xr2[e2]; if (!t) throw new Error(`Unsupported encoding "${e2}"`); return (e2 === "utf8" || e2 === "utf-8") && globalThis.Buffer != null && globalThis.Buffer.from != null ? globalThis.Buffer.from(o4, "utf8") : t.decoder.decode(`${t.prefix}${o4}`); } var Gt2 = class { constructor(e2, t) { this.core = e2, this.logger = t, this.keychain = /* @__PURE__ */ new Map(), this.name = Ze, this.version = Qe, this.initialized = false, this.storagePrefix = x4, this.init = async () => { if (!this.initialized) { const s3 = await this.getKeyChain(); typeof s3 < "u" && (this.keychain = s3), this.initialized = true; } }, this.has = (s3) => (this.isInitialized(), this.keychain.has(s3)), this.set = async (s3, i4) => { this.isInitialized(), this.keychain.set(s3, i4), await this.persist(); }, this.get = (s3) => { this.isInitialized(); const i4 = this.keychain.get(s3); if (typeof i4 > "u") { const { message: r4 } = S("NO_MATCHING_KEY", `${this.name}: ${s3}`); throw new Error(r4); } return i4; }, this.del = async (s3) => { this.isInitialized(), this.keychain.delete(s3), await this.persist(); }, this.core = e2, this.logger = E(t, this.name); } get context() { return y2(this.logger); } get storageKey() { return this.storagePrefix + this.version + this.core.customStoragePrefix + "//" + this.name; } async setKeyChain(e2) { await this.core.storage.setItem(this.storageKey, Tt(e2)); } async getKeyChain() { const e2 = await this.core.storage.getItem(this.storageKey); return typeof e2 < "u" ? Pt(e2) : void 0; } async persist() { await this.setKeyChain(this.keychain); } isInitialized() { if (!this.initialized) { const { message: e2 } = S("NOT_INITIALIZED", this.name); throw new Error(e2); } } }; var Ht2 = class { constructor(e2, t, s3) { this.core = e2, this.logger = t, this.name = Xe2, this.randomSessionIdentifier = pr(), this.initialized = false, this.init = async () => { this.initialized || (await this.keychain.init(), this.initialized = true); }, this.hasKeys = (i4) => (this.isInitialized(), this.keychain.has(i4)), this.getClientId = async () => { this.isInitialized(); const i4 = await this.getClientSeed(), r4 = generateKeyPair(i4); return encodeIss(r4.publicKey); }, this.generateKeyPair = () => { this.isInitialized(); const i4 = fr(); return this.setPrivateKey(i4.publicKey, i4.privateKey); }, this.signJWT = async (i4) => { this.isInitialized(); const r4 = await this.getClientSeed(), n5 = generateKeyPair(r4), a4 = this.randomSessionIdentifier, h5 = We2; return await signJWT(a4, i4, h5, n5); }, this.generateSharedKey = (i4, r4, n5) => { this.isInitialized(); const a4 = this.getPrivateKey(i4), h5 = mr(a4, r4); return this.setSymKey(h5, n5); }, this.setSymKey = async (i4, r4) => { this.isInitialized(); const n5 = r4 || hr(i4); return await this.keychain.set(n5, i4), n5; }, this.deleteKeyPair = async (i4) => { this.isInitialized(), await this.keychain.del(i4); }, this.deleteSymKey = async (i4) => { this.isInitialized(), await this.keychain.del(i4); }, this.encode = async (i4, r4, n5) => { this.isInitialized(); const a4 = On(n5), h5 = safeJsonStringify(r4); if (Nr(a4)) return vr(h5, n5 == null ? void 0 : n5.encoding); if (Or(a4)) { const D4 = a4.senderPublicKey, m2 = a4.receiverPublicKey; i4 = await this.generateSharedKey(D4, m2); } const c5 = this.getSymKey(i4), { type: l4, senderPublicKey: p3 } = a4; return gr({ type: l4, symKey: c5, message: h5, senderPublicKey: p3, encoding: n5 == null ? void 0 : n5.encoding }); }, this.decode = async (i4, r4, n5) => { this.isInitialized(); const a4 = wr(r4, n5); if (Nr(a4)) { const h5 = Er(r4, n5 == null ? void 0 : n5.encoding); return safeJsonParse(h5); } if (Or(a4)) { const h5 = a4.receiverPublicKey, c5 = a4.senderPublicKey; i4 = await this.generateSharedKey(h5, c5); } try { const h5 = this.getSymKey(i4), c5 = br({ symKey: h5, encoded: r4, encoding: n5 == null ? void 0 : n5.encoding }); return safeJsonParse(c5); } catch (h5) { this.logger.error(`Failed to decode message from topic: '${i4}', clientId: '${await this.getClientId()}'`), this.logger.error(h5); } }, this.getPayloadType = (i4, r4 = ge) => { const n5 = Q({ encoded: i4, encoding: r4 }); return A(n5.type); }, this.getPayloadSenderPublicKey = (i4, r4 = ge) => { const n5 = Q({ encoded: i4, encoding: r4 }); return n5.senderPublicKey ? toString2(n5.senderPublicKey, g) : void 0; }, this.core = e2, this.logger = E(t, this.name), this.keychain = s3 || new Gt2(this.core, this.logger); } get context() { return y2(this.logger); } async setPrivateKey(e2, t) { return await this.keychain.set(e2, t), e2; } getPrivateKey(e2) { return this.keychain.get(e2); } async getClientSeed() { let e2 = ""; try { e2 = this.keychain.get(me2); } catch { e2 = pr(), await this.keychain.set(me2, e2); } return Wr(e2, "base16"); } getSymKey(e2) { return this.keychain.get(e2); } isInitialized() { if (!this.initialized) { const { message: e2 } = S("NOT_INITIALIZED", this.name); throw new Error(e2); } } }; var Yt2 = class extends a2 { constructor(e2, t) { super(e2, t), this.logger = e2, this.core = t, this.messages = /* @__PURE__ */ new Map(), this.name = et2, this.version = tt, this.initialized = false, this.storagePrefix = x4, this.init = async () => { if (!this.initialized) { this.logger.trace("Initialized"); try { const s3 = await this.getRelayerMessages(); typeof s3 < "u" && (this.messages = s3), this.logger.debug(`Successfully Restored records for ${this.name}`), this.logger.trace({ type: "method", method: "restore", size: this.messages.size }); } catch (s3) { this.logger.debug(`Failed to Restore records for ${this.name}`), this.logger.error(s3); } finally { this.initialized = true; } } }, this.set = async (s3, i4) => { this.isInitialized(); const r4 = yr(i4); let n5 = this.messages.get(s3); return typeof n5 > "u" && (n5 = {}), typeof n5[r4] < "u" || (n5[r4] = i4, this.messages.set(s3, n5), await this.persist()), r4; }, this.get = (s3) => { this.isInitialized(); let i4 = this.messages.get(s3); return typeof i4 > "u" && (i4 = {}), i4; }, this.has = (s3, i4) => { this.isInitialized(); const r4 = this.get(s3), n5 = yr(i4); return typeof r4[n5] < "u"; }, this.del = async (s3) => { this.isInitialized(), this.messages.delete(s3), await this.persist(); }, this.logger = E(e2, this.name), this.core = t; } get context() { return y2(this.logger); } get storageKey() { return this.storagePrefix + this.version + this.core.customStoragePrefix + "//" + this.name; } async setRelayerMessages(e2) { await this.core.storage.setItem(this.storageKey, Tt(e2)); } async getRelayerMessages() { const e2 = await this.core.storage.getItem(this.storageKey); return typeof e2 < "u" ? Pt(e2) : void 0; } async persist() { await this.setRelayerMessages(this.messages); } isInitialized() { if (!this.initialized) { const { message: e2 } = S("NOT_INITIALIZED", this.name); throw new Error(e2); } } }; var Zr2 = class extends g3 { constructor(e2, t) { super(e2, t), this.relayer = e2, this.logger = t, this.events = new import_events7.EventEmitter(), this.name = st2, this.queue = /* @__PURE__ */ new Map(), this.publishTimeout = (0, import_time4.toMiliseconds)(import_time4.ONE_MINUTE), this.failedPublishTimeout = (0, import_time4.toMiliseconds)(import_time4.ONE_SECOND), this.needsTransportRestart = false, this.publish = async (s3, i4, r4) => { var n5; this.logger.debug("Publishing Payload"), this.logger.trace({ type: "method", method: "publish", params: { topic: s3, message: i4, opts: r4 } }); const a4 = (r4 == null ? void 0 : r4.ttl) || it2, h5 = Ir(r4), c5 = (r4 == null ? void 0 : r4.prompt) || false, l4 = (r4 == null ? void 0 : r4.tag) || 0, p3 = (r4 == null ? void 0 : r4.id) || getBigIntRpcId().toString(), D4 = { topic: s3, message: i4, opts: { ttl: a4, relay: h5, prompt: c5, tag: l4, id: p3, attestation: r4 == null ? void 0 : r4.attestation } }, m2 = `Failed to publish payload, please try again. id:${p3} tag:${l4}`, u3 = Date.now(); let g4, _4 = 1; try { for (; g4 === void 0; ) { if (Date.now() - u3 > this.publishTimeout) throw new Error(m2); this.logger.trace({ id: p3, attempts: _4 }, `publisher.publish - attempt ${_4}`), g4 = await await kt(this.rpcPublish(s3, i4, a4, h5, c5, l4, p3, r4 == null ? void 0 : r4.attestation).catch((y6) => this.logger.warn(y6)), this.publishTimeout, m2), _4++, g4 || await new Promise((y6) => setTimeout(y6, this.failedPublishTimeout)); } this.relayer.events.emit(v3.publish, D4), this.logger.debug("Successfully Published Payload"), this.logger.trace({ type: "method", method: "publish", params: { id: p3, topic: s3, message: i4, opts: r4 } }); } catch (y6) { if (this.logger.debug("Failed to Publish Payload"), this.logger.error(y6), (n5 = r4 == null ? void 0 : r4.internal) != null && n5.throwOnFailedPublish) throw y6; this.queue.set(p3, D4); } }, this.on = (s3, i4) => { this.events.on(s3, i4); }, this.once = (s3, i4) => { this.events.once(s3, i4); }, this.off = (s3, i4) => { this.events.off(s3, i4); }, this.removeListener = (s3, i4) => { this.events.removeListener(s3, i4); }, this.relayer = e2, this.logger = E(t, this.name), this.registerEventListeners(); } get context() { return y2(this.logger); } rpcPublish(e2, t, s3, i4, r4, n5, a4, h5) { var c5, l4, p3, D4; const m2 = { method: jr(i4.protocol).publish, params: { topic: e2, message: t, ttl: s3, prompt: r4, tag: n5, attestation: h5 }, id: a4 }; return I((c5 = m2.params) == null ? void 0 : c5.prompt) && ((l4 = m2.params) == null || delete l4.prompt), I((p3 = m2.params) == null ? void 0 : p3.tag) && ((D4 = m2.params) == null || delete D4.tag), this.logger.debug("Outgoing Relay Payload"), this.logger.trace({ type: "message", direction: "outgoing", request: m2 }), this.relayer.request(m2); } removeRequestFromQueue(e2) { this.queue.delete(e2); } checkQueue() { this.queue.forEach(async (e2) => { const { topic: t, message: s3, opts: i4 } = e2; await this.publish(t, s3, i4); }); } registerEventListeners() { this.relayer.core.heartbeat.on(r3.pulse, () => { if (this.needsTransportRestart) { this.needsTransportRestart = false, this.relayer.events.emit(v3.connection_stalled); return; } this.checkQueue(); }), this.relayer.on(v3.message_ack, (e2) => { this.removeRequestFromQueue(e2.id.toString()); }); } }; var Qr2 = class { constructor() { this.map = /* @__PURE__ */ new Map(), this.set = (e2, t) => { const s3 = this.get(e2); this.exists(e2, t) || this.map.set(e2, [...s3, t]); }, this.get = (e2) => this.map.get(e2) || [], this.exists = (e2, t) => this.get(e2).includes(t), this.delete = (e2, t) => { if (typeof t > "u") { this.map.delete(e2); return; } if (!this.map.has(e2)) return; const s3 = this.get(e2); if (!this.exists(e2, t)) return; const i4 = s3.filter((r4) => r4 !== t); if (!i4.length) { this.map.delete(e2); return; } this.map.set(e2, i4); }, this.clear = () => { this.map.clear(); }; } get topics() { return Array.from(this.map.keys()); } }; var en2 = Object.defineProperty; var tn2 = Object.defineProperties; var sn2 = Object.getOwnPropertyDescriptors; var Jt2 = Object.getOwnPropertySymbols; var rn2 = Object.prototype.hasOwnProperty; var nn2 = Object.prototype.propertyIsEnumerable; var Xt2 = (o4, e2, t) => e2 in o4 ? en2(o4, e2, { enumerable: true, configurable: true, writable: true, value: t }) : o4[e2] = t; var W2 = (o4, e2) => { for (var t in e2 || (e2 = {})) rn2.call(e2, t) && Xt2(o4, t, e2[t]); if (Jt2) for (var t of Jt2(e2)) nn2.call(e2, t) && Xt2(o4, t, e2[t]); return o4; }; var we2 = (o4, e2) => tn2(o4, sn2(e2)); var Wt2 = class extends d2 { constructor(e2, t) { super(e2, t), this.relayer = e2, this.logger = t, this.subscriptions = /* @__PURE__ */ new Map(), this.topicMap = new Qr2(), this.events = new import_events7.EventEmitter(), this.name = ut2, this.version = dt, this.pending = /* @__PURE__ */ new Map(), this.cached = [], this.initialized = false, this.pendingSubscriptionWatchLabel = "pending_sub_watch_label", this.pollingInterval = 20, this.storagePrefix = x4, this.subscribeTimeout = (0, import_time4.toMiliseconds)(import_time4.ONE_MINUTE), this.restartInProgress = false, this.batchSubscribeTopicsLimit = 500, this.pendingBatchMessages = [], this.init = async () => { this.initialized || (this.logger.trace("Initialized"), this.registerEventListeners(), this.clientId = await this.relayer.core.crypto.getClientId(), await this.restore()), this.initialized = true; }, this.subscribe = async (s3, i4) => { this.isInitialized(), this.logger.debug("Subscribing Topic"), this.logger.trace({ type: "method", method: "subscribe", params: { topic: s3, opts: i4 } }); try { const r4 = Ir(i4), n5 = { topic: s3, relay: r4, transportType: i4 == null ? void 0 : i4.transportType }; this.pending.set(s3, n5); const a4 = await this.rpcSubscribe(s3, r4, i4); return typeof a4 == "string" && (this.onSubscribe(a4, n5), this.logger.debug("Successfully Subscribed Topic"), this.logger.trace({ type: "method", method: "subscribe", params: { topic: s3, opts: i4 } })), a4; } catch (r4) { throw this.logger.debug("Failed to Subscribe Topic"), this.logger.error(r4), r4; } }, this.unsubscribe = async (s3, i4) => { await this.restartToComplete(), this.isInitialized(), typeof (i4 == null ? void 0 : i4.id) < "u" ? await this.unsubscribeById(s3, i4.id, i4) : await this.unsubscribeByTopic(s3, i4); }, this.isSubscribed = async (s3) => { if (this.topics.includes(s3)) return true; const i4 = `${this.pendingSubscriptionWatchLabel}_${s3}`; return await new Promise((r4, n5) => { const a4 = new import_time4.Watch(); a4.start(i4); const h5 = setInterval(() => { !this.pending.has(s3) && this.topics.includes(s3) && (clearInterval(h5), a4.stop(i4), r4(true)), a4.elapsed(i4) >= pt && (clearInterval(h5), a4.stop(i4), n5(new Error("Subscription resolution timeout"))); }, this.pollingInterval); }).catch(() => false); }, this.on = (s3, i4) => { this.events.on(s3, i4); }, this.once = (s3, i4) => { this.events.once(s3, i4); }, this.off = (s3, i4) => { this.events.off(s3, i4); }, this.removeListener = (s3, i4) => { this.events.removeListener(s3, i4); }, this.start = async () => { await this.onConnect(); }, this.stop = async () => { await this.onDisconnect(); }, this.restart = async () => { this.restartInProgress = true, await this.restore(), await this.reset(), this.restartInProgress = false; }, this.relayer = e2, this.logger = E(t, this.name), this.clientId = ""; } get context() { return y2(this.logger); } get storageKey() { return this.storagePrefix + this.version + this.relayer.core.customStoragePrefix + "//" + this.name; } get length() { return this.subscriptions.size; } get ids() { return Array.from(this.subscriptions.keys()); } get values() { return Array.from(this.subscriptions.values()); } get topics() { return this.topicMap.topics; } hasSubscription(e2, t) { let s3 = false; try { s3 = this.getSubscription(e2).topic === t; } catch { } return s3; } onEnable() { this.cached = [], this.initialized = true; } onDisable() { this.cached = this.values, this.subscriptions.clear(), this.topicMap.clear(); } async unsubscribeByTopic(e2, t) { const s3 = this.topicMap.get(e2); await Promise.all(s3.map(async (i4) => await this.unsubscribeById(e2, i4, t))); } async unsubscribeById(e2, t, s3) { this.logger.debug("Unsubscribing Topic"), this.logger.trace({ type: "method", method: "unsubscribe", params: { topic: e2, id: t, opts: s3 } }); try { const i4 = Ir(s3); await this.rpcUnsubscribe(e2, t, i4); const r4 = U("USER_DISCONNECTED", `${this.name}, ${e2}`); await this.onUnsubscribe(e2, t, r4), this.logger.debug("Successfully Unsubscribed Topic"), this.logger.trace({ type: "method", method: "unsubscribe", params: { topic: e2, id: t, opts: s3 } }); } catch (i4) { throw this.logger.debug("Failed to Unsubscribe Topic"), this.logger.error(i4), i4; } } async rpcSubscribe(e2, t, s3) { var i4; (s3 == null ? void 0 : s3.transportType) === M3.relay && await this.restartToComplete(); const r4 = { method: jr(t.protocol).subscribe, params: { topic: e2 } }; this.logger.debug("Outgoing Relay Payload"), this.logger.trace({ type: "payload", direction: "outgoing", request: r4 }); const n5 = (i4 = s3 == null ? void 0 : s3.internal) == null ? void 0 : i4.throwOnFailedPublish; try { const a4 = yr(e2 + this.clientId); if ((s3 == null ? void 0 : s3.transportType) === M3.link_mode) return setTimeout(() => { (this.relayer.connected || this.relayer.connecting) && this.relayer.request(r4).catch((c5) => this.logger.warn(c5)); }, (0, import_time4.toMiliseconds)(import_time4.ONE_SECOND)), a4; const h5 = await kt(this.relayer.request(r4).catch((c5) => this.logger.warn(c5)), this.subscribeTimeout, `Subscribing to ${e2} failed, please try again`); if (!h5 && n5) throw new Error(`Subscribing to ${e2} failed, please try again`); return h5 ? a4 : null; } catch (a4) { if (this.logger.debug("Outgoing Relay Subscribe Payload stalled"), this.relayer.events.emit(v3.connection_stalled), n5) throw a4; } return null; } async rpcBatchSubscribe(e2) { if (!e2.length) return; const t = e2[0].relay, s3 = { method: jr(t.protocol).batchSubscribe, params: { topics: e2.map((i4) => i4.topic) } }; this.logger.debug("Outgoing Relay Payload"), this.logger.trace({ type: "payload", direction: "outgoing", request: s3 }); try { return await await kt(this.relayer.request(s3).catch((i4) => this.logger.warn(i4)), this.subscribeTimeout); } catch { this.relayer.events.emit(v3.connection_stalled); } } async rpcBatchFetchMessages(e2) { if (!e2.length) return; const t = e2[0].relay, s3 = { method: jr(t.protocol).batchFetchMessages, params: { topics: e2.map((r4) => r4.topic) } }; this.logger.debug("Outgoing Relay Payload"), this.logger.trace({ type: "payload", direction: "outgoing", request: s3 }); let i4; try { i4 = await await kt(this.relayer.request(s3).catch((r4) => this.logger.warn(r4)), this.subscribeTimeout); } catch { this.relayer.events.emit(v3.connection_stalled); } return i4; } rpcUnsubscribe(e2, t, s3) { const i4 = { method: jr(s3.protocol).unsubscribe, params: { topic: e2, id: t } }; return this.logger.debug("Outgoing Relay Payload"), this.logger.trace({ type: "payload", direction: "outgoing", request: i4 }), this.relayer.request(i4); } onSubscribe(e2, t) { this.setSubscription(e2, we2(W2({}, t), { id: e2 })), this.pending.delete(t.topic); } onBatchSubscribe(e2) { e2.length && e2.forEach((t) => { this.setSubscription(t.id, W2({}, t)), this.pending.delete(t.topic); }); } async onUnsubscribe(e2, t, s3) { this.events.removeAllListeners(t), this.hasSubscription(t, e2) && this.deleteSubscription(t, s3), await this.relayer.messages.del(e2); } async setRelayerSubscriptions(e2) { await this.relayer.core.storage.setItem(this.storageKey, e2); } async getRelayerSubscriptions() { return await this.relayer.core.storage.getItem(this.storageKey); } setSubscription(e2, t) { this.logger.debug("Setting subscription"), this.logger.trace({ type: "method", method: "setSubscription", id: e2, subscription: t }), this.addSubscription(e2, t); } addSubscription(e2, t) { this.subscriptions.set(e2, W2({}, t)), this.topicMap.set(t.topic, e2), this.events.emit(O4.created, t); } getSubscription(e2) { this.logger.debug("Getting subscription"), this.logger.trace({ type: "method", method: "getSubscription", id: e2 }); const t = this.subscriptions.get(e2); if (!t) { const { message: s3 } = S("NO_MATCHING_KEY", `${this.name}: ${e2}`); throw new Error(s3); } return t; } deleteSubscription(e2, t) { this.logger.debug("Deleting subscription"), this.logger.trace({ type: "method", method: "deleteSubscription", id: e2, reason: t }); const s3 = this.getSubscription(e2); this.subscriptions.delete(e2), this.topicMap.delete(s3.topic, e2), this.events.emit(O4.deleted, we2(W2({}, s3), { reason: t })); } async persist() { await this.setRelayerSubscriptions(this.values), this.events.emit(O4.sync); } async reset() { if (this.cached.length) { const e2 = Math.ceil(this.cached.length / this.batchSubscribeTopicsLimit); for (let t = 0; t < e2; t++) { const s3 = this.cached.splice(0, this.batchSubscribeTopicsLimit); await this.batchFetchMessages(s3), await this.batchSubscribe(s3); } } this.events.emit(O4.resubscribed); } async restore() { try { const e2 = await this.getRelayerSubscriptions(); if (typeof e2 > "u" || !e2.length) return; if (this.subscriptions.size) { const { message: t } = S("RESTORE_WILL_OVERRIDE", this.name); throw this.logger.error(t), this.logger.error(`${this.name}: ${JSON.stringify(this.values)}`), new Error(t); } this.cached = e2, this.logger.debug(`Successfully Restored subscriptions for ${this.name}`), this.logger.trace({ type: "method", method: "restore", subscriptions: this.values }); } catch (e2) { this.logger.debug(`Failed to Restore subscriptions for ${this.name}`), this.logger.error(e2); } } async batchSubscribe(e2) { if (!e2.length) return; const t = await this.rpcBatchSubscribe(e2); L(t) && this.onBatchSubscribe(t.map((s3, i4) => we2(W2({}, e2[i4]), { id: s3 }))); } async batchFetchMessages(e2) { if (!e2.length) return; this.logger.trace(`Fetching batch messages for ${e2.length} subscriptions`); const t = await this.rpcBatchFetchMessages(e2); t && t.messages && (this.pendingBatchMessages = this.pendingBatchMessages.concat(t.messages)); } async onConnect() { await this.restart(), this.onEnable(); } onDisconnect() { this.onDisable(); } async checkPending() { if (!this.initialized || !this.relayer.connected) return; const e2 = []; this.pending.forEach((t) => { e2.push(t); }), await this.batchSubscribe(e2), this.pendingBatchMessages.length && (await this.relayer.handleBatchMessageEvents(this.pendingBatchMessages), this.pendingBatchMessages = []); } registerEventListeners() { this.relayer.core.heartbeat.on(r3.pulse, async () => { await this.checkPending(); }), this.events.on(O4.created, async (e2) => { const t = O4.created; this.logger.info(`Emitting ${t}`), this.logger.debug({ type: "event", event: t, data: e2 }), await this.persist(); }), this.events.on(O4.deleted, async (e2) => { const t = O4.deleted; this.logger.info(`Emitting ${t}`), this.logger.debug({ type: "event", event: t, data: e2 }), await this.persist(); }); } isInitialized() { if (!this.initialized) { const { message: e2 } = S("NOT_INITIALIZED", this.name); throw new Error(e2); } } async restartToComplete() { !this.relayer.connected && !this.relayer.connecting && await this.relayer.transportOpen(), this.restartInProgress && await new Promise((e2) => { const t = setInterval(() => { this.restartInProgress || (clearInterval(t), e2()); }, this.pollingInterval); }); } }; var on2 = Object.defineProperty; var Zt2 = Object.getOwnPropertySymbols; var an2 = Object.prototype.hasOwnProperty; var hn2 = Object.prototype.propertyIsEnumerable; var Qt2 = (o4, e2, t) => e2 in o4 ? on2(o4, e2, { enumerable: true, configurable: true, writable: true, value: t }) : o4[e2] = t; var ei = (o4, e2) => { for (var t in e2 || (e2 = {})) an2.call(e2, t) && Qt2(o4, t, e2[t]); if (Zt2) for (var t of Zt2(e2)) hn2.call(e2, t) && Qt2(o4, t, e2[t]); return o4; }; var ti = class extends u { constructor(e2) { super(e2), this.protocol = "wc", this.version = 2, this.events = new import_events7.EventEmitter(), this.name = ot, this.transportExplicitlyClosed = false, this.initialized = false, this.connectionAttemptInProgress = false, this.connectionStatusPollingInterval = 20, this.staleConnectionErrors = ["socket hang up", "stalled", "interrupted"], this.hasExperiencedNetworkDisruption = false, this.requestsInFlight = /* @__PURE__ */ new Map(), this.heartBeatTimeout = (0, import_time4.toMiliseconds)(import_time4.THIRTY_SECONDS + import_time4.ONE_SECOND), this.request = async (t) => { var s3, i4; this.logger.debug("Publishing Request Payload"); const r4 = t.id || getBigIntRpcId().toString(); await this.toEstablishConnection(); try { const n5 = this.provider.request(t); this.requestsInFlight.set(r4, { promise: n5, request: t }), this.logger.trace({ id: r4, method: t.method, topic: (s3 = t.params) == null ? void 0 : s3.topic }, "relayer.request - attempt to publish..."); const a4 = await new Promise(async (h5, c5) => { const l4 = () => { c5(new Error(`relayer.request - publish interrupted, id: ${r4}`)); }; this.provider.on(I3.disconnect, l4); const p3 = await n5; this.provider.off(I3.disconnect, l4), h5(p3); }); return this.logger.trace({ id: r4, method: t.method, topic: (i4 = t.params) == null ? void 0 : i4.topic }, "relayer.request - published"), a4; } catch (n5) { throw this.logger.debug(`Failed to Publish Request: ${r4}`), n5; } finally { this.requestsInFlight.delete(r4); } }, this.resetPingTimeout = () => { if (ce()) try { clearTimeout(this.pingTimeout), this.pingTimeout = setTimeout(() => { var t, s3, i4; (i4 = (s3 = (t = this.provider) == null ? void 0 : t.connection) == null ? void 0 : s3.socket) == null || i4.terminate(); }, this.heartBeatTimeout); } catch (t) { this.logger.warn(t); } }, this.onPayloadHandler = (t) => { this.onProviderPayload(t), this.resetPingTimeout(); }, this.onConnectHandler = () => { this.logger.trace("relayer connected"), this.startPingTimeout(), this.events.emit(v3.connect); }, this.onDisconnectHandler = () => { this.logger.trace("relayer disconnected"), this.onProviderDisconnect(); }, this.onProviderErrorHandler = (t) => { this.logger.error(t), this.events.emit(v3.error, t), this.logger.info("Fatal socket error received, closing transport"), this.transportClose(); }, this.registerProviderListeners = () => { this.provider.on(I3.payload, this.onPayloadHandler), this.provider.on(I3.connect, this.onConnectHandler), this.provider.on(I3.disconnect, this.onDisconnectHandler), this.provider.on(I3.error, this.onProviderErrorHandler); }, this.core = e2.core, this.logger = typeof e2.logger < "u" && typeof e2.logger != "string" ? E(e2.logger, this.name) : (0, import_pino2.default)(k2({ level: e2.logger || nt })), this.messages = new Yt2(this.logger, e2.core), this.subscriber = new Wt2(this, this.logger), this.publisher = new Zr2(this, this.logger), this.relayUrl = (e2 == null ? void 0 : e2.relayUrl) || be2, this.projectId = e2.projectId, this.bundleId = Ot(), this.provider = {}; } async init() { if (this.logger.trace("Initialized"), this.registerEventListeners(), await Promise.all([this.messages.init(), this.subscriber.init()]), this.initialized = true, this.subscriber.cached.length > 0) try { await this.transportOpen(); } catch (e2) { this.logger.warn(e2); } } get context() { return y2(this.logger); } get connected() { var e2, t, s3; return ((s3 = (t = (e2 = this.provider) == null ? void 0 : e2.connection) == null ? void 0 : t.socket) == null ? void 0 : s3.readyState) === 1; } get connecting() { var e2, t, s3; return ((s3 = (t = (e2 = this.provider) == null ? void 0 : e2.connection) == null ? void 0 : t.socket) == null ? void 0 : s3.readyState) === 0; } async publish(e2, t, s3) { this.isInitialized(), await this.publisher.publish(e2, t, s3), await this.recordMessageEvent({ topic: e2, message: t, publishedAt: Date.now(), transportType: M3.relay }); } async subscribe(e2, t) { var s3, i4, r4; this.isInitialized(), (t == null ? void 0 : t.transportType) === "relay" && await this.toEstablishConnection(); const n5 = typeof ((s3 = t == null ? void 0 : t.internal) == null ? void 0 : s3.throwOnFailedPublish) > "u" ? true : (i4 = t == null ? void 0 : t.internal) == null ? void 0 : i4.throwOnFailedPublish; let a4 = ((r4 = this.subscriber.topicMap.get(e2)) == null ? void 0 : r4[0]) || "", h5; const c5 = (l4) => { l4.topic === e2 && (this.subscriber.off(O4.created, c5), h5()); }; return await Promise.all([new Promise((l4) => { h5 = l4, this.subscriber.on(O4.created, c5); }), new Promise(async (l4, p3) => { a4 = await this.subscriber.subscribe(e2, ei({ internal: { throwOnFailedPublish: n5 } }, t)).catch((D4) => { n5 && p3(D4); }) || a4, l4(); })]), a4; } async unsubscribe(e2, t) { this.isInitialized(), await this.subscriber.unsubscribe(e2, t); } on(e2, t) { this.events.on(e2, t); } once(e2, t) { this.events.once(e2, t); } off(e2, t) { this.events.off(e2, t); } removeListener(e2, t) { this.events.removeListener(e2, t); } async transportDisconnect() { if (!this.hasExperiencedNetworkDisruption && this.connected && this.requestsInFlight.size > 0) try { await Promise.all(Array.from(this.requestsInFlight.values()).map((e2) => e2.promise)); } catch (e2) { this.logger.warn(e2); } this.provider.disconnect && (this.hasExperiencedNetworkDisruption || this.connected) ? await kt(this.provider.disconnect(), 2e3, "provider.disconnect()").catch(() => this.onProviderDisconnect()) : this.onProviderDisconnect(); } async transportClose() { this.transportExplicitlyClosed = true, await this.transportDisconnect(); } async transportOpen(e2) { await this.confirmOnlineStateOrThrow(), e2 && e2 !== this.relayUrl && (this.relayUrl = e2, await this.transportDisconnect()), await this.createProvider(), this.connectionAttemptInProgress = true, this.transportExplicitlyClosed = false; try { await new Promise(async (t, s3) => { const i4 = () => { this.provider.off(I3.disconnect, i4), s3(new Error("Connection interrupted while trying to subscribe")); }; this.provider.on(I3.disconnect, i4), await kt(this.provider.connect(), (0, import_time4.toMiliseconds)(import_time4.ONE_MINUTE), `Socket stalled when trying to connect to ${this.relayUrl}`).catch((r4) => { s3(r4); }).finally(() => { clearTimeout(this.reconnectTimeout), this.reconnectTimeout = void 0; }), this.subscriber.start().catch((r4) => { this.logger.error(r4), this.onDisconnectHandler(); }), this.hasExperiencedNetworkDisruption = false, t(); }); } catch (t) { this.logger.error(t); const s3 = t; if (this.hasExperiencedNetworkDisruption = true, !this.isConnectionStalled(s3.message)) throw t; } finally { this.connectionAttemptInProgress = false; } } async restartTransport(e2) { this.connectionAttemptInProgress || (this.relayUrl = e2 || this.relayUrl, await this.confirmOnlineStateOrThrow(), await this.transportClose(), await this.transportOpen()); } async confirmOnlineStateOrThrow() { if (!await mo()) throw new Error("No internet connection detected. Please restart your network and try again."); } async handleBatchMessageEvents(e2) { if ((e2 == null ? void 0 : e2.length) === 0) { this.logger.trace("Batch message events is empty. Ignoring..."); return; } const t = e2.sort((s3, i4) => s3.publishedAt - i4.publishedAt); this.logger.trace(`Batch of ${t.length} message events sorted`); for (const s3 of t) try { await this.onMessageEvent(s3); } catch (i4) { this.logger.warn(i4); } this.logger.trace(`Batch of ${t.length} message events processed`); } async onLinkMessageEvent(e2, t) { const { topic: s3 } = e2; if (!t.sessionExists) { const i4 = Mt(import_time4.FIVE_MINUTES), r4 = { topic: s3, expiry: i4, relay: { protocol: "irn" }, active: false }; await this.core.pairing.pairings.set(s3, r4); } this.events.emit(v3.message, e2), await this.recordMessageEvent(e2); } startPingTimeout() { var e2, t, s3, i4, r4; if (ce()) try { (t = (e2 = this.provider) == null ? void 0 : e2.connection) != null && t.socket && ((r4 = (i4 = (s3 = this.provider) == null ? void 0 : s3.connection) == null ? void 0 : i4.socket) == null || r4.once("ping", () => { this.resetPingTimeout(); })), this.resetPingTimeout(); } catch (n5) { this.logger.warn(n5); } } isConnectionStalled(e2) { return this.staleConnectionErrors.some((t) => e2.includes(t)); } async createProvider() { this.provider.connection && this.unregisterProviderListeners(); const e2 = await this.core.crypto.signJWT(this.relayUrl); this.provider = new o2(new f2($t({ sdkVersion: se, protocol: this.protocol, version: this.version, relayUrl: this.relayUrl, projectId: this.projectId, auth: e2, useOnCloseEvent: true, bundleId: this.bundleId }))), this.registerProviderListeners(); } async recordMessageEvent(e2) { const { topic: t, message: s3 } = e2; await this.messages.set(t, s3); } async shouldIgnoreMessageEvent(e2) { const { topic: t, message: s3 } = e2; if (!s3 || s3.length === 0) return this.logger.debug(`Ignoring invalid/empty message: ${s3}`), true; if (!await this.subscriber.isSubscribed(t)) return this.logger.debug(`Ignoring message for non-subscribed topic ${t}`), true; const i4 = this.messages.has(t, s3); return i4 && this.logger.debug(`Ignoring duplicate message: ${s3}`), i4; } async onProviderPayload(e2) { if (this.logger.debug("Incoming Relay Payload"), this.logger.trace({ type: "payload", direction: "incoming", payload: e2 }), isJsonRpcRequest(e2)) { if (!e2.method.endsWith(at2)) return; const t = e2.params, { topic: s3, message: i4, publishedAt: r4, attestation: n5 } = t.data, a4 = { topic: s3, message: i4, publishedAt: r4, transportType: M3.relay, attestation: n5 }; this.logger.debug("Emitting Relayer Payload"), this.logger.trace(ei({ type: "event", event: t.id }, a4)), this.events.emit(t.id, a4), await this.acknowledgePayload(e2), await this.onMessageEvent(a4); } else isJsonRpcResponse(e2) && this.events.emit(v3.message_ack, e2); } async onMessageEvent(e2) { await this.shouldIgnoreMessageEvent(e2) || (this.events.emit(v3.message, e2), await this.recordMessageEvent(e2)); } async acknowledgePayload(e2) { const t = formatJsonRpcResult(e2.id, true); await this.provider.connection.send(t); } unregisterProviderListeners() { this.provider.off(I3.payload, this.onPayloadHandler), this.provider.off(I3.connect, this.onConnectHandler), this.provider.off(I3.disconnect, this.onDisconnectHandler), this.provider.off(I3.error, this.onProviderErrorHandler), clearTimeout(this.pingTimeout); } async registerEventListeners() { let e2 = await mo(); ho(async (t) => { e2 !== t && (e2 = t, t ? await this.restartTransport().catch((s3) => this.logger.error(s3)) : (this.hasExperiencedNetworkDisruption = true, await this.transportDisconnect(), this.transportExplicitlyClosed = false)); }); } async onProviderDisconnect() { await this.subscriber.stop(), this.requestsInFlight.clear(), clearTimeout(this.pingTimeout), this.events.emit(v3.disconnect), this.connectionAttemptInProgress = false, !this.transportExplicitlyClosed && (this.reconnectTimeout || (this.reconnectTimeout = setTimeout(async () => { await this.transportOpen().catch((e2) => this.logger.error(e2)); }, (0, import_time4.toMiliseconds)(ht)))); } isInitialized() { if (!this.initialized) { const { message: e2 } = S("NOT_INITIALIZED", this.name); throw new Error(e2); } } async toEstablishConnection() { await this.confirmOnlineStateOrThrow(), !this.connected && (this.connectionAttemptInProgress && await new Promise((e2) => { const t = setInterval(() => { this.connected && (clearInterval(t), e2()); }, this.connectionStatusPollingInterval); }), await this.transportOpen()); } }; var cn2 = Object.defineProperty; var ii = Object.getOwnPropertySymbols; var ln2 = Object.prototype.hasOwnProperty; var un2 = Object.prototype.propertyIsEnumerable; var si = (o4, e2, t) => e2 in o4 ? cn2(o4, e2, { enumerable: true, configurable: true, writable: true, value: t }) : o4[e2] = t; var ri = (o4, e2) => { for (var t in e2 || (e2 = {})) ln2.call(e2, t) && si(o4, t, e2[t]); if (ii) for (var t of ii(e2)) un2.call(e2, t) && si(o4, t, e2[t]); return o4; }; var ni = class extends p2 { constructor(e2, t, s3, i4 = x4, r4 = void 0) { super(e2, t, s3, i4), this.core = e2, this.logger = t, this.name = s3, this.map = /* @__PURE__ */ new Map(), this.version = ct, this.cached = [], this.initialized = false, this.storagePrefix = x4, this.recentlyDeleted = [], this.recentlyDeletedLimit = 200, this.init = async () => { this.initialized || (this.logger.trace("Initialized"), await this.restore(), this.cached.forEach((n5) => { this.getKey && n5 !== null && !I(n5) ? this.map.set(this.getKey(n5), n5) : Yr(n5) ? this.map.set(n5.id, n5) : Qr(n5) && this.map.set(n5.topic, n5); }), this.cached = [], this.initialized = true); }, this.set = async (n5, a4) => { this.isInitialized(), this.map.has(n5) ? await this.update(n5, a4) : (this.logger.debug("Setting value"), this.logger.trace({ type: "method", method: "set", key: n5, value: a4 }), this.map.set(n5, a4), await this.persist()); }, this.get = (n5) => (this.isInitialized(), this.logger.debug("Getting value"), this.logger.trace({ type: "method", method: "get", key: n5 }), this.getData(n5)), this.getAll = (n5) => (this.isInitialized(), n5 ? this.values.filter((a4) => Object.keys(n5).every((h5) => (0, import_lodash.default)(a4[h5], n5[h5]))) : this.values), this.update = async (n5, a4) => { this.isInitialized(), this.logger.debug("Updating value"), this.logger.trace({ type: "method", method: "update", key: n5, update: a4 }); const h5 = ri(ri({}, this.getData(n5)), a4); this.map.set(n5, h5), await this.persist(); }, this.delete = async (n5, a4) => { this.isInitialized(), this.map.has(n5) && (this.logger.debug("Deleting value"), this.logger.trace({ type: "method", method: "delete", key: n5, reason: a4 }), this.map.delete(n5), this.addToRecentlyDeleted(n5), await this.persist()); }, this.logger = E(t, this.name), this.storagePrefix = i4, this.getKey = r4; } get context() { return y2(this.logger); } get storageKey() { return this.storagePrefix + this.version + this.core.customStoragePrefix + "//" + this.name; } get length() { return this.map.size; } get keys() { return Array.from(this.map.keys()); } get values() { return Array.from(this.map.values()); } addToRecentlyDeleted(e2) { this.recentlyDeleted.push(e2), this.recentlyDeleted.length >= this.recentlyDeletedLimit && this.recentlyDeleted.splice(0, this.recentlyDeletedLimit / 2); } async setDataStore(e2) { await this.core.storage.setItem(this.storageKey, e2); } async getDataStore() { return await this.core.storage.getItem(this.storageKey); } getData(e2) { const t = this.map.get(e2); if (!t) { if (this.recentlyDeleted.includes(e2)) { const { message: i4 } = S("MISSING_OR_INVALID", `Record was recently deleted - ${this.name}: ${e2}`); throw this.logger.error(i4), new Error(i4); } const { message: s3 } = S("NO_MATCHING_KEY", `${this.name}: ${e2}`); throw this.logger.error(s3), new Error(s3); } return t; } async persist() { await this.setDataStore(this.values); } async restore() { try { const e2 = await this.getDataStore(); if (typeof e2 > "u" || !e2.length) return; if (this.map.size) { const { message: t } = S("RESTORE_WILL_OVERRIDE", this.name); throw this.logger.error(t), new Error(t); } this.cached = e2, this.logger.debug(`Successfully Restored value for ${this.name}`), this.logger.trace({ type: "method", method: "restore", value: this.values }); } catch (e2) { this.logger.debug(`Failed to Restore value for ${this.name}`), this.logger.error(e2); } } isInitialized() { if (!this.initialized) { const { message: e2 } = S("NOT_INITIALIZED", this.name); throw new Error(e2); } } }; var oi = class { constructor(e2, t) { this.core = e2, this.logger = t, this.name = gt2, this.version = yt, this.events = new import_events7.default(), this.initialized = false, this.storagePrefix = x4, this.ignoredPayloadTypes = [D], this.registeredMethods = [], this.init = async () => { this.initialized || (await this.pairings.init(), await this.cleanup(), this.registerRelayerEvents(), this.registerExpirerEvents(), this.initialized = true, this.logger.trace("Initialized")); }, this.register = ({ methods: s3 }) => { this.isInitialized(), this.registeredMethods = [.../* @__PURE__ */ new Set([...this.registeredMethods, ...s3])]; }, this.create = async (s3) => { this.isInitialized(); const i4 = pr(), r4 = await this.core.crypto.setSymKey(i4), n5 = Mt(import_time4.FIVE_MINUTES), a4 = { protocol: rt }, h5 = { topic: r4, expiry: n5, relay: a4, active: false, methods: s3 == null ? void 0 : s3.methods }, c5 = Dr({ protocol: this.core.protocol, version: this.core.version, topic: r4, symKey: i4, relay: a4, expiryTimestamp: n5, methods: s3 == null ? void 0 : s3.methods }); return this.events.emit(V2.create, h5), this.core.expirer.set(r4, n5), await this.pairings.set(r4, h5), await this.core.relayer.subscribe(r4, { transportType: s3 == null ? void 0 : s3.transportType }), { topic: r4, uri: c5 }; }, this.pair = async (s3) => { this.isInitialized(); const i4 = this.core.eventClient.createEvent({ properties: { topic: s3 == null ? void 0 : s3.uri, trace: [z4.pairing_started] } }); this.isValidPair(s3, i4); const { topic: r4, symKey: n5, relay: a4, expiryTimestamp: h5, methods: c5 } = kr(s3.uri); i4.props.properties.topic = r4, i4.addTrace(z4.pairing_uri_validation_success), i4.addTrace(z4.pairing_uri_not_expired); let l4; if (this.pairings.keys.includes(r4)) { if (l4 = this.pairings.get(r4), i4.addTrace(z4.existing_pairing), l4.active) throw i4.setError($2.active_pairing_already_exists), new Error(`Pairing already exists: ${r4}. Please try again with a new connection URI.`); i4.addTrace(z4.pairing_not_expired); } const p3 = h5 || Mt(import_time4.FIVE_MINUTES), D4 = { topic: r4, relay: a4, expiry: p3, active: false, methods: c5 }; this.core.expirer.set(r4, p3), await this.pairings.set(r4, D4), i4.addTrace(z4.store_new_pairing), s3.activatePairing && await this.activate({ topic: r4 }), this.events.emit(V2.create, D4), i4.addTrace(z4.emit_inactive_pairing), this.core.crypto.keychain.has(r4) || await this.core.crypto.setSymKey(n5, r4), i4.addTrace(z4.subscribing_pairing_topic); try { await this.core.relayer.confirmOnlineStateOrThrow(); } catch { i4.setError($2.no_internet_connection); } try { await this.core.relayer.subscribe(r4, { relay: a4 }); } catch (m2) { throw i4.setError($2.subscribe_pairing_topic_failure), m2; } return i4.addTrace(z4.subscribe_pairing_topic_success), D4; }, this.activate = async ({ topic: s3 }) => { this.isInitialized(); const i4 = Mt(import_time4.THIRTY_DAYS); this.core.expirer.set(s3, i4), await this.pairings.update(s3, { active: true, expiry: i4 }); }, this.ping = async (s3) => { this.isInitialized(), await this.isValidPing(s3); const { topic: i4 } = s3; if (this.pairings.keys.includes(i4)) { const r4 = await this.sendRequest(i4, "wc_pairingPing", {}), { done: n5, resolve: a4, reject: h5 } = _t(); this.events.once(Lt("pairing_ping", r4), ({ error: c5 }) => { c5 ? h5(c5) : a4(); }), await n5(); } }, this.updateExpiry = async ({ topic: s3, expiry: i4 }) => { this.isInitialized(), await this.pairings.update(s3, { expiry: i4 }); }, this.updateMetadata = async ({ topic: s3, metadata: i4 }) => { this.isInitialized(), await this.pairings.update(s3, { peerMetadata: i4 }); }, this.getPairings = () => (this.isInitialized(), this.pairings.values), this.disconnect = async (s3) => { this.isInitialized(), await this.isValidDisconnect(s3); const { topic: i4 } = s3; this.pairings.keys.includes(i4) && (await this.sendRequest(i4, "wc_pairingDelete", U("USER_DISCONNECTED")), await this.deletePairing(i4)); }, this.formatUriFromPairing = (s3) => { this.isInitialized(); const { topic: i4, relay: r4, expiry: n5, methods: a4 } = s3, h5 = this.core.crypto.keychain.get(i4); return Dr({ protocol: this.core.protocol, version: this.core.version, topic: i4, symKey: h5, relay: r4, expiryTimestamp: n5, methods: a4 }); }, this.sendRequest = async (s3, i4, r4) => { const n5 = formatJsonRpcRequest(i4, r4), a4 = await this.core.crypto.encode(s3, n5), h5 = B3[i4].req; return this.core.history.set(s3, n5), this.core.relayer.publish(s3, a4, h5), n5.id; }, this.sendResult = async (s3, i4, r4) => { const n5 = formatJsonRpcResult(s3, r4), a4 = await this.core.crypto.encode(i4, n5), h5 = await this.core.history.get(i4, s3), c5 = B3[h5.request.method].res; await this.core.relayer.publish(i4, a4, c5), await this.core.history.resolve(n5); }, this.sendError = async (s3, i4, r4) => { const n5 = formatJsonRpcError(s3, r4), a4 = await this.core.crypto.encode(i4, n5), h5 = await this.core.history.get(i4, s3), c5 = B3[h5.request.method] ? B3[h5.request.method].res : B3.unregistered_method.res; await this.core.relayer.publish(i4, a4, c5), await this.core.history.resolve(n5); }, this.deletePairing = async (s3, i4) => { await this.core.relayer.unsubscribe(s3), await Promise.all([this.pairings.delete(s3, U("USER_DISCONNECTED")), this.core.crypto.deleteSymKey(s3), i4 ? Promise.resolve() : this.core.expirer.del(s3)]); }, this.cleanup = async () => { const s3 = this.pairings.getAll().filter((i4) => Kt(i4.expiry)); await Promise.all(s3.map((i4) => this.deletePairing(i4.topic))); }, this.onRelayEventRequest = (s3) => { const { topic: i4, payload: r4 } = s3; switch (r4.method) { case "wc_pairingPing": return this.onPairingPingRequest(i4, r4); case "wc_pairingDelete": return this.onPairingDeleteRequest(i4, r4); default: return this.onUnknownRpcMethodRequest(i4, r4); } }, this.onRelayEventResponse = async (s3) => { const { topic: i4, payload: r4 } = s3, n5 = (await this.core.history.get(i4, r4.id)).request.method; switch (n5) { case "wc_pairingPing": return this.onPairingPingResponse(i4, r4); default: return this.onUnknownRpcMethodResponse(n5); } }, this.onPairingPingRequest = async (s3, i4) => { const { id: r4 } = i4; try { this.isValidPing({ topic: s3 }), await this.sendResult(r4, s3, true), this.events.emit(V2.ping, { id: r4, topic: s3 }); } catch (n5) { await this.sendError(r4, s3, n5), this.logger.error(n5); } }, this.onPairingPingResponse = (s3, i4) => { const { id: r4 } = i4; setTimeout(() => { isJsonRpcResult(i4) ? this.events.emit(Lt("pairing_ping", r4), {}) : isJsonRpcError(i4) && this.events.emit(Lt("pairing_ping", r4), { error: i4.error }); }, 500); }, this.onPairingDeleteRequest = async (s3, i4) => { const { id: r4 } = i4; try { this.isValidDisconnect({ topic: s3 }), await this.deletePairing(s3), this.events.emit(V2.delete, { id: r4, topic: s3 }); } catch (n5) { await this.sendError(r4, s3, n5), this.logger.error(n5); } }, this.onUnknownRpcMethodRequest = async (s3, i4) => { const { id: r4, method: n5 } = i4; try { if (this.registeredMethods.includes(n5)) return; const a4 = U("WC_METHOD_UNSUPPORTED", n5); await this.sendError(r4, s3, a4), this.logger.error(a4); } catch (a4) { await this.sendError(r4, s3, a4), this.logger.error(a4); } }, this.onUnknownRpcMethodResponse = (s3) => { this.registeredMethods.includes(s3) || this.logger.error(U("WC_METHOD_UNSUPPORTED", s3)); }, this.isValidPair = (s3, i4) => { var r4; if (!to(s3)) { const { message: a4 } = S("MISSING_OR_INVALID", `pair() params: ${s3}`); throw i4.setError($2.malformed_pairing_uri), new Error(a4); } if (!Gr(s3.uri)) { const { message: a4 } = S("MISSING_OR_INVALID", `pair() uri: ${s3.uri}`); throw i4.setError($2.malformed_pairing_uri), new Error(a4); } const n5 = kr(s3 == null ? void 0 : s3.uri); if (!((r4 = n5 == null ? void 0 : n5.relay) != null && r4.protocol)) { const { message: a4 } = S("MISSING_OR_INVALID", "pair() uri#relay-protocol"); throw i4.setError($2.malformed_pairing_uri), new Error(a4); } if (!(n5 != null && n5.symKey)) { const { message: a4 } = S("MISSING_OR_INVALID", "pair() uri#symKey"); throw i4.setError($2.malformed_pairing_uri), new Error(a4); } if (n5 != null && n5.expiryTimestamp && (0, import_time4.toMiliseconds)(n5 == null ? void 0 : n5.expiryTimestamp) < Date.now()) { i4.setError($2.pairing_expired); const { message: a4 } = S("EXPIRED", "pair() URI has expired. Please try again with a new connection URI."); throw new Error(a4); } }, this.isValidPing = async (s3) => { if (!to(s3)) { const { message: r4 } = S("MISSING_OR_INVALID", `ping() params: ${s3}`); throw new Error(r4); } const { topic: i4 } = s3; await this.isValidPairingTopic(i4); }, this.isValidDisconnect = async (s3) => { if (!to(s3)) { const { message: r4 } = S("MISSING_OR_INVALID", `disconnect() params: ${s3}`); throw new Error(r4); } const { topic: i4 } = s3; await this.isValidPairingTopic(i4); }, this.isValidPairingTopic = async (s3) => { if (!b(s3, false)) { const { message: i4 } = S("MISSING_OR_INVALID", `pairing topic should be a string: ${s3}`); throw new Error(i4); } if (!this.pairings.keys.includes(s3)) { const { message: i4 } = S("NO_MATCHING_KEY", `pairing topic doesn't exist: ${s3}`); throw new Error(i4); } if (Kt(this.pairings.get(s3).expiry)) { await this.deletePairing(s3); const { message: i4 } = S("EXPIRED", `pairing topic: ${s3}`); throw new Error(i4); } }, this.core = e2, this.logger = E(t, this.name), this.pairings = new ni(this.core, this.logger, this.name, this.storagePrefix); } get context() { return y2(this.logger); } isInitialized() { if (!this.initialized) { const { message: e2 } = S("NOT_INITIALIZED", this.name); throw new Error(e2); } } registerRelayerEvents() { this.core.relayer.on(v3.message, async (e2) => { const { topic: t, message: s3, transportType: i4 } = e2; if (!this.pairings.keys.includes(t) || i4 === M3.link_mode || this.ignoredPayloadTypes.includes(this.core.crypto.getPayloadType(s3))) return; const r4 = await this.core.crypto.decode(t, s3); try { isJsonRpcRequest(r4) ? (this.core.history.set(t, r4), this.onRelayEventRequest({ topic: t, payload: r4 })) : isJsonRpcResponse(r4) && (await this.core.history.resolve(r4), await this.onRelayEventResponse({ topic: t, payload: r4 }), this.core.history.delete(t, r4.id)); } catch (n5) { this.logger.error(n5); } }); } registerExpirerEvents() { this.core.expirer.on(S5.expired, async (e2) => { const { topic: t } = Vt(e2.target); t && this.pairings.keys.includes(t) && (await this.deletePairing(t, true), this.events.emit(V2.expire, { topic: t })); }); } }; var ai = class extends h3 { constructor(e2, t) { super(e2, t), this.core = e2, this.logger = t, this.records = /* @__PURE__ */ new Map(), this.events = new import_events7.EventEmitter(), this.name = Dt2, this.version = mt2, this.cached = [], this.initialized = false, this.storagePrefix = x4, this.init = async () => { this.initialized || (this.logger.trace("Initialized"), await this.restore(), this.cached.forEach((s3) => this.records.set(s3.id, s3)), this.cached = [], this.registerEventListeners(), this.initialized = true); }, this.set = (s3, i4, r4) => { if (this.isInitialized(), this.logger.debug("Setting JSON-RPC request history record"), this.logger.trace({ type: "method", method: "set", topic: s3, request: i4, chainId: r4 }), this.records.has(i4.id)) return; const n5 = { id: i4.id, topic: s3, request: { method: i4.method, params: i4.params || null }, chainId: r4, expiry: Mt(import_time4.THIRTY_DAYS) }; this.records.set(n5.id, n5), this.persist(), this.events.emit(P2.created, n5); }, this.resolve = async (s3) => { if (this.isInitialized(), this.logger.debug("Updating JSON-RPC response history record"), this.logger.trace({ type: "method", method: "update", response: s3 }), !this.records.has(s3.id)) return; const i4 = await this.getRecord(s3.id); typeof i4.response > "u" && (i4.response = isJsonRpcError(s3) ? { error: s3.error } : { result: s3.result }, this.records.set(i4.id, i4), this.persist(), this.events.emit(P2.updated, i4)); }, this.get = async (s3, i4) => (this.isInitialized(), this.logger.debug("Getting record"), this.logger.trace({ type: "method", method: "get", topic: s3, id: i4 }), await this.getRecord(i4)), this.delete = (s3, i4) => { this.isInitialized(), this.logger.debug("Deleting record"), this.logger.trace({ type: "method", method: "delete", id: i4 }), this.values.forEach((r4) => { if (r4.topic === s3) { if (typeof i4 < "u" && r4.id !== i4) return; this.records.delete(r4.id), this.events.emit(P2.deleted, r4); } }), this.persist(); }, this.exists = async (s3, i4) => (this.isInitialized(), this.records.has(i4) ? (await this.getRecord(i4)).topic === s3 : false), this.on = (s3, i4) => { this.events.on(s3, i4); }, this.once = (s3, i4) => { this.events.once(s3, i4); }, this.off = (s3, i4) => { this.events.off(s3, i4); }, this.removeListener = (s3, i4) => { this.events.removeListener(s3, i4); }, this.logger = E(t, this.name); } get context() { return y2(this.logger); } get storageKey() { return this.storagePrefix + this.version + this.core.customStoragePrefix + "//" + this.name; } get size() { return this.records.size; } get keys() { return Array.from(this.records.keys()); } get values() { return Array.from(this.records.values()); } get pending() { const e2 = []; return this.values.forEach((t) => { if (typeof t.response < "u") return; const s3 = { topic: t.topic, request: formatJsonRpcRequest(t.request.method, t.request.params, t.id), chainId: t.chainId }; return e2.push(s3); }), e2; } async setJsonRpcRecords(e2) { await this.core.storage.setItem(this.storageKey, e2); } async getJsonRpcRecords() { return await this.core.storage.getItem(this.storageKey); } getRecord(e2) { this.isInitialized(); const t = this.records.get(e2); if (!t) { const { message: s3 } = S("NO_MATCHING_KEY", `${this.name}: ${e2}`); throw new Error(s3); } return t; } async persist() { await this.setJsonRpcRecords(this.values), this.events.emit(P2.sync); } async restore() { try { const e2 = await this.getJsonRpcRecords(); if (typeof e2 > "u" || !e2.length) return; if (this.records.size) { const { message: t } = S("RESTORE_WILL_OVERRIDE", this.name); throw this.logger.error(t), new Error(t); } this.cached = e2, this.logger.debug(`Successfully Restored records for ${this.name}`), this.logger.trace({ type: "method", method: "restore", records: this.values }); } catch (e2) { this.logger.debug(`Failed to Restore records for ${this.name}`), this.logger.error(e2); } } registerEventListeners() { this.events.on(P2.created, (e2) => { const t = P2.created; this.logger.info(`Emitting ${t}`), this.logger.debug({ type: "event", event: t, record: e2 }); }), this.events.on(P2.updated, (e2) => { const t = P2.updated; this.logger.info(`Emitting ${t}`), this.logger.debug({ type: "event", event: t, record: e2 }); }), this.events.on(P2.deleted, (e2) => { const t = P2.deleted; this.logger.info(`Emitting ${t}`), this.logger.debug({ type: "event", event: t, record: e2 }); }), this.core.heartbeat.on(r3.pulse, () => { this.cleanup(); }); } cleanup() { try { this.isInitialized(); let e2 = false; this.records.forEach((t) => { (0, import_time4.toMiliseconds)(t.expiry || 0) - Date.now() <= 0 && (this.logger.info(`Deleting expired history log: ${t.id}`), this.records.delete(t.id), this.events.emit(P2.deleted, t, false), e2 = true); }), e2 && this.persist(); } catch (e2) { this.logger.warn(e2); } } isInitialized() { if (!this.initialized) { const { message: e2 } = S("NOT_INITIALIZED", this.name); throw new Error(e2); } } }; var hi = class extends x3 { constructor(e2, t) { super(e2, t), this.core = e2, this.logger = t, this.expirations = /* @__PURE__ */ new Map(), this.events = new import_events7.EventEmitter(), this.name = bt2, this.version = ft, this.cached = [], this.initialized = false, this.storagePrefix = x4, this.init = async () => { this.initialized || (this.logger.trace("Initialized"), await this.restore(), this.cached.forEach((s3) => this.expirations.set(s3.target, s3)), this.cached = [], this.registerEventListeners(), this.initialized = true); }, this.has = (s3) => { try { const i4 = this.formatTarget(s3); return typeof this.getExpiration(i4) < "u"; } catch { return false; } }, this.set = (s3, i4) => { this.isInitialized(); const r4 = this.formatTarget(s3), n5 = { target: r4, expiry: i4 }; this.expirations.set(r4, n5), this.checkExpiry(r4, n5), this.events.emit(S5.created, { target: r4, expiration: n5 }); }, this.get = (s3) => { this.isInitialized(); const i4 = this.formatTarget(s3); return this.getExpiration(i4); }, this.del = (s3) => { if (this.isInitialized(), this.has(s3)) { const i4 = this.formatTarget(s3), r4 = this.getExpiration(i4); this.expirations.delete(i4), this.events.emit(S5.deleted, { target: i4, expiration: r4 }); } }, this.on = (s3, i4) => { this.events.on(s3, i4); }, this.once = (s3, i4) => { this.events.once(s3, i4); }, this.off = (s3, i4) => { this.events.off(s3, i4); }, this.removeListener = (s3, i4) => { this.events.removeListener(s3, i4); }, this.logger = E(t, this.name); } get context() { return y2(this.logger); } get storageKey() { return this.storagePrefix + this.version + this.core.customStoragePrefix + "//" + this.name; } get length() { return this.expirations.size; } get keys() { return Array.from(this.expirations.keys()); } get values() { return Array.from(this.expirations.values()); } formatTarget(e2) { if (typeof e2 == "string") return Dt(e2); if (typeof e2 == "number") return xt(e2); const { message: t } = S("UNKNOWN_TYPE", `Target type: ${typeof e2}`); throw new Error(t); } async setExpirations(e2) { await this.core.storage.setItem(this.storageKey, e2); } async getExpirations() { return await this.core.storage.getItem(this.storageKey); } async persist() { await this.setExpirations(this.values), this.events.emit(S5.sync); } async restore() { try { const e2 = await this.getExpirations(); if (typeof e2 > "u" || !e2.length) return; if (this.expirations.size) { const { message: t } = S("RESTORE_WILL_OVERRIDE", this.name); throw this.logger.error(t), new Error(t); } this.cached = e2, this.logger.debug(`Successfully Restored expirations for ${this.name}`), this.logger.trace({ type: "method", method: "restore", expirations: this.values }); } catch (e2) { this.logger.debug(`Failed to Restore expirations for ${this.name}`), this.logger.error(e2); } } getExpiration(e2) { const t = this.expirations.get(e2); if (!t) { const { message: s3 } = S("NO_MATCHING_KEY", `${this.name}: ${e2}`); throw this.logger.warn(s3), new Error(s3); } return t; } checkExpiry(e2, t) { const { expiry: s3 } = t; (0, import_time4.toMiliseconds)(s3) - Date.now() <= 0 && this.expire(e2, t); } expire(e2, t) { this.expirations.delete(e2), this.events.emit(S5.expired, { target: e2, expiration: t }); } checkExpirations() { this.core.relayer.connected && this.expirations.forEach((e2, t) => this.checkExpiry(t, e2)); } registerEventListeners() { this.core.heartbeat.on(r3.pulse, () => this.checkExpirations()), this.events.on(S5.created, (e2) => { const t = S5.created; this.logger.info(`Emitting ${t}`), this.logger.debug({ type: "event", event: t, data: e2 }), this.persist(); }), this.events.on(S5.expired, (e2) => { const t = S5.expired; this.logger.info(`Emitting ${t}`), this.logger.debug({ type: "event", event: t, data: e2 }), this.persist(); }), this.events.on(S5.deleted, (e2) => { const t = S5.deleted; this.logger.info(`Emitting ${t}`), this.logger.debug({ type: "event", event: t, data: e2 }), this.persist(); }); } isInitialized() { if (!this.initialized) { const { message: e2 } = S("NOT_INITIALIZED", this.name); throw new Error(e2); } } }; var ci = class extends y4 { constructor(e2, t, s3) { super(e2, t, s3), this.core = e2, this.logger = t, this.store = s3, this.name = _t2, this.verifyUrlV3 = vt2, this.storagePrefix = x4, this.version = De, this.init = async () => { var i4; this.isDevEnv || (this.publicKey = await this.store.getItem(this.storeKey), this.publicKey && (0, import_time4.toMiliseconds)((i4 = this.publicKey) == null ? void 0 : i4.expiresAt) < Date.now() && (this.logger.debug("verify v2 public key expired"), await this.removePublicKey())); }, this.register = async (i4) => { if (!V() || this.isDevEnv) return; const r4 = window.location.origin, { id: n5, decryptedId: a4 } = i4, h5 = `${this.verifyUrlV3}/attestation?projectId=${this.core.projectId}&origin=${r4}&id=${n5}&decryptedId=${a4}`; try { const c5 = (0, import_window_getters2.getDocument)(), l4 = this.startAbortTimer(import_time4.ONE_SECOND * 5), p3 = await new Promise((D4, m2) => { const u3 = () => { window.removeEventListener("message", _4), c5.body.removeChild(g4), m2("attestation aborted"); }; this.abortController.signal.addEventListener("abort", u3); const g4 = c5.createElement("iframe"); g4.src = h5, g4.style.display = "none", g4.addEventListener("error", u3, { signal: this.abortController.signal }); const _4 = (y6) => { if (y6.data && typeof y6.data == "string") try { const b5 = JSON.parse(y6.data); if (b5.type === "verify_attestation") { if (decodeJWT(b5.attestation).payload.id !== n5) return; clearInterval(l4), c5.body.removeChild(g4), this.abortController.signal.removeEventListener("abort", u3), window.removeEventListener("message", _4), D4(b5.attestation === null ? "" : b5.attestation); } } catch (b5) { this.logger.warn(b5); } }; c5.body.appendChild(g4), window.addEventListener("message", _4, { signal: this.abortController.signal }); }); return this.logger.debug("jwt attestation", p3), p3; } catch (c5) { this.logger.warn(c5); } return ""; }, this.resolve = async (i4) => { if (this.isDevEnv) return ""; const { attestationId: r4, hash: n5, encryptedId: a4 } = i4; if (r4 === "") { this.logger.debug("resolve: attestationId is empty, skipping"); return; } if (r4) { if (decodeJWT(r4).payload.id !== a4) return; const c5 = await this.isValidJwtAttestation(r4); if (c5) { if (!c5.isVerified) { this.logger.warn("resolve: jwt attestation: origin url not verified"); return; } return c5; } } if (!n5) return; const h5 = this.getVerifyUrl(i4 == null ? void 0 : i4.verifyUrl); return this.fetchAttestation(n5, h5); }, this.fetchAttestation = async (i4, r4) => { this.logger.debug(`resolving attestation: ${i4} from url: ${r4}`); const n5 = this.startAbortTimer(import_time4.ONE_SECOND * 5), a4 = await fetch(`${r4}/attestation/${i4}?v2Supported=true`, { signal: this.abortController.signal }); return clearTimeout(n5), a4.status === 200 ? await a4.json() : void 0; }, this.getVerifyUrl = (i4) => { let r4 = i4 || J; return wt.includes(r4) || (this.logger.info(`verify url: ${r4}, not included in trusted list, assigning default: ${J}`), r4 = J), r4; }, this.fetchPublicKey = async () => { try { this.logger.debug(`fetching public key from: ${this.verifyUrlV3}`); const i4 = this.startAbortTimer(import_time4.FIVE_SECONDS), r4 = await fetch(`${this.verifyUrlV3}/public-key`, { signal: this.abortController.signal }); return clearTimeout(i4), await r4.json(); } catch (i4) { this.logger.warn(i4); } }, this.persistPublicKey = async (i4) => { this.logger.debug("persisting public key to local storage", i4), await this.store.setItem(this.storeKey, i4), this.publicKey = i4; }, this.removePublicKey = async () => { this.logger.debug("removing verify v2 public key from storage"), await this.store.removeItem(this.storeKey), this.publicKey = void 0; }, this.isValidJwtAttestation = async (i4) => { const r4 = await this.getPublicKey(); try { if (r4) return this.validateAttestation(i4, r4); } catch (a4) { this.logger.error(a4), this.logger.warn("error validating attestation"); } const n5 = await this.fetchAndPersistPublicKey(); try { if (n5) return this.validateAttestation(i4, n5); } catch (a4) { this.logger.error(a4), this.logger.warn("error validating attestation"); } }, this.getPublicKey = async () => this.publicKey ? this.publicKey : await this.fetchAndPersistPublicKey(), this.fetchAndPersistPublicKey = async () => { if (this.fetchPromise) return await this.fetchPromise, this.publicKey; this.fetchPromise = new Promise(async (r4) => { const n5 = await this.fetchPublicKey(); n5 && (await this.persistPublicKey(n5), r4(n5)); }); const i4 = await this.fetchPromise; return this.fetchPromise = void 0, i4; }, this.validateAttestation = (i4, r4) => { const n5 = Rr(i4, r4.publicKey), a4 = { hasExpired: (0, import_time4.toMiliseconds)(n5.exp) < Date.now(), payload: n5 }; if (a4.hasExpired) throw this.logger.warn("resolve: jwt attestation expired"), new Error("JWT attestation expired"); return { origin: a4.payload.origin, isScam: a4.payload.isScam, isVerified: a4.payload.isVerified }; }, this.logger = E(t, this.name), this.abortController = new AbortController(), this.isDevEnv = Wt(), this.init(); } get storeKey() { return this.storagePrefix + this.version + this.core.customStoragePrefix + "//verify:public:key"; } get context() { return y2(this.logger); } startAbortTimer(e2) { return this.abortController = new AbortController(), setTimeout(() => this.abortController.abort(), (0, import_time4.toMiliseconds)(e2)); } }; var li = class extends v2 { constructor(e2, t) { super(e2, t), this.projectId = e2, this.logger = t, this.context = It, this.registerDeviceToken = async (s3) => { const { clientId: i4, token: r4, notificationType: n5, enableEncrypted: a4 = false } = s3, h5 = `${Tt2}/${this.projectId}/clients`; await fetch(h5, { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ client_id: i4, type: n5, token: r4, always_raw: a4 }) }); }, this.logger = E(t, this.context); } }; var dn2 = Object.defineProperty; var ui = Object.getOwnPropertySymbols; var pn = Object.prototype.hasOwnProperty; var gn2 = Object.prototype.propertyIsEnumerable; var di = (o4, e2, t) => e2 in o4 ? dn2(o4, e2, { enumerable: true, configurable: true, writable: true, value: t }) : o4[e2] = t; var Z2 = (o4, e2) => { for (var t in e2 || (e2 = {})) pn.call(e2, t) && di(o4, t, e2[t]); if (ui) for (var t of ui(e2)) gn2.call(e2, t) && di(o4, t, e2[t]); return o4; }; var pi = class extends C4 { constructor(e2, t, s3 = true) { super(e2, t, s3), this.core = e2, this.logger = t, this.context = Pt2, this.storagePrefix = x4, this.storageVersion = Ct, this.events = /* @__PURE__ */ new Map(), this.shouldPersist = false, this.init = async () => { if (!Wt()) try { const i4 = { eventId: Ht(), timestamp: Date.now(), domain: this.getAppDomain(), props: { event: "INIT", type: "", properties: { client_id: await this.core.crypto.getClientId(), user_agent: Ge(this.core.relayer.protocol, this.core.relayer.version, se) } } }; await this.sendEvent([i4]); } catch (i4) { this.logger.warn(i4); } }, this.createEvent = (i4) => { const { event: r4 = "ERROR", type: n5 = "", properties: { topic: a4, trace: h5 } } = i4, c5 = Ht(), l4 = this.core.projectId || "", p3 = Date.now(), D4 = Z2({ eventId: c5, timestamp: p3, props: { event: r4, type: n5, properties: { topic: a4, trace: h5 } }, bundleId: l4, domain: this.getAppDomain() }, this.setMethods(c5)); return this.telemetryEnabled && (this.events.set(c5, D4), this.shouldPersist = true), D4; }, this.getEvent = (i4) => { const { eventId: r4, topic: n5 } = i4; if (r4) return this.events.get(r4); const a4 = Array.from(this.events.values()).find((h5) => h5.props.properties.topic === n5); if (a4) return Z2(Z2({}, a4), this.setMethods(a4.eventId)); }, this.deleteEvent = (i4) => { const { eventId: r4 } = i4; this.events.delete(r4), this.shouldPersist = true; }, this.setEventListeners = () => { this.core.heartbeat.on(r3.pulse, async () => { this.shouldPersist && await this.persist(), this.events.forEach((i4) => { (0, import_time4.fromMiliseconds)(Date.now()) - (0, import_time4.fromMiliseconds)(i4.timestamp) > St && (this.events.delete(i4.eventId), this.shouldPersist = true); }); }); }, this.setMethods = (i4) => ({ addTrace: (r4) => this.addTrace(i4, r4), setError: (r4) => this.setError(i4, r4) }), this.addTrace = (i4, r4) => { const n5 = this.events.get(i4); n5 && (n5.props.properties.trace.push(r4), this.events.set(i4, n5), this.shouldPersist = true); }, this.setError = (i4, r4) => { const n5 = this.events.get(i4); n5 && (n5.props.type = r4, n5.timestamp = Date.now(), this.events.set(i4, n5), this.shouldPersist = true); }, this.persist = async () => { await this.core.storage.setItem(this.storageKey, Array.from(this.events.values())), this.shouldPersist = false; }, this.restore = async () => { try { const i4 = await this.core.storage.getItem(this.storageKey) || []; if (!i4.length) return; i4.forEach((r4) => { this.events.set(r4.eventId, Z2(Z2({}, r4), this.setMethods(r4.eventId))); }); } catch (i4) { this.logger.warn(i4); } }, this.submit = async () => { if (!this.telemetryEnabled || this.events.size === 0) return; const i4 = []; for (const [r4, n5] of this.events) n5.props.type && i4.push(n5); if (i4.length !== 0) try { if ((await this.sendEvent(i4)).ok) for (const r4 of i4) this.events.delete(r4.eventId), this.shouldPersist = true; } catch (r4) { this.logger.warn(r4); } }, this.sendEvent = async (i4) => { const r4 = this.getAppDomain() ? "" : "&sp=desktop"; return await fetch(`${Rt}?projectId=${this.core.projectId}&st=events_sdk&sv=js-${se}${r4}`, { method: "POST", body: JSON.stringify(i4) }); }, this.getAppDomain = () => Nt().url, this.logger = E(t, this.context), this.telemetryEnabled = s3, s3 ? this.restore().then(async () => { await this.submit(), this.setEventListeners(); }) : this.persist(); } get storageKey() { return this.storagePrefix + this.storageVersion + this.core.customStoragePrefix + "//" + this.context; } }; var yn2 = Object.defineProperty; var gi = Object.getOwnPropertySymbols; var Dn2 = Object.prototype.hasOwnProperty; var mn = Object.prototype.propertyIsEnumerable; var yi = (o4, e2, t) => e2 in o4 ? yn2(o4, e2, { enumerable: true, configurable: true, writable: true, value: t }) : o4[e2] = t; var Di = (o4, e2) => { for (var t in e2 || (e2 = {})) Dn2.call(e2, t) && yi(o4, t, e2[t]); if (gi) for (var t of gi(e2)) mn.call(e2, t) && yi(o4, t, e2[t]); return o4; }; var ne2 = class _ne extends n4 { constructor(e2) { var t; super(e2), this.protocol = ye2, this.version = De, this.name = ie, this.events = new import_events7.EventEmitter(), this.initialized = false, this.on = (n5, a4) => this.events.on(n5, a4), this.once = (n5, a4) => this.events.once(n5, a4), this.off = (n5, a4) => this.events.off(n5, a4), this.removeListener = (n5, a4) => this.events.removeListener(n5, a4), this.dispatchEnvelope = ({ topic: n5, message: a4, sessionExists: h5 }) => { if (!n5 || !a4) return; const c5 = { topic: n5, message: a4, publishedAt: Date.now(), transportType: M3.link_mode }; this.relayer.onLinkMessageEvent(c5, { sessionExists: h5 }); }, this.projectId = e2 == null ? void 0 : e2.projectId, this.relayUrl = (e2 == null ? void 0 : e2.relayUrl) || be2, this.customStoragePrefix = e2 != null && e2.customStoragePrefix ? `:${e2.customStoragePrefix}` : ""; const s3 = k2({ level: typeof (e2 == null ? void 0 : e2.logger) == "string" && e2.logger ? e2.logger : Ye.logger }), { logger: i4, chunkLoggerController: r4 } = A2({ opts: s3, maxSizeInBytes: e2 == null ? void 0 : e2.maxLogBlobSizeInBytes, loggerOverride: e2 == null ? void 0 : e2.logger }); this.logChunkController = r4, (t = this.logChunkController) != null && t.downloadLogsBlobInBrowser && (window.downloadLogsBlobInBrowser = async () => { var n5, a4; (n5 = this.logChunkController) != null && n5.downloadLogsBlobInBrowser && ((a4 = this.logChunkController) == null || a4.downloadLogsBlobInBrowser({ clientId: await this.crypto.getClientId() })); }), this.logger = E(i4, this.name), this.heartbeat = new i2(), this.crypto = new Ht2(this, this.logger, e2 == null ? void 0 : e2.keychain), this.history = new ai(this, this.logger), this.expirer = new hi(this, this.logger), this.storage = e2 != null && e2.storage ? e2.storage : new h2(Di(Di({}, Je2), e2 == null ? void 0 : e2.storageOptions)), this.relayer = new ti({ core: this, logger: this.logger, relayUrl: this.relayUrl, projectId: this.projectId }), this.pairing = new oi(this, this.logger), this.verify = new ci(this, this.logger, this.storage), this.echoClient = new li(this.projectId || "", this.logger), this.linkModeSupportedApps = [], this.eventClient = new pi(this, this.logger, e2 == null ? void 0 : e2.telemetryEnabled); } static async init(e2) { const t = new _ne(e2); await t.initialize(); const s3 = await t.crypto.getClientId(); return await t.storage.setItem(lt, s3), t; } get context() { return y2(this.logger); } async start() { this.initialized || await this.initialize(); } async getLogsBlob() { var e2; return (e2 = this.logChunkController) == null ? void 0 : e2.logsToBlob({ clientId: await this.crypto.getClientId() }); } async addLinkModeSupportedApp(e2) { this.linkModeSupportedApps.includes(e2) || (this.linkModeSupportedApps.push(e2), await this.storage.setItem(fe2, this.linkModeSupportedApps)); } async initialize() { this.logger.trace("Initialized"); try { await this.crypto.init(), await this.history.init(), await this.expirer.init(), await this.relayer.init(), await this.heartbeat.init(), await this.pairing.init(), this.eventClient.init(), this.linkModeSupportedApps = await this.storage.getItem(fe2) || [], this.initialized = true, this.logger.info("Core Initialization Success"); } catch (e2) { throw this.logger.warn(`Core Initialization Failure at epoch ${Date.now()}`, e2), this.logger.error(e2.message), e2; } } }; var bn2 = ne2; // node_modules/@walletconnect/sign-client/dist/index.es.js var import_events8 = __toESM(require_events()); var import_time5 = __toESM(require_cjs()); var be3 = "wc"; var Ce3 = 2; var Le2 = "client"; var ye3 = `${be3}@${Ce3}:${Le2}:`; var we3 = { name: Le2, logger: "error", controller: false, relayUrl: "wss://relay.walletconnect.org" }; var xe = "WALLETCONNECT_DEEPLINK_CHOICE"; var st3 = "proposal"; var it3 = "Proposal expired"; var rt2 = "session"; var z5 = import_time5.SEVEN_DAYS; var nt2 = "engine"; var v4 = { wc_sessionPropose: { req: { ttl: import_time5.FIVE_MINUTES, prompt: true, tag: 1100 }, res: { ttl: import_time5.FIVE_MINUTES, prompt: false, tag: 1101 }, reject: { ttl: import_time5.FIVE_MINUTES, prompt: false, tag: 1120 }, autoReject: { ttl: import_time5.FIVE_MINUTES, prompt: false, tag: 1121 } }, wc_sessionSettle: { req: { ttl: import_time5.FIVE_MINUTES, prompt: false, tag: 1102 }, res: { ttl: import_time5.FIVE_MINUTES, prompt: false, tag: 1103 } }, wc_sessionUpdate: { req: { ttl: import_time5.ONE_DAY, prompt: false, tag: 1104 }, res: { ttl: import_time5.ONE_DAY, prompt: false, tag: 1105 } }, wc_sessionExtend: { req: { ttl: import_time5.ONE_DAY, prompt: false, tag: 1106 }, res: { ttl: import_time5.ONE_DAY, prompt: false, tag: 1107 } }, wc_sessionRequest: { req: { ttl: import_time5.FIVE_MINUTES, prompt: true, tag: 1108 }, res: { ttl: import_time5.FIVE_MINUTES, prompt: false, tag: 1109 } }, wc_sessionEvent: { req: { ttl: import_time5.FIVE_MINUTES, prompt: true, tag: 1110 }, res: { ttl: import_time5.FIVE_MINUTES, prompt: false, tag: 1111 } }, wc_sessionDelete: { req: { ttl: import_time5.ONE_DAY, prompt: false, tag: 1112 }, res: { ttl: import_time5.ONE_DAY, prompt: false, tag: 1113 } }, wc_sessionPing: { req: { ttl: import_time5.ONE_DAY, prompt: false, tag: 1114 }, res: { ttl: import_time5.ONE_DAY, prompt: false, tag: 1115 } }, wc_sessionAuthenticate: { req: { ttl: import_time5.ONE_HOUR, prompt: true, tag: 1116 }, res: { ttl: import_time5.ONE_HOUR, prompt: false, tag: 1117 }, reject: { ttl: import_time5.FIVE_MINUTES, prompt: false, tag: 1118 }, autoReject: { ttl: import_time5.FIVE_MINUTES, prompt: false, tag: 1119 } } }; var me3 = { min: import_time5.FIVE_MINUTES, max: import_time5.SEVEN_DAYS }; var x5 = { idle: "IDLE", active: "ACTIVE" }; var ot2 = "request"; var at3 = ["wc_sessionPropose", "wc_sessionRequest", "wc_authRequest", "wc_sessionAuthenticate"]; var ct2 = "wc"; var lt2 = "auth"; var pt2 = "authKeys"; var ht2 = "pairingTopics"; var dt2 = "requests"; var oe2 = `${ct2}@${1.5}:${lt2}:`; var ae3 = `${oe2}:PUB_KEY`; var ys2 = Object.defineProperty; var ws = Object.defineProperties; var ms = Object.getOwnPropertyDescriptors; var ut3 = Object.getOwnPropertySymbols; var _s = Object.prototype.hasOwnProperty; var Es = Object.prototype.propertyIsEnumerable; var gt3 = (q3, o4, e2) => o4 in q3 ? ys2(q3, o4, { enumerable: true, configurable: true, writable: true, value: e2 }) : q3[o4] = e2; var I4 = (q3, o4) => { for (var e2 in o4 || (o4 = {})) _s.call(o4, e2) && gt3(q3, e2, o4[e2]); if (ut3) for (var e2 of ut3(o4)) Es.call(o4, e2) && gt3(q3, e2, o4[e2]); return q3; }; var D3 = (q3, o4) => ws(q3, ms(o4)); var Rs2 = class extends M2 { constructor(o4) { super(o4), this.name = nt2, this.events = new import_events8.default(), this.initialized = false, this.requestQueue = { state: x5.idle, queue: [] }, this.sessionRequestQueue = { state: x5.idle, queue: [] }, this.requestQueueDelay = import_time5.ONE_SECOND, this.expectedPairingMethodMap = /* @__PURE__ */ new Map(), this.recentlyDeletedMap = /* @__PURE__ */ new Map(), this.recentlyDeletedLimit = 200, this.relayMessageCache = [], this.init = async () => { this.initialized || (await this.cleanup(), this.registerRelayerEvents(), this.registerExpirerEvents(), this.registerPairingEvents(), await this.registerLinkModeListeners(), this.client.core.pairing.register({ methods: Object.keys(v4) }), this.initialized = true, setTimeout(() => { this.sessionRequestQueue.queue = this.getPendingSessionRequests(), this.processSessionRequestQueue(); }, (0, import_time5.toMiliseconds)(this.requestQueueDelay))); }, this.connect = async (e2) => { this.isInitialized(), await this.confirmOnlineStateOrThrow(); const t = D3(I4({}, e2), { requiredNamespaces: e2.requiredNamespaces || {}, optionalNamespaces: e2.optionalNamespaces || {} }); await this.isValidConnect(t); const { pairingTopic: s3, requiredNamespaces: i4, optionalNamespaces: r4, sessionProperties: n5, relays: a4 } = t; let c5 = s3, h5, p3 = false; try { c5 && (p3 = this.client.core.pairing.pairings.get(c5).active); } catch (E3) { throw this.client.logger.error(`connect() -> pairing.get(${c5}) failed`), E3; } if (!c5 || !p3) { const { topic: E3, uri: S6 } = await this.client.core.pairing.create(); c5 = E3, h5 = S6; } if (!c5) { const { message: E3 } = S("NO_MATCHING_KEY", `connect() pairing topic: ${c5}`); throw new Error(E3); } const d3 = await this.client.core.crypto.generateKeyPair(), l4 = v4.wc_sessionPropose.req.ttl || import_time5.FIVE_MINUTES, w4 = Mt(l4), m2 = I4({ requiredNamespaces: i4, optionalNamespaces: r4, relays: a4 ?? [{ protocol: rt }], proposer: { publicKey: d3, metadata: this.client.metadata }, expiryTimestamp: w4, pairingTopic: c5 }, n5 && { sessionProperties: n5 }), { reject: y6, resolve: _4, done: R2 } = _t(l4, it3); this.events.once(Lt("session_connect"), async ({ error: E3, session: S6 }) => { if (E3) y6(E3); else if (S6) { S6.self.publicKey = d3; const M4 = D3(I4({}, S6), { pairingTopic: m2.pairingTopic, requiredNamespaces: m2.requiredNamespaces, optionalNamespaces: m2.optionalNamespaces, transportType: M3.relay }); await this.client.session.set(S6.topic, M4), await this.setExpiry(S6.topic, S6.expiry), c5 && await this.client.core.pairing.updateMetadata({ topic: c5, metadata: S6.peer.metadata }), this.cleanupDuplicatePairings(M4), _4(M4); } }); const V3 = await this.sendRequest({ topic: c5, method: "wc_sessionPropose", params: m2, throwOnFailedPublish: true }); return await this.setProposal(V3, I4({ id: V3 }, m2)), { uri: h5, approval: R2 }; }, this.pair = async (e2) => { this.isInitialized(), await this.confirmOnlineStateOrThrow(); try { return await this.client.core.pairing.pair(e2); } catch (t) { throw this.client.logger.error("pair() failed"), t; } }, this.approve = async (e2) => { var t, s3, i4; const r4 = this.client.core.eventClient.createEvent({ properties: { topic: (t = e2 == null ? void 0 : e2.id) == null ? void 0 : t.toString(), trace: [Is.session_approve_started] } }); try { this.isInitialized(), await this.confirmOnlineStateOrThrow(); } catch (N11) { throw r4.setError(Ts.no_internet_connection), N11; } try { await this.isValidProposalId(e2 == null ? void 0 : e2.id); } catch (N11) { throw this.client.logger.error(`approve() -> proposal.get(${e2 == null ? void 0 : e2.id}) failed`), r4.setError(Ts.proposal_not_found), N11; } try { await this.isValidApprove(e2); } catch (N11) { throw this.client.logger.error("approve() -> isValidApprove() failed"), r4.setError(Ts.session_approve_namespace_validation_failure), N11; } const { id: n5, relayProtocol: a4, namespaces: c5, sessionProperties: h5, sessionConfig: p3 } = e2, d3 = this.client.proposal.get(n5); this.client.core.eventClient.deleteEvent({ eventId: r4.eventId }); const { pairingTopic: l4, proposer: w4, requiredNamespaces: m2, optionalNamespaces: y6 } = d3; let _4 = (s3 = this.client.core.eventClient) == null ? void 0 : s3.getEvent({ topic: l4 }); _4 || (_4 = (i4 = this.client.core.eventClient) == null ? void 0 : i4.createEvent({ type: Is.session_approve_started, properties: { topic: l4, trace: [Is.session_approve_started, Is.session_namespaces_validation_success] } })); const R2 = await this.client.core.crypto.generateKeyPair(), V3 = w4.publicKey, E3 = await this.client.core.crypto.generateSharedKey(R2, V3), S6 = I4(I4({ relay: { protocol: a4 ?? "irn" }, namespaces: c5, controller: { publicKey: R2, metadata: this.client.metadata }, expiry: Mt(z5) }, h5 && { sessionProperties: h5 }), p3 && { sessionConfig: p3 }), M4 = M3.relay; _4.addTrace(Is.subscribing_session_topic); try { await this.client.core.relayer.subscribe(E3, { transportType: M4 }); } catch (N11) { throw _4.setError(Ts.subscribe_session_topic_failure), N11; } _4.addTrace(Is.subscribe_session_topic_success); const W3 = D3(I4({}, S6), { topic: E3, requiredNamespaces: m2, optionalNamespaces: y6, pairingTopic: l4, acknowledged: false, self: S6.controller, peer: { publicKey: w4.publicKey, metadata: w4.metadata }, controller: R2, transportType: M3.relay }); await this.client.session.set(E3, W3), _4.addTrace(Is.store_session); try { _4.addTrace(Is.publishing_session_settle), await this.sendRequest({ topic: E3, method: "wc_sessionSettle", params: S6, throwOnFailedPublish: true }).catch((N11) => { throw _4 == null ? void 0 : _4.setError(Ts.session_settle_publish_failure), N11; }), _4.addTrace(Is.session_settle_publish_success), _4.addTrace(Is.publishing_session_approve), await this.sendResult({ id: n5, topic: l4, result: { relay: { protocol: a4 ?? "irn" }, responderPublicKey: R2 }, throwOnFailedPublish: true }).catch((N11) => { throw _4 == null ? void 0 : _4.setError(Ts.session_approve_publish_failure), N11; }), _4.addTrace(Is.session_approve_publish_success); } catch (N11) { throw this.client.logger.error(N11), this.client.session.delete(E3, U("USER_DISCONNECTED")), await this.client.core.relayer.unsubscribe(E3), N11; } return this.client.core.eventClient.deleteEvent({ eventId: _4.eventId }), await this.client.core.pairing.updateMetadata({ topic: l4, metadata: w4.metadata }), await this.client.proposal.delete(n5, U("USER_DISCONNECTED")), await this.client.core.pairing.activate({ topic: l4 }), await this.setExpiry(E3, Mt(z5)), { topic: E3, acknowledged: () => Promise.resolve(this.client.session.get(E3)) }; }, this.reject = async (e2) => { this.isInitialized(), await this.confirmOnlineStateOrThrow(); try { await this.isValidReject(e2); } catch (r4) { throw this.client.logger.error("reject() -> isValidReject() failed"), r4; } const { id: t, reason: s3 } = e2; let i4; try { i4 = this.client.proposal.get(t).pairingTopic; } catch (r4) { throw this.client.logger.error(`reject() -> proposal.get(${t}) failed`), r4; } i4 && (await this.sendError({ id: t, topic: i4, error: s3, rpcOpts: v4.wc_sessionPropose.reject }), await this.client.proposal.delete(t, U("USER_DISCONNECTED"))); }, this.update = async (e2) => { this.isInitialized(), await this.confirmOnlineStateOrThrow(); try { await this.isValidUpdate(e2); } catch (p3) { throw this.client.logger.error("update() -> isValidUpdate() failed"), p3; } const { topic: t, namespaces: s3 } = e2, { done: i4, resolve: r4, reject: n5 } = _t(), a4 = payloadId(), c5 = getBigIntRpcId().toString(), h5 = this.client.session.get(t).namespaces; return this.events.once(Lt("session_update", a4), ({ error: p3 }) => { p3 ? n5(p3) : r4(); }), await this.client.session.update(t, { namespaces: s3 }), await this.sendRequest({ topic: t, method: "wc_sessionUpdate", params: { namespaces: s3 }, throwOnFailedPublish: true, clientRpcId: a4, relayRpcId: c5 }).catch((p3) => { this.client.logger.error(p3), this.client.session.update(t, { namespaces: h5 }), n5(p3); }), { acknowledged: i4 }; }, this.extend = async (e2) => { this.isInitialized(), await this.confirmOnlineStateOrThrow(); try { await this.isValidExtend(e2); } catch (a4) { throw this.client.logger.error("extend() -> isValidExtend() failed"), a4; } const { topic: t } = e2, s3 = payloadId(), { done: i4, resolve: r4, reject: n5 } = _t(); return this.events.once(Lt("session_extend", s3), ({ error: a4 }) => { a4 ? n5(a4) : r4(); }), await this.setExpiry(t, Mt(z5)), this.sendRequest({ topic: t, method: "wc_sessionExtend", params: {}, clientRpcId: s3, throwOnFailedPublish: true }).catch((a4) => { n5(a4); }), { acknowledged: i4 }; }, this.request = async (e2) => { this.isInitialized(); try { await this.isValidRequest(e2); } catch (w4) { throw this.client.logger.error("request() -> isValidRequest() failed"), w4; } const { chainId: t, request: s3, topic: i4, expiry: r4 = v4.wc_sessionRequest.req.ttl } = e2, n5 = this.client.session.get(i4); (n5 == null ? void 0 : n5.transportType) === M3.relay && await this.confirmOnlineStateOrThrow(); const a4 = payloadId(), c5 = getBigIntRpcId().toString(), { done: h5, resolve: p3, reject: d3 } = _t(r4, "Request expired. Please try again."); this.events.once(Lt("session_request", a4), ({ error: w4, result: m2 }) => { w4 ? d3(w4) : p3(m2); }); const l4 = this.getAppLinkIfEnabled(n5.peer.metadata, n5.transportType); return l4 ? (await this.sendRequest({ clientRpcId: a4, relayRpcId: c5, topic: i4, method: "wc_sessionRequest", params: { request: D3(I4({}, s3), { expiryTimestamp: Mt(r4) }), chainId: t }, expiry: r4, throwOnFailedPublish: true, appLink: l4 }).catch((w4) => d3(w4)), this.client.events.emit("session_request_sent", { topic: i4, request: s3, chainId: t, id: a4 }), await h5()) : await Promise.all([new Promise(async (w4) => { await this.sendRequest({ clientRpcId: a4, relayRpcId: c5, topic: i4, method: "wc_sessionRequest", params: { request: D3(I4({}, s3), { expiryTimestamp: Mt(r4) }), chainId: t }, expiry: r4, throwOnFailedPublish: true }).catch((m2) => d3(m2)), this.client.events.emit("session_request_sent", { topic: i4, request: s3, chainId: t, id: a4 }), w4(); }), new Promise(async (w4) => { var m2; if (!((m2 = n5.sessionConfig) != null && m2.disableDeepLink)) { const y6 = await qt(this.client.core.storage, xe); await Ft({ id: a4, topic: i4, wcDeepLink: y6 }); } w4(); }), h5()]).then((w4) => w4[2]); }, this.respond = async (e2) => { this.isInitialized(), await this.isValidRespond(e2); const { topic: t, response: s3 } = e2, { id: i4 } = s3, r4 = this.client.session.get(t); r4.transportType === M3.relay && await this.confirmOnlineStateOrThrow(); const n5 = this.getAppLinkIfEnabled(r4.peer.metadata, r4.transportType); isJsonRpcResult(s3) ? await this.sendResult({ id: i4, topic: t, result: s3.result, throwOnFailedPublish: true, appLink: n5 }) : isJsonRpcError(s3) && await this.sendError({ id: i4, topic: t, error: s3.error, appLink: n5 }), this.cleanupAfterResponse(e2); }, this.ping = async (e2) => { this.isInitialized(), await this.confirmOnlineStateOrThrow(); try { await this.isValidPing(e2); } catch (s3) { throw this.client.logger.error("ping() -> isValidPing() failed"), s3; } const { topic: t } = e2; if (this.client.session.keys.includes(t)) { const s3 = payloadId(), i4 = getBigIntRpcId().toString(), { done: r4, resolve: n5, reject: a4 } = _t(); this.events.once(Lt("session_ping", s3), ({ error: c5 }) => { c5 ? a4(c5) : n5(); }), await Promise.all([this.sendRequest({ topic: t, method: "wc_sessionPing", params: {}, throwOnFailedPublish: true, clientRpcId: s3, relayRpcId: i4 }), r4()]); } else this.client.core.pairing.pairings.keys.includes(t) && await this.client.core.pairing.ping({ topic: t }); }, this.emit = async (e2) => { this.isInitialized(), await this.confirmOnlineStateOrThrow(), await this.isValidEmit(e2); const { topic: t, event: s3, chainId: i4 } = e2, r4 = getBigIntRpcId().toString(); await this.sendRequest({ topic: t, method: "wc_sessionEvent", params: { event: s3, chainId: i4 }, throwOnFailedPublish: true, relayRpcId: r4 }); }, this.disconnect = async (e2) => { this.isInitialized(), await this.confirmOnlineStateOrThrow(), await this.isValidDisconnect(e2); const { topic: t } = e2; if (this.client.session.keys.includes(t)) await this.sendRequest({ topic: t, method: "wc_sessionDelete", params: U("USER_DISCONNECTED"), throwOnFailedPublish: true }), await this.deleteSession({ topic: t, emitEvent: false }); else if (this.client.core.pairing.pairings.keys.includes(t)) await this.client.core.pairing.disconnect({ topic: t }); else { const { message: s3 } = S("MISMATCHED_TOPIC", `Session or pairing topic not found: ${t}`); throw new Error(s3); } }, this.find = (e2) => (this.isInitialized(), this.client.session.getAll().filter((t) => zr(t, e2))), this.getPendingSessionRequests = () => this.client.pendingRequest.getAll(), this.authenticate = async (e2, t) => { var s3; this.isInitialized(), this.isValidAuthenticate(e2); const i4 = t && this.client.core.linkModeSupportedApps.includes(t) && ((s3 = this.client.metadata.redirect) == null ? void 0 : s3.linkMode), r4 = i4 ? M3.link_mode : M3.relay; r4 === M3.relay && await this.confirmOnlineStateOrThrow(); const { chains: n5, statement: a4 = "", uri: c5, domain: h5, nonce: p3, type: d3, exp: l4, nbf: w4, methods: m2 = [], expiry: y6 } = e2, _4 = [...e2.resources || []], { topic: R2, uri: V3 } = await this.client.core.pairing.create({ methods: ["wc_sessionAuthenticate"], transportType: r4 }); this.client.logger.info({ message: "Generated new pairing", pairing: { topic: R2, uri: V3 } }); const E3 = await this.client.core.crypto.generateKeyPair(), S6 = hr(E3); if (await Promise.all([this.client.auth.authKeys.set(ae3, { responseTopic: S6, publicKey: E3 }), this.client.auth.pairingTopics.set(S6, { topic: S6, pairingTopic: R2 })]), await this.client.core.relayer.subscribe(S6, { transportType: r4 }), this.client.logger.info(`sending request to new pairing topic: ${R2}`), m2.length > 0) { const { namespace: O5 } = re(n5[0]); let T2 = ir(O5, "request", m2); Y(_4) && (T2 = cr(T2, _4.pop())), _4.push(T2); } const M4 = y6 && y6 > v4.wc_sessionAuthenticate.req.ttl ? y6 : v4.wc_sessionAuthenticate.req.ttl, W3 = { authPayload: { type: d3 ?? "caip122", chains: n5, statement: a4, aud: c5, domain: h5, version: "1", nonce: p3, iat: (/* @__PURE__ */ new Date()).toISOString(), exp: l4, nbf: w4, resources: _4 }, requester: { publicKey: E3, metadata: this.client.metadata }, expiryTimestamp: Mt(M4) }, N11 = { eip155: { chains: n5, methods: [.../* @__PURE__ */ new Set(["personal_sign", ...m2])], events: ["chainChanged", "accountsChanged"] } }, De2 = { requiredNamespaces: {}, optionalNamespaces: N11, relays: [{ protocol: "irn" }], pairingTopic: R2, proposer: { publicKey: E3, metadata: this.client.metadata }, expiryTimestamp: Mt(v4.wc_sessionPropose.req.ttl) }, { done: wt2, resolve: Ve, reject: Ee3 } = _t(M4, "Request expired"), ce2 = async ({ error: O5, session: T2 }) => { if (this.events.off(Lt("session_request", G2), Re2), O5) Ee3(O5); else if (T2) { T2.self.publicKey = E3, await this.client.session.set(T2.topic, T2), await this.setExpiry(T2.topic, T2.expiry), R2 && await this.client.core.pairing.updateMetadata({ topic: R2, metadata: T2.peer.metadata }); const le2 = this.client.session.get(T2.topic); await this.deleteProposal(Z3), Ve({ session: le2 }); } }, Re2 = async (O5) => { var T2, le2, Me; if (await this.deletePendingAuthRequest(G2, { message: "fulfilled", code: 0 }), O5.error) { const te = U("WC_METHOD_UNSUPPORTED", "wc_sessionAuthenticate"); return O5.error.code === te.code ? void 0 : (this.events.off(Lt("session_connect"), ce2), Ee3(O5.error.message)); } await this.deleteProposal(Z3), this.events.off(Lt("session_connect"), ce2); const { cacaos: ke, responder: j2 } = O5.result, Ie2 = [], $e2 = []; for (const te of ke) { await nr({ cacao: te, projectId: this.client.core.projectId }) || (this.client.logger.error(te, "Signature verification failed"), Ee3(U("SESSION_SETTLEMENT_FAILED", "Signature verification failed"))); const { p: fe3 } = te, ve3 = Y(fe3.resources), Ke2 = [ln(fe3.iss)], mt3 = fe(fe3.iss); if (ve3) { const qe2 = ar(ve3), _t3 = ur(ve3); Ie2.push(...qe2), Ke2.push(..._t3); } for (const qe2 of Ke2) $e2.push(`${qe2}:${mt3}`); } const ee3 = await this.client.core.crypto.generateSharedKey(E3, j2.publicKey); let pe2; Ie2.length > 0 && (pe2 = { topic: ee3, acknowledged: true, self: { publicKey: E3, metadata: this.client.metadata }, peer: j2, controller: j2.publicKey, expiry: Mt(z5), requiredNamespaces: {}, optionalNamespaces: {}, relay: { protocol: "irn" }, pairingTopic: R2, namespaces: Jr([...new Set(Ie2)], [...new Set($e2)]), transportType: r4 }, await this.client.core.relayer.subscribe(ee3, { transportType: r4 }), await this.client.session.set(ee3, pe2), R2 && await this.client.core.pairing.updateMetadata({ topic: R2, metadata: j2.metadata }), pe2 = this.client.session.get(ee3)), (T2 = this.client.metadata.redirect) != null && T2.linkMode && (le2 = j2.metadata.redirect) != null && le2.linkMode && (Me = j2.metadata.redirect) != null && Me.universal && t && (this.client.core.addLinkModeSupportedApp(j2.metadata.redirect.universal), this.client.session.update(ee3, { transportType: M3.link_mode })), Ve({ auths: ke, session: pe2 }); }, G2 = payloadId(), Z3 = payloadId(); this.events.once(Lt("session_connect"), ce2), this.events.once(Lt("session_request", G2), Re2); let Se2; try { if (i4) { const O5 = formatJsonRpcRequest("wc_sessionAuthenticate", W3, G2); this.client.core.history.set(R2, O5); const T2 = await this.client.core.crypto.encode("", O5, { type: M, encoding: lr }); Se2 = xr(t, R2, T2); } else await Promise.all([this.sendRequest({ topic: R2, method: "wc_sessionAuthenticate", params: W3, expiry: e2.expiry, throwOnFailedPublish: true, clientRpcId: G2 }), this.sendRequest({ topic: R2, method: "wc_sessionPropose", params: De2, expiry: v4.wc_sessionPropose.req.ttl, throwOnFailedPublish: true, clientRpcId: Z3 })]); } catch (O5) { throw this.events.off(Lt("session_connect"), ce2), this.events.off(Lt("session_request", G2), Re2), O5; } return await this.setProposal(Z3, I4({ id: Z3 }, De2)), await this.setAuthRequest(G2, { request: D3(I4({}, W3), { verifyContext: {} }), pairingTopic: R2, transportType: r4 }), { uri: Se2 ?? V3, response: wt2 }; }, this.approveSessionAuthenticate = async (e2) => { const { id: t, auths: s3 } = e2, i4 = this.client.core.eventClient.createEvent({ properties: { topic: t.toString(), trace: [Cs.authenticated_session_approve_started] } }); try { this.isInitialized(); } catch (y6) { throw i4.setError(Ps.no_internet_connection), y6; } const r4 = this.getPendingAuthRequest(t); if (!r4) throw i4.setError(Ps.authenticated_session_pending_request_not_found), new Error(`Could not find pending auth request with id ${t}`); const n5 = r4.transportType || M3.relay; n5 === M3.relay && await this.confirmOnlineStateOrThrow(); const a4 = r4.requester.publicKey, c5 = await this.client.core.crypto.generateKeyPair(), h5 = hr(a4), p3 = { type: D, receiverPublicKey: a4, senderPublicKey: c5 }, d3 = [], l4 = []; for (const y6 of s3) { if (!await nr({ cacao: y6, projectId: this.client.core.projectId })) { i4.setError(Ps.invalid_cacao); const S6 = U("SESSION_SETTLEMENT_FAILED", "Signature verification failed"); throw await this.sendError({ id: t, topic: h5, error: S6, encodeOpts: p3 }), new Error(S6.message); } i4.addTrace(Cs.cacaos_verified); const { p: _4 } = y6, R2 = Y(_4.resources), V3 = [ln(_4.iss)], E3 = fe(_4.iss); if (R2) { const S6 = ar(R2), M4 = ur(R2); d3.push(...S6), V3.push(...M4); } for (const S6 of V3) l4.push(`${S6}:${E3}`); } const w4 = await this.client.core.crypto.generateSharedKey(c5, a4); i4.addTrace(Cs.create_authenticated_session_topic); let m2; if ((d3 == null ? void 0 : d3.length) > 0) { m2 = { topic: w4, acknowledged: true, self: { publicKey: c5, metadata: this.client.metadata }, peer: { publicKey: a4, metadata: r4.requester.metadata }, controller: a4, expiry: Mt(z5), authentication: s3, requiredNamespaces: {}, optionalNamespaces: {}, relay: { protocol: "irn" }, pairingTopic: r4.pairingTopic, namespaces: Jr([...new Set(d3)], [...new Set(l4)]), transportType: n5 }, i4.addTrace(Cs.subscribing_authenticated_session_topic); try { await this.client.core.relayer.subscribe(w4, { transportType: n5 }); } catch (y6) { throw i4.setError(Ps.subscribe_authenticated_session_topic_failure), y6; } i4.addTrace(Cs.subscribe_authenticated_session_topic_success), await this.client.session.set(w4, m2), i4.addTrace(Cs.store_authenticated_session), await this.client.core.pairing.updateMetadata({ topic: r4.pairingTopic, metadata: r4.requester.metadata }); } i4.addTrace(Cs.publishing_authenticated_session_approve); try { await this.sendResult({ topic: h5, id: t, result: { cacaos: s3, responder: { publicKey: c5, metadata: this.client.metadata } }, encodeOpts: p3, throwOnFailedPublish: true, appLink: this.getAppLinkIfEnabled(r4.requester.metadata, n5) }); } catch (y6) { throw i4.setError(Ps.authenticated_session_approve_publish_failure), y6; } return await this.client.auth.requests.delete(t, { message: "fulfilled", code: 0 }), await this.client.core.pairing.activate({ topic: r4.pairingTopic }), this.client.core.eventClient.deleteEvent({ eventId: i4.eventId }), { session: m2 }; }, this.rejectSessionAuthenticate = async (e2) => { this.isInitialized(); const { id: t, reason: s3 } = e2, i4 = this.getPendingAuthRequest(t); if (!i4) throw new Error(`Could not find pending auth request with id ${t}`); i4.transportType === M3.relay && await this.confirmOnlineStateOrThrow(); const r4 = i4.requester.publicKey, n5 = await this.client.core.crypto.generateKeyPair(), a4 = hr(r4), c5 = { type: D, receiverPublicKey: r4, senderPublicKey: n5 }; await this.sendError({ id: t, topic: a4, error: s3, encodeOpts: c5, rpcOpts: v4.wc_sessionAuthenticate.reject, appLink: this.getAppLinkIfEnabled(i4.requester.metadata, i4.transportType) }), await this.client.auth.requests.delete(t, { message: "rejected", code: 0 }), await this.client.proposal.delete(t, U("USER_DISCONNECTED")); }, this.formatAuthMessage = (e2) => { this.isInitialized(); const { request: t, iss: s3 } = e2; return dn(t, s3); }, this.processRelayMessageCache = () => { setTimeout(async () => { if (this.relayMessageCache.length !== 0) for (; this.relayMessageCache.length > 0; ) try { const e2 = this.relayMessageCache.shift(); e2 && await this.onRelayMessage(e2); } catch (e2) { this.client.logger.error(e2); } }, 50); }, this.cleanupDuplicatePairings = async (e2) => { if (e2.pairingTopic) try { const t = this.client.core.pairing.pairings.get(e2.pairingTopic), s3 = this.client.core.pairing.pairings.getAll().filter((i4) => { var r4, n5; return ((r4 = i4.peerMetadata) == null ? void 0 : r4.url) && ((n5 = i4.peerMetadata) == null ? void 0 : n5.url) === e2.peer.metadata.url && i4.topic && i4.topic !== t.topic; }); if (s3.length === 0) return; this.client.logger.info(`Cleaning up ${s3.length} duplicate pairing(s)`), await Promise.all(s3.map((i4) => this.client.core.pairing.disconnect({ topic: i4.topic }))), this.client.logger.info("Duplicate pairings clean up finished"); } catch (t) { this.client.logger.error(t); } }, this.deleteSession = async (e2) => { var t; const { topic: s3, expirerHasDeleted: i4 = false, emitEvent: r4 = true, id: n5 = 0 } = e2, { self: a4 } = this.client.session.get(s3); await this.client.core.relayer.unsubscribe(s3), await this.client.session.delete(s3, U("USER_DISCONNECTED")), this.addToRecentlyDeleted(s3, "session"), this.client.core.crypto.keychain.has(a4.publicKey) && await this.client.core.crypto.deleteKeyPair(a4.publicKey), this.client.core.crypto.keychain.has(s3) && await this.client.core.crypto.deleteSymKey(s3), i4 || this.client.core.expirer.del(s3), this.client.core.storage.removeItem(xe).catch((c5) => this.client.logger.warn(c5)), this.getPendingSessionRequests().forEach((c5) => { c5.topic === s3 && this.deletePendingSessionRequest(c5.id, U("USER_DISCONNECTED")); }), s3 === ((t = this.sessionRequestQueue.queue[0]) == null ? void 0 : t.topic) && (this.sessionRequestQueue.state = x5.idle), r4 && this.client.events.emit("session_delete", { id: n5, topic: s3 }); }, this.deleteProposal = async (e2, t) => { if (t) try { const s3 = this.client.proposal.get(e2), i4 = this.client.core.eventClient.getEvent({ topic: s3.pairingTopic }); i4 == null ? void 0 : i4.setError(Ts.proposal_expired); } catch { } await Promise.all([this.client.proposal.delete(e2, U("USER_DISCONNECTED")), t ? Promise.resolve() : this.client.core.expirer.del(e2)]), this.addToRecentlyDeleted(e2, "proposal"); }, this.deletePendingSessionRequest = async (e2, t, s3 = false) => { await Promise.all([this.client.pendingRequest.delete(e2, t), s3 ? Promise.resolve() : this.client.core.expirer.del(e2)]), this.addToRecentlyDeleted(e2, "request"), this.sessionRequestQueue.queue = this.sessionRequestQueue.queue.filter((i4) => i4.id !== e2), s3 && (this.sessionRequestQueue.state = x5.idle, this.client.events.emit("session_request_expire", { id: e2 })); }, this.deletePendingAuthRequest = async (e2, t, s3 = false) => { await Promise.all([this.client.auth.requests.delete(e2, t), s3 ? Promise.resolve() : this.client.core.expirer.del(e2)]); }, this.setExpiry = async (e2, t) => { this.client.session.keys.includes(e2) && (this.client.core.expirer.set(e2, t), await this.client.session.update(e2, { expiry: t })); }, this.setProposal = async (e2, t) => { this.client.core.expirer.set(e2, Mt(v4.wc_sessionPropose.req.ttl)), await this.client.proposal.set(e2, t); }, this.setAuthRequest = async (e2, t) => { const { request: s3, pairingTopic: i4, transportType: r4 = M3.relay } = t; this.client.core.expirer.set(e2, s3.expiryTimestamp), await this.client.auth.requests.set(e2, { authPayload: s3.authPayload, requester: s3.requester, expiryTimestamp: s3.expiryTimestamp, id: e2, pairingTopic: i4, verifyContext: s3.verifyContext, transportType: r4 }); }, this.setPendingSessionRequest = async (e2) => { const { id: t, topic: s3, params: i4, verifyContext: r4 } = e2, n5 = i4.request.expiryTimestamp || Mt(v4.wc_sessionRequest.req.ttl); this.client.core.expirer.set(t, n5), await this.client.pendingRequest.set(t, { id: t, topic: s3, params: i4, verifyContext: r4 }); }, this.sendRequest = async (e2) => { const { topic: t, method: s3, params: i4, expiry: r4, relayRpcId: n5, clientRpcId: a4, throwOnFailedPublish: c5, appLink: h5 } = e2, p3 = formatJsonRpcRequest(s3, i4, a4); let d3; const l4 = !!h5; try { const y6 = l4 ? lr : ge; d3 = await this.client.core.crypto.encode(t, p3, { encoding: y6 }); } catch (y6) { throw await this.cleanup(), this.client.logger.error(`sendRequest() -> core.crypto.encode() for topic ${t} failed`), y6; } let w4; if (at3.includes(s3)) { const y6 = yr(JSON.stringify(p3)), _4 = yr(d3); w4 = await this.client.core.verify.register({ id: _4, decryptedId: y6 }); } const m2 = v4[s3].req; if (m2.attestation = w4, r4 && (m2.ttl = r4), n5 && (m2.id = n5), this.client.core.history.set(t, p3), l4) { const y6 = xr(h5, t, d3); await global.Linking.openURL(y6, this.client.name); } else { const y6 = v4[s3].req; r4 && (y6.ttl = r4), n5 && (y6.id = n5), c5 ? (y6.internal = D3(I4({}, y6.internal), { throwOnFailedPublish: true }), await this.client.core.relayer.publish(t, d3, y6)) : this.client.core.relayer.publish(t, d3, y6).catch((_4) => this.client.logger.error(_4)); } return p3.id; }, this.sendResult = async (e2) => { const { id: t, topic: s3, result: i4, throwOnFailedPublish: r4, encodeOpts: n5, appLink: a4 } = e2, c5 = formatJsonRpcResult(t, i4); let h5; const p3 = a4 && typeof (global == null ? void 0 : global.Linking) < "u"; try { const l4 = p3 ? lr : ge; h5 = await this.client.core.crypto.encode(s3, c5, D3(I4({}, n5 || {}), { encoding: l4 })); } catch (l4) { throw await this.cleanup(), this.client.logger.error(`sendResult() -> core.crypto.encode() for topic ${s3} failed`), l4; } let d3; try { d3 = await this.client.core.history.get(s3, t); } catch (l4) { throw this.client.logger.error(`sendResult() -> history.get(${s3}, ${t}) failed`), l4; } if (p3) { const l4 = xr(a4, s3, h5); await global.Linking.openURL(l4, this.client.name); } else { const l4 = v4[d3.request.method].res; r4 ? (l4.internal = D3(I4({}, l4.internal), { throwOnFailedPublish: true }), await this.client.core.relayer.publish(s3, h5, l4)) : this.client.core.relayer.publish(s3, h5, l4).catch((w4) => this.client.logger.error(w4)); } await this.client.core.history.resolve(c5); }, this.sendError = async (e2) => { const { id: t, topic: s3, error: i4, encodeOpts: r4, rpcOpts: n5, appLink: a4 } = e2, c5 = formatJsonRpcError(t, i4); let h5; const p3 = a4 && typeof (global == null ? void 0 : global.Linking) < "u"; try { const l4 = p3 ? lr : ge; h5 = await this.client.core.crypto.encode(s3, c5, D3(I4({}, r4 || {}), { encoding: l4 })); } catch (l4) { throw await this.cleanup(), this.client.logger.error(`sendError() -> core.crypto.encode() for topic ${s3} failed`), l4; } let d3; try { d3 = await this.client.core.history.get(s3, t); } catch (l4) { throw this.client.logger.error(`sendError() -> history.get(${s3}, ${t}) failed`), l4; } if (p3) { const l4 = xr(a4, s3, h5); await global.Linking.openURL(l4, this.client.name); } else { const l4 = n5 || v4[d3.request.method].res; this.client.core.relayer.publish(s3, h5, l4); } await this.client.core.history.resolve(c5); }, this.cleanup = async () => { const e2 = [], t = []; this.client.session.getAll().forEach((s3) => { let i4 = false; Kt(s3.expiry) && (i4 = true), this.client.core.crypto.keychain.has(s3.topic) || (i4 = true), i4 && e2.push(s3.topic); }), this.client.proposal.getAll().forEach((s3) => { Kt(s3.expiryTimestamp) && t.push(s3.id); }), await Promise.all([...e2.map((s3) => this.deleteSession({ topic: s3 })), ...t.map((s3) => this.deleteProposal(s3))]); }, this.onRelayEventRequest = async (e2) => { this.requestQueue.queue.push(e2), await this.processRequestsQueue(); }, this.processRequestsQueue = async () => { if (this.requestQueue.state === x5.active) { this.client.logger.info("Request queue already active, skipping..."); return; } for (this.client.logger.info(`Request queue starting with ${this.requestQueue.queue.length} requests`); this.requestQueue.queue.length > 0; ) { this.requestQueue.state = x5.active; const e2 = this.requestQueue.queue.shift(); if (e2) try { await this.processRequest(e2); } catch (t) { this.client.logger.warn(t); } } this.requestQueue.state = x5.idle; }, this.processRequest = async (e2) => { const { topic: t, payload: s3, attestation: i4, transportType: r4, encryptedId: n5 } = e2, a4 = s3.method; if (!this.shouldIgnorePairingRequest({ topic: t, requestMethod: a4 })) switch (a4) { case "wc_sessionPropose": return await this.onSessionProposeRequest({ topic: t, payload: s3, attestation: i4, encryptedId: n5 }); case "wc_sessionSettle": return await this.onSessionSettleRequest(t, s3); case "wc_sessionUpdate": return await this.onSessionUpdateRequest(t, s3); case "wc_sessionExtend": return await this.onSessionExtendRequest(t, s3); case "wc_sessionPing": return await this.onSessionPingRequest(t, s3); case "wc_sessionDelete": return await this.onSessionDeleteRequest(t, s3); case "wc_sessionRequest": return await this.onSessionRequest({ topic: t, payload: s3, attestation: i4, encryptedId: n5, transportType: r4 }); case "wc_sessionEvent": return await this.onSessionEventRequest(t, s3); case "wc_sessionAuthenticate": return await this.onSessionAuthenticateRequest({ topic: t, payload: s3, attestation: i4, encryptedId: n5, transportType: r4 }); default: return this.client.logger.info(`Unsupported request method ${a4}`); } }, this.onRelayEventResponse = async (e2) => { const { topic: t, payload: s3, transportType: i4 } = e2, r4 = (await this.client.core.history.get(t, s3.id)).request.method; switch (r4) { case "wc_sessionPropose": return this.onSessionProposeResponse(t, s3, i4); case "wc_sessionSettle": return this.onSessionSettleResponse(t, s3); case "wc_sessionUpdate": return this.onSessionUpdateResponse(t, s3); case "wc_sessionExtend": return this.onSessionExtendResponse(t, s3); case "wc_sessionPing": return this.onSessionPingResponse(t, s3); case "wc_sessionRequest": return this.onSessionRequestResponse(t, s3); case "wc_sessionAuthenticate": return this.onSessionAuthenticateResponse(t, s3); default: return this.client.logger.info(`Unsupported response method ${r4}`); } }, this.onRelayEventUnknownPayload = (e2) => { const { topic: t } = e2, { message: s3 } = S("MISSING_OR_INVALID", `Decoded payload on topic ${t} is not identifiable as a JSON-RPC request or a response.`); throw new Error(s3); }, this.shouldIgnorePairingRequest = (e2) => { const { topic: t, requestMethod: s3 } = e2, i4 = this.expectedPairingMethodMap.get(t); return !i4 || i4.includes(s3) ? false : !!(i4.includes("wc_sessionAuthenticate") && this.client.events.listenerCount("session_authenticate") > 0); }, this.onSessionProposeRequest = async (e2) => { const { topic: t, payload: s3, attestation: i4, encryptedId: r4 } = e2, { params: n5, id: a4 } = s3; try { const c5 = this.client.core.eventClient.getEvent({ topic: t }); this.isValidConnect(I4({}, s3.params)); const h5 = n5.expiryTimestamp || Mt(v4.wc_sessionPropose.req.ttl), p3 = I4({ id: a4, pairingTopic: t, expiryTimestamp: h5 }, n5); await this.setProposal(a4, p3); const d3 = await this.getVerifyContext({ attestationId: i4, hash: yr(JSON.stringify(s3)), encryptedId: r4, metadata: p3.proposer.metadata }); this.client.events.listenerCount("session_proposal") === 0 && (console.warn("No listener for session_proposal event"), c5 == null ? void 0 : c5.setError($2.proposal_listener_not_found)), c5 == null ? void 0 : c5.addTrace(z4.emit_session_proposal), this.client.events.emit("session_proposal", { id: a4, params: p3, verifyContext: d3 }); } catch (c5) { await this.sendError({ id: a4, topic: t, error: c5, rpcOpts: v4.wc_sessionPropose.autoReject }), this.client.logger.error(c5); } }, this.onSessionProposeResponse = async (e2, t, s3) => { const { id: i4 } = t; if (isJsonRpcResult(t)) { const { result: r4 } = t; this.client.logger.trace({ type: "method", method: "onSessionProposeResponse", result: r4 }); const n5 = this.client.proposal.get(i4); this.client.logger.trace({ type: "method", method: "onSessionProposeResponse", proposal: n5 }); const a4 = n5.proposer.publicKey; this.client.logger.trace({ type: "method", method: "onSessionProposeResponse", selfPublicKey: a4 }); const c5 = r4.responderPublicKey; this.client.logger.trace({ type: "method", method: "onSessionProposeResponse", peerPublicKey: c5 }); const h5 = await this.client.core.crypto.generateSharedKey(a4, c5); this.client.logger.trace({ type: "method", method: "onSessionProposeResponse", sessionTopic: h5 }); const p3 = await this.client.core.relayer.subscribe(h5, { transportType: s3 }); this.client.logger.trace({ type: "method", method: "onSessionProposeResponse", subscriptionId: p3 }), await this.client.core.pairing.activate({ topic: e2 }); } else if (isJsonRpcError(t)) { await this.client.proposal.delete(i4, U("USER_DISCONNECTED")); const r4 = Lt("session_connect"); if (this.events.listenerCount(r4) === 0) throw new Error(`emitting ${r4} without any listeners, 954`); this.events.emit(Lt("session_connect"), { error: t.error }); } }, this.onSessionSettleRequest = async (e2, t) => { const { id: s3, params: i4 } = t; try { this.isValidSessionSettleRequest(i4); const { relay: r4, controller: n5, expiry: a4, namespaces: c5, sessionProperties: h5, sessionConfig: p3 } = t.params, d3 = D3(I4(I4({ topic: e2, relay: r4, expiry: a4, namespaces: c5, acknowledged: true, pairingTopic: "", requiredNamespaces: {}, optionalNamespaces: {}, controller: n5.publicKey, self: { publicKey: "", metadata: this.client.metadata }, peer: { publicKey: n5.publicKey, metadata: n5.metadata } }, h5 && { sessionProperties: h5 }), p3 && { sessionConfig: p3 }), { transportType: M3.relay }), l4 = Lt("session_connect"); if (this.events.listenerCount(l4) === 0) throw new Error(`emitting ${l4} without any listeners 997`); this.events.emit(Lt("session_connect"), { session: d3 }), await this.sendResult({ id: t.id, topic: e2, result: true, throwOnFailedPublish: true }); } catch (r4) { await this.sendError({ id: s3, topic: e2, error: r4 }), this.client.logger.error(r4); } }, this.onSessionSettleResponse = async (e2, t) => { const { id: s3 } = t; isJsonRpcResult(t) ? (await this.client.session.update(e2, { acknowledged: true }), this.events.emit(Lt("session_approve", s3), {})) : isJsonRpcError(t) && (await this.client.session.delete(e2, U("USER_DISCONNECTED")), this.events.emit(Lt("session_approve", s3), { error: t.error })); }, this.onSessionUpdateRequest = async (e2, t) => { const { params: s3, id: i4 } = t; try { const r4 = `${e2}_session_update`, n5 = yo.get(r4); if (n5 && this.isRequestOutOfSync(n5, i4)) { this.client.logger.info(`Discarding out of sync request - ${i4}`), this.sendError({ id: i4, topic: e2, error: U("INVALID_UPDATE_REQUEST") }); return; } this.isValidUpdate(I4({ topic: e2 }, s3)); try { yo.set(r4, i4), await this.client.session.update(e2, { namespaces: s3.namespaces }), await this.sendResult({ id: i4, topic: e2, result: true, throwOnFailedPublish: true }); } catch (a4) { throw yo.delete(r4), a4; } this.client.events.emit("session_update", { id: i4, topic: e2, params: s3 }); } catch (r4) { await this.sendError({ id: i4, topic: e2, error: r4 }), this.client.logger.error(r4); } }, this.isRequestOutOfSync = (e2, t) => parseInt(t.toString().slice(0, -3)) <= parseInt(e2.toString().slice(0, -3)), this.onSessionUpdateResponse = (e2, t) => { const { id: s3 } = t, i4 = Lt("session_update", s3); if (this.events.listenerCount(i4) === 0) throw new Error(`emitting ${i4} without any listeners`); isJsonRpcResult(t) ? this.events.emit(Lt("session_update", s3), {}) : isJsonRpcError(t) && this.events.emit(Lt("session_update", s3), { error: t.error }); }, this.onSessionExtendRequest = async (e2, t) => { const { id: s3 } = t; try { this.isValidExtend({ topic: e2 }), await this.setExpiry(e2, Mt(z5)), await this.sendResult({ id: s3, topic: e2, result: true, throwOnFailedPublish: true }), this.client.events.emit("session_extend", { id: s3, topic: e2 }); } catch (i4) { await this.sendError({ id: s3, topic: e2, error: i4 }), this.client.logger.error(i4); } }, this.onSessionExtendResponse = (e2, t) => { const { id: s3 } = t, i4 = Lt("session_extend", s3); if (this.events.listenerCount(i4) === 0) throw new Error(`emitting ${i4} without any listeners`); isJsonRpcResult(t) ? this.events.emit(Lt("session_extend", s3), {}) : isJsonRpcError(t) && this.events.emit(Lt("session_extend", s3), { error: t.error }); }, this.onSessionPingRequest = async (e2, t) => { const { id: s3 } = t; try { this.isValidPing({ topic: e2 }), await this.sendResult({ id: s3, topic: e2, result: true, throwOnFailedPublish: true }), this.client.events.emit("session_ping", { id: s3, topic: e2 }); } catch (i4) { await this.sendError({ id: s3, topic: e2, error: i4 }), this.client.logger.error(i4); } }, this.onSessionPingResponse = (e2, t) => { const { id: s3 } = t, i4 = Lt("session_ping", s3); if (this.events.listenerCount(i4) === 0) throw new Error(`emitting ${i4} without any listeners`); setTimeout(() => { isJsonRpcResult(t) ? this.events.emit(Lt("session_ping", s3), {}) : isJsonRpcError(t) && this.events.emit(Lt("session_ping", s3), { error: t.error }); }, 500); }, this.onSessionDeleteRequest = async (e2, t) => { const { id: s3 } = t; try { this.isValidDisconnect({ topic: e2, reason: t.params }), Promise.all([new Promise((i4) => { this.client.core.relayer.once(v3.publish, async () => { i4(await this.deleteSession({ topic: e2, id: s3 })); }); }), this.sendResult({ id: s3, topic: e2, result: true, throwOnFailedPublish: true }), this.cleanupPendingSentRequestsForTopic({ topic: e2, error: U("USER_DISCONNECTED") })]).catch((i4) => this.client.logger.error(i4)); } catch (i4) { this.client.logger.error(i4); } }, this.onSessionRequest = async (e2) => { var t, s3, i4; const { topic: r4, payload: n5, attestation: a4, encryptedId: c5, transportType: h5 } = e2, { id: p3, params: d3 } = n5; try { await this.isValidRequest(I4({ topic: r4 }, d3)); const l4 = this.client.session.get(r4), w4 = await this.getVerifyContext({ attestationId: a4, hash: yr(JSON.stringify(formatJsonRpcRequest("wc_sessionRequest", d3, p3))), encryptedId: c5, metadata: l4.peer.metadata, transportType: h5 }), m2 = { id: p3, topic: r4, params: d3, verifyContext: w4 }; await this.setPendingSessionRequest(m2), h5 === M3.link_mode && (t = l4.peer.metadata.redirect) != null && t.universal && this.client.core.addLinkModeSupportedApp((s3 = l4.peer.metadata.redirect) == null ? void 0 : s3.universal), (i4 = this.client.signConfig) != null && i4.disableRequestQueue ? this.emitSessionRequest(m2) : (this.addSessionRequestToSessionRequestQueue(m2), this.processSessionRequestQueue()); } catch (l4) { await this.sendError({ id: p3, topic: r4, error: l4 }), this.client.logger.error(l4); } }, this.onSessionRequestResponse = (e2, t) => { const { id: s3 } = t, i4 = Lt("session_request", s3); if (this.events.listenerCount(i4) === 0) throw new Error(`emitting ${i4} without any listeners`); isJsonRpcResult(t) ? this.events.emit(Lt("session_request", s3), { result: t.result }) : isJsonRpcError(t) && this.events.emit(Lt("session_request", s3), { error: t.error }); }, this.onSessionEventRequest = async (e2, t) => { const { id: s3, params: i4 } = t; try { const r4 = `${e2}_session_event_${i4.event.name}`, n5 = yo.get(r4); if (n5 && this.isRequestOutOfSync(n5, s3)) { this.client.logger.info(`Discarding out of sync request - ${s3}`); return; } this.isValidEmit(I4({ topic: e2 }, i4)), this.client.events.emit("session_event", { id: s3, topic: e2, params: i4 }), yo.set(r4, s3); } catch (r4) { await this.sendError({ id: s3, topic: e2, error: r4 }), this.client.logger.error(r4); } }, this.onSessionAuthenticateResponse = (e2, t) => { const { id: s3 } = t; this.client.logger.trace({ type: "method", method: "onSessionAuthenticateResponse", topic: e2, payload: t }), isJsonRpcResult(t) ? this.events.emit(Lt("session_request", s3), { result: t.result }) : isJsonRpcError(t) && this.events.emit(Lt("session_request", s3), { error: t.error }); }, this.onSessionAuthenticateRequest = async (e2) => { var t; const { topic: s3, payload: i4, attestation: r4, encryptedId: n5, transportType: a4 } = e2; try { const { requester: c5, authPayload: h5, expiryTimestamp: p3 } = i4.params, d3 = await this.getVerifyContext({ attestationId: r4, hash: yr(JSON.stringify(i4)), encryptedId: n5, metadata: c5.metadata, transportType: a4 }), l4 = { requester: c5, pairingTopic: s3, id: i4.id, authPayload: h5, verifyContext: d3, expiryTimestamp: p3 }; await this.setAuthRequest(i4.id, { request: l4, pairingTopic: s3, transportType: a4 }), a4 === M3.link_mode && (t = c5.metadata.redirect) != null && t.universal && this.client.core.addLinkModeSupportedApp(c5.metadata.redirect.universal), this.client.events.emit("session_authenticate", { topic: s3, params: i4.params, id: i4.id, verifyContext: d3 }); } catch (c5) { this.client.logger.error(c5); const h5 = i4.params.requester.publicKey, p3 = await this.client.core.crypto.generateKeyPair(), d3 = this.getAppLinkIfEnabled(i4.params.requester.metadata, a4), l4 = { type: D, receiverPublicKey: h5, senderPublicKey: p3 }; await this.sendError({ id: i4.id, topic: s3, error: c5, encodeOpts: l4, rpcOpts: v4.wc_sessionAuthenticate.autoReject, appLink: d3 }); } }, this.addSessionRequestToSessionRequestQueue = (e2) => { this.sessionRequestQueue.queue.push(e2); }, this.cleanupAfterResponse = (e2) => { this.deletePendingSessionRequest(e2.response.id, { message: "fulfilled", code: 0 }), setTimeout(() => { this.sessionRequestQueue.state = x5.idle, this.processSessionRequestQueue(); }, (0, import_time5.toMiliseconds)(this.requestQueueDelay)); }, this.cleanupPendingSentRequestsForTopic = ({ topic: e2, error: t }) => { const s3 = this.client.core.history.pending; s3.length > 0 && s3.filter((i4) => i4.topic === e2 && i4.request.method === "wc_sessionRequest").forEach((i4) => { const r4 = i4.request.id, n5 = Lt("session_request", r4); if (this.events.listenerCount(n5) === 0) throw new Error(`emitting ${n5} without any listeners`); this.events.emit(Lt("session_request", i4.request.id), { error: t }); }); }, this.processSessionRequestQueue = () => { if (this.sessionRequestQueue.state === x5.active) { this.client.logger.info("session request queue is already active."); return; } const e2 = this.sessionRequestQueue.queue[0]; if (!e2) { this.client.logger.info("session request queue is empty."); return; } try { this.sessionRequestQueue.state = x5.active, this.emitSessionRequest(e2); } catch (t) { this.client.logger.error(t); } }, this.emitSessionRequest = (e2) => { this.client.events.emit("session_request", e2); }, this.onPairingCreated = (e2) => { if (e2.methods && this.expectedPairingMethodMap.set(e2.topic, e2.methods), e2.active) return; const t = this.client.proposal.getAll().find((s3) => s3.pairingTopic === e2.topic); t && this.onSessionProposeRequest({ topic: e2.topic, payload: formatJsonRpcRequest("wc_sessionPropose", { requiredNamespaces: t.requiredNamespaces, optionalNamespaces: t.optionalNamespaces, relays: t.relays, proposer: t.proposer, sessionProperties: t.sessionProperties }, t.id) }); }, this.isValidConnect = async (e2) => { if (!to(e2)) { const { message: a4 } = S("MISSING_OR_INVALID", `connect() params: ${JSON.stringify(e2)}`); throw new Error(a4); } const { pairingTopic: t, requiredNamespaces: s3, optionalNamespaces: i4, sessionProperties: r4, relays: n5 } = e2; if (I(t) || await this.isValidPairingTopic(t), !eo(n5, true)) { const { message: a4 } = S("MISSING_OR_INVALID", `connect() relays: ${n5}`); throw new Error(a4); } !I(s3) && Z(s3) !== 0 && this.validateNamespaces(s3, "requiredNamespaces"), !I(i4) && Z(i4) !== 0 && this.validateNamespaces(i4, "optionalNamespaces"), I(r4) || this.validateSessionProps(r4, "sessionProperties"); }, this.validateNamespaces = (e2, t) => { const s3 = Xr(e2, "connect()", t); if (s3) throw new Error(s3.message); }, this.isValidApprove = async (e2) => { if (!to(e2)) throw new Error(S("MISSING_OR_INVALID", `approve() params: ${e2}`).message); const { id: t, namespaces: s3, relayProtocol: i4, sessionProperties: r4 } = e2; this.checkRecentlyDeleted(t), await this.isValidProposalId(t); const n5 = this.client.proposal.get(t), a4 = Wn(s3, "approve()"); if (a4) throw new Error(a4.message); const c5 = zn(n5.requiredNamespaces, s3, "approve()"); if (c5) throw new Error(c5.message); if (!b(i4, true)) { const { message: h5 } = S("MISSING_OR_INVALID", `approve() relayProtocol: ${i4}`); throw new Error(h5); } I(r4) || this.validateSessionProps(r4, "sessionProperties"); }, this.isValidReject = async (e2) => { if (!to(e2)) { const { message: i4 } = S("MISSING_OR_INVALID", `reject() params: ${e2}`); throw new Error(i4); } const { id: t, reason: s3 } = e2; if (this.checkRecentlyDeleted(t), await this.isValidProposalId(t), !ro(s3)) { const { message: i4 } = S("MISSING_OR_INVALID", `reject() reason: ${JSON.stringify(s3)}`); throw new Error(i4); } }, this.isValidSessionSettleRequest = (e2) => { if (!to(e2)) { const { message: c5 } = S("MISSING_OR_INVALID", `onSessionSettleRequest() params: ${e2}`); throw new Error(c5); } const { relay: t, controller: s3, namespaces: i4, expiry: r4 } = e2; if (!Jn(t)) { const { message: c5 } = S("MISSING_OR_INVALID", "onSessionSettleRequest() relay protocol should be a string"); throw new Error(c5); } const n5 = Zr(s3, "onSessionSettleRequest()"); if (n5) throw new Error(n5.message); const a4 = Wn(i4, "onSessionSettleRequest()"); if (a4) throw new Error(a4.message); if (Kt(r4)) { const { message: c5 } = S("EXPIRED", "onSessionSettleRequest()"); throw new Error(c5); } }, this.isValidUpdate = async (e2) => { if (!to(e2)) { const { message: a4 } = S("MISSING_OR_INVALID", `update() params: ${e2}`); throw new Error(a4); } const { topic: t, namespaces: s3 } = e2; this.checkRecentlyDeleted(t), await this.isValidSessionTopic(t); const i4 = this.client.session.get(t), r4 = Wn(s3, "update()"); if (r4) throw new Error(r4.message); const n5 = zn(i4.requiredNamespaces, s3, "update()"); if (n5) throw new Error(n5.message); }, this.isValidExtend = async (e2) => { if (!to(e2)) { const { message: s3 } = S("MISSING_OR_INVALID", `extend() params: ${e2}`); throw new Error(s3); } const { topic: t } = e2; this.checkRecentlyDeleted(t), await this.isValidSessionTopic(t); }, this.isValidRequest = async (e2) => { if (!to(e2)) { const { message: a4 } = S("MISSING_OR_INVALID", `request() params: ${e2}`); throw new Error(a4); } const { topic: t, request: s3, chainId: i4, expiry: r4 } = e2; this.checkRecentlyDeleted(t), await this.isValidSessionTopic(t); const { namespaces: n5 } = this.client.session.get(t); if (!co(n5, i4)) { const { message: a4 } = S("MISSING_OR_INVALID", `request() chainId: ${i4}`); throw new Error(a4); } if (!oo(s3)) { const { message: a4 } = S("MISSING_OR_INVALID", `request() ${JSON.stringify(s3)}`); throw new Error(a4); } if (!ao(n5, i4, s3.method)) { const { message: a4 } = S("MISSING_OR_INVALID", `request() method: ${s3.method}`); throw new Error(a4); } if (r4 && !po(r4, me3)) { const { message: a4 } = S("MISSING_OR_INVALID", `request() expiry: ${r4}. Expiry must be a number (in seconds) between ${me3.min} and ${me3.max}`); throw new Error(a4); } }, this.isValidRespond = async (e2) => { var t; if (!to(e2)) { const { message: r4 } = S("MISSING_OR_INVALID", `respond() params: ${e2}`); throw new Error(r4); } const { topic: s3, response: i4 } = e2; try { await this.isValidSessionTopic(s3); } catch (r4) { throw (t = e2 == null ? void 0 : e2.response) != null && t.id && this.cleanupAfterResponse(e2), r4; } if (!so(i4)) { const { message: r4 } = S("MISSING_OR_INVALID", `respond() response: ${JSON.stringify(i4)}`); throw new Error(r4); } }, this.isValidPing = async (e2) => { if (!to(e2)) { const { message: s3 } = S("MISSING_OR_INVALID", `ping() params: ${e2}`); throw new Error(s3); } const { topic: t } = e2; await this.isValidSessionOrPairingTopic(t); }, this.isValidEmit = async (e2) => { if (!to(e2)) { const { message: n5 } = S("MISSING_OR_INVALID", `emit() params: ${e2}`); throw new Error(n5); } const { topic: t, event: s3, chainId: i4 } = e2; await this.isValidSessionTopic(t); const { namespaces: r4 } = this.client.session.get(t); if (!co(r4, i4)) { const { message: n5 } = S("MISSING_OR_INVALID", `emit() chainId: ${i4}`); throw new Error(n5); } if (!io(s3)) { const { message: n5 } = S("MISSING_OR_INVALID", `emit() event: ${JSON.stringify(s3)}`); throw new Error(n5); } if (!uo(r4, i4, s3.name)) { const { message: n5 } = S("MISSING_OR_INVALID", `emit() event: ${JSON.stringify(s3)}`); throw new Error(n5); } }, this.isValidDisconnect = async (e2) => { if (!to(e2)) { const { message: s3 } = S("MISSING_OR_INVALID", `disconnect() params: ${e2}`); throw new Error(s3); } const { topic: t } = e2; await this.isValidSessionOrPairingTopic(t); }, this.isValidAuthenticate = (e2) => { const { chains: t, uri: s3, domain: i4, nonce: r4 } = e2; if (!Array.isArray(t) || t.length === 0) throw new Error("chains is required and must be a non-empty array"); if (!b(s3, false)) throw new Error("uri is required parameter"); if (!b(i4, false)) throw new Error("domain is required parameter"); if (!b(r4, false)) throw new Error("nonce is required parameter"); if ([...new Set(t.map((a4) => re(a4).namespace))].length > 1) throw new Error("Multi-namespace requests are not supported. Please request single namespace only."); const { namespace: n5 } = re(t[0]); if (n5 !== "eip155") throw new Error("Only eip155 namespace is supported for authenticated sessions. Please use .connect() for non-eip155 chains."); }, this.getVerifyContext = async (e2) => { const { attestationId: t, hash: s3, encryptedId: i4, metadata: r4, transportType: n5 } = e2, a4 = { verified: { verifyUrl: r4.verifyUrl || J, validation: "UNKNOWN", origin: r4.url || "" } }; try { if (n5 === M3.link_mode) { const h5 = this.getAppLinkIfEnabled(r4, n5); return a4.verified.validation = h5 && new URL(h5).origin === new URL(r4.url).origin ? "VALID" : "INVALID", a4; } const c5 = await this.client.core.verify.resolve({ attestationId: t, hash: s3, encryptedId: i4, verifyUrl: r4.verifyUrl }); c5 && (a4.verified.origin = c5.origin, a4.verified.isScam = c5.isScam, a4.verified.validation = c5.origin === new URL(r4.url).origin ? "VALID" : "INVALID"); } catch (c5) { this.client.logger.warn(c5); } return this.client.logger.debug(`Verify context: ${JSON.stringify(a4)}`), a4; }, this.validateSessionProps = (e2, t) => { Object.values(e2).forEach((s3) => { if (!b(s3, false)) { const { message: i4 } = S("MISSING_OR_INVALID", `${t} must be in Record format. Received: ${JSON.stringify(s3)}`); throw new Error(i4); } }); }, this.getPendingAuthRequest = (e2) => { const t = this.client.auth.requests.get(e2); return typeof t == "object" ? t : void 0; }, this.addToRecentlyDeleted = (e2, t) => { if (this.recentlyDeletedMap.set(e2, t), this.recentlyDeletedMap.size >= this.recentlyDeletedLimit) { let s3 = 0; const i4 = this.recentlyDeletedLimit / 2; for (const r4 of this.recentlyDeletedMap.keys()) { if (s3++ >= i4) break; this.recentlyDeletedMap.delete(r4); } } }, this.checkRecentlyDeleted = (e2) => { const t = this.recentlyDeletedMap.get(e2); if (t) { const { message: s3 } = S("MISSING_OR_INVALID", `Record was recently deleted - ${t}: ${e2}`); throw new Error(s3); } }, this.isLinkModeEnabled = (e2, t) => { var s3, i4, r4, n5, a4, c5, h5, p3, d3; return !e2 || t !== M3.link_mode ? false : ((i4 = (s3 = this.client.metadata) == null ? void 0 : s3.redirect) == null ? void 0 : i4.linkMode) === true && ((n5 = (r4 = this.client.metadata) == null ? void 0 : r4.redirect) == null ? void 0 : n5.universal) !== void 0 && ((c5 = (a4 = this.client.metadata) == null ? void 0 : a4.redirect) == null ? void 0 : c5.universal) !== "" && ((h5 = e2 == null ? void 0 : e2.redirect) == null ? void 0 : h5.universal) !== void 0 && ((p3 = e2 == null ? void 0 : e2.redirect) == null ? void 0 : p3.universal) !== "" && ((d3 = e2 == null ? void 0 : e2.redirect) == null ? void 0 : d3.linkMode) === true && this.client.core.linkModeSupportedApps.includes(e2.redirect.universal) && typeof (global == null ? void 0 : global.Linking) < "u"; }, this.getAppLinkIfEnabled = (e2, t) => { var s3; return this.isLinkModeEnabled(e2, t) ? (s3 = e2 == null ? void 0 : e2.redirect) == null ? void 0 : s3.universal : void 0; }, this.handleLinkModeMessage = ({ url: e2 }) => { if (!e2 || !e2.includes("wc_ev") || !e2.includes("topic")) return; const t = Bt(e2, "topic") || "", s3 = decodeURIComponent(Bt(e2, "wc_ev") || ""), i4 = this.client.session.keys.includes(t); i4 && this.client.session.update(t, { transportType: M3.link_mode }), this.client.core.dispatchEnvelope({ topic: t, message: s3, sessionExists: i4 }); }, this.registerLinkModeListeners = async () => { var e2; if (Wt() || _() && (e2 = this.client.metadata.redirect) != null && e2.linkMode) { const t = global == null ? void 0 : global.Linking; if (typeof t < "u") { t.addEventListener("url", this.handleLinkModeMessage, this.client.name); const s3 = await t.getInitialURL(); s3 && setTimeout(() => { this.handleLinkModeMessage({ url: s3 }); }, 50); } } }; } isInitialized() { if (!this.initialized) { const { message: o4 } = S("NOT_INITIALIZED", this.name); throw new Error(o4); } } async confirmOnlineStateOrThrow() { await this.client.core.relayer.confirmOnlineStateOrThrow(); } registerRelayerEvents() { this.client.core.relayer.on(v3.message, (o4) => { !this.initialized || this.relayMessageCache.length > 0 ? this.relayMessageCache.push(o4) : this.onRelayMessage(o4); }); } async onRelayMessage(o4) { const { topic: e2, message: t, attestation: s3, transportType: i4 } = o4, { publicKey: r4 } = this.client.auth.authKeys.keys.includes(ae3) ? this.client.auth.authKeys.get(ae3) : { responseTopic: void 0, publicKey: void 0 }, n5 = await this.client.core.crypto.decode(e2, t, { receiverPublicKey: r4, encoding: i4 === M3.link_mode ? lr : ge }); try { isJsonRpcRequest(n5) ? (this.client.core.history.set(e2, n5), this.onRelayEventRequest({ topic: e2, payload: n5, attestation: s3, transportType: i4, encryptedId: yr(t) })) : isJsonRpcResponse(n5) ? (await this.client.core.history.resolve(n5), await this.onRelayEventResponse({ topic: e2, payload: n5, transportType: i4 }), this.client.core.history.delete(e2, n5.id)) : this.onRelayEventUnknownPayload({ topic: e2, payload: n5, transportType: i4 }); } catch (a4) { this.client.logger.error(a4); } } registerExpirerEvents() { this.client.core.expirer.on(S5.expired, async (o4) => { const { topic: e2, id: t } = Vt(o4.target); if (t && this.client.pendingRequest.keys.includes(t)) return await this.deletePendingSessionRequest(t, S("EXPIRED"), true); if (t && this.client.auth.requests.keys.includes(t)) return await this.deletePendingAuthRequest(t, S("EXPIRED"), true); e2 ? this.client.session.keys.includes(e2) && (await this.deleteSession({ topic: e2, expirerHasDeleted: true }), this.client.events.emit("session_expire", { topic: e2 })) : t && (await this.deleteProposal(t, true), this.client.events.emit("proposal_expire", { id: t })); }); } registerPairingEvents() { this.client.core.pairing.events.on(V2.create, (o4) => this.onPairingCreated(o4)), this.client.core.pairing.events.on(V2.delete, (o4) => { this.addToRecentlyDeleted(o4.topic, "pairing"); }); } isValidPairingTopic(o4) { if (!b(o4, false)) { const { message: e2 } = S("MISSING_OR_INVALID", `pairing topic should be a string: ${o4}`); throw new Error(e2); } if (!this.client.core.pairing.pairings.keys.includes(o4)) { const { message: e2 } = S("NO_MATCHING_KEY", `pairing topic doesn't exist: ${o4}`); throw new Error(e2); } if (Kt(this.client.core.pairing.pairings.get(o4).expiry)) { const { message: e2 } = S("EXPIRED", `pairing topic: ${o4}`); throw new Error(e2); } } async isValidSessionTopic(o4) { if (!b(o4, false)) { const { message: e2 } = S("MISSING_OR_INVALID", `session topic should be a string: ${o4}`); throw new Error(e2); } if (this.checkRecentlyDeleted(o4), !this.client.session.keys.includes(o4)) { const { message: e2 } = S("NO_MATCHING_KEY", `session topic doesn't exist: ${o4}`); throw new Error(e2); } if (Kt(this.client.session.get(o4).expiry)) { await this.deleteSession({ topic: o4 }); const { message: e2 } = S("EXPIRED", `session topic: ${o4}`); throw new Error(e2); } if (!this.client.core.crypto.keychain.has(o4)) { const { message: e2 } = S("MISSING_OR_INVALID", `session topic does not exist in keychain: ${o4}`); throw await this.deleteSession({ topic: o4 }), new Error(e2); } } async isValidSessionOrPairingTopic(o4) { if (this.checkRecentlyDeleted(o4), this.client.session.keys.includes(o4)) await this.isValidSessionTopic(o4); else if (this.client.core.pairing.pairings.keys.includes(o4)) this.isValidPairingTopic(o4); else if (b(o4, false)) { const { message: e2 } = S("NO_MATCHING_KEY", `session or pairing topic doesn't exist: ${o4}`); throw new Error(e2); } else { const { message: e2 } = S("MISSING_OR_INVALID", `session or pairing topic should be a string: ${o4}`); throw new Error(e2); } } async isValidProposalId(o4) { if (!no(o4)) { const { message: e2 } = S("MISSING_OR_INVALID", `proposal id should be a number: ${o4}`); throw new Error(e2); } if (!this.client.proposal.keys.includes(o4)) { const { message: e2 } = S("NO_MATCHING_KEY", `proposal id doesn't exist: ${o4}`); throw new Error(e2); } if (Kt(this.client.proposal.get(o4).expiryTimestamp)) { await this.deleteProposal(o4); const { message: e2 } = S("EXPIRED", `proposal id: ${o4}`); throw new Error(e2); } } }; var Ss2 = class extends ni { constructor(o4, e2) { super(o4, e2, st3, ye3), this.core = o4, this.logger = e2; } }; var yt2 = class extends ni { constructor(o4, e2) { super(o4, e2, rt2, ye3), this.core = o4, this.logger = e2; } }; var Is2 = class extends ni { constructor(o4, e2) { super(o4, e2, ot2, ye3, (t) => t.id), this.core = o4, this.logger = e2; } }; var fs = class extends ni { constructor(o4, e2) { super(o4, e2, pt2, oe2, () => ae3), this.core = o4, this.logger = e2; } }; var vs2 = class extends ni { constructor(o4, e2) { super(o4, e2, ht2, oe2), this.core = o4, this.logger = e2; } }; var qs2 = class extends ni { constructor(o4, e2) { super(o4, e2, dt2, oe2, (t) => t.id), this.core = o4, this.logger = e2; } }; var Ts2 = class { constructor(o4, e2) { this.core = o4, this.logger = e2, this.authKeys = new fs(this.core, this.logger), this.pairingTopics = new vs2(this.core, this.logger), this.requests = new qs2(this.core, this.logger); } async init() { await this.authKeys.init(), await this.pairingTopics.init(), await this.requests.init(); } }; var _e3 = class __e extends S3 { constructor(o4) { super(o4), this.protocol = be3, this.version = Ce3, this.name = we3.name, this.events = new import_events8.EventEmitter(), this.on = (t, s3) => this.events.on(t, s3), this.once = (t, s3) => this.events.once(t, s3), this.off = (t, s3) => this.events.off(t, s3), this.removeListener = (t, s3) => this.events.removeListener(t, s3), this.removeAllListeners = (t) => this.events.removeAllListeners(t), this.connect = async (t) => { try { return await this.engine.connect(t); } catch (s3) { throw this.logger.error(s3.message), s3; } }, this.pair = async (t) => { try { return await this.engine.pair(t); } catch (s3) { throw this.logger.error(s3.message), s3; } }, this.approve = async (t) => { try { return await this.engine.approve(t); } catch (s3) { throw this.logger.error(s3.message), s3; } }, this.reject = async (t) => { try { return await this.engine.reject(t); } catch (s3) { throw this.logger.error(s3.message), s3; } }, this.update = async (t) => { try { return await this.engine.update(t); } catch (s3) { throw this.logger.error(s3.message), s3; } }, this.extend = async (t) => { try { return await this.engine.extend(t); } catch (s3) { throw this.logger.error(s3.message), s3; } }, this.request = async (t) => { try { return await this.engine.request(t); } catch (s3) { throw this.logger.error(s3.message), s3; } }, this.respond = async (t) => { try { return await this.engine.respond(t); } catch (s3) { throw this.logger.error(s3.message), s3; } }, this.ping = async (t) => { try { return await this.engine.ping(t); } catch (s3) { throw this.logger.error(s3.message), s3; } }, this.emit = async (t) => { try { return await this.engine.emit(t); } catch (s3) { throw this.logger.error(s3.message), s3; } }, this.disconnect = async (t) => { try { return await this.engine.disconnect(t); } catch (s3) { throw this.logger.error(s3.message), s3; } }, this.find = (t) => { try { return this.engine.find(t); } catch (s3) { throw this.logger.error(s3.message), s3; } }, this.getPendingSessionRequests = () => { try { return this.engine.getPendingSessionRequests(); } catch (t) { throw this.logger.error(t.message), t; } }, this.authenticate = async (t, s3) => { try { return await this.engine.authenticate(t, s3); } catch (i4) { throw this.logger.error(i4.message), i4; } }, this.formatAuthMessage = (t) => { try { return this.engine.formatAuthMessage(t); } catch (s3) { throw this.logger.error(s3.message), s3; } }, this.approveSessionAuthenticate = async (t) => { try { return await this.engine.approveSessionAuthenticate(t); } catch (s3) { throw this.logger.error(s3.message), s3; } }, this.rejectSessionAuthenticate = async (t) => { try { return await this.engine.rejectSessionAuthenticate(t); } catch (s3) { throw this.logger.error(s3.message), s3; } }, this.name = (o4 == null ? void 0 : o4.name) || we3.name, this.metadata = (o4 == null ? void 0 : o4.metadata) || Nt(), this.signConfig = o4 == null ? void 0 : o4.signConfig; const e2 = typeof (o4 == null ? void 0 : o4.logger) < "u" && typeof (o4 == null ? void 0 : o4.logger) != "string" ? o4.logger : (0, import_pino2.default)(k2({ level: (o4 == null ? void 0 : o4.logger) || we3.logger })); this.core = (o4 == null ? void 0 : o4.core) || new bn2(o4), this.logger = E(e2, this.name), this.session = new yt2(this.core, this.logger), this.proposal = new Ss2(this.core, this.logger), this.pendingRequest = new Is2(this.core, this.logger), this.engine = new Rs2(this), this.auth = new Ts2(this.core, this.logger); } static async init(o4) { const e2 = new __e(o4); return await e2.initialize(), e2; } get context() { return y2(this.logger); } get pairing() { return this.core.pairing.pairings; } async initialize() { this.logger.trace("Initialized"); try { await this.core.start(), await this.session.init(), await this.proposal.init(), await this.pendingRequest.init(), await this.auth.init(), await this.engine.init(), this.logger.info("SignClient Initialization Success"), this.engine.processRelayMessageCache(); } catch (o4) { throw this.logger.info("SignClient Initialization Failure"), this.logger.error(o4.message), o4; } } }; var Ps2 = _e3; export { require_events, safeJsonParse, safeJsonStringify, re, mt, N, Oe, Dn, U, L, Z, import_pino2 as import_pino, k2 as k, parseConnectionError, formatJsonRpcRequest, formatJsonRpcResult, formatJsonRpcError, isHttpUrl, esm_exports, o2 as o, it3 as it, _e3 as _e, Ps2 as Ps }; /*! Bundled license information: tslib/tslib.es6.js: (*! ***************************************************************************** Copyright (c) Microsoft Corporation. Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted. THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. ***************************************************************************** *) js-sha3/src/sha3.js: (** * [js-sha3]{@link https://github.com/emn178/js-sha3} * * @version 0.8.0 * @author Chen, Yi-Cyuan [emn178@gmail.com] * @copyright Chen, Yi-Cyuan 2015-2018 * @license MIT *) */ //# sourceMappingURL=chunk-EHYTL2NA.js.map ================================================ FILE: 17-Crowd-Funding-Dapp/Frontend/.vite/deps_temp_6cf5ba4c/chunk-EIBOABXT.js ================================================ // node_modules/thirdweb/dist/esm/wallets/types.js var socialAuthOptions = [ "google", "apple", "facebook", "discord", "line", "x", "coinbase", "farcaster", "telegram", "github", "twitch" ]; var authOptions = [ ...socialAuthOptions, "guest", "email", "phone", "passkey", "wallet" ]; export { socialAuthOptions, authOptions }; //# sourceMappingURL=chunk-EIBOABXT.js.map ================================================ FILE: 17-Crowd-Funding-Dapp/Frontend/.vite/deps_temp_6cf5ba4c/chunk-EIVAOYE5.js ================================================ import { keccak256 } from "./chunk-67BSOYLQ.js"; import { stringToBytes } from "./chunk-B7XHB4Z2.js"; import { LruMap } from "./chunk-SNQ54XRM.js"; // node_modules/thirdweb/dist/esm/utils/address.js var ADRESS_REGEX = /^0x[a-fA-F0-9]{40}$/; var IS_ADDRESS_CACHE = new LruMap(4096); function isAddress(address) { if (IS_ADDRESS_CACHE.has(address)) { return IS_ADDRESS_CACHE.get(address); } const result = (() => { if (!ADRESS_REGEX.test(address)) { return false; } if (address.toLowerCase() === address) { return true; } return checksumAddress(address) === address; })(); IS_ADDRESS_CACHE.set(address, result); return result; } function checksumAddress(address) { const hexAddress = address.substring(2).toLowerCase(); const hash = keccak256(stringToBytes(hexAddress), "bytes"); const address_ = hexAddress.split(""); for (let i = 0; i < 40; i += 2) { if (hash[i >> 1] >> 4 >= 8 && address[i]) { address_[i] = address_[i].toUpperCase(); } if ((hash[i >> 1] & 15) >= 8 && address[i + 1]) { address_[i + 1] = address_[i + 1].toUpperCase(); } } return `0x${address_.join("")}`; } function getAddress(address) { if (!isAddress(address)) { throw new Error(`Invalid address: ${address}`); } return checksumAddress(address); } function shortenAddress(address, length = 4) { const _address = getAddress(address); return shortenHex(_address, length); } function shortenHex(hex, length = 4) { return `${hex.slice(0, length + 2)}...${hex.slice(-length)}`; } export { isAddress, checksumAddress, getAddress, shortenAddress, shortenHex }; //# sourceMappingURL=chunk-EIVAOYE5.js.map ================================================ FILE: 17-Crowd-Funding-Dapp/Frontend/.vite/deps_temp_6cf5ba4c/chunk-F2BEZVSV.js ================================================ import { allowance } from "./chunk-NKFQ2LZT.js"; import { DEBUG, DUMMY_SIGNATURE, ENTRYPOINT_ADDRESS_v0_6, ENTRYPOINT_ADDRESS_v0_7, MANAGED_ACCOUNT_GAS_BUFFER, getDefaultAccountFactory, getDefaultBundlerUrl, getEntryPointVersion } from "./chunk-FNI7M3UI.js"; import { isContractDeployed } from "./chunk-Q3TN3POE.js"; import { parseTypedData } from "./chunk-SWMZXE3E.js"; import { populateEip712Transaction, signEip712Transaction } from "./chunk-5EFACFVF.js"; import { parseEventLogs, prepareEvent } from "./chunk-DYKFWRMQ.js"; import { approve } from "./chunk-TTOANXGP.js"; import { prepareContractCall } from "./chunk-6XF6HOWC.js"; import { getDefaultGasOverrides, toSerializableTransaction } from "./chunk-JZC47WAY.js"; import { resolvePromisedValue } from "./chunk-QC3K2OKT.js"; import { isZkSyncChain } from "./chunk-7ZCK2FX5.js"; import { encode } from "./chunk-7QDK5KLB.js"; import { concatHex } from "./chunk-4BCIASJM.js"; import { getContract } from "./chunk-7VZHRFCE.js"; import { readContract } from "./chunk-AG4NO6K6.js"; import { hashTypedData } from "./chunk-LO5SQBMX.js"; import { getAddress } from "./chunk-EIVAOYE5.js"; import { hexToBytes } from "./chunk-B7XHB4Z2.js"; import { concat, decodeErrorResult, maxUint96, pad, toHex as toHex2 } from "./chunk-GINVHONX.js"; import { stringify } from "./chunk-NJUWOGZE.js"; import { getCachedChain } from "./chunk-TFBEDS4S.js"; import { getClientFetch, isThirdwebUrl } from "./chunk-3GSJ2FQJ.js"; import { hexToBigInt, isHex, stringToHex, toHex } from "./chunk-BBNNHC5G.js"; // node_modules/thirdweb/dist/esm/extensions/erc4337/__generated__/IEntryPoint/events/UserOperationRevertReason.js function userOperationRevertReasonEvent(filters = {}) { return prepareEvent({ signature: "event UserOperationRevertReason(bytes32 indexed userOpHash, address indexed sender, uint256 nonce, bytes revertReason)", filters }); } // node_modules/thirdweb/dist/esm/extensions/erc4337/__generated__/IEntryPoint_v07/events/PostOpRevertReason.js function postOpRevertReasonEvent(filters = {}) { return prepareEvent({ signature: "event PostOpRevertReason(bytes32 indexed userOpHash, address indexed sender, uint256 nonce, bytes revertReason)", filters }); } // node_modules/thirdweb/dist/esm/wallets/smart/types.js function formatUserOperationReceipt(userOpReceiptRaw) { const { receipt: transactionReceipt } = userOpReceiptRaw; const receipt = { ...transactionReceipt, transactionHash: transactionReceipt.transactionHash, blockNumber: transactionReceipt.blockNumber ? BigInt(transactionReceipt.blockNumber) : null, contractAddress: transactionReceipt.contractAddress ? transactionReceipt.contractAddress : null, cumulativeGasUsed: transactionReceipt.cumulativeGasUsed ? BigInt(transactionReceipt.cumulativeGasUsed) : null, effectiveGasPrice: transactionReceipt.effectiveGasPrice ? BigInt(transactionReceipt.effectiveGasPrice) : null, gasUsed: transactionReceipt.gasUsed ? BigInt(transactionReceipt.gasUsed) : null, logs: transactionReceipt.logs, to: transactionReceipt.to ? transactionReceipt.to : null, transactionIndex: transactionReceipt.transactionIndex, status: transactionReceipt.status, type: transactionReceipt.type }; if (transactionReceipt.blobGasPrice) receipt.blobGasPrice = BigInt(transactionReceipt.blobGasPrice); if (transactionReceipt.blobGasUsed) receipt.blobGasUsed = BigInt(transactionReceipt.blobGasUsed); const userOpReceipt = { ...userOpReceiptRaw, receipt, userOpHash: userOpReceiptRaw.userOpHash, actualGasCost: BigInt(userOpReceiptRaw.actualGasCost), actualGasUsed: BigInt(userOpReceiptRaw.actualGasUsed), nonce: BigInt(userOpReceiptRaw.nonce) }; return userOpReceipt; } // node_modules/thirdweb/dist/esm/wallets/smart/lib/utils.js var generateRandomUint192 = () => { const rand1 = BigInt(Math.floor(Math.random() * 4294967296)); const rand2 = BigInt(Math.floor(Math.random() * 4294967296)); const rand3 = BigInt(Math.floor(Math.random() * 4294967296)); const rand4 = BigInt(Math.floor(Math.random() * 4294967296)); const rand5 = BigInt(Math.floor(Math.random() * 4294967296)); const rand6 = BigInt(Math.floor(Math.random() * 4294967296)); return rand1 << BigInt(160) | rand2 << BigInt(128) | rand3 << BigInt(96) | rand4 << BigInt(64) | rand5 << BigInt(32) | rand6; }; function hexlifyUserOp(userOp) { return Object.fromEntries(Object.entries(userOp).map(([key, val]) => [ key, // turn any value that's not hex into hex val === void 0 || val === null || isHex(val) ? val : toHex(val) ])); } // node_modules/thirdweb/dist/esm/wallets/smart/lib/bundler.js async function bundleUserOp(args) { return sendBundlerRequest({ ...args, operation: "eth_sendUserOperation", params: [ hexlifyUserOp(args.userOp), args.options.entrypointAddress ?? ENTRYPOINT_ADDRESS_v0_6 ] }); } async function estimateUserOpGas(args) { const res = await sendBundlerRequest({ ...args, operation: "eth_estimateUserOperationGas", params: [ hexlifyUserOp(args.userOp), args.options.entrypointAddress ?? ENTRYPOINT_ADDRESS_v0_6 ] }); return { preVerificationGas: hexToBigInt(res.preVerificationGas), verificationGas: res.verificationGas !== void 0 ? hexToBigInt(res.verificationGas) : void 0, verificationGasLimit: hexToBigInt(res.verificationGasLimit), callGasLimit: hexToBigInt(res.callGasLimit) + MANAGED_ACCOUNT_GAS_BUFFER, paymasterVerificationGasLimit: res.paymasterVerificationGasLimit !== void 0 ? hexToBigInt(res.paymasterVerificationGasLimit) : void 0, paymasterPostOpGasLimit: res.paymasterPostOpGasLimit !== void 0 ? hexToBigInt(res.paymasterPostOpGasLimit) : void 0 }; } async function getUserOpGasFees(args) { const res = await sendBundlerRequest({ ...args, operation: "thirdweb_getUserOperationGasPrice", params: [] }); return { maxPriorityFeePerGas: hexToBigInt(res.maxPriorityFeePerGas), maxFeePerGas: hexToBigInt(res.maxFeePerGas) }; } async function getUserOpReceipt(args) { var _a, _b; const res = await getUserOpReceiptRaw(args); if (!res) { return void 0; } if (res.success === false) { const logs = parseEventLogs({ events: [userOperationRevertReasonEvent(), postOpRevertReasonEvent()], logs: res.logs }); const revertReason = (_b = (_a = logs[0]) == null ? void 0 : _a.args) == null ? void 0 : _b.revertReason; if (!revertReason) { throw new Error(`UserOp failed at txHash: ${res.receipt.transactionHash}`); } const revertMsg = decodeErrorResult({ data: revertReason }); throw new Error(`UserOp failed with reason: '${revertMsg.args.join(",")}' at txHash: ${res.receipt.transactionHash}`); } return res.receipt; } async function getUserOpReceiptRaw(args) { const res = await sendBundlerRequest({ options: args, operation: "eth_getUserOperationReceipt", params: [args.userOpHash] }); if (!res) { return void 0; } return formatUserOperationReceipt(res); } async function getZkPaymasterData(args) { const res = await sendBundlerRequest({ options: args.options, operation: "zk_paymasterData", params: [args.transaction] }); return { paymaster: res.paymaster, paymasterInput: res.paymasterInput }; } async function broadcastZkTransaction(args) { const res = await sendBundlerRequest({ options: args.options, operation: "zk_broadcastTransaction", params: [ { ...args.transaction, signedTransaction: args.signedTransaction } ] }); return { transactionHash: res.transactionHash }; } async function sendBundlerRequest(args) { const { options, operation, params } = args; if (DEBUG) { console.debug(`>>> sending ${operation} with payload:`, params); } const bundlerUrl = options.bundlerUrl ?? getDefaultBundlerUrl(options.chain); const fetchWithHeaders = getClientFetch(options.client); const response = await fetchWithHeaders(bundlerUrl, { method: "POST", headers: { "Content-Type": "application/json" }, body: stringify({ jsonrpc: "2.0", id: 1, method: operation, params }) }); const res = await response.json(); if (!response.ok || res.error) { let error = res.error || response.statusText; if (typeof error === "object") { error = stringify(error); } const code = res.code || "UNKNOWN"; throw new Error(`${operation} error: ${error} Status: ${response.status} Code: ${code}`); } if (DEBUG) { console.debug(`<<< ${operation} result:`, res); } return res.result; } // node_modules/thirdweb/dist/esm/wallets/smart/lib/calls.js async function predictAddress(args) { const { factoryContract, predictAddressOverride: predictAddress2, adminAddress, accountSalt, accountAddress } = args; if (predictAddress2) { return predictAddress2(factoryContract); } if (accountAddress) { return accountAddress; } if (!adminAddress) { throw new Error("Account address is required to predict the smart wallet address."); } const saltHex = accountSalt && isHex(accountSalt) ? accountSalt : stringToHex(accountSalt ?? ""); return readContract({ contract: factoryContract, method: "function getAddress(address, bytes) returns (address)", params: [adminAddress, saltHex] }); } function prepareCreateAccount(args) { const { adminAddress, factoryContract, createAccountOverride: createAccount, accountSalt } = args; if (createAccount) { return createAccount(factoryContract); } const saltHex = accountSalt && isHex(accountSalt) ? accountSalt : stringToHex(accountSalt ?? ""); return prepareContractCall({ contract: factoryContract, method: "function createAccount(address, bytes) returns (address)", params: [adminAddress, saltHex] }); } function prepareExecute(args) { const { accountContract, transaction, executeOverride: execute } = args; if (execute) { return execute(accountContract, transaction); } return prepareContractCall({ contract: accountContract, method: "function execute(address, uint256, bytes)", params: [ transaction.to || "", transaction.value || 0n, transaction.data || "0x" ], // if gas is specified for the inner tx, use that and add 21k for the execute call on the account contract // this avoids another estimateGas call when bundling the userOp // and also allows for passing custom gas limits for the inner tx gas: transaction.gas ? transaction.gas + 21000n : void 0 }); } function prepareBatchExecute(args) { const { accountContract, transactions, executeBatchOverride: executeBatch } = args; if (executeBatch) { return executeBatch(accountContract, transactions); } return prepareContractCall({ contract: accountContract, method: "function executeBatch(address[], uint256[], bytes[])", params: [ transactions.map((tx) => tx.to || ""), transactions.map((tx) => tx.value || 0n), transactions.map((tx) => tx.data || "0x") ] }); } // node_modules/thirdweb/dist/esm/extensions/erc4337/__generated__/IEntryPoint/read/getNonce.js var FN_SELECTOR = "0x35567e1a"; var FN_INPUTS = [ { type: "address", name: "sender" }, { type: "uint192", name: "key" } ]; var FN_OUTPUTS = [ { type: "uint256", name: "nonce" } ]; async function getNonce(options) { return readContract({ contract: options.contract, method: [FN_SELECTOR, FN_INPUTS, FN_OUTPUTS], params: [options.sender, options.key] }); } // node_modules/thirdweb/dist/esm/extensions/erc4337/__generated__/IEntryPoint/read/getUserOpHash.js var FN_SELECTOR2 = "0xa6193531"; var FN_INPUTS2 = [ { type: "tuple", name: "userOp", components: [ { type: "address", name: "sender" }, { type: "uint256", name: "nonce" }, { type: "bytes", name: "initCode" }, { type: "bytes", name: "callData" }, { type: "uint256", name: "callGasLimit" }, { type: "uint256", name: "verificationGasLimit" }, { type: "uint256", name: "preVerificationGas" }, { type: "uint256", name: "maxFeePerGas" }, { type: "uint256", name: "maxPriorityFeePerGas" }, { type: "bytes", name: "paymasterAndData" }, { type: "bytes", name: "signature" } ] } ]; var FN_OUTPUTS2 = [ { type: "bytes32" } ]; async function getUserOpHash(options) { return readContract({ contract: options.contract, method: [FN_SELECTOR2, FN_INPUTS2, FN_OUTPUTS2], params: [options.userOp] }); } // node_modules/thirdweb/dist/esm/extensions/erc4337/__generated__/IEntryPoint_v07/read/getUserOpHash.js var FN_SELECTOR3 = "0x22cdde4c"; var FN_INPUTS3 = [ { type: "tuple", name: "userOp", components: [ { type: "address", name: "sender" }, { type: "uint256", name: "nonce" }, { type: "bytes", name: "initCode" }, { type: "bytes", name: "callData" }, { type: "bytes32", name: "accountGasLimits" }, { type: "uint256", name: "preVerificationGas" }, { type: "bytes32", name: "gasFees" }, { type: "bytes", name: "paymasterAndData" }, { type: "bytes", name: "signature" } ] } ]; var FN_OUTPUTS3 = [ { type: "bytes32" } ]; async function getUserOpHash2(options) { return readContract({ contract: options.contract, method: [FN_SELECTOR3, FN_INPUTS3, FN_OUTPUTS3], params: [options.userOp] }); } // node_modules/thirdweb/dist/esm/wallets/smart/lib/packUserOp.js function getInitCode(unpackedUserOperation) { return unpackedUserOperation.factory ? concat([ unpackedUserOperation.factory, unpackedUserOperation.factoryData || "0x" ]) : "0x"; } function getAccountGasLimits(unpackedUserOperation) { return concat([ pad(toHex2(unpackedUserOperation.verificationGasLimit), { size: 16 }), pad(toHex2(unpackedUserOperation.callGasLimit), { size: 16 }) ]); } function getGasLimits(unpackedUserOperation) { return concat([ pad(toHex2(unpackedUserOperation.maxPriorityFeePerGas), { size: 16 }), pad(toHex2(unpackedUserOperation.maxFeePerGas), { size: 16 }) ]); } function getPaymasterAndData(unpackedUserOperation) { return unpackedUserOperation.paymaster ? concat([ unpackedUserOperation.paymaster, pad(toHex2(unpackedUserOperation.paymasterVerificationGasLimit || BigInt(0)), { size: 16 }), pad(toHex2(unpackedUserOperation.paymasterPostOpGasLimit || BigInt(0)), { size: 16 }), unpackedUserOperation.paymasterData || "0x" ]) : "0x"; } var getPackedUserOperation = (userOperation) => { return { sender: userOperation.sender, nonce: userOperation.nonce, initCode: getInitCode(userOperation), callData: userOperation.callData, accountGasLimits: getAccountGasLimits(userOperation), preVerificationGas: userOperation.preVerificationGas, gasFees: getGasLimits(userOperation), paymasterAndData: getPaymasterAndData(userOperation), signature: userOperation.signature }; }; // node_modules/thirdweb/dist/esm/wallets/smart/lib/paymaster.js async function getPaymasterAndData2(args) { var _a; const { userOp, paymasterOverride, client, chain, entrypointAddress } = args; if (paymasterOverride) { return paymasterOverride(userOp); } const headers = { "Content-Type": "application/json" }; const entrypoint = entrypointAddress ?? ENTRYPOINT_ADDRESS_v0_6; const paymasterUrl = getDefaultBundlerUrl(chain); const fetchWithHeaders = getClientFetch(client); const response = await fetchWithHeaders(paymasterUrl, { method: "POST", headers, body: stringify({ jsonrpc: "2.0", id: 1, method: "pm_sponsorUserOperation", params: [hexlifyUserOp(userOp), entrypoint] }) }); const res = await response.json(); if (!response.ok) { const error2 = res.error || response.statusText; const code = res.code || "UNKNOWN"; throw new Error(`Paymaster error: ${error2} Status: ${response.status} Code: ${code}`); } if (DEBUG) { console.debug("Paymaster result:", res); } if (res.result) { if (typeof res.result === "string") { return { paymasterAndData: res.result }; } return { paymasterAndData: res.result.paymasterAndData, verificationGasLimit: res.result.verificationGasLimit ? hexToBigInt(res.result.verificationGasLimit) : void 0, preVerificationGas: res.result.preVerificationGas ? hexToBigInt(res.result.preVerificationGas) : void 0, callGasLimit: res.result.callGasLimit ? hexToBigInt(res.result.callGasLimit) : void 0, paymaster: res.result.paymaster, paymasterData: res.result.paymasterData, paymasterVerificationGasLimit: res.result.paymasterVerificationGasLimit ? hexToBigInt(res.result.paymasterVerificationGasLimit) : void 0, paymasterPostOpGasLimit: res.result.paymasterPostOpGasLimit ? hexToBigInt(res.result.paymasterPostOpGasLimit) : void 0 }; } const error = ((_a = res.error) == null ? void 0 : _a.message) || res.error || response.statusText || "unknown error"; throw new Error(`Paymaster error from ${paymasterUrl}: ${error}`); } // node_modules/thirdweb/dist/esm/wallets/smart/lib/userop.js var isDeployingSet = /* @__PURE__ */ new Set(); var getKey = (accountContract) => { return `${accountContract.chain.id}:${accountContract.address}`; }; var markAccountDeploying = (accountContract) => { isDeployingSet.add(getKey(accountContract)); }; var clearAccountDeploying = (accountContract) => { isDeployingSet.delete(getKey(accountContract)); }; var isAccountDeploying = (accountContract) => { return isDeployingSet.has(getKey(accountContract)); }; async function waitForUserOpReceipt(args) { const timeout = args.timeoutMs || 12e4; const interval = args.intervalMs || 1e3; const endtime = Date.now() + timeout; while (Date.now() < endtime) { const userOpReceipt = await getUserOpReceipt(args); if (userOpReceipt) { return userOpReceipt; } await new Promise((resolve) => setTimeout(resolve, interval)); } throw new Error("Timeout waiting for userOp to be mined"); } async function createUnsignedUserOp(args) { var _a; const { transaction: executeTx, accountContract, factoryContract, adminAddress, overrides, sponsorGas, waitForDeployment = true } = args; const chain = executeTx.chain; const client = executeTx.client; const bundlerOptions = { client, chain, bundlerUrl: overrides == null ? void 0 : overrides.bundlerUrl, entrypointAddress: overrides == null ? void 0 : overrides.entrypointAddress }; const entrypointVersion = getEntryPointVersion(((_a = args.overrides) == null ? void 0 : _a.entrypointAddress) || ENTRYPOINT_ADDRESS_v0_6); const [isDeployed, callData, callGasLimit, gasFees, nonce] = await Promise.all([ isContractDeployed(accountContract), encode(executeTx), resolvePromisedValue(executeTx.gas), getGasFees({ executeTx, bundlerOptions, chain, client }), getAccountNonce({ accountContract, chain, client, entrypointAddress: overrides == null ? void 0 : overrides.entrypointAddress, getNonceOverride: overrides == null ? void 0 : overrides.getAccountNonce }) ]); const { maxFeePerGas, maxPriorityFeePerGas } = gasFees; if (entrypointVersion === "v0.7") { return populateUserOp_v0_7({ bundlerOptions, factoryContract, accountContract, adminAddress, sponsorGas, overrides, isDeployed, nonce, callData, callGasLimit, maxFeePerGas, maxPriorityFeePerGas, waitForDeployment }); } return populateUserOp_v0_6({ bundlerOptions, factoryContract, accountContract, adminAddress, sponsorGas, overrides, isDeployed, nonce, callData, callGasLimit, maxFeePerGas, maxPriorityFeePerGas, waitForDeployment }); } async function getGasFees(args) { const { executeTx, bundlerOptions, chain, client } = args; let { maxFeePerGas, maxPriorityFeePerGas } = executeTx; const bundlerUrl = (bundlerOptions == null ? void 0 : bundlerOptions.bundlerUrl) ?? getDefaultBundlerUrl(chain); if (isThirdwebUrl(bundlerUrl)) { const bundlerGasPrice = await getUserOpGasFees({ options: bundlerOptions }); maxFeePerGas = bundlerGasPrice.maxFeePerGas; maxPriorityFeePerGas = bundlerGasPrice.maxPriorityFeePerGas; } else { const [resolvedMaxFeePerGas, resolvedMaxPriorityFeePerGas] = await Promise.all([ resolvePromisedValue(maxFeePerGas), resolvePromisedValue(maxPriorityFeePerGas) ]); if (resolvedMaxFeePerGas && resolvedMaxPriorityFeePerGas) { maxFeePerGas = resolvedMaxFeePerGas; maxPriorityFeePerGas = resolvedMaxPriorityFeePerGas; } else { const feeData = await getDefaultGasOverrides(client, chain); maxPriorityFeePerGas = resolvedMaxPriorityFeePerGas ?? feeData.maxPriorityFeePerGas ?? 0n; maxFeePerGas = resolvedMaxFeePerGas ?? feeData.maxFeePerGas ?? 0n; } } return { maxFeePerGas, maxPriorityFeePerGas }; } async function populateUserOp_v0_7(args) { const { bundlerOptions, isDeployed, factoryContract, accountContract, adminAddress, sponsorGas, overrides, nonce, callData, callGasLimit, maxFeePerGas, maxPriorityFeePerGas, waitForDeployment } = args; const { chain, client } = bundlerOptions; let factory; let factoryData; if (isDeployed || isAccountDeploying(accountContract)) { factoryData = "0x"; if (waitForDeployment) { await waitForAccountDeployed(accountContract); } } else { factory = factoryContract.address; factoryData = await encode(prepareCreateAccount({ factoryContract, adminAddress, accountSalt: overrides == null ? void 0 : overrides.accountSalt, createAccountOverride: overrides == null ? void 0 : overrides.createAccount })); markAccountDeploying(accountContract); } const partialOp = { sender: accountContract.address, nonce, callData, maxFeePerGas, maxPriorityFeePerGas, callGasLimit: callGasLimit ?? 0n, verificationGasLimit: 0n, preVerificationGas: 0n, factory, factoryData, paymaster: void 0, paymasterData: "0x", paymasterVerificationGasLimit: 0n, paymasterPostOpGasLimit: 0n, signature: DUMMY_SIGNATURE }; if (sponsorGas) { const paymasterResult = await getPaymasterAndData2({ userOp: partialOp, chain, client, entrypointAddress: overrides == null ? void 0 : overrides.entrypointAddress, paymasterOverride: overrides == null ? void 0 : overrides.paymaster }); if (paymasterResult.paymaster && paymasterResult.paymasterData) { partialOp.paymaster = paymasterResult.paymaster; partialOp.paymasterData = paymasterResult.paymasterData; } if (paymasterResult.callGasLimit && paymasterResult.verificationGasLimit && paymasterResult.preVerificationGas && paymasterResult.paymasterPostOpGasLimit && paymasterResult.paymasterVerificationGasLimit) { partialOp.callGasLimit = paymasterResult.callGasLimit; partialOp.verificationGasLimit = paymasterResult.verificationGasLimit; partialOp.preVerificationGas = paymasterResult.preVerificationGas; partialOp.paymasterPostOpGasLimit = paymasterResult.paymasterPostOpGasLimit; partialOp.paymasterVerificationGasLimit = paymasterResult.paymasterVerificationGasLimit; } else { const estimates = await estimateUserOpGas({ userOp: partialOp, options: bundlerOptions }); partialOp.callGasLimit = estimates.callGasLimit; partialOp.verificationGasLimit = estimates.verificationGasLimit; partialOp.preVerificationGas = estimates.preVerificationGas; partialOp.paymasterPostOpGasLimit = paymasterResult.paymasterPostOpGasLimit || 0n; partialOp.paymasterVerificationGasLimit = paymasterResult.paymasterVerificationGasLimit || 0n; const paymasterResult2 = await getPaymasterAndData2({ userOp: partialOp, chain, client, entrypointAddress: overrides == null ? void 0 : overrides.entrypointAddress, paymasterOverride: overrides == null ? void 0 : overrides.paymaster }); if (paymasterResult2.paymaster && paymasterResult2.paymasterData) { partialOp.paymaster = paymasterResult2.paymaster; partialOp.paymasterData = paymasterResult2.paymasterData; } } } else { const estimates = await estimateUserOpGas({ userOp: partialOp, options: bundlerOptions }); partialOp.callGasLimit = estimates.callGasLimit; partialOp.verificationGasLimit = estimates.verificationGasLimit; partialOp.preVerificationGas = estimates.preVerificationGas; partialOp.paymasterPostOpGasLimit = estimates.paymasterPostOpGasLimit || 0n; partialOp.paymasterVerificationGasLimit = estimates.paymasterVerificationGasLimit || 0n; } return { ...partialOp, signature: "0x" }; } async function populateUserOp_v0_6(args) { const { bundlerOptions, isDeployed, factoryContract, accountContract, adminAddress, sponsorGas, overrides, nonce, callData, callGasLimit, maxFeePerGas, maxPriorityFeePerGas, waitForDeployment } = args; const { chain, client } = bundlerOptions; let initCode; if (isDeployed || isAccountDeploying(accountContract)) { initCode = "0x"; if (waitForDeployment) { await waitForAccountDeployed(accountContract); } } else { initCode = await getAccountInitCode({ factoryContract, adminAddress, accountSalt: overrides == null ? void 0 : overrides.accountSalt, createAccountOverride: overrides == null ? void 0 : overrides.createAccount }); markAccountDeploying(accountContract); } const partialOp = { sender: accountContract.address, nonce, initCode, callData, maxFeePerGas, maxPriorityFeePerGas, callGasLimit: callGasLimit ?? 0n, verificationGasLimit: 0n, preVerificationGas: 0n, paymasterAndData: "0x", signature: DUMMY_SIGNATURE }; if (sponsorGas) { const paymasterResult = await getPaymasterAndData2({ userOp: partialOp, chain, client, entrypointAddress: overrides == null ? void 0 : overrides.entrypointAddress, paymasterOverride: overrides == null ? void 0 : overrides.paymaster }); const paymasterAndData = "paymasterAndData" in paymasterResult ? paymasterResult.paymasterAndData : "0x"; if (paymasterAndData && paymasterAndData !== "0x") { partialOp.paymasterAndData = paymasterAndData; } if (paymasterResult.callGasLimit && paymasterResult.verificationGasLimit && paymasterResult.preVerificationGas) { partialOp.callGasLimit = paymasterResult.callGasLimit; partialOp.verificationGasLimit = paymasterResult.verificationGasLimit; partialOp.preVerificationGas = paymasterResult.preVerificationGas; } else { const estimates = await estimateUserOpGas({ userOp: partialOp, options: bundlerOptions }); partialOp.callGasLimit = estimates.callGasLimit; partialOp.verificationGasLimit = estimates.verificationGasLimit; partialOp.preVerificationGas = estimates.preVerificationGas; if (paymasterAndData && paymasterAndData !== "0x") { const paymasterResult2 = await getPaymasterAndData2({ userOp: partialOp, chain, client, entrypointAddress: overrides == null ? void 0 : overrides.entrypointAddress, paymasterOverride: overrides == null ? void 0 : overrides.paymaster }); const paymasterAndData2 = "paymasterAndData" in paymasterResult2 ? paymasterResult2.paymasterAndData : "0x"; if (paymasterAndData2 && paymasterAndData2 !== "0x") { partialOp.paymasterAndData = paymasterAndData2; } } } } else { const estimates = await estimateUserOpGas({ userOp: partialOp, options: bundlerOptions }); partialOp.callGasLimit = estimates.callGasLimit; partialOp.verificationGasLimit = estimates.verificationGasLimit; partialOp.preVerificationGas = estimates.preVerificationGas; } return { ...partialOp, signature: "0x" }; } async function signUserOp(args) { const { userOp, chain, entrypointAddress, adminAccount } = args; const entrypointVersion = getEntryPointVersion(entrypointAddress || ENTRYPOINT_ADDRESS_v0_6); let userOpHash; if (entrypointVersion === "v0.7") { const packedUserOp = getPackedUserOperation(userOp); userOpHash = await getUserOpHash2({ contract: getContract({ address: entrypointAddress || ENTRYPOINT_ADDRESS_v0_7, chain, client: args.client }), userOp: packedUserOp }); } else { userOpHash = await getUserOpHash({ contract: getContract({ address: entrypointAddress || ENTRYPOINT_ADDRESS_v0_6, chain, client: args.client }), userOp }); } if (adminAccount.signMessage) { const signature = await adminAccount.signMessage({ message: { raw: hexToBytes(userOpHash) } }); return { ...userOp, signature }; } throw new Error("signMessage not implemented in signingAccount"); } async function getAccountInitCode(options) { const { factoryContract, adminAddress, accountSalt, createAccountOverride } = options; const deployTx = prepareCreateAccount({ factoryContract, adminAddress, accountSalt, createAccountOverride }); return concat([factoryContract.address, await encode(deployTx)]); } async function getAccountNonce(options) { const { accountContract, chain, client, entrypointAddress, getNonceOverride } = options; if (getNonceOverride) { return getNonceOverride(accountContract); } return getNonce({ contract: getContract({ address: entrypointAddress || ENTRYPOINT_ADDRESS_v0_6, chain, client }), key: generateRandomUint192(), sender: accountContract.address }); } async function waitForAccountDeployed(accountContract) { const startTime = Date.now(); while (isAccountDeploying(accountContract)) { if (Date.now() - startTime > 6e4) { clearAccountDeploying(accountContract); throw new Error("Account deployment is taking too long (over 1 minute). Please try again."); } await new Promise((resolve) => setTimeout(resolve, 500)); } } // node_modules/thirdweb/dist/esm/wallets/smart/index.js function isSmartWallet(wallet) { return wallet.id === "smart"; } var personalAccountToSmartAccountMap = /* @__PURE__ */ new WeakMap(); var smartWalletToPersonalAccountMap = /* @__PURE__ */ new WeakMap(); async function connectSmartWallet(wallet, connectionOptions, creationOptions) { var _a, _b, _c, _d, _e; const { personalAccount, client, chain: connectChain } = connectionOptions; if (!personalAccount) { throw new Error("Personal wallet does not have an account"); } const options = creationOptions; const chain = connectChain ?? options.chain; if (options.factoryAddress && !((_a = options.overrides) == null ? void 0 : _a.entrypointAddress)) { const entrypointAddress = await getEntrypointFromFactory(options.factoryAddress, client, chain); if (entrypointAddress) { options.overrides = { ...options.overrides, entrypointAddress }; } } const factoryAddress = options.factoryAddress ?? getDefaultAccountFactory((_b = options.overrides) == null ? void 0 : _b.entrypointAddress); const sponsorGas = "gasless" in options ? options.gasless : options.sponsorGas; if (await isZkSyncChain(chain)) { return [ createZkSyncAccount({ creationOptions, connectionOptions, chain, sponsorGas }), chain ]; } const factoryContract = getContract({ client, address: factoryAddress, chain }); const accountAddress = await predictAddress({ factoryContract, adminAddress: personalAccount.address, predictAddressOverride: (_c = options.overrides) == null ? void 0 : _c.predictAddress, accountSalt: (_d = options.overrides) == null ? void 0 : _d.accountSalt, accountAddress: (_e = options.overrides) == null ? void 0 : _e.accountAddress }).then((address) => address).catch((err) => { throw new Error(`Failed to get account address with factory contract ${factoryContract.address} on chain ID ${chain.id}: ${(err == null ? void 0 : err.message) || "unknown error"}`, { cause: err }); }); const accountContract = getContract({ client, address: accountAddress, chain }); const account = await createSmartAccount({ ...options, chain, sponsorGas, personalAccount, accountContract, factoryContract, client }); personalAccountToSmartAccountMap.set(personalAccount, wallet); smartWalletToPersonalAccountMap.set(wallet, personalAccount); return [account, chain]; } async function disconnectSmartWallet(wallet) { const personalAccount = smartWalletToPersonalAccountMap.get(wallet); if (personalAccount) { personalAccountToSmartAccountMap.delete(personalAccount); smartWalletToPersonalAccountMap.delete(wallet); } } async function createSmartAccount(options) { const { accountContract } = options; const account = { address: getAddress(accountContract.address), async sendTransaction(transaction) { var _a, _b, _c, _d; const erc20Paymaster = (_a = options.overrides) == null ? void 0 : _a.erc20Paymaster; let paymasterOverride = void 0; if (erc20Paymaster) { await approveERC20({ accountContract, erc20Paymaster, options }); const paymasterCallback = async () => { return { paymasterAndData: concatHex([ erc20Paymaster.address, erc20Paymaster == null ? void 0 : erc20Paymaster.token ]), // for 0.7 compatibility paymaster: erc20Paymaster.address, paymasterData: "0x" }; }; paymasterOverride = ((_b = options.overrides) == null ? void 0 : _b.paymaster) || paymasterCallback; } else { paymasterOverride = (_c = options.overrides) == null ? void 0 : _c.paymaster; } const executeTx = prepareExecute({ accountContract, transaction, executeOverride: (_d = options.overrides) == null ? void 0 : _d.execute }); return _sendUserOp({ executeTx, options: { ...options, overrides: { ...options.overrides, paymaster: paymasterOverride } } }); }, async sendBatchTransaction(transactions) { var _a; const executeTx = prepareBatchExecute({ accountContract, transactions, executeBatchOverride: (_a = options.overrides) == null ? void 0 : _a.executeBatch }); return _sendUserOp({ executeTx, options }); }, async signMessage({ message }) { const [{ isContractDeployed: isContractDeployed2 }, { readContract: readContract2 }, { encodeAbiParameters: encodeAbiParameters2 }, { hashMessage }, { checkContractWalletSignature }] = await Promise.all([ import("./is-contract-deployed-AZVYEI5B.js"), import("./read-contract-EXVZZYXE.js"), import("./encodeAbiParameters-UF4TQP7R.js"), import("./hashMessage-NHJEFPJB.js"), import("./checkContractWalletSignature-6DFUQS7E.js") ]); const isDeployed = await isContractDeployed2(accountContract); if (!isDeployed) { await _deployAccount({ options, account, accountContract }); await confirmContractDeployment({ accountContract }); } const originalMsgHash = hashMessage(message); let factorySupports712 = false; try { await readContract2({ contract: accountContract, method: "function getMessageHash(bytes32 _hash) public view returns (bytes32)", params: [originalMsgHash] }); factorySupports712 = true; } catch { } let sig; if (factorySupports712) { const wrappedMessageHash = encodeAbiParameters2([{ type: "bytes32" }], [originalMsgHash]); sig = await options.personalAccount.signTypedData({ domain: { name: "Account", version: "1", chainId: options.chain.id, verifyingContract: accountContract.address }, primaryType: "AccountMessage", types: { AccountMessage: [{ name: "message", type: "bytes" }] }, message: { message: wrappedMessageHash } }); } else { sig = await options.personalAccount.signMessage({ message }); } const isValid = await checkContractWalletSignature({ contract: accountContract, message, signature: sig }); if (isValid) { return sig; } throw new Error("Unable to verify signature on smart account, please make sure the smart account is deployed and the signature is valid."); }, async signTypedData(_typedData) { var _a, _b, _c; const typedData = parseTypedData(_typedData); const [{ isContractDeployed: isContractDeployed2 }, { readContract: readContract2 }, { encodeAbiParameters: encodeAbiParameters2 }, { checkContractWalletSignedTypedData }] = await Promise.all([ import("./is-contract-deployed-AZVYEI5B.js"), import("./read-contract-EXVZZYXE.js"), import("./encodeAbiParameters-UF4TQP7R.js"), import("./checkContractWalletSignedTypedData-SEVCYJA7.js") ]); const isSelfVerifyingContract = ((_b = (_a = typedData.domain) == null ? void 0 : _a.verifyingContract) == null ? void 0 : _b.toLowerCase()) === ((_c = accountContract.address) == null ? void 0 : _c.toLowerCase()); if (isSelfVerifyingContract) { return options.personalAccount.signTypedData(typedData); } const isDeployed = await isContractDeployed2(accountContract); if (!isDeployed) { await _deployAccount({ options, account, accountContract }); await confirmContractDeployment({ accountContract }); } const originalMsgHash = hashTypedData(typedData); let factorySupports712 = false; try { await readContract2({ contract: accountContract, method: "function getMessageHash(bytes32 _hash) public view returns (bytes32)", params: [originalMsgHash] }); factorySupports712 = true; } catch { } let sig; if (factorySupports712) { const wrappedMessageHash = encodeAbiParameters2([{ type: "bytes32" }], [originalMsgHash]); sig = await options.personalAccount.signTypedData({ domain: { name: "Account", version: "1", chainId: options.chain.id, verifyingContract: accountContract.address }, primaryType: "AccountMessage", types: { AccountMessage: [{ name: "message", type: "bytes" }] }, message: { message: wrappedMessageHash } }); } else { sig = await options.personalAccount.signTypedData(typedData); } const isValid = await checkContractWalletSignedTypedData({ contract: accountContract, data: typedData, signature: sig }); if (isValid) { return sig; } throw new Error("Unable to verify signature on smart account, please make sure the smart account is deployed and the signature is valid."); }, async onTransactionRequested(transaction) { var _a, _b; return (_b = (_a = options.personalAccount).onTransactionRequested) == null ? void 0 : _b.call(_a, transaction); } }; return account; } async function approveERC20(args) { var _a; const { accountContract, erc20Paymaster, options } = args; const tokenAddress = erc20Paymaster.token; const tokenContract = getContract({ address: tokenAddress, chain: accountContract.chain, client: accountContract.client }); const accountAllowance = await allowance({ contract: tokenContract, owner: accountContract.address, spender: erc20Paymaster.address }); if (accountAllowance > 0n) { return; } const approveTx = approve({ contract: tokenContract, spender: erc20Paymaster.address, amountWei: maxUint96 - 1n }); const transaction = await toSerializableTransaction({ transaction: approveTx, from: accountContract.address }); const executeTx = prepareExecute({ accountContract, transaction, executeOverride: (_a = options.overrides) == null ? void 0 : _a.execute }); await _sendUserOp({ executeTx, options: { ...options, overrides: { ...options.overrides, erc20Paymaster: void 0 } } }); } function createZkSyncAccount(args) { const { creationOptions, connectionOptions, chain } = args; const account = { address: connectionOptions.personalAccount.address, async sendTransaction(transaction) { var _a, _b, _c, _d; const prepTx = { data: transaction.data, to: transaction.to ?? void 0, value: transaction.value ?? 0n, chain: getCachedChain(transaction.chainId), client: connectionOptions.client, eip712: transaction.eip712 }; let serializableTransaction = await populateEip712Transaction({ account, transaction: prepTx }); if (args.sponsorGas && !serializableTransaction.paymaster) { const pmData = await getZkPaymasterData({ options: { client: connectionOptions.client, chain, bundlerUrl: (_a = creationOptions.overrides) == null ? void 0 : _a.bundlerUrl, entrypointAddress: (_b = creationOptions.overrides) == null ? void 0 : _b.entrypointAddress }, transaction: serializableTransaction }); serializableTransaction = { ...serializableTransaction, ...pmData }; } const signedTransaction = await signEip712Transaction({ account, chainId: chain.id, eip712Transaction: serializableTransaction }); const txHash = await broadcastZkTransaction({ options: { client: connectionOptions.client, chain, bundlerUrl: (_c = creationOptions.overrides) == null ? void 0 : _c.bundlerUrl, entrypointAddress: (_d = creationOptions.overrides) == null ? void 0 : _d.entrypointAddress }, transaction: serializableTransaction, signedTransaction }); return { transactionHash: txHash.transactionHash, client: connectionOptions.client, chain }; }, async signMessage({ message }) { return connectionOptions.personalAccount.signMessage({ message }); }, async signTypedData(_typedData) { const typedData = parseTypedData(_typedData); return connectionOptions.personalAccount.signTypedData(typedData); }, async onTransactionRequested(transaction) { var _a, _b; return (_b = (_a = connectionOptions.personalAccount).onTransactionRequested) == null ? void 0 : _b.call(_a, transaction); } }; return account; } async function _deployAccount(args) { const { options, account, accountContract } = args; const [{ sendTransaction }, { prepareTransaction }] = await Promise.all([ import("./send-transaction-3VCDCFKW.js"), import("./prepare-transaction-ENVXVTJF.js") ]); const dummyTx = prepareTransaction({ client: options.client, chain: options.chain, to: accountContract.address, value: 0n, gas: 50000n // force gas to avoid simulation error }); const deployResult = await sendTransaction({ transaction: dummyTx, account }); return deployResult; } async function _sendUserOp(args) { var _a, _b, _c; const { executeTx, options } = args; const unsignedUserOp = await createUnsignedUserOp({ transaction: executeTx, factoryContract: options.factoryContract, accountContract: options.accountContract, adminAddress: options.personalAccount.address, sponsorGas: options.sponsorGas, overrides: options.overrides }); const signedUserOp = await signUserOp({ client: options.client, chain: options.chain, adminAccount: options.personalAccount, entrypointAddress: (_a = options.overrides) == null ? void 0 : _a.entrypointAddress, userOp: unsignedUserOp }); const bundlerOptions = { chain: options.chain, client: options.client, bundlerUrl: (_b = options.overrides) == null ? void 0 : _b.bundlerUrl, entrypointAddress: (_c = options.overrides) == null ? void 0 : _c.entrypointAddress }; const userOpHash = await bundleUserOp({ options: bundlerOptions, userOp: signedUserOp }); const receipt = await waitForUserOpReceipt({ ...bundlerOptions, userOpHash }); clearAccountDeploying(options.accountContract); return { client: options.client, chain: options.chain, transactionHash: receipt.transactionHash }; } async function confirmContractDeployment(args) { const { accountContract } = args; const startTime = Date.now(); const timeout = 6e4; const { isContractDeployed: isContractDeployed2 } = await import("./is-contract-deployed-AZVYEI5B.js"); let isDeployed = await isContractDeployed2(accountContract); while (!isDeployed) { if (Date.now() - startTime > timeout) { throw new Error("Timeout: Smart account deployment not confirmed after 1 minute"); } await new Promise((resolve) => setTimeout(resolve, 500)); isDeployed = await isContractDeployed2(accountContract); } } async function getEntrypointFromFactory(factoryAddress, client, chain) { const factoryContract = getContract({ address: factoryAddress, client, chain }); try { const entrypointAddress = await readContract({ contract: factoryContract, method: "function entrypoint() public view returns (address)" }); return entrypointAddress; } catch { return void 0; } } export { isSmartWallet, connectSmartWallet, disconnectSmartWallet }; //# sourceMappingURL=chunk-F2BEZVSV.js.map ================================================ FILE: 17-Crowd-Funding-Dapp/Frontend/.vite/deps_temp_6cf5ba4c/chunk-FHZU65JA.js ================================================ import { isERC1155, isERC721 } from "./chunk-QLCPWJYR.js"; import { EcosystemWalletConnectUI_default } from "./chunk-EGJT3UEX.js"; import { createWalletConnectClient, createWalletConnectSession, disconnectWalletConnectSession, getActiveWalletConnectSessions } from "./chunk-YG7T4W43.js"; import { AccentFailIcon, AnyWalletConnectUI, PoweredByThirdweb, QRCode, SmartConnectUI, TOS, WalletSelector, getDefaultWallets, wait } from "./chunk-7ZNEOXS2.js"; import { InputSelectionUI, LoadingScreen, ScreenSetupContext, compactModalMaxHeight, modalCloseFadeOutDuration, modalMaxWidthCompact, modalMaxWidthWide, onModalUnmount, reservedScreens, useActiveAccount, useSetupScreen, wideModalMaxHeight, wideModalScreenThreshold } from "./chunk-KWA5PGSC.js"; import { WalletLogoSpinner } from "./chunk-MGEBXLXC.js"; import { getProfiles } from "./chunk-65EUCVOP.js"; import { Fuse, createWallet, isMobile, useDebouncedValue, useShowMore } from "./chunk-HO57TQQM.js"; import { Input, Label, Spinner, WalletButtonEl, WalletUIStatesProvider, useIsWalletModalOpen, useSetIsWalletModalOpen, useSetSelectionData } from "./chunk-AARWH2GQ.js"; import { ArrowRightIcon, Button, ButtonLink, CheckCircledIcon, CheckIcon, ChevronDownIcon, ChevronRightIcon, ClockIcon, Container, CopyIcon, Cross1Icon, Cross2Icon, CrossCircledIcon, CustomThemeProvider, EmailIcon, ExitIcon, ExternalLinkIcon, FingerPrintIcon, IconButton, IdCardIcon, Img, Line, Link, MagnifyingGlassIcon, MinusIcon, ModalHeader, ModalTitle, OutlineWalletIcon, PaperPlaneIcon, PhoneIcon, PinBottomIcon, PlusIcon, RadiobuttonIcon, ReloadIcon, ShuffleIcon, Skeleton, Spacer, StyledButton, StyledDiv, StyledP, StyledUl, Text, TextAlignJustifyIcon, TriangleDownIcon, UNIVERSAL_RESOLVER_ADDRESS, WalletImage, fadeInAnimation, fontSize, genericTokenIcon, getLastAuthProvider, getSocialIcon, getWalletBalance, hasSponsoredTransactionsEnabled, iconSize, keyframes, media, namehash, newStyled, noScrollBar, packetToBytes, parseTheme, radius, resolve, setLastAuthProvider, shadow, spacing, useActiveWallet, useConnectedWalletDetails, useConnectionManager, useConnectionManagerCtx, useCustomTheme, useEnsAvatar, useEnsName, useMutation, useQueries, useQuery, useQueryClient, useSocialProfiles, useWalletBalance, useWalletInfo } from "./chunk-HI6IFF64.js"; import { require_jsx_runtime } from "./chunk-U3QNWT4A.js"; import { getCurrencyMetadata } from "./chunk-GGVPULQZ.js"; import { deleteConnectParamsFromStorage } from "./chunk-YGRUPXVB.js"; import { formatExplorerAddressUrl, formatExplorerTxUrl } from "./chunk-5U5XBS6S.js"; import { isEcosystemWallet } from "./chunk-XC5J5ANL.js"; import { getNFT } from "./chunk-36FW3ZLE.js"; import { getNFT as getNFT2 } from "./chunk-7ETS5GH6.js"; import { getInstalledWalletProviders, injectedProvider } from "./chunk-PWFRCBEK.js"; import { smartWallet } from "./chunk-2HYPHUAF.js"; import { isContractDeployed } from "./chunk-Q3TN3POE.js"; import { isInAppWallet } from "./chunk-O6KA6WKL.js"; import { ethereum } from "./chunk-ZLJ6VYSG.js"; import { decimals } from "./chunk-4RRAU5V7.js"; import { COINBASE } from "./chunk-BZXRHH4X.js"; import { socialAuthOptions } from "./chunk-EIBOABXT.js"; import { track } from "./chunk-N24CESYN.js"; import { ClientScopedStorage } from "./chunk-CYVKJMZE.js"; import { webLocalStorage } from "./chunk-VIBS7Y3M.js"; import { resolveArweaveScheme } from "./chunk-6FLJU7W7.js"; import { require_react_dom } from "./chunk-SJKAB62J.js"; import { require_react } from "./chunk-2MTJELC7.js"; import { estimateGasCost, getBuyWithCryptoQuote, getBuyWithCryptoStatus, getBuyWithCryptoTransfer, getPayBuyHistoryEndpoint, getPayBuyWithFiatQuoteEndpoint, getPayBuyWithFiatStatusEndpoint, getPaySupportedDestinations, getPaySupportedSources } from "./chunk-PHVX3XOV.js"; import { sendAndConfirmTransaction } from "./chunk-ADIC4TC2.js"; import { eth_getBalance } from "./chunk-4PEUWIWY.js"; import { once, prepareContractCall } from "./chunk-6XF6HOWC.js"; import { sendTransaction } from "./chunk-JTR2PIFP.js"; import { getGasPrice } from "./chunk-JZC47WAY.js"; import { resolvePromisedValue } from "./chunk-QC3K2OKT.js"; import { encode } from "./chunk-7QDK5KLB.js"; import { toTokens, toUnits, toWei } from "./chunk-UY2SRO54.js"; import { NATIVE_TOKEN_ADDRESS } from "./chunk-673YCYST.js"; import { waitForReceipt } from "./chunk-JBQP4JIV.js"; import { createStore, getTransactionStore } from "./chunk-3DBHE3NE.js"; import { resolveScheme } from "./chunk-ZNEQLT5Q.js"; import { getContract } from "./chunk-7VZHRFCE.js"; import { prepareTransaction } from "./chunk-CNLOA7AS.js"; import { readContract } from "./chunk-AG4NO6K6.js"; import { encodeAbiParameters } from "./chunk-U7TO6S3N.js"; import { getAddress, isAddress, shortenAddress, shortenHex } from "./chunk-EIVAOYE5.js"; import { getRpcClient } from "./chunk-I5DK3TWY.js"; import { stringify } from "./chunk-NJUWOGZE.js"; import { cacheChains, convertApiChainToChain, defineChain, getCachedChain, getChainDecimals, getChainMetadata, getChainNativeCurrencyName, getChainSymbol } from "./chunk-TFBEDS4S.js"; import { withCache } from "./chunk-GOA7IGSB.js"; import { getThirdwebDomains } from "./chunk-QHKZ43P6.js"; import { getClientFetch } from "./chunk-3GSJ2FQJ.js"; import { toHex } from "./chunk-BBNNHC5G.js"; import { hexToNumber } from "./chunk-SPELR2RL.js"; import { __toESM } from "./chunk-SEVZ5PBP.js"; // node_modules/thirdweb/dist/esm/react/web/ui/ConnectWallet/screens/Buy/BuyScreen.js var import_jsx_runtime99 = __toESM(require_jsx_runtime(), 1); var import_react60 = __toESM(require_react(), 1); // node_modules/thirdweb/dist/esm/pay/buyWithFiat/isSwapRequiredPostOnramp.js function isSwapRequiredPostOnramp(buyWithFiatQuote) { const sameChain = buyWithFiatQuote.toToken.chainId === buyWithFiatQuote.onRampToken.token.chainId; const sameToken = getAddress(buyWithFiatQuote.toToken.tokenAddress) === getAddress(buyWithFiatQuote.onRampToken.token.tokenAddress); return !(sameChain && sameToken); } // node_modules/thirdweb/dist/esm/utils/formatNumber.js function formatNumber(value, decimalPlaces) { if (value === 0) return 0; const precision = 10 ** decimalPlaces; const threshold = 1 / 10 ** decimalPlaces; const fn = value < threshold ? "ceil" : "round"; return Math[fn]((value + Number.EPSILON) * precision) / precision; } // node_modules/thirdweb/dist/esm/react/core/hooks/pay/useBuyWithCryptoQuote.js function useBuyWithCryptoQuote(params, queryParams) { return useQuery({ ...queryParams, queryKey: ["buyWithCryptoQuote", params], queryFn: () => { if (!params) { throw new Error("Swap params are required"); } return getBuyWithCryptoQuote(params); }, enabled: !!params, retry(failureCount, error) { if (failureCount > 3) { return false; } try { const serverError = error.error; if (serverError.code === "MINIMUM_PURCHASE_AMOUNT") { return false; } if (serverError.statusCode === 404 || serverError.statusCode >= 500) { return false; } } catch { return true; } return true; } }); } // node_modules/thirdweb/dist/esm/pay/buyWithFiat/getQuote.js async function getBuyWithFiatQuote(params) { try { const clientFetch = getClientFetch(params.client); const response = await clientFetch(getPayBuyWithFiatQuoteEndpoint(), { method: "POST", headers: { Accept: "application/json", "Content-Type": "application/json" }, body: stringify({ toAddress: params.toAddress, fromCurrencySymbol: params.fromCurrencySymbol, toChainId: params.toChainId.toString(), toTokenAddress: params.toTokenAddress, fromAmount: params.fromAmount, toAmount: params.toAmount, maxSlippageBPS: params.maxSlippageBPS, isTestMode: params.isTestMode, purchaseData: params.purchaseData, fromAddress: params.fromAddress, toGasAmountWei: params.toGasAmountWei, preferredProvider: params.preferredProvider }) }); if (!response.ok) { const errorObj = await response.json(); if (errorObj && "error" in errorObj) { throw errorObj; } throw new Error(`HTTP error! status: ${response.status}`); } return (await response.json()).result; } catch (error) { console.error("Error getting buy with fiat quote", error); throw error; } } // node_modules/thirdweb/dist/esm/react/core/hooks/pay/useBuyWithFiatQuote.js function useBuyWithFiatQuote(params, queryOptions) { return useQuery({ ...queryOptions, queryKey: ["useBuyWithFiatQuote", params], queryFn: async () => { if (!params) { throw new Error("No params provided"); } return getBuyWithFiatQuote(params); }, enabled: !!params, retry(failureCount, error) { if (failureCount > 3) { return false; } try { const serverError = error.error; if (serverError.code === "MINIMUM_PURCHASE_AMOUNT") { return false; } if (serverError.statusCode === 404 || serverError.statusCode >= 500) { return false; } } catch { return true; } return true; } }); } // node_modules/thirdweb/dist/esm/react/core/providers/invalidateWalletBalance.js function invalidateWalletBalance(queryClient, chainId) { return queryClient.invalidateQueries({ // invalidate any walletBalance queries for this chainId // TODO: add wallet address in here if we can get it somehow queryKey: chainId ? ["walletBalance", chainId] : ["walletBalance"] }); } // node_modules/thirdweb/dist/esm/react/web/ui/components/ChainName.js var import_jsx_runtime = __toESM(require_jsx_runtime(), 1); // node_modules/thirdweb/dist/esm/react/core/hooks/others/useChainQuery.js var import_react = __toESM(require_react(), 1); // node_modules/thirdweb/dist/esm/utils/promise/p-limit.js var Node2 = class { constructor(value) { Object.defineProperty(this, "value", { enumerable: true, configurable: true, writable: true, value: void 0 }); Object.defineProperty(this, "next", { enumerable: true, configurable: true, writable: true, value: void 0 }); this.value = value; } }; var Queue = class { constructor() { Object.defineProperty(this, "head", { enumerable: true, configurable: true, writable: true, value: void 0 }); Object.defineProperty(this, "tail", { enumerable: true, configurable: true, writable: true, value: void 0 }); Object.defineProperty(this, "size", { enumerable: true, configurable: true, writable: true, value: void 0 }); this.clear(); this.size = 0; } enqueue(value) { const node = new Node2(value); if (this.head) { if (this.tail) { this.tail.next = node; } this.tail = node; } else { this.head = node; this.tail = node; } this.size++; } dequeue() { var _a; const current = this.head; if (!current) { return; } this.head = (_a = this.head) == null ? void 0 : _a.next; this.size--; return current.value; } clear() { this.head = void 0; this.tail = void 0; this.size = 0; } *[Symbol.iterator]() { let current = this.head; while (current) { yield current.value; current = current.next; } } }; var AsyncResource = { bind(fn, _type, thisArg) { return fn.bind(thisArg); } }; function pLimit(concurrency) { if (!((Number.isInteger(concurrency) || concurrency === Number.POSITIVE_INFINITY) && concurrency > 0)) { throw new TypeError("Expected `concurrency` to be a number from 1 and up"); } const queue = new Queue(); let activeCount = 0; const next = () => { activeCount--; if (queue.size > 0) { const fn = queue.dequeue(); if (fn) { fn(); } } }; const run = async (function_, resolve2, arguments_) => { activeCount++; const result = (async () => function_(...arguments_))(); resolve2(result); try { await result; } catch { } next(); }; const enqueue = (function_, resolve2, arguments_) => { queue.enqueue(AsyncResource.bind(run.bind(void 0, function_, resolve2, arguments_))); (async () => { await Promise.resolve(); if (activeCount < concurrency && queue.size > 0) { const fn = queue.dequeue(); if (fn) { fn(); } } })(); }; const generator = (function_, ...arguments_) => new Promise((resolve2) => { enqueue(function_, resolve2, arguments_); }); Object.defineProperties(generator, { activeCount: { get: () => activeCount }, pendingCount: { get: () => queue.size }, clearQueue: { value() { queue.clear(); } } }); return generator; } // node_modules/thirdweb/dist/esm/react/core/hooks/others/useChainQuery.js function useChainName(chain) { var _a; const isEnabled = !!chain && !chain.name; const chainQuery = useQuery({ queryKey: ["chain", chain == null ? void 0 : chain.id], enabled: isEnabled, retry: false, // 1 hour staleTime: 60 * 60 * 1e3, queryFn: async () => { if (!chain) { throw new Error("chain is required"); } return convertApiChainToChain(await getChainMetadata(chain)); } }); return { name: (chain == null ? void 0 : chain.name) ?? ((_a = chainQuery.data) == null ? void 0 : _a.name), isLoading: isEnabled && chainQuery.isLoading }; } function useChainIconUrl(chain) { var _a, _b, _c, _d; const isEnabled = !!chain && !((_a = chain.icon) == null ? void 0 : _a.url); const chainQuery = useQuery({ queryKey: ["chain", chain == null ? void 0 : chain.id], // only if we have a chain and no chain icon url! enabled: isEnabled, retry: false, // 1 hour staleTime: 60 * 60 * 1e3, queryFn: async () => { if (!chain) { throw new Error("chain is required"); } return convertApiChainToChain(await getChainMetadata(chain)); } }); return { url: ((_b = chain == null ? void 0 : chain.icon) == null ? void 0 : _b.url) ?? ((_d = (_c = chainQuery.data) == null ? void 0 : _c.icon) == null ? void 0 : _d.url), isLoading: isEnabled && chainQuery.isLoading }; } function useChainFaucets(chain) { var _a, _b; const isEnabled = !!chain && "testnet" in chain && !((_a = chain.faucets) == null ? void 0 : _a.length) && chain.id !== 1337; const chainQuery = useQuery({ queryKey: ["chain", chain == null ? void 0 : chain.id], enabled: isEnabled, retry: false, // 1 hour staleTime: 60 * 60 * 1e3, queryFn: async () => { if (!chain) { throw new Error("chain is required"); } return convertApiChainToChain(await getChainMetadata(chain)); } }); return { faucets: (chain == null ? void 0 : chain.faucets) ?? ((_b = chainQuery.data) == null ? void 0 : _b.faucets) ?? [], isLoading: isEnabled && chainQuery.isLoading }; } function useChainSymbol(chain) { var _a, _b, _c, _d; const isEnabled = !!chain && !((_a = chain.nativeCurrency) == null ? void 0 : _a.symbol); const chainQuery = useQuery({ queryKey: ["chain", chain == null ? void 0 : chain.id], // only if we have a chain and no chain icon url! enabled: isEnabled, retry: false, // 1 hour staleTime: 60 * 60 * 1e3, queryFn: async () => { if (!chain) { throw new Error("chain is required"); } return convertApiChainToChain(await getChainMetadata(chain)); } }); return { symbol: ((_b = chain == null ? void 0 : chain.nativeCurrency) == null ? void 0 : _b.symbol) ?? ((_d = (_c = chainQuery.data) == null ? void 0 : _c.nativeCurrency) == null ? void 0 : _d.symbol), isLoading: isEnabled && chainQuery.isLoading }; } function useChainExplorers(chain) { var _a, _b; const isEnabled = !!chain && !((_a = chain.blockExplorers) == null ? void 0 : _a.length); const chainQuery = useQuery({ queryKey: ["chain", chain == null ? void 0 : chain.id], enabled: isEnabled, retry: false, // 1 hour staleTime: 60 * 60 * 1e3, queryFn: async () => { if (!chain) { throw new Error("chain is required"); } return convertApiChainToChain(await getChainMetadata(chain)); } }); return { explorers: (chain == null ? void 0 : chain.blockExplorers) ?? ((_b = chainQuery.data) == null ? void 0 : _b.blockExplorers) ?? [], isLoading: isEnabled && chainQuery.isLoading }; } function getQueryOptions(chain) { return { queryKey: ["chain", chain], enabled: !!chain, staleTime: 1e3 * 60 * 60 // 1 hour }; } function useChainMetadata(chain) { return useQuery({ ...getQueryOptions(chain), queryFn: async () => { if (!chain) { throw new Error("chainId is required"); } return getChainMetadata(chain); } }); } function useChainsQuery(chains, maxConcurrency) { const queryList = (0, import_react.useMemo)(() => { const limit = pLimit(maxConcurrency); return chains.map((chain) => { return { ...getQueryOptions(chain), queryFn: () => limit(() => getChainMetadata(chain)) }; }); }, [chains, maxConcurrency]); return useQueries({ queries: queryList }); } // node_modules/thirdweb/dist/esm/react/web/ui/components/ChainName.js var ChainName = (props) => { const { name } = useChainName(props.chain); if (name) { return (0, import_jsx_runtime.jsx)(Text, { size: props.size, children: props.short ? shorterChainName(name) : name }); } return (0, import_jsx_runtime.jsx)(Skeleton, { width: "50px", height: fontSize[props.size] }); }; function shorterChainName(name) { const split = name.split(" "); const wordsToRemove = /* @__PURE__ */ new Set(["mainnet", "testnet", "chain"]); return split.filter((s) => { return !wordsToRemove.has(s.toLowerCase()); }).join(" "); } // node_modules/thirdweb/dist/esm/react/web/ui/components/Drawer.js var import_jsx_runtime11 = __toESM(require_jsx_runtime(), 1); var import_react9 = __toESM(require_react(), 1); // node_modules/thirdweb/dist/esm/react/web/ui/components/DynamicHeight.js var import_jsx_runtime2 = __toESM(require_jsx_runtime(), 1); var import_react2 = __toESM(require_react(), 1); function DynamicHeight(props) { const { height, elementRef } = useHeightObserver(); return (0, import_jsx_runtime2.jsx)("div", { style: { height: height ? `${height}px` : "auto", transition: "height 210ms cubic-bezier(0.175, 0.885, 0.32, 1.1)", overflow: "hidden", boxSizing: "border-box" }, children: (0, import_jsx_runtime2.jsx)("div", { ref: elementRef, style: { maxHeight: props.maxHeight }, children: props.children }) }); } function useHeightObserver() { const elementRef = (0, import_react2.useRef)(null); const [height, setHeight] = (0, import_react2.useState)(); (0, import_react2.useEffect)(() => { const element = elementRef.current; if (!element) { return; } const resizeObserver = new ResizeObserver(() => { setHeight(element.scrollHeight); }); resizeObserver.observe(element); return () => { resizeObserver.disconnect(); }; }, []); return { height, elementRef }; } // node_modules/thirdweb/dist/esm/react/web/ui/components/Modal.js var import_jsx_runtime10 = __toESM(require_jsx_runtime(), 1); // node_modules/@radix-ui/react-dialog/dist/index.mjs var React25 = __toESM(require_react(), 1); // node_modules/@radix-ui/primitive/dist/index.mjs function composeEventHandlers(originalEventHandler, ourEventHandler, { checkForDefaultPrevented = true } = {}) { return function handleEvent(event) { originalEventHandler == null ? void 0 : originalEventHandler(event); if (checkForDefaultPrevented === false || !event.defaultPrevented) { return ourEventHandler == null ? void 0 : ourEventHandler(event); } }; } // node_modules/@radix-ui/react-compose-refs/dist/index.mjs var React = __toESM(require_react(), 1); function setRef(ref, value) { if (typeof ref === "function") { ref(value); } else if (ref !== null && ref !== void 0) { ref.current = value; } } function composeRefs(...refs) { return (node) => refs.forEach((ref) => setRef(ref, node)); } function useComposedRefs(...refs) { return React.useCallback(composeRefs(...refs), refs); } // node_modules/@radix-ui/react-context/dist/index.mjs var React2 = __toESM(require_react(), 1); var import_jsx_runtime3 = __toESM(require_jsx_runtime(), 1); function createContext2(rootComponentName, defaultContext) { const Context = React2.createContext(defaultContext); const Provider2 = (props) => { const { children, ...context } = props; const value = React2.useMemo(() => context, Object.values(context)); return (0, import_jsx_runtime3.jsx)(Context.Provider, { value, children }); }; Provider2.displayName = rootComponentName + "Provider"; function useContext22(consumerName) { const context = React2.useContext(Context); if (context) return context; if (defaultContext !== void 0) return defaultContext; throw new Error(`\`${consumerName}\` must be used within \`${rootComponentName}\``); } return [Provider2, useContext22]; } function createContextScope(scopeName, createContextScopeDeps = []) { let defaultContexts = []; function createContext32(rootComponentName, defaultContext) { const BaseContext = React2.createContext(defaultContext); const index2 = defaultContexts.length; defaultContexts = [...defaultContexts, defaultContext]; const Provider2 = (props) => { var _a; const { scope, children, ...context } = props; const Context = ((_a = scope == null ? void 0 : scope[scopeName]) == null ? void 0 : _a[index2]) || BaseContext; const value = React2.useMemo(() => context, Object.values(context)); return (0, import_jsx_runtime3.jsx)(Context.Provider, { value, children }); }; Provider2.displayName = rootComponentName + "Provider"; function useContext22(consumerName, scope) { var _a; const Context = ((_a = scope == null ? void 0 : scope[scopeName]) == null ? void 0 : _a[index2]) || BaseContext; const context = React2.useContext(Context); if (context) return context; if (defaultContext !== void 0) return defaultContext; throw new Error(`\`${consumerName}\` must be used within \`${rootComponentName}\``); } return [Provider2, useContext22]; } const createScope = () => { const scopeContexts = defaultContexts.map((defaultContext) => { return React2.createContext(defaultContext); }); return function useScope(scope) { const contexts = (scope == null ? void 0 : scope[scopeName]) || scopeContexts; return React2.useMemo( () => ({ [`__scope${scopeName}`]: { ...scope, [scopeName]: contexts } }), [scope, contexts] ); }; }; createScope.scopeName = scopeName; return [createContext32, composeContextScopes(createScope, ...createContextScopeDeps)]; } function composeContextScopes(...scopes) { const baseScope = scopes[0]; if (scopes.length === 1) return baseScope; const createScope = () => { const scopeHooks = scopes.map((createScope2) => ({ useScope: createScope2(), scopeName: createScope2.scopeName })); return function useComposedScopes(overrideScopes) { const nextScopes = scopeHooks.reduce((nextScopes2, { useScope, scopeName }) => { const scopeProps = useScope(overrideScopes); const currentScope = scopeProps[`__scope${scopeName}`]; return { ...nextScopes2, ...currentScope }; }, {}); return React2.useMemo(() => ({ [`__scope${baseScope.scopeName}`]: nextScopes }), [nextScopes]); }; }; createScope.scopeName = baseScope.scopeName; return createScope; } // node_modules/@radix-ui/react-id/dist/index.mjs var React4 = __toESM(require_react(), 1); // node_modules/@radix-ui/react-use-layout-effect/dist/index.mjs var React3 = __toESM(require_react(), 1); var useLayoutEffect2 = Boolean(globalThis == null ? void 0 : globalThis.document) ? React3.useLayoutEffect : () => { }; // node_modules/@radix-ui/react-id/dist/index.mjs var useReactId = React4["useId".toString()] || (() => void 0); var count = 0; function useId(deterministicId) { const [id, setId] = React4.useState(useReactId()); useLayoutEffect2(() => { if (!deterministicId) setId((reactId) => reactId ?? String(count++)); }, [deterministicId]); return deterministicId || (id ? `radix-${id}` : ""); } // node_modules/@radix-ui/react-use-controllable-state/dist/index.mjs var React6 = __toESM(require_react(), 1); // node_modules/@radix-ui/react-use-callback-ref/dist/index.mjs var React5 = __toESM(require_react(), 1); function useCallbackRef(callback) { const callbackRef = React5.useRef(callback); React5.useEffect(() => { callbackRef.current = callback; }); return React5.useMemo(() => (...args) => { var _a; return (_a = callbackRef.current) == null ? void 0 : _a.call(callbackRef, ...args); }, []); } // node_modules/@radix-ui/react-use-controllable-state/dist/index.mjs function useControllableState({ prop, defaultProp, onChange = () => { } }) { const [uncontrolledProp, setUncontrolledProp] = useUncontrolledState({ defaultProp, onChange }); const isControlled = prop !== void 0; const value = isControlled ? prop : uncontrolledProp; const handleChange = useCallbackRef(onChange); const setValue = React6.useCallback( (nextValue) => { if (isControlled) { const setter = nextValue; const value2 = typeof nextValue === "function" ? setter(prop) : nextValue; if (value2 !== prop) handleChange(value2); } else { setUncontrolledProp(nextValue); } }, [isControlled, prop, setUncontrolledProp, handleChange] ); return [value, setValue]; } function useUncontrolledState({ defaultProp, onChange }) { const uncontrolledState = React6.useState(defaultProp); const [value] = uncontrolledState; const prevValueRef = React6.useRef(value); const handleChange = useCallbackRef(onChange); React6.useEffect(() => { if (prevValueRef.current !== value) { handleChange(value); prevValueRef.current = value; } }, [value, prevValueRef, handleChange]); return uncontrolledState; } // node_modules/@radix-ui/react-dismissable-layer/dist/index.mjs var React10 = __toESM(require_react(), 1); // node_modules/@radix-ui/react-primitive/dist/index.mjs var React8 = __toESM(require_react(), 1); var ReactDOM = __toESM(require_react_dom(), 1); // node_modules/@radix-ui/react-slot/dist/index.mjs var React7 = __toESM(require_react(), 1); var import_jsx_runtime4 = __toESM(require_jsx_runtime(), 1); var Slot = React7.forwardRef((props, forwardedRef) => { const { children, ...slotProps } = props; const childrenArray = React7.Children.toArray(children); const slottable = childrenArray.find(isSlottable); if (slottable) { const newElement = slottable.props.children; const newChildren = childrenArray.map((child) => { if (child === slottable) { if (React7.Children.count(newElement) > 1) return React7.Children.only(null); return React7.isValidElement(newElement) ? newElement.props.children : null; } else { return child; } }); return (0, import_jsx_runtime4.jsx)(SlotClone, { ...slotProps, ref: forwardedRef, children: React7.isValidElement(newElement) ? React7.cloneElement(newElement, void 0, newChildren) : null }); } return (0, import_jsx_runtime4.jsx)(SlotClone, { ...slotProps, ref: forwardedRef, children }); }); Slot.displayName = "Slot"; var SlotClone = React7.forwardRef((props, forwardedRef) => { const { children, ...slotProps } = props; if (React7.isValidElement(children)) { const childrenRef = getElementRef(children); return React7.cloneElement(children, { ...mergeProps(slotProps, children.props), // @ts-ignore ref: forwardedRef ? composeRefs(forwardedRef, childrenRef) : childrenRef }); } return React7.Children.count(children) > 1 ? React7.Children.only(null) : null; }); SlotClone.displayName = "SlotClone"; var Slottable = ({ children }) => { return (0, import_jsx_runtime4.jsx)(import_jsx_runtime4.Fragment, { children }); }; function isSlottable(child) { return React7.isValidElement(child) && child.type === Slottable; } function mergeProps(slotProps, childProps) { const overrideProps = { ...childProps }; for (const propName in childProps) { const slotPropValue = slotProps[propName]; const childPropValue = childProps[propName]; const isHandler = /^on[A-Z]/.test(propName); if (isHandler) { if (slotPropValue && childPropValue) { overrideProps[propName] = (...args) => { childPropValue(...args); slotPropValue(...args); }; } else if (slotPropValue) { overrideProps[propName] = slotPropValue; } } else if (propName === "style") { overrideProps[propName] = { ...slotPropValue, ...childPropValue }; } else if (propName === "className") { overrideProps[propName] = [slotPropValue, childPropValue].filter(Boolean).join(" "); } } return { ...slotProps, ...overrideProps }; } function getElementRef(element) { var _a, _b; let getter = (_a = Object.getOwnPropertyDescriptor(element.props, "ref")) == null ? void 0 : _a.get; let mayWarn = getter && "isReactWarning" in getter && getter.isReactWarning; if (mayWarn) { return element.ref; } getter = (_b = Object.getOwnPropertyDescriptor(element, "ref")) == null ? void 0 : _b.get; mayWarn = getter && "isReactWarning" in getter && getter.isReactWarning; if (mayWarn) { return element.props.ref; } return element.props.ref || element.ref; } // node_modules/@radix-ui/react-primitive/dist/index.mjs var import_jsx_runtime5 = __toESM(require_jsx_runtime(), 1); var NODES = [ "a", "button", "div", "form", "h2", "h3", "img", "input", "label", "li", "nav", "ol", "p", "span", "svg", "ul" ]; var Primitive = NODES.reduce((primitive, node) => { const Node3 = React8.forwardRef((props, forwardedRef) => { const { asChild, ...primitiveProps } = props; const Comp = asChild ? Slot : node; if (typeof window !== "undefined") { window[Symbol.for("radix-ui")] = true; } return (0, import_jsx_runtime5.jsx)(Comp, { ...primitiveProps, ref: forwardedRef }); }); Node3.displayName = `Primitive.${node}`; return { ...primitive, [node]: Node3 }; }, {}); function dispatchDiscreteCustomEvent(target, event) { if (target) ReactDOM.flushSync(() => target.dispatchEvent(event)); } // node_modules/@radix-ui/react-use-escape-keydown/dist/index.mjs var React9 = __toESM(require_react(), 1); function useEscapeKeydown(onEscapeKeyDownProp, ownerDocument = globalThis == null ? void 0 : globalThis.document) { const onEscapeKeyDown = useCallbackRef(onEscapeKeyDownProp); React9.useEffect(() => { const handleKeyDown = (event) => { if (event.key === "Escape") { onEscapeKeyDown(event); } }; ownerDocument.addEventListener("keydown", handleKeyDown, { capture: true }); return () => ownerDocument.removeEventListener("keydown", handleKeyDown, { capture: true }); }, [onEscapeKeyDown, ownerDocument]); } // node_modules/@radix-ui/react-dismissable-layer/dist/index.mjs var import_jsx_runtime6 = __toESM(require_jsx_runtime(), 1); var DISMISSABLE_LAYER_NAME = "DismissableLayer"; var CONTEXT_UPDATE = "dismissableLayer.update"; var POINTER_DOWN_OUTSIDE = "dismissableLayer.pointerDownOutside"; var FOCUS_OUTSIDE = "dismissableLayer.focusOutside"; var originalBodyPointerEvents; var DismissableLayerContext = React10.createContext({ layers: /* @__PURE__ */ new Set(), layersWithOutsidePointerEventsDisabled: /* @__PURE__ */ new Set(), branches: /* @__PURE__ */ new Set() }); var DismissableLayer = React10.forwardRef( (props, forwardedRef) => { const { disableOutsidePointerEvents = false, onEscapeKeyDown, onPointerDownOutside, onFocusOutside, onInteractOutside, onDismiss, ...layerProps } = props; const context = React10.useContext(DismissableLayerContext); const [node, setNode] = React10.useState(null); const ownerDocument = (node == null ? void 0 : node.ownerDocument) ?? (globalThis == null ? void 0 : globalThis.document); const [, force] = React10.useState({}); const composedRefs = useComposedRefs(forwardedRef, (node2) => setNode(node2)); const layers = Array.from(context.layers); const [highestLayerWithOutsidePointerEventsDisabled] = [...context.layersWithOutsidePointerEventsDisabled].slice(-1); const highestLayerWithOutsidePointerEventsDisabledIndex = layers.indexOf(highestLayerWithOutsidePointerEventsDisabled); const index2 = node ? layers.indexOf(node) : -1; const isBodyPointerEventsDisabled = context.layersWithOutsidePointerEventsDisabled.size > 0; const isPointerEventsEnabled = index2 >= highestLayerWithOutsidePointerEventsDisabledIndex; const pointerDownOutside = usePointerDownOutside((event) => { const target = event.target; const isPointerDownOnBranch = [...context.branches].some((branch) => branch.contains(target)); if (!isPointerEventsEnabled || isPointerDownOnBranch) return; onPointerDownOutside == null ? void 0 : onPointerDownOutside(event); onInteractOutside == null ? void 0 : onInteractOutside(event); if (!event.defaultPrevented) onDismiss == null ? void 0 : onDismiss(); }, ownerDocument); const focusOutside = useFocusOutside((event) => { const target = event.target; const isFocusInBranch = [...context.branches].some((branch) => branch.contains(target)); if (isFocusInBranch) return; onFocusOutside == null ? void 0 : onFocusOutside(event); onInteractOutside == null ? void 0 : onInteractOutside(event); if (!event.defaultPrevented) onDismiss == null ? void 0 : onDismiss(); }, ownerDocument); useEscapeKeydown((event) => { const isHighestLayer = index2 === context.layers.size - 1; if (!isHighestLayer) return; onEscapeKeyDown == null ? void 0 : onEscapeKeyDown(event); if (!event.defaultPrevented && onDismiss) { event.preventDefault(); onDismiss(); } }, ownerDocument); React10.useEffect(() => { if (!node) return; if (disableOutsidePointerEvents) { if (context.layersWithOutsidePointerEventsDisabled.size === 0) { originalBodyPointerEvents = ownerDocument.body.style.pointerEvents; ownerDocument.body.style.pointerEvents = "none"; } context.layersWithOutsidePointerEventsDisabled.add(node); } context.layers.add(node); dispatchUpdate(); return () => { if (disableOutsidePointerEvents && context.layersWithOutsidePointerEventsDisabled.size === 1) { ownerDocument.body.style.pointerEvents = originalBodyPointerEvents; } }; }, [node, ownerDocument, disableOutsidePointerEvents, context]); React10.useEffect(() => { return () => { if (!node) return; context.layers.delete(node); context.layersWithOutsidePointerEventsDisabled.delete(node); dispatchUpdate(); }; }, [node, context]); React10.useEffect(() => { const handleUpdate = () => force({}); document.addEventListener(CONTEXT_UPDATE, handleUpdate); return () => document.removeEventListener(CONTEXT_UPDATE, handleUpdate); }, []); return (0, import_jsx_runtime6.jsx)( Primitive.div, { ...layerProps, ref: composedRefs, style: { pointerEvents: isBodyPointerEventsDisabled ? isPointerEventsEnabled ? "auto" : "none" : void 0, ...props.style }, onFocusCapture: composeEventHandlers(props.onFocusCapture, focusOutside.onFocusCapture), onBlurCapture: composeEventHandlers(props.onBlurCapture, focusOutside.onBlurCapture), onPointerDownCapture: composeEventHandlers( props.onPointerDownCapture, pointerDownOutside.onPointerDownCapture ) } ); } ); DismissableLayer.displayName = DISMISSABLE_LAYER_NAME; var BRANCH_NAME = "DismissableLayerBranch"; var DismissableLayerBranch = React10.forwardRef((props, forwardedRef) => { const context = React10.useContext(DismissableLayerContext); const ref = React10.useRef(null); const composedRefs = useComposedRefs(forwardedRef, ref); React10.useEffect(() => { const node = ref.current; if (node) { context.branches.add(node); return () => { context.branches.delete(node); }; } }, [context.branches]); return (0, import_jsx_runtime6.jsx)(Primitive.div, { ...props, ref: composedRefs }); }); DismissableLayerBranch.displayName = BRANCH_NAME; function usePointerDownOutside(onPointerDownOutside, ownerDocument = globalThis == null ? void 0 : globalThis.document) { const handlePointerDownOutside = useCallbackRef(onPointerDownOutside); const isPointerInsideReactTreeRef = React10.useRef(false); const handleClickRef = React10.useRef(() => { }); React10.useEffect(() => { const handlePointerDown = (event) => { if (event.target && !isPointerInsideReactTreeRef.current) { let handleAndDispatchPointerDownOutsideEvent2 = function() { handleAndDispatchCustomEvent( POINTER_DOWN_OUTSIDE, handlePointerDownOutside, eventDetail, { discrete: true } ); }; var handleAndDispatchPointerDownOutsideEvent = handleAndDispatchPointerDownOutsideEvent2; const eventDetail = { originalEvent: event }; if (event.pointerType === "touch") { ownerDocument.removeEventListener("click", handleClickRef.current); handleClickRef.current = handleAndDispatchPointerDownOutsideEvent2; ownerDocument.addEventListener("click", handleClickRef.current, { once: true }); } else { handleAndDispatchPointerDownOutsideEvent2(); } } else { ownerDocument.removeEventListener("click", handleClickRef.current); } isPointerInsideReactTreeRef.current = false; }; const timerId = window.setTimeout(() => { ownerDocument.addEventListener("pointerdown", handlePointerDown); }, 0); return () => { window.clearTimeout(timerId); ownerDocument.removeEventListener("pointerdown", handlePointerDown); ownerDocument.removeEventListener("click", handleClickRef.current); }; }, [ownerDocument, handlePointerDownOutside]); return { // ensures we check React component tree (not just DOM tree) onPointerDownCapture: () => isPointerInsideReactTreeRef.current = true }; } function useFocusOutside(onFocusOutside, ownerDocument = globalThis == null ? void 0 : globalThis.document) { const handleFocusOutside = useCallbackRef(onFocusOutside); const isFocusInsideReactTreeRef = React10.useRef(false); React10.useEffect(() => { const handleFocus = (event) => { if (event.target && !isFocusInsideReactTreeRef.current) { const eventDetail = { originalEvent: event }; handleAndDispatchCustomEvent(FOCUS_OUTSIDE, handleFocusOutside, eventDetail, { discrete: false }); } }; ownerDocument.addEventListener("focusin", handleFocus); return () => ownerDocument.removeEventListener("focusin", handleFocus); }, [ownerDocument, handleFocusOutside]); return { onFocusCapture: () => isFocusInsideReactTreeRef.current = true, onBlurCapture: () => isFocusInsideReactTreeRef.current = false }; } function dispatchUpdate() { const event = new CustomEvent(CONTEXT_UPDATE); document.dispatchEvent(event); } function handleAndDispatchCustomEvent(name, handler, detail, { discrete }) { const target = detail.originalEvent.target; const event = new CustomEvent(name, { bubbles: false, cancelable: true, detail }); if (handler) target.addEventListener(name, handler, { once: true }); if (discrete) { dispatchDiscreteCustomEvent(target, event); } else { target.dispatchEvent(event); } } // node_modules/@radix-ui/react-focus-scope/dist/index.mjs var React11 = __toESM(require_react(), 1); var import_jsx_runtime7 = __toESM(require_jsx_runtime(), 1); var AUTOFOCUS_ON_MOUNT = "focusScope.autoFocusOnMount"; var AUTOFOCUS_ON_UNMOUNT = "focusScope.autoFocusOnUnmount"; var EVENT_OPTIONS = { bubbles: false, cancelable: true }; var FOCUS_SCOPE_NAME = "FocusScope"; var FocusScope = React11.forwardRef((props, forwardedRef) => { const { loop = false, trapped = false, onMountAutoFocus: onMountAutoFocusProp, onUnmountAutoFocus: onUnmountAutoFocusProp, ...scopeProps } = props; const [container, setContainer] = React11.useState(null); const onMountAutoFocus = useCallbackRef(onMountAutoFocusProp); const onUnmountAutoFocus = useCallbackRef(onUnmountAutoFocusProp); const lastFocusedElementRef = React11.useRef(null); const composedRefs = useComposedRefs(forwardedRef, (node) => setContainer(node)); const focusScope = React11.useRef({ paused: false, pause() { this.paused = true; }, resume() { this.paused = false; } }).current; React11.useEffect(() => { if (trapped) { let handleFocusIn2 = function(event) { if (focusScope.paused || !container) return; const target = event.target; if (container.contains(target)) { lastFocusedElementRef.current = target; } else { focus(lastFocusedElementRef.current, { select: true }); } }, handleFocusOut2 = function(event) { if (focusScope.paused || !container) return; const relatedTarget = event.relatedTarget; if (relatedTarget === null) return; if (!container.contains(relatedTarget)) { focus(lastFocusedElementRef.current, { select: true }); } }, handleMutations2 = function(mutations) { const focusedElement = document.activeElement; if (focusedElement !== document.body) return; for (const mutation of mutations) { if (mutation.removedNodes.length > 0) focus(container); } }; var handleFocusIn = handleFocusIn2, handleFocusOut = handleFocusOut2, handleMutations = handleMutations2; document.addEventListener("focusin", handleFocusIn2); document.addEventListener("focusout", handleFocusOut2); const mutationObserver = new MutationObserver(handleMutations2); if (container) mutationObserver.observe(container, { childList: true, subtree: true }); return () => { document.removeEventListener("focusin", handleFocusIn2); document.removeEventListener("focusout", handleFocusOut2); mutationObserver.disconnect(); }; } }, [trapped, container, focusScope.paused]); React11.useEffect(() => { if (container) { focusScopesStack.add(focusScope); const previouslyFocusedElement = document.activeElement; const hasFocusedCandidate = container.contains(previouslyFocusedElement); if (!hasFocusedCandidate) { const mountEvent = new CustomEvent(AUTOFOCUS_ON_MOUNT, EVENT_OPTIONS); container.addEventListener(AUTOFOCUS_ON_MOUNT, onMountAutoFocus); container.dispatchEvent(mountEvent); if (!mountEvent.defaultPrevented) { focusFirst(removeLinks(getTabbableCandidates(container)), { select: true }); if (document.activeElement === previouslyFocusedElement) { focus(container); } } } return () => { container.removeEventListener(AUTOFOCUS_ON_MOUNT, onMountAutoFocus); setTimeout(() => { const unmountEvent = new CustomEvent(AUTOFOCUS_ON_UNMOUNT, EVENT_OPTIONS); container.addEventListener(AUTOFOCUS_ON_UNMOUNT, onUnmountAutoFocus); container.dispatchEvent(unmountEvent); if (!unmountEvent.defaultPrevented) { focus(previouslyFocusedElement ?? document.body, { select: true }); } container.removeEventListener(AUTOFOCUS_ON_UNMOUNT, onUnmountAutoFocus); focusScopesStack.remove(focusScope); }, 0); }; } }, [container, onMountAutoFocus, onUnmountAutoFocus, focusScope]); const handleKeyDown = React11.useCallback( (event) => { if (!loop && !trapped) return; if (focusScope.paused) return; const isTabKey = event.key === "Tab" && !event.altKey && !event.ctrlKey && !event.metaKey; const focusedElement = document.activeElement; if (isTabKey && focusedElement) { const container2 = event.currentTarget; const [first, last] = getTabbableEdges(container2); const hasTabbableElementsInside = first && last; if (!hasTabbableElementsInside) { if (focusedElement === container2) event.preventDefault(); } else { if (!event.shiftKey && focusedElement === last) { event.preventDefault(); if (loop) focus(first, { select: true }); } else if (event.shiftKey && focusedElement === first) { event.preventDefault(); if (loop) focus(last, { select: true }); } } } }, [loop, trapped, focusScope.paused] ); return (0, import_jsx_runtime7.jsx)(Primitive.div, { tabIndex: -1, ...scopeProps, ref: composedRefs, onKeyDown: handleKeyDown }); }); FocusScope.displayName = FOCUS_SCOPE_NAME; function focusFirst(candidates, { select = false } = {}) { const previouslyFocusedElement = document.activeElement; for (const candidate of candidates) { focus(candidate, { select }); if (document.activeElement !== previouslyFocusedElement) return; } } function getTabbableEdges(container) { const candidates = getTabbableCandidates(container); const first = findVisible(candidates, container); const last = findVisible(candidates.reverse(), container); return [first, last]; } function getTabbableCandidates(container) { const nodes = []; const walker = document.createTreeWalker(container, NodeFilter.SHOW_ELEMENT, { acceptNode: (node) => { const isHiddenInput = node.tagName === "INPUT" && node.type === "hidden"; if (node.disabled || node.hidden || isHiddenInput) return NodeFilter.FILTER_SKIP; return node.tabIndex >= 0 ? NodeFilter.FILTER_ACCEPT : NodeFilter.FILTER_SKIP; } }); while (walker.nextNode()) nodes.push(walker.currentNode); return nodes; } function findVisible(elements, container) { for (const element of elements) { if (!isHidden(element, { upTo: container })) return element; } } function isHidden(node, { upTo }) { if (getComputedStyle(node).visibility === "hidden") return true; while (node) { if (upTo !== void 0 && node === upTo) return false; if (getComputedStyle(node).display === "none") return true; node = node.parentElement; } return false; } function isSelectableInput(element) { return element instanceof HTMLInputElement && "select" in element; } function focus(element, { select = false } = {}) { if (element && element.focus) { const previouslyFocusedElement = document.activeElement; element.focus({ preventScroll: true }); if (element !== previouslyFocusedElement && isSelectableInput(element) && select) element.select(); } } var focusScopesStack = createFocusScopesStack(); function createFocusScopesStack() { let stack = []; return { add(focusScope) { const activeFocusScope = stack[0]; if (focusScope !== activeFocusScope) { activeFocusScope == null ? void 0 : activeFocusScope.pause(); } stack = arrayRemove(stack, focusScope); stack.unshift(focusScope); }, remove(focusScope) { var _a; stack = arrayRemove(stack, focusScope); (_a = stack[0]) == null ? void 0 : _a.resume(); } }; } function arrayRemove(array, item) { const updatedArray = [...array]; const index2 = updatedArray.indexOf(item); if (index2 !== -1) { updatedArray.splice(index2, 1); } return updatedArray; } function removeLinks(items) { return items.filter((item) => item.tagName !== "A"); } // node_modules/@radix-ui/react-portal/dist/index.mjs var React12 = __toESM(require_react(), 1); var import_react_dom = __toESM(require_react_dom(), 1); var import_jsx_runtime8 = __toESM(require_jsx_runtime(), 1); var PORTAL_NAME = "Portal"; var Portal = React12.forwardRef((props, forwardedRef) => { var _a; const { container: containerProp, ...portalProps } = props; const [mounted, setMounted] = React12.useState(false); useLayoutEffect2(() => setMounted(true), []); const container = containerProp || mounted && ((_a = globalThis == null ? void 0 : globalThis.document) == null ? void 0 : _a.body); return container ? import_react_dom.default.createPortal((0, import_jsx_runtime8.jsx)(Primitive.div, { ...portalProps, ref: forwardedRef }), container) : null; }); Portal.displayName = PORTAL_NAME; // node_modules/@radix-ui/react-presence/dist/index.mjs var React22 = __toESM(require_react(), 1); var React13 = __toESM(require_react(), 1); function useStateMachine(initialState, machine) { return React13.useReducer((state, event) => { const nextState = machine[state][event]; return nextState ?? state; }, initialState); } var Presence = (props) => { const { present, children } = props; const presence = usePresence(present); const child = typeof children === "function" ? children({ present: presence.isPresent }) : React22.Children.only(children); const ref = useComposedRefs(presence.ref, getElementRef2(child)); const forceMount = typeof children === "function"; return forceMount || presence.isPresent ? React22.cloneElement(child, { ref }) : null; }; Presence.displayName = "Presence"; function usePresence(present) { const [node, setNode] = React22.useState(); const stylesRef = React22.useRef({}); const prevPresentRef = React22.useRef(present); const prevAnimationNameRef = React22.useRef("none"); const initialState = present ? "mounted" : "unmounted"; const [state, send] = useStateMachine(initialState, { mounted: { UNMOUNT: "unmounted", ANIMATION_OUT: "unmountSuspended" }, unmountSuspended: { MOUNT: "mounted", ANIMATION_END: "unmounted" }, unmounted: { MOUNT: "mounted" } }); React22.useEffect(() => { const currentAnimationName = getAnimationName(stylesRef.current); prevAnimationNameRef.current = state === "mounted" ? currentAnimationName : "none"; }, [state]); useLayoutEffect2(() => { const styles = stylesRef.current; const wasPresent = prevPresentRef.current; const hasPresentChanged = wasPresent !== present; if (hasPresentChanged) { const prevAnimationName = prevAnimationNameRef.current; const currentAnimationName = getAnimationName(styles); if (present) { send("MOUNT"); } else if (currentAnimationName === "none" || (styles == null ? void 0 : styles.display) === "none") { send("UNMOUNT"); } else { const isAnimating = prevAnimationName !== currentAnimationName; if (wasPresent && isAnimating) { send("ANIMATION_OUT"); } else { send("UNMOUNT"); } } prevPresentRef.current = present; } }, [present, send]); useLayoutEffect2(() => { if (node) { let timeoutId; const ownerWindow = node.ownerDocument.defaultView ?? window; const handleAnimationEnd = (event) => { const currentAnimationName = getAnimationName(stylesRef.current); const isCurrentAnimation = currentAnimationName.includes(event.animationName); if (event.target === node && isCurrentAnimation) { send("ANIMATION_END"); if (!prevPresentRef.current) { const currentFillMode = node.style.animationFillMode; node.style.animationFillMode = "forwards"; timeoutId = ownerWindow.setTimeout(() => { if (node.style.animationFillMode === "forwards") { node.style.animationFillMode = currentFillMode; } }); } } }; const handleAnimationStart = (event) => { if (event.target === node) { prevAnimationNameRef.current = getAnimationName(stylesRef.current); } }; node.addEventListener("animationstart", handleAnimationStart); node.addEventListener("animationcancel", handleAnimationEnd); node.addEventListener("animationend", handleAnimationEnd); return () => { ownerWindow.clearTimeout(timeoutId); node.removeEventListener("animationstart", handleAnimationStart); node.removeEventListener("animationcancel", handleAnimationEnd); node.removeEventListener("animationend", handleAnimationEnd); }; } else { send("ANIMATION_END"); } }, [node, send]); return { isPresent: ["mounted", "unmountSuspended"].includes(state), ref: React22.useCallback((node2) => { if (node2) stylesRef.current = getComputedStyle(node2); setNode(node2); }, []) }; } function getAnimationName(styles) { return (styles == null ? void 0 : styles.animationName) || "none"; } function getElementRef2(element) { var _a, _b; let getter = (_a = Object.getOwnPropertyDescriptor(element.props, "ref")) == null ? void 0 : _a.get; let mayWarn = getter && "isReactWarning" in getter && getter.isReactWarning; if (mayWarn) { return element.ref; } getter = (_b = Object.getOwnPropertyDescriptor(element, "ref")) == null ? void 0 : _b.get; mayWarn = getter && "isReactWarning" in getter && getter.isReactWarning; if (mayWarn) { return element.props.ref; } return element.props.ref || element.ref; } // node_modules/@radix-ui/react-focus-guards/dist/index.mjs var React14 = __toESM(require_react(), 1); var count2 = 0; function useFocusGuards() { React14.useEffect(() => { const edgeGuards = document.querySelectorAll("[data-radix-focus-guard]"); document.body.insertAdjacentElement("afterbegin", edgeGuards[0] ?? createFocusGuard()); document.body.insertAdjacentElement("beforeend", edgeGuards[1] ?? createFocusGuard()); count2++; return () => { if (count2 === 1) { document.querySelectorAll("[data-radix-focus-guard]").forEach((node) => node.remove()); } count2--; }; }, []); } function createFocusGuard() { const element = document.createElement("span"); element.setAttribute("data-radix-focus-guard", ""); element.tabIndex = 0; element.style.outline = "none"; element.style.opacity = "0"; element.style.position = "fixed"; element.style.pointerEvents = "none"; return element; } // node_modules/react-remove-scroll/node_modules/tslib/tslib.es6.mjs var __assign = function() { __assign = Object.assign || function __assign3(t) { for (var s, i = 1, n = arguments.length; i < n; i++) { s = arguments[i]; for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p]; } return t; }; return __assign.apply(this, arguments); }; function __rest(s, e) { var t = {}; for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0) t[p] = s[p]; if (s != null && typeof Object.getOwnPropertySymbols === "function") for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) { if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i])) t[p[i]] = s[p[i]]; } return t; } function __spreadArray(to, from, pack) { if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) { if (ar || !(i in from)) { if (!ar) ar = Array.prototype.slice.call(from, 0, i); ar[i] = from[i]; } } return to.concat(ar || Array.prototype.slice.call(from)); } // node_modules/react-remove-scroll/dist/es2015/Combination.js var React24 = __toESM(require_react()); // node_modules/react-remove-scroll/dist/es2015/UI.js var React19 = __toESM(require_react()); // node_modules/react-remove-scroll-bar/dist/es2015/constants.js var zeroRightClassName = "right-scroll-bar-position"; var fullWidthClassName = "width-before-scroll-bar"; var noScrollbarsClassName = "with-scroll-bars-hidden"; var removedBarSizeVariable = "--removed-body-scroll-bar-size"; // node_modules/use-callback-ref/dist/es2015/assignRef.js function assignRef(ref, value) { if (typeof ref === "function") { ref(value); } else if (ref) { ref.current = value; } return ref; } // node_modules/use-callback-ref/dist/es2015/useRef.js var import_react3 = __toESM(require_react()); function useCallbackRef2(initialValue, callback) { var ref = (0, import_react3.useState)(function() { return { // value value: initialValue, // last callback callback, // "memoized" public interface facade: { get current() { return ref.value; }, set current(value) { var last = ref.value; if (last !== value) { ref.value = value; ref.callback(value, last); } } } }; })[0]; ref.callback = callback; return ref.facade; } // node_modules/use-callback-ref/dist/es2015/useMergeRef.js var React15 = __toESM(require_react()); var useIsomorphicLayoutEffect = typeof window !== "undefined" ? React15.useLayoutEffect : React15.useEffect; var currentValues = /* @__PURE__ */ new WeakMap(); function useMergeRefs(refs, defaultValue) { var callbackRef = useCallbackRef2(defaultValue || null, function(newValue) { return refs.forEach(function(ref) { return assignRef(ref, newValue); }); }); useIsomorphicLayoutEffect(function() { var oldValue = currentValues.get(callbackRef); if (oldValue) { var prevRefs_1 = new Set(oldValue); var nextRefs_1 = new Set(refs); var current_1 = callbackRef.current; prevRefs_1.forEach(function(ref) { if (!nextRefs_1.has(ref)) { assignRef(ref, null); } }); nextRefs_1.forEach(function(ref) { if (!prevRefs_1.has(ref)) { assignRef(ref, current_1); } }); } currentValues.set(callbackRef, refs); }, [refs]); return callbackRef; } // node_modules/use-sidecar/node_modules/tslib/tslib.es6.mjs var __assign2 = function() { __assign2 = Object.assign || function __assign3(t) { for (var s, i = 1, n = arguments.length; i < n; i++) { s = arguments[i]; for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p]; } return t; }; return __assign2.apply(this, arguments); }; function __rest2(s, e) { var t = {}; for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0) t[p] = s[p]; if (s != null && typeof Object.getOwnPropertySymbols === "function") for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) { if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i])) t[p[i]] = s[p[i]]; } return t; } // node_modules/use-sidecar/dist/es2015/hoc.js var React16 = __toESM(require_react()); // node_modules/use-sidecar/dist/es2015/hook.js var import_react4 = __toESM(require_react()); // node_modules/use-sidecar/dist/es2015/medium.js function ItoI(a) { return a; } function innerCreateMedium(defaults, middleware) { if (middleware === void 0) { middleware = ItoI; } var buffer = []; var assigned = false; var medium = { read: function() { if (assigned) { throw new Error("Sidecar: could not `read` from an `assigned` medium. `read` could be used only with `useMedium`."); } if (buffer.length) { return buffer[buffer.length - 1]; } return defaults; }, useMedium: function(data) { var item = middleware(data, assigned); buffer.push(item); return function() { buffer = buffer.filter(function(x) { return x !== item; }); }; }, assignSyncMedium: function(cb) { assigned = true; while (buffer.length) { var cbs = buffer; buffer = []; cbs.forEach(cb); } buffer = { push: function(x) { return cb(x); }, filter: function() { return buffer; } }; }, assignMedium: function(cb) { assigned = true; var pendingQueue = []; if (buffer.length) { var cbs = buffer; buffer = []; cbs.forEach(cb); pendingQueue = buffer; } var executeQueue = function() { var cbs2 = pendingQueue; pendingQueue = []; cbs2.forEach(cb); }; var cycle = function() { return Promise.resolve().then(executeQueue); }; cycle(); buffer = { push: function(x) { pendingQueue.push(x); cycle(); }, filter: function(filter) { pendingQueue = pendingQueue.filter(filter); return buffer; } }; } }; return medium; } function createSidecarMedium(options) { if (options === void 0) { options = {}; } var medium = innerCreateMedium(null); medium.options = __assign2({ async: true, ssr: false }, options); return medium; } // node_modules/use-sidecar/dist/es2015/renderProp.js var React17 = __toESM(require_react()); var import_react5 = __toESM(require_react()); // node_modules/use-sidecar/dist/es2015/exports.js var React18 = __toESM(require_react()); var SideCar = function(_a) { var sideCar = _a.sideCar, rest = __rest2(_a, ["sideCar"]); if (!sideCar) { throw new Error("Sidecar: please provide `sideCar` property to import the right car"); } var Target = sideCar.read(); if (!Target) { throw new Error("Sidecar medium not found"); } return React18.createElement(Target, __assign2({}, rest)); }; SideCar.isSideCarExport = true; function exportSidecar(medium, exported) { medium.useMedium(exported); return SideCar; } // node_modules/react-remove-scroll/dist/es2015/medium.js var effectCar = createSidecarMedium(); // node_modules/react-remove-scroll/dist/es2015/UI.js var nothing = function() { return; }; var RemoveScroll = React19.forwardRef(function(props, parentRef) { var ref = React19.useRef(null); var _a = React19.useState({ onScrollCapture: nothing, onWheelCapture: nothing, onTouchMoveCapture: nothing }), callbacks = _a[0], setCallbacks = _a[1]; var forwardProps = props.forwardProps, children = props.children, className = props.className, removeScrollBar = props.removeScrollBar, enabled = props.enabled, shards = props.shards, sideCar = props.sideCar, noIsolation = props.noIsolation, inert = props.inert, allowPinchZoom = props.allowPinchZoom, _b = props.as, Container2 = _b === void 0 ? "div" : _b, gapMode = props.gapMode, rest = __rest(props, ["forwardProps", "children", "className", "removeScrollBar", "enabled", "shards", "sideCar", "noIsolation", "inert", "allowPinchZoom", "as", "gapMode"]); var SideCar2 = sideCar; var containerRef = useMergeRefs([ref, parentRef]); var containerProps = __assign(__assign({}, rest), callbacks); return React19.createElement( React19.Fragment, null, enabled && React19.createElement(SideCar2, { sideCar: effectCar, removeScrollBar, shards, noIsolation, inert, setCallbacks, allowPinchZoom: !!allowPinchZoom, lockRef: ref, gapMode }), forwardProps ? React19.cloneElement(React19.Children.only(children), __assign(__assign({}, containerProps), { ref: containerRef })) : React19.createElement(Container2, __assign({}, containerProps, { className, ref: containerRef }), children) ); }); RemoveScroll.defaultProps = { enabled: true, removeScrollBar: true, inert: false }; RemoveScroll.classNames = { fullWidth: fullWidthClassName, zeroRight: zeroRightClassName }; // node_modules/react-remove-scroll/dist/es2015/SideEffect.js var React23 = __toESM(require_react()); // node_modules/react-remove-scroll-bar/dist/es2015/component.js var React21 = __toESM(require_react()); // node_modules/react-style-singleton/dist/es2015/hook.js var React20 = __toESM(require_react()); // node_modules/get-nonce/dist/es2015/index.js var currentNonce; var getNonce = function() { if (currentNonce) { return currentNonce; } if (typeof __webpack_nonce__ !== "undefined") { return __webpack_nonce__; } return void 0; }; // node_modules/react-style-singleton/dist/es2015/singleton.js function makeStyleTag() { if (!document) return null; var tag = document.createElement("style"); tag.type = "text/css"; var nonce = getNonce(); if (nonce) { tag.setAttribute("nonce", nonce); } return tag; } function injectStyles(tag, css) { if (tag.styleSheet) { tag.styleSheet.cssText = css; } else { tag.appendChild(document.createTextNode(css)); } } function insertStyleTag(tag) { var head = document.head || document.getElementsByTagName("head")[0]; head.appendChild(tag); } var stylesheetSingleton = function() { var counter = 0; var stylesheet = null; return { add: function(style) { if (counter == 0) { if (stylesheet = makeStyleTag()) { injectStyles(stylesheet, style); insertStyleTag(stylesheet); } } counter++; }, remove: function() { counter--; if (!counter && stylesheet) { stylesheet.parentNode && stylesheet.parentNode.removeChild(stylesheet); stylesheet = null; } } }; }; // node_modules/react-style-singleton/dist/es2015/hook.js var styleHookSingleton = function() { var sheet = stylesheetSingleton(); return function(styles, isDynamic) { React20.useEffect(function() { sheet.add(styles); return function() { sheet.remove(); }; }, [styles && isDynamic]); }; }; // node_modules/react-style-singleton/dist/es2015/component.js var styleSingleton = function() { var useStyle = styleHookSingleton(); var Sheet = function(_a) { var styles = _a.styles, dynamic = _a.dynamic; useStyle(styles, dynamic); return null; }; return Sheet; }; // node_modules/react-remove-scroll-bar/dist/es2015/utils.js var zeroGap = { left: 0, top: 0, right: 0, gap: 0 }; var parse = function(x) { return parseInt(x || "", 10) || 0; }; var getOffset = function(gapMode) { var cs = window.getComputedStyle(document.body); var left = cs[gapMode === "padding" ? "paddingLeft" : "marginLeft"]; var top = cs[gapMode === "padding" ? "paddingTop" : "marginTop"]; var right = cs[gapMode === "padding" ? "paddingRight" : "marginRight"]; return [parse(left), parse(top), parse(right)]; }; var getGapWidth = function(gapMode) { if (gapMode === void 0) { gapMode = "margin"; } if (typeof window === "undefined") { return zeroGap; } var offsets = getOffset(gapMode); var documentWidth = document.documentElement.clientWidth; var windowWidth = window.innerWidth; return { left: offsets[0], top: offsets[1], right: offsets[2], gap: Math.max(0, windowWidth - documentWidth + offsets[2] - offsets[0]) }; }; // node_modules/react-remove-scroll-bar/dist/es2015/component.js var Style = styleSingleton(); var lockAttribute = "data-scroll-locked"; var getStyles = function(_a, allowRelative, gapMode, important) { var left = _a.left, top = _a.top, right = _a.right, gap = _a.gap; if (gapMode === void 0) { gapMode = "margin"; } return "\n .".concat(noScrollbarsClassName, " {\n overflow: hidden ").concat(important, ";\n padding-right: ").concat(gap, "px ").concat(important, ";\n }\n body[").concat(lockAttribute, "] {\n overflow: hidden ").concat(important, ";\n overscroll-behavior: contain;\n ").concat([ allowRelative && "position: relative ".concat(important, ";"), gapMode === "margin" && "\n padding-left: ".concat(left, "px;\n padding-top: ").concat(top, "px;\n padding-right: ").concat(right, "px;\n margin-left:0;\n margin-top:0;\n margin-right: ").concat(gap, "px ").concat(important, ";\n "), gapMode === "padding" && "padding-right: ".concat(gap, "px ").concat(important, ";") ].filter(Boolean).join(""), "\n }\n \n .").concat(zeroRightClassName, " {\n right: ").concat(gap, "px ").concat(important, ";\n }\n \n .").concat(fullWidthClassName, " {\n margin-right: ").concat(gap, "px ").concat(important, ";\n }\n \n .").concat(zeroRightClassName, " .").concat(zeroRightClassName, " {\n right: 0 ").concat(important, ";\n }\n \n .").concat(fullWidthClassName, " .").concat(fullWidthClassName, " {\n margin-right: 0 ").concat(important, ";\n }\n \n body[").concat(lockAttribute, "] {\n ").concat(removedBarSizeVariable, ": ").concat(gap, "px;\n }\n"); }; var getCurrentUseCounter = function() { var counter = parseInt(document.body.getAttribute(lockAttribute) || "0", 10); return isFinite(counter) ? counter : 0; }; var useLockAttribute = function() { React21.useEffect(function() { document.body.setAttribute(lockAttribute, (getCurrentUseCounter() + 1).toString()); return function() { var newCounter = getCurrentUseCounter() - 1; if (newCounter <= 0) { document.body.removeAttribute(lockAttribute); } else { document.body.setAttribute(lockAttribute, newCounter.toString()); } }; }, []); }; var RemoveScrollBar = function(_a) { var noRelative = _a.noRelative, noImportant = _a.noImportant, _b = _a.gapMode, gapMode = _b === void 0 ? "margin" : _b; useLockAttribute(); var gap = React21.useMemo(function() { return getGapWidth(gapMode); }, [gapMode]); return React21.createElement(Style, { styles: getStyles(gap, !noRelative, gapMode, !noImportant ? "!important" : "") }); }; // node_modules/react-remove-scroll/dist/es2015/aggresiveCapture.js var passiveSupported = false; if (typeof window !== "undefined") { try { options = Object.defineProperty({}, "passive", { get: function() { passiveSupported = true; return true; } }); window.addEventListener("test", options, options); window.removeEventListener("test", options, options); } catch (err) { passiveSupported = false; } } var options; var nonPassive = passiveSupported ? { passive: false } : false; // node_modules/react-remove-scroll/dist/es2015/handleScroll.js var alwaysContainsScroll = function(node) { return node.tagName === "TEXTAREA"; }; var elementCanBeScrolled = function(node, overflow) { if (!(node instanceof Element)) { return false; } var styles = window.getComputedStyle(node); return ( // not-not-scrollable styles[overflow] !== "hidden" && // contains scroll inside self !(styles.overflowY === styles.overflowX && !alwaysContainsScroll(node) && styles[overflow] === "visible") ); }; var elementCouldBeVScrolled = function(node) { return elementCanBeScrolled(node, "overflowY"); }; var elementCouldBeHScrolled = function(node) { return elementCanBeScrolled(node, "overflowX"); }; var locationCouldBeScrolled = function(axis, node) { var ownerDocument = node.ownerDocument; var current = node; do { if (typeof ShadowRoot !== "undefined" && current instanceof ShadowRoot) { current = current.host; } var isScrollable = elementCouldBeScrolled(axis, current); if (isScrollable) { var _a = getScrollVariables(axis, current), scrollHeight = _a[1], clientHeight = _a[2]; if (scrollHeight > clientHeight) { return true; } } current = current.parentNode; } while (current && current !== ownerDocument.body); return false; }; var getVScrollVariables = function(_a) { var scrollTop = _a.scrollTop, scrollHeight = _a.scrollHeight, clientHeight = _a.clientHeight; return [ scrollTop, scrollHeight, clientHeight ]; }; var getHScrollVariables = function(_a) { var scrollLeft = _a.scrollLeft, scrollWidth = _a.scrollWidth, clientWidth = _a.clientWidth; return [ scrollLeft, scrollWidth, clientWidth ]; }; var elementCouldBeScrolled = function(axis, node) { return axis === "v" ? elementCouldBeVScrolled(node) : elementCouldBeHScrolled(node); }; var getScrollVariables = function(axis, node) { return axis === "v" ? getVScrollVariables(node) : getHScrollVariables(node); }; var getDirectionFactor = function(axis, direction) { return axis === "h" && direction === "rtl" ? -1 : 1; }; var handleScroll = function(axis, endTarget, event, sourceDelta, noOverscroll) { var directionFactor = getDirectionFactor(axis, window.getComputedStyle(endTarget).direction); var delta = directionFactor * sourceDelta; var target = event.target; var targetInLock = endTarget.contains(target); var shouldCancelScroll = false; var isDeltaPositive = delta > 0; var availableScroll = 0; var availableScrollTop = 0; do { var _a = getScrollVariables(axis, target), position = _a[0], scroll_1 = _a[1], capacity = _a[2]; var elementScroll = scroll_1 - capacity - directionFactor * position; if (position || elementScroll) { if (elementCouldBeScrolled(axis, target)) { availableScroll += elementScroll; availableScrollTop += position; } } if (target instanceof ShadowRoot) { target = target.host; } else { target = target.parentNode; } } while ( // portaled content !targetInLock && target !== document.body || // self content targetInLock && (endTarget.contains(target) || endTarget === target) ); if (isDeltaPositive && (noOverscroll && Math.abs(availableScroll) < 1 || !noOverscroll && delta > availableScroll)) { shouldCancelScroll = true; } else if (!isDeltaPositive && (noOverscroll && Math.abs(availableScrollTop) < 1 || !noOverscroll && -delta > availableScrollTop)) { shouldCancelScroll = true; } return shouldCancelScroll; }; // node_modules/react-remove-scroll/dist/es2015/SideEffect.js var getTouchXY = function(event) { return "changedTouches" in event ? [event.changedTouches[0].clientX, event.changedTouches[0].clientY] : [0, 0]; }; var getDeltaXY = function(event) { return [event.deltaX, event.deltaY]; }; var extractRef = function(ref) { return ref && "current" in ref ? ref.current : ref; }; var deltaCompare = function(x, y) { return x[0] === y[0] && x[1] === y[1]; }; var generateStyle = function(id) { return "\n .block-interactivity-".concat(id, " {pointer-events: none;}\n .allow-interactivity-").concat(id, " {pointer-events: all;}\n"); }; var idCounter = 0; var lockStack = []; function RemoveScrollSideCar(props) { var shouldPreventQueue = React23.useRef([]); var touchStartRef = React23.useRef([0, 0]); var activeAxis = React23.useRef(); var id = React23.useState(idCounter++)[0]; var Style2 = React23.useState(styleSingleton)[0]; var lastProps = React23.useRef(props); React23.useEffect(function() { lastProps.current = props; }, [props]); React23.useEffect(function() { if (props.inert) { document.body.classList.add("block-interactivity-".concat(id)); var allow_1 = __spreadArray([props.lockRef.current], (props.shards || []).map(extractRef), true).filter(Boolean); allow_1.forEach(function(el) { return el.classList.add("allow-interactivity-".concat(id)); }); return function() { document.body.classList.remove("block-interactivity-".concat(id)); allow_1.forEach(function(el) { return el.classList.remove("allow-interactivity-".concat(id)); }); }; } return; }, [props.inert, props.lockRef.current, props.shards]); var shouldCancelEvent = React23.useCallback(function(event, parent) { if ("touches" in event && event.touches.length === 2 || event.type === "wheel" && event.ctrlKey) { return !lastProps.current.allowPinchZoom; } var touch = getTouchXY(event); var touchStart = touchStartRef.current; var deltaX = "deltaX" in event ? event.deltaX : touchStart[0] - touch[0]; var deltaY = "deltaY" in event ? event.deltaY : touchStart[1] - touch[1]; var currentAxis; var target = event.target; var moveDirection = Math.abs(deltaX) > Math.abs(deltaY) ? "h" : "v"; if ("touches" in event && moveDirection === "h" && target.type === "range") { return false; } var canBeScrolledInMainDirection = locationCouldBeScrolled(moveDirection, target); if (!canBeScrolledInMainDirection) { return true; } if (canBeScrolledInMainDirection) { currentAxis = moveDirection; } else { currentAxis = moveDirection === "v" ? "h" : "v"; canBeScrolledInMainDirection = locationCouldBeScrolled(moveDirection, target); } if (!canBeScrolledInMainDirection) { return false; } if (!activeAxis.current && "changedTouches" in event && (deltaX || deltaY)) { activeAxis.current = currentAxis; } if (!currentAxis) { return true; } var cancelingAxis = activeAxis.current || currentAxis; return handleScroll(cancelingAxis, parent, event, cancelingAxis === "h" ? deltaX : deltaY, true); }, []); var shouldPrevent = React23.useCallback(function(_event) { var event = _event; if (!lockStack.length || lockStack[lockStack.length - 1] !== Style2) { return; } var delta = "deltaY" in event ? getDeltaXY(event) : getTouchXY(event); var sourceEvent = shouldPreventQueue.current.filter(function(e) { return e.name === event.type && (e.target === event.target || event.target === e.shadowParent) && deltaCompare(e.delta, delta); })[0]; if (sourceEvent && sourceEvent.should) { if (event.cancelable) { event.preventDefault(); } return; } if (!sourceEvent) { var shardNodes = (lastProps.current.shards || []).map(extractRef).filter(Boolean).filter(function(node) { return node.contains(event.target); }); var shouldStop = shardNodes.length > 0 ? shouldCancelEvent(event, shardNodes[0]) : !lastProps.current.noIsolation; if (shouldStop) { if (event.cancelable) { event.preventDefault(); } } } }, []); var shouldCancel = React23.useCallback(function(name, delta, target, should) { var event = { name, delta, target, should, shadowParent: getOutermostShadowParent(target) }; shouldPreventQueue.current.push(event); setTimeout(function() { shouldPreventQueue.current = shouldPreventQueue.current.filter(function(e) { return e !== event; }); }, 1); }, []); var scrollTouchStart = React23.useCallback(function(event) { touchStartRef.current = getTouchXY(event); activeAxis.current = void 0; }, []); var scrollWheel = React23.useCallback(function(event) { shouldCancel(event.type, getDeltaXY(event), event.target, shouldCancelEvent(event, props.lockRef.current)); }, []); var scrollTouchMove = React23.useCallback(function(event) { shouldCancel(event.type, getTouchXY(event), event.target, shouldCancelEvent(event, props.lockRef.current)); }, []); React23.useEffect(function() { lockStack.push(Style2); props.setCallbacks({ onScrollCapture: scrollWheel, onWheelCapture: scrollWheel, onTouchMoveCapture: scrollTouchMove }); document.addEventListener("wheel", shouldPrevent, nonPassive); document.addEventListener("touchmove", shouldPrevent, nonPassive); document.addEventListener("touchstart", scrollTouchStart, nonPassive); return function() { lockStack = lockStack.filter(function(inst) { return inst !== Style2; }); document.removeEventListener("wheel", shouldPrevent, nonPassive); document.removeEventListener("touchmove", shouldPrevent, nonPassive); document.removeEventListener("touchstart", scrollTouchStart, nonPassive); }; }, []); var removeScrollBar = props.removeScrollBar, inert = props.inert; return React23.createElement( React23.Fragment, null, inert ? React23.createElement(Style2, { styles: generateStyle(id) }) : null, removeScrollBar ? React23.createElement(RemoveScrollBar, { gapMode: props.gapMode }) : null ); } function getOutermostShadowParent(node) { var shadowParent = null; while (node !== null) { if (node instanceof ShadowRoot) { shadowParent = node.host; node = node.host; } node = node.parentNode; } return shadowParent; } // node_modules/react-remove-scroll/dist/es2015/sidecar.js var sidecar_default = exportSidecar(effectCar, RemoveScrollSideCar); // node_modules/react-remove-scroll/dist/es2015/Combination.js var ReactRemoveScroll = React24.forwardRef(function(props, ref) { return React24.createElement(RemoveScroll, __assign({}, props, { ref, sideCar: sidecar_default })); }); ReactRemoveScroll.classNames = RemoveScroll.classNames; var Combination_default = ReactRemoveScroll; // node_modules/aria-hidden/dist/es2015/index.js var getDefaultParent = function(originalTarget) { if (typeof document === "undefined") { return null; } var sampleTarget = Array.isArray(originalTarget) ? originalTarget[0] : originalTarget; return sampleTarget.ownerDocument.body; }; var counterMap = /* @__PURE__ */ new WeakMap(); var uncontrolledNodes = /* @__PURE__ */ new WeakMap(); var markerMap = {}; var lockCount = 0; var unwrapHost = function(node) { return node && (node.host || unwrapHost(node.parentNode)); }; var correctTargets = function(parent, targets) { return targets.map(function(target) { if (parent.contains(target)) { return target; } var correctedTarget = unwrapHost(target); if (correctedTarget && parent.contains(correctedTarget)) { return correctedTarget; } console.error("aria-hidden", target, "in not contained inside", parent, ". Doing nothing"); return null; }).filter(function(x) { return Boolean(x); }); }; var applyAttributeToOthers = function(originalTarget, parentNode, markerName, controlAttribute) { var targets = correctTargets(parentNode, Array.isArray(originalTarget) ? originalTarget : [originalTarget]); if (!markerMap[markerName]) { markerMap[markerName] = /* @__PURE__ */ new WeakMap(); } var markerCounter = markerMap[markerName]; var hiddenNodes = []; var elementsToKeep = /* @__PURE__ */ new Set(); var elementsToStop = new Set(targets); var keep = function(el) { if (!el || elementsToKeep.has(el)) { return; } elementsToKeep.add(el); keep(el.parentNode); }; targets.forEach(keep); var deep = function(parent) { if (!parent || elementsToStop.has(parent)) { return; } Array.prototype.forEach.call(parent.children, function(node) { if (elementsToKeep.has(node)) { deep(node); } else { try { var attr = node.getAttribute(controlAttribute); var alreadyHidden = attr !== null && attr !== "false"; var counterValue = (counterMap.get(node) || 0) + 1; var markerValue = (markerCounter.get(node) || 0) + 1; counterMap.set(node, counterValue); markerCounter.set(node, markerValue); hiddenNodes.push(node); if (counterValue === 1 && alreadyHidden) { uncontrolledNodes.set(node, true); } if (markerValue === 1) { node.setAttribute(markerName, "true"); } if (!alreadyHidden) { node.setAttribute(controlAttribute, "true"); } } catch (e) { console.error("aria-hidden: cannot operate on ", node, e); } } }); }; deep(parentNode); elementsToKeep.clear(); lockCount++; return function() { hiddenNodes.forEach(function(node) { var counterValue = counterMap.get(node) - 1; var markerValue = markerCounter.get(node) - 1; counterMap.set(node, counterValue); markerCounter.set(node, markerValue); if (!counterValue) { if (!uncontrolledNodes.has(node)) { node.removeAttribute(controlAttribute); } uncontrolledNodes.delete(node); } if (!markerValue) { node.removeAttribute(markerName); } }); lockCount--; if (!lockCount) { counterMap = /* @__PURE__ */ new WeakMap(); counterMap = /* @__PURE__ */ new WeakMap(); uncontrolledNodes = /* @__PURE__ */ new WeakMap(); markerMap = {}; } }; }; var hideOthers = function(originalTarget, parentNode, markerName) { if (markerName === void 0) { markerName = "data-aria-hidden"; } var targets = Array.from(Array.isArray(originalTarget) ? originalTarget : [originalTarget]); var activeParentNode = parentNode || getDefaultParent(originalTarget); if (!activeParentNode) { return function() { return null; }; } targets.push.apply(targets, Array.from(activeParentNode.querySelectorAll("[aria-live]"))); return applyAttributeToOthers(targets, activeParentNode, markerName, "aria-hidden"); }; // node_modules/@radix-ui/react-dialog/dist/index.mjs var import_jsx_runtime9 = __toESM(require_jsx_runtime(), 1); var DIALOG_NAME = "Dialog"; var [createDialogContext, createDialogScope] = createContextScope(DIALOG_NAME); var [DialogProvider, useDialogContext] = createDialogContext(DIALOG_NAME); var Dialog = (props) => { const { __scopeDialog, children, open: openProp, defaultOpen, onOpenChange, modal = true } = props; const triggerRef = React25.useRef(null); const contentRef = React25.useRef(null); const [open = false, setOpen] = useControllableState({ prop: openProp, defaultProp: defaultOpen, onChange: onOpenChange }); return (0, import_jsx_runtime9.jsx)( DialogProvider, { scope: __scopeDialog, triggerRef, contentRef, contentId: useId(), titleId: useId(), descriptionId: useId(), open, onOpenChange: setOpen, onOpenToggle: React25.useCallback(() => setOpen((prevOpen) => !prevOpen), [setOpen]), modal, children } ); }; Dialog.displayName = DIALOG_NAME; var TRIGGER_NAME = "DialogTrigger"; var DialogTrigger = React25.forwardRef( (props, forwardedRef) => { const { __scopeDialog, ...triggerProps } = props; const context = useDialogContext(TRIGGER_NAME, __scopeDialog); const composedTriggerRef = useComposedRefs(forwardedRef, context.triggerRef); return (0, import_jsx_runtime9.jsx)( Primitive.button, { type: "button", "aria-haspopup": "dialog", "aria-expanded": context.open, "aria-controls": context.contentId, "data-state": getState(context.open), ...triggerProps, ref: composedTriggerRef, onClick: composeEventHandlers(props.onClick, context.onOpenToggle) } ); } ); DialogTrigger.displayName = TRIGGER_NAME; var PORTAL_NAME2 = "DialogPortal"; var [PortalProvider, usePortalContext] = createDialogContext(PORTAL_NAME2, { forceMount: void 0 }); var DialogPortal = (props) => { const { __scopeDialog, forceMount, children, container } = props; const context = useDialogContext(PORTAL_NAME2, __scopeDialog); return (0, import_jsx_runtime9.jsx)(PortalProvider, { scope: __scopeDialog, forceMount, children: React25.Children.map(children, (child) => (0, import_jsx_runtime9.jsx)(Presence, { present: forceMount || context.open, children: (0, import_jsx_runtime9.jsx)(Portal, { asChild: true, container, children: child }) })) }); }; DialogPortal.displayName = PORTAL_NAME2; var OVERLAY_NAME = "DialogOverlay"; var DialogOverlay = React25.forwardRef( (props, forwardedRef) => { const portalContext = usePortalContext(OVERLAY_NAME, props.__scopeDialog); const { forceMount = portalContext.forceMount, ...overlayProps } = props; const context = useDialogContext(OVERLAY_NAME, props.__scopeDialog); return context.modal ? (0, import_jsx_runtime9.jsx)(Presence, { present: forceMount || context.open, children: (0, import_jsx_runtime9.jsx)(DialogOverlayImpl, { ...overlayProps, ref: forwardedRef }) }) : null; } ); DialogOverlay.displayName = OVERLAY_NAME; var DialogOverlayImpl = React25.forwardRef( (props, forwardedRef) => { const { __scopeDialog, ...overlayProps } = props; const context = useDialogContext(OVERLAY_NAME, __scopeDialog); return ( // Make sure `Content` is scrollable even when it doesn't live inside `RemoveScroll` // ie. when `Overlay` and `Content` are siblings (0, import_jsx_runtime9.jsx)(Combination_default, { as: Slot, allowPinchZoom: true, shards: [context.contentRef], children: (0, import_jsx_runtime9.jsx)( Primitive.div, { "data-state": getState(context.open), ...overlayProps, ref: forwardedRef, style: { pointerEvents: "auto", ...overlayProps.style } } ) }) ); } ); var CONTENT_NAME = "DialogContent"; var DialogContent = React25.forwardRef( (props, forwardedRef) => { const portalContext = usePortalContext(CONTENT_NAME, props.__scopeDialog); const { forceMount = portalContext.forceMount, ...contentProps } = props; const context = useDialogContext(CONTENT_NAME, props.__scopeDialog); return (0, import_jsx_runtime9.jsx)(Presence, { present: forceMount || context.open, children: context.modal ? (0, import_jsx_runtime9.jsx)(DialogContentModal, { ...contentProps, ref: forwardedRef }) : (0, import_jsx_runtime9.jsx)(DialogContentNonModal, { ...contentProps, ref: forwardedRef }) }); } ); DialogContent.displayName = CONTENT_NAME; var DialogContentModal = React25.forwardRef( (props, forwardedRef) => { const context = useDialogContext(CONTENT_NAME, props.__scopeDialog); const contentRef = React25.useRef(null); const composedRefs = useComposedRefs(forwardedRef, context.contentRef, contentRef); React25.useEffect(() => { const content = contentRef.current; if (content) return hideOthers(content); }, []); return (0, import_jsx_runtime9.jsx)( DialogContentImpl, { ...props, ref: composedRefs, trapFocus: context.open, disableOutsidePointerEvents: true, onCloseAutoFocus: composeEventHandlers(props.onCloseAutoFocus, (event) => { var _a; event.preventDefault(); (_a = context.triggerRef.current) == null ? void 0 : _a.focus(); }), onPointerDownOutside: composeEventHandlers(props.onPointerDownOutside, (event) => { const originalEvent = event.detail.originalEvent; const ctrlLeftClick = originalEvent.button === 0 && originalEvent.ctrlKey === true; const isRightClick = originalEvent.button === 2 || ctrlLeftClick; if (isRightClick) event.preventDefault(); }), onFocusOutside: composeEventHandlers( props.onFocusOutside, (event) => event.preventDefault() ) } ); } ); var DialogContentNonModal = React25.forwardRef( (props, forwardedRef) => { const context = useDialogContext(CONTENT_NAME, props.__scopeDialog); const hasInteractedOutsideRef = React25.useRef(false); const hasPointerDownOutsideRef = React25.useRef(false); return (0, import_jsx_runtime9.jsx)( DialogContentImpl, { ...props, ref: forwardedRef, trapFocus: false, disableOutsidePointerEvents: false, onCloseAutoFocus: (event) => { var _a, _b; (_a = props.onCloseAutoFocus) == null ? void 0 : _a.call(props, event); if (!event.defaultPrevented) { if (!hasInteractedOutsideRef.current) (_b = context.triggerRef.current) == null ? void 0 : _b.focus(); event.preventDefault(); } hasInteractedOutsideRef.current = false; hasPointerDownOutsideRef.current = false; }, onInteractOutside: (event) => { var _a, _b; (_a = props.onInteractOutside) == null ? void 0 : _a.call(props, event); if (!event.defaultPrevented) { hasInteractedOutsideRef.current = true; if (event.detail.originalEvent.type === "pointerdown") { hasPointerDownOutsideRef.current = true; } } const target = event.target; const targetIsTrigger = (_b = context.triggerRef.current) == null ? void 0 : _b.contains(target); if (targetIsTrigger) event.preventDefault(); if (event.detail.originalEvent.type === "focusin" && hasPointerDownOutsideRef.current) { event.preventDefault(); } } } ); } ); var DialogContentImpl = React25.forwardRef( (props, forwardedRef) => { const { __scopeDialog, trapFocus, onOpenAutoFocus, onCloseAutoFocus, ...contentProps } = props; const context = useDialogContext(CONTENT_NAME, __scopeDialog); const contentRef = React25.useRef(null); const composedRefs = useComposedRefs(forwardedRef, contentRef); useFocusGuards(); return (0, import_jsx_runtime9.jsxs)(import_jsx_runtime9.Fragment, { children: [ (0, import_jsx_runtime9.jsx)( FocusScope, { asChild: true, loop: true, trapped: trapFocus, onMountAutoFocus: onOpenAutoFocus, onUnmountAutoFocus: onCloseAutoFocus, children: (0, import_jsx_runtime9.jsx)( DismissableLayer, { role: "dialog", id: context.contentId, "aria-describedby": context.descriptionId, "aria-labelledby": context.titleId, "data-state": getState(context.open), ...contentProps, ref: composedRefs, onDismiss: () => context.onOpenChange(false) } ) } ), (0, import_jsx_runtime9.jsxs)(import_jsx_runtime9.Fragment, { children: [ (0, import_jsx_runtime9.jsx)(TitleWarning, { titleId: context.titleId }), (0, import_jsx_runtime9.jsx)(DescriptionWarning, { contentRef, descriptionId: context.descriptionId }) ] }) ] }); } ); var TITLE_NAME = "DialogTitle"; var DialogTitle = React25.forwardRef( (props, forwardedRef) => { const { __scopeDialog, ...titleProps } = props; const context = useDialogContext(TITLE_NAME, __scopeDialog); return (0, import_jsx_runtime9.jsx)(Primitive.h2, { id: context.titleId, ...titleProps, ref: forwardedRef }); } ); DialogTitle.displayName = TITLE_NAME; var DESCRIPTION_NAME = "DialogDescription"; var DialogDescription = React25.forwardRef( (props, forwardedRef) => { const { __scopeDialog, ...descriptionProps } = props; const context = useDialogContext(DESCRIPTION_NAME, __scopeDialog); return (0, import_jsx_runtime9.jsx)(Primitive.p, { id: context.descriptionId, ...descriptionProps, ref: forwardedRef }); } ); DialogDescription.displayName = DESCRIPTION_NAME; var CLOSE_NAME = "DialogClose"; var DialogClose = React25.forwardRef( (props, forwardedRef) => { const { __scopeDialog, ...closeProps } = props; const context = useDialogContext(CLOSE_NAME, __scopeDialog); return (0, import_jsx_runtime9.jsx)( Primitive.button, { type: "button", ...closeProps, ref: forwardedRef, onClick: composeEventHandlers(props.onClick, () => context.onOpenChange(false)) } ); } ); DialogClose.displayName = CLOSE_NAME; function getState(open) { return open ? "open" : "closed"; } var TITLE_WARNING_NAME = "DialogTitleWarning"; var [WarningProvider, useWarningContext] = createContext2(TITLE_WARNING_NAME, { contentName: CONTENT_NAME, titleName: TITLE_NAME, docsSlug: "dialog" }); var TitleWarning = ({ titleId }) => { const titleWarningContext = useWarningContext(TITLE_WARNING_NAME); const MESSAGE = `\`${titleWarningContext.contentName}\` requires a \`${titleWarningContext.titleName}\` for the component to be accessible for screen reader users. If you want to hide the \`${titleWarningContext.titleName}\`, you can wrap it with our VisuallyHidden component. For more information, see https://radix-ui.com/primitives/docs/components/${titleWarningContext.docsSlug}`; React25.useEffect(() => { if (titleId) { const hasTitle = document.getElementById(titleId); if (!hasTitle) console.error(MESSAGE); } }, [MESSAGE, titleId]); return null; }; var DESCRIPTION_WARNING_NAME = "DialogDescriptionWarning"; var DescriptionWarning = ({ contentRef, descriptionId }) => { const descriptionWarningContext = useWarningContext(DESCRIPTION_WARNING_NAME); const MESSAGE = `Warning: Missing \`Description\` or \`aria-describedby={undefined}\` for {${descriptionWarningContext.contentName}}.`; React25.useEffect(() => { var _a; const describedById = (_a = contentRef.current) == null ? void 0 : _a.getAttribute("aria-describedby"); if (descriptionId && describedById) { const hasDescription = document.getElementById(descriptionId); if (!hasDescription) console.warn(MESSAGE); } }, [MESSAGE, contentRef, descriptionId]); return null; }; var Root = Dialog; var Trigger = DialogTrigger; var Portal2 = DialogPortal; var Overlay = DialogOverlay; var Content = DialogContent; var Title = DialogTitle; var Close = DialogClose; // node_modules/thirdweb/dist/esm/react/web/ui/components/Modal.js var import_react7 = __toESM(require_react(), 1); // node_modules/thirdweb/dist/esm/react/web/ui/components/Overlay.js var Overlay2 = StyledDiv((_) => { const theme = useCustomTheme(); return { backgroundColor: theme.colors.modalOverlayBg, zIndex: 9999, position: "fixed", inset: 0, animation: `${fadeInAnimation} 400ms cubic-bezier(0.16, 1, 0.3, 1)`, backdropFilter: "blur(10px)" }; }); // node_modules/thirdweb/dist/esm/react/web/ui/components/Modal.js var Modal = (props) => { const [open, setOpen] = (0, import_react7.useState)(props.open); const contentRef = (0, import_react7.useRef)(null); const overlayRef = (0, import_react7.useRef)(null); (0, import_react7.useEffect)(() => { var _a; if (!props.open) { if (contentRef.current) { const animationConfig = { duration: modalCloseFadeOutDuration, fill: "forwards", easing: "ease" }; contentRef.current.animate([{ opacity: 0 }], { ...animationConfig }).onfinish = () => { setOpen(false); }; (_a = overlayRef.current) == null ? void 0 : _a.animate([{ opacity: 0 }], { ...animationConfig, duration: modalCloseFadeOutDuration + 100 }); } else { setOpen(props.open); } } else { setOpen(props.open); } }, [props.open]); return (0, import_jsx_runtime10.jsxs)(Root, { open, onOpenChange: props.setOpen, children: [props.trigger && (0, import_jsx_runtime10.jsx)(Trigger, { asChild: true, children: props.trigger }), (0, import_jsx_runtime10.jsxs)(Portal2, { children: [!props.hide && (0, import_jsx_runtime10.jsx)(Overlay, { asChild: true, children: (0, import_jsx_runtime10.jsx)(Overlay2, { ref: overlayRef }) }), (0, import_jsx_runtime10.jsx)(FocusScope, { trapped: !props.hide, children: (0, import_jsx_runtime10.jsx)(Content, { asChild: true, "aria-describedby": void 0, children: (0, import_jsx_runtime10.jsxs)(DialogContent2, { ref: contentRef, style: props.hide ? { width: 0, height: 0, overflow: "hidden", opacity: 0 } : { height: props.size === "compact" ? "auto" : wideModalMaxHeight, maxWidth: props.size === "compact" ? modalMaxWidthCompact : modalMaxWidthWide }, children: [(0, import_jsx_runtime10.jsx)(Title, { style: { position: "absolute", width: "1px", height: "1px", padding: 0, margin: "-1px", overflow: "hidden", clip: "rect(0, 0, 0, 0)", whiteSpace: "nowrap", borderWidth: 0 }, children: "Connect Modal" }), props.size === "compact" ? (0, import_jsx_runtime10.jsx)(DynamicHeight, { maxHeight: compactModalMaxHeight, children: props.children }) : props.children, !props.hideCloseIcon && (0, import_jsx_runtime10.jsx)(CrossContainer, { children: (0, import_jsx_runtime10.jsx)(Close, { asChild: true, children: (0, import_jsx_runtime10.jsx)(IconButton, { autoFocus: true, type: "button", "aria-label": "Close", children: (0, import_jsx_runtime10.jsx)(Cross2Icon, { width: iconSize.md, height: iconSize.md, style: { color: "inherit" } }) }) }) })] }) }) })] })] }); }; var CrossContainer = StyledDiv({ position: "absolute", top: spacing.lg, right: spacing.lg, transform: "translateX(6px)" }); var modalAnimationDesktop = keyframes` from { opacity: 0; transform: translate(-50%, -48%) scale(0.96); } to { opacity: 1; transform: translate(-50%, -50%) scale(1); } `; var modalAnimationMobile = keyframes` from { opacity: 0; transform: translate(0, 50%); } to { opacity: 1; transform: translate(0, 0); } `; var DialogContent2 = StyledDiv((_) => { const theme = useCustomTheme(); return { zIndex: 1e4, background: theme.colors.modalBg, "--bg": theme.colors.modalBg, color: theme.colors.primaryText, borderRadius: radius.lg, position: "fixed", top: "50%", left: "50%", transform: "translate(-50%, -50%)", width: "calc(100vw - 40px)", boxSizing: "border-box", animation: `${modalAnimationDesktop} 300ms ease`, boxShadow: shadow.lg, lineHeight: "normal", border: `1px solid ${theme.colors.borderColor}`, outline: "none", overflow: "hidden", fontFamily: theme.fontFamily, "& *": { boxSizing: "border-box" }, [media.mobile]: { top: "auto", bottom: 0, left: 0, right: 0, transform: "none", width: "100vw", animation: `${modalAnimationMobile} 0.35s cubic-bezier(0.15, 1.15, 0.6, 1)`, borderRadius: radius.xl, borderBottomRightRadius: 0, borderBottomLeftRadius: 0, maxWidth: "none !important" }, "& *::selection": { backgroundColor: theme.colors.selectedTextBg, color: theme.colors.selectedTextColor }, ...noScrollBar }; }); // node_modules/thirdweb/dist/esm/react/web/ui/components/Drawer.js var Drawer = (0, import_react9.forwardRef)(function Drawer_(props, ref) { return (0, import_jsx_runtime11.jsx)(DrawerContainer, { ref, children: (0, import_jsx_runtime11.jsx)(DynamicHeight, { children: (0, import_jsx_runtime11.jsxs)(Container, { p: "lg", children: [(0, import_jsx_runtime11.jsx)(CrossContainer, { children: (0, import_jsx_runtime11.jsx)(IconButton, { type: "button", "aria-label": "Close", onClick: props.close, children: (0, import_jsx_runtime11.jsx)(Cross2Icon, { width: iconSize.md, height: iconSize.md, style: { color: "inherit" } }) }) }), props.children] }) }) }); }); var DrawerContainer = StyledDiv((_) => { const theme = useCustomTheme(); return { zIndex: 1e4, borderTopLeftRadius: radius.xl, borderTopRightRadius: radius.xl, background: theme.colors.modalBg, position: "absolute", bottom: 0, left: 0, right: 0, animation: `${drawerOpenAnimation} 0.3s cubic-bezier(0.175, 0.885, 0.32, 1.1)`, borderTop: `1px solid ${theme.colors.borderColor}` }; }); var drawerOpenAnimation = keyframes` from { opacity: 0; transform: translateY(100px); } to { opacity: 1; transform: translateY(0); } `; var DrawerOverlay = StyledDiv((_) => { const theme = useCustomTheme(); return { backgroundColor: theme.colors.modalOverlayBg, zIndex: 9999, position: "absolute", inset: 0, animation: `${fadeInAnimation} 400ms cubic-bezier(0.16, 1, 0.3, 1)` }; }); function useDrawer() { const [isOpen, _setIsOpen] = (0, import_react9.useState)(false); const drawerRef = (0, import_react9.useRef)(null); const drawerOverlayRef = (0, import_react9.useRef)(null); const closeDrawerAnimation = (0, import_react9.useCallback)(() => { return new Promise((resolve2) => { var _a; if (drawerRef.current) { const animOptions = { easing: "cubic-bezier(0.175, 0.885, 0.32, 1.1)", fill: "forwards", duration: 300 }; const closeAnimation = drawerRef.current.animate([{ transform: "translateY(100%)", opacity: 0 }], animOptions); (_a = drawerOverlayRef.current) == null ? void 0 : _a.animate([{ opacity: 0 }], animOptions); closeAnimation.onfinish = () => resolve2(); } else { resolve2(); } }); }, []); const setIsOpen = (0, import_react9.useCallback)(async (value) => { if (value) { _setIsOpen(true); } else { await closeDrawerAnimation(); _setIsOpen(false); } }, [closeDrawerAnimation]); (0, import_react9.useLayoutEffect)(() => { if (!isOpen) { return; } const handleClick = (event) => { if (drawerRef.current && event.target instanceof Node && !drawerRef.current.contains(event.target)) { setIsOpen(false); } }; requestAnimationFrame(() => { document.addEventListener("click", handleClick); }); return () => { document.removeEventListener("click", handleClick); }; }, [isOpen, setIsOpen]); return { drawerRef, drawerOverlayRef, setIsOpen, isOpen }; } // node_modules/thirdweb/dist/esm/react/web/ui/components/SwitchNetwork.js var import_jsx_runtime12 = __toESM(require_jsx_runtime(), 1); var import_react10 = __toESM(require_react(), 1); function SwitchNetworkButton(props) { const [isSwitching, setIsSwitching] = (0, import_react10.useState)(false); return (0, import_jsx_runtime12.jsx)(Button, { ...props, gap: "xs", onClick: async () => { setIsSwitching(true); try { await props.switchChain(); } catch { } setIsSwitching(false); }, children: isSwitching ? (0, import_jsx_runtime12.jsxs)(import_jsx_runtime12.Fragment, { children: ["Switching", (0, import_jsx_runtime12.jsx)(Spinner, { size: "sm", color: "accentButtonText" })] }) : "Switch Network" }); } // node_modules/thirdweb/dist/esm/react/web/ui/components/token/TokenSymbol.js var import_jsx_runtime13 = __toESM(require_jsx_runtime(), 1); // node_modules/thirdweb/dist/esm/react/web/ui/ConnectWallet/screens/nativeToken.js var NATIVE_TOKEN = { nativeToken: true }; function isNativeToken(token) { var _a; return "nativeToken" in token || ((_a = token.address) == null ? void 0 : _a.toLowerCase()) === NATIVE_TOKEN_ADDRESS.toLowerCase(); } // node_modules/thirdweb/dist/esm/react/web/ui/components/token/TokenSymbol.js function TokenSymbol(props) { if (!isNativeToken(props.token)) { return (0, import_jsx_runtime13.jsx)(Text, { size: props.size, color: props.color || "primaryText", inline: props.inline, children: props.token.symbol }); } return (0, import_jsx_runtime13.jsx)(NativeTokenSymbol, { chain: props.chain, size: props.size, color: props.color, inline: props.inline }); } function NativeTokenSymbol(props) { const chainSymbolQuery = useChainSymbol(props.chain); if (chainSymbolQuery.isLoading) { return (0, import_jsx_runtime13.jsx)(Skeleton, { width: "70px", height: fontSize[props.size] }); } return (0, import_jsx_runtime13.jsx)(Text, { size: props.size, color: props.color || "primaryText", inline: props.inline, children: chainSymbolQuery.symbol ?? "ETH" }); } // node_modules/thirdweb/dist/esm/react/web/ui/ConnectWallet/ConnectButton.js var import_jsx_runtime84 = __toESM(require_jsx_runtime(), 1); var import_react51 = __toESM(require_react(), 1); // node_modules/thirdweb/dist/esm/react/core/hooks/auth/useSiweAuth.js function useSiweAuth(activeWallet, activeAccount, authOptions) { const requiresAuth = !!authOptions; const queryClient = useQueryClient(); const isLoggedInQuery = useQuery({ queryKey: ["siwe_auth", "isLoggedIn", activeAccount == null ? void 0 : activeAccount.address], enabled: requiresAuth && !!(activeAccount == null ? void 0 : activeAccount.address), queryFn: () => { if (!authOptions || !(activeAccount == null ? void 0 : activeAccount.address)) { return false; } return authOptions.isLoggedIn(activeAccount.address); }, gcTime: 0, placeholderData: false, refetchOnWindowFocus: false }); const loginMutation = useMutation({ mutationKey: ["siwe_auth", "login", activeAccount == null ? void 0 : activeAccount.address], mutationFn: async () => { if (!authOptions) { throw new Error("No auth options provided"); } if (!activeWallet) { throw new Error("No active wallet"); } const chain = activeWallet.getChain(); if (!chain) { throw new Error("No active chain"); } if (!activeAccount) { throw new Error("No active account"); } const [payload, { signLoginPayload }] = await Promise.all([ authOptions.getLoginPayload({ address: activeAccount.address, chainId: chain.id }), // we lazy-load this because it's only needed when logging in import("./sign-login-payload-EEOP3RDN.js") ]); if (payload.chain_id) { await activeWallet.switchChain(getCachedChain(Number(payload.chain_id))); } const signedPayload = await signLoginPayload({ payload, account: activeAccount }); return await authOptions.doLogin(signedPayload); }, onSettled: () => { return queryClient.invalidateQueries({ queryKey: ["siwe_auth", "isLoggedIn"] }); } }); const logoutMutation = useMutation({ mutationKey: ["siwe_auth", "logout", activeAccount == null ? void 0 : activeAccount.address], mutationFn: async () => { if (!authOptions) { throw new Error("No auth options provided"); } return await authOptions.doLogout(); }, onSettled: () => { return queryClient.invalidateQueries({ queryKey: ["siwe_auth", "isLoggedIn"] }); } }); return { // is auth even enabled requiresAuth, // login doLogin: loginMutation.mutateAsync, isLoggingIn: loginMutation.isPending, // logout doLogout: logoutMutation.mutateAsync, isLoggingOut: logoutMutation.isPending, // checking if logged in isLoggedIn: isLoggedInQuery.data, isLoading: isLoggedInQuery.isFetching }; } // node_modules/thirdweb/dist/esm/react/core/hooks/wallets/useActiveWalletConnectionStatus.js var import_react11 = __toESM(require_react(), 1); function useActiveWalletConnectionStatus() { const manager = useConnectionManagerCtx("useActiveWalletConnectionStatus"); const store = manager.activeWalletConnectionStatusStore; return (0, import_react11.useSyncExternalStore)(store.subscribe, store.getValue, store.getValue); } // node_modules/thirdweb/dist/esm/react/core/utils/defaultTokens.js var wrappedEthIcon = "data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHdpZHRoPSIyNTAwIiBoZWlnaHQ9IjI1MDAiIHZpZXdCb3g9IjAgMCAzMiAzMiI+PGcgZmlsbD0ibm9uZSIgZmlsbC1ydWxlPSJldmVub2RkIj48Y2lyY2xlIGN4PSIxNiIgY3k9IjE2IiByPSIxNiIgZmlsbD0iIzYyN0VFQSIvPjxnIGZpbGw9IiNGRkYiIGZpbGwtcnVsZT0ibm9uemVybyI+PHBhdGggZmlsbC1vcGFjaXR5PSIuNjAyIiBkPSJNMTYuNDk4IDR2OC44N2w3LjQ5NyAzLjM1eiIvPjxwYXRoIGQ9Ik0xNi40OTggNEw5IDE2LjIybDcuNDk4LTMuMzV6Ii8+PHBhdGggZmlsbC1vcGFjaXR5PSIuNjAyIiBkPSJNMTYuNDk4IDIxLjk2OHY2LjAyN0wyNCAxNy42MTZ6Ii8+PHBhdGggZD0iTTE2LjQ5OCAyNy45OTV2LTYuMDI4TDkgMTcuNjE2eiIvPjxwYXRoIGZpbGwtb3BhY2l0eT0iLjIiIGQ9Ik0xNi40OTggMjAuNTczbDcuNDk3LTQuMzUzLTcuNDk3LTMuMzQ4eiIvPjxwYXRoIGZpbGwtb3BhY2l0eT0iLjYwMiIgZD0iTTkgMTYuMjJsNy40OTggNC4zNTN2LTcuNzAxeiIvPjwvZz48L2c+PC9zdmc+"; var tetherUsdIcon = "data:image/svg+xml;base64,PHN2ZyBpZD0iTGF5ZXJfMSIgZGF0YS1uYW1lPSJMYXllciAxIiB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHZpZXdCb3g9IjAgMCAzMzkuNDMgMjk1LjI3Ij48dGl0bGU+dGV0aGVyLXVzZHQtbG9nbzwvdGl0bGU+PHBhdGggZD0iTTYyLjE1LDEuNDVsLTYxLjg5LDEzMGEyLjUyLDIuNTIsMCwwLDAsLjU0LDIuOTRMMTY3Ljk1LDI5NC41NmEyLjU1LDIuNTUsMCwwLDAsMy41MywwTDMzOC42MywxMzQuNGEyLjUyLDIuNTIsMCwwLDAsLjU0LTIuOTRsLTYxLjg5LTEzMEEyLjUsMi41LDAsMCwwLDI3NSwwSDY0LjQ1YTIuNSwyLjUsMCwwLDAtMi4zLDEuNDVoMFoiIHN0eWxlPSJmaWxsOiM1MGFmOTU7ZmlsbC1ydWxlOmV2ZW5vZGQiLz48cGF0aCBkPSJNMTkxLjE5LDE0NC44djBjLTEuMi4wOS03LjQsMC40Ni0yMS4yMywwLjQ2LTExLDAtMTguODEtLjMzLTIxLjU1LTAuNDZ2MGMtNDIuNTEtMS44Ny03NC4yNC05LjI3LTc0LjI0LTE4LjEzczMxLjczLTE2LjI1LDc0LjI0LTE4LjE1djI4LjkxYzIuNzgsMC4yLDEwLjc0LjY3LDIxLjc0LDAuNjcsMTMuMiwwLDE5LjgxLS41NSwyMS0wLjY2di0yOC45YzQyLjQyLDEuODksNzQuMDgsOS4yOSw3NC4wOCwxOC4xM3MtMzEuNjUsMTYuMjQtNzQuMDgsMTguMTJoMFptMC0zOS4yNVY3OS42OGg1OS4yVjQwLjIzSDg5LjIxVjc5LjY4SDE0OC40djI1Ljg2Yy00OC4xMSwyLjIxLTg0LjI5LDExLjc0LTg0LjI5LDIzLjE2czM2LjE4LDIwLjk0LDg0LjI5LDIzLjE2djgyLjloNDIuNzhWMTUxLjgzYzQ4LTIuMjEsODQuMTItMTEuNzMsODQuMTItMjMuMTRzLTM2LjA5LTIwLjkzLTg0LjEyLTIzLjE1aDBabTAsMGgwWiIgc3R5bGU9ImZpbGw6I2ZmZjtmaWxsLXJ1bGU6ZXZlbm9kZCIvPjwvc3ZnPg=="; var usdcIcon = "data:image/svg+xml;base64,PHN2ZyBkYXRhLW5hbWU9Ijg2OTc3Njg0LTEyZGItNDg1MC04ZjMwLTIzM2E3YzI2N2QxMSIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIiB2aWV3Qm94PSIwIDAgMjAwMCAyMDAwIj4KICA8cGF0aCBkPSJNMTAwMCAyMDAwYzU1NC4xNyAwIDEwMDAtNDQ1LjgzIDEwMDAtMTAwMFMxNTU0LjE3IDAgMTAwMCAwIDAgNDQ1LjgzIDAgMTAwMHM0NDUuODMgMTAwMCAxMDAwIDEwMDB6IiBmaWxsPSIjMjc3NWNhIi8+CiAgPHBhdGggZD0iTTEyNzUgMTE1OC4zM2MwLTE0NS44My04Ny41LTE5NS44My0yNjIuNS0yMTYuNjYtMTI1LTE2LjY3LTE1MC01MC0xNTAtMTA4LjM0czQxLjY3LTk1LjgzIDEyNS05NS44M2M3NSAwIDExNi42NyAyNSAxMzcuNSA4Ny41IDQuMTcgMTIuNSAxNi42NyAyMC44MyAyOS4xNyAyMC44M2g2Ni42NmMxNi42NyAwIDI5LjE3LTEyLjUgMjkuMTctMjkuMTZ2LTQuMTdjLTE2LjY3LTkxLjY3LTkxLjY3LTE2Mi41LTE4Ny41LTE3MC44M3YtMTAwYzAtMTYuNjctMTIuNS0yOS4xNy0zMy4zMy0zMy4zNGgtNjIuNWMtMTYuNjcgMC0yOS4xNyAxMi41LTMzLjM0IDMzLjM0djk1LjgzYy0xMjUgMTYuNjctMjA0LjE2IDEwMC0yMDQuMTYgMjA0LjE3IDAgMTM3LjUgODMuMzMgMTkxLjY2IDI1OC4zMyAyMTIuNSAxMTYuNjcgMjAuODMgMTU0LjE3IDQ1LjgzIDE1NC4xNyAxMTIuNXMtNTguMzQgMTEyLjUtMTM3LjUgMTEyLjVjLTEwOC4zNCAwLTE0NS44NC00NS44NC0xNTguMzQtMTA4LjM0LTQuMTYtMTYuNjYtMTYuNjYtMjUtMjkuMTYtMjVoLTcwLjg0Yy0xNi42NiAwLTI5LjE2IDEyLjUtMjkuMTYgMjkuMTd2NC4xN2MxNi42NiAxMDQuMTYgODMuMzMgMTc5LjE2IDIyMC44MyAyMDB2MTAwYzAgMTYuNjYgMTIuNSAyOS4xNiAzMy4zMyAzMy4zM2g2Mi41YzE2LjY3IDAgMjkuMTctMTIuNSAzMy4zNC0zMy4zM3YtMTAwYzEyNS0yMC44NCAyMDguMzMtMTA4LjM0IDIwOC4zMy0yMjAuODR6IiBmaWxsPSIjZmZmIi8+CiAgPHBhdGggZD0iTTc4Ny41IDE1OTUuODNjLTMyNS0xMTYuNjYtNDkxLjY3LTQ3OS4xNi0zNzAuODMtODAwIDYyLjUtMTc1IDIwMC0zMDguMzMgMzcwLjgzLTM3MC44MyAxNi42Ny04LjMzIDI1LTIwLjgzIDI1LTQxLjY3VjMyNWMwLTE2LjY3LTguMzMtMjkuMTctMjUtMzMuMzMtNC4xNyAwLTEyLjUgMC0xNi42NyA0LjE2LTM5NS44MyAxMjUtNjEyLjUgNTQ1Ljg0LTQ4Ny41IDk0MS42NyA3NSAyMzMuMzMgMjU0LjE3IDQxMi41IDQ4Ny41IDQ4Ny41IDE2LjY3IDguMzMgMzMuMzQgMCAzNy41LTE2LjY3IDQuMTctNC4xNiA0LjE3LTguMzMgNC4xNy0xNi42NnYtNTguMzRjMC0xMi41LTEyLjUtMjkuMTYtMjUtMzcuNXpNMTIyOS4xNyAyOTUuODNjLTE2LjY3LTguMzMtMzMuMzQgMC0zNy41IDE2LjY3LTQuMTcgNC4xNy00LjE3IDguMzMtNC4xNyAxNi42N3Y1OC4zM2MwIDE2LjY3IDEyLjUgMzMuMzMgMjUgNDEuNjcgMzI1IDExNi42NiA0OTEuNjcgNDc5LjE2IDM3MC44MyA4MDAtNjIuNSAxNzUtMjAwIDMwOC4zMy0zNzAuODMgMzcwLjgzLTE2LjY3IDguMzMtMjUgMjAuODMtMjUgNDEuNjdWMTcwMGMwIDE2LjY3IDguMzMgMjkuMTcgMjUgMzMuMzMgNC4xNyAwIDEyLjUgMCAxNi42Ny00LjE2IDM5NS44My0xMjUgNjEyLjUtNTQ1Ljg0IDQ4Ny41LTk0MS42Ny03NS0yMzcuNS0yNTguMzQtNDE2LjY3LTQ4Ny41LTQ5MS42N3oiIGZpbGw9IiNmZmYiLz4KPC9zdmc+Cg=="; var wrappedBtcIcon = "data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHZpZXdCb3g9IjAgMCAxMDkuMjYgMTA5LjI2Ij48ZGVmcz48c3R5bGU+LmNscy0xe2ZpbGw6IzVhNTU2NDt9LmNscy0ye2ZpbGw6I2YwOTI0Mjt9LmNscy0ze2ZpbGw6IzI4MjEzODt9PC9zdHlsZT48L2RlZnM+PHRpdGxlPndyYXBwZWQtYml0Y29pbi13YnRjPC90aXRsZT48ZyBpZD0iTGF5ZXJfMiIgZGF0YS1uYW1lPSJMYXllciAyIj48ZyBpZD0iTGF5ZXJfMS0yIiBkYXRhLW5hbWU9IkxheWVyIDEiPjxnIGlkPSJQYWdlLTEiPjxnIGlkPSJ3YnRjX2NvbG91ciIgZGF0YS1uYW1lPSJ3YnRjIGNvbG91ciI+PHBhdGggaWQ9IlNoYXBlIiBjbGFzcz0iY2xzLTEiIGQ9Ik04OS4wOSwyMi45M2wtMywzYTQyLjQ3LDQyLjQ3LDAsMCwxLDAsNTcuMzJsMywzYTQ2Ljc2LDQ2Ljc2LDAsMCwwLDAtNjMuMzlaIi8+PHBhdGggaWQ9IlNoYXBlLTIiIGRhdGEtbmFtZT0iU2hhcGUiIGNsYXNzPSJjbHMtMSIgZD0iTTI2LDIzLjE5YTQyLjQ3LDQyLjQ3LDAsMCwxLDU3LjMyLDBsMy0zYTQ2Ljc2LDQ2Ljc2LDAsMCwwLTYzLjM5LDBaIi8+PHBhdGggaWQ9IlNoYXBlLTMiIGRhdGEtbmFtZT0iU2hhcGUiIGNsYXNzPSJjbHMtMSIgZD0iTTIzLjE5LDgzLjI4YTQyLjQ3LDQyLjQ3LDAsMCwxLDAtNTcuMjlsLTMtM2E0Ni43Niw0Ni43NiwwLDAsMCwwLDYzLjM5WiIvPjxwYXRoIGlkPSJTaGFwZS00IiBkYXRhLW5hbWU9IlNoYXBlIiBjbGFzcz0iY2xzLTEiIGQ9Ik04My4yOCw4Ni4wNWE0Mi40Nyw0Mi40NywwLDAsMS01Ny4zMiwwbC0zLDNhNDYuNzYsNDYuNzYsMCwwLDAsNjMuMzksMFoiLz48cGF0aCBpZD0iU2hhcGUtNSIgZGF0YS1uYW1lPSJTaGFwZSIgY2xhc3M9ImNscy0yIiBkPSJNNzMuNTcsNDQuNjJjLS42LTYuMjYtNi04LjM2LTEyLjgzLTlWMjdINTUuNDZ2OC40NmMtMS4zOSwwLTIuODEsMC00LjIyLDBWMjdINDZ2OC42OEgzNS4yOXY1LjY1czMuOS0uMDcsMy44NCwwYTIuNzMsMi43MywwLDAsMSwzLDIuMzJWNjcuNDFhMS44NSwxLjg1LDAsMCwxLS42NCwxLjI5LDEuODMsMS44MywwLDAsMS0xLjM2LjQ2Yy4wNy4wNi0zLjg0LDAtMy44NCwwbC0xLDYuMzFINDUuOXY4LjgyaDUuMjhWNzUuNkg1NS40djguNjVoNS4yOVY3NS41M2M4LjkyLS41NCwxNS4xNC0yLjc0LDE1LjkyLTExLjA5LjYzLTYuNzItMi41My05LjcyLTcuNTgtMTAuOTNDNzIuMSw1Miw3NCw0OS4yLDczLjU3LDQ0LjYyWk02Ni4xNyw2My40YzAsNi41Ni0xMS4yNCw1LjgxLTE0LjgyLDUuODFWNTcuNTdDNTQuOTMsNTcuNTgsNjYuMTcsNTYuNTUsNjYuMTcsNjMuNFpNNjMuNzIsNDdjMCw2LTkuMzgsNS4yNy0xMi4zNiw1LjI3VjQxLjY5QzU0LjM0LDQxLjY5LDYzLjcyLDQwLjc1LDYzLjcyLDQ3WiIvPjxwYXRoIGlkPSJTaGFwZS02IiBkYXRhLW5hbWU9IlNoYXBlIiBjbGFzcz0iY2xzLTMiIGQ9Ik01NC42MiwxMDkuMjZhNTQuNjMsNTQuNjMsMCwxLDEsNTQuNjQtNTQuNjRBNTQuNjMsNTQuNjMsMCwwLDEsNTQuNjIsMTA5LjI2Wm0wLTEwNUE1MC4zNCw1MC4zNCwwLDEsMCwxMDUsNTQuNjIsNTAuMzQsNTAuMzQsMCwwLDAsNTQuNjIsNC4yNloiLz48L2c+PC9nPjwvZz48L2c+PC9zdmc+"; var maticIcon = "data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iMTAyNCIgaGVpZ2h0PSIxMDI0IiB2aWV3Qm94PSIwIDAgMTAyNCAxMDI0IiBmaWxsPSJub25lIiB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciPgo8Y2lyY2xlIGN4PSI1MTIiIGN5PSI1MTIiIHI9IjUxMiIgZmlsbD0iIzgyNDdFNSIvPgo8cGF0aCBkPSJNNjgxLjQ2OSA0MDIuNDU2QzY2OS4xODkgMzk1LjMxMiA2NTMuMjI0IDM5NS4zMTIgNjM5LjcxNiA0MDIuNDU2TDU0My45MjggNDU3LjIyOEw0NzguODQyIDQ5Mi45NDlMMzgzLjA1NSA1NDcuNzIxQzM3MC43NzQgNTU0Ljg2NSAzNTQuODEgNTU0Ljg2NSAzNDEuMzAxIDU0Ny43MjFMMjY1LjE2MiA1MDQuODU2QzI1Mi44ODIgNDk3LjcxMiAyNDQuMjg2IDQ4NC42MTQgMjQ0LjI4NiA0NzAuMzI1VjM4NS43ODZDMjQ0LjI4NiAzNzEuNDk4IDI1MS42NTQgMzU4LjQgMjY1LjE2MiAzNTEuMjU2TDM0MC4wNzMgMzA5LjU4MUMzNTIuMzUzIDMwMi40MzcgMzY4LjMxOCAzMDIuNDM3IDM4MS44MjcgMzA5LjU4MUw0NTYuNzM3IDM1MS4yNTZDNDY5LjAxOCAzNTguNCA0NzcuNjE0IDM3MS40OTggNDc3LjYxNCAzODUuNzg2VjQ0MC41NThMNTQyLjcgNDAzLjY0NlYzNDguODc0QzU0Mi43IDMzNC41ODYgNTM1LjMzMiAzMjEuNDg4IDUyMS44MjQgMzE0LjM0NEwzODMuMDU1IDIzNS43NThDMzcwLjc3NCAyMjguNjE0IDM1NC44MSAyMjguNjE0IDM0MS4zMDEgMjM1Ljc1OEwyMDAuMDc2IDMxNC4zNDRDMTg2LjU2NyAzMjEuNDg4IDE3OS4xOTkgMzM0LjU4NiAxNzkuMTk5IDM0OC44NzRWNTA3LjIzN0MxNzkuMTk5IDUyMS41MjUgMTg2LjU2NyA1MzQuNjIzIDIwMC4wNzYgNTQxLjc2N0wzNDEuMzAxIDYyMC4zNTNDMzUzLjU4MiA2MjcuNDk4IDM2OS41NDYgNjI3LjQ5OCAzODMuMDU1IDYyMC4zNTNMNDc4Ljg0MiA1NjYuNzcyTDU0My45MjggNTI5Ljg2TDYzOS43MTYgNDc2LjI3OUM2NTEuOTk2IDQ2OS4xMzUgNjY3Ljk2MSA0NjkuMTM1IDY4MS40NjkgNDc2LjI3OUw3NTYuMzggNTE3Ljk1M0M3NjguNjYgNTI1LjA5OCA3NzcuMjU3IDUzOC4xOTUgNzc3LjI1NyA1NTIuNDg0VjYzNy4wMjNDNzc3LjI1NyA2NTEuMzEyIDc2OS44ODggNjY0LjQwOSA3NTYuMzggNjcxLjU1M0w2ODEuNDY5IDcxNC40MTlDNjY5LjE4OSA3MjEuNTYzIDY1My4yMjQgNzIxLjU2MyA2MzkuNzE2IDcxNC40MTlMNTY0LjgwNSA2NzIuNzQ0QzU1Mi41MjUgNjY1LjYgNTQzLjkyOCA2NTIuNTAyIDU0My45MjggNjM4LjIxNFY1ODMuNDQyTDQ3OC44NDIgNjIwLjM1M1Y2NzUuMTI1QzQ3OC44NDIgNjg5LjQxNCA0ODYuMjEgNzAyLjUxMiA0OTkuNzE5IDcwOS42NTZMNjQwLjk0NCA3ODguMjQyQzY1My4yMjQgNzk1LjM4NiA2NjkuMTg5IDc5NS4zODYgNjgyLjY5NyA3ODguMjQyTDgyMy45MjIgNzA5LjY1NkM4MzYuMjAzIDcwMi41MTIgODQ0Ljc5OSA2ODkuNDE0IDg0NC43OTkgNjc1LjEyNVY1MTYuNzYzQzg0NC43OTkgNTAyLjQ3NCA4MzcuNDMxIDQ4OS4zNzcgODIzLjkyMiA0ODIuMjMyTDY4MS40NjkgNDAyLjQ1NloiIGZpbGw9IndoaXRlIi8+Cjwvc3ZnPgo="; var binanceCoinIcon = "data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHdpZHRoPSIzMiIgaGVpZ2h0PSIzMiI+PGcgZmlsbD0ibm9uZSI+PGNpcmNsZSBjeD0iMTYiIGN5PSIxNiIgcj0iMTYiIGZpbGw9IiNGM0JBMkYiLz48cGF0aCBmaWxsPSIjRkZGIiBkPSJNMTIuMTE2IDE0LjQwNEwxNiAxMC41MmwzLjg4NiAzLjg4NiAyLjI2LTIuMjZMMTYgNmwtNi4xNDQgNi4xNDQgMi4yNiAyLjI2ek02IDE2bDIuMjYtMi4yNkwxMC41MiAxNmwtMi4yNiAyLjI2TDYgMTZ6bTYuMTE2IDEuNTk2TDE2IDIxLjQ4bDMuODg2LTMuODg2IDIuMjYgMi4yNTlMMTYgMjZsLTYuMTQ0LTYuMTQ0LS4wMDMtLjAwMyAyLjI2My0yLjI1N3pNMjEuNDggMTZsMi4yNi0yLjI2TDI2IDE2bC0yLjI2IDIuMjZMMjEuNDggMTZ6bS0zLjE4OC0uMDAyaC4wMDJ2LjAwMkwxNiAxOC4yOTRsLTIuMjkxLTIuMjktLjAwNC0uMDA0LjAwNC0uMDAzLjQwMS0uNDAyLjE5NS0uMTk1TDE2IDEzLjcwNmwyLjI5MyAyLjI5M3oiLz48L2c+PC9zdmc+"; var BUSDIcon = "data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHZpZXdCb3g9IjAgMCAzMzYuNDEgMzM3LjQyIj48ZGVmcz48c3R5bGU+LmNscy0xe2ZpbGw6I2YwYjkwYjtzdHJva2U6I2YwYjkwYjt9PC9zdHlsZT48L2RlZnM+PHRpdGxlPkFzc2V0IDE8L3RpdGxlPjxnIGlkPSJMYXllcl8yIiBkYXRhLW5hbWU9IkxheWVyIDIiPjxnIGlkPSJMYXllcl8xLTIiIGRhdGEtbmFtZT0iTGF5ZXIgMSI+PHBhdGggY2xhc3M9ImNscy0xIiBkPSJNMTY4LjIuNzFsNDEuNSw0Mi41TDEwNS4yLDE0Ny43MWwtNDEuNS00MS41WiIvPjxwYXRoIGNsYXNzPSJjbHMtMSIgZD0iTTIzMS4yLDYzLjcxbDQxLjUsNDIuNUwxMDUuMiwyNzMuNzFsLTQxLjUtNDEuNVoiLz48cGF0aCBjbGFzcz0iY2xzLTEiIGQ9Ik00Mi4yLDEyNi43MWw0MS41LDQyLjUtNDEuNSw0MS41TC43LDE2OS4yMVoiLz48cGF0aCBjbGFzcz0iY2xzLTEiIGQ9Ik0yOTQuMiwxMjYuNzFsNDEuNSw0Mi41TDE2OC4yLDMzNi43MWwtNDEuNS00MS41WiIvPjwvZz48L2c+PC9zdmc+"; var fantomIcon = "data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHhtbG5zOnhsaW5rPSJodHRwOi8vd3d3LnczLm9yZy8xOTk5L3hsaW5rIiB2aWV3Qm94PSIwIDAgMzIgMzIiPjxkZWZzPjxzdHlsZT4uY2xzLTF7ZmlsbDojZmZmO2ZpbGwtcnVsZTpldmVub2RkO30uY2xzLTJ7ZmlsbDojMTNiNWVjO30uY2xzLTN7bWFzazp1cmwoI21hc2spO308L3N0eWxlPjxtYXNrIGlkPSJtYXNrIiB4PSIxMCIgeT0iNiIgd2lkdGg9IjkzLjEiIGhlaWdodD0iMjAiIG1hc2tVbml0cz0idXNlclNwYWNlT25Vc2UiPjxnIGlkPSJhIj48cGF0aCBjbGFzcz0iY2xzLTEiIGQ9Ik0xMCw2aDkzLjFWMjZIMTBaIi8+PC9nPjwvbWFzaz48L2RlZnM+PHRpdGxlPmZhPC90aXRsZT48ZyBpZD0iTGF5ZXJfMiIgZGF0YS1uYW1lPSJMYXllciAyIj48ZyBpZD0iTGF5ZXJfMS0yIiBkYXRhLW5hbWU9IkxheWVyIDEiPjxjaXJjbGUgY2xhc3M9ImNscy0yIiBjeD0iMTYiIGN5PSIxNiIgcj0iMTYiLz48ZyBjbGFzcz0iY2xzLTMiPjxwYXRoIGNsYXNzPSJjbHMtMSIgZD0iTTE3LjIsMTIuOWwzLjYtMi4xVjE1Wm0zLjYsOUwxNiwyNC43bC00LjgtMi44VjE3TDE2LDE5LjgsMjAuOCwxN1pNMTEuMiwxMC44bDMuNiwyLjFMMTEuMiwxNVptNS40LDMuMUwyMC4yLDE2bC0zLjYsMi4xWm0tMS4yLDQuMkwxMS44LDE2bDMuNi0yLjFabTQuOC04LjNMMTYsMTIuMiwxMS44LDkuOCwxNiw3LjNaTTEwLDkuNFYyMi41bDYsMy40LDYtMy40VjkuNEwxNiw2WiIvPjwvZz48L2c+PC9nPjwvc3ZnPg=="; var DEFAULT_TOKENS = { "1": [ { address: "0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2", name: "Wrapped Ether", symbol: "WETH", icon: wrappedEthIcon }, { address: "0xdAC17F958D2ee523a2206206994597C13D831ec7", name: "Tether USD", symbol: "USDT", icon: tetherUsdIcon }, { address: "0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48", name: "USD Coin", symbol: "USDC", icon: usdcIcon }, { address: "0x2260FAC5E5542a773Aa44fBCfeDf7C193bc2C599", name: "Wrapped Bitcoin", symbol: "WBTC", icon: wrappedBtcIcon }, { address: "0x7D1AfA7B718fb893dB30A3aBc0Cfc608AaCfeBB0", name: "Polygon", symbol: "WMATIC", icon: maticIcon } ], "11155111": [ { address: "0x1c7D4B196Cb0C7B01d743Fbc6116a902379C7238", name: "USD Coin", symbol: "USDC", icon: usdcIcon } ], "10": [ { address: "0x4200000000000000000000000000000000000006", name: "Wrapped Ether", symbol: "WETH", icon: wrappedEthIcon }, { address: "0x0b2c639c533813f4aa9d7837caf62653d097ff85", name: "USD Coin", symbol: "USDC", icon: usdcIcon } ], "56": [ { address: "0xbb4CdB9CBd36B01bD1cBaEBF2De08d9173bc095c", name: "Wrapped Binance Chain Token", symbol: "WBNB", icon: binanceCoinIcon }, { address: "0xe9e7CEA3DedcA5984780Bafc599bD69ADd087D56", name: "Binance USD", symbol: "BUSD", icon: BUSDIcon } ], "97": [ { address: "0xae13d989daC2f0dEbFf460aC112a837C89BAa7cd", name: "Wrapped Binance Chain Testnet Token", symbol: "WBNB", icon: binanceCoinIcon }, { address: "0xed24fc36d5ee211ea25a80239fb8c4cfd80f12ee", name: "Binance USD", symbol: "BUSD", icon: BUSDIcon } ], "137": [ { address: "0x3c499c542cEF5E3811e1192ce70d8cC03d5c3359", name: "USD Coin", symbol: "USDC", icon: usdcIcon }, { address: "0x0d500B1d8E8eF31E21C99d1Db9A6444d3ADf1270", name: "Wrapped Matic", symbol: "WMATIC", icon: maticIcon }, { address: "0x7ceB23fD6bC0adD59E62ac25578270cFf1b9f619", name: "Wrapped Ether", symbol: "WETH", icon: wrappedEthIcon }, { address: "0xc2132D05D31c914a87C6611C10748AEb04B58e8F", name: "Tether USD", symbol: "USDT", icon: tetherUsdIcon }, { address: "0x1BFD67037B42Cf73acF2047067bd4F2C47D9BfD6", name: "Wrapped BTC", symbol: "WBTC", icon: wrappedBtcIcon } ], "250": [ { address: "0x21be370D5312f44cB42ce377BC9b8a0cEF1A4C83", name: "Wrapped Fantom", symbol: "WFTM", icon: fantomIcon }, { name: "Wrapped Ether", address: "0x74b23882a30290451A17c44f4F05243b6b58C76d", symbol: "WETH", icon: wrappedEthIcon }, { name: "USD Coin", address: "0x04068DA6C83AFCFA0e13ba15A6696662335D5B75", symbol: "USDC", icon: usdcIcon }, { name: "Wrapped Bitcoin", address: "0x321162Cd933E2Be498Cd2267a90534A804051b11", symbol: "WBTC", icon: wrappedBtcIcon } ], "420": [ { address: "0x4200000000000000000000000000000000000006", name: "Wrapped Ether", symbol: "WETH", icon: wrappedEthIcon } ], "4002": [ { address: "0xf1277d1Ed8AD466beddF92ef448A132661956621", name: "Wrapped Fantom", symbol: "WFTM", icon: fantomIcon } ], "42161": [ { address: "0x82af49447d8a07e3bd95bd0d56f35241523fbab1", name: "Wrapped Ether", symbol: "WETH", icon: wrappedEthIcon }, { address: "0xaf88d065e77c8cC2239327C5EDb3A432268e5831", name: "USD Coin", symbol: "USDC", icon: usdcIcon } ], "43113": [ { address: "0xd00ae08403B9bbb9124bB305C09058E32C39A48c", name: "Wrapped AVAX", symbol: "WAVAX", icon: "data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iMTUwMyIgaGVpZ2h0PSIxNTA0IiB2aWV3Qm94PSIwIDAgMTUwMyAxNTA0IiBmaWxsPSJub25lIiB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciPgo8cmVjdCB4PSIyODciIHk9IjI1OCIgd2lkdGg9IjkyOCIgaGVpZ2h0PSI4NDQiIGZpbGw9IndoaXRlIi8+CjxwYXRoIGZpbGwtcnVsZT0iZXZlbm9kZCIgY2xpcC1ydWxlPSJldmVub2RkIiBkPSJNMTUwMi41IDc1MkMxNTAyLjUgMTE2Ni43NyAxMTY2LjI3IDE1MDMgNzUxLjUgMTUwM0MzMzYuNzM0IDE1MDMgMC41IDExNjYuNzcgMC41IDc1MkMwLjUgMzM3LjIzNCAzMzYuNzM0IDEgNzUxLjUgMUMxMTY2LjI3IDEgMTUwMi41IDMzNy4yMzQgMTUwMi41IDc1MlpNNTM4LjY4OCAxMDUwLjg2SDM5Mi45NEMzNjIuMzE0IDEwNTAuODYgMzQ3LjE4NiAxMDUwLjg2IDMzNy45NjIgMTA0NC45NkMzMjcuOTk5IDEwMzguNSAzMjEuOTExIDEwMjcuOCAzMjEuMTczIDEwMTUuOTlDMzIwLjYxOSAxMDA1LjExIDMyOC4xODQgOTkxLjgyMiAzNDMuMzEyIDk2NS4yNTVMNzAzLjE4MiAzMzAuOTM1QzcxOC40OTUgMzAzLjk5OSA3MjYuMjQzIDI5MC41MzEgNzM2LjAyMSAyODUuNTVDNzQ2LjUzNyAyODAuMiA3NTkuMDgzIDI4MC4yIDc2OS41OTkgMjg1LjU1Qzc3OS4zNzcgMjkwLjUzMSA3ODcuMTI2IDMwMy45OTkgODAyLjQzOCAzMzAuOTM1TDg3Ni40MiA0NjAuMDc5TDg3Ni43OTcgNDYwLjczOEM4OTMuMzM2IDQ4OS42MzUgOTAxLjcyMyA1MDQuMjg5IDkwNS4zODUgNTE5LjY2OUM5MDkuNDQzIDUzNi40NTggOTA5LjQ0MyA1NTQuMTY5IDkwNS4zODUgNTcwLjk1OEM5MDEuNjk1IDU4Ni40NTUgODkzLjM5MyA2MDEuMjE1IDg3Ni42MDQgNjMwLjU0OUw2ODcuNTczIDk2NC43MDJMNjg3LjA4NCA5NjUuNTU4QzY3MC40MzYgOTk0LjY5MyA2NjEuOTk5IDEwMDkuNDYgNjUwLjMwNiAxMDIwLjZDNjM3LjU3NiAxMDMyLjc4IDYyMi4yNjMgMTA0MS42MyA2MDUuNDc0IDEwNDYuNjJDNTkwLjE2MSAxMDUwLjg2IDU3My4wMDQgMTA1MC44NiA1MzguNjg4IDEwNTAuODZaTTkwNi43NSAxMDUwLjg2SDExMTUuNTlDMTE0Ni40IDEwNTAuODYgMTE2MS45IDEwNTAuODYgMTE3MS4xMyAxMDQ0Ljc4QzExODEuMDkgMTAzOC4zMiAxMTg3LjM2IDEwMjcuNDMgMTE4Ny45MiAxMDE1LjYzQzExODguNDUgMTAwNS4xIDExODEuMDUgOTkyLjMzIDExNjYuNTUgOTY3LjMwN0MxMTY2LjA1IDk2Ni40NTUgMTE2NS41NSA5NjUuNTg4IDExNjUuMDQgOTY0LjcwNkwxMDYwLjQzIDc4NS43NUwxMDU5LjI0IDc4My43MzVDMTA0NC41NCA3NTguODc3IDEwMzcuMTIgNzQ2LjMyNCAxMDI3LjU5IDc0MS40NzJDMTAxNy4wOCA3MzYuMTIxIDEwMDQuNzEgNzM2LjEyMSA5OTQuMTk5IDc0MS40NzJDOTg0LjYwNSA3NDYuNDUzIDk3Ni44NTcgNzU5LjU1MiA5NjEuNTQ0IDc4NS45MzRMODU3LjMwNiA5NjQuODkxTDg1Ni45NDkgOTY1LjUwN0M4NDEuNjkgOTkxLjg0NyA4MzQuMDY0IDEwMDUuMDEgODM0LjYxNCAxMDE1LjgxQzgzNS4zNTIgMTAyNy42MiA4NDEuNDQgMTAzOC41IDg1MS40MDIgMTA0NC45NkM4NjAuNDQzIDEwNTAuODYgODc1Ljk0IDEwNTAuODYgOTA2Ljc1IDEwNTAuODZaIiBmaWxsPSIjRTg0MTQyIi8+Cjwvc3ZnPgo=" }, { address: "0x5425890298aed601595a70AB815c96711a31Bc65", name: "USD Coin", symbol: "USDC", icon: usdcIcon } ], "43114": [ { address: "0xB31f66AA3C1e785363F0875A1B74E27b85FD66c7", name: "Wrapped AVAX", symbol: "WAVAX", icon: "data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iMTUwMyIgaGVpZ2h0PSIxNTA0IiB2aWV3Qm94PSIwIDAgMTUwMyAxNTA0IiBmaWxsPSJub25lIiB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciPgo8cmVjdCB4PSIyODciIHk9IjI1OCIgd2lkdGg9IjkyOCIgaGVpZ2h0PSI4NDQiIGZpbGw9IndoaXRlIi8+CjxwYXRoIGZpbGwtcnVsZT0iZXZlbm9kZCIgY2xpcC1ydWxlPSJldmVub2RkIiBkPSJNMTUwMi41IDc1MkMxNTAyLjUgMTE2Ni43NyAxMTY2LjI3IDE1MDMgNzUxLjUgMTUwM0MzMzYuNzM0IDE1MDMgMC41IDExNjYuNzcgMC41IDc1MkMwLjUgMzM3LjIzNCAzMzYuNzM0IDEgNzUxLjUgMUMxMTY2LjI3IDEgMTUwMi41IDMzNy4yMzQgMTUwMi41IDc1MlpNNTM4LjY4OCAxMDUwLjg2SDM5Mi45NEMzNjIuMzE0IDEwNTAuODYgMzQ3LjE4NiAxMDUwLjg2IDMzNy45NjIgMTA0NC45NkMzMjcuOTk5IDEwMzguNSAzMjEuOTExIDEwMjcuOCAzMjEuMTczIDEwMTUuOTlDMzIwLjYxOSAxMDA1LjExIDMyOC4xODQgOTkxLjgyMiAzNDMuMzEyIDk2NS4yNTVMNzAzLjE4MiAzMzAuOTM1QzcxOC40OTUgMzAzLjk5OSA3MjYuMjQzIDI5MC41MzEgNzM2LjAyMSAyODUuNTVDNzQ2LjUzNyAyODAuMiA3NTkuMDgzIDI4MC4yIDc2OS41OTkgMjg1LjU1Qzc3OS4zNzcgMjkwLjUzMSA3ODcuMTI2IDMwMy45OTkgODAyLjQzOCAzMzAuOTM1TDg3Ni40MiA0NjAuMDc5TDg3Ni43OTcgNDYwLjczOEM4OTMuMzM2IDQ4OS42MzUgOTAxLjcyMyA1MDQuMjg5IDkwNS4zODUgNTE5LjY2OUM5MDkuNDQzIDUzNi40NTggOTA5LjQ0MyA1NTQuMTY5IDkwNS4zODUgNTcwLjk1OEM5MDEuNjk1IDU4Ni40NTUgODkzLjM5MyA2MDEuMjE1IDg3Ni42MDQgNjMwLjU0OUw2ODcuNTczIDk2NC43MDJMNjg3LjA4NCA5NjUuNTU4QzY3MC40MzYgOTk0LjY5MyA2NjEuOTk5IDEwMDkuNDYgNjUwLjMwNiAxMDIwLjZDNjM3LjU3NiAxMDMyLjc4IDYyMi4yNjMgMTA0MS42MyA2MDUuNDc0IDEwNDYuNjJDNTkwLjE2MSAxMDUwLjg2IDU3My4wMDQgMTA1MC44NiA1MzguNjg4IDEwNTAuODZaTTkwNi43NSAxMDUwLjg2SDExMTUuNTlDMTE0Ni40IDEwNTAuODYgMTE2MS45IDEwNTAuODYgMTE3MS4xMyAxMDQ0Ljc4QzExODEuMDkgMTAzOC4zMiAxMTg3LjM2IDEwMjcuNDMgMTE4Ny45MiAxMDE1LjYzQzExODguNDUgMTAwNS4xIDExODEuMDUgOTkyLjMzIDExNjYuNTUgOTY3LjMwN0MxMTY2LjA1IDk2Ni40NTUgMTE2NS41NSA5NjUuNTg4IDExNjUuMDQgOTY0LjcwNkwxMDYwLjQzIDc4NS43NUwxMDU5LjI0IDc4My43MzVDMTA0NC41NCA3NTguODc3IDEwMzcuMTIgNzQ2LjMyNCAxMDI3LjU5IDc0MS40NzJDMTAxNy4wOCA3MzYuMTIxIDEwMDQuNzEgNzM2LjEyMSA5OTQuMTk5IDc0MS40NzJDOTg0LjYwNSA3NDYuNDUzIDk3Ni44NTcgNzU5LjU1MiA5NjEuNTQ0IDc4NS45MzRMODU3LjMwNiA5NjQuODkxTDg1Ni45NDkgOTY1LjUwN0M4NDEuNjkgOTkxLjg0NyA4MzQuMDY0IDEwMDUuMDEgODM0LjYxNCAxMDE1LjgxQzgzNS4zNTIgMTAyNy42MiA4NDEuNDQgMTAzOC41IDg1MS40MDIgMTA0NC45NkM4NjAuNDQzIDEwNTAuODYgODc1Ljk0IDEwNTAuODYgOTA2Ljc1IDEwNTAuODZaIiBmaWxsPSIjRTg0MTQyIi8+Cjwvc3ZnPgo=" }, { address: "0x49D5c2BdFfac6CE2BFdB6640F4F80f226bc10bAB", name: "Wrapped Ether", symbol: "WETH", icon: wrappedEthIcon }, { address: "0x9702230a8ea53601f5cd2dc00fdbc13d4df4a8c7", name: "Tether USD", symbol: "USDT", icon: tetherUsdIcon }, { address: "0xB97EF9Ef8734C71904D8002F8b6Bc66Dd9c48a6E", name: "USD Coin", symbol: "USDC", icon: usdcIcon }, { address: "0x50b7545627a5162F82A992c33b87aDc75187B218", name: "Wrapped BTC", symbol: "WBTC", icon: wrappedBtcIcon } ], "80001": [ { address: "0x9c3C9283D3e44854697Cd22D3Faa240Cfb032889", name: "Wrapped Matic", symbol: "WMATIC", icon: maticIcon }, { name: "Wrapped Ether", address: "0xa6fa4fb5f76172d178d61b04b0ecd319c5d1c0aa", symbol: "WETH", icon: wrappedEthIcon }, { address: "0x0FA8781a83E46826621b3BC094Ea2A0212e71B23", name: "USD Coin", symbol: "USDC", icon: usdcIcon }, { name: "Tether USD", address: "0x3813e82e6f7098b9583FC0F33a962D02018B6803", symbol: "USDT", icon: tetherUsdIcon } ], "421613": [ { address: "0xe39Ab88f8A4777030A534146A9Ca3B52bd5D43A3", name: "Wrapped Ether", symbol: "WETH", icon: wrappedEthIcon }, { address: "0xfd064A18f3BF249cf1f87FC203E90D8f650f2d63", name: "USD Coin", symbol: "USDC", icon: usdcIcon } ], // Base mainnet "8453": [ { address: "0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913", name: "USD Coin", symbol: "USDC", icon: usdcIcon } ], // Base sepolia "84532": [ { address: "0x036CbD53842c5426634e7929541eC2318f3dCF7e", name: "USD Coin", symbol: "USDC", icon: usdcIcon } ] }; var defaultTokens = DEFAULT_TOKENS; function getDefaultToken(chain, symbol) { const tokens = defaultTokens[chain.id]; return tokens == null ? void 0 : tokens.find((t) => t.symbol === symbol); } // node_modules/thirdweb/dist/esm/react/web/utils/canFitWideModal.js function canFitWideModal() { if (typeof window !== "undefined") { return window.innerWidth >= wideModalScreenThreshold; } return false; } // node_modules/thirdweb/dist/esm/react/web/utils/usePreloadWalletProviders.js function usePreloadWalletProviders({ client, wallets }) { useQueries({ queries: wallets.filter((w) => w.id === COINBASE || w.id === "inApp" || isEcosystemWallet(w.id)).map((w) => ({ queryKey: ["preload-wallet", w.id], queryFn: async () => { var _a; switch (true) { case COINBASE === w.id: { const { getCoinbaseWebProvider } = await import("./coinbaseWebSDK-RVHYUQN6.js"); await getCoinbaseWebProvider(w.getConfig()); return true; } case "inApp" === w.id: { const [{ InAppWebConnector }, { getOrCreateInAppWalletConnector }] = await Promise.all([ import("./web-connector-5CMXT4ED.js"), import("./in-app-core-HIWEYDMM.js") ]); await getOrCreateInAppWalletConnector(client, async (client2) => { return new InAppWebConnector({ client: client2 }); }); return true; } case isEcosystemWallet(w.id): { const [{ InAppWebConnector }, { getOrCreateInAppWalletConnector }] = await Promise.all([ import("./web-connector-5CMXT4ED.js"), import("./in-app-core-HIWEYDMM.js") ]); const ecosystemWallet = w; await getOrCreateInAppWalletConnector(client, async (client2) => { var _a2; return new InAppWebConnector({ client: client2, ecosystem: { id: ecosystemWallet.id, partnerId: (_a2 = ecosystemWallet.getConfig()) == null ? void 0 : _a2.partnerId } }); }, { id: ecosystemWallet.id, partnerId: (_a = ecosystemWallet.getConfig()) == null ? void 0 : _a.partnerId }); return true; } default: { return false; } } } })) }); } // node_modules/thirdweb/dist/esm/react/web/ui/AutoConnect/AutoConnect.js var import_jsx_runtime14 = __toESM(require_jsx_runtime(), 1); // node_modules/thirdweb/dist/esm/wallets/in-app/web/lib/get-url-token.js function getUrlToken() { if (!(window == null ? void 0 : window.location)) { return {}; } const queryString = window.location.search; const params = new URLSearchParams(queryString); const authResultString = params.get("authResult"); const walletId = params.get("walletId"); const authProvider = params.get("authProvider"); const authCookie = params.get("authCookie"); if ((authCookie || authResultString) && walletId) { const authResult = (() => { if (authResultString) { params.delete("authResult"); return JSON.parse(decodeURIComponent(authResultString)); } })(); params.delete("walletId"); params.delete("authProvider"); params.delete("authCookie"); window.history.pushState({}, "", `${window.location.pathname}?${params.toString()}`); return { walletId, authResult, authProvider, authCookie }; } return {}; } // node_modules/thirdweb/dist/esm/react/core/utils/isSmartWallet.js function hasSmartAccount(activeWallet) { const config = activeWallet == null ? void 0 : activeWallet.getConfig(); return activeWallet !== void 0 && (activeWallet.id === "smart" || activeWallet.id === "inApp" && !!config && "smartAccount" in config || isEcosystemWallet(activeWallet) && !!config && "smartAccount" in config); } // node_modules/thirdweb/dist/esm/reactive/computedStore.js function computedStore(computation, dependencies) { const listeners = /* @__PURE__ */ new Set(); let value = computation(); const notify = () => { for (const listener of listeners) { listener(); } }; const setValue = (newValue) => { value = newValue; notify(); }; for (const store of dependencies) { store.subscribe(() => { setValue(computation()); }); } return { getValue() { return value; }, subscribe(listener) { listeners.add(listener); return () => { listeners.delete(listener); }; } }; } // node_modules/thirdweb/dist/esm/reactive/effect.js function effect(effectFn, dependencies, runOnMount = true) { if (runOnMount) { effectFn(); } const unsubscribeList = dependencies.map((store) => { return store.subscribe(() => { effectFn(); }); }); return () => { for (const fn of unsubscribeList) { fn(); } }; } // node_modules/thirdweb/dist/esm/wallets/manager/index.js var CONNECTED_WALLET_IDS = "thirdweb:connected-wallet-ids"; var LAST_ACTIVE_EOA_ID = "thirdweb:active-wallet-id"; var LAST_ACTIVE_CHAIN = "thirdweb:active-chain"; function createConnectionManager(storage) { const activeWalletStore = createStore(void 0); const activeAccountStore = createStore(void 0); const activeWalletChainStore = createStore(void 0); const activeWalletConnectionStatusStore = createStore("disconnected"); const definedChainsStore = createStore(/* @__PURE__ */ new Map()); effect(() => { cacheChains([...definedChainsStore.getValue().values()]); }, [definedChainsStore]); effect(() => { const chainVal = activeWalletChainStore.getValue(); if (!chainVal) { return; } const definedChain = definedChainsStore.getValue().get(chainVal.id); if (!definedChain || definedChain === chainVal) { return; } activeWalletChainStore.setValue(definedChain); }, [definedChainsStore, activeWalletChainStore]); const walletIdToConnectedWalletMap = createStore(/* @__PURE__ */ new Map()); const isAutoConnecting = createStore(false); const connectedWallets = computedStore(() => { return Array.from(walletIdToConnectedWalletMap.getValue().values()); }, [walletIdToConnectedWalletMap]); const addConnectedWallet = (wallet) => { const oldValue = walletIdToConnectedWalletMap.getValue(); if (oldValue.has(wallet.id)) { return; } const newValue = new Map(oldValue); newValue.set(wallet.id, wallet); walletIdToConnectedWalletMap.setValue(newValue); }; const removeConnectedWallet = (wallet) => { const oldValue = walletIdToConnectedWalletMap.getValue(); const newValue = new Map(oldValue); newValue.delete(wallet.id); walletIdToConnectedWalletMap.setValue(newValue); }; const onWalletDisconnect = (wallet) => { deleteConnectParamsFromStorage(storage, wallet.id); removeConnectedWallet(wallet); if (activeWalletStore.getValue() === wallet) { storage.removeItem(LAST_ACTIVE_EOA_ID); activeAccountStore.setValue(void 0); activeWalletChainStore.setValue(void 0); activeWalletStore.setValue(void 0); activeWalletConnectionStatusStore.setValue("disconnected"); } }; const disconnectWallet = (wallet) => { onWalletDisconnect(wallet); wallet.disconnect(); }; const handleConnection = async (wallet, options) => { const account = wallet.getAccount(); if (!account) { throw new Error("Can not set a wallet without an account as active"); } const personalWallet = wallet; let activeWallet = personalWallet; const isInAppSmartAccount = hasSmartAccount(wallet); if ((options == null ? void 0 : options.accountAbstraction) && !isInAppSmartAccount) { activeWallet = smartWallet(options.accountAbstraction); await activeWallet.connect({ personalAccount: wallet.getAccount(), client: options.client }); } addConnectedWallet(personalWallet); if (personalWallet.id !== "smart") { await storage.setItem(LAST_ACTIVE_EOA_ID, personalWallet.id); } return activeWallet; }; const connect = async (wallet, options) => { var _a; const connectedWallet = await handleConnection(wallet, options); (_a = options == null ? void 0 : options.onConnect) == null ? void 0 : _a.call(options, connectedWallet); handleSetActiveWallet(connectedWallet); wallet.subscribe("accountChanged", async () => { var _a2; const newConnectedWallet = await handleConnection(wallet, options); (_a2 = options == null ? void 0 : options.onConnect) == null ? void 0 : _a2.call(options, newConnectedWallet); handleSetActiveWallet(newConnectedWallet); }); return connectedWallet; }; const handleSetActiveWallet = (activeWallet) => { const account = activeWallet.getAccount(); if (!account) { throw new Error("Can not set a wallet without an account as active"); } addConnectedWallet(activeWallet); activeWalletStore.setValue(activeWallet); activeAccountStore.setValue(account); activeWalletChainStore.setValue(activeWallet.getChain()); activeWalletConnectionStatusStore.setValue("connected"); const onAccountsChanged = (newAccount) => { activeAccountStore.setValue(newAccount); }; const unsubAccounts = activeWallet.subscribe("accountChanged", onAccountsChanged); const unsubChainChanged = activeWallet.subscribe("chainChanged", (chain) => activeWalletChainStore.setValue(chain)); const unsubDisconnect = activeWallet.subscribe("disconnect", () => { handleDisconnect(); }); const handleDisconnect = () => { onWalletDisconnect(activeWallet); unsubAccounts(); unsubChainChanged(); unsubDisconnect(); }; }; const setActiveWallet = async (activeWallet) => { handleSetActiveWallet(activeWallet); if (activeWallet.id !== "smart") { await storage.setItem(LAST_ACTIVE_EOA_ID, activeWallet.id); } }; effect(() => { const _chain = activeWalletChainStore.getValue(); if (_chain) { storage.setItem(LAST_ACTIVE_CHAIN, stringify(_chain)); } else { storage.removeItem(LAST_ACTIVE_CHAIN); } }, [activeWalletChainStore], false); effect(() => { const accounts = connectedWallets.getValue(); const ids = accounts.map((acc) => acc == null ? void 0 : acc.id).filter((c) => !!c); storage.setItem(CONNECTED_WALLET_IDS, stringify(ids)); }, [connectedWallets], false); const switchActiveWalletChain = async (chain) => { const wallet = activeWalletStore.getValue(); if (!wallet) { throw new Error("no wallet found"); } if (!wallet.switchChain) { throw new Error("wallet does not support switching chains"); } if (wallet.id === "smart") { const personalWalletId = await getStoredActiveWalletId(storage); if (personalWalletId) { const personalWallet = connectedWallets.getValue().find((w) => w.id === personalWalletId); if (personalWallet) { await personalWallet.switchChain(chain); } } await wallet.switchChain(chain); handleSetActiveWallet(wallet); } else { await wallet.switchChain(chain); } activeWalletChainStore.setValue(wallet.getChain()); }; function defineChains(chains) { const currentMapVal = definedChainsStore.getValue(); const allChainsSame = chains.every((c) => { const definedChain = currentMapVal.get(c.id); return stringify(definedChain) === stringify(c); }); if (allChainsSame) { return; } const newMapVal = new Map(currentMapVal); for (const c of chains) { newMapVal.set(c.id, c); } definedChainsStore.setValue(newMapVal); } return { activeWalletStore, activeAccountStore, connectedWallets, addConnectedWallet, disconnectWallet, setActiveWallet, connect, handleConnection, activeWalletChainStore, switchActiveWalletChain, activeWalletConnectionStatusStore, isAutoConnecting, removeConnectedWallet, defineChains }; } async function getStoredConnectedWalletIds(storage) { try { const value = await storage.getItem(CONNECTED_WALLET_IDS); if (value) { return JSON.parse(value); } return []; } catch { return []; } } async function getStoredActiveWalletId(storage) { try { const value = await storage.getItem(LAST_ACTIVE_EOA_ID); if (value) { return value; } return null; } catch { return null; } } async function getLastConnectedChain(storage) { try { const value = await storage.getItem(LAST_ACTIVE_CHAIN); if (value) { return JSON.parse(value); } return null; } catch { return null; } } // node_modules/thirdweb/dist/esm/react/core/utils/timeoutPromise.js function timeoutPromise(promise, option) { return new Promise((resolve2, reject) => { const timeoutId = setTimeout(() => { reject(new Error(option.message)); }, option.ms); promise.then((res) => { clearTimeout(timeoutId); resolve2(res); }, (err) => { clearTimeout(timeoutId); reject(err); }); }); } // node_modules/thirdweb/dist/esm/react/core/hooks/wallets/useConnect.js var import_react12 = __toESM(require_react(), 1); // node_modules/thirdweb/dist/esm/react/core/hooks/wallets/useSetActiveWalletConnectionStatus.js function useSetActiveWalletConnectionStatus() { const manager = useConnectionManagerCtx("useSetActiveWalletConnectionStatus"); return manager.activeWalletConnectionStatusStore.setValue; } // node_modules/thirdweb/dist/esm/react/core/hooks/wallets/useConnect.js function useConnect(options) { const manager = useConnectionManagerCtx("useConnect"); const { connect } = manager; const setConnectionStatus = useSetActiveWalletConnectionStatus(); const [isConnecting, setIsConnecting] = (0, import_react12.useState)(false); const [error, setError] = (0, import_react12.useState)(null); const handleConnection = (0, import_react12.useCallback)(async (walletOrFn) => { setError(null); setConnectionStatus("connecting"); if (typeof walletOrFn !== "function") { const account = await connect(walletOrFn, options); setConnectionStatus("connected"); return account; } setIsConnecting(true); try { const w = await walletOrFn(); const account = await connect(w, options); setConnectionStatus("connected"); return account; } catch (e) { console.error(e); setError(e); setConnectionStatus("disconnected"); } finally { setIsConnecting(false); } return null; }, [connect, options, setConnectionStatus]); return { connect: handleConnection, isConnecting, error }; } // node_modules/thirdweb/dist/esm/react/core/hooks/wallets/useAutoConnect.js function useAutoConnectCore(storage, props, createWalletFn, getInstalledWallets) { const manager = useConnectionManagerCtx("useAutoConnect"); const setConnectionStatus = useSetActiveWalletConnectionStatus(); const { connect } = useConnect({ client: props.client, accountAbstraction: props.accountAbstraction }); const { isAutoConnecting } = manager; const { wallets, onConnect } = props; const timeout = props.timeout ?? 15e3; const autoConnect = async () => { var _a; let autoConnected = false; isAutoConnecting.setValue(true); let [lastConnectedWalletIds, lastActiveWalletId] = await Promise.all([ getStoredConnectedWalletIds(storage), getStoredActiveWalletId(storage) ]); const { authResult, walletId, authProvider, authCookie } = getUrlToken(); const wallet = wallets.find((w) => w.id === walletId); if (authCookie && wallet) { const clientStorage = new ClientScopedStorage({ storage, clientId: props.client.clientId, ecosystem: isEcosystemWallet(wallet) ? { id: wallet.id, partnerId: (_a = wallet.getConfig()) == null ? void 0 : _a.partnerId } : void 0 }); await clientStorage.saveAuthCookie(authCookie); } if (walletId) { lastActiveWalletId = walletId; lastConnectedWalletIds = (lastConnectedWalletIds == null ? void 0 : lastConnectedWalletIds.includes(walletId)) ? lastConnectedWalletIds : [walletId, ...lastConnectedWalletIds || []]; } if (authProvider) { await setLastAuthProvider(authProvider, storage); } if (!lastConnectedWalletIds) { return autoConnected; } const lastConnectedChain = await getLastConnectedChain(storage) || props.chain; async function handleWalletConnection(wallet2) { return wallet2.autoConnect({ client: props.client, chain: lastConnectedChain ?? void 0, authResult }); } const availableWallets = [...wallets, ...(getInstalledWallets == null ? void 0 : getInstalledWallets()) ?? []]; const activeWallet = lastActiveWalletId && (availableWallets.find((w) => w.id === lastActiveWalletId) || createWalletFn(lastActiveWalletId)); if (activeWallet) { try { setConnectionStatus("connecting"); await timeoutPromise(handleWalletConnection(activeWallet), { ms: timeout, message: `AutoConnect timeout: ${timeout}ms limit exceeded.` }); const connectedWallet = await connect(activeWallet); if (connectedWallet) { if (onConnect) { try { onConnect(connectedWallet); autoConnected = true; } catch { } } } else { setConnectionStatus("disconnected"); } } catch (e) { if (e instanceof Error) { console.warn("Error auto connecting wallet:", e.message); } setConnectionStatus("disconnected"); } } else { setConnectionStatus("disconnected"); } const otherWallets = wallets.filter((w) => w.id !== lastActiveWalletId && lastConnectedWalletIds.includes(w.id)); for (const wallet2 of otherWallets) { try { await handleWalletConnection(wallet2); manager.addConnectedWallet(wallet2); } catch { } } isAutoConnecting.setValue(false); return autoConnected; }; const query = useQuery({ queryKey: ["autoConnect", props.client.clientId], queryFn: autoConnect, refetchOnMount: false, refetchOnWindowFocus: false }); return query; } // node_modules/thirdweb/dist/esm/react/web/hooks/wallets/useAutoConnect.js function useAutoConnect(props) { const wallets = props.wallets || getDefaultWallets(props); return useAutoConnectCore(webLocalStorage, { ...props, wallets }, createWallet, () => { const specifiedWalletIds = new Set(wallets.map((x) => x.id)); const installedWallets = getInstalledWalletProviders().filter((x) => !specifiedWalletIds.has(x.info.rdns)).map((x) => createWallet(x.info.rdns)); return installedWallets; }); } // node_modules/thirdweb/dist/esm/react/web/ui/AutoConnect/AutoConnect.js function AutoConnect(props) { useAutoConnect(props); return (0, import_jsx_runtime14.jsx)(import_jsx_runtime14.Fragment, {}); } // node_modules/thirdweb/dist/esm/react/web/ui/ConnectWallet/Details.js var import_jsx_runtime81 = __toESM(require_jsx_runtime(), 1); var import_react49 = __toESM(require_react(), 1); // node_modules/thirdweb/dist/esm/analytics/track/pay.js async function trackPayEvent(args) { return track({ client: args.client, ecosystem: args.ecosystem, data: { source: "pay", action: args.event, clientId: args.client.clientId, chainId: args.chainId, walletAddress: args.walletAddress, walletType: args.walletType, tokenAddress: args.fromToken, amountWei: args.fromAmount, dstTokenAddress: args.toToken, dstChainId: args.chainId } }); } // node_modules/thirdweb/dist/esm/react/core/hooks/wallets/useActiveWalletChain.js var import_react13 = __toESM(require_react(), 1); function useActiveWalletChain() { const manager = useConnectionManagerCtx("useActiveWalletChain"); const store = manager.activeWalletChainStore; return (0, import_react13.useSyncExternalStore)(store.subscribe, store.getValue, store.getValue); } // node_modules/thirdweb/dist/esm/react/core/hooks/wallets/useConnectedWallets.js var import_react14 = __toESM(require_react(), 1); function useConnectedWallets() { const manager = useConnectionManagerCtx("useConnectedWallets"); const store = manager.connectedWallets; return (0, import_react14.useSyncExternalStore)(store.subscribe, store.getValue, store.getValue); } // node_modules/thirdweb/dist/esm/react/core/hooks/wallets/useAdminWallet.js function useAdminWallet() { var _a; const activeWallet = useActiveWallet(); const connectedWallets = useConnectedWallets(); const adminAccount = (_a = activeWallet == null ? void 0 : activeWallet.getAdminAccount) == null ? void 0 : _a.call(activeWallet); if (!adminAccount) { return activeWallet; } return connectedWallets.find((wallet) => { var _a2, _b, _c; return ((_b = (_a2 = wallet.getAccount()) == null ? void 0 : _a2.address) == null ? void 0 : _b.toLowerCase()) === ((_c = adminAccount == null ? void 0 : adminAccount.address) == null ? void 0 : _c.toLowerCase()); }); } // node_modules/thirdweb/dist/esm/react/core/hooks/wallets/useDisconnect.js function useDisconnect() { const manager = useConnectionManagerCtx("useDisconnect"); const disconnect = manager.disconnectWallet; return { disconnect }; } // node_modules/thirdweb/dist/esm/react/core/hooks/wallets/useSwitchActiveWalletChain.js function useSwitchActiveWalletChain() { const manager = useConnectionManagerCtx("useSwitchActiveWalletChain"); return manager.switchActiveWalletChain; } // node_modules/thirdweb/dist/esm/react/core/providers/RootElementContext.js var import_react15 = __toESM(require_react(), 1); var SetRootElementContext = (0, import_react15.createContext)(() => { }); // node_modules/thirdweb/dist/esm/react/web/ui/components/ChainIcon.js var import_jsx_runtime15 = __toESM(require_jsx_runtime(), 1); var fallbackChainIcon = "data:image/svg+xml;charset=UTF-8,%3csvg width='15' height='14' viewBox='0 0 15 14' fill='none' xmlns='http://www.w3.org/2000/svg'%3e%3cpath d='M7 8.04238e-07C5.1435 8.04238e-07 3.36301 0.737501 2.05025 2.05025C0.7375 3.36301 0 5.1435 0 7C0 7.225 -1.52737e-07 7.445 0.0349998 7.665C0.16385 9.0151 0.68213 10.2988 1.52686 11.3598C2.37158 12.4209 3.50637 13.2137 4.79326 13.642C6.0801 14.0702 7.4637 14.1153 8.7758 13.7719C10.0879 13.4285 11.2719 12.7113 12.184 11.7075C13.0961 10.7038 13.6969 9.4567 13.9135 8.1178C14.1301 6.7789 13.9531 5.406 13.4039 4.16587C12.8548 2.92574 11.9573 1.87184 10.8204 1.13228C9.6835 0.392721 8.3563 -0.000649196 7 8.04238e-07ZM7 1C8.581 1.00137 10.0975 1.62668 11.22 2.74V3.24C9.2438 2.55991 7.0956 2.56872 5.125 3.265C4.96758 3.1116 4.76997 3.00586 4.555 2.96H4.43C4.37 2.75 4.315 2.54 4.27 2.325C4.225 2.11 4.2 1.92 4.175 1.715C5.043 1.24658 6.0137 1.00091 7 1ZM5.5 3.935C7.3158 3.32693 9.2838 3.34984 11.085 4C10.8414 5.2703 10.3094 6.4677 9.53 7.5C9.312 7.4077 9.0707 7.3855 8.8395 7.4366C8.6083 7.4877 8.3988 7.6094 8.24 7.785C8.065 7.685 7.89 7.585 7.74 7.47C6.7307 6.7966 5.8877 5.9023 5.275 4.855C5.374 4.73221 5.4461 4.58996 5.4866 4.43749C5.5271 4.28502 5.5351 4.12575 5.51 3.97L5.5 3.935ZM3.5 2.135C3.5 2.24 3.53 2.35 3.55 2.455C3.595 2.675 3.655 2.89 3.715 3.105C3.52353 3.21838 3.36943 3.38531 3.2717 3.58522C3.17397 3.78513 3.13688 4.00927 3.165 4.23C2.37575 4.7454 1.67078 5.3795 1.075 6.11C1.19455 5.3189 1.47112 4.55966 1.88843 3.87701C2.30575 3.19437 2.85539 2.60208 3.505 2.135H3.5ZM3.5 9.99C3.30481 10.0555 3.13037 10.1714 2.9943 10.3259C2.85822 10.4804 2.76533 10.6681 2.725 10.87H2.405C1.59754 9.9069 1.1146 8.7136 1.025 7.46L1.08 7.365C1.70611 6.3942 2.52463 5.562 3.485 4.92C3.62899 5.0704 3.81094 5.179 4.01162 5.2345C4.2123 5.2899 4.42423 5.2901 4.625 5.235C5.2938 6.3652 6.208 7.3306 7.3 8.06C7.505 8.195 7.715 8.32 7.925 8.44C7.9082 8.6312 7.9391 8.8237 8.015 9C7.1 9.7266 6.0445 10.256 4.915 10.555C4.78401 10.3103 4.57028 10.1201 4.31199 10.0184C4.05369 9.9167 3.76766 9.9102 3.505 10L3.5 9.99ZM7 12.99C5.9831 12.9903 4.98307 12.7304 4.095 12.235L4.235 12.205C4.43397 12.1397 4.61176 12.0222 4.74984 11.8648C4.88792 11.7074 4.98122 11.5158 5.02 11.31C6.2985 10.984 7.4921 10.3872 8.52 9.56C8.7642 9.7027 9.0525 9.75 9.3295 9.6927C9.6064 9.6355 9.8524 9.4778 10.02 9.25C10.7254 9.4334 11.4511 9.5275 12.18 9.53H12.445C11.9626 10.5673 11.1938 11.4451 10.2291 12.0599C9.2643 12.6747 8.144 13.0009 7 13V12.99ZM10.255 8.54C10.2545 8.3304 10.1975 8.1249 10.09 7.945C10.9221 6.8581 11.5012 5.5991 11.785 4.26C12.035 4.37667 12.2817 4.50667 12.525 4.65C13.0749 5.9495 13.1493 7.4012 12.735 8.75C11.9049 8.8142 11.0698 8.7484 10.26 8.555L10.255 8.54Z' fill='%23646D7A'/%3e%3c/svg%3e"; var ChainIcon = (props) => { const getSrc = () => { const url = props.chainIconUrl; if (!url) { return fallbackChainIcon; } try { return resolveScheme({ uri: url, client: props.client }); } catch { return fallbackChainIcon; } }; return (0, import_jsx_runtime15.jsxs)(Container, { style: { position: "relative", display: "flex", flexShrink: 0, alignItems: "center" }, children: [(0, import_jsx_runtime15.jsx)(Img, { src: getSrc(), width: props.size, height: props.size, fallbackImage: fallbackChainIcon, client: props.client }), props.active && (0, import_jsx_runtime15.jsx)(ActiveDot, {})] }); }; var ActiveDot = StyledDiv({ width: "28%", height: "28%", borderRadius: "50%", position: "absolute", bottom: 0, right: 0, backgroundColor: "#00d395", boxShadow: "0 0 0 2px var(--bg)" }); // node_modules/thirdweb/dist/esm/react/web/ui/components/CopyIcon.js var import_jsx_runtime22 = __toESM(require_jsx_runtime(), 1); // node_modules/thirdweb/dist/esm/react/web/ui/hooks/useCopyClipboard.js var import_react16 = __toESM(require_react(), 1); function useClipboard(text) { const [hasCopied, setHasCopied] = (0, import_react16.useState)(false); const onCopy = (0, import_react16.useCallback)(async () => { await navigator.clipboard.writeText(text); setHasCopied(true); }, [text]); (0, import_react16.useEffect)(() => { let timeoutId = null; if (hasCopied) { timeoutId = window.setTimeout(() => { setHasCopied(false); }, 1500); } return () => { if (timeoutId) { window.clearTimeout(timeoutId); } }; }, [hasCopied]); return { onCopy, hasCopied }; } // node_modules/thirdweb/dist/esm/react/web/ui/components/Tooltip.js var import_jsx_runtime21 = __toESM(require_jsx_runtime(), 1); // node_modules/@radix-ui/react-tooltip/dist/index.mjs var React32 = __toESM(require_react(), 1); // node_modules/@radix-ui/react-popper/dist/index.mjs var React30 = __toESM(require_react(), 1); // node_modules/@floating-ui/utils/dist/floating-ui.utils.mjs var sides = ["top", "right", "bottom", "left"]; var alignments = ["start", "end"]; var placements = sides.reduce((acc, side) => acc.concat(side, side + "-" + alignments[0], side + "-" + alignments[1]), []); var min = Math.min; var max = Math.max; var round = Math.round; var floor = Math.floor; var createCoords = (v) => ({ x: v, y: v }); var oppositeSideMap = { left: "right", right: "left", bottom: "top", top: "bottom" }; var oppositeAlignmentMap = { start: "end", end: "start" }; function clamp(start, value, end) { return max(start, min(value, end)); } function evaluate(value, param) { return typeof value === "function" ? value(param) : value; } function getSide(placement) { return placement.split("-")[0]; } function getAlignment(placement) { return placement.split("-")[1]; } function getOppositeAxis(axis) { return axis === "x" ? "y" : "x"; } function getAxisLength(axis) { return axis === "y" ? "height" : "width"; } function getSideAxis(placement) { return ["top", "bottom"].includes(getSide(placement)) ? "y" : "x"; } function getAlignmentAxis(placement) { return getOppositeAxis(getSideAxis(placement)); } function getAlignmentSides(placement, rects, rtl) { if (rtl === void 0) { rtl = false; } const alignment = getAlignment(placement); const alignmentAxis = getAlignmentAxis(placement); const length = getAxisLength(alignmentAxis); let mainAlignmentSide = alignmentAxis === "x" ? alignment === (rtl ? "end" : "start") ? "right" : "left" : alignment === "start" ? "bottom" : "top"; if (rects.reference[length] > rects.floating[length]) { mainAlignmentSide = getOppositePlacement(mainAlignmentSide); } return [mainAlignmentSide, getOppositePlacement(mainAlignmentSide)]; } function getExpandedPlacements(placement) { const oppositePlacement = getOppositePlacement(placement); return [getOppositeAlignmentPlacement(placement), oppositePlacement, getOppositeAlignmentPlacement(oppositePlacement)]; } function getOppositeAlignmentPlacement(placement) { return placement.replace(/start|end/g, (alignment) => oppositeAlignmentMap[alignment]); } function getSideList(side, isStart, rtl) { const lr = ["left", "right"]; const rl = ["right", "left"]; const tb = ["top", "bottom"]; const bt = ["bottom", "top"]; switch (side) { case "top": case "bottom": if (rtl) return isStart ? rl : lr; return isStart ? lr : rl; case "left": case "right": return isStart ? tb : bt; default: return []; } } function getOppositeAxisPlacements(placement, flipAlignment, direction, rtl) { const alignment = getAlignment(placement); let list = getSideList(getSide(placement), direction === "start", rtl); if (alignment) { list = list.map((side) => side + "-" + alignment); if (flipAlignment) { list = list.concat(list.map(getOppositeAlignmentPlacement)); } } return list; } function getOppositePlacement(placement) { return placement.replace(/left|right|bottom|top/g, (side) => oppositeSideMap[side]); } function expandPaddingObject(padding) { return { top: 0, right: 0, bottom: 0, left: 0, ...padding }; } function getPaddingObject(padding) { return typeof padding !== "number" ? expandPaddingObject(padding) : { top: padding, right: padding, bottom: padding, left: padding }; } function rectToClientRect(rect) { const { x, y, width, height } = rect; return { width, height, top: y, left: x, right: x + width, bottom: y + height, x, y }; } // node_modules/@floating-ui/core/dist/floating-ui.core.mjs function computeCoordsFromPlacement(_ref, placement, rtl) { let { reference, floating } = _ref; const sideAxis = getSideAxis(placement); const alignmentAxis = getAlignmentAxis(placement); const alignLength = getAxisLength(alignmentAxis); const side = getSide(placement); const isVertical = sideAxis === "y"; const commonX = reference.x + reference.width / 2 - floating.width / 2; const commonY = reference.y + reference.height / 2 - floating.height / 2; const commonAlign = reference[alignLength] / 2 - floating[alignLength] / 2; let coords; switch (side) { case "top": coords = { x: commonX, y: reference.y - floating.height }; break; case "bottom": coords = { x: commonX, y: reference.y + reference.height }; break; case "right": coords = { x: reference.x + reference.width, y: commonY }; break; case "left": coords = { x: reference.x - floating.width, y: commonY }; break; default: coords = { x: reference.x, y: reference.y }; } switch (getAlignment(placement)) { case "start": coords[alignmentAxis] -= commonAlign * (rtl && isVertical ? -1 : 1); break; case "end": coords[alignmentAxis] += commonAlign * (rtl && isVertical ? -1 : 1); break; } return coords; } var computePosition = async (reference, floating, config) => { const { placement = "bottom", strategy = "absolute", middleware = [], platform: platform2 } = config; const validMiddleware = middleware.filter(Boolean); const rtl = await (platform2.isRTL == null ? void 0 : platform2.isRTL(floating)); let rects = await platform2.getElementRects({ reference, floating, strategy }); let { x, y } = computeCoordsFromPlacement(rects, placement, rtl); let statefulPlacement = placement; let middlewareData = {}; let resetCount = 0; for (let i = 0; i < validMiddleware.length; i++) { const { name, fn } = validMiddleware[i]; const { x: nextX, y: nextY, data, reset } = await fn({ x, y, initialPlacement: placement, placement: statefulPlacement, strategy, middlewareData, rects, platform: platform2, elements: { reference, floating } }); x = nextX != null ? nextX : x; y = nextY != null ? nextY : y; middlewareData = { ...middlewareData, [name]: { ...middlewareData[name], ...data } }; if (reset && resetCount <= 50) { resetCount++; if (typeof reset === "object") { if (reset.placement) { statefulPlacement = reset.placement; } if (reset.rects) { rects = reset.rects === true ? await platform2.getElementRects({ reference, floating, strategy }) : reset.rects; } ({ x, y } = computeCoordsFromPlacement(rects, statefulPlacement, rtl)); } i = -1; } } return { x, y, placement: statefulPlacement, strategy, middlewareData }; }; async function detectOverflow(state, options) { var _await$platform$isEle; if (options === void 0) { options = {}; } const { x, y, platform: platform2, rects, elements, strategy } = state; const { boundary = "clippingAncestors", rootBoundary = "viewport", elementContext = "floating", altBoundary = false, padding = 0 } = evaluate(options, state); const paddingObject = getPaddingObject(padding); const altContext = elementContext === "floating" ? "reference" : "floating"; const element = elements[altBoundary ? altContext : elementContext]; const clippingClientRect = rectToClientRect(await platform2.getClippingRect({ element: ((_await$platform$isEle = await (platform2.isElement == null ? void 0 : platform2.isElement(element))) != null ? _await$platform$isEle : true) ? element : element.contextElement || await (platform2.getDocumentElement == null ? void 0 : platform2.getDocumentElement(elements.floating)), boundary, rootBoundary, strategy })); const rect = elementContext === "floating" ? { x, y, width: rects.floating.width, height: rects.floating.height } : rects.reference; const offsetParent = await (platform2.getOffsetParent == null ? void 0 : platform2.getOffsetParent(elements.floating)); const offsetScale = await (platform2.isElement == null ? void 0 : platform2.isElement(offsetParent)) ? await (platform2.getScale == null ? void 0 : platform2.getScale(offsetParent)) || { x: 1, y: 1 } : { x: 1, y: 1 }; const elementClientRect = rectToClientRect(platform2.convertOffsetParentRelativeRectToViewportRelativeRect ? await platform2.convertOffsetParentRelativeRectToViewportRelativeRect({ elements, rect, offsetParent, strategy }) : rect); return { top: (clippingClientRect.top - elementClientRect.top + paddingObject.top) / offsetScale.y, bottom: (elementClientRect.bottom - clippingClientRect.bottom + paddingObject.bottom) / offsetScale.y, left: (clippingClientRect.left - elementClientRect.left + paddingObject.left) / offsetScale.x, right: (elementClientRect.right - clippingClientRect.right + paddingObject.right) / offsetScale.x }; } var arrow = (options) => ({ name: "arrow", options, async fn(state) { const { x, y, placement, rects, platform: platform2, elements, middlewareData } = state; const { element, padding = 0 } = evaluate(options, state) || {}; if (element == null) { return {}; } const paddingObject = getPaddingObject(padding); const coords = { x, y }; const axis = getAlignmentAxis(placement); const length = getAxisLength(axis); const arrowDimensions = await platform2.getDimensions(element); const isYAxis = axis === "y"; const minProp = isYAxis ? "top" : "left"; const maxProp = isYAxis ? "bottom" : "right"; const clientProp = isYAxis ? "clientHeight" : "clientWidth"; const endDiff = rects.reference[length] + rects.reference[axis] - coords[axis] - rects.floating[length]; const startDiff = coords[axis] - rects.reference[axis]; const arrowOffsetParent = await (platform2.getOffsetParent == null ? void 0 : platform2.getOffsetParent(element)); let clientSize = arrowOffsetParent ? arrowOffsetParent[clientProp] : 0; if (!clientSize || !await (platform2.isElement == null ? void 0 : platform2.isElement(arrowOffsetParent))) { clientSize = elements.floating[clientProp] || rects.floating[length]; } const centerToReference = endDiff / 2 - startDiff / 2; const largestPossiblePadding = clientSize / 2 - arrowDimensions[length] / 2 - 1; const minPadding = min(paddingObject[minProp], largestPossiblePadding); const maxPadding = min(paddingObject[maxProp], largestPossiblePadding); const min$1 = minPadding; const max2 = clientSize - arrowDimensions[length] - maxPadding; const center = clientSize / 2 - arrowDimensions[length] / 2 + centerToReference; const offset4 = clamp(min$1, center, max2); const shouldAddOffset = !middlewareData.arrow && getAlignment(placement) != null && center !== offset4 && rects.reference[length] / 2 - (center < min$1 ? minPadding : maxPadding) - arrowDimensions[length] / 2 < 0; const alignmentOffset = shouldAddOffset ? center < min$1 ? center - min$1 : center - max2 : 0; return { [axis]: coords[axis] + alignmentOffset, data: { [axis]: offset4, centerOffset: center - offset4 - alignmentOffset, ...shouldAddOffset && { alignmentOffset } }, reset: shouldAddOffset }; } }); var flip = function(options) { if (options === void 0) { options = {}; } return { name: "flip", options, async fn(state) { var _middlewareData$arrow, _middlewareData$flip; const { placement, middlewareData, rects, initialPlacement, platform: platform2, elements } = state; const { mainAxis: checkMainAxis = true, crossAxis: checkCrossAxis = true, fallbackPlacements: specifiedFallbackPlacements, fallbackStrategy = "bestFit", fallbackAxisSideDirection = "none", flipAlignment = true, ...detectOverflowOptions } = evaluate(options, state); if ((_middlewareData$arrow = middlewareData.arrow) != null && _middlewareData$arrow.alignmentOffset) { return {}; } const side = getSide(placement); const initialSideAxis = getSideAxis(initialPlacement); const isBasePlacement = getSide(initialPlacement) === initialPlacement; const rtl = await (platform2.isRTL == null ? void 0 : platform2.isRTL(elements.floating)); const fallbackPlacements = specifiedFallbackPlacements || (isBasePlacement || !flipAlignment ? [getOppositePlacement(initialPlacement)] : getExpandedPlacements(initialPlacement)); const hasFallbackAxisSideDirection = fallbackAxisSideDirection !== "none"; if (!specifiedFallbackPlacements && hasFallbackAxisSideDirection) { fallbackPlacements.push(...getOppositeAxisPlacements(initialPlacement, flipAlignment, fallbackAxisSideDirection, rtl)); } const placements2 = [initialPlacement, ...fallbackPlacements]; const overflow = await detectOverflow(state, detectOverflowOptions); const overflows = []; let overflowsData = ((_middlewareData$flip = middlewareData.flip) == null ? void 0 : _middlewareData$flip.overflows) || []; if (checkMainAxis) { overflows.push(overflow[side]); } if (checkCrossAxis) { const sides2 = getAlignmentSides(placement, rects, rtl); overflows.push(overflow[sides2[0]], overflow[sides2[1]]); } overflowsData = [...overflowsData, { placement, overflows }]; if (!overflows.every((side2) => side2 <= 0)) { var _middlewareData$flip2, _overflowsData$filter; const nextIndex = (((_middlewareData$flip2 = middlewareData.flip) == null ? void 0 : _middlewareData$flip2.index) || 0) + 1; const nextPlacement = placements2[nextIndex]; if (nextPlacement) { return { data: { index: nextIndex, overflows: overflowsData }, reset: { placement: nextPlacement } }; } let resetPlacement = (_overflowsData$filter = overflowsData.filter((d) => d.overflows[0] <= 0).sort((a, b) => a.overflows[1] - b.overflows[1])[0]) == null ? void 0 : _overflowsData$filter.placement; if (!resetPlacement) { switch (fallbackStrategy) { case "bestFit": { var _overflowsData$filter2; const placement2 = (_overflowsData$filter2 = overflowsData.filter((d) => { if (hasFallbackAxisSideDirection) { const currentSideAxis = getSideAxis(d.placement); return currentSideAxis === initialSideAxis || // Create a bias to the `y` side axis due to horizontal // reading directions favoring greater width. currentSideAxis === "y"; } return true; }).map((d) => [d.placement, d.overflows.filter((overflow2) => overflow2 > 0).reduce((acc, overflow2) => acc + overflow2, 0)]).sort((a, b) => a[1] - b[1])[0]) == null ? void 0 : _overflowsData$filter2[0]; if (placement2) { resetPlacement = placement2; } break; } case "initialPlacement": resetPlacement = initialPlacement; break; } } if (placement !== resetPlacement) { return { reset: { placement: resetPlacement } }; } } return {}; } }; }; function getSideOffsets(overflow, rect) { return { top: overflow.top - rect.height, right: overflow.right - rect.width, bottom: overflow.bottom - rect.height, left: overflow.left - rect.width }; } function isAnySideFullyClipped(overflow) { return sides.some((side) => overflow[side] >= 0); } var hide = function(options) { if (options === void 0) { options = {}; } return { name: "hide", options, async fn(state) { const { rects } = state; const { strategy = "referenceHidden", ...detectOverflowOptions } = evaluate(options, state); switch (strategy) { case "referenceHidden": { const overflow = await detectOverflow(state, { ...detectOverflowOptions, elementContext: "reference" }); const offsets = getSideOffsets(overflow, rects.reference); return { data: { referenceHiddenOffsets: offsets, referenceHidden: isAnySideFullyClipped(offsets) } }; } case "escaped": { const overflow = await detectOverflow(state, { ...detectOverflowOptions, altBoundary: true }); const offsets = getSideOffsets(overflow, rects.floating); return { data: { escapedOffsets: offsets, escaped: isAnySideFullyClipped(offsets) } }; } default: { return {}; } } } }; }; async function convertValueToCoords(state, options) { const { placement, platform: platform2, elements } = state; const rtl = await (platform2.isRTL == null ? void 0 : platform2.isRTL(elements.floating)); const side = getSide(placement); const alignment = getAlignment(placement); const isVertical = getSideAxis(placement) === "y"; const mainAxisMulti = ["left", "top"].includes(side) ? -1 : 1; const crossAxisMulti = rtl && isVertical ? -1 : 1; const rawValue = evaluate(options, state); let { mainAxis, crossAxis, alignmentAxis } = typeof rawValue === "number" ? { mainAxis: rawValue, crossAxis: 0, alignmentAxis: null } : { mainAxis: rawValue.mainAxis || 0, crossAxis: rawValue.crossAxis || 0, alignmentAxis: rawValue.alignmentAxis }; if (alignment && typeof alignmentAxis === "number") { crossAxis = alignment === "end" ? alignmentAxis * -1 : alignmentAxis; } return isVertical ? { x: crossAxis * crossAxisMulti, y: mainAxis * mainAxisMulti } : { x: mainAxis * mainAxisMulti, y: crossAxis * crossAxisMulti }; } var offset = function(options) { if (options === void 0) { options = 0; } return { name: "offset", options, async fn(state) { var _middlewareData$offse, _middlewareData$arrow; const { x, y, placement, middlewareData } = state; const diffCoords = await convertValueToCoords(state, options); if (placement === ((_middlewareData$offse = middlewareData.offset) == null ? void 0 : _middlewareData$offse.placement) && (_middlewareData$arrow = middlewareData.arrow) != null && _middlewareData$arrow.alignmentOffset) { return {}; } return { x: x + diffCoords.x, y: y + diffCoords.y, data: { ...diffCoords, placement } }; } }; }; var shift = function(options) { if (options === void 0) { options = {}; } return { name: "shift", options, async fn(state) { const { x, y, placement } = state; const { mainAxis: checkMainAxis = true, crossAxis: checkCrossAxis = false, limiter = { fn: (_ref) => { let { x: x2, y: y2 } = _ref; return { x: x2, y: y2 }; } }, ...detectOverflowOptions } = evaluate(options, state); const coords = { x, y }; const overflow = await detectOverflow(state, detectOverflowOptions); const crossAxis = getSideAxis(getSide(placement)); const mainAxis = getOppositeAxis(crossAxis); let mainAxisCoord = coords[mainAxis]; let crossAxisCoord = coords[crossAxis]; if (checkMainAxis) { const minSide = mainAxis === "y" ? "top" : "left"; const maxSide = mainAxis === "y" ? "bottom" : "right"; const min2 = mainAxisCoord + overflow[minSide]; const max2 = mainAxisCoord - overflow[maxSide]; mainAxisCoord = clamp(min2, mainAxisCoord, max2); } if (checkCrossAxis) { const minSide = crossAxis === "y" ? "top" : "left"; const maxSide = crossAxis === "y" ? "bottom" : "right"; const min2 = crossAxisCoord + overflow[minSide]; const max2 = crossAxisCoord - overflow[maxSide]; crossAxisCoord = clamp(min2, crossAxisCoord, max2); } const limitedCoords = limiter.fn({ ...state, [mainAxis]: mainAxisCoord, [crossAxis]: crossAxisCoord }); return { ...limitedCoords, data: { x: limitedCoords.x - x, y: limitedCoords.y - y, enabled: { [mainAxis]: checkMainAxis, [crossAxis]: checkCrossAxis } } }; } }; }; var limitShift = function(options) { if (options === void 0) { options = {}; } return { options, fn(state) { const { x, y, placement, rects, middlewareData } = state; const { offset: offset4 = 0, mainAxis: checkMainAxis = true, crossAxis: checkCrossAxis = true } = evaluate(options, state); const coords = { x, y }; const crossAxis = getSideAxis(placement); const mainAxis = getOppositeAxis(crossAxis); let mainAxisCoord = coords[mainAxis]; let crossAxisCoord = coords[crossAxis]; const rawOffset = evaluate(offset4, state); const computedOffset = typeof rawOffset === "number" ? { mainAxis: rawOffset, crossAxis: 0 } : { mainAxis: 0, crossAxis: 0, ...rawOffset }; if (checkMainAxis) { const len = mainAxis === "y" ? "height" : "width"; const limitMin = rects.reference[mainAxis] - rects.floating[len] + computedOffset.mainAxis; const limitMax = rects.reference[mainAxis] + rects.reference[len] - computedOffset.mainAxis; if (mainAxisCoord < limitMin) { mainAxisCoord = limitMin; } else if (mainAxisCoord > limitMax) { mainAxisCoord = limitMax; } } if (checkCrossAxis) { var _middlewareData$offse, _middlewareData$offse2; const len = mainAxis === "y" ? "width" : "height"; const isOriginSide = ["top", "left"].includes(getSide(placement)); const limitMin = rects.reference[crossAxis] - rects.floating[len] + (isOriginSide ? ((_middlewareData$offse = middlewareData.offset) == null ? void 0 : _middlewareData$offse[crossAxis]) || 0 : 0) + (isOriginSide ? 0 : computedOffset.crossAxis); const limitMax = rects.reference[crossAxis] + rects.reference[len] + (isOriginSide ? 0 : ((_middlewareData$offse2 = middlewareData.offset) == null ? void 0 : _middlewareData$offse2[crossAxis]) || 0) - (isOriginSide ? computedOffset.crossAxis : 0); if (crossAxisCoord < limitMin) { crossAxisCoord = limitMin; } else if (crossAxisCoord > limitMax) { crossAxisCoord = limitMax; } } return { [mainAxis]: mainAxisCoord, [crossAxis]: crossAxisCoord }; } }; }; var size = function(options) { if (options === void 0) { options = {}; } return { name: "size", options, async fn(state) { var _state$middlewareData, _state$middlewareData2; const { placement, rects, platform: platform2, elements } = state; const { apply = () => { }, ...detectOverflowOptions } = evaluate(options, state); const overflow = await detectOverflow(state, detectOverflowOptions); const side = getSide(placement); const alignment = getAlignment(placement); const isYAxis = getSideAxis(placement) === "y"; const { width, height } = rects.floating; let heightSide; let widthSide; if (side === "top" || side === "bottom") { heightSide = side; widthSide = alignment === (await (platform2.isRTL == null ? void 0 : platform2.isRTL(elements.floating)) ? "start" : "end") ? "left" : "right"; } else { widthSide = side; heightSide = alignment === "end" ? "top" : "bottom"; } const maximumClippingHeight = height - overflow.top - overflow.bottom; const maximumClippingWidth = width - overflow.left - overflow.right; const overflowAvailableHeight = min(height - overflow[heightSide], maximumClippingHeight); const overflowAvailableWidth = min(width - overflow[widthSide], maximumClippingWidth); const noShift = !state.middlewareData.shift; let availableHeight = overflowAvailableHeight; let availableWidth = overflowAvailableWidth; if ((_state$middlewareData = state.middlewareData.shift) != null && _state$middlewareData.enabled.x) { availableWidth = maximumClippingWidth; } if ((_state$middlewareData2 = state.middlewareData.shift) != null && _state$middlewareData2.enabled.y) { availableHeight = maximumClippingHeight; } if (noShift && !alignment) { const xMin = max(overflow.left, 0); const xMax = max(overflow.right, 0); const yMin = max(overflow.top, 0); const yMax = max(overflow.bottom, 0); if (isYAxis) { availableWidth = width - 2 * (xMin !== 0 || xMax !== 0 ? xMin + xMax : max(overflow.left, overflow.right)); } else { availableHeight = height - 2 * (yMin !== 0 || yMax !== 0 ? yMin + yMax : max(overflow.top, overflow.bottom)); } } await apply({ ...state, availableWidth, availableHeight }); const nextDimensions = await platform2.getDimensions(elements.floating); if (width !== nextDimensions.width || height !== nextDimensions.height) { return { reset: { rects: true } }; } return {}; } }; }; // node_modules/@floating-ui/utils/dist/floating-ui.utils.dom.mjs function hasWindow() { return typeof window !== "undefined"; } function getNodeName(node) { if (isNode2(node)) { return (node.nodeName || "").toLowerCase(); } return "#document"; } function getWindow(node) { var _node$ownerDocument; return (node == null || (_node$ownerDocument = node.ownerDocument) == null ? void 0 : _node$ownerDocument.defaultView) || window; } function getDocumentElement(node) { var _ref; return (_ref = (isNode2(node) ? node.ownerDocument : node.document) || window.document) == null ? void 0 : _ref.documentElement; } function isNode2(value) { if (!hasWindow()) { return false; } return value instanceof Node || value instanceof getWindow(value).Node; } function isElement(value) { if (!hasWindow()) { return false; } return value instanceof Element || value instanceof getWindow(value).Element; } function isHTMLElement(value) { if (!hasWindow()) { return false; } return value instanceof HTMLElement || value instanceof getWindow(value).HTMLElement; } function isShadowRoot(value) { if (!hasWindow() || typeof ShadowRoot === "undefined") { return false; } return value instanceof ShadowRoot || value instanceof getWindow(value).ShadowRoot; } function isOverflowElement(element) { const { overflow, overflowX, overflowY, display } = getComputedStyle2(element); return /auto|scroll|overlay|hidden|clip/.test(overflow + overflowY + overflowX) && !["inline", "contents"].includes(display); } function isTableElement(element) { return ["table", "td", "th"].includes(getNodeName(element)); } function isTopLayer(element) { return [":popover-open", ":modal"].some((selector) => { try { return element.matches(selector); } catch (e) { return false; } }); } function isContainingBlock(elementOrCss) { const webkit = isWebKit(); const css = isElement(elementOrCss) ? getComputedStyle2(elementOrCss) : elementOrCss; return css.transform !== "none" || css.perspective !== "none" || (css.containerType ? css.containerType !== "normal" : false) || !webkit && (css.backdropFilter ? css.backdropFilter !== "none" : false) || !webkit && (css.filter ? css.filter !== "none" : false) || ["transform", "perspective", "filter"].some((value) => (css.willChange || "").includes(value)) || ["paint", "layout", "strict", "content"].some((value) => (css.contain || "").includes(value)); } function getContainingBlock(element) { let currentNode = getParentNode(element); while (isHTMLElement(currentNode) && !isLastTraversableNode(currentNode)) { if (isContainingBlock(currentNode)) { return currentNode; } else if (isTopLayer(currentNode)) { return null; } currentNode = getParentNode(currentNode); } return null; } function isWebKit() { if (typeof CSS === "undefined" || !CSS.supports) return false; return CSS.supports("-webkit-backdrop-filter", "none"); } function isLastTraversableNode(node) { return ["html", "body", "#document"].includes(getNodeName(node)); } function getComputedStyle2(element) { return getWindow(element).getComputedStyle(element); } function getNodeScroll(element) { if (isElement(element)) { return { scrollLeft: element.scrollLeft, scrollTop: element.scrollTop }; } return { scrollLeft: element.scrollX, scrollTop: element.scrollY }; } function getParentNode(node) { if (getNodeName(node) === "html") { return node; } const result = ( // Step into the shadow DOM of the parent of a slotted node. node.assignedSlot || // DOM Element detected. node.parentNode || // ShadowRoot detected. isShadowRoot(node) && node.host || // Fallback. getDocumentElement(node) ); return isShadowRoot(result) ? result.host : result; } function getNearestOverflowAncestor(node) { const parentNode = getParentNode(node); if (isLastTraversableNode(parentNode)) { return node.ownerDocument ? node.ownerDocument.body : node.body; } if (isHTMLElement(parentNode) && isOverflowElement(parentNode)) { return parentNode; } return getNearestOverflowAncestor(parentNode); } function getOverflowAncestors(node, list, traverseIframes) { var _node$ownerDocument2; if (list === void 0) { list = []; } if (traverseIframes === void 0) { traverseIframes = true; } const scrollableAncestor = getNearestOverflowAncestor(node); const isBody = scrollableAncestor === ((_node$ownerDocument2 = node.ownerDocument) == null ? void 0 : _node$ownerDocument2.body); const win = getWindow(scrollableAncestor); if (isBody) { const frameElement = getFrameElement(win); return list.concat(win, win.visualViewport || [], isOverflowElement(scrollableAncestor) ? scrollableAncestor : [], frameElement && traverseIframes ? getOverflowAncestors(frameElement) : []); } return list.concat(scrollableAncestor, getOverflowAncestors(scrollableAncestor, [], traverseIframes)); } function getFrameElement(win) { return win.parent && Object.getPrototypeOf(win.parent) ? win.frameElement : null; } // node_modules/@floating-ui/dom/dist/floating-ui.dom.mjs function getCssDimensions(element) { const css = getComputedStyle2(element); let width = parseFloat(css.width) || 0; let height = parseFloat(css.height) || 0; const hasOffset = isHTMLElement(element); const offsetWidth = hasOffset ? element.offsetWidth : width; const offsetHeight = hasOffset ? element.offsetHeight : height; const shouldFallback = round(width) !== offsetWidth || round(height) !== offsetHeight; if (shouldFallback) { width = offsetWidth; height = offsetHeight; } return { width, height, $: shouldFallback }; } function unwrapElement(element) { return !isElement(element) ? element.contextElement : element; } function getScale(element) { const domElement = unwrapElement(element); if (!isHTMLElement(domElement)) { return createCoords(1); } const rect = domElement.getBoundingClientRect(); const { width, height, $ } = getCssDimensions(domElement); let x = ($ ? round(rect.width) : rect.width) / width; let y = ($ ? round(rect.height) : rect.height) / height; if (!x || !Number.isFinite(x)) { x = 1; } if (!y || !Number.isFinite(y)) { y = 1; } return { x, y }; } var noOffsets = createCoords(0); function getVisualOffsets(element) { const win = getWindow(element); if (!isWebKit() || !win.visualViewport) { return noOffsets; } return { x: win.visualViewport.offsetLeft, y: win.visualViewport.offsetTop }; } function shouldAddVisualOffsets(element, isFixed, floatingOffsetParent) { if (isFixed === void 0) { isFixed = false; } if (!floatingOffsetParent || isFixed && floatingOffsetParent !== getWindow(element)) { return false; } return isFixed; } function getBoundingClientRect(element, includeScale, isFixedStrategy, offsetParent) { if (includeScale === void 0) { includeScale = false; } if (isFixedStrategy === void 0) { isFixedStrategy = false; } const clientRect = element.getBoundingClientRect(); const domElement = unwrapElement(element); let scale = createCoords(1); if (includeScale) { if (offsetParent) { if (isElement(offsetParent)) { scale = getScale(offsetParent); } } else { scale = getScale(element); } } const visualOffsets = shouldAddVisualOffsets(domElement, isFixedStrategy, offsetParent) ? getVisualOffsets(domElement) : createCoords(0); let x = (clientRect.left + visualOffsets.x) / scale.x; let y = (clientRect.top + visualOffsets.y) / scale.y; let width = clientRect.width / scale.x; let height = clientRect.height / scale.y; if (domElement) { const win = getWindow(domElement); const offsetWin = offsetParent && isElement(offsetParent) ? getWindow(offsetParent) : offsetParent; let currentWin = win; let currentIFrame = getFrameElement(currentWin); while (currentIFrame && offsetParent && offsetWin !== currentWin) { const iframeScale = getScale(currentIFrame); const iframeRect = currentIFrame.getBoundingClientRect(); const css = getComputedStyle2(currentIFrame); const left = iframeRect.left + (currentIFrame.clientLeft + parseFloat(css.paddingLeft)) * iframeScale.x; const top = iframeRect.top + (currentIFrame.clientTop + parseFloat(css.paddingTop)) * iframeScale.y; x *= iframeScale.x; y *= iframeScale.y; width *= iframeScale.x; height *= iframeScale.y; x += left; y += top; currentWin = getWindow(currentIFrame); currentIFrame = getFrameElement(currentWin); } } return rectToClientRect({ width, height, x, y }); } function getWindowScrollBarX(element, rect) { const leftScroll = getNodeScroll(element).scrollLeft; if (!rect) { return getBoundingClientRect(getDocumentElement(element)).left + leftScroll; } return rect.left + leftScroll; } function getHTMLOffset(documentElement, scroll, ignoreScrollbarX) { if (ignoreScrollbarX === void 0) { ignoreScrollbarX = false; } const htmlRect = documentElement.getBoundingClientRect(); const x = htmlRect.left + scroll.scrollLeft - (ignoreScrollbarX ? 0 : ( // RTL scrollbar. getWindowScrollBarX(documentElement, htmlRect) )); const y = htmlRect.top + scroll.scrollTop; return { x, y }; } function convertOffsetParentRelativeRectToViewportRelativeRect(_ref) { let { elements, rect, offsetParent, strategy } = _ref; const isFixed = strategy === "fixed"; const documentElement = getDocumentElement(offsetParent); const topLayer = elements ? isTopLayer(elements.floating) : false; if (offsetParent === documentElement || topLayer && isFixed) { return rect; } let scroll = { scrollLeft: 0, scrollTop: 0 }; let scale = createCoords(1); const offsets = createCoords(0); const isOffsetParentAnElement = isHTMLElement(offsetParent); if (isOffsetParentAnElement || !isOffsetParentAnElement && !isFixed) { if (getNodeName(offsetParent) !== "body" || isOverflowElement(documentElement)) { scroll = getNodeScroll(offsetParent); } if (isHTMLElement(offsetParent)) { const offsetRect = getBoundingClientRect(offsetParent); scale = getScale(offsetParent); offsets.x = offsetRect.x + offsetParent.clientLeft; offsets.y = offsetRect.y + offsetParent.clientTop; } } const htmlOffset = documentElement && !isOffsetParentAnElement && !isFixed ? getHTMLOffset(documentElement, scroll, true) : createCoords(0); return { width: rect.width * scale.x, height: rect.height * scale.y, x: rect.x * scale.x - scroll.scrollLeft * scale.x + offsets.x + htmlOffset.x, y: rect.y * scale.y - scroll.scrollTop * scale.y + offsets.y + htmlOffset.y }; } function getClientRects(element) { return Array.from(element.getClientRects()); } function getDocumentRect(element) { const html = getDocumentElement(element); const scroll = getNodeScroll(element); const body = element.ownerDocument.body; const width = max(html.scrollWidth, html.clientWidth, body.scrollWidth, body.clientWidth); const height = max(html.scrollHeight, html.clientHeight, body.scrollHeight, body.clientHeight); let x = -scroll.scrollLeft + getWindowScrollBarX(element); const y = -scroll.scrollTop; if (getComputedStyle2(body).direction === "rtl") { x += max(html.clientWidth, body.clientWidth) - width; } return { width, height, x, y }; } function getViewportRect(element, strategy) { const win = getWindow(element); const html = getDocumentElement(element); const visualViewport = win.visualViewport; let width = html.clientWidth; let height = html.clientHeight; let x = 0; let y = 0; if (visualViewport) { width = visualViewport.width; height = visualViewport.height; const visualViewportBased = isWebKit(); if (!visualViewportBased || visualViewportBased && strategy === "fixed") { x = visualViewport.offsetLeft; y = visualViewport.offsetTop; } } return { width, height, x, y }; } function getInnerBoundingClientRect(element, strategy) { const clientRect = getBoundingClientRect(element, true, strategy === "fixed"); const top = clientRect.top + element.clientTop; const left = clientRect.left + element.clientLeft; const scale = isHTMLElement(element) ? getScale(element) : createCoords(1); const width = element.clientWidth * scale.x; const height = element.clientHeight * scale.y; const x = left * scale.x; const y = top * scale.y; return { width, height, x, y }; } function getClientRectFromClippingAncestor(element, clippingAncestor, strategy) { let rect; if (clippingAncestor === "viewport") { rect = getViewportRect(element, strategy); } else if (clippingAncestor === "document") { rect = getDocumentRect(getDocumentElement(element)); } else if (isElement(clippingAncestor)) { rect = getInnerBoundingClientRect(clippingAncestor, strategy); } else { const visualOffsets = getVisualOffsets(element); rect = { x: clippingAncestor.x - visualOffsets.x, y: clippingAncestor.y - visualOffsets.y, width: clippingAncestor.width, height: clippingAncestor.height }; } return rectToClientRect(rect); } function hasFixedPositionAncestor(element, stopNode) { const parentNode = getParentNode(element); if (parentNode === stopNode || !isElement(parentNode) || isLastTraversableNode(parentNode)) { return false; } return getComputedStyle2(parentNode).position === "fixed" || hasFixedPositionAncestor(parentNode, stopNode); } function getClippingElementAncestors(element, cache) { const cachedResult = cache.get(element); if (cachedResult) { return cachedResult; } let result = getOverflowAncestors(element, [], false).filter((el) => isElement(el) && getNodeName(el) !== "body"); let currentContainingBlockComputedStyle = null; const elementIsFixed = getComputedStyle2(element).position === "fixed"; let currentNode = elementIsFixed ? getParentNode(element) : element; while (isElement(currentNode) && !isLastTraversableNode(currentNode)) { const computedStyle = getComputedStyle2(currentNode); const currentNodeIsContaining = isContainingBlock(currentNode); if (!currentNodeIsContaining && computedStyle.position === "fixed") { currentContainingBlockComputedStyle = null; } const shouldDropCurrentNode = elementIsFixed ? !currentNodeIsContaining && !currentContainingBlockComputedStyle : !currentNodeIsContaining && computedStyle.position === "static" && !!currentContainingBlockComputedStyle && ["absolute", "fixed"].includes(currentContainingBlockComputedStyle.position) || isOverflowElement(currentNode) && !currentNodeIsContaining && hasFixedPositionAncestor(element, currentNode); if (shouldDropCurrentNode) { result = result.filter((ancestor) => ancestor !== currentNode); } else { currentContainingBlockComputedStyle = computedStyle; } currentNode = getParentNode(currentNode); } cache.set(element, result); return result; } function getClippingRect(_ref) { let { element, boundary, rootBoundary, strategy } = _ref; const elementClippingAncestors = boundary === "clippingAncestors" ? isTopLayer(element) ? [] : getClippingElementAncestors(element, this._c) : [].concat(boundary); const clippingAncestors = [...elementClippingAncestors, rootBoundary]; const firstClippingAncestor = clippingAncestors[0]; const clippingRect = clippingAncestors.reduce((accRect, clippingAncestor) => { const rect = getClientRectFromClippingAncestor(element, clippingAncestor, strategy); accRect.top = max(rect.top, accRect.top); accRect.right = min(rect.right, accRect.right); accRect.bottom = min(rect.bottom, accRect.bottom); accRect.left = max(rect.left, accRect.left); return accRect; }, getClientRectFromClippingAncestor(element, firstClippingAncestor, strategy)); return { width: clippingRect.right - clippingRect.left, height: clippingRect.bottom - clippingRect.top, x: clippingRect.left, y: clippingRect.top }; } function getDimensions(element) { const { width, height } = getCssDimensions(element); return { width, height }; } function getRectRelativeToOffsetParent(element, offsetParent, strategy) { const isOffsetParentAnElement = isHTMLElement(offsetParent); const documentElement = getDocumentElement(offsetParent); const isFixed = strategy === "fixed"; const rect = getBoundingClientRect(element, true, isFixed, offsetParent); let scroll = { scrollLeft: 0, scrollTop: 0 }; const offsets = createCoords(0); if (isOffsetParentAnElement || !isOffsetParentAnElement && !isFixed) { if (getNodeName(offsetParent) !== "body" || isOverflowElement(documentElement)) { scroll = getNodeScroll(offsetParent); } if (isOffsetParentAnElement) { const offsetRect = getBoundingClientRect(offsetParent, true, isFixed, offsetParent); offsets.x = offsetRect.x + offsetParent.clientLeft; offsets.y = offsetRect.y + offsetParent.clientTop; } else if (documentElement) { offsets.x = getWindowScrollBarX(documentElement); } } const htmlOffset = documentElement && !isOffsetParentAnElement && !isFixed ? getHTMLOffset(documentElement, scroll) : createCoords(0); const x = rect.left + scroll.scrollLeft - offsets.x - htmlOffset.x; const y = rect.top + scroll.scrollTop - offsets.y - htmlOffset.y; return { x, y, width: rect.width, height: rect.height }; } function isStaticPositioned(element) { return getComputedStyle2(element).position === "static"; } function getTrueOffsetParent(element, polyfill) { if (!isHTMLElement(element) || getComputedStyle2(element).position === "fixed") { return null; } if (polyfill) { return polyfill(element); } let rawOffsetParent = element.offsetParent; if (getDocumentElement(element) === rawOffsetParent) { rawOffsetParent = rawOffsetParent.ownerDocument.body; } return rawOffsetParent; } function getOffsetParent(element, polyfill) { const win = getWindow(element); if (isTopLayer(element)) { return win; } if (!isHTMLElement(element)) { let svgOffsetParent = getParentNode(element); while (svgOffsetParent && !isLastTraversableNode(svgOffsetParent)) { if (isElement(svgOffsetParent) && !isStaticPositioned(svgOffsetParent)) { return svgOffsetParent; } svgOffsetParent = getParentNode(svgOffsetParent); } return win; } let offsetParent = getTrueOffsetParent(element, polyfill); while (offsetParent && isTableElement(offsetParent) && isStaticPositioned(offsetParent)) { offsetParent = getTrueOffsetParent(offsetParent, polyfill); } if (offsetParent && isLastTraversableNode(offsetParent) && isStaticPositioned(offsetParent) && !isContainingBlock(offsetParent)) { return win; } return offsetParent || getContainingBlock(element) || win; } var getElementRects = async function(data) { const getOffsetParentFn = this.getOffsetParent || getOffsetParent; const getDimensionsFn = this.getDimensions; const floatingDimensions = await getDimensionsFn(data.floating); return { reference: getRectRelativeToOffsetParent(data.reference, await getOffsetParentFn(data.floating), data.strategy), floating: { x: 0, y: 0, width: floatingDimensions.width, height: floatingDimensions.height } }; }; function isRTL(element) { return getComputedStyle2(element).direction === "rtl"; } var platform = { convertOffsetParentRelativeRectToViewportRelativeRect, getDocumentElement, getClippingRect, getOffsetParent, getElementRects, getClientRects, getDimensions, getScale, isElement, isRTL }; function observeMove(element, onMove) { let io = null; let timeoutId; const root = getDocumentElement(element); function cleanup() { var _io; clearTimeout(timeoutId); (_io = io) == null || _io.disconnect(); io = null; } function refresh(skip, threshold) { if (skip === void 0) { skip = false; } if (threshold === void 0) { threshold = 1; } cleanup(); const { left, top, width, height } = element.getBoundingClientRect(); if (!skip) { onMove(); } if (!width || !height) { return; } const insetTop = floor(top); const insetRight = floor(root.clientWidth - (left + width)); const insetBottom = floor(root.clientHeight - (top + height)); const insetLeft = floor(left); const rootMargin = -insetTop + "px " + -insetRight + "px " + -insetBottom + "px " + -insetLeft + "px"; const options = { rootMargin, threshold: max(0, min(1, threshold)) || 1 }; let isFirstUpdate = true; function handleObserve(entries) { const ratio = entries[0].intersectionRatio; if (ratio !== threshold) { if (!isFirstUpdate) { return refresh(); } if (!ratio) { timeoutId = setTimeout(() => { refresh(false, 1e-7); }, 1e3); } else { refresh(false, ratio); } } isFirstUpdate = false; } try { io = new IntersectionObserver(handleObserve, { ...options, // Handle