### Install Freighter API with npm Source: https://github.com/stellar/freighter/blob/master/docs/docs/guide/gettingStarted.md Installs the Freighter API JavaScript library for ES2023 applications using the npm package manager. ```Shell npm install @stellar/freighter-api ``` -------------------------------- ### Start Stellar Freighter Development Environment Source: https://github.com/stellar/freighter/blob/master/README.md Commands to initialize and launch the development environment for the Freighter project. This setup starts multiple parallel watching builds for the API module, documentation, the web application, and the extension itself, enabling real-time development. ```Shell yarn setup yarn start ``` -------------------------------- ### Install Freighter API with Yarn Source: https://github.com/stellar/freighter/blob/master/docs/docs/guide/gettingStarted.md Installs the Freighter API JavaScript library for ES2023 applications using the Yarn package manager. ```Shell yarn add @stellar/freighter-api ``` -------------------------------- ### Start Freighter Web Extension Development Server Source: https://github.com/stellar/freighter/blob/master/extension/README.md Commands to initiate a local development server for the Freighter web extension's popup, enabling hot reloads and access to features under development. ```shell yarn start ``` ```shell yarn start:experimental ``` -------------------------------- ### Include Freighter API via CDN Source: https://github.com/stellar/freighter/blob/master/docs/docs/guide/gettingStarted.md Includes the Freighter API JavaScript library in browser-based applications using a script tag from cdnjs. Note that version 1.1.2 or above is required. ```HTML ``` -------------------------------- ### Start Individual Freighter Workspaces Source: https://github.com/stellar/freighter/blob/master/README.md Command to start a specific workspace within the Freighter project in development mode. This allows developers to focus on a single component, such as 'freighter-api', 'docs', or 'extension', with dedicated watching builds. ```Shell yarn start: ``` -------------------------------- ### Start Freighter Local Development Server Source: https://github.com/stellar/freighter/blob/master/docs/README.md This command initiates the local development server for the Freighter project. Before running, ensure the `@stellar/freighter-api` dependency has been built by navigating to its directory and executing `yarn build`. ```Shell $ yarn start ``` -------------------------------- ### Install Xcode Command Line Tools Source: https://github.com/stellar/freighter/blob/master/fastlane/README.md Installs the necessary Xcode command line tools, which are a prerequisite for fastlane and other development tools on macOS. This command prompts the user to confirm the installation. ```sh xcode-select --install ``` -------------------------------- ### Build Production Stellar Freighter Extension Source: https://github.com/stellar/freighter/blob/master/README.md Instructions to build a production-ready version of the Freighter browser extension. This process involves installing all necessary project dependencies, setting up the workspace, and then executing the specific command to compile the extension for release. ```Shell yarn install yarn setup yarn build:extension:production ``` -------------------------------- ### Build Individual Freighter Workspaces Source: https://github.com/stellar/freighter/blob/master/README.md Command to build a specific workspace within the Freighter project, similar to the start command but for generating final compiled output. This is useful for targeted builds of components like 'freighter-api' or 'extension'. ```Shell yarn build: ``` -------------------------------- ### Example: Adding Soroban Tokens to Freighter Wallet Source: https://github.com/stellar/freighter/blob/master/docs/docs/guide/usingFreighterWebApp.md Provides a TypeScript example demonstrating how to use the `addToken` function from `@stellar/freighter-api` to programmatically add a Soroban token to the user's Freighter wallet, including connection checks and error handling. ```TypeScript import { isConnected, addToken } from "@stellar/freighter-api"; const addSorobanToken = async () => { if (!(await isConnected())) { return; } const result = await addToken({ contractId: "CC...ABCD", // The Soroban token contract ID networkPassphrase: "Test SDF Network ; September 2015", // Optional, defaults to Pubnet }); if (result.error) { console.error(result.error); return; } console.log( `Successfully added token with contract ID: ${result.contractId}` ); }; ``` -------------------------------- ### fastlane macOS Actions Source: https://github.com/stellar/freighter/blob/master/fastlane/README.md This section details available fastlane actions specifically for macOS, providing commands to manage certificates and build IPA files for applications. The 'bundle exec' prefix is optional and depends on your Ruby environment setup. ```APIDOC fastlane mac sync_certificates - Description: Sync certificates fastlane mac build - Description: Create ipa ``` -------------------------------- ### Submit Signed Stellar Transactions to Horizon with SDK Source: https://github.com/stellar/freighter/blob/master/docs/docs/guide/usingFreighterWebApp.md Illustrates how to take a transaction XDR signed by Stellar Freighter and submit it to the Stellar Horizon network using the `stellar-sdk`. This example shows the complete flow from signing to submission. ```TypeScript import { Server, TransactionBuilder } from "stellar-sdk"; const userSignTransaction = async ( xdr: string, network: string, signWith: string ) => { const signedTransactionRes = await signTransaction(xdr, { network, address: signWith, }); if (signedTransactionRes.error) { throw new Error(signedTransactionRes.error.message); } else { return signedTransactionRes.signedTxXdr; } }; const xdr = ""; // replace this with an xdr string of the transaction you want to sign const userSignedTransaction = userSignTransaction(xdr, "TESTNET"); const SERVER_URL = "https://horizon-testnet.stellar.org"; const server = new Server(SERVER_URL); const transactionToSubmit = TransactionBuilder.fromXDR( userSignedTransaction, SERVER_URL ); const response = await server.submitTransaction(transactionToSubmit); ``` -------------------------------- ### Verify Signed Message with Stellar Keypair in JavaScript Source: https://github.com/stellar/freighter/blob/master/docs/docs/playground/signMessage.mdx This example demonstrates how to verify a message signed using the Freighter `signMessage` method. It uses a Stellar keypair to verify the base64 encoded signature against the original message, ensuring its authenticity. ```JavaScript const kp = const res = await stellarApi.signMessage("hi", { networkPassphrase: SorobanClient.Networks.TESTNET }) const passes = kp.verify(Buffer.from("hi", "base64"), Buffer.from(res.signedMessage, "base64")) // true ``` -------------------------------- ### Check Freighter connection status (isConnected) Source: https://github.com/stellar/freighter/blob/master/docs/docs/guide/usingFreighterWebApp.md Checks if the Freighter browser extension is installed and connected. This function is useful for determining if a user in your application has Freighter available. It returns a promise resolving to an object indicating connection status and potential errors. ```APIDOC isConnected() -> > - Purpose: Determines if the Freighter browser extension is installed and connected. - Returns: A Promise that resolves to an object with: - `isConnected`: `boolean` - True if Freighter is connected. - `error`: `string` (optional) - An error message if connection fails. ``` ```typescript import { isConnected } from "@stellar/freighter-api"; const isAppConnected = await isConnected(); if (isAppConnected.isConnected) { alert("User has Freighter!"); } ``` -------------------------------- ### Stop Watching Stellar Freighter Wallet Changes Source: https://github.com/stellar/freighter/blob/master/docs/docs/guide/usingFreighterWebApp.md This snippet demonstrates how to initialize `WatchWalletChanges` to monitor Stellar wallet details (address, network, passphrase) and then use the `stop()` method to cease polling for updates after a specified duration. It shows the setup for continuous monitoring and its graceful termination. ```typescript import { WatchWalletChanges } from "@stellar/freighter-api"; const Watcher = new WatchWalletChanges(1000); Watcher.watch((watcherResults) => { document.querySelector("#address").innerHTML = watcherResults.address; document.querySelector("#network").innerHTML = watcherResults.network; document.querySelector("#networkPassphrase").innerHTML = watcherResults.networkPassphrase; }); setTimeout(() => { // after 30 seconds, stop watching Watcher.stop(); }, 30000); ``` -------------------------------- ### Build Freighter Web Extension Source: https://github.com/stellar/freighter/blob/master/extension/README.md Commands to compile the Freighter web extension for standard development, experimental features, and production environments. Production builds include minification and security guardrails. ```shell yarn build ``` ```shell yarn build:experimental ``` ```shell yarn build:production ``` -------------------------------- ### Build All Freighter Workspaces Source: https://github.com/stellar/freighter/blob/master/README.md Command to generate the final output for all components of the Freighter project. This includes compiling the documentation, the `@stellar/freighter` npm module, and the browser extension into their respective build directories. ```Shell yarn build ``` -------------------------------- ### Configure Freighter Backend URL Source: https://github.com/stellar/freighter/blob/master/extension/README.md Instructions for configuring the backend URL for the Freighter web extension by setting the `INDEXER_URL` environment variable in an `.env` file located at `extension/.env`. ```text INDEXER_URL=https://freighter-backend-prd.stellar.org/api/v1 ``` -------------------------------- ### Configure NVM for Husky Git Hooks Source: https://github.com/stellar/freighter/blob/master/README.md Configuration snippet for the `~/.huskryc` file, designed to ensure that Husky git hooks correctly load NVM and use the project's specified Node.js version. This prevents compatibility issues during pre-push operations by setting the appropriate `NVM_DIR` and sourcing `nvm.sh`. ```Shell export NVM_DIR="$HOME/.nvm" [ -s "$NVM_DIR/nvm.sh" ] && \. "$NVM_DIR/nvm.sh" ``` -------------------------------- ### Convert Freighter Extension for Safari Testing Source: https://github.com/stellar/freighter/blob/master/README.md Command to convert the built Freighter extension into an Xcode project, enabling testing within Safari. This uses the `safari-web-extension-converter` utility and specifies the output project location. ```Shell xcrun safari-web-extension-converter freighter/extension/build --project-location freighter-safari ``` -------------------------------- ### Demonstrate Freighter WatchWalletChangesDemo Component Usage Source: https://github.com/stellar/freighter/blob/master/docs/docs/playground/watchWalletChanges.mdx This snippet illustrates the process of importing the `WatchWalletChangesDemo` component from its module and subsequently rendering it within a JSX context. This component is designed to facilitate testing and observation of wallet changes within the Freighter environment. ```JavaScript import { WatchWalletChangesDemo } from "./components/WatchWalletChangesDemo"; ``` ```JSX ``` -------------------------------- ### Importing Freighter API modules Source: https://github.com/stellar/freighter/blob/master/docs/docs/guide/usingFreighterWebApp.md Demonstrates how to import the entire Freighter API library or specific modules for use in an ES2023 application, providing flexibility based on required functionality. ```javascript import freighterApi from "@stellar/freighter-api"; ``` ```javascript import { isConnected, getAddress, signAuthEntry, signTransaction, signBlob, addToken } from "@stellar/freighter-api"; ``` -------------------------------- ### signMessage API Reference for Stellar Freighter Source: https://github.com/stellar/freighter/blob/master/docs/docs/guide/usingFreighterWebApp.md Documents the `signMessage` function provided by the Stellar Freighter API, detailing its parameters, return types, and behavior for signing arbitrary messages. ```APIDOC signMessage(message: string, opts: { address: string }) -> > - This function accepts a string as the first parameter, which it will decode, sign as the user, and return a base64 encoded string of the signed contents. - The second parameter is an optional `opts` object where you can specify which account's signature you’re requesting. If Freighter has the public key requested, it will switch to that account. If not, it will alert the user that they do not have the requested account. ``` -------------------------------- ### Automate Node.js Version Switching with .nvmrc Source: https://github.com/stellar/freighter/blob/master/README.md This shell script snippet checks for the presence of an `.nvmrc` file in the current directory. If found, it executes `nvm use` to switch to the Node.js version specified in that file. This mechanism is often employed in development workflows or pre-commit git hooks to ensure all contributors are using the project's designated Node.js version, promoting consistency and preventing environment-related issues. ```bash # If you have an .nvmrc file, we use the relevant node version if [[ -f ".nvmrc" ]]; then nvm use fi ``` -------------------------------- ### Connect to Freighter and Sign Stellar Transactions Source: https://github.com/stellar/freighter/blob/master/docs/docs/guide/usingFreighterWebApp.md Demonstrates how to connect to the Stellar Freighter wallet, retrieve the user's public key, and sign Stellar transactions (XDRs) using the `@stellar/freighter-api`. It includes error handling and asynchronous operations. ```TypeScript import { isConnected, getPublicKey, signTransaction, signBlob, } from "@stellar/freighter-api"; const isAppConnected = await isConnected(); if (isAppConnected.isConnected) { alert("User has Freighter!"); } const retrievePublicKey = async () => { const accessObj = await requestAccess(); if (accessObj.error) { throw new Error(accessObj.error.message); } else { return accessObj.address; } }; const retrievedPublicKey = retrievePublicKey(); const userSignTransaction = async ( xdr: string, network: string, signWith: string ) => { const signedTransactionRes = await signTransaction(xdr, { network, address: signWith, }); if (signedTransactionRes.error) { throw new Error(signedTransactionRes.error.message); } else { return signedTransactionRes.signedTxXdr; } }; const xdr = ""; // replace this with an xdr string of the transaction you want to sign const userSignedTransaction = userSignTransaction(xdr, "TESTNET"); ``` -------------------------------- ### Freighter addToken API Reference Source: https://github.com/stellar/freighter/blob/master/docs/docs/guide/addToken.md Detailed specification for the `addToken` API, including its parameters, return values, and workflow for integrating Soroban tokens into Freighter. ```APIDOC addToken(contractId: string, networkPassphrase?: string) - Description: Triggers a workflow to add a Soroban token to Freighter. - Parameters: - contractId: string (required) The unique identifier of the Soroban token contract. - networkPassphrase: string (optional) The network passphrase to use for loading token details (symbol, name, decimals, balance). If omitted, it defaults to Pubnet's passphrase. - Returns: - On success: The `contractId` that was passed as input, after user confirmation. - On failure: An error object. - Behavior: 1. Freighter uses the provided `contractId` and `networkPassphrase` to load token details. 2. A modal popup is displayed to the user showing token details and any applicable warnings for review and verification. 3. User approval is required to proceed with adding the token. 4. Upon successful approval, Freighter tracks the token's balance and displays it alongside other account balances. ``` -------------------------------- ### Importing and Using RequestAccessDemo Component Source: https://github.com/stellar/freighter/blob/master/docs/docs/playground/requestAccess.mdx Demonstrates how to import the `RequestAccessDemo` component and use it within a React/JSX environment. This component provides a user interface to test the `requestAccess` method's functionality. ```JavaScript import { RequestAccessDemo } from "./components/RequestAccessDemo"; ``` -------------------------------- ### Encoding Soroban Smart Contract Values for Token Transfer in JavaScript Source: https://github.com/stellar/freighter/blob/master/docs/docs/guide/developingForSoroban.md This JavaScript snippet demonstrates how to encode human-readable values (public keys, destination addresses, and amounts) into Soroban smart contract (SC) values using `@stellar/stellar-sdk`. It outlines the process of building a transaction, adding a contract call (specifically for a token transfer adhering to SEP-0041), simulating it, and assembling the final XDR for signing, suitable for wallet development. ```javascript import { Address, Contract, TransactionBuilder, Memo, SorobanRpc, XdrLargeInt, } from "stellar-sdk"; /* For this example, we are assuming the token adheres to the interface documented in SEP-0041 */ const generateTransferXdr = (contractId, serverUrl, publicKey, destination, amount, fee, networkPassphrase, memo) => { // the contract id of the token const contract = new Contract(contractId); const server = new SorobanRpc.Server(serverUrl); const sourceAccount = await server.getAccount(publicKey); const builder = new TransactionBuilder(sourceAccount, { fee, networkPassphrase, }); // these values would be entered by the user // we will use some helper methods to convert the addresses and the amount into SC vals const transferParams = [ new Address(publicKey).toScVal(), // from new Address(destination).toScVal(), // to new XdrLargeInt("i128", amount).toI128(), // amount ]; // call the `transfer` method with the listed params const transaction = builder .addOperation(contract.call("transfer", ...transferParams)) .setTimeout(180); if (memo) { transaction.addMemo(Memo.text(memo)); } transaction.build(); // simulate the transaction const simulationTransaction = await server.simulateTransaction( transaction, ); // and now assemble the transaction before signing const preparedTransaction = SorobanRpc.assembleTransaction( transaction, simulationTransaction, ) .build() .toXDR(); return { simulationTransaction, preparedTransaction, }; } ``` -------------------------------- ### Importing GetAddressDemo Component in JavaScript Source: https://github.com/stellar/freighter/blob/master/docs/docs/playground/getAddress.mdx Illustrates how to import the `GetAddressDemo` component from a relative path, typically within a JavaScript or TypeScript module for a web application. ```JavaScript import { GetAddressDemo } from "./components/GetAddressDemo"; ``` -------------------------------- ### Parsing Stellar XDR Invocations and SC Values in JavaScript Source: https://github.com/stellar/freighter/blob/master/docs/docs/guide/developingForSoroban.md This JavaScript snippet demonstrates how to walk an XDR transaction's invocation tree, extract details such as function names, contract IDs, and arguments from both root and sub-invocations. It then shows how to convert the Stellar Smart Contract (SC) values within these arguments into native JavaScript types, making them human-readable. This process is vital for applications that need to display transaction authorization details to users. ```javascript const walkAndParse = (transactionXdr, networkPassphrase) => { const transaction = TransactionBuilder.fromXDR( transactionXdr, networkPassphrase ); // for this simple example, let's just grab the first operation's first auth entry const op = transaction.operations[0]; const firstAuthEntry = op.auth[0]; const rootInvocation = firstAuthEntry.rootInvocation(); /* This is a generic example of how to grab the function name, contract id, and the parameters of the invocation. This is useful for showing a user some details about the function that is actually going to be called by the smart contract */ const getInvocationArgs = (invocation) => { const fn = invocation.function(); const _invocation = fn.contractFn(); const contractId = StrKey.encodeContract( _invocation.contractAddress().contractId() ); const fnName = _invocation.functionName().toString(); const args = _invocation.args(); return { fnName, contractId, args }; }; const invocations = []; /* We'll recursively walk the invocation tree to get all of the sub-invocations and pull out the function name, contractId, and args, as shown above */ walkInvocationTree(rootInvocation, (inv) => { const args = getInvocationArgs(inv); if (args) { invocations.push(args); } return null; }); /* We now have some each information about the root invocation and its subinvocations, but all the data is in SC val format, so it is still unreadable for users */ // For simplicity, let's just grab the first invocation and show how to parse it const firstInvocation = invocations[0]; const firstInvocationArgs = firstInvocation.args; /* Generally, we can just use `scValToNative` to decode a SC val into a usable JS data type but this may not work for all SC vals. For more information check the function scValByType in extension/src/popup/helpers/soroban.ts */ const humanReadableArgs = firstInvocationArgs.map((a) => scValToNative(a)); return humanReadableArgs; }; ``` -------------------------------- ### Using GetAddressDemo React Component in JSX Source: https://github.com/stellar/freighter/blob/master/docs/docs/playground/getAddress.mdx Demonstrates the usage of the `GetAddressDemo` React component within JSX, likely for rendering a UI element that interacts with or tests the Freighter `getAddress` method. ```JSX ``` -------------------------------- ### WatchWalletChanges API Reference for Freighter Source: https://github.com/stellar/freighter/blob/master/docs/docs/guide/usingFreighterWebApp.md Documents the `WatchWalletChanges` class and its `watch` method, which enable applications to monitor and react to changes in the user's Stellar Freighter wallet, such as account address or network updates. ```APIDOC WatchWalletChanges -> new WatchWalletChanges(timeout?: number) - The class `WatchWalletChanges` provides methods to watch changes from Freighter. To use this class, first instantiate with an optional `timeout` param to determine how often you want to check for changes in the wallet. The default is `3000` ms. WatchWalletChanges.watch(callback: ({ address: string; network: string; networkPassphrase; string }) => void) - The `watch()` method starts polling the extension for updates. By passing a callback into the method, you can access Freighter's `address`, `network`, and `networkPassphrase`. This method will only emit results when something has changed. ``` -------------------------------- ### Request user public key and access from Freighter (requestAccess) Source: https://github.com/stellar/freighter/blob/master/docs/docs/guide/usingFreighterWebApp.md Prompts the user to grant access and retrieve their public key. If the user has previously authorized the application, the key is returned immediately without a prompt. It returns a promise resolving to an object containing the public key or an error. ```APIDOC requestAccess() -> > - Purpose: Prompts the user to grant access and retrieve their public key. If previously authorized, the key is returned immediately. - Returns: A Promise that resolves to an object with: - `address`: `string` - The user's public key (Stellar address). - `error`: `string` (optional) - An error message if access is denied or fails. ``` ```typescript import { isConnected, requestAccess, signAuthEntry, signTransaction, signBlob } from "@stellar/freighter-api"; const isAppConnected = await isConnected(); if ("isConnected" in isAppConnected && isAppConnected.isConnected) { alert("User has Freighter!"); } const retrievePublicKey = async () => { const accessObj = await requestAccess(); if (accessObj.error) { return accessObj.error; } else { return accessObj.address; } }; const result = retrievePublicKey(); ``` -------------------------------- ### Freighter signAuthEntry Method API Reference Source: https://github.com/stellar/freighter/blob/master/docs/docs/playground/signAuthEntry.mdx This method allows users to sign an authentication entry (XDR string) using a specified address via the Freighter wallet. It returns a promise that resolves with the signed entry or an error. ```APIDOC signAuthEntry(authEntryXdr: string, opts: { address: string }) -> Promise<{ signedAuthEntry: Buffer | null; signerAddress: string } & { error?: string; }> - Description: Signs an authentication entry (XDR string) using the Freighter wallet. - Parameters: - authEntryXdr: string - Description: The XDR string representation of the authentication entry to be signed. - opts: object - Description: Options for the signing operation. - Properties: - address: string - Description: The Stellar public address of the account that will sign the entry. - Returns: Promise - Description: A Promise that resolves to an object containing the result of the signing operation. - Properties of resolved object: - signedAuthEntry: Buffer | null - Description: The signed authentication entry as a Node.js Buffer, or null if the signing failed. - signerAddress: string - Description: The Stellar public address of the account that performed the signing. - error?: string - Description: Optional. An error message if the signing operation encountered an issue. ``` -------------------------------- ### Import GetNetworkDemo Component in React Source: https://github.com/stellar/freighter/blob/master/docs/docs/playground/getNetwork.mdx Imports the `GetNetworkDemo` React component from a local file path. This component is designed to encapsulate the logic for testing and demonstrating Freighter's `getNetwork` method. ```JavaScript import { GetNetworkDemo } from "./components/GetNetworkDemo"; ``` -------------------------------- ### Retrieve Detailed Network Information with Freighter Source: https://github.com/stellar/freighter/blob/master/docs/docs/guide/usingFreighterWebApp.md This function retrieves comprehensive network configuration from the Stellar Freighter extension, including the full network URL, network passphrase, and Soroban RPC URL. Unlike `getNetwork()`, it provides detailed information essential for working with Soroban smart contracts or when specific network endpoints are required. ```typescript import { isConnected, getNetwork, getNetworkDetails, } from "@stellar/freighter-api"; const checkNetworks = async () => { if (!(await isConnected())) { return; } // Basic network name const network = await getNetwork(); console.log("Network:", network); // e.g., "TESTNET" // Detailed network information const details = await getNetworkDetails(); console.log("Network:", details.network); // e.g., "TESTNET" console.log("Network URL:", details.networkUrl); // e.g., "https://horizon-testnet.stellar.org" console.log("Network Passphrase:", details.networkPassphrase); // e.g., "Test SDF Network ; September 2015" console.log("Soroban RPC URL:", details.sorobanRpcUrl); // e.g., "https://soroban-testnet.stellar.org" }; ``` -------------------------------- ### Importing Google Fonts via CSS Source: https://github.com/stellar/freighter/blob/master/extension/public/index.html This CSS snippet demonstrates how to import external fonts from Google Fonts using the @import rule. These fonts are typically used for styling the application's typography and ensuring consistent visual presentation across the UI. ```CSS @import url("https://fonts.googleapis.com/css2?family=Muli:ital,wght@0,200;0,400;0,700;1,200;1,400;1,700&display=swap"); @import url("https://fonts.googleapis.com/css2?family=Roboto+Mono&display=swap"); ``` -------------------------------- ### addToken API Reference for Soroban Tokens Source: https://github.com/stellar/freighter/blob/master/docs/docs/guide/usingFreighterWebApp.md Details the `addToken` function in the Stellar Freighter API, which allows users to add Soroban tokens to their wallet. It specifies parameters like `contractId` and `networkPassphrase`, and describes the user workflow and return values. ```APIDOC addToken({ contractId: string, networkPassphrase?: string }) -> > - This function allows you to trigger an "add token" workflow to add a Soroban token to the user's Freighter wallet. It takes a contract ID as a required parameter and an optional network passphrase. If the network passphrase is omitted, it defaults to Pubnet's passphrase. - When called, Freighter will load the token details (symbol, name, decimals, and balance) from the contract and display them in a modal popup for user review. The user can then verify the token's legitimacy and approve adding it to their wallet. After approval, Freighter will track the token's balance and display it alongside other account balances. - The function returns a Promise that resolves to an object containing either: - The contract ID of the added token on success - An error message if the request fails or the user rejects it ``` -------------------------------- ### Freighter API Methods for Dapp Connection Source: https://github.com/stellar/freighter/blob/master/docs/docs/guide/whatsNew.md Documentation for the `@stellar/freighter-api` methods used by decentralized applications (dapps) to establish a connection with the Freighter wallet. These methods are crucial for initiating the connection flow, allowing dapps to interact with the user's active keypair. As of this update, dapps must use these methods to connect before being able to sign transactions or messages. ```APIDOC @stellar/freighter-api: setAllowed(): boolean - Purpose: Initiates the connection flow, allowing a dapp to request access to the user's Freighter wallet. This method is used by dapps to establish a trusted connection. - Parameters: None explicitly mentioned in the provided text, typically inferred from the dapp's origin or context during the connection prompt. - Returns: A boolean indicating the success or failure of the connection request, based on user approval. - Usage: Called by a dapp to prompt the user for connection approval, enabling subsequent transaction signing. requestAccess(): boolean - Purpose: Another method for initiating the connection flow, similar to `setAllowed`, used by dapps to gain access to the user's Freighter wallet. This method is part of the required connection process before signing. - Parameters: None explicitly mentioned in the provided text, typically inferred from the dapp's origin or context during the connection prompt. - Returns: A boolean indicating the success or failure of the connection request, based on user approval. - Usage: Called by a dapp to prompt the user for connection approval, enabling subsequent transaction signing. ``` -------------------------------- ### Check Freighter API Connection in Browser Source: https://github.com/stellar/freighter/blob/master/docs/docs/guide/usingFreighterBrowser.mdx This JavaScript snippet demonstrates how to verify if the Freighter browser extension is connected and accessible within a web page. It checks for the presence and connectivity of the `window.freighterApi` object. ```JavaScript if (await window.freighterApi.isConnected()) { alert("User has Freighter!"); } ``` -------------------------------- ### Importing SetAllowedDemo Component Source: https://github.com/stellar/freighter/blob/master/docs/docs/playground/setAllowed.mdx Imports the `SetAllowedDemo` component from a relative path, making it available for use in the current JavaScript/TypeScript module, typically within a React application. ```JavaScript import { SetAllowedDemo } from "./components/SetAllowedDemo"; ``` -------------------------------- ### Freighter getNetworkDetails API Method Source: https://github.com/stellar/freighter/blob/master/docs/docs/playground/getNetworkDetails.mdx Documents the `getNetworkDetails` method available in the Freighter library, used for retrieving network-specific details. This method is typically invoked to interact with the Stellar network and obtain its current configuration or status. ```APIDOC `getNetworkDetails()` - Purpose: Retrieves network-specific details from the connected Stellar network via Freighter. - Parameters: None. - Returns: A Promise that resolves to an object containing network details (e.g., network passphrase, current ledger, etc.). The exact structure of the returned object is dependent on the Freighter implementation. ``` -------------------------------- ### Freighter requestAccess API Method Source: https://github.com/stellar/freighter/blob/master/docs/docs/playground/requestAccess.mdx Documents the `requestAccess` method available in the Freighter project. This method is typically used to initiate a request for user access or permissions within the application. ```APIDOC requestAccess() - Description: Initiates a request for access within the Freighter application. This method typically prompts the user for permission or connects to a wallet/identity provider. - Parameters: None - Returns: Promise - A Promise that resolves to `true` if access is granted, `false` otherwise, or rejects if an error occurs during the request process. ``` -------------------------------- ### Request application authorization from Freighter (setAllowed) Source: https://github.com/stellar/freighter/blob/master/docs/docs/guide/usingFreighterWebApp.md Prompts the user to grant the application privileges to receive user data from Freighter. If accepted, the app is added to the extension's 'Allow list', enabling immediate data provision without further user action. It returns a promise resolving to an object indicating authorization status and potential errors. ```APIDOC setAllowed() -> > - Purpose: Prompts the user to grant the application privileges to receive user data from Freighter. - Returns: A Promise that resolves to an object with: - `isAllowed`: `boolean` - True if the app was successfully added to Freighter's Allow List. - `error`: `string` (optional) - An error message if the operation fails or is denied. ``` ```typescript import { setAllowed } from "@stellar/freighter-api"; const isAppAllowed = await setAllowed(); if (isAppAllowed.isAllowed) { alert("Successfully added the app to Freighter's Allow List"); } ``` -------------------------------- ### Freighter signMessage API Method Source: https://github.com/stellar/freighter/blob/master/docs/docs/playground/signMessage.mdx Documents the `signMessage` method provided by the Freighter API, used for signing arbitrary messages. It returns a promise that resolves with the signed message and the signer's address, or an error. ```APIDOC signMessage(message: string, opts: { address: string }) - Description: Signs an arbitrary string message using the connected Freighter wallet. - Parameters: - message (string): The message string to be signed. - opts (object): Options for the signing operation. - address (string): The Stellar public address of the account to use for signing. - Returns: Promise<{ signedMessage: string | null; signerAddress: string; } & { error?: string; }> - Description: A promise that resolves to an object containing the signed message and signer details. - Properties of the resolved object: - signedMessage (string | null): The base64 encoded signature of the message, or null if signing failed. - signerAddress (string): The Stellar public address of the account that signed the message. - error (string, optional): An error message if the signing operation failed. ``` -------------------------------- ### Retrieve current Stellar network from Freighter (getNetwork) Source: https://github.com/stellar/freighter/blob/master/docs/docs/guide/usingFreighterWebApp.md Determines the Stellar network (e.g., PUBLIC, TESTNET, FUTURENET, or STANDALONE for custom networks) that the user has configured Freighter to use. This is crucial for ensuring transactions are built for the correct network. It returns a promise resolving to an object containing network details or an error. ```APIDOC getNetwork() -> > - Purpose: Determines what Stellar network the user has configured Freighter to use (PUBLIC, TESTNET, FUTURENET, or STANDALONE). - Returns: A Promise that resolves to an object with: - `network`: `string` - The name of the Stellar network. - `networkPassphrase`: `string` - The network passphrase for the configured network. - `error`: `string` (optional) - An error message if retrieval fails. ``` ```typescript import { isConnected, getNetwork, signAuthEntry, signTransaction, signBlob } from "@stellar/freighter-api"; const isAppConnected = await isConnected(); if (isAppConnected.isConnected) { alert("User has Freighter!"); } const retrieveNetwork = async () => { const networkObj = await getNetwork(); if (networkObj.error) { return networkObj.error; } else { return { network: networkObj.network, networkPassphrase: networkObj.networkPassphrase }; } }; const result = retrieveNetwork(); ``` -------------------------------- ### Retrieve user public key from Freighter (getAddress) Source: https://github.com/stellar/freighter/blob/master/docs/docs/guide/usingFreighterWebApp.md A lightweight function to retrieve the user's public key if the application is already authorized and Freighter is connected. It returns the public key directly under these conditions; otherwise, it returns an empty string or an error. ```APIDOC getAddress() -> > - Purpose: A lightweight version of `requestAccess` to retrieve the user's public key if the application is already authorized and Freighter is connected. - Returns: A Promise that resolves to an object with: - `address`: `string` - The user's public key (Stellar address). - `error`: `string` (optional) - An error message if retrieval fails or conditions are not met. ``` ```typescript import { getAddress } from "@stellar/freighter-api"; const retrievePublicKey = async () => { const addressObj = await getAddress(); if (addressObj.error) { return addressObj.error; } else { return addressObj.address; } }; const result = retrievePublicKey(); ``` -------------------------------- ### Render GetNetworkDemo Component in JSX Source: https://github.com/stellar/freighter/blob/master/docs/docs/playground/getNetwork.mdx Renders the `GetNetworkDemo` React component within a JSX context. This component, once rendered, executes and displays the results of testing Freighter's `getNetwork` method. ```JSX ``` -------------------------------- ### Freighter addToken API Method Source: https://github.com/stellar/freighter/blob/master/docs/docs/playground/addToken.mdx Documents the `addToken` method available in the Stellar Freighter SDK, used for adding custom tokens to a user's wallet. It specifies the required contract ID and optional network passphrase, detailing the expected return value. ```APIDOC addToken({ contractId: string, networkPassphrase?: string }) -> > - Description: Initiates the process to add a custom token to the Freighter wallet. This method prompts the user to confirm the addition of a token identified by its contract ID. - Parameters: - contractId: string - The unique identifier (contract ID) of the token to be added. This is a mandatory parameter. - networkPassphrase?: string - (Optional) The network passphrase of the Stellar network the token belongs to. If not provided, Freighter will attempt to infer it or use the currently connected network. - Returns: Promise<{ contractId: string; } & { error?: string; }> - A Promise that resolves with an object containing: - contractId: string - The contract ID of the token that was successfully added. - error?: string - (Optional) An error message string if the operation failed (e.g., user rejected, invalid contract ID, network issues). - Usage Example: ```javascript import { addToken } from '@stellar/freighter-api'; async function addNewToken() { try { const result = await addToken({ contractId: 'CA1234567890ABCDEF...', // Replace with actual token contract ID networkPassphrase: 'Test SDF Network ; September 2015' // Optional }); console.log('Token added:', result.contractId); } catch (e) { console.error('Failed to add token:', e); } } addNewToken(); ``` ``` -------------------------------- ### Stellar Freighter Transaction and Authorization Signing API Source: https://github.com/stellar/freighter/blob/master/docs/docs/guide/usingFreighterWebApp.md This section details the API functions provided by Stellar Freighter for signing various types of Stellar-related data. It includes methods for signing full transaction XDRs and authorization entry preimages, allowing applications to securely request user signatures through the Freighter extension. ```APIDOC signTransaction(xdr: string, opts?: { network?: string, networkPassphrase?: string, address?: string }) -> > - Accepts a transaction XDR string, decodes it, signs as the user, and returns the signed transaction. - Parameters: - xdr: The transaction XDR string to be signed. - opts: Optional configuration object. - network: (Optional) The network name for the transaction (maps to js-stellar-sdk Networks enum). - networkPassphrase: (Optional) A custom network passphrase to use if not found in js-stellar-sdk. Overrides 'network' if both are provided. - address: (Optional) The public key of the account whose signature is requested. Freighter will switch to this account if available. - Returns: A Promise resolving to an object containing: - signedTxXdr: The signed transaction XDR string. - signerAddress: The public key of the signer. - error: (Optional) An error message if the operation failed. - Notes: - User password may be required if the private key is not cached (5-minute access after entry). - User must review and accept transaction details within 5 minutes. - Requires a valid transaction XDR string. - Provides blocking error messages if the intended network differs from Freighter's configuration. signAuthEntry(authEntryXdr: string, opts: { address: string }) -> > - Accepts an authorization entry preimage XDR and returns a signed hash of the same authorization entry. This signed hash can be added to the address credentials of the entry. - Parameters: - authEntryXdr: The authorization entry preimage XDR string. - opts: Configuration object. - address: The public key of the account whose signature is requested. Freighter will switch to this account if available. - Returns: A Promise resolving to an object containing: - signedAuthEntry: The signed authorization entry hash (Buffer) or null if signing failed. - signerAddress: The public key of the signer. - error: (Optional) An error message if the operation failed. - Notes: - Refer to js-stellar-base for examples on how this works (e.g., `authorizeEntry` helper). ``` -------------------------------- ### Check application authorization with Freighter (isAllowed) Source: https://github.com/stellar/freighter/blob/master/docs/docs/guide/usingFreighterWebApp.md Determines if the user has previously authorized your application to receive data from Freighter. This function helps ascertain if the app is on Freighter's 'Allow list' without prompting the user. It returns a promise resolving to an object indicating authorization status and potential errors. ```APIDOC isAllowed() -> > - Purpose: Determines if the user has previously authorized the application to receive data from Freighter. - Returns: A Promise that resolves to an object with: - `isAllowed`: `boolean` - Indicates if the app is authorized. - `error`: `string` (optional) - An error message if authorization check fails. ``` ```typescript import { isAllowed } from "@stellar/freighter-api"; const isAppAllowed = await isAllowed(); if (isAppAllowed.isAllowed) { alert("User has allowed your app!"); } ``` -------------------------------- ### Freighter getAddress Method API Source: https://github.com/stellar/freighter/blob/master/docs/docs/playground/getAddress.mdx Documents the `getAddress` method provided by the Freighter library. This method is used to retrieve the user's Stellar address from the connected Freighter wallet. ```APIDOC getAddress() ``` -------------------------------- ### Rendering SetAllowedDemo Component Source: https://github.com/stellar/freighter/blob/master/docs/docs/playground/setAllowed.mdx Renders the `SetAllowedDemo` React component within a JSX context, likely to display a user interface element or trigger functionality related to testing Freighter's `setAllowed` method. ```JSX ``` -------------------------------- ### Freighter signTransaction API Reference Source: https://github.com/stellar/freighter/blob/master/docs/docs/playground/signTransaction.mdx This entry details the `signTransaction` method, which allows users to sign a Stellar transaction XDR string using Freighter. It supports optional parameters for network specification and signer address, returning the signed transaction XDR and the signer's address, or an error. ```APIDOC signTransaction(xdr: string, opts?: { network?: string, networkPassphrase?: string, address?: string }) - Signs a Stellar transaction XDR string. - Parameters: - xdr: string The transaction XDR string to be signed. - opts?: object (optional) An object containing optional configuration for signing. - network?: string (optional) The network to use for signing (e.g., 'public', 'testnet'). - networkPassphrase?: string (optional) The network passphrase for the Stellar network. - address?: string (optional) The specific address to use for signing if multiple accounts are available. - Returns: Promise A Promise that resolves to an object containing the signed transaction XDR and signer address. - signedTxXdr: string The signed transaction XDR string. - signerAddress: string The public address of the signer. - error?: string (optional) An error message if the signing operation fails. ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.