repo_id
stringclasses
563 values
file_path
stringlengths
40
166
content
stringlengths
1
2.94M
__index_level_0__
int64
0
0
solana_public_repos/anza-xyz/wallet-adapter/packages/ui/react-ui
solana_public_repos/anza-xyz/wallet-adapter/packages/ui/react-ui/src/BaseWalletConnectionButton.tsx
import type { WalletName } from '@solana/wallet-adapter-base'; import React from 'react'; import { Button } from './Button.js'; import { WalletIcon } from './WalletIcon.js'; type Props = React.ComponentProps<typeof Button> & { walletIcon?: string; walletName?: WalletName; }; export function BaseWalletConnectionButton({ walletIcon, walletName, ...props }: Props) { return ( <Button {...props} className="wallet-adapter-button-trigger" startIcon={ walletIcon && walletName ? ( <WalletIcon wallet={{ adapter: { icon: walletIcon, name: walletName } }} /> ) : undefined } /> ); }
0
solana_public_repos/anza-xyz/wallet-adapter/packages/ui/react-ui
solana_public_repos/anza-xyz/wallet-adapter/packages/ui/react-ui/src/WalletListItem.tsx
import { WalletReadyState } from '@solana/wallet-adapter-base'; import type { Wallet } from '@solana/wallet-adapter-react'; import type { FC, MouseEventHandler } from 'react'; import React from 'react'; import { Button } from './Button.js'; import { WalletIcon } from './WalletIcon.js'; export interface WalletListItemProps { handleClick: MouseEventHandler<HTMLButtonElement>; tabIndex?: number; wallet: Wallet; } export const WalletListItem: FC<WalletListItemProps> = ({ handleClick, tabIndex, wallet }) => { return ( <li> <Button onClick={handleClick} startIcon={<WalletIcon wallet={wallet} />} tabIndex={tabIndex}> {wallet.adapter.name} {wallet.readyState === WalletReadyState.Installed && <span>Detected</span>} </Button> </li> ); };
0
solana_public_repos/anza-xyz/wallet-adapter/packages/ui/react-ui
solana_public_repos/anza-xyz/wallet-adapter/packages/ui/react-ui/src/BaseWalletConnectButton.tsx
import { useWalletConnectButton } from '@solana/wallet-adapter-base-ui'; import React from 'react'; import { BaseWalletConnectionButton } from './BaseWalletConnectionButton.js'; import type { ButtonProps } from './Button.js'; type Props = ButtonProps & { labels: { [TButtonState in ReturnType<typeof useWalletConnectButton>['buttonState']]: string }; }; export function BaseWalletConnectButton({ children, disabled, labels, onClick, ...props }: Props) { const { buttonDisabled, buttonState, onButtonClick, walletIcon, walletName } = useWalletConnectButton(); return ( <BaseWalletConnectionButton {...props} disabled={disabled || buttonDisabled} onClick={(e) => { if (onClick) { onClick(e); } if (e.defaultPrevented) { return; } if (onButtonClick) { onButtonClick(); } }} walletIcon={walletIcon} walletName={walletName} > {children ? children : labels[buttonState]} </BaseWalletConnectionButton> ); }
0
solana_public_repos/anza-xyz/wallet-adapter/packages/ui/react-ui
solana_public_repos/anza-xyz/wallet-adapter/packages/ui/react-ui/src/index.ts
export * from './useWalletModal.js'; export * from './BaseWalletConnectButton.js'; export * from './BaseWalletDisconnectButton.js'; export * from './BaseWalletMultiButton.js'; export * from './WalletConnectButton.js'; export * from './WalletModal.js'; export * from './WalletModalButton.js'; export * from './WalletModalProvider.js'; export * from './WalletDisconnectButton.js'; export * from './WalletIcon.js'; export * from './WalletMultiButton.js';
0
solana_public_repos/anza-xyz/wallet-adapter/packages/ui/react-ui
solana_public_repos/anza-xyz/wallet-adapter/packages/ui/react-ui/src/Button.tsx
import type { CSSProperties, FC, MouseEvent, PropsWithChildren, ReactElement } from 'react'; import React from 'react'; export type ButtonProps = PropsWithChildren<{ className?: string; disabled?: boolean; endIcon?: ReactElement; onClick?: (e: MouseEvent<HTMLButtonElement>) => void; startIcon?: ReactElement; style?: CSSProperties; tabIndex?: number; }>; export const Button: FC<ButtonProps> = (props) => { return ( <button className={`wallet-adapter-button ${props.className || ''}`} disabled={props.disabled} style={props.style} onClick={props.onClick} tabIndex={props.tabIndex || 0} type="button" > {props.startIcon && <i className="wallet-adapter-button-start-icon">{props.startIcon}</i>} {props.children} {props.endIcon && <i className="wallet-adapter-button-end-icon">{props.endIcon}</i>} </button> ); };
0
solana_public_repos/anza-xyz/wallet-adapter/packages/ui
solana_public_repos/anza-xyz/wallet-adapter/packages/ui/base-ui/LICENSE
Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 1. Definitions. "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and (b) You must cause any modified files to carry prominent notices stating that You changed the files; and (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. END OF TERMS AND CONDITIONS APPENDIX: How to apply the Apache License to your work. To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "[]" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives. Copyright [yyyy] [name of copyright owner] 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.
0
solana_public_repos/anza-xyz/wallet-adapter/packages/ui
solana_public_repos/anza-xyz/wallet-adapter/packages/ui/base-ui/tsconfig.esm.json
{ "extends": "../../../tsconfig.esm.json", "include": ["src"], "compilerOptions": { "outDir": "lib/esm", "declarationDir": "lib/types", "jsx": "react" } }
0
solana_public_repos/anza-xyz/wallet-adapter/packages/ui
solana_public_repos/anza-xyz/wallet-adapter/packages/ui/base-ui/package.json
{ "name": "@solana/wallet-adapter-base-ui", "version": "0.1.2", "author": "Solana Maintainers <maintainers@solana.foundation>", "repository": "https://github.com/anza-xyz/wallet-adapter", "license": "Apache-2.0", "publishConfig": { "access": "public" }, "files": [ "lib", "src", "LICENSE" ], "engines": { "node": ">=18" }, "type": "module", "sideEffects": false, "main": "./lib/cjs/index.js", "module": "./lib/esm/index.js", "types": "./lib/types/index.d.ts", "exports": { "require": "./lib/cjs/index.js", "import": "./lib/esm/index.js", "types": "./lib/types/index.d.ts" }, "scripts": { "build": "tsc --build --verbose && pnpm run package", "clean": "shx mkdir -p lib && shx rm -rf lib", "lint": "prettier --check 'src/{*,**/*}.{ts,tsx,js,jsx,json}' && eslint", "package": "shx mkdir -p lib/cjs && shx echo '{ \"type\": \"commonjs\" }' > lib/cjs/package.json" }, "peerDependencies": { "@solana/web3.js": "^1.77.3", "react": "*" }, "dependencies": { "@solana/wallet-adapter-react": "workspace:^" }, "devDependencies": { "@solana/web3.js": "^1.77.3", "@types/react": "^18.2.13", "react": "^18.2.0", "react-dom": "^18.2.0", "shx": "^0.3.4" } }
0
solana_public_repos/anza-xyz/wallet-adapter/packages/ui
solana_public_repos/anza-xyz/wallet-adapter/packages/ui/base-ui/tsconfig.cjs.json
{ "extends": "../../../tsconfig.cjs.json", "include": ["src"], "compilerOptions": { "outDir": "lib/cjs", "jsx": "react" } }
0
solana_public_repos/anza-xyz/wallet-adapter/packages/ui
solana_public_repos/anza-xyz/wallet-adapter/packages/ui/base-ui/tsconfig.json
{ "extends": "../../../tsconfig.root.json", "references": [ { "path": "./tsconfig.cjs.json" }, { "path": "./tsconfig.esm.json" } ] }
0
solana_public_repos/anza-xyz/wallet-adapter/packages/ui/base-ui
solana_public_repos/anza-xyz/wallet-adapter/packages/ui/base-ui/src/useWalletMultiButton.ts
import { useWallet, type Wallet } from '@solana/wallet-adapter-react'; import type { PublicKey } from '@solana/web3.js'; import { useCallback } from 'react'; type ButtonState = { buttonState: 'connecting' | 'connected' | 'disconnecting' | 'has-wallet' | 'no-wallet'; onConnect?: () => void; onDisconnect?: () => void; onSelectWallet?: () => void; publicKey?: PublicKey; walletIcon?: Wallet['adapter']['icon']; walletName?: Wallet['adapter']['name']; }; type Config = { onSelectWallet: (config: { onSelectWallet: (walletName: Wallet['adapter']['name']) => void; wallets: Wallet[]; }) => void; }; export function useWalletMultiButton({ onSelectWallet }: Config): ButtonState { const { connect, connected, connecting, disconnect, disconnecting, publicKey, select, wallet, wallets } = useWallet(); let buttonState: ButtonState['buttonState']; if (connecting) { buttonState = 'connecting'; } else if (connected) { buttonState = 'connected'; } else if (disconnecting) { buttonState = 'disconnecting'; } else if (wallet) { buttonState = 'has-wallet'; } else { buttonState = 'no-wallet'; } const handleConnect = useCallback(() => { connect().catch(() => { // Silently catch because any errors are caught by the context `onError` handler }); }, [connect]); const handleDisconnect = useCallback(() => { disconnect().catch(() => { // Silently catch because any errors are caught by the context `onError` handler }); }, [disconnect]); const handleSelectWallet = useCallback(() => { onSelectWallet({ onSelectWallet: select, wallets }); }, [onSelectWallet, select, wallets]); return { buttonState, onConnect: buttonState === 'has-wallet' ? handleConnect : undefined, onDisconnect: buttonState !== 'disconnecting' && buttonState !== 'no-wallet' ? handleDisconnect : undefined, onSelectWallet: handleSelectWallet, publicKey: publicKey ?? undefined, walletIcon: wallet?.adapter.icon, walletName: wallet?.adapter.name, }; }
0
solana_public_repos/anza-xyz/wallet-adapter/packages/ui/base-ui
solana_public_repos/anza-xyz/wallet-adapter/packages/ui/base-ui/src/useWalletDisconnectButton.ts
import { useWallet, type Wallet } from '@solana/wallet-adapter-react'; import { useCallback } from 'react'; type ButtonState = { buttonDisabled: boolean; buttonState: 'disconnecting' | 'has-wallet' | 'no-wallet'; onButtonClick?: () => void; walletIcon?: Wallet['adapter']['icon']; walletName?: Wallet['adapter']['name']; }; export function useWalletDisconnectButton(): ButtonState { const { disconnecting, disconnect, wallet } = useWallet(); let buttonState: ButtonState['buttonState']; if (disconnecting) { buttonState = 'disconnecting'; } else if (wallet) { buttonState = 'has-wallet'; } else { buttonState = 'no-wallet'; } const handleDisconnectButtonClick = useCallback(() => { disconnect().catch(() => { // Silently catch because any errors are caught by the context `onError` handler }); }, [disconnect]); return { buttonDisabled: buttonState !== 'has-wallet', buttonState, onButtonClick: buttonState === 'has-wallet' ? handleDisconnectButtonClick : undefined, walletIcon: wallet?.adapter.icon, walletName: wallet?.adapter.name, }; }
0
solana_public_repos/anza-xyz/wallet-adapter/packages/ui/base-ui
solana_public_repos/anza-xyz/wallet-adapter/packages/ui/base-ui/src/index.ts
export * from './useWalletConnectButton.js'; export * from './useWalletDisconnectButton.js'; export * from './useWalletMultiButton.js';
0
solana_public_repos/anza-xyz/wallet-adapter/packages/ui/base-ui
solana_public_repos/anza-xyz/wallet-adapter/packages/ui/base-ui/src/useWalletConnectButton.ts
import { useWallet, type Wallet } from '@solana/wallet-adapter-react'; import { useCallback } from 'react'; type ButtonState = { buttonDisabled: boolean; buttonState: 'connecting' | 'connected' | 'has-wallet' | 'no-wallet'; onButtonClick?: () => void; walletIcon?: Wallet['adapter']['icon']; walletName?: Wallet['adapter']['name']; }; export function useWalletConnectButton(): ButtonState { const { connect, connected, connecting, wallet } = useWallet(); let buttonState: ButtonState['buttonState']; if (connecting) { buttonState = 'connecting'; } else if (connected) { buttonState = 'connected'; } else if (wallet) { buttonState = 'has-wallet'; } else { buttonState = 'no-wallet'; } const handleConnectButtonClick = useCallback(() => { connect().catch(() => { // Silently catch because any errors are caught by the context `onError` handler }); }, [connect]); return { buttonDisabled: buttonState !== 'has-wallet', buttonState, onButtonClick: buttonState === 'has-wallet' ? handleConnectButtonClick : undefined, walletIcon: wallet?.adapter.icon, walletName: wallet?.adapter.name, }; }
0
solana_public_repos/anza-xyz/wallet-adapter/packages/ui
solana_public_repos/anza-xyz/wallet-adapter/packages/ui/ant-design/LICENSE
Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 1. Definitions. "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and (b) You must cause any modified files to carry prominent notices stating that You changed the files; and (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. END OF TERMS AND CONDITIONS APPENDIX: How to apply the Apache License to your work. To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "[]" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives. Copyright [yyyy] [name of copyright owner] 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.
0
solana_public_repos/anza-xyz/wallet-adapter/packages/ui
solana_public_repos/anza-xyz/wallet-adapter/packages/ui/ant-design/styles.css
.wallet-adapter-icon { width: 24px; height: 24px; margin-right: 8px; margin-left: -4px; } .wallet-adapter-modal-menu { border-right: 0px; } .wallet-adapter-modal-menu > .ant-menu-submenu { display: flex; flex-direction: column-reverse; } .wallet-adapter-modal-menu .ant-menu-submenu-arrow { right: 18px; } .wallet-adapter-modal-menu .ant-menu-submenu-title { margin: 0; } .wallet-adapter-modal-menu .ant-menu-submenu-title:hover, .wallet-adapter-modal-menu .ant-menu-submenu:hover > .ant-menu-submenu-title > .ant-menu-submenu-arrow { color: white; } .wallet-adapter-modal-menu .ant-menu-submenu-title > .ant-menu-title-content { padding-left: 25px; } .wallet-adapter-modal-menu .wallet-adapter-modal-menu-item { margin: 0px; padding: 0px; height: 44px; line-height: 44px; box-shadow: inset 0 -1px 0 0 rgba(255, 255, 255, 0.1); } .wallet-adapter-modal-menu .wallet-adapter-modal-menu-item:not(:last-child) { margin-bottom: 0px; } .wallet-adapter-modal-menu-button { height: 44px; padding-left: 24px; display: flex; flex-direction: row-reverse; justify-content: space-between; align-items: center; } .wallet-adapter-modal-menu-button-icon { width: 24px; height: 24px; margin-left: 8px; } .wallet-adapter-multi-button-menu { padding: 0px; margin-top: -44px; } .wallet-adapter-multi-button-menu-item { padding: 0px; } .wallet-adapter-multi-button-menu-button { text-align: left; } .wallet-adapter-multi-button-icon { font-size: 20px; margin-right: 12px; } .wallet-adapter-multi-button-item { padding: 0px; padding-left: 12px; padding-right: 16px; padding-top: 8px; padding-bottom: 8px; }
0
solana_public_repos/anza-xyz/wallet-adapter/packages/ui
solana_public_repos/anza-xyz/wallet-adapter/packages/ui/ant-design/tsconfig.esm.json
{ "extends": "../../../tsconfig.esm.json", "include": ["src"], "compilerOptions": { "outDir": "lib/esm", "declarationDir": "lib/types", "jsx": "react" } }
0
solana_public_repos/anza-xyz/wallet-adapter/packages/ui
solana_public_repos/anza-xyz/wallet-adapter/packages/ui/ant-design/package.json
{ "name": "@solana/wallet-adapter-ant-design", "version": "0.11.32", "author": "Solana Maintainers <maintainers@solana.foundation>", "repository": "https://github.com/anza-xyz/wallet-adapter", "license": "Apache-2.0", "publishConfig": { "access": "public" }, "files": [ "lib", "src", "LICENSE", "styles.css" ], "engines": { "node": ">=18" }, "type": "module", "sideEffects": false, "main": "./lib/cjs/index.js", "module": "./lib/esm/index.js", "types": "./lib/types/index.d.ts", "exports": { ".": { "import": "./lib/esm/index.js", "require": "./lib/cjs/index.js", "types": "./lib/types/index.d.ts" }, "./styles.css": "./styles.css" }, "scripts": { "build": "tsc --build --verbose && pnpm run package", "clean": "shx mkdir -p lib && shx rm -rf lib", "lint": "prettier --check 'src/{*,**/*}.{ts,tsx,js,jsx,json}' && eslint", "package": "shx mkdir -p lib/cjs && shx echo '{ \"type\": \"commonjs\" }' > lib/cjs/package.json" }, "peerDependencies": { "@ant-design/icons": "*", "@solana/web3.js": "^1.77.3", "antd": "*", "react": "*", "react-dom": "*" }, "dependencies": { "@solana/wallet-adapter-base": "workspace:^", "@solana/wallet-adapter-base-ui": "workspace:^", "@solana/wallet-adapter-react": "workspace:^" }, "devDependencies": { "@ant-design/icons": "^4.8.0", "@solana/web3.js": "^1.77.3", "@types/react": "^18.2.13", "@types/react-dom": "^18.2.6", "antd": "^4.24.10", "react": "^18.2.0", "react-dom": "^18.2.0", "shx": "^0.3.4" } }
0
solana_public_repos/anza-xyz/wallet-adapter/packages/ui
solana_public_repos/anza-xyz/wallet-adapter/packages/ui/ant-design/tsconfig.cjs.json
{ "extends": "../../../tsconfig.cjs.json", "include": ["src"], "compilerOptions": { "outDir": "lib/cjs", "jsx": "react" } }
0
solana_public_repos/anza-xyz/wallet-adapter/packages/ui
solana_public_repos/anza-xyz/wallet-adapter/packages/ui/ant-design/tsconfig.json
{ "extends": "../../../tsconfig.root.json", "references": [ { "path": "./tsconfig.cjs.json" }, { "path": "./tsconfig.esm.json" } ] }
0
solana_public_repos/anza-xyz/wallet-adapter/packages/ui/ant-design
solana_public_repos/anza-xyz/wallet-adapter/packages/ui/ant-design/src/WalletModalButton.tsx
import type { ButtonProps } from 'antd'; import type { FC, MouseEventHandler } from 'react'; import React, { useCallback } from 'react'; import { BaseWalletConnectionButton } from './BaseWalletConnectionButton.js'; import { useWalletModal } from './useWalletModal.js'; export const WalletModalButton: FC<ButtonProps> = ({ children = 'Select Wallet', onClick, ...props }) => { const { setVisible } = useWalletModal(); const handleClick: MouseEventHandler<HTMLButtonElement> = useCallback( (event) => { if (onClick) onClick(event); if (!event.defaultPrevented) setVisible(true); }, [onClick, setVisible] ); return ( <BaseWalletConnectionButton {...props} onClick={handleClick}> {children} </BaseWalletConnectionButton> ); };
0
solana_public_repos/anza-xyz/wallet-adapter/packages/ui/ant-design
solana_public_repos/anza-xyz/wallet-adapter/packages/ui/ant-design/src/WalletIcon.tsx
import type { Wallet } from '@solana/wallet-adapter-react'; import type { DetailedHTMLProps, FC, ImgHTMLAttributes } from 'react'; import React from 'react'; export interface WalletIconProps extends DetailedHTMLProps<ImgHTMLAttributes<HTMLImageElement>, HTMLImageElement> { wallet: { adapter: Pick<Wallet['adapter'], 'icon' | 'name'> } | null; } export const WalletIcon: FC<WalletIconProps> = ({ wallet, ...props }) => { return ( wallet && ( <img src={wallet.adapter.icon} alt={`${wallet.adapter.name} icon`} className="wallet-adapter-icon" {...props} /> ) ); };
0
solana_public_repos/anza-xyz/wallet-adapter/packages/ui/ant-design
solana_public_repos/anza-xyz/wallet-adapter/packages/ui/ant-design/src/WalletConnectButton.tsx
import type { ButtonProps } from 'antd'; import React from 'react'; import { BaseWalletConnectButton } from './BaseWalletConnectButton.js'; const LABELS = { connecting: 'Connecting ...', connected: 'Connected', 'has-wallet': 'Connect', 'no-wallet': 'Connect Wallet', } as const; export function WalletConnectButton(props: ButtonProps) { return <BaseWalletConnectButton {...props} labels={LABELS} />; }
0
solana_public_repos/anza-xyz/wallet-adapter/packages/ui/ant-design
solana_public_repos/anza-xyz/wallet-adapter/packages/ui/ant-design/src/WalletModal.tsx
import type { WalletName } from '@solana/wallet-adapter-base'; import { WalletReadyState } from '@solana/wallet-adapter-base'; import { useWallet, type Wallet } from '@solana/wallet-adapter-react'; import type { ModalProps } from 'antd'; import { Menu, Modal } from 'antd'; import type { FC, MouseEvent } from 'react'; import React, { useCallback, useMemo, useState } from 'react'; import { useWalletModal } from './useWalletModal.js'; import { WalletMenuItem } from './WalletMenuItem.js'; export interface WalletModalProps extends Omit<ModalProps, 'visible'> { featuredWallets?: number; } export const WalletModal: FC<WalletModalProps> = ({ title = 'Select your wallet', featuredWallets = 3, onCancel, ...props }) => { const { wallets, select } = useWallet(); const { visible, setVisible } = useWalletModal(); const [expanded, setExpanded] = useState(false); const [featured, more] = useMemo(() => { const installed: Wallet[] = []; const notInstalled: Wallet[] = []; for (const wallet of wallets) { if (wallet.readyState === WalletReadyState.Installed) { installed.push(wallet); } else { notInstalled.push(wallet); } } const orderedWallets = [...installed, ...notInstalled]; return [orderedWallets.slice(0, featuredWallets), orderedWallets.slice(featuredWallets)]; }, [wallets, featuredWallets]); const handleCancel = useCallback( (event: MouseEvent<HTMLElement>) => { if (onCancel) onCancel(event); if (!event.defaultPrevented) setVisible(false); }, [onCancel, setVisible] ); const handleWalletClick = useCallback( (event: MouseEvent<HTMLElement>, walletName: WalletName) => { select(walletName); handleCancel(event); }, [select, handleCancel] ); const onOpenChange = useCallback(() => setExpanded(!expanded), [setExpanded, expanded]); return ( <Modal title={title} visible={visible} centered={true} onCancel={handleCancel} footer={null} width={320} bodyStyle={{ padding: 0 }} {...props} > <Menu className="wallet-adapter-modal-menu" inlineIndent={0} mode="inline" onOpenChange={onOpenChange}> {featured.map((wallet) => ( <WalletMenuItem key={wallet.adapter.name} onClick={(event) => handleWalletClick(event, wallet.adapter.name)} wallet={wallet} /> ))} {more.length ? ( <Menu.SubMenu key="wallet-adapter-modal-submenu" title={`${expanded ? 'Less' : 'More'} options`}> {more.map((wallet) => ( <WalletMenuItem key={wallet.adapter.name} onClick={(event) => handleWalletClick(event, wallet.adapter.name)} wallet={wallet} /> ))} </Menu.SubMenu> ) : null} </Menu> </Modal> ); };
0
solana_public_repos/anza-xyz/wallet-adapter/packages/ui/ant-design
solana_public_repos/anza-xyz/wallet-adapter/packages/ui/ant-design/src/WalletModalProvider.tsx
import type { FC, ReactNode } from 'react'; import React, { useState } from 'react'; import { WalletModalContext } from './useWalletModal.js'; import type { WalletModalProps } from './WalletModal.js'; import { WalletModal } from './WalletModal.js'; export interface WalletModalProviderProps extends WalletModalProps { children: ReactNode; } export const WalletModalProvider: FC<WalletModalProviderProps> = ({ children, ...props }) => { const [visible, setVisible] = useState(false); return ( <WalletModalContext.Provider value={{ visible, setVisible, }} > {children} <WalletModal {...props} /> </WalletModalContext.Provider> ); };
0
solana_public_repos/anza-xyz/wallet-adapter/packages/ui/ant-design
solana_public_repos/anza-xyz/wallet-adapter/packages/ui/ant-design/src/WalletMultiButton.tsx
import type { ButtonProps } from 'antd'; import React from 'react'; import { BaseWalletMultiButton } from './BaseWalletMultiButton.js'; const LABELS = { 'change-wallet': 'Change wallet', connecting: 'Connecting ...', 'copy-address': 'Copy address', disconnect: 'Disconnect', 'has-wallet': 'Connect', 'no-wallet': 'Select Wallet', } as const; export function WalletMultiButton(props: ButtonProps) { return <BaseWalletMultiButton {...props} labels={LABELS} />; }
0
solana_public_repos/anza-xyz/wallet-adapter/packages/ui/ant-design
solana_public_repos/anza-xyz/wallet-adapter/packages/ui/ant-design/src/WalletMenuItem.tsx
import type { Wallet } from '@solana/wallet-adapter-react'; import type { MenuItemProps } from 'antd'; import { Button, Menu } from 'antd'; import type { FC, MouseEventHandler } from 'react'; import React from 'react'; import { WalletIcon } from './WalletIcon.js'; interface WalletMenuItemProps extends Omit<MenuItemProps, 'onClick'> { onClick: MouseEventHandler<HTMLButtonElement>; wallet: Wallet; } export const WalletMenuItem: FC<WalletMenuItemProps> = ({ onClick, wallet, ...props }) => { return ( <Menu.Item className="wallet-adapter-modal-menu-item" {...props}> <Button onClick={onClick} icon={<WalletIcon wallet={wallet} className="wallet-adapter-modal-menu-button-icon" />} type="text" className="wallet-adapter-modal-menu-button" htmlType="button" block > {wallet.adapter.name} </Button> </Menu.Item> ); };
0
solana_public_repos/anza-xyz/wallet-adapter/packages/ui/ant-design
solana_public_repos/anza-xyz/wallet-adapter/packages/ui/ant-design/src/BaseWalletMultiButton.tsx
import { CopyOutlined as CopyIcon, DisconnectOutlined as DisconnectIcon, SwapOutlined as SwitchIcon, } from '@ant-design/icons'; import { useWalletMultiButton } from '@solana/wallet-adapter-base-ui'; import type { ButtonProps } from 'antd'; import { Dropdown, Menu } from 'antd'; import React, { useMemo } from 'react'; import { BaseWalletConnectionButton } from './BaseWalletConnectionButton.js'; import { useWalletModal } from './useWalletModal.js'; type Props = ButtonProps & { labels: Omit< { [TButtonState in ReturnType<typeof useWalletMultiButton>['buttonState']]: string }, 'connected' | 'disconnecting' > & { 'copy-address': string; 'change-wallet': string; disconnect: string; }; }; export function BaseWalletMultiButton({ children, labels, ...props }: Props) { const { setVisible: setModalVisible } = useWalletModal(); const { buttonState, onConnect, onDisconnect, publicKey, walletIcon, walletName } = useWalletMultiButton({ onSelectWallet() { setModalVisible(true); }, }); const content = useMemo(() => { if (children) { return children; } else if (publicKey) { const base58 = publicKey.toBase58(); return base58.slice(0, 4) + '..' + base58.slice(-4); } else if (buttonState === 'connecting' || buttonState === 'has-wallet') { return labels[buttonState]; } else { return labels['no-wallet']; } }, [buttonState, children, labels, publicKey]); return ( <Dropdown overlay={ <Menu className="wallet-adapter-multi-button-menu"> <Menu.Item className="wallet-adapter-multi-button-menu-item"> <BaseWalletConnectionButton {...props} block className="wallet-adapter-multi-button-menu-button" walletIcon={walletIcon} walletName={walletName} > {walletName} </BaseWalletConnectionButton> </Menu.Item> {publicKey ? ( <Menu.Item className="wallet-adapter-multi-button-item" icon={<CopyIcon className=".wallet-adapter-multi-button-icon" />} onClick={async () => { await navigator.clipboard.writeText(publicKey?.toBase58()); }} > {labels['copy-address']} </Menu.Item> ) : null} <Menu.Item onClick={() => setTimeout(() => setModalVisible(true), 100)} icon={<SwitchIcon className=".wallet-adapter-multi-button-icon" />} className="wallet-adapter-multi-button-item" > {labels['change-wallet']} </Menu.Item> {onDisconnect ? ( <Menu.Item onClick={onDisconnect} icon={<DisconnectIcon className=".wallet-adapter-multi-button-icon" />} className="wallet-adapter-multi-button-item" > {labels['disconnect']} </Menu.Item> ) : null} </Menu> } trigger={buttonState === 'connected' ? ['click'] : []} > <BaseWalletConnectionButton {...props} onClick={() => { switch (buttonState) { case 'no-wallet': setModalVisible(true); break; case 'has-wallet': if (onConnect) { onConnect(); } break; } }} walletIcon={walletIcon} walletName={walletName} > {content} </BaseWalletConnectionButton> </Dropdown> ); }
0
solana_public_repos/anza-xyz/wallet-adapter/packages/ui/ant-design
solana_public_repos/anza-xyz/wallet-adapter/packages/ui/ant-design/src/WalletDisconnectButton.tsx
import type { ButtonProps } from 'antd'; import React from 'react'; import { BaseWalletDisconnectButton } from './BaseWalletDisconnectButton.js'; const LABELS = { disconnecting: 'Disconnecting ...', 'has-wallet': 'Disconnect', 'no-wallet': 'Disconnect Wallet', } as const; export function WalletDisconnectButton(props: ButtonProps) { return <BaseWalletDisconnectButton {...props} labels={LABELS} />; }
0
solana_public_repos/anza-xyz/wallet-adapter/packages/ui/ant-design
solana_public_repos/anza-xyz/wallet-adapter/packages/ui/ant-design/src/BaseWalletDisconnectButton.tsx
import { useWalletDisconnectButton } from '@solana/wallet-adapter-base-ui'; import type { ButtonProps } from 'antd'; import React from 'react'; import { BaseWalletConnectionButton } from './BaseWalletConnectionButton.js'; type Props = ButtonProps & { labels: { [TButtonState in ReturnType<typeof useWalletDisconnectButton>['buttonState']]: string }; }; export function BaseWalletDisconnectButton({ children, disabled, labels, onClick, ...props }: Props) { const { buttonDisabled, buttonState, onButtonClick, walletIcon, walletName } = useWalletDisconnectButton(); return ( <BaseWalletConnectionButton {...props} disabled={disabled || buttonDisabled} onClick={(e) => { if (onClick) { onClick(e); } if (e.defaultPrevented) { return; } if (onButtonClick) { onButtonClick(); } }} walletIcon={walletIcon} walletName={walletName} > {children ? children : labels[buttonState]} </BaseWalletConnectionButton> ); }
0
solana_public_repos/anza-xyz/wallet-adapter/packages/ui/ant-design
solana_public_repos/anza-xyz/wallet-adapter/packages/ui/ant-design/src/BaseWalletConnectionButton.tsx
import type { WalletName } from '@solana/wallet-adapter-base'; import type { ButtonProps } from 'antd'; import { Button } from 'antd'; import React from 'react'; import { WalletIcon } from './WalletIcon.js'; type Props = ButtonProps & { walletIcon?: string; walletName?: WalletName; }; export function BaseWalletConnectionButton({ htmlType = 'button', size = 'large', type = 'primary', walletIcon, walletName, ...props }: Props) { return ( <Button {...props} htmlType={htmlType} icon={ walletIcon && walletName ? ( <WalletIcon wallet={{ adapter: { icon: walletIcon, name: walletName } }} /> ) : undefined } type={type} size={size} /> ); }
0
solana_public_repos/anza-xyz/wallet-adapter/packages/ui/ant-design
solana_public_repos/anza-xyz/wallet-adapter/packages/ui/ant-design/src/BaseWalletConnectButton.tsx
import { useWalletConnectButton } from '@solana/wallet-adapter-base-ui'; import type { ButtonProps } from 'antd'; import React from 'react'; import { BaseWalletConnectionButton } from './BaseWalletConnectionButton.js'; type Props = ButtonProps & { labels: { [TButtonState in ReturnType<typeof useWalletConnectButton>['buttonState']]: string }; }; export function BaseWalletConnectButton({ children, disabled, labels, onClick, ...props }: Props) { const { buttonDisabled, buttonState, onButtonClick, walletIcon, walletName } = useWalletConnectButton(); return ( <BaseWalletConnectionButton {...props} disabled={disabled || buttonDisabled} onClick={(e) => { if (onClick) { onClick(e); } if (e.defaultPrevented) { return; } if (onButtonClick) { onButtonClick(); } }} walletIcon={walletIcon} walletName={walletName} > {children ? children : labels[buttonState]} </BaseWalletConnectionButton> ); }
0
solana_public_repos/anza-xyz/wallet-adapter/packages/ui/ant-design
solana_public_repos/anza-xyz/wallet-adapter/packages/ui/ant-design/src/index.ts
export * from './useWalletModal.js'; export * from './BaseWalletConnectButton.js'; export * from './BaseWalletDisconnectButton.js'; export * from './BaseWalletMultiButton.js'; export * from './WalletConnectButton.js'; export * from './WalletModal.js'; export * from './WalletModalButton.js'; export * from './WalletModalProvider.js'; export * from './WalletDisconnectButton.js'; export * from './WalletIcon.js'; export * from './WalletMultiButton.js';
0
solana_public_repos/anza-xyz/wallet-adapter/packages/ui/ant-design
solana_public_repos/anza-xyz/wallet-adapter/packages/ui/ant-design/src/useWalletModal.ts
import { createContext, useContext } from 'react'; export interface WalletModalContextState { visible: boolean; setVisible: (open: boolean) => void; } const DEFAULT_CONTEXT = { setVisible(_open: boolean) { console.error(constructMissingProviderErrorMessage('call', 'setVisible')); }, visible: false, }; Object.defineProperty(DEFAULT_CONTEXT, 'visible', { get() { console.error(constructMissingProviderErrorMessage('read', 'visible')); return false; }, }); function constructMissingProviderErrorMessage(action: string, valueName: string) { return ( 'You have tried to ' + ` ${action} "${valueName}"` + ' on a WalletModalContext without providing one.' + ' Make sure to render a WalletModalProvider' + ' as an ancestor of the component that uses ' + 'WalletModalContext' ); } export const WalletModalContext = createContext<WalletModalContextState>(DEFAULT_CONTEXT as WalletModalContextState); export function useWalletModal(): WalletModalContextState { return useContext(WalletModalContext); }
0
solana_public_repos/anza-xyz/wallet-adapter/packages/core
solana_public_repos/anza-xyz/wallet-adapter/packages/core/react/jest.resolver.cjs
module.exports = (path, options) => { // Call the defaultResolver, so we leverage its cache, error handling, etc. return options.defaultResolver(path, { ...options, // Use packageFilter to process parsed `package.json` before the resolution (see https://www.npmjs.com/package/resolve#resolveid-opts-cb) packageFilter: (pkg) => { // This is a workaround for https://github.com/uuidjs/uuid/pull/616 // // jest-environment-jsdom 28+ tries to use browser exports instead of default exports, // but uuid only offers an ESM browser export and not a CommonJS one. Jest does not yet // support ESM modules natively, so this causes a Jest error related to trying to parse // "export" syntax. // // This workaround prevents Jest from considering uuid's module-based exports at all; // it falls back to uuid's CommonJS+node "main" property. // // Once we're able to migrate our Jest config to ESM and a browser crypto // implementation is available for the browser+ESM version of uuid to use (eg, via // https://github.com/jsdom/jsdom/pull/3352 or a similar polyfill), this can go away. if (pkg.name === 'uuid') { delete pkg['exports']; delete pkg['module']; } return pkg; }, }); };
0
solana_public_repos/anza-xyz/wallet-adapter/packages/core
solana_public_repos/anza-xyz/wallet-adapter/packages/core/react/LICENSE
Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 1. Definitions. "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and (b) You must cause any modified files to carry prominent notices stating that You changed the files; and (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. END OF TERMS AND CONDITIONS APPENDIX: How to apply the Apache License to your work. To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "[]" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives. Copyright [yyyy] [name of copyright owner] 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.
0
solana_public_repos/anza-xyz/wallet-adapter/packages/core
solana_public_repos/anza-xyz/wallet-adapter/packages/core/react/jest.config.js
import { dirname } from 'path'; import { fileURLToPath } from 'url'; const __dirname = dirname(fileURLToPath(import.meta.url)); /** @type {import('ts-jest/dist/types').InitialOptionsTsJest} */ export default { preset: 'ts-jest/presets/default-esm', moduleNameMapper: { '^(\\.{1,2}/.*)\\.js$': '$1', }, resolver: `${__dirname}/jest.resolver.cjs`, globals: { IS_REACT_ACT_ENVIRONMENT: true, 'ts-jest': { tsconfig: './tsconfig.tests.json', }, }, testEnvironment: 'node', transformIgnorePatterns: ['/node_modules/(?!(uuid))'], };
0
solana_public_repos/anza-xyz/wallet-adapter/packages/core
solana_public_repos/anza-xyz/wallet-adapter/packages/core/react/tsconfig.tests.json
{ "extends": "../../../tsconfig.tests.json", "include": ["src"], "compilerOptions": { "jsx": "react" } }
0
solana_public_repos/anza-xyz/wallet-adapter/packages/core
solana_public_repos/anza-xyz/wallet-adapter/packages/core/react/tsconfig.esm.json
{ "extends": "../../../tsconfig.esm.json", "include": ["src"], "exclude": ["src/**/__mocks__", "src/**/__tests__"], "compilerOptions": { "outDir": "lib/esm", "declarationDir": "lib/types", "jsx": "react" } }
0
solana_public_repos/anza-xyz/wallet-adapter/packages/core
solana_public_repos/anza-xyz/wallet-adapter/packages/core/react/package.json
{ "name": "@solana/wallet-adapter-react", "version": "0.15.35", "author": "Solana Maintainers <maintainers@solana.foundation>", "repository": "https://github.com/anza-xyz/wallet-adapter", "license": "Apache-2.0", "publishConfig": { "access": "public" }, "files": [ "lib", "src", "LICENSE" ], "engines": { "node": ">=18" }, "type": "module", "sideEffects": false, "main": "./lib/cjs/index.js", "module": "./lib/esm/index.js", "types": "./lib/types/index.d.ts", "exports": { "require": "./lib/cjs/index.js", "import": "./lib/esm/index.js", "types": "./lib/types/index.d.ts" }, "scripts": { "build": "tsc --build --verbose && pnpm run package", "clean": "shx mkdir -p lib && shx rm -rf lib", "lint": "prettier --check 'src/{*,**/*}.{ts,tsx,js,jsx,json}' && eslint", "package": "shx mkdir -p lib/cjs && shx echo '{ \"type\": \"commonjs\" }' > lib/cjs/package.json", "test": "jest" }, "peerDependencies": { "@solana/web3.js": "^1.77.3", "react": "*" }, "dependencies": { "@solana-mobile/wallet-adapter-mobile": "^2.0.0", "@solana/wallet-adapter-base": "workspace:^", "@solana/wallet-standard-wallet-adapter-react": "^1.1.0" }, "devDependencies": { "@solana/web3.js": "^1.77.3", "@types/jest": "^28.1.8", "@types/react": "^18.2.13", "@types/react-dom": "^18.2.6", "jest": "^28.1.3", "jest-environment-jsdom": "^28.1.3", "jest-localstorage-mock": "^2.4.26", "react": "^18.2.0", "react-dom": "^18.2.0", "shx": "^0.3.4", "ts-jest": "^28.0.8" } }
0
solana_public_repos/anza-xyz/wallet-adapter/packages/core
solana_public_repos/anza-xyz/wallet-adapter/packages/core/react/tsconfig.cjs.json
{ "extends": "../../../tsconfig.cjs.json", "include": ["src"], "exclude": ["src/**/__mocks__", "src/**/__tests__"], "compilerOptions": { "outDir": "lib/cjs", "jsx": "react" } }
0
solana_public_repos/anza-xyz/wallet-adapter/packages/core
solana_public_repos/anza-xyz/wallet-adapter/packages/core/react/tsconfig.json
{ "extends": "../../../tsconfig.root.json", "references": [ { "path": "./tsconfig.cjs.json" }, { "path": "./tsconfig.esm.json" }, { "path": "./tsconfig.tests.json" } ] }
0
solana_public_repos/anza-xyz/wallet-adapter/packages/core/react/__mocks__
solana_public_repos/anza-xyz/wallet-adapter/packages/core/react/__mocks__/@solana-mobile/wallet-adapter-mobile.ts
import { type WalletName } from '@solana/wallet-adapter-base'; import { MockWalletAdapter } from '../../src/__mocks__/MockWalletAdapter.js'; export const SolanaMobileWalletAdapterWalletName = 'Solana Mobile Wallet Adapter Name For Tests'; export const createDefaultAddressSelector = jest.fn(); export const createDefaultAuthorizationResultCache = jest.fn(); export const createDefaultWalletNotFoundHandler = jest.fn(); class MockSolanaMobileWalletAdapter extends MockWalletAdapter { name = SolanaMobileWalletAdapterWalletName as WalletName<string>; icon = 'sms.png'; url = 'https://solanamobile.com'; publicKey = null; } export const SolanaMobileWalletAdapter = jest.fn().mockImplementation( (...args) => new MockSolanaMobileWalletAdapter( // @ts-ignore ...args ) );
0
solana_public_repos/anza-xyz/wallet-adapter/packages/core/react
solana_public_repos/anza-xyz/wallet-adapter/packages/core/react/src/useAnchorWallet.ts
import { type PublicKey, type Transaction, type VersionedTransaction } from '@solana/web3.js'; import { useMemo } from 'react'; import { useWallet } from './useWallet.js'; export interface AnchorWallet { publicKey: PublicKey; signTransaction<T extends Transaction | VersionedTransaction>(transaction: T): Promise<T>; signAllTransactions<T extends Transaction | VersionedTransaction>(transactions: T[]): Promise<T[]>; } export function useAnchorWallet(): AnchorWallet | undefined { const { publicKey, signTransaction, signAllTransactions } = useWallet(); return useMemo( () => publicKey && signTransaction && signAllTransactions ? { publicKey, signTransaction, signAllTransactions } : undefined, [publicKey, signTransaction, signAllTransactions] ); }
0
solana_public_repos/anza-xyz/wallet-adapter/packages/core/react
solana_public_repos/anza-xyz/wallet-adapter/packages/core/react/src/errors.ts
import { WalletError } from '@solana/wallet-adapter-base'; export class WalletNotSelectedError extends WalletError { name = 'WalletNotSelectedError'; }
0
solana_public_repos/anza-xyz/wallet-adapter/packages/core/react
solana_public_repos/anza-xyz/wallet-adapter/packages/core/react/src/ConnectionProvider.tsx
import { Connection, type ConnectionConfig } from '@solana/web3.js'; import React, { type FC, type ReactNode, useMemo } from 'react'; import { ConnectionContext } from './useConnection.js'; export interface ConnectionProviderProps { children: ReactNode; endpoint: string; config?: ConnectionConfig; } export const ConnectionProvider: FC<ConnectionProviderProps> = ({ children, endpoint, config = { commitment: 'confirmed' }, }) => { const connection = useMemo(() => new Connection(endpoint, config), [endpoint, config]); return <ConnectionContext.Provider value={{ connection }}>{children}</ConnectionContext.Provider>; };
0
solana_public_repos/anza-xyz/wallet-adapter/packages/core/react
solana_public_repos/anza-xyz/wallet-adapter/packages/core/react/src/getEnvironment.ts
import { SolanaMobileWalletAdapterWalletName } from '@solana-mobile/wallet-adapter-mobile'; import { type Adapter, WalletReadyState } from '@solana/wallet-adapter-base'; export enum Environment { DESKTOP_WEB, MOBILE_WEB, } type Config = Readonly<{ adapters: Adapter[]; userAgentString: string | null; }>; function isWebView(userAgentString: string) { return /(WebView|Version\/.+(Chrome)\/(\d+)\.(\d+)\.(\d+)\.(\d+)|; wv\).+(Chrome)\/(\d+)\.(\d+)\.(\d+)\.(\d+))/i.test( userAgentString ); } export default function getEnvironment({ adapters, userAgentString }: Config): Environment { if ( adapters.some( (adapter) => adapter.name !== SolanaMobileWalletAdapterWalletName && adapter.readyState === WalletReadyState.Installed ) ) { /** * There are only two ways a browser extension adapter should be able to reach `Installed` status: * * 1. Its browser extension is installed. * 2. The app is running on a mobile wallet's in-app browser. * * In either case, we consider the environment to be desktop-like. */ return Environment.DESKTOP_WEB; } if ( userAgentString && // Step 1: Check whether we're on a platform that supports MWA at all. /android/i.test(userAgentString) && // Step 2: Determine that we are *not* running in a WebView. !isWebView(userAgentString) ) { return Environment.MOBILE_WEB; } else { return Environment.DESKTOP_WEB; } }
0
solana_public_repos/anza-xyz/wallet-adapter/packages/core/react
solana_public_repos/anza-xyz/wallet-adapter/packages/core/react/src/useLocalStorage.native.ts
import { useState } from 'react'; import { type useLocalStorage as baseUseLocalStorage } from './useLocalStorage.js'; export const useLocalStorage: typeof baseUseLocalStorage = function useLocalStorage<T>( _key: string, defaultState: T ): [T, React.Dispatch<React.SetStateAction<T>>] { /** * Until such time as we have a strategy for implementing wallet * memorization on React Native, simply punt and return a no-op. */ return useState(defaultState); };
0
solana_public_repos/anza-xyz/wallet-adapter/packages/core/react
solana_public_repos/anza-xyz/wallet-adapter/packages/core/react/src/useConnection.ts
import { type Connection } from '@solana/web3.js'; import { createContext, useContext } from 'react'; export interface ConnectionContextState { connection: Connection; } export const ConnectionContext = createContext<ConnectionContextState>({} as ConnectionContextState); export function useConnection(): ConnectionContextState { return useContext(ConnectionContext); }
0
solana_public_repos/anza-xyz/wallet-adapter/packages/core/react
solana_public_repos/anza-xyz/wallet-adapter/packages/core/react/src/useLocalStorage.ts
import { type Dispatch, type SetStateAction, useEffect, useRef, useState } from 'react'; export function useLocalStorage<T>(key: string, defaultState: T): [T, Dispatch<SetStateAction<T>>] { const state = useState<T>(() => { try { const value = localStorage.getItem(key); if (value) return JSON.parse(value) as T; } catch (error: any) { if (typeof window !== 'undefined') { console.error(error); } } return defaultState; }); const value = state[0]; const isFirstRenderRef = useRef(true); useEffect(() => { if (isFirstRenderRef.current) { isFirstRenderRef.current = false; return; } try { if (value === null) { localStorage.removeItem(key); } else { localStorage.setItem(key, JSON.stringify(value)); } } catch (error: any) { if (typeof window !== 'undefined') { console.error(error); } } }, [value, key]); return state; }
0
solana_public_repos/anza-xyz/wallet-adapter/packages/core/react
solana_public_repos/anza-xyz/wallet-adapter/packages/core/react/src/WalletProviderBase.tsx
import { type Adapter, type MessageSignerWalletAdapterProps, type SignerWalletAdapterProps, type SignInMessageSignerWalletAdapterProps, type WalletAdapterProps, type WalletError, type WalletName, WalletNotConnectedError, WalletNotReadyError, WalletReadyState, } from '@solana/wallet-adapter-base'; import { type PublicKey } from '@solana/web3.js'; import React, { type ReactNode, useCallback, useEffect, useMemo, useRef, useState } from 'react'; import { WalletNotSelectedError } from './errors.js'; import { WalletContext } from './useWallet.js'; export interface WalletProviderBaseProps { children: ReactNode; wallets: Adapter[]; adapter: Adapter | null; isUnloadingRef: React.RefObject<boolean>; // NOTE: The presence/absence of this handler implies that auto-connect is enabled/disabled. onAutoConnectRequest?: () => Promise<void>; onConnectError: () => void; onError?: (error: WalletError, adapter?: Adapter) => void; onSelectWallet: (walletName: WalletName | null) => void; } export function WalletProviderBase({ children, wallets: adapters, adapter, isUnloadingRef, onAutoConnectRequest, onConnectError, onError, onSelectWallet, }: WalletProviderBaseProps) { const isConnectingRef = useRef(false); const [connecting, setConnecting] = useState(false); const isDisconnectingRef = useRef(false); const [disconnecting, setDisconnecting] = useState(false); const [publicKey, setPublicKey] = useState(() => adapter?.publicKey ?? null); const [connected, setConnected] = useState(() => adapter?.connected ?? false); /** * Store the error handlers as refs so that a change in the * custom error handler does not recompute other dependencies. */ const onErrorRef = useRef(onError); useEffect(() => { onErrorRef.current = onError; return () => { onErrorRef.current = undefined; }; }, [onError]); const handleErrorRef = useRef((error: WalletError, adapter?: Adapter) => { if (!isUnloadingRef.current) { if (onErrorRef.current) { onErrorRef.current(error, adapter); } else { console.error(error, adapter); if (error instanceof WalletNotReadyError && typeof window !== 'undefined' && adapter) { window.open(adapter.url, '_blank'); } } } return error; }); // Wrap adapters to conform to the `Wallet` interface const [wallets, setWallets] = useState(() => adapters .map((adapter) => ({ adapter, readyState: adapter.readyState, })) .filter(({ readyState }) => readyState !== WalletReadyState.Unsupported) ); // When the adapters change, start to listen for changes to their `readyState` useEffect(() => { // When the adapters change, wrap them to conform to the `Wallet` interface setWallets((wallets) => adapters .map((adapter, index) => { const wallet = wallets[index]; // If the wallet hasn't changed, return the same instance return wallet && wallet.adapter === adapter && wallet.readyState === adapter.readyState ? wallet : { adapter: adapter, readyState: adapter.readyState, }; }) .filter(({ readyState }) => readyState !== WalletReadyState.Unsupported) ); function handleReadyStateChange(this: Adapter, readyState: WalletReadyState) { setWallets((prevWallets) => { const index = prevWallets.findIndex(({ adapter }) => adapter === this); if (index === -1) return prevWallets; // eslint-disable-next-line @typescript-eslint/no-non-null-assertion const { adapter } = prevWallets[index]!; return [ ...prevWallets.slice(0, index), { adapter, readyState }, ...prevWallets.slice(index + 1), ].filter(({ readyState }) => readyState !== WalletReadyState.Unsupported); }); } adapters.forEach((adapter) => adapter.on('readyStateChange', handleReadyStateChange, adapter)); return () => { adapters.forEach((adapter) => adapter.off('readyStateChange', handleReadyStateChange, adapter)); }; }, [adapter, adapters]); const wallet = useMemo(() => wallets.find((wallet) => wallet.adapter === adapter) ?? null, [adapter, wallets]); // Setup and teardown event listeners when the adapter changes useEffect(() => { if (!adapter) return; const handleConnect = (publicKey: PublicKey) => { setPublicKey(publicKey); isConnectingRef.current = false; setConnecting(false); setConnected(true); isDisconnectingRef.current = false; setDisconnecting(false); }; const handleDisconnect = () => { if (isUnloadingRef.current) return; setPublicKey(null); isConnectingRef.current = false; setConnecting(false); setConnected(false); isDisconnectingRef.current = false; setDisconnecting(false); }; const handleError = (error: WalletError) => { handleErrorRef.current(error, adapter); }; adapter.on('connect', handleConnect); adapter.on('disconnect', handleDisconnect); adapter.on('error', handleError); return () => { adapter.off('connect', handleConnect); adapter.off('disconnect', handleDisconnect); adapter.off('error', handleError); handleDisconnect(); }; }, [adapter, isUnloadingRef]); // When the adapter changes, clear the `autoConnect` tracking flag const didAttemptAutoConnectRef = useRef(false); useEffect(() => { return () => { didAttemptAutoConnectRef.current = false; }; }, [adapter]); // If auto-connect is enabled, request to connect when the adapter changes and is ready useEffect(() => { if ( didAttemptAutoConnectRef.current || isConnectingRef.current || connected || !onAutoConnectRequest || !(wallet?.readyState === WalletReadyState.Installed || wallet?.readyState === WalletReadyState.Loadable) ) return; isConnectingRef.current = true; setConnecting(true); didAttemptAutoConnectRef.current = true; (async function () { try { await onAutoConnectRequest(); } catch { onConnectError(); // Drop the error. It will be caught by `handleError` anyway. } finally { setConnecting(false); isConnectingRef.current = false; } })(); }, [connected, onAutoConnectRequest, onConnectError, wallet]); // Send a transaction using the provided connection const sendTransaction: WalletAdapterProps['sendTransaction'] = useCallback( async (transaction, connection, options) => { if (!adapter) throw handleErrorRef.current(new WalletNotSelectedError()); if (!connected) throw handleErrorRef.current(new WalletNotConnectedError(), adapter); return await adapter.sendTransaction(transaction, connection, options); }, [adapter, connected] ); // Sign a transaction if the wallet supports it const signTransaction: SignerWalletAdapterProps['signTransaction'] | undefined = useMemo( () => adapter && 'signTransaction' in adapter ? async (transaction) => { if (!connected) throw handleErrorRef.current(new WalletNotConnectedError(), adapter); return await adapter.signTransaction(transaction); } : undefined, [adapter, connected] ); // Sign multiple transactions if the wallet supports it const signAllTransactions: SignerWalletAdapterProps['signAllTransactions'] | undefined = useMemo( () => adapter && 'signAllTransactions' in adapter ? async (transactions) => { if (!connected) throw handleErrorRef.current(new WalletNotConnectedError(), adapter); return await adapter.signAllTransactions(transactions); } : undefined, [adapter, connected] ); // Sign an arbitrary message if the wallet supports it const signMessage: MessageSignerWalletAdapterProps['signMessage'] | undefined = useMemo( () => adapter && 'signMessage' in adapter ? async (message) => { if (!connected) throw handleErrorRef.current(new WalletNotConnectedError(), adapter); return await adapter.signMessage(message); } : undefined, [adapter, connected] ); // Sign in if the wallet supports it const signIn: SignInMessageSignerWalletAdapterProps['signIn'] | undefined = useMemo( () => adapter && 'signIn' in adapter ? async (input) => { return await adapter.signIn(input); } : undefined, [adapter] ); const handleConnect = useCallback(async () => { if (isConnectingRef.current || isDisconnectingRef.current || wallet?.adapter.connected) return; if (!wallet) throw handleErrorRef.current(new WalletNotSelectedError()); const { adapter, readyState } = wallet; if (!(readyState === WalletReadyState.Installed || readyState === WalletReadyState.Loadable)) throw handleErrorRef.current(new WalletNotReadyError(), adapter); isConnectingRef.current = true; setConnecting(true); try { await adapter.connect(); } catch (e) { onConnectError(); throw e; } finally { setConnecting(false); isConnectingRef.current = false; } }, [onConnectError, wallet]); const handleDisconnect = useCallback(async () => { if (isDisconnectingRef.current) return; if (!adapter) return; isDisconnectingRef.current = true; setDisconnecting(true); try { await adapter.disconnect(); } finally { setDisconnecting(false); isDisconnectingRef.current = false; } }, [adapter]); return ( <WalletContext.Provider value={{ autoConnect: !!onAutoConnectRequest, wallets, wallet, publicKey, connected, connecting, disconnecting, select: onSelectWallet, connect: handleConnect, disconnect: handleDisconnect, sendTransaction, signTransaction, signAllTransactions, signMessage, signIn, }} > {children} </WalletContext.Provider> ); }
0
solana_public_repos/anza-xyz/wallet-adapter/packages/core/react
solana_public_repos/anza-xyz/wallet-adapter/packages/core/react/src/getInferredClusterFromEndpoint.ts
import { type Cluster } from '@solana/web3.js'; export default function getInferredClusterFromEndpoint(endpoint?: string): Cluster { if (!endpoint) { return 'mainnet-beta'; } if (/devnet/i.test(endpoint)) { return 'devnet'; } else if (/testnet/i.test(endpoint)) { return 'testnet'; } else { return 'mainnet-beta'; } }
0
solana_public_repos/anza-xyz/wallet-adapter/packages/core/react
solana_public_repos/anza-xyz/wallet-adapter/packages/core/react/src/index.ts
export * from './ConnectionProvider.js'; export * from './errors.js'; export * from './useAnchorWallet.js'; export * from './useConnection.js'; export * from './useLocalStorage.js'; export * from './useWallet.js'; export * from './WalletProvider.js';
0
solana_public_repos/anza-xyz/wallet-adapter/packages/core/react
solana_public_repos/anza-xyz/wallet-adapter/packages/core/react/src/useWallet.ts
import { type Adapter, type MessageSignerWalletAdapterProps, type SignerWalletAdapterProps, type SignInMessageSignerWalletAdapterProps, type WalletAdapterProps, type WalletName, type WalletReadyState, } from '@solana/wallet-adapter-base'; import { type PublicKey } from '@solana/web3.js'; import { createContext, useContext } from 'react'; export interface Wallet { adapter: Adapter; readyState: WalletReadyState; } export interface WalletContextState { autoConnect: boolean; wallets: Wallet[]; wallet: Wallet | null; publicKey: PublicKey | null; connecting: boolean; connected: boolean; disconnecting: boolean; select(walletName: WalletName | null): void; connect(): Promise<void>; disconnect(): Promise<void>; sendTransaction: WalletAdapterProps['sendTransaction']; signTransaction: SignerWalletAdapterProps['signTransaction'] | undefined; signAllTransactions: SignerWalletAdapterProps['signAllTransactions'] | undefined; signMessage: MessageSignerWalletAdapterProps['signMessage'] | undefined; signIn: SignInMessageSignerWalletAdapterProps['signIn'] | undefined; } const EMPTY_ARRAY: ReadonlyArray<never> = []; const DEFAULT_CONTEXT: Partial<WalletContextState> = { autoConnect: false, connecting: false, connected: false, disconnecting: false, select() { logMissingProviderError('call', 'select'); }, connect() { return Promise.reject(logMissingProviderError('call', 'connect')); }, disconnect() { return Promise.reject(logMissingProviderError('call', 'disconnect')); }, sendTransaction() { return Promise.reject(logMissingProviderError('call', 'sendTransaction')); }, signTransaction() { return Promise.reject(logMissingProviderError('call', 'signTransaction')); }, signAllTransactions() { return Promise.reject(logMissingProviderError('call', 'signAllTransactions')); }, signMessage() { return Promise.reject(logMissingProviderError('call', 'signMessage')); }, signIn() { return Promise.reject(logMissingProviderError('call', 'signIn')); }, }; Object.defineProperty(DEFAULT_CONTEXT, 'wallets', { get() { logMissingProviderError('read', 'wallets'); return EMPTY_ARRAY; }, }); Object.defineProperty(DEFAULT_CONTEXT, 'wallet', { get() { logMissingProviderError('read', 'wallet'); return null; }, }); Object.defineProperty(DEFAULT_CONTEXT, 'publicKey', { get() { logMissingProviderError('read', 'publicKey'); return null; }, }); function logMissingProviderError(action: string, property: string) { const error = new Error( `You have tried to ${action} "${property}" on a WalletContext without providing one. ` + 'Make sure to render a WalletProvider as an ancestor of the component that uses WalletContext.' ); console.error(error); return error; } export const WalletContext = createContext<WalletContextState>(DEFAULT_CONTEXT as WalletContextState); export function useWallet(): WalletContextState { return useContext(WalletContext); }
0
solana_public_repos/anza-xyz/wallet-adapter/packages/core/react
solana_public_repos/anza-xyz/wallet-adapter/packages/core/react/src/defineProperty.ts
type InferValue<Prop extends PropertyKey, Desc> = Desc extends { get(): any; value: any } ? never : Desc extends { value: infer T } ? Record<Prop, T> : Desc extends { get(): infer T } ? Record<Prop, T> : never; type DefineProperty<Prop extends PropertyKey, Desc extends PropertyDescriptor> = Desc extends { writable: any; set(val: any): any; } ? never : Desc extends { writable: any; get(): any } ? never : Desc extends { writable: false } ? Readonly<InferValue<Prop, Desc>> : Desc extends { writable: true } ? InferValue<Prop, Desc> : Readonly<InferValue<Prop, Desc>>; export default function defineProperty<Obj extends object, Key extends PropertyKey, PDesc extends PropertyDescriptor>( obj: Obj, prop: Key, val: PDesc ): asserts obj is Obj & DefineProperty<Key, PDesc> { Object.defineProperty(obj, prop, val); }
0
solana_public_repos/anza-xyz/wallet-adapter/packages/core/react
solana_public_repos/anza-xyz/wallet-adapter/packages/core/react/src/WalletProvider.tsx
import { createDefaultAddressSelector, createDefaultAuthorizationResultCache, createDefaultWalletNotFoundHandler, SolanaMobileWalletAdapter, SolanaMobileWalletAdapterWalletName, } from '@solana-mobile/wallet-adapter-mobile'; import { type Adapter, type WalletError, type WalletName } from '@solana/wallet-adapter-base'; import { useStandardWalletAdapters } from '@solana/wallet-standard-wallet-adapter-react'; import React, { type ReactNode, useCallback, useEffect, useMemo, useRef } from 'react'; import getEnvironment, { Environment } from './getEnvironment.js'; import getInferredClusterFromEndpoint from './getInferredClusterFromEndpoint.js'; import { useConnection } from './useConnection.js'; import { useLocalStorage } from './useLocalStorage.js'; import { WalletProviderBase } from './WalletProviderBase.js'; export interface WalletProviderProps { children: ReactNode; wallets: Adapter[]; autoConnect?: boolean | ((adapter: Adapter) => Promise<boolean>); localStorageKey?: string; onError?: (error: WalletError, adapter?: Adapter) => void; } let _userAgent: string | null; function getUserAgent() { if (_userAgent === undefined) { _userAgent = globalThis.navigator?.userAgent ?? null; } return _userAgent; } function getIsMobile(adapters: Adapter[]) { const userAgentString = getUserAgent(); return getEnvironment({ adapters, userAgentString }) === Environment.MOBILE_WEB; } function getUriForAppIdentity() { const location = globalThis.location; if (!location) return; return `${location.protocol}//${location.host}`; } export function WalletProvider({ children, wallets: adapters, autoConnect, localStorageKey = 'walletName', onError, }: WalletProviderProps) { const { connection } = useConnection(); const adaptersWithStandardAdapters = useStandardWalletAdapters(adapters); const mobileWalletAdapter = useMemo(() => { if (!getIsMobile(adaptersWithStandardAdapters)) { return null; } const existingMobileWalletAdapter = adaptersWithStandardAdapters.find( (adapter) => adapter.name === SolanaMobileWalletAdapterWalletName ); if (existingMobileWalletAdapter) { return existingMobileWalletAdapter; } return new SolanaMobileWalletAdapter({ addressSelector: createDefaultAddressSelector(), appIdentity: { uri: getUriForAppIdentity(), }, authorizationResultCache: createDefaultAuthorizationResultCache(), cluster: getInferredClusterFromEndpoint(connection?.rpcEndpoint), onWalletNotFound: createDefaultWalletNotFoundHandler(), }); }, [adaptersWithStandardAdapters, connection?.rpcEndpoint]); const adaptersWithMobileWalletAdapter = useMemo(() => { if (mobileWalletAdapter == null || adaptersWithStandardAdapters.indexOf(mobileWalletAdapter) !== -1) { return adaptersWithStandardAdapters; } return [mobileWalletAdapter, ...adaptersWithStandardAdapters]; }, [adaptersWithStandardAdapters, mobileWalletAdapter]); const [walletName, setWalletName] = useLocalStorage<WalletName | null>( localStorageKey, getIsMobile(adaptersWithStandardAdapters) ? SolanaMobileWalletAdapterWalletName : null ); const adapter = useMemo( () => adaptersWithMobileWalletAdapter.find((a) => a.name === walletName) ?? null, [adaptersWithMobileWalletAdapter, walletName] ); const changeWallet = useCallback( (nextWalletName: WalletName<string> | null) => { if (walletName === nextWalletName) return; if ( adapter && // Selecting a wallet other than the mobile wallet adapter is not // sufficient reason to call `disconnect` on the mobile wallet adapter. // Calling `disconnect` on the mobile wallet adapter causes the entire // authorization store to be wiped. adapter.name !== SolanaMobileWalletAdapterWalletName ) { adapter.disconnect(); } setWalletName(nextWalletName); }, [adapter, setWalletName, walletName] ); useEffect(() => { if (!adapter) return; function handleDisconnect() { if (isUnloadingRef.current) return; // Leave the adapter selected in the event of a disconnection. if (walletName === SolanaMobileWalletAdapterWalletName && getIsMobile(adaptersWithStandardAdapters)) return; setWalletName(null); } adapter.on('disconnect', handleDisconnect); return () => { adapter.off('disconnect', handleDisconnect); }; }, [adapter, adaptersWithStandardAdapters, setWalletName, walletName]); const hasUserSelectedAWallet = useRef(false); const handleAutoConnectRequest = useMemo(() => { if (!autoConnect || !adapter) return; return async () => { // If autoConnect is true or returns true, use the default autoConnect behavior. if (autoConnect === true || (await autoConnect(adapter))) { if (hasUserSelectedAWallet.current) { await adapter.connect(); } else { await adapter.autoConnect(); } } }; }, [autoConnect, adapter]); const isUnloadingRef = useRef(false); useEffect(() => { if (walletName === SolanaMobileWalletAdapterWalletName && getIsMobile(adaptersWithStandardAdapters)) { isUnloadingRef.current = false; return; } function handleBeforeUnload() { isUnloadingRef.current = true; } /** * Some wallets fire disconnection events when the window unloads. Since there's no way to * distinguish between a disconnection event received because a user initiated it, and one * that was received because they've closed the window, we have to track window unload * events themselves. Downstream components use this information to decide whether to act * upon or drop wallet events and errors. */ window.addEventListener('beforeunload', handleBeforeUnload); return () => { window.removeEventListener('beforeunload', handleBeforeUnload); }; }, [adaptersWithStandardAdapters, walletName]); const handleConnectError = useCallback(() => { if (adapter && adapter.name !== SolanaMobileWalletAdapterWalletName) { // If any error happens while connecting, unset the adapter. changeWallet(null); } }, [adapter, changeWallet]); const selectWallet = useCallback( (walletName: WalletName | null) => { hasUserSelectedAWallet.current = true; changeWallet(walletName); }, [changeWallet] ); return ( <WalletProviderBase wallets={adaptersWithMobileWalletAdapter} adapter={adapter} isUnloadingRef={isUnloadingRef} onAutoConnectRequest={handleAutoConnectRequest} onConnectError={handleConnectError} onError={onError} onSelectWallet={selectWallet} > {children} </WalletProviderBase> ); }
0
solana_public_repos/anza-xyz/wallet-adapter/packages/core/react/src
solana_public_repos/anza-xyz/wallet-adapter/packages/core/react/src/__mocks__/MockWalletAdapter.ts
import { BaseWalletAdapter, WalletReadyState } from '@solana/wallet-adapter-base'; import { act } from 'react-dom/test-utils'; export abstract class MockWalletAdapter extends BaseWalletAdapter { connectedValue = false; get connected() { return this.connectedValue; } readyStateValue: WalletReadyState = WalletReadyState.Installed; get readyState() { return this.readyStateValue; } connecting = false; connect = jest.fn(async () => { this.connecting = true; this.connecting = false; this.connectedValue = true; act(() => { // eslint-disable-next-line @typescript-eslint/no-non-null-assertion this.emit('connect', this.publicKey!); }); }); disconnect = jest.fn(async () => { this.connecting = false; this.connectedValue = false; act(() => { this.emit('disconnect'); }); }); sendTransaction = jest.fn(); supportedTransactionVersions = null; autoConnect = jest.fn(); }
0
solana_public_repos/anza-xyz/wallet-adapter/packages/core/react/src
solana_public_repos/anza-xyz/wallet-adapter/packages/core/react/src/__tests__/useLocalStorage-test.tsx
/** * @jest-environment jsdom */ 'use strict'; import 'jest-localstorage-mock'; import React, { createRef, forwardRef, useImperativeHandle } from 'react'; import { createRoot } from 'react-dom/client'; import { act } from 'react-dom/test-utils'; import { useLocalStorage } from '../useLocalStorage.js'; type TestRefType = { getPersistedValue(): string; persistValue(value: string | null): void; }; const DEFAULT_VALUE = 'default value'; const STORAGE_KEY = 'storageKey'; /** * Sometimes merely accessing `localStorage` on the `window` object can result * in a fatal error being thrown - for example in a private window in Firefox. * Call this method to simulate this in your tests, and don't forget to call * the cleanup function after you're done, so that other tests can run. */ function configureLocalStorageToFatalOnAccess(): () => void { const savedPropertyDescriptor = Object.getOwnPropertyDescriptor(window, 'localStorage') as PropertyDescriptor; Object.defineProperty(window, 'localStorage', { get() { throw new Error( 'Error: Accessing `localStorage` resulted in a fatal ' + '(eg. accessing it in a private window in Firefox).' ); }, }); return function restoreOldLocalStorage() { Object.defineProperty(window, 'localStorage', savedPropertyDescriptor); }; } const TestComponent = forwardRef(function TestComponentImpl(_props, ref) { const [persistedValue, setPersistedValue] = useLocalStorage<string | null>(STORAGE_KEY, DEFAULT_VALUE); useImperativeHandle( ref, () => ({ getPersistedValue() { return persistedValue; }, persistValue(newValue: string | null) { setPersistedValue(newValue); }, }), [persistedValue, setPersistedValue] ); return null; }); describe('useLocalStorage', () => { let container: HTMLDivElement | null; let root: ReturnType<typeof createRoot>; let ref: React.RefObject<TestRefType>; function renderTest() { act(() => { root.render(<TestComponent ref={ref} />); }); } beforeEach(() => { localStorage.clear(); jest.resetAllMocks(); container = document.createElement('div'); document.body.appendChild(container); root = createRoot(container); ref = createRef(); }); afterEach(() => { if (root) { root.unmount(); } }); describe('getting the persisted value', () => { describe('when local storage has a value for the storage key', () => { const PERSISTED_VALUE = 'value'; beforeEach(() => { (localStorage.getItem as jest.Mock).mockImplementation((storageKey) => { if (storageKey !== STORAGE_KEY) { return null; } return JSON.stringify(PERSISTED_VALUE); }); expect(renderTest).not.toThrow(); }); it('returns that value', () => { expect(ref.current?.getPersistedValue()).toBe(PERSISTED_VALUE); }); }); describe('when local storage has no value for the storage key', () => { const PERSISTED_VALUE = 'value'; beforeEach(() => { (localStorage.getItem as jest.Mock).mockReturnValue(null); expect(renderTest).not.toThrow(); }); it('returns the default value', () => { expect(ref.current?.getPersistedValue()).toBe(DEFAULT_VALUE); }); }); describe('when merely accessing local storage results in a fatal error', () => { let restoreOldLocalStorage: () => void; beforeEach(() => { restoreOldLocalStorage = configureLocalStorageToFatalOnAccess(); expect(renderTest).not.toThrow(); }); afterEach(() => { restoreOldLocalStorage(); }); it('renders with the default value', () => { expect(ref.current?.getPersistedValue()).toBe(DEFAULT_VALUE); }); }); describe('when local storage fatals on read', () => { beforeEach(() => { (localStorage.getItem as jest.Mock).mockImplementation(() => { throw new Error('Local storage derped'); }); expect(renderTest).not.toThrow(); }); it('renders with the default value', () => { expect(ref.current?.getPersistedValue()).toBe(DEFAULT_VALUE); }); }); describe('when local storage does not exist', () => { let cachedLocalStorage: Storage; beforeEach(() => { cachedLocalStorage = localStorage; // @ts-ignore - readonly delete global.localStorage; expect(renderTest).not.toThrow(); }); afterEach(() => { // @ts-ignore - readonly global.localStorage = cachedLocalStorage; }); it('renders with the default value', () => { expect(ref.current?.getPersistedValue()).toBe(DEFAULT_VALUE); }); }); describe('when local storage contains invalid JSON', () => { beforeEach(() => { (localStorage.getItem as jest.Mock).mockReturnValue('' /* <- not valid JSON! */); expect(renderTest).not.toThrow(); }); it('renders with the default value', () => { expect(ref.current?.getPersistedValue()).toBe(DEFAULT_VALUE); }); }); }); describe('setting the persisted value', () => { describe('when setting to a non-null value', () => { const NEW_VALUE = 'new value'; beforeEach(() => { expect(renderTest).not.toThrow(); }); it('sets that value in local storage', () => { act(() => { ref.current?.persistValue(NEW_VALUE); }); expect(localStorage.setItem).toHaveBeenCalledWith(STORAGE_KEY, JSON.stringify(NEW_VALUE)); }); it('re-renders the component with the new value', () => { act(() => { ref.current?.persistValue(NEW_VALUE); }); expect(ref.current?.getPersistedValue()).toBe(NEW_VALUE); }); describe('many times in a row', () => { it('sets the new value in local storage once', () => { act(() => { ref.current?.persistValue(NEW_VALUE); ref.current?.persistValue(NEW_VALUE); }); expect(window.localStorage.setItem).toHaveBeenCalledTimes(1); expect(window.localStorage.setItem).toHaveBeenCalledWith(STORAGE_KEY, JSON.stringify(NEW_VALUE)); }); }); describe('multiple times ending with the current value', () => { it("does not call local storage's setter", () => { act(() => { ref.current?.persistValue(NEW_VALUE); ref.current?.persistValue(DEFAULT_VALUE); }); expect(window.localStorage.setItem).toHaveBeenCalledTimes(0); }); }); }); describe('when setting to `null`', () => { beforeEach(() => { expect(renderTest).not.toThrow(); }); it('removes the key from local storage', () => { act(() => { ref.current?.persistValue(null); }); expect(localStorage.removeItem).toHaveBeenCalledWith(STORAGE_KEY); }); it('re-renders the component with `null`', () => { act(() => { ref.current?.persistValue(null); }); expect(ref.current?.getPersistedValue()).toBe(null); }); }); describe('when merely accessing local storage results in a fatal error', () => { const NEW_VALUE = 'new value'; let restoreOldLocalStorage: () => void; beforeEach(() => { restoreOldLocalStorage = configureLocalStorageToFatalOnAccess(); expect(renderTest).not.toThrow(); }); afterEach(() => { restoreOldLocalStorage(); }); it('re-renders the component with the new value', () => { act(() => { ref.current?.persistValue(NEW_VALUE); }); expect(ref.current?.getPersistedValue()).toBe(NEW_VALUE); }); }); describe('when local storage fatals on write', () => { const NEW_VALUE = 'new value'; beforeEach(() => { (localStorage.setItem as jest.Mock).mockImplementation(() => { throw new Error('Local storage derped'); }); expect(renderTest).not.toThrow(); }); it('re-renders the component with the new value', () => { act(() => { ref.current?.persistValue(NEW_VALUE); }); expect(ref.current?.getPersistedValue()).toBe(NEW_VALUE); }); }); describe('when local storage does not exist', () => { let cachedLocalStorage: Storage; beforeEach(() => { cachedLocalStorage = localStorage; // @ts-ignore - readonly delete global.localStorage; expect(renderTest).not.toThrow(); }); afterEach(() => { // @ts-ignore - readonly global.localStorage = cachedLocalStorage; }); describe('when setting to a non-null value', () => { const NEW_VALUE = 'new value'; it('re-renders the component with the new value', () => { act(() => { ref.current?.persistValue(NEW_VALUE); }); expect(ref.current?.getPersistedValue()).toBe(NEW_VALUE); }); }); describe('when setting to `null`', () => { it('re-renders the component with `null`', () => { act(() => { ref.current?.persistValue(null); }); expect(ref.current?.getPersistedValue()).toBe(null); }); }); }); }); });
0
solana_public_repos/anza-xyz/wallet-adapter/packages/core/react/src
solana_public_repos/anza-xyz/wallet-adapter/packages/core/react/src/__tests__/WalletProviderDesktop-test.tsx
/** * @jest-environment jsdom */ 'use strict'; import { type AddressSelector, type AuthorizationResultCache, SolanaMobileWalletAdapter, } from '@solana-mobile/wallet-adapter-mobile'; import { type Adapter, WalletError, type WalletName, WalletReadyState } from '@solana/wallet-adapter-base'; import { PublicKey } from '@solana/web3.js'; import 'jest-localstorage-mock'; import React, { createRef, forwardRef, useImperativeHandle } from 'react'; import { createRoot } from 'react-dom/client'; import { act } from 'react-dom/test-utils'; import { MockWalletAdapter } from '../__mocks__/MockWalletAdapter.js'; import { useWallet, type WalletContextState } from '../useWallet.js'; import { WalletProvider, type WalletProviderProps } from '../WalletProvider.js'; jest.mock('../getEnvironment.js', () => ({ ...jest.requireActual('../getEnvironment.js'), __esModule: true, default: () => jest.requireActual('../getEnvironment.js').Environment.DESKTOP_WEB, })); type TestRefType = { getWalletContextState(): WalletContextState; }; const TestComponent = forwardRef(function TestComponentImpl(_props, ref) { const wallet = useWallet(); useImperativeHandle( ref, () => ({ getWalletContextState() { return wallet; }, }), [wallet] ); return null; }); const WALLET_NAME_CACHE_KEY = 'cachedWallet'; /** * NOTE: If you add a test to this suite, also add it to `WalletProviderMobile-test.tsx`. * * You may be wondering why these suites haven't been designed as one suite with a procedurally * generated `describe` block that mocks `getEnvironment` differently on each pass. The reason has * to do with the way `jest.resetModules()` plays havoc with the React test renderer. If you have * a solution, please do send a PR. */ describe('WalletProvider when the environment is `DESKTOP_WEB`', () => { let ref: React.RefObject<TestRefType>; let root: ReturnType<typeof createRoot>; let container: HTMLElement; let fooWalletAdapter: MockWalletAdapter; let adapters: Adapter[]; function renderTest(props: Omit<WalletProviderProps, 'appIdentity' | 'children' | 'cluster' | 'wallets'>) { act(() => { root.render( <WalletProvider {...props} localStorageKey={WALLET_NAME_CACHE_KEY} wallets={adapters}> <TestComponent ref={ref} /> </WalletProvider> ); }); } class FooWalletAdapter extends MockWalletAdapter { name = 'FooWallet' as WalletName<'FooWallet'>; url = 'https://foowallet.com'; icon = 'foo.png'; publicKey = new PublicKey('Foo11111111111111111111111111111111111111111'); } beforeEach(() => { localStorage.clear(); jest.clearAllMocks().resetModules(); container = document.createElement('div'); document.body.appendChild(container); root = createRoot(container); ref = createRef(); fooWalletAdapter = new FooWalletAdapter(); adapters = [fooWalletAdapter]; }); afterEach(() => { if (root) { root.unmount(); } }); describe('given a selected wallet', () => { beforeEach(async () => { fooWalletAdapter.readyStateValue = WalletReadyState.NotDetected; renderTest({}); await act(async () => { ref.current?.getWalletContextState().select('FooWallet' as WalletName<'FooWallet'>); await Promise.resolve(); // Flush all promises in effects after calling `select()`. }); expect(ref.current?.getWalletContextState().wallet?.readyState).toBe(WalletReadyState.NotDetected); }); it('should store the wallet name', () => { expect(localStorage.setItem).toHaveBeenCalledWith( WALLET_NAME_CACHE_KEY, JSON.stringify(fooWalletAdapter.name) ); }); describe('when the wallet disconnects of its own accord', () => { beforeEach(() => { jest.clearAllMocks(); act(() => { fooWalletAdapter.disconnect(); }); }); it('should clear the stored wallet name', () => { expect(localStorage.removeItem).toHaveBeenCalledWith(WALLET_NAME_CACHE_KEY); }); }); describe('when the wallet disconnects as a consequence of the window unloading', () => { beforeEach(() => { jest.clearAllMocks(); act(() => { window.dispatchEvent(new Event('beforeunload')); fooWalletAdapter.disconnect(); }); }); it('should not clear the stored wallet name', () => { expect(localStorage.removeItem).not.toHaveBeenCalledWith(WALLET_NAME_CACHE_KEY); }); }); }); describe('when there is no mobile wallet adapter in the adapters array', () => { it('does not create a new mobile wallet adapter', () => { renderTest({}); expect(jest.mocked(SolanaMobileWalletAdapter).mock.instances).toHaveLength(0); }); }); describe('when a custom mobile wallet adapter is supplied in the adapters array', () => { let customAdapter: Adapter; const CUSTOM_APP_IDENTITY = { uri: 'https://custom.com', }; const CUSTOM_CLUSTER = 'devnet'; beforeEach(() => { customAdapter = new SolanaMobileWalletAdapter({ addressSelector: jest.fn() as unknown as AddressSelector, appIdentity: CUSTOM_APP_IDENTITY, authorizationResultCache: jest.fn() as unknown as AuthorizationResultCache, cluster: CUSTOM_CLUSTER, onWalletNotFound: jest.fn(), }); adapters.push(customAdapter); jest.clearAllMocks(); }); it('does not load the custom mobile wallet adapter into state as the default', () => { renderTest({}); expect(ref.current?.getWalletContextState().wallet?.adapter).not.toBe(customAdapter); }); }); describe('when there exists no stored wallet name', () => { beforeEach(() => { (localStorage.getItem as jest.Mock).mockReturnValue(null); }); it('loads no wallet into state', () => { renderTest({}); expect(ref.current?.getWalletContextState().wallet).toBeNull(); }); it('loads no public key into state', () => { renderTest({}); expect(ref.current?.getWalletContextState().publicKey).toBeNull(); }); }); describe('when there exists a stored wallet name', () => { beforeEach(() => { (localStorage.getItem as jest.Mock).mockReturnValue(JSON.stringify('FooWallet')); }); it('loads the corresponding adapter into state', () => { renderTest({}); expect(ref.current?.getWalletContextState().wallet?.adapter).toBeInstanceOf(FooWalletAdapter); }); it('loads the corresponding public key into state', () => { renderTest({}); expect(ref.current?.getWalletContextState().publicKey).toBe(fooWalletAdapter.publicKey); }); it('sets state tracking variables to defaults', () => { renderTest({}); expect(ref.current?.getWalletContextState()).toMatchObject({ connected: false, connecting: false, }); }); }); describe('autoConnect', () => { beforeEach(async () => { renderTest({}); await act(async () => { ref.current?.getWalletContextState().select('FooWallet' as WalletName<'FooWallet'>); await Promise.resolve(); // Flush all promises in effects after calling `select()`. }); }); describe('when autoConnect is disabled', () => { beforeEach(() => { renderTest({ autoConnect: false }); }); it('does not call `autoConnect`', () => { // eslint-disable-next-line @typescript-eslint/no-non-null-assertion const adapter = ref.current!.getWalletContextState().wallet!.adapter; expect(adapter.connect).not.toHaveBeenCalled(); expect(adapter.autoConnect).not.toHaveBeenCalled(); }); }); describe('when autoConnect is enabled', () => { beforeEach(() => { renderTest({ autoConnect: true }); }); it('calls `connect`', () => { // eslint-disable-next-line @typescript-eslint/no-non-null-assertion const adapter = ref.current!.getWalletContextState().wallet!.adapter; expect(adapter.connect).toHaveBeenCalled(); expect(adapter.autoConnect).not.toHaveBeenCalled(); }); }); }); describe('onError', () => { let onError: jest.Mock; let errorThrown: WalletError; beforeEach(() => { errorThrown = new WalletError('o no'); onError = jest.fn(); renderTest({ onError }); }); describe('when the wallet emits an error', () => { let adapter: Adapter; beforeEach(() => { act(() => { adapter = ref.current?.getWalletContextState().wallet?.adapter as Adapter; adapter.emit('error', errorThrown); }); }); it('should fire the `onError` callback', () => { expect(onError).toHaveBeenCalledWith(errorThrown, adapter); }); }); describe('when window `beforeunload` event fires', () => { beforeEach(() => { act(() => { window.dispatchEvent(new Event('beforeunload')); }); }); describe('then the wallet emits an error', () => { beforeEach(() => { act(() => { const adapter = ref.current?.getWalletContextState().wallet?.adapter as Adapter; adapter.emit('error', errorThrown); }); }); it('should not fire the `onError` callback', () => { expect(onError).not.toHaveBeenCalled(); }); }); }); }); describe('disconnect()', () => { describe('when there is already a wallet connected', () => { beforeEach(async () => { window.open = jest.fn(); renderTest({}); await act(async () => { ref.current?.getWalletContextState().select('FooWallet' as WalletName<'FooWallet'>); await Promise.resolve(); // Flush all promises in effects after calling `select()`. }); await act(() => { ref.current?.getWalletContextState().connect(); }); }); describe('and you select a different wallet', () => { beforeEach(async () => { await act(async () => { ref.current?.getWalletContextState().select('BarWallet' as WalletName<'BarWallet'>); await Promise.resolve(); // Flush all promises in effects after calling `select()`. }); }); it('should disconnect the old wallet', () => { expect(fooWalletAdapter.disconnect).toHaveBeenCalled(); }); }); describe('and you select the same wallet', () => { beforeEach(async () => { await act(async () => { ref.current?.getWalletContextState().select('FooWallet' as WalletName<'FooWallet'>); await Promise.resolve(); // Flush all promises in effects after calling `select()`. }); }); it('should not disconnect the old wallet', () => { expect(fooWalletAdapter.disconnect).not.toHaveBeenCalled(); }); }); describe('once disconnected', () => { beforeEach(async () => { jest.clearAllMocks(); ref.current?.getWalletContextState().disconnect(); await Promise.resolve(); // Flush all promises in effects after calling `disconnect()`. }); it('should clear the stored wallet name', () => { expect(localStorage.removeItem).toHaveBeenCalledWith(WALLET_NAME_CACHE_KEY); }); it('sets state tracking variables to defaults', () => { renderTest({}); expect(ref.current?.getWalletContextState()).toMatchObject({ connected: false, connecting: false, publicKey: null, }); }); }); }); }); });
0
solana_public_repos/anza-xyz/wallet-adapter/packages/core/react/src
solana_public_repos/anza-xyz/wallet-adapter/packages/core/react/src/__tests__/getClusterFromConnection-test.ts
import getInferredClusterFromEndpoint from '../getInferredClusterFromEndpoint.js'; describe('getInferredClusterFromEndpoint()', () => { describe('when the endpoint is `undefined`', () => { const endpoint = undefined; it('creates a new mobile wallet adapter with `mainnet-beta` as the cluster', () => { expect(getInferredClusterFromEndpoint(endpoint)).toBe('mainnet-beta'); }); }); describe('when the endpoint is the empty string', () => { const endpoint = ''; it('creates a new mobile wallet adapter with `mainnet-beta` as the cluster', () => { expect(getInferredClusterFromEndpoint(endpoint)).toBe('mainnet-beta'); }); }); describe("when the endpoint contains the word 'devnet'", () => { const endpoint = 'https://foo-devnet.com'; it('creates a new mobile wallet adapter with `devnet` as the cluster', () => { expect(getInferredClusterFromEndpoint(endpoint)).toBe('devnet'); }); }); describe("when the endpoint contains the word 'testnet'", () => { const endpoint = 'https://foo-testnet.com'; it('creates a new mobile wallet adapter with `testnet` as the cluster', () => { expect(getInferredClusterFromEndpoint(endpoint)).toBe('testnet'); }); }); describe("when the endpoint contains the word 'mainnet-beta'", () => { const endpoint = 'https://foo-mainnet-beta.com'; it('creates a new mobile wallet adapter with `mainnet-beta` as the cluster', () => { expect(getInferredClusterFromEndpoint(endpoint)).toBe('mainnet-beta'); }); }); });
0
solana_public_repos/anza-xyz/wallet-adapter/packages/core/react/src
solana_public_repos/anza-xyz/wallet-adapter/packages/core/react/src/__tests__/WalletProviderBase-test.tsx
/** * @jest-environment jsdom */ 'use strict'; import { type Adapter, BaseWalletAdapter, WalletError, type WalletName, WalletNotReadyError, WalletReadyState, } from '@solana/wallet-adapter-base'; import { PublicKey } from '@solana/web3.js'; import React, { createRef, forwardRef, useImperativeHandle } from 'react'; import { createRoot } from 'react-dom/client'; import { act } from 'react-dom/test-utils'; import { useWallet, type WalletContextState } from '../useWallet.js'; import { WalletProviderBase, type WalletProviderBaseProps } from '../WalletProviderBase.js'; type TestRefType = { getWalletContextState(): WalletContextState; }; const TestComponent = forwardRef(function TestComponentImpl(_props, ref) { const wallet = useWallet(); useImperativeHandle( ref, () => ({ getWalletContextState() { return wallet; }, }), [wallet] ); return null; }); describe('WalletProviderBase', () => { let ref: React.RefObject<TestRefType>; let root: ReturnType<typeof createRoot>; let container: HTMLElement; let fooWalletAdapter: MockWalletAdapter; let barWalletAdapter: MockWalletAdapter; let bazWalletAdapter: MockWalletAdapter; let adapters: Adapter[]; let isUnloading: React.MutableRefObject<boolean>; function renderTest( props: Omit< WalletProviderBaseProps, 'children' | 'wallets' | 'isUnloadingRef' | 'onConnectError' | 'onSelectWallet' > ) { act(() => { root.render( <WalletProviderBase wallets={adapters} isUnloadingRef={isUnloading} onConnectError={jest.fn()} onSelectWallet={jest.fn()} {...props} > <TestComponent ref={ref} /> </WalletProviderBase> ); }); } abstract class MockWalletAdapter extends BaseWalletAdapter { connectionPromise: null | Promise<void> = null; disconnectionPromise: null | Promise<void> = null; connectedValue = false; get connected() { return this.connectedValue; } readyStateValue: WalletReadyState = WalletReadyState.Installed; get readyState() { return this.readyStateValue; } connecting = false; connect = jest.fn(async () => { this.connecting = true; if (this.connectionPromise) { await this.connectionPromise; } this.connecting = false; this.connectedValue = true; act(() => { // eslint-disable-next-line @typescript-eslint/no-non-null-assertion this.emit('connect', this.publicKey!); }); }); disconnect = jest.fn(async () => { this.connecting = false; if (this.disconnectionPromise) { await this.disconnectionPromise; } this.connectedValue = false; act(() => { this.emit('disconnect'); }); }); sendTransaction = jest.fn(); supportedTransactionVersions = null; } class FooWalletAdapter extends MockWalletAdapter { name = 'FooWallet' as WalletName<'FooWallet'>; url = 'https://foowallet.com'; icon = 'foo.png'; publicKey = new PublicKey('Foo11111111111111111111111111111111111111111'); } class BarWalletAdapter extends MockWalletAdapter { name = 'BarWallet' as WalletName<'BarWallet'>; url = 'https://barwallet.com'; icon = 'bar.png'; publicKey = new PublicKey('Bar11111111111111111111111111111111111111111'); } class BazWalletAdapter extends MockWalletAdapter { name = 'BazWallet' as WalletName<'BazWallet'>; url = 'https://bazwallet.com'; icon = 'baz.png'; publicKey = new PublicKey('Baz11111111111111111111111111111111111111111'); } beforeEach(() => { jest.resetAllMocks(); container = document.createElement('div'); document.body.appendChild(container); isUnloading = { current: false }; root = createRoot(container); ref = createRef(); fooWalletAdapter = new FooWalletAdapter(); barWalletAdapter = new BarWalletAdapter(); bazWalletAdapter = new BazWalletAdapter(); adapters = [fooWalletAdapter, barWalletAdapter, bazWalletAdapter]; }); afterEach(() => { if (root) { root.unmount(); } }); describe('given a selected wallet', () => { beforeEach(async () => { fooWalletAdapter.readyStateValue = WalletReadyState.NotDetected; renderTest({ adapter: fooWalletAdapter }); expect(ref.current?.getWalletContextState().wallet?.readyState).toBe(WalletReadyState.NotDetected); }); describe('that then becomes ready', () => { beforeEach(() => { act(() => { fooWalletAdapter.readyStateValue = WalletReadyState.Installed; fooWalletAdapter.emit('readyStateChange', WalletReadyState.Installed); }); }); it('sets `ready` to true', () => { expect(ref.current?.getWalletContextState().wallet?.readyState).toBe(WalletReadyState.Installed); }); }); describe('when the wallet disconnects of its own accord', () => { beforeEach(() => { act(() => { fooWalletAdapter.disconnect(); }); }); it('clears out the state', () => { expect(ref.current?.getWalletContextState()).toMatchObject({ connected: false, connecting: false, publicKey: null, }); }); }); describe('when the wallet disconnects as a consequence of the window unloading', () => { beforeEach(() => { act(() => { isUnloading.current = true; fooWalletAdapter.disconnect(); }); }); it('should not clear out the state', () => { expect(ref.current?.getWalletContextState().wallet?.adapter).toBe(fooWalletAdapter); expect(ref.current?.getWalletContextState().publicKey).not.toBeNull(); }); }); }); describe('given the presence of an unsupported wallet', () => { beforeEach(() => { bazWalletAdapter.readyStateValue = WalletReadyState.Unsupported; renderTest({ adapter: fooWalletAdapter }); }); it('filters out the unsupported wallet', () => { const adapters = ref.current?.getWalletContextState().wallets.map(({ adapter }) => adapter); expect(adapters).not.toContain(bazWalletAdapter); }); }); describe('when auto connect is disabled', () => { beforeEach(() => { renderTest({ onAutoConnectRequest: undefined, adapter: fooWalletAdapter }); }); it('`autoConnect` is `false` on state', () => { expect(ref.current?.getWalletContextState().autoConnect).toBe(false); }); }); describe('and auto connect is enabled', () => { let onAutoConnectRequest: jest.Mock; beforeEach(() => { onAutoConnectRequest = jest.fn(); fooWalletAdapter.readyStateValue = WalletReadyState.NotDetected; renderTest({ adapter: fooWalletAdapter, onAutoConnectRequest }); }); it('`autoConnect` is `true` on state', () => { expect(ref.current?.getWalletContextState().autoConnect).toBe(true); }); describe('before the adapter is ready', () => { it('does not call `connect` on the adapter', () => { expect(fooWalletAdapter.connect).not.toHaveBeenCalled(); }); describe('once the adapter becomes ready', () => { beforeEach(async () => { await act(async () => { fooWalletAdapter.readyStateValue = WalletReadyState.Installed; fooWalletAdapter.emit('readyStateChange', WalletReadyState.Installed); await Promise.resolve(); // Flush all promises in effects after calling `select()`. }); }); it('calls `onAutoConnectRequest`', () => { expect(onAutoConnectRequest).toHaveBeenCalledTimes(1); }); describe('when switching to another adapter', () => { beforeEach(async () => { jest.clearAllMocks(); renderTest({ adapter: barWalletAdapter, onAutoConnectRequest }); }); it('calls `onAutoConnectRequest` despite having called it once before on the old adapter', () => { expect(onAutoConnectRequest).toHaveBeenCalledTimes(1); }); }); describe('once the adapter connects', () => { beforeEach(async () => { await act(async () => { await fooWalletAdapter.connect(); }); }); describe('then disconnects', () => { beforeEach(async () => { jest.clearAllMocks(); await act(async () => { await fooWalletAdapter.disconnect(); }); }); it('does not make a second attempt to auto connect', () => { expect(onAutoConnectRequest).not.toHaveBeenCalled(); }); }); }); }); }); }); describe('custom error handler', () => { const errorToEmit = new WalletError(); let onError: jest.Mock; beforeEach(async () => { onError = jest.fn(); renderTest({ adapter: fooWalletAdapter, onError }); }); it('gets called in response to adapter errors', () => { act(() => { fooWalletAdapter.emit('error', errorToEmit); }); expect(onError).toBeCalledWith(errorToEmit, fooWalletAdapter); }); it('does not get called if the window is unloading', () => { const errorToEmit = new WalletError(); act(() => { isUnloading.current = true; fooWalletAdapter.emit('error', errorToEmit); }); expect(onError).not.toBeCalled(); }); describe('when a wallet is connected', () => { beforeEach(async () => { await act(() => { ref.current?.getWalletContextState().connect(); }); expect(ref.current?.getWalletContextState()).toMatchObject({ connected: true, }); }); describe('then the `onError` function changes', () => { beforeEach(async () => { const differentOnError = jest.fn(); /* Some function, different from the one above */ renderTest({ adapter: fooWalletAdapter, onError: differentOnError }); }); it('does not cause state to be cleared when it changes', () => { // Regression test for https://github.com/anza-xyz/wallet-adapter/issues/636 expect(ref.current?.getWalletContextState()).toMatchObject({ connected: true, }); }); }); }); }); describe('connect()', () => { describe('given an adapter that is not ready', () => { beforeEach(async () => { window.open = jest.fn(); fooWalletAdapter.readyStateValue = WalletReadyState.NotDetected; renderTest({ adapter: fooWalletAdapter }); expect(ref.current?.getWalletContextState().wallet?.readyState).toBe(WalletReadyState.NotDetected); act(() => { expect(ref.current?.getWalletContextState().connect()).rejects.toThrow(); }); }); it("opens the wallet's URL in a new window", () => { expect(window.open).toBeCalledWith('https://foowallet.com', '_blank'); }); it('throws a `WalletNotReady` error', () => { act(() => { expect(ref.current?.getWalletContextState().connect()).rejects.toThrow(new WalletNotReadyError()); }); }); }); describe('given an adapter that is ready', () => { let commitConnection: () => void; beforeEach(async () => { renderTest({ adapter: fooWalletAdapter }); fooWalletAdapter.connectionPromise = new Promise<void>((resolve) => { commitConnection = resolve; }); await act(() => { ref.current?.getWalletContextState().connect(); }); }); it('calls connect on the adapter', () => { expect(fooWalletAdapter.connect).toHaveBeenCalled(); }); it('updates state tracking variables appropriately', () => { expect(ref.current?.getWalletContextState()).toMatchObject({ connected: false, connecting: true, }); }); describe('once connected', () => { beforeEach(async () => { await act(() => { commitConnection(); }); }); it('updates state tracking variables appropriately', () => { expect(ref.current?.getWalletContextState()).toMatchObject({ connected: true, connecting: false, }); }); }); }); }); describe('disconnect()', () => { describe('when there is already an adapter supplied', () => { let commitDisconnection: () => void; beforeEach(async () => { window.open = jest.fn(); renderTest({ adapter: fooWalletAdapter }); await act(() => { ref.current?.getWalletContextState().connect(); }); fooWalletAdapter.disconnectionPromise = new Promise<void>((resolve) => { commitDisconnection = resolve; }); await act(() => { ref.current?.getWalletContextState().disconnect(); }); }); it('updates state tracking variables appropriately', () => { expect(ref.current?.getWalletContextState()).toMatchObject({ connected: true, }); }); describe('once disconnected', () => { beforeEach(async () => { await act(() => { commitDisconnection(); }); }); it('clears out the state', () => { expect(ref.current?.getWalletContextState()).toMatchObject({ connected: false, connecting: false, publicKey: null, }); }); }); }); }); describe('when there is no adapter supplied', () => { beforeEach(() => { renderTest({ adapter: null }); }); describe('and one becomes supplied', () => { beforeEach(() => { renderTest({ adapter: fooWalletAdapter }); }); it('sets the state tracking variables', () => { expect(ref.current?.getWalletContextState()).toMatchObject({ wallet: { adapter: fooWalletAdapter, readyState: fooWalletAdapter.readyState }, connected: false, connecting: false, publicKey: null, }); }); }); }); describe('when there is already an adapter supplied', () => { let commitFooWalletDisconnection: () => void; beforeEach(async () => { fooWalletAdapter.disconnectionPromise = new Promise<void>((resolve) => { commitFooWalletDisconnection = resolve; }); renderTest({ adapter: fooWalletAdapter }); }); describe('when you null out the adapter', () => { beforeEach(() => { renderTest({ adapter: null }); }); it('clears out the state', () => { expect(ref.current?.getWalletContextState()).toMatchObject({ wallet: null, connected: false, connecting: false, publicKey: null, }); }); }); describe('and a different adapter becomes supplied', () => { beforeEach(async () => { renderTest({ adapter: barWalletAdapter }); }); it('the adapter of the new wallet should be set in state', () => { expect(ref.current?.getWalletContextState().wallet?.adapter).toBe(barWalletAdapter); }); /** * Regression test: a race condition in the wallet name setter could result in the * wallet reverting back to an old value, depending on the cadence of the previous * wallets' disconnect operation. */ describe('then a different one becomes supplied before the first one has disconnected', () => { beforeEach(async () => { renderTest({ adapter: bazWalletAdapter }); act(() => { commitFooWalletDisconnection(); }); }); it('the wallet you selected last should be set in state', () => { expect(ref.current?.getWalletContextState().wallet?.adapter).toBe(bazWalletAdapter); }); }); }); }); });
0
solana_public_repos/anza-xyz/wallet-adapter/packages/core/react/src
solana_public_repos/anza-xyz/wallet-adapter/packages/core/react/src/__tests__/getEnvironment-test.ts
import { type Adapter, WalletReadyState } from '@solana/wallet-adapter-base'; import getEnvironment, { Environment } from '../getEnvironment.js'; describe('getEnvironment()', () => { [ { description: 'on Android', expectedEnvironmentWithInstalledAdapter: Environment.DESKTOP_WEB, expectedEnvironmentWithNoInstalledAdapter: Environment.MOBILE_WEB, userAgentString: 'Android', }, { description: 'in a webview', expectedEnvironmentWithInstalledAdapter: Environment.DESKTOP_WEB, expectedEnvironmentWithNoInstalledAdapter: Environment.DESKTOP_WEB, userAgentString: 'WebView', }, { description: 'on desktop', expectedEnvironmentWithInstalledAdapter: Environment.DESKTOP_WEB, expectedEnvironmentWithNoInstalledAdapter: Environment.DESKTOP_WEB, userAgentString: 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/105.0.0.0 Safari/537.36', }, { description: 'the user agent is null', expectedEnvironmentWithInstalledAdapter: Environment.DESKTOP_WEB, expectedEnvironmentWithNoInstalledAdapter: Environment.DESKTOP_WEB, userAgentString: null, }, ].forEach( ({ description, expectedEnvironmentWithInstalledAdapter, expectedEnvironmentWithNoInstalledAdapter, userAgentString, }) => { describe(`when ${description}`, () => { describe('with no installed adapters', () => { it(`returns \`${Environment[expectedEnvironmentWithNoInstalledAdapter]}\``, () => { const adapters = [ { readyState: WalletReadyState.Loadable } as Adapter, { readyState: WalletReadyState.NotDetected } as Adapter, { readyState: WalletReadyState.Unsupported } as Adapter, ]; expect(getEnvironment({ adapters, userAgentString })).toBe( expectedEnvironmentWithNoInstalledAdapter ); }); }); describe('with at least one installed adapter', () => { it(`returns \`${Environment[expectedEnvironmentWithInstalledAdapter]}\``, () => { const adapters = [ { readyState: WalletReadyState.Loadable } as Adapter, { readyState: WalletReadyState.Installed } as Adapter, { readyState: WalletReadyState.NotDetected } as Adapter, { readyState: WalletReadyState.Unsupported } as Adapter, ]; expect(getEnvironment({ adapters, userAgentString })).toBe( expectedEnvironmentWithInstalledAdapter ); }); }); }); } ); });
0
solana_public_repos/anza-xyz/wallet-adapter/packages/core/react/src
solana_public_repos/anza-xyz/wallet-adapter/packages/core/react/src/__tests__/WalletProviderMobile-test.tsx
/** * @jest-environment jsdom */ 'use strict'; import { type AddressSelector, type AuthorizationResultCache, SolanaMobileWalletAdapter, SolanaMobileWalletAdapterWalletName, } from '@solana-mobile/wallet-adapter-mobile'; import { type Adapter, BaseWalletAdapter, WalletError, type WalletName, WalletReadyState, } from '@solana/wallet-adapter-base'; import { type Connection, PublicKey } from '@solana/web3.js'; import 'jest-localstorage-mock'; import React, { createRef, forwardRef, useImperativeHandle } from 'react'; import { createRoot } from 'react-dom/client'; import { act } from 'react-dom/test-utils'; import { useConnection } from '../useConnection.js'; import { useWallet, type WalletContextState } from '../useWallet.js'; import { WalletProvider, type WalletProviderProps } from '../WalletProvider.js'; jest.mock('../getEnvironment.js', () => ({ ...jest.requireActual('../getEnvironment.js'), __esModule: true, default: () => jest.requireActual('../getEnvironment.js').Environment.MOBILE_WEB, })); jest.mock('../getInferredClusterFromEndpoint.js', () => ({ ...jest.requireActual('../getInferredClusterFromEndpoint.js'), __esModule: true, default: (endpoint?: string) => { switch (endpoint) { case 'https://fake-endpoint-for-test.com': return 'fake-cluster-for-test'; default: return 'mainnet-beta'; } }, })); jest.mock('../useConnection.js'); type TestRefType = { getWalletContextState(): WalletContextState; }; const TestComponent = forwardRef(function TestComponentImpl(_props, ref) { const wallet = useWallet(); useImperativeHandle( ref, () => ({ getWalletContextState() { return wallet; }, }), [wallet] ); return null; }); const WALLET_NAME_CACHE_KEY = 'cachedWallet'; /** * NOTE: If you add a test to this suite, also add it to `WalletProviderDesktop-test.tsx`. * * You may be wondering why these suites haven't been designed as one suite with a procedurally * generated `describe` block that mocks `getEnvironment` differently on each pass. The reason has * to do with the way `jest.resetModules()` plays havoc with the React test renderer. If you have * a solution, please do send a PR. */ describe('WalletProvider when the environment is `MOBILE_WEB`', () => { let ref: React.RefObject<TestRefType>; let root: ReturnType<typeof createRoot>; let container: HTMLElement; let fooWalletAdapter: MockWalletAdapter; let adapters: Adapter[]; function renderTest(props: Omit<WalletProviderProps, 'appIdentity' | 'children' | 'cluster' | 'wallets'>) { act(() => { root.render( <WalletProvider {...props} localStorageKey={WALLET_NAME_CACHE_KEY} wallets={adapters}> <TestComponent ref={ref} /> </WalletProvider> ); }); } abstract class MockWalletAdapter extends BaseWalletAdapter { connectedValue = false; get connected() { return this.connectedValue; } readyStateValue: WalletReadyState = WalletReadyState.Installed; get readyState() { return this.readyStateValue; } connecting = false; connect = jest.fn(async () => { this.connecting = true; this.connecting = false; this.connectedValue = true; act(() => { // eslint-disable-next-line @typescript-eslint/no-non-null-assertion this.emit('connect', this.publicKey!); }); }); disconnect = jest.fn(async () => { this.connecting = false; this.connectedValue = false; act(() => { this.emit('disconnect'); }); }); sendTransaction = jest.fn(); supportedTransactionVersions = null; autoConnect = jest.fn(); } class FooWalletAdapter extends MockWalletAdapter { name = 'FooWallet' as WalletName<'FooWallet'>; url = 'https://foowallet.com'; icon = 'foo.png'; publicKey = new PublicKey('Foo11111111111111111111111111111111111111111'); } beforeEach(() => { localStorage.clear(); jest.clearAllMocks().resetModules(); jest.mocked(useConnection).mockImplementation(() => ({ connection: { rpcEndpoint: 'https://fake-endpoint-for-test.com', } as Connection, })); container = document.createElement('div'); document.body.appendChild(container); root = createRoot(container); ref = createRef(); fooWalletAdapter = new FooWalletAdapter(); adapters = [fooWalletAdapter]; }); afterEach(() => { if (root) { root.unmount(); } }); describe('given a selected wallet', () => { beforeEach(async () => { fooWalletAdapter.readyStateValue = WalletReadyState.NotDetected; renderTest({}); await act(async () => { ref.current?.getWalletContextState().select('FooWallet' as WalletName<'FooWallet'>); await Promise.resolve(); // Flush all promises in effects after calling `select()`. }); expect(ref.current?.getWalletContextState().wallet?.readyState).toBe(WalletReadyState.NotDetected); }); it('should store the wallet name', () => { expect(localStorage.setItem).toHaveBeenCalledWith( WALLET_NAME_CACHE_KEY, JSON.stringify(fooWalletAdapter.name) ); }); describe('when the wallet disconnects of its own accord', () => { beforeEach(() => { jest.clearAllMocks(); act(() => { fooWalletAdapter.disconnect(); }); }); it('should clear the stored wallet name', () => { expect(localStorage.removeItem).toHaveBeenCalledWith(WALLET_NAME_CACHE_KEY); }); }); describe('when the wallet disconnects as a consequence of the window unloading', () => { beforeEach(() => { jest.clearAllMocks(); act(() => { window.dispatchEvent(new Event('beforeunload')); fooWalletAdapter.disconnect(); }); }); it('should not clear the stored wallet name', () => { expect(localStorage.removeItem).not.toHaveBeenCalledWith(WALLET_NAME_CACHE_KEY); }); }); }); describe('when there is no mobile wallet adapter in the adapters array', () => { it("creates a new mobile wallet adapter with the document's host as the uri of the `appIdentity`", () => { renderTest({}); expect(jest.mocked(SolanaMobileWalletAdapter).mock.instances).toHaveLength(1); expect(jest.mocked(SolanaMobileWalletAdapter).mock.calls[0][0].appIdentity.uri).toBe( `${document.location.protocol}//${document.location.host}` ); }); it('creates a new mobile wallet adapter with the appropriate cluster for the given endpoint', () => { renderTest({}); expect(jest.mocked(SolanaMobileWalletAdapter).mock.instances).toHaveLength(1); expect(jest.mocked(SolanaMobileWalletAdapter).mock.calls[0][0].cluster).toBe('fake-cluster-for-test'); }); }); describe('when a custom mobile wallet adapter is supplied in the adapters array', () => { let customAdapter: Adapter; const CUSTOM_APP_IDENTITY = { uri: 'https://custom.com', }; const CUSTOM_CLUSTER = 'devnet'; beforeEach(() => { customAdapter = new SolanaMobileWalletAdapter({ addressSelector: jest.fn() as unknown as AddressSelector, appIdentity: CUSTOM_APP_IDENTITY, authorizationResultCache: jest.fn() as unknown as AuthorizationResultCache, cluster: CUSTOM_CLUSTER, onWalletNotFound: jest.fn(), }); adapters.push(customAdapter); jest.clearAllMocks(); }); it('loads the custom mobile wallet adapter into state as the default', () => { renderTest({}); expect(ref.current?.getWalletContextState().wallet?.adapter).toBe(customAdapter); }); it('does not construct any further mobile wallet adapters', () => { renderTest({}); expect(jest.mocked(SolanaMobileWalletAdapter).mock.calls.length).toBe(0); }); }); describe('when there exists no stored wallet name', () => { beforeEach(() => { localStorage.removeItem(WALLET_NAME_CACHE_KEY); }); it('loads the mobile wallet adapter into state as the default', () => { renderTest({}); expect(ref.current?.getWalletContextState().wallet?.adapter.name).toBe(SolanaMobileWalletAdapterWalletName); }); it('loads no public key into state', () => { renderTest({}); expect(ref.current?.getWalletContextState().publicKey).toBeNull(); }); }); describe('when there exists a stored wallet name', () => { beforeEach(() => { localStorage.setItem(WALLET_NAME_CACHE_KEY, JSON.stringify('FooWallet')); }); it('loads the corresponding adapter into state', () => { renderTest({}); expect(ref.current?.getWalletContextState().wallet?.adapter).toBeInstanceOf(FooWalletAdapter); }); it('loads the corresponding public key into state', () => { renderTest({}); expect(ref.current?.getWalletContextState().publicKey).toBe(fooWalletAdapter.publicKey); }); it('sets state tracking variables to defaults', () => { renderTest({}); expect(ref.current?.getWalletContextState()).toMatchObject({ connected: false, connecting: false, }); }); }); describe('autoConnect', () => { describe('given a mobile wallet adapter is connected', () => { beforeEach(async () => { renderTest({}); await act(async () => { ref.current?.getWalletContextState().select(SolanaMobileWalletAdapterWalletName); await Promise.resolve(); // Flush all promises in effects after calling `select()`. }); }); describe('when autoConnect is disabled', () => { beforeEach(() => { renderTest({ autoConnect: false }); }); it('does not call `connect`', () => { const adapter = ref.current?.getWalletContextState().wallet?.adapter as SolanaMobileWalletAdapter; expect(adapter.connect).not.toHaveBeenCalled(); expect(adapter.autoConnect).not.toHaveBeenCalled(); }); }); describe('when autoConnect is enabled', () => { beforeEach(() => { renderTest({ autoConnect: true }); }); it('calls the connect method on the mobile wallet adapter', () => { const adapter = ref.current?.getWalletContextState().wallet?.adapter as SolanaMobileWalletAdapter; expect(adapter.connect).toHaveBeenCalled(); expect(adapter.autoConnect).not.toHaveBeenCalled(); }); }); }); describe('given a non-mobile wallet adapter is connected', () => { beforeEach(async () => { renderTest({}); await act(async () => { ref.current?.getWalletContextState().select('FooWallet' as WalletName<'FooWallet'>); await Promise.resolve(); // Flush all promises in effects after calling `select()`. }); }); describe('when autoConnect is disabled', () => { beforeEach(() => { renderTest({ autoConnect: false }); }); it('does not call `autoConnect`', () => { // eslint-disable-next-line @typescript-eslint/no-non-null-assertion const adapter = ref.current!.getWalletContextState().wallet!.adapter; expect(adapter.connect).not.toHaveBeenCalled(); expect(adapter.autoConnect).not.toHaveBeenCalled(); }); }); describe('when autoConnect is enabled', () => { beforeEach(() => { renderTest({ autoConnect: true }); }); it('calls `connect`', () => { // eslint-disable-next-line @typescript-eslint/no-non-null-assertion const adapter = ref.current!.getWalletContextState().wallet!.adapter; expect(adapter.connect).toHaveBeenCalled(); expect(adapter.autoConnect).not.toHaveBeenCalled(); }); }); }); }); describe('onError', () => { let onError: jest.Mock; let errorThrown: WalletError; beforeEach(() => { errorThrown = new WalletError('o no'); onError = jest.fn(); renderTest({ onError }); }); describe('when the wallet emits an error', () => { let adapter: Adapter; beforeEach(() => { act(() => { adapter = ref.current?.getWalletContextState().wallet?.adapter as SolanaMobileWalletAdapter; adapter.emit('error', errorThrown); }); }); it('should fire the `onError` callback', () => { expect(onError).toHaveBeenCalledWith(errorThrown, adapter); }); }); describe('when window `beforeunload` event fires', () => { beforeEach(() => { act(() => { window.dispatchEvent(new Event('beforeunload')); }); }); describe('then the wallet emits an error', () => { let adapter: Adapter; beforeEach(() => { act(() => { adapter = ref.current?.getWalletContextState().wallet?.adapter as SolanaMobileWalletAdapter; adapter.emit('error', errorThrown); }); }); it('should fire the `onError` callback', () => { expect(onError).toHaveBeenCalledWith(errorThrown, adapter); }); }); }); }); describe('disconnect()', () => { describe('when there is already a wallet connected', () => { beforeEach(async () => { window.open = jest.fn(); renderTest({}); await act(async () => { ref.current?.getWalletContextState().select('FooWallet' as WalletName<'FooWallet'>); await Promise.resolve(); // Flush all promises in effects after calling `select()`. }); await act(() => { ref.current?.getWalletContextState().connect(); }); }); describe('and you select a different wallet', () => { beforeEach(async () => { await act(async () => { ref.current?.getWalletContextState().select('BarWallet' as WalletName<'BarWallet'>); await Promise.resolve(); // Flush all promises in effects after calling `select()`. }); }); it('should disconnect the old wallet', () => { expect(fooWalletAdapter.disconnect).toHaveBeenCalled(); }); }); describe('and you select the same wallet', () => { beforeEach(async () => { await act(async () => { ref.current?.getWalletContextState().select('FooWallet' as WalletName<'FooWallet'>); await Promise.resolve(); // Flush all promises in effects after calling `select()`. }); }); it('should not disconnect the old wallet', () => { expect(fooWalletAdapter.disconnect).not.toHaveBeenCalled(); }); }); describe('once disconnected', () => { beforeEach(async () => { jest.clearAllMocks(); ref.current?.getWalletContextState().disconnect(); await Promise.resolve(); // Flush all promises in effects after calling `disconnect()`. }); it('should clear the stored wallet name', () => { expect(localStorage.removeItem).toHaveBeenCalledWith(WALLET_NAME_CACHE_KEY); }); it('sets state tracking variables to defaults', () => { renderTest({}); expect(ref.current?.getWalletContextState()).toMatchObject({ connected: false, connecting: false, publicKey: null, }); }); }); }); describe('given a mobile wallet adapter is connected', () => { let mobileWalletAdapter: Adapter; beforeEach(async () => { renderTest({}); await act(async () => { ref.current?.getWalletContextState().select(SolanaMobileWalletAdapterWalletName); await Promise.resolve(); // Flush all promises in effects after calling `select()`. }); mobileWalletAdapter = jest.mocked(SolanaMobileWalletAdapter).mock.results[0].value; await act(() => { ref.current?.getWalletContextState().connect(); }); }); describe('then a non-mobile wallet adapter is selected', () => { beforeEach(async () => { renderTest({}); await act(async () => { ref.current?.getWalletContextState().select('FooWallet' as WalletName<'FooWallet'>); await Promise.resolve(); // Flush all promises in effects after calling `select()`. }); }); it('does not call `disconnect` on the mobile wallet adapter', () => { expect(mobileWalletAdapter.disconnect).not.toHaveBeenCalled(); }); it('should not clear the stored wallet name', () => { expect(localStorage.removeItem).not.toHaveBeenCalled(); }); }); describe('when the wallet disconnects of its own accord', () => { beforeEach(() => { jest.clearAllMocks(); act(() => { mobileWalletAdapter.disconnect(); }); }); it('should not clear the stored wallet name', () => { expect(localStorage.removeItem).not.toHaveBeenCalled(); }); }); describe('when window beforeunload event fires', () => { beforeEach(() => { jest.clearAllMocks(); act(() => { window.dispatchEvent(new Event('beforeunload')); }); }); describe('then the wallet disconnects of its own accord', () => { beforeEach(() => { jest.clearAllMocks(); act(() => { mobileWalletAdapter.disconnect(); }); }); it('should not clear the stored wallet name', () => { expect(localStorage.removeItem).not.toHaveBeenCalled(); }); it('should clear out the state', () => { expect(ref.current?.getWalletContextState()).toMatchObject({ connected: false, connecting: false, publicKey: null, }); }); }); }); }); }); });
0
solana_public_repos/anza-xyz/wallet-adapter/packages/core
solana_public_repos/anza-xyz/wallet-adapter/packages/core/base/LICENSE
Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 1. Definitions. "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and (b) You must cause any modified files to carry prominent notices stating that You changed the files; and (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. END OF TERMS AND CONDITIONS APPENDIX: How to apply the Apache License to your work. To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "[]" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives. Copyright [yyyy] [name of copyright owner] 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.
0
solana_public_repos/anza-xyz/wallet-adapter/packages/core
solana_public_repos/anza-xyz/wallet-adapter/packages/core/base/tsconfig.esm.json
{ "extends": "../../../tsconfig.esm.json", "include": ["src"], "compilerOptions": { "outDir": "lib/esm", "declarationDir": "lib/types" } }
0
solana_public_repos/anza-xyz/wallet-adapter/packages/core
solana_public_repos/anza-xyz/wallet-adapter/packages/core/base/package.json
{ "name": "@solana/wallet-adapter-base", "version": "0.9.23", "author": "Solana Maintainers <maintainers@solana.foundation>", "repository": "https://github.com/anza-xyz/wallet-adapter", "license": "Apache-2.0", "publishConfig": { "access": "public" }, "files": [ "lib", "src", "LICENSE" ], "engines": { "node": ">=18" }, "type": "module", "sideEffects": false, "main": "./lib/cjs/index.js", "module": "./lib/esm/index.js", "types": "./lib/types/index.d.ts", "exports": { "require": "./lib/cjs/index.js", "import": "./lib/esm/index.js", "types": "./lib/types/index.d.ts" }, "scripts": { "build": "tsc --build --verbose && pnpm run package", "clean": "shx mkdir -p lib && shx rm -rf lib", "lint": "prettier --check 'src/{*,**/*}.{ts,tsx,js,jsx,json}' && eslint", "package": "shx mkdir -p lib/cjs && shx echo '{ \"type\": \"commonjs\" }' > lib/cjs/package.json" }, "peerDependencies": { "@solana/web3.js": "^1.77.3" }, "dependencies": { "@solana/wallet-standard-features": "^1.1.0", "@wallet-standard/base": "^1.0.1", "@wallet-standard/features": "^1.0.3", "eventemitter3": "^4.0.7" }, "devDependencies": { "@solana/web3.js": "^1.77.3", "@types/node-fetch": "^2.6.4", "shx": "^0.3.4" } }
0
solana_public_repos/anza-xyz/wallet-adapter/packages/core
solana_public_repos/anza-xyz/wallet-adapter/packages/core/base/tsconfig.cjs.json
{ "extends": "../../../tsconfig.cjs.json", "include": ["src"], "compilerOptions": { "outDir": "lib/cjs" } }
0
solana_public_repos/anza-xyz/wallet-adapter/packages/core
solana_public_repos/anza-xyz/wallet-adapter/packages/core/base/tsconfig.json
{ "extends": "../../../tsconfig.root.json", "references": [ { "path": "./tsconfig.cjs.json" }, { "path": "./tsconfig.esm.json" } ] }
0
solana_public_repos/anza-xyz/wallet-adapter/packages/core/base
solana_public_repos/anza-xyz/wallet-adapter/packages/core/base/src/signer.ts
import type { SolanaSignInInput, SolanaSignInOutput } from '@solana/wallet-standard-features'; import type { Connection, TransactionSignature } from '@solana/web3.js'; import { BaseWalletAdapter, type SendTransactionOptions, type WalletAdapter, type WalletAdapterProps, } from './adapter.js'; import { WalletSendTransactionError, WalletSignTransactionError } from './errors.js'; import { isVersionedTransaction, type TransactionOrVersionedTransaction } from './transaction.js'; export interface SignerWalletAdapterProps<Name extends string = string> extends WalletAdapterProps<Name> { signTransaction<T extends TransactionOrVersionedTransaction<this['supportedTransactionVersions']>>( transaction: T ): Promise<T>; signAllTransactions<T extends TransactionOrVersionedTransaction<this['supportedTransactionVersions']>>( transactions: T[] ): Promise<T[]>; } export type SignerWalletAdapter<Name extends string = string> = WalletAdapter<Name> & SignerWalletAdapterProps<Name>; export abstract class BaseSignerWalletAdapter<Name extends string = string> extends BaseWalletAdapter<Name> implements SignerWalletAdapter<Name> { async sendTransaction( transaction: TransactionOrVersionedTransaction<this['supportedTransactionVersions']>, connection: Connection, options: SendTransactionOptions = {} ): Promise<TransactionSignature> { let emit = true; try { if (isVersionedTransaction(transaction)) { if (!this.supportedTransactionVersions) throw new WalletSendTransactionError( `Sending versioned transactions isn't supported by this wallet` ); if (!this.supportedTransactionVersions.has(transaction.version)) throw new WalletSendTransactionError( `Sending transaction version ${transaction.version} isn't supported by this wallet` ); try { transaction = await this.signTransaction(transaction); const rawTransaction = transaction.serialize(); return await connection.sendRawTransaction(rawTransaction, options); } catch (error: any) { // If the error was thrown by `signTransaction`, rethrow it and don't emit a duplicate event if (error instanceof WalletSignTransactionError) { emit = false; throw error; } throw new WalletSendTransactionError(error?.message, error); } } else { try { const { signers, ...sendOptions } = options; transaction = await this.prepareTransaction(transaction, connection, sendOptions); signers?.length && transaction.partialSign(...signers); transaction = await this.signTransaction(transaction); const rawTransaction = transaction.serialize(); return await connection.sendRawTransaction(rawTransaction, sendOptions); } catch (error: any) { // If the error was thrown by `signTransaction`, rethrow it and don't emit a duplicate event if (error instanceof WalletSignTransactionError) { emit = false; throw error; } throw new WalletSendTransactionError(error?.message, error); } } } catch (error: any) { if (emit) { this.emit('error', error); } throw error; } } abstract signTransaction<T extends TransactionOrVersionedTransaction<this['supportedTransactionVersions']>>( transaction: T ): Promise<T>; async signAllTransactions<T extends TransactionOrVersionedTransaction<this['supportedTransactionVersions']>>( transactions: T[] ): Promise<T[]> { for (const transaction of transactions) { if (isVersionedTransaction(transaction)) { if (!this.supportedTransactionVersions) throw new WalletSignTransactionError( `Signing versioned transactions isn't supported by this wallet` ); if (!this.supportedTransactionVersions.has(transaction.version)) throw new WalletSignTransactionError( `Signing transaction version ${transaction.version} isn't supported by this wallet` ); } } const signedTransactions: T[] = []; for (const transaction of transactions) { signedTransactions.push(await this.signTransaction(transaction)); } return signedTransactions; } } export interface MessageSignerWalletAdapterProps<Name extends string = string> extends WalletAdapterProps<Name> { signMessage(message: Uint8Array): Promise<Uint8Array>; } export type MessageSignerWalletAdapter<Name extends string = string> = WalletAdapter<Name> & MessageSignerWalletAdapterProps<Name>; export abstract class BaseMessageSignerWalletAdapter<Name extends string = string> extends BaseSignerWalletAdapter<Name> implements MessageSignerWalletAdapter<Name> { abstract signMessage(message: Uint8Array): Promise<Uint8Array>; } export interface SignInMessageSignerWalletAdapterProps<Name extends string = string> extends WalletAdapterProps<Name> { signIn(input?: SolanaSignInInput): Promise<SolanaSignInOutput>; } export type SignInMessageSignerWalletAdapter<Name extends string = string> = WalletAdapter<Name> & SignInMessageSignerWalletAdapterProps<Name>; export abstract class BaseSignInMessageSignerWalletAdapter<Name extends string = string> extends BaseMessageSignerWalletAdapter<Name> implements SignInMessageSignerWalletAdapter<Name> { abstract signIn(input?: SolanaSignInInput): Promise<SolanaSignInOutput>; }
0
solana_public_repos/anza-xyz/wallet-adapter/packages/core/base
solana_public_repos/anza-xyz/wallet-adapter/packages/core/base/src/errors.ts
export class WalletError extends Error { error: any; // eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types constructor(message?: string, error?: any) { super(message); this.error = error; } } export class WalletNotReadyError extends WalletError { name = 'WalletNotReadyError'; } export class WalletLoadError extends WalletError { name = 'WalletLoadError'; } export class WalletConfigError extends WalletError { name = 'WalletConfigError'; } export class WalletConnectionError extends WalletError { name = 'WalletConnectionError'; } export class WalletDisconnectedError extends WalletError { name = 'WalletDisconnectedError'; } export class WalletDisconnectionError extends WalletError { name = 'WalletDisconnectionError'; } export class WalletAccountError extends WalletError { name = 'WalletAccountError'; } export class WalletPublicKeyError extends WalletError { name = 'WalletPublicKeyError'; } export class WalletKeypairError extends WalletError { name = 'WalletKeypairError'; } export class WalletNotConnectedError extends WalletError { name = 'WalletNotConnectedError'; } export class WalletSendTransactionError extends WalletError { name = 'WalletSendTransactionError'; } export class WalletSignTransactionError extends WalletError { name = 'WalletSignTransactionError'; } export class WalletSignMessageError extends WalletError { name = 'WalletSignMessageError'; } export class WalletSignInError extends WalletError { name = 'WalletSignInError'; } export class WalletTimeoutError extends WalletError { name = 'WalletTimeoutError'; } export class WalletWindowBlockedError extends WalletError { name = 'WalletWindowBlockedError'; } export class WalletWindowClosedError extends WalletError { name = 'WalletWindowClosedError'; }
0
solana_public_repos/anza-xyz/wallet-adapter/packages/core/base
solana_public_repos/anza-xyz/wallet-adapter/packages/core/base/src/types.ts
import type { WalletAdapter } from './adapter.js'; import type { MessageSignerWalletAdapter, SignerWalletAdapter, SignInMessageSignerWalletAdapter } from './signer.js'; import type { StandardWalletAdapter } from './standard.js'; export type Adapter = | WalletAdapter | SignerWalletAdapter | MessageSignerWalletAdapter | SignInMessageSignerWalletAdapter | StandardWalletAdapter; export enum WalletAdapterNetwork { Mainnet = 'mainnet-beta', Testnet = 'testnet', Devnet = 'devnet', }
0
solana_public_repos/anza-xyz/wallet-adapter/packages/core/base
solana_public_repos/anza-xyz/wallet-adapter/packages/core/base/src/standard.ts
import { SolanaSignAndSendTransaction, type SolanaSignAndSendTransactionFeature, type SolanaSignInFeature, type SolanaSignMessageFeature, SolanaSignTransaction, type SolanaSignTransactionFeature, } from '@solana/wallet-standard-features'; import type { Wallet as StandardWallet, WalletWithFeatures as StandardWalletWithFeatures } from '@wallet-standard/base'; import { StandardConnect, type StandardConnectFeature, type StandardDisconnectFeature, StandardEvents, type StandardEventsFeature, } from '@wallet-standard/features'; import type { WalletAdapter, WalletAdapterProps } from './adapter.js'; export type WalletAdapterCompatibleStandardWallet = StandardWalletWithFeatures< StandardConnectFeature & StandardEventsFeature & (SolanaSignAndSendTransactionFeature | SolanaSignTransactionFeature) & (StandardDisconnectFeature | SolanaSignMessageFeature | SolanaSignInFeature | object) >; export interface StandardWalletAdapterProps<Name extends string = string> extends WalletAdapterProps<Name> { wallet: WalletAdapterCompatibleStandardWallet; standard: true; } export type StandardWalletAdapter<Name extends string = string> = WalletAdapter<Name> & StandardWalletAdapterProps<Name>; export function isWalletAdapterCompatibleStandardWallet( wallet: StandardWallet ): wallet is WalletAdapterCompatibleStandardWallet { return ( StandardConnect in wallet.features && StandardEvents in wallet.features && (SolanaSignAndSendTransaction in wallet.features || SolanaSignTransaction in wallet.features) ); }
0
solana_public_repos/anza-xyz/wallet-adapter/packages/core/base
solana_public_repos/anza-xyz/wallet-adapter/packages/core/base/src/adapter.ts
import type { Connection, PublicKey, SendOptions, Signer, Transaction, TransactionSignature } from '@solana/web3.js'; import EventEmitter from 'eventemitter3'; import { type WalletError, WalletNotConnectedError } from './errors.js'; import type { SupportedTransactionVersions, TransactionOrVersionedTransaction } from './transaction.js'; export { EventEmitter }; export interface WalletAdapterEvents { connect(publicKey: PublicKey): void; disconnect(): void; error(error: WalletError): void; readyStateChange(readyState: WalletReadyState): void; } export interface SendTransactionOptions extends SendOptions { signers?: Signer[]; } // WalletName is a nominal type that wallet adapters should use, e.g. `'MyCryptoWallet' as WalletName<'MyCryptoWallet'>` // https://medium.com/@KevinBGreene/surviving-the-typescript-ecosystem-branding-and-type-tagging-6cf6e516523d export type WalletName<T extends string = string> = T & { __brand__: 'WalletName' }; export interface WalletAdapterProps<Name extends string = string> { name: WalletName<Name>; url: string; icon: string; readyState: WalletReadyState; publicKey: PublicKey | null; connecting: boolean; connected: boolean; supportedTransactionVersions?: SupportedTransactionVersions; autoConnect(): Promise<void>; connect(): Promise<void>; disconnect(): Promise<void>; sendTransaction( transaction: TransactionOrVersionedTransaction<this['supportedTransactionVersions']>, connection: Connection, options?: SendTransactionOptions ): Promise<TransactionSignature>; } export type WalletAdapter<Name extends string = string> = WalletAdapterProps<Name> & EventEmitter<WalletAdapterEvents>; /** * A wallet's readiness describes a series of states that the wallet can be in, * depending on what kind of wallet it is. An installable wallet (eg. a browser * extension like Phantom) might be `Installed` if we've found the Phantom API * in the global scope, or `NotDetected` otherwise. A loadable, zero-install * runtime (eg. Torus Wallet) might simply signal that it's `Loadable`. Use this * metadata to personalize the wallet list for each user (eg. to show their * installed wallets first). */ export enum WalletReadyState { /** * User-installable wallets can typically be detected by scanning for an API * that they've injected into the global context. If such an API is present, * we consider the wallet to have been installed. */ Installed = 'Installed', NotDetected = 'NotDetected', /** * Loadable wallets are always available to you. Since you can load them at * any time, it's meaningless to say that they have been detected. */ Loadable = 'Loadable', /** * If a wallet is not supported on a given platform (eg. server-rendering, or * mobile) then it will stay in the `Unsupported` state. */ Unsupported = 'Unsupported', } export abstract class BaseWalletAdapter<Name extends string = string> extends EventEmitter<WalletAdapterEvents> implements WalletAdapter<Name> { abstract name: WalletName<Name>; abstract url: string; abstract icon: string; abstract readyState: WalletReadyState; abstract publicKey: PublicKey | null; abstract connecting: boolean; abstract supportedTransactionVersions?: SupportedTransactionVersions; get connected() { return !!this.publicKey; } async autoConnect() { await this.connect(); } abstract connect(): Promise<void>; abstract disconnect(): Promise<void>; abstract sendTransaction( transaction: TransactionOrVersionedTransaction<this['supportedTransactionVersions']>, connection: Connection, options?: SendTransactionOptions ): Promise<TransactionSignature>; protected async prepareTransaction( transaction: Transaction, connection: Connection, options: SendOptions = {} ): Promise<Transaction> { const publicKey = this.publicKey; if (!publicKey) throw new WalletNotConnectedError(); transaction.feePayer = transaction.feePayer || publicKey; transaction.recentBlockhash = transaction.recentBlockhash || ( await connection.getLatestBlockhash({ commitment: options.preflightCommitment, minContextSlot: options.minContextSlot, }) ).blockhash; return transaction; } } export function scopePollingDetectionStrategy(detect: () => boolean): void { // Early return when server-side rendering if (typeof window === 'undefined' || typeof document === 'undefined') return; const disposers: (() => void)[] = []; function detectAndDispose() { const detected = detect(); if (detected) { for (const dispose of disposers) { dispose(); } } } // Strategy #1: Try detecting every second. const interval = // TODO: #334 Replace with idle callback strategy. setInterval(detectAndDispose, 1000); disposers.push(() => clearInterval(interval)); // Strategy #2: Detect as soon as the DOM becomes 'ready'/'interactive'. if ( // Implies that `DOMContentLoaded` has not yet fired. document.readyState === 'loading' ) { document.addEventListener('DOMContentLoaded', detectAndDispose, { once: true }); disposers.push(() => document.removeEventListener('DOMContentLoaded', detectAndDispose)); } // Strategy #3: Detect after the `window` has fully loaded. if ( // If the `complete` state has been reached, we're too late. document.readyState !== 'complete' ) { window.addEventListener('load', detectAndDispose, { once: true }); disposers.push(() => window.removeEventListener('load', detectAndDispose)); } // Strategy #4: Detect synchronously, now. detectAndDispose(); } /** * Users on iOS can be redirected into a wallet's in-app browser automatically, * if that wallet has a universal link configured to do so * But should not be redirected from within a webview, eg. if they're already * inside a wallet's browser * This function can be used to identify users who are on iOS and can be redirected * * @returns true if the user can be redirected */ export function isIosAndRedirectable() { // SSR: return false if (!navigator) return false; const userAgent = navigator.userAgent.toLowerCase(); // if on iOS the user agent will contain either iPhone or iPad // caveat: if requesting desktop site then this won't work const isIos = userAgent.includes('iphone') || userAgent.includes('ipad'); // if in a webview then it will not include Safari // note that other iOS browsers also include Safari // so we will redirect only if Safari is also included const isSafari = userAgent.includes('safari'); return isIos && isSafari; }
0
solana_public_repos/anza-xyz/wallet-adapter/packages/core/base
solana_public_repos/anza-xyz/wallet-adapter/packages/core/base/src/transaction.ts
import type { Transaction, TransactionVersion, VersionedTransaction } from '@solana/web3.js'; export type SupportedTransactionVersions = ReadonlySet<TransactionVersion> | null | undefined; export type TransactionOrVersionedTransaction<S extends SupportedTransactionVersions> = S extends null | undefined ? Transaction : Transaction | VersionedTransaction; export function isVersionedTransaction( transaction: Transaction | VersionedTransaction ): transaction is VersionedTransaction { return 'version' in transaction; }
0
solana_public_repos/anza-xyz/wallet-adapter/packages/core/base
solana_public_repos/anza-xyz/wallet-adapter/packages/core/base/src/index.ts
export * from './adapter.js'; export * from './errors.js'; export * from './signer.js'; export * from './standard.js'; export * from './transaction.js'; export * from './types.js';
0
solana_public_repos/anza-xyz/wallet-adapter/packages/starter
solana_public_repos/anza-xyz/wallet-adapter/packages/starter/material-ui-starter/LICENSE
Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 1. Definitions. "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and (b) You must cause any modified files to carry prominent notices stating that You changed the files; and (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. END OF TERMS AND CONDITIONS APPENDIX: How to apply the Apache License to your work. To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "[]" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives. Copyright [yyyy] [name of copyright owner] 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.
0
solana_public_repos/anza-xyz/wallet-adapter/packages/starter
solana_public_repos/anza-xyz/wallet-adapter/packages/starter/material-ui-starter/.prettierignore
/.parcel-cache /dist /lib /node_modules
0
solana_public_repos/anza-xyz/wallet-adapter/packages/starter
solana_public_repos/anza-xyz/wallet-adapter/packages/starter/material-ui-starter/.editorconfig
root = true [*] charset = utf-8 indent_style = space indent_size = 4 end_of_line = lf insert_final_newline = true trim_trailing_whitespace = true
0
solana_public_repos/anza-xyz/wallet-adapter/packages/starter
solana_public_repos/anza-xyz/wallet-adapter/packages/starter/material-ui-starter/package.json
{ "name": "@solana/wallet-adapter-material-ui-starter", "version": "0.13.32", "author": "Solana Maintainers <maintainers@solana.foundation>", "repository": "https://github.com/anza-xyz/wallet-adapter", "license": "Apache-2.0", "publishConfig": { "access": "public" }, "files": [ "src", ".editorconfig", ".env", ".gitignore", ".prettierignore", ".prettierrc", "LICENSE", "package.json", "tsconfig.json" ], "scripts": { "build": "tsc --build --verbose && parcel build src/index.html", "clean": "shx mkdir -p .parcel-cache dist lib && shx rm -rf .parcel-cache dist lib", "lint": "prettier --check 'src/{*,**/*}.{ts,tsx,js,jsx,json}' && eslint", "start": "parcel src/index.html" }, "dependencies": { "@emotion/react": "^11.11.1", "@emotion/styled": "^11.11.0", "@mui/icons-material": "^5.11.16", "@mui/material": "^5.13.5", "@solana/wallet-adapter-base": "workspace:^", "@solana/wallet-adapter-material-ui": "workspace:^", "@solana/wallet-adapter-react": "workspace:^", "@solana/wallet-adapter-wallets": "workspace:^", "@solana/web3.js": "^1.77.3", "notistack": "^3.0.1", "react": "^18.2.0", "react-dom": "^18.2.0" }, "devDependencies": { "@types/react": "^18.2.13", "@types/react-dom": "^18.2.6", "parcel": "^2.9.2", "prettier": "^2.8.8", "process": "^0.11.10", "shx": "^0.3.4", "typescript": "~4.7.4" } }
0
solana_public_repos/anza-xyz/wallet-adapter/packages/starter
solana_public_repos/anza-xyz/wallet-adapter/packages/starter/material-ui-starter/.prettierrc
{ "printWidth": 120, "trailingComma": "es5", "tabWidth": 4, "semi": true, "singleQuote": true }
0
solana_public_repos/anza-xyz/wallet-adapter/packages/starter
solana_public_repos/anza-xyz/wallet-adapter/packages/starter/material-ui-starter/tsconfig.json
{ "extends": "../../../tsconfig.root.json", "include": ["src"], "compilerOptions": { "outDir": "lib", "noEmit": true, "target": "esnext", "module": "esnext", "moduleResolution": "node", "jsx": "react", "strict": true, "esModuleInterop": true, "resolveJsonModule": true, "isolatedModules": true } }
0
solana_public_repos/anza-xyz/wallet-adapter/packages/starter/material-ui-starter
solana_public_repos/anza-xyz/wallet-adapter/packages/starter/material-ui-starter/src/index.tsx
import React, { StrictMode } from 'react'; import { createRoot } from 'react-dom/client'; import { App } from './App'; // eslint-disable-next-line @typescript-eslint/no-non-null-assertion createRoot(document.getElementById('app')!).render( <StrictMode> <App /> </StrictMode> );
0
solana_public_repos/anza-xyz/wallet-adapter/packages/starter/material-ui-starter
solana_public_repos/anza-xyz/wallet-adapter/packages/starter/material-ui-starter/src/App.tsx
import type { Adapter, WalletError } from '@solana/wallet-adapter-base'; import { WalletAdapterNetwork } from '@solana/wallet-adapter-base'; import { WalletDialogProvider, WalletMultiButton } from '@solana/wallet-adapter-material-ui'; import { ConnectionProvider, WalletProvider } from '@solana/wallet-adapter-react'; import { UnsafeBurnerWalletAdapter } from '@solana/wallet-adapter-wallets'; import { clusterApiUrl } from '@solana/web3.js'; import { useSnackbar } from 'notistack'; import type { FC, ReactNode } from 'react'; import React, { useCallback, useMemo } from 'react'; import { Theme } from './Theme'; export const App: FC = () => { return ( <Theme> <Context> <Content /> </Context> </Theme> ); }; const Context: FC<{ children: ReactNode }> = ({ children }) => { // The network can be set to 'devnet', 'testnet', or 'mainnet-beta'. const network = WalletAdapterNetwork.Devnet; // You can also provide a custom RPC endpoint. const endpoint = useMemo(() => clusterApiUrl(network), [network]); const wallets = useMemo( () => [ /** * Wallets that implement either of these standards will be available automatically. * * - Solana Mobile Stack Mobile Wallet Adapter Protocol * (https://github.com/solana-mobile/mobile-wallet-adapter) * - Solana Wallet Standard * (https://github.com/solana-labs/wallet-standard) * * If you wish to support a wallet that supports neither of those standards, * instantiate its legacy wallet adapter here. Common legacy adapters can be found * in the npm package `@solana/wallet-adapter-wallets`. */ new UnsafeBurnerWalletAdapter(), ], // eslint-disable-next-line react-hooks/exhaustive-deps [network] ); const { enqueueSnackbar } = useSnackbar(); const onError = useCallback( (error: WalletError, adapter?: Adapter) => { enqueueSnackbar(error.message ? `${error.name}: ${error.message}` : error.name, { variant: 'error' }); console.error(error, adapter); }, [enqueueSnackbar] ); return ( <ConnectionProvider endpoint={endpoint}> <WalletProvider wallets={wallets} onError={onError} autoConnect> <WalletDialogProvider>{children}</WalletDialogProvider> </WalletProvider> </ConnectionProvider> ); }; const Content: FC = () => { return <WalletMultiButton />; };
0
solana_public_repos/anza-xyz/wallet-adapter/packages/starter/material-ui-starter
solana_public_repos/anza-xyz/wallet-adapter/packages/starter/material-ui-starter/src/index.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>WalletAdapter Starter</title> <link rel="stylesheet" href="index.css" /> </head> <body> <div id="app"></div> <script type="module" src="index.tsx"></script> </body> </html>
0
solana_public_repos/anza-xyz/wallet-adapter/packages/starter/material-ui-starter
solana_public_repos/anza-xyz/wallet-adapter/packages/starter/material-ui-starter/src/reset.css
/* Box sizing rules */ *, *::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 with a list role, which suggests default styling will be removed */ ul[role='list'], ol[role='list'] { list-style: none; } /* 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; } /* 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; } }
0
solana_public_repos/anza-xyz/wallet-adapter/packages/starter/material-ui-starter
solana_public_repos/anza-xyz/wallet-adapter/packages/starter/material-ui-starter/src/index.css
@import './reset.css'; html, body { background-color: #303030; color: #FFFFFF; } #app { min-height: 100vh; display: flex; justify-content: center; align-items: center; }
0
solana_public_repos/anza-xyz/wallet-adapter/packages/starter/material-ui-starter
solana_public_repos/anza-xyz/wallet-adapter/packages/starter/material-ui-starter/src/Theme.tsx
import { createTheme, StyledEngineProvider, ThemeProvider } from '@mui/material'; import { deepPurple } from '@mui/material/colors'; import { SnackbarProvider } from 'notistack'; import type { FC, ReactNode } from 'react'; import React from 'react'; const theme = createTheme({ palette: { mode: 'dark', primary: { main: deepPurple[700], }, }, components: { MuiButtonBase: { styleOverrides: { root: { justifyContent: 'flex-start', }, }, }, MuiButton: { styleOverrides: { root: { textTransform: 'none', padding: '12px 16px', }, startIcon: { marginRight: 8, }, endIcon: { marginLeft: 8, }, }, }, }, }); export const Theme: FC<{ children: ReactNode }> = ({ children }) => { return ( <StyledEngineProvider injectFirst> <ThemeProvider theme={theme}> <SnackbarProvider>{children}</SnackbarProvider> </ThemeProvider> </StyledEngineProvider> ); };
0
solana_public_repos/anza-xyz/wallet-adapter/packages/starter
solana_public_repos/anza-xyz/wallet-adapter/packages/starter/create-react-app-starter/LICENSE
Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 1. Definitions. "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and (b) You must cause any modified files to carry prominent notices stating that You changed the files; and (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. END OF TERMS AND CONDITIONS APPENDIX: How to apply the Apache License to your work. To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "[]" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives. Copyright [yyyy] [name of copyright owner] 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.
0
solana_public_repos/anza-xyz/wallet-adapter/packages/starter
solana_public_repos/anza-xyz/wallet-adapter/packages/starter/create-react-app-starter/.prettierignore
/build /lib /node_modules
0
solana_public_repos/anza-xyz/wallet-adapter/packages/starter
solana_public_repos/anza-xyz/wallet-adapter/packages/starter/create-react-app-starter/.editorconfig
root = true [*] charset = utf-8 indent_style = space indent_size = 4 end_of_line = lf insert_final_newline = true trim_trailing_whitespace = true
0
solana_public_repos/anza-xyz/wallet-adapter/packages/starter
solana_public_repos/anza-xyz/wallet-adapter/packages/starter/create-react-app-starter/package.json
{ "name": "@solana/wallet-adapter-create-react-app-starter", "version": "0.1.30", "author": "Solana Maintainers <maintainers@solana.foundation>", "repository": "https://github.com/anza-xyz/wallet-adapter", "license": "Apache-2.0", "publishConfig": { "access": "public" }, "files": [ "public", "src", ".gitignore", "config-overrides.js", "LICENSE", "package.json", "README.md", "tsconfig.json" ], "scripts": { "build": "tsc --build --verbose && react-app-rewired build", "clean": "shx mkdir -p build lib && shx rm -rf build lib", "lint": "prettier --check 'src/{*,**/*}.{ts,tsx,js,jsx,json}' && eslint", "start": "react-app-rewired start", "test": "CI=true react-app-rewired test --passWithNoTests", "test:watch": "react-app-rewired test --passWithNoTests", "eject": "react-scripts eject" }, "dependencies": { "@solana/wallet-adapter-base": "workspace:^", "@solana/wallet-adapter-react": "workspace:^", "@solana/wallet-adapter-react-ui": "workspace:^", "@solana/wallet-adapter-wallets": "workspace:^", "@solana/web3.js": "^1.77.3", "react": "^18.2.0", "react-app-rewired": "^2.2.1", "react-dom": "^18.2.0", "react-scripts": "5.0.1", "web-vitals": "^2.1.4" }, "devDependencies": { "@testing-library/jest-dom": "^5.16.5", "@testing-library/react": "^13.4.0", "@testing-library/user-event": "^14.4.3", "@types/jest": "^28.1.8", "@types/react": "^18.2.13", "@types/react-dom": "^18.2.6", "@types/testing-library__jest-dom": "^5.14.6", "browserify-zlib": "^0.2.0", "crypto-browserify": "^3.12.0", "https-browserify": "^1.0.0", "process": "^0.11.10", "shx": "^0.3.4", "source-map-loader": "^4.0.1", "stream-browserify": "^3.0.0", "stream-http": "^3.2.0", "typescript": "~4.7.4", "url": "^0.11.1", "webpack": "^5.88.0" }, "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" ] } }
0
solana_public_repos/anza-xyz/wallet-adapter/packages/starter
solana_public_repos/anza-xyz/wallet-adapter/packages/starter/create-react-app-starter/.prettierrc
{ "printWidth": 120, "trailingComma": "es5", "tabWidth": 4, "semi": true, "singleQuote": true }
0
solana_public_repos/anza-xyz/wallet-adapter/packages/starter
solana_public_repos/anza-xyz/wallet-adapter/packages/starter/create-react-app-starter/config-overrides.js
const { ProvidePlugin } = require('webpack'); module.exports = function (config, env) { return { ...config, module: { ...config.module, rules: [ ...config.module.rules, { test: /\.m?[jt]sx?$/, enforce: 'pre', use: ['source-map-loader'], }, { test: /\.m?[jt]sx?$/, resolve: { fullySpecified: false, }, }, ], }, plugins: [ ...config.plugins, new ProvidePlugin({ process: 'process/browser', }), ], resolve: { ...config.resolve, fallback: { assert: require.resolve('assert'), buffer: require.resolve('buffer'), crypto: require.resolve('crypto-browserify'), http: require.resolve('stream-http'), https: require.resolve('https-browserify'), stream: require.resolve('stream-browserify'), url: require.resolve('url/'), zlib: require.resolve('browserify-zlib'), }, }, ignoreWarnings: [/Failed to parse source map/], }; };
0
solana_public_repos/anza-xyz/wallet-adapter/packages/starter
solana_public_repos/anza-xyz/wallet-adapter/packages/starter/create-react-app-starter/tsconfig.json
{ "extends": "../../../tsconfig.root.json", "include": ["src"], "compilerOptions": { "outDir": "lib", "target": "es5", "lib": ["dom", "dom.iterable", "esnext"], "allowJs": true, "skipLibCheck": true, "esModuleInterop": true, "allowSyntheticDefaultImports": true, "strict": true, "forceConsistentCasingInFileNames": true, "noFallthroughCasesInSwitch": true, "module": "esnext", "moduleResolution": "node", "resolveJsonModule": true, "isolatedModules": true, "noEmit": true, "jsx": "react-jsx" } }
0
solana_public_repos/anza-xyz/wallet-adapter/packages/starter/create-react-app-starter
solana_public_repos/anza-xyz/wallet-adapter/packages/starter/create-react-app-starter/public/index.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8" /> <link rel="icon" href="%PUBLIC_URL%/favicon.ico" /> <meta name="viewport" content="width=device-width, initial-scale=1" /> <meta name="theme-color" content="#000000" /> <meta name="description" content="Web site created using create-react-app" /> <link rel="apple-touch-icon" href="%PUBLIC_URL%/logo192.png" /> <!-- manifest.json provides metadata used when your web app is installed on a user's mobile device or desktop. See https://developers.google.com/web/fundamentals/web-app-manifest/ --> <link rel="manifest" href="%PUBLIC_URL%/manifest.json" /> <!-- Notice the use of %PUBLIC_URL% in the tags above. It will be replaced with the URL of the `public` folder during the build. Only files inside the `public` folder can be referenced from the HTML. Unlike "/favicon.ico" or "favicon.ico", "%PUBLIC_URL%/favicon.ico" will work correctly both with client-side routing and a non-root public URL. Learn how to configure a non-root public URL by running `npm run build`. --> <title>React App</title> </head> <body> <noscript>You need to enable JavaScript to run this app.</noscript> <div id="root"></div> <!-- This HTML file is a template. If you open it directly in the browser, you will see an empty page. You can add webfonts, meta tags, or analytics to this file. The build step will place the bundled scripts into the <body> tag. To begin the development, run `npm start` or `yarn start`. To create a production bundle, use `npm run build` or `yarn build`. --> </body> </html>
0
solana_public_repos/anza-xyz/wallet-adapter/packages/starter/create-react-app-starter
solana_public_repos/anza-xyz/wallet-adapter/packages/starter/create-react-app-starter/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" }
0
solana_public_repos/anza-xyz/wallet-adapter/packages/starter/create-react-app-starter
solana_public_repos/anza-xyz/wallet-adapter/packages/starter/create-react-app-starter/public/robots.txt
# https://www.robotstxt.org/robotstxt.html User-agent: * Disallow:
0
solana_public_repos/anza-xyz/wallet-adapter/packages/starter/create-react-app-starter
solana_public_repos/anza-xyz/wallet-adapter/packages/starter/create-react-app-starter/src/index.tsx
import React from 'react'; import ReactDOM from 'react-dom'; import App from './App'; import './index.css'; import reportWebVitals from './reportWebVitals'; ReactDOM.render( <React.StrictMode> <App /> </React.StrictMode>, document.getElementById('root') ); // 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();
0
solana_public_repos/anza-xyz/wallet-adapter/packages/starter/create-react-app-starter
solana_public_repos/anza-xyz/wallet-adapter/packages/starter/create-react-app-starter/src/App.tsx
import { WalletAdapterNetwork } from '@solana/wallet-adapter-base'; import { ConnectionProvider, WalletProvider } from '@solana/wallet-adapter-react'; import { WalletModalProvider, WalletMultiButton } from '@solana/wallet-adapter-react-ui'; import { UnsafeBurnerWalletAdapter } from '@solana/wallet-adapter-wallets'; import { clusterApiUrl } from '@solana/web3.js'; import React, { FC, ReactNode, useMemo } from 'react'; require('./App.css'); require('@solana/wallet-adapter-react-ui/styles.css'); const App: FC = () => { return ( <Context> <Content /> </Context> ); }; export default App; const Context: FC<{ children: ReactNode }> = ({ children }) => { // The network can be set to 'devnet', 'testnet', or 'mainnet-beta'. const network = WalletAdapterNetwork.Devnet; // You can also provide a custom RPC endpoint. const endpoint = useMemo(() => clusterApiUrl(network), [network]); const wallets = useMemo( () => [ /** * Wallets that implement either of these standards will be available automatically. * * - Solana Mobile Stack Mobile Wallet Adapter Protocol * (https://github.com/solana-mobile/mobile-wallet-adapter) * - Solana Wallet Standard * (https://github.com/solana-labs/wallet-standard) * * If you wish to support a wallet that supports neither of those standards, * instantiate its legacy wallet adapter here. Common legacy adapters can be found * in the npm package `@solana/wallet-adapter-wallets`. */ new UnsafeBurnerWalletAdapter(), ], // eslint-disable-next-line react-hooks/exhaustive-deps [network] ); return ( <ConnectionProvider endpoint={endpoint}> <WalletProvider wallets={wallets} autoConnect> <WalletModalProvider>{children}</WalletModalProvider> </WalletProvider> </ConnectionProvider> ); }; const Content: FC = () => { return ( <div className="App"> <WalletMultiButton /> </div> ); };
0
solana_public_repos/anza-xyz/wallet-adapter/packages/starter/create-react-app-starter
solana_public_repos/anza-xyz/wallet-adapter/packages/starter/create-react-app-starter/src/App.css
.App { min-height: 100vh; display: flex; justify-content: center; align-items: center; }
0