Making Bitcoin Transactions Smart And Interactive With Structured Metadata

Bitcoin transactions hold only static data which doesn’t include much more relevant information to look into. what if transactions can have additional information (metadata).

Making Bitcoin Transactions Smart And Interactive With Structured Metadata

A new future of Bitcoin Transactions exploring numerous use cases, bringing Bitcoin in our day to day life 💰

Abstract

Specifications such as WebLN bought better solutions to the UX for Lightning Network and enhanced applications of Bitcoin.

On top of this, many broad applications such as 💻—

  • Instant payments via a web browser using Bitcoin Sats (eg. Alby)
  • Tippings for content writers, podcasts and streamers
  • Sat’s streaming
  • Instant purchases on the Web and many more came into working…

Transaction lists as we know them from our private bank accounts are often a simple list of transactions sorted by date. Each transaction has data like Sender, Receiver, amount, reason and date.

Similarly, Bitcoin transactions hold only static data which doesn’t include much more relevant information to look into. what if transactions can have additional information (metadata) such as 💫 —

  • Purpose of Transaction
  • What was bought with that particular transaction
  • Accessing bought right out of the wallet
  • Allow users to interact with transactions depending on the additional information each transaction will hold

Every transaction can store additional information in form of metadata which can make specifications such as WebLN more broad and applicative in terms of interactivity and extend the scope of the Bitcoin use cases in numerous ways building a different future for the Lightning Network and Bitcoin.

This project aims to extend existing technology standards such as WebLN to enrich transactions with additional information as structured metadata so that transactions containing static data contain more meaningful information giving more interactivity to the transactions.


What is WebLN? 🤔

Lightning Web Standard (WebLN) ⚡ is a specification used to build a Bitcoin Lightning-driven web application.

WebLN is a set of specifications for Lightning apps and client providers to facilitate communication between web apps and users’ Lightning nodes in a secure way. It provides a programmatic, permissioned interface for letting applications ask users to send payments, generate invoices to receive payments, and much more.

WebLN Provider Functionality

Sending Payments Via WebLN Along With Metadata 🧾

WebLN SendPayment which takes paymentRequest parameter holding Bolt11 invoice, we can extend this function to add an extra “optional” parameter named metadata which will hold metadata as a string which can be passed to the Wallets.

Function Signature::

sendPayment(paymentRequest: string, metadata?: string): Promise<SendPaymentResponse>;

WebLN Provider attached by wallets currently

WebLN Provider attached by wallets after implementation of spec


Working/architecture of this spec ⚙️

1.   Make a Request to Wallet for WebLN Provider Via Triggering SendPayment()

sendPayment(paymentRequest: string, metadata?: string): Promise<SendPaymentResponse>;

2.   Structure Metadata and pass it to the wallet in Callback

Use Schema.org specifications to structure metadata in form of JSON-LD.

eg.

var Metadata = {};
Metadata = {
 "context": "https://schema.org",
 "type": "AudioObject",
 "name": "title",
 "creator": "artist",
 "image": "image" 
 }
 export var Metadata;

Learn more about how to structure metadata for Bitcoin Transactions Visit — Here

3.   Validate Metadata

Metadata is user-generated, such type of metadata should be cross-checked for its correctness and before performing any further action we have to do validation of metadata.

What is JSON Schema? 🧐

JSON Schema is a JSON media type for defining the structure of JSON data. JSON Schema provides a contract for what JSON data is required for a given application and how to interact with it.

Schemas can be created to validate received data against a predefined data model. To do this many validator plugins are available too -

  • Generate Schema
  • Compile Schema
  • Validate received data for that particular schema

Zod plugin can be used to validate JSON schemas as well as Object schemas. The best thing about this plugin is that it has zero external dependencies involved.

Validator function which validates schemas using zod plugin

  • Schema Created using Zod plugin
import { z } from "zod";
export const audioObjectSchema = z.object({
  type: z.string(),
  name: z.string().optional(),
  creator: z.string().optional(),
  image: z.string().optional(),
});
  • Validator function to validate metadata
import { audioObjectSchema } from "./audioObjectSchema";
export function isBase64(str: string) {
  if (str === "" || str.trim() === "") {
    return false;
  }
  try {
    return btoa(atob(str)) == str;
  } catch (err) {
    return false;
  }
}
export function MetadataValidator(metadata: { [key: string]: string }) {
  let hasValidType = false;
  let hasValidImage = true;
  for (const key in metadata) {
    if (key == "type") {
      if (metadata[key] == "AudioObject") {
        const parsed = audioObjectSchema.safeParse(metadata);
        if (parsed.success) {
          hasValidType = true;
        }
      }
    }
    if (key == "image") {
      hasValidImage = isBase64(metadata[key]);
    }
  }
return hasValidType && hasValidImage;
}

To Validate Metadata Just call the function by passing metadata

const isMetadataValid = MetadataValidator(metadata);

4.   Render Metadata in Confirmation Dialogue (If Valid) 🚦

If metadata is successfully validated, we can show the user the amount the user will be paying along with the content used will be buying in form of metadata.

Here users can see the purpose of the transaction, looking over the content, the user will be buying through this transaction and will have a clear idea of everything before making the payment.

5.   Store, Interact and do after actions with Metadata 💾

Once the user confirms their payment and the transaction gets successful -

  • In Bitcoin Lightning Wallet

We can store and render the metadata in the transaction database of the wallet allowing users to interact with the metadata.

  • In Lightning Application

Once the payment is successful, we can allow the user to access his purchased content such as allowing the user to download a song, once the payment is successful.

webln.sendPayment(Bolt 11 invoice, Metadata)
          .then(function(r) {
            if(r != undefined){  
            // do after payment actions with the metadata. eg. allowing user to download song after payment is done 
          }
          })
          .catch(function(e) {
            alert("Failed: " + e.message);
            console.log('err pay:', e);
          });
    })
    .catch(function(e) {
      alert("Webln error, check console");
      console.log('err, provider', e);
    });
}

Use cases 🔥

These new specifications on top of Bitcoin and the Lightning Network make Transactions happening on top of Bitcoin much more interactive and smart

The potential of use cases after implementation is vast and transactions no longer only hold details about the performed payment but also include structured metadata of the consumed objects. 💫

For instance, it allows users to perform actions directly out of their wallet such as accessing purchased digital content, renewing expiring subscriptions, recollateralize open trades on trading platforms or topping up gift card budgets. ✨

To demonstrate the concept more clearly, I decided to create a simple prototype through which a visitor can play a song if they like they can buy a song. While buying a song during confirmation payment they get to know about the song name, artist, and song image(send as base64 encoded string, decode on Alby side).

After successful payment, a song gets downloaded into users’ local storage. 🎉

Buy Song

Prototype Code

Alby with extended webLN specification


This article by Pavan Joshi, a Summer of Bitcoin intern at Alby, was originally written on Medium. Reshared here with permission