We're using on a local machine, once you're ready to start, initialize a project with npm init -y and install the BSV Blockchain official SDK.
Build Your First Transaction
To create your first transcation you need to send some BSV into a locking script you control. Let's set up our local node.js environment with a key we can use.
Run the above code by copying it into createKey.js and running node createKey.js
Now you should get something in your console which looks like this:
{ address: '1E7ZM72qRDSa0rqUhZoMCMb5MAFYFEaKQp' }
To continue developing and testing, this address will require some funding. This can be done by sending BSV to this wallet, and due the low cost of transactions only a few satoshis will suffice ($0.01 equivalent is recommended). This way, you also ensure that you're not affected if you would lose access to the keys.
Once mined, a green button which says "Raw Tx" will be visible, which allows you to download the full transaction bytes as a hex string file. That's going to be our sourceTransaction which will fund the transaction we are going to define with the SDK. Copy the hex string into a file in the working directory called .transactions. The file contents should look something like this:
You can keep running the same script - it will keep appending new transactions to the .transactions file until you run out of funds. BSV is so cheap that this could be a few thousand transactions later.
In the mean time, you can create your own Bitcoin ScriptTemplates by defining your own classes like so:
const { LockingScript, UnlockingScript, OP } = require('@bsv/sdk')
class SumScript {
lock(sum) {
const ls = new LockingScript()
ls.writeOpCode(OP.OP_ADD)
ls.writeNumber(sum)
ls.writeOpCode(OP.OP_EQUAL)
return ls
}
unlock(a, b) {
const sign = async () => {
const us = new UnlockingScript()
us.writeNumber(a)
us.writeNumber(b)
return us
}
return { sign, estimateLength: async () => 6 }
}
}
To create this output you simply add the class to an output:
tx.addOutput({
satoshis: 3,
lockingScript: new SumScript().lock(41)
})
Unlocking it in a future transaction you can simply do:
tx.addInput({
sourceTransaction,
sourceOutputIndex: 0,
unlockingScriptTemplate: new SumScript.unlock(21, 20)
})
To check that the script works you can then run:
await tx.verify('scripts only')
For more guidance from the documentation - jump here.