### Setup: Clone and Install Dependencies (Shell) Source: https://github.com/blinkbitcoin/dev.blink.sv/blob/main/docs/self-host/b-deployment/d-mobile-wallet.md These commands clone the Blink mobile wallet repository from GitHub, change the current directory into the project folder, and install the necessary Node.js dependencies using Yarn. Ensure you have Yarn and Git installed and have completed the React Native environment setup prerequisite. ```Shell $ git clone git@github.com/GaloyMoney/blink-mobile.git ``` ```Shell $ cd blink-mobile ``` ```Shell $ yarn install ``` -------------------------------- ### Run Blink Dev Setup - Shell Source: https://github.com/blinkbitcoin/dev.blink.sv/blob/main/docs/self-host/b-deployment/b-backend-servers.md Command to start the local development environment for Blink, including backend servers and dependencies, using the buck2 build tool. ```Shell buck2 run //dev:up ``` -------------------------------- ### Example Oauth2-Token Header String Source: https://github.com/blinkbitcoin/dev.blink.sv/blob/main/docs/api/oauth2.md Provides a simple string example demonstrating the format of the 'Oauth2-Token' header value used for authentication with Blink APIs. ```text "Oauth2-Token" "ory_at_..." ``` -------------------------------- ### Example Staging OAuth2 Authorization URL Source: https://github.com/blinkbitcoin/dev.blink.sv/blob/main/docs/api/oauth2.md An example URL constructed to initiate the authorization code flow on the staging environment. It includes required parameters like client ID, redirect URI, requested scopes, and a state parameter for security. ```Text https://oauth.staging.blink.sv/oauth2/auth?response_type=code&client_id=&redirect_uri=https%3A%2F%2Fyourapp.com%2Fcallback&scope=read+receive+write&state= ``` -------------------------------- ### Running: Start React Native Bundler (Shell) Source: https://github.com/blinkbitcoin/dev.blink.sv/blob/main/docs/self-host/b-deployment/d-mobile-wallet.md This command starts the Metro bundler, which is required to serve the JavaScript code to the React Native application running on a simulator or device. This command should typically be run in a separate terminal window and kept running while developing. ```Shell $ yarn start ``` -------------------------------- ### Run Blink Pay Locally Source: https://github.com/blinkbitcoin/dev.blink.sv/blob/main/docs/self-host/b-deployment/c-blink-pay.md Installs project dependencies and starts the Blink Pay application in development mode. Requires setting the NEXT_PUBLIC_GRAPHQL_HOSTNAME environment variable in a .env.local file. ```Shell yarn install yarn dev ``` -------------------------------- ### Start Local Development Server Source: https://github.com/blinkbitcoin/dev.blink.sv/blob/main/README.md Starts the Docusaurus local development server. This command typically opens the site in a browser and provides live reloading for most changes. ```Shell yarn start ``` -------------------------------- ### Running: Launch on iOS Simulator/Device (Shell) Source: https://github.com/blinkbitcoin/dev.blink.sv/blob/main/docs/self-host/b-deployment/d-mobile-wallet.md This command builds and launches the React Native application on an attached iOS device or simulator. Ensure you have Xcode installed and configured for iOS development. ```Shell $ yarn ios ``` -------------------------------- ### Example Callback URL with Authorization Code Source: https://github.com/blinkbitcoin/dev.blink.sv/blob/main/docs/api/oauth2.md An example of the URL your application's callback endpoint receives after the user grants permission. It contains the authorization code in the 'code' query parameter, along with the granted 'scope' and the original 'state'. ```Text https://yourapp.com/callback?code=ory_ac_AUTHORIZATION_CODE&scope=read+receive+write&state= ``` -------------------------------- ### Clone Repository and Install Project Dependencies Source: https://github.com/blinkbitcoin/dev.blink.sv/blob/main/README.md Clones the Blink Developer Documentation repository from GitHub, changes into the project directory, and installs the project's Node.js dependencies using Yarn. ```Shell git clone https://github.com/blinkbitcoin/dev.blink.sv cd dev.blink.sv yarn ``` -------------------------------- ### Running: Launch on Android Emulator/Device (Shell) Source: https://github.com/blinkbitcoin/dev.blink.sv/blob/main/docs/self-host/b-deployment/d-mobile-wallet.md This command builds and launches the React Native application on an attached Android device or running emulator. Ensure you have Android Studio installed and configured for Android development. ```Shell $ yarn android ``` -------------------------------- ### Build Blink Pay for Production Source: https://github.com/blinkbitcoin/dev.blink.sv/blob/main/docs/self-host/b-deployment/c-blink-pay.md Installs project dependencies and builds the Blink Pay application for production deployment. The output is optimized and placed in a build folder. ```Shell yarn install yarn build ``` -------------------------------- ### Install Dependencies on Linux Source: https://github.com/blinkbitcoin/dev.blink.sv/blob/main/README.md Installs required dependencies (git, nodejs, yarn) on a Linux system using the apt package manager. Requires root privileges. ```Shell sudo apt install -y git nodejs yarn ``` -------------------------------- ### Authenticating Blink API WebSocket Connection Source: https://github.com/blinkbitcoin/dev.blink.sv/blob/main/docs/api/authentication-examples.md Shows how to establish a WebSocket connection to the Blink GraphQL endpoint and authenticate by including the API key in the `connection_init` payload. It also includes an example of subscribing to updates after a successful connection acknowledgment. ```javascript // Using a WebSocket client const ws = new WebSocket('wss://ws.blink.sv/graphql', 'graphql-transport-ws'); // Connection initialization with API key ws.onopen = () => { ws.send(JSON.stringify({ type: 'connection_init', payload: { 'X-API-KEY': 'blink_your_api_key_here' } })); }; // Handle connection acknowledgment ws.onmessage = (event) => { const message = JSON.parse(event.data); if (message.type === 'connection_ack') { console.log('Connection established successfully'); // Subscribe to updates after connection is established ws.send(JSON.stringify({ id: '1', type: 'subscribe', payload: { query: ` subscription { myUpdates { update { ... on LnUpdate { transaction { initiationVia { ... on InitiationViaLn { paymentHash } } direction } } } } } ` } })); } }; ``` -------------------------------- ### Example Access Token Response Source: https://github.com/blinkbitcoin/dev.blink.sv/blob/main/docs/api/oauth2.md Shows the expected JSON format of the response received after successfully exchanging an authorization code for an access token. Includes the access token, expiration time, scope, and token type. ```json { "access_token": "ory_at_...", "expires_in": 3599, "scope": "read receive write", "token_type": "bearer" } ``` -------------------------------- ### Install Websocat on Linux (Bash) Source: https://github.com/blinkbitcoin/dev.blink.sv/blob/main/docs/api/websocket.md Command to install the websocat tool on Linux systems using cargo, assuming a Rust toolchain is already installed. ```bash cargo install websocat ``` -------------------------------- ### Install Dependencies on MacOS Source: https://github.com/blinkbitcoin/dev.blink.sv/blob/main/README.md Installs required dependencies (git, node, yarn) on a MacOS system using the Homebrew package manager. ```Shell brew install git node yarn ``` -------------------------------- ### Example API Request with JavaScript Fetch (Server-Side) Source: https://github.com/blinkbitcoin/dev.blink.sv/blob/main/docs/api/auth.mdx Provides a JavaScript example using the Fetch API to make an authenticated GraphQL POST request. It includes a warning that this code should only be used in a secure server-side environment due to the API key. ```javascript // This should only be used in a secure server-side environment, not in browser code const response = await fetch('https://api.blink.sv/graphql', { method: 'POST', headers: { 'Content-Type': 'application/json', 'X-API-KEY': 'blink_your_api_key_here' }, body: JSON.stringify({ query: 'query me { me { defaultAccount { wallets { id walletCurrency }}}}' }) }); ``` -------------------------------- ### Install Websocat on MacOS (Bash) Source: https://github.com/blinkbitcoin/dev.blink.sv/blob/main/docs/api/websocket.md Command to install the websocat tool on MacOS systems using brew (Homebrew package manager). ```bash brew install websocat ``` -------------------------------- ### Authenticating Blink API with cURL Source: https://github.com/blinkbitcoin/dev.blink.sv/blob/main/docs/api/authentication-examples.md Demonstrates how to make a POST request to the Blink GraphQL API using cURL, including setting the `Content-Type` and `X-API-KEY` headers and providing a GraphQL query in the request body. ```bash curl --request POST \ --url 'https://api.blink.sv/graphql' \ --header 'Content-Type: application/json' \ --header 'X-API-KEY: blink_your_api_key_here' \ --data '{"query":"query me { me { defaultAccount { wallets { id walletCurrency }}}}}}' ``` -------------------------------- ### Authenticating Blink API with Python Requests Source: https://github.com/blinkbitcoin/dev.blink.sv/blob/main/docs/api/authentication-examples.md Shows a Python function using the `requests` library to perform a POST request to the Blink GraphQL API. It demonstrates setting headers (`Content-Type`, `X-API-KEY`), defining the GraphQL query, and handling the API response. ```python import requests def get_wallet_data(api_key): url = "https://api.blink.sv/graphql" headers = { "Content-Type": "application/json", "X-API-KEY": api_key } query = """ query me { me { defaultAccount { wallets { id walletCurrency } } } } """ payload = {"query": query} response = requests.post(url, json=payload, headers=headers) if response.status_code == 200: return response.json() else: raise Exception(f"Query failed with status code {response.status_code}: {response.text}") ``` -------------------------------- ### Configure next-auth for Blink OAuth Source: https://github.com/blinkbitcoin/dev.blink.sv/blob/main/docs/api/oauth2.md Provides a configuration example for integrating Blink OAuth as a custom provider within the next-auth library. It defines the provider details and callback functions for handling JWT and session data. ```typescript export const authOptions: NextAuthOptions = { providers: [ { id: "blink", clientId: env.CLIENT_ID, clientSecret: env.CLIENT_SECRET, wellKnown: `${env.HYDRA_PUBLIC}/.well-known/openid-configuration`, authorization: { params: { scope: "read" }, }, idToken: false, name: "Blink", type, profile(profile) { return { id: profile.sub, } }, }, ], debug: process.env.NODE_ENV === "development", secret: env.NEXTAUTH_SECRET, callbacks: { async jwt({ token, account, profile }) { if (account) { token.accessToken = account.access_token token.expiresAt = account.expires_at token.refreshToken = account.refresh_token token.id = profile?.id } return token }, async session({ session, token }) { if ( !token.accessToken || !token.sub || typeof token.accessToken !== "string" || typeof token.sub !== "string" ) { throw new Error("Invalid token") } const res = await fetchUserData({ token: token.accessToken }) if (!(res instanceof Error)) { session.userData = res.data } session.sub = token.sub session.accessToken = token.accessToken return session }, }, } ``` -------------------------------- ### Generating API Reference Formats Without Nix Source: https://github.com/blinkbitcoin/dev.blink.sv/blob/main/README-api-reference-generator.md If not using Nix, first make the script files executable, then run the desired generation script directly. This requires manually installing Node.js, npm, git, and curl. ```bash # Make scripts executable chmod +x scripts/generate-api-reference-*.sh # Generate all formats ./scripts/generate-api-reference-combined.sh # Or generate specific formats ./scripts/generate-api-reference-for-llm.sh # JSON/YAML formats ./scripts/generate-api-reference-markdown.sh # Markdown documentation ./scripts/generate-api-reference-openapi.sh # OpenAPI format ``` -------------------------------- ### Starting Electrum Wallet with Signet Support Source: https://github.com/blinkbitcoin/dev.blink.sv/blob/main/docs/self-host/b-deployment/g-signet.md Command to launch the Electrum wallet application with the --signet flag enabled, allowing it to connect to the Bitcoin Signet network instead of mainnet or testnet. This is required to use Electrum with Signet. ```Shell electrum-4.4.0-x86_64.AppImage --signet ``` -------------------------------- ### JavaScript/TypeScript Header Object Example Source: https://github.com/blinkbitcoin/dev.blink.sv/blob/main/docs/api/oauth2.md Shows how to conditionally add the 'Oauth2-Token' header to a JavaScript/TypeScript headers object based on whether a token is available. ```typescript headers: { ...(options?.token ? { ["Oauth2-Token"]: options.token } : {}), }, ``` -------------------------------- ### Example API Request with Curl (Bash) Source: https://github.com/blinkbitcoin/dev.blink.sv/blob/main/docs/api/auth.mdx Demonstrates how to make an authenticated GraphQL POST request using curl, including setting the `X-API-KEY` header and providing a query in the body. ```bash curl --request POST \ --url 'https://api.blink.sv/graphql' \ --header 'Content-Type: application/json' \ --header 'X-API-KEY: blink_your_api_key_here' \ --data '{"query":"query me { me { defaultAccount { wallets { id walletCurrency }}}}"}' ``` -------------------------------- ### Running Galoy Admin Panel Locally (Shell) Source: https://github.com/blinkbitcoin/dev.blink.sv/blob/main/docs/self-host/b-deployment/f-admin-panel.md Instructions to set up and run the Galoy Admin Panel locally for development. Requires yarn and sets the GraphQL API endpoint environment variable before starting the application. ```Shell yarn install export GRAPHQL_URI=`https://graphql-admin.domain.com` yarn start ``` -------------------------------- ### Staging OAuth2 Authorization Endpoint URL Source: https://github.com/blinkbitcoin/dev.blink.sv/blob/main/docs/api/oauth2.md The URL for initiating the OAuth2 authorization flow on the staging Blink environment. Use this endpoint for testing and development. ```Text https://oauth.staging.blink.sv/oauth2/auth ``` -------------------------------- ### Authenticating Blink API with JavaScript Fetch Source: https://github.com/blinkbitcoin/dev.blink.sv/blob/main/docs/api/authentication-examples.md Provides an asynchronous JavaScript function using the Fetch API to send a POST request to the Blink GraphQL endpoint. It includes setting necessary headers (`Content-Type`, `X-API-KEY`) and sending a GraphQL query in the request body. ```javascript const fetchWalletData = async (apiKey) => { try { const response = await fetch('https://api.blink.sv/graphql', { method: 'POST', headers: { 'Content-Type': 'application/json', 'X-API-KEY': apiKey }, body: JSON.stringify({ query: ` query me { me { defaultAccount { wallets { id walletCurrency } } } } ` }) }); const data = await response.json(); return data; } catch (error) { console.error('Error fetching wallet data:', error); throw error; } }; ``` -------------------------------- ### Blink OAuth2 Authorization Endpoint URL Source: https://github.com/blinkbitcoin/dev.blink.sv/blob/main/docs/api/oauth2.md The URL for initiating the OAuth2 authorization flow on the production Blink environment. Applications redirect users to this endpoint. ```Text https://oauth.blink.sv/oauth2/auth ``` -------------------------------- ### Authenticating Blink API with Node.js Axios Source: https://github.com/blinkbitcoin/dev.blink.sv/blob/main/docs/api/authentication-examples.md Presents an asynchronous Node.js function using the Axios library to make a POST request to the Blink GraphQL endpoint. It illustrates setting headers (`Content-Type`, `X-API-KEY`) and sending a GraphQL query in the request body. ```javascript const axios = require('axios'); async function getWalletData(apiKey) { try { const response = await axios({ url: 'https://api.blink.sv/graphql', method: 'post', headers: { 'Content-Type': 'application/json', 'X-API-KEY': apiKey }, data: { query: ` query me { me { defaultAccount { wallets { id walletCurrency } } } } ` } }); return response.data; } catch (error) { console.error('Error fetching wallet data:', error); throw error; } } ``` -------------------------------- ### Staging OAuth2 Token Endpoint URL Source: https://github.com/blinkbitcoin/dev.blink.sv/blob/main/docs/api/oauth2.md The URL for exchanging the authorization code for an access token on the staging Blink environment. Use this endpoint for testing token exchange. ```Text https://oauth.staging.blink.sv/oauth2/token ``` -------------------------------- ### Example Webhook Payload: receive.lightning Source: https://github.com/blinkbitcoin/dev.blink.sv/blob/main/docs/api/webhooks.md This JSON snippet shows the structure and content of the payload sent by the Blink API for a `receive.lightning` webhook event. It includes details about the account, wallet, transaction, amounts, currencies, and status. ```json { "accountId":"1580f7f2-0e4c-4187-b97f-9ed6eaff8f55", "eventType":"receive.lightning", "walletId":"21087d73-80d8-4556-a73a-e1b6b0657784", "transaction":{ "createdAt":"2023-11-21T01:49:38.375Z", "id":"655cd1926445716f60b89418", "initiationVia":{ "paymentHash":"bf6b61f814b2e2284f5cbb7c9f9e67887018ffe3f53bedb9b70dec0a15ebca1c", "pubkey":"d75a81acb76fd85dafe491799bbd1940a25e8a8fa776cacccda4ee8444555e3e", "type":"lightning" }, "memo":null, "settlementAmount":2707, "settlementCurrency":"BTC", "settlementDisplayAmount":"1.00", "settlementDisplayFee":"0.00", "settlementDisplayPrice":{ "base":"36941263391", "displayCurrency":"USD", "offset":"12", "walletCurrency":"BTC" }, "settlementFee":0, "settlementVia":{ "type":"lightning" }, "status":"success", "walletId":"21087d73-80d8-4556-a73a-e1b6b0657784" } } ``` -------------------------------- ### Make Authenticated API Request using curl Source: https://github.com/blinkbitcoin/dev.blink.sv/blob/main/docs/api/oauth2.md Illustrates how to use the obtained access token to authenticate API requests. The token is included in the 'Oauth2-Token' header for authentication. ```bash ACCESS_TOKEN= curl -sS --request POST --header 'content-type: application/json' \ --header 'Oauth2-Token: $ACCESS_TOKEN' \ --url 'https://api.blink.sv/graphql' \ --data '{"query":"query me { me { defaultAccount { wallets { id walletCurrency }}}}", "variables":{}}' ``` -------------------------------- ### Variables for Initial Transaction Query - JSON Source: https://github.com/blinkbitcoin/dev.blink.sv/blob/main/docs/api/pagination.md JSON variables used in the initial GraphQL request to fetch the first 2 transactions for the default account, starting from the beginning (`after: null`). ```json { "first": 2, "after": null } ``` -------------------------------- ### Blink API GraphQL Query Body for Postman Source: https://github.com/blinkbitcoin/dev.blink.sv/blob/main/docs/api/authentication-examples.md Provides the JSON structure for the request body when making a GraphQL POST request to the Blink API using a tool like Postman. It contains the `query` field with the GraphQL query string. ```json { "query": "query me { me { defaultAccount { wallets { id walletCurrency }}}}" } ``` -------------------------------- ### Exchange Authorization Code for Access Token using curl Source: https://github.com/blinkbitcoin/dev.blink.sv/blob/main/docs/api/oauth2.md Demonstrates how to make a POST request to the token endpoint using curl to exchange an authorization code for an access token. Requires the authorization code, client ID, client secret, and redirect URI. ```bash # set the variables AUTHORIZATION_CODE= YOUR_CALLBACK_URL= YOUR_CLIENT_ID= YOUR_CLIENT_SECRET= curl -X POST \ -u "$YOUR_CLIENT_ID:$YOUR_CLIENT_SECRET" \ -d "grant_type=authorization_code" \ -d "code=$AUTHORIZATION_CODE" \ -d "redirect_uri=$YOUR_CALLBACK_URL" \ https://oauth.blink.sv/oauth2/token ``` -------------------------------- ### Blink OAuth2 Token Endpoint URL Source: https://github.com/blinkbitcoin/dev.blink.sv/blob/main/docs/api/oauth2.md The URL for exchanging the authorization code for an access token on the production Blink environment. Applications make a server-side request to this endpoint. ```Text https://oauth.blink.sv/oauth2/token ``` -------------------------------- ### Postman Subscribe to Price Updates (JSON) Source: https://github.com/blinkbitcoin/dev.blink.sv/blob/main/docs/api/websocket.md Provides an example of a subscribe message payload for requesting real-time price updates via the WebSocket connection in Postman. It includes the subscription query and variables. ```json { "id": "1", "type": "subscribe", "payload": { "query": "subscription { price( input: { amount: 100 amountCurrencyUnit: BTCSAT priceCurrencyUnit: USDCENT } ) { errors { message } price { base offset currencyUnit } }}", "variables": {} } } ``` -------------------------------- ### Terraform Configuration for Hydra OAuth2 Client (Dashboard) Source: https://github.com/blinkbitcoin/dev.blink.sv/blob/main/docs/api/oauth2.md Shows a Terraform configuration block using the `hydra_oauth2_client` resource to define an OAuth2 client for the Blink API Dashboard. Specifies grant types, response types, scopes, and redirect URIs. ```terraform resource "hydra_oauth2_client" "api_dashboard" { client_name = "Blink Api Dashboard" grant_types = ["authorization_code"] response_types = ["code", "id_token"] token_endpoint_auth_method = "client_secret_basic" scopes = ["read", "write"] redirect_uris = [local.api_dashboard_hydra_redirect_uri] skip_consent = true } ``` -------------------------------- ### Configuring Hydra OAuth2 Client for Blink PoS (Terraform) Source: https://github.com/blinkbitcoin/dev.blink.sv/blob/main/docs/api/oauth2.md This Terraform resource block defines an OAuth2 client within Hydra for the Blink PoS application. It specifies the client name, allowed grant and response types, authentication method, requested scopes, and the redirect URIs for the authorization callback. ```Terraform resource "hydra_oauth2_client" "galoy_pay" { client_name = "Blink POS" grant_types = ["authorization_code"] response_types = ["code", "id_token"] token_endpoint_auth_method = "client_secret_basic" scopes = ["read"] redirect_uris = [for host in local.galoy_pay_hosts : "https://${host}/api/auth/callback/blink"] skip_consent = true } ``` -------------------------------- ### Creating OpenAI Assistant with Blink API Schema File (JavaScript) Source: https://github.com/blinkbitcoin/dev.blink.sv/blob/main/docs/api/llm-api-reference.md Shows how to download the Blink GraphQL API schema, save it to a file, and create an OpenAI Assistant that uses this file as context to help users interact with the Blink GraphQL API. ```javascript const { OpenAI } = require('openai'); const fs = require('fs'); const path = require('path'); const openai = new OpenAI({ apiKey: process.env.OPENAI_API_KEY, }); async function createAssistantWithBlinkAPI() { // Download the API schema const response = await fetch('https://dev.blink.sv/reference/graphql-api-for-llm.json'); const apiSchema = await response.json(); // Save it to a file fs.writeFileSync('blink-api-schema.json', JSON.stringify(apiSchema)); // Create an assistant with the API schema as a file const assistant = await openai.beta.assistants.create({ name: "Blink API Assistant", instructions: "You are an assistant that helps users interact with the Blink GraphQL API. Use the provided API schema to answer questions and generate code examples.", model: "gpt-4-turbo", tools: [{ type: "code_interpreter" }], file_ids: [ // Upload the API schema file to OpenAI and get its file ID await openai.files.create({ file: fs.createReadStream(path.resolve('blink-api-schema.json')), purpose: 'assistants', }).then(file => file.id) ] }); console.log("Assistant created with ID:", assistant.id); return assistant; } createAssistantWithBlinkAPI(); ``` -------------------------------- ### Querying User Information with GraphQL Source: https://github.com/blinkbitcoin/dev.blink.sv/blob/main/docs/api/graphql-intro.md Demonstrates the basic structure of the `me` query in GraphQL, used to retrieve information about the authenticated user. Placeholder comment indicates where specific user fields would be added. ```GraphQL me { # Query fields related to user information } ``` -------------------------------- ### Build Static Website Source: https://github.com/blinkbitcoin/dev.blink.sv/blob/main/README.md Generates the static content for the website into the `build` directory. The output can be served by any static file hosting service. ```Shell yarn build ``` -------------------------------- ### Generating API Reference Formats with Nix Source: https://github.com/blinkbitcoin/dev.blink.sv/blob/main/README-api-reference-generator.md After entering the Nix shell, use these helper commands to generate the API reference files. You can generate all formats at once or select specific ones like JSON/YAML, Markdown, or OpenAPI. ```bash # Generate all formats generate-all # Or generate specific formats generate-json # JSON/YAML formats generate-md # Markdown documentation generate-openapi # OpenAPI format ``` -------------------------------- ### Entering the Nix Development Environment Source: https://github.com/blinkbitcoin/dev.blink.sv/blob/main/README-api-reference-generator.md Use this command to enter the isolated Nix shell environment, which provides all necessary dependencies for running the API reference generation scripts. ```bash nix-shell ``` -------------------------------- ### Run Prettier Formatting - Shell Source: https://github.com/blinkbitcoin/dev.blink.sv/blob/main/docs/self-host/b-deployment/b-backend-servers.md Executes the Prettier code formatter via yarn to format all files in the current directory and its subdirectories, ensuring consistent code style. ```Shell $ yarn prettier -w . ``` -------------------------------- ### Using Blink GraphQL API Schema with LangChain Agent (Python) Source: https://github.com/blinkbitcoin/dev.blink.sv/blob/main/docs/api/llm-api-reference.md Demonstrates how to load the Blink GraphQL API schema from a URL, create a LangChain Tool that references the schema, and initialize a LangChain agent with the schema provided in the context for interacting with the API. ```python from langchain.agents import Tool from langchain.agents import initialize_agent from langchain.llms import OpenAI import requests import json # Load the API schema api_schema_url = "https://dev.blink.sv/reference/graphql-api-for-llm.json" api_schema = json.loads(requests.get(api_schema_url).text) # Create a tool that provides the API schema as context tools = [ Tool( name="BlinkAPI", func=lambda _: "API schema is already provided in your context", description="Blink GraphQL API schema information" ) ] # Initialize the agent with the API schema in its context llm = OpenAI(temperature=0) agent = initialize_agent(tools, llm, agent="zero-shot-react-description", verbose=True) # Use the agent with the API schema as context agent.run( input="How do I create a lightning invoice using the Blink API?", context={"api_schema": api_schema} ) ``` -------------------------------- ### Generating Blink API Reference Schemas (Bash) Source: https://github.com/blinkbitcoin/dev.blink.sv/blob/main/docs/api/llm-api-reference.md Provides the command to manually run the script that generates all machine-readable formats of the Blink GraphQL API schema. ```bash ./scripts/generate-api-reference-combined.sh ``` -------------------------------- ### Using the X-API-KEY Header (Bash/Text) Source: https://github.com/blinkbitcoin/dev.blink.sv/blob/main/docs/api/auth.mdx All authenticated API requests to Blink require the `X-API-KEY` header with your API key. ```bash X-API-KEY: blink_... ``` -------------------------------- ### Manually Deploy Changes (SSH) Source: https://github.com/blinkbitcoin/dev.blink.sv/blob/main/README.md Deploys the built website to the `gh-pages` branch using Yarn and SSH for authentication. This method is typically used by repository administrators. ```Shell USE_SSH=true yarn deploy ``` -------------------------------- ### Querying Wallets for Default Account with GraphQL Source: https://github.com/blinkbitcoin/dev.blink.sv/blob/main/docs/api/graphql-intro.md Shows the nested GraphQL query structure to access the `wallets` associated with the `defaultAccount`, which is itself nested under the `me` query. This allows drilling down into wallet-specific data. Placeholder comment indicates where specific wallet fields would be added. ```GraphQL me { defaultAccount { wallets { # Query fields related to wallets } } } ``` -------------------------------- ### Manually Deploy Changes (Non-SSH) Source: https://github.com/blinkbitcoin/dev.blink.sv/blob/main/README.md Deploys the built website to the `gh-pages` branch using Yarn, requiring the GitHub username to be provided. This method is an alternative to SSH deployment. ```Shell GIT_USER= yarn deploy ``` -------------------------------- ### Sample Response for Initial Transaction Query - JSON Source: https://github.com/blinkbitcoin/dev.blink.sv/blob/main/docs/api/pagination.md Sample JSON response showing the structure of the data returned by the GraphQL query for the first page of transactions. Includes `pageInfo` with `endCursor` and `hasNextPage`, and `edges` containing transaction details. ```json { "data": { "me": { "id": "dd3771d0-66b2-4b28-8757-b1a5db0f8fcf", "defaultAccount": { "transactions": { "pageInfo": { "endCursor": "653787e933905fc03c13e2bc", "hasNextPage": true }, "edges": [ { "cursor": "6538bda9491e13fd6416b5f3", "node": { "direction": "RECEIVE", "settlementCurrency": "USD", "settlementDisplayAmount": "0.01", "status": "SUCCESS", "createdAt": 1698217385 } }, { "cursor": "6538b68c491e13fd6416722d", "node": { "direction": "RECEIVE", "settlementCurrency": "USD", "settlementDisplayAmount": "1.00", "status": "SUCCESS", "createdAt": 1698215564 } }, { "cursor": "653787e933905fc03c13e2bc", "node": { "direction": "RECEIVE", "settlementCurrency": "BTC", "settlementDisplayAmount": "0.47", "status": "SUCCESS", "createdAt": 1698138089 } } ] } } } } } ``` -------------------------------- ### Configure LNbits .env for Blink Funding Source Source: https://github.com/blinkbitcoin/dev.blink.sv/blob/main/docs/examples/lnbits-funding-source.md This snippet shows the required environment variables to set in the LNbits .env file to configure Blink as the backend wallet. It specifies the wallet class, the Blink API and WebSocket endpoints, and a placeholder for the user's API key. ```Environment Configuration LNBITS_BACKEND_WALLET_CLASS=BlinkWallet BLINK_API_ENDPOINT=https://api.blink.sv/graphql BLINK_WS_ENDPOINT=wss://ws.blink.sv/graphql BLINK_TOKEN= ``` -------------------------------- ### Authenticating with X-API-KEY Header Source: https://github.com/blinkbitcoin/dev.blink.sv/blob/main/docs/api/graphql-intro.md Shows the required HTTP header format for authenticating API calls using an API key. The header name is `X-API-KEY`, and the value is the user's specific API key. ```HTTP Header X-API-KEY: blink_your_api_key_here ``` -------------------------------- ### Sample Response for Paginated Transaction Query - JSON Source: https://github.com/blinkbitcoin/dev.blink.sv/blob/main/docs/api/pagination.md Sample JSON response showing the structure of the data returned by the GraphQL query for the second page of transactions, demonstrating the use of the `after` cursor for pagination. ```json { "data": { "me": { "id": "dd3771d0-66b2-4b28-8757-b1a5db0f8fcf", "defaultAccount": { "transactions": { "pageInfo": { "endCursor": "653787c033905fc03c13e0a3", "hasNextPage": true }, "edges": [ { "cursor": "653787e933905fc03c13e286", "node": { "direction": "SEND", "settlementCurrency": "BTC", "settlementDisplayAmount": "-0.47", "status": "SUCCESS", "createdAt": 1698138089 } }, { "cursor": "653787c033905fc03c13e0a3", "node": { "direction": "SEND", "settlementCurrency": "BTC", "settlementDisplayAmount": "-0.47", "status": "SUCCESS", "createdAt": 1698138048 } } ] } } } } } ``` -------------------------------- ### Connect to WebSocket and Subscribe to Updates (Authenticated) Source: https://github.com/blinkbitcoin/dev.blink.sv/blob/main/docs/api/websocket.md Demonstrates connecting to the WebSocket endpoint using `websocat` and subscribing to the `myUpdates` and `lnInvoicePaymentStatus` GraphQL subscriptions with authentication. Shows the connection handshake, authentication payload, and subsequent data payloads. ```bash websocat ${websocket_endpoint} -H 'Sec-WebSocket-Protocol: graphql-transport-ws' -v [INFO websocat::lints] Auto-inserting the line mode [INFO websocat::stdio_threaded_peer] get_stdio_peer (threaded) [INFO websocat::ws_client_peer] get_ws_client_peer [INFO websocat::ws_client_peer] Connected to ws { "type": "connection_init", "payload": { "X-API-KEY": "blink_xxxx" } } {"type":"connection_ack"} [INFO websocat::ws_peer] Received WebSocket ping { "id": "1", "type": "subscribe", "payload": { "query": "subscription { myUpdates { update { ... on LnUpdate { transaction { initiationVia { ... on InitiationViaLn { paymentHash } } direction } } } } }", "variables": {} }} {"id":"1","type":"next","payload":{"data":{"myUpdates":{"update":{}}}}} {"id":"1","type":"next","payload":{"data":{"myUpdates":{"update":{}}}}} [INFO websocat::ws_peer] Received WebSocket ping {"id":"1","type":"next","payload":{"data":{"myUpdates":{"update":{}}}}} {"id":"1","type":"next","payload":{"data":{"myUpdates":{"update":{}}}}} { "id": "2", "type": "subscribe", "payload": { "query": "subscription LnInvoicePaymentStatus($input: LnInvoicePaymentStatusInput!) { lnInvoicePaymentStatus(input: $input) { status errors { code message path } }}", "variables": { "input": { "paymentRequest": "lntbs1220n1pjklpx5pp5wn0zrhygl8u8p7k5nggsa3hcj9htkk0t8df5mxm2hrumk5gedgwsdq0w3jhxapqd4jk6mccqzpuxqyz5vqsp566v7qag22wnl5spf3zhrfruxyaek5m3uv5pu4dzpwmffk6adykpq9qyyssq62exrk3zcwfeh9c0hnhlpv9lmn33fryz4l9acmq79myp57lgj29390tucf4rycxn3zxtre8fzuzs6acu0w4umuetu9zr04zusa56duspsmsxv5" } } }} {"id":"2","type":"next","payload":{"data":{"lnInvoicePaymentStatus":{"status":"PAID","errors":[]}}}} [INFO websocat::ws_peer] Received WebSocket ping ``` -------------------------------- ### Configure LND Debug Level - Configuration File Source: https://github.com/blinkbitcoin/dev.blink.sv/blob/main/docs/self-host/b-deployment/b-backend-servers.md Sets the debug level for LND to 'critical' in the lnd.conf file to reduce disk usage from logs, which can help improve integration test performance. ```Configuration File debuglevel=critical ``` -------------------------------- ### Reinstall Node Modules Source: https://github.com/blinkbitcoin/dev.blink.sv/blob/main/README.md Cleans the Yarn cache, removes the existing `node_modules` directory, and reinstalls all project dependencies using Yarn. Useful for resolving dependency issues. ```Shell yarn cache clean rm -rf node_modules yarn install ``` -------------------------------- ### Connect with Websocat (Bash) Source: https://github.com/blinkbitcoin/dev.blink.sv/blob/main/docs/api/websocket.md Bash command using websocat to establish a WebSocket connection to the specified endpoint, including setting the Sec-WebSocket-Protocol header. ```bash websocat ${websocket_endpoint} -H 'Sec-WebSocket-Protocol: graphql-transport-ws' -v ``` -------------------------------- ### Sample GraphQL Response with Proof Details (JSON) Source: https://github.com/blinkbitcoin/dev.blink.sv/blob/main/docs/api/proof-of-payment.md This is a sample JSON response demonstrating the structure of the data returned by the `PaymentsWithProof` GraphQL query. It shows how the `paymentRequest`, `paymentHash`, and `preImage` are nested within the transaction nodes. ```JSON { "data": { "me": { "defaultAccount": { "transactions": { "edges": [ { "node": { "initiationVia": { "paymentRequest": "lntbs320n1pjehuh8pp5cf6ckqv265qu6ppul0mhv4qpw4zkmd6rcxx080f8cqaz3w5p5m2qhp5ermsf933ju2t2vzpehcndlf8kpjqa780h6kzaa5eevpq6s8a7t9qcqzpuxqyz5vqsp5xs2v586kum4lu7exwskukkf0wjyw29l50293c8scdetlvszdgdds9qyyssqgzxzle9hz6384qt8uzh74wy3ylp6g3yw74q06zelxuhxtgwk9ehxvgtmqh53furqceecm22jsv2aypcangdn2tayl0vl095qx0wh3hqpwrfl8j", "paymentHash": "c2758b018ad501cd043cfbf776540175456db743c18cf3bd27c03a28ba81a6d4" }, "settlementVia": { "preImage": "9e92a2d24e89c92c93d2c63ffe126605bcd3bf614c727a1f6e3f52064b83c2ec" } } }, { "node": { "initiationVia": { "paymentRequest": "lntbs10n1pjehukhpp57ngk3ddxtmytqdzcyqa4l2e87ny29rwjsqx46g6m0pvpj7tvp6vshp5at629lcgdgt53gsapw77s59ykxxn7lkxyfk4n7zdx78c65s9502scqzpuxqyz5vqsp5nru4r9hu7asuvn86euyuskzdppl3lt4xue5wl8jxawaxc5rmzynq9qyyssq4c0d6lmszx6udlw8elv6dcawlsu7069fqd60wc4xxc3v6h5lmag45f8ks9lrdwnajysc0ka3lmgchfwrjjlgx4a8dg8g7gjlqaezecgqn706p3", "paymentHash": "f4d168b5a65ec8b03458203b5fab27f4c8a28dd2800d5d235b785819796c0e99" }, "settlementVia": { "preImage": "f3a2290961be4b91bb230cfe7ae9d8159667dd9da33ca95b7c609bf82034285c" } } } ] } } } } } ``` -------------------------------- ### Connect to WebSocket and Subscribe to Price Updates (Unauthenticated) Source: https://github.com/blinkbitcoin/dev.blink.sv/blob/main/docs/api/websocket.md Demonstrates connecting to the WebSocket endpoint using `websocat` and subscribing to the `price` and `realtimePrice` GraphQL subscriptions without authentication. Shows the initial connection handshake and subsequent data payloads. ```bash websocat ${websocket_endpoint} -H 'Sec-WebSocket-Protocol: graphql-transport-ws' -v [INFO websocat::lints] Auto-inserting the line mode [INFO websocat::stdio_threaded_peer] get_stdio_peer (threaded) [INFO websocat::ws_client_peer] get_ws_client_peer [INFO websocat::ws_client_peer] Connected to ws { "type": "connection_init", "payload": {}} {"type":"connection_ack"} { "id": "1", "type": "subscribe", "payload": { "query": "subscription { price( input: { amount: 100 amountCurrencyUnit: BTCSAT priceCurrencyUnit: USDCENT } ) { errors { message } price { base offset currencyUnit } }}", "variables": {} }} {"id":"1","type":"next","payload":{"data":{"price":{"errors":[],"price":{"base":4364414843750,"offset":12,"currencyUnit":"USDCENT"}}}}} [INFO websocat::ws_peer] Received WebSocket ping { "id": "2", "type": "subscribe", "payload": { "query": "subscription realtimePrice($input: RealtimePriceInput!) { realtimePrice(input: $input) { realtimePrice { id btcSatPrice { base offset } } errors { code message path } }}", "variables": { "input": { "currency": "USD" } } }} {"id":"2","type":"next","payload":{"data":{"realtimePrice":{"realtimePrice":{"id":"a6e2abdb-431e-5455-81c1-92fbaccfb0de","btcSatPrice":{"base":43623050781,"offset":12}},"errors":[]}}}} [INFO websocat::ws_peer] Received WebSocket ping {"id":"1","type":"next","payload":{"data":{"price":{"errors":[],"price":{"base":4362700000000,"offset":12,"currencyUnit":"USDCENT"}}}}} {"id":"2","type":"next","payload":{"data":{"realtimePrice":{"realtimePrice":{"id":"6d453741-e0ad-5fec-b27f-3d987571f5ad","btcSatPrice":{"base":43627000000,"offset":12}},"errors":[]}}}} ``` -------------------------------- ### Verifying Pre-image Hash in Linux (Bash) Source: https://github.com/blinkbitcoin/dev.blink.sv/blob/main/docs/api/proof-of-payment.md This Bash command pipeline verifies a Lightning pre-image by taking its hexadecimal representation (``), converting it to binary, and then calculating its SHA256 hash. The resulting hash should match the payment hash from the invoice to prove payment. ```Bash $ echo -n ''| xxd -r -p | sha256sum ``` -------------------------------- ### Sample GraphQL Query with Mixed Authorization Source: https://github.com/blinkbitcoin/dev.blink.sv/blob/main/docs/api/error-handling.md Demonstrates a GraphQL query combining fields that require authorization ('me') with fields that do not ('globals'). This illustrates how a single query can request different types of data, potentially resulting in partial success. ```GraphQL query me { globals { network } me { email { address } } } ``` -------------------------------- ### Querying Transactions with Proof of Payment (GraphQL) Source: https://github.com/blinkbitcoin/dev.blink.sv/blob/main/docs/api/proof-of-payment.md This GraphQL query retrieves recent transactions from the user's default account, specifically fetching the payment request and payment hash from the initiation details and the pre-image from the settlement details for both intra-ledger and Lightning settlements. It includes a variable `$first` to limit the number of results. ```GraphQL query PaymentsWithProof($first: Int) { me { defaultAccount { transactions(first: $first) { edges { node { initiationVia { ... on InitiationViaLn { paymentRequest paymentHash } } settlementVia { ... on SettlementViaIntraLedger { preImage } ... on SettlementViaLn { preImage } } } } } } } } ``` -------------------------------- ### Decoding Lightning Invoice with LND CLI (Bash) Source: https://github.com/blinkbitcoin/dev.blink.sv/blob/main/docs/api/proof-of-payment.md This Bash command uses the `lncli` tool from LND to decode a given Lightning invoice (``), providing details such as the payment hash, destination node, and amount. ```Bash $ lncli decodepayreq ``` -------------------------------- ### Querying Default Account Information with GraphQL Source: https://github.com/blinkbitcoin/dev.blink.sv/blob/main/docs/api/graphql-intro.md Illustrates how to query the `defaultAccount` field nested within the `me` query. This structure is used to access details about the user's primary or "master" account. Placeholder comment indicates where specific account fields would be added. ```GraphQL me { defaultAccount { # Query fields related to the master account } } ``` -------------------------------- ### Decoding Lightning Invoice with CLN CLI (Bash) Source: https://github.com/blinkbitcoin/dev.blink.sv/blob/main/docs/api/proof-of-payment.md This Bash command uses the `lightning-cli` tool from Core Lightning (CLN) to decode a given Lightning invoice (``), revealing its contents including the payment hash and other details. ```Bash $ lightning-cli decode ``` -------------------------------- ### Render GitHub Follow Button (React/JSX) Source: https://github.com/blinkbitcoin/dev.blink.sv/blob/main/docs/self-host/c-contribute/README.md This snippet uses the `react-github-btn` component to render a standard GitHub 'Follow' button. It is configured to follow the '@blinkbitcoin' organization, display the follower count, and adapt its color scheme based on user preferences. ```JSX Follow @blinkbitcoin ``` -------------------------------- ### Connect Blink to BTCPay Server (Specific Wallet) Source: https://github.com/blinkbitcoin/dev.blink.sv/blob/main/docs/examples/btcpayserver-plugin.md This connection string format allows specifying a particular wallet (BTC or USD) by including its Wallet ID. It also explicitly sets the server URL, although this is optional unless using a custom backend instance. ```BTCPay Connection String type=blink;server=https://api.blink.sv/graphql;api-key=blink_...;wallet-id=xyz ``` -------------------------------- ### Creating Lightning Invoice (GraphQL) Source: https://github.com/blinkbitcoin/dev.blink.sv/blob/main/docs/api/btc-ln-receive.mdx Explains how to generate a Lightning invoice using a GraphQL mutation. Requires an `LnInvoiceCreateInput` variable. The response includes the payment request, payment hash, payment secret, and satoshi amount. Use the `paymentRequest` to pay the invoice. ```GraphQL mutation LnInvoiceCreate($input: LnInvoiceCreateInput!) { lnInvoiceCreate(input: $input) { invoice { paymentRequest paymentHash paymentSecret satoshis } errors { message } } } ``` -------------------------------- ### Querying Transactions with Pagination - GraphQL Source: https://github.com/blinkbitcoin/dev.blink.sv/blob/main/docs/api/pagination.md GraphQL query to fetch transactions for an account, supporting pagination using `first` and `after` variables. Includes `pageInfo` for cursor-based navigation and `edges` for transaction data. ```graphql query transactionsForAccount($walletIds: [WalletId], $first: Int, $after: String) { me { id defaultAccount { transactions(walletIds: $walletIds, first: $first, after: $after) { pageInfo { endCursor hasNextPage } edges { cursor node { direction settlementCurrency settlementDisplayAmount status createdAt } } } } } } ``` -------------------------------- ### Querying Wallet Balances (GraphQL) Source: https://github.com/blinkbitcoin/dev.blink.sv/blob/main/docs/api/btc-ln-send.mdx This GraphQL query retrieves the user's default account and lists the IDs, currencies (BTC/USD), and balances for all associated wallets. The BTC balance is in satoshis, and the USD balance is in cents. Useful for checking balances before and after transactions. ```GraphQL query Me { me { defaultAccount { wallets { id walletCurrency balance } } } } ``` -------------------------------- ### Query Wallet Balances (GraphQL) Source: https://github.com/blinkbitcoin/dev.blink.sv/blob/main/docs/api/usd-ln-send.mdx Query to retrieve wallet information for the authenticated user, including wallet ID, currency (BTC or USD), and balance. The BTC balance is in satoshis, and the USD balance is in cents. ```GraphQL query Me { me { defaultAccount { wallets { id walletCurrency balance } } } } ``` -------------------------------- ### Connect Blink to BTCPay Server (Default Wallet) Source: https://github.com/blinkbitcoin/dev.blink.sv/blob/main/docs/examples/btcpayserver-plugin.md This connection string format is used in BTCPay Server to connect to a Blink account using an API key. When only the API key is provided, BTCPay Server will use the default wallet configured on the Blink server. ```BTCPay Connection String type=blink;api-key=blink_... ```