npm

@nano.gift/nano.js

1.1.6 • Public • Published
Integrate nano to your service today!

Nano.js

Interact with the nano blockchain using javascript easily! 🔥

Table of contents

Table of Contents

Introduction

Nano.js is a comprehensive JavaScript library for interacting with the Nano cryptocurrency.

Installation

npm i @nano.gift/nano.js --save

Wallet Functions

consists of block functions, websocket, rpc, privacy addons and an embedded database for storing wallet state

the program is completely written with security first in mind, if you find any flaws or want to report a bug, feel free to open a github issue.

To Fellow Explorers

a module could easily be extracted from it for devs to easily interact with the nano blockchain, and you're welcome! just dont forget to credit me :3 Edit: I made it a module for you :D

Example Usage

image

Documentation

Wallet Class

Initialize Wallet

const wallet = new Wallet(masterSeed, {
  WS_URL: string,
  RPC_URL: string,
  WORK_SERVER?: string,
  Headers?: Record<string, any>,
  autoReceive?: boolean,
});
  • masterSeed (string): The master seed for deriving Nano accounts.
  • WS_URL (string): WebSocket URL for Nano blockchain interaction.
  • RPC_URL (string): RPC URL for Nano blockchain interaction.
  • WORK_SERVER (string, optional): Work server URL for generating proof-of-work.
  • Headers (Record<string, any>, optional): Headers for authentication.
  • autoReceive (boolean, optional): Set to true for automatic handling of received transactions.

Manage Accounts

note: index is an integer which is used to derive the account from the master key.

Get All Accounts

const allAccounts = wallet.getAllAccounts();

Add an Account

const newAccount = wallet.addAccount(index);

Remove an Account

wallet.removeAccount(index);

Get an Account

const accountDetails = wallet.getAccount(index);

Transaction Operations

Send Nano

const sendHash = await wallet.send({
  recipient: string,
  amount: number,
  from: number,
  isRaw?: boolean,
});

Set Representative

const representativeResult = await wallet.setRepresentative({
  newRepresentative: string,
  accountIndex: number,
});

Reset Wallet

wallet.resetWallet();

⚠️ this function removes all db files and config

Receiving Nano

Single Block

const received = await wallet.Block().receive({hash, amount}, privateKey);

All Transactions

const allArrayReceived = await wallet.Block().receiveAll(privateKey);

Wallet Events

wallet.once("ready", () => callback); // emitted upon wallet initialization
wallet.on("receive/send/representative", (hash) => console.log(hash.hash); 

Creating Invoices

Invoice Builder

const invoice = new InvoiceBuilder({
  useRaw: false, // raw nano values
  liveUpdate: true, // uses websocket
  rpcEndpoint: "nano_rpc_url",
  wsEndpoint?: "Websocket url if you\'re using it",
  customHeaders: { /* add your custom headers if needed */ },
  maxHistory: "50", // this is the history calls to check if ws is disabled
});

you initialize your invoice builder class here and can further use our functions

Creating Invoices

const newInvoice = invoice.create(options: {
recipientAddress: "the address to receive nano on",
amountNano: amount,
label?: string,
message?: message,
roundingPercent: integer
});
  • label and message are optional values for the QRCode
  • roundingPercent is the % you are okay at neglecting if the sender makes a small percent difference in payment, i would suggest setting it to zero if you are creating multiple invoices on same address

@ returns invoice ID

Retrieving Invoices

const invoiceData = invoice.get(newInvoiceId);

// returns:
{
  id: 'invoice id',
  data: {
    uri: 'nano:<address>?amount=<raw>&label=if?&message=if?',
    qrCode: QRBUFFER,
    address: '<address>',
    amount: '<raw>',
    label?: string,
    message?: string,
    roundingPercent: integer,
    status: 'waiting',
    invoiceId: 'invoice id'
  }
}

Fetch Status

await invoice.checkStatus(invoiceID);

returns null if not found, satisfies payment and returns paid object if received

Remove Invoice

invoice.remove(invoiceID);

invoices stay in memory as in a map, remove them through this function.

Invoice Events

invoice.on("payment", (invoiceData) => {
  console.log("Payment received:", invoiceData); // payment done on $invoiceID
});

invoice.on("error", (errorDetails) => {
  console.error("Error:", errorDetails); // eg: already paid
});

payment events are only available if liveUpdate is enabled and a valid nano ws uri is inputted in the InvoiceBuilder constructor

Creating QRs

const qrResult = await createQr({
  address: "address",
  amount: integer, 
  label: "Example Label",
  message: "Example Message",
  isRaw: false, // Set to true if the amount is already in raw
});

@returns uri (nano protocol standard url) and qrCode (buffer), here is an example:

QR Code

PLEASE DONT SEND ANY NANO HERE IT IS AN EXAMPLE QR!

RPC Usage

RPC Constructor

const rpc = new RPC(RPC_URL = "nano rpc url", customHeaders: Record, WORK_URL? = "rpc url used if not found");

Account Info

await rpc.account_info(address);

Work Generate

await rpc.generate_work(hash);

Receivable

await rpc.receivable(address);

Process

await rpc.process();

this is used to publish signed blocks to the blockchain through the node

Custom Call

await rpc.request({
"action",
...params
});

this method can be used to invoke any available rpc function, please refer to official rpc docs here to find available rpc commands

WS Usage

WS Constructor

const ws = new WebSocket(ws_url: string)

Send To Ws

check params which are available to use here

ws.send(json)

WS Events

ws.on("ready", () => console.log("socket opened");
ws.on("error", (error) => console.log("socket exitted with error," e);
ws.on("close", (event) => console.log("ws closed") // reconnects by default
ws.on("message", (message) => console.log(`received message from socket ${message});

Converting Units

here is an example code to convert between raw and nano

const toRaw = nanoToRaw(3); // 3000000000000000000000000000000
const toNano = nanoToRaw(3); // 0.000000000000000000000000000003

Credits

Much thanks to them who helped me with libs:


Benskalz

💻

Numsu

💻

Marvin Roger

💻

special thanks to nanswap nodes for letting me use their nodes! <3

© Celio Sevii 2024, you are free to use it for commercial products :D

Readme

Keywords

none

Package Sidebar

Install

npm i @nano.gift/nano.js

Weekly Downloads

0

Version

1.1.6

License

ISC

Unpacked Size

204 kB

Total Files

81

Last publish

Collaborators

  • nan481