### Install ic-siws-js and Dependencies Source: https://github.com/kristoferlund/ic-siws/blob/main/packages/ic_siws_js/README.md Installs the ic-siws-js library along with its required peer dependencies for Solana wallet integration and Internet Computer communication. ```bash npm install ic-siws-js @solana/wallet-adapter-base @solana/web3.js @dfinity/agent @dfinity/candid @dfinity/identity ``` -------------------------------- ### Configure Runtime Features Source: https://github.com/kristoferlund/ic-siws/blob/main/packages/ic_siws_provider/README.md Examples of configuring runtime features for the ic_siws_provider canister and ic_siws library. This includes enabling IncludeUriInSeed, disabling SolToPrincipal mapping, and disabling PrincipalToSol mapping. ```bash runtime_features = opt vec { \ variant { IncludeUriInSeed } \ }; ``` ```bash runtime_features = opt vec { \ variant { DisableSolToPrincipalMapping } \ }; ``` ```bash runtime_features = opt vec { \ variant { DisablePrincipalToSolMapping } \ }; ``` -------------------------------- ### Configure ic_siws_provider Canister Source: https://github.com/kristoferlund/ic-siws/blob/main/packages/ic_siws_provider/README.md Example of configuring the ic_siws_provider canister during deployment using the dfx command line tool. This includes setting domain, URI, salt, chain ID, and targets. ```bash dfx deploy ic_siws_provider --argument $'( record { domain = "127.0.0.1"; uri = "http://127.0.0.1:5173"; salt = "my secret salt"; chain_id = opt "mainnet"; scheme = opt "http"; statement = opt "Login to the app"; sign_in_expires_in = opt 300000000000; # 5 minutes session_expires_in = opt 604800000000000; # 1 week targets = opt vec { "'$(dfx canister id ic_siws_provider)'"; # Must be included "'$(dfx canister id my_app_canister)'"; # Allow identity to be used with this canister }; runtime_features = null; } )' ``` -------------------------------- ### Install ic_siws_provider Canister in dfx.json Source: https://github.com/kristoferlund/ic-siws/blob/main/packages/ic_siws_provider/README.md Add the pre-built `ic_siws_provider` canister to your `dfx.json` file to enable Solana wallet authentication in your Internet Computer project. This configuration specifies the canister type, candid interface, and WASM file. ```json { "canisters": { "ic_siws_provider": { "type": "custom", "candid": "https://github.com/kristoferlund/ic-siws/releases/download/v0.1.0/ic_siws_provider.did", "wasm": "https://github.com/kristoferlund/ic-siws/releases/download/v0.1.0/ic_siws_provider.wasm.gz" } } } ``` -------------------------------- ### React SIWS Setup with SiweIdentityProvider and useSiws Hook Source: https://github.com/kristoferlund/ic-siws/blob/main/packages/ic_siws_js/README.md Shows how to set up the `SiweIdentityProvider` component in a React application to provide SIWE identity context to child components. It also demonstrates using the `useSiws` hook to access SIWE functionalities like login and state management. ```jsx // App.tsx import { SiwsIdentityProvider } from 'ic-siws-js/react'; import { canisterId } from "../../ic_siws_provider/declarations/index"; import type { SignInMessageSignerWalletAdapter } from '@solana/wallet-adapter-base'; import { useWallet } from '@solana/wallet-adapter-react'; function App() { const wallet = useWallet() as SignInMessageSignerWalletAdapter; return ( {/* ...your app components */} ); } // Usage within a component: import { useSiws } from "ic-siws-js/react"; function MyComponent() { const { login, loginStatus, prepareLoginStatus } = useSiws(); return ( ); } ``` -------------------------------- ### Integrate SiwsIdentityProvider in React Source: https://github.com/kristoferlund/ic-siws/blob/main/packages/ic_siws_provider/README.md Example of wrapping a React application's root component with SiwsIdentityProvider from the ic-siws-js package. It uses the useWallet hook from @solana/wallet-adapter-react to provide the wallet adapter. ```jsx import { useWallet } from "@solana/wallet-adapter-react"; import { SiwsIdentityProvider } from "ic-siws-js/react"; import { canisterId } from "../../../ic_siws_provider/declarations/index"; export default function SiwsProvider({ children, }: { children: React.ReactNode; }) { // Listen for changes to the selected wallet const { wallet } = useWallet(); // Update the SiwsIdentityProvider with the selected wallet adapter return ( {children} ); } ``` -------------------------------- ### Use useSiws Hook in React Component Source: https://github.com/kristoferlund/ic-siws/blob/main/packages/ic_siws_provider/README.md Example of using the useSiws hook within a React component to access SIWS functionalities like initiating the login process. ```jsx // Component.tsx import { useSiws } from "ic-siws-js/react"; function MyComponent() { const { login, clear, identity, ... } = useSiws(); // ... } ``` -------------------------------- ### SIWS Canister Interface Definition Source: https://github.com/kristoferlund/ic-siws/blob/main/packages/ic_siws/README.md Defines the types and service methods for the SIWS canister interface, including data structures for addresses, keys, signatures, and messages, as well as methods for preparing login, logging in, and getting delegations. ```text type Address = text; type CanisterPublicKey = PublicKey; type Principal = blob; type PublicKey = blob; type SessionKey = PublicKey; type SiwsSignature = text; type Timestamp = nat64; type Nonce = text; type RuntimeFeature = variant { IncludeUriInSeed; DisableSolToPrincipalMapping; DisablePrincipalToSolMapping }; type SettingsInput = record { domain : text; uri : text; salt : text; chain_id : opt text; scheme : opt text; statement : opt text; sign_in_expires_in : opt nat64; session_expires_in : opt nat64; targets : opt vec text; runtime_features: opt vec RuntimeFeature; }; type GetAddressResponse = variant { Ok : Address; Err : text; }; type GetDelegationResponse = variant { Ok : SignedDelegation; Err : text; }; type SignedDelegation = record { delegation : Delegation; signature : blob; }; type Delegation = record { pubkey : PublicKey; expiration : Timestamp; targets : opt vec principal; }; type GetPrincipalResponse = variant { Ok : Principal; Err : text; }; type LoginResponse = variant { Ok : LoginDetails; Err : text; }; type LoginDetails = record { expiration : Timestamp; user_canister_pubkey : CanisterPublicKey; }; type SiwsMessage = record { domain : text; address : Address; statement : text; uri : text; version : nat32; chain_id : text; nonce : text; issued_at : nat64; expiration_time : nat64; }; type PrepareLoginResponse = variant { Ok : SiwsMessage; Err : text; }; service : (settings_input : SettingsInput) -> { "get_address" : (Principal) -> (GetAddressResponse) query; "get_caller_address" : () -> (GetAddressResponse) query; "get_principal" : (Address) -> (GetPrincipalResponse) query; "siws_prepare_login" : (Address) -> (PrepareLoginResponse); "siws_login" : (SiwsSignature, Address, SessionKey, Nonce) -> (LoginResponse); "siws_get_delegation" : (Address, SessionKey, Timestamp) -> (GetDelegationResponse) query; }; ``` -------------------------------- ### Get Caller Solana Address Source: https://github.com/kristoferlund/ic-siws/blob/main/packages/ic_siws_provider/README.md Retrieves the Solana address associated with the caller. This function internally calls `get_address` and returns the same output. ```rust pub async fn get_caller_address() -> Result { get_address().await } ``` -------------------------------- ### Get Principal from Solana Address Source: https://github.com/kristoferlund/ic-siws/blob/main/packages/ic_siws_provider/README.md Retrieves the principal associated with a given Solana address. It takes a Base58 encoded Solana address as input and returns the principal or an error message. ```rust pub async fn get_principal(solana_address: String) -> Result { // Implementation details for converting Solana address to principal // ... } ``` -------------------------------- ### Prepare SIWS Login Challenge Source: https://github.com/kristoferlund/ic-siws/blob/main/packages/ic_siws_provider/README.md Generates a SIWS message challenge to initiate the login process. It takes a Solana address as input and returns the challenge message or an error. ```rust pub async fn siws_prepare_login(solana_address: String) -> Result { // Implementation details for generating SIWS challenge // ... } ``` -------------------------------- ### Canister Initialization and Upgrade Endpoints Source: https://github.com/kristoferlund/ic-siws/blob/main/packages/ic_siws_provider/README.md Handles the initialization and upgrade of the `ic_siws_provider` canister. Both functions accept a `SettingsInput` struct to configure SIWS parameters like domain, URI, salt, and chain ID. ```APIDOC init(settings: SettingsInput) - Initializes the canister with provided SIWS settings. - Input: - settings: SettingsInput struct containing domain, uri, salt, chain_id, etc. - Operation: Configures the SIWS library with the given settings. upgrade(settings: SettingsInput) - Maintains canister state and settings during an upgrade. - Input: - settings: SettingsInput struct with updated or existing SIWS configuration. - Operation: Preserves and reapplies SIWS settings and state after an upgrade. ``` -------------------------------- ### SIWS Login and Delegation Preparation Source: https://github.com/kristoferlund/ic-siws/blob/main/packages/ic_siws_provider/README.md Verifies the signature of a SIWS message and prepares the delegation for authentication. It requires the signature, Solana address, session key, and nonce. Returns login details or an error. ```rust pub async fn siws_login( signature: String, solana_address: String, session_key: ByteBuf, nonce: String, ) -> Result { // Implementation details for verifying signature and preparing delegation // ... } ``` -------------------------------- ### Vanilla JS/TS SIWS Manager Initialization and Usage Source: https://github.com/kristoferlund/ic-siws/blob/main/packages/ic_siws_js/README.md Demonstrates how to initialize the `SiwsManager` in Vanilla JavaScript/TypeScript, set up event listeners for login/logout buttons, and subscribe to state changes in the `siwsStateStore` to update the UI based on the login status. ```ts import { canisterId } from "../../ic_siws_provider/declarations/index"; import { SiwsManager, siwsStateStore } from "ic-siws-js"; // Initialize the SiwsManager with the canisterId of the SIWS provider canister. const siws = new SiwsManager(canisterId); // Set up HTML elements for login and logout buttons, etc. // ... // Interact with the SiwsManager instance to trigger the login process or to logout. loginButton.addEventListener("click", () => siws.login()); logoutButton.addEventListener("click", () => siws.clear()); // Listen for changes to the siwsStateStore and update the UI accordingly. siwsStateStore.subscribe((snapshot) => { const { prepareLoginStatus, prepareLoginError, loginStatus, loginError, signMessageStatus, } = snapshot.context; if (loginStatus === "idle") { loginButton.innerHTML = "Login"; loginButton.disabled = false; } if (loginStatus === "logging-in") { loginButton.innerHTML = "Logging in..."; loginButton.disabled = true; } // Handle other states ... }); ``` -------------------------------- ### SettingsInput Structure Definition Source: https://github.com/kristoferlund/ic-siws/blob/main/packages/ic_siws_provider/README.md Defines the input structure for configuring the ic_siws_provider canister. It includes fields for domain, URI, salt, chain ID, session timeouts, and allowed targets. ```rust pub struct SettingsInput { /// The domain from where the frontend that uses SIWS is served. /// Example: "example.com" or "sub.example.com". pub domain: String, /// The full URI, including port number, of the frontend that uses SIWS. /// Example: "https://example.com" or "https://sub.example.com:8080". pub uri: String, /// The salt used when generating the seed that uniquely identifies each user principal. /// The salt can only contain printable ASCII characters. pub salt: String, /// Optional. The Solana chain ID for ic-siws. Defaults to "mainnet". /// Valid values: "mainnet", "testnet", "devnet", "localnet", "solana:mainnet", "solana:testnet", "solana:devnet". pub chain_id: Option, /// Optional. The scheme used to serve the frontend (e.g., "http" or "https"). /// Defaults to "https". pub scheme: Option, /// Optional. The statement is a message or declaration presented to the user by their Solana wallet. /// Defaults to "SIWS Fields:". pub statement: Option, /// Optional. Time-to-live for a sign-in message in nanoseconds. Defaults to 5 minutes. pub sign_in_expires_in: Option, /// Optional. Time-to-live for a session in nanoseconds. Defaults to 30 minutes. pub session_expires_in: Option, /// Optional. List of canister IDs (as text) for which the identity delegation is allowed. /// Must include this canister's ID if set. pub targets: Option>, /// Optional. Runtime features to customize canister behavior. pub runtime_features: Option>, } ``` -------------------------------- ### SIWS Canister Interface API Source: https://github.com/kristoferlund/ic-siws/blob/main/packages/ic_siws/README.md Provides API documentation for the SIWS canister interface, detailing the methods for initiating login, authenticating users, and retrieving delegations. ```APIDOC SIWS Canister Interface: get_address(principal: Principal) -> GetAddressResponse - Retrieves the address associated with a given principal. - Parameters: - principal: The principal for which to get the address. - Returns: GetAddressResponse (Ok: Address | Err: text) get_caller_address() -> GetAddressResponse - Retrieves the address of the current caller. - Returns: GetAddressResponse (Ok: Address | Err: text) get_principal(address: Address) -> GetPrincipalResponse - Retrieves the principal associated with a given address. - Parameters: - address: The address for which to get the principal. - Returns: GetPrincipalResponse (Ok: Principal | Err: text) siws_prepare_login(address: Address) -> PrepareLoginResponse - Initiates the login flow by generating a SIWS message. - This method is called by the frontend application to prompt the user to sign the message with their Solana wallet. - Parameters: - address: The user's Solana address. - Returns: PrepareLoginResponse (Ok: SiwsMessage | Err: text) siws_login(signature: SiwsSignature, address: Address, session_key: SessionKey, nonce: Nonce) -> LoginResponse - Authenticates the user by verifying the SIWS message signature. - Prepares the delegation to be fetched in the siws_get_delegation function. - Parameters: - signature: The signature of the SIWS message from the user's wallet. - address: The user's Solana address. - session_key: The session key for the user. - nonce: The nonce used in the SIWS message. - Returns: LoginResponse (Ok: LoginDetails | Err: text) siws_get_delegation(address: Address, session_key: SessionKey, timestamp: Timestamp) -> GetDelegationResponse - Retrieves the signed delegation for the user. - Parameters: - address: The user's Solana address. - session_key: The session key for the user. - timestamp: The current timestamp. - Returns: GetDelegationResponse (Ok: SignedDelegation | Err: text) ``` -------------------------------- ### Vue SIWS Initialization and Adapter Management Source: https://github.com/kristoferlund/ic-siws/blob/main/packages/ic_siws_js/README.md Illustrates how to initialize the SIWS identity provider in a Vue application using `createSiwsIdentityProvider` in the root `App.vue`. It also shows how to manage the Solana wallet adapter and clear the identity upon wallet disconnect using the `useSiws` hook. ```vue ``` -------------------------------- ### Svelte SIWS Initialization Source: https://github.com/kristoferlund/ic-siws/blob/main/packages/ic_siws_js/README.md Shows how to initialize the SIWS manager in a Svelte application by calling the `init` function with the canister ID and an optional adapter. This should be done in the top-level component. ```svelte ``` -------------------------------- ### SIWS Delegation Flow Source: https://github.com/kristoferlund/ic-siws/blob/main/packages/ic_siws/README.md Illustrates the process of preparing and creating a delegation for SIWS. This involves obtaining a canister public key and setting an expiration for the delegation. ```mermaid graph TD A[User] --> B(Frontend) B --> C(Canister) C --> D(SolWallet) C -- Prepare delegation --> C C -- OK, canister_pubkey, delegation_expires --> B B -- siws_get_delegation() --> C C -- OK, delegation --> B B -- Create delegation identity --> B B -- OK, logged in with Principal niuiu-iuhbi...-oiu --> A ``` -------------------------------- ### Fetch SIWS Delegation Source: https://github.com/kristoferlund/ic-siws/blob/main/packages/ic_siws_provider/README.md Fetches the delegation required for authentication after a successful login. It takes the Solana address, session key, and expiration timestamp as input, returning the signed delegation or an error. ```rust pub async fn siws_get_delegation( solana_address: String, session_key: ByteBuf, expiration_timestamp: u64, ) -> Result { // Implementation details for fetching delegation // ... } ``` -------------------------------- ### ic_siws_provider Canister Integration Source: https://github.com/kristoferlund/ic-siws/blob/main/packages/ic_siws/README.md The prebuilt `ic-siws-provider` canister offers a plug-and-play solution for integrating Solana wallet authentication into ICP applications. By adding this canister to the `dfx.json` file of an ICP project, developers can quickly enable Solana wallet-based authentication, simplifying the process of managing SIWS messages and user sessions. ```APIDOC Integration Steps: 1. Add the `ic-siws-provider` canister to your ICP project's `dfx.json`. 2. The canister handles SIWS message creation and verification. 3. Manages user session management. Benefits: - Plug-and-play solution. - Minimal coding requirements. - Simplifies authentication flow. ``` -------------------------------- ### Service Interface: get_address Source: https://github.com/kristoferlund/ic-siws/blob/main/packages/ic_siws_provider/README.md API documentation for the get_address endpoint, which retrieves the Solana address associated with a given ICP principal. It specifies input format, output types, and potential errors. ```rust get_address - Purpose: Retrieves the Solana address associated with a given ICP principal. - Input: A `ByteBuf` containing the principal's bytes (expected to be 29 bytes). - Output: - `Ok(String)`: The Base58 encoded Solana address, if found. - `Err(String)`: An error message if the principal cannot be converted or no address is found. ``` -------------------------------- ### SiwsIdentityContextType Interface Source: https://github.com/kristoferlund/ic-siws/blob/main/packages/ic_siws_js/README.md Defines the structure and methods for managing a user's identity context within the SIWS (Sign-In With Solana) flow. It includes states for initialization, login preparation, login status, message signing, and properties for the identity, delegation chain, and public key. ```APIDOC SiwsIdentityContextType: isInitializing: boolean Is set to `true` on mount until a stored identity is loaded from local storage or none is found. setAdapter: (adapter: Adapter) => Promise Sets the wallet adapter to be used for signing the SIWE message. This must be called before calling `login()`. Alternatively, you can pass the adapter to the SiwsManager constructor. prepareLogin: () => void Load a SIWE message from the provider canister, to be used for login. Calling prepareLogin is optional, as it will be called automatically on login if not called manually. prepareLoginStatus: PrepareLoginStatus Reflects the current status of the prepareLogin process. isPreparingLogin: boolean `prepareLoginStatus === "loading"` isPrepareLoginError: boolean `prepareLoginStatus === "error"` isPrepareLoginSuccess: boolean `prepareLoginStatus === "success"` isPrepareLoginIdle: boolean `prepareLoginStatus === "idle"` prepareLoginError?: Error Error that occurred during the prepareLogin process. login: () => Promise Initiates the login process by requesting a SIWE message from the backend. loginStatus: LoginStatus Reflects the current status of the login process. isLoggingIn: boolean `loginStatus === "logging-in"` isLoginError: boolean `loginStatus === "error"` isLoginSuccess: boolean `loginStatus === "success"` isLoginIdle: boolean `loginStatus === "idle"` loginError?: Error Error that occurred during the login process. signMessageStatus: SignMessageStatus Status of the SIWE message signing process. signMessageError?: Error Error that occurred during the SIWE message signing process. delegationChain?: DelegationChain The delegation chain is available after successfully loading the identity from local storage or completing the login process. identity?: DelegationIdentity The identity is available after successfully loading the identity from local storage or completing the login process. identityPublicKey?: PublicKey The Ethereum address associated with current identity. This address is not necessarily the same as the address of the currently connected wallet - on wallet change, the addresses will differ. clear: () => void Clears the identity from the state and local storage. Effectively "logs the user out". ``` -------------------------------- ### ic-siws Provider Settings API Source: https://github.com/kristoferlund/ic-siws/blob/main/packages/ic_siws_provider/README.md Defines the structure and parameters for configuring the ic_siws_provider canister. This includes essential settings for domain, URI, salt, and optional parameters for chain ID, scheme, statement, expiration times, targets, and runtime features. ```APIDOC SettingsInput: domain: String The domain from where the frontend that uses SIWS is served. Example: "example.com" or "sub.example.com". uri: String The full URI, including port number, of the frontend that uses SIWS. Example: "https://example.com" or "https://sub.example.com:8080". salt: String The salt used when generating the seed that uniquely identifies each user principal. The salt can only contain printable ASCII characters. chain_id: Option Optional. The Solana chain ID for ic-siws. Defaults to "mainnet". Valid values: "mainnet", "testnet", "devnet", "localnet", "solana:mainnet", "solana:testnet", "solana:devnet". scheme: Option Optional. The scheme used to serve the frontend (e.g., "http" or "https"). Defaults to "https". statement: Option Optional. The statement is a message or declaration presented to the user by their Solana wallet. Defaults to "SIWS Fields:". sign_in_expires_in: Option Optional. Time-to-live for a sign-in message in nanoseconds. Defaults to 5 minutes. session_expires_in: Option Optional. Time-to-live for a session in nanoseconds. Defaults to 30 minutes. targets: Option> Optional. List of canister IDs (as text) for which the identity delegation is allowed. Must include this canister's ID if set. runtime_features: Option> Optional. Runtime features to customize canister behavior. ``` -------------------------------- ### Login Flow Functions Source: https://github.com/kristoferlund/ic-siws/blob/main/packages/ic_siws/README.md The `ic_siws` library provides functions to manage the Solana wallet login flow on the Internet Computer. These functions include preparing the login message, handling the actual login process, and retrieving delegation information. ```APIDOC siws_prepare_login(): - Prepares the SIWS message for login. - Typically involves generating a nonce and constructing the message payload. siws_login(): - Handles the user's authentication after they sign the SIWS message. - Verifies the signature and creates an ICP identity/session. siws_get_delegation(): - Retrieves delegation information for the authenticated user. - Allows for timebound sessions and controlled access. ``` -------------------------------- ### ic_siws Rust Library Functionality Source: https://github.com/kristoferlund/ic-siws/blob/main/README.md The `ic_siws` Rust library provides core functionality for SIWS-enabled canisters. It handles the generation of SIWS login messages, verification of Solana wallet signatures, and issuance of delegated IC identities (Principals). This library allows for full control and customization of the SIWS flow within your canister project. ```rust /// Generates a SIWS login message. /// /// # Arguments /// * `domain` - The domain of the application. /// * `address` - The Solana wallet address. /// /// # Returns /// A SIWS login message string. fn generate_login_message(domain: &str, address: &str) -> String; /// Verifies a Solana wallet signature for a SIWS message. /// /// # Arguments /// * `message` - The SIWS login message. /// * `signature` - The Solana wallet signature. /// * `public_key` - The public key corresponding to the signature. /// /// # Returns /// `Ok(true)` if the signature is valid, `Ok(false)` otherwise, or an `Err` if verification fails. fn verify_signature(message: &str, signature: &str, public_key: &str) -> Result; /// Issues a delegated IC identity (Principal) based on a verified Solana address. /// /// # Arguments /// * `solana_address` - The verified Solana wallet address. /// /// # Returns /// A delegated IC Principal. fn issue_delegated_identity(solana_address: &str) -> Principal; ``` -------------------------------- ### ic-siws-js Frontend Library Usage Source: https://github.com/kristoferlund/ic-siws/blob/main/README.md The `ic-siws-js` library is a frontend support library for interacting with SIWS-enabled canisters. It simplifies the process of requesting login messages, prompting users to sign with their Solana wallets, and sending the signed message back to the canister for verification and identity issuance. It supports various JavaScript frameworks. ```javascript // Example usage with ic-siws-js import { SiwsClient } from 'ic-siws-js'; async function signInWithSolana(canisterId) { const client = new SiwsClient(canisterId); // Request login message from canister const message = await client.requestLoginMessage(); // Prompt user to sign message with Solana wallet (e.g., Phantom) const signedMessage = await client.signMessage(message); // Verify signature and get IC identity const identity = await client.verifySignature(signedMessage); console.log('Authenticated with IC Principal:', identity.getPrincipal().toText()); } ``` -------------------------------- ### SiwsIdentityProvider Props Source: https://github.com/kristoferlund/ic-siws/blob/main/packages/ic_siws_js/README.md Details the properties that can be passed to the `SiwsIdentityProvider` component in React and Vue, or `SiwsIdentityProvider.svelte` in Svelte. These props configure the SIWS provider. ```APIDOC SiwsIdentityProvider props: The `SiwsIdentityProvider` component (for React and Vue) or `SiwsIdentityProvider.svelte` component (for Svelte) accepts the following options: - `canisterId: string` — The unique identifier of the SIWS provider canister on the Internet Computer network. - `adapter?: SignInMessageSignerWalletAdapter` — Optional Solana wallet adapter from `@solana/wallet-adapter-base`. - `httpAgentOptions?: HttpAgentOptions` — Optional HTTP agent configuration for Internet Computer communication. - `actorOptions?: ActorConfig` — Optional actor configuration options. - `children: ReactNode` — (React only) Child components to wrap. In Svelte and Vue, use the default slot or provided hook respectively. ``` -------------------------------- ### ic-siws-provider Canister Interface Source: https://github.com/kristoferlund/ic-siws/blob/main/README.md The `ic_siws_provider` is a prebuilt, ready-to-use SIWS-enabled canister. It implements the interface for generating SIWS login messages, verifying Solana wallet signatures, and issuing delegated IC identities. This canister can be directly integrated into any ICP application by adding it to `dfx.json` and configuring it. ```APIDOC service :ic_siws_provider { // Generates a SIWS login message for the given domain and Solana address. // Parameters: // domain: The domain of the application (text). // address: The Solana wallet address (text). // Returns: // A SIWS login message (text). generate_login_message: (domain: text, address: text) -> (text); // Verifies a signed SIWS message and issues a delegated IC identity. // Parameters: // signed_message: The SIWS message signed by the Solana wallet (text). // Returns: // A delegated IC Principal (principal). // Throws an error if the signature is invalid or verification fails. verify_signature_and_issue_identity: (signed_message: text) -> (principal); // Retrieves the current session information. // Returns: // An optional Principal representing the authenticated user (opt principal). get_session: () -> (opt principal); // Clears the current session. // Returns: // Void. logout: () -> (); } ``` -------------------------------- ### siws_get_delegation Method Source: https://github.com/kristoferlund/ic-siws/blob/main/packages/ic_siws/README.md The siws_get_delegation method is invoked by the frontend after a successful login. Its purpose is to retrieve a signed delegation, which is then used to authenticate subsequent user actions. ```text ## `siws_get_delegation` - The `siws_get_delegation` method is called by the frontend application after a successful login. - Retrieves a signed delegation for a user to authenticate further actions. The login flow is illustrated in the following diagram: ```text ┌────────┐ ┌────────┐ ┌─────────┐ │Frontend│ │Canister│ │SolWallet│ User └───┬────┘ └───┬────┘ └────┬────┘ │ Push login button ┌┴┐ │ │ │ ────────────────────────────>│ │ │ │ │ │ │ │ │ │ │ │ siws_prepare_login(address) ┌┴┐ │ │ │ │ ─────────────────────────────────────────────>│ │ │ │ │ │ └┬┘ │ │ │ │ OK, siws_message │ │ │ │ │ <─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ │ │ │ │ │ │ │ │ │ Sign siws_message ┌┴┐ │ │ │ ──────────────────────────────────────────────────────────────────────────────────────>│ │ │ │ │ │ │ │ │ │ │ Ask user to confirm │ │ │ │ <───────────────────────────────────────────────────────────────────────────────────────────────────────────────────────│ │ │ │ │ │ │ │ │ │ │ OK │ │ │ │ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ >│ │ │ │ │ │ └┬┘ │ │ │ OK, signature │ │ │ │ <─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ │ │ │ │ │ │ │ │────┐ │ │ │ │ │ │ Generate random session_identity │ │ │ │ │<───┘ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ siws_login() ┌┴┐ │ │ │ │ ─────────────────────────────────────────────>│ │ │ │ │ │ │ │ │ │ │ │ │ │────┐ │ │ │ │ │ │ │ Verify signature and address │ │ │ │ │ │<───┘ │ │ │ │ │ │ │ ``` ``` -------------------------------- ### Svelte SIWS Store Usage Source: https://github.com/kristoferlund/ic-siws/blob/main/packages/ic_siws_js/README.md Illustrates how to use the SIWS store in any Svelte component to access login, logout, and status-related functions and properties. It includes conditional rendering for login/logout buttons. ```svelte {#if identity == null} {#if !identity} {/if} {#if identity} {/if} {/if} ``` -------------------------------- ### Vue useSiws Hook Usage Source: https://github.com/kristoferlund/ic-siws/blob/main/packages/ic_siws_js/README.md Demonstrates how to use the `useSiws` hook in a Vue 3 application. It sets up a watcher to update the SIWS adapter when the wallet public key changes and provides a login button. ```vue ``` -------------------------------- ### RuntimeFeature Enum Source: https://github.com/kristoferlund/ic-siws/blob/main/packages/ic_siws_provider/README.md Defines runtime features that can be enabled or disabled to control the behavior of the SIWS provider canister. These features affect identity seed generation and address mapping. ```rust pub enum RuntimeFeature { // Include the app frontend URI in the identity seed. IncludeUriInSeed, // Disable mapping of Solana address to principal, also disables `get_principal` endpoint. DisableSolToPrincipalMapping, // Disable mapping of principal to Solana address, also disables `get_address` and `get_caller_address` endpoints. DisablePrincipalToSolMapping, } ``` -------------------------------- ### SIWS Protocol Overview Source: https://github.com/kristoferlund/ic-siws/blob/main/packages/ic_siws/README.md Sign In With Solana (SIWS) is a Solana wallet standard that allows users to authenticate to dapps by signing messages with their Solana wallets. It streamlines the authentication process by standardizing message formats, building on principles from ERC-4361. The core of SIWS is a signed message containing the user's Solana address and metadata, verified by the application's backend to create a user session. ```APIDOC SIWS Message Structure: - Contains Solana address and metadata. - Signed by the user's Solana wallet. Verification Process: 1. Application backend receives the SIWS message. 2. Backend verifies the signature and Solana address. 3. Backend creates a user session. Implemented SIWS Standard Features: - Most parts of the SIWS standard are implemented. Not Implemented SIWS Standard Features: - `not-before`, `request-id`, `resources` (marked as OPTIONAL in SIWS standard). ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.