Skip to main content

Adding metadata to transactions

Sometimes you need to include more information with a transaction. For example:

  • You want to associate a transaction with a specific purchase.
  • You need to include a payment reference with the transaction.
  • You want to include metadata to keep the ledger in sync with an external system.
First time working through a Numscript guide?

Make sure that you're set up properly: Read through the prerequisites first!. Otherwise the examples below won't work.

Attaching transaction metadataโ€‹

In the game land of Cones Dunshire, building cones is a central part of playing the game. As ledgerman, we want to keep track of how much players have spent on building cones for analytical reasons. We can do this by flagging transactions that represent spending on cone building, using metadata.

Player leslieknope just spent 100 coin to build a minor cone. Let's create that transaction, and flag it with metadata. Create a file called metadata.num:

And run it with

numary exec dunshire metadata.num
caution

Are you seeing

FATA[0000] account had insufficient funds

in your output? The source accounts need to have enough funds before you run this example. Make sure you're set up properly.

Once you've run that transaction succesfully, let's have a look at leslieknope's balance' to find that transaction. It should be the topmost one listed. Click the details arrow to the right of the transaction to get more details.

Where to find the detail arrow

On the transaction detail page, you'll find a snippet of JSON at the end that will look something like this:

{
"reference": "",
"timestamp": "2022-04-13T07:10:12Z",
"metadata": {
"cone_size": {
"type": "number",
"value": 15
},
"for_cone": {
"type": "string",
"value": "true"
}
}
}

You can see the metadata field with the details of the information we added to the transaction.

What's going on here?โ€‹

Metadata is arbitrary data that you can attach to a transaction (or an account! But more on that later). This data is typed, and can be a string or a number. You can retrieve (or even add to) this metadata later using the HTTP API, for integration into your own bespoke workflows.

Storing variables in metadataโ€‹

You can store the value of template variables in metadata as well. Template variables may only be of monetary, account, or portion types, and must be specified like the following examples:

{
"base_fee": {
"type": "monetary",
"value": {
"amount": 15,
"asset": "COIN"
}
}
}
{
"seller": {
"type": "account",
"value": "player:benwyatt"
}
}
{
"commission": {
"type": "portion",
"value": "15/100"
}
}

Going furtherโ€‹

There's much more to metadata

Formance Ledger allows you to also add metadata to accounts. This metadata can be used to construct much more sophisticated transactions, with variables that bind to specific metadata at execution time. At the moment, we don't have documentation for how to use these feature, but expect them soon.