### 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