utxoninja

Bitcoin and Paymail Management Done Right

Usage no npm install needed!

<script type="module">
  import utxoninja from 'https://cdn.skypack.dev/utxoninja';
</script>

README

utxoninja

Bitcoin and Paymail Management Done Right

The code is on GitHub and the package is available through NPM.

There is a web interface that wraps this library available at ninja.babbage.systems.

Refer to the Dojo API docs for additional, useful information.

With the exception of getTransactionWithOutputs (which just automates the creation and signing of the simpler transactions), most of the functions here are just one-to-one mappings of the Dojo API endpoints themselves. HTTP, API request authentication and the parsing of responses are handled for you by this library.

To get started making transactions, you should check out getTransactionWithOutputs after funding your account

If you need help, don't hesitate to send a message to Ty Everett on the Atlantis Slack.

API

Table of Contents

getPaymail

Returns the current Paymail handle

Parameters

  • obj Object All parameters are given in an object (optional, default {})

    • obj.xprivKey String The key of the user
    • obj.config Object? Config object, see config section (optional, default CONFIG)

Returns Promise<String> The Paymail handle

setPaymail

Changes the Paymail handle of the user. NOTE that the old handle will be available for others to use. NOTE that to prevent span, you may only do this if there is at least one unspent output under Dojo management.

Parameters

  • obj Object All parameters are given in an object (optional, default {})

    • obj.xprivKey String The key of the user
    • obj.config Object? Config object, see config section (optional, default CONFIG)
    • obj.paymail String A new Paymail handle

Returns Promise<Object> A success object with status: "success"

getSettings

Returns the current receive policy

Parameters

  • obj Object All parameters are given in an object (optional, default {})

    • obj.xprivKey String The key of the user
    • obj.config Object? Config object, see config section (optional, default CONFIG)

Returns Promise<Object> The receive policy of the user, see the receive policy section of the Dojo docs

setSettings

Sets a new receive policy

Parameters

  • obj Object All parameters are given in an object (optional, default {})

    • obj.xprivKey String The key of the user
    • obj.config Object? Config object, see config section (optional, default CONFIG)
    • obj.settings Object A receive policy object. See the Dojo API docs for details on the fields in the receive policy (optional, default {})

Returns Promise<Object> A success object with status: "success"

Avatar

Type: Object

Properties

  • name String The name of the user
  • photoURL String An HTTPS or UHRP URL to a photo of the user

getAvatar

Returns the name and photo URL of the user

Parameters

  • obj Object All parameters are given in an object (optional, default {})

    • obj.xprivKey String The key of the user
    • obj.config Object? Config object, see config section (optional, default CONFIG)

Returns Promise<Avatar> The avatar of the user

setAvatar

Sets a new name and photo URL

Parameters

  • obj Object All parameters are given in an object (optional, default {})

    • obj.xprivKey String The key of the user
    • obj.config Object? Config object, see config section (optional, default CONFIG)
    • obj.name String A new name
    • obj.photoURL String A new UHRP or HTTPS URL to a photo of the user

Returns Promise<Object> A success object with status: "success"

GetTransactionsTx

Type: Object

Properties

  • txid String The transaction ID
  • amount Number The number of satoshis added or removed from Dojo by this transaction
  • status String The current state of the transaction. Common statuses are completed and waitingForSenderToSend.
  • senderPaymail String The Paymail handle of the person who sent the transaction
  • recipientPaymail String The Paymail handle of the person who received the transaction
  • isOutgoing Boolean Whether or not the transaction was created with createTransaction
  • note String The human-readable tag for the transaction, provided by the person who initiated it
  • created_at String The time the transaction was registered with the Dojo
  • referenceNumber String The Dojo reference number for the transaction
  • labels Array<String> A set of all the labels affixed to the transaction

GetTransactionsResult

Type: Object

Properties

  • totalTransactions Number The number of transactions in the complete set
  • transactions Array<GetTransactionsTx> The specific transactions from the set that were requested, based on limit and offset

getTransactions

Returns a set of transactions that match the criteria

Parameters

  • obj Object All parameters are given in an object (optional, default {})

    • obj.xprivKey String The key of the user
    • obj.config Object? Config object, see config section (optional, default CONFIG)
    • obj.involving String? Only include transactions sent to or reveiced from this Paymail handle
    • obj.status String? If provided, only transactions with the given status will be returned
    • obj.label String? Only include transactions affixed with this label
    • obj.limit Number Include only this maximum number of transactions in the set (optional, default 25)
    • obj.offset Number Include transactions offset by this number in the full set (optional, default 0)
    • obj.orderBy String Sort order, can be newest-first or oldest-first (optional, default newest-first)

Returns Promise<GetTransactionsResult> The transactions and the total size of the set

GetPendingTransactionsTx

Type: Object

Properties

  • amount Number The number of satoshis added or removed from Dojo by this transaction
  • senderPaymail String The Paymail handle of the person who sent the transaction
  • created_at String The time the transaction was registered with the Dojo
  • referenceNumber String The Dojo reference number for the transaction

getPendingTransactions

Returns a set of all transactions that need to be signed and submitted, or canceled

Parameters

  • obj Object All parameters are given in an object (optional, default {})

    • obj.xprivKey String The key of the user
    • obj.config Object? Config object, see config section (optional, default CONFIG)

Returns Promise<Array<GetPendingTransactionsTx>> The array of pending transactions

getTotalOfAmounts

Returns the total of the amounts of transactions that fall under certain criteria

Parameters

  • obj Object All parameters are given in an object (optional, default {})

    • obj.xprivKey String The key of the user
    • obj.config Object? Config object, see config section (optional, default CONFIG)
    • obj.involving String? The Paymail handle of a user who must be involved with the transactions
    • obj.label String? The label that must be affixed to the transactions
    • obj.direction String Must be either "incoming" or "outgoing", transactions in only one direction can be totaled
    • obj.startTime Number? The earlies time of the transactions to include, an epoch timestamp in seconds
    • obj.endTime Number? The latest time of the transactions to include, an epoch timestamp in seconds

Returns Promise<Object> An object containing total, a number of satoshis

getTotalValue

Returns the total of unspent outputs

Parameters

  • obj Object All parameters are given in an object (optional, default {})

    • obj.xprivKey String The key of the user
    • obj.config Object? Config object, see config section (optional, default CONFIG)

Returns Promise<Object> An object containing total, a non-negative number of satoshis

GetTxWithOutputsOutput

Type: Object

Properties

  • script String The hex representing the locking script of the output
  • satoshis Number The number of satoshis to put in the output

GetTxWithOutputsResult

Type: Object

Properties

  • rawTx String The serialized, signed transaction that is ready for broadcast
  • referenceNumber String The reference number that should now be provided back to processTransaction (or updateTransactionStatus`)
  • inputs Object This is the fully-formed inputs field of this transaction, as per the SPV Envelope specification.
  • amount Number The amount of the transaction

getTransactionWithOutputs

Creates and signs a transaction with specified outputs, so that it can be processed with processTransaction. This is a higher-level wrapper around createTransaction so that you do not need to manually handle signing, when you are not providing any non-Dojo inputs.

Use this by default, and fall back to createTransaction if you need more customization.

Parameters

  • obj Object All parameters are given in an object (optional, default {})

    • obj.xprivKey String The key of the user
    • obj.config Object? Config object, see config section (optional, default CONFIG)
    • obj.outputs Array<GetTxWithOutputsOutput> A set of outputs to include, each with script and satoshis.
    • obj.rPuzzleInputSigningWIF String? A WIF-formatted private key that, if provided, requires at least one input to be P2RPH, and uses the key to sign when redeeming it.
    • obj.feePerKb Number The number of satoshis to pay per KB of block space used by this transaction. (optional, default 500)
    • obj.labels Array<String>? A set of label strings to affix to the transaction
    • obj.inputs Object? Input scripts to spend as part of this transaction. This is an object whose keys are TXIDs and whose values are Everett-style transaction envelopes that contain an additional field called outputsToRedeen. This is an array of objects, each containing index and unlockingScript properties. The index property is the output number in the transaction you are spending, and unlockingScript is the hex scriptcode that unlocks the satoshis. 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. (optional, default {})
    • obj.autoProcess Boolean Whether the transaction should be processed automatically with processTransaction. Note that this will return mapiResponses and note instead of referenceNumber (optional, default false)

Returns Promise<GetTxWithOutputsResult> The serialized transaction, inputs, reference number and amount

TxRedeemableOutput

Type: Object

Properties

  • index Number The index of the output to redeem in the transaction
  • unlockingScriptLength Number The byte length of the unlocking script you intend to use to unlock this output

TxOutput

Type: Object

Properties

  • satoshis Number The amount of satoshis that will be in the output
  • script String The hex string representing the output locking script

InputTemplate

Type: Object

Properties

  • providedBy String Identifies the provider(s) of the output(s) to redeem trom the associated transaction. Can be "dojo", "you" (for externally-provided inputs), or "you-and-dojo"
  • outputsToRedeem Array<Number> A set of numbers indicating the index of each output that should be redeemed from this transaction
  • rawTx String As specified in the SPV envelope specification, the serialized transaction is provided
  • instructions Object? When "providedBy" is "dojo" or "you-and-dojo", this is an object whose keys are numbers (from "outputsToRedeem") that correspond to Dojo-provided inputs

OutputTemplate

Type: Object

Properties

  • satoshis Number The number of satoshis that will be put into this output
  • script String The hex string representing the output script
  • providedBy String Who is responsible for this output - Either "you" or "dojo"
  • purpose String? When the output is provided by Dojo, its purpose can either be "change" or "service-charge"
  • destinationBasket String? When the output is provided by Dojo, this indicates which basket it is destined for

TransactionTemplate

Type: Object

Properties

  • referenceNumber String The reference number you will use to either process the transaction (with processTransaction) or cancel it (with updateTransactionStatus).
  • inputs Object<InputTemplate> The set of input templates for this transaction. This is an object whose keys are TXIDs and whose values are InputTemplate objects.
  • outputs Array<OutputTemplate> The set of output templates to include in this transaction

TxInputEnvelope

Type: Object

Properties

  • rawTx String The serialized hex of the transaction
  • inputs Object? As specified by SPV Envelope
  • mapiResponses Array<Object>? As specified by SPV Envelope
  • proof Object? As specified by SPV Envelope
  • outputsToRedeem Array<TxRedeemableOutput> In addition to the fields for a normal envelope, this is used to indicate the outputs in the transaction that you are redeeming here.

createTransaction

Creates a new transaction that must be processed with processTransaction after you sign it

Parameters

  • obj Object All parameters are given in an object (optional, default {})

    • obj.xprivKey String The key of the user

    • obj.config Object? Config object, see config section (optional, default CONFIG)

    • obj.inputs Object<TxInputEnvelope>? Specify any additional inputs to the transaction (if any) that are not to be provided by the Dojo. If you do not provide inputs here, or if they are insufficient, Dojo will select additional inputs for you to sign. To control this input selection behavior, see the inputSelection parameter. This inputs parameter is an object whose keys are TXIDs of input transactions, and whose values are their associated SPV envelopes.

    • obj.inputSelection Object? If Dojo needs to select more inputs beyond what you provided in the inputs parameter, this parameter describes which kinds of inputs can be selected, and from where.

      • obj.inputSelection.disable Boolean? This is a boolean that, when true, will forbid Dojo from adding any additional inputs to your transaction, beyond what you specified in the inputs parameter. Thus, if you have not sufficiently funded the transaction yourself, or if inputs is empty, you will get an error.
      • obj.inputSelection.maxUnconfirmedChainLength Number? An integer representing the maximum length for any chain of unconfirmed parents that a selected input can have. When -1 (the default), no maximum is specified. Cannot be zero. When 1, indicates that the input must itself be confirmed. When 2, input parents must be confirmed. 3 denotes grandparents, 4 great-grandparents and so forth.
    • obj.outputs Array<TxOutput>? External outputs that you will include when you create this transaction. These outputs can contain custom scripts as specified by recipients. If the inputs to the transaction go beyond what is needed to fund these outputs (plus the transaction fee), additional Dojo-managed UTXOs will be generated to collect the remainder (see the outputGeneration parameter for more on this).

    • obj.outputGeneration Object? If Dojo needs to generate additional outputs for the transaction beyond what was specified, this object describes what kind of outputs to generate, and where they should be kept.

      • obj.outputGeneration.method String The method used to generate outputs. "auto" selects the amount and types of generated outputs based on the selected basket's configuration for how many of each type to keep on hand, then uses Benford's law to distribute the satoshis across them. "single" just uses one output, randomly selected from the available types, that contains all the satoshis. (optional, default auto)
    • obj.fee Object? Represents the fee the transaction will pay

      • obj.fee.model String Fee model to use, currently always "sat/kb" (optional, default sat/kb)
      • obj.fee.value Number When the fee model is "sat/kb", this is the number of satoshis per kilobyte of block space that the transaction will pay. (optional, default 500)
    • obj.labels Array<String>? The labels to affix to this transaction

Returns Promise<TransactionTemplate> The template you need to sign and process

processTransaction

After a transaction is created (with createTransaction or with getTransactionWithOutputs) this is used to process the transaction, thereby activating any change outputs and flagging designated inputs as spent

Parameters

  • obj Object All parameters are given in an object (optional, default {})

    • obj.xprivKey String The key of the user
    • obj.config Object? Config object, see config section (optional, default CONFIG)
    • obj.submittedTransaction String The transaction that has been created and signed
    • obj.note String? A numan-readable note describing the transaction
    • obj.recipient String? The Paymail handle for the recipient of the transaction
    • obj.reference String The reference number provided by createTransaction or getTransactionWithOutputs

Returns Promise<Object> An object containing a note field with a success message, and mapiResponses, for use in creating an SPV Envelope

processPendingTransactions

Signs and processes all pending transactions, useful when recovering from an error or crash, or on startup. If a transaction fails to process, marks it as failed.

Parameters

  • obj Object All parameters are given in an object (optional, default {})

    • obj.xprivKey String The key of the user
    • obj.config Object? Config object, see config section (optional, default CONFIG)

Returns Promise Resolves once the operation is complete

markMissingTxInputsAsSpent

This function has been deprecated, because blockchain scanning services it relied upon have been shut down.

TransactionOutputDescriptor

Type: Object

Properties

  • txid String Transaction ID of transaction that created the output
  • vout Number Index in the transaction of the output
  • amount Number Number of satoshis in the output
  • outputScript String Hex representation of output locking script
  • type String The type of output, for example "P2PKH" or "P2RPH"
  • spendable Boolean Whether this output is free to be spent

getTransactionOutputs

Returns a set of transaction outputs that Dojo has tracked

Parameters

  • obj Object All parameters are given in an object (optional, default {})

    • obj.xprivKey String The key of the user
    • obj.config Object? Config object, see config section (optional, default CONFIG)
    • obj.spendable Boolean? If given as true or false, only outputs that have or have not (respectively) been spent will be returned. If not given, both spent and unspent outputs will be returned.
    • obj.type String? If provided, only outputs of the specified type will be returned. If not provided, outputs of all types will be returned.
    • obj.limit Number? Provide a limit on the number of outputs that will be returned. (optional, default 25)
    • obj.offset Number? Provide an offset into the list of outputs. (optional, default 0)

Returns Promise<Array<TransactionOutputDescriptor>> A set of outputs that match the criteria

updateTransactionStatus

Use this endpoint to update the status of a transaction. This is useful for flagging incomplete transactions as aborted or reverting a completed transaction back into a pending status if it never got confirmed. Setting the status to "completed" or "waitingForSenderToSend" will make any selected UTXOs unavailable for spending, while any other status value will free up the UTXOs for use in other transactions.

Parameters

  • obj Object All parameters are given in an object (optional, default {})

    • obj.xprivKey String The key of the user
    • obj.config Object? Config object, see config section (optional, default CONFIG)
    • obj.reference String The Dojo reference number for the transaction
    • obj.status String The new status of the transaction

Returns Promise<Object> A success object with status: "success"

updateOutpointStatus

Use this endpoint to update the status of one of your outputs, given as the TXID of a transaction and the vout (output index) in that transaction. This is useful for flagging transaction outpoints as spent if they were inadvertantly broadcasted or used without properly submitting them to the Dojo, or to undo the spending of an output if it was never actually spent.

Parameters

  • obj Object All parameters are given in an object (optional, default {})

    • obj.xprivKey String The key of the user
    • obj.config Object? Config object, see config section (optional, default CONFIG)
    • obj.txid String The TXID of the transaction that created the output
    • obj.vout Number The index of the output in the transaction
    • obj.spendable Boolean The true spendability status of this outpoint

Returns Promise<Object> A success object with status: "success"

Handling Errors

When errors are returned from the Dojo API, they take the form of an object with three fields:

  • status: Will be error if there is an error.
  • code: The machine-readable error code. Example: ERR_BAD_THING
  • description: The human-readable error message. Example: A bad thing has happened.

The UTXONinja wrapper will raise JavaScript errors in the following format:

ERR_BAD_THING: A bad thing has happened.

You can parse these error messages into a usable format as follows:

try {
  await ninja.someFunction()
} catch (e) {
  console.error(`Error code: ${e.message.split(':')[0]}`)
  console.error(`Error message: ${e.message.split(':')[1].trim()}`)
}

If you want custom error messages, or if you are building an internationalized (non-English) application, you can utilize the machine-readable error codes. A list of current codes can be found in the Table of Errors in the Dojo API Documentation.

License

The license for this library, which is a wrapper for the proprietary Dojo API, is the Open BSV License. It can only be used on the BSV blockchain. The Dojo API itself, including the rights to create and host Dojo servers 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 Dojo servers or create copies or alternative implementations of the proprietary Dojo API without other permission.