Orange Connect
This documentation is also available at https://www.npmjs.com/package/@orangecrypto/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-connectUsing 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:
Capability Name: Specifies the type of operation to be performed (e.g.,
"getInfo","signMessage").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.
BTC 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).sendBRC20 | sendBrc20OneStep: Conduct a BRC-20 token transfer in one step.sendRune: Send Rune tokens.sendManyRunes: Send Multiple rune transfers.
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
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
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:
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
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:
psbt
The base64 encoded signed PSBT.
txid
The transaction ID as a hex-encoded string. This is only returned if the transaction was broadcasted.
sendBRC20 | sendBrc20OneStep
You can use the sendBRC20 | 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
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 sendBRC20 |sendBrc20OneStep method returns a Promise that resolves to the sendTransferResult object:
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
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:
txid
The transaction ID as a hex-encoded string.
sendManyRunes
sendManyRunesYou can use the sendManyRune method to request a transfer of any amount of specified RUNES token to one recipient from the user's wallet.
Request parameters
recipient
An object with address, amount and runeName properties
Example
try {
const response = await request("sendManyRunes", {
recipients: [
{
address: recipient,
amount: Number(amount),
runeName: "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 sendManyRunes method returns a Promise that resolves to the sendTransferResult object:
txid
The transaction ID as a hex-encoded string.
STX Supported Capabilities
Below is a list of supported capabilities and their use cases:
stx_getAccounts: Fetch stacks address.stx_signMessage: Sign an arbitrary message with the user's wallet.stx_transfer: Initiate a stx transfer to one or more recipients.stx_signTx: Sign transaction using stacks.
Each capability has specific examples and use cases, detailed below.
stx_getAccounts
Your application can request to connect to the user’s Stacks wallet using the stx_getAccounts method, which prompts the user to share their Stacks address.
Request
No parameters are required:
try {
const response = await request("stx_getAccounts", {});
if (response.status === "success") {
alert("Success getting accounts. Check console for results.");
console.log("Accounts:", response.result);
} else {
alert("Error getting accounts. Check console for details.");
console.error(response);
}
} catch (err) {
console.error("Request failed:", err);
}Behavior
When stx_getAccounts is called:
The wallet prompts the user with a Connection Request.
If the user approves, a promise resolves with a GetAccountsResult, which is an array of account objects.
If the user declines or closes the pop-up, the promise is rejected.
Response: GetAccountsResult
GetAccountsResultEach account object in the response contains the following fields:
address
The user's connected Stacks wallet address
publicKey
Hex-encoded public key for the address
network
"mainnet" or "testnet"
gaiaHubUrl
URL of the user’s Gaia hub for off-chain storage
gaiaAppKey
Hex-encoded Gaia app key used for encrypting app data
stx_signMessage
You can request your user to sign a message with arbitrary (unstructured) data using their wallet's Stacks address by invoking the stx_signMessage method.
This can be used to:
Authenticate ownership of a wallet address
Signal user intent (e.g., agreeing to Terms of Service)
Request Parameters
message
A UTF-8 string representing the message to be signed
publicKey
A string representing the public key of the address used for signing
Example
const message = "Hello World 123";
const publicKey = "yourPublicKeyHere";
const response = await request("stx_signMessage", {
message,
publicKey,
});
if (response.status === "success") {
console.log(response);
alert(response.result.signature);
} else {
console.error("Failed to sign message:", response.error);
}stx_transfer
You can use the stx_transfer method to request a transfer of any amount of Stacks (STX) tokens to a recipient from the user's wallet.
Request Parameters
amount
A string representing the amount of STX to transfer, in microstacks (1 STX = 1,000,000 microstacks). Any value parseable by BigInt is acceptable.
recipient
A string representing the Crockford base-32 encoded Stacks address of the recipient.
memo (optional)
A string representing the transaction memo.
Example
try {
const response = await request("stx_transfer", {
recipient,
amount: Number(amount),
memo,
});
if ("result" in response) {
alert(response.result.txid);
} else {
alert(response.error.message);
}
} catch (error) {
console.error(error);
alert(error.message);
}Behavior
The transaction will be signed and broadcasted upon user approval.
If the user approves, the method returns a TransferStxResult object.
If the user declines or closes the prompt, the Promise is rejected.
Response: TransferStxResult
TransferStxResulttxid
A hex-encoded string representing the ID of the signed and broadcasted STX transaction
transaction
A hex-encoded string representing the raw signed STX transaction
stx_signTx
You can use the stx_signTx method to request the signature of any hex-encoded Stacks transaction from your user's Stacks wallet address.
Request Parameters
transaction
A hex-encoded string representing the Stacks transaction to sign
broadcast (optional)
A boolean flag specifying whether to broadcast the signed transaction after signing. Defaults to true.
You can use any Stacks library to construct these transactions. Below are examples using helper functions from the @stacks/transactions package.
Example Usage
try {
const response = await request("stx_signTx", {
transaction: uint8ArrayToHex(transaction.serialize()),
});
if (response.status === "success") {
console.log(response.result.transaction);
} else {
alert(errorMessage);
console.error(response.error);
}
} catch (error) {
alert(errorMessage);
console.error(error);Behavior
The transaction will be signed and broadcasted upon user approval.
If the user approves, the stx_signTransaction method returns a Promise that resolves to the SignTransactionResult object.
If the user declines or closes the prompt, the Promise is rejected.
Response: SignTransactionResult
SignTransactionResulttransaction
A hex-encoded string representing the signed STX transaction
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
getAddressOverview
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
Initial Setup: Begin by importing the
getAddressmethod from the@orangecrypto/orange-connectlibrary to leverage its capabilities within your application.
import { getAddress } from "@orangecrypto orange-connect";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"),
};Executing the Request: Invoke
getAddresswith 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
onFinishcallback function is executed, where you can handle the received addresses.On Cancellation: If the user declines or dismisses the prompt, the
onCancelcallback is invoked.
Utilizing signMessage
signMessageTo 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
sendBtcTransactionBy 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
signTransactionThe 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.
Last updated
