Skip to content

NodeJS Backend

To integrate with NodeJS you need to make sure that your trix project has the typescript bindings generation enabled in the config:

[[bindings]]
plugin = "typescript"
output_dir = "./gen/typescript"

With the binding generation enabled, run the following command from your CLI to trigger the code generator:

trix bindgen

If things went well, you should see the following new files:

my-protocol/
└── gen/
└── typescript/
├── protocol.ts
├── package.json
└── tsconfig.json

That new protocol.ts file has the required types and functions to call your protocol from a Typescript code. It works on the backend and also in the browser (with the corresponding bundling).

The package.json and tsconfig.json files are standard files for Typescript projects.

Now, we can use the generated bindings to build a transaction using our protocol.

First access to the gen/typescript folder and install the dependencies:

Terminal window
cd gen/typescript && npm install

NOTE: You can use yarn, pnpm or any other package manager you prefer.

We need to open protocol.ts and update the TRP endpoint to point to the correct URL (unless you have it configured in trix.toml). For the local Devnet the TRP endpoint is available at http://localhost:8164/ (update this value accordingly if you’re using a different port or network).

For the following example, we will use the main.tx3 file generated by trix.

Before running the example below, start the local Devnet in a separate terminal with:

Terminal window
trix devnet

The Devnet prints sample wallets and addresses when it starts. If you don’t see addresses in the console, fetch a wallet’s addresses with trix wallet <name> (for example trix wallet alice).

Now, create a new file called test.ts in the same folder (or any other folder) and add the following code (replace the placeholder addresses with the ones printed by trix devnet or obtained via trix wallet):

import { protocol, type TransferParams } from './gen/typescript/protocol';
const transferParams: TransferParams ={
sender: 'addr_test1vqn7k6gfllvhauxkzw478ds2f9axmu4qw78pm86dtyd40yqg2w3rq',
receiver: 'addr_test1vqxazu4ekxrxlk238wt0e03h3gk44hrlkjvef85gvh2nahcgnmpfc',
quantity: 100000000,
};
async function main() {
try {
let cbor = await protocol.transferTx(transferParams);
console.log(cbor);
} catch (error) {
console.error('Error:', error);
}
}
main();

Finally, we can run the test file to build a transaction using our protocol:

Terminal window
npx tsx test.ts

If everything went well, you should see a message like this:

Terminal window
{
tx: '84a400d9010281825820705e5d956d318264043baf8031e250c14b8703b69947ab2d3212d67210c4b240010182a200581d60464d4cb029fc90cf720600b2f271a2d433517ad32a67eac5eb9bba5c011a05f5e100a200581d605189743c77fc84cc571235062e4f0de28370f6273ade37697d850b40011b0000000248151b86021a0005833d0f00a0f5f6'
}