Socket
Socket
Sign inDemoInstall

@babbage/sdk-ts

Package Overview
Dependencies
12
Maintainers
3
Versions
47
Alerts
File Explorer

Advanced tools

Install Socket

Detect and block malicious and high-risk dependencies

Install

    @babbage/sdk-ts

Build Babbage Apps with TypeScript


Version published
Weekly downloads
23
decreased by-63.49%
Maintainers
3
Install size
7.32 MB
Created
Weekly downloads
 

Readme

Source

@babbage/sdk-ts

Build Babbage apps in TypeScript

NPM Package

GitHub Repository

Installation

npm i @babbage/sdk

By Example

There are a few example projects you can check out which implement the Babbage SDK:

  • 🎵Tempo: A platform for creating and sharing music, and empowering artists with micropayments
  • ✅Simple ToDo List: An app that demonstrates the basics of Bitcoin tokenization and identity

Documentation

📒 The JavaScript API is documented below the examples, in the API section

The 📚Babbage Learn website hosts the concepts, guides and reference materials that show you how the SDK works.

Example Usage

Encryption

import { encrypt, decrypt } from '@babbage/sdk-ts'

// Encrypt and decrypt data using the Babbage SDK
const encryptedData = await encrypt({
  plaintext: Buffer.from('some data'),
  protocolID: [0, 'Hello World'],
  keyID: '1'
})

// The same protocol and key ID is needed for decryption
const decryptedData = await decrypt({
  ciphertext: encryptedData,
  protocolID: [0, 'Hello World'],
  keyID: '1',
  returnType: 'string'
})

Creating and Redeeming Bitcoin tokens

This example also uses PushDrop

import { createAction } from '@babbage/sdk-ts'
import { create, redeem } from 'pushdrop'

const bitcoinOutputScript = await create({
  fields: [ // The "fields" are the data payload to attach to the token.
    Buffer.from('My First Token'),
    Buffer.from('My name is Ty') // Tokens can represent anything!
  ],
  // The "first token" protocol and key ID can be used to sign and 
  // lock this new Bitcoin PushDrop token.
  protocolID: 'first token',
  keyID: '1'
})

const newToken = await createAction({
  // The Bitcoin transaction ("Action" with a capital A) has an output, 
  // because it has led to the creation of a new Bitcoin token.
  outputs: [{
    // The output amount is how much Bitcoin (measured in "satoshis") 
    // this token is worth. Let's use 1000 satoshis.
    satoshis: 1000,
    // The output script for this token was created by the PushDrop library, 
    // which you can see above.
    script: bitcoinOutputScript
  }],
  // Finally, we'll describe the Action for the user
  description: 'Create my first token'
})

// Here, we're using the PushDrop library to unlcok / redeem the PushDrop 
// token that was previously created. By providing this information, 
// PushDrop can "unlock" and spend the token. When the token gets spent, 
// the user gets their 1000 satoshis back.
const unlockingScript = await pushdrop.redeem({
  // To unlock the token, we need to use the same "first token" protocol 
  // and key ID as when we created the token before. Otherwise, the 
  // key won't fit the lock and the Bitcoins won't come out.
  protocolID: 'first token',
  keyID: '1',
  // We're telling PushDrop which previous transaction and output we want to
  // unlock, so that the correct unlocking puzzle can be prepared.
  prevTxId: newToken.txid,
  outputIndex: 0, // The first output from the transaction
  // We also give PushDrop a copy of the locking puzzle ("script") that 
  // we want to open, which is helpful in preparing to unlock it.
  lockingScript: bitcoinOutputScript,
  // Finally, the number of satoshis we are expecting to unlock when the 
  // puzzle gets solved.
  outputAmount: 1000
})

// Now, we're going to use the unlocking puzle that PushDrop has prepared for us,
// so that the user can get their Bitcoins back. This is another "Action", which
// is just a Bitcoin transaction.
// The amount the user gets back will be slightly less, because of transaction fees.
await createAction({
  inputs: { // These are inputs, which unlock Bitcoin tokens.
    // The input comes from the token which we're completing
    [newToken.txid]: {
      ...newToken,
      // The output we want to redeem is specified here, and we also give 
      // the unlocking puzzle ("script") from PushDrop.
      outputsToRedeem: [{
        index: 0, // The first output of the transaction
        unlockingScript
      }]
    }
  },
  // Let the user know why they're getting some Bitcoins back
  description: 'Redeem my first token'
})

🏆 After reading the above two examples, could you implement a token with encrypted data? 🏆

API

Links: API, Interfaces, Classes, Functions, Types, Variables

Interfaces

AbortActionResultDojoCreatingTxInputsApiListActionsTransactionOutput
CertificateApiDojoCreatingTxInstructionsApiMapiResponseApi
CounterpartyKeyLinkageResultDojoCreatingTxOutputApiProveCertificateResult
CreateActionInputDojoOutputToRedeemApiSignActionResult
CreateActionOutputEnvelopeApiSpecificKeyLinkageResult
CreateActionOutputToRedeemEnvelopeEvidenceApiSubmitDirectTransaction
CreateActionResultGetTransactionOutputResultSubmitDirectTransactionOutput
CreateCertificateResultListActionsResultSubmitDirectTransactionResult
DojoCreateTransactionResultApiListActionsTransactionTscMerkleProofApi
DojoCreateTxOutputApiListActionsTransactionInput

Links: API, Interfaces, Classes, Functions, Types, Variables


Interface: TscMerkleProofApi

As defined in https://github.com/bitcoin-sv-specs/brfc-merchantapi/blob/master/README.md

export interface TscMerkleProofApi {
    height?: number;
    index: number;
    txOrId: string | Buffer;
    target: string | Buffer;
    nodes: string[] | Buffer;
    targetType?: "hash" | "header" | "merkleRoot" | "height";
    proofType?: "branch" | "tree";
    composite?: boolean;
}
Interface TscMerkleProofApi Details
Property height

The most efficient way of confirming a proof should also be the most common, when the containing block's height is known.

height?: number
Property index

Index of transaction in its block. First transaction is index zero.

index: number
Property nodes

Merkle tree sibling hash values required to compute root from txid. Duplicates (sibling hash === computed hash) are indicated by "*" or type byte === 1. type byte === 2... Strings are encoded as hex.

nodes: string[] | Buffer
Property target

Merkle root (length === 32) or serialized block header containing it (length === 80). If string, encoding is hex.

target: string | Buffer
Property txOrId

Full transaction (length > 32 bytes) or just its double SHA256 hash (length === 32 bytes). If string, encoding is hex.

txOrId: string | Buffer

Links: API, Interfaces, Classes, Functions, Types, Variables


Interface: MapiResponseApi
export interface MapiResponseApi {
    payload: string;
    signature: string;
    publicKey: string;
    encoding?: string;
    mimetype?: string;
}
Interface MapiResponseApi Details
Property encoding

encoding of the payload data

encoding?: string
Property mimetype

mime type of the payload data

mimetype?: string
Property payload

Contents of the envelope. Validate using signature and publicKey. encoding and mimetype may assist with decoding validated payload.

payload: string
Property publicKey

public key to use to verify signature of payload data

publicKey: string
Property signature

signature producted by correpsonding private key on payload data

signature: string

Links: API, Interfaces, Classes, Functions, Types, Variables


Interface: EnvelopeApi

Simplest case of an envelope is a rawTx and merkle proof that ties the transaction to a known block header. This will be the case for any sufficiently old transaction.

If the transaction has been mined but for some reason the block headers may not be known, an array of headers linking known headers to the one needed by the proof may be provided. They must be in height order and need to overlap a known header.

If the transaction has not been minded yet but it has been submitted to one or more miners then the mapi responses received, proving that specific miners have received the transaction for processing, are included in the mapiResponses array. Note that the miner reputations must be checked to give weight to these responses.

Additionally, when the transaction hasn't been mined or a proof is unavailable and mapi responses proving miner acceptance are unavailable, then all the transactions providing inputs can be submitted in an inputs object.

The keys of the inputs object are the transaction hashes (txids) of each of the input transactions. The value of each inputs object property is another envelope object.

References: Section 2 of https://projectbabbage.com/assets/simplified-payments.pdf https://gist.github.com/ty-everett/44b6a0e7f3d6c48439f9ff26068f8d8b

export interface EnvelopeApi extends EnvelopeEvidenceApi {
    headers?: string[];
    reference?: string;
}
Interface EnvelopeApi Details
Property headers

For root nodes only. Array of 80 byte block headers encoded as 160 character hex strings Include headers the envelope creator is aware of but which the resipient may not have.

headers?: string[]
Property reference

Arbitrary reference string associated with the envelope, typically root node only.

reference?: string

Links: API, Interfaces, Classes, Functions, Types, Variables


Interface: EnvelopeEvidenceApi

Either inputs or proof are required.

export interface EnvelopeEvidenceApi {
    rawTx: string;
    proof?: TscMerkleProofApi | Buffer;
    inputs?: Record<string, EnvelopeEvidenceApi>;
    txid?: string;
    mapiResponses?: MapiResponseApi[];
    depth?: number;
}
Interface EnvelopeEvidenceApi Details
Property depth

count of maximum number of chained unproven transactions before a proven leaf node proof nodes have depth zero.

depth?: number
Property inputs

Only one of proof or inputs must be valid. Branching nodes have inputs with a sub envelope (values) for every input transaction txid (keys)

inputs?: Record<string, EnvelopeEvidenceApi>
Property mapiResponses

Array of mapi transaction status update responses Only the payload, signature, and publicKey properties are relevant.

Branching inputs nodes only. Array of mapi transaction status update responses confirming unproven transctions have at least been submitted for processing.

mapiResponses?: MapiResponseApi[]
Property proof

Either proof, or inputs, must have a value. Leaf nodes have proofs.

If value is a Buffer, content is binary encoded serialized proof see: chaintracks-spv.utils.serializeTscMerkleProof

proof?: TscMerkleProofApi | Buffer
Property rawTx

A valid bitcoin transaction encoded as a hex string.

rawTx: string
Property txid

double SHA256 hash of serialized rawTx. Optional.

txid?: string

Links: API, Interfaces, Classes, Functions, Types, Variables


Interface: CertificateApi
export interface CertificateApi {
    type: string;
    subject: string;
    validationKey: string;
    serialNumber: string;
    certifier: string;
    revocationOutpoint: string;
    signature: string;
    fields?: Record<string, string>;
}
Interface CertificateApi Details
Property certifier

max length of 255

certifier: string
Property fields

Certificate fields object where keys are field names and values are field value.

fields?: Record<string, string>
Property revocationOutpoint

max length of 255

revocationOutpoint: string
Property serialNumber

max length of 255

serialNumber: string
Property signature

max length of 255

signature: string
Property subject

max length of 255

subject: string
Property type

max length of 255

type: string
Property validationKey

max length of 255

validationKey: string

Links: API, Interfaces, Classes, Functions, Types, Variables


Interface: CreateCertificateResult
export interface CreateCertificateResult extends CertificateApi {
    type: string;
    subject: string;
    validationKey: string;
    serialNumber: string;
    certifier: string;
    revocationOutpoint: string;
    signature: string;
    fields?: Record<string, string>;
    masterKeyring?: Record<string, string>;
}
Interface CreateCertificateResult Details
Property certifier

max length of 255

certifier: string
Property fields

Certificate fields object where keys are field names and values are field value.

fields?: Record<string, string>
Property masterKeyring

Certificate masterKeyring object where keys are field names and values are field masterKey value.

masterKeyring?: Record<string, string>
Property revocationOutpoint

max length of 255

revocationOutpoint: string
Property serialNumber

max length of 255

serialNumber: string
Property signature

max length of 255

signature: string
Property subject

max length of 255

subject: string
Property type

max length of 255

type: string
Property validationKey

max length of 255

validationKey: string

Links: API, Interfaces, Classes, Functions, Types, Variables


Interface: ProveCertificateResult
export interface ProveCertificateResult extends CertificateApi {
    type: string;
    subject: string;
    validationKey: string;
    serialNumber: string;
    certifier: string;
    revocationOutpoint: string;
    signature: string;
    fields?: Record<string, string>;
    keyring: Record<string, string>;
}
Interface ProveCertificateResult Details
Property certifier

max length of 255

certifier: string
Property fields

Plaintext field names and values of only those fields requested in fieldsToReveal

fields?: Record<string, string>
Property keyring

field revelation keyring for the given verifier

keyring: Record<string, string>
Property revocationOutpoint

max length of 255

revocationOutpoint: string
Property serialNumber

max length of 255

serialNumber: string
Property signature

max length of 255

signature: string
Property subject

max length of 255

subject: string
Property type

max length of 255

type: string
Property validationKey

max length of 255

validationKey: string

Links: API, Interfaces, Classes, Functions, Types, Variables


Interface: ListActionsTransaction
export interface ListActionsTransaction {
    txid: string;
    amount: number;
    status: TransactionStatusApi;
    senderPaymail: string;
    recipientPaymail: string;
    isOutgoing: boolean;
    note: string;
    created_at: string;
    referenceNumber: string;
    labels: string[];
    inputs?: ListActionsTransactionInput[];
    outputs?: ListActionsTransactionOutput[];
}
Interface ListActionsTransaction Details
Property amount

The number of satoshis added or removed from Dojo by this transaction

amount: number
Property created_at

The time the transaction was registered with the Dojo

created_at: string
Property isOutgoing

Whether or not the transaction was created with createTransaction

isOutgoing: boolean
Property labels

A set of all the labels affixed to the transaction

labels: string[]
Property note

The human-readable tag for the transaction, provided by the person who initiated it

note: string
Property recipientPaymail

The Paymail handle of the person who received the transaction

recipientPaymail: string
Property referenceNumber

The Dojo reference number for the transaction

referenceNumber: string
Property senderPaymail

The Paymail handle of the person who sent the transaction

senderPaymail: string
Property status

The current state of the transaction. Common statuses are completed and unproven.

status: TransactionStatusApi
Property txid

The transaction ID

txid: string

Links: API, Interfaces, Classes, Functions, Types, Variables


Interface: ListActionsTransactionInput
export interface ListActionsTransactionInput {
    txid: string;
    vout: number;
    amount: number;
    outputScript: string;
    type: string;
    spendable: boolean;
    spendingDescription?: string;
    basket?: string;
    tags?: string[];
}
Interface ListActionsTransactionInput Details
Property amount

Number of satoshis in the output

amount: number
Property basket

Optionally included basket assignment.

basket?: string
Property outputScript

Hex representation of output locking script

outputScript: string
Property spendable

Whether this output is free to be spent

spendable: boolean
Property spendingDescription

Spending description for this transaction input

spendingDescription?: string
Property tags

Optionally included tag assignments.

tags?: string[]
Property txid

Transaction ID of transaction that created the output

txid: string
Property type

The type of output, for example "P2PKH" or "P2RPH"

type: string
Property vout

Index in the transaction of the output

vout: number

Links: API, Interfaces, Classes, Functions, Types, Variables


Interface: ListActionsTransactionOutput
export interface ListActionsTransactionOutput {
    txid: string;
    vout: number;
    amount: number;
    outputScript: string;
    type: string;
    spendable: boolean;
    description?: string;
    basket?: string;
    tags?: string[];
}
Interface ListActionsTransactionOutput Details
Property amount

Number of satoshis in the output

amount: number
Property basket

Optionally included basket assignment.

basket?: string
Property description

Output description

description?: string
Property outputScript

Hex representation of output locking script

outputScript: string
Property spendable

Whether this output is free to be spent

spendable: boolean
Property tags

Optionally included tag assignments.

tags?: string[]
Property txid

Transaction ID of transaction that created the output

txid: string
Property type

The type of output, for example "P2PKH" or "P2RPH"

type: string
Property vout

Index in the transaction of the output

vout: number

Links: API, Interfaces, Classes, Functions, Types, Variables


Interface: ListActionsResult
export interface ListActionsResult {
    totalTransactions: number;
    transactions: ListActionsTransaction[];
}
Interface ListActionsResult Details
Property totalTransactions

The number of transactions in the complete set

totalTransactions: number
Property transactions

The specific transactions from the set that were requested, based on limit and offset

transactions: ListActionsTransaction[]

Links: API, Interfaces, Classes, Functions, Types, Variables


Interface: CounterpartyKeyLinkageResult
export interface CounterpartyKeyLinkageResult {
    type: "counterparty-revelation";
    prover: string;
    verifier: string;
    counterparty: string;
    revelationTime: string;
    encryptedLinkage: string;
}
Interface CounterpartyKeyLinkageResult Details
Property revelationTime

ISO date string

revelationTime: string

Links: API, Interfaces, Classes, Functions, Types, Variables


Interface: SpecificKeyLinkageResult
export interface SpecificKeyLinkageResult {
    type: "specific-revelation";
    prover: string;
    verifier: string;
    counterparty: string;
    protocolID: ProtocolID;
    encryptedLinkage: string;
}

Links: API, Interfaces, Classes, Functions, Types, Variables


Interface: CreateActionOutputToRedeem
export interface CreateActionOutputToRedeem {
    index: number;
    unlockingScript: string | number;
    spendingDescription?: string;
    sequenceNumber?: number;
}
Interface CreateActionOutputToRedeem Details
Property index

Zero based output index within its transaction to spend.

index: number
Property sequenceNumber

Sequence number to use when spending

sequenceNumber?: number
Property unlockingScript

Hex scriptcode that unlocks the satoshis or the maximum script length (in bytes) if using signAction.

Note that you should create any signatures with SIGHASH_NONE | ANYONECANPAY or similar so that the additional Dojo outputs can be added afterward without invalidating your signature.

unlockingScript: string | number

Links: API, Interfaces, Classes, Functions, Types, Variables


Interface: CreateActionInput
export interface CreateActionInput extends EnvelopeEvidenceApi {
    outputsToRedeem: CreateActionOutputToRedeem[];
}

Links: API, Interfaces, Classes, Functions, Types, Variables


Interface: CreateActionOutput

A specific output to be created as part of a new transactions. These outputs can contain custom scripts as specified by recipients.

export interface CreateActionOutput {
    script: string;
    satoshis: number;
    description?: string;
    basket?: string;
    customInstructions?: string;
    tags?: string[];
}
Interface CreateActionOutput Details
Property basket

Destination output basket name for the new UTXO

basket?: string
Property customInstructions

Custom spending instructions (metadata, string, optional)

customInstructions?: string
Property description

Human-readable output line-item description

description?: string
Property satoshis

The amount of the output in satoshis

satoshis: number
Property script

The output script that will be included, hex encoded

script: string
Property tags

Optional array of output tags to assign to this output.

tags?: string[]

Links: API, Interfaces, Classes, Functions, Types, Variables


Interface: SignActionResult
export interface SignActionResult {
    rawTx: string;
    inputs: Record<string, EnvelopeEvidenceApi>;
    mapiResponses: MapiResponseApi[];
    txid: string;
    log?: string;
}

Links: API, Interfaces, Classes, Functions, Types, Variables


Interface: AbortActionResult
export interface AbortActionResult {
    referenceNumber: string;
    log?: string;
}

Links: API, Interfaces, Classes, Functions, Types, Variables


Interface: DojoOutputToRedeemApi
export interface DojoOutputToRedeemApi {
    index: number;
    unlockingScriptLength: number;
    spendingDescription?: string;
}
Interface DojoOutputToRedeemApi Details
Property index

Zero based output index within its transaction to spend.

index: number
Property unlockingScriptLength

byte length of unlocking script

Note: To protect client keys and utxo control, unlocking scripts are never shared with Dojo.

unlockingScriptLength: number

Links: API, Interfaces, Classes, Functions, Types, Variables


Interface: DojoCreatingTxInstructionsApi
export interface DojoCreatingTxInstructionsApi {
    type: string;
    derivationPrefix?: string;
    derivationSuffix?: string;
    senderIdentityKey?: string;
    paymailHandle?: string;
}

Links: API, Interfaces, Classes, Functions, Types, Variables


Interface: DojoCreatingTxInputsApi
export interface DojoCreatingTxInputsApi extends EnvelopeEvidenceApi {
    outputsToRedeem: DojoOutputToRedeemApi[];
    providedBy: DojoProvidedByApi;
    instructions: Record<number, DojoCreatingTxInstructionsApi>;
}

Links: API, Interfaces, Classes, Functions, Types, Variables


Interface: DojoCreateTxOutputApi

A specific output to be created as part of a new transactions. These outputs can contain custom scripts as specified by recipients.

export interface DojoCreateTxOutputApi {
    script: string;
    satoshis: number;
    description?: string;
    basket?: string;
    customInstructions?: string;
    tags?: string[];
}
Interface DojoCreateTxOutputApi Details
Property basket

Destination output basket name for the new UTXO

basket?: string
Property customInstructions

Custom spending instructions (metadata, string, optional)

customInstructions?: string
Property description

Human-readable output line-item description

description?: string
Property satoshis

The amount of the output in satoshis

satoshis: number
Property script

The output script that will be included, hex encoded

script: string
Property tags

Optional array of output tags to assign to this output.

tags?: string[]

Links: API, Interfaces, Classes, Functions, Types, Variables


Interface: DojoCreatingTxOutputApi
export interface DojoCreatingTxOutputApi extends DojoCreateTxOutputApi {
    providedBy: DojoProvidedByApi;
    purpose?: string;
    destinationBasket?: string;
    derivationSuffix?: string;
    keyOffset?: string;
}

Links: API, Interfaces, Classes, Functions, Types, Variables


Interface: DojoCreateTransactionResultApi
export interface DojoCreateTransactionResultApi {
    inputs: Record<string, DojoCreatingTxInputsApi>;
    outputs: DojoCreatingTxOutputApi[];
    derivationPrefix: string;
    version: number;
    lockTime: number;
    referenceNumber: string;
    paymailHandle: string;
    note?: string;
    log?: string;
}

Links: API, Interfaces, Classes, Functions, Types, Variables


Interface: CreateActionResult
export interface CreateActionResult {
    signActionRequired?: boolean;
    createResult?: DojoCreateTransactionResultApi;
    rawTx?: string;
    inputs: Record<string, EnvelopeEvidenceApi>;
    mapiResponses?: MapiResponseApi[];
    txid?: string;
    log?: string;
}

Links: API, Interfaces, Classes, Functions, Types, Variables


Interface: GetTransactionOutputResult
export interface GetTransactionOutputResult {
    txid: string;
    vout: number;
    amount: number;
    outputScript: string;
    type: string;
    spendable: boolean;
    envelope?: EnvelopeApi;
    customInstructions?: string;
    basket?: string;
    tags?: string[];
}
Interface GetTransactionOutputResult Details
Property amount

Number of satoshis in the output

amount: number
Property basket

If includeBasket option is true, name of basket to which this output belongs.

basket?: string
Property customInstructions

When envelope requested, any custom instructions associated with this output.

customInstructions?: string
Property envelope

When requested and available, output validity support envelope.

envelope?: EnvelopeApi
Property outputScript

Hex representation of output locking script

outputScript: string
Property spendable

Whether this output is free to be spent

spendable: boolean
Property tags

If includeTags option is true, tags assigned to this output.

tags?: string[]
Property txid

Transaction ID of transaction that created the output

txid: string
Property type

The type of output, for example "P2PKH" or "P2RPH"

type: string
Property vout

Index in the transaction of the output

vout: number

Links: API, Interfaces, Classes, Functions, Types, Variables


Interface: SubmitDirectTransactionOutput
export interface SubmitDirectTransactionOutput {
    vout: number;
    satoshis: number;
    basket?: string;
    derivationPrefix?: string;
    derivationSuffix?: string;
    customInstructions?: string;
    senderIdentityKey?: string;
    tags?: string[];
}

Links: API, Interfaces, Classes, Functions, Types, Variables


Interface: SubmitDirectTransaction
export interface SubmitDirectTransaction {
    rawTx: string;
    txid?: string;
    inputs?: Record<string, EnvelopeEvidenceApi>;
    mapiResponses?: MapiResponseApi[];
    proof?: TscMerkleProofApi;
    outputs: SubmitDirectTransactionOutput[];
    referenceNumber?: string;
}

Links: API, Interfaces, Classes, Functions, Types, Variables


Interface: SubmitDirectTransactionResult
export interface SubmitDirectTransactionResult {
    transactionId: number;
    referenceNumber: string;
}

Links: API, Interfaces, Classes, Functions, Types, Variables


Classes

Class: Communicator
export class Communicator {
    static setCached(substrate: string, version: string): Communicator 
    static getCached(): Communicator | undefined 
    async dispatch<P extends object>(args: {
        name: string;
        params: P;
        isGet?: boolean;
        bodyParamKey?: string;
        bodyJsonParams?: boolean;
        contentType?: string;
        nameHttp?: string;
        isNinja?: boolean;
    }): Promise<unknown> 
}

Links: API, Interfaces, Classes, Functions, Types, Variables


Functions

abortActionencryptAsStringproveCertificate
buildTransactionForSignActionUnlockinggetCertificatesrequestGroupPermission
connectToSubstrategetHeightrevealKeyLinkage
createActiongetMerkleRootForHeightrevealKeyLinkageCounterparty
createCertificategetNetworkrevealKeyLinkageSpecific
createHmacgetPreferredCurrencysignAction
createSignaturegetPublicKeystampLog
decryptgetRandomIDstampLogFormat
decryptAsArraygetTransactionOutputssubmitDirectTransaction
decryptAsStringgetVersionunbasketOutput
discoverByAttributesisAuthenticatedverifyHmac
discoverByIdentityKeylistActionsverifySignature
encryptmakeHttpRequestwaitForAuthentication
encryptAsArraypromiseWithTimeout

Links: API, Interfaces, Classes, Functions, Types, Variables


Function: makeHttpRequest
export default async function makeHttpRequest<R>(routeURL: string, requestInput: RequestInit = {}): Promise<R> 

Links: API, Interfaces, Classes, Functions, Types, Variables


Function: promiseWithTimeout

Provides a timedout promise.

export default async function promiseWithTimeout<T>(obj: {
    timeout: number;
    promise: Promise<T>;
    error?: Error;
}): Promise<T> 
Function promiseWithTimeout Details

Argument Details

  • obj
    • All parameters for this function are provided in an object

Links: API, Interfaces, Classes, Functions, Types, Variables


Function: getRandomID
export default function getRandomID(): string 

Links: API, Interfaces, Classes, Functions, Types, Variables


Function: connectToSubstrate
export default async function connectToSubstrate(): Promise<Communicator> 

Links: API, Interfaces, Classes, Functions, Types, Variables


Function: stampLog

If a log is being kept, add a time stamped line.

export function stampLog(log: string | undefined, lineToAdd: string): string | undefined 
Function stampLog Details

Returns

undefined or log extended by time stamped lineToAdd and new line.

Argument Details

  • log
    • Optional time stamped log to extend
  • lineToAdd
    • Content to add to line.

Links: API, Interfaces, Classes, Functions, Types, Variables


Function: stampLogFormat

Replaces individual timestamps with delta msecs. Looks for two network crossings and adjusts clock for clock skew if found. Assumes log built by repeated calls to stampLog

export function stampLogFormat(log?: string): string 
Function stampLogFormat Details

Returns

reformated multi-line event log

Argument Details

  • log
    • Each logged event starts with ISO time stamp, space, rest of line, terminated by \n.

Links: API, Interfaces, Classes, Functions, Types, Variables


Function: abortAction

Aborts a previously created action which required custom input unlocking script signing.

export async function abortAction(args: {
    referenceNumber: string;
    log?: string;
}): Promise<AbortActionResult> 
Function abortAction Details

Returns

An Action object containing "txid", "rawTx" "mapiResponses" and "inputs".

Argument Details

  • args
    • All parameters for this function are provided in an object

Links: API, Interfaces, Classes, Functions, Types, Variables


Function: createAction

Creates and broadcasts a BitCoin transaction with the provided inputs and outputs.

export async function createAction(args: {
    inputs?: Record<string, CreateActionInput>;
    outputs?: CreateActionOutput[];
    lockTime?: number;
    version?: number;
    description: string;
    labels?: string[];
    acceptDelayedBroadcast?: boolean;
    log?: string;
}): Promise<CreateActionResult> 
Function createAction Details

Returns

An Action object containing "txid", "rawTx" "mapiResponses" and "inputs".

Argument Details

  • args
    • All parameters for this function are provided in an object

Links: API, Interfaces, Classes, Functions, Types, Variables


Function: createHmac

Creates a SHA-256 HMAC with a key belonging to the user.

export async function createHmac(args: {
    data: Uint8Array | string;
    protocolID: ProtocolID;
    keyID: string;
    description?: string;
    counterparty?: string;
    privileged?: boolean;
}): Promise<Uint8Array> 
Function createHmac Details

Returns

The SHA-256 HMAC of the data.

Argument Details

  • args
    • All parameters are passed in an object.

Links: API, Interfaces, Classes, Functions, Types, Variables


Function: createCertificate

Creates a signed certificate

export async function createCertificate(args: {
    certificateType: string;
    fieldObject: Record<string, string>;
    certifierUrl: string;
    certifierPublicKey: string;
}): Promise<CreateCertificateResult> 
Function createCertificate Details

Returns

A signed certificate

Argument Details

  • args
    • All parameters for this function are provided in an object

Links: API, Interfaces, Classes, Functions, Types, Variables


Function: createSignature

Creates a digital signature with a key belonging to the user. The SHA-256 hash of the data is used with ECDSA.

To allow other users to externally verify the signature, use getPublicKey with the same protocolID, keyID and privileged parameters. The signature should be valid under that public key.

export async function createSignature(args: {
    data: Uint8Array | string;
    protocolID: ProtocolID;
    keyID: string;
    description?: string;
    counterparty?: string;
    privileged?: boolean;
}): Promise<Uint8Array> 
Function createSignature Details

Returns

The ECDSA message signature.

Argument Details

  • args
    • All parameters are passed in an object.

Links: API, Interfaces, Classes, Functions, Types, Variables


Function: decrypt

Decrypts data with a key belonging to the user. The same protocolID, keyID, counterparty and privileged parameters that were used during encryption must be used to successfully decrypt.

export async function decrypt(args: {
    ciphertext: string | Uint8Array;
    protocolID: ProtocolID;
    keyID: string;
    description?: string;
    counterparty?: string;
    privileged?: boolean;
    returnType?: "Uint8Array" | "string";
}): Promise<string | Uint8Array> 
Function decrypt Details

Returns

The decrypted plaintext.

Argument Details

  • args
    • All parameters are passed in an object.

Links: API, Interfaces, Classes, Functions, Types, Variables


Function: decryptAsString

Decrypts data with a key belonging to the user. The same protocolID, keyID, counterparty and privileged parameters that were used during encryption must be used to successfully decrypt.

export async function decryptAsString(args: {
    ciphertext: string | Uint8Array;
    protocolID: ProtocolID;
    keyID: string;
    description?: string;
    counterparty?: string;
    privileged?: boolean;
}): Promise<string> 
Function decryptAsString Details

Returns

The decrypted plaintext TextDecoder decoded to string.

Argument Details

  • args
    • All parameters are passed in an object.

Links: API, Interfaces, Classes, Functions, Types, Variables


Function: decryptAsArray

Decrypts data with a key belonging to the user. The same protocolID, keyID, counterparty and privileged parameters that were used during encryption must be used to successfully decrypt.

export async function decryptAsArray(args: {
    ciphertext: string | Uint8Array;
    protocolID: ProtocolID;
    keyID: string;
    description?: string;
    counterparty?: string;
    privileged?: boolean;
}): Promise<Uint8Array> 
Function decryptAsArray Details

Returns

The decrypted plaintext.

Argument Details

  • args
    • All parameters are passed in an object.

Links: API, Interfaces, Classes, Functions, Types, Variables


Function: discoverByAttributes

Resolves identity information by attributes from the user's trusted certifiers.

export async function discoverByAttributes(args: {
    attributes: Record<string, string>;
    description: string;
}): Promise<object[]> 
Function discoverByAttributes Details

Argument Details

  • obj
    • All parameters are provided in an object

Links: API, Interfaces, Classes, Functions, Types, Variables


Function: discoverByIdentityKey

Resolves identity information by identity key from the user's trusted certifiers.

export async function discoverByIdentityKey(args: {
    identityKey: string;
    description: string;
}): Promise<object[]> 
Function discoverByIdentityKey Details

Argument Details

  • obj
    • All parameters are provided in an object

Links: API, Interfaces, Classes, Functions, Types, Variables


Function: getPreferredCurrency

Returns the user's preferred currency for displaying within apps

export async function getPreferredCurrency(args: {
    description?: string;
}): Promise<string> 
Function getPreferredCurrency Details

Returns

The user's preferred currency

Argument Details

  • args
    • All parameters are passed in an object.

Links: API, Interfaces, Classes, Functions, Types, Variables


Function: encrypt

Encrypts data with a key belonging to the user. If a counterparty is provided, also allows the counterparty to decrypt the data. The same protocolID, keyID, counterparty and privileged parameters must be used when decrypting.

export async function encrypt(args: {
    plaintext: string | Uint8Array;
    protocolID: ProtocolID;
    keyID: string;
    description?: string;
    counterparty?: string;
    privileged?: boolean;
    returnType?: "Uint8Array" | "string";
}): Promise<string | Uint8Array> 
Function encrypt Details

Returns

The encrypted ciphertext.

Argument Details

  • args
    • All parameters are passed in an object.

Links: API, Interfaces, Classes, Functions, Types, Variables


Function: encryptAsString

Encrypts data with a key belonging to the user. If a counterparty is provided, also allows the counterparty to decrypt the data. The same protocolID, keyID, counterparty and privileged parameters must be used when decrypting.

export async function encryptAsString(args: {
    plaintext: string | Uint8Array;
    protocolID: string;
    keyID: string;
    description?: string;
    counterparty?: string;
    privileged?: boolean;
}): Promise<string> 
Function encryptAsString Details

Returns

The encrypted ciphertext data as base64 encoded string.

Argument Details

  • args
    • All parameters are passed in an object.

Links: API, Interfaces, Classes, Functions, Types, Variables


Function: encryptAsArray

Encrypts data with a key belonging to the user. If a counterparty is provided, also allows the counterparty to decrypt the data. The same protocolID, keyID, counterparty and privileged parameters must be used when decrypting.

export async function encryptAsArray(args: {
    plaintext: string | Uint8Array;
    protocolID: string;
    keyID: string;
    description?: string;
    counterparty?: string;
    privileged?: boolean;
}): Promise<Uint8Array> 
Function encryptAsArray Details

Returns

The encrypted ciphertext data.

Argument Details

  • args
    • All parameters are passed in an object.

Links: API, Interfaces, Classes, Functions, Types, Variables


Function: getCertificates

Returns found certificates

export async function getCertificates(args: {
    certifiers: string[];
    types: Record<string, string[]>;
}): Promise<CreateCertificateResult[]> 
Function getCertificates Details

Returns

An object containing the found certificates

Argument Details

  • obj
    • All parameters for this function are provided in an object

Links: API, Interfaces, Classes, Functions, Types, Variables


Function: getHeight

Returns the current chain height of the network

export async function getHeight(): Promise<number> 
Function getHeight Details

Returns

The current chain height

Links: API, Interfaces, Classes, Functions, Types, Variables


Function: getMerkleRootForHeight

A method to verify the validity of a Merkle root for a given block height.

export async function getMerkleRootForHeight(height: number): Promise<string | undefined> 
Function getMerkleRootForHeight Details

Returns

Returns the merkle root for height or undefined, if height doesn't have a known merkle root or is invalid.

Links: API, Interfaces, Classes, Functions, Types, Variables


Function: getNetwork

Returns which BSV network we are using (mainnet or testnet)

export async function getNetwork(format?: "default" | "nonet"): Promise<string> 
Function getNetwork Details

Returns

The current BSV network formatted as requested.

Argument Details

  • format
    • for the returned string. Either with (default) or without (nonet) a 'net' suffix.

Links: API, Interfaces, Classes, Functions, Types, Variables


Function: getPublicKey

Returns the public key. If identityKey is specified, returns the current user's identity key. If a counterparty is specified, derives a public key for the counterparty.

export async function getPublicKey(args: {
    protocolID?: ProtocolID;
    keyID?: string;
    privileged?: boolean;
    identityKey?: boolean;
    reason?: string;
    counterparty?: string;
    forSelf?: boolean;
}): Promise<string> 
Function getPublicKey Details

Returns

The user's public key

Argument Details

  • args
    • All parameters are passed in an object.

Links: API, Interfaces, Classes, Functions, Types, Variables


Function: getTransactionOutputs

Returns a set of transaction outputs that Dojo has tracked

export async function getTransactionOutputs(args: {
    basket?: string;
    tracked?: boolean;
    spendable?: boolean;
    tags?: string[];
    type?: string;
    includeEnvelope?: boolean;
    includeBasket?: boolean;
    includeCustomInstructions?: boolean;
    includeTags?: boolean;
    tagQueryMode?: "all" | "any";
    limit?: number;
    offset?: number;
}): Promise<GetTransactionOutputResult[]> 
Function getTransactionOutputs Details

Returns

A set of outputs that match the criteria

Argument Details

  • args
    • All parameters are given in an object

Links: API, Interfaces, Classes, Functions, Types, Variables


Function: getVersion

Returns the current version of the kernal

export async function getVersion(): Promise<string> 
Function getVersion Details

Returns

The current kernel version (e.g. "0.3.49")

Links: API, Interfaces, Classes, Functions, Types, Variables


Function: isAuthenticated

Checks if a user is currently authenticated.

export async function isAuthenticated(): Promise<boolean> 
Function isAuthenticated Details

Returns

Returns whether a user is currently authenticated.

Links: API, Interfaces, Classes, Functions, Types, Variables


Function: listActions

Returns a list of Actions with a given label

export async function listActions(args: {
    label: string;
    addInputsAndOutputs?: boolean;
    includeBasket?: boolean;
    includeTags?: boolean;
    noRawTx?: boolean;
    limit?: number;
    offset?: number;
}): Promise<ListActionsResult> 
Function listActions Details

Returns

A set of outputs that match the criteria

Argument Details

  • args
    • All parameters are given in an object

Links: API, Interfaces, Classes, Functions, Types, Variables


Function: proveCertificate

Creates certificate proof specifically for verifier

export async function proveCertificate(args: {
    certificate: CertificateApi;
    fieldsToReveal: string[];
    verifierPublicIdentityKey: string;
}): Promise<ProveCertificateResult> 
Function proveCertificate Details

Returns

A certificate for presentation to the verifier for field examination

Argument Details

  • args
    • All parameters for this function are provided in an object

Links: API, Interfaces, Classes, Functions, Types, Variables


Function: requestGroupPermission

Requests group permissions for an application.

export async function requestGroupPermission(): Promise<void> 
Function requestGroupPermission Details

Returns

Resolves after group permissions are completed by the user.

Links: API, Interfaces, Classes, Functions, Types, Variables


Function: revealKeyLinkage

Reveals the linkage between a key held by this user and a key held by another user. In one mode, reveals all keys associated with a counterparty, in the other mode reveals only the linkage of a specific interaction.

Encrypts the linkage value so that only the specified verifier can access it. Refer to BRC-72 for full details.

export async function revealKeyLinkage(args: {
    mode: "counterparty" | "specific";
    counterparty: string;
    verifier: string;
    protocolID: ProtocolID;
    keyID: string;
    description: string;
    privileged?: boolean;
}): Promise<CounterpartyKeyLinkageResult | SpecificKeyLinkageResult> 
Function revealKeyLinkage Details

Returns

The revealed linkage payload, as described in BRC-72.

Argument Details

  • args
    • All parameters are passed in an object.

Links: API, Interfaces, Classes, Functions, Types, Variables


Function: revealKeyLinkageCounterparty

Reveals the linkage between a key held by this user and a key held by another user. Reveals all keys associated with a counterparty,

Encrypts the linkage value so that only the specified verifier can access it. Refer to BRC-72 for full details.

export async function revealKeyLinkageCounterparty(args: {
    counterparty: string;
    verifier: string;
    protocolID: ProtocolID;
    description: string;
    privileged?: boolean;
}): Promise<CounterpartyKeyLinkageResult> 
Function revealKeyLinkageCounterparty Details

Returns

The revealed linkage payload, as described in BRC-72.

Argument Details

  • args
    • All parameters are passed in an object.

Links: API, Interfaces, Classes, Functions, Types, Variables


Function: revealKeyLinkageSpecific

Reveals the linkage between a key held by this user and a key held by another user. Reveals only the linkage of a specific interaction.

Encrypts the linkage value so that only the specified verifier can access it. Refer to BRC-72 for full details.

export async function revealKeyLinkageSpecific(args: {
    counterparty: string;
    verifier: string;
    protocolID: ProtocolID;
    keyID: string;
    description: string;
    privileged?: boolean;
}): Promise<SpecificKeyLinkageResult> 
Function revealKeyLinkageSpecific Details

Returns

The revealed linkage payload, as described in BRC-72.

Argument Details

  • args
    • All parameters are passed in an object.

Links: API, Interfaces, Classes, Functions, Types, Variables


Function: signAction

Completes a previously created action which required custom input unlocking script signing.

export async function signAction(args: {
    inputs?: Record<string, CreateActionInput>;
    createResult: DojoCreateTransactionResultApi;
    acceptDelayedBroadcast?: boolean;
    log?: string;
}): Promise<SignActionResult> 
Function signAction Details

Returns

An Action object containing "txid", "rawTx" "mapiResponses" and "inputs".

Argument Details

  • args
    • All parameters for this function are provided in an object

Links: API, Interfaces, Classes, Functions, Types, Variables


Function: submitDirectTransaction

Submits a transaction directly to a ninja

export async function submitDirectTransaction(args: {
    protocol?: string;
    transaction: SubmitDirectTransaction;
    senderIdentityKey: string;
    note: string;
    amount: number;
    labels?: string[];
    derivationPrefix?: string;
}): Promise<SubmitDirectTransactionResult> 
Function submitDirectTransaction Details

Returns

Object containing reference number, status=success, and human-readable note acknowledging the transaction

Argument Details

  • args
    • All parameters for this function are provided in an object

Links: API, Interfaces, Classes, Functions, Types, Variables


Function: unbasketOutput

Removes the uniquely identified output's basket assignment.

The output will no longer belong to any basket.

This is typically only useful for outputs that are no longer usefull.

export async function unbasketOutput(args: {
    txid: string;
    vout: number;
    basket: string;
}): Promise<void> 
Function unbasketOutput Details

Argument Details

  • args
    • All parameters are given in an object

Links: API, Interfaces, Classes, Functions, Types, Variables


Function: verifyHmac

Verifies that a SHA-256 HMAC was created with a key that belongs to the user.

export async function verifyHmac(args: {
    data: Uint8Array | string;
    hmac: Uint8Array | string;
    protocolID: ProtocolID;
    keyID: string;
    description?: string;
    counterparty?: string;
    privileged?: boolean;
}): Promise<boolean> 
Function verifyHmac Details

Returns

Whether the HMAC has been erified.

Argument Details

  • args
    • All parameters are passed in an object.

Links: API, Interfaces, Classes, Functions, Types, Variables


Function: verifySignature

Verifies that a digital signature was created with a key belonging to the user.

export async function verifySignature(args: {
    data: Uint8Array | string;
    signature: Uint8Array | string;
    protocolID: ProtocolID;
    keyID: string;
    description?: string;
    counterparty?: string;
    privileged?: boolean;
    reason?: string;
}): Promise<boolean> 
Function verifySignature Details

Returns

An whether the signature was successfully verified.

Argument Details

  • args
    • All parameters are passed in an object.

Links: API, Interfaces, Classes, Functions, Types, Variables


Function: waitForAuthentication

Waits for a user to be authenticated.

export async function waitForAuthentication(): Promise<boolean> 
Function waitForAuthentication Details

Returns

Always returns true

Links: API, Interfaces, Classes, Functions, Types, Variables


Function: buildTransactionForSignActionUnlocking

Constructs a

export async function buildTransactionForSignActionUnlocking(ninjaInputs: Record<string, CreateActionInput>, createResult: DojoCreateTransactionResultApi): Promise<Transaction> 
Function buildTransactionForSignActionUnlocking Details

Argument Details

  • ninjaInputs
    • Ninja inputs as passed to createAction
  • createResult
    • Create transaction results returned by createAction when signActionRequires is true.
  • changeKeys
    • Dummy keys can be used to create a transaction with which to generate Ninja input lockingScripts.

Links: API, Interfaces, Classes, Functions, Types, Variables


Types

DojoProvidedByApi
ProtocolID
TransactionStatusApi

Links: API, Interfaces, Classes, Functions, Types, Variables


Type: ProtocolID
export type ProtocolID = string | [
    0 | 1 | 2,
    string
]

Links: API, Interfaces, Classes, Functions, Types, Variables


Type: TransactionStatusApi
export type TransactionStatusApi = "completed" | "failed" | "unprocessed" | "sending" | "unproven" | "unsigned"

Links: API, Interfaces, Classes, Functions, Types, Variables


Type: DojoProvidedByApi
export type DojoProvidedByApi = "you" | "dojo" | "you-and-dojo"

Links: API, Interfaces, Classes, Functions, Types, Variables


Variables

Variable: BabbageSDK
BabbageSDK = {
    abortAction,
    createAction,
    createHmac,
    createCertificate,
    createSignature,
    decrypt,
    decryptAsArray,
    decryptAsString,
    discoverByAttributes,
    discoverByIdentityKey,
    getPreferredCurrency,
    encrypt,
    encryptAsArray,
    encryptAsString,
    getCertificates,
    getHeight,
    getMerkleRootForHeight,
    getNetwork,
    getPublicKey,
    getTransactionOutputs,
    getVersion,
    isAuthenticated,
    listActions,
    proveCertificate,
    requestGroupPermission,
    revealKeyLinkage,
    revealKeyLinkageCounterparty,
    revealKeyLinkageSpecific,
    signAction,
    submitDirectTransaction,
    unbasketOutput,
    verifyHmac,
    verifySignature,
    waitForAuthentication,
}

Links: API, Interfaces, Classes, Functions, Types, Variables


SDK Connection Substrates

The Babbage SDK connects to a running Computing with Integrity (CWI) kernel instance, allowing applications to plug into user-owned identities. There are currently three substrates (connection modes) that the SDK can use to link an application to a MetaNet identity provider:

  1. Window API: In a web browser, the SDK will first try to use a window.CWI interface for communicating with the kernel.
  2. Babbage XDM: In a browser or iframe window, the SDK will next try to use XDM (cross-document messaging) to communicate with a running kernel instance.
  3. Cicada API: Lastly, the SDK will attempt to communicate over localhost:3301 to a running HTTP MetaNet service. This Port 3301 Substrate is named Cicada, in honor of Cicada 3301.

License

The license for this library, which is a wrapper for the proprietary Babbage API, is the Open BSV License. It can only be used on the BSV blockchain. The Babbage API itself, including the rights to create and host Babbage software or any other related infrastructure, is not covered by the Open BSV License and remains proprietary and restricted. The Open BSV License only extends to the code in this repository, and you are not permitted to host Babbage software, servers or create copies or alternative implementations of the proprietary Babbage API without other permission.

FAQs

Last updated on 11 May 2024

Did you know?

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc