### Initialize Node.js Project and Install Sonr SDK (Bash)
Source: https://github.com/sonr-io/motr/blob/main/docs/quickstart/react.mdx
This snippet shows how to create a new Node.js project directory, initialize it with npm, and install the necessary Sonr SDK and TypeScript dependencies.
```bash
mkdir sonr-ts-quickstart
cd sonr-ts-quickstart
npm init -y
npm install @sonr/sdk typescript ts-node @types/node
```
--------------------------------
### Start Development Server (Bash)
Source: https://github.com/sonr-io/motr/blob/main/apps/frontend/README.md
Command to launch the development server for the frontend application. Navigates to the frontend directory and starts the dev process. Assumes dependencies are installed.
```bash
cd apps/frontend
pnpm dev
```
--------------------------------
### Bash Commands for Sonr Browser Server Setup
Source: https://github.com/sonr-io/motr/blob/main/docs/quickstart/browser.mdx
Provides the necessary bash commands to install and run the `http-server` package, which is used to serve the Sonr browser application locally. This facilitates testing and development in a browser environment.
```bash
# Install http-server
npm install -g http-server
# Start the server
http-server
```
--------------------------------
### Quick Start: IPFS Client Setup and Data Operations (TypeScript)
Source: https://github.com/sonr-io/motr/blob/main/pkgs/sdk/README.md
Demonstrates how to create an IPFS client, store enclave data using JSON, and retrieve it. Includes client initialization with gateway configuration and cleanup.
```typescript
import { ipfs } from '@sonr.io/sdk';
// Create IPFS client
const client = await ipfs.createIPFSClient({
gateways: ['https://gateway.pinata.cloud'],
enablePersistence: true,
});
// Store enclave data
const enclaveData = {
publicKey: 'ed25519:...',
privateKeyShares: ['share1', 'share2', 'share3'],
threshold: 2,
parties: 3,
};
const { cid } = await client.addEnclaveData(
new TextEncoder().encode(JSON.stringify(enclaveData))
);
// Retrieve data
const retrieved = await client.getEnclaveData(cid);
const data = JSON.parse(new TextDecoder().decode(retrieved));
// Clean up
await client.cleanup();
```
--------------------------------
### Install Sonr SDK and TypeScript Dependencies
Source: https://github.com/sonr-io/motr/blob/main/docs/quickstart/cloudflare.mdx
Installs the necessary Sonr SDK package, TypeScript, and related type definitions for Node.js. These are essential for developing applications that interact with the Sonr network using TypeScript.
```bash
npm install @sonr/sdk typescript ts-node @types/node
```
--------------------------------
### Initialize Node.js Project with npm
Source: https://github.com/sonr-io/motr/blob/main/docs/quickstart/cloudflare.mdx
This command initializes a new Node.js project in a specified directory using npm. It creates a 'package.json' file to manage project dependencies and metadata. This is the first step in setting up a new project.
```bash
mkdir sonr-ts-quickstart
cd sonr-ts-quickstart
npm init -y
```
--------------------------------
### Create Sonr Wallet and Log Details (TypeScript)
Source: https://github.com/sonr-io/motr/blob/main/docs/quickstart/react.mdx
This TypeScript code demonstrates how to initialize the Sonr SDK, create a new wallet, and log its address and mnemonic. It requires the Sonr SDK and a running local Sonr network.
```typescript
import { Sonr } from "@sonr/sdk";
async function main() {
console.log("Creating a new Sonr wallet...");
const sonr = new Sonr({ httpUrl: "http://localhost:1317" });
const wallet = await sonr.createWallet();
console.log(`Wallet created!`);
console.log(`Address: ${wallet.address}`);
console.log(`Mnemonic: ${wallet.mnemonic}`);
}
main().catch(console.error);
```
--------------------------------
### Install @sonr.io/ui via npm, pnpm, or yarn
Source: https://github.com/sonr-io/motr/blob/main/docs/guides/signin-with-sonr.mdx
Installs the @sonr.io/ui package, which is necessary for integrating Sonr authentication into your application. Supports npm, pnpm, and yarn package managers.
```bash
npm install @sonr.io/ui
```
```bash
pnpm add @sonr.io/ui
```
```bash
yarn add @sonr.io/ui
```
--------------------------------
### Run Unit Tests (Bash)
Source: https://github.com/sonr-io/motr/blob/main/pkgs/sdk/README.md
Command to execute the project's unit tests using the `pnpm` package manager. Ensure all dependencies are installed before running.
```bash
pnpm test
```
--------------------------------
### Install Dependencies and Build Packages (Bash)
Source: https://github.com/sonr-io/motr/blob/main/apps/frontend/README.md
Commands to install project dependencies and build essential packages within the monorepo. Requires Node.js and pnpm.
```bash
pnpm install
pnpm build:es
pnpm build:ui
```
--------------------------------
### PDK Configuration Loading Example (Go)
Source: https://github.com/sonr-io/motr/blob/main/docs/guides/pdk-environment.mdx
Demonstrates how to load PDK configuration in Go, prioritizing environment variables and then overriding with settings from a configuration file. This function illustrates a common pattern for initializing application configurations.
```go
import (
"io/ioutil"
"encoding/json"
)
func loadPDKConfiguration() (*PDKConfig, error) {
// Load from environment variables
config := &PDKConfig{}
// Override with config file if exists
configFile, err := ioutil.ReadFile("/etc/sonr/pdk.json")
if err == nil {
json.Unmarshal(configFile, config)
}
return config, nil
}
```
--------------------------------
### PKCE Implementation
Source: https://github.com/sonr-io/motr/blob/main/docs/guides/signin-with-sonr.mdx
Explains how to enable Proof Key for Code Exchange (PKCE) for enhanced security, especially for public clients.
```APIDOC
## PKCE Implementation
### Description
This section describes how to enable Proof Key for Code Exchange (PKCE) when initializing the `OAuth2Client`. PKCE is recommended for public clients to prevent authorization code interception attacks.
### Method
N/A (Client Initialization)
### Endpoint
N/A (Client Initialization)
### Parameters
#### Path Parameters
None
#### Query Parameters
None
#### Request Body
None
### Request Example
```typescript PKCE Configuration
const client = new OAuth2Client({
clientId: 'public-client',
pkce: true, // Enabled by default for public clients
});
```
### Response
#### Success Response (200)
N/A
#### Response Example
N/A
```
--------------------------------
### React Hooks Integration
Source: https://github.com/sonr-io/motr/blob/main/docs/guides/signin-with-sonr.mdx
Example of how to use the `useSignInWithSonr` hook for authentication in a React application.
```APIDOC
## React Hooks Authentication
### Description
This hook provides a simple way to manage user authentication state, including sign-in, sign-out, and token management within React components.
### Method
N/A (Hook)
### Endpoint
N/A (Hook)
### Parameters
#### Path Parameters
None
#### Query Parameters
None
#### Request Body
None
### Request Example
```tsx React Hooks
import { useSignInWithSonr } from '@sonr.io/ui';
function LoginComponent() {
const {
user,
token,
isAuthenticated,
isLoading,
signIn,
signOut,
refreshToken,
} = useSignInWithSonr({
clientId: 'your-client-id',
redirectUri: 'http://localhost:3000/callback',
scopes: ['openid', 'profile', 'vault:read'],
});
if (isLoading) return
Loading...
;
if (isAuthenticated) {
return (
Welcome, {user.name}!
);
}
return ;
}
```
### Response
#### Success Response (200)
N/A (Hook manages state internally)
#### Response Example
N/A
```
--------------------------------
### Run Integration Tests with Docker (Bash)
Source: https://github.com/sonr-io/motr/blob/main/pkgs/sdk/README.md
Commands to set up and run integration tests. This involves starting Docker Compose with IPFS enabled and then executing the integration tests using `pnpm`.
```bash
docker-compose up -d ipfs
pnpm test:integration
```
--------------------------------
### Install @sonr.io/sdk for Cosmos SDK v0.50
Source: https://github.com/sonr-io/motr/blob/main/pkgs/sdk/README.md
Installs the @sonr.io/sdk package with the 'sdk50' tag, specifically for compatibility with Cosmos SDK v0.50. Supports npm, pnpm, and yarn.
```sh
npm install @sonr.io/sdk@sdk50
pnpm add @sonr.io/sdk@sdk50
yarn add @sonr.io/sdk@sdk50
```
--------------------------------
### Basic Service Worker Setup for Vault
Source: https://github.com/sonr-io/motr/blob/main/libs/vault/README.md
This TypeScript code demonstrates how to register the Vault Service Worker and initialize the WASM module. It includes registering the worker script and setting up event listeners for installation and activation.
```typescript
// main.ts - Register the service worker
if ('serviceWorker' in navigator) {
await navigator.serviceWorker.register('/vault-worker.js', {
scope: '/',
type: 'module'
});
console.log('Vault Service Worker registered');
}
// vault-worker.js - Service worker implementation
import { loadVault } from '@sonr.io/vault/loader';
self.addEventListener('install', (event) => {
event.waitUntil(
loadVault({
wasmPath: '/vault.wasm',
runtimePath: '/wasm_exec.js',
debug: true
}).then(() => {
console.log('[Vault] WASM loaded in service worker');
self.skipWaiting(); // Activate immediately
})
);
});
self.addEventListener('activate', (event) => {
event.waitUntil(
self.clients.claim() // Take control of all clients
);
});
```
--------------------------------
### Install @sonr.io/vault
Source: https://github.com/sonr-io/motr/blob/main/libs/vault/README.md
This command installs the @sonr.io/vault package using pnpm. It's a prerequisite for using the vault service worker in your project.
```bash
pnpm add @sonr.io/vault
```
--------------------------------
### Load Sonr SDK from CDN
Source: https://github.com/sonr-io/motr/blob/main/pkgs/sdk/README.md
This method demonstrates how to load the Sonr SDK directly from a CDN using a script tag. It includes an example of waiting for the SDK to be ready and performing WebAuthn registration.
```APIDOC
## Load from CDN
### Description
Load the Sonr autoloader script from a CDN and initialize the SDK. This example shows how to wait for the `sonr:ready` event and then perform a WebAuthn registration.
### Method
HTML script tag with `src` attribute pointing to the CDN URL.
### Endpoint
`https://unpkg.com/@sonr.io/sdk@latest/dist/autoloader.js`
### Parameters
None directly for loading, but SDK initialization can take a configuration object.
### Request Example
```html
Sonr ES Example
```
### Response
None directly from the script load. SDK functionality is accessed via the `window.Sonr` object after the `sonr:ready` event.
```
--------------------------------
### Install @sonr.io/sdk for Cosmos SDK v0.47 and below
Source: https://github.com/sonr-io/motr/blob/main/pkgs/sdk/README.md
Installs the latest version of the @sonr.io/sdk package compatible with Cosmos SDK v0.47 and below. This command works across different package managers like npm, pnpm, and yarn.
```sh
npm install @sonr.io/sdk
pnpm add @sonr.io/sdk
yarn add @sonr.io/sdk
```
--------------------------------
### SignInWithSonr Component Props
Source: https://github.com/sonr-io/motr/blob/main/docs/guides/signin-with-sonr.mdx
API reference for the properties available for the `SignInWithSonr` component.
```APIDOC
## SignInWithSonr Component Props
### Description
This reference details the properties (props) that can be passed to the `SignInWithSonr` component to customize its behavior and appearance.
### Method
N/A (Component Props)
### Endpoint
N/A (Component Props)
### Parameters
#### Path Parameters
None
#### Query Parameters
None
#### Request Body
None
### Request Example
```typescript
interface SignInWithSonrProps {
clientId: string;
redirectUri: string;
authorizationUrl?: string;
scopes?: string[];
state?: string;
variant?: 'default' | 'outline' | 'ghost' | 'dark';
size?: 'default' | 'sm' | 'lg';
isLoading?: boolean;
text?: string;
showLogo?: boolean;
onAuthStart?: () => void;
onAuthError?: (error: Error) => void;
}
```
### Response
#### Success Response (200)
N/A
#### Response Example
N/A
```
--------------------------------
### Install @sonr.io/enclave Package
Source: https://github.com/sonr-io/motr/blob/main/libs/enclave/README.md
Installs the @sonr.io/enclave package using the pnpm package manager. This is the first step to integrating the cryptographic vault into your project.
```bash
pnpm add @sonr.io/enclave
```
--------------------------------
### Query Sonr Account Balance (TypeScript)
Source: https://github.com/sonr-io/motr/blob/main/docs/quickstart/react.mdx
This TypeScript snippet shows how to query the balance of a Sonr account using the SDK. It requires a wallet address and assumes the account has been funded.
```typescript
// ... after creating the wallet
console.log("Querying account balance...");
// The localnet validator has funds, so we'll use its address for the query
const validatorAddress = "snr1..._validator_address_..."; // Replace with the actual validator address from your localnet
const balance = await sonr.getAccountBalance(validatorAddress);
console.log(`Balance for ${validatorAddress}:`, balance);
```
--------------------------------
### JavaScript Event Listener for Identity Creation
Source: https://github.com/sonr-io/motr/blob/main/docs/quickstart/browser.mdx
Sets up an event listener for a 'Create Identity' button in the browser. It displays a loading message and prepares for identity creation, including error handling for potential issues during the process.
```javascript
document
.getElementById("create-identity")
.addEventListener("click", async () => {
const output = document.getElementById("output");
output.innerHTML = "Creating identity...";
try {
// Code to create identity will go here
} catch (error) {
output.innerHTML = `Error: ${error.message}`;
}
});
```
--------------------------------
### Use Sonr SDK in Node.js/Build Systems
Source: https://github.com/sonr-io/motr/blob/main/pkgs/sdk/README.md
This method illustrates how to use the Sonr SDK within Node.js environments or build systems. It covers importing specific modules for tree-shaking and provides an example of initialization, WebAuthn registration, plugin creation, and codec usage.
```APIDOC
## Using in Node.js/Build Systems
### Description
Import specific modules from the Sonr SDK for better tree-shaking or import the entire autoloader. This example demonstrates initializing Sonr, performing WebAuthn registration, creating a Motor plugin, and using codec utilities.
### Method
`import` statement for ES Modules in Node.js or build systems.
### Endpoint
`@sonr.io/sdk/client/auth`
`@sonr.io/sdk/plugins`
`@sonr.io/sdk/codec`
`@sonr.io/sdk/autoloader`
### Parameters
`Sonr.init(config)`: Initializes the SDK with a configuration object.
- `enableMotor` (boolean): Enable Motor WASM plugin.
- `enableVault` (boolean): Enable Vault client.
### Request Example
```javascript
// Import specific modules (tree-shakeable)
import { registerWithPasskey, loginWithPasskey } from '@sonr.io/sdk/client/auth';
import { createMotorPlugin } from '@sonr.io/sdk/plugins';
import { bech32 } from '@sonr.io/sdk/codec';
// Or import the entire autoloader
import Sonr from '@sonr.io/sdk/autoloader';
// Initialize and use
async function main() {
// Initialize Sonr
await Sonr.init({
enableMotor: true,
enableVault: false
});
// Use WebAuthn
if (await Sonr.webauthn.isAvailable()) {
const result = await Sonr.webauthn.register({
username: 'bob',
displayName: 'Bob Smith',
rpId: 'example.com',
rpName: 'Example App'
});
console.log('Registered:', result);
}
// Access plugins
const motor = await Sonr.createMotorPlugin();
console.log('Motor plugin ready:', motor);
// Use codec utilities
const address = Sonr.codec.bech32.encode('sonr', [1, 2, 3, 4]);
console.log('Encoded address:', address);
}
main();
```
### Response
None directly from the import. SDK functionality is accessed via the imported modules or the `Sonr` object after initialization.
```
--------------------------------
### Configure TypeScript for Sonr Project (JSON)
Source: https://github.com/sonr-io/motr/blob/main/docs/quickstart/react.mdx
This JSON configuration sets up TypeScript for a Sonr project, specifying target version, module system, and strictness options for better code quality and compatibility.
```json
{
"compilerOptions": {
"target": "es2020",
"module": "commonjs",
"esModuleInterop": true,
"forceConsistentCasingInFileNames": true,
"strict": true,
"skipLibCheck": true
}
}
```
--------------------------------
### HTML Structure for Sonr Browser App
Source: https://github.com/sonr-io/motr/blob/main/docs/quickstart/browser.mdx
Basic HTML structure for a Sonr browser application, including a title, script imports, and interactive elements like buttons and output divs. It assumes an external app.js file for logic and imports the Sonr SDK via CDN.
```html
Sonr Browser Quickstart
Sonr Browser Quickstart
```
--------------------------------
### Import Sonr SDK and WebAuthn in Browser
Source: https://github.com/sonr-io/motr/blob/main/docs/quickstart/browser.mdx
Imports the Sonr SDK and WebAuthn modules from a CDN into the browser's window object, making them globally accessible for use in the application. This allows direct usage of Sonr functionalities without complex module resolution.
```javascript
import { Sonr, WebAuthn } from "https://cdn.jsdelivr.net/npm/@sonr/sdk";
window.Sonr = Sonr;
window.WebAuthn = WebAuthn;
```
--------------------------------
### Package Development Commands (Bash)
Source: https://github.com/sonr-io/motr/blob/main/pkgs/ui/README.md
Provides essential bash commands for developing and maintaining the '@sonr.io/ui' package. These include dependency installation, linting, type checking, adding shadcn components, and building the package.
```bash
# Install dependencies
pnpm install
# Lint the package
pnpm lint
# Type check
pnpm exec tsc --noEmit
# Add new shadcn component
npx shadcn@latest add [component-name]
# Build the package
pnpm run build
```
--------------------------------
### Handle Connection Failures with Fallback Gateways (TypeScript)
Source: https://github.com/sonr-io/motr/blob/main/pkgs/sdk/README.md
Provides a code example for configuring multiple fallback gateways to improve connection reliability. If the primary gateway fails, the client can attempt to connect to the listed alternatives.
```typescript
// Provide fallback gateways
const client = await createIPFSClient({
gateways: [
'http://localhost:5001', // Local node
'https://gateway.pinata.cloud', // Public gateway
'https://ipfs.io' // Fallback
]
});
```
--------------------------------
### Configure RPC Endpoint (Environment Variables)
Source: https://github.com/sonr-io/motr/blob/main/apps/frontend/README.md
Example of how to configure the RPC endpoint URL in a .env file. Supports testnet, mainnet, and local development configurations.
```env
# Testnet (default)
VITE_RPC_URL=https://rpc.testnet.sonr.io
# Mainnet
# VITE_RPC_URL=https://rpc.mainnet.sonr.io
# Local development
# VITE_RPC_URL=http://localhost:26657
```
--------------------------------
### Next.js App Router Integration
Source: https://github.com/sonr-io/motr/blob/main/docs/guides/signin-with-sonr.mdx
Guides for setting up Sonr authentication within a Next.js application using the App Router, including an AuthProvider component.
```APIDOC
## Next.js App Router Authentication
### Description
This section provides instructions for integrating Sonr authentication into a Next.js application using the App Router. It includes setting up a root layout and an `AuthProvider` component to manage authentication state globally.
### Method
N/A (Component Setup)
### Endpoint
N/A (Component Setup)
### Parameters
#### Path Parameters
None
#### Query Parameters
None
#### Request Body
None
### Request Example
```tsx Next.js Layout
// app/layout.tsx
import { AuthProvider } from '@/components/AuthProvider';
export default function RootLayout({ children }) {
return (
{children}
);
}
```
```tsx Auth Provider
'use client';
import { createContext, useContext, useEffect, useState } from 'react';
import { OAuth2Client } from '@sonr.io/ui';
const AuthContext = createContext();
export function AuthProvider({ children }) {
const [client] = useState(() => new OAuth2Client({
clientId: process.env.NEXT_PUBLIC_SONR_CLIENT_ID,
redirectUri: process.env.NEXT_PUBLIC_REDIRECT_URI,
}));
// ... authentication logic
return (
{children}
);
}
export const useAuth = () => useContext(AuthContext);
```
### Response
#### Success Response (200)
N/A
#### Response Example
N/A
```
--------------------------------
### Project Testing and Linting Commands (Bash)
Source: https://github.com/sonr-io/motr/blob/main/libs/vault/README.md
These commands use 'pnpm' to manage testing and code quality. 'pnpm test' executes Go tests, while 'pnpm lint' formats the Go code. 'pnpm dev' starts a development server with service worker support for local testing.
```bash
# Run Go tests
pnpm test
# Format Go code
pnpm lint
# Test service worker locally
pnpm dev # Starts dev server with service worker support
```
--------------------------------
### Token Management API
Source: https://github.com/sonr-io/motr/blob/main/docs/guides/signin-with-sonr.mdx
Illustrates how to use the `OAuth2Client` for managing authentication tokens, including checking status, refreshing tokens, and logging out.
```APIDOC
## Token Management
### Description
This section details the methods available on the `OAuth2Client` for managing authentication tokens programmatically. It covers checking authentication status, retrieving access tokens, refreshing tokens, fetching user information, and logging out.
### Method
N/A (Client Methods)
### Endpoint
N/A (Client Methods)
### Parameters
#### Path Parameters
None
#### Query Parameters
None
#### Request Body
None
### Request Example
```typescript Token Management
const client = new OAuth2Client(config);
// Check authentication status
if (client.isAuthenticated()) {
// Get current access token
const accessToken = client.getAccessToken();
// Refresh token before expiry
const newToken = await client.refreshToken();
// Get user information
const userInfo = await client.getUserInfo();
// Revoke tokens on logout
await client.logout();
}
```
### Response
#### Success Response (200)
N/A (Methods return data or perform actions)
#### Response Example
N/A
```
--------------------------------
### Install TypeScript SDK Package
Source: https://github.com/sonr-io/motr/blob/main/README.md
Installs the core Sonr SDK package for use in browser and Node.js environments. This command uses pnpm, a package manager. After installation, the SDK can be imported and used in TypeScript projects.
```bash
# Install
pnpm add @sonr.io/sdk
```
--------------------------------
### Buffer Polyfill for Station Wallet
Source: https://github.com/sonr-io/motr/blob/main/pkgs/sdk/README.md
Provides a polyfill for the Buffer class when using the Station wallet, which relies on WalletConnect v1. This involves installing the 'buffer' package and importing a polyfill script in the application's entry point.
```typescript
// First, install the buffer package
npm install buffer
// Then, create a new file 'polyfill.ts'
import { Buffer } from "buffer";
(window as any).Buffer = Buffer;
// Finally, import the above file in your entry file
import "./polyfill";
```
--------------------------------
### Example Plugin Environment Configuration (JSON)
Source: https://github.com/sonr-io/motr/blob/main/docs/guides/decentralized-web-node.mdx
Illustrates a sample JSON structure for configuring environment variables for a 'motor' type plugin. This includes enclave configuration, chain ID, and log level.
```json
{
"motor_plugin": {
"enclave_config": { ... },
"chain_id": "sonr-testnet-1",
"log_level": "debug"
}
}
```
--------------------------------
### Sonr PKCE Client Configuration
Source: https://github.com/sonr-io/motr/blob/main/docs/guides/signin-with-sonr.mdx
Illustrates enabling Proof Key for Code Exchange (PKCE) for public clients using the `OAuth2Client`. PKCE is enabled by default for public clients, enhancing security by preventing authorization code interception. Requires `@sonr.io/ui`.
```typescript
const client = new OAuth2Client({
clientId: 'public-client',
pkce: true, // Enabled by default for public clients
});
```
--------------------------------
### Install Sonr Vault Plugin using npm, yarn, or pnpm
Source: https://github.com/sonr-io/motr/blob/main/docs/guides/vault-plugin-usage.mdx
Instructions for installing the Sonr Vault Plugin using different package managers. This is a prerequisite for using the plugin in your project.
```bash
npm install @sonr.io/sdk
```
```bash
yarn add @sonr.io/sdk
```
```bash
pnpm add @sonr.io/sdk
```
--------------------------------
### Basic React Implementation for Sign in with Sonr
Source: https://github.com/sonr-io/motr/blob/main/docs/guides/signin-with-sonr.mdx
Provides a basic React component for implementing 'Sign in with Sonr' functionality. It requires a clientId, redirectUri, and a list of scopes for authentication.
```tsx
import { SignInWithSonr } from '@sonr.io/ui';
function App() {
return (
);
}
```
--------------------------------
### Vite Plugin Setup (TypeScript)
Source: https://github.com/sonr-io/motr/blob/main/libs/enclave/README.md
Configures the Vite build tool to include the `@sonr.io/enclave/vite-plugin`. This plugin automates the process of copying the WASM file, setting necessary CORS headers for web workers, and providing a virtual module for the WASM URL, streamlining the integration of the enclave into Vite projects.
```typescript
// vite.config.ts
import { defineConfig } from 'vite';
import { enclavePlugin } from '@sonr.io/enclave/vite-plugin';
export default defineConfig({
plugins: [
enclavePlugin({
wasmPath: 'dist/enclave.wasm',
enableWorker: true,
debug: true,
copyToPublic: true
})
]
});
```
--------------------------------
### Initialize Enclave Worker Client (TypeScript)
Source: https://github.com/sonr-io/motr/blob/main/libs/enclave/README.md
Demonstrates the basic setup for initializing the EnclaveWorkerClient. It shows how to create an instance with persistence enabled and then initialize it with the WASM file path and an account address. It also includes a check for readiness.
```typescript
import { EnclaveWorkerClient } from '@sonr.io/enclave';
// Create worker client with default configuration
const client = new EnclaveWorkerClient({
enablePersistence: true,
debug: false,
});
// Initialize with account address
await client.initialize(
'/enclave.wasm', // Path to WASM file
'sonr1accountaddress...' // Sonr account address
);
// Check if ready
console.log('Vault ready:', client.isReady());
```
--------------------------------
### Sonr OAuth Endpoint Environment Variables
Source: https://github.com/sonr-io/motr/blob/main/docs/guides/signin-with-sonr.mdx
Lists essential environment variables for configuring Sonr's OAuth endpoints. These include client ID, redirect URI, and URLs for authorization, token exchange, and user information.
```env
# OAuth Endpoints
NEXT_PUBLIC_SONR_CLIENT_ID=your-client-id
NEXT_PUBLIC_REDIRECT_URI=http://localhost:3000/callback
NEXT_PUBLIC_AUTH_URL=https://auth.sonr.io/oauth/authorize
NEXT_PUBLIC_TOKEN_URL=https://auth.sonr.io/oauth/token
NEXT_PUBLIC_USERINFO_URL=https://auth.sonr.io/oauth/userinfo
```
--------------------------------
### Run Development Server for Frontend
Source: https://github.com/sonr-io/motr/blob/main/README.md
Starts the development server for the frontend application. This command is typically used during development to serve the TanStack React frontend with hot-reloading capabilities.
```bash
# Start frontend development server
make dev
```
--------------------------------
### Install Motor SDK with npm, pnpm, or yarn
Source: https://github.com/sonr-io/motr/blob/main/docs/guides/motr-usage.mdx
Installs the Motor SDK package using different Node.js package managers. Ensure Node.js 20+ and pnpm are installed for project setup. This package provides the necessary client-side functionalities for interacting with the Motor WASM service worker.
```bash
npm install @sonr.io/sdk
```
```bash
pnpm add @sonr.io/sdk
```
```bash
yarn add @sonr.io/sdk
```
--------------------------------
### Sonr Token Management Operations
Source: https://github.com/sonr-io/motr/blob/main/docs/guides/signin-with-sonr.mdx
Demonstrates essential token management operations using the `OAuth2Client` from `@sonr.io/ui`. This includes checking authentication status, retrieving access tokens, refreshing tokens, fetching user info, and logging out. Assumes a pre-configured client object.
```typescript
const client = new OAuth2Client(config);
// Check authentication status
if (client.isAuthenticated()) {
// Get current access token
const accessToken = client.getAccessToken();
// Refresh token before expiry
const newToken = await client.refreshToken();
// Get user information
const userInfo = await client.getUserInfo();
// Revoke tokens on logout
await client.logout();
}
```
--------------------------------
### Basic Enclave Setup Configuration (JSON)
Source: https://github.com/sonr-io/motr/blob/main/docs/guides/pdk-environment.mdx
Defines the basic structure for MPC enclave configuration, including its ID, key type, threshold, and participants. This is a foundational step for setting up secure multi-party computation environments within the PDK.
```json
{
"enclave": {
"id": "unique-enclave-identifier",
"key_type": "secp256k1",
"threshold": 2,
"participants": [
{ "id": "participant1", "public_key": "..." },
{ "id": "participant2", "public_key": "..." }
]
}
}
```
--------------------------------
### Create and Configure IPFS Client (TypeScript)
Source: https://github.com/sonr-io/motr/blob/main/pkgs/sdk/README.md
Demonstrates how to create an IPFS client using default or custom configurations. It also shows how to dynamically update the client's configuration and retrieve the current settings.
```typescript
import { createIPFSClient, DEFAULT_IPFS_CONFIG } from '@sonr.io/sdk/ipfs'
// Use defaults
const client = await createIPFSClient()
// Custom configuration
const customClient = await createIPFSClient({
gatewayUrl: 'https://my.gateway.com',
apiUrl: 'https://my.api.com:5001',
environment: 'testnet',
timeout: 60000,
maxRetries: 5
})
// Update configuration dynamically
client.updateConfig({
gatewayUrl: 'https://new.gateway.com',
timeout: 30000
})
// Get current configuration
const config = client.getConfig()
console.log('Using gateway:', config.gatewayUrl)
```
--------------------------------
### State Parameter Validation
Source: https://github.com/sonr-io/motr/blob/main/docs/guides/signin-with-sonr.mdx
Provides an example of how to generate and validate the state parameter for CSRF protection during the OAuth flow.
```APIDOC
## State Parameter Prevention
### Description
This example demonstrates the security practice of using a state parameter to prevent Cross-Site Request Forgery (CSRF) attacks. It covers generating a unique state value before initiating the authorization request and validating it upon receiving the callback.
### Method
N/A (Client-side Logic)
### Endpoint
N/A (Client-side Logic)
### Parameters
#### Path Parameters
None
#### Query Parameters
None
#### Request Body
None
### Request Example
```typescript State Validation
// Generate random state
const state = crypto.randomUUID();
sessionStorage.setItem('oauth_state', state);
// Validate on callback
const returnedState = params.get('state');
const savedState = sessionStorage.getItem('oauth_state');
if (returnedState !== savedState) {
throw new Error('State mismatch - possible CSRF attack');
}
```
### Response
#### Success Response (200)
N/A
#### Response Example
N/A
```
--------------------------------
### HTML Button for Sending Transactions
Source: https://github.com/sonr-io/motr/blob/main/docs/quickstart/browser.mdx
Adds a disabled 'Send Transaction' button to the HTML. This button will be enabled after a user's Vault has been successfully claimed, providing a UI element for initiating transactions.
```html
```
--------------------------------
### Use Sonr SDK in Node.js/Build Systems
Source: https://github.com/sonr-io/motr/blob/main/pkgs/sdk/README.md
Demonstrates importing specific Sonr SDK modules for tree-shaking or importing the entire autoloader in a Node.js or build system environment. It shows initialization, WebAuthn registration, creating a Motor plugin, and using codec utilities like Bech32 encoding.
```javascript
// Import specific modules (tree-shakeable)
import { registerWithPasskey, loginWithPasskey } from '@sonr.io/sdk/client/auth';
import { createMotorPlugin } from '@sonr.io/sdk/plugins';
import { bech32 } from '@sonr.io/sdk/codec';
// Or import the entire autoloader
import Sonr from '@sonr.io/sdk/autoloader';
// Initialize and use
async function main() {
// Initialize Sonr
await Sonr.init({
enableMotor: true,
enableVault: false
});
// Use WebAuthn
if (await Sonr.webauthn.isAvailable()) {
const result = await Sonr.webauthn.register({
username: 'bob',
displayName: 'Bob Smith',
rpId: 'example.com',
rpName: 'Example App'
});
console.log('Registered:', result);
}
// Access plugins
const motor = await Sonr.createMotorPlugin();
console.log('Motor plugin ready:', motor);
// Use codec utilities
const address = Sonr.codec.bech32.encode('sonr', [1, 2, 3, 4]);
console.log('Encoded address:', address);
}
main();
```
--------------------------------
### Send Sonr Transaction (TypeScript)
Source: https://github.com/sonr-io/motr/blob/main/docs/quickstart/react.mdx
This TypeScript code illustrates how to send a transaction, transferring Sonr tokens from one wallet to another. It requires two funded wallets and specifies the amount and recipient address.
```typescript
// ... inside your main function
const wallet1 = await sonr.createWallet(); // Fund this from the faucet
const wallet2 = await sonr.createWallet();
console.log(`Sending 1 SNR from ${wallet1.address} to ${wallet2.address}`);
const result = await wallet1.send({
to: wallet2.address,
amount: "1000000usnr", // 1 SNR
});
console.log(`Transaction successful! TxHash: ${result.txhash}`);
```
--------------------------------
### Import Sonr SDK as ES Module and Initialize
Source: https://github.com/sonr-io/motr/blob/main/pkgs/sdk/README.md
Imports the Sonr autoloader as an ES module and initializes it with custom configuration, including enabling specific plugins like Motor and Vault. It then demonstrates accessing environment information and performing WebAuthn login.
```html
```
--------------------------------
### Adding New Components via shadcn CLI (Bash)
Source: https://github.com/sonr-io/motr/blob/main/docs/reference/packages/es.mdx
Provides instructions for adding new UI components using the shadcn CLI within the `packages/ui` directory. This command-line interface helps maintain the centralized component library by ensuring new components are integrated correctly.
```bash
# Navigate to packages/ui
cd packages/ui
# Add a new component
npx shadcn-ui@latest add button
```
--------------------------------
### Load Sonr SDK from CDN and use WebAuthn in Browser
Source: https://github.com/sonr-io/motr/blob/main/pkgs/sdk/README.md
Loads the Sonr autoloader from a CDN and demonstrates how to wait for the SDK to be ready. It then checks for WebAuthn availability and performs user registration using passkeys. This method is suitable for direct browser integration without a build system.
```html
Sonr ES Example
```
--------------------------------
### Sonr Custom Authorization Component
Source: https://github.com/sonr-io/motr/blob/main/docs/guides/signin-with-sonr.mdx
Shows how to use the `` component for custom authorization flows, allowing explicit configuration of authorization URLs, scopes, and CSRF state. Includes event handlers for auth start and errors. Requires `@sonr.io/ui`.
```tsx
console.log('Starting auth...')}
onAuthError={(error) => console.error('Auth failed:', error)}
/>
```
--------------------------------
### JavaScript Event Listener for Sending Transactions
Source: https://github.com/sonr-io/motr/blob/main/docs/quickstart/browser.mdx
Adds an event listener to the 'Send Transaction' button. Upon click, it initiates a transaction using the previously claimed Vault instance, sending a specified amount to a recipient address. Includes output for transaction status and error handling.
```javascript
let vaultInstance;
// After claiming the vault...
vaultInstance = vault;
document.getElementById("send-transaction").disabled = false;
document
.getElementById("send-transaction")
.addEventListener("click", async () => {
const output = document.getElementById("output");
output.innerHTML = "Sending transaction...";
try {
const result = await vaultInstance.send({
to: "snr1..._recipient_address_...",
amount: "1000000usnr", // 1 SNR
});
output.innerHTML = `Transaction successful! TxHash: ${result.txhash}`;
} catch (error) {
output.innerHTML = `Error: ${error.message}`;
}
});
```
--------------------------------
### Build Production Application (Bash)
Source: https://github.com/sonr-io/motr/blob/main/apps/frontend/README.md
Command to create a production-ready build of the frontend application. This optimizes assets and code for deployment.
```bash
pnpm build
```
--------------------------------
### Monorepo Structure Overview
Source: https://github.com/sonr-io/motr/blob/main/docs/reference/packages/pkl.mdx
Visualizes the monorepo directory structure, highlighting the 'packages/ui' directory as the central location for all shared UI components, utilities, and styles.
```text
sonr/
├── packages/
│ └── ui/
│ ├── components/
│ │ └── ui/
│ │ ├── button.tsx
│ │ ├── input.tsx
│ │ └── ...
│ ├── lib/
│ │ └── utils.ts
│ └── styles/
│ └── globals.css
```
--------------------------------
### JavaScript for Sonr Identity and Vault Creation
Source: https://github.com/sonr-io/motr/blob/main/docs/quickstart/browser.mdx
Implements the logic within the identity creation event listener. It uses WebAuthn to create a user credential and then leverages the Sonr SDK to claim a Vault on the network, displaying the Vault's DID upon success. Requires a running Sonr network.
```javascript
// Inside the try block
const credential = await WebAuthn.createCredential({
rp: { name: "Sonr Quickstart" },
user: {
id: new Uint8Array(16), // Should be a unique user ID
name: "user@example.com",
displayName: "Test User",
},
});
output.innerHTML = `Credential created: ${credential.id}`;
const sonr = new Sonr({ httpUrl: "http://localhost:1317" });
const vault = await sonr.claimVault(credential);
output.innerHTML = `Vault claimed! DID: ${vault.did}`;
```
--------------------------------
### Listen for Sonr SDK Ready Event (JavaScript)
Source: https://github.com/sonr-io/motr/blob/main/pkgs/sdk/README.md
This snippet demonstrates how to listen for the `sonr:ready` event, which is fired when the Sonr library is fully loaded and initialized. It accesses the Sonr instance from the event details and logs a ready message to the console. No external dependencies are required beyond a browser environment that supports event listeners.
```javascript
window.addEventListener('sonr:ready', (event) => {
const Sonr = event.detail;
console.log('Sonr is ready!', Sonr);
});
```
--------------------------------
### Initialization Methods
Source: https://github.com/sonr-io/motr/blob/main/libs/enclave/README.md
Methods for initializing and managing the client's readiness and cleanup.
```APIDOC
## Initialization Methods
### Initialize
#### Description
Initializes the Enclave Worker Client with WASM path and account address.
#### Method
`initialize(wasmPath: string, accountAddress: string): Promise`
#### Endpoint
N/A (Method call)
### IsReady
#### Description
Checks if the Enclave Worker Client is ready for operations.
#### Method
`isReady(): boolean`
#### Endpoint
N/A (Method call)
### Cleanup
#### Description
Cleans up resources used by the Enclave Worker Client.
#### Method
`cleanup(): Promise`
#### Endpoint
N/A (Method call)
```
--------------------------------
### Importing UI Components from @sonr.io/ui
Source: https://github.com/sonr-io/motr/blob/main/docs/reference/packages/es.mdx
Demonstrates how to import specific UI components, such as Button and Input, directly from the centralized @sonr.io/ui package. This ensures consistent usage of pre-defined, styled components.
```tsx
import { Button } from "@sonr.io/ui/components/ui/button";
import { Input } from "@sonr.io/ui/components/ui/input";
```
--------------------------------
### Get Payment Status (GET /api/payment/status/:id)
Source: https://github.com/sonr-io/motr/blob/main/libs/vault/README.md
Retrieves the status of a payment transaction using its ID. Returns details like transaction ID, status, confirmations, hash, and timestamp.
```json
{
"transaction_id": "tx_123",
"status": "confirmed",
"confirmations": 12,
"hash": "0x123...",
"timestamp": 1234567890
}
```
--------------------------------
### Import Sonr SDK as ES Module
Source: https://github.com/sonr-io/motr/blob/main/pkgs/sdk/README.md
This method shows how to import the Sonr SDK as an ES Module, allowing for direct initialization with custom configurations and immediate use of its features, such as WebAuthn login.
```APIDOC
## Import as ES Module
### Description
Import the Sonr autoloader directly as an ES Module and initialize it with custom configurations. This example demonstrates enabling specific plugins and performing a WebAuthn login.
### Method
`import` statement for ES Modules.
### Endpoint
`https://unpkg.com/@sonr.io/sdk@latest/dist/autoloader.js`
### Parameters
`Sonr.init(config)`: Initializes the SDK with a configuration object.
- `enableMotor` (boolean): Enable Motor WASM plugin.
- `enableVault` (boolean): Enable Vault client.
- `motor.wasmUrl` (string): Custom URL for the Motor WASM file.
- `vault.endpoint` (string): Endpoint for the Vault client.
### Request Example
```html
```
### Response
None directly from the import. SDK functionality is accessed via the `Sonr` object after initialization.
```
--------------------------------
### GET /health
Source: https://github.com/sonr-io/motr/blob/main/libs/vault/README.md
Health check endpoint to verify the service is running.
```APIDOC
## GET /health
### Description
Health check endpoint to verify the service is running.
### Method
GET
### Endpoint
/health
### Response
#### Success Response (200)
- **status** (string) - Indicates the health status of the service, expected to be 'ok'.
- **timestamp** (integer) - The Unix timestamp of when the health check was performed.
- **version** (string) - The current version of the service.
#### Response Example
{
"status": "ok",
"timestamp": 1234567890,
"version": "1.0.0"
}
```
--------------------------------
### GET /status
Source: https://github.com/sonr-io/motr/blob/main/libs/vault/README.md
Detailed service status endpoint providing operational metrics.
```APIDOC
## GET /status
### Description
Detailed service status endpoint providing operational metrics.
### Method
GET
### Endpoint
/status
### Response
#### Success Response (200)
- **vault** (string) - The current status of the vault service (e.g., 'active').
- **uptime** (integer) - The duration in seconds the service has been running.
- **requests_handled** (integer) - The total number of requests processed by the service.
- **cache_size** (string) - The current size of the service's cache (e.g., '2.5MB').
#### Response Example
{
"vault": "active",
"uptime": 3600,
"requests_handled": 1234,
"cache_size": "2.5MB"
}
```