We're using node.js and npm 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.
// createKey.jsconst { PrivateKey } =require('@bsv/sdk')const { readFile,writeFile,chmod } =require('fs/promises')constcrypto=require('crypto')global.self = { crypto }asyncfunctioncreateKey() {try {constWIF=awaitreadFile('.wif')constkey=PrivateKey.fromWif(WIF.toString())console.error('You already have a key file, delete .wif manually if you know what you\'re doing.')console.log({ address:key.toAddress() }) } catch (error) {constkey=PrivateKey.fromRandom()constWIF=key.toWif()awaitwriteFile('.wif',WIF)awaitchmod('.wif',0o400)console.log({ address:key.toAddress() }) }}createKey()
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'}
You can copy and paste the address into any BSV wallet and send a few satoshis to it. If you have zero BSV - go buy some, or ask the BSV community on X or discord to send you a few satoshis.
Make sure you're sending BSV, and only a few satoshis, so that you don't care if you lose access to it. $0.01 equivalent is perfect.
Once you've sent the funds, grab the whole transaction from Whats On Chain by pasting in the txid to the search box.
There's a green button which says "Raw Tx" 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')classSumScript {lock(sum) {constls=newLockingScript()ls.writeOpCode(OP.OP_ADD)ls.writeNumber(sum)ls.writeOpCode(OP.OP_EQUAL)return ls }unlock(a, b) {constsign=async () => {constus=newUnlockingScript()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:
Ask the AI if you want to learn more, or join our discord if you need help from a human.
If you want to contribute new ScriptTemplates of your own design there's a repo for that here.
For more guidance from the documentation - jump here.