Code Monkey home page Code Monkey logo

algorand-qrcode's Introduction

Algorand QR Code Generator V2.0.0

npm NPM JavaScript Style Guide npm

A comprehensive javascript module with a complete set of tools to generate an standard Algorand URI (RFC 3986) and QR code, exportable to SVG, PNG and UTF8. Exported media types are File, UTF8 text and DataURL. Works in Terminal, Node and modern browsers. Contains a full set of examples including API server, static server and web form QR generator. Includes a full featured CLI to generate QR codes in terminals too.

algorand://AMESZ5UX7ZJL5M6GYEHXM63OMFCPOJ23UXCQ6CVTI2HVX6WUELYIY262WI?label=emg110@gmail.com

Demo

Links

News

Version 2.0.0 is out!

Now completely supports React importing

With rawUri option you can bypass algorand URI spec and create QRCode with your own URI or generally string of characters.

Background Image added with options (withBgLogo & bgLogo)

Image printing on QR Code (position, style). Center Image logo added with options (withLogo & logo)

QR Code Scanner has been added (thanks to JSQR ES6)

Technical notes

  • Default amount is considered in Micro Algos by default (what ever amount will be multiplied by 1000000 during URI creation andbefore QR Code generation) since version 1.0.0.

  • Dear developers please beware to set your wallet's mode into development mode and network to testnet or betanet before getting started to avoid any unwanted transactions on mainnet which means real transfer of Algo or some assets. So please do as a developer would do.

  • Algorand URI reference specificatgion: Algorand payment prompts specification.

  • Requires NodeJS version later than 10.

  • Automatically checks & detecs out of scope characters and encodes them forcefully..

  • This library will closely follow Algorand’s URI specification document drafts and published versions closely as well as Algorand official WalletQR Scanner feature to match and adopt new features, specification requirements and extensions.

Table of contents

Screenshots

Highlights

  • This library can be built for browser, be imported or required in NodeJS or directly rendered in terminal.
  • Supports RFC 3986 and Algorand URI ABNF Grammar.
  • Optionally can automatically escape HTML (--html in CLI or {html:true} in code).
  • Validates Algorand fields on client side without js-algorand-sdk (address, amount, asset ID, ...).
  • CLI utility.
  • Save QR code as image (SVG, PNG, JPEG,...).
  • Support for some styling and colors (dark , light,..).
  • Support for chinese, cyrillic, greek and japanese characters in transaction labels and notes.
  • Auto generates optimized segments for best data compression and smallest QR Code size.
  • App agnostic readability, Generated QR Codes by definition are app agnostic.

Algorand URI ABNF Grammar

    algorandurn     = "algorand://" algorandaddress [ "?" algorandparams ]
    algorandaddress = *base32
    algorandparams  = algorandparam [ "&" algorandparams ]
    algorandparam   = [ amountparam / labelparam / noteparam / assetparam / otherparam ]
    amountparam     = "amount=" *digit
    labelparam      = "label=" *qchar
    assetparam      = "asset=" *digit
    noteparam       = (xnote | note)
    xnote           = "xnote=" *qchar
    note            = "note=" *qchar

Installation

Inside your project folder do:

npm install --save algorand-qrcode

and then

cd bin && node qrcode [options]

or, install it globally to use qrcode from the command line to save Algorand URI qrcode and barcode images or generate ones you can view in your terminal.

npm install -g algorand-qrcode

and then

qrcode [options]

Usage

React

import * as QRCode from "algorand-qrcode";

 QRCode.toDataURL({wallet:"AMESZ5UX7ZJL5M6GYEHXM63OMFCPOJ23UXCQ6CVTI2HVX6WUELYIY262WI", label:"[email protected]"})
      .then(({ dataUrl, alrorandURI }) => {
        console.log(algorandUri);
      })
      .catch((err) => {
        console.error(err);
      });

CLI

Usage: qrcode [options]

Algorand switch:
  -x, --xnote Expects "xnote" instread of "note" for Algorand URI      [boolean]
  -y, --html  Automatically HTML escapes all text strings              [boolean]

Algorand options:
  -a, --amount Amount (in Micro Algos) of Algorand transaction          [number]
  -l, --label Label of Algorand transaction                             [string]
  -s, --asset Algorand asset id (in case of Algorand ASA transfer)      [string]
  -n, --note note/xnote (depends on -a | --xnote switch)                [string]
  -d, --dest Destination Wallet address (Algorand account address)      [string]

QR Code options:
  -v, --qversion  QR Code symbol version (1 - 40)                       [number]
  -e, --error     Error correction level           [choices: "L", "M", "Q", "H"]
  -m, --mask      Mask pattern (0 - 7)                                  [number]


Renderer options:
  -t, --type        Output type                  [choices: "png", "svg", "utf8"]
  -w, --width       Image width (px)                                    [number]
  -r, --ratio       Scale ratio factor                                  [number]
  -q, --qzone       Quiet zone size                                     [number]
  -b, --background  Light RGBA hex color
  -f, --foreground   Dark RGBA hex color
  -p, --puny  Output smaller QR code to terminal                       [boolean]
  -i, --inverse  Invert foreground and background colors               [boolean]

Options:
  -o, --output  Output file
  -h, --help    Show help                                              [boolean]
  --version     Show version number                                    [boolean]

Examples:
    - Draw Algorand USDT(Tether) payment transaction QR Code in terminal window:
    node qrcode -d "AMESZ5UX7ZJL5M6GYEHXM63OMFCPOJ23UXCQ6CVTI2HVX6WUELYIY262WI" -a 25 -s 45 -n "This is an Algorand USDT Tether payment transaction QR Code" -p

    - Save Algorand contact label as png image:
    node qrcode -d "AMESZ5UX7ZJL5M6GYEHXM63OMFCPOJ23UXCQ6CVTI2HVX6WUELYIY262WI" -l "[email protected]" -o emg110ContactQrCode.png 

    - Use red as foreground color:
    node qrcode -d "AMESZ5UX7ZJL5M6GYEHXM63OMFCPOJ23UXCQ6CVTI2HVX6WUELYIY262WI" -f F00 -o paymentQR.png -a 12 -x -n "This is an Algorand Algo payment transaction QR Code"

If not specified, output type is guessed from file extension.
Recognized extensions are png, svg and txt.

Browser

algorand-qrcode can be used in browser through including the precompiled bundle present in build/ folder.

// index.js -> bundle.js
var QRCode = require('algorand-qrcode')
var canvas = document.getElementById('canvas')

QRCode.toCanvas(canvas, {wallet:"AMESZ5UX7ZJL5M6GYEHXM63OMFCPOJ23UXCQ6CVTI2HVX6WUELYIY262WI", label:"[email protected]"}, function (error) {
  if (error) console.error(error)
  console.log('success!');
})

Precompiled bundle

<canvas id="canvas"></canvas>

<script src="/build/qrcode.js"></script>
<script>
  QRCode.toCanvas(document.getElementById('canvas'), {wallet:"AMESZ5UX7ZJL5M6GYEHXM63OMFCPOJ23UXCQ6CVTI2HVX6WUELYIY262WI", label:"[email protected]"}, function (error) {
    if (error) console.error(error)
    console.log('success!');
  })
</script>

If you install through npm, precompiled files will be available in node_modules/algorand-qrcode/build/ folder.

The precompiled bundle have support for Internet Explorer 10+, Safari 5.1+, and all evergreen browsers.

NodeJS

Require the module algorand-qrcode

var QRCode = require('algorand-qrcode')

QRCode.toDataURL({wallet:"AMESZ5UX7ZJL5M6GYEHXM63OMFCPOJ23UXCQ6CVTI2HVX6WUELYIY262WI", label:"[email protected]"}, function (err, url) {
  console.log(url)
})

render a qrcode for the terminal

var QRCode = require('algorand-qrcode')

QRCode.toString({type:'terminal',wallet:"AMESZ5UX7ZJL5M6GYEHXM63OMFCPOJ23UXCQ6CVTI2HVX6WUELYIY262WI", label:"[email protected]"}, function (err, url) {
  console.log(url)
})

ES6/ES7

Promises and Async/Await can be used in place of callback function.

import * as QRCode from 'algorand-qrcode'

// With promises
QRCode.toDataURL({wallet:"AMESZ5UX7ZJL5M6GYEHXM63OMFCPOJ23UXCQ6CVTI2HVX6WUELYIY262WI", label:"[email protected]"})
  .then(({ dataUrl, alrorandURI }) => {
    console.log(dataUrl)
    console.log(alrorandURI)
  })
  .catch(err => {
    console.error(err)
  })

// With async/await
const generateQR = async text => {
  try {
    console.log(await QRCode.toDataURL({wallet:"AMESZ5UX7ZJL5M6GYEHXM63OMFCPOJ23UXCQ6CVTI2HVX6WUELYIY262WI", label:"[email protected]"}))
  } catch (err) {
    console.error(err)
  }
}

Error correction level

Error correction capability allows to successfully scan a QR Code even if the symbol is dirty or damaged. Four levels are available to choose according to the operating environment.

Higher levels offer a better error resistance but reduce the symbol's capacity.
If the chances that the QR Code symbol may be corrupted are low (for example if it is showed through a monitor) is possible to safely use a low error level such as Low or Medium.

Possible levels are shown below:

Level Error resistance
L (Low) ~7%
M (Medium) ~15%
Q (Quartile) ~25%
H (High) ~30%

The percentage indicates the maximum amount of damaged surface after which the symbol becomes unreadable.

Error level can be set through options.errorCorrectionLevel property.
If not specified, the default value is M.

QRCode.toDataURL({wallet:"AMESZ5UX7ZJL5M6GYEHXM63OMFCPOJ23UXCQ6CVTI2HVX6WUELYIY262WI", label:"[email protected]", errorCorrectionLevel: 'H'}, function (err, url) {
  console.log(url)
})

API

Browser:

Server:

Browser API

create([options])

Creates QR Code symbol and returns a qrcode object.

options

See QR Code options.
See Algorand URI options.

returns

Type: Object

// QRCode object
{
  modules,              // Bitmatrix class with modules data
  version,              // Calculated QR Code version
  errorCorrectionLevel, // Error Correction Level
  maskPattern,          // Calculated Mask pattern
  segments              // Generated segments
}

toCanvas(canvasElement, [options], [cb(error)])

toCanvas([options], [cb(error, canvas)])

Draws qr code symbol to canvas.
If canvasElement is omitted a new canvas is returned.

canvasElement

Type: DOMElement

Canvas where to draw QR Code.

options

See All Options.
See Algorand URI options.

cb

Type: Function

Callback function called on finish.

Example
QRCode.toCanvas({wallet:"AMESZ5UX7ZJL5M6GYEHXM63OMFCPOJ23UXCQ6CVTI2HVX6WUELYIY262WI", label:"[email protected]"}, function (err, canvas) {
  if (err) throw err

  var container = document.getElementById('container')
  container.appendChild(canvas)
})

toDataURL([options], [cb(error, url)])

toDataURL(canvasElement, [options], [cb(error, url)])

Returns a Data URI containing a representation of the QR Code image.
If provided, canvasElement will be used as canvas to generate the data URI.

canvasElement

Type: DOMElement

Canvas where to draw QR Code.

options
  • type

    Type: String
    Default: image/png

    Data URI format.
    Possible values are: image/png, image/jpeg, image/webp.

  • rendererOpts.quality

    Type: Number
    Default: 0.92

    A Number between 0 and 1 indicating image quality if the requested type is image/jpeg or image/webp.

See All Options.
See Algorand URI options.

cb

Type: Function

Callback function called on finish.

Example
var opts = {
  wallet:"AMESZ5UX7ZJL5M6GYEHXM63OMFCPOJ23UXCQ6CVTI2HVX6WUELYIY262WI",
  label:"[email protected]",
  errorCorrectionLevel: 'H',
  type: 'image/jpeg',
  quality: 0.3,
  margin: 1,
  color: {
    dark:"#010599FF",
    light:"#FFBF60FF"
  }
}

QRCode.toDataURL(opts, function (err, url) {
  if (err) throw err

  var img = document.getElementById('image')
  img.src = url
})

toString([options], [cb(error, string)])

Returns a string representation of the QR Code.

options
  • type

    Type: String
    Default: utf8

    Output format.
    Possible values are: terminal,utf8, and svg.

See All Options.
See Algorand URI options.

cb

Type: Function

Callback function called on finish.

Example
QRCode.toString({wallet:"AMESZ5UX7ZJL5M6GYEHXM63OMFCPOJ23UXCQ6CVTI2HVX6WUELYIY262WI", label:"[email protected]"}, function (err, string) {
  if (err) throw err
  console.log(string)
})

Server API

create([options])

See create.
See Algorand URI options.


toCanvas(canvas, [options], [cb(error)])

Draws qr code symbol to node canvas.

options

See All Options.
See Algorand URI options.

cb

Type: Function

Callback function called on finish.


toDataURL([options], [cb(error, url)])

Returns a Data URI containing a representation of the QR Code image.
Only works with image/png type for now.

options

See All Options.
See Algorand URI options.

cb

Type: Function

Callback function called on finish.


toString([options], [cb(error, string)])

Returns a string representation of the QR Code.
If choosen output format is svg it will returns a string containing xml code.

options
type

Type: String
Default: utf8

Output format.
Possible values are: utf8, svg, terminal.

See All Options.
See Algorand URI options.

cb

Type: Function

Callback function called on finish.

Example
QRCode.toString({wallet:"AMESZ5UX7ZJL5M6GYEHXM63OMFCPOJ23UXCQ6CVTI2HVX6WUELYIY262WI", label:"[email protected]", type: 'utf8'}, function (err, string) {
  if (err) throw err
  console.log(string)
})

toFile(path, [options], [cb(error)])

Saves QR Code to image file.
If options.type is not specified, the format will be guessed from file extension.
Recognized extensions are png, svg, txt.

path

Type: String

Path where to save the file.

options
  • type

    Type: String
    Default: png

    Output format.
    Possible values are: png, svg, utf8.

  • rendererOpts.deflateLevel (png only)

    Type: Number
    Default: 9

    Compression level for deflate.

  • rendererOpts.deflateStrategy (png only)

    Type: Number
    Default: 3

    Compression strategy for deflate.

See All Options.
See Algorand URI options.

cb

Type: Function

Callback function called on finish.

Example
QRCode.toFile('path/to/filename.png', {
  wallet:"AMESZ5UX7ZJL5M6GYEHXM63OMFCPOJ23UXCQ6CVTI2HVX6WUELYIY262WI",
  label:"[email protected]",
  color: {
    dark: '#00F',  // Blue dots
    light: '#0000' // Transparent background
  }
}, function (err) {
  if (err) throw err
  console.log('done')
})

toFileStream(stream, [options])

Writes QR Code image to stream. Only works with png format for now.

stream

Type: stream.Writable

Node stream.

options

See All Options.
See Algorand URI options.

All Options

QR Code options

version

Type: Number

QR Code version. If not specified the more suitable value will be calculated.

errorCorrectionLevel

Type: String
Default: M

Error correction level.
Possible values are low, medium, quartile, high or L, M, Q, H.

maskPattern

Type: Number

Mask pattern used to mask the symbol.
Possible values are 0, 1, 2, 3, 4, 5, 6, 7.
If not specified the more suitable value will be calculated.

html

Type: Boolean

Specifies if the text string fields are to be HTML Escaped or not.

withBgLogo

Type: Boolean

Specifies if the QR Code should use an image (passed as bgLogo option) as background image.

withBg

Type: Boolean

Specifies if the QR Code should use an image (passed as bgLogo option) as centered logo image with specified size (logoSize option).

bgLogo

Type: String

Base 64 DataURL string of background image.

logo

Type: String

Base 64 DataURL string of centered image.

logoSize

Type: Number

Specifies size of centered logo image if the boolean option withLogo is set as TRUE

Algorand URI params

wallet

Type: String

Wallet address for Algorand transaction.

xnote

Type: Boolean

Specifies if the xnote or note field is used for Algorand URI construction.

amount

Type: Number

Amount of Algorand transaction in MicroAlgos or Standard Asset Unit.

label

Type: String

Label of Algorand transaction.

asset

Type: String

Asset Id of Algorand transaction if used. If not specified , Algo will be used as fungible token.

note

Type: String

note or xnote field content of Algorand transaction. The xnote option determines the name of the field with this content to be note or xnote.

Renderers options

margin

Type: Number
Default: 4

Define how much wide the quiet zone should be.

scale

Type: Number
Default: 4

Scale factor. A value of 1 means 1px per modules (black dots).

small

Type: Boolean
Default: false

Relevant only for terminal renderer. Outputs smaller QR code.

width

Type: Number

Forces a specific width for the output image.
If width is too small to contain the qr symbol, this option will be ignored.
Takes precedence over scale.

color.dark

Type: String
Default: #000000ff

Color of dark module. Value must be in hex format (RGBA).
Note: dark color should always be darker than color.light.

color.light

Type: String
Default: #ffffffff

Color of light module. Value must be in hex format (RGBA).

Coming Soon

GS1 QR Codes : What defines a GS1 qrcode is a header with metadata that describes your gs1 information.

More options: More configuration options on styling.

Advanced Masks: Advance masking formulas for practicality and beautification.

License

MIT

Credits

Special appreciations to Sheghzo.

This repository uses and appreciates great open source software and code by forking, extention and integration of:

The idea for this lib was inspired by: Algorand developers portal Article Payment Prompts with Algorand Mobile Wallet ,from Jason Paulos.

Mentioned Trademarks

"QR Code" curtsey of :

"Algorand" curtsey of:

algorand-qrcode's People

Contributors

stardev930 avatar sheghzo avatar

Stargazers

smart-topdeveloper avatar

Watchers

 avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.