Skip to main content

Simple Transaction Builder

When calling a contract function on a Contract object, an incomplete Transaction object is returned. This transaction can be completed by providing a number of outputs using the to() or withOpReturn() functions. Other chained functions are included to set other transaction parameters.

Most of the available transaction options are only useful in very specific use cases, but the functions to(), withOpReturn() and send() are commonly used. withHardcodedFee() is also commonly used with covenant contracts.

Transaction options​

to()​

transaction.to(to: string, amount: bigint, token?: TokenDetails): this
transaction.to(outputs: Array<Recipient>): this

The to() function allows you to add outputs to the transaction. Either a single pair to/amount pair can be provided, or a list of them. This function can be called any number of times, and the provided outputs will be added to the list of earlier added outputs. Tokens can be sent by providing a TokenDetails object as the third parameter, or including it in your array of outputs with the .token property.

interface Recipient {
to: string;
amount: bigint;
token?: TokenDetails;
}

interface TokenDetails {
amount: bigint;
groupId: string;
}
note

The NexScript SDK supports automatic UTXO selection for Nexa, fungible tokens and non-fungible tokens (token subgroups). Creating new non-fungible tokens requires automatic selection: the SDK adds the contract's parent group authority with SUBGROUP, while with from() every non-fungible token output must match a non-fungible token input.

Also note, that the automatic UTXO selection does best effort not to burn tokens and an token authority UTXOs. If this is your desired behaviour make sure to explicitly configure transaction with from() and to() prepared in a way which would allow to burn them.

An output that carries tokens holds the amount you pass, which must be at least the dust limit of 546 satoshis; 546n is the usual choice.

Example​

.to('nexa:nqtsq5g537fcf6z85pgwk4my5e5ddmypa2sm47mkzavt6zky', 500000n)

withOpReturn()​

transaction.withOpReturn(chunks: string[]): this

The withOpReturn() function allows you to add OP_RETURN outputs to the transaction. The chunks parameter can include regular UTF-8 encoded strings, or hex strings prefixed with 0x. This function can be called any number of times, and the provided outputs will be added to the list of earlier added outputs.

Example​

.withOpReturn(['0x6d02', 'Hello World!'])

from()​

transaction.from(input: Utxo): this
transaction.from(inputs: Utxo[]): this

The from() function allows you to provide a single contract UTXO or a hardcoded list of them to be used in the transaction. This overrides the regular UTXO selection performed by the NexScript SDK, so no further selection will be performed on the provided UTXOs. This function can be called any number of times, and the provided UTXOs will be added to the list of earlier added UTXOs.

tip

The built-in UTXO selection is generally sufficient. But there are specific use cases for which it makes sense to use a custom selection algorithm.

Example​

.from(await instance.getUtxos())

fromReadOnly()​

transaction.fromReadOnly(input: Utxo): this
transaction.fromReadOnly(inputs: Utxo[]): this

The fromReadOnly() function adds read-only inputs to the transaction. A read-only input refers to a UTXO without spending it, so the contract can inspect it (e.g. with tx.inputs[i].value or tx.inputs[i].lockingBytecode, and tx.inputs[i].type is 1). Read-only inputs are added after the spent inputs, have no unlocking script, and do not count towards the transaction's value or token balances. They are never used in UTXO selection, and a UTXO can't be both spent and read-only in the same transaction. This function can be called any number of times, and the provided UTXOs will be added to the list of earlier added read-only UTXOs.

note

Rostrum up to v14.0.1 lists a UTXO referenced by a read-only input as spent, although the node keeps it unspent.

caution

A read-only input without an unlocking script doesn't run its locking script, and anyone can add one for any UTXO. A contract that trusts another input because of its lockingBytecode, e.g. to require that another contract is spent alongside it, must also check that the input is spent: require(tx.inputs[i].type == 0).

Example​

.fromReadOnly(oracleUtxo)

fromP2PKT()​

transaction.fromP2PKT(input: Utxo, template: SignatureTemplate): this
transaction.fromP2PKT(inputs: Utxo[], template: SignatureTemplate): this

The fromP2PKT() function allows you to add P2PKT UTXOs to the transaction, for example to pay the fee from a regular address. They are signed with the provided SignatureTemplate. Like from(), this disables the automatic UTXO selection, so add any contract UTXOs to spend with from(). Change is sent to the contract address.

Example​

.from(await instance.getUtxos())
.fromP2PKT(await provider.getUtxos(aliceAddress), aliceTemplate)

withFeePerByte()​

transaction.withFeePerByte(feePerByte: number): this

The withFeePerByte() function allows you to specify the fee per per bytes for the transaction. By default the fee per bytes is set to 2.0 satoshis, which is nearly always enough to be included in the next block. So it's generally not necessary to change this.

Example​

.withFeePerByte(2.3)

withHardcodedFee()​

transaction.withHardcodedFee(hardcodedFee: bigint): this

The withHardcodedFee() function allows you to specify a hardcoded fee to the transaction. By default the transaction fee is automatically calculated by the NexScript SDK, but there are certain use cases where the smart contract relies on a hardcoded fee.

tip

If you're not building a covenant contract, you probably do not need a hardcoded transaction fee.

Example​

.withHardcodedFee(1000n)

withMinChange()​

transaction.withMinChange(minChange: bigint): this

The withMinChange() function allows you to set a threshold for including a change output. Any remaining amount under this threshold will be added to the transaction fee instead.

tip

This is generally only useful in specific covenant use cases.

Example​

.withMinChange(1000n)

withoutChange()​

transaction.withoutChange(): this

The withoutChange() function allows you to disable the change output. The remaining amount will be added to the transaction fee instead. This is equivalent to withMinChange(Number.MAX_VALUE).

caution

Be sure to check that the remaining amount (sum of inputs - sum of outputs) is not too high. The difference will be added to the transaction fee and cannot be reclaimed.

Example​

.withoutChange()

withoutTokenChange()​

transaction.withoutTokenChange(): this

The withoutTokenChange() function allows you to disable the change output for tokens. This also stops the SDK from adding outputs that return unused NFTs and token authorities to the contract.

caution

Be sure to check that the remaining amount (sum of inputs - sum of outputs) is not too high. The difference will be burned and cannot be reclaimed.

Example​

.withoutTokenChange()

withAge()​

transaction.withAge(age: number): this

The withAge() function allows you to specify the minimum age of the transaction inputs. This is necessary if you want to to use the tx.age NexScript functionality, and the age parameter passed into this function will be the value of tx.age inside the smart contract. For more information, refer to BIP68.

Example​

.withAge(10)

withTime()​

transaction.withTime(time: number): this

The withTime() function allows you to specify the minimum block number that the transaction can be included in. The time parameter will be the value of tx.time inside the smart contract. Values of 500,000,000 and above are read as a unix timestamp instead of a block number.

tip

By default, the transaction's time variable is set to the most recent block number, which is the most common use case. So you should only override this in specific use cases.

Example​

.withTime(700000)

Transaction building​

send()​

async transaction.send(): Promise<ITransaction>
async transaction.send(raw: true): Promise<string>

After completing a transaction, the send() function can be used to send the transaction to the Nexa network. An incomplete transaction cannot be sent. Once the network provider can return the sent transaction, send() returns it as a libnexa-ts ITransaction object, or as a raw hex string when called as send(true).

interface ITransaction {
id: string;
idem: string;
version: number;
inputs: IInput[];
outputs: IOutput[];
nLockTime: number;
fee?: number;
feePerByte?: number;
changeIndex?: number;
changeScript?: string;
}

Example​

import { alice } from './somewhere';

const txDetails = await instance.functions
.transfer(new SignatureTemplate(alice))
.withOpReturn(['0x6d02', 'Hello World!'])
.to('nexa:nqtsq5g537fcf6z85pgwk4my5e5ddmypa2sm47mkzavt6zky', 200000n)
.to('nexa:nqtsq5g5wtkt44pfqusjj3wulk2n2pd27lhpzg0m326kcnsj', 100000n)
.withHardcodedFee(1000n)
.send()

console.log(txDetails.id, txDetails.idem)

build()​

async transaction.build(): Promise<string>

After completing a transaction, the build() function can be used to build the entire transaction and return the signed transaction hex string. This can then be imported into other libraries or applications as necessary.

Example​

const txHex = await instance.functions
.transfer(new SignatureTemplate(alice))
.to('nexa:nqtsq5g537fcf6z85pgwk4my5e5ddmypa2sm47mkzavt6zky', 500000n)
.withAge(10)
.withFeePerByte(10)
.build()

meep()​

async transaction.meep(): Promise<string>

The meep() function builds the transaction without sending it and returns a meep debug command for it, which debugs the first input against the contract's script. The same string is included in the error thrown when send() fails.

Example​

const meepStr = await instance.functions
.transfer(new SignatureTemplate(alice))
.to('nexa:nqtsq5g537fcf6z85pgwk4my5e5ddmypa2sm47mkzavt6zky', 500000n)
.meep()

Transaction errors​

Transactions can fail for a number of reasons. Most of these are related to the execution of the smart contract (e.g. wrong parameters or a bug in the contract code). But errors can also occur because of other reasons (e.g. a fee that's too low or the same transaction already exists in the mempool). To facilitate error handling in your applications, the NexScript SDK provides an enum of different reasons for a failure.

This Reason enum only includes errors that are related to smart contract execution, so other reasons have to be caught separately. Besides the Reason enum, there are also several error classes that can be caught and acted on:

  • FailedRequireError, signifies a failed require statement. This includes the following reasons:
    • Reason.EVAL_FALSE
    • Reason.VERIFY
    • Reason.EQUALVERIFY
    • Reason.CHECKMULTISIGVERIFY
    • Reason.CHECKSIGVERIFY
    • Reason.CHECKDATASIGVERIFY
    • Reason.NUMEQUALVERIFY
  • FailedTimeCheckError, signifies a failed time check using tx.time or tx.age. This includes the following reasons:
    • Reason.NEGATIVE_LOCKTIME
    • Reason.UNSATISFIED_LOCKTIME
  • FailedSigCheckError, signifies a failed signature check. This includes the following reasons:
    • Reason.SIG_COUNT
    • Reason.PUBKEY_COUNT
    • Reason.SIG_HASHTYPE
    • Reason.SIG_DER
    • Reason.SIG_HIGH_S
    • Reason.SIG_NULLFAIL
    • Reason.SIG_BADLENGTH
    • Reason.SIG_NONSCHNORR
  • FailedTransactionError, signifies a general fallback error. This includes all remaining reasons listed in the Reason enum as well as any other reasons unrelated to the smart contract execution.

These errors are thrown by send(). The first three extend FailedTransactionError, which has a reason field with the reason reported by the node and a meep field with the meep() output.

The SDK also throws these errors before a transaction is sent:

  • OutputSatoshisTooSmallError, thrown by to() when an output's amount is below the dust limit of 546 satoshis, and by TransactionBuilder.build() for a token output below it.
  • TypeError, thrown when a constructor or function argument does not match its type in the contract, e.g. a string for an int parameter or a bytes value of the wrong length.
enum Reason {
EVAL_FALSE = 'Script evaluated without error but finished with a false/empty top stack element',
VERIFY = 'Script failed an OP_VERIFY operation',
EQUALVERIFY = 'Script failed an OP_EQUALVERIFY operation',
CHECKMULTISIGVERIFY = 'Script failed an OP_CHECKMULTISIGVERIFY operation',
CHECKSIGVERIFY = 'Script failed an OP_CHECKSIGVERIFY operation',
CHECKDATASIGVERIFY = 'Script failed an OP_CHECKDATASIGVERIFY operation',
NUMEQUALVERIFY = 'Script failed an OP_NUMEQUALVERIFY operation',
SCRIPT_SIZE = 'Script is too big',
PUSH_SIZE = 'Push value size limit exceeded',
OP_COUNT = 'Operation limit exceeded',
STACK_SIZE = 'Stack size limit exceeded',
SIG_COUNT = 'Signature count negative or greater than pubkey count',
PUBKEY_COUNT = 'Pubkey count negative or limit exceeded',
INVALID_OPERAND_SIZE = 'Invalid operand size',
INVALID_NUMBER_RANGE = 'Given operand is not a number within the valid range',
SCRIPT_NUMBER_OVERFLOW = 'Script number overflow',
IMPOSSIBLE_ENCODING = 'The requested encoding is impossible to satisfy',
INVALID_SPLIT_RANGE = 'Invalid OP_SPLIT range',
INVALID_BIT_COUNT = 'Invalid number of bit set in OP_CHECKMULTISIG',
BAD_OPCODE = 'Opcode missing or not understood',
DISABLED_OPCODE = 'Attempted to use a disabled opcode',
INVALID_STACK_OPERATION = 'Operation not valid with the current stack size',
INVALID_ALTSTACK_OPERATION = 'Operation not valid with the current altstack size',
OP_RETURN = 'OP_RETURN was encountered',
UNBALANCED_CONDITIONAL = 'Invalid OP_IF construction',
DIV_BY_ZERO = 'Division by zero error',
MOD_BY_ZERO = 'Modulo by zero error',
INVALID_BITFIELD_SIZE = 'Bitfield of unexpected size error',
INVALID_BIT_RANGE = 'Bitfield\'s bit out of the expected range',
NEGATIVE_LOCKTIME = 'Negative locktime',
UNSATISFIED_LOCKTIME = 'Locktime requirement not satisfied',
SIG_HASHTYPE = 'Signature hash type missing or not understood',
SIG_DER = 'Non-canonical DER signature',
MINIMALDATA = 'Data push larger than necessary',
SIG_PUSHONLY = 'Only push operators allowed in signature scripts',
SIG_HIGH_S = 'Non-canonical signature: S value is unnecessarily high',
MINIMALIF = 'OP_IF/NOTIF argument must be minimal',
SIG_NULLFAIL = 'Signature must be zero for failed CHECKSIG operation',
SIG_BADLENGTH = 'Signature cannot be 65 bytes in CHECKMULTISIG',
SIG_NONSCHNORR = 'Only Schnorr signatures allowed in this operation',
DISCOURAGE_UPGRADABLE_NOPS = 'NOPx reserved for soft-fork upgrades',
PUBKEYTYPE = 'Public key is neither compressed or uncompressed',
CLEANSTACK = 'Script did not clean its stack',
NONCOMPRESSED_PUBKEY = 'Using non-compressed public key',
ILLEGAL_FORKID = 'Illegal use of SIGHASH_FORKID',
MUST_USE_FORKID = 'Signature must use SIGHASH_FORKID',
UNKNOWN = 'unknown error',
}