1.0.3 • Published 1 month ago

@orangecrypto/orange-connect v1.0.3

Weekly downloads
-
License
ISC
Repository
github
Last release
1 month ago

Orange Connect

Getting Started with Orange Connect

Orange Connect offers a streamlined JavaScript library designed to facilitate the integration of Orange Bitcoin 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

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.

1.0.3

1 month ago

1.0.2

2 months ago

1.0.1

2 months ago

1.0.0

2 months ago