Build a token plugin
This page walks you through building a token protocol as a package of its own that plugs into libspiffy: the wallet makes your tokens, tracks the ones it owns outside its balance, and spends them again. It builds on Script plugins, which describes the interfaces; here is how to put them together, and the rules a token plugin runs into. The running example is a PushDrop token, the format BRC-100 overlays use: data fields in a one-satoshi output, locked to a key.
The package
Section titled “The package”Your package depends on libspiffy and dartsv, and libspiffy never depends on it. Keep two layers apart:
- The script template: pure functions that write and read your locking script. No wallet, no I/O. This is the part you check against the protocol’s reference implementation, byte for byte.
- The plugin: a
TransactionBuilderPluginthat uses the template to recognise your outputs and to build the transactions that make and spend them.
dependencies: dartsv: ^3.1.4 libspiffy: ^6.0.0The script template
Section titled “The script template”Read your script strictly. The wallet asks every plugin about every script it does not know, so
identifyScript must claim your exact shape and nothing else. A PushDrop token is the locking key, a
checksig, the fields, and drops that take exactly those fields off the stack:
// A sketch of the template's reading side; the writing side pushes each field in its minimal encoding.PushDropToken? decode(SVScript script) { final chunks = script.chunks; if (chunks.length < 4 || chunks[1].opcodenum != OpCodes.OP_CHECKSIG) return null; final key = chunks[0].buf; if (key == null || key.length != 33) return null; // ... read the pushes after the checksig as fields, then require OP_2DROP / OP_DROP // to drop exactly that many fields, with nothing after them.}When the protocol has a reference implementation, record test vectors from it (scripts, keys, signatures) and check your template against them. Two encodings of the same fields are two different scripts, and an overlay or indexer that expects the reference’s bytes will not find yours.
Recognise and track your tokens
Section titled “Recognise and track your tokens”extractMetadata decides which tokens are the wallet’s. The wallet credits an output a plugin claims only
when the metadata’s ownerAddress is one of its addresses, so name the address of the token’s locking key.
An address belongs to a network, so give the plugin the wallet’s network:
class PushDropPlugin extends TransactionBuilderPlugin { PushDropPlugin({required this.network});
final NetworkType network;
@override String get pluginId => 'pushdrop';
@override String? identifyScript(SVScript script) => decode(script) == null ? null : 'pushdrop';
@override Map<String, dynamic>? extractMetadata(SVScript script) { final token = decode(script); if (token == null) return null; return { 'ownerAddress': Address.fromPublicKey(SVPublicKey.fromHex(token.lockingPublicKey), network).toBase58(), 'lockingPublicKey': token.lockingPublicKey, }; }
// displayName, scriptTypes, supportedActions, createLockBuilder, createUnlockBuilder, // validateTransactionStructure and buildTransaction follow.}The wallet then keeps those UTXOs out of its balance and out of coin selection. Read them back with
libspiffy.walletStorage.getUTXOsByPlugin(walletId, 'pushdrop').
Build the transactions
Section titled “Build the transactions”A payment builds through your plugin when its outputs hold a PluginOutputSpec whose params['action'] is
one of your supportedActions. One action can cover a whole lifecycle: a transaction that spends the old
token and makes the new one replaces it; one that only spends it withdraws it.
// A sketch: one helper the app calls, so params stay in one place.static PluginOutputSpec outputSpec({List<Map<String, Object>> outputs = const [], List<Map<String, Object>> spends = const [], required BigInt allowance}) => PluginOutputSpec( pluginId: 'pushdrop', pluginScriptType: 'pushdrop', params: {'action': outputs.isEmpty ? 'spend' : 'create', 'outputs': outputs, 'spends': spends}, amount: tokenSatoshis(outputs) + allowance, );Four rules shape buildTransaction:
- Params are plain data. Hex strings, ints and lists: a spec often crosses an isolate boundary as a map
(
toMap()/InvoiceOutputSpec.fromMap). Pass satoshis as strings, asPluginOutputSpecdoes. - Budget for the bytes the selection does not see. For a plugin transaction the wallet selects coins for
the total of the specs’
amounts, and sizes the fee by the funding inputs alone. Your token outputs, the inputs that spend tokens and your change output are not in that fee. Add an allowance for them to the spec’samount; what the transaction does not pay comes back as change. - Pay the policy rate, and return the change. Size the transaction yourself and charge
request.feeRate.feeFor(size). Send the rest to a wallet address, such as the first funding input’sutxo.address, or the wallet loses it. - Fund through
fundingInputs. SetspendsAnyWalletOutputtotrueand spend each funding coin withinput.outpointandinput.newUnlocker(), so any coin the wallet can sign alone can fund you.
Spend a token
Section titled “Spend a token”A token is spent with a signature by its locking key, and you get a signer for a wallet key with
request.keyFor(pubkeyHash). The HASH160 is of the locking key the token names:
// A sketch of the part of buildTransaction that spends one token.final token = decode(spend.lockingScript)!;final owner = await request.keyFor(hex.encode(hash160(hex.decode(token.lockingPublicKey))));builder.spendFromOutpointWithSigner( owner.signer, TransactionOutpoint(spend.txid, spend.vout, spend.satoshis, spend.lockingScript), TransactionInput.MAX_SEQ_NUMBER, PushDropUnlockBuilder(), // the unlocking script is the signature alone);keyFor fails unless the wallet holds the key. An HD key of the wallet works. So does a BRC-42 (type-42)
key derived from one of its anchor keys, once you record it with RecordType42AddressesCommand (since
5.5.0). Record it before the first payment that uses it; the reply comes once the read model holds the
address, so a payment right after it finds the key.
A BRC-100 child of an anchor key is such a key. For protocol [1, 'my protocol'], key ID 1 and
counterparty self, the derivation names the anchor key as both anchor and sender:
final derivation = Type42Derivation( anchorPublicKey: anchorKey, // from IssueAnchorKeyCommand anchorContext: anchorContext, senderPublicKey: anchorKey, // counterparty 'self' invoiceNumber: Brc43Protocol(1, 'my protocol').invoiceNumber('1'),);final recorded = await libspiffy.coordinator.ask( RecordType42AddressesCommand(walletId: walletId, derivations: [derivation]));// recorded.addresses.single is the P2PKH address of the token's locking keyBoth keys come from the wallet’s seed and the anchor context, so a wallet restored from its seed derives the same locking key and can record it again to spend its tokens.
Signed fields need a second key
Section titled “Signed fields need a second key”Many BRC-100 tokens also carry a signature over their fields, made with Brc100KeyOperationCommand
(createSignature). The wallet refuses every operation but getPublicKey for a key it holds coins under:
the BRC-29 protocol, and any type-42 address it recorded. A signature over data you choose can be a
transaction signature, so signing data with a spend key could spend its coins.
So once a token’s locking key is recorded, the wallet will not sign fields with it again. Use two keys:
- Sign the fields with the child the protocol’s verifiers check, for example counterparty
anyone. Never record it. - Lock the token to a different child, for example counterparty
self, and record that one.
Check that the verifiers look only at the field signature and not at the locking key before you do this.
The BRC-100 message box overlay (tm_messagebox), for one, verifies the signature by the identity’s
anyone child and ignores the lock.
Register the plugin
Section titled “Register the plugin”PluginRegistry is a singleton per isolate. Register the plugin in the isolate where
LibSpiffyActorSystem runs, before the wallet starts building. If you start the wallet again in the same
isolate, on a network switch for example, register throws because the id is taken; unregister it first:
PluginRegistry() ..unregister(PushDropPlugin.id) ..register(PushDropPlugin(network: NetworkName.toDartsv(networkType)));Test it
Section titled “Test it”- The template: against the reference implementation’s vectors.
- The build: call
buildTransactionwith aPluginTransactionRequestyou make yourself, with a dartsvDefaultTransactionSignerfor the funding key and akeyLookupthat returnsPluginKeys for your token keys. Then check every input with dartsv’sInterpreter().correctlySpends(...), and that the fee coversfeeRate.feeForof the signed size. - The wallet: make, replace and withdraw a token through a real wallet, and check that
getUTXOsByPluginfollows it and the balance never counts it.
libtokensv is a complete example: PushDrop as a
TransactionBuilderPlugin, its tests, and a client for the BSV overlays that index such tokens.
Related
Section titled “Related”- Script plugins: the interfaces in full
- Commands:
RecordType42AddressesCommand,Brc100KeyOperationCommand - API reference