Sophon 백서

Sophon

원문

bitpro가 원문에서 글자만 모은 내용이에요. 표·그림·수식은 빠지거나 깨질 수 있어요. 전체 10쪽 중 8쪽

ype="string"> Issuer of the JWT token. This claim always shows **auth.sophon.xyz** generated and issued the JWT. </ResponseField> <ResponseField name="sub" type="string"> Subject of the JWT token, representing the user's smart wallet address. </ResponseField> <ResponseField name="iat" type="string"> Timestamp when the JWT token was issued. </ResponseField> <ResponseField name="exp" type="string"> Timestamp when the JWT token will expire. This is generally some hours after the token was issued. </ResponseField> <ResponseField name="scope" type="string"> The scope of data granted by the user that allows us to share specific data with the application that the user is connecting to. Possible scopes are: `email`, `twitter`, `gmail`, `discord` and `telegram`. Multiple scopes could be provided and they are separated by a space. </ResponseField> ## Sending the Token Once you got the token issued, you can send it during the calls to your API using the classic header `Authorization: Bearer <token>`. See how to do it with different frameworks: <CodeGroup> ```typescript axios theme={null} import axios from 'axios'; export const callBackend = (token: string) => { const response = await axios.get(`${process.env.BACKEND_URL}/do-something`, { headers: { Authorization: `Bearer ${token}`, }, }); if (response.status !== 200) { throw new Error('Failed to call backend.'); } return response.data; }; ``` ```typescript fetch theme={null} export const callBackend = (token: string) => { const response = await fetch(`${process.env.BACKEND_URL}/do-something`, { method: 'POST', headers: { 'Authorization': `Bearer ${accessToken}` }, body: JSON.stringify(data) }); if (!response.ok) { throw new Error('Failed to call backend.'); } return response.json(); } ``` </CodeGroup> ## Decoding the JWT When you have the token, it is useful to decode it for additional verification during your backend processing. Given that only Sophon can issue tokens, you can validate that the token you are receiving is valid, and it assert that the user owns the account. By using the JWKS standard, and having the public key we provide, you can decode by yourself, without having to making additional calls. ### Decode Using Sophon Account SDK To make things easier, we provide a SDK that can decode the token for you: <CodeGroup> ```bash npm theme={null} npm install @sophon-labs/account-api-sdk ``` ```bash yarn theme={null} yarn add @sophon-labs/account-api-sdk ``` ```bash pnpm theme={null} pnpm add @sophon-labs/account-api-sdk ``` </CodeGroup> Then, you can use it in your code: ```typescript theme={null} import { SophonAPISDK } from "@sophon-labs/account-api-sdk"; const partnerId = "my-partner-id"; const sdk = SophonAPISDK("testnet", partnerId); const decodedToken = sdk.auth.decodeJWT(token); console.log(decodedToken); // { iss: 'xxxx', exp: nnnn, ... } ``` ### Decoding the token using JWKS libraries One of the options is to use a JWKS library to decode the token. For example, using `jsonwebtoken` and `jwks-rsa` libraries: ```typescript theme={null} import jwt, { JwtPayload } from "jsonwebtoken"; import { JwksClient } from "jwks-rsa"; const jwksUrl = `https://api.my.staging.sophon.xyz/.well-known/jwks.json`; // https://api.my.sophon.xyz/.well-known/jwks.json for production // The client should be initialized as const client = new JwksClient({ jwksUri: jwksUrl, rateLimit: true, cache: true, cacheMaxEntries: 5, // Maximum number of cached keys cacheMaxAge: 600000, // Cache duration in milliseconds (10 minutes in this case))} }); const signingKey = await client.getSigningKey(); const publicKey = signingKey.getPublicKey(); const decodedToken: JwtPayload = jwt.verify(encodedJwt, publicKey, { ignoreExpiration: false, }) as JwtPayload; console.log(decodedToken); // { iss: 'xxxx', exp: nnnn, ... } ``` # Data Scopes Source: https://docs.sophon.xyz/sophon-account/authentication/data-scopes <Warning> Tokens are accessible only when using the React and React Native SDKs with a valid `partnerId`. Partners integrating via EIP-6963 will not have access to user tokens. </Warning> As an authentication provider, Sophon Account is able to provide a list of data scopes that the user can grant to the application. You are required to specify the data scopes that you want to request from the user when you are initializing the SDK Context Provider. The available scopes right now are: * `email` * `x` * `gmail` * `discord` * `telegram` The user has the option to grant or not to grant the scopes to the application during the authentication process. To use it in code, you can do the following: ```typescript Requesting Data Scopes theme={null} import { DataScopes } from "@sophon-labs/account-core"; import { SophonContextProvider } from "@sophon-labs/account-react-native"; export default function App() { return ( <SophonContextProvider partnerId="$YOUR_PARTNER_ID" dataScopes={[DataScopes.email, DataScopes.x]} network="testnet" > {/* Your components*/} </SophonContextProvider> ); } ``` Then you will have the scopes available in the user JWT token, and fetch the info in the backend. For more information, please check the [JWT & Access Tokens](./access-tokens) documentation. # EIP-6963 Source: https://docs.sophon.xyz/sophon-account/authentication/eip6963 [EIP-6963](https://eips.ethereum.org/EIPS/eip-6963) is a standard way to add support for **Sophon Account** using the main wallet providers in the market. The implementation is very simple, you just need to import the package and it will automatically broadcast the provider to the wallet provider that you are using. Most modern wallet connection libraries, like RainbowKit, wagmi, or Reown Appkit, support [EIP-6963](https://eips.ethereum.org/EIPS/eip-6963). <CodeGroup> ```bash npm theme={null} npm install @sophon-labs/account-eip6963 ``` ```bash yarn theme={null} yarn add @sophon-labs/account-eip6963 ``` ```bash pnpm theme={null} pnpm add @sophon-labs/account-eip6963 ``` </CodeGroup> Then you need to import and initialize the [EIP-6963](https://eips.ethereum.org/EIPS/eip-6963) emitter in your application entry point, the simplest way is: <CodeGroup> ```typescript testnet theme={null} import "@sophon-labs/account-eip6963/testnet"; ``` ```typescript mainnet theme={null} import "@sophon-labs/account-eip6963/mainnet"; ``` </CodeGroup> If you need dynamic network support, you can use the root package, for example: ```typescript theme={null} import { getDefaultConfig } from "@rainbow-me/rainbowkit"; import { sophonTestnet, sophon } from "wagmi/chains"; import { createSophonEIP6963Emitter } from "@sophon-labs/account-eip6963"; createSophonEIP6963Emitter("testnet"); export const config = getDefaultConfig({ appName: "Your Application", projectId: "YOUR_PROJECT_ID", chains: [sophon, sophonTestnet], ssr: true, }); ``` This will automatically: * Register the **Sophon Account** provider * Announce it through the [EIP-6963](https://eips.ethereum.org/EIPS/eip-6963) events * Make it available to [EIP-6963](https://eips.ethereum.org/EIPS/eip-6963) compatible applications You can find examples of implementing EIP-6963 with other common libraries: * [RainbowKit](../examples/rainbowkit) * [Reown AppKit](../examples/appkit) * [ConnectKit](../examples/connectkit) * [Thirdweb Wallet](../examples/thirdweb) <CardGroup> <Card title="EIP-6963 Example Repository" icon="github" href="https://github.com/sophon-org/sophon-account-sso/tree/main/examples/web/eip6963"> You can check an example of implementing EIP-6963 with RainbowKit. </Card> </CardGroup> # Overview Source: https://docs.sophon.xyz/sophon-account/authentication/intro There are some different ways to integrate Sophon Account into your application: * Using the **React** and **React Native** SDKs * Using the **EIP-6963** standard on *any* web plaform <CardGroup> <Card title="EIP-6963" icon="globe" href="./eip6963"> Fast integration by just importing a package into your existing project. </Card> <Card title="React" icon="react" href="./react"> Integrate any web app with Sophon Account. </Card> <Card title="React Native" icon="mobile" href="./react-native"> Integrate any mobile app with Sophon Account. </Card> </CardGroup> <Note> Some of the options available require a valid `partnerId` to be provided to the SDK. Email us at [product@sophon.xyz](mailto:product@sophon.xyz) to request yours. </Note> # React Source: https://docs.sophon.xyz/sophon-account/authentication/react You can add support for Sophon Account in your React application by using the `@sophon-labs/account-react` package. ## Installation <CodeGroup> ```sh npm theme={null} # Sophon Library npm install @sophon-labs/account-react ``` ```sh yarn theme={null} # Sophon Library yarn add @sophon-labs/account-react ``` ```sh pnpm theme={null} # Sophon Library pnpm add @sophon-labs/account-react ``` </CodeGroup> ## Usage Before anything, you need to wrap your application with `SophonContextProvider`, that will store context information about the account and walletClient connection. ```ts theme={null} 'use client'; import { DataScopes } from '@sophon-labs/account-core'; import { SophonContextProvider, SophonWagmiConnector, } from '@sophon-labs/account-react'; import { QueryClient, QueryClientProvider } from '@tanstack/react-query'; import { type ReactNode, useState } from 'react'; import { type State, WagmiProvider } from 'wagmi'; import { getWagmiConfig } from '../lib/wagmi'; export default function Web3ModalProvider({ children, initialState, }: { children: ReactNode; initialState?: State; }) { const [config] = useState(() => getWagmiConfig()); const [queryClient] = useState(() => new QueryClient()); return ( <SophonContextProvider network="testnet" partnerId="123b216c-678e-4611-af9a-2d5b7b061258" dataScopes={[DataScopes.email]} > <WagmiProvider config={config} initialState={initialState}> <QueryClientProvider client={queryClient}> <SophonWagmiConnector>{children}</SophonWagmiConnector> </QueryClientProvider> </WagmiProvider> </SophonContextProvider> ); } ``` With that ready, you can now use our hooks to interact with Sophon. ```ts theme={null} import { useSophonAccount } from "@sophon-labs/account-react"; export default function YourComponent() { const { connect, account, disconnect } = useSophonAccount(); // ... } ``` And you can use any wagmi hook to interact with the wallet as well. <Card title="React Example" icon="github" href="https://github.com/sophon-org/sophon-account-sso/tree/main/examples/web/react"> You can check an example of implementing React Native with Sophon Account. </Card> # React Native Source: https://docs.sophon.xyz/sophon-account/authentication/react-native <Warning> Because of how **React Native** libraries work, you will need to install dependencies that have native code directly in your app so that we can use them. </Warning> You can add support for Sophon Account in your React Native application by using the `@sophon-labs/account-react-native` package. ## Installation <Tip> The SDK is compatible with Expo Go without the need of prebuilding the app. </Tip> Before you start, you need these libraries: <CodeGroup> ```sh npm theme={null} # Expo packages npx expo install react-native-webview expo-standard-web-crypto expo-crypto expo-network expo-secure-store ``` ```sh yarn theme={null} # Expo packages npx expo install react-native-webview expo-standard-web-crypto expo-crypto expo-network expo-secure-store ``` ```sh pnpm theme={null} # Expo packages npx expo install react-native-webview expo-standard-web-crypto expo-crypto expo-network expo-secure-store ``` </CodeGroup> After that, you are ready to install our SDK: <CodeGroup> ```sh npm theme={null} # Sophon Library npm install @sophon-labs/account-react-native ``` ```sh yarn theme={null} # Sophon Library yarn add @sophon-labs/account-react-native ``` ```sh pnpm theme={null} # Sophon Library pnpm add @sophon-labs/account-react-native ``` </CodeGroup> ## Usage Before anything, you need to wrap your application with `SophonContextProvider`, that will store context information about the account and walletClient connection. ```ts theme={null} import { DataScopes } from "@sophon-labs/account-core"; import { SophonContextProvider } from "@sophon-labs/account-react-native"; export default function RootLayout() { // ... return ( <SophonContextProvider partnerId="$YOUR_PARTNER_ID" dataScopes={[DataScopes.email, DataScopes.x]} network="testnet" > {/* Your components*/} </SophonContextProvider> ); } ``` With that ready, you can now use our hooks to interact with Sophon. ```ts theme={null} import { useSophonAccount } from "@sophon-labs/account-react-native"; export default function YourComponent() { const { connect, account, disconnect } = useSophonAccount(); // ... } ``` <Card title="React Native Example" icon="github" href="https://github.com/sophon-org/sophon-account-sso/tree/main/examples/mobile/expo-53-go"> You can check an example of implementing React Native with Sophon Account. </Card> # Overview Source: https://docs.sophon.xyz/sophon-account/connectors/intro Sophon Account can be used with most popular wallet connectors in the market. <CardGroup> <Card title="Viem" icon="cube" href="./viem" /> <Card title="Wagmi" icon="cubes" href="./wagmi" /> </CardGroup> # Integrating with Viem Source: https://docs.sophon.xyz/sophon-account/connectors/viem <Note>Viem is actually a dependency for Sophon Account.</Note> We expose an [EIP-1193](https://eips.ethereum.org/EIPS/eip-1193) provider that can be used directly with [Viem](https://viem.sh/). ```ts theme={null} import { createSophonEIP1193Provider } from "@sophon-labs/account-connector"; import { useCallback, useMemo, useState } from "react"; import { type Address, createWalletClient, custom } from "viem"; import { sophonTestnet } from "viem/chains"; import { eip712WalletActions } from "viem/zksync"; export default function Home() { const [address, setAddress] = useState<Address>(); const [error, setError] = useState<string>(); const [signature, setSignature] = useState<string>(); const provider = useMemo(() => { return createSophonEIP1193Provider( 'testnet', '123b216c-678e-4611-af9a-2d5b7b061258', ); }, []); const walletClient = useMemo(() => { return createWalletClient({ chain: sophonTestnet, transport: custom(provider), }).extend(eip712WalletActions()); }, [provider]); const handleConnect = useCallback(async () => { const addresses = await walletClient.requestAddresses(); if (!addresses.length) { setError("No addresses found"); return; } setAddress(addresses[0]); const signature = await walletClient.signMessage({ account: addresses[0], message: 'Hello from Sophon', }); setSignature(signature); }, [walletClient]); const handleDisconnect = useCallback(async () => { setAddress(undefined); setError(undefined); setSignature(undefined); await provider.disconnect(); }, [provider]); return ( // ... your logic here ); } ``` <Card title="Viem Example" icon="github" href="https://github.com/sophon-org/sophon-account-sso/tree/main/examples/web/viem"> You can check an example of using Viem directly with Sophon Account. </Card> # Integrating with Wagmi Source: https://docs.sophon.xyz/sophon-account/connectors/wagmi To integrate Sophon Account with Wagmi, you need to install the `@sophon-labs/account-connector` package. ```bash theme={null} npm install @sophon-labs/account-connector ``` Then, you need to create a new connector: ```ts theme={null} import { sophon, sophonTestnet } from "viem/chains"; import { createConfig, http, WagmiProvider } from "wagmi"; // Wagmi config const wagmiConfig = createConfig({ chains: [sophonTestnet], connectors: [sophonSsoConnector("testnet")], // or 'mainnet' transports: { [sophon.id]: http(), [sophonTestnet.id]: http(), }, }); ``` And that's it, you can now use wagmi hooks and componentes to interact with Sophon Account. ## Signin Messages Simple message signature is supported: ```ts theme={null} import { useSignMessage } from "wagmi"; // ... const { signMessage } = useSignMessage(); // ... signMessage({ message: "Hello from Sophon SSO!", }); ``` ## Signin Types Messages Typed data signature is supported: ```ts theme={null} import { useSignTypedData } from "wagmi"; // ... const { signMessage } = useSignTypedData(); // ... signTypedData({ domain: { name: "Sophon SSO", version: "1", chainId: sophonTestnet.id, }, types: { Message: [ { name: "content", type: "string" }, { name: "from", type: "address" }, { name: "timestamp", type: "uint256" }, ], }, primaryType: "Message", message: { content: `Hello from Sophon SSO!\n\nThis message confirms you control this wallet.`, from: address as `0x${string}`, timestamp: BigInt(Math.floor(Date.now() / 1000)), }, }); ``` <Card title="Wagmi Connector Example" icon="github" href="https://github.com/sophon-org/sophon-account-sso/tree/main/examples/web/wagmi"> You can check an example of using a custom Wagmi connector with Sophon Account. </Card> # Reown AppKit Source: https://docs.sophon.xyz/sophon-account/examples/appkit Integrate the Sophon Account with Reown AppKit ## Reown AppKit Reown AppKit is a versatile wallet connector for React, enabling seamless wallet connection and transaction signing. <CardGroup> <Card title="Sophon Account + Reown AppKit example repository" icon="code" href="https://github.com/sophon-org/sophon-account/tree/main/examples/eip-6963-appkit"> Reown AppKit Example </Card> </CardGroup> ### Installation <CodeGroup> ```npm yarn pnpm bun theme={null} npm install @sophon-labs/account-eip6963 wagmi viem @reown/appkit @tanstack/react-query ``` </CodeGroup> ### Live demo <div> <iframe /> </div> ### Sample configuration ```typescript {10, 32-42} theme={null} "use client"; import React, { ReactNode } from "react"; import { QueryClient, QueryClientProvider } from "@tanstack/react-query"; import { createAppKit } from "@reown/appkit/react"; import { sophonTestnet } from "@reown/appkit/networks"; import { WagmiAdapter } from "@reown/appkit-adapter-wagmi"; import { State, WagmiProvider } from "wagmi"; import "@sophon-labs/account-eip6963/testnet"; // Get your project ID from https://cloud.reown.com export const projectId = process.env.NEXT_PUBLIC_PROJECT_ID; const queryClient = new QueryClient(); if (!projectId) throw new Error("Project ID is not defined"); const metadata = { // optional name: "AppKit", description: "AppKit Example", url: "https://example.com", icons: ["https://avatars.githubusercontent.com/u/179229932"], }; const wagmiAdapter = new WagmiAdapter({ networks: [sophonTestnet], projectId, }); createAppKit({ enableWalletConnect: false, enableEIP6963: true, adapters: [wagmiAdapter], networks: [sophonTestnet], metadata: metadata, projectId, features: { analytics: true, connectMethodsOrder: ["wallet", "social", "email"], }, }); export default function Web3ModalProvider({ children, initialState, }: { children: ReactNode; initialState?: State; }) { return ( <WagmiProvider config={wagmiAdapter.wagmiConfig} initialState={initialState}> <QueryClientProvider client={queryClient}>{children}</QueryClientProvider> </WagmiProvider> ); } ``` # ConnectKit Source: https://docs.sophon.xyz/sophon-account/examples/connectkit Integrate the Sophon Account with ConnectKit ## ConnectKit ConnectKit is a wallet connector for React that allows users to connect to a wallet and sign transactions. <CardGroup> <Card title="Sophon Account + ConnectKit example repository" icon="code" href="https://github.com/sophon-org/sophon-account/tree/main/examples/eip-6963-connectkit"> ConnectKit Example </Card> </CardGroup> ### Installation <CodeGroup> ```npm yarn pnpm bun theme={null} npm instal
프로젝트로 돌아가기