Module agora.utils.TxBuilder

An helper utility to build transactions

This utility exposes a mutable transaction builder, used to simplify generating complex Transactions, as well as ensuring that generated transactions are valid. Generating invalid Transactions is not supported, however one can generate a valid Transaction and mutate it afterwards.

Usage recommendation

The TransactionBuilder needs to access keys (more precisely, unlocker) in order to generate valid transaction. However, supplying those keys every time the TransactionBuilder is to be instantiated greatly reduce usability. For this reason, we recommmend something along the following: ` private KeyPair[PublicKey] allKeys; private Unlock keyUnlocker (in Transaction tx, in OutputRef out_ref) @safe nothrow { auto ownerKP = allKeys[out_ref.output.address]; assert(ownerKP !is KeyPair.init) return genKeyUnlock(ownerKP.sign(tx.getChallenge())); }

/// Publicly exposed alias used by other modules public alias TxBuilder = StaticTransactionBuilder!keyUnlocker; ` The following sections assume such a usage and thus reference TxBuilder.

Basics

When building a transaction, one must first attach an Output, or a Transaction, using either the constructors or attach. All attached outputs are contributed towards a "refund" Output. Operations will draw from this refund transactions and create new Outputs.

In order to finalize the Transaction, one must call sign, which will return the signed Transaction. If there is any fund left, the refund Output will be the last output in the transaction.

An example would be:

auto tx1 = TxBuilder(myTx).split(addr1, addr2)
                          .attach(otherTx).split(addr3, addr4)
                          .sign();
// Equivalent to:
auto tx2 = TxBuilder(myTx.outputs[0].address)
               .attach(myTx).split(addr1, addr2)
               .attach(otherTx).split(addr3, addr4)
               .sign();

This will create 4 or 5 outputs, depending on the amounts. The first two will split myTx evenly towards addr1 and addr2, the next two will split otherTx evenly between addr3 and addr4. If either transaction has an uneven amount, a refund transaction towards the owner of the first output of myTx will be created.

Refund Address

When making a TxBuilder, the minimum requirement is to provide a refund address. If an output is provided, the address which owns this output will be the refund address, and if a Transaction is provided, the owner of the first output will be the refund address.

Chaining

As can be seen in the example, operations which modify the state will return a reference to the TxBuilder to allow for easy chaining.

Note

This struct is currently not reusable as there is not yet a use case for it, but could be made so in the future. Currently, calling sign will invalidate the internal state.

Structs

NameDescription
OutputRef A reference to an Output within a Transaction
StaticTransactionBuilder
TransactionBuilder