Orange Crypto
WebsiteDocsXTelegramDiscord
  • Orange
  • Orange Alpha
    • Orange Year In Review 2024
  • GTM Overview
  • Orange Connect
  • Orange Wallet
    • Features
    • Security
    • Security Audit
    • FAQs
    • Installing Orange Wallet
    • Creating a New Wallet
    • Restoring an Existing Wallet
    • Navigating the Orange Wallet
    • Adding a New Coin
    • Sending an Asset
    • Receiving an Asset
    • Swapping an Asset
    • Using Orange Wallet with Ledger
    • Testing Orange Wallet Mobile Beta
  • Orange Bridge
    • Using Orange Bridge
    • $ORNJ Token Bridge Details
  • Orange Marketcap
    • APIs
  • Orange Explorer
  • Orange Indexer
    • APIs
      • BRC-20 Tokens
      • Inscriptions
      • Statistics
      • Satoshis
  • Orange Web Services
  • Orange Rewards
    • FAQs
  • Orange Token
    • Utility
    • Tokenomics
    • Liquidity
  • Partners
  • FAQs
  • Links
  • General Knowledge Base
    • Bitcoin 101
    • BRC-20 Standard
    • Bitcoin Wallet Addresses
    • Glossary
  • Legal
    • Terms of Service
    • Privacy Policy
    • Offering Agreement
    • Disclaimer
    • Corporate Registration
Powered by GitBook
On this page
  • Getting Started with Orange Connect
  • Using the Request Method
  • General Skeleton for Request
  • getAddresses
  • signMessage
  • sendTransfer
  • signPsbt
  • sendBrc20OneStep
  • sendRune
  • Legacy Methods
  • Connecting to the User's Wallet with getAddress
  • Utilizing signMessage
  • How to Use sendBtcTransaction
  • Implementing signTransaction
  • Initiating Inscriptions
  • React Component for File Inscriptions

Orange Connect

Getting Started with Orange Connect

Orange Connect offers a streamlined JavaScript library designed to facilitate the integration of Orange Wallet functionalities into applications. It enables the retrieval of wallet addresses from users, as well as the initiation of transaction signings and message signatures.

This introductory guide outlines the fundamental operations you can perform with Orange Connect, including:

  • Acquiring wallet address(es) from users

  • Initiating the signing process for Bitcoin transactions that are partially signed (PSBTs)

  • Signing arbitrary messages

  • Conducting Bitcoin transactions to single or multiple recipients

  • Embedding arbitrary content into satoshis

Begin by incorporating Orange Connect into your project with the following command:

npm install @orangecrypto/orange-connect

Using the Request Method

The request method provides a versatile and consistent interface for interacting with various Orange Connect functionalities. By leveraging this single method, developers can handle multiple capabilities with ease, improving maintainability and reducing code complexity.

General Skeleton for Request

The request method accepts two main parameters:

  1. Capability Name: Specifies the type of operation to be performed (e.g., "getInfo", "signMessage").

  2. Payload: Provides the data required to execute the specified operation. The structure of the payload varies depending on the capability.

const response = await request(capabilityName, payload);

if (response.status === "success") {
  console.log("Operation successful", response.result);
} else {
  console.error("Operation failed", response.error.message);
}

Response Structure

The response from the request method is consistent across all capabilities:

  • status: Indicates the outcome of the operation ("success" or "error").

  • result: Contains the result of the operation if successful.

  • error: Provides error details if the operation fails.

Supported Capabilities

Below is a list of supported capabilities and their use cases:

  • getAddresses: Fetch wallet addresses based on specified criteria.

  • signMessage: Sign an arbitrary message with the user's wallet.

  • sendTransfer: Initiate a Bitcoin transfer to one or more recipients.

  • signPsbt: Sign a partially signed Bitcoin transaction (PSBT).

  • sendBrc20OneStep: Conduct a BRC-20 token transfer in one step.

  • sendRune: Send Rune tokens.

Each capability has specific examples and use cases, detailed below.

getAddresses

The getAddresses capability retrieves wallet addresses for specified purposes, such as payments, ordinals, or Stacks operations. You can customize the request with a message explaining the purpose to the user.

Example Usage

const payload = {
  purposes: ["payment", "ordinals"],
  message: "Please provide addresses for payments and ordinals.",
};

const response = await request("getAddresses", payload);

if (response.status === "success") {
  console.log("Addresses retrieved:", response.result.addresses);
  response.result.addresses.forEach((address) => {
    console.log(`Address: ${address.address}, Purpose: ${address.purpose}`);
  });
} else {
  console.error("Failed to retrieve addresses:", response.error.message);
}

Understanding the Response

Upon successful request approval, getAddresses returns an object containing an array of wallet address details. Each address object includes:

  • Address: The wallet address string.

  • Public Key: A hexadecimal string representing the public key associated with the address.

  • Purpose: Categorized use of the address ("payment", "ordinals", or "stacks").

  • Address Type: Specifies the address format (e.g., "p2tr" for Taproot addresses).

signMessage

The signMessage capability allows users to sign arbitrary messages with their wallet. This can be useful for authentication or data verification purposes.

Example

const payload = {
  address: "1A1zP1eP5QGefi2DMPTfTL5SLmv7DivfNa",
  message: "Hello, Bitcoin!",
};

const response = await request("signMessage", payload);

if (response.status === "success") {
  console.log("Message signed successfully:", response.result.signature);
} else {
  console.error("Failed to sign message:", response.error.message);
}

Response

Property
Description

signature

The signature of the message.

messageHash

Hashed message sent in the payload.

address

Address used for signing.

sendTransfer

You can use the sendTransfer method to request a transfer of any amount of Bitcoin to one or more recipients from the user's wallet.

Request parameters

Parameter
Description

recipients

An array of objects with address and amount properties: - address: A string representing the recipient's address. - amount: A number representing the amount of Bitcoin to send, denominated in satoshis (Bitcoin's base unit).

Example

try {
  const response = await request("sendTransfer", {
    recipients: [
      {
        address: recipient,
        amount: Number(amount),
      },
    ],
  });

  if (response.status !== "success") {
    throw new Error(response.error.message);
  }
  console.log('Txid', response.result.txid);
} catch (err) {
  console.error(err.error.message);
}

Response

The sendTransfer method returns a Promise that resolves to the sendTransferResult object:

Property
Description

txid

The transaction ID as a hex-encoded string.

signPsbt

You can use the signPsbt method to request the signature of a Partially Signed Bitcoin Transaction (PSBT) from your user's Bitcoin wallet addresses.

Request parameters

Parameter
Description

psbt

A string representing the PSBT to sign, encoded in base64.

signInputs

A Record<string, number[]> where the keys are the addresses to use for signing, and the values are the indexes of the inputs to sign with each address.

broadcast

A boolean flag that specifies whether to broadcast the signed transaction after the signature.

allowedSignHash

A flag to specify the allowed signature types for signing (e.g. SIGHASH_ALL)

Example

const signInputs = {
  [paymentAddress]: [0],
  [ordinalsAddress]: [1],
};

try {
  const response = await request("signPsbt", {
    psbt: psbtBase64,
    broadcast: false,
    signInputs: signInputs,
    allowedSignHash: btc.SigHash.ALL | btc.SignatureHash.ANYONECANPAY,
  });

  if (response.status !== "success") {
    throw new Error(response.error.message);
  }

  alert(response.result.psbt);
  console.log("res:-", response);
} catch (err) {
  console.log(err);
}

Response

The signPsbt method returns a Promise that resolves to the SignPsbtResult object:

Property
Description

psbt

The base64 encoded signed PSBT.

txid

The transaction ID as a hex-encoded string. This is only returned if the transaction was broadcasted.

sendBrc20OneStep

You can use the sendBrc20OneStep method to request a transfer of any amount of specified BRC-20 token to one recipient from the user's wallet.

We are planning to support multiple recipients in the near future for this method.

Request parameters

Parameter
Description

recipient

An object with address, amount and ticker properties

Example


try {
  const response = await request("sendBrc20OneStep", {
    recipient: 
      {
        address: recipient,
        amount: Number(amount),
        ticker: 'ordi', 
      }
  });

  if (response.status !== "success") {
    throw new Error(response.error.message);
  }
  console.log('Txid', response.result.txid);
} catch (err) {
  console.error(err.error.message);
}

Response

The sendBrc20OneStep method returns a Promise that resolves to the sendTransferResult object:

Property
Description

txid

The transaction ID as a hex-encoded string.

sendRune

You can use the sendRune method to request a transfer of any amount of specified RUNES token to one recipient from the user's wallet.

We are planning to support multiple recipients in the near future for this method.

Request parameters

Parameter
Description

recipient

An object with address, amount and ticker properties

Example


try {
  const response = await request("sendRune", {
    recipient: 
      {
        address: recipient,
        amount: Number(amount),
        ticker: 'SATOSHI•NAKAMOTO', 
      }
  });

  if (response.status !== "success") {
    throw new Error(response.error.message);
  }
  console.log('Txid', response.result.txid);
} catch (err) {
  console.error(err.error.message);
}

Response

The sendRune method returns a Promise that resolves to the sendTransferResult object:

Property
Description

txid

The transaction ID as a hex-encoded string.

Legacy Methods

These are still available & can be used as they are not being depracted and is very much in use. Older wallet versions used these methods

Connecting to the User's Wallet with getAddress

Overview

The getAddress function plays a pivotal role in integrating user wallet connectivity into your application. This method facilitates the acquisition of user wallet addresses from Bitcoin and Stacks networks, requiring user permission through a prompt.

Implementation Steps

  1. Initial Setup: Begin by importing the getAddress method from the @orangecrypto/orange-connect library to leverage its capabilities within your application.

import { getAddress } from "@orangecrypto orange-connect";
  1. Configuring Request Parameters: Tailor your request to fit your application's needs by specifying desired wallet addresses and custom messages. These parameters are encapsulated within an options object passed to getAddress.

  • Network Selection: Define the Bitcoin network context (Mainnet or Testnet) for the operation.

  • Address Purposes: Indicate the types of addresses you're requesting: Bitcoin ordinals address, Bitcoin payment address, or Stacks address.

  • User Prompt Message: Craft a concise message to be displayed in the wallet connection prompt, explaining the reason for the address request.

Example Configuration:

const getAddressOptions = {
  payload: {
    purposes: ["ordinals", "payment"],
    message: "Address for receiving Ordinals and payments",
    network: {
      type: "Mainnet",
    },
  },
  onFinish: (response) => {
    console.log(response);
  },
  onCancel: () => alert("Request canceled"),
};
  1. Executing the Request: Invoke getAddress with the previously defined options. This method returns a promise, resolving upon user approval with their wallet addresses.

    javascriptCopy code

    await getAddress(getAddressOptions);

Understanding the Response

Upon successful request approval, getAddress returns an object containing an array of wallet address details. Each address object includes:

  • Address: The wallet address string.

  • Public Key: A hexadecimal string representing the public key associated with the address.

  • Purpose: Categorized use of the address ("payment", "ordinals", or "stacks").

  • Address Type: Specifies the address format (e.g., "p2tr" for Taproot addresses).

Handling User Actions

  • On Approval: The onFinish callback function is executed, where you can handle the received addresses.

  • On Cancellation: If the user declines or dismisses the prompt, the onCancel callback is invoked.

Utilizing signMessage

To initiate a signature request, use the signMessage method provided by Orange Connect. This method supports message signing through two distinct signature schemes, depending on the type of Bitcoin address used:

  • ECDSA Signatures: Utilized for messages signed with BTC payment addresses, specifically those of the type p2sh(p2wpkh).

  • BIP322 Signatures: Employed when signing with Ordinals addresses, or p2tr.

Preparing the Signature Request

Your request to sign a message must include details about the network, the address performing the signing, and the message itself. Here's a breakdown of the required fields:

  • Network: Specifies whether the target Bitcoin chain is Mainnet or Testnet.

  • Address: The Bitcoin address used for signing the message.

  • Message: The actual content you wish the wallet to sign.

Example Signature Request

Configure your request as follows, replacing values as necessary to suit your application's needs:

const signMessageOptions = {
  payload: {
    network: {
      type: "Testnet",
    },
    address: "yourAddressHere",
    message: "Your message here",
  },
  onFinish: (response) => {
    alert("Signature: " + response);
  },
  onCancel: () => alert("Signature request canceled"),
};

await signMessage(signMessageOptions);

How to Use sendBtcTransaction

By invoking sendBtcTransaction, you can specify the details of your transaction, including the recipients, the sender address, and the network (Mainnet or Testnet). Here's a brief overview of the payload parameters:

  • Recipients: A list detailing the addresses and the corresponding amounts (in satoshis) to be sent.

  • Sender Address: Specifies the originating address for the transaction funds.

  • Network: Determines the Bitcoin network over which the transaction is conducted.

Sample Transaction Request

The following example demonstrates how to construct a transaction request, sending Bitcoin to multiple recipients:

const sendBtcOptions = {
  payload: {
    network: {
      type: "Testnet",
    },
    recipients: [
      {
        address: 'exampleAddress1',
        amountSats: 1500,
      },
      {
        address: 'exampleAddress2',
        amountSats: 1500,
      },
    ],
    senderAddress: 'yourSenderAddress',
  },
  onFinish: (response) => {
    //...
  },
  onCancel: () => //...,
};

await sendBtcTransaction(sendBtcOptions);

Upon request, the user will be prompted to review and confirm the transaction in their wallet, ensuring transparency and user control over the transaction process.

Implementing signTransaction

The signTransaction method provided by Orange Connect is your gateway to initiating PSBT signings. This method requires a base64-encoded PSBT, which can be prepared using any reputable Bitcoin library. Here's how to define the payload for your signing request:

  • Network: Indicates the Bitcoin network, choosing between Mainnet and Testnet.

  • psbtBase64: The PSBT encoded in base64 format.

  • Broadcast: A boolean flag to determine whether the signed transaction should be automatically broadcasted.

  • InputsToSign: Details the specific inputs within the transaction that require signing, including the address and index of each input.

Constructing a Signing Request

To prepare your transaction for signing, define your request as follows, adjusting the parameters to fit your transaction's requirements:

javascriptCopy code

const signPsbtOptions = {
  payload: {
    network: {
      type: 'Mainnet'
    },
    psbtBase64: `yourBase64EncodedPSBT`,
    broadcast: false,
    inputsToSign: [
      {
        address: "exampleAddress1",
        signingIndexes: [0],
      },
      {
        address: "exampleAddress2",
        signingIndexes: [1, 2],
      },
    ],
  },
  onFinish: (response) => {
    //
  },
  onCancel: () => //,
};

await signTransaction(signPsbtOptions);

This setup ensures that you can specify which inputs to sign and which addresses are used for signing, providing flexibility and security for transaction operations.

Initiating Inscriptions

Leveraging the createInscription function from Orange Connect, your application can facilitate users in embedding their desired content into the blockchain. This action is executed from the user's wallet address, with the final inscription manifesting in their ordinals address.

For those looking to monetize their services, Orange Connect offers the ability to incorporate a service fee directly into the inscription transaction. This is achieved through the optional appFee and appFeeAddress parameters, adding an additional output to the transaction for the service charge.

Upon user consent, the inscription transaction is promptly broadcasted, and the transaction ID is returned for tracking purposes.

Payload Parameters

  • network: Designates the Bitcoin network, restricted to Mainnet for inscriptions.

  • contentType: Specifies the MIME type of the inscribed content, essential for accurate content representation.

  • payloadType: Defines the content format, which can be either "PLAIN_TEXT" for direct inscriptions or "BASE_64" for binary data.

  • content: The actual data to be inscribed, tailored according to the payload type.

  • appFee (optional): The service charge for the inscription, in satoshis.

  • appFeeAddress (optional): The recipient address for the service fee.

  • suggestedMinerFeeRate (optional): Proposes an initial miner fee rate, adjustable by the user in their wallet.

Examples

  • Text Inscription:

await createInscription({
  payload: {
    network: { type: 'Mainnet' },
    contentType: "text/html",
    content: "Here is my inscription text",
    payloadType: "PLAIN_TEXT",
    appFeeAddress: "yourFeeAddress",
    appFee: 1500,
    suggestedMinerFeeRate: 10,
  },
  onFinish: (response) => {
    //
  },
  onCancel: () => //,
});
  • Binary Data Inscription:

await createInscription({
  payload: {
    network: { type: "Mainnet" },
    contentType: "image/jpeg",
    content: "yourBase64EncodedContent",
    payloadType: "BASE_64",
  },
  onFinish: (response) => alert(`Transaction ID: ${response.txId}`),
  onCancel: () => alert("Inscription canceled"),
});

React Component for File Inscriptions

For applications built with React, the following component provides a user interface for creating inscriptions from files:

import { useState } from "react";
import {
  createInscription,
  BitcoinNetworkType,
} from "@orangecrypto/orange-connect";

const CreateBinaryInscription = ({ network }) => {
  const [content, setContent] = useState("");
  const [contentType, setContentType] = useState("image/jpeg");

  const handleFileSelection = (event) => {
    const file = event.target.files?.[0];
    if (!file) return;
    const reader = new FileReader();
    reader.onloadend = () => {
      setContent(reader.result.toString().split(",")[1]);
    };
    reader.readAsDataURL(file);
  };

  const createInscriptionOnClick = async () => {
    await createInscription({
      payload: {
        network: { type: network },
        contentType,
        content,
        payloadType: "BASE_64",
      },
      onFinish: (response) => alert(`Transaction ID: ${response.txId}`),
      onCancel: () => alert("Inscription process canceled"),
    });
  };

  return (
    <div>
      <h3>Create File Inscription</h3>
      <input
        type="text"
        placeholder="Content Type (e.g., image/jpeg)"
        value={contentType}
        onChange={(e) => setContentType(e.target.value)}
      />
      <input type="file" onChange={handleFileSelection} />
      <button onClick={createInscriptionOnClick}>Submit Inscription</button>
    </div>
  );
};

export default CreateBinaryInscription;

This component simplifies the process of uploading and inscribing binary data, providing a straightforward interface for users to interact with the blockchain in an innovative way.

PreviousGTM OverviewNextOrange Wallet

Last updated 5 months ago

Page cover image