vledger

1.0.16 • Public • Published

Installation

Using npm:

npm i vledger

Description

VLedger is a Express and MongoDB library that can be installed to enable a database ledger storing balances for individual user accounts. Balances managed by VLedger can be backed by any real world currency via API connectors written by the developer. VLedger uses a safe mathematics library to perform transactions between user accounts. VLedger is the perfect choice for your web or finance application

Requirements

VLedger works on MongoDB, it doesnt handle any authentication and must be passed a MongoClient() created by the developer. VLedger requires the developer to run a single setup to install some necessary data into the database(s), this is handled automatically in the VLedger demo which you can run yourself. VLedger can work on any developers database as it can be passed an object denoting the database and collection names to use. Importantly VLedger can connect to any external ledger such as a merchant bank API. In order to do this the developer must write some functions to interact with said API and then pass them to VLedger. VLesger also requires Node environmental variables via process.env .

Demo

let vledger=require('vledger')

async function test()
{
        //USE YOUR MONGODB CONNECTION STRING HERE
        let URI='mongodb://localhost:27017'
        let vl=new vledger()
        let s=await vl.testsetup(URI)
        let l=await vl.testledger(URI)
}

test()

This should run successfully with no errors. Make sure to use your own correct MongoDB connection string.

Usage

VLedger works with MongoDB, to setup VLedger you must define database names and collections for VLedger to use. These names must not be the same as other names used in your application. The databse configuration is stored in process.env.vl.

process.env.vl=JSON.stringify({
	config:{
		db:{
			tokens:{d:"main",c:"tokens"},
			plan:{d:"main",c:"plan"},
			fees:{d:"main",c:"fees"},
			wdconfig:{d:"main",c:"wdconfig"},
			common:{d:"main",c:"common"},  //store , user
			users:{d:"main",c:"users"},
			transit:{d:"main",c:"transit"},
			process:{d:"main",c:"process"}		
		}	
	}
})

VLedger can connect to practically any external ledger system to enable the management of currencies that exist on those systems within your own server running VLedger. In order to connect to another ledger you must write functions that:

  • create accounts
  • read balance
  • transfer assets
  • confirm transactions are complete

Create a file called api.js and paste in the following code:

/*
	A DEMO CODE TO CONNECT VLEDGER TO AN API PROVIDED BY MYBANK.
	THE CODE USES THE SECRET KEY TO TRANSFER CURRENCY

*/

let _=require('lodash')


let CorpBank={
	IBAN:"djvnkdjnvvkj",
	AN:0384893,
	country:"United Kingdom",
	bank:"Gold Bank Ltd"
}

let APIKEY="SECRETKEY"

module.exports={
	mybank:{
	getDeposit:async (params)=>{
		//IGNORE
	},
	create:async (params)=>{
		//CREATE A RANDOM REFERENCE FOR AN INDIVIDUAL USER DEPOSIT ACCOUNT
		if(params.type=="deposit"){
			let ref="NKC489U38EJNVKJDNK"
			console.log("DEPOSIT")
			//VLedger uses the key "address" to discriminate accounts
			let ret={
				address:ref,
				fiat:_.assign(CorpBank,{reference:ref})			
			}
			return ret
		}
		else if(params.type=="common"){
			//VLedger needs address to discriminate between accounts
			let ret={
				address:CorpBank.IBAN,
				fiat:CorpBank			
			}
			return ret
		}
		return undefined
	},
	getBalance:async (params)=>{
		//read balance of a deposit account by checking new transactions on the reference
		if(params.type=="deposit")
		{
			
			//READ BALANCE OF ALL INCOME TRANSACTIONS
			//TEST MODE IGNORES THIS FUNCTION AND INCREASES THE BALANCE
			return '0' 
		}
		else if(params.type=="common")
		{
			return '0'
		}
	},
	transfer:async (params)=>{
		if(params.type=="deposit")
		{
			//GET TRANSACTION CONFIRMATION FOR THE DEPOSIT
			return "A DEPOSIT"
		}
		else if(params.type=="withdraw")
		{
			return "A TRANSFER"
		}		
		//transfer from a common account using the external API
		//Should return an object on success, and undefined on failure
	},
	confirm:async (params)=>{
		let fields={
			confirmation:params.confirmation		
		}
		// CALL BANK
		return {status:"OK"}
	}
}
}

You can use VLedger to enable the use of a currency in a ledger on another server for example a merchant bank or other digital currency. In order to use a particular currency with VLedger the currency must be installed into your database. In addition you must install a collections defining transaction fees and the withdrawal fees you want to use on your server.

const tokens=[
	{platform:"mybank",network:"main",class:"fiat",address:"GBP"}
]

const fees=[
	{platform:"mybank",network:"main",fee_unit:"1"}
]

const wd=[
	{
		token:{
			currency:{
				platform:"mybank",
				class:"fiat",
				network:"main",
				address:"GBP"
			}		
		},
		minimum:"10",
		fees:{
			free:{type:"q",amount:0.05},
			bronze:{type:"q",amount:0.03},
			silver:{type:"q",amount:0.02},
			gold:{type:"q",amount:0.01}
		}
	}
]

Next you must enable the use of the installed currency by users on your server. First by creating ledger accounts for the users ,then creating deposit accounts for each user where they can transfer funds into the server. Finally you must create a subscription plan for each user to set their withdrawal fees. This works with the general withdrawal fes object set above.

let plan={
	accountID:"user01",
	subscription:{
		planID:"free",
		status:"active"
	}
}

Here is the full script for initial setup of vledger which can be used (requires lodash and mongodb too):

let vledger=require('vledger')
let mongo=require('mongodb')
let _=require('lodash')
let api=require('./api.js')

const URI='mongodb://localhost:27017'
let config={
			db:{
				tokens:{d:"main",c:"tokens"},
				plan:{d:"main",c:"plan"},
				fees:{d:"main",c:"fees"},
				wdconfig:{d:"main",c:"wdconfig"},
				common:{d:"main",c:"common"},  //store , user
				users:{d:"main",c:"users"},
				transit:{d:"main",c:"transit"},
				process:{d:"main",c:"process"}	
	
				
			}	
		}
	


let tokens=[
    {class:"fiat",platform:"mybank",network:"1",address:"GBP",nickname:"British Pound Sterling",decimals:2,symbol:"GBP",
    description:"British Pound Sterling"}
]	
	
let wdconfig=[
	{
		token:{
			currency:{
				platform:"mybank",
				class:"fiat",
				network:"1",
				address:"GBP"
			}		
		},
		minimum:"10",
		fees:{
			free:{type:"q",amount:0.05},
			bronze:{type:"q",amount:0.05},
			silver:{type:"q",amount:0.05},
			gold:{type:"q",amount:0.05}
		}
			
	}
]

let setup=async()=>{
	let MongoClient=require('mongodb').MongoClient
	let client=new MongoClient(URI)
	let p=new Promise((resolve,reject)=>{
		client.connect(async (err)=>{
			console.log("BEGIN VLEDGER INSTALLATION")
			let vl=new vledger(config)
			let c=config.db
			let tkn=tokens[0]
			let r=await client.db(c.tokens.d).collection(c.tokens.c).insertMany(tokens)
			let fees=[
				{platform:"mybank",network:"1",fee_unit:"1"}
			]
			let r1=await client.db(c.fees.d).collection(c.fees.c).insertMany(fees)
			//INSTALL WITHDRAW CONFIGURATION		
			let r2=await client.db(c.wdconfig.d).collection(c.wdconfig.c).insertMany(wdconfig)

			let rc=await vl.create({type:"common",nickname:"common01",currency:tkn,api:api},client)
			console.log('CREATE COMMON ACCOUNT')	
			console.log(rc)
			
			
			console.log('CREATE USER ACCOUNT')	
			let ru=await vl.create({type:"user",accountID:"user01"},client)
			console.log(ru)
			
			let r3=await vl.deposit({type:"deposit",accountID:"user01",currency:tkn,api:api},client,true)
			console.log('CREATE DEPOSIT')
			console.log(r3)
			
			let plan={
				accountID:"user01",
				subscription:{
					planID:"free",
					status:"active"
				}			
			}
			let rw=await client.db(_.get(c,'plan.d')).collection(_.get(c,'plan.c')).insertOne(plan)
			console.log('CREATE USER PLAN')
			console.log(rw)
			
			console.log("END VLEDGER INSTALLATION")					
		
		})
	})
		
	
}
setup()

Now you will be able to create user accounts,mint and burn tokens and send transactions. Copy the code below to complete this within your project.

let vledger=require('vledger')
let mongo=require('mongodb')
let _=require('lodash')
let api=require('./api.js')

const URI='mongodb://localhost:27017'
let config={
			db:{
				tokens:{d:"main",c:"tokens"},
				plan:{d:"main",c:"plan"},
				fees:{d:"main",c:"fees"},
				wdconfig:{d:"main",c:"wdconfig"},
				common:{d:"main",c:"common"},  //store , user
				users:{d:"main",c:"users"},
				transit:{d:"main",c:"transit"},
				process:{d:"main",c:"process"}	
	
				
			}	
}

let tkn={class:"fiat",platform:"mybank",network:"1",address:"GBP",nickname:"British Pound Sterling",decimals:2,symbol:"GBP",
    description:"British Pound Sterling"}
let transact=async ()=>{
	let MongoClient=require('mongodb').MongoClient
	let client=new MongoClient(URI)
	let p=new Promise((resolve,reject)=>{
	client.connect(async (err)=>{
		let vl=new vledger(config)
		let c=config.db
		//create a new user
		let u2=await vl.create({type:'user',accountID:'user02'},client)	
		
		//mint tokens for user01
		let common=await client.db(_.get(c,'common.d')).collection(_.get(c,'common.c')).findOne({'currency.platform':tkn.platform,
				'currency.network':tkn.network,
				'currency.class':tkn.class,
				'currency.address':tkn.address},client)	
		let mint=await vl.mint({
				to:"user01",
				currency:tkn,
				amount:"1000000000000",	
				account:{address:common.address,type:"common"}},client)
		console.log('MINTED TOKENS 1000000000000 FOR USER01')
				
		//read user balances
		let b1=await vl.balance({accountID:"user01",currency:tkn},client)
		console.log('USER 1 BALANCE')
		console.log(b1)
		let b2=await vl.balance({accountID:"user02",currency:tkn},client)
		console.log('USER 2 BALANCE')
		console.log(b2)
		//transfer tokens to user02
		let tx=await vl.transfer({
			from:"user01",to:"user02",amount:"10000",
			unit:"dec",
			platform:"mybank",
			network:"1",
			currency:tkn
			},client)
		console.log('TRANSFER 10000 tokens to USER 02')
		console.log(tx)
		
		b1=await vl.balance({accountID:"user01",currency:tkn},client)
		console.log('USER 1 BALANCE')
		console.log(b1)
		b2=await vl.balance({accountID:"user02",currency:tkn},client)
		console.log('USER 2 BALANCE')
		console.log(b2)
		console.log('BURNING 100000 tokens from USER 01')
		
		let b3=await vl.burn({
			from:"user01",
			amount:"100000",
			currency:tkn,
			type:"common",
			account:{address:common.address}},client)
		
		console.log('USER 1 BALANCE')
		b1=await vl.balance({accountID:"user01",currency:tkn},client)
		console.log(b1)
		resolve(true)
		return
	})
	})
	return
}
transact()

In order to process deposits and withdrawals you must create separate task scripts that your installation will run as scheduled scripts. These will use deposit and withdrawal methods from VLedger. You should setup the scripts to run very regularly on the server.

As shown above the methods vl.[method] from the vledger library must be called within an async function with the ongo client.

To display deposit information:

let info=await vl.udeposit.get({accountID:'user01',currency:tkn},client)

Here tkn is the same object created in the previous code example.

To process deposits you must execute these lines in scheduled scripts:

		let f=await vl.udeposit.find({currency:tkn,api:api},client)
		console.log(f)
		let t=await vl.udeposit.transfer({api:api},client)
		console.log(t)
		let ch=await vl.udeposit.check({api:api},client)
		console.log(ch)

To start a new withdrawal from a user account:

	let r=await vl.withdraw.create({
				payment:{
					r:"123",
					from:'user01',
					to:{
						IBAN:"IBANIBANIBANIBAN489R54879",
						AN:38349489,
						SC:389432,
						country:"UK"
					},
					amount:"100000",
					unit:"dec",
					currency:tkn	
				}},client)

To process withdrawals you must execute these lines in scheduled scripts, the last argument true makes the function run in test mode:

		let t=await vl.withdraw.transfer({currency:tkn,api:api},client,true)
		console.log(t)
		let ch=await vl.withdraw.check({currency:tkn,api:api},client)
		console.log(ch)

Package Sidebar

Install

npm i vledger

Weekly Downloads

1

Version

1.0.16

License

MIT

Unpacked Size

155 kB

Total Files

48

Last publish

Collaborators

  • daniwo