").append(x.parseHTML(e)).find(r):e)}).complete(n&&function(e,t){s.each(n,o||[e.responseText,t,e])}),this},x.each(["ajaxStart","ajaxStop","ajaxComplete","ajaxError","ajaxSuccess","ajaxSend"],function(e,t){x.fn[t]=function(e){return this.on(t,e)}}),x.extend({active:0,lastModified:{},etag:{},ajaxSettings:{url:Xt,type:"GET",isLocal:Qt.test(_t[1]),global:!0,processData:!0,async:!0,contentType:"application/x-www-form-urlencoded; charset=UTF-8",accepts:{"*":on,text:"text/plain",html:"text/html",xml:"application/xml, text/xml",json:"application/json, text/javascript"},contents:{xml:/xml/,html:/html/,json:/json/},responseFields:{xml:"responseXML",text:"responseText",json:"responseJSON"},converters:{"* text":String,"text html":!0,"text json":x.parseJSON,"text xml":x.parseXML},flatOptions:{url:!0,context:!0}},ajaxSetup:function(e,t){return t?ln(ln(e,x.ajaxSettings),t):ln(x.ajaxSettings,e)},ajaxPrefilter:an(nn),ajaxTransport:an(rn),ajax:function(e,t){"object"==typeof e&&(t=e,e=undefined),t=t||{};var n,r,i,o,s,a,u,l,c=x.ajaxSetup({},t),f=c.context||c,p=c.context&&(f.nodeType||f.jquery)?x(f):x.event,h=x.Deferred(),d=x.Callbacks("once memory"),g=c.statusCode||{},m={},y={},v=0,b="canceled",T={readyState:0,getResponseHeader:function(e){var t;if(2===v){if(!o){o={};while(t=Jt.exec(i))o[t[1].toLowerCase()]=t[2]}t=o[e.toLowerCase()]}return null==t?null:t},getAllResponseHeaders:function(){return 2===v?i:null},setRequestHeader:function(e,t){var n=e.toLowerCase();return v||(e=y[n]=y[n]||e,m[e]=t),this},overrideMimeType:function(e){return v||(c.mimeType=e),this},statusCode:function(e){var t;if(e)if(2>v)for(t in e)g[t]=[g[t],e[t]];else T.always(e[T.status]);return this},abort:function(e){var t=e||b;return n&&n.abort(t),k(0,t),this}};if(h.promise(T).complete=d.add,T.success=T.done,T.error=T.fail,c.url=((e||c.url||Xt)+"").replace(Vt,"").replace(Zt,_t[1]+"//"),c.type=t.method||t.type||c.method||c.type,c.dataTypes=x.trim(c.dataType||"*").toLowerCase().match(w)||[""],null==c.crossDomain&&(a=en.exec(c.url.toLowerCase()),c.crossDomain=!(!a||a[1]===_t[1]&&a[2]===_t[2]&&(a[3]||("http:"===a[1]?"80":"443"))===(_t[3]||("http:"===_t[1]?"80":"443")))),c.data&&c.processData&&"string"!=typeof c.data&&(c.data=x.param(c.data,c.traditional)),un(nn,c,t,T),2===v)return T;u=c.global,u&&0===x.active++&&x.event.trigger("ajaxStart"),c.type=c.type.toUpperCase(),c.hasContent=!Kt.test(c.type),r=c.url,c.hasContent||(c.data&&(r=c.url+=(Yt.test(r)?"&":"?")+c.data,delete c.data),c.cache===!1&&(c.url=Gt.test(r)?r.replace(Gt,"$1_="+Ut++):r+(Yt.test(r)?"&":"?")+"_="+Ut++)),c.ifModified&&(x.lastModified[r]&&T.setRequestHeader("If-Modified-Since",x.lastModified[r]),x.etag[r]&&T.setRequestHeader("If-None-Match",x.etag[r])),(c.data&&c.hasContent&&c.contentType!==!1||t.contentType)&&T.setRequestHeader("Content-Type",c.contentType),T.setRequestHeader("Accept",c.dataTypes[0]&&c.accepts[c.dataTypes[0]]?c.accepts[c.dataTypes[0]]+("*"!==c.dataTypes[0]?", "+on+"; q=0.01":""):c.accepts["*"]);for(l in c.headers)T.setRequestHeader(l,c.headers[l]);if(c.beforeSend&&(c.beforeSend.call(f,T,c)===!1||2===v))return T.abort();b="abort";for(l in{success:1,error:1,complete:1})T[l](c[l]);if(n=un(rn,c,t,T)){T.readyState=1,u&&p.trigger("ajaxSend",[T,c]),c.async&&c.timeout>0&&(s=setTimeout(function(){T.abort("timeout")},c.timeout));try{v=1,n.send(m,k)}catch(C){if(!(2>v))throw C;k(-1,C)}}else k(-1,"No Transport");function k(e,t,o,a){var l,m,y,b,w,C=t;2!==v&&(v=2,s&&clearTimeout(s),n=undefined,i=a||"",T.readyState=e>0?4:0,l=e>=200&&300>e||304===e,o&&(b=cn(c,T,o)),b=fn(c,b,T,l),l?(c.ifModified&&(w=T.getResponseHeader("Last-Modified"),w&&(x.lastModified[r]=w),w=T.getResponseHeader("etag"),w&&(x.etag[r]=w)),204===e?C="nocontent":304===e?C="notmodified":(C=b.state,m=b.data,y=b.error,l=!y)):(y=C,(e||!C)&&(C="error",0>e&&(e=0))),T.status=e,T.statusText=(t||C)+"",l?h.resolveWith(f,[m,C,T]):h.rejectWith(f,[T,C,y]),T.statusCode(g),g=undefined,u&&p.trigger(l?"ajaxSuccess":"ajaxError",[T,c,l?m:y]),d.fireWith(f,[T,C]),u&&(p.trigger("ajaxComplete",[T,c]),--x.active||x.event.trigger("ajaxStop")))}return T},getJSON:function(e,t,n){return x.get(e,t,n,"json")},getScript:function(e,t){return x.get(e,undefined,t,"script")}}),x.each(["get","post"],function(e,t){x[t]=function(e,n,r,i){return x.isFunction(n)&&(i=i||r,r=n,n=undefined),x.ajax({url:e,type:t,dataType:i,data:n,success:r})}});function cn(e,t,n){var r,i,o,s,a=e.contents,u=e.dataTypes;while("*"===u[0])u.shift(),r===undefined&&(r=e.mimeType||t.getResponseHeader("Content-Type"));if(r)for(i in a)if(a[i]&&a[i].test(r)){u.unshift(i);break}if(u[0]in n)o=u[0];else{for(i in n){if(!u[0]||e.converters[i+" "+u[0]]){o=i;break}s||(s=i)}o=o||s}return o?(o!==u[0]&&u.unshift(o),n[o]):undefined}function fn(e,t,n,r){var i,o,s,a,u,l={},c=e.dataTypes.slice();if(c[1])for(s in e.converters)l[s.toLowerCase()]=e.converters[s];o=c.shift();while(o)if(e.responseFields[o]&&(n[e.responseFields[o]]=t),!u&&r&&e.dataFilter&&(t=e.dataFilter(t,e.dataType)),u=o,o=c.shift())if("*"===o)o=u;else if("*"!==u&&u!==o){if(s=l[u+" "+o]||l["* "+o],!s)for(i in l)if(a=i.split(" "),a[1]===o&&(s=l[u+" "+a[0]]||l["* "+a[0]])){s===!0?s=l[i]:l[i]!==!0&&(o=a[0],c.unshift(a[1]));break}if(s!==!0)if(s&&e["throws"])t=s(t);else try{t=s(t)}catch(f){return{state:"parsererror",error:s?f:"No conversion from "+u+" to "+o}}}return{state:"success",data:t}}x.ajaxSetup({accepts:{script:"text/javascript, application/javascript, application/ecmascript, application/x-ecmascript"},contents:{script:/(?:java|ecma)script/},converters:{"text script":function(e){return x.globalEval(e),e}}}),x.ajaxPrefilter("script",function(e){e.cache===undefined&&(e.cache=!1),e.crossDomain&&(e.type="GET")}),x.ajaxTransport("script",function(e){if(e.crossDomain){var t,n;return{send:function(r,i){t=x("
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
Class: userAirdropDetailCache
-
-
-
-
-
- userAirdropDetailCache
-
-
-
-
-
-
-
-
-
-
-
-
- new userAirdropDetailCache(params)
-
-
-
-
-
-
-
-
-
-
-
-
-
- Parameters:
-
-
-
-
-
-
- Name
-
-
- Type
-
-
-
-
-
- Description
-
-
-
-
-
-
-
-
- params
-
-
-
-
-
-Object
-
-
-
-
-
-
-
-
-
-
- cache key generation & expiry related params
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- Extends
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- Methods
-
-
-
-
-
- fetchDataFromSource()
-
-
-
-
-
-
-
- fetch data from source
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- Overrides:
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- Returns:
-
-
-
-
-
-
- Type
-
-
-
-Result
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- getCacheKey(address)
-
-
-
-
-
-
-
- Get cache keys
-
-
-
-
-
-
-
-
-
- Parameters:
-
-
-
-
-
-
- Name
-
-
- Type
-
-
-
-
-
- Description
-
-
-
-
-
-
-
-
- address
-
-
-
-
-
-string
-
-
-
-
-
-
-
-
-
-
- address
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- Overrides:
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- Returns:
-
-
-
-
-
-
- Type
-
-
-
-string
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- setCacheExpiry()
-
-
-
-
-
-
-
- set cache expiry in oThis.cacheExpiry and return it
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- Overrides:
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- Returns:
-
-
-
-
-
-
- Type
-
-
-
-Number
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- setCacheKeys()
-
-
-
-
-
-
-
- set cache key
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- Overrides:
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- Returns:
-
-
-
-
-
-
- Type
-
-
-
-Object
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
\ No newline at end of file
diff --git a/helpers/basic_helper.js b/helpers/basic_helper.js
deleted file mode 100644
index cfe7cc5..0000000
--- a/helpers/basic_helper.js
+++ /dev/null
@@ -1,213 +0,0 @@
-"use strict";
-
-/**
- * Perform basic validations
- *
- * @module helpers/basic_helper
- */
-
-const BigNumber = require('bignumber.js')
-;
-
-
-/**
- * Basic helper methods constructor
- *
- * @constructor
- *
- */
-const BasicHelperKlass = function() {};
-
-BasicHelperKlass.prototype = {
-
- /**
- * Check if address is valid or not
- *
- * @param {string} address - Address
- *
- * @return {boolean}
- */
- isAddressValid: function (address) {
- if (typeof address !== "string") {
- return false;
- }
- return /^0x[0-9a-fA-F]{40}$/.test(address);
- },
-
- /**
- * Check if uuid is valid or not
- *
- * @param {string} uuid - Branded Token UUID
- *
- * @return {boolean}
- */
- isUuidValid: function (uuid) {
- if (typeof uuid !== "string") {
- return false;
- }
- return /^0x[0-9a-fA-F]{64}$/.test(uuid);
- },
-
- /**
- * Check if transaction hash is valid or not
- *
- * @param {string} transactionHash - Transaction hash
- *
- * @return {boolean}
- */
- isTxHashValid: function (transactionHash) {
- if (typeof transactionHash !== "string") {
- return false;
- }
- return /^0x[0-9a-fA-F]{64}$/.test(transactionHash);
- },
-
- /**
- * Check if amount is valid wei number and not zero
- *
- * @param {number} amountInWei - amount in wei
- *
- * @return {boolean}
- */
- isNonZeroWeiValid: function (amountInWei) {
- const oneForMod = new BigNumber('1');
-
- // Convert amount in BigNumber
- var bigNumAmount = null;
- if (amountInWei instanceof BigNumber) {
- bigNumAmount = amountInWei;
- } else {
- var numAmount = Number(amountInWei);
- if (!isNaN(numAmount)) {
- bigNumAmount = new BigNumber(numAmount);
- }
- }
-
- return (!bigNumAmount || bigNumAmount.lessThan(1) || bigNumAmount.isNaN() ||
- !bigNumAmount.isFinite() || bigNumAmount.mod(oneForMod) != 0) ? false : true;
- },
-
- /**
- * get return type for transaction
- *
- * @param {string} returnType - return from geth transactions when following event is received
- *
- * @return {string}
- */
- getReturnType: function (returnType) {
- return ['uuid', 'txHash', 'txReceipt'].includes(returnType) ? returnType : 'txHash';
- },
-
- /**
- * check if return type is uuid or not
- *
- * @param {string} returnType - return type
- *
- * @return {boolean}
- */
- isReturnTypeUUID: function(returnType) {
- return returnType === 'uuid';
- },
-
- /**
- * check if return type is txHash or not
- *
- * @param {string} returnType - return type
- *
- * @return {boolean}
- */
- isReturnTypeTxHash: function(returnType) {
- return returnType === 'txHash';
- },
-
- /**
- * check if return type is txReceipt or not
- *
- * @param {string} returnType - return type
- *
- * @return {boolean}
- */
- isReturnTypeTxReceipt: function(returnType) {
- return returnType === 'txReceipt';
- },
-
- /**
- * Check if branded token name is valid or not
- *
- * @param {string} name - Branded token name
- *
- * @return {boolean}
- */
- isBTNameValid: function (name) {
- if (typeof name !== "string") {
- return false;
- }
- return (/^[a-z0-9\s]{1,}$/i).test(name);
- },
-
- /**
- * Check if branded token symbol is valid or not
- *
- * @param {string} symbol - Branded token symbol
- *
- * @return {boolean}
- */
- isBTSymbolValid: function (symbol) {
- if (typeof symbol !== "string") {
- return false;
- }
- return (/^[a-z0-9]{1,}$/i).test(symbol);
- },
-
- /**
- * Check if branded token conversion rate is valid or not
- *
- * @param {number} conversionRate - Branded token conversion rate
- *
- * @return {boolean}
- */
- isBTConversionRateValid: function (conversionRate) {
- if (isNaN(conversionRate) || (conversionRate % 1) != 0 || parseInt(conversionRate) < 1) {
- return false;
- }
- return true;
- },
-
- /**
- * Convert wei to proper string. Make sure it's a valid number
- *
- * @param {number} amountInWei - amount in wei to be formatted
- *
- * @return {string}
- */
- formatWeiToString: function (amountInWei) {
- const oThis = this;
- return oThis.convertToBigNumber(amountInWei).toString(10);
- },
-
- /**
- * Convert number to big number. Make sure it's a valid number
- *
- * @param {number} amountInWei - amount in wei to be formatted
- *
- * @return {BigNumber}
- */
- convertToBigNumber: function (number) {
- return (number instanceof BigNumber) ? number : new BigNumber(number);
- },
-
- /**
- * Check if chainId is valid
- *
- * @param {Number} chainId - chainId
- *
- * @return {Bool}
- */
- isValidChainId: function (chainId) {
- const chainIdBigNumberObject = new BigNumber(chainId);
- return chainIdBigNumberObject.isNaN() || !chainIdBigNumberObject.isInteger() ? false : true
- }
-
-};
-
-module.exports = new BasicHelperKlass();
\ No newline at end of file
diff --git a/helpers/custom_console_logger.js b/helpers/custom_console_logger.js
deleted file mode 100644
index ef4cb05..0000000
--- a/helpers/custom_console_logger.js
+++ /dev/null
@@ -1,16 +0,0 @@
-"use strict";
-
-/*
- * Custom Console log methods.
- *
- */
-const OSTBase = require('@openstfoundation/openst-base')
- , Logger = OSTBase.Logger
-;
-
-const rootPrefix = '..'
- , coreConstants = require(rootPrefix + '/config/core_constants')
- , loggerLevel = coreConstants.DEBUG_ENABLED == 1 ? Logger.LOG_LEVELS.TRACE : Logger.LOG_LEVELS.INFO
-;
-
-module.exports = new Logger("openst-payments", loggerLevel);
diff --git a/index.js b/index.js
deleted file mode 100644
index 5a28327..0000000
--- a/index.js
+++ /dev/null
@@ -1,20 +0,0 @@
-"use strict";
-
-/**
- * Index File of "@openstfoundation/openst-payments" node module
- */
-
-const rootPrefix = "."
- , version = require(rootPrefix + '/package.json').version
- , serviceManifest = require(rootPrefix + '/services/manifest')
-;
-
-const OSTPayment = function () {
- const oThis = this;
-
- oThis.version = version;
-
- oThis.services = serviceManifest;
-};
-
-module.exports = new OSTPayment();
\ No newline at end of file
diff --git a/lib/airdrop_management/adjust_airdrop_amount.js b/lib/airdrop_management/adjust_airdrop_amount.js
deleted file mode 100644
index bf467c8..0000000
--- a/lib/airdrop_management/adjust_airdrop_amount.js
+++ /dev/null
@@ -1,306 +0,0 @@
-"use strict";
-
-/**
- *
- * This class would be used for calculating user airdrop balance.
- *
- * @module lib/airdrop_management/adjust_airdrop_amount
- *
- */
-
-const rootPrefix = '../..'
- , responseHelper = require(rootPrefix + '/lib/formatter/response')
- , AirdropModelCacheKlass = require(rootPrefix + '/lib/cache_management/airdrop_model')
- , logger = require(rootPrefix + '/helpers/custom_console_logger')
- , userAirdropDetailKlass = require(rootPrefix + '/app/models/user_airdrop_detail')
- , BigNumber = require('bignumber.js')
- , paramErrorConfig = require(rootPrefix + '/config/param_error_config')
- , apiErrorConfig = require(rootPrefix + '/config/api_error_config')
-;
-
-const errorConfig = {
- param_error_config: paramErrorConfig,
- api_error_config: apiErrorConfig
-};
-
-/**
- * Constructor to create object of userBalance
- *
- * @constructor
- *
- * @param {Hex} airdropContractAddress - airdrop contract address
- * @param {Array} userAddress - Array of user addressed
- * @param {BigNumber} airdropAmountUsed - used airdrop amount
- *
- * @return {Object}
- *
- */
-const AdjustAirdropAmountKlass = function(params) {
- logger.debug("=======AdjustAirdropAmountKlass.params=======");
- logger.debug(params);
- const oThis = this;
- oThis.airdropContractAddress = params.airdropContractAddress;
- oThis.userAddress = params.userAddress;
- oThis.airdropAmountUsed = params.airdropAmountUsed;
-};
-
-AdjustAirdropAmountKlass.prototype = {
-
- /**
- * Debit airdrop used amount
- *
- * @return {Promise}
- *
- */
- debitAirdropUsedAmount: function () {
- const oThis = this;
- return new Promise(async function (onResolve, onReject) {
- var amountAdjustedLog = {};
- try {
- const airdropModelCacheObject = new AirdropModelCacheKlass({useObject: true, contractAddress: oThis.airdropContractAddress})
- , airdropModelCacheResponse = await airdropModelCacheObject.fetch()
- , airdropRecord = airdropModelCacheResponse.data[oThis.airdropContractAddress]
- ;
- var totalRemainingAmountToAdjust = new BigNumber(oThis.airdropAmountUsed);
- // Zero airdrop amount is possible
- if (totalRemainingAmountToAdjust.equals(0)) {
- return onResolve(responseHelper.successWithData({}));
- }
- if (totalRemainingAmountToAdjust.lt(0)) {
-
- let errorParams = {
- internal_error_identifier: 'l_am_aaa_daua_1',
- api_error_identifier: 'amount_invalid',
- error_config: errorConfig,
- params_error_identifiers: ['negative_airdrop_amount'],
- debug_options: {}
- };
-
- return onResolve(responseHelper.paramValidationError(errorParams));
- }
- if (!oThis.userAddress) {
-
- let errorParams = {
- internal_error_identifier: 'l_am_aaa_daua_2',
- api_error_identifier: 'invalid_api_params',
- error_config: errorConfig,
- params_error_identifiers: ['invalid_user_address'],
- debug_options: {}
- };
- return onResolve(responseHelper.paramValidationError(errorParams));
- }
- var userAirdropDetailModel = new userAirdropDetailKlass();
- const userAirdropDetailResults = await userAirdropDetailModel.select("id, airdrop_id, user_address, CONVERT(airdrop_amount, char) as airdrop_amount, CONVERT(airdrop_used_amount, char) as airdrop_used_amount").
- where({airdrop_id: airdropRecord.id, user_address: oThis.userAddress}).
- where(["airdrop_amount > airdrop_used_amount"]).fire();
- logger.debug("\n======debitAirdropUsedAmount.userAirdropDetailResults=========", userAirdropDetailResults);
- // Return error if no record found. Means airdrop_used_amount is not updated correctly in previous adjustments
- if (!userAirdropDetailResults[0]) {
- let errorParams = {
- internal_error_identifier: 'l_am_aaa_daua_3',
- api_error_identifier: 'record_not_found',
- error_config: errorConfig,
- debug_options: {}
- };
- return onResolve(responseHelper.error(errorParams));
- }
- for (var uadIndex in userAirdropDetailResults) {
- const uad = userAirdropDetailResults[uadIndex];
- const dbAirdropUsedAmount = new BigNumber(uad.airdrop_used_amount);
- const dbAmountForAdjusting = new BigNumber(uad.airdrop_amount).minus(dbAirdropUsedAmount);
- const amountToAdjustWithCurrentRecord = BigNumber.min(totalRemainingAmountToAdjust, dbAmountForAdjusting);
- if (amountToAdjustWithCurrentRecord.lte(0)) {
- return onResolve(responseHelper.successWithData({amountAdjustedLog: amountAdjustedLog}));
- }
- userAirdropDetailModel = new userAirdropDetailKlass();
- const updateResult = await userAirdropDetailModel.update(["airdrop_used_amount=airdrop_used_amount+?", amountToAdjustWithCurrentRecord.toString(10)]).
- where(["id = ? AND ((airdrop_used_amount+?) <= airdrop_amount)", uad.id, amountToAdjustWithCurrentRecord.toString(10)]).fire();
- logger.debug("\ndebitAirdropUsedAmount.updateResult: ", updateResult);
- if (updateResult.affectedRows < 1) {
- continue; // Don't subtract totalRemainingAmountToAdjust if update is failed
- } else{
- amountAdjustedLog[uad.id] = amountToAdjustWithCurrentRecord.toString(10);
- totalRemainingAmountToAdjust = totalRemainingAmountToAdjust.minus(amountToAdjustWithCurrentRecord);
- logger.debug("\n=====debitAirdropUsedAmount.updateSuccess=======", "\ntotalRemainingAmountToAdjust: ",totalRemainingAmountToAdjust.toString(10));
- }
- }
- } catch (err) {
- logger.error("debitAirdropUsedAmount error: ", err);
- // Rollback all adjusted amount
- if (Object.keys(amountAdjustedLog).length > 0){
- await oThis.rollbackDebitAirdropAdjustedAmount(amountAdjustedLog);
- }
-
- let errorParams = {
- internal_error_identifier: 'l_am_aaa_daua_4',
- api_error_identifier: 'amount_update_failed',
- error_config: errorConfig,
- debug_options: { amountAdjustedLog: amountAdjustedLog, err: err }
- };
- return onResolve(responseHelper.error(errorParams));
- }
- // In case totalRemainingAmountToAdjust > 0 means no record available for adjusting or parallel requests issue
- if (totalRemainingAmountToAdjust.gt(0)) {
- // Rollback all adjusted amount
- if (Object.keys(amountAdjustedLog).length > 0){
- await oThis.rollbackDebitAirdropAdjustedAmount(amountAdjustedLog);
- }
- let errorParams = {
- internal_error_identifier: 'l_am_aaa_daua_5',
- api_error_identifier: 'airdrop_adjust_failed',
- error_config: errorConfig,
- debug_options: { amountAdjustedLog: amountAdjustedLog }
- };
- return onResolve(responseHelper.error(errorParams));
- }
- return onResolve(responseHelper.successWithData({amountAdjustedLog: amountAdjustedLog}));
- });
-
- },
-
- /**
- * Rollback debit airdrop used amount
- *
- * @return {}
- *
- */
- rollbackDebitAirdropAdjustedAmount: async function(amountAdjustedLog){
- for (var uadId in amountAdjustedLog) {
- const rollbackAmount = amountAdjustedLog[uadId];
- const userAirdropDetailModel = new userAirdropDetailKlass();
- await userAirdropDetailModel.update(["airdrop_used_amount=airdrop_used_amount-?", rollbackAmount]).
- where(["id = ?", uadId]).fire();
- }
- },
-
- /**
- * Credit airdrop used amount. decreases airdrop_used_amount of user_airdrop_details table
- *
- * @return {Promise}
- *
- */
- creditAirdropUsedAmount: function () {
- const oThis = this;
- return new Promise(async function (onResolve, onReject) {
- var amountAdjustedLog = {};
- try {
- const airdropModelCacheObject = new AirdropModelCacheKlass({useObject: true, contractAddress: oThis.airdropContractAddress})
- , airdropModelCacheResponse = await airdropModelCacheObject.fetch()
- , airdropRecord = airdropModelCacheResponse.data[oThis.airdropContractAddress]
- ;
- var totalRemainingAmountToAdjust = new BigNumber(oThis.airdropAmountUsed);
- // Zero airdrop amount is possible
- if (totalRemainingAmountToAdjust.equals(0)) {
- return onResolve(responseHelper.successWithData({}));
- }
- if (totalRemainingAmountToAdjust.lt(0)) {
- let errorParams = {
- internal_error_identifier: 'l_am_aaa_caua_1',
- api_error_identifier: 'invalid_api_params',
- error_config: errorConfig,
- params_error_identifiers: ['negative_airdrop_amount'],
- debug_options: {}
- };
-
- return onResolve(responseHelper.paramValidationError(errorParams));
- }
- if (!oThis.userAddress) {
-
- let errorParams = {
- internal_error_identifier: 'l_am_aaa_caua_2',
- api_error_identifier: 'invalid_user_address',
- error_config: errorConfig,
- debug_options: {}
- };
- return onResolve(responseHelper.error(errorParams));
- }
- var userAirdropDetailModel = new userAirdropDetailKlass();
- const userAirdropDetailResults = await userAirdropDetailModel.select("id, airdrop_id, user_address, CONVERT(airdrop_amount, char) as airdrop_amount, CONVERT(airdrop_used_amount, char) as airdrop_used_amount").
- where({airdrop_id: airdropRecord.id, user_address: oThis.userAddress}).
- where(["airdrop_used_amount > 0 AND airdrop_amount >= airdrop_used_amount"]).fire();
- logger.debug("======creditAirdropUsedAmount.userAirdropDetailResults=========");
- logger.debug(userAirdropDetailResults);
- // Return error if no record found to adjust
- if (!userAirdropDetailResults[0]) {
- let errorParams = {
- internal_error_identifier: 'l_am_aaa_caua_3',
- api_error_identifier: 'record_not_found',
- error_config: errorConfig,
- debug_options: {}
- };
- return onResolve(responseHelper.error(errorParams));
- }
- for (var uadIndex in userAirdropDetailResults) {
- const uad = userAirdropDetailResults[uadIndex];
- const dbAmount = new BigNumber(uad.airdrop_used_amount);
- const toAdjustAmount = BigNumber.min(dbAmount, totalRemainingAmountToAdjust);
- // Saves Query
- if (toAdjustAmount.lte(0)) {
- return onResolve(responseHelper.successWithData({amountAdjustedLog: amountAdjustedLog}));
- }
- userAirdropDetailModel = new userAirdropDetailKlass();
- const updateResult = await userAirdropDetailModel.update(["airdrop_used_amount=airdrop_used_amount-?",toAdjustAmount.toString(10)]).
- where(["id = ? AND (airdrop_amount >= airdrop_used_amount) AND (airdrop_used_amount-?)>=0", uad.id, toAdjustAmount.toString(10)]).fire();
- logger.debug("\ndebitAirdropUsedAmount.updateResult: ", updateResult);
- if (updateResult.affectedRows < 1) {
- continue; // Don't subtract totalRemainingAmountToAdjust if update is failed
- } else {
- totalRemainingAmountToAdjust = totalRemainingAmountToAdjust.minus(toAdjustAmount);
- amountAdjustedLog[uad.id] = toAdjustAmount.toString(10);
- logger.debug("\n=====creditAirdropUsedAmount.updateSuccess=======", "\ntotalRemainingAmountToAdjust: ",totalRemainingAmountToAdjust.toString(10));
- }
- }
- } catch (err) {
- logger.error("creditAirdropUsedAmount error: ", err);
- // Rollback all adjusted amount
- if (Object.keys(amountAdjustedLog).length > 0){
- await oThis.rollbackCreditAirdropAdjustedAmount(amountAdjustedLog);
- }
-
- let errorParams = {
- internal_error_identifier: 'l_am_aaa_caua_4',
- api_error_identifier: 'amount_update_failed',
- error_config: errorConfig,
- debug_options: { amountAdjustedLog: amountAdjustedLog, err: err }
- };
- return onResolve(responseHelper.error(errorParams));
- }
- // In case totalRemainingAmountToAdjust > 0 means no record available for adjusting or parallel requests issue
- if (totalRemainingAmountToAdjust.gt(0)) {
- // Rollback all adjusted amount
- if (Object.keys(amountAdjustedLog).length > 0){
- await oThis.rollbackCreditAirdropAdjustedAmount(amountAdjustedLog);
- }
- logger.error('%Error - Airdrop used Amount not adjusted. This could be because of same user payment requests in parallel');
- let errorParams = {
- internal_error_identifier: 'l_am_aaa_caua_5',
- api_error_identifier: 'amount_update_failed',
- error_config: errorConfig,
- debug_options: { amountAdjustedLog: amountAdjustedLog }
- };
- return onResolve(responseHelper.error(errorParams));
- }
- return onResolve(responseHelper.successWithData({amountAdjustedLog: amountAdjustedLog}));
- });
-
- },
-
- /**
- * Rollback credit airdrop used amount
- *
- * @return {}
- *
- */
- rollbackCreditAirdropAdjustedAmount: async function(amountAdjustedLog){
- for (var uadId in amountAdjustedLog) {
- const rollbackAmount = amountAdjustedLog[uadId];
- const userAirdropDetailModel = new userAirdropDetailKlass();
- await userAirdropDetailModel.update(["airdrop_used_amount=airdrop_used_amount+?", rollbackAmount]).
- where(["id = ?", uadId]).fire();
- }
- },
-
-};
-
-module.exports = AdjustAirdropAmountKlass;
-
diff --git a/lib/auto_scaling_service.js b/lib/auto_scaling_service.js
deleted file mode 100644
index 5fe730a..0000000
--- a/lib/auto_scaling_service.js
+++ /dev/null
@@ -1,21 +0,0 @@
-"use strict";
-
-/*
- * Autoscaling Service Object
- */
-
-const rootPrefix = '..'
- , coreConstants = require(rootPrefix + '/config/core_constants')
-;
-
-var autoscalingServiceObj = null;
-
-if (coreConstants.RUNNING_TESTS_IN != 'travis' ) {
- const OSTStorage = require('@openstfoundation/openst-storage')
- , autoScalingConfig = require(rootPrefix + '/config/autoscaling')
- ;
-
- autoscalingServiceObj = new OSTStorage.AutoScaling(autoScalingConfig);
-}
-
-module.exports = autoscalingServiceObj;
\ No newline at end of file
diff --git a/lib/cache_management/airdrop.js b/lib/cache_management/airdrop.js
deleted file mode 100644
index 09db132..0000000
--- a/lib/cache_management/airdrop.js
+++ /dev/null
@@ -1,81 +0,0 @@
-//"use strict";
-
-/**
- *
- * This is cache layer for airdrop balance related caching
- *
- * @module lib/cache_management/airdrop_cache
- *
- */
-const rootPrefix = '../..'
- , PricerCacheKlass = require(rootPrefix + '/lib/cache_management/pricer')
-;
-
-const AIR_DROP_BUDGET_HOLDER = "airdrop_budget_holder"
-;
-
-/**
- * constructor
- *
- * @param {string} chainId - Chain id
- * @param {string} airdropAddress - address of airdrop contract
- *
- * @augments PricerCacheKlass
- *
- * @constructor
- */
-const AirdropBalanceCache = function(chainId, airdropAddress) {
- const oThis = this
- ;
-
- PricerCacheKlass.call(oThis, chainId, airdropAddress);
-};
-
-AirdropBalanceCache.prototype = Object.create(PricerCacheKlass.prototype);
-
-const AirdropBalanceCacheSpecificPrototype = {
- /**
- * Get airdrop budger holder address
- *
- * @return {promise
}
- */
- getAirdropBudgetHolder: function () {
- const oThis = this
- , cacheKey = oThis.getCacheKey(AIR_DROP_BUDGET_HOLDER)
- ;
-
- return oThis.getCacheValue(cacheKey);
- },
-
- /**
- * Set airdrop bugdet holder address
- *
- * @param {string} address - airdrop budget holder address
- *
- * @return {promise}
- */
- setAirdropBudgetHolder: function (address) {
- const oThis = this
- , cacheKey = oThis.getCacheKey(AIR_DROP_BUDGET_HOLDER)
- ;
-
- return oThis.setCacheValue(cacheKey, address);
- },
-
- /**
- * Clear airdrop budget holder address
- *
- * @return {promise}
- */
- clearPriceOracles: function () {
- const oThis = this
- , cacheKey = oThis.getCacheKey(AIR_DROP_BUDGET_HOLDER)
- ;
-
- return oThis.clearCache(cacheKey);
- }
-};
-
-Object.assign(AirdropBalanceCache.prototype, AirdropBalanceCacheSpecificPrototype);
-
-module.exports = AirdropBalanceCache;
\ No newline at end of file
diff --git a/lib/cache_management/airdrop_model.js b/lib/cache_management/airdrop_model.js
deleted file mode 100644
index fc6514b..0000000
--- a/lib/cache_management/airdrop_model.js
+++ /dev/null
@@ -1,93 +0,0 @@
-"use strict";
-
-const rootPrefix = '../..'
- , baseCache = require(rootPrefix + '/lib/cache_management/base')
- , AirdropModelKlass = require(rootPrefix + '/app/models/airdrop')
- , responseHelper = require(rootPrefix + '/lib/formatter/response')
-;
-
-/**
- * constructor
- *
- * @param {object} cache get/set related arguments
- * @constructor
- *
- */
-const AirdropModelCacheKlass = function(params) {
-
- const oThis = this;
-
- oThis.contractAddress = params.contractAddress;
- baseCache.call(oThis, params);
-
-};
-
-AirdropModelCacheKlass.prototype = Object.create(baseCache.prototype);
-
-const AirdropModelCacheKlassPrototype = {
-
- /**
- * set cache key
- *
- * @return {String}
- */
- setCacheKey: function() {
-
- const oThis = this;
-
- oThis.cacheKey = oThis._cacheKeyPrefix() + "airdrop_"+oThis.contractAddress.toLowerCase();
-
- return oThis.cacheKey;
-
- },
-
- /**
- * set cache expiry in oThis.cacheExpiry and return it
- *
- * @return {Number}
- */
- setCacheExpiry: function() {
-
- const oThis = this;
-
- oThis.cacheExpiry = 86400; // 24 hours ;
-
- return oThis.cacheExpiry;
-
- },
-
- /**
- * Fetch data from source
- *
- * @return {Result}
- */
- fetchDataFromSource: function() {
-
- const oThis = this;
-
- return new Promise(async function(onResolve, onReject){
-
- const airdropModelObject = new AirdropModelKlass()
- , airdropResponse = await airdropModelObject.getByContractAddress(oThis.contractAddress)
- , airdropRecord = airdropResponse[0]
- ;
-
- // Return null if airdrop record not found
- if (!airdropRecord){
- return onResolve(responseHelper.successWithData({id: 0}));
- }
-
- var formattedAirdropDetails = {};
- formattedAirdropDetails[airdropRecord.contract_address] = {id: airdropRecord.id};
-
- return onResolve(responseHelper.successWithData(formattedAirdropDetails));
-
- });
-
- }
-
-};
-
-Object.assign(AirdropModelCacheKlass.prototype, AirdropModelCacheKlassPrototype);
-
-module.exports = AirdropModelCacheKlass;
\ No newline at end of file
diff --git a/lib/cache_management/base.js b/lib/cache_management/base.js
deleted file mode 100644
index ee8e5e5..0000000
--- a/lib/cache_management/base.js
+++ /dev/null
@@ -1,202 +0,0 @@
-"use strict";
-
-const rootPrefix = '../..'
- , openStCache = require('@openstfoundation/openst-cache')
- , coreConstants = require(rootPrefix + '/config/core_constants')
- , responseHelper = require(rootPrefix + '/lib/formatter/response')
- , logger = require(rootPrefix+'/helpers/custom_console_logger')
- , cacheImplementer = new openStCache.cache(coreConstants.CACHING_ENGINE, true);
-;
-
-/**
- * constructor
- *
- * @param {Object} params - cache key generation & expiry related params
- *
- * @constructor
- */
-const baseCacheManagementKlass = function(params) {
-
- const oThis = this;
-
- if(!params){
- params = {};
- }
-
- oThis.params = params;
-
- oThis.useObject = params.useObject === true;
-
- oThis.cacheKey = null;
-
- oThis.cacheExpiry = null;
-
- // Set cacheImplementer to perform caching operations
- oThis.cacheImplementer = cacheImplementer;
- // call sub class method to set cache key using params provided
- oThis.setCacheKey();
-
- // call sub class method to set cache expiry using params provided
- oThis.setCacheExpiry();
-
-};
-
-baseCacheManagementKlass.prototype = {
-
- /**
- * Fetch data from cache, in case of cache miss calls sub class method to fetch data from source
- *
- * @return {Promise} - On success, data.value has value. On failure, error details returned.
- */
- fetch: async function () {
-
- const oThis = this;
-
- var data = await oThis._fetchFromCache()
- , fetchDataRsp = null;
-
- // if cache miss call sub class method to fetch data from source and set cache
- if (!data) {
-
- fetchDataRsp = await oThis.fetchDataFromSource();
-
- // if fetch from source failed do not set cache and return error response
- if (fetchDataRsp.isFailure()) {
- logger.error('l_cm_b_fetch_1', 'Something Went Wrong', fetchDataRsp);
- return fetchDataRsp;
- } else {
- data = fetchDataRsp.data;
- // DO NOT WAIT for cache being set
- oThis._setCache(data);
- }
-
- }
-
- return Promise.resolve(responseHelper.successWithData(data));
-
- },
-
- /**
- * clear cache
- *
- * @return {Promise}
- */
- clear: function () {
-
- const oThis = this;
-
- return oThis.cacheImplementer.del(oThis.cacheKey);
-
- },
-
- // methods which sub class would have to implement
-
- /**
- * set cache key in oThis.cacheKey and return it
- *
- * @return {String}
- */
- setCacheKey: function() {
- throw 'sub class to implement';
- },
-
- /**
- * set cache expiry in oThis.cacheExpiry and return it
- *
- * @return {Number}
- */
- setCacheExpiry: function() {
- throw 'sub class to implement';
- },
-
- /**
- * fetch data from source
- * return should be of klass Result
- * data attr of return is returned and set in cache
- *
- * @return {Result}
- */
- fetchDataFromSource: async function() {
- throw 'sub class to implement';
- },
-
- // private methods from here
-
- /**
- * fetch from cache
- *
- * @return {Object}
- */
- _fetchFromCache: async function () {
-
- const oThis = this;
- var cacheFetchResponse = null
- , cacheData = null
- ;
-
- if(oThis.useObject) {
- cacheFetchResponse = await oThis.cacheImplementer.getObject(oThis.cacheKey);
- } else {
- cacheFetchResponse = await oThis.cacheImplementer.get(oThis.cacheKey);
- }
-
- if (cacheFetchResponse.isSuccess()) {
- cacheData = cacheFetchResponse.data.response;
- }
-
- return cacheData;
-
- },
-
- /**
- * set data in cache.
- *
- * @param {Object} dataToSet - data to se tin cache
- *
- * @return {Result}
- */
- _setCache: function (dataToSet) {
-
- const oThis = this;
-
- var setCacheFunction = function() {
- if(oThis.useObject) {
- return oThis.cacheImplementer.setObject(oThis.cacheKey, dataToSet, oThis.cacheExpiry);
- } else {
- return oThis.cacheImplementer.set(oThis.cacheKey, dataToSet, oThis.cacheExpiry);
- }
-
- };
-
- setCacheFunction().then(function(cacheSetResponse){
-
- if (cacheSetResponse.isFailure()) {
- logger.notify('l_cm_b_setCache_1', 'Something Went Wrong', cacheSetResponse);
- }
- });
-
- },
-
- /**
- * cache key prefix
- *
- * @return {String}
- */
- _cacheKeyPrefix: function () {
- return 'ost_payment_';
- },
-
- /**
- * Shared cache key prefix
- * This cache is shared between company api and saas
- * Cache keys with these prefixes can be flushed via company api or saas.
- *
- * @return {String}
- */
- _sharedCacheKeyPrefix: function () {
- return 'ost_payment__shared_';
- }
-
-}
-
-module.exports = baseCacheManagementKlass;
diff --git a/lib/cache_management/pricer.js b/lib/cache_management/pricer.js
deleted file mode 100644
index 9285e76..0000000
--- a/lib/cache_management/pricer.js
+++ /dev/null
@@ -1,401 +0,0 @@
-//"use strict";
-
-/**
- *
- * This is cache layer for pricer balance related caching
- *
- * @module lib/cache_management/pricer_cache
- *
- */
-const openStCache = require('@openstfoundation/openst-cache');
-
-const rootPrefix = '../..'
- , coreConstants = require(rootPrefix + '/config/core_constants')
- , cacheImplementer = new openStCache.cache(coreConstants.CACHING_ENGINE, true)
- , openSTCacheKeys = openStCache.OpenSTCacheKeys
-;
-
-/**
- * constructor
- *
- * @param {string} chainId - Chain id
- * @param {string} contractAddress - address of pricer/airdrop contract
- *
- * @constructor
- */
-const PricerCache = module.exports= function(chainId, contractAddress) {
- const oThis = this;
- oThis.chainId = chainId;
- oThis.contractAddress = contractAddress;
-};
-
-const CONVERSION_RATE_KEY = PricerCache.CONVERSION_RATE_KEY = "conversion_rate"
- , CONVERSION_RATE_DECIMALS_KEY = PricerCache.CONVERSION_RATE_DECIMALS_KEY = "conversion_rate_decimals"
- , DECIMALS_KEY = PricerCache.DECIMALS_KEY = "decimals"
- , BRANDED_TOKEN_ADDRESS = PricerCache.BRANDED_TOKEN_ADDRESS = "branded_token_address"
- , ACCEPTED_MARGINS = PricerCache.ACCEPTED_MARGINS = "accepted_margins"
- , PRICE_ORACLE_ADDRESS = PricerCache.PRICE_ORACLE_ADDRESS = "price_oracle_address"
- ;
-
-PricerCache.prototype = {
-
- chainId: null,
- contractAddress: null,
-
- /**
- * Get conversion rate for pricer
- *
- * @param {string} owner - address of user whose balance is to be found
- *
- * @return {promise}
- *
- */
- getCacheKey: function(key) {
- const oThis = this;
- return `${oThis.chainId}_${oThis.contractAddress.toLowerCase()}_${key}`;
- },
-
- /**
- * Get cached value
- *
- * @param {string} key - key
- *
- * @return {promise}
- *
- */
- getCacheValue: function(cacheKey) {
- const oThis = this;
- return cacheImplementer.get(cacheKey);
- },
-
- /**
- * Set value in cache
- *
- * @param {string} key - key
- * @param {string} value - value
- *
- * @return {promise}
- *
- */
- setCacheValue: function (cacheKey, cacheValue) {
-
- const oThis = this;
- return cacheImplementer.set(cacheKey, cacheValue);
- },
-
- /**
- * Clear cache for given key
- *
- * @param {string} key - cache key
- *
- * @return {promise}
- *
- */
- clearCache: function (key) {
- return cacheImplementer.del(key);
- },
-
- /**
- * Get conversion rate for pricer
- *
- * @return {promise}
- *
- */
- getConversionRate: function () {
-
- const oThis = this;
- const cacheKey = oThis.getCacheKey(CONVERSION_RATE_KEY);
- return oThis.getCacheValue(cacheKey);
- },
-
- /**
- * Set conversion rate to cache
- *
- * @param {BigNumber} conversionRate - conversion rate of pricer/airdrop
- *
- * @return {promise}
- *
- */
- setConversionRate: function (conversionRate) {
-
- const oThis = this;
- const cacheKey = oThis.getCacheKey(CONVERSION_RATE_KEY);
- return oThis.setCacheValue(cacheKey, conversionRate.toString(10));
- },
-
-
- /**
- * Clear conversion rate from cache
- *
- * @return {promise}
- *
- */
- clearConversionRate: function () {
-
- const oThis = this;
- const cacheKey = oThis.getCacheKey(CONVERSION_RATE_KEY);
- return oThis.clearCache(cacheKey);
- },
-
- /**
- * Get conversion rate decimals for pricer
- *
- * @return {promise}
- *
- */
- getConversionRateDecimals: function () {
-
- const oThis = this;
- const cacheKey = oThis.getCacheKey(CONVERSION_RATE_DECIMALS_KEY);
- return oThis.getCacheValue(cacheKey);
- },
-
- /**
- * Set conversion rate decimals to cache
- *
- * @param {BigNumber} conversionRateDecimals - conversion rate of pricer/airdrop
- *
- * @return {promise}
- *
- */
- setConversionRateDecimals: function (conversionRateDecimals) {
-
- const oThis = this;
- const cacheKey = oThis.getCacheKey(CONVERSION_RATE_DECIMALS_KEY);
- return oThis.setCacheValue(cacheKey, conversionRateDecimals.toString(10));
- },
-
- /**
- * Clear conversion rate decimals from cache
- *
- * @return {promise}
- *
- */
- clearConversionRateDecimals: function () {
-
- const oThis = this;
- const cacheKey = oThis.getCacheKey(CONVERSION_RATE_DECIMALS_KEY);
- return oThis.clearCache(cacheKey);
- },
-
- /**
- * Get decimals for pricer
- *
- * @return {promise}
- *
- */
- getDecimals: function () {
-
- const oThis = this;
- const cacheKey = oThis.getCacheKey(DECIMALS_KEY);
- return oThis.getCacheValue(cacheKey);
- },
-
- /**
- * Set decimals to cache
- *
- * @param {BigNumber} conversionRateDecimals - conversion rate of pricer/airdrop
- *
- * @return {promise}
- *
- */
- setDecimals: function (decimals) {
-
- const oThis = this;
- const cacheKey = oThis.getCacheKey(DECIMALS_KEY);
- return oThis.setCacheValue(cacheKey, decimals.toString(10));
- },
-
- /**
- * clear decimals from cache
- *
- * @return {promise}
- *
- */
- clearDecimals: function () {
-
- const oThis = this;
- const cacheKey = oThis.getCacheKey(DECIMALS_KEY);
- return oThis.clearCache(cacheKey);
- },
-
-
- /**
- * Get branded token address for pricer
- *
- * @return {promise}
- *
- */
- getBrandedTokenAddress: function () {
-
- const oThis = this;
- const cacheKey = oThis.getCacheKey(BRANDED_TOKEN_ADDRESS);
- return oThis.getCacheValue(cacheKey);
- },
-
- /**
- * Set branded token address for pricer
- *
- * @param {string} brandedTokenAddress - branded token address
- *
- * @return {promise}
- *
- */
- setBrandedTokenAddress: function (brandedTokenAddress) {
-
- const oThis = this;
- const cacheKey = oThis.getCacheKey(BRANDED_TOKEN_ADDRESS);
- return oThis.setCacheValue(cacheKey, brandedTokenAddress);
- },
-
- /**
- * clear branded token address cache
- *
- * @param {string} brandedTokenAddress - branded token address
- *
- * @return {promise}
- *
- */
- clearBrandedTokenAddress: function (brandedTokenAddress) {
-
- const oThis = this;
- const cacheKey = oThis.getCacheKey(BRANDED_TOKEN_ADDRESS);
- return oThis.clearCache(cacheKey);
- },
-
- /**
- * Get accepted margin
- *
- * @param {string} currency - currency
- * @return {promise}
- *
- */
- getAcceptedMargins: function (currency) {
-
- const oThis = this;
- const cacheKey = oThis.getCacheKey(`${currency}_${ACCEPTED_MARGINS}`);
- return oThis.getCacheValue(cacheKey);
- },
-
- /**
- * Set accepted margin
- *
- * @param {string} currency - currency
- * @param {BigNumber} margin - accepted margin value
- *
- * @return {promise}
- *
- */
- setAcceptedMargins: function (currency, margin) {
-
- const oThis = this;
- const cacheKey = oThis.getCacheKey(`${currency}_${ACCEPTED_MARGINS}`);
- return oThis.setCacheValue(cacheKey, margin.toString(10));
- },
-
- /**
- * reset accepted margin cache
- *
- * @param {string} currency - currency
- *
- * @return {promise}
- *
- */
- clearAcceptedMargins: function (currency) {
- const oThis = this;
- const cacheKey = oThis.getCacheKey(`${currency}_${ACCEPTED_MARGINS}`);
- return oThis.clearCache(cacheKey);
- },
-
-
- /**
- * Get price point of price oracle from cache
- *
- * @param {string} address - price oracle address
- * @return {promise}
- *
- */
- getPricePoint: function (address) {
-
- const oThis = this;
- const cacheKey = openSTCacheKeys.oraclePricePoint(oThis.chainId, address);
- return oThis.getCacheValue(cacheKey);
- },
-
- /**
- * Set price point of price oracle from cache
- *
- * @param {string} pricePoint - price oracle price point
- * @param {string} address - price oracle address
- * @return {promise}
- *
- */
- setPricePoint: function (address, pricePoint) {
-
- const oThis = this;
- const cacheKey = openSTCacheKeys.oraclePricePoint(oThis.chainId, address);
- return oThis.setCacheValue(cacheKey, pricePoint);
- },
-
- /**
- * Clear price point of price oracle from cache
- *
- * @param {string} address - price oracle address
- * @return {promise}
- *
- */
- clearPricePoint: function (address) {
-
- const oThis = this;
- const cacheKey = openSTCacheKeys.oraclePricePoint(oThis.chainId, address);
- return oThis.clearCache(cacheKey);
- },
-
-
- /**
- * Get price oracle address for given currency from cache
- *
- * @param {string} currency - currency
- * @return {promise}
- *
- */
- getPriceOracles: function (currency) {
-
- const oThis = this;
- const cacheKey = oThis.getCacheKey(`${currency}_${PRICE_ORACLE_ADDRESS}`);
- return oThis.getCacheValue(cacheKey);
- },
-
-
- /**
- * Set price oracle address for given currency in cache
- *
- * @param {string} currency - currency
- * @param {string} address - price oracle address
- * @return {promise}
- *
- */
- setPriceOracles: function (currency, address) {
-
- const oThis = this;
- const cacheKey = oThis.getCacheKey(`${currency}_${PRICE_ORACLE_ADDRESS}`);
- return oThis.setCacheValue(cacheKey, address);
- },
-
-
- /**
- * Clear price oracle address for given currency in cache
- *
- * @param {string} currency - currency
- * @param {string} address - price oracle address
- * @return {promise}
- *
- */
- clearPriceOracles: function (currency) {
-
- const oThis = this;
- const cacheKey = oThis.getCacheKey(`${currency}_${PRICE_ORACLE_ADDRESS}`);
- return oThis.clearCache(cacheKey);
- }
-
-};
diff --git a/lib/cache_multi_management/base.js b/lib/cache_multi_management/base.js
deleted file mode 100644
index 079665c..0000000
--- a/lib/cache_multi_management/base.js
+++ /dev/null
@@ -1,189 +0,0 @@
-"use strict";
-
-const rootPrefix = '../..'
- , coreConstants = require(rootPrefix + '/config/core_constants')
- , openStCache = require('@openstfoundation/openst-cache')
- , cacheImplementer = new openStCache.cache(coreConstants.CACHING_ENGINE, true)
- , responseHelper = require(rootPrefix + '/lib/formatter/response')
- , logger = require(rootPrefix+'/helpers/custom_console_logger')
- , utils = require(rootPrefix + '/lib/utils')
-;
-
-/**
- * constructor
- *
- * @param {Object} params - cache key generation & expiry related params
- *
- * @constructor
- */
-const baseCacheMultiManagementKlass = function(params) {
-
- const oThis = this;
-
- if (!params) {
- params = {};
- }
-
- oThis.params = params;
-
- oThis.cacheKeys = {};
-
- // call sub class method to set cache keys using params provided
- oThis.setCacheKeys();
-
-};
-
-baseCacheMultiManagementKlass.prototype = {
-
- /**
- * Fetch data from cache, in case of cache miss calls sub class method to fetch data from source
- *
- * @return {Promise} - On success, data.value has value. On failure, error details returned.
- */
- fetch: async function () {
-
- const oThis = this;
-
- var data = await oThis._fetchFromCache()
- , fetchDataRsp = null;
-
- // if there are any cache misses then fetch that data from source.
- if (data['cacheMiss'].length > 0) {
-
- fetchDataRsp = await oThis.fetchDataFromSource(data['cacheMiss']);
-
- // if fetch from source failed do not set cache and return error response
- if (fetchDataRsp.isFailure()) {
- logger.notify('l_cm_b_1', 'Something Went Wrong', fetchDataRsp);
- return Promise.resolve(fetchDataRsp);
- } else {
- // DO NOT WAIT for cache being set
- var cacheKeys = Object.keys(fetchDataRsp.data);
- for (var i=0; i}
- */
- clear: function () {
-
- const oThis = this;
-
- for (var i=0; iError while getting from cache: ", cacheFetchResponse);
- for (var i = 0; i < cacheKeys.length; i++) {
- var cacheKey = cacheKeys[i];
- cacheMiss.push(oThis.cacheKeys[cacheKey]);
- }
- }
-
- return {cacheMiss: cacheMiss, cachedData: cachedResponse};
- },
-
- /**
- * set data in cache.
- *
- * @param {Object} dataToSet - data to set in cache
- *
- * @return {Result}
- */
- _setCache: function (key, dataToSet) {
-
- const oThis = this;
-
- var setCacheFunction = function(k, v) {
- var cacheKey = utils.invert(oThis.cacheKeys)[k];
- return cacheImplementer.set(cacheKey, JSON.stringify(v), oThis.cacheExpiry);
- };
-
- setCacheFunction(key, dataToSet).then(function(cacheSetResponse) {
-
- if (cacheSetResponse.isFailure()) {
- logger.error('cmm_b_2', 'Something Went Wrong', cacheSetResponse);
- }
- });
-
- }
-
-};
-
-module.exports = baseCacheMultiManagementKlass;
diff --git a/lib/cache_multi_management/user_airdrop_detail.js b/lib/cache_multi_management/user_airdrop_detail.js
deleted file mode 100644
index c97db4e..0000000
--- a/lib/cache_multi_management/user_airdrop_detail.js
+++ /dev/null
@@ -1,129 +0,0 @@
-"use strict";
-
-const rootPrefix = '../..'
- , baseCache = require(rootPrefix + '/lib/cache_multi_management/base')
- , UserAirdropDetailKlass = require(rootPrefix + '/app/models/user_airdrop_detail')
- , responseHelper = require(rootPrefix + '/lib/formatter/response')
- , logger = require(rootPrefix + '/helpers/custom_console_logger')
- , paramErrorConfig = require(rootPrefix + '/config/param_error_config')
- , apiErrorConfig = require(rootPrefix + '/config/api_error_config')
-;
-
-const errorConfig = {
- param_error_config: paramErrorConfig,
- api_error_config: apiErrorConfig
-};
-
-/**
- * @constructor
- * @augments userAirdropDetailCache
- *
- * @param {Object} params - cache key generation & expiry related params
- *
- */
-const userAirdropDetailCache = module.exports = function (params) {
- logger.debug("===========cacheManagement.user_airdrop_details.params===============");
- logger.debug(params);
- const oThis = this;
- oThis.userAddresses = params['userAddresses'];
- oThis.chainId = params['chainId'];
- oThis.airdropId = params['airdropId'];
-
- baseCache.call(this, params);
-
- oThis.useObject = true;
-
-};
-
-userAirdropDetailCache.prototype = Object.create(baseCache.prototype);
-
-userAirdropDetailCache.prototype.constructor = userAirdropDetailCache;
-
-/**
- * fetch data from source
- *
- * @return {Result}
- */
-userAirdropDetailCache.prototype.fetchDataFromSource = async function (cacheIds) {
- const oThis = this;
- logger.debug("===========cacheManagement.user_airdrop_details.fetchDataFromSource.cacheIds===============");
- logger.debug(cacheIds);
- if (!cacheIds) {
-
- let errorParams = {
- internal_error_identifier: 'l_cm_uad_1',
- api_error_identifier: 'user_address_invalid',
- error_config: errorConfig,
- debug_options: {}
- };
- return responseHelper.error(errorParams);
- }
-
- logger.debug("===========cacheManagement.user_airdrop_details.callingFromDB===============");
- const userAirdropDetailModel = new UserAirdropDetailKlass();
- const queryResponse = await userAirdropDetailModel.getByUserAddresses(oThis.airdropId, cacheIds);
-
- if (queryResponse.isSuccess()) {
- return queryResponse;
- } else {
-
- let errorParams = {
- internal_error_identifier: 'l_cm_uad_2',
- api_error_identifier: 'data_not_found',
- error_config: errorConfig,
- debug_options: {}
- };
-
- return responseHelper.error(errorParams);
- }
-
-};
-
-/**
- * set cache key
- *
- * @return {Object}
- */
-userAirdropDetailCache.prototype.setCacheKeys = function () {
-
- const oThis = this;
-
- oThis.cacheKeys = {};
- for (var i = 0; i < oThis.userAddresses.length; i++) {
- const key = oThis.getCacheKey(oThis.userAddresses[i]);
- oThis.cacheKeys[key] = oThis.userAddresses[i];
- }
-
- return oThis.cacheKeys;
-
-};
-
-/**
- * set cache expiry in oThis.cacheExpiry and return it
- *
- * @return {Number}
- */
-userAirdropDetailCache.prototype.setCacheExpiry = function () {
-
- const oThis = this;
-
- oThis.cacheExpiry = 300 // 5 minutes ;
-
- return oThis.cacheExpiry;
-
-};
-
-
-/**
- * Get cache keys
- *
- * @param {string} address - address
- *
- * @return {string}
- *
- */
-userAirdropDetailCache.prototype.getCacheKey = function(address) {
- const oThis = this;
- return `{${oThis.chainId}_${oThis.airdropId}}_${address.toLowerCase()}`;
-};
-
diff --git a/lib/contract_interact/EIP20TokenMock.js b/lib/contract_interact/EIP20TokenMock.js
deleted file mode 100644
index 6514c29..0000000
--- a/lib/contract_interact/EIP20TokenMock.js
+++ /dev/null
@@ -1,176 +0,0 @@
-//"use strict";
-
-/**
- *
- * This is a utility file which would be used for executing all methods on Pricer contract.
- *
- * @module lib/contract_interact/pricer
- *
- */
-
-const openSTStorage = require('@openstfoundation/openst-storage')
-;
-
-const rootPrefix = '../..'
- , helper = require(rootPrefix + '/lib/contract_interact/helper')
- , coreAddresses = require(rootPrefix + '/config/core_addresses')
- , web3Provider = require(rootPrefix + '/lib/web3/providers/ws')
- , gasLimitGlobalConstant = require(rootPrefix + '/lib/global_constant/gas_limit')
- , ddbServiceObj = require(rootPrefix + '/lib/dynamoDB_service')
- , autoScalingServiceObj = require(rootPrefix + '/lib/auto_scaling_service')
- , basicHelper = require(rootPrefix + '/helpers/basic_helper')
- , logger = require(rootPrefix + '/helpers/custom_console_logger')
-;
-
-const contractName = 'eip20tokenmock'
- , contractAbi = coreAddresses.getAbiForContract(contractName)
- , currContract = new web3Provider.eth.Contract(contractAbi)
-;
-
-
-/**
- * @constructor
- *
- */
-const MockToken = module.exports = function (mockTokenAddress) {
- this.contractAddress = mockTokenAddress;
-};
-
-MockToken.prototype = {
-
- /**
- * Get balance of address
- *
- * @param {String} ownerAddress - address for which balance is to be fetched
- *
- * @return {Promise}
- *
- */
- balanceOf: async function (ownerAddress) {
- const transactionObject = currContract.methods.balanceOf(ownerAddress);
- const encodedABI = transactionObject.encodeABI();
- const transactionOutputs = helper.getTransactionOutputs(transactionObject);
- const response = await helper.call(web3Provider, this.contractAddress, encodedABI, {}, transactionOutputs);
- return Promise.resolve(response[0]);
- },
-
- /**
- * Set balance
- *
- * @param {string} senderAddr - address of user who is sending amount
- * @param {string} senderPassphrase - sender address passphrase
- * @param {string} ownerAddress - address for which balance is to be set
- * @param {BigNumber} value - amount which is being transferred (in wei)
- * @param {BigNumber} gasPrice - gas price
- *
- * @return {Promise}
- *
- */
- setBalance: function (senderAddress, senderPassphrase, ownerAddress, value, gasPrice) {
- const oThis = this;
-
- if (!gasPrice) {
- return Promise.reject('GasPrice is mandatory');
- }
- helper.assertAddress(ownerAddress);
- helper.assertAddress(senderAddress);
-
- currContract.options.address = oThis.contractAddress;
- //currContract.setProvider( web3Provider.currentProvider );
- const transactionObject = currContract.methods.setBalance(ownerAddress, value);
- const encodedABI = transactionObject.encodeABI();
- return helper.safeSendFromAddr(
- web3Provider,
- oThis.contractAddress,
- encodedABI,
- senderAddress,
- senderPassphrase,
- { gasPrice: gasPrice, gas: gasLimitGlobalConstant.default() }
- ).then(async function(transactionReceipt) {
- // set balance in dynamo and cache.
- const balanceUpdateResponse = await new openSTStorage.TokenBalanceModel({
- ddb_service: ddbServiceObj,
- auto_scaling: autoScalingServiceObj,
- erc20_contract_address: oThis.contractAddress
- }).set({
- ethereum_address: ownerAddress,
- settle_amount: basicHelper.convertToBigNumber(value).toString(10),
- pessimistic_settled_balance: basicHelper.convertToBigNumber(value).toString(10),
- un_settled_debit_amount: basicHelper.convertToBigNumber(0).toString(10),
- }).catch(function (error) {
- logger.error('lib/contract_interact/EIP20TokenMock.js:set Balance inside catch:', error);
- });
- return Promise.resolve(transactionReceipt);
- });
- },
-
- /**
- * Set conversion rate
- *
- * @param {string} senderAddr - address of sender
- * @param {string} senderPassphrase - passphrase of sender
- * @param {number} conversionRate - conversion rate of branded token
- * @param {BigNumber} gasPrice - gas price
- *
- * @return {Promise}
- *
- */
- setConversionRate: function (senderAddress, senderPassphrase, conversionRate, gasPrice) {
- if (!gasPrice) {
- return Promise.reject('GasPrice is mandatory');
- }
- helper.assertAddress(senderAddress);
-
- currContract.options.address = this.contractAddress;
- //currContract.setProvider( web3Provider.currentProvider );
- const transactionObject = currContract.methods.setConverionRate(conversionRate);
- const encodedABI = transactionObject.encodeABI();
- return helper.safeSendFromAddr(
- web3Provider,
- this.contractAddress,
- encodedABI,
- senderAddress,
- senderPassphrase,
- { gasPrice: gasPrice, gas: gasLimitGlobalConstant.default() }
- ).then(function(transactionReceipt) {
- return Promise.resolve(transactionReceipt);
- });
- },
-
- /**
- * Approve
- *
- * @param {string} senderAddr - address of sender
- * @param {string} senderPassphrase - passphrase of sender
- * @param {string} spenderAddress - address which will be approved for spending
- * @param {BigNumber} value - amount which is being approved (in wei)
- * @param {BigNumber} gasPrice - gas price
- *
- * @return {Promise}
- *
- */
- approve: function (senderAddress, senderPassphrase, spenderAddress, value, gasPrice) {
- if (!gasPrice) {
- return Promise.reject('GasPrice is mandatory');
- }
- helper.assertAddress(senderAddress);
- helper.assertAddress(spenderAddress);
-
- currContract.options.address = this.contractAddress;
- //currContract.setProvider( web3Provider.currentProvider );
- const transactionObject = currContract.methods.approve(spenderAddress, value);
- const encodedABI = transactionObject.encodeABI();
- return helper.safeSendFromAddr(
- web3Provider,
- this.contractAddress,
- encodedABI,
- senderAddress,
- senderPassphrase,
- { gasPrice: gasPrice, gas: gasLimitGlobalConstant.default() }
- ).then(function(transactionReceipt) {
- return Promise.resolve(transactionReceipt);
- });
- }
-
-};
-
diff --git a/lib/contract_interact/airdrop.js b/lib/contract_interact/airdrop.js
deleted file mode 100644
index b28cd55..0000000
--- a/lib/contract_interact/airdrop.js
+++ /dev/null
@@ -1,538 +0,0 @@
-"use strict";
-
-/**
- *
- * This is a utility file which would be used for executing all methods on Pricer.sol contract.
- *
- * @module lib/contract_interact/airdrop
- *
- */
-const BigNumber = require('bignumber.js')
-;
-
-const rootPrefix = '../..'
- , helper = require(rootPrefix + '/lib/contract_interact/helper')
- , coreAddresses = require(rootPrefix + '/config/core_addresses')
- , web3Provider = require(rootPrefix + '/lib/web3/providers/ws')
- , responseHelper = require(rootPrefix + '/lib/formatter/response')
- , basicHelper = require(rootPrefix + '/helpers/basic_helper')
- , logger = require(rootPrefix + '/helpers/custom_console_logger')
- , eventGlobalConstants = require(rootPrefix + '/lib/global_constant/events')
- , notificationGlobalConstant = require(rootPrefix + '/lib/global_constant/notification')
- , gasLimitGlobalConstant = require(rootPrefix + '/lib/global_constant/gas_limit')
- , Pricer = require(rootPrefix + '/lib/contract_interact/pricer')
- , AirdropCacheKlass = require(rootPrefix + '/lib/cache_management/airdrop')
- , AirdropUserBalanceKlass = require(rootPrefix + '/services/airdrop_management/user_balance')
- , paramErrorConfig = require(rootPrefix + '/config/param_error_config')
- , apiErrorConfig = require(rootPrefix + '/config/api_error_config')
-;
-
-const errorConfig = {
- param_error_config: paramErrorConfig,
- api_error_config: apiErrorConfig
-};
-
-const contractAbi = coreAddresses.getAbiForContract('airdrop')
- , currContract = new web3Provider.eth.Contract(contractAbi)
-;
-
-/**
- * @constructor
- *
- * @param {string} airdropContractAddress - airdrop contract address
- * @param {string} chainId - chain ID
- *
- * @augments Pricer
- *
- */
-const Airdrop = function (airdropContractAddress, chainId) {
- const oThis = this
- ;
-
- Pricer.call(oThis, airdropContractAddress, chainId);
-
- oThis.contractName = 'airdrop';
- oThis.contractAddress = airdropContractAddress;
- oThis.chainId = chainId;
-
- oThis.airdropCache = new AirdropCacheKlass(chainId, airdropContractAddress);
-};
-
-Airdrop.prototype = Object.create(Pricer.prototype);
-
-const AirdropSpecificPrototype = {
- constructor: Airdrop,
-
- /**
- * Actual pay method - can give rejections of Promise
- *
- * @param {string} senderWorkerAddress - address of worker
- * @param {string} senderWorkerPassphrase - passphrase of worker
- * @param {string} beneficiaryAddress - address of beneficiary account
- * @param {BigNumber} transferAmount - transfer amount (in wei)
- * @param {string} commissionBeneficiaryAddress - address of commision beneficiary account
- * @param {BigNumber} commissionAmount - commission amount (in wei)
- * @param {string} currency - quote currency
- * @param {BigNumber} intendedPricePoint - price point at which the pay is intended (in wei)
- * @param {string} spender - User address
- * @param {Hex} gasPrice - gas price
- * @param {object} options - for params like returnType, tag.
- *
- * @return {promise}
- *
- */
- pay: function (senderWorkerAddress, senderWorkerPassphrase, beneficiaryAddress,
- transferAmount, commissionBeneficiaryAddress, commissionAmount, currency, intendedPricePoint,
- spender, gasPrice, options) {
- const oThis = this
- ;
-
- return oThis._asyncPay(senderWorkerAddress, senderWorkerPassphrase, beneficiaryAddress,
- transferAmount, commissionBeneficiaryAddress, commissionAmount, currency, intendedPricePoint,
- spender, gasPrice, options)
- .catch(function (error) {
- if (responseHelper.isCustomResult(error)) {
- return error;
- } else {
- logger.error(`${__filename}::pay::catch`);
- logger.error(error);
- return responseHelper.error({
- internal_error_identifier: 'l_ci_a_pay_1',
- api_error_identifier: 'unhandled_api_error',
- error_config: errorConfig,
- debug_options: {}
- });
- }
- });
- },
-
- _asyncPay: async function (senderWorkerAddress, senderWorkerPassphrase, beneficiaryAddress,
- transferAmount, commissionBeneficiaryAddress, commissionAmount, currency, intendedPricePoint,
- spender, gasPrice, options) {
- logger.debug("\nAirdrop.pay.params");
- logger.debug("\nsenderWorkerAddress: ", senderWorkerAddress, "\nbeneficiaryAddress: ", beneficiaryAddress, "\ntransferAmount: ",
- transferAmount, "\ncommissionBeneficiaryAddress ", commissionBeneficiaryAddress,
- "\ncommissionAmount: ", commissionAmount, "\ncurrency: ", currency, "\nintendedPricePoint", intendedPricePoint,
- "\nspender", spender, "\ngasPrice", gasPrice, "\noptions", options);
-
- const oThis = this
- ;
-
- await helper.validateAirdropPayParams(senderWorkerAddress,
- beneficiaryAddress,
- transferAmount,
- commissionBeneficiaryAddress,
- commissionAmount,
- currency,
- intendedPricePoint,
- gasPrice,
- spender);
-
- // validate if spender has the balance
- let totalTransferAmount = 0;
- // If currency is not present, amounts are in BT
- if (!currency) {
- totalTransferAmount = basicHelper.convertToBigNumber(0)
- .plus(transferAmount)
- .plus(commissionAmount);
- } else { // amounts are in USD
- totalTransferAmount = await oThis.getEstimatedTotalAmount(transferAmount, commissionAmount, intendedPricePoint);
- logger.debug("=========totalAmount========", totalTransferAmount);
- }
-
- const spenderOnChainAvailableBalanceResponse = await oThis.getBalanceOf(spender);
- logger.debug("==========airdrop.pay.senderAccountBalanceResponse===========");
- logger.debug(spenderOnChainAvailableBalanceResponse);
- if (spenderOnChainAvailableBalanceResponse.isFailure()) {
- let errorParams = {
- internal_error_identifier: 'l_ci_a_async_pay_1',
- api_error_identifier: 'db_get_failed',
- error_config: errorConfig,
- debug_options: {}
- };
- return Promise.reject(responseHelper.error(errorParams));
- }
-
- let spenderOnChainAvailableBalance = basicHelper.convertToBigNumber(spenderOnChainAvailableBalanceResponse.data.balance);
- logger.debug(`\nuserInitialBalance: ${spenderOnChainAvailableBalance.toString(10)}`);
-
- let spenderAirdropBalanceResponse = await new AirdropUserBalanceKlass({
- chain_id: oThis.chainId,
- airdrop_contract_address: oThis.contractAddress,
- user_addresses: [spender]
- }).perform();
-
- logger.debug("==========airdrop.pay.airdropBalanceResult===========");
- logger.debug(spenderAirdropBalanceResponse);
- if (spenderAirdropBalanceResponse.isFailure()) {
- return Promise.reject(spenderAirdropBalanceResponse);
- }
-
- let spenderAirdropBalance = spenderAirdropBalanceResponse.data[spender] ?
- basicHelper.convertToBigNumber(spenderAirdropBalanceResponse.data[spender].balanceAirdropAmount) :
- basicHelper.convertToBigNumber(0)
- ;
-
- // to give airdrop balance higher preference, we compute the min of total amount and airdrop balance
- let airdropBalanceToUse = BigNumber.min(totalTransferAmount, spenderAirdropBalance)
- ;
-
- logger.debug(`\nairdropBalanceToUse: ${airdropBalanceToUse.toString(10)}`);
- logger.debug(`\ntotalAmount: ${totalTransferAmount.toString(10)}`);
- logger.debug(`\nuserInitialBalance.plus(airdropBalanceToUse): ${(spenderOnChainAvailableBalance.plus(airdropBalanceToUse)).toString(10)}`);
-
- // validate if the spender has enough balance (airdrop + on chain available)
- if ((spenderOnChainAvailableBalance.plus(airdropBalanceToUse)).lt(totalTransferAmount)) {
- let errorParams = {
- internal_error_identifier: 'l_ci_a_async_pay_2',
- api_error_identifier: 'insufficient_funds',
- error_config: errorConfig,
- debug_options: {}
- };
- return Promise.reject(responseHelper.error(errorParams));
- }
-
- const brandedTokenResponse = await oThis.brandedToken();
- if (brandedTokenResponse.isFailure()) return Promise.reject(brandedTokenResponse);
-
- let brandedTokenAddress = brandedTokenResponse.data.brandedToken;
-
- const airdropBudgetHolderResponse = await oThis.airdropBudgetHolder();
- if (airdropBudgetHolderResponse.isFailure()) return Promise.reject(airdropBudgetHolderResponse);
-
- let airdropBudgetHolder = airdropBudgetHolderResponse.data.airdropBudgetHolder;
-
- const returnType = basicHelper.getReturnType(options.returnType);
- logger.debug("==========airdrop.pay.params===========");
- logger.debug(beneficiaryAddress, transferAmount, commissionBeneficiaryAddress, commissionAmount, currency,
- intendedPricePoint, spender, spenderAirdropBalance.toString(10));
-
- const notificationData = helper.getNotificationData(
- ['transfer.payments.airdrop.pay'],
- notificationGlobalConstant.publisher(),
- 'pay',
- oThis.contractName,
- oThis.contractAddress,
- web3Provider,
- oThis.chainId,
- options);
- notificationData.message.payload.erc20_contract_address = brandedTokenAddress;
-
-
- const postPayParams = {
- beneficiaryAddress: beneficiaryAddress,
- commissionBeneficiaryAddress: commissionBeneficiaryAddress,
- spender: spender,
- brandedTokenAddress: brandedTokenAddress,
- contractAddress: oThis.contractAddress,
- totalAmount: totalTransferAmount.toString(10),
- airdropAmountToUse: airdropBalanceToUse.toString(10),
- airdropBudgetHolder: airdropBudgetHolder,
- chainId: oThis.chainId
- };
-
- const failCallback = function (reason) {
- return oThis.onAirdropPayFailure(postPayParams);
- };
-
- const successCallback = async function (receipt) {
-
- const setAddressToNameMapResponse = await oThis.setAddressToNameMap();
- if (setAddressToNameMapResponse.isFailure()) {
- return setAddressToNameMapResponse;
- }
-
- const actualAmountsFromReceipt = oThis.transactionHelper.getActualAmountsFromReceipt(receipt, oThis.addressToNameMap,
- eventGlobalConstants.eventAirdropPayment());
- logger.debug("========airdrop.pay.actualAmountsFromReceipt Response========");
- logger.debug(actualAmountsFromReceipt);
- if (actualAmountsFromReceipt.isSuccess()) {
- return await oThis.onAirdropPaySuccess(postPayParams, actualAmountsFromReceipt.data);
- } else {
- return failCallback("Status 0x0");
- }
- };
-
- const transactionObject = currContract.methods.payAirdrop(
- beneficiaryAddress,
- transferAmount,
- commissionBeneficiaryAddress,
- commissionAmount,
- web3Provider.utils.asciiToHex(currency),
- intendedPricePoint,
- spender,
- spenderAirdropBalance.toString(10));
-
- const sendPerformParams = {
- transactionObject: transactionObject,
- notificationData: notificationData,
- senderAddress: senderWorkerAddress,
- senderPassphrase: senderWorkerPassphrase,
- contractAddress: oThis.contractAddress,
- gasPrice: gasPrice,
- gasLimit: gasLimitGlobalConstant.airdropPay(),
- web3Provider: web3Provider,
- successCallback: successCallback,
- failCallback: failCallback,
- errorCode: "l_ci_ad_p_3"
- };
-
- if (options && options.shouldHandlePostPay == 0) {
- sendPerformParams.processReceipt = 0;
- sendPerformParams.postReceiptProcessParams = postPayParams;
- } else {
- sendPerformParams.processReceipt = 1;
- }
-
- const beforePayResponse = await oThis.transactionHelper.beforeAirdropPay(
- brandedTokenAddress,
- oThis.contractAddress,
- spender,
- totalTransferAmount,
- airdropBalanceToUse,
- airdropBudgetHolder);
-
- const isAllResponseSuccessful = oThis.transactionHelper.isAllResponseSuccessful(beforePayResponse);
- if (isAllResponseSuccessful) {
- return Promise.resolve(helper.performSend(sendPerformParams, returnType));
- } else {
- let errorParams = {
- internal_error_identifier: 'l_ci_a_async_pay_3',
- api_error_identifier: 'could_not_process',
- error_config: errorConfig,
- debug_options: {}
- };
- logger.error('%Error - Something went wrong. It could be that either cache or airdrop used amount promise failed.');
- // TODO: Discuss: we may need to do some revert ?
- return Promise.reject(responseHelper.error(errorParams));
- }
- },
-
- /**
- * postAirdropPay
- *
- * @param {Object} airdropPostPayParams - airdrop post pay params
- * @param {string} airdropPostPayParams.beneficiaryAddress - beneficiary address
- * @param {string} airdropPostPayParams.commissionBeneficiaryAddress - commission beneficiary address
- * @param {string} airdropPostPayParams.spender - spender address
- * @param {string} airdropPostPayParams.brandedTokenAddress - branded token address
- * @param {string} airdropPostPayParams.contractAddress - contractAddress address
- * @param {string} airdropPostPayParams.airdropBudgetHolder - airdrop budget holder address
- * @param {number} airdropPostPayParams.totalAmount - total amount that was debited from spender account
- * @param {number} airdropPostPayParams.airdropAmountToUse - airdrop amount that was used in the transaction
- * @param {number} airdropPostPayParams.chainId - chain id
- * @param {Object} decodedEvents - decoded events from trasaction receipt
- * @param {number} status - transactions status (0 => failure, 1 => success)
- *
- * @return {promise}
- *
- */
- postAirdropPay: async function (airdropPostPayParams, decodedEvents, status) {
- const oThis = this
- ;
-
- if (status == 1) {
-
- const actualAmountsFromReceipt = oThis.transactionHelper.getActualAmountsFromDecodedEvents(decodedEvents,
- eventGlobalConstants.eventAirdropPayment());
-
- if (actualAmountsFromReceipt.isSuccess()) {
- return await oThis.onAirdropPaySuccess(airdropPostPayParams, actualAmountsFromReceipt.data);
- }
- }
-
- return await oThis.onAirdropPayFailure(airdropPostPayParams);
-
- },
-
- /**
- * onAirdropPaySuccess
- *
- * @param {Object} airdropPostPayParams - airdrop post pay params
- * @param {string} airdropPostPayParams.beneficiaryAddress - beneficiary address
- * @param {string} airdropPostPayParams.commissionBeneficiaryAddress - commission beneficiary address
- * @param {string} airdropPostPayParams.spender - spender address
- * @param {string} airdropPostPayParams.brandedTokenAddress - branded token address
- * @param {string} airdropPostPayParams.contractAddress - contractAddress address
- * @param {string} airdropPostPayParams.airdropBudgetHolder - airdrop budget holder address
- * @param {number} airdropPostPayParams.totalAmount - total amount that was debited from spender account
- * @param {number} airdropPostPayParams.airdropAmountToUse - airdrop amount that was used in the transaction
- * @param {number} airdropPostPayParams.chainId - chain id
- * @param {Object} actualAmountsFromReceipt - Actual transfer amounts from receipt
- *
- * @return {promise}
- *
- */
- onAirdropPaySuccess: async function (airdropPostPayParams, actualAmountsFromReceipt) {
-
- const oThis = this
- , validationResponse = helper.validatePostAirdropPayParams(airdropPostPayParams);
-
- if (validationResponse.isFailure()) return Promise.resolve(validationResponse);
-
- const brandedTokenAddress = airdropPostPayParams.brandedTokenAddress
- , contractAddress = airdropPostPayParams.contractAddress
- , spender = airdropPostPayParams.spender
- , totalTransferAmount = basicHelper.convertToBigNumber(airdropPostPayParams.totalAmount)
- , airdropAmountToUse = basicHelper.convertToBigNumber(airdropPostPayParams.airdropAmountToUse)
- , beneficiaryAddress = airdropPostPayParams.beneficiaryAddress
- , commissionBeneficiaryAddress = airdropPostPayParams.commissionBeneficiaryAddress
- , airdropBudgetHolder = airdropPostPayParams.airdropBudgetHolder
- ;
-
- const afterSuccessResponse = await oThis.transactionHelper.afterAirdropPaySuccess(
- brandedTokenAddress,
- contractAddress,
- spender,
- totalTransferAmount,
- airdropAmountToUse,
- beneficiaryAddress,
- actualAmountsFromReceipt.actualBeneficiaryAmount,
- commissionBeneficiaryAddress,
- actualAmountsFromReceipt.actualCommissionAmount,
- actualAmountsFromReceipt.actualAirdropAmount,
- airdropBudgetHolder);
-
- const isAllResponseSuccessful = oThis.transactionHelper.isAllResponseSuccessful(afterSuccessResponse);
- if (isAllResponseSuccessful) {
- return Promise.resolve(responseHelper.successWithData({}));
- }
- let errorParams = {
- internal_error_identifier: 'l_ci_a_onAirdropPaySuccess_1',
- api_error_identifier: 'could_not_process',
- error_config: errorConfig,
- debug_options: {}
- };
- return Promise.resolve(responseHelper.error(errorParams));
- },
-
- /**
- * onAirdropPayFailure
- *
- * @param {Object} airdropPostPayParams - airdrop post pay params
- * @param {string} airdropPostPayParams.beneficiaryAddress - beneficiary address
- * @param {string} airdropPostPayParams.commissionBeneficiaryAddress - commission beneficiary address
- * @param {string} airdropPostPayParams.spender - spender address
- * @param {string} airdropPostPayParams.brandedTokenAddress - branded token address
- * @param {string} airdropPostPayParams.contractAddress - contractAddress address
- * @param {string} airdropPostPayParams.airdropBudgetHolder - airdrop budget holder address
- * @param {number} airdropPostPayParams.totalAmount - total amount that was debited from spender account
- * @param {number} airdropPostPayParams.airdropAmountToUse - airdrop amount that was used in the transaction
- * @param {number} airdropPostPayParams.chainId - chain id
- *
- * @return {promise}
- *
- */
- onAirdropPayFailure: async function (airdropPostPayParams) {
-
- const oThis = this
- ;
-
- const validationResponse = helper.validatePostAirdropPayParams(airdropPostPayParams);
- if (validationResponse.isFailure()) return Promise.reject(validationResponse);
-
- const brandedTokenAddress = airdropPostPayParams.brandedTokenAddress
- , contractAddress = airdropPostPayParams.contractAddress
- , spender = airdropPostPayParams.spender
- , totalTransferAmount = basicHelper.convertToBigNumber(airdropPostPayParams.totalAmount)
- , airdropAmountToUse = basicHelper.convertToBigNumber(airdropPostPayParams.airdropAmountToUse)
- , airdropBudgetHolderAddress = airdropPostPayParams.airdropBudgetHolder
- ;
-
- const afterFailureResponse = await oThis.transactionHelper.afterAirdropPayFailure(
- brandedTokenAddress,
- contractAddress,
- spender,
- totalTransferAmount,
- airdropAmountToUse,
- airdropBudgetHolderAddress);
-
- const isAllResponseSuccessful = oThis.transactionHelper.isAllResponseSuccessful(afterFailureResponse);
- if (isAllResponseSuccessful) {
- return Promise.resolve(responseHelper.successWithData({}));
- }
- let errorParams = {
- internal_error_identifier: 'l_ci_a_onAirdropPayFailure_1',
- api_error_identifier: 'could_not_process',
- error_config: errorConfig,
- debug_options: {}
- };
- return Promise.resolve(responseHelper.error(errorParams));
-
- },
-
-
- /**
- * Get airdrop budget holder address of airdrop
- *
- * @return {promise}
- *
- */
- airdropBudgetHolder: async function () {
- const oThis = this
- ;
-
- try {
- const cacheResult = await oThis.airdropCache.getAirdropBudgetHolder();
- if (cacheResult.isSuccess() && cacheResult.data.response != null) {
- return Promise.resolve(responseHelper.successWithData({airdropBudgetHolder: cacheResult.data.response}));
- } else {
- const getAirdropBudgetHolderFromContractResponse = await oThis.getAirdropBudgetHolderFromContract();
- if (getAirdropBudgetHolderFromContractResponse.isSuccess()) {
- await oThis.airdropCache.setAirdropBudgetHolder(getAirdropBudgetHolderFromContractResponse.data.airdropBudgetHolder);
- }
- return Promise.resolve(getAirdropBudgetHolderFromContractResponse);
- }
-
- } catch (err) {
- let errorParams = {
- internal_error_identifier: 'l_ci_a_airdropBudgetHolder_1',
- api_error_identifier: 'unhandled_api_error',
- error_config: errorConfig,
- debug_options: {}
- };
- logger.error("lib/contract_interact/airdrop.js:airdropBudgetHolder inside catch ", err);
- return Promise.resolve(responseHelper.error(errorParams));
- }
- },
-
- /**
- * Get airdrop budget holder address of airdrop from contract
- *
- * @return {promise}
- *
- */
- getAirdropBudgetHolderFromContract: async function () {
- const oThis = this
- ;
-
- const transactionObject = currContract.methods.airdropBudgetHolder()
- , encodedABI = transactionObject.encodeABI()
- , transactionOutputs = helper.getTransactionOutputs(transactionObject)
- , response = await helper.call(web3Provider, oThis.contractAddress, encodedABI, {}, transactionOutputs);
-
- return Promise.resolve(responseHelper.successWithData({airdropBudgetHolder: response[0]}));
- },
-
- /**
- * Get worker contract address
- *
- * @return {promise}
- *
- */
- getWorkers: async function () {
- const oThis = this
- ;
-
- const transactionObject = currContract.methods.workers()
- , encodedABI = transactionObject.encodeABI()
- , transactionOutputs = helper.getTransactionOutputs(transactionObject)
- , response = await helper.call(web3Provider, oThis.contractAddress, encodedABI, {}, transactionOutputs);
-
- return Promise.resolve(responseHelper.successWithData({workerContractAddress: response[0]}));
- }
-};
-
-Object.assign(Airdrop.prototype, AirdropSpecificPrototype);
-
-module.exports = Airdrop;
diff --git a/lib/contract_interact/branded_token.js b/lib/contract_interact/branded_token.js
deleted file mode 100644
index 2d756c6..0000000
--- a/lib/contract_interact/branded_token.js
+++ /dev/null
@@ -1,446 +0,0 @@
-"use strict";
-
-/**
- *
- * This is a utility file which would be used for executing all methods on EIP20Token contract.
- *
- * @module lib/contract_interact/branded_token
- *
- */
-const openSTStorage = require('@openstfoundation/openst-storage')
-;
-
-const rootPrefix = '../..'
- , helper = require(rootPrefix + '/lib/contract_interact/helper')
- , coreAddresses = require(rootPrefix + '/config/core_addresses')
- , web3Provider = require(rootPrefix + '/lib/web3/providers/ws')
- , coreConstants = require(rootPrefix + '/config/core_constants')
- , responseHelper = require(rootPrefix + '/lib/formatter/response')
- , basicHelper = require(rootPrefix + '/helpers/basic_helper')
- , logger = require(rootPrefix + '/helpers/custom_console_logger')
- , notificationGlobalConstant = require(rootPrefix + '/lib/global_constant/notification')
- , gasLimitGlobalConstant = require(rootPrefix + '/lib/global_constant/gas_limit')
- , paramErrorConfig = require(rootPrefix + '/config/param_error_config')
- , apiErrorConfig = require(rootPrefix + '/config/api_error_config')
- , ddbServiceObj = require(rootPrefix + '/lib/dynamoDB_service')
- , autoScalingServiceObj = require(rootPrefix + '/lib/auto_scaling_service')
-;
-
-const errorConfig = {
- param_error_config: paramErrorConfig,
- api_error_config: apiErrorConfig
-};
-
-const contractName = 'brandedToken'
- , contractAbi = coreAddresses.getAbiForContract(contractName)
- , currContract = new web3Provider.eth.Contract(contractAbi)
-;
-
-/**
- * Constructor to create object of BrandedToken
- *
- * @constructor
- *
- * @param {string} brandedTokenAddress - Branded token address
- * @param {number} chainId - chainId
- *
- */
-const BrandedToken = function (brandedTokenAddress, chainId) {
- const oThis = this
- ;
-
- oThis.brandedTokenAddress = brandedTokenAddress;
- oThis.chainId = chainId;
-};
-
-BrandedToken.prototype = {
-
- /**
- * branded token address
- */
- brandedTokenAddress: null,
-
- /**
- * chain id
- */
- chainId: null,
-
- /**
- * Fetch Balance For a given address
- *
- * @param {string} owner - address for which balance is to be fetched
- *
- * @return {promise}
- *
- */
- getBalanceOf: async function (owner) {
- const oThis = this
- ;
-
- try {
-
- // Validate addresses
- if (!basicHelper.isAddressValid(owner)) {
- let errObj = responseHelper.error({
- internal_error_identifier: 'l_ci_bt_getBalanceOf_1',
- api_error_identifier: 'invalid_address',
- error_config: errorConfig
- });
-
- return Promise.resolve(errObj);
- }
-
- const balanceResponse = await new openSTStorage.TokenBalanceCache({
- ddb_service: ddbServiceObj,
- auto_scaling: autoScalingServiceObj,
- erc20_contract_address: oThis.brandedTokenAddress,
- ethereum_addresses: [owner]
- }).fetch();
-
- if (balanceResponse.isFailure()) {
- return Promise.resolve(balanceResponse);
- }
-
- const ownerBalance = balanceResponse.data[owner.toLowerCase()].available_balance;
-
- return responseHelper.successWithData({balance: ownerBalance});
-
- } catch(err) {
- let errorParams = {
- internal_error_identifier: 'l_ci_bt_getBalanceOf_2',
- api_error_identifier: 'unhandled_api_error',
- error_config: errorConfig,
- debug_options: {}
- };
- logger.error('lib/contract_interact/branded_token.js:getBalanceOf inside catch:', err);
- return Promise.resolve(responseHelper.error(errorParams));
- }
- },
-
- /**
- * Transfer amount to budget holder
- *
- * @param {string} senderAddress - address of sender
- * @param {string} senderPassphrase - passphrase of sender
- * @param {string} airdropBudgetHolderAddress - recipient address
- * @param {BigNumber} amount - amount in wei
- * @param {BigNumber} gasPrice - gas price
- * @param {object} options - for params like returnType, tag.
- *
- * @return {promise}
- *
- */
- transferToAirdropBudgetHolder: async function (senderAddress, senderPassphrase, airdropBudgetHolderAddress,
- amount, gasPrice, options) {
- const oThis = this
- ;
-
- try {
- const returnType = basicHelper.getReturnType(options.returnType)
- , transactionObject = currContract.methods.transfer(airdropBudgetHolderAddress, amount)
- ;
-
- const notificationData = helper.getNotificationData(
- ['transfer.payments.brandedToken.transferToBudgetHolder'],
- notificationGlobalConstant.publisher(),
- 'transferToBudgetHolder',
- contractName,
- oThis.brandedTokenAddress,
- web3Provider,
- oThis.chainId,
- options);
- notificationData.message.payload.erc20_contract_address = oThis.brandedTokenAddress;
-
- const onSuccess = async function(receipt) {
- if(coreConstants.STANDALONE_MODE == '1') {
- await oThis._afterTransferSuccess(senderAddress, airdropBudgetHolderAddress, amount);
- }
- };
- const onFail = async function(receipt) {
- await oThis._afterTransferFail(senderAddress, amount);
- };
-
- const params = {
- transactionObject: transactionObject,
- notificationData: notificationData,
- senderAddress: senderAddress,
- senderPassphrase: senderPassphrase,
- contractAddress: oThis.brandedTokenAddress,
- gasPrice: gasPrice,
- gasLimit: gasLimitGlobalConstant.transferToAirdropBudgetHolder(),
- web3Provider: web3Provider,
- successCallback: onSuccess,
- failCallback: onFail,
- errorCode: "l_ci_bt_transferToAirdropBudgetHolder_1"
- };
-
- const beforeTransferResponse = await oThis._beforeTransfer(senderAddress, amount);
-
- if (beforeTransferResponse.isSuccess()) {
- return Promise.resolve(helper.performSend(params, returnType));
- } else {
- return Promise.resolve(beforeTransferResponse);
- }
- } catch(err) {
- let errorParams = {
- internal_error_identifier: 'l_ci_bt_transferToAirdropBudgetHolder_2',
- api_error_identifier: 'unhandled_api_error',
- error_config: errorConfig,
- debug_options: {}
- };
- logger.error('lib/contract_interact/branded_token.js:transferToAirdropBudgetHolder inside catch:', err);
- return Promise.resolve(responseHelper.error(errorParams));
- }
- },
-
- /**
- * Credit balance in cache
- *
- * @param {string} owner - Account address
- * @param {BigNumber} amount - amount to be credited
- *
- * @return {promise}
- */
- creditBalance: async function (owner, amount) {
- const oThis = this
- , bigAmount = basicHelper.convertToBigNumber(amount)
- ;
-
- try {
-
- const balanceUpdateResponse = await new openSTStorage.TokenBalanceModel({
- ddb_service: ddbServiceObj,
- auto_scaling: autoScalingServiceObj,
- erc20_contract_address: oThis.brandedTokenAddress
- }).update({
- ethereum_address: owner,
- settle_amount: bigAmount.toString(10)
- }).catch(function (error) {
- return error;
- });
-
- if (balanceUpdateResponse.isFailure()) {
- return balanceUpdateResponse;
- }
- return Promise.resolve(responseHelper.successWithData({}));
-
- } catch(err) {
- let errorParams = {
- internal_error_identifier: 'l_ci_bt_creditBalance_1',
- api_error_identifier: 'unhandled_api_error',
- error_config: errorConfig,
- debug_options: {}
- };
- logger.error('lib/contract_interact/branded_token.js:creditBalance inside catch:', err);
- return Promise.resolve(responseHelper.error(errorParams));
- }
- },
-
- /**
- * Debit balance in cache
- *
- * @param {string} owner - Account address
- * @param {BigNumber} bigAmount - amount to be debited
- *
- * @return {promise}
- */
- debitBalance: async function (owner, amount) {
- const oThis = this
- , debitAmount = (basicHelper.convertToBigNumber(amount)).mul(basicHelper.convertToBigNumber(-1));
-
- try {
-
- const balanceUpdateResponse = await new openSTStorage.TokenBalanceModel({
- ddb_service: ddbServiceObj,
- auto_scaling: autoScalingServiceObj,
- erc20_contract_address: oThis.brandedTokenAddress
- }).update({
- ethereum_address: owner,
- settle_amount: debitAmount.toString(10),
- un_settled_debit_amount: debitAmount.toString(10)
- }).catch(function (error) {
- return error;
- });
-
- if (balanceUpdateResponse.isFailure()) {
- return balanceUpdateResponse;
- }
- return Promise.resolve(responseHelper.successWithData({}));
-
- } catch(err) {
- let errorParams = {
- internal_error_identifier: 'l_ci_bt_debitBalance_1',
- api_error_identifier: 'unhandled_api_error',
- error_config: errorConfig,
- debug_options: {}
- };
- logger.error('lib/contract_interact/branded_token.js:debitBalance inside catch:', err);
- return Promise.resolve(responseHelper.error(errorParams));
- }
- },
-
-
- /**
- * Debit balance in cache for pessimistic caching
- *
- * @param {string} owner - Account address
- * @param {BigNumber} bigAmount - amount to be debited
- *
- * @return {promise}
- *
- * @ignore
- */
- pessimisticDebit: async function (owner, amount) {
-
- const oThis = this
- , bigAmount = basicHelper.convertToBigNumber(amount)
- ;
-
- const balanceUpdateResponse = await new openSTStorage.TokenBalanceModel({
- ddb_service: ddbServiceObj,
- auto_scaling: autoScalingServiceObj,
- erc20_contract_address: oThis.brandedTokenAddress
- }).update({
- ethereum_address: owner,
- un_settled_debit_amount: bigAmount.toString(10)
- }).catch(function (error) {
- return error;
- });
-
- if (balanceUpdateResponse.isFailure()) {
- return balanceUpdateResponse;
- }
- return responseHelper.successWithData({});
-
- },
-
- /**
- * Approve amount to budget holder
- *
- * @param {string} airdropBudgetHolderAddress - address of airdropBudgetHolder
- * @param {string} airdropBudgetHolderPassphrase - Passphrase of airdropBudgetHolder
- * @param {string} airdropContractAddress - airdrop contract address
- * @param {BigNumber} amount - amount in wei
- * @param {BigNumber} gasPrice - gas price
- * @param {object} options - for params like returnType, tag.
- *
- * @return {promise}
- *
- */
- approveByBudgetHolder: function (airdropBudgetHolderAddress, airdropBudgetHolderPassphrase, airdropContractAddress,
- amount, gasPrice, options) {
-
- const oThis = this
- ;
-
- try {
- const returnType = basicHelper.getReturnType(options.returnType)
- , transactionObject = currContract.methods.approve(airdropContractAddress, amount);
-
- const notificationData = helper.getNotificationData(
- ['payments.brandedToken.approveToBudgetHolder'],
- notificationGlobalConstant.publisher(),
- 'approveByBudgetHolder',
- contractName,
- oThis.brandedTokenAddress,
- web3Provider,
- oThis.chainId,
- options);
-
- const params = {
- transactionObject: transactionObject,
- notificationData: notificationData,
- senderAddress: airdropBudgetHolderAddress,
- senderPassphrase: airdropBudgetHolderPassphrase,
- contractAddress: oThis.brandedTokenAddress,
- gasPrice: gasPrice,
- gasLimit: gasLimitGlobalConstant.approveByBudgetHolder(),
- web3Provider: web3Provider,
- successCallback: null,
- failCallback: null,
- errorCode: "l_ci_bt_approveByBudgetHolder_1"
- };
-
- return helper.performSend(params, returnType);
- } catch(err) {
- let errorParams = {
- internal_error_identifier: 'l_ci_bt_approveByBudgetHolder_2',
- api_error_identifier: 'unhandled_api_error',
- error_config: errorConfig,
- debug_options: {}
- };
- logger.error('lib/contract_interact/branded_token.js:approveByBudgetHolder inside catch:', err);
- return Promise.resolve(responseHelper.error(errorParams));
- }
- },
-
- /**
- * Called before transfer to airdrop budget holder
- *
- * @param {string} address - address
- * @param {BigNumber} amount - amount in wei
- *
- * @return {Promise}
- * @ignore
- * @private
- *
- */
- _beforeTransfer: function(address, amount) {
- const oThis = this
- ;
-
- logger.debug('_beforeTransfer called with params:', {address: address, amount: amount});
-
- return oThis.pessimisticDebit(address, amount);
- },
-
- /**
- * Called after successful transfer to airdrop budget holder
- *
- * @param {string} spenderAddress - spenderAddress
- * @param {string} airdropBudgetHolderAddress - airdropBudgetHolderAddress
- * @param {BigNumber} amount - amount in wei
- *
- * @return {Promise}
- * @ignore
- * @private
- *
- */
- _afterTransferSuccess: async function(spenderAddress, airdropBudgetHolderAddress, amount) {
- const oThis = this
- ;
-
- logger.debug('_afterTransferSuccess called with params:', {spenderAddress: spenderAddress, amount: amount});
-
- //Credit the amount to the recipient.
- await oThis.creditBalance(airdropBudgetHolderAddress, amount);
- //Debit the amount to the sender.
- await oThis.debitBalance(spenderAddress, amount);
-
- return Promise.resolve(responseHelper.successWithData({}));
- },
-
- /**
- * Called after unsuccessful transfer to airdrop budget holder
- *
- * @param {string} address - address
- * @param {BigNumber} amount - amount in wei
- *
- * @return {Promise}
- * @ignore
- * @private
- *
- */
- _afterTransferFail: function(address, amount) {
- const oThis = this
- ;
-
- logger.debug('_afterTransferFail called with params:', {address: address, amount: amount});
-
- return oThis.pessimisticDebit(address, (basicHelper.convertToBigNumber(amount)).mul(basicHelper.convertToBigNumber(-1)));
- },
-
-};
-
-module.exports = BrandedToken;
-
diff --git a/lib/contract_interact/helper.js b/lib/contract_interact/helper.js
deleted file mode 100644
index 9dbe91b..0000000
--- a/lib/contract_interact/helper.js
+++ /dev/null
@@ -1,1058 +0,0 @@
-"use strict";
-
-/**
- * This is utility class for contract interacts
- *
- * @module lib/contract_interact/helper
- */
-
-const assert = require("assert")
- , BigNumber = require('bignumber.js')
- , openSTNotification = require('@openstfoundation/openst-notification')
- , uuid = require('uuid')
-;
-
-const rootPrefix = '../..'
- , coreAddresses = require(rootPrefix+'/config/core_addresses')
- , web3EventsDecoder = require(rootPrefix+'/lib/web3/events/decoder')
- , responseHelper = require(rootPrefix + '/lib/formatter/response')
- , basicHelper = require(rootPrefix + '/helpers/basic_helper')
- , logger = require(rootPrefix + '/helpers/custom_console_logger')
- , paramErrorConfig = require(rootPrefix + '/config/param_error_config')
- , apiErrorConfig = require(rootPrefix + '/config/api_error_config')
-;
-
-const errorConfig = {
- param_error_config: paramErrorConfig,
- api_error_config: apiErrorConfig
-};
-
-/**
- * contract interact helper constructor
- *
- * @constructor
- */
-const ContractInteractHelper = function () {};
-
-ContractInteractHelper.prototype = {
- /**
- * Call methods (execute methods which DO NOT modify state of contracts)
- *
- * @param {object} web3Provider - It could be value chain or utility chain provider
- * @param {String} currContractAddr - current contract address
- * @param {Object} encodeABI - encoded method ABI data
- * @param {Object} [options] - optional params
- * @param {Object} [transactionOutputs] - optional transactionOutputs
- *
- * @return {promise}
- *
- */
- call: async function (web3Provider, currContractAddr, encodeABI, options, transactionOutputs) {
- const params = {
- to: currContractAddr,
- data: encodeABI
- };
- if (options) {
- Object.assign(params, options);
- }
-
- const response = await web3Provider.eth.call(params);
-
- if (transactionOutputs) {
- try {
- return Promise.resolve(web3Provider.eth.abi.decodeParameters(transactionOutputs, response));
- }
- catch (err) {
- return Promise.reject(err);
- }
- } else {
- return Promise.resolve(response);
- }
- },
-
- /**
- * get outputs of a given transaction
- *
- * @param {object} transactionObject - transactionObject is returned from call method.
- *
- * @return {array}
- *
- */
- getTransactionOutputs: function (transactionObject) {
- return transactionObject._method.outputs;
- },
-
- /**
- * Send methods (execute methods which modify state of a contracts)
- *
- * @param {Web3} web3Provider - It could be value chain or utility chain provider
- * @param {String} currContractAddr - current contract address
- * @param {Object} encodeABI - encoded method ABI data
- * @param {Object} [options] - optional params
- * @param {Object} [transactionOutputs] - optional transactionOutputs
- *
- * @return {promise}
- *
- */
- send: async function (web3Provider, currContractAddr, encodeABI, options, transactionOutputs) {
- const params = {
- to: currContractAddr,
- data: encodeABI
- };
- if (options) {
- Object.assign(params, options);
- }
-
- const response = web3Provider.eth.sendTransaction(params);
-
- if ( transactionOutputs ) {
- return Promise.resolve(web3Provider.eth.abi.decodeParameters(transactionOutputs, response));
- } else {
- return Promise.resolve(response);
- }
- },
-
- /**
- * @ignore
- */
- sendTxAsync: function (web3Provider, currContractAddr, encodeABI, senderName, txOptions) {
- const oThis = this
- , senderAddr = coreAddresses.getAddressForUser(senderName)
- ,senderPassphrase = coreAddresses.getPassphraseForUser(senderName)
- ;
-
- return oThis.sendTxAsyncFromAddr(web3Provider, currContractAddr, encodeABI, senderAddr, senderPassphrase, txOptions);
- },
-
- /**
- * @ignore
- */
- sendTxAsyncFromAddr: function (web3Provider, currContractAddr, encodeABI, senderAddr, senderPassphrase, txOptions) {
- const txParams = {
- from: senderAddr,
- to: currContractAddr,
- data: encodeABI
- };
- Object.assign(txParams, txOptions);
-
- return web3Provider.eth.personal.unlockAccount( senderAddr, senderPassphrase)
- .then( _ => {
- var isPromiseSettled = false;
- return new Promise(async function (onResolve, onReject) {
- try {
- web3Provider.eth.sendTransaction(txParams ,function (error, result) {
- //THIS CALLBACK IS IMPORTANT -> on('error') Does not explain the reason.
- if ( error ) {
- !isPromiseSettled && onReject( error );
- }
- })
- .on('transactionHash', txHash => {
- isPromiseSettled = true;
- onResolve( txHash );
- });
- } catch ( ex ) {
- onReject( ex );
- }
- });
- })
- .catch( reason => {
- return Promise.reject( reason );
- });
- },
-
- /**
- * Safe Send a transaction (this internally waits for transaction to be mined)
- *
- * @param {Web3} web3Provider - It could be value chain or utility chain provider
- * @param {String} currContractAddr - current contract address
- * @param {String} senderName - name of transaction's sender
- * @param {Object} encodeABI - encoded method ABI data
- * @param {Object} [txOptions] - optional txOptions
- * @param {Object} [addressToNameMap] - optional addressToNameMap
- *
- * @return {Promise}
- *
- */
- safeSend: function (web3Provider, currContractAddr, encodeABI, senderName, txOptions, addressToNameMap) {
- const oThis = this
- ;
-
- return oThis.sendTxAsync(web3Provider, currContractAddr, encodeABI, senderName, txOptions)
- .then(function(transactionHash) {
- return oThis.getTxReceipt(web3Provider, transactionHash, addressToNameMap)
- .then(function(txReceipt) {
- /*if (txReceipt.gasUsed == txOptions.gasPrice) {
- console.error("safeSend used complete gas gasPrice : " + txOptions.gasPrice);
- }
- */
- return Promise.resolve(txReceipt);
- });
- }
- );
- },
-
- /**
- * Safe Send a transaction (this internally waits for transaction to be mined)
- *
- * @param {Web3} web3Provider - It could be value chain or utility chain provider
- * @param {String} currContractAddr - current contract address
- * @param {String} senderAddr - address of transaction's sender senderAddr
- * @param {String} senderPassphrase - passphrase of
- * @param {Object} encodeABI - encoded method ABI data
- * @param {Object} [txOptions] - optional txOptions
- * @param {Object} [addressToNameMap] - optional addressToNameMap
- *
- * @return {Promise}
- *
- */
- safeSendFromAddr: function (web3Provider, currContractAddr, encodeABI, senderAddr, senderPassphrase, txOptions, addressToNameMap) {
- const oThis = this
- ;
- return oThis.sendTxAsyncFromAddr(web3Provider, currContractAddr, encodeABI, senderAddr, senderPassphrase, txOptions).then(
- function(transactionHash) {
- return oThis.getTxReceipt(web3Provider, transactionHash, addressToNameMap);
- }
- );
- },
-
- /**
- * @ignore
- */
- getTxReceipt: function(web3Provider, transactionHash, addressToNameMap) {
- return new Promise (function(onResolve, onReject) {
-
- var tryReceipt = function() {
- setTimeout( function() {
- web3Provider.eth.getTransactionReceipt(transactionHash).then(handleResponse);
- },
- 5000
- );
- };
-
- var handleResponse = function (response) {
- if (response) {
- //clearInterval(txSetInterval);
- const web3EventsDecoderResult = web3EventsDecoder.perform(response, addressToNameMap);
- onResolve(web3EventsDecoderResult);
- } else {
- tryReceipt();
- }
- };
-
- tryReceipt();
-
- });
- },
-
- /**
- * Decode result and typecast it to an Address
- *
- * @param {Web3} web3Provider - It could be value chain or utility chain provider
- * @param {String} result - current contract address
- *
- * @return {Promise}
- *
- */
- toAddress: function (web3Provider, result) {
- return new Promise(function(onResolve, onReject){
- onResolve(web3Provider.eth.abi.decodeParameter('address', result));
- });
- },
-
- /**
- * Decode result and typecast it to a String
- *
- * @param {Web3} web3Provider - It could be value chain or utility chain provider
- * @param {String} result - current contract address
- *
- * @return {Promise}
- *
- */
- toString: function (web3Provider, result) {
- return new Promise(function(onResolve, onReject){
- onResolve(web3Provider.eth.abi.decodeParameter('bytes32', result));
- });
- },
-
- /**
- * Decode result and typecast it to a Number
- *
- * @param {Web3} web3Provider - It could be value chain or utility chain provider
- * @param {String} result - current contract address
- *
- * @return {Promise}
- *
- */
- toNumber: function (web3Provider, result) {
- return new Promise(function(onResolve, onReject){
- onResolve(web3Provider.utils.hexToNumber(result));
- });
- },
-
- /**
- * @ignore
- */
- decodeUint256: function (web3Provider, result) {
- return new Promise(function(onResolve, onReject){
- onResolve(web3Provider.eth.abi.decodeParameter('uint256', result));
- });
- },
-
- /**
- * @ignore
- */
- assertAddress: function ( address ) {
- assert.ok(/^0x[0-9a-fA-F]{40}$/.test(address), `Invalid blockchain address: ${address}`);
- },
-
- /**
- * Stub method to generate managed key passphrase
- *
- * @return {String}
- *
- */
- generateManagedKeyPassphrase: function (...arg) {
- //STUB METHOD.
- //We will have some algorithm here to generate the passphrase based on passed arguments.
- //args will be inputs from various sources like foundation/member company/the enduser.
- return process.env.OST_MANAGED_KEY_PASSPHRASE;
- },
-
- /**
- * Get transaction receipt
- *
- * @param {Web3} web3Provider - It could be value chain or utility chain provider
- * @param {String} transactionHash - transaction hash
- *
- * @return {Promise}
- *
- */
- getTransactionReceiptFromTrasactionHash: function (web3Provider, transactionHash) {
- return new Promise(function(onResolve, onReject) {
- // number of times it will attempt to fetch
- var maxAttempts = 1000;
-
- // time interval
- const timeInterval = 2000;
-
- var getReceipt = async function() {
- if (maxAttempts > 0) {
- logger.debug(`\n====== Attempting to get receipt ======\n`);
- const receipt = await web3Provider.eth.getTransactionReceipt(transactionHash);
- logger.debug(`\n====== receipt: ${receipt} ======\n`);
- if (receipt) {
- logger.debug(`\n====== got the receipt ======\n`);
- return onResolve(responseHelper.successWithData({receipt: receipt}));
- } else {
- setTimeout(getReceipt, timeInterval);
- }
- } else {
- let errorParams = {
- internal_error_identifier: 'l_ci_h_pse_gtrfth',
- api_error_identifier: 'get_receipt_failed',
- error_config: errorConfig,
- debug_options: {}
- };
- logger.debug(`\n====== unable to get receipt ======\n`);
- return onResolve(responseHelper.error(errorParams));
- }
- maxAttempts--;
- };
-
-
- getReceipt();
- });
- },
-
- /**
- * Perform send
- *
- * @param {params} Object - parmaters
- * @param {returnType} string - return type
- * @param {String} senderAddr - address of transaction's sender senderAddr
- *
- * @return {Promise}
- *
- */
- performSend: function (params, returnType) {
- const oThis = this
- , notificationData = params.notificationData
- , txUUID = notificationData.message.payload.uuid
- ;
-
- var isValueReturned = false
- , processReceipt = 1
- ;
-
- if (params.processReceipt != undefined) {
- processReceipt = params.processReceipt;
- }
- const transactionObject = params.transactionObject;
-
- const encodedABI = transactionObject.encodeABI();
-
- //TODO: calculate the gas limit
- const txParams = {
- from: params.senderAddress,
- to: params.contractAddress,
- data: encodedABI,
- gasPrice: params.gasPrice,
- gas: params.gasLimit
- };
-
- // set params in notification data
- notificationData.message.payload.params.txParams = txParams;
-
- const web3Provider = params.web3Provider;
-
- const successCallback = params.successCallback;
- const failCallback = params.failCallback;
- var transactionHashRef = null;
-
-
- const notifyTransactionInitiated = function (transactionHash) {
- transactionHashRef = transactionHash;
- // set transaction hash in notification data
- // eslint-disable-next-line camelcase
- notificationData.message.payload.transaction_hash = transactionHash;
- // Publish event
- notificationData.message.kind = 'transaction_initiated';
- openSTNotification.publishEvent.perform(notificationData);
- };
-
- const notifyTrasactionMined = function (receipt) {
- // Publish event
- notificationData.message.kind = 'transaction_mined';
- notificationData.message.payload.receipt = receipt;
- openSTNotification.publishEvent.perform(notificationData);
- };
-
- const notifyTransactionError = function(errorReason) {
- // set error data in notification data
- notificationData.message.payload.error_data = errorReason;
-
- // Publish event
- notificationData.message.kind = 'transaction_error';
- openSTNotification.publishEvent.perform(notificationData);
- };
-
- const onTransactionHash = function (transactionHash) {
- notifyTransactionInitiated(transactionHash);
- const transactionResponseData = {
- transaction_uuid: txUUID,
- transaction_hash: transactionHash,
- transaction_receipt: {}
- };
-
- if (params.postReceiptProcessParams) {
- transactionResponseData.post_receipt_process_params = params.postReceiptProcessParams;
- }
-
- return responseHelper.successWithData(transactionResponseData);
- };
- const onReceiptSuccess = async function (receipt) {
- // call success callback.
- if (successCallback != undefined && successCallback != null) {
- logger.debug("======helper.Calling successCallback=======");
- await successCallback(receipt);
- }
- notifyTrasactionMined(receipt);
- return responseHelper.successWithData(
- {
- transaction_uuid: txUUID,
- transaction_hash: receipt.transactionHash,
- transaction_receipt: receipt
- });
- };
- const onReceiptFail = async function (errorCode, errorReason, receipt) {
- // call fail callback
- if (failCallback != undefined && failCallback != null) {
- logger.debug("======helper.Calling failCallback=======");
- await failCallback(receipt);
- }
- notifyTransactionError(errorReason);
-
- let errorParams = {
- internal_error_identifier: `${params.errorCode}|${errorCode}`,
- api_error_identifier: 'unhandled_api_error',
- error_config: errorConfig,
- debug_options: {}
- };
- const errorMessage = (errorReason && errorReason.message) ? errorReason.message : `Something went wrong: l_ci_h_pse`;
- logger.error(errorMessage);
- return responseHelper.error(errorParams);
-
- };
- const onReceipt = function(receipt) {
- logger.debug("\n=======receipt========\n");
- logger.debug(receipt);
- if (receipt.status == 0x1) {
- return onReceiptSuccess(receipt);
- } else {
- const errorReason = "Transaction status is 0";
- return onReceiptFail('l_ci_h_pse_status_0', errorReason, receipt);
- }
- };
-
- const onCatch = function (reason) {
- if (reason && reason.message && reason.message.includes('not mined within')) {
- oThis.getTransactionReceiptFromTrasactionHash(web3Provider, transactionHashRef).then( function(getReceiptResponse) {
- if (getReceiptResponse.isSuccess()) {
- const onReceiptResponse = onReceipt(getReceiptResponse.data.receipt);
- return onReceiptResponse;
- } else {
- const errorReason = "Unable to get receipt";
- const receiptFailResponse = onReceiptFail('l_ci_h_pse_1', errorReason, {});
- return receiptFailResponse;
- }
- });
-
- } else {
- var errorCode = 'l_ci_h_pse_2';
- if (reason && reason.message && reason.message.includes('insufficient funds for gas * price + value')) {
- errorCode = 'l_ci_h_pse_gas_low';
- reason.message = "insufficient gas"
- }
- const receiptFailResponse = onReceiptFail(errorCode, reason, {});
- return receiptFailResponse;
- }
- };
-
- if (basicHelper.isReturnTypeTxReceipt(returnType) && processReceipt==0){
- const errorCode = 'l_ci_h_pse_3'
- , reason = 'not supported for returnType=txReceipt and processReceipt=0'
- , receiptFailResponse = onReceiptFail(errorCode, reason, {})
- ;
- if (isValueReturned == false) {
- isValueReturned = true;
- return Promise.resolve(receiptFailResponse);
- }
- }
-
- /* if (processReceipt==0 && !params.postReceiptProcessParams) {
- const errorCode = 'l_ci_h_pse_4'
- , reason = 'post pay params mandatory'
- , receiptFailResponse =onReceiptFail(errorCode, reason, {});
- ;
- if (isValueReturned == false) {
- isValueReturned = true;
- return Promise.resolve(receiptFailResponse);
- }
- }
-*/
- const asyncPerform = function () {
-
- return new Promise(function (onResolve, onReject) {
- // Unlock account
- web3Provider.eth.personal.unlockAccount(
- params.senderAddress,
- params.senderPassphrase)
- .then(function() {
- if (processReceipt) {
- web3Provider.eth.sendTransaction(txParams)
- .on('transactionHash', function(transactionHash) {
- logger.debug(`\n=======transactionHash received========: ${transactionHash} \n`);
- const onTransactionHashResponse = onTransactionHash(transactionHash);
- if (basicHelper.isReturnTypeTxHash(returnType)) {
- isValueReturned = true;
- return onResolve(onTransactionHashResponse);
- }
- })
- .on('receipt', function(receipt) {
- logger.debug(`\n=======receipt received========: ${receipt} \n`);
- const onReceiptResponse = onReceipt(receipt);
- if (basicHelper.isReturnTypeTxReceipt(returnType)) {
- isValueReturned = true;
- return onResolve(onReceiptResponse);
- }
- })
- .catch( function(reason) {
- logger.error(`\n=======Exception at location 1========: ${reason} \n`);
- if (isValueReturned == false) {
- isValueReturned = true;
- return onResolve(onCatch(reason));
- }
- });
- } else {
- web3Provider.eth.sendTransaction(txParams)
- .on('transactionHash', function(transactionHash) {
- logger.debug(`\n=======transactionHash received========: ${transactionHash} \n`);
- const onTransactionHashResponse = onTransactionHash(transactionHash);
- if (basicHelper.isReturnTypeTxHash(returnType)) {
- isValueReturned = true;
- return onResolve(onTransactionHashResponse);
- }
- })
- .catch( function(reason) {
- logger.error(`\n=======Exception at location 1========: ${reason} \n`);
- if (isValueReturned == false) {
- isValueReturned = true;
- return onResolve(onCatch(reason));
- }
- });
- }
- })
- .catch(function(reason) {
- logger.error(`\n=======Exception at location 2========: ${reason} \n`);
- const receiptFailResponse =onReceiptFail('l_ci_h_pse_3', reason, {});
- if (isValueReturned == false) {
- isValueReturned = true;
- return onResolve(receiptFailResponse);
- }
- });
-
- });
-
- };
- if (basicHelper.isReturnTypeUUID(returnType)) {
- isValueReturned = true;
- asyncPerform();
- const transactionResponseData = {
- transaction_uuid: txUUID,
- transaction_hash: "",
- transaction_receipt: {}
- };
- if (params.postReceiptProcessParams) {
- transactionResponseData.post_receipt_process_params = params.postReceiptProcessParams;
- }
- return Promise.resolve(responseHelper.successWithData(transactionResponseData));
- } else {
- return asyncPerform();
- }
- },
-
- /**
- * get notification event formatted data
- *
- * @param {array} topics - topics where the event will be published
- * @param {String} publisher - publisher name
- * @param {String} method - method name
- * @param {String} contractName - name of contract
- * @param {String} contractAddress - address of contract
- * @param {Object} web3Provider - address of contract
- * @param {Object} options - options
- *
- * @return {Promise}
- *
- */
- getNotificationData: function(
- topics,
- publisher,
- method,
- contractName,
- contractAddress,
- web3Provider,
- chainId,
- options) {
-
- /*eslint-disable */
- options = options || {};
- const chainKind = '';
-
- const txUUID = uuid.v4()
- , tag = options.tag || ''
- , notificationData = {
- topics: topics,
- publisher: publisher,
- message: {
- kind: '', // populate later: with every stage
- payload: {
- contract_name: contractName,
- contract_address: contractAddress,
- method: method,
- params: {args: [], txParams: {}}, // populate later: when Tx params created
- transaction_hash: '', // populate later: when Tx submitted
- chain_id: chainId,
- chain_kind: chainKind,
- uuid: txUUID,
- tag: tag,
- error_data: {} // populate later: when error received
- }
- }
- };
- /*eslint-enable */
-
- return notificationData;
- },
-
- /**
- * valid currency
- *
- * @param {string} currency - currency
- * @param {bool} allow_blank - true / false, '' if allow_blank is true
- *
- * @return {Bool} - true / false
- */
- isValidCurrency: function(currency, allow_blank){
- if (currency === undefined || currency === null || (currency !== currency.toUpperCase())){
- return false;
- }
- allow_blank = (allow_blank || false);
- if (!allow_blank && (currency === '' || currency.length !== 3)){
- return false;
- }
- return true;
- },
-
- /** check if return type is true/false
- *
- * @param {Number} num - Number
- *
- * @return {boolean}
- *
- * Note - Don't use for BigNumbers
- */
- isDecimal: function(num) {
- return (num % 1 != 0);
- },
-
- /**
- * Validate common pay params
- *
- * @param {string} senderAddress - address of sender
- * @param {string} beneficiaryAddress - address of beneficiary account
- * @param {BigNumber} transferAmount - transfer amount (in wei)
- * @param {string} commissionBeneficiaryAddress - address of commision beneficiary account
- * @param {BigNumber} commissionAmount - commission amount (in wei)
- * @param {string} currency - quote currency
- *
- * @return {promise}
- *
- */
- validateCommonPayParams: async function (senderAddress,
- beneficiaryAddress,
- transferAmount,
- commissionBeneficiaryAddress,
- commissionAmount,
- currency) {
- const oThis = this
- ;
-
- transferAmount = new BigNumber(transferAmount);
- commissionAmount = new BigNumber(commissionAmount);
-
- if (!basicHelper.isAddressValid(senderAddress)) {
- let errorParams = {
- internal_error_identifier: 'l_ci_h_vcpp_1',
- api_error_identifier: 'invalid_api_params',
- error_config: errorConfig,
- params_error_identifiers: ['invalid_sender_address'],
- debug_options: {}
- };
-
- return Promise.reject(responseHelper.paramValidationError(errorParams));
- }
- if (transferAmount.isNaN() || !transferAmount.isInteger()) {
- let errorParams = {
- internal_error_identifier: 'l_ci_h_vcpp_2',
- api_error_identifier: 'invalid_api_params',
- error_config: errorConfig,
- params_error_identifiers: ['negative_transfer_amount'],
- debug_options: {}
- };
-
- return Promise.reject(responseHelper.paramValidationError(errorParams));
- }
- if (transferAmount.equals(0)) {
-
- let errorParams = {
- internal_error_identifier: 'l_ci_h_vcpp_3',
- api_error_identifier: 'invalid_api_params',
- error_config: errorConfig,
- params_error_identifiers: ['zero_transfer_amount'],
- debug_options: {}
- };
- return Promise.reject(responseHelper.paramValidationError(errorParams));
- }
- if (commissionAmount.isNaN() || !commissionAmount.isInteger()) {
- let errorParams = {
- internal_error_identifier: 'l_ci_h_vcpp_4',
- api_error_identifier: 'invalid_api_params',
- error_config: errorConfig,
- params_error_identifiers: ['invalid_commission_amount'],
- debug_options: {}
- };
- return Promise.reject(responseHelper.paramValidationError(errorParams));
- }
- if (!basicHelper.isAddressValid(beneficiaryAddress)) {
-
- let errorParams = {
- internal_error_identifier: 'l_ci_h_vcpp_5',
- api_error_identifier: 'invalid_api_params',
- error_config: errorConfig,
- params_error_identifiers: ['beneficiary_address_invalid'],
- debug_options: {}
- };
- return Promise.reject(responseHelper.paramValidationError(errorParams));
- }
- if (!basicHelper.isAddressValid(commissionBeneficiaryAddress)) {
- let errorParams = {
- internal_error_identifier: 'l_ci_h_vcpp_6',
- api_error_identifier: 'invalid_api_params',
- error_config: errorConfig,
- params_error_identifiers: ['commission_beneficiary_address_invalid'],
- debug_options: {}
- };
- return Promise.reject(responseHelper.paramValidationError(errorParams));
- }
- if (!oThis.isValidCurrency(currency, true)) {
- let errorParams = {
- internal_error_identifier: 'l_ci_h_vcpp_7',
- api_error_identifier: 'invalid_api_params',
- error_config: errorConfig,
- params_error_identifiers: ['invalid_currency'],
- debug_options: {}
- };
- return Promise.reject(responseHelper.paramValidationError(errorParams));
- }
-
- return Promise.resolve(responseHelper.successWithData({}));
- },
-
- /**
- * Validate Airdrop params
- *
- * @param {string} senderAddress - address of sender
- * @param {string} beneficiaryAddress - address of beneficiary account
- * @param {BigNumber} transferAmount - transfer amount (in wei)
- * @param {string} commissionBeneficiaryAddress - address of commision beneficiary account
- * @param {BigNumber} commissionAmount - commission amount (in wei)
- * @param {string} currency - quote currency
- * @param {BigNumber} intendedPricePoint - price point at which the pay is intended (in wei)
- * @param {BigNumber} gasPrice - gas price
- *
- * @return {promise}
- *
- */
- validatePayParams: async function(
- senderAddress,
- beneficiaryAddress,
- transferAmount,
- commissionBeneficiaryAddress,
- commissionAmount,
- currency,
- intendedPricePoint,
- gasPrice) {
-
- const oThis = this
- ;
-
- intendedPricePoint = new BigNumber(intendedPricePoint);
-
- await oThis.validateCommonPayParams(senderAddress,
- beneficiaryAddress,
- transferAmount,
- commissionBeneficiaryAddress,
- commissionAmount,
- currency);
-
-
- if (intendedPricePoint.isNaN() || !intendedPricePoint.isInteger()) {
- let errorParams = {
- internal_error_identifier: 'l_ci_h_vpp_8',
- api_error_identifier: 'invalid_api_params',
- error_config: errorConfig,
- params_error_identifiers: ['price_point_invalid'],
- debug_options: {}
- };
- return Promise.reject(responseHelper.paramValidationError(errorParams));
- }
- if (!gasPrice ) {
- let errorParams = {
- internal_error_identifier: 'l_ci_h_vpp_9',
- api_error_identifier: 'invalid_api_params',
- error_config: errorConfig,
- params_error_identifiers: ['gas_price_invalid'],
- debug_options: {}
- };
- return Promise.reject(responseHelper.paramValidationError(errorParams));
- }
- return Promise.resolve(responseHelper.successWithData({}));
- },
-
- /**
- * Validate Airdrop pay params
- *
- * @param {string} senderAddress - address of sender
- * @param {string} beneficiaryAddress - address of beneficiary account
- * @param {BigNumber} transferAmount - transfer amount (in wei)
- * @param {string} commissionBeneficiaryAddress - address of commision beneficiary account
- * @param {BigNumber} commissionAmount - commission amount (in wei)
- * @param {string} currency - quote currency
- * @param {BigNumber} intendedPricePoint - price point at which the pay is intended (in wei)
- * @param {BigNumber} gasPrice - gas price
- * @param {Hex} user - User address
- *
- * @return {Promise}
- *
- */
- validateAirdropPayParams: async function(
- senderAddress,
- beneficiaryAddress,
- transferAmount,
- commissionBeneficiaryAddress,
- commissionAmount,
- currency,
- intendedPricePoint,
- gasPrice,
- user) {
-
- const oThis = this
- ;
-
- await oThis.validatePayParams(senderAddress,
- beneficiaryAddress,
- transferAmount,
- commissionBeneficiaryAddress,
- commissionAmount,
- currency,
- intendedPricePoint,
- gasPrice);
-
- if (!basicHelper.isAddressValid(user)) {
- let errorParams = {
- internal_error_identifier: 'l_ci_h_vapp_2',
- api_error_identifier: 'invalid_api_params',
- error_config: errorConfig,
- params_error_identifiers: ['invalid_user_address'],
- debug_options: {}
- };
- return Promise.reject(responseHelper.paramValidationError(errorParams));
- }
-
- return Promise.resolve(responseHelper.successWithData({}));
- },
-
- /**
- * Validate post airdrop pay params
- *
- * @params {object} params -
- * @param {string} params.beneficiaryAddress - beneficiary address
- * @param {string} params.commissionBeneficiaryAddress - commission beneficiary address
- * @param {string} params.spender - spender address
- * @param {string} params.brandedTokenAddress - branded token address
- * @param {string} params.contractAddress - contractAddress address
- * @param {string} params.airdropBudgetHolder - airdrop budget holder address
- * @param {number} params.totalAmount - total amount that was debited from spender account
- * @param {number} params.airdropAmountToUse - airdrop amount that was used in the transaction
- *
- * @return {Promise}
- *
- */
-
- validatePostAirdropPayParams: function(postPayParams) {
-
- const oThis = this
- , beneficiaryAddress = postPayParams.beneficiaryAddress
- , commissionBeneficiaryAddress = postPayParams.commissionBeneficiaryAddress
- , spender = postPayParams.spender
- , brandedTokenAddress = postPayParams.brandedTokenAddress
- , contractAddress = postPayParams.contractAddress
- , totalAmount = postPayParams.totalAmount
- , airdropAmountToUse = postPayParams.airdropAmountToUse
- , airdropBudgetHolder = postPayParams.airdropBudgetHolder
- , chainId = postPayParams.chainId
- ;
-
-
- if (!basicHelper.isValidChainId(chainId)) {
- let errorParams = {
- internal_error_identifier: 'l_ci_h_vapp_1',
- api_error_identifier: 'invalid_api_params',
- error_config: errorConfig,
- params_error_identifiers: ['chain_id_invalid'],
- debug_options: {}
- };
- return responseHelper.paramValidationError(errorParams);
- }
- if (!basicHelper.isAddressValid(beneficiaryAddress)) {
- let errorParams = {
- internal_error_identifier: 'l_ci_h_vapp_2',
- api_error_identifier: 'invalid_api_params',
- error_config: errorConfig,
- params_error_identifiers: ['beneficiary_address_invalid'],
- debug_options: {}
- };
- return responseHelper.paramValidationError(errorParams);
- }
- if (!basicHelper.isAddressValid(commissionBeneficiaryAddress)) {
- let errorParams = {
- internal_error_identifier: 'l_ci_h_vapp_3',
- api_error_identifier: 'invalid_api_params',
- error_config: errorConfig,
- params_error_identifiers: ['commission_beneficiary_address_invalid'],
- debug_options: {}
- };
- return responseHelper.paramValidationError(errorParams);
- }
- if (!basicHelper.isAddressValid(spender)) {
- let errorParams = {
- internal_error_identifier: 'l_ci_h_vapp_4',
- api_error_identifier: 'invalid_api_params',
- error_config: errorConfig,
- params_error_identifiers: ['invalid_spender_address'],
- debug_options: {}
- };
- return responseHelper.paramValidationError(errorParams);
- }
- if (!basicHelper.isAddressValid(brandedTokenAddress)) {
- let errorParams = {
- internal_error_identifier: 'l_ci_h_vapp_5',
- api_error_identifier: 'invalid_api_params',
- error_config: errorConfig,
- params_error_identifiers: ['branded_token_address_invalid'],
- debug_options: {}
- };
- return responseHelper.paramValidationError(errorParams);
- }
- if (!basicHelper.isAddressValid(contractAddress)) {
-
- let errorParams = {
- internal_error_identifier: 'l_ci_h_vapp_6',
- api_error_identifier: 'invalid_api_params',
- error_config: errorConfig,
- params_error_identifiers: ['branded_token_address_invalid'],
- debug_options: {}
- };
- return responseHelper.paramValidationError(errorParams);
- }
- if (!basicHelper.isAddressValid(airdropBudgetHolder)) {
- let errorParams = {
- internal_error_identifier: 'l_ci_h_vapp_7',
- api_error_identifier: 'invalid_api_params',
- error_config: errorConfig,
- params_error_identifiers: ['airdrop_budget_holder_invalid'],
- debug_options: {}
- };
- return responseHelper.paramValidationError(errorParams);
- }
-
- const bnTotalAmount = new BigNumber(totalAmount);
- if (bnTotalAmount.isNaN() || !bnTotalAmount.isInteger()) {
- let errorParams = {
- internal_error_identifier: 'l_ci_h_vapp_9',
- api_error_identifier: 'invalid_api_params',
- error_config: errorConfig,
- params_error_identifiers: ['total_amount_invalid'],
- debug_options: {}
- };
- return responseHelper.paramValidationError(errorParams);
- }
-
- const bnAirdropAmountToUse = new BigNumber(airdropAmountToUse);
- if (bnAirdropAmountToUse.isNaN() || !bnAirdropAmountToUse.isInteger()) {
- let errorParams = {
- internal_error_identifier: 'l_ci_h_vapp_10',
- api_error_identifier: 'invalid_api_params',
- error_config: errorConfig,
- params_error_identifiers: ['airdrop_amount_invalid'],
- debug_options: {}
- };
- return responseHelper.paramValidationError(errorParams);
- }
-
- return responseHelper.successWithData({});
- }
-};
-
-module.exports = new ContractInteractHelper();
diff --git a/lib/contract_interact/ops_managed_contract.js b/lib/contract_interact/ops_managed_contract.js
deleted file mode 100644
index d29f24f..0000000
--- a/lib/contract_interact/ops_managed_contract.js
+++ /dev/null
@@ -1,142 +0,0 @@
-"use strict";
-
-/**
- * This is a utility file which would be used for executing all methods on OpsManaged Contract.
- *
- * @module lib/contract_interact/ops_managed_contract
- */
-
-const rootPrefix = '../..'
- , helper = require(rootPrefix + '/lib/contract_interact/helper')
- , coreAddresses = require(rootPrefix + '/config/core_addresses')
- , basicHelper = require(rootPrefix + '/helpers/basic_helper')
- , coreConstants = require(rootPrefix + '/config/core_constants')
- , web3Provider = require(rootPrefix + '/lib/web3/providers/ws')
- , notificationGlobalConstant = require(rootPrefix + '/lib/global_constant/notification')
- , gasLimitGlobalConstant = require(rootPrefix + '/lib/global_constant/gas_limit')
- , logger = require(rootPrefix + '/helpers/custom_console_logger')
- , responseHelper = require(rootPrefix + '/lib/formatter/response')
- , OwnedContract = require(rootPrefix + '/lib/contract_interact/owned_contract')
- , paramErrorConfig = require(rootPrefix + '/config/param_error_config')
- , apiErrorConfig = require(rootPrefix + '/config/api_error_config')
-;
-
-const errorConfig = {
- param_error_config: paramErrorConfig,
- api_error_config: apiErrorConfig
-};
-
-const contractName = 'opsManaged'
- , contractAbi = coreAddresses.getAbiForContract(contractName)
- , currContract = new web3Provider.eth.Contract(contractAbi)
-;
-
-/**
- * Ops managed contract interact constructor
- *
- * @param {string} contractAddress - address where Contract has been deployed
- * @param {string} defaultGasPrice - default Gas Price
- * @param {number} chainId - chain id
- *
- * @constructor
- * @augments OwnedContract
- *
- */
-const OpsManagedContract = function (contractAddress, defaultGasPrice, chainId) {
- this.contractAddress = contractAddress;
- this.web3Provider = web3Provider;
- this.currContract = currContract;
- this.defaultGasPrice = defaultGasPrice;
- this.currContract.options.address = contractAddress;
- //this.currContract.setProvider(web3Provider.currentProvider);
- this.chainId = chainId;
- OwnedContract.call(this, contractAddress, web3Provider, currContract, defaultGasPrice);
-};
-
-OpsManagedContract.prototype = Object.create(OwnedContract.prototype);
-
-OpsManagedContract.prototype.constructor = OpsManagedContract;
-
-/**
- * Get currContract's Ops Address
- *
- * @return {promise}
- *
- */
-OpsManagedContract.prototype.getOpsAddress = async function() {
- try {
- const transactionObject = this.currContract.methods.opsAddress()
- , encodedABI = transactionObject.encodeABI()
- , transactionOutputs = helper.getTransactionOutputs( transactionObject )
- , response = await helper.call(this.web3Provider, this.contractAddress, encodedABI, {}, transactionOutputs);
-
- return Promise.resolve(responseHelper.successWithData({opsAddress: response[0]}));
- } catch(err) {
- let errorParams = {
- internal_error_identifier: 'l_ci_omc_getOpsAddress_1',
- api_error_identifier: 'unhandled_api_error',
- error_config: errorConfig,
- debug_options: {}
- };
- logger.error('lib/contract_interact/ops_managed_contract.js:getOpsAddress inside catch:', err);
- return Promise.resolve(responseHelper.error(errorParams));
- }
-};
-
-/**
- * Set currContract's Ops Address
- *
- * @param {string} senderAddress - Sender Address
- * @param {String} senderPassphrase - Sender Passphrase
- * @param {String} opsAddress - address which is to be made Ops Address of currContract
- * @param {Object} options - options for this transaction
- *
- * @return {promise}
- *
- */
-OpsManagedContract.prototype.setOpsAddress = async function(senderAddress, senderPassphrase, opsAddress, options) {
- const oThis = this
- ;
-
- try {
- const returnType = basicHelper.getReturnType(options.returnType)
- , transactionObject = oThis.currContract.methods.setOpsAddress(opsAddress);
-
- const notificationData = helper.getNotificationData(
- ['payments.opsManaged.setOpsAddress'],
- notificationGlobalConstant.publisher(),
- 'setOpsAddress',
- contractName,
- oThis.contractAddress,
- web3Provider,
- oThis.chainId,
- options);
-
- const params = {
- transactionObject: transactionObject,
- notificationData: notificationData,
- senderAddress: senderAddress,
- senderPassphrase: senderPassphrase,
- contractAddress: oThis.contractAddress,
- gasPrice: oThis.defaultGasPrice,
- gasLimit: gasLimitGlobalConstant.setOps(),
- web3Provider: web3Provider,
- successCallback: null,
- failCallback: null,
- errorCode: "l_ci_omc_setOpsAddress_1"
- };
-
- return Promise.resolve(helper.performSend(params, returnType));
- } catch(err) {
- let errorParams = {
- internal_error_identifier: 'l_ci_omc_setOpsAddress_2',
- api_error_identifier: 'unhandled_api_error',
- error_config: errorConfig,
- debug_options: {}
- };
- logger.error('lib/contract_interact/ops_managed_contract.js:setOpsAddress inside catch:', err);
- return Promise.resolve(responseHelper.error(errorParams));
- }
-};
-
-module.exports = OpsManagedContract;
\ No newline at end of file
diff --git a/lib/contract_interact/owned_contract.js b/lib/contract_interact/owned_contract.js
deleted file mode 100644
index 9b1f3da..0000000
--- a/lib/contract_interact/owned_contract.js
+++ /dev/null
@@ -1,105 +0,0 @@
-"use strict";
-
-/**
- * This is a utility file which would be used for executing all methods on Owned Contract.
- *
- * @module lib/contract_interact/owned_contract
- */
-
-const rootPrefix = '../..'
- , helper = require(rootPrefix + '/lib/contract_interact/helper')
- , responseHelper = require(rootPrefix + '/lib/formatter/response')
- , paramErrorConfig = require(rootPrefix + '/config/param_error_config')
- , apiErrorConfig = require(rootPrefix + '/config/api_error_config')
-;
-
-const errorConfig = {
- param_error_config: paramErrorConfig,
- api_error_config: apiErrorConfig
-};
-
-/**
- * Owned contract interact constructor
- *
- * @param {String} contractAddress - address where Contract has been deployed
- * @param {String} web3Provider - web3 provider of network where currContract has been deployed
- * @param {String} currContract - Contract Instance
- * @param {String} defaultGasPrice - default Gas Price
- *
- * @constructor
- */
-const OwnedContract = function (contractAddress, web3Provider, currContract, defaultGasPrice) {
- this.contractAddress = contractAddress;
- this.web3Provider = web3Provider;
- this.currContract = currContract;
- this.defaultGasPrice = defaultGasPrice;
- this.currContract.options.address = contractAddress;
- //this.currContract.setProvider( web3Provider.currentProvider );
-};
-
-OwnedContract.prototype = {
- /**
- * Initiate Ownership of currContract
- *
- * @param {string} senderName - Sender of this Transaction
- * @param {string} proposedOwner - address to which ownership needs to be transferred
- * @param {object} customOptions - custom params of this transaction
- *
- * @return {promise}
- *
- */
- initiateOwnerShipTransfer: async function(senderName, proposedOwner, customOptions) {
- try {
- const encodedABI = this.currContract.methods.initiateOwnershipTransfer(proposedOwner).encodeABI()
- , options = { gasPrice: this.defaultGasPrice };
-
- Object.assign(options, customOptions);
-
- const transactionResponse = await helper.safeSend(
- this.web3Provider,
- this.contractAddress,
- encodedABI,
- senderName,
- options
- );
-
- return Promise.resolve(transactionResponse);
- } catch(err) {
- let errorParams = {
- internal_error_identifier: 'l_ci_oc_initiateOwnerShipTransfer_1',
- api_error_identifier: 'unhandled_api_error',
- error_config: errorConfig,
- debug_options: {}
- };
- logger.error('lib/contract_interact/owned_contract.js:initiateOwnerShipTransfer inside catch:', err);
- return Promise.resolve(responseHelper.error(errorParams));
- }
- },
-
- /**
- * Get address of Owner of currContract
- *
- * @return {promise}
- */
- getOwner: async function() {
- try {
- const transactionObject = this.currContract.methods.proposedOwner()
- , encodedABI = transactionObject.encodeABI()
- , transactionOutputs = helper.getTransactionOutputs( transactionObject )
- , response = await helper.call(this.web3Provider, this.contractAddress, encodedABI, {}, transactionOutputs);
-
- return Promise.resolve(responseHelper.successWithData({owner: response[0]}));
- } catch(err) {
- let errorParams = {
- internal_error_identifier: 'l_ci_oc_getOwner_1',
- api_error_identifier: 'unhandled_api_error',
- error_config: errorConfig,
- debug_options: {}
- };
- logger.error('lib/contract_interact/owned_contract.js:getOwner inside catch:', err);
- return Promise.resolve(responseHelper.error(errorParams));
- }
- }
-};
-
-module.exports = OwnedContract;
\ No newline at end of file
diff --git a/lib/contract_interact/pricer.js b/lib/contract_interact/pricer.js
deleted file mode 100644
index 3ab4b93..0000000
--- a/lib/contract_interact/pricer.js
+++ /dev/null
@@ -1,1346 +0,0 @@
-"use strict";
-
-/**
- *
- * This is a utility file which would be used for executing all methods on Pricer contract.
- *
- * @module lib/contract_interact/pricer
- *
- */
-
-const BigNumber = require('bignumber.js')
-;
-
-const rootPrefix = '../..'
- , Token = require(rootPrefix + '/lib/contract_interact/branded_token')
- , basicHelper = require(rootPrefix + '/helpers/basic_helper')
- , coreAddresses = require(rootPrefix + '/config/core_addresses')
- , coreConstants = require(rootPrefix + '/config/core_constants')
- , web3EventsDecoder = require(rootPrefix + '/lib/web3/events/decoder')
- , helper = require(rootPrefix + '/lib/contract_interact/helper')
- , responseHelper = require(rootPrefix + '/lib/formatter/response')
- , web3Provider = require(rootPrefix + '/lib/web3/providers/ws')
- , logger = require(rootPrefix + '/helpers/custom_console_logger')
- , TrasactionHelperKlass = require(rootPrefix + '/lib/transaction_helper')
- , PricerCacheKlass = require(rootPrefix + '/lib/cache_management/pricer')
- , eventGlobalConstants = require(rootPrefix+'/lib/global_constant/events')
- , notificationGlobalConstant = require(rootPrefix + '/lib/global_constant/notification')
- , gasLimitGlobalConstant = require(rootPrefix + '/lib/global_constant/gas_limit')
- , paramErrorConfig = require(rootPrefix + '/config/param_error_config')
- , apiErrorConfig = require(rootPrefix + '/config/api_error_config')
-;
-
-const errorConfig = {
- param_error_config: paramErrorConfig,
- api_error_config: apiErrorConfig
-};
-
-const contractAbi = coreAddresses.getAbiForContract('pricer')
- , currContract = new web3Provider.eth.Contract(contractAbi)
-;
-
-/**
- * @constructor
- *
- * @param {string} pricerAddress - Pricer contract address
- * @param {string} chainId - chain ID
- *
- */
-const Pricer = function (pricerAddress, chainId) {
- const oThis = this
- ;
-
- oThis.addressToNameMap = {};
- oThis.contractAddress = pricerAddress;
- oThis.chainId = chainId;
- oThis.contractName = 'pricer';
-
- oThis.pricerCache = new PricerCacheKlass(chainId, pricerAddress);
- oThis.transactionHelper = new TrasactionHelperKlass(chainId);
-};
-
-Pricer.prototype = {
- // Define all the properties
- /**
- * contract address
- * @ignore
- */
- contractAddress: null,
-
- /**
- * chain id
- * @ignore
- */
- chainId: null,
-
- /**
- * token object
- * @ignore
- */
- token: null,
-
- /**
- * address to name map
- * @ignore
- */
- addressToNameMap: null,
-
- /**
- * transaction helper object
- * @ignore
- */
- transactionHelper: null,
-
- /**
- * pricer cache object
- * @ignore
- */
- pricerCache: null,
-
- /**
- * set address to name map
- *
- * @return {promise}
- *
- */
- setAddressToNameMap: async function() {
- const oThis = this
- ;
-
- if(Object.keys(oThis.addressToNameMap).length === 0) {
- const brandedTokenResponse = await oThis.brandedToken();
-
- if (brandedTokenResponse.isSuccess()) {
- const tokenAddress = brandedTokenResponse.data.brandedToken;
- oThis.addressToNameMap[tokenAddress.toLowerCase()] = 'brandedToken';
-
- oThis.addressToNameMap[oThis.contractAddress.toLowerCase()] = oThis.contractName;
-
- return Promise.resolve(responseHelper.successWithData({addressToNameMap: oThis.addressToNameMap}));
- } else {
- return Promise.resolve(brandedTokenResponse);
- }
- } else {
- return Promise.resolve(responseHelper.successWithData({addressToNameMap: oThis.addressToNameMap}));
- }
- },
-
- /**
- * set token object
- *
- * @return {promise}
- *
- */
- setTokenObj: async function() {
- const oThis = this
- ;
-
- if(!oThis.token) {
- const brandedTokenResponse = await oThis.brandedToken();
-
- if (brandedTokenResponse.isSuccess()) {
- const tokenAddress = brandedTokenResponse.data.brandedToken;
- oThis.token = new Token(tokenAddress, oThis.chainId);
- return Promise.resolve(responseHelper.successWithData({token: oThis.token}));
- } else {
- return Promise.resolve(brandedTokenResponse);
- }
- } else {
- return Promise.resolve(responseHelper.successWithData({token: oThis.token}));
- }
- },
-
- /**
- * Get branded token address of pricer from cache, if not found in cache get from contract
- *
- * @return {promise}
- *
- */
- brandedToken: async function () {
- const oThis = this
- ;
- try{
- const cacheResult = await oThis.pricerCache.getBrandedTokenAddress();
-
- if (cacheResult.isSuccess() && cacheResult.data.response != null) {
- return Promise.resolve(responseHelper.successWithData({brandedToken: cacheResult.data.response}));
- } else {
- const getBrandedTokenAddressFromContractResponse = await oThis.getBrandedTokenAddressFromContract();
- if (getBrandedTokenAddressFromContractResponse.isSuccess()) {
- await oThis.pricerCache.setBrandedTokenAddress(getBrandedTokenAddressFromContractResponse.data.brandedToken);
- }
- return Promise.resolve(getBrandedTokenAddressFromContractResponse);
- }
- } catch(err) {
- let errorParams = {
- internal_error_identifier: 'l_ci_p_brandedToken_1',
- api_error_identifier: 'unhandled_api_error',
- error_config: errorConfig,
- debug_options: {}
- };
- logger.error("lib/contract_interact/pricer.js:brandedToken inside catch ", err);
- return Promise.resolve(responseHelper.error(errorParams));
- }
- },
-
- /**
- * Get branded token address of pricer from contract
- *
- * @return {promise}
- *
- */
- getBrandedTokenAddressFromContract: async function() {
- const transactionObject = currContract.methods.brandedToken()
- , encodedABI = transactionObject.encodeABI()
- , transactionOutputs = helper.getTransactionOutputs(transactionObject)
- , response = await helper.call(web3Provider, this.contractAddress, encodedABI, {}, transactionOutputs);
-
- return Promise.resolve(responseHelper.successWithData({brandedToken: response[0]}));
- },
-
- /**
- * Get acceptable margin for the given currency
- *
- * @param {string} currency - quote currency
- *
- * @return {promise}
- *
- */
- acceptedMargins: async function (currency) {
- const oThis = this;
-
- try {
- if (!helper.isValidCurrency(currency, false)) {
-
- let errorParams = {
- internal_error_identifier: 'l_ci_p_acceptedMargins_1',
- api_error_identifier: 'invalid_api_params',
- error_config: errorConfig,
- params_error_identifiers: ['invalid_currency'],
- debug_options: {}
- };
- return Promise.resolve(responseHelper.paramValidationError(errorParams));
- }
-
- const cacheResult = await oThis.pricerCache.getAcceptedMargins(currency);
- if (cacheResult.isSuccess() && cacheResult.data.response != null) {
- return Promise.resolve(responseHelper.successWithData({acceptedMargins: cacheResult.data.response}));
- } else {
- const getAcceptedMarginsFromContractResponse = await oThis.getAcceptedMarginsFromContract(currency);
- if (getAcceptedMarginsFromContractResponse.isSuccess()) {
- await oThis.pricerCache.setAcceptedMargins(currency, getAcceptedMarginsFromContractResponse.data.acceptedMargins);
- }
- return Promise.resolve(getAcceptedMarginsFromContractResponse);
- }
- } catch(err) {
- let errorParams = {
- internal_error_identifier: 'l_ci_p_acceptedMargins_2',
- api_error_identifier: 'unhandled_api_error',
- error_config: errorConfig,
- debug_options: {}
- };
- //Format the error
- logger.error("lib/contract_interact/pricer.js:acceptedMargins inside catch ", err);
- return Promise.resolve(responseHelper.error(errorParams));
- }
-
- },
-
- /**
- * Get acceptable margin for the given currency from contract
- *
- * @param {string} currency - quote currency
- *
- * @return {promise}
- *
- */
- getAcceptedMarginsFromContract: async function (currency) {
- const oThis = this
- ;
-
- if (!helper.isValidCurrency(currency, false)) {
- let errorParams = {
- internal_error_identifier: 'l_ci_p_getAcceptedMarginsFromContract_1',
- api_error_identifier: 'invalid_api_params',
- error_config: errorConfig,
- params_error_identifiers: ['invalid_currency'],
- debug_options: {}
- };
- return Promise.resolve(responseHelper.paramValidationError(errorParams));
- }
-
- const transactionObject = currContract.methods.acceptedMargins(web3Provider.utils.asciiToHex(currency))
- , encodedABI = transactionObject.encodeABI()
- , transactionOutputs = helper.getTransactionOutputs(transactionObject)
- , response = await helper.call(web3Provider, this.contractAddress, encodedABI, {}, transactionOutputs);
-
- return Promise.resolve(responseHelper.successWithData({acceptedMargins: response[0]}));
- },
-
- /**
- * Get address of price oracle for the given currency
- *
- * @param {string} currency - quote currency
- *
- * @return {promise}
- *
- */
- priceOracles: async function (currency) {
- const oThis = this
- ;
-
- try {
- if (!helper.isValidCurrency(currency, false)) {
- let errorParams = {
- internal_error_identifier: 'l_ci_p_priceOracles_1',
- api_error_identifier: 'invalid_api_params',
- error_config: errorConfig,
- params_error_identifiers: ['invalid_currency'],
- debug_options: {}
- };
- return Promise.resolve(responseHelper.paramValidationError(errorParams));
- }
-
- const cacheResult = await oThis.pricerCache.getPriceOracles(currency);
- if (cacheResult.isSuccess() && cacheResult.data.response != null) {
- return Promise.resolve(responseHelper.successWithData({priceOracles: cacheResult.data.response}));
- } else {
- const getPriceOraclesFromContractResponse = await oThis.getPriceOraclesFromContract(currency);
-
- if (getPriceOraclesFromContractResponse.isSuccess()) {
- await oThis.pricerCache.setPriceOracles(currency, getPriceOraclesFromContractResponse.data.priceOracles);
- }
-
- return Promise.resolve(getPriceOraclesFromContractResponse);
- }
- } catch(err) {
-
- let errorParams = {
- internal_error_identifier: 'l_ci_p_priceOracles_2',
- api_error_identifier: 'unhandled_api_error',
- error_config: errorConfig,
- debug_options: {}
- };
- //Format the error
- logger.error("lib/contract_interact/pricer.js:priceOracles inside catch ", err);
- return Promise.resolve(responseHelper.error(errorParams));
- }
- },
-
- /**
- * Get address of price oracle for the given currency from contract
- *
- * @param {string} currency - quote currency
- *
- * @return {promise}
- *
- */
- getPriceOraclesFromContract: async function (currency) {
- if (!helper.isValidCurrency(currency, false)) {
-
- let errorParams = {
- internal_error_identifier: 'l_ci_p_getPriceOraclesFromContract_1',
- api_error_identifier: 'invalid_api_params',
- error_config: errorConfig,
- params_error_identifiers: ['invalid_currency'],
- debug_options: {}
- };
- return Promise.resolve(responseHelper.error(errorParams));
- }
-
- const transactionObject = currContract.methods.priceOracles(web3Provider.utils.asciiToHex(currency))
- , encodedABI = transactionObject.encodeABI()
- , transactionOutputs = helper.getTransactionOutputs(transactionObject)
- , response = await helper.call(web3Provider, this.contractAddress, encodedABI, {}, transactionOutputs);
-
- return Promise.resolve(responseHelper.successWithData({priceOracles: response[0]}));
- },
-
- /**
- * Get base currency of pricer
- *
- * @return {promise}
- *
- */
- baseCurrency: async function () {
- const transactionObject = currContract.methods.baseCurrency()
- , encodedABI = transactionObject.encodeABI()
- , transactionOutputs = helper.getTransactionOutputs(transactionObject)
- , response = await helper.call(web3Provider, this.contractAddress, encodedABI, {}, transactionOutputs);
-
- return Promise.resolve(responseHelper.successWithData(
- {baseCurrency: response[0], symbol: web3Provider.utils.hexToString(response[0])}));
- },
-
- /**
- * Get decimal of pricer
- *
- * @return {promise}
- *
- */
- decimals: async function () {
- const oThis = this
- ;
-
- try {
- const cacheResult = await oThis.pricerCache.getDecimals();
-
- if(cacheResult.isSuccess() && cacheResult.data.response != null) {
- return Promise.resolve(responseHelper.successWithData({decimals: cacheResult.data.response}));
- } else {
- const getDecimalsFromContractResponse = await oThis.getDecimalsFromContract();
-
- if (getDecimalsFromContractResponse.isSuccess()) {
- await oThis.pricerCache.setDecimals(getDecimalsFromContractResponse.data.decimals);
- }
- return Promise.resolve(getDecimalsFromContractResponse);
- }
- } catch(err) {
- let errorParams = {
- internal_error_identifier: 'l_ci_p_decimals_1',
- api_error_identifier: 'unhandled_api_error',
- error_config: errorConfig,
- debug_options: {}
- };
- //Format the error
- logger.error("lib/contract_interact/pricer.js:decimals inside catch ", err);
- return Promise.resolve(responseHelper.error(errorParams));
- }
- },
-
- /**
- * Get decimal of pricer from contract
- *
- * @return {promise}
- *
- */
- getDecimalsFromContract: async function () {
- const transactionObject = currContract.methods.decimals()
- , encodedABI = transactionObject.encodeABI()
- , transactionOutputs = helper.getTransactionOutputs(transactionObject)
- , response = await helper.call(web3Provider, this.contractAddress, encodedABI, {}, transactionOutputs);
-
- return Promise.resolve(responseHelper.successWithData({decimals: response[0]}));
- },
-
- /**
- * Get conversion rate of pricer
- *
- * @return {promise}
- *
- */
- conversionRate: async function () {
- const oThis = this
- ;
-
- try {
- const cacheResult = await oThis.pricerCache.getConversionRate();
-
- if (cacheResult.isSuccess() && cacheResult.data.response != null) {
- return Promise.resolve(responseHelper.successWithData({conversionRate: cacheResult.data.response}));
- } else {
- const getConversionRateFromContractResponse = await oThis.getConversionRateFromContract();
- if (getConversionRateFromContractResponse.isSuccess()) {
- await oThis.pricerCache.setConversionRate(getConversionRateFromContractResponse.data.conversionRate);
- }
-
- return Promise.resolve(getConversionRateFromContractResponse);
- }
- } catch(err) {
- let errorParams = {
- internal_error_identifier: 'l_ci_p_conversionRate_1',
- api_error_identifier: 'unhandled_api_error',
- error_config: errorConfig,
- debug_options: {}
- };
- //Format the error
- logger.error("lib/contract_interact/pricer.js:conversionRate inside catch ", err);
- return Promise.resolve(responseHelper.error(errorParams));
- }
- },
-
- /**
- * Get conversion rate of pricer from contract
- *
- * @return {promise}
- *
- */
- getConversionRateFromContract: async function () {
- const transactionObject = currContract.methods.conversionRate()
- , encodedABI = transactionObject.encodeABI()
- , transactionOutputs = helper.getTransactionOutputs(transactionObject)
- , response = await helper.call(web3Provider, this.contractAddress, encodedABI, {}, transactionOutputs);
-
- return Promise.resolve(responseHelper.successWithData({conversionRate: response[0]}));
- },
-
- /**
- * Get conversion rate decimals of pricer
- *
- * @return {promise}
- *
- */
- conversionRateDecimals: async function () {
- const oThis = this
- ;
-
- try {
- const cacheResult = await oThis.pricerCache.getConversionRateDecimals();
-
- if (cacheResult.isSuccess() && cacheResult.data.response != null) {
- return Promise.resolve(responseHelper.successWithData({conversionRateDecimals: cacheResult.data.response}));
- } else {
- const getConversionRateDecimalsFromContractResponse = await oThis.getConversionRateDecimalsFromContract();
- if (getConversionRateDecimalsFromContractResponse.isSuccess()) {
- await oThis.pricerCache.setConversionRateDecimals(
- getConversionRateDecimalsFromContractResponse.data.conversionRateDecimals);
- }
-
- return Promise.resolve(getConversionRateDecimalsFromContractResponse);
- }
- } catch(err) {
- let errorParams = {
- internal_error_identifier: 'l_ci_p_conversionRateDecimals_1',
- api_error_identifier: 'unhandled_api_error',
- error_config: errorConfig,
- debug_options: {}
- };
- //Format the error
- logger.error("lib/contract_interact/pricer.js:conversionRateDecimals inside catch ", err);
- return Promise.resolve(responseHelper.error(errorParams));
- }
- },
-
-
- /**
- * Get conversion rate decimals of pricer from contract
- *
- * @return {promise}
- *
- */
- getConversionRateDecimalsFromContract: async function () {
- const transactionObject = currContract.methods.conversionRateDecimals()
- , encodedABI = transactionObject.encodeABI()
- , transactionOutputs = helper.getTransactionOutputs(transactionObject)
- , response = await helper.call(web3Provider, this.contractAddress, encodedABI, {}, transactionOutputs);
-
- return Promise.resolve(responseHelper.successWithData({conversionRateDecimals: response[0]}));
- },
-
- /**
- * Validate set price oracle parameters
- *
- * @param {string} senderAddress - address of sender
- * @param {string} currency - quote currency
- * @param {string} address - address of price pracle
- * @param {BigNumber} gasPrice - gas price
- *
- * @return {result}
- *
- */
- validateSetPriceOracleParams: function (senderAddress, currency, address, gasPrice) {
- if (!helper.isValidCurrency(currency, false)) {
- let errorParams = {
- internal_error_identifier: 'l_ci_p_validateSetPriceOracleParams_1',
- api_error_identifier: 'invalid_api_params',
- error_config: errorConfig,
- params_error_identifiers: ['invalid_currency'],
- debug_options: {}
- };
- return responseHelper.error(errorParams);
- }
-
- if (!gasPrice) {
- let errorParams = {
- internal_error_identifier: 'l_ci_p_validateSetPriceOracleParams_2',
- api_error_identifier: 'invalid_api_params',
- error_config: errorConfig,
- params_error_identifiers: ['gas_price_invalid'],
- debug_options: {}
- };
- return responseHelper.paramValidationError(errorParams);
- }
-
- if (!basicHelper.isAddressValid(address)) {
- let errorParams = {
- internal_error_identifier: 'l_ci_p_validateSetPriceOracleParams_3',
- api_error_identifier: 'contract_address_invalid',
- error_config: errorConfig,
- debug_options: {}
- };
- return responseHelper.error(errorParams);
- }
-
- if (!basicHelper.isAddressValid(senderAddress)) {
- let errorParams = {
- internal_error_identifier: 'l_ci_p_validateSetPriceOracleParams_4',
- api_error_identifier: 'invalid_api_params',
- error_config: errorConfig,
- params_error_identifiers: ['invalid_sender_address'],
- debug_options: {}
- };
- return responseHelper.paramValidationError(errorParams);
- }
-
- return responseHelper.successWithData({});
- },
-
- /**
- * Set or updates the price oracle address for a given currency
- *
- * @param {string} senderAddress - address of sender
- * @param {string} senderPassphrase - passphrase of sender
- * @param {string} currency - quote currency
- * @param {string} address - address of price pracle
- * @param {BigNumber} gasPrice - gas price
- * @param {object} options - for params like returnType, tag.
- *
- * @return {promise}
- *
- */
- setPriceOracle: function (senderAddress, senderPassphrase, currency, address, gasPrice, options) {
- const oThis = this
- ;
-
- const validationResponse = oThis.validateSetPriceOracleParams(senderAddress, currency, address, gasPrice);
-
- if (validationResponse.isFailure()) return Promise.resolve(validationResponse);
-
- const returnType = basicHelper.getReturnType(options.returnType);
-
- const transactionObject = currContract.methods.setPriceOracle(
- web3Provider.utils.asciiToHex(currency),
- address);
-
- const notificationData = helper.getNotificationData(
- ['payments.pricer.setPriceOracle'],
- notificationGlobalConstant.publisher(),
- 'setPriceOracle',
- oThis.contractName,
- oThis.contractAddress,
- web3Provider,
- oThis.chainId,
- options);
-
- const successCallback = function(receipt) {
- return oThis.pricerCache.clearPriceOracles(currency);
- };
-
- const params = {
- transactionObject: transactionObject,
- notificationData: notificationData,
- senderAddress: senderAddress,
- senderPassphrase: senderPassphrase,
- contractAddress: oThis.contractAddress,
- gasPrice: gasPrice,
- gasLimit: gasLimitGlobalConstant.setPriceOracle(),
- web3Provider: web3Provider,
- successCallback: successCallback,
- failCallback: null,
- errorCode: "l_ci_p_spo_5"
- };
-
- return helper.performSend(params, returnType);
- },
-
-
- /**
- * Validate unset price oracle parameters
- *
- * @param {string} senderAddress - address of sender
- * @param {string} currency - quote currency
- * @param {BigNumber} gasPrice - gas price
- *
- * @return {promise}
- *
- */
- validateUnsetPriceOracleParams: function (senderAddress, currency, gasPrice) {
- if (!helper.isValidCurrency(currency, false)) {
- let errorParams = {
- internal_error_identifier: 'l_ci_p_validateUnsetPriceOracleParams_1',
- api_error_identifier: 'invalid_api_params',
- error_config: errorConfig,
- params_error_identifiers: ['invalid_currency'],
- debug_options: {}
- };
- return responseHelper.paramValidationError(errorParams);
- }
-
- if (!gasPrice) {
- let errorParams = {
- internal_error_identifier: 'l_ci_p_validateUnsetPriceOracleParams_2',
- api_error_identifier: 'invalid_api_params',
- error_config: errorConfig,
- params_error_identifiers: ['gas_price_invalid'],
- debug_options: {}
- };
- return responseHelper.paramValidationError(errorParams);
- }
-
- if (!basicHelper.isAddressValid(senderAddress)) {
- let errorParams = {
- internal_error_identifier: 'l_ci_p_validateUnsetPriceOracleParams_3',
- api_error_identifier: 'invalid_api_params',
- error_config: errorConfig,
- params_error_identifiers: ['invalid_sender_address'],
- debug_options: {}
- };
- return responseHelper.error(errorParams);
- }
-
- return responseHelper.successWithData({});
- },
-
- /**
- * Remove the price oracle address for a given currency
- *
- * @param {string} senderAddress - address of sender
- * @param {string} senderPassphrase - passphrase of sender
- * @param {string} currency - quote currency
- * @param {BigNumber} gasPrice - gas price
- * @param {object} options - for params like returnType, tag.
- *
- * @return {promise}
- *
- */
- unsetPriceOracle: function (senderAddress, senderPassphrase, currency, gasPrice, options) {
-
- const oThis = this
- ;
-
- const validationResponse = oThis.validateUnsetPriceOracleParams(senderAddress, currency, gasPrice);
-
- if (validationResponse.isFailure()) return Promise.resolve(validationResponse);
-
- const returnType = basicHelper.getReturnType(options.returnType)
- , transactionObject = currContract.methods.unsetPriceOracle(web3Provider.utils.asciiToHex(currency));
-
- const notificationData = helper.getNotificationData(
- ['payments.pricer.unsetPriceOracle'],
- notificationGlobalConstant.publisher(),
- 'unsetPriceOracle',
- oThis.contractName,
- oThis.contractAddress,
- web3Provider,
- oThis.chainId,
- options);
-
- const successCallback = function(receipt) {
- return oThis.pricerCache.clearPriceOracles(currency);
- };
-
- const params = {
- transactionObject: transactionObject,
- notificationData: notificationData,
- senderAddress: senderAddress,
- senderPassphrase: senderPassphrase,
- contractAddress: oThis.contractAddress,
- gasPrice: gasPrice,
- gasLimit: gasLimitGlobalConstant.default(),
- web3Provider: web3Provider,
- successCallback: successCallback,
- failCallback: null,
- errorCode: "l_ci_p_uspo_4"
- };
-
- return helper.performSend(params, returnType);
- },
-
- /**
- * Validate set accepted margin params parameters
- *
- * @param {string} senderAddress - address of sender
- * @param {string} currency - quote currency
- * @param {BigNumber} acceptedMargin - accepted margin for the given currency (in wei)
- * @param {BigNumber} gasPrice - gas price
- *
- * @return {result}
- *
- */
- validateSetAcceptedMarginParams: function (senderAddress, currency, acceptedMargin, gasPrice) {
- if (!helper.isValidCurrency(currency, false)) {
- let errorParams = {
- internal_error_identifier: 'l_ci_p_validateSetAcceptedMarginParams_1',
- api_error_identifier: 'invalid_api_params',
- error_config: errorConfig,
- params_error_identifiers: ['invalid_currency'],
- debug_options: {}
- };
- return responseHelper.paramValidationError(errorParams);
- }
-
- if (!gasPrice) {
- let errorParams = {
- internal_error_identifier: 'l_ci_p_validateSetAcceptedMarginParams_2',
- api_error_identifier: 'invalid_api_params',
- error_config: errorConfig,
- params_error_identifiers: ['gas_price_invalid'],
- debug_options: {}
- };
- return responseHelper.paramValidationError(errorParams);
- }
-
- const bigNumberAcceptedMargin = new BigNumber(acceptedMargin);
-
- if (bigNumberAcceptedMargin.isNaN() || !bigNumberAcceptedMargin.isInteger() || bigNumberAcceptedMargin.lt(0)) {
- let errorParams = {
- internal_error_identifier: 'l_ci_p_validateSetAcceptedMarginParams_3',
- api_error_identifier: 'invalid_api_params',
- error_config: errorConfig,
- params_error_identifiers: ['accepted_margin_invalid'],
- debug_options: {}
- };
- return responseHelper.paramValidationError(errorParams);
- }
-
- if (!basicHelper.isAddressValid(senderAddress)) {
- let errorParams = {
- internal_error_identifier: 'l_ci_p_validateSetAcceptedMarginParams_4',
- api_error_identifier: 'invalid_api_params',
- error_config: errorConfig,
- params_error_identifiers: ['invalid_sender_address'],
- debug_options: {}
- };
- return responseHelper.paramValidationError(errorParams);
- }
-
- return responseHelper.successWithData({});
- },
-
- /**
- * Set or update the acceptable margin range for a given currency
- *
- * @param {string} senderAddress - address of sender
- * @param {string} senderPassphrase - passphrase of sender
- * @param {string} currency - quote currency
- * @param {BigNumber} acceptedMargin - accepted margin for the given currency (in wei)
- * @param {BigNumber} gasPrice - gas price
- * @param {object} options - for params like returnType, tag.
- *
- * @return {promise}
- *
- */
- setAcceptedMargin: function (senderAddress, senderPassphrase, currency, acceptedMargin, gasPrice, options) {
- const oThis = this
- ;
-
- const validationResponse = oThis.validateSetAcceptedMarginParams(senderAddress, currency, acceptedMargin, gasPrice);
-
- if (validationResponse.isFailure()) return Promise.resolve(validationResponse);
-
- const returnType = basicHelper.getReturnType(options.returnType);
-
- const transactionObject = currContract.methods.setAcceptedMargin(
- web3Provider.utils.asciiToHex(currency),
- acceptedMargin);
-
- const notificationData = helper.getNotificationData(
- ['payments.pricer.setAcceptedMargin'],
- notificationGlobalConstant.publisher(),
- 'setAcceptedMargin',
- oThis.contractName,
- oThis.contractAddress,
- web3Provider,
- oThis.chainId,
- options);
-
- const successCallback = function(receipt) {
- return oThis.verifyReceiptAndUpdateAcceptedMarginCache(acceptedMargin, currency, receipt);
- };
-
- const params = {
- transactionObject: transactionObject,
- notificationData: notificationData,
- senderAddress: senderAddress,
- senderPassphrase: senderPassphrase,
- contractAddress: oThis.contractAddress,
- gasPrice: gasPrice,
- gasLimit: gasLimitGlobalConstant.setAcceptedMargin(),
- web3Provider: web3Provider,
- successCallback: successCallback,
- failCallback: null,
- errorCode: "l_ci_p_sam_6"
- };
-
- return helper.performSend(params, returnType);
- },
-
-
- /**
- * Verify receipt and update accepted margin in cache
- *
- * @param {BigNumber} acceptedMargin - accepted margin for the given currency (in wei)
- * @param {string} currency - quote currency
- * @param {Object} receipt - transaction receipt
- *
- * @return {promise}
- *
- */
- verifyReceiptAndUpdateAcceptedMarginCache: async function (acceptedMargin, currency, receipt) {
- const oThis = this
- ;
-
- var isReceiptValid = false;
- // decode events
-
- const setAddressToNameMapResponse = await oThis.setAddressToNameMap();
-
- if (setAddressToNameMapResponse.isFailure()) return Promise.resolve(setAddressToNameMapResponse);
-
- const decodedEvent = web3EventsDecoder.perform(receipt, oThis.addressToNameMap);
-
- if (decodedEvent != undefined || decodedEvent != null) {
- // get event data
- const eventData =decodedEvent.formattedTransactionReceipt.eventsData[0];
- if (eventData != undefined || eventData != null) {
- for (var i = 0; i< eventData.events.length; i++) {
- const eventItem = eventData.events[i];
- if (eventItem.name =='_acceptedMargin') {
- isReceiptValid = (eventItem.value == acceptedMargin);
- break;
- }
- }
- }
- }
-
- if (isReceiptValid) {
- // update cache
- return oThis.pricerCache.clearAcceptedMargins(currency);
- } else {
- let errorParams = {
- internal_error_identifier: 'l_ci_p_verifyReceiptAndUpdateAcceptedMarginCache_1',
- api_error_identifier: 'invalid_receipt',
- error_config: errorConfig,
- debug_options: {}
- };
- return Promise.resolve(responseHelper.error(errorParams));
- }
- },
-
- /**
- * Pay
- *
- * @param {string} spenderAddress - address of sender
- * @param {string} senderPassphrase - passphrase of sender
- * @param {string} beneficiaryAddress - address of beneficiary account
- * @param {BigNumber} transferAmount - transfer amount (in wei)
- * @param {string} commissionBeneficiaryAddress - address of commision beneficiary account
- * @param {BigNumber} commissionAmount - commission amount (in wei)
- * @param {string} currency - quote currency
- * @param {BigNumber} intendedPricePoint - price point at which the pay is intended (in wei)
- * @param {BigNumber} gasPrice - gas price
- * @param {object} options - for params like returnType, tag.
- *
- * @return {promise}
- *
- */
- pay: function (spenderAddress, senderPassphrase, beneficiaryAddress, transferAmount, commissionBeneficiaryAddress,
- commissionAmount, currency, intendedPricePoint, gasPrice, options) {
- const oThis = this
- ;
-
- return oThis._asyncPay(spenderAddress, senderPassphrase, beneficiaryAddress, transferAmount, commissionBeneficiaryAddress,
- commissionAmount, currency, intendedPricePoint, gasPrice, options)
- .catch(function (error) {
- if (responseHelper.isCustomResult(error)) {
- return error;
- } else {
- logger.error(`${__filename}::pay::catch`);
- logger.error(error);
- return responseHelper.error({
- internal_error_identifier: 'l_ci_p_pay_1',
- api_error_identifier: 'unhandled_api_error',
- error_config: errorConfig,
- debug_options: {}
- });
- }
- });
- },
-
- /**
- * Actual Pay - can give rejections of promise
- *
- * @param {string} spenderAddress - address of sender
- * @param {string} senderPassphrase - passphrase of sender
- * @param {string} beneficiaryAddress - address of beneficiary account
- * @param {BigNumber} transferAmount - transfer amount (in wei)
- * @param {string} commissionBeneficiaryAddress - address of commision beneficiary account
- * @param {BigNumber} commissionAmount - commission amount (in wei)
- * @param {string} currency - quote currency
- * @param {BigNumber} intendedPricePoint - price point at which the pay is intended (in wei)
- * @param {BigNumber} gasPrice - gas price
- * @param {object} options - for params like returnType, tag.
- *
- * @return {promise}
- *
- */
- _asyncPay: async function (spenderAddress, senderPassphrase, beneficiaryAddress, transferAmount, commissionBeneficiaryAddress,
- commissionAmount, currency, intendedPricePoint, gasPrice, options) {
-
- const oThis = this
- ;
-
- await helper.validatePayParams(spenderAddress,
- beneficiaryAddress,
- transferAmount,
- commissionBeneficiaryAddress,
- commissionAmount,
- currency,
- intendedPricePoint,
- gasPrice);
-
- // validate if user has the balance
- var totalTransferAmount = 0;
- if (!currency) {
- // If currency not present
- totalTransferAmount = new BigNumber(0)
- .plus(transferAmount)
- .plus(commissionAmount);
- } else {
- // If currency is present
- totalTransferAmount = await oThis.getEstimatedTotalAmount(transferAmount, commissionAmount, intendedPricePoint);
- }
-
- const senderAccountBalanceResponse = await oThis.getBalanceOf(spenderAddress);
-
- if (senderAccountBalanceResponse.isFailure()) {
- let errorParams = {
- internal_error_identifier: 'l_ci_p_async_pay_1',
- api_error_identifier: 'get_balance_failed',
- error_config: errorConfig,
- debug_options: {}
- };
- return Promise.reject(responseHelper.error(errorParams));
- }
- const spenderOnChainAvailableBalanceResponse = new BigNumber(senderAccountBalanceResponse.data.balance);
-
- // if available balance is insufficient, error out
- if (spenderOnChainAvailableBalanceResponse.lt(totalTransferAmount)) {
- let errorParams = {
- internal_error_identifier: 'l_ci_p_async_pay_2',
- api_error_identifier: 'insufficient_funds',
- error_config: errorConfig,
- debug_options: {}
- };
- return Promise.reject(responseHelper.error(errorParams));
- }
-
- const brandedTokenResponse = await oThis.brandedToken();
- if(brandedTokenResponse.isFailure()) return Promise.reject(brandedTokenResponse);
-
- let brandedTokenAddress = brandedTokenResponse.data.brandedToken;
-
- const returnType = basicHelper.getReturnType(options.returnType);
-
- const successCallback = async function(receipt) {
- const setAddressToNameMapResponse = await oThis.setAddressToNameMap();
- if (setAddressToNameMapResponse.isFailure()){
- return setAddressToNameMapResponse;
- }
- const actualAmountFromReceipt = oThis.transactionHelper.getActualAmountsFromReceipt(receipt,
- oThis.addressToNameMap, eventGlobalConstants.eventPayment());
-
- if (actualAmountFromReceipt.isSuccess()) {
- return oThis.transactionHelper.afterPaySuccess(
- brandedTokenAddress,
- spenderAddress,
- totalTransferAmount,
- beneficiaryAddress,
- actualAmountFromReceipt.data.actualBeneficiaryAmount,
- commissionBeneficiaryAddress,
- actualAmountFromReceipt.data.actualCommissionAmount);
- } else {
- return oThis.transactionHelper.afterPayFailure(brandedTokenAddress, spenderAddress, totalTransferAmount);
- }
-
- };
-
- const failCallback = function(reason) {
- return oThis.transactionHelper.afterPayFailure(brandedTokenAddress, spenderAddress, totalTransferAmount);
- };
-
- const transactionObject = currContract.methods.pay(
- beneficiaryAddress,
- transferAmount,
- commissionBeneficiaryAddress,
- commissionAmount,
- web3Provider.utils.asciiToHex(currency),
- intendedPricePoint);
-
- const notificationData = helper.getNotificationData(
- ['transfer.payments.pricer.pay'],
- notificationGlobalConstant.publisher(),
- 'pay',
- oThis.contractName,
- oThis.contractAddress,
- web3Provider,
- oThis.chainId,
- options);
- notificationData.message.payload.erc20_contract_address = brandedTokenAddress;
-
- const performSendParams = {
- transactionObject: transactionObject,
- notificationData: notificationData,
- senderAddress: spenderAddress,
- senderPassphrase: senderPassphrase,
- contractAddress: oThis.contractAddress,
- gasPrice: gasPrice,
- gasLimit: gasLimitGlobalConstant.airdropPay(),
- web3Provider: web3Provider,
- successCallback: successCallback,
- failCallback: failCallback,
- errorCode: "l_ci_p_p_8"
- };
-
- const beforePayResponse = await oThis.transactionHelper.beforePay(brandedTokenAddress, spenderAddress, totalTransferAmount);
- if(beforePayResponse.isFailure()) return Promise.reject(beforePayResponse);
-
- return Promise.resolve(helper.performSend(performSendParams, returnType));
- },
-
- /**
- * Get estimated total amount
- *
- * @param {BigNumber} transferAmount - Transfer amount
- * @param {BigNumber} commissionAmount - Commission amount
- * @param {BigNumber} intendedPricePoint - Intended price point
- *
- * @return {BigNumber}
- *
- */
- getEstimatedTotalAmount: async function (transferAmount, commissionAmount, intendedPricePoint) {
-
- const oThis = this
- , conversionRateResponse = await oThis.conversionRate()
- , pricerConversionRate = new BigNumber(conversionRateResponse.data.conversionRate)
- , conversionRateDecimalsResponse = await oThis.conversionRateDecimals()
- , pricerConversionRateDecimals = new BigNumber(conversionRateDecimalsResponse.data.conversionRateDecimals)
- , decimalsResponse = await oThis.decimals()
- , pricerDecimals = new BigNumber(decimalsResponse.data.decimals);
-
- transferAmount = new BigNumber(transferAmount);
- commissionAmount = new BigNumber(commissionAmount);
- intendedPricePoint = new BigNumber(intendedPricePoint);
-
- const adjConversionRate = ((pricerConversionRate.mul((new BigNumber(10).pow(pricerDecimals)))).div((
- new BigNumber(10).pow(pricerConversionRateDecimals)))).floor();
-
- const estimatedAmount = ((transferAmount.mul(adjConversionRate)).div(intendedPricePoint)).floor()
- , estimatedCommisionAmount = ((commissionAmount.mul(adjConversionRate)).div(intendedPricePoint)).floor();
-
- return estimatedAmount.plus(estimatedCommisionAmount);
- },
-
- /**
- * Get current price point from the price oracle for the give currency
- *
- * @param {string} currency - quote currency
- *
- * @return {promise}
- *
- */
- getPricePoint: async function (currency) {
-
- const oThis = this
- ;
-
- try {
- if (!helper.isValidCurrency(currency, false)) {
- let errorParams = {
- internal_error_identifier: 'l_ci_p_getPricePoint_1',
- api_error_identifier: 'invalid_api_params',
- error_config: errorConfig,
- params_error_identifiers: ['invalid_currency'],
- debug_options: {}
- };
- return Promise.resolve(responseHelper.paramValidationError(errorParams));
- }
-
- const priceOraclesResponse = await oThis.priceOracles(currency);
- if (priceOraclesResponse.isFailure()) {
- let errorParams = {
- internal_error_identifier: 'l_ci_p_getPricePoint_2',
- api_error_identifier: 'unhandled_api_error',
- error_config: errorConfig,
- debug_options: {}
- };
- return Promise.resolve(responseHelper.error(errorParams));
- }
- const poAddress = priceOraclesResponse.data.priceOracles;
-
- const cacheResult = await oThis.pricerCache.getPricePoint(poAddress);
- if (cacheResult.isSuccess() && cacheResult.data.response != null) {
- return Promise.resolve(responseHelper.successWithData({pricePoint: cacheResult.data.response}));
- } else {
- const getPricePointFromContractResponse = await oThis.getPricePointFromContract(currency);
- if (getPricePointFromContractResponse.isSuccess()) {
- await oThis.pricerCache.setPricePoint(poAddress, getPricePointFromContractResponse.data.pricePoint);
- }
- return Promise.resolve(getPricePointFromContractResponse);
- }
-
- } catch(err) {
- let errorParams = {
- internal_error_identifier: 'l_ci_p_getPricePoint_3',
- api_error_identifier: 'unhandled_api_error',
- error_config: errorConfig,
- debug_options: {}
- };
- //Format the error
- logger.error("lib/contract_interact/pricer.js:getPricePoint inside catch ", err);
- return Promise.resolve(responseHelper.error(errorParams));
- }
- },
-
- /**
- * Get current price point from the price oracle for the give currency from contract
- *
- * @param {string} currency - quote currency
- *
- * @return {promise}
- *
- */
- getPricePointFromContract: async function (currency) {
- if (!helper.isValidCurrency(currency, false)) {
- let errorParams = {
- internal_error_identifier: 'l_ci_p_getPricePointFromContract_1',
- api_error_identifier: 'invalid_api_params',
- error_config: errorConfig,
- params_error_identifiers: ['invalid_currency'],
- debug_options: {}
- };
- return Promise.resolve(responseHelper.paramValidationError(errorParams));
- }
-
- const transactionObject = currContract.methods.getPricePoint(web3Provider.utils.asciiToHex(currency))
- , encodedABI = transactionObject.encodeABI()
- , transactionOutputs = helper.getTransactionOutputs(transactionObject);
-
- try {
- const response = await helper.call(web3Provider, this.contractAddress, encodedABI, {}, transactionOutputs);
- return Promise.resolve(responseHelper.successWithData({pricePoint: response[0]}));
- } catch(err) {
- let errorParams = {
- internal_error_identifier: 'l_ci_p_getPriceOraclesFromContract_1',
- api_error_identifier: 'unhandled_api_error',
- error_config: errorConfig,
- debug_options: {}
- };
- //Format the error
- logger.error("lib/contract_interact/pricer.js:getPricePointFromContract inside catch ", err);
- return Promise.resolve(responseHelper.error(errorParams));
- }
- },
-
- /**
- * Get current price point and calculated token amounts
- *
- * @param {BigNumber} transferAmount - transfer amount (in wei)
- * @param {BigNumber} commissionAmount - commision amount (in wei)
- * @param {string} currency - quote currency
- *
- * @return {promise}
- *
- */
- getPricePointAndCalculatedAmounts: async function (transferAmount, commissionAmount, currency) {
- if (!helper.isValidCurrency(currency, false)) {
- let errorParams = {
- internal_error_identifier: 'l_ci_p_getPricePointAndCalculatedAmounts_1',
- api_error_identifier: 'invalid_api_params',
- error_config: errorConfig,
- params_error_identifiers: ['invalid_currency'],
- debug_options: {}
- };
- return Promise.resolve(responseHelper.paramValidationError(errorParams));
- }
-
- const transactionObject = currContract.methods.getPricePointAndCalculatedAmounts(transferAmount, commissionAmount,
- web3Provider.utils.asciiToHex(currency));
-
- const encodedABI = transactionObject.encodeABI()
- , transactionOutputs = helper.getTransactionOutputs(transactionObject);
-
- try {
- const response = await helper.call(web3Provider, this.contractAddress, encodedABI, {}, transactionOutputs);
- return Promise.resolve(responseHelper.successWithData({pricePoint: response[0], tokenAmount: response[1],
- commissionTokenAmount: response[2]}));
- } catch(err) {
- let errorParams = {
- internal_error_identifier: 'l_ci_p_getPricePointAndCalculatedAmounts_2',
- api_error_identifier: 'unhandled_api_error',
- error_config: errorConfig,
- debug_options: {}
- };
- //Format the error
- logger.error("lib/contract_interact/pricer.js:getPricePointAndCalculatedAmounts inside catch ", err);
- return Promise.resolve(responseHelper.error(errorParams));
- }
- },
-
- /**
- * Convert value in wei
- *
- * @param {BigNumber} value - amount in decimal
- *
- * @return {BigNumer} 10^18
- *
- */
- toWei: function(value) {
- return web3Provider.utils.toWei(value, "ether");
- },
-
- /**
- * Get transaction receipt from transaction hash
- *
- * @param {string} transactionHash - transaction hash
- *
- * @return {BigNumer} 10^18
- *
- */
- getTxReceipt: async function(transactionHash) {
- if (!transactionHash) {
- let errorParams = {
- internal_error_identifier: 'l_ci_p_getTxReceipt_1',
- api_error_identifier: 'invalid_api_params',
- error_config: errorConfig,
- params_error_identifiers: ['invalid_transaction_hash'],
- debug_options: {}
- };
- return responseHelper.paramValidationError(errorParams);
- }
- const transactionReceipt = await helper.getTxReceipt(web3Provider, transactionHash, {});
- return Promise.resolve(responseHelper.successWithData({transactionReceipt: transactionReceipt}));
- },
-
- /**
- * Get balance of the account
- *
- * @param {string} owner - account address
- *
- * @return {BigNumer} 10^18
- *
- */
- getBalanceOf: async function(owner) {
- const oThis = this;
- // Validate addresses
- if (!basicHelper.isAddressValid(owner)) {
- let errorParams = {
- internal_error_identifier: 'l_ci_p_getBalanceOf_1',
- api_error_identifier: 'invalid_api_params',
- error_config: errorConfig,
- params_error_identifiers: ['invalid_sender_address'],
- debug_options: {}
- };
- return Promise.resolve(responseHelper.paramValidationError(errorParams));
- }
-
- const setTokenResponse = await oThis.setTokenObj();
- if (setTokenResponse.isFailure()) {
- return Promise.resolve(setTokenResponse);
- }
-
- return oThis.token.getBalanceOf(owner);
- }
-};
-
-module.exports = Pricer;
\ No newline at end of file
diff --git a/lib/contract_interact/workers.js b/lib/contract_interact/workers.js
deleted file mode 100644
index 40501a3..0000000
--- a/lib/contract_interact/workers.js
+++ /dev/null
@@ -1,390 +0,0 @@
-"use strict";
-
-/**
- *
- * This is a utility file which would be used for executing all methods on Workers contract.
- *
- * @module lib/contract_interact/workers
- *
- */
-const BigNumber = require('bignumber.js')
-;
-
-const rootPrefix = '../..'
- , basicHelper = require(rootPrefix + '/helpers/basic_helper')
- , coreAddresses = require(rootPrefix + '/config/core_addresses')
- , coreConstants = require(rootPrefix + '/config/core_constants')
- , helper = require(rootPrefix + '/lib/contract_interact/helper')
- , responseHelper = require(rootPrefix + '/lib/formatter/response')
- , web3Provider = require(rootPrefix + '/lib/web3/providers/ws')
- , logger = require(rootPrefix + '/helpers/custom_console_logger')
- , notificationGlobalConstant = require(rootPrefix + '/lib/global_constant/notification')
- , gasLimitGlobalConstant = require(rootPrefix + '/lib/global_constant/gas_limit')
- , paramErrorConfig = require(rootPrefix + '/config/param_error_config')
- , apiErrorConfig = require(rootPrefix + '/config/api_error_config')
-;
-
-const errorConfig = {
- param_error_config: paramErrorConfig,
- api_error_config: apiErrorConfig
-};
-
-const contractName = 'workers'
- , contractAbi = coreAddresses.getAbiForContract(contractName)
- , currContract = new web3Provider.eth.Contract(contractAbi)
-;
-
-/**
- * Workers contract interact class constructor
- *
- * @param {string} workerAddress - address of worker (external address)
- * @param {number} chainId - chain id
- *
- * @constructor
- *
- */
-const Workers = module.exports = function (workerAddress, chainId) {
- this.contractAddress = workerAddress;
- this.chainId = chainId;
-};
-
-Workers.prototype = {
-
- /**
- * Contract address
- *
- * @ignore
- * @private
- */
- contractAddress: null,
-
- /**
- * Set or update the worker
- *
- * @param {string} senderAddress - address of sender
- * @param {string} senderPassphrase - passphrase of sender
- * @param {string} workerAddress - worker address
- * @param {number} deactivationHeight - block number till which the worker is valid
- * @param {BigNumber} gasPrice - gas price
- * @param {object} options - for params like returnType, tag.
- *
- * @return {promise}
- *
- */
- setWorker: async function (senderAddress, senderPassphrase, workerAddress, deactivationHeight, gasPrice, options) {
- const oThis = this
- ;
-
- try {
- const returnType = basicHelper.getReturnType(options.returnType)
- , transactionObject = currContract.methods.setWorker(workerAddress, deactivationHeight);
-
- const notificationData = helper.getNotificationData(
- ['payments.workers.setWorker'],
- notificationGlobalConstant.publisher(),
- 'setWorker',
- contractName,
- oThis.contractAddress,
- web3Provider,
- oThis.chainId,
- options);
-
- const params = {
- transactionObject: transactionObject,
- notificationData: notificationData,
- senderAddress: senderAddress,
- senderPassphrase: senderPassphrase,
- contractAddress: oThis.contractAddress,
- gasPrice: gasPrice,
- gasLimit: gasLimitGlobalConstant.setWorker(),
- web3Provider: web3Provider,
- successCallback: null,
- failCallback: null,
- errorCode: "l_ci_w_setWorker_1"
- };
-
- return Promise.resolve(helper.performSend(params, returnType));
- } catch(err) {
- let errorParams = {
- internal_error_identifier: 'l_ci_w_setWorker_2',
- api_error_identifier: 'unhandled_api_error',
- error_config: errorConfig,
- debug_options: {}
- };
- logger.error('lib/contract_interact/workers.js:setWorker inside catch:', err);
- return Promise.resolve(responseHelper.error(errorParams));
- }
- },
-
- /**
- * Remove worker
- *
- * @param {string} senderAddress - address of sender
- * @param {string} senderPassphrase - passphrase of sender
- * @param {string} workerAddress - worker address
- * @param {BigNumber} gasPrice - gas price
- * @param {object} options - for params like returnType, tag.
- *
- * @return {promise}
- *
- */
- removeWorker: function (senderAddress, senderPassphrase, workerAddress, gasPrice, options) {
- const oThis = this
- ;
-
- try {
- const validationResponse = oThis._validateRemoveWorkerParams(senderAddress, workerAddress, gasPrice);
- if (validationResponse.isFailure()) return Promise.resolve(validationResponse);
-
- const returnType = basicHelper.getReturnType(options.returnType)
- , transactionObject = currContract.methods.removeWorker(workerAddress);
-
- const notificationData = helper.getNotificationData(
- ['payments.workers.removeWorker'],
- notificationGlobalConstant.publisher(),
- 'removeWorker',
- contractName,
- oThis.contractAddress,
- web3Provider,
- oThis.chainId,
- options);
-
- const params = {
- transactionObject: transactionObject,
- notificationData: notificationData,
- senderAddress: senderAddress,
- senderPassphrase: senderPassphrase,
- contractAddress: oThis.contractAddress,
- gasPrice: gasPrice,
- gasLimit: gasLimitGlobalConstant.default(),
- web3Provider: web3Provider,
- successCallback: null,
- failCallback: null,
- errorCode: "l_ci_w_removeWorker_1"
- };
-
- return Promise.resolve(helper.performSend(params, returnType));
- } catch(err) {
- let errorParams = {
- internal_error_identifier: 'l_ci_w_removeWorker_2',
- api_error_identifier: 'unhandled_api_error',
- error_config: errorConfig,
- debug_options: {}
- };
- logger.error('lib/contract_interact/workers.js:removeWorker inside catch:', err);
- return Promise.resolve(responseHelper.error(errorParams));
- }
- },
-
- /**
- * Remove (selfdestruct)
- *
- * @param {string} senderAddr - address of sender
- * @param {string} senderPassphrase - passphrase of sender
- * @param {BigNumber} gasPrice - gas price
- * @param {options} object - for params like returnType, tag.
- *
- * @return {Promise}
- *
- */
- remove: function (senderAddress, senderPassphrase, gasPrice, options) {
- const oThis = this
- ;
-
- try {
- const validationResponse = oThis._validateRemoveParams(senderAddress, gasPrice);
- if (validationResponse.isFailure()) return Promise.resolve(validationResponse);
-
- const returnType = basicHelper.getReturnType(options.returnType)
- , transactionObject = currContract.methods.remove();
-
- const notificationData = helper.getNotificationData(
- ['payments.workers.remove'],
- notificationGlobalConstant.publisher(),
- 'remove',
- contractName,
- oThis.contractAddress,
- web3Provider,
- oThis.chainId,
- options);
-
- const params = {
- transactionObject: transactionObject,
- notificationData: notificationData,
- senderAddress: senderAddress,
- senderPassphrase: senderPassphrase,
- contractAddress: oThis.contractAddress,
- gasPrice: gasPrice,
- gasLimit: gasLimitGlobalConstant.default(),
- web3Provider: web3Provider,
- successCallback: null,
- failCallback: null,
- errorCode: "l_ci_w_remove_1"
- };
-
- return Promise.resolve(helper.performSend(params, returnType));
- } catch(err) {
- let errorParams = {
- internal_error_identifier: 'l_ci_w_remove_2',
- api_error_identifier: 'unhandled_api_error',
- error_config: errorConfig,
- debug_options: {}
- };
- logger.error('lib/contract_interact/workers.js:remove inside catch:', err);
- return Promise.resolve(responseHelper.error(errorParams));
- }
- },
-
- /**
- * Check if the given worker address is valid or not
- *
- * @param {string} workerAddress - worker address
- *
- * @return {Promise}
- *
- */
- isWorker: async function (workerAddress) {
- try {
- if (!basicHelper.isAddressValid(workerAddress)) {
- let errorParams = {
- internal_error_identifier: 'l_ci_w_isWorker_1',
- api_error_identifier: 'invalid_api_params',
- error_config: errorConfig,
- params_error_identifiers: ['invalid_worker_address'],
- debug_options: {}
- };
- return Promise.resolve(responseHelper.paramValidationError(errorParams));
- }
-
- const transactionObject = currContract.methods.isWorker(workerAddress)
- , encodedABI = transactionObject.encodeABI()
- , transactionOutputs = helper.getTransactionOutputs(transactionObject)
- , response = await helper.call(web3Provider, this.contractAddress, encodedABI, {}, transactionOutputs)
- ;
-
- return Promise.resolve(responseHelper.successWithData({isValid: response[0]}));
- } catch(err) {
- let errorParams = {
- internal_error_identifier: 'l_ci_w_isWorker_2',
- api_error_identifier: 'unhandled_api_error',
- error_config: errorConfig,
- debug_options: {}
- };
- logger.error('lib/contract_interact/workers.js:isWorker inside catch:', err);
- return Promise.resolve(responseHelper.error(errorParams));
- }
- },
-
- /**
- * Validate remove worker params
- *
- * @param {string} senderAddress - address of sender
- * @param {string} workerAddress - worker address
- * @param {BigNumber} gasPrice - gas price
- *
- * @return {result}
- *
- */
- _validateRemoveWorkerParams: function (senderAddress, workerAddress, gasPrice) {
- if (!gasPrice) {
- let errorParams = {
- internal_error_identifier: 'l_ci_w_validateRemoveWorkerParams_1',
- api_error_identifier: 'invalid_api_params',
- error_config: errorConfig,
- params_error_identifiers: ['gas_price_invalid'],
- debug_options: {}
- };
- return responseHelper.paramValidationError(errorParams);
- }
- if (!basicHelper.isAddressValid(senderAddress)) {
- let errorParams = {
- internal_error_identifier: 'l_ci_w_validateRemoveWorkerParams_2',
- api_error_identifier: 'invalid_api_params',
- error_config: errorConfig,
- params_error_identifiers: ['invalid_sender_address'],
- debug_options: {}
- };
- return responseHelper.error(errorParams);
- }
- if (!basicHelper.isAddressValid(workerAddress)) {
- let errorParams = {
- internal_error_identifier: 'l_ci_w_validateRemoveWorkerParams_3',
- api_error_identifier: 'invalid_api_params',
- error_config: errorConfig,
- params_error_identifiers: ['invalid_worker_address'],
- debug_options: {}
- };
- return responseHelper.paramValidationError(errorParams);
- }
-
- return responseHelper.successWithData({});
- },
-
- /**
- * Validate Remove (selfdestruct) params
- *
- * @param {string} senderAddress - address of sender
- * @param {BigNumber} gasPrice - gas price
- *
- * @return {result}
- *
- */
- _validateRemoveParams: function (senderAddress, gasPrice) {
- if (!gasPrice) {
- let errorParams = {
- internal_error_identifier: 'l_ci_w_validateRemoveParams_1',
- api_error_identifier: 'invalid_api_params',
- error_config: errorConfig,
- params_error_identifiers: ['gas_price_invalid'],
- debug_options: {}
- };
- return responseHelper.paramValidationError(errorParams);
- }
- if (!basicHelper.isAddressValid(senderAddress)) {
- let errorParams = {
- internal_error_identifier: 'l_ci_w_validateRemoveParams_2',
- api_error_identifier: 'invalid_api_params',
- error_config: errorConfig,
- params_error_identifiers: ['invalid_sender_address'],
- debug_options: {}
- };
- return responseHelper.paramValidationError(errorParams);
- }
- return responseHelper.successWithData({});
- },
-
- /**
- * Get transaction receipt from transaction hash
- *
- * @param {string} transactionHash - transaction hash
- * TODO - this can be moved to a util class
- *
- * @return {promise}
- */
- getTxReceipt: async function(transactionHash) {
- try {
- if (!transactionHash) {
- let errorParams = {
- internal_error_identifier: 'l_ci_w_getTxReceipt_1',
- api_error_identifier: 'invalid_api_params',
- error_config: errorConfig,
- params_error_identifiers: ['invalid_transaction_hash'],
- debug_options: {}
- };
- return Promise.resolve(responseHelper.error(errorParams));
- }
-
- const transactionReceipt = await helper.getTxReceipt(web3Provider, transactionHash, {});
- return Promise.resolve(responseHelper.successWithData({transactionReceipt: transactionReceipt}));
- } catch(err) {
- let errorParams = {
- internal_error_identifier: 'l_ci_w_getTxReceipt_2',
- api_error_identifier: 'unhandled_api_error',
- error_config: errorConfig,
- debug_options: {}
- };
- logger.error('lib/contract_interact/workers.js:getTxReceipt inside catch:', err);
- return Promise.resolve(responseHelper.error(errorParams));
- }
- }
-};
diff --git a/lib/dynamoDB_service.js b/lib/dynamoDB_service.js
deleted file mode 100644
index ff01f13..0000000
--- a/lib/dynamoDB_service.js
+++ /dev/null
@@ -1,14 +0,0 @@
-"use strict";
-
-/*
- * Dynamodb Service Object
- */
-
-const OSTStorage = require('@openstfoundation/openst-storage');
-
-const rootPrefix = '..'
- , dynamodbConnectionParams = require(rootPrefix + '/config/dynamoDB')
- , ddbServiceObj = new OSTStorage.Dynamodb(dynamodbConnectionParams)
-;
-
-module.exports = ddbServiceObj;
\ No newline at end of file
diff --git a/lib/dynamo_db_service.js b/lib/dynamo_db_service.js
deleted file mode 100644
index ff01f13..0000000
--- a/lib/dynamo_db_service.js
+++ /dev/null
@@ -1,14 +0,0 @@
-"use strict";
-
-/*
- * Dynamodb Service Object
- */
-
-const OSTStorage = require('@openstfoundation/openst-storage');
-
-const rootPrefix = '..'
- , dynamodbConnectionParams = require(rootPrefix + '/config/dynamoDB')
- , ddbServiceObj = new OSTStorage.Dynamodb(dynamodbConnectionParams)
-;
-
-module.exports = ddbServiceObj;
\ No newline at end of file
diff --git a/lib/formatter/response.js b/lib/formatter/response.js
deleted file mode 100644
index 8085dc9..0000000
--- a/lib/formatter/response.js
+++ /dev/null
@@ -1,15 +0,0 @@
-"use strict";
-
-/*
- * Restful API response formatter
- *
- */
-
-const rootPrefix = '../..'
- , OSTBase = require('@openstfoundation/openst-base')
- , responseHelper = new OSTBase.responseHelper({
- moduleName: 'openst-payments'
- });
-
-
-module.exports = responseHelper;
\ No newline at end of file
diff --git a/lib/global_constant/airdrop.js b/lib/global_constant/airdrop.js
deleted file mode 100644
index a96f609..0000000
--- a/lib/global_constant/airdrop.js
+++ /dev/null
@@ -1,11 +0,0 @@
-"use strict";
-
-const airdrop = {
-
- batchSize: function(){
- return 2000;
- }
-
-};
-
-module.exports = airdrop;
\ No newline at end of file
diff --git a/lib/global_constant/events.js b/lib/global_constant/events.js
deleted file mode 100644
index 7c90234..0000000
--- a/lib/global_constant/events.js
+++ /dev/null
@@ -1,28 +0,0 @@
-"use strict";
-
-const events = {
-
- // below are the event names
- eventAirdropPayment: function() {
- return "AirdropPayment";
- },
-
- eventPayment: function() {
- return "Payment";
- }
-};
-
-// below are the event attribute names
-events.eventAttribute = {
- tokenAmount: function() {
- return "_tokenAmount";
- },
- commissionTokenAmount: function() {
- return "_commissionTokenAmount";
- },
- airdropAmount: function() {
- return "_airdropUsed";
- }
-};
-
-module.exports = events;
diff --git a/lib/global_constant/gas_limit.js b/lib/global_constant/gas_limit.js
deleted file mode 100644
index 04f82d6..0000000
--- a/lib/global_constant/gas_limit.js
+++ /dev/null
@@ -1,65 +0,0 @@
-"use strict";
-
-const gasLimit = {
-
- buffer: function() {
- return 20000;
- },
-
- default: function() {
- return 9000000;
- },
-
- setOps: function() {
- return 45822+this.buffer();
- },
-
- deployWorker: function() {
- return 569731+this.buffer();
- },
-
- // deployment gas 1645052
- deployAirdrop: function() {
- return 1803725+this.buffer();
- },
-
- deployPriceOracle: function() {
- return 579067+this.buffer();
- },
-
- deployOpsManaged: function() {
- return 45690+this.buffer();
- },
-
- setPriceOracle: function() {
- return 64585+this.buffer();
- },
-
- setAcceptedMargin: function() {
- return 44726+this.buffer();
- },
-
- setWorker: function() {
- return 46402+this.buffer();
- },
-
- transferToAirdropBudgetHolder: function() {
- return 51705+this.buffer();
- },
-
- approveByBudgetHolder: function() {
- return 45675+this.buffer();
- },
-
- approveToUser: function() {
- return 45611+this.buffer();
- },
-
- airdropPay: function(){
- return 134842+this.buffer();
- },
-
-
-};
-
-module.exports = gasLimit;
\ No newline at end of file
diff --git a/lib/global_constant/notification.js b/lib/global_constant/notification.js
deleted file mode 100644
index 2dee532..0000000
--- a/lib/global_constant/notification.js
+++ /dev/null
@@ -1,11 +0,0 @@
-"use strict";
-
-const notification = {
-
- publisher: function(){
- return 'OST';
- }
-
-};
-
-module.exports = notification;
\ No newline at end of file
diff --git a/lib/global_constant/return_types.js b/lib/global_constant/return_types.js
deleted file mode 100644
index 9b87ff8..0000000
--- a/lib/global_constant/return_types.js
+++ /dev/null
@@ -1,19 +0,0 @@
-"use strict";
-
-const returnTypes = {
-
- transactionHash: function(){
- return 'txHash';
- },
-
- transactionReceipt: function(){
- return 'txReceipt'
- },
-
- transactionUuid: function(){
- return 'uuid';
- }
-
-};
-
-module.exports = returnTypes;
\ No newline at end of file
diff --git a/lib/mysql_wrapper.js b/lib/mysql_wrapper.js
deleted file mode 100644
index 8d8b010..0000000
--- a/lib/mysql_wrapper.js
+++ /dev/null
@@ -1,81 +0,0 @@
-"use strict";
-/*
- * Manage mysql clusters and connection pools
- */
-var rootPrefix = '..'
- , mysql = require('mysql')
- , mysqlConfig = require(rootPrefix + '/config/mysql')
- , logger = require(rootPrefix + '/helpers/custom_console_logger')
- , poolClusters = {};
-
-
-const generatePoolClusters = {
-
- // creating pool cluster object in poolClusters map
- generateCluster: function(cName, dbName, cConfig) {
- var oThis = this
- , clusterName = cName + "." + dbName;
-
- // initializing the pool cluster obj using the commonClusterConfig
- poolClusters[clusterName] = mysql.createPoolCluster(mysqlConfig["commonClusterConfig"]);
-
- // looping over each node and adding it to the pool cluster obj
- for (var nName in cConfig) {
- var finalConfig = Object.assign({}, cConfig[nName], mysqlConfig["commonNodeConfig"], {"database": dbName});
- poolClusters[clusterName].add(nName, finalConfig);
- }
-
- // when a node dis-functions, it is removed from the pool cluster obj and following CB is called
- poolClusters[clusterName].on('remove', function (nodeId) {
- logger.notify('m_w_1', 'REMOVED NODE : ' + nodeId + " in " + clusterName);
- });
- },
-
- // this loops over all the databases and creates pool cluster objects map in poolClusters
- init: function () {
- var oThis = this;
- // looping over all databases
- for (var dbName in mysqlConfig["databases"]) {
- var dbClusters = mysqlConfig["databases"][dbName];
- // looping over all clusters for the database
- for(var i=0; i < dbClusters.length; i++){
- var cName = dbClusters[i]
- , cConfig = mysqlConfig["clusters"][cName];
-
- // creating pool cluster object in poolClusters map
- oThis.generateCluster(cName, dbName, cConfig);
- }
- }
- }
-
-};
-
-generatePoolClusters.init();
-
-// helper methods for mysql pool clusters
-const mysqlWrapper = {
-
- getPoolFor: function (dbName, nodeType, clusterName) {
- if (!clusterName) {
- var clusterNames = mysqlConfig["databases"][dbName];
- if (clusterNames.length > 1) {
- throw 'Multiple clusters are defined for this DB. Specify cluster name.';
- }
- clusterName = clusterNames[0];
- }
- var dbClusterName = clusterName + "." + dbName
- , sanitizedNType = (nodeType == "slave" ? 'slave*' : 'master');
- return poolClusters[dbClusterName].of(sanitizedNType);
- },
-
- getPoolClustersFor: function (dbName) {
- var clusterPools = []
- , clusterNames = mysqlConfig["databases"][dbName];
- for (var i=0; i < clusterNames.length; i++) {
- clusterPools.push(mysqlWrapper.getPoolFor(dbName, clusterNames[i], 'master'));
- }
- return clusterPools;
- }
-};
-
-module.exports = mysqlWrapper;
\ No newline at end of file
diff --git a/lib/query_builders/mysql.js b/lib/query_builders/mysql.js
deleted file mode 100755
index 98989e8..0000000
--- a/lib/query_builders/mysql.js
+++ /dev/null
@@ -1,1168 +0,0 @@
-"use strict";
-
-/**
- *
- * Form mysql query
- *
- *
- * Max supported SELECT query:
- * SELECT [columns]
- * FROM [table]
- * WHERE [where conditions]
- * GROUP BY [columns]
- * ORDER BY [order by columns]
- * HAVING [having condition]
- * LIMIT [limit and offset];
- *
- * Max supported INSERT query:
- * INSERT INTO [table] ([columns])
- * VALUES ([values]), ([values])
- * ON DUPLICATE KEY UPDATE [conditions];
- *
- * Max supported UPDATE query:
- * UPDATE [table]
- * SET [column=value], [column=value]
- * WHERE [where conditions]
- * ORDER BY [order by columns]
- * LIMIT [limit];
- *
- * Max supported DELETE query:
- * DELETE FROM [table]
- * WHERE [where conditions]
- * ORDER BY [order by columns]
- * LIMIT [limit];
- *
- * @module lib/query_builder/mysql
- *
- */
-
-var rootPrefix = '../..'
- , logger = require(rootPrefix + '/helpers/custom_console_logger')
- , responseHelper = require(rootPrefix + '/lib/formatter/response')
-;
-
-/**
- * Use following to test for SELECT after any changes in file
- *
- *
- var mysqlQuery = require('./lib/query_builders/mysql');
- var mysqlWrapper = require('./lib/mysql_wrapper');
- var mysql = require('mysql');
- var dbName = 'saas_client_economy_sandbox_development';
- var tableName = 'client_branded_tokens';
-
- function queryBuilder() {
- return new mysqlQuery({table_name: tableName});
- }
- function printQuery(query, queryData) {
- var sql = mysql.format(query, queryData);
- return sql;
- }
-
- var queryResponse = queryBuilder().select().select().select(['client_id']).select(['id', 'name']).select('sum(id) as total').select('created_at').where(['id IN (?) AND created_at > ?', [1,2], '2018-02-19']).where(['symbol_icon IN (?) AND symbol IS ?', ['ST1', 'ST2'], null]).where('symbol IS NULL').where('name="ST1"').where({conversion_rate: [1,2,3], symbol: 'ST1'}).where({conversion_rate: 2}).group_by(['id','token_uuid']).group_by(['symbol']).group_by('name, created_at').group_by('updated_at').order_by('id ASC').having(['MIN(`id`) < ? and max(id) > ?', 20, 200]).having(['MIN(`id`) < ? and max(id) > ?', 10, 100]).having('SUM(`id`) < 10').having('SUM(`id`) < 100').order_by('client_id DESC').order_by(['name', 'reserve_managed_address_id']).order_by(['symbol']).order_by({id: 'asc', client_id: 'desc'}).order_by({symbol: 'AsC'}).limit(10).offset(20).generate();
- var finalQuery = printQuery(queryResponse.data.query, queryResponse.data.queryData);
- finalQuery == "SELECT client_branded_tokens.*, client_branded_tokens.*, `client_id`, `id`, `name`, sum(id) as total, created_at FROM `client_branded_tokens` WHERE (id IN (1, 2) AND created_at > '2018-02-19') AND (symbol_icon IN ('ST1', 'ST2') AND symbol IS NULL) AND (symbol IS NULL) AND (name=\"ST1\") AND (`conversion_rate` IN (1, 2, 3) AND `symbol`='ST1') AND (`conversion_rate`=2) GROUP BY `id`, `token_uuid`, `symbol`, name, created_at, updated_at HAVING (MIN(`id`) < 20 and max(id) > 200) AND (MIN(`id`) < 10 and max(id) > 100) AND (SUM(`id`) < 10) AND (SUM(`id`) < 100) ORDER BY id ASC, client_id DESC, `name`, `reserve_managed_address_id`, `symbol`, `id` ASC, `client_id` DESC, `symbol` ASC LIMIT 20, 10";
- *
- *
- */
-
-/**
- * Use following to test for UPDATE after any changes in file
- *
- *
- var mysqlQuery = require('./lib/query_builders/mysql');
- var mysqlWrapper = require('./lib/mysql_wrapper');
- var mysql = require('mysql');
- var dbName = 'saas_client_economy_sandbox_development';
- var tableName = 'client_branded_tokens';
-
- function queryBuilder() {
- return new mysqlQuery({table_name: tableName});
- }
- function printQuery(query, queryData) {
- var sql = mysql.format(query, queryData);
- return sql;
- }
-
- var queryResponse = queryBuilder().update(['name=?, id=?', 'ACMA', 10], {touch: false}).update(['name=?, id=?', '1', 1000]).update({name: 'CMA', id: 0}).update({name: 'MA', id: 110}).update('id=30').update('id=40').where(['id IN (?) AND created_at > ?', [1,2], '2018-02-19']).where(['symbol_icon IN (?) AND symbol IS ?', ['ST1', 'ST2'], null]).where('symbol IS NULL').where('name="ST1"').where({conversion_rate: [1,2,3], symbol: 'ST1'}).where({conversion_rate: 2}).order_by('id ASC').order_by('client_id DESC').order_by(['name', 'reserve_managed_address_id']).order_by(['symbol']).order_by({id: 'asc', client_id: 'desc'}).order_by({symbol: 'AsC'}).limit(10).generate();
- var finalQuery = printQuery(queryResponse.data.query, queryResponse.data.queryData);
- finalQuery == "UPDATE `client_branded_tokens` SET name='ACMA', id=10, name='1', id=1000, `name`='CMA', `id`=0, `name`='MA', `id`=110, id=30, id=40 WHERE (id IN (1, 2) AND created_at > '2018-02-19') AND (symbol_icon IN ('ST1', 'ST2') AND symbol IS NULL) AND (symbol IS NULL) AND (name=\"ST1\") AND (`conversion_rate` IN (1, 2, 3) AND `symbol`='ST1') AND (`conversion_rate`=2) ORDER BY id ASC, client_id DESC, `name`, `reserve_managed_address_id`, `symbol`, `id` ASC, `client_id` DESC, `symbol` ASC LIMIT 10";
-
- var queryResponse = queryBuilder().update(['name=?, id=?', 'ACMA', 10]).update(['name=?, id=?', '1', 1000]).update({name: 'CMA', id: 0}).update({name: 'MA', id: 110}).update('id=30').update('id=40').where(['id IN (?) AND created_at > ?', [1,2], '2018-02-19']).where(['symbol_icon IN (?) AND symbol IS ?', ['ST1', 'ST2'], null]).where('symbol IS NULL').where('name="ST1"').where({conversion_rate: 3, symbol: 'ST1'}).where({conversion_rate: 2}).order_by('id ASC').order_by('client_id DESC').order_by(['name', 'reserve_managed_address_id']).order_by(['symbol']).order_by({id: 'asc', client_id: 'desc'}).order_by({symbol: 'AsC'}).limit(10).generate();
- var finalQuery = printQuery(queryResponse.data.query, queryResponse.data.queryData);
- finalQuery.includes("UPDATE `client_branded_tokens` SET name='ACMA', id=10, name='1', id=1000, `name`='CMA', `id`=0, `name`='MA', `id`=110, id=30, id=40, updated_at='");
- *
- *
- */
-
-/**
- * Use following to test for DELETE after any changes in file
- *
- *
- var mysqlQuery = require('./lib/query_builders/mysql');
- var mysqlWrapper = require('./lib/mysql_wrapper');
- var mysql = require('mysql');
- var dbName = 'saas_client_economy_sandbox_development';
- var tableName = 'client_branded_tokens';
-
- function queryBuilder() {
- return new mysqlQuery({table_name: tableName});
- }
- function printQuery(query, queryData) {
- var sql = mysql.format(query, queryData);
- return sql;
- }
-
- var queryResponse = queryBuilder().delete().where(['id IN (?) AND created_at > ?', [1,2], '2018-02-19']).where(['symbol_icon IN (?) AND symbol IS ?', ['ST1', 'ST2'], null]).where('symbol IS NULL').where('name="ST1"').where({conversion_rate: 3, symbol: 'ST1'}).where({conversion_rate: 2}).order_by('id ASC').order_by('client_id DESC').order_by(['name', 'reserve_managed_address_id']).order_by(['symbol']).order_by({id: 'asc', client_id: 'desc'}).order_by({symbol: 'AsC'}).limit(10).generate();
- var finalQuery = printQuery(queryResponse.data.query, queryResponse.data.queryData);
- finalQuery == "DELETE FROM `client_branded_tokens` WHERE (id IN (1, 2) AND created_at > '2018-02-19') AND (symbol_icon IN ('ST1', 'ST2') AND symbol IS NULL) AND (symbol IS NULL) AND (name=\"ST1\") AND (`conversion_rate`=3 AND `symbol`='ST1') AND (`conversion_rate`=2) ORDER BY id ASC, client_id DESC, `name`, `reserve_managed_address_id`, `symbol`, `id` ASC, `client_id` DESC, `symbol` ASC LIMIT 10";
-
- var queryResponse = queryBuilder().delete().order_by('id ASC').order_by('client_id DESC').order_by(['name', 'reserve_managed_address_id']).order_by(['symbol']).order_by({id: 'asc', client_id: 'desc'}).order_by({symbol: 'AsC'}).limit(10).generate();
- var finalQuery = printQuery(queryResponse.data.dangerQuery, queryResponse.data.queryData);
- finalQuery == "DELETE FROM `client_branded_tokens` ORDER BY id ASC, client_id DESC, `name`, `reserve_managed_address_id`, `symbol`, `id` ASC, `client_id` DESC, `symbol` ASC LIMIT 10";
- *
- *
- */
-
-/**
- * Use following to test for INSERT after any changes in file
- *
- *
- var mysqlQuery = require('./lib/query_builders/mysql');
- var mysqlWrapper = require('./lib/mysql_wrapper');
- var mysql = require('mysql');
- var dbName = 'saas_client_economy_sandbox_development';
- var tableName = 'client_branded_tokens';
-
- function queryBuilder() {
- return new mysqlQuery({table_name: tableName});
- }
- function printQuery(query, queryData) {
- var sql = mysql.format(query, queryData);
- return sql;
- }
-
- var queryResponse = queryBuilder().insert({name: 'a', age: 21}, {touch: false}).generate();
- var finalQuery = printQuery(queryResponse.data.query, queryResponse.data.queryData);
- finalQuery == "INSERT INTO `client_branded_tokens` (`name`, `age`) VALUES ('a', 21)";
-
- var queryResponse = queryBuilder().insert({name: 'a', age: 21}, {touch: false}).onDuplicate({name: 'aman', age: 25}).onDuplicate(['name=?, age=?', 'a', 100]).onDuplicate('id = 7, id2 = 74').generate();
- var finalQuery = printQuery(queryResponse.data.query, queryResponse.data.queryData);
- finalQuery == "INSERT INTO `client_branded_tokens` (`name`, `age`) VALUES ('a', 21) ON DUPLICATE KEY UPDATE `name`='aman', `age`=25, name='a', age=100, id = 7, id2 = 74";
-
- var queryResponse = queryBuilder().insert({name: 'a', age: 21}).generate();
- var finalQuery = printQuery(queryResponse.data.query, queryResponse.data.queryData);
- finalQuery.includes("INSERT INTO `client_branded_tokens` (`name`, `age`, `updated_at`, `created_at`) VALUES ('a', 21, '");
-
- var queryResponse = queryBuilder().insert({name: 'a', age: 21, created_at: '2018-01-01 00:00:00'}).generate();
- var finalQuery = printQuery(queryResponse.data.query, queryResponse.data.queryData);
- finalQuery.includes("INSERT INTO `client_branded_tokens` (`name`, `age`, `created_at`, `updated_at`) VALUES ('a', 21, '2018-01-01 00:00:00', '");
-
- var queryResponse = queryBuilder().insert({name: 'a', age: 21, created_at: '2018-01-01 00:00:00', updated_at: '2018-01-02 00:00:00'}).generate();
- var finalQuery = printQuery(queryResponse.data.query, queryResponse.data.queryData);
- finalQuery.includes("INSERT INTO `client_branded_tokens` (`name`, `age`, `created_at`, `updated_at`) VALUES ('a', 21, '2018-01-01 00:00:00', '2018-01-02 00:00:00')");
- *
- */
-
-/**
- * Use following to test for INSERT MULTIPLE after any changes in file
- *
- *
- var mysqlQuery = require('./lib/query_builders/mysql');
- var mysqlWrapper = require('./lib/mysql_wrapper');
- var mysql = require('mysql');
- var dbName = 'saas_client_economy_sandbox_development';
- var tableName = 'client_branded_tokens';
-
- function queryBuilder() {
- return new mysqlQuery({table_name: tableName});
- }
- function printQuery(query, queryData) {
- var sql = mysql.format(query, queryData);
- return sql;
- }
-
- var queryResponse = queryBuilder().insertMultiple(['name', 'age'], [['a', 21], ['b', 22]], {touch: false}).generate();
- var finalQuery = printQuery(queryResponse.data.query, queryResponse.data.queryData);
- finalQuery == "INSERT INTO `client_branded_tokens` (`name`, `age`) VALUES ('a', 21), ('b', 22)";
-
- var queryResponse = queryBuilder().insertMultiple(['name', 'age'], [['a', 21], ['b', 22]], {touch: false}).onDuplicate({name: 'aman', age: 25}).onDuplicate(['name=?, age=?', 'a', 100]).onDuplicate('id = 7, id2 = 74').generate();
- var finalQuery = printQuery(queryResponse.data.query, queryResponse.data.queryData);
- finalQuery == "INSERT INTO `client_branded_tokens` (`name`, `age`) VALUES ('a', 21), ('b', 22) ON DUPLICATE KEY UPDATE `name`='aman', `age`=25, name='a', age=100, id = 7, id2 = 74";
-
- var queryResponse = queryBuilder().insertMultiple(['name', 'age'], [['a', 21], ['b', 22]]).generate();
- var finalQuery = printQuery(queryResponse.data.query, queryResponse.data.queryData);
- finalQuery.includes("INSERT INTO `client_branded_tokens` (`name`, `age`, `updated_at`, `created_at`) VALUES ('a', 21, '");
-
- var queryResponse = queryBuilder().insertMultiple(['name', 'age', 'created_at'], [['a', 21, '2018-01-01 00:00:00'], ['b', 22, '2018-01-01 10:00:00']]).generate();
- var finalQuery = printQuery(queryResponse.data.query, queryResponse.data.queryData);
- finalQuery.includes("INSERT INTO `client_branded_tokens` (`name`, `age`, `created_at`, `updated_at`) VALUES ('a', 21, '2018-01-01 00:00:00', '");
-
- var queryResponse = queryBuilder().insertMultiple(['name', 'age', 'created_at', 'updated_at'], [['a', 21, '2018-01-01 00:00:00', '2018-01-02 00:00:00'], ['b', 22, '2018-01-01 10:00:00', '2018-01-02 10:00:00']]).generate();
- var finalQuery = printQuery(queryResponse.data.query, queryResponse.data.queryData);
- finalQuery.includes("INSERT INTO `client_branded_tokens` (`name`, `age`, `created_at`, `updated_at`) VALUES ('a', 21, '2018-01-01 00:00:00', '2018-01-02 00:00:00'), ('b', 22, '2018-01-01 10:00:00', '2018-01-02 10:00:00')");
- *
- */
-
-
-/**
- *
- * MySQL query builder constructor
- *
- * @param {Object} params -
- * @param {String} [params.table_name] - MySQL table name for which query need to be build
- *
- * @constructor
- *
- */
-const MySQLQueryBuilderKlass = function (params) {
- const oThis = this
- ;
-
- oThis.tableName = oThis.tableName || (params || {}).table_name;
-
- oThis.queryType = null;
-
- // Select query type
- oThis.selectSubQueries = [];
- oThis.selectSubQueriesReplacement = [];
-
- // Insert, Bulk Insert query type
- oThis.insertIntoColumns = [];
- oThis.insertIntoColumnValues = [];
-
- // Update query type
- oThis.updateSubQueries = [];
- oThis.updateSubQueriesReplacement = [];
- oThis.touchUpdatedAt = true;
-
- // delete Query type has no specific parameters
-
- // --- common variables ---
-
- //used in Select, Delete, Update Query
- oThis.whereSubQueries = [];
- oThis.whereSubQueriesReplacement = [];
-
- //used in Select, Delete, Update Query
- oThis.orderBySubQueries = [];
- oThis.orderBySubQueriesReplacement = [];
-
- //used in Select, Delete, Update Query
- oThis.selectLimit = 0;
-
- //used only with Select Query
- oThis.selectOffset = 0;
-
- //used only with Select Query
- oThis.groupBySubQueries = [];
- oThis.groupBySubQueriesReplacement = [];
-
- //used only with Select Query
- oThis.havingSubQueries = [];
- oThis.havingSubQueriesReplacement = [];
-
- //used only with INSERT Query
- oThis.onDuplicateSubQueries = [];
- oThis.onDuplicateSubQueriesReplacement = [];
-
- return oThis;
-};
-
-MySQLQueryBuilderKlass.prototype = {
-
- tableName: null,
-
- queryType: null,
-
- selectSubQueries: null,
- selectSubQueriesReplacement: null,
-
- insertIntoColumns: null,
- insertIntoColumnValues: null,
-
- updateSubQueries: null,
- updateSubQueriesReplacement: null,
- touchUpdatedAt: null,
-
- whereSubQueries: null,
- whereSubQueriesReplacement: null,
-
- orderBySubQueries: null,
- orderBySubQueriesReplacement: null,
-
- selectLimit: null,
- selectOffset: null,
-
- groupBySubQueries: null,
- groupBySubQueriesReplacement: null,
-
- havingSubQueries: null,
- havingSubQueriesReplacement: null,
-
- onDuplicateSubQueries: null,
- onDuplicateSubQueriesReplacement: null,
-
- /**
- * List of fields to be selected from table. If called multiple times, select columns will be joined by COMMA.
- *
- * Possible data types:
- * * blank/undefined - '*' will be used to fetch all columns
- * * Array - list of field names will be joined by comma
- * * String - list of field names will be used as it is
- *
- * Example 1: '*' will be used to fetch all columns
- * select()
- *
- * Example 2: list of field names in array. Will be joined by comma
- * select(['name', 'created_at'])
- *
- * Example 3: list of field names in string. Will be used as it is
- * select('name, created_at')
- *
- * @return {object} oThis
- */
- select: function (fields) {
- const oThis = this
- ;
-
- if (![undefined, null, '', 'SELECT'].includes(oThis.queryType)) {
- throw "Multiple type of query statements in single query builder object";
- }
-
- oThis.queryType = "SELECT";
-
- if (fields === undefined || fields === '') {
-
- // if fields are not mentioned, fetch all columns
- oThis.selectSubQueries.push(oThis.tableName + ".*");
-
- } else if (Array.isArray(fields)) {
-
- // list of columns will be fetched
- oThis.selectSubQueries.push("??");
- oThis.selectSubQueriesReplacement.push(fields);
-
- } else if (typeof fields === 'string') {
-
- // custom columns list will be fetched
- oThis.selectSubQueries.push(fields);
-
- } else {
- throw "Unsupported data type for fields in SELECT clause";
- }
-
- return oThis;
- },
-
- /**
- * Insert single record in table. Method can't be called twice on same object
- *
- * Example 1: Insert in object format.
- * insert({name: 'ACMA', id: 10})
- *
- * @param (object) insertFields - key and value pairs of columns and values to be inserted
- * @param (object) insertOptions -
- * @param (object) [insertOptions.touch] - if true, auto insert created_at and updated_at values. Default is true.
- *
- * @return {object} oThis
- */
- insert: function (insertFields, insertOptions) {
- const oThis = this;
-
- if (typeof insertFields !== 'object') {
- throw "Unsupported INSERT fields data type";
- }
-
- var insertColumns = Object.keys(insertFields)
- , insertValues = Object.values(insertFields)
- ;
-
- return oThis.insertMultiple(insertColumns, [insertValues], insertOptions);
- },
-
- /**
- * Insert multiple records in table. Method can't be called twice on same object
- *
- * Example 1:
- * insertMultiple(['name', 'symbol'], [['ABC', '123'], ['ABD', '456']])
- *
- * @param {array} insertColumns - list of columns. also columns are mandatory
- * @param {array} insertValues - array of array with values
- * @param {object} insertOptions -
- * @param {object} [insertOptions.touch] - if true, auto insert created_at and updated_at values. Default is true.
- *
- * @return {object} oThis
- */
- insertMultiple: function (insertColumns, insertValues, insertOptions) {
- const oThis = this
- , touchTimestampColumns = ((insertOptions || {}).touch===false ? false : true)
- , currentDate = new Date()
- ;
-
- if (![undefined, null, ''].includes(oThis.queryType)) {
- throw "Multiple type of query statements in single query builder object";
- }
-
- oThis.queryType = "INSERT";
-
- if (!Array.isArray(insertColumns) || insertColumns.length == 0) {
- throw "Unsupported INSERT columns data type";
- }
-
- if (!Array.isArray(insertValues)) {
- throw "Unsupported INSERT values data type";
- }
-
- // insert columns can be left empty
- oThis.insertIntoColumns = insertColumns;
-
- // Manage created_at and updated_at columns
- var createdAtDateTime = null
- , updatedAtDateTime = null
- ;
- if (touchTimestampColumns) {
- if (!oThis.insertIntoColumns.includes('updated_at')) {
- oThis.insertIntoColumns.push('updated_at');
- updatedAtDateTime = currentDate;
- }
- if (!oThis.insertIntoColumns.includes('created_at')) {
- oThis.insertIntoColumns.push('created_at');
- createdAtDateTime = currentDate;
- }
- }
-
- // insert values
- var totalColumnsToInsert = oThis.insertIntoColumns.length;
- for (var i = 0; i < insertValues.length; i++) {
-
- // Add timestamp column values
- if (updatedAtDateTime !== null) {
- insertValues[i].push(updatedAtDateTime);
- }
- if (createdAtDateTime !== null) {
- insertValues[i].push(createdAtDateTime);
- }
-
- if (totalColumnsToInsert != insertValues[i].length) {
- throw "Column length is not equal to value length";
- }
- }
- oThis.insertIntoColumnValues = insertValues;
-
- return oThis;
- },
-
- /**
- * Update columns to be applied to the query. If called multiple times, update fields will be joined by COMMA.
- *
- * Possible data types:
- * * Array - index 0 should have the update sub query and other indexes should have the valued to be replaced in sub query
- * * Object - key and value pairs of columns and values to be joined by COMMA to form update sub query
- * * String - update sub query, used as it is.
- *
- * @param {*} updateFields - refer possible data types
- * @param {object} insertOptions -
- * @param {object} [insertOptions.touch] - if true, auto insert created_at and updated_at values. Default is true.
- *
- * Example 1: update in array format
- * update(['name=?, id=?', 'ACMA', 10])
- *
- * Example 2: Update in object format. Fields will be joined by {,}
- * update({name: 'ACMA', id: 10})
- *
- * Example 3: Update in string. Will be used as it is
- * update('id=10')
- *
- * @return {object} oThis
- */
- update: function (updateFields, insertOptions) {
- const oThis = this
- ;
-
- // validations
- if (updateFields === undefined || updateFields === '') {
- throw "UPDATE fields can not be blank";
- }
-
- oThis.queryType = "UPDATE";
-
- if (typeof updateFields === 'string') {
-
- // simply push string to sub-queries array
- oThis.updateSubQueries.push(updateFields);
-
- } else if (Array.isArray(updateFields)) {
-
- // extract first element and push it to sub-queries array
- oThis.updateSubQueries.push(updateFields.shift());
-
- // remain array will be concatenated at the end of replacement array
- if (updateFields.length > 0) {
- oThis.updateSubQueriesReplacement = oThis.updateSubQueriesReplacement.concat(updateFields);
- }
-
- } else if (typeof updateFields === 'object') {
-
- // Extract keys and values in different arrays.
- // For sub-queries create string locally and push it to sub-queries array by joining with AND.
- // Also push key and value alternatively in local replacement array.
- var updateColumns = Object.keys(updateFields)
- , updateValues = Object.values(updateFields)
- , localSubQueries = []
- , localReplacements = [];
-
-
- if (updateColumns.length > 0) {
- for (var i = 0; i < updateColumns.length; i++) {
- localSubQueries.push("??=?");
- localReplacements.push(updateColumns[i]);
- localReplacements.push(updateValues[i]);
- }
- oThis.updateSubQueries.push(localSubQueries.join(', '));
- oThis.updateSubQueriesReplacement = oThis.updateSubQueriesReplacement.concat(localReplacements);
- } else {
- throw "Unsupported data type for UPDATE clause";
- }
-
- } else {
- throw "Unsupported data type for UPDATE clause";
- }
-
- // Manage updated_at column
- if (oThis.touchUpdatedAt !== false) {
- oThis.touchUpdatedAt = ((insertOptions || {}).touch===false ? false : true);
- }
-
- return oThis;
- },
-
- /**
- * Delete row from table
- *
- * Example 1:
- * delete()
- *
- * @return {object} oThis
- */
- delete: function () {
- const oThis = this;
-
- if (![undefined, null, ''].includes(oThis.queryType)) {
- throw "Multiple type of query statements in single query builder object";
- }
-
- oThis.queryType = "DELETE";
-
- return oThis;
- },
-
- /**
- * Where conditions to be applied to the query. If called multiple times, where conditions will be joined by AND.
- *
- * Possible data types:
- * * Array - index 0 should have the where sub query and other indexes should have the valued to be replaced in sub query
- * * Object - key and value pairs of columns and values to be joined by AND to form where sub query
- * * String - where sub query, used as it is.
- *
- * Example 1: Where in array format
- * where(['name=? AND id=?', 'ACMA', 10])
- *
- * Example 2: Where in object format. Conditions will be joined by AND
- * where({name: 'ACMA', id: 10})
- * where({name: [1,2,3], id: 10})
- *
- * Example 3: condition in string. Will be used as it is
- * where('id=10')
- *
- * @return {object} oThis
- */
- where: function (whereConditions) {
- const oThis = this
- ;
-
- // validations
- if (!['SELECT', 'UPDATE', 'DELETE'].includes(oThis.queryType)) {
- throw "Please select the query type before WHERE clause. Current query type: " + oThis.queryType;
- }
- if (whereConditions === undefined || whereConditions === '') {
- throw "WHERE condition can not be blank";
- }
-
- if (typeof whereConditions === 'string') {
-
- // simply push string to sub-queries array
- oThis.whereSubQueries.push(whereConditions);
-
- } else if (Array.isArray(whereConditions)) {
-
- // extract first element and push it to sub-queries array
- oThis.whereSubQueries.push(whereConditions.shift());
-
- // remain array will be concatenated at the end of replacement array
- if (whereConditions.length > 0) {
- oThis.whereSubQueriesReplacement = oThis.whereSubQueriesReplacement.concat(whereConditions);
- }
-
- } else if (typeof whereConditions === 'object') {
-
- // Extract keys and values in different arrays.
- // For sub-queries create string locally and push it to sub-queries array by joining with AND.
- // Also push key and value alternatively in local replacement array.
- var whereColumns = Object.keys(whereConditions)
- , whereValues = Object.values(whereConditions)
- , localSubQueries = []
- , localReplacements = [];
-
-
- if (whereColumns.length > 0) {
- for (var i = 0; i < whereColumns.length; i++) {
- if (Array.isArray(whereValues[i])) {
- localSubQueries.push("?? IN (?)");
- } else {
- localSubQueries.push("??=?");
- }
- localReplacements.push(whereColumns[i]);
- localReplacements.push(whereValues[i]);
- }
- oThis.whereSubQueries.push(localSubQueries.join(' AND '));
- oThis.whereSubQueriesReplacement = oThis.whereSubQueriesReplacement.concat(localReplacements);
- } else {
- throw "Unsupported data type for WHERE clause";
- }
-
- } else {
- throw "Unsupported data type for WHERE clause";
- }
-
- return oThis;
- },
-
- /**
- * List of fields to be grouped by from table. If called multiple times, group by conditions will be joined by COMMA.
- *
- * Possible data types:
- * * Array - list of field names will be joined by comma
- * * String - list of field names will be used as it is
- *
- * Example 1:
- * group_by(['name', 'created_at'])
- *
- * Example 2:
- * group_by('name, created_at')
- *
- * @return {object} oThis
- */
- group_by: function (groupByConditions) {
- const oThis = this
- ;
-
- // validations
- if (!['SELECT'].includes(oThis.queryType)) {
- throw "Please select the query type before GROUP BY. Current query type: " + oThis.queryType;
- }
- if (groupByConditions === undefined || groupByConditions === '') {
- throw "GROUP BY condition can not be blank";
- }
-
- if (Array.isArray(groupByConditions)) {
-
- // list of columns to be group by on
- oThis.groupBySubQueries.push("??");
- oThis.groupBySubQueriesReplacement.push(groupByConditions);
-
- } else if (typeof groupByConditions === 'string') {
-
- // custom columns list will be fetched
- oThis.groupBySubQueries.push(groupByConditions);
-
- } else {
- throw "Unsupported data type for GROUP BY";
- }
-
- return oThis;
- },
-
- /**
- * List of fields to be ordered by from table. If called multiple times, order by conditions will be joined by COMMA.
- *
- * Possible data types:
- * * Object - where keys are column names and value is order
- * * String - order will be used as it is
- *
- * Example 1:
- * order_by({'name': 'ASC', 'created_at': 'DESC'})
- *
- * Example 2:
- * order_by('name ASC, created_at DESC')
- *
- * Example 3:
- * order_by([1, 2, 3])
- *
- * @return {object} oThis
- */
- order_by: function (orderByConditions) {
- const oThis = this
- ;
-
- // validations
- if (!['SELECT', 'UPDATE', 'DELETE'].includes(oThis.queryType)) {
- throw "Please select the query type before ORDER BY. Current query type: " + oThis.queryType;
- }
- if (orderByConditions === undefined || orderByConditions === '') {
- throw "ORDER BY condition can not be blank";
- }
-
- if (Array.isArray(orderByConditions)) {
-
- // list of columns to be group by on
- oThis.orderBySubQueries.push("??");
- oThis.orderBySubQueriesReplacement.push(orderByConditions);
-
- } else if (typeof orderByConditions === 'object') {
-
- // Extract keys and values in different arrays.
- // For sub-queries create string locally and push it to sub-queries array by joining with COMMA.
- // Also push key and value alternatively in local replacement array.
- var orderColumns = Object.keys(orderByConditions)
- , orderValues = Object.values(orderByConditions)
- , localSubQueries = []
- , localReplacements = [];
-
- if (orderColumns.length > 0) {
- for (var i = 0; i < orderColumns.length; i++) {
- localSubQueries.push("?? " + (orderValues[i].toUpperCase() == "DESC" ? "DESC" : "ASC"));
- localReplacements.push(orderColumns[i]);
- }
- oThis.orderBySubQueries.push(localSubQueries.join(', '));
- oThis.orderBySubQueriesReplacement = oThis.orderBySubQueriesReplacement.concat(localReplacements);
- } else {
- throw "Unsupported data type for ORDER BY";
- }
-
- } else if (typeof orderByConditions === 'string') {
-
- // custom columns list will be fetched
- oThis.orderBySubQueries.push(orderByConditions);
-
- } else {
- throw "Unsupported data type for ORDER BY";
- }
-
- return oThis;
- },
-
- /**
- * List of fields for having clause. If called multiple times, having conditions will be joined by AND.
- *
- * Possible data types:
- * * Array - index 0 should have the having sub query and other indexes should have the valued to be replaced in sub query
- * * String - where sub query, used as it is.
- *
- * Example 1: Where in array format
- * having(['MIN(`salary`) < ?', 10])
- *
- * Example 2: condition in string. Will be used as it is
- * having('MIN(`salary`) < 10')
- *
- * @return {object} oThis
- */
- having: function (havingConditions) {
- const oThis = this
- ;
-
- // validations
- if (!['SELECT'].includes(oThis.queryType)) {
- throw "Please select the query type before HAVING condition. Current query type: " + oThis.queryType;
- }
- if (havingConditions === undefined || havingConditions === '') {
- throw "HAVING condition can not be blank";
- }
-
- if (typeof havingConditions === 'string') {
-
- // simply push string to sub-queries array
- oThis.havingSubQueries.push(havingConditions);
-
- } else if (Array.isArray(havingConditions)) {
-
- // extract first element and push it to sub-queries array
- oThis.havingSubQueries.push(havingConditions.shift());
-
- // remaining array will be concatenated at the end of replacement array
- if (havingConditions.length > 0) {
- oThis.havingSubQueriesReplacement = oThis.havingSubQueriesReplacement.concat(havingConditions);
- }
-
- } else {
- throw "Unsupported data type for HAVING";
- }
-
- return oThis;
- },
-
- /**
- * Limit of records to be fetched. If called multiple times, it will overwrite the previous value
- *
- * Example 1:
- * limit(100)
- *
- * @param (number) recordsLimit - limit for select query
- *
- * @return {object} oThis
- */
- limit: function (recordsLimit) {
- const oThis = this
- ;
-
- // Validations
- if (!['SELECT', 'UPDATE', 'DELETE'].includes(oThis.queryType)) {
- throw "Please select the query type before LIMIT. Current query type: " + oThis.queryType;
- }
-
- if (parseInt(recordsLimit) > 0) {
-
- // simply use the number in limit clause
- oThis.selectLimit = parseInt(recordsLimit);
-
- } else {
- throw "Unsupported data type for select LIMIT";
- }
-
- return oThis;
- },
-
- /**
- * Offset for records to be fetched. If called multiple times, it will overwrite the previous value. limit is mandatory for offset
- *
- * Example 1:
- * offset(10)
- *
- * @param (number) recordsOffset - offset for select query
- *
- * @return {object} oThis
- */
- offset: function (recordsOffset) {
- const oThis = this
- ;
-
- // Validations
- if (!['SELECT'].includes(oThis.queryType)) {
- throw "Please select the query type before OFFSET. Current query type: " + oThis.queryType;
- }
-
- if (parseInt(recordsOffset) > 0) {
-
- // simply use the number in limit clause
- oThis.selectOffset = parseInt(recordsOffset);
-
- } else {
- throw "Unsupported data type for select OFFSET";
- }
-
- return oThis;
- },
-
- /**
- * On Duplicate conditions to be applied to the INSERT query. If called multiple times, conditions will be joined by COMMA.
- *
- * Possible data types:
- * * Array - index 0 should have the On Duplicate sub query and other indexes should have the valued to be replaced in sub query
- * * Object - key and value pairs of columns and values to be joined by COMMA to form On Duplicate sub query
- * * String - sub query, used as it is.
- *
- * Example 1: ON DUPLICATE in array format
- * onDuplicate(['name=? , id=?', 'ACMA', 10])
- *
- * Example 2: ON DUPLICATE in object format. Conditions will be joined by ,
- * onDuplicate({name: 'ACMA', id: 10})
- *
- * Example 3: ON DUPLICATE in string. Will be used as it is
- * onDuplicate('id=10')
- *
- * @return {object} oThis
- */
- onDuplicate: function (onDuplicateConditions) {
- const oThis = this
- ;
-
- // validations
- if (!['INSERT'].includes(oThis.queryType)) {
- throw "Please select the query type before ON DUPLICATE clause. Current query type: " + oThis.queryType;
- }
- if (onDuplicateConditions === undefined || onDuplicateConditions === '') {
- throw "ON DUPLICATE condition can not be blank";
- }
-
- if (typeof onDuplicateConditions === 'string') {
-
- // simply push string to sub-queries array
- oThis.onDuplicateSubQueries.push(onDuplicateConditions);
-
- } else if (Array.isArray(onDuplicateConditions)) {
-
- // extract first element and push it to sub-queries array
- oThis.onDuplicateSubQueries.push(onDuplicateConditions.shift());
-
- // remain array will be concatenated at the end of replacement array
- if (onDuplicateConditions.length > 0) {
- oThis.onDuplicateSubQueriesReplacement = oThis.onDuplicateSubQueriesReplacement.concat(onDuplicateConditions);
- }
-
- } else if (typeof onDuplicateConditions === 'object') {
-
- // Extract keys and values in different arrays.
- // For sub-queries create string locally and push it to sub-queries array by joining with COMMA.
- // Also push key and value alternatively in local replacement array.
- var onDuplicateColumns = Object.keys(onDuplicateConditions)
- , onDuplicateValues = Object.values(onDuplicateConditions)
- , localSubQueries = []
- , localReplacements = [];
-
-
- if (onDuplicateColumns.length > 0) {
- for (var i = 0; i < onDuplicateColumns.length; i++) {
- localSubQueries.push("??=?");
- localReplacements.push(onDuplicateColumns[i]);
- localReplacements.push(onDuplicateValues[i]);
- }
- oThis.onDuplicateSubQueries.push(localSubQueries.join(', '));
- oThis.onDuplicateSubQueriesReplacement = oThis.onDuplicateSubQueriesReplacement.concat(localReplacements);
- } else {
- throw "Unsupported data type for ON DUPLICATE clause";
- }
-
- } else {
- throw "Unsupported data type for ON DUPLICATE clause";
- }
-
- return oThis;
- },
-
- /**
- * Generate final query supported by mysql node module
- *
- * @return {object}
- */
- generate: function () {
- const oThis = this
- ;
-
- if (oThis.queryType === "SELECT") {
-
- return oThis._generateSelect();
-
- } else if (oThis.queryType == "INSERT") {
-
- return oThis._generateInsert();
-
- } else if (oThis.queryType == "UPDATE") {
-
- return oThis._generateUpdate();
-
- } else if (oThis.queryType == "DELETE") {
-
- return oThis._generateDelete();
-
- } else {
- throw "Unsupported query type";
- }
- },
-
- /**
- * Generate the final SELECT statement
- *
- * @private
- */
- _generateSelect: function () {
- const oThis = this
- ;
-
- // Select query generation starts
- var queryString = oThis.queryType
- , queryData = [];
-
- // Select part of the query and it's data part
- if (oThis.selectSubQueries.length === 0) {
- // put * if no select mentioned ??
- throw "What do you want to select? Please mention.";
- }
- queryString += " " + oThis.selectSubQueries.join(', ');
- queryData = queryData.concat(oThis.selectSubQueriesReplacement);
-
- // If table name is present, generate the rest of the query and it's data
- if (oThis.tableName) {
-
- // from part of the query and it's data part
- queryString += " FROM ??";
- queryData.push(oThis.tableName);
-
- if (oThis.whereSubQueries.length > 0) {
- queryString += " WHERE (" + oThis.whereSubQueries.join(') AND (') + ")";
- queryData = queryData.concat(oThis.whereSubQueriesReplacement);
- }
-
- if (oThis.groupBySubQueries.length > 0) {
- queryString += " GROUP BY " + oThis.groupBySubQueries.join(', ');
- queryData = queryData.concat(oThis.groupBySubQueriesReplacement);
- }
-
- if (oThis.havingSubQueries.length > 0) {
- queryString += " HAVING (" + oThis.havingSubQueries.join(') AND (') + ")";
- queryData = queryData.concat(oThis.havingSubQueriesReplacement);
- }
-
- if (oThis.orderBySubQueries.length > 0) {
- queryString += " ORDER BY " + oThis.orderBySubQueries.join(', ');
- queryData = queryData.concat(oThis.orderBySubQueriesReplacement);
- }
-
- if (oThis.selectLimit > 0) {
- queryString += " LIMIT " + ((oThis.selectOffset > 0) ? oThis.selectOffset + ", " : "") + oThis.selectLimit;
- }
-
- }
-
- return responseHelper.successWithData({query: queryString, queryData: queryData});
- },
-
- /**
- * Generate the final INSERT statement
- *
- * @private
- */
- _generateInsert: function () {
- const oThis = this
- ;
-
- // Insert query generation starts
- var queryString = oThis.queryType
- , queryData = [];
-
- // insert columns should be present
- if (oThis.insertIntoColumns.length === 0) {
- throw "What do you want to insert? Please mention.";
- }
-
- if (!oThis.tableName) {
- throw "No Table Name given. Please mention.";
- }
-
- // from part of the query and it's data part
- queryString += " INTO ??";
- queryData.push(oThis.tableName);
-
- queryString += " (??)";
- queryData.push(oThis.insertIntoColumns);
-
- queryString += " VALUES ?";
- queryData.push(oThis.insertIntoColumnValues);
-
- if (oThis.onDuplicateSubQueries.length > 0) {
- queryString += " ON DUPLICATE KEY UPDATE " + oThis.onDuplicateSubQueries.join(', ');
- queryData = queryData.concat(oThis.onDuplicateSubQueriesReplacement);
- }
-
- return responseHelper.successWithData({query: queryString, queryData: queryData});
- },
-
- /**
- * Generate the final DELETE statement
- *
- * @private
- */
- _generateDelete: function () {
- const oThis = this
- ;
-
- // Delete query generation starts
- var queryString = oThis.queryType
- , queryData = []
- , queryWithoutWhere = true;
-
- if (!oThis.tableName) {
- throw "No Table Name given. Please mention.";
- }
-
- // from part of the query and it's data part
- queryString += " FROM ??";
- queryData.push(oThis.tableName);
-
- if (oThis.whereSubQueries.length > 0) {
- queryString += " WHERE (" + oThis.whereSubQueries.join(') AND (') + ")";
- queryData = queryData.concat(oThis.whereSubQueriesReplacement);
- queryWithoutWhere = false;
- }
-
- if (oThis.orderBySubQueries.length > 0) {
- queryString += " ORDER BY " + oThis.orderBySubQueries.join(', ');
- queryData = queryData.concat(oThis.orderBySubQueriesReplacement);
- }
-
- if (oThis.selectLimit > 0) {
- queryString += " LIMIT " + oThis.selectLimit;
- }
-
- // when where condition is not mentioned, query will be returned in a different key
- if (queryWithoutWhere) {
- return responseHelper.successWithData({dangerQuery: queryString, queryData: queryData});
- } else {
- return responseHelper.successWithData({query: queryString, queryData: queryData});
- }
-
- },
-
- /**
- * Generate the final UPDATE statement
- *
- * @private
- */
- _generateUpdate: function () {
- const oThis = this
- ;
-
- // Update query generation starts
- var queryString = oThis.queryType
- , queryData = [];
-
- if (!oThis.tableName) {
- throw "No Table Name given. Please mention.";
- }
-
- // from part of the query and it's data part
- queryString += " ??";
- queryData.push(oThis.tableName);
-
- if (oThis.updateSubQueries.length == 0) {
- throw "No update fields selected";
- }
-
- // Manage updated_at column
- if (oThis.touchUpdatedAt) {
- oThis.updateSubQueries.push('updated_at=?');
- oThis.updateSubQueriesReplacement = oThis.updateSubQueriesReplacement.concat([new Date()]);
- }
-
- queryString += " SET " + oThis.updateSubQueries.join(', ');
- queryData = queryData.concat(oThis.updateSubQueriesReplacement);
-
- if (oThis.whereSubQueries.length > 0) {
- queryString += " WHERE (" + oThis.whereSubQueries.join(') AND (') + ")";
- queryData = queryData.concat(oThis.whereSubQueriesReplacement);
- }
-
- if (oThis.orderBySubQueries.length > 0) {
- queryString += " ORDER BY " + oThis.orderBySubQueries.join(', ');
- queryData = queryData.concat(oThis.orderBySubQueriesReplacement);
- }
-
- if (oThis.selectLimit > 0) {
- queryString += " LIMIT " + oThis.selectLimit;
- }
-
- return responseHelper.successWithData({query: queryString, queryData: queryData});
- }
-
-};
-
-module.exports = MySQLQueryBuilderKlass;
\ No newline at end of file
diff --git a/lib/set_worker_and_ops.js b/lib/set_worker_and_ops.js
deleted file mode 100644
index 8f07e28..0000000
--- a/lib/set_worker_and_ops.js
+++ /dev/null
@@ -1,128 +0,0 @@
-"use strict";
-
-/**
- * Set Worker Contract and OPS Address
- *
- * @module lib/set_worker_and_ops
- */
-const rootPrefix = ".."
- , logger = require(rootPrefix + '/helpers/custom_console_logger')
- , returnTypes = require(rootPrefix + "/lib/global_constant/return_types")
- , coreAddresses = require(rootPrefix + '/config/core_addresses')
- , responseHelper = require(rootPrefix + '/lib/formatter/response')
- , openstPayment = require(rootPrefix + '/index')
- , SetOpsKlass = openstPayment.services.opsManaged.setOps
- , GetOpsKlass = openstPayment.services.opsManaged.getOps
- , DeployWorkersKlass = openstPayment.services.deploy.workers
- , paramErrorConfig = require(rootPrefix + '/config/param_error_config')
- , apiErrorConfig = require(rootPrefix + '/config/api_error_config')
-;
-
-const errorConfig = {
- param_error_config: paramErrorConfig,
- api_error_config: apiErrorConfig
-};
-
-// Different addresses used for deployment
-const deployerName = "deployer"
- , deployerAddress = coreAddresses.getAddressForUser(deployerName)
- , deployerPassphrase = coreAddresses.getPassphraseForUser(deployerName)
-;
-
-// Set Ops Address
-const opsName = "ops"
- , opsAddress = coreAddresses.getAddressForUser(opsName)
-;
-
-/**
- * Set Worker Contract and OPS Address
- *
- * @constructor
- */
-const SetWorkerOps = function(){};
-
-SetWorkerOps.prototype = {
-
- /**
- * Set Worker and Ops for a contract.
- *
- * @param {object} [options]
- * @param {number} [options.gasPrice] - Gas Price to use
- * @param {number} [options.chainId] - Chain Id where contract need to be deployed
- *
- * @return {Promise}
- */
- perform: async function(options){
-
- const gasPrice = (options || {}).gasPrice
- , chainId = (options || {}).chainId
- , deployOptions = {returnType: returnTypes.transactionReceipt()}
- ;
-
- if(!gasPrice || !chainId){
- let errorParams = {
- internal_error_identifier: 'l_swao_2',
- api_error_identifier: 'invalid_api_params',
- error_config: errorConfig,
- params_error_identifiers: ['gas_price_invalid', 'chain_id_invalid'],
- debug_options: {}
- };
- return Promise.resolve(responseHelper.paramValidationError(errorParams));
- }
- const DeployWorkerObject = new DeployWorkersKlass({
- gas_price: gasPrice,
- options: deployOptions
- });
- const deployResult = await DeployWorkerObject.perform();
-
- if (deployResult.isSuccess()) {
- const contractAddress = deployResult.data.transaction_receipt.contractAddress;
- logger.win("contractAddress: ", contractAddress);
-
- logger.debug("Setting Ops Address to: ", opsAddress);
- const setOpsOptions = {
- returnType: returnTypes.transactionReceipt(),
- tag: ''
- }
- ;
- const SetOpsObject = new SetOpsKlass({
- contract_address: contractAddress,
- gas_price: gasPrice,
- chain_id: chainId,
- deployer_address: deployerAddress,
- deployer_passphrase: deployerPassphrase,
- ops_address: opsAddress,
- options: setOpsOptions
- });
- var result = await SetOpsObject.perform();
- logger.debug(result);
-
- const GetOpsObject = new GetOpsKlass({
- contract_address: contractAddress,
- gas_price: gasPrice,
- chain_id: chainId
- });
- const getOpsResult = await GetOpsObject.perform();
- const contractOpsAddress = getOpsResult.data.opsAddress;
- logger.debug("Ops Address Set to: ", contractOpsAddress);
- return Promise.resolve(responseHelper.successWithData({workerContractAddress: contractAddress}));
- } else{
- logger.error("Error deploying contract");
- logger.error(deployResult);
- return Promise.resolve(deployResult);
- }
-
- let errorParams = {
- internal_error_identifier: 'l_swao_1',
- api_error_identifier: 'unhandled_api_error',
- error_config: errorConfig,
- debug_options: {}
- };
-
- return Promise.resolve(responseHelper.error(errorParams));
- }
-
-};
-
-module.exports = SetWorkerOps;
-
diff --git a/lib/transaction_helper.js b/lib/transaction_helper.js
deleted file mode 100644
index 255b51c..0000000
--- a/lib/transaction_helper.js
+++ /dev/null
@@ -1,797 +0,0 @@
-//"use strict";
-
-/**
- *
- * This is transaction helper that manages the cache updation
- *
- * @module lib/transaction_helper
- *
- */
-const BigNumber = require('bignumber.js')
- , openSTStorage = require('@openstfoundation/openst-storage')
-;
-
-const rootPrefix = '..'
- , responseHelper = require(rootPrefix + '/lib/formatter/response')
- , Token = require(rootPrefix + '/lib/contract_interact/branded_token')
- , UserAirdropDetailCacheKlass = require(rootPrefix + '/lib/cache_multi_management/user_airdrop_detail')
- , AdjustAirdropAmountKlass = require(rootPrefix + '/lib/airdrop_management/adjust_airdrop_amount')
- , web3EventsDecoder = require(rootPrefix + '/lib/web3/events/decoder')
- , logger = require(rootPrefix + '/helpers/custom_console_logger')
- , eventGlobalConstants = require(rootPrefix+'/lib/global_constant/events')
- , basicHelper = require(rootPrefix + '/helpers/basic_helper')
- , AirdropModelCacheKlass = require(rootPrefix + '/lib/cache_management/airdrop_model')
- , paramErrorConfig = require(rootPrefix + '/config/param_error_config')
- , apiErrorConfig = require(rootPrefix + '/config/api_error_config')
- , ddbServiceObj = require(rootPrefix + '/lib/dynamoDB_service')
- , autoScalingServiceObj = require(rootPrefix + '/lib/auto_scaling_service')
-;
-
-const errorConfig = {
- param_error_config: paramErrorConfig,
- api_error_config: apiErrorConfig
-};
-
-/**
- * constructor
- *
- * @param {string} chainId - chain id
- *
- * @constructor
- */
-const TransactionHelper = module.exports= function(chainId) {
- const oThis = this
- ;
-
- oThis.chainId = chainId;
-};
-
-TransactionHelper.prototype = {
- /**
- * Credit balance in cache
- *
- * @param {string} brandedTokenAddress - branded token address
- * @param {string} owner - Account address
- * @param {BigNumber} bigAmount - amount to be credited
- *
- * @return {promise}
- */
- creditBalance: function (brandedTokenAddress, owner, bigAmount) {
- const oThis = this
- , brandedToken = new Token(brandedTokenAddress, oThis.chainId)
- ;
-
- return brandedToken.creditBalance(owner, bigAmount);
- },
-
- /**
- * Debit balance in cache
- *
- * @param {string} brandedTokenAddress - branded token address
- * @param {string} owner - Account address
- * @param {BigNumber} bigAmount - amount to be debited
- *
- * @return {promise}
- */
- debitBalance: function (brandedTokenAddress, owner, bigAmount) {
- const oThis = this
- , brandedToken = new Token(brandedTokenAddress, oThis.chainId)
- ;
-
- return brandedToken.debitBalance(owner, bigAmount);
- },
-
- /**
- * Update balance to cache
- *
- * @param {string} brandedTokenAddress - branded token address
- * @param {string} owner - Account address
- * @param {BigNumber} toCreditBigAmount - to credit amount - this can be negative also
- *
- * @return {promise}
- */
- updateBalance: function (brandedTokenAddress, owner, toCreditBigAmount) {
- const oThis = this
- ;
-
- if(basicHelper.convertToBigNumber(toCreditBigAmount).gt(0)) {
- return oThis.creditBalance(brandedTokenAddress, owner, toCreditBigAmount);
- } else if(basicHelper.convertToBigNumber(toCreditBigAmount).lt(0)) {
- return oThis.debitBalance(brandedTokenAddress, owner, basicHelper.convertToBigNumber(toCreditBigAmount).mul(-1));
- } else {
- return Promise.resolve(responseHelper.successWithData({}));
- }
- },
-
- /**
- * Update airdrop balance
- *
- * @param {string} airdropContractAddress - airdrop contract address
- * @param {string} owner - Account address
- * @param {BigNumber} toCreditBigAmount - to credit amount - this can be negative also
- *
- * @return {promise}
- */
- updateAirdropBalance: function (airdropContractAddress, owner, toCreditBigAmount) {
- const oThis = this
- ;
-
- if(basicHelper.convertToBigNumber(toCreditBigAmount).gt(0)) {
- return oThis.creditAirdropBalance(airdropContractAddress, owner, toCreditBigAmount);
- } else if(basicHelper.convertToBigNumber(toCreditBigAmount).lt(0)) {
- return oThis.debitAirdropBalance(airdropContractAddress, owner,
- basicHelper.convertToBigNumber(toCreditBigAmount).mul(-1));
- } else {
- return Promise.resolve(responseHelper.successWithData({}));
- }
- },
-
- /**
- * Credit airdrop balance in db and clear cache
- * It decreases airdrop_used_amount for user in user_airdrop_details table
- * Clears the cache
- *
- * @param {string} airdropContractAddress - airdrop contract address
- * @param {string} owner - Account address
- * @param {BigNumber} bigAmount - amount to be credited
- *
- * @return {promise}
- */
- creditAirdropBalance: async function (airdropContractAddress, owner, bigAmount) {
- const oThis = this
- ;
-
- bigAmount = basicHelper.convertToBigNumber(bigAmount);
- if (bigAmount.gt(0)) {
- const AdjustAirdropAmountObject = new AdjustAirdropAmountKlass({
- airdropContractAddress: airdropContractAddress,
- userAddress: owner,
- airdropAmountUsed: bigAmount.toString(10)
- });
- const creditAirdropUsedAmountResponse = await AdjustAirdropAmountObject.creditAirdropUsedAmount();
-
- logger.debug('creditAirdropBalance.result', creditAirdropUsedAmountResponse);
- oThis.clearUserDetailCache(airdropContractAddress, owner);
- return Promise.resolve(creditAirdropUsedAmountResponse);
- }
- return Promise.resolve(responseHelper.successWithData({}));
- },
-
- /**
- * Debit airdrop balance in db and clear cache
- * It increases airdrop_used_amount for user in user_airdrop_details table
- * Clears the cache
- *
- * @param {string} airdropContractAddress - airdrop contract address
- * @param {string} owner - Account address
- * @param {BigNumber} bigAmount - amount to be debited
- *
- * @return {promise}
- */
- debitAirdropBalance: async function (airdropContractAddress, owner, bigAmount) {
- const oThis = this;
- bigAmount = basicHelper.convertToBigNumber(bigAmount);
- if (bigAmount.gt(0)) {
- const AdjustAirdropAmountObject = new AdjustAirdropAmountKlass({
- airdropContractAddress: airdropContractAddress,
- userAddress: owner,
- airdropAmountUsed: bigAmount.toString(10)
- });
- const debitAirdropUsedAmountResponse = await AdjustAirdropAmountObject.debitAirdropUsedAmount();
-
- logger.debug('debitAirdropBalance.result', debitAirdropUsedAmountResponse);
- oThis.clearUserDetailCache(airdropContractAddress, owner);
- return Promise.resolve(debitAirdropUsedAmountResponse);
- }
- return Promise.resolve(responseHelper.successWithData({}));
- },
-
- /**
- * Clear user detail cache for the user addressess
- *
- * @param {string} airdropContractAddress - airdrop contract address
- * @param {string} owner - Account address
- *
- * @return {promise}
- */
- clearUserDetailCache: async function(airdropContractAddress, owner) {
- const oThis = this
- , airdropModelCacheObject = new AirdropModelCacheKlass({useObject: true, contractAddress: airdropContractAddress})
- , airdropModelCacheResponse = await airdropModelCacheObject.fetch()
- , airdropRecord = airdropModelCacheResponse.data[airdropContractAddress]
- ;
-
- const userAirdropDetailCache = new UserAirdropDetailCacheKlass({
- chainId: oThis.chainId,
- airdropId: airdropRecord.id,
- userAddresses: [owner]
- });
-
- return Promise.resolve(await userAirdropDetailCache.clear());
- },
-
- /**
- * Before pay function, this is called before the pay is called
- *
- * @param {string} brandedTokenAddress - branded token address
- * @param {string} spenderAddress - spender address
- * @param {BigNumber} estimatedPayAmount - estimated pay amount in weis
- *
- * @return {promise}
- *
- */
- beforePay: async function(brandedTokenAddress, spenderAddress, estimatedPayAmount) {
- const oThis = this
- ;
-
- logger.debug('lib/transaction_helper.js:beforePay called with params:',
- {brandedTokenAddress: brandedTokenAddress, spender: spenderAddress, estimatedPayAmount: estimatedPayAmount});
-
- const balanceUpdateResponse = await new openSTStorage.TokenBalanceModel({
- ddb_service: ddbServiceObj,
- auto_scaling: autoScalingServiceObj,
- erc20_contract_address: brandedTokenAddress
- }).update({
- ethereum_address: spenderAddress,
- un_settled_debit_amount: estimatedPayAmount.toString(10)
- }).catch(function (error) {
- if (responseHelper.isCustomResult(error)) {
- return error;
- } else {
- logger.error(`${__filename}::beforeAirdropPay::catch`);
- logger.error(error);
- return responseHelper.error({
- internal_error_identifier: 'l_th_beforePay_1',
- api_error_identifier: 'unhandled_api_error',
- error_config: errorConfig,
- debug_options: {}
- });
- }
- });
-
- if (balanceUpdateResponse.isFailure()) {
- return balanceUpdateResponse;
- }
- return responseHelper.successWithData({});
- },
-
- /**
- * After pay function, this is called after the pay is successfull
- *
- * @param {string} brandedTokenAddress - branded token address
- * @param {string} spenderAddress - spender address
- * @param {BigNumber} estimatedPayAmount - estimated pay amount in weis
- * @param {string} beneficiaryAddress - beneficiary address
- * @param {BigNumber} actualBeneficiaryAmount - actual beneficiary amount in weis
- * @param {string} commissionBeneficiaryAddress - commission beneficiary address
- * @param {BigNumber} actualCommissionBeneficiaryAmount - actual commission beneficiary amount
- *
- * @return {promise}
- *
- */
- afterPaySuccess: async function(brandedTokenAddress, spenderAddress, estimatedPayAmount, beneficiaryAddress,
- actualBeneficiaryAmount, commissionBeneficiaryAddress, actualCommissionBeneficiaryAmount) {
- const oThis = this
- , promiseArray = []
- , actualTotalAmount = actualBeneficiaryAmount.plus(actualCommissionBeneficiaryAmount)
- ;
-
- promiseArray.push(new openSTStorage.TokenBalanceModel({
- ddb_service: ddbServiceObj,
- auto_scaling: autoScalingServiceObj,
- erc20_contract_address: brandedTokenAddress
- }).update({
- ethereum_address: beneficiaryAddress,
- settle_amount: actualBeneficiaryAmount.toString(10)
- }).catch(function (error) {
- if (responseHelper.isCustomResult(error)) {
- return error;
- } else {
- logger.error(`${__filename}::afterPaySuccess::catch`);
- logger.error(error);
- return responseHelper.error({
- internal_error_identifier: 'l_th_afterPaySuccess_1',
- api_error_identifier: 'unhandled_api_error',
- error_config: errorConfig,
- debug_options: {}
- });
- }
- }));
-
- // credit commissionBeneficiaryAddress with actualCommissionBeneficiaryAmount - add it to the settled_amount
- promiseArray.push(new openSTStorage.TokenBalanceModel({
- ddb_service: ddbServiceObj,
- auto_scaling: autoScalingServiceObj,
- erc20_contract_address: brandedTokenAddress
- }).update({
- ethereum_address: commissionBeneficiaryAddress,
- settle_amount: actualCommissionBeneficiaryAmount.toString(10)
- }).catch(function (error) {
- if (responseHelper.isCustomResult(error)) {
- return error;
- } else {
- logger.error(`${__filename}::afterPaySuccess::catch`);
- logger.error(error);
- return responseHelper.error({
- internal_error_identifier: 'l_th_afterPaySuccess_2',
- api_error_identifier: 'unhandled_api_error',
- error_config: errorConfig,
- debug_options: {}
- });
- }
- }));
-
- // we had pessimistically debitted estimatedDebitAmount from spenderAddress.
- // now adjusting the debit to actualDebitAmount.
- // subtract estimatedDebitAmount from un_settled_debit_amount AND subtract actualDebitAmount from settle_amount.
- promiseArray.push(new openSTStorage.TokenBalanceModel({
- ddb_service: ddbServiceObj,
- auto_scaling: autoScalingServiceObj,
- erc20_contract_address: brandedTokenAddress
- }).update({
- ethereum_address: spenderAddress,
- settle_amount: (actualTotalAmount.mul(basicHelper.convertToBigNumber(-1))).toString(10),
- un_settled_debit_amount: (estimatedPayAmount.mul(basicHelper.convertToBigNumber(-1))).toString(10)
- }).catch(function (error) {
- if (responseHelper.isCustomResult(error)) {
- return error;
- } else {
- logger.error(`${__filename}::afterPaySuccess::catch`);
- logger.error(error);
- return responseHelper.error({
- internal_error_identifier: 'l_th_afterPaySuccess_3',
- api_error_identifier: 'unhandled_api_error',
- error_config: errorConfig,
- debug_options: {}
- });
- }
- }));
-
- return Promise.all(promiseArray);
- },
-
- /**
- * After pay function, this is called after the pay is failed
- *
- * @param {string} brandedTokenAddress - branded token address
- * @param {string} spenderAddress - spender address
- * @param {BigNumber} estimatedPayAmount - estimated pay amount in weis
- *
- * @return {promise}
- */
- afterPayFailure: async function (brandedTokenAddress, spenderAddress, estimatedPayAmount) {
- const oThis = this
- ;
-
- logger.debug('lib/transaction_helper.js:afterPayFailure called with params:',
- {brandedTokenAddress: brandedTokenAddress, spender: spenderAddress, estimatedPayAmount: estimatedPayAmount});
-
- const balanceUpdateResponse = await new openSTStorage.TokenBalanceModel({
- ddb_service: ddbServiceObj,
- auto_scaling: autoScalingServiceObj,
- erc20_contract_address: brandedTokenAddress
- }).update({
- ethereum_address: spenderAddress,
- un_settled_debit_amount: (estimatedPayAmount.mul(basicHelper.convertToBigNumber(-1))).toString(10)
- }).catch(function (error) {
- if (responseHelper.isCustomResult(error)) {
- return error;
- } else {
- logger.error(`${__filename}::afterPayFailure::catch`);
- logger.error(error);
- return responseHelper.error({
- internal_error_identifier: 'l_th_afterPayFailure_1',
- api_error_identifier: 'unhandled_api_error',
- error_config: errorConfig,
- debug_options: {}
- });
- }
- });
-
- if (balanceUpdateResponse.isFailure()) {
- return balanceUpdateResponse;
- }
- return responseHelper.successWithData({});
- },
-
- /**
- * Before airdrop pay function, this is called before the pay is called
- * @param {string} brandedTokenAddress - branded token address
- * @param {string} airdropAddress - airdrop contract address
- * @param {string} spenderAddress - spender address
- * @param {BigNumber} totalTransferAmount - estimated pay amount in weis
- * @param {BigNumber} airdropBalanceToUse - estimated airdrop amount
- * @param {string} airdropBugdetAddress - airdrop budget holder address
- *
- * @return {promise>}
- *
- */
- beforeAirdropPay: async function(brandedTokenAddress, airdropAddress, spenderAddress, totalTransferAmount, airdropBalanceToUse,
- airdropBugdetAddress) {
-
- logger.debug('lib/transaction_helper.js:beforeAirdropPay called with params:',
- {brandedTokenAddress: brandedTokenAddress, airdropAddress: airdropAddress, spender: spenderAddress,
- estimatedAirdropAmount: airdropBalanceToUse, airdropBugdetAddress: airdropBugdetAddress});
-
- const oThis = this
- , amountToDebitFromChain = totalTransferAmount.minus(airdropBalanceToUse)
- , promiseArray = []
- ;
-
- // Pessimistic debit of spender.
- if (amountToDebitFromChain.gt(0)) {
- promiseArray.push(new openSTStorage.TokenBalanceModel({
- ddb_service: ddbServiceObj,
- auto_scaling: autoScalingServiceObj,
- erc20_contract_address: brandedTokenAddress
- }).update({
- ethereum_address: spenderAddress,
- un_settled_debit_amount: amountToDebitFromChain.toString(10)
- }).catch(function (error) {
- if (responseHelper.isCustomResult(error)) {
- return error;
- } else {
- logger.error(`${__filename}::beforeAirdropPay::catch`);
- logger.error(error);
- return responseHelper.error({
- internal_error_identifier: 'l_th_beforeAirdropPay_1',
- api_error_identifier: 'unhandled_api_error',
- error_config: errorConfig,
- debug_options: {}
- });
- }
- }));
- }
-
- //Debit airdrop balance of spender from DB.
- promiseArray.push(oThis.updateAirdropBalance(airdropAddress, spenderAddress, airdropBalanceToUse.mul(basicHelper.convertToBigNumber(-1))));
-
- // pessimistic debit of airdrop budget holder.
- promiseArray.push(new openSTStorage.TokenBalanceModel({
- ddb_service: ddbServiceObj,
- auto_scaling: autoScalingServiceObj,
- erc20_contract_address: brandedTokenAddress
- }).update({
- ethereum_address: airdropBugdetAddress,
- un_settled_debit_amount: airdropBalanceToUse.toString(10)
- }).catch(function (error) {
- if (responseHelper.isCustomResult(error)) {
- return error;
- } else {
- logger.error(`${__filename}::beforeAirdropPay::catch`);
- logger.error(error);
- return responseHelper.error({
- internal_error_identifier: 'l_th_beforeAirdropPay_2',
- api_error_identifier: 'unhandled_api_error',
- error_config: errorConfig,
- debug_options: {}
- });
- }
- }));
-
- return Promise.all(promiseArray);
- },
-
- /**
- * After airdrop pay function, this is called after the pay is successfull
- *
- * @param {string} brandedTokenAddress - branded token address
- * @param {string} airdropAddress - airdrop contract address
- * @param {string} spenderAddress - spender address
- * @param {BigNumber} estimatedPayAmount - estimated pay amount in weis
- * @param {BigNumber} estimatedAirdropAmount - estimated airdrop amount
- * @param {string} beneficiaryAddress - beneficiary address
- * @param {BigNumber} actualBeneficiaryAmount - actual beneficiary amount in weis
- * @param {string} commissionBeneficiaryAddress - commission beneficiary address
- * @param {BigNumber} actualCommissionBeneficiaryAmount - actual commission beneficiary amount
- * @param {BigNumber} actualAirdropAmount - actual airdrop amount
- * @param {string} airdropBugdetAddress - airdrop budget holder address
- *
- * @return {promise}
- */
- afterAirdropPaySuccess: async function(brandedTokenAddress, airdropAddress, spenderAddress, estimatedPayAmount,
- estimatedAirdropAmount, beneficiaryAddress, actualBeneficiaryAmount,
- commissionBeneficiaryAddress, actualCommissionBeneficiaryAmount,
- actualAirdropAmount, airdropBugdetAddress) {
-
- console.log("-PPP--------------------------------------------------------------6--", Date.now(), 'ms');
- logger.debug('lib/transaction_helper.js:afterAirdropPaySuccess called with params:',
- {brandedTokenAddress: brandedTokenAddress, airdropAddress: airdropAddress, spender: spenderAddress,
- estimatedPayAmount: estimatedPayAmount, beneficiaryAddress: beneficiaryAddress,
- actualBeneficiaryAmount: actualBeneficiaryAmount, commissionBeneficiaryAddress: commissionBeneficiaryAddress,
- actualCommissionBeneficiaryAmount: actualCommissionBeneficiaryAmount,
- estimatedAirdropAmount: estimatedAirdropAmount, airdropBugdetAddress: airdropBugdetAddress,
- actualAirdropAmount: actualAirdropAmount});
-
- const oThis = this
- , estimatedDebitAmount = estimatedPayAmount.minus(estimatedAirdropAmount)
- , actualTotalAmount = actualBeneficiaryAmount.plus(actualCommissionBeneficiaryAmount)
- , actualDebitAmount = actualTotalAmount.minus(actualAirdropAmount)
- , promiseArray = []
- ;
-
- // credit beneficiaryAddress with actualBeneficiaryAmount - add it to the settled_amount
- promiseArray.push(new openSTStorage.TokenBalanceModel({
- ddb_service: ddbServiceObj,
- auto_scaling: autoScalingServiceObj,
- erc20_contract_address: brandedTokenAddress
- }).update({
- ethereum_address: beneficiaryAddress,
- settle_amount: actualBeneficiaryAmount.toString(10)
- }).catch(function (error) {
- if (responseHelper.isCustomResult(error)) {
- return error;
- } else {
- logger.error(`${__filename}::afterAirdropPaySuccess::catch`);
- logger.error(error);
- return responseHelper.error({
- internal_error_identifier: 'l_th_afterAirdropPaySuccess_1',
- api_error_identifier: 'unhandled_api_error',
- error_config: errorConfig,
- debug_options: {}
- });
- }
- }));
- console.log("-PPP--------------------------------------------------------------6.1--", Date.now(), 'ms');
- // credit commissionBeneficiaryAddress with actualCommissionBeneficiaryAmount - add it to the settled_amount
- promiseArray.push(new openSTStorage.TokenBalanceModel({
- ddb_service: ddbServiceObj,
- auto_scaling: autoScalingServiceObj,
- erc20_contract_address: brandedTokenAddress
- }).update({
- ethereum_address: commissionBeneficiaryAddress,
- settle_amount: actualCommissionBeneficiaryAmount.toString(10)
- }).catch(function (error) {
- if (responseHelper.isCustomResult(error)) {
- return error;
- } else {
- logger.error(`${__filename}::afterAirdropPaySuccess::catch`);
- logger.error(error);
- return responseHelper.error({
- internal_error_identifier: 'l_th_afterAirdropPaySuccess_2',
- api_error_identifier: 'unhandled_api_error',
- error_config: errorConfig,
- debug_options: {}
- });
- }
- }));
- console.log("-PPP--------------------------------------------------------------6.2--", Date.now(), 'ms');
- // we had pessimistically debitted estimatedDebitAmount from spenderAddress.
- // now adjusting the debit to actualDebitAmount.
- // subtract estimatedDebitAmount from un_settled_debit_amount AND subtract actualDebitAmount from settle_amount.
- promiseArray.push(new openSTStorage.TokenBalanceModel({
- ddb_service: ddbServiceObj,
- auto_scaling: autoScalingServiceObj,
- erc20_contract_address: brandedTokenAddress
- }).update({
- ethereum_address: spenderAddress,
- settle_amount: (actualDebitAmount.mul(basicHelper.convertToBigNumber(-1))).toString(10),
- un_settled_debit_amount: (estimatedDebitAmount.mul(basicHelper.convertToBigNumber(-1))).toString(10)
- }).catch(function (error) {
- if (responseHelper.isCustomResult(error)) {
- return error;
- } else {
- logger.error(`${__filename}::afterAirdropPaySuccess::catch`);
- logger.error(error);
- return responseHelper.error({
- internal_error_identifier: 'l_th_afterAirdropPaySuccess_3',
- api_error_identifier: 'unhandled_api_error',
- error_config: errorConfig,
- debug_options: {}
- });
- }
- }));
- console.log("-PPP--------------------------------------------------------------6.3--", Date.now(), 'ms');
- // we had debited estimatedAirdropAmount previously from spender balance, now adjusting the delta.
- promiseArray.push(oThis.updateAirdropBalance(airdropAddress, spenderAddress, estimatedAirdropAmount.minus(actualAirdropAmount)));
- console.log("-PPP--------------------------------------------------------------6.4--", Date.now(), 'ms');
- // changes for spender address.
- // we had added estimatedAirdropAmount previously to airdropBugdetAddress un_settled_debit_amount, now subtracting the same.
- // AND subtracting actualAirdropAmount from settle_amount
- promiseArray.push(new openSTStorage.TokenBalanceModel({
- ddb_service: ddbServiceObj,
- auto_scaling: autoScalingServiceObj,
- erc20_contract_address: brandedTokenAddress
- }).update({
- ethereum_address: airdropBugdetAddress,
- settle_amount: (actualAirdropAmount.mul(basicHelper.convertToBigNumber(-1))).toString(10),
- un_settled_debit_amount: (estimatedAirdropAmount.mul(basicHelper.convertToBigNumber(-1))).toString(10)
- }).catch(function (error) {
- if (responseHelper.isCustomResult(error)) {
- return error;
- } else {
- logger.error(`${__filename}::afterAirdropPaySuccess::catch`);
- logger.error(error);
- return responseHelper.error({
- internal_error_identifier: 'l_th_afterAirdropPaySuccess_4',
- api_error_identifier: 'unhandled_api_error',
- error_config: errorConfig,
- debug_options: {}
- });
- }
- }));
- console.log("-PPP--------------------------------------------------------------6.5--", Date.now(), 'ms');
- let resp = await Promise.all(promiseArray)
- console.log("-PPP--------------------------------------------------------------6.6--", Date.now(), 'ms');
- return resp;
- },
-
- /**
- * After airdrop pay function, this is called after the pay is failed
- *
- * @param {string} brandedTokenAddress - branded token address
- * @param {string} airdropAddress - airdrop contract address
- * @param {string} spenderAddress - spender address
- * @param {BigNumber} estimatedPayAmount - estimated pay amount in weis
- * @param {BigNumber} estimatedAirdropAmount - estimated airdrop amount
- * @param {string} airdropBugdetAddress - airdrop budget holder address
- *
- * @return {promise}
- *
- */
- afterAirdropPayFailure: function (brandedTokenAddress, airdropAddress, spenderAddress,
- estimatedPayAmount, estimatedAirdropAmount, airdropBugdetAddress) {
-
- logger.debug('lib/transaction_helper.js:afterAirdropPayFailure called with params:',
- {brandedTokenAddress: brandedTokenAddress, airdropAddress: airdropAddress, spender: spenderAddress,
- estimatedAirdropAmount: estimatedAirdropAmount, airdropBugdetAddress: airdropBugdetAddress});
-
- const oThis = this
- , amountToCreditToChain = estimatedPayAmount.minus(estimatedAirdropAmount)
- , zero = basicHelper.convertToBigNumber(0)
- , addressToBalanceChangeMap = {}
- , addressToAirdropBalanceChangeMap = {}
- ;
-
- addressToBalanceChangeMap[spenderAddress] = zero;
- addressToBalanceChangeMap[airdropBugdetAddress] = zero;
- addressToAirdropBalanceChangeMap[spenderAddress] = zero;
-
- const promiseArray = [];
-
- if (amountToCreditToChain.gt(0)) {
- // rollback the pessimistic debit made from the spender address
- promiseArray.push(new openSTStorage.TokenBalanceModel({
- ddb_service: ddbServiceObj,
- auto_scaling: autoScalingServiceObj,
- erc20_contract_address: brandedTokenAddress
- }).update({
- ethereum_address: spenderAddress,
- un_settled_debit_amount: (amountToCreditToChain.mul(basicHelper.convertToBigNumber(-1))).toString(10)
- }).catch(function (error) {
- if (responseHelper.isCustomResult(error)) {
- return error;
- } else {
- logger.error(`${__filename}::afterAirdropPayFailure::catch`);
- logger.error(error);
- return responseHelper.error({
- internal_error_identifier: 'l_th_afterAirdropPayFailure_1',
- api_error_identifier: 'unhandled_api_error',
- error_config: errorConfig,
- debug_options: {}
- });
- }
- }));
- }
-
- promiseArray.push(oThis.updateAirdropBalance(airdropAddress, spenderAddress, estimatedAirdropAmount));
-
- // rollback the pessimistic debit made from airdrop budget holder address.
- promiseArray.push(new openSTStorage.TokenBalanceModel({
- ddb_service: ddbServiceObj,
- auto_scaling: autoScalingServiceObj,
- erc20_contract_address: brandedTokenAddress
- }).update({
- ethereum_address: airdropBugdetAddress,
- un_settled_debit_amount: (estimatedAirdropAmount.mul(basicHelper.convertToBigNumber(-1))).toString(10)
- }).catch(function (error) {
- if (responseHelper.isCustomResult(error)) {
- return error;
- } else {
- logger.error(`${__filename}::afterAirdropPayFailure::catch`);
- logger.error(error);
- return responseHelper.error({
- internal_error_identifier: 'l_th_afterAirdropPayFailure_2',
- api_error_identifier: 'unhandled_api_error',
- error_config: errorConfig,
- debug_options: {}
- });
- }
- }));
-
- return Promise.all(promiseArray);
- },
-
- /**
- * Get actual beneficiary amount, actual commission amount and actual airdrop amount from transaction receipt
- *
- * @param {Object} transactionReceipt - transaction receipt
- * @param {Object} addressToNameMap - address to name map object
- * @param {string} eventName - Event name
- *
- * @return {result}
- */
- getActualAmountsFromReceipt: function(transactionReceipt, addressToNameMap, eventName) {
-
- const oThis = this;
- // decode events
- const decodedEvent = web3EventsDecoder.perform(transactionReceipt, addressToNameMap);
- return oThis.getActualAmountsFromDecodedEvents(decodedEvent.formattedTransactionReceipt.eventsData, eventName);
-
- },
-
- /**
- * Get actual beneficiary amount, actual commission amount and actual airdrop amount from decoded events
- *
- * @param {Object} decodedEvent - Decoded event from receipt
- * @param {string} eventName - Event name
- *
- * @return {result}
- */
- getActualAmountsFromDecodedEvents: function(events, eventName) {
-
- var actualBeneficiaryAmount = new BigNumber(0)
- , actualCommissionAmount = new BigNumber(0)
- , actualAirdropAmount = new BigNumber(0)
- , isEventDecoded = false
- ;
-
- // get event data
- if (events != undefined && events != null) {
- // get whats the actual transfer amounts
- for (var i = 0; i < events.length; i++) {
- const eventData = events[i];
- if (eventData.name === eventName) {
- const paymentEvents = eventData.events;
- for (var eventCount = 0; eventCount < paymentEvents.length; eventCount++) {
- const paymentEventsData = paymentEvents[eventCount];
- if (paymentEventsData.name === eventGlobalConstants.eventAttribute.tokenAmount()) {
- isEventDecoded = true;
- actualBeneficiaryAmount = new BigNumber(paymentEventsData.value);
- } else if (paymentEventsData.name === eventGlobalConstants.eventAttribute.commissionTokenAmount()) {
- isEventDecoded = true;
- actualCommissionAmount = new BigNumber(paymentEventsData.value);
- } else if (paymentEventsData.name === eventGlobalConstants.eventAttribute.airdropAmount()) {
- isEventDecoded = true;
- actualAirdropAmount = new BigNumber(paymentEventsData.value);
- }
- }
- }
-
- }
- }
- if (isEventDecoded) {
- return responseHelper.successWithData(
- {actualBeneficiaryAmount: actualBeneficiaryAmount, actualCommissionAmount: actualCommissionAmount,
- actualAirdropAmount: actualAirdropAmount});
- } else {
- let errorParams = {
- internal_error_identifier: 'l_th_getActualAmountsFromDecodedEvents_1',
- api_error_identifier: 'no_events_in_receipt',
- error_config: errorConfig,
- debug_options: {}
- };
- return responseHelper.error(errorParams);
- }
- },
-
- /**
- * Check if all response is success
- *
- * @param {array} results - response array
- *
- * @return {boolean}
- *
- */
- isAllResponseSuccessful: function (results) {
- var isSuccess = true;
- for (var i = results.length - 1; i >= 0; i--) {
- const resultObject = results[i];
- if (resultObject.isFailure()) {
- isSuccess = false;
- break;
- }
- }
- return isSuccess;
- }
-};
diff --git a/lib/utils.js b/lib/utils.js
deleted file mode 100644
index 1d6aa75..0000000
--- a/lib/utils.js
+++ /dev/null
@@ -1,36 +0,0 @@
-"use strict";
-
-const Utils = function () {};
-
-Utils.prototype = {
-
- constructor: Utils,
-
- formatDbDate: function (dateObj) {
- function pad(n) {
- return n<10 ? "0"+n : n
- }
-
- return dateObj.getFullYear()+"-"+
- pad(dateObj.getMonth()+1)+"-"+
- pad(dateObj.getDate())+" "+
- pad(dateObj.getHours())+":"+
- pad(dateObj.getMinutes())+":"+
- pad(dateObj.getSeconds())
- },
-
- invert: function(json){
- var ret = {};
- for(var key in json){
- ret[json[key]] = key;
- }
- return ret;
- },
-
- clone: function (obj) {
- return JSON.parse(JSON.stringify(obj));
- }
-
-};
-
-module.exports = new Utils;
\ No newline at end of file
diff --git a/lib/web3/events/decoder.js b/lib/web3/events/decoder.js
deleted file mode 100644
index 89e7549..0000000
--- a/lib/web3/events/decoder.js
+++ /dev/null
@@ -1,110 +0,0 @@
-"use strict";
-
-/**
- * Decode logs from a transaction receipt
- *
- * @module lib/web3/events/formatter
- *
- */
-
-const rootPrefix = '../../..'
- , coreAddresses = require(rootPrefix+'/config/core_addresses')
- ;
-
-const web3EventsDecoder = function () {};
-
-/**
- * Ivent Decoder.
- *
- * @namespace web3EventsDecoder
- *
- */
-web3EventsDecoder.prototype = {
-
- /**
- * performer
- *
- * @param {Object} txReceipt
- * @param {Hash} addressToNameMap - Map of the address(key) to name(value)
- *
- * @returns {result} object of {@link resulthelpwe\\er}
- *
- * @methodOf web3EventsDecoder
- *
- */
- perform: function(txReceipt, addressToNameMap) {
- const oThis = this;
-
- var decodedEvents = [];
-
- // Transaction receipt not found
- if (!txReceipt) {
- return 'Transaction receipt was not found.';
- }
-
- // Block not yet mined
- if (!txReceipt.blockNumber) {
- return 'Transaction not yet mined. Please try after some time.';
- }
-
- var toAddr = txReceipt.to;
- var contractName = oThis.getContractNameFor(toAddr, addressToNameMap);
-
-
- // if the address is a known address
- if (contractName && txReceipt.logs.length > 0) {
-
- var abiDecoder = require('abi-decoder')
- , relevantLogs = [];
-
- for (var i = 0; i < txReceipt.logs.length; i++) {
-
- var currContract = oThis.getContractNameFor(txReceipt.logs[i].address, addressToNameMap);
-
- console.debug('**** contract address: ' + txReceipt.logs[i].address + ' at log index(' + i + ') in TxHash: ' + txReceipt.transactionHash + '');
-
- if (!currContract) {
- console.error('**** No contract found for contract address: ' + txReceipt.logs[i].address + ' at log index(' + i + ') in TxHash: ' + txReceipt.transactionHash + '');
- continue;
- }
-
- const currContractABI = coreAddresses.getAbiForContract(currContract);
-
- // ABI not found
- if (!currContractABI) {
- return 'ABI not found for contract ';
- }
-
- relevantLogs.push(txReceipt.logs[i]);
- abiDecoder.addABI(currContractABI);
- }
-
- if(relevantLogs.length > 0) {
- decodedEvents = abiDecoder.decodeLogs(relevantLogs);
- }
-
- }
-
- return {
- rawTransactionReceipt: txReceipt,
- formattedTransactionReceipt: {
- transactionHash: txReceipt.transactionHash,
- blockHash: txReceipt.blockHash,
- blockNumber: txReceipt.blockNumber,
- eventsData: decodedEvents,
- toAddress: toAddr,
- contractAddress: txReceipt.contractAddress || ''
- }
- };
- }
- , getContractNameFor: function ( address, addressToNameMap ) {
- const lcAddress = String( address ).toLowerCase();
- if ( !addressToNameMap || !( addressToNameMap[ address ] || addressToNameMap[ lcAddress ] ) ) {
- return coreAddresses.getContractNameFor( address );
- }
- return addressToNameMap[ address ] || addressToNameMap[ lcAddress ];
- }
-
-};
-
-module.exports = new web3EventsDecoder();
\ No newline at end of file
diff --git a/lib/web3/events/formatter.js b/lib/web3/events/formatter.js
deleted file mode 100644
index 92ddc94..0000000
--- a/lib/web3/events/formatter.js
+++ /dev/null
@@ -1,53 +0,0 @@
-"use strict";
-
-/**
- * Format decoded event into Hash with all the events received into it.
- *
- * @module lib/web3/events/formatter
- *
- */
-
-const web3EventsFormatter = module.exports = function () {};
-
-/**
- * Event Formatter.
- *
- * @namespace web3EventsFormatter
- *
- */
-web3EventsFormatter.prototype = {
-
- /**
- * performer
- *
- * @param formattedTransactionReceipt
- * @returns {Promise.<{}>}
- *
- * @methodOf web3EventsFormatter
- *
- */
- perform: function(formattedTransactionReceipt) {
- var eventsData = formattedTransactionReceipt.eventsData
- , formattedEvents = {};
-
- for (var i = 0; i < eventsData.length; i++) {
- var currEvent = eventsData[i]
- , currEventName = currEvent.name
- , currEventAddr = currEvent.address
- , currEventParams = currEvent.events;
-
- formattedEvents[currEventName] = {address: currEventAddr};
-
- for (var j = 0; j < currEventParams.length; j++) {
- var p = currEventParams[j];
- formattedEvents[currEventName][p.name] = p.value;
- }
-
- }
-
- return Promise.resolve(formattedEvents);
- }
-
-};
-
-module.exports = new web3EventsFormatter();
\ No newline at end of file
diff --git a/lib/web3/providers/rpc.js b/lib/web3/providers/rpc.js
deleted file mode 100644
index 68ca949..0000000
--- a/lib/web3/providers/rpc.js
+++ /dev/null
@@ -1,13 +0,0 @@
-"use strict";
-
-
-const OSTBase = require("@openstfoundation/openst-base");
-
-const rootPrefix = '../../..'
- , coreConstants = require(rootPrefix + '/config/core_constants')
- , OstWeb3 = OSTBase.OstWeb3
-;
-
-const web3RpcProvider = new OstWeb3(coreConstants.OST_UTILITY_GETH_RPC_PROVIDER);
-
-module.exports = web3RpcProvider;
diff --git a/lib/web3/providers/ws.js b/lib/web3/providers/ws.js
deleted file mode 100644
index 5495496..0000000
--- a/lib/web3/providers/ws.js
+++ /dev/null
@@ -1,12 +0,0 @@
-"use strict";
-
-const OstBase = require("@openstfoundation/openst-base");
-
-const rootPrefix = '../../..'
- , coreConstants = require(rootPrefix + '/config/core_constants')
- , OstWeb3 = OstBase.OstWeb3
-;
-
-const web3WSProvider = new OstWeb3(coreConstants.OST_UTILITY_GETH_WS_PROVIDER);
-
-module.exports = web3WSProvider;
diff --git a/migrations/1_initial_migration.js b/migrations/1_initial_migration.js
index 4d5f3f9..f28d653 100644
--- a/migrations/1_initial_migration.js
+++ b/migrations/1_initial_migration.js
@@ -1,5 +1,5 @@
-var Migrations = artifacts.require("./Migrations.sol");
+const Migrations = artifacts.require('./Migrations.sol');
-module.exports = function(deployer) {
- deployer.deploy(Migrations);
+module.exports = function (deployer) {
+ deployer.deploy(Migrations);
};
diff --git a/migrations/create_tables.js b/migrations/create_tables.js
deleted file mode 100644
index e891877..0000000
--- a/migrations/create_tables.js
+++ /dev/null
@@ -1,84 +0,0 @@
-"use strict";
-
-/**
- * This is Script to create tables
- *
- * @module migrations/create_tables
- */
-
-var rootPrefix = '..'
- , coreConstants = require(rootPrefix + '/config/core_constants')
- , QueryDBKlass = require(rootPrefix + '/app/models/queryDb')
- , QueryDB = new QueryDBKlass(coreConstants.MYSQL_DATABASE)
- , logger = require(rootPrefix + '/helpers/custom_console_logger')
-;
-
-/**
- * Create payments table
- *
- * @exports migrations/create_tables
- */
-const createTables = {
-
- perform: async function() {
- logger.win("\nStarting Table Creation");
-
- const allQueries = createTables.getQueries();
- var query = null
- ;
-
- for(var i in allQueries){
- query = allQueries[i];
- logger.win("\nRunning Query");
- logger.debug(query);
- var response = await QueryDB.migrate(query);
- logger.win("\nQuery Response");
- logger.debug(response);
- }
-
- logger.win("\nCompleted Table Creation");
- process.exit(0);
-
- },
-
- getQueries: function() {
- const createAirdropTableQuery = 'CREATE TABLE IF NOT EXISTS `airdrops` (\n' +
- ' `id` bigint(20) NOT NULL AUTO_INCREMENT,\n' +
- ' `contract_address` varchar(50) NOT NULL,\n' +
- ' `created_at` datetime NOT NULL,\n' +
- ' `updated_at` datetime NOT NULL,\n' +
- ' PRIMARY KEY (`id`),\n' +
- ' UNIQUE KEY `UNIQUE_CONTRACT_ADDRESS` (`contract_address`) USING BTREE\n'+
- ') ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;';
-
- const createUserAirdropDetailsTableQuery = 'CREATE TABLE IF NOT EXISTS `user_airdrop_details` (\n' +
- ' `id` bigint(20) NOT NULL AUTO_INCREMENT,\n' +
- ' `user_address` varchar(50) NOT NULL,\n' +
- ' `airdrop_id` bigint(20) NOT NULL,\n' +
- ' `airdrop_amount` decimal(30,0) NOT NULL DEFAULT \'0\',\n' +
- ' `airdrop_used_amount` decimal(30,0) NOT NULL DEFAULT \'0\',\n' +
- ' `expiry_timestamp` bigint(20) NOT NULL DEFAULT \'0\',\n' +
- ' `created_at` datetime NOT NULL,\n' +
- ' `updated_at` datetime NOT NULL,\n' +
- ' PRIMARY KEY (`id`),\n' +
- ' INDEX (user_address, airdrop_id)\n' +
- ') ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;';
-
- const airdropTransferProofDetails = 'CREATE TABLE IF NOT EXISTS `airdrop_allocation_proof_details` (\n' +
- ' `id` bigint(20) NOT NULL AUTO_INCREMENT,\n' +
- ' `transaction_hash` varchar(100) NOT NULL,\n' +
- ' `airdrop_amount` decimal(30,0) NOT NULL DEFAULT \'0\',\n' +
- ' `airdrop_allocated_amount` decimal(30,0) NOT NULL DEFAULT \'0\',\n' +
- ' `created_at` datetime NOT NULL,\n' +
- ' `updated_at` datetime NOT NULL,\n' +
- ' PRIMARY KEY (`id`),\n' +
- ' UNIQUE KEY `UNIQUE_TRANSACTION_HASH` (`transaction_hash`) USING BTREE\n'+
- ') ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;';
-
- return [createAirdropTableQuery, createUserAirdropDetailsTableQuery, airdropTransferProofDetails];
- }
-
-};
-
-module.exports = createTables;
-createTables.perform();
diff --git a/mocha_test/lib/constants.js b/mocha_test/lib/constants.js
deleted file mode 100644
index a5287eb..0000000
--- a/mocha_test/lib/constants.js
+++ /dev/null
@@ -1,54 +0,0 @@
-const rootPrefix = '../..'
- , returnTypes = require(rootPrefix + "/lib/global_constant/return_types")
-;
-
-const constants = {
- gasUsed: 0xBA43B7400,
- deployer: process.env.OST_UTILITY_DEPLOYER_ADDR,
- deployerPassphrase: process.env.OST_UTILITY_DEPLOYER_PASSPHRASE,
- ops: process.env.OST_UTILITY_OPS_ADDR,
- opsPassphrase: process.env.OST_UTILITY_OPS_PASSPHRASE,
- account1: process.env.OST_UTILITY_TEST_ACCOUNT1,
- accountPassphrase1: process.env.OST_UTILITY_TEST_ACCOUNT1_PASSPHRASE,
- account2: process.env.OST_UTILITY_TEST_ACCOUNT2,
- accountPassphrase2: process.env.OST_UTILITY_TEST_ACCOUNT2_PASSPHRASE,
- account3: process.env.OST_UTILITY_TEST_ACCOUNT3,
- accountPassphrase3: process.env.OST_UTILITY_TEST_ACCOUNT3_PASSPHRASE,
- account4: process.env.OST_UTILITY_TEST_ACCOUNT4,
- accountPassphrase4: process.env.OST_UTILITY_TEST_ACCOUNT4_PASSPHRASE,
- account5: process.env.OST_UTILITY_TEST_ACCOUNT5,
- accountPassphrase5: process.env.OST_UTILITY_TEST_ACCOUNT5_PASSPHRASE,
- currencyUSD: "USD",
- currencyEUR: "EUR",
- currencyINR: "INR",
- currencyBlank: "",
- pricerOstUsdAddress: process.env.OST_UTILITY_TEST_PRICER_C5_ADDRESS,
- pricerOstEurAddress: process.env.OST_UTILITY_TEST_PRICER_C2_ADDRESS,
- pricerOstUsd10DecimalAddress: process.env.OST_UTILITY_TEST_PRICER_C3_ADDRESS,
- priceOracles: JSON.parse(process.env.OST_UTILITY_PRICE_ORACLES),
- TC5Address: process.env.OST_UTILITY_TEST_COIN1_C5_ADDRESS,
- TC2Address: process.env.OST_UTILITY_TEST_COIN2_C2_ADDRESS,
- TC3Address: process.env.OST_UTILITY_TEST_COIN3_C3_ADDRESS,
- chainId: process.env.OST_UTILITY_CHAIN_ID,
- returnTypeUUID: returnTypes.transactionUuid(),
- returnTypeHash: returnTypes.transactionHash(),
- returnTypeReceipt: returnTypes.transactionReceipt(),
- optionsUUID: {returnType: returnTypes.transactionUuid(), tag: returnTypes.transactionUuid()},
- optionsHash: {returnType: returnTypes.transactionHash(), tag: returnTypes.transactionHash()},
- optionsReceipt: {returnType: returnTypes.transactionReceipt(), tag: returnTypes.transactionReceipt()},
- // Worker specific constants
- workerAccount1: process.env.OST_WORKER_TEST_ACCOUNT1,
- workerAccountPassphrase1: process.env.OST_WORKER_TEST_ACCOUNT1_PASSPHRASE,
- // Airdrop specific constants
- airdropBudgetHolder: process.env.OST_AIRDROP_BUDGET_HOLDER,
- airdropBudgetHolderPassphrase: process.env.OST_AIRDROP_BUDGET_HOLDER_PASSPHRASE,
- workersContractAddress: process.env.OST_UTILITY_WORKER_CONTRACT_ADDRESS,
- airdropOstUsdAddress: process.env.OST_UTILITY_TEST_AIRDROP1_CONTRACT_ADDRESS,
- account1InitialBrandedTokenBalance: '200001',
- airdropBudgetBrandedTokenBalance: '100000',
- airdropUsers: {
- '0x934ebd34b2a4f16d4de16256df36a6013785557d': {airdropAmount: 50*10**18, expiryTimestamp: 0},
- '0x934ebd34b2a4f16d4de16256df36a6013785557e': {airdropAmount: 50*10**18, expiryTimestamp: 0}
- }
-};
-module.exports = constants;
diff --git a/mocha_test/lib/event_listener.js b/mocha_test/lib/event_listener.js
deleted file mode 100644
index 1f4e1cd..0000000
--- a/mocha_test/lib/event_listener.js
+++ /dev/null
@@ -1,35 +0,0 @@
-const openSTNotification = require('@openstfoundation/openst-notification');
-
-var notificationRef = null;
-var allEvents = {};
-
-
-module.exports.verifyIfEventFired = function(uuid, kind) {
- const key = `${uuid}_${kind}`;
- return allEvents[key] !== undefined && allEvents[key] !== "undefined" && allEvents[key] !== null && allEvents[key] !== '';
-};
-
-module.exports.startObserving = function() {
- if (notificationRef === null) {
- openSTNotification.subscribeEvent.local(
- [
- "payments.pricer.setAcceptedMargin",
- "payments.pricer.setPriceOracle",
- "payments.pricer.unsetPriceOracle",
- "transfer.payments.pricer.pay",
- "transfer.payments.airdrop.pay",
- "payments.workers.setWorker",
- "payments.workers.removeWorker",
- "payments.workers.remove",
- "payments.opsManaged.setOpsAddress",
- "transfer.payments.brandedToken.transferToBudgetHolder",
- "payments.brandedToken.approveToBudgetHolder"
- ],
- function(msgContent) {
- const messageData = JSON.parse(msgContent);
- const key = `${messageData.message.payload.uuid}_${messageData.message.kind}`;
- allEvents[key] = messageData.message;
- });
- notificationRef = openSTNotification;
- }
-};
diff --git a/mocha_test/lib/helper.js b/mocha_test/lib/helper.js
deleted file mode 100644
index f0a6046..0000000
--- a/mocha_test/lib/helper.js
+++ /dev/null
@@ -1,25 +0,0 @@
-"use strict";
-
-/**
- * This is utility class for contract interacts
- *
- * Ref: {@link module:ContractHelper}
- *
- * @module lib/contract_helper/helper
- */
-
-const rootPrefix = '../..'
- , BigNumber = require('bignumber.js')
-;
-
-/**
- * Mocha Test Helper class
- *
- * @exports lib/contract_helper/helper
- */
-const helper = {
-
-};
-
-module.exports = helper;
-
diff --git a/mocha_test/lib/populate_env_vars.js b/mocha_test/lib/populate_env_vars.js
deleted file mode 100644
index 3747494..0000000
--- a/mocha_test/lib/populate_env_vars.js
+++ /dev/null
@@ -1,62 +0,0 @@
-"use strict";
-
-/*
- * Helper
- *
- * * Author: Deepesh
- * * Date: 29/01/2018
- * * Reviewed by:
- */
-
-const mustache = require('mustache')
- , fs = require('fs')
- , Path = require('path')
- , envVarsSourceFile = '../../mocha_test/scripts/env_vars.sh';
-
-
-const addressTemplate = "export OST_UTILITY_DEPLOYER_ADDR='{{ost_utility_deployer_address}}'\n" +
- "export OST_UTILITY_OPS_ADDR='{{ost_utility_ops_address}}'\n" +
- "export OST_UTILITY_TEST_ACCOUNT1='{{ost_utility_test_account_1}}'\n" +
- "export OST_UTILITY_TEST_ACCOUNT1_PASSPHRASE='testtest'\n" +
- "export OST_UTILITY_TEST_ACCOUNT2='{{ost_utility_test_account_2}}'\n" +
- "export OST_UTILITY_TEST_ACCOUNT2_PASSPHRASE='testtest'\n" +
- "export OST_UTILITY_TEST_ACCOUNT3='{{ost_utility_test_account_3}}'\n" +
- "export OST_UTILITY_TEST_ACCOUNT3_PASSPHRASE='testtest'\n" +
- "export OST_UTILITY_TEST_ACCOUNT4='{{ost_utility_test_account_4}}'\n" +
- "export OST_UTILITY_TEST_ACCOUNT4_PASSPHRASE='testtest'\n" +
- "export OST_UTILITY_TEST_ACCOUNT5='{{ost_utility_test_account_5}}'\n" +
- "export OST_UTILITY_TEST_ACCOUNT5_PASSPHRASE='testtest'\n" +
- "export OST_AIRDROP_BUDGET_HOLDER='{{ost_airdrop_budget_holder}}'\n" +
- "export OST_AIRDROP_BUDGET_HOLDER_PASSPHRASE='testtest'\n" +
- "export OST_WORKER_TEST_ACCOUNT1='{{ost_worker_test_account_1}}'\n" +
- "export OST_WORKER_TEST_ACCOUNT1_PASSPHRASE='testtest'\n"
-;
-
-const populateEnvVars = {
-
- renderAndPopulate: function (type, vars) {
- var renderData = '';
- try {
- if (type === 'address') {
- renderData = mustache.to_html(addressTemplate, vars);
- }
- else {
- console.error(" Invalid Template Type To render");
- process.exit(1);
- }
- var existingSourceFileData = fs.readFileSync(Path.join(__dirname, '/' + envVarsSourceFile));
- var dataToWrite = existingSourceFileData.toString() + "\n\n" + renderData;
- //logger.debug("ENV Constants to Write");
- //logger.debug(dataToWrite);
- fs.writeFileSync(Path.join(__dirname, '/' + envVarsSourceFile), dataToWrite);
- } catch (e) {
- console.error("Error Reading and Populating Source File");
- console.error(e);
- process.exit(1);
- }
-
- }
-
-};
-
-module.exports = populateEnvVars;
diff --git a/mocha_test/lib/utils.js b/mocha_test/lib/utils.js
deleted file mode 100644
index 8f03b29..0000000
--- a/mocha_test/lib/utils.js
+++ /dev/null
@@ -1,64 +0,0 @@
-/*eslint-disable */
-const chai = require('chai')
- , assert = chai.assert
- , rootPrefix = '../..'
- , eventListener = require(rootPrefix+'/mocha_test/lib/event_listener')
- , helper = require(rootPrefix + '/lib/contract_interact/helper')
- ;
-/*eslint-enable */
-
-eventListener.startObserving();
-
-
-module.exports.verifyIfMined = async (contract, transactionHash) => {
-
- const receipt = await contract.getTxReceipt(transactionHash);
- assert.equal(receipt.isSuccess(), true);
- assert.exists(receipt.data.transactionReceipt);
- assert.equal(transactionHash, receipt.data.transactionReceipt.formattedTransactionReceipt.transactionHash);
-
-};
-
-module.exports.verifyTransactionUUID = function (response) {
-
- // verify if the response is success
- assert.equal(response.isSuccess(), true, "response success check");
-
- // verify if the uuid, transaction has and transaction receipt is available
- assert.isNotEmpty(response.data.transaction_uuid, "check if transaction uuid exists");
- assert.isEmpty(response.data.transaction_hash, "check if transaction hash does not exists");
- assert.isEmpty(response.data.transaction_receipt, "check if transaction receipt does not exists");
-
-};
-
-module.exports.verifyTransactionHash = function (response) {
-
- // verify if the response is success
- assert.equal(response.isSuccess(), true, "response success check");
-
- // verify if the uuid, transaction has and transaction receipt is available
- assert.isNotEmpty(response.data.transaction_uuid, "check if transaction uuid exists");
- assert.isNotEmpty(response.data.transaction_hash, "check if transaction hash exists");
- assert.isEmpty(response.data.transaction_receipt, "check if transaction receipt does not exists");
-
- // verify if the events were fired
- assert.equal(eventListener.verifyIfEventFired(response.data.transaction_uuid, "transaction_initiated"), true, "Event verification for transaction_initiated");
-
-};
-
-module.exports.verifyTransactionReceipt = function (response) {
-
- // verify if the response is success
- assert.equal(response.isSuccess(), true, "response success check");
-
- // verify if the uuid, transaction has and transaction receipt is available
- assert.isNotEmpty(response.data.transaction_uuid, "check if transaction uuid exists");
- assert.isNotEmpty(response.data.transaction_hash, "check if transaction hash exists");
- assert.exists(response.data.transaction_receipt, "check if transaction receipt exists");
-
- // verify if the events were fired
- assert.equal(eventListener.verifyIfEventFired(response.data.transaction_uuid, "transaction_initiated"), true, "Event verification for transaction_initiated");
- assert.equal(eventListener.verifyIfEventFired(response.data.transaction_uuid, "transaction_mined"), true, "Event verification for transaction_mined");
-
-};
-
diff --git a/mocha_test/scripts/_init_addresses.js b/mocha_test/scripts/_init_addresses.js
deleted file mode 100644
index c239249..0000000
--- a/mocha_test/scripts/_init_addresses.js
+++ /dev/null
@@ -1,106 +0,0 @@
-const fs = require('fs');
-const Path = require('path');
-
-const _addresses = {
- "deployerAdd": null,
- "opsAdd": null,
- "account1": null,
- "account2": null,
- "account3": null,
- "account4": null,
- "account5": null,
- "airdropBudgetHolder": null
-};
-
-const rootPrefix = "../.."
- , coreConstants = require( rootPrefix + '/config/core_constants' )
- , logger = require(rootPrefix + '/helpers/custom_console_logger')
- , populateEnvVars = require( rootPrefix + "/mocha_test/lib/populate_env_vars.js")
- , poaGenesis = require( rootPrefix + "/mocha_test/scripts/poa-genesis.json")
-;
-
-function main( addressFile ) {
- const _path = Path.join(__dirname, addressFile );
- const fileContent = fs.readFileSync( _path, "utf8");
- fileContent.toString().split('\n').forEach(function (line, index) {
-
- var thisAddress = line.replace("Address: {", "0x").replace("}","").trim();
- if ( thisAddress.length < 40 ) {
- return;
- }
-
- if ( !_addresses.deployerAdd ) {
- //First Address
- _addresses.deployerAdd = thisAddress;
- fundAddress(thisAddress);
- } else if ( !_addresses.opsAdd ) {
- _addresses.opsAdd = thisAddress;
- fundAddress(thisAddress);
- } else if ( !_addresses.account1 ) {
- _addresses.account1 = thisAddress;
- fundAddress(thisAddress);
- } else if ( !_addresses.account2 ) {
- _addresses.account2 = thisAddress;
- fundAddress(thisAddress);
- } else if ( !_addresses.account3 ) {
- _addresses.account3 = thisAddress;
- fundAddress(thisAddress);
- } else if ( !_addresses.account4 ) {
- _addresses.account4 = thisAddress;
- fundAddress(thisAddress);
- } else if ( !_addresses.account5 ) {
- _addresses.account5 = thisAddress;
- fundAddress(thisAddress);
- } else if ( !_addresses.airdropBudgetHolder ) {
- _addresses.airdropBudgetHolder = thisAddress;
- fundAddress(thisAddress);
- } else if ( !_addresses.workerAccount1 ) {
- _addresses.workerAccount1 = thisAddress;
- fundAddress(thisAddress);
- }
- });
-
- populateEnvVars.renderAndPopulate('address', {
- ost_utility_deployer_address: _addresses.deployerAdd,
- ost_utility_ops_address: _addresses.opsAdd,
- ost_utility_test_account_1: _addresses.account1,
- ost_utility_test_account_2: _addresses.account2,
- ost_utility_test_account_3: _addresses.account3,
- ost_utility_test_account_4: _addresses.account4,
- ost_utility_test_account_5: _addresses.account5,
- ost_airdrop_budget_holder: _addresses.airdropBudgetHolder,
- ost_worker_test_account_1: _addresses.workerAccount1
- }
- );
-}
-
-function fundAddress( address ) {
-
- //Update poa-genesis-value
- updateGenesisAlloc( poaGenesis, address, "0x200000000000000000000000000000000000000000000000000000000000000");
- writeJsonToFile(poaGenesis, "./poa-genesis.json");
-
-}
-function updateGenesisAlloc( genesis, foundation, value ) {
- const _alloc = genesis.alloc;
- _alloc[ foundation ] = { "balance" : value };
- //Remove the place holder if it exists.
- _alloc[ "" ] && (delete _alloc[ "" ] );
-}
-
-function writeJsonToFile( jsObject, relativeFilePath, tab_space ) {
- tab_space = tab_space || 2;
- var json = JSON.stringify(jsObject, null, tab_space);
-
- var jsonFilePath = relativeFilePath;
- if ( !Path.isAbsolute( jsonFilePath ) ) {
- jsonFilePath = Path.join(__dirname, '/' + relativeFilePath );
- }
-
- logger.debug("writeJsonToFile :: jsonFilePath :: ", jsonFilePath);
-
- fs.writeFileSync(jsonFilePath, json );
-}
-
-
-main( process.argv[2] );
diff --git a/mocha_test/scripts/deploy_all.sh b/mocha_test/scripts/deploy_all.sh
deleted file mode 100644
index 7475a23..0000000
--- a/mocha_test/scripts/deploy_all.sh
+++ /dev/null
@@ -1,90 +0,0 @@
-
-#!/bin/bash
-cd ..
-sh ../contracts/compile.sh
-. ./scripts/env_vars.sh
-
-echo "\n********* Deploying test coin 1 *************"
-node ../tools/deploy/EIP20TokenMock.js 5 TC1 TestCoin1 18 0x12A05F200 travis tc1.txt
-export OST_UTILITY_TEST_COIN1_C5_ADDRESS=$(cat ../tools/deploy/tc1.txt)
-echo '\nexport OST_UTILITY_TEST_COIN1_C5_ADDRESS='\'$OST_UTILITY_TEST_COIN1_C5_ADDRESS\'>>scripts/env_vars.sh
-rm ../tools/deploy/tc1.txt
-echo "\n********* Done *************"
-
-echo "\n********* Deploying test coin 2 *************"
-. ./scripts/env_vars.sh
-node ../tools/deploy/EIP20TokenMock.js 2 TC2 TestCoin2 18 0x12A05F200 travis tc2.txt
-export OST_UTILITY_TEST_COIN2_C2_ADDRESS=$(cat ../tools/deploy/tc2.txt)
-echo '\nexport OST_UTILITY_TEST_COIN2_C2_ADDRESS='\'$OST_UTILITY_TEST_COIN2_C2_ADDRESS\'>>scripts/env_vars.sh
-rm ../tools/deploy/tc2.txt
-echo "\n********* Done *************"
-
-echo "\n********* Deploying test coin 3 *************"
-. ./scripts/env_vars.sh
-node ../tools/deploy/EIP20TokenMock.js 3 TC3 TestCoin3 10 0x12A05F200 travis tc3.txt
-export OST_UTILITY_TEST_COIN3_C3_ADDRESS=$(cat ../tools/deploy/tc3.txt)
-echo '\nexport OST_UTILITY_TEST_COIN3_C3_ADDRESS='\'$OST_UTILITY_TEST_COIN3_C3_ADDRESS\'>>scripts/env_vars.sh
-rm ../tools/deploy/tc3.txt
-echo "\n********* Done *************"
-
-
-echo "\n********* Deploying Pricer 1 *************"
-. ./scripts/env_vars.sh
-node ../tools/deploy/pricer.js $OST_UTILITY_TEST_COIN1_C5_ADDRESS OST 0x12A05F200 $OST_UTILITY_CHAIN_ID travis tp1.txt
-export OST_UTILITY_TEST_PRICER_C5_ADDRESS=$(cat ../tools/deploy/tp1.txt)
-echo '\nexport OST_UTILITY_TEST_PRICER_C5_ADDRESS='\'$OST_UTILITY_TEST_PRICER_C5_ADDRESS\'>>scripts/env_vars.sh
-rm ../tools/deploy/tp1.txt
-echo "\n********* Done *************"
-
-echo "\n********* Deploying Pricer 2 *************"
-. ./scripts/env_vars.sh
-node ../tools/deploy/pricer.js $OST_UTILITY_TEST_COIN2_C2_ADDRESS OST 0x12A05F200 $OST_UTILITY_CHAIN_ID travis tp2.txt
-export OST_UTILITY_TEST_PRICER_C2_ADDRESS=$(cat ../tools/deploy/tp2.txt)
-echo '\nexport OST_UTILITY_TEST_PRICER_C2_ADDRESS='\'$OST_UTILITY_TEST_PRICER_C2_ADDRESS\'>>scripts/env_vars.sh
-rm ../tools/deploy/tp2.txt
-echo "\n********* Done *************"
-
-echo "\n********* Deploying Pricer 3 *************"
-. ./scripts/env_vars.sh
-node ../tools/deploy/pricer.js $OST_UTILITY_TEST_COIN3_C3_ADDRESS OST 0x12A05F200 $OST_UTILITY_CHAIN_ID travis tp3.txt
-export OST_UTILITY_TEST_PRICER_C3_ADDRESS=$(cat ../tools/deploy/tp3.txt)
-echo '\nexport OST_UTILITY_TEST_PRICER_C3_ADDRESS='\'$OST_UTILITY_TEST_PRICER_C3_ADDRESS\'>>scripts/env_vars.sh
-rm ../tools/deploy/tp3.txt
-echo "\n********* Done *************"
-
-echo "\n********* Deploying Worker Contract Address *************"
-node ../tools/deploy/workers.js 0x12A05F200 $OST_UTILITY_CHAIN_ID travis w1.txt
-export OST_UTILITY_WORKER_CONTRACT_ADDRESS=$(cat ../tools/deploy/w1.txt)
-echo '\nexport OST_UTILITY_WORKER_CONTRACT_ADDRESS='\'$OST_UTILITY_WORKER_CONTRACT_ADDRESS\'>>scripts/env_vars.sh
-rm ../tools/deploy/w1.txt
-echo "\n********* Done *************"
-
-echo "\n Sourcing env_vars again"
-. ./scripts/env_vars.sh
-
-echo "\n********* Deploying Airdrop Contract Address *************"
-. ./scripts/env_vars.sh
-node ../tools/deploy/airdrop.js $OST_UTILITY_TEST_COIN1_C5_ADDRESS OST $OST_UTILITY_WORKER_CONTRACT_ADDRESS $OST_AIRDROP_BUDGET_HOLDER 0x12A05F200 $OST_UTILITY_CHAIN_ID travis ad1.txt
-export OST_UTILITY_TEST_AIRDROP1_CONTRACT_ADDRESS=$(cat ../tools/deploy/ad1.txt)
-echo '\nexport OST_UTILITY_TEST_AIRDROP1_CONTRACT_ADDRESS='\'$OST_UTILITY_TEST_AIRDROP1_CONTRACT_ADDRESS\'>>scripts/env_vars.sh
-rm ../tools/deploy/ad1.txt
-echo "\n********* Done *************"
-
-
-echo "\n********* Setting env variables *************"
-. ./scripts/env_vars.sh
-cd scripts
-
-export OST_UTILITY_PRICE_ORACLES='{}'
-export OST_UTILITY_CHAIN_ID=$OST_UTILITY_CHAIN_ID
-export OST_CACHING_ENGINE='none'
-
-echo '\nexport OST_UTILITY_PRICE_ORACLES='\'$OST_UTILITY_PRICE_ORACLES\'>>env_vars.sh
-echo '\nexport OST_UTILITY_CHAIN_ID='\'$OST_UTILITY_CHAIN_ID\'>>env_vars.sh
-echo '\nexport OST_CACHING_ENGINE='\'$OST_CACHING_ENGINE\'>>env_vars.sh
-
-
-echo "\n********* Done *************"
-
-sh deploy_price_oracle.sh
-
diff --git a/mocha_test/scripts/deploy_price_oracle.sh b/mocha_test/scripts/deploy_price_oracle.sh
deleted file mode 100644
index d5d7028..0000000
--- a/mocha_test/scripts/deploy_price_oracle.sh
+++ /dev/null
@@ -1,34 +0,0 @@
-#!/bin/bash
-
-echo "\n********* Preparing price oracle deployment *************"
-npm install @ostdotcom/ost-price-oracle@1.0.1-beta.3
-cd ../../node_modules/@ostdotcom/ost-price-oracle/
-echo "\n********* Done *************"
-
-echo "\n********* Deploying PO 1 *************"
-node ./tools/deploy/price_oracle.js OST USD 0x12A05F200 travis po1.txt
-echo "\n********* Done *************"
-echo "\n********* Deploying PO 2 *************"
-node ./tools/deploy/price_oracle.js OST EUR 0x12A05F200 travis po2.txt
-echo "\n********* Done *************"
-echo "\n********* Deploying PO 3 *************"
-node ./tools/deploy/price_oracle.js OST INR 0x12A05F200 travis po3.txt
-echo "\n********* Done *************"
-echo "\n********* Deploying PO 4 *************"
-node ./tools/deploy/price_oracle.js ETH USD 0x12A05F200 travis po4.txt
-echo "\n********* Done *************"
-
-export OST_UTILITY_PRICE_ORACLES="{\"OST\":{\"USD\":\"$(cat ./tools/deploy/po1.txt)\",\"EUR\":\"$(cat ./tools/deploy/po2.txt)\",\"INR\":\"$(cat ./tools/deploy/po3.txt)\"},\"ETH\":{\"USD\":\"$(cat ./tools/deploy/po4.txt)\"}}"
-echo '\nexport OST_UTILITY_PRICE_ORACLES='\'$OST_UTILITY_PRICE_ORACLES\'>>../../../mocha_test/scripts/env_vars.sh
-echo OST_UTILITY_PRICE_ORACLES=$OST_UTILITY_PRICE_ORACLES
-
-node ./test/scripts/set_price.js OST USD 0.5 0x12A05F200
-node ./test/scripts/set_price.js OST EUR 0.2 0x12A05F200
-node ./test/scripts/set_price.js ETH USD 20.2 0x12A05F200
-
-rm ./tools/deploy/po1.txt
-rm ./tools/deploy/po2.txt
-rm ./tools/deploy/po3.txt
-rm ./tools/deploy/po4.txt
-
-
diff --git a/mocha_test/scripts/geth_checker.js b/mocha_test/scripts/geth_checker.js
deleted file mode 100644
index 79b24a3..0000000
--- a/mocha_test/scripts/geth_checker.js
+++ /dev/null
@@ -1,42 +0,0 @@
-'use strict';
-
-const rootPrefix = '../..'
- , logger = require(rootPrefix + '/helpers/custom_console_logger')
- , web3Provider = require(rootPrefix + '/lib/web3/providers/ws')
-;
-
-const performer = async function () {
-
- const delay = 10 * 1000
- , timeoutValue = 30 * 60 * 1000
- ;
-
- var counter = 0
- , totalTime = counter * delay
- , isInProcess = false
- ;
-
- setInterval(function () {
- if (totalTime <= timeoutValue) {
- if (isInProcess == false) {
- isInProcess = true;
- web3Provider.eth.getBlockNumber(function (err, blocknumber) {
- if (err || blocknumber < 1) {
- logger.debug("Unable to get blocknumber");
- } else {
- logger.debug("blocknumber", blocknumber);
- process.exit(0);
- }
- isInProcess = false;
- });
- }
- } else {
- logger.error("GethChecker unable to complete process in time: ", timeoutValue);
- process.exit(1);
- }
- counter++;
- totalTime = counter * delay;
- }, delay);
-}
-
-performer();
diff --git a/mocha_test/scripts/init_chain.sh b/mocha_test/scripts/init_chain.sh
deleted file mode 100755
index ebfa5e7..0000000
--- a/mocha_test/scripts/init_chain.sh
+++ /dev/null
@@ -1,9 +0,0 @@
-#!/bin/bash
-DATADIR=./st-poa
-
-mkdir -p "$DATADIR"
-
-rm -rf "$DATADIR/geth"
-
-geth --datadir "$DATADIR" init poa-genesis.json
-
diff --git a/mocha_test/scripts/init_keys.sh b/mocha_test/scripts/init_keys.sh
deleted file mode 100755
index 1743fcc..0000000
--- a/mocha_test/scripts/init_keys.sh
+++ /dev/null
@@ -1,64 +0,0 @@
-#!/bin/sh
-DATADIR=./st-poa
-ADDRESS_FILE=./new_addresses
-
-echo "Init/Re-Init chain..."
-#!/bin/bash
-sh ./init_chain.sh
-echo "" > $ADDRESS_FILE
-echo "...Done Init"
-
-
-echo "Generate new addresses..."
-
-. ./env_vars.sh
-
-
-# Utility Chain Deployer Address
-echo $OST_UTILITY_DEPLOYER_PASSPHRASE > ./pw
-geth --datadir "$DATADIR" account new --password ./pw >> $ADDRESS_FILE
-
-#Ops Address
-echo $OST_UTILITY_OPS_PASSPHRASE > ./pw
-geth --datadir "$DATADIR" account new --password ./pw >> $ADDRESS_FILE
-
-#Test account 1
-echo "testtest" > ./pw
-geth --datadir "$DATADIR" account new --password ./pw >> $ADDRESS_FILE
-
-#Test account 2
-echo "testtest" > ./pw
-geth --datadir "$DATADIR" account new --password ./pw >> $ADDRESS_FILE
-
-#Test account 3
-echo "testtest" > ./pw
-geth --datadir "$DATADIR" account new --password ./pw >> $ADDRESS_FILE
-
-#Test account 4
-echo "testtest" > ./pw
-geth --datadir "$DATADIR" account new --password ./pw >> $ADDRESS_FILE
-
-#Test account 5
-echo "testtest" > ./pw
-geth --datadir "$DATADIR" account new --password ./pw >> $ADDRESS_FILE
-
-#Airdrop Budget Holder Address
-echo $OST_AIRDROP_BUDGET_HOLDER_PASSPHRASE > ./pw
-geth --datadir "$DATADIR" account new --password ./pw >> $ADDRESS_FILE
-
-#Worker Test account 1
-echo "testtest" > ./pw
-geth --datadir "$DATADIR" account new --password ./pw >> $ADDRESS_FILE
-
-echo "...New addresses generated"
-cat $ADDRESS_FILE
-#Invoke JS script to init addresses in various JSON files.
-echo "Populate configs..."
-node ./_init_addresses.js $ADDRESS_FILE
-#clean-up $ADDRESS_FILE
-rm $ADDRESS_FILE
-echo "...configs populated"
-
-echo "Re-Init chain with updated config..."
-sh ./init_chain.sh
-echo "...Done Re-Init"
\ No newline at end of file
diff --git a/mocha_test/scripts/install_geth_1.7.2.sh b/mocha_test/scripts/install_geth_1.7.2.sh
deleted file mode 100644
index 4038a94..0000000
--- a/mocha_test/scripts/install_geth_1.7.2.sh
+++ /dev/null
@@ -1,5 +0,0 @@
-#!/bin/bash
-curl https://gethstore.blob.core.windows.net/builds/geth-linux-amd64-1.7.2-1db4ecdc.tar.gz | tar xvz
-mv geth-linux-amd64-1.7.2-1db4ecdc /usr/local/bin
-ln -s /usr/local/bin/geth-linux-amd64-1.7.2-1db4ecdc/geth /usr/local/bin/geth
-export PATH="$PATH:/usr/local/bin/geth-linux-amd64-1.7.2-1db4ecdc"
diff --git a/mocha_test/scripts/install_geth_1.7.3.sh b/mocha_test/scripts/install_geth_1.7.3.sh
deleted file mode 100644
index 2991ac4..0000000
--- a/mocha_test/scripts/install_geth_1.7.3.sh
+++ /dev/null
@@ -1,5 +0,0 @@
-#!/bin/bash
-curl https://gethstore.blob.core.windows.net/builds/geth-linux-amd64-1.7.3-4bb3c89d.tar.gz | tar xvz
-mv geth-linux-amd64-1.7.3-4bb3c89d /usr/local/bin
-ln -s /usr/local/bin/geth-linux-amd64-1.7.3-4bb3c89d/geth /usr/local/bin/geth
-export PATH="$PATH:/usr/local/bin/geth-linux-amd64-1.7.3-4bb3c89d"
diff --git a/mocha_test/scripts/install_geth_1.8.3.sh b/mocha_test/scripts/install_geth_1.8.3.sh
deleted file mode 100644
index 3ea630d..0000000
--- a/mocha_test/scripts/install_geth_1.8.3.sh
+++ /dev/null
@@ -1,8 +0,0 @@
-#!/bin/bash
-curl https://gethstore.blob.core.windows.net/builds/geth-linux-amd64-1.8.3-329ac18e.tar.gz | tar xvz
-mv geth-linux-amd64-1.8.3-329ac18e /usr/local/bin
-ln -s /usr/local/bin/geth-linux-amd64-1.8.3-329ac18e/geth /usr/local/bin/geth
-export PATH="$PATH:/usr/local/bin/geth-linux-amd64-1.8.3-329ac18e"
-
-
-
diff --git a/mocha_test/scripts/install_geth_1.8.8.sh b/mocha_test/scripts/install_geth_1.8.8.sh
deleted file mode 100644
index 749b3bd..0000000
--- a/mocha_test/scripts/install_geth_1.8.8.sh
+++ /dev/null
@@ -1,9 +0,0 @@
-#!/bin/bash
-curl https://gethstore.blob.core.windows.net/builds/geth-linux-amd64-1.8.8-2688dab4.tar.gz | tar xvz
-mv geth-linux-amd64-1.8.8-2688dab4 /usr/local/bin
-ln -s /usr/local/bin/geth-linux-amd64-1.8.8-2688dab4/geth /usr/local/bin/geth
-export PATH="$PATH:/usr/local/bin/geth-linux-amd64-1.8.8-2688dab4"
-
-
-
-
diff --git a/mocha_test/scripts/poa-genesis-template.json b/mocha_test/scripts/poa-genesis-template.json
deleted file mode 100644
index 609c860..0000000
--- a/mocha_test/scripts/poa-genesis-template.json
+++ /dev/null
@@ -1,16 +0,0 @@
-{
- "config": {
- "chainId": 2000,
- "homesteadBlock": 1,
- "eip150Block": 2,
- "eip150Hash": "0x0000000000000000000000000000000000000000000000000000000000000000",
- "eip155Block": 3,
- "eip158Block": 3,
- "byzantiumBlock": 4
- },
- "gasLimit": "0x989680",
- "difficulty": "0x1",
- "alloc": {},
- "number": "0x0",
- "gasUsed": "0x0"
-}
\ No newline at end of file
diff --git a/mocha_test/scripts/run_chain.sh b/mocha_test/scripts/run_chain.sh
deleted file mode 100755
index de9607e..0000000
--- a/mocha_test/scripts/run_chain.sh
+++ /dev/null
@@ -1,6 +0,0 @@
-#!/bin/bash
-
-DATADIR=$(pwd)/st-poa
-LOCAL_NETWORK_ID="--networkid 20171010"
-
-geth --datadir "$DATADIR" $LOCAL_NETWORK_ID --port 30301 --rpcport 9546 --rpcapi net,eth,web3,personal --wsapi net,eth,web3,personal --ws --wsport 19546 --wsorigins "*" --gasprice 0 --targetgaslimit 100000000 --etherbase 0 --unlock 0 --password pw --rpc --maxpeers 0 --mine --minerthreads 4
diff --git a/mocha_test/scripts/set_env_vars.sh b/mocha_test/scripts/set_env_vars.sh
deleted file mode 100644
index eab0594..0000000
--- a/mocha_test/scripts/set_env_vars.sh
+++ /dev/null
@@ -1,41 +0,0 @@
-
-#!/bin/bash
-
-export OST_UTILITY_GAS_PRICE='0x12A05F200'
-export OST_UTILITY_GETH_RPC_PROVIDER='http://127.0.0.1:9546'
-export OST_UTILITY_GETH_WS_PROVIDER='ws://127.0.0.1:19546'
-
-export OST_UTILITY_DEPLOYER_ADDR=''
-export OST_UTILITY_DEPLOYER_PASSPHRASE='testtest'
-export OST_UTILITY_OPS_ADDR=''
-export OST_UTILITY_OPS_PASSPHRASE='testtest'
-export OST_UTILITY_CHAIN_ID=2000
-export OST_AIRDROP_BUDGET_HOLDER=''
-export OST_AIRDROP_BUDGET_HOLDER_PASSPHRASE='testtest'
-
-export OP_MYSQL_HOST='127.0.0.1'
-export OP_MYSQL_USER='travis'
-export OP_MYSQL_PASSWORD=''
-export OP_MYSQL_DATABASE='payment_development'
-export OP_MYSQL_CONNECTION_POOL_SIZE='5'
-
-export OST_CACHING_ENGINE='none'
-export OST_DEBUG_ENABLED=1
-
-
-export OS_DYNAMODB_API_VERSION='2012-08-10'
-export OS_DYNAMODB_ACCESS_KEY_ID='x'
-export OS_DYNAMODB_SECRET_ACCESS_KEY='x'
-export OS_DYNAMODB_REGION='localhost'
-export OS_DYNAMODB_ENDPOINT='http://localhost:8000'
-
-export OS_AUTOSCALING_API_VERSION='2016-02-06'
-export OS_AUTOSCALING_ACCESS_KEY_ID='x'
-export OS_AUTOSCALING_SECRET_ACCESS_KEY='x'
-export OS_AUTOSCALING_REGION='localhost'
-export OS_AUTOSCALING_ENDPOINT='http://localhost:8000'
-export OS_AUTOSCALING_SSL_ENABLED='0'
-export OS_AUTOSCALING_LOGGING_ENABLED='0'
-
-export OST_STANDALONE_MODE=1
-export RUNNING_TESTS_IN='travis'
diff --git a/mocha_test/scripts/start_test_chain.sh b/mocha_test/scripts/start_test_chain.sh
deleted file mode 100644
index 44bee8b..0000000
--- a/mocha_test/scripts/start_test_chain.sh
+++ /dev/null
@@ -1,10 +0,0 @@
-#!/bin/bash
-cat poa-genesis-template.json>poa-genesis.json
-cat set_env_vars.sh>env_vars.sh
-. ./env_vars.sh
-sh init_keys.sh
-sh init_chain.sh
-nohup sh run_chain.sh /dev/null 2>&1 &
-sleep 10
-node ./geth_checker.js
-
diff --git a/mocha_test/scripts/travis_test.sh b/mocha_test/scripts/travis_test.sh
deleted file mode 100644
index 1f4effc..0000000
--- a/mocha_test/scripts/travis_test.sh
+++ /dev/null
@@ -1,12 +0,0 @@
-#!/bin/bash
-sh start_test_chain.sh
-sh deploy_all.sh
-. ./env_vars.sh
-node ./../../migrations/create_tables.js
-./../../node_modules/mocha/bin/mocha ./../../mocha_test/services/pricer/*.js ./../../mocha_test/services/airdrop/*.js ./../../mocha_test/services/workers/_is_worker.js ./../../mocha_test/services/workers/_remove_worker.js ./../../mocha_test/services/workers/_set_worker.js ./../../mocha_test/services/workers/remove.js --exit
-
-# run worker test at last, and in the following sequence as in the test case it removes the worker contract that is needed for other tests.
-# 1. _is_worker.js
-# 2. _remove_worker.js
-# 3. _set_worker.js
-# 4. remove.js
\ No newline at end of file
diff --git a/mocha_test/services/airdrop/airdrop_budget_holder.js b/mocha_test/services/airdrop/airdrop_budget_holder.js
deleted file mode 100644
index f766af2..0000000
--- a/mocha_test/services/airdrop/airdrop_budget_holder.js
+++ /dev/null
@@ -1,23 +0,0 @@
-
-const chai = require('chai')
- , assert = chai.assert;
-
-const rootPrefix = "../../.."
- , constants = require(rootPrefix + '/mocha_test/lib/constants')
- , airdrop = require(rootPrefix + '/lib/contract_interact/airdrop')
- , airdropContract = new airdrop(constants.airdropOstUsdAddress, constants.chainId)
- , web3Provider = require(rootPrefix + '/lib/web3/providers/ws')
-;
-
-describe('Get Airdrop Budget Holder', function() {
-
- it('should return correct airdrop budget holder address', async function() {
- this.timeout(100000);
- const airdropWorkersResult = await airdropContract.airdropBudgetHolder();
- assert.equal(airdropWorkersResult.isSuccess(), true);
- assert.equal(airdropWorkersResult.data.airdropBudgetHolder,
- web3Provider.utils.toChecksumAddress(constants.airdropBudgetHolder));
-
- });
-
-});
diff --git a/mocha_test/services/airdrop/get_workers.js b/mocha_test/services/airdrop/get_workers.js
deleted file mode 100644
index 1a5b92e..0000000
--- a/mocha_test/services/airdrop/get_workers.js
+++ /dev/null
@@ -1,23 +0,0 @@
-
-const chai = require('chai')
- , assert = chai.assert;
-
-const rootPrefix = "../../.."
- , constants = require(rootPrefix + '/mocha_test/lib/constants')
- , airdrop = require(rootPrefix + '/lib/contract_interact/airdrop')
- , airdropContract = new airdrop(constants.airdropOstUsdAddress, constants.chainId)
- , web3Provider = require(rootPrefix + '/lib/web3/providers/ws')
-;
-
-describe('Get Workers', function() {
-
- it('should return correct worker contract address', async function() {
-
- const airdropWorkersResult = await airdropContract.getWorkers();
- assert.equal(airdropWorkersResult.isSuccess(), true);
- assert.equal(airdropWorkersResult.data.workerContractAddress,
- web3Provider.utils.toChecksumAddress(constants.workersContractAddress));
-
- });
-
-});
diff --git a/mocha_test/services/airdrop/pay.js b/mocha_test/services/airdrop/pay.js
deleted file mode 100644
index 2709114..0000000
--- a/mocha_test/services/airdrop/pay.js
+++ /dev/null
@@ -1,1184 +0,0 @@
-/* global describe, it */
-
-const chai = require('chai')
- , assert = chai.assert;
-
-const rootPrefix = "../../.."
- , constants = require(rootPrefix + '/mocha_test/lib/constants')
- , BigNumber = require('bignumber.js')
- , utils = require(rootPrefix+'/mocha_test/lib/utils')
- , airdrop = require(rootPrefix + '/lib/contract_interact/airdrop')
- , mockToken = require(rootPrefix + '/lib/contract_interact/EIP20TokenMock')
- , BrandedTokenKlass = require(rootPrefix + '/lib/contract_interact/branded_token')
- , web3Provider = require(rootPrefix + '/lib/web3/providers/ws')
- , logger = require(rootPrefix + '/helpers/custom_console_logger')
- , paramErrorConfig = require(rootPrefix + '/config/param_error_config')
- , apiErrorConfig = require(rootPrefix + '/config/api_error_config')
-;
-
-const errorConfig = {
- param_error_config: paramErrorConfig,
- api_error_config: apiErrorConfig
-};
-
-const airdropOstUsd = new airdrop(constants.airdropOstUsdAddress, constants.chainId)
- , TC5 = new mockToken(constants.TC5Address)
- , brandedTokenObject = new BrandedTokenKlass(constants.TC5Address, constants.chainId)
-;
-
-const AirdropModelCacheKlass = require(rootPrefix + '/lib/cache_management/airdrop_model')
- , openstPayment = require(rootPrefix + '/index')
- , SetWorkerKlass = openstPayment.services.workers.setWorker
- , IsWorkerKlass = openstPayment.services.workers.isWorker
- , RegisterKlass = openstPayment.services.airdropManager.registerAirdrop
- , TransferKlass = openstPayment.services.airdropManager.transfer
- , ApproveKlass = openstPayment.services.airdropManager.approve
- , BatchAllocatorKlass = openstPayment.services.airdropManager.batchAllocator
- , UserBalanceKlass = openstPayment.services.airdropManager.userBalance
- , PayKlass = openstPayment.services.airdropManager.pay
- , SetPriceOracleKlass = openstPayment.services.airdropManager.setPriceOracle
- , SetAcceptedMarginKlass = openstPayment.services.airdropManager.setAcceptedMargin
- , airdropAllocationProofDetailKlass = require(rootPrefix + '/app/models/airdrop_allocation_proof_detail')
- , UserAirdropDetailKlass = require(rootPrefix + '/app/models/user_airdrop_detail')
- , responseHelper = require(rootPrefix + '/lib/formatter/response')
-;
-
-var transferToAirdropBudgetHolderTransactionHash = ''
-;
-
-/**
- * Utitlity function to test set accepted margin
- *
- * @param {Object} airdropObject - airdrop object
- * @param {string} currency - currency
- * @param {string} margin - accepted margin
- *
- */
-
-async function setAcceptedMargin(airdropObject, currency, margin) {
- // set accepted margin
- const SetAcceptedMarginObject = new SetAcceptedMarginKlass({
- airdrop_contract_address: constants.airdropOstUsdAddress,
- chain_id: constants.chainId,
- sender_address: constants.ops,
- sender_passphrase: constants.opsPassphrase,
- currency: currency,
- accepted_margin: margin,
- gas_price: constants.gasUsed,
- options: constants.optionsReceipt
- });
- const amResponse = await SetAcceptedMarginObject.perform();
- assert.equal(amResponse.isSuccess(), true);
- // verify if the transaction receipt is valid
- utils.verifyTransactionReceipt(amResponse);
- // verify if the transaction has was actually mined
- await utils.verifyIfMined(airdropObject, amResponse.data.transaction_hash);
- // verify if its set
- const amResult = await airdropObject.acceptedMargins(currency);
- assert.equal(amResult.isSuccess(), true);
- assert.equal(margin, amResult.data.acceptedMargins);
-}
-
-
-/**
- * Utitlity function to test set price oracle
- *
- * @param {Object} airdropObject - airdrop object
- * @param {string} currency - currency
- * @param {string} address - price oracle address
- *
- */
-async function setPriceOracle(airdropObject, currency, address) {
- // Set Price Oracle
- const SetPriceOracleObject = new SetPriceOracleKlass({
- airdrop_contract_address: constants.airdropOstUsdAddress,
- chain_id: constants.chainId,
- sender_address: constants.ops,
- sender_passphrase: constants.opsPassphrase,
- currency: currency,
- price_oracle_contract_address: address,
- gas_price: constants.gasUsed,
- options: constants.optionsReceipt
- });
- const spoResponse = await SetPriceOracleObject.perform();
- assert.equal(spoResponse.isSuccess(), true);
- // verify if the transaction receipt is valid
- utils.verifyTransactionReceipt(spoResponse);
- // verify if the transaction has was actually mined
- await utils.verifyIfMined(airdropObject, spoResponse.data.transaction_hash);
- // verify if its set
- const poResult = await airdropObject.priceOracles(currency);
- assert.equal(poResult.isSuccess(), true);
- assert.equal(address, poResult.data.priceOracles);
-}
-
-
-/**
- * Utitlity function to test set worker
- *
- * @param {string} workerAddress - worker address
- * @param {Bignumber} deactivationHeight - deactivation height of the worker
- *
- */
-async function setWorker(workerAddress, deactivationHeight) {
- const SetWorkerObject = new SetWorkerKlass({
- workers_contract_address: constants.workersContractAddress,
- sender_address: constants.ops,
- sender_passphrase: constants.opsPassphrase,
- worker_address: workerAddress,
- deactivation_height: deactivationHeight.toString(10),
- gas_price: constants.gasUsed,
- chain_id: constants.chainId,
- options: constants.optionsReceipt
- });
- const setWorkerResponse = await SetWorkerObject.perform();
-
- assert.equal(setWorkerResponse.isSuccess(), true);
- // verify if the transaction receipt is valid
- utils.verifyTransactionReceipt(setWorkerResponse);
-
- // confirm that worker is a set
- const IsWorkerObject = new IsWorkerKlass({
- workers_contract_address: constants.workersContractAddress,
- worker_address: workerAddress,
- chain_id: constants.chainId
- });
- const isWorkerResponse = await IsWorkerObject.perform();
- assert.equal(isWorkerResponse.isSuccess(), true);
- assert.equal(isWorkerResponse.data.isValid, true);
-}
-
-
-/**
- * Utitlity function to test setBalance
- *
- * @param {Object} token - branded token object
- * @param {string} address - account address
- * @param {string} amount - amount that need to be set
- * @param {BigNumber} gasPrice - gas price
- *
- */
-async function setBalance(token, address, amount) {
- const amountInWei = airdropOstUsd.toWei(amount);
- await token.setBalance(
- constants.ops,
- constants.opsPassphrase,
- address,
- amountInWei,
- constants.gasUsed);
- // check if the balance was set
- const accountBalance = await token.balanceOf(address);
- assert.equal(accountBalance, amountInWei);
-}
-
-/**
- * Utitlity function to get airdrop id from airdrop address
- *
- * @param {string} airdropAddress - airdrop address
- *
- * @return {Object} - formatted response
- */
-
-async function getAirdropIdFromAirdropAddress(airdropAddress) {
- const airdropModelCacheObject = new AirdropModelCacheKlass({useObject: true, contractAddress: airdropAddress})
- , airdropModelCacheResponse = await airdropModelCacheObject.fetch()
- , airdropRecord = airdropModelCacheResponse.data[airdropAddress]
- ;
- if (airdropRecord) {
- return responseHelper.successWithData({airdropId: airdropRecord.id});
- }
- let errorParams = {
- internal_error_identifier: 'gaidfad',
- api_error_identifier: 'data_not_found',
- error_config: errorConfig,
- debug_options: {}
- };
- return responseHelper.error(errorParams);
-}
-
-/**
- * Utitlity function to register airdrop if not already registered
- *
- * @param {string} airdropAddress - airdrop address
- *
- */
-async function registerAirdrop(airdropAddress) {
- // Do Airdrop Setup if setup was not done
- const airDropIdResponse = await getAirdropIdFromAirdropAddress(airdropAddress);
- if (airDropIdResponse.isFailure()) {
- const RegisterObject = new RegisterKlass({
- airdrop_contract_address: airdropAddress,
- chain_id: constants.chainId
- });
- const registerAirdropResponse = await RegisterObject.perform();
- assert.equal(registerAirdropResponse.isSuccess(), true);
-
- // check again if the database awas set;
- const airDropIdAfterRegisterResponse = await getAirdropIdFromAirdropAddress(airdropAddress);
- assert.equal(airDropIdAfterRegisterResponse.isSuccess(), true);
- }
-}
-
-/**
- * Utitlity function to transfer token to airdrop budget holder
- *
- * @param {Object} token - Branded token object
- * @param {string} airdropAddress - airdrop address
- * @param {string} fromAddress - reserve address
- * @param {string} fromPassphrase - passphrase
- * @param {string} budgetHolderAddress - budget holder address
- * @param {string} amount - amount to transfer to budget holder
- *
- * @return {transaction hash}
- */
-async function transferTokenToAirdropBugetHolder (token, airdropAddress, fromAddress, fromPassphrase, budgetHolderAddress, amount) {
-
- const airdropBudgetAmountInWei = new BigNumber(airdropOstUsd.toWei(amount));
- const initialBalance = new BigNumber(await token.balanceOf(fromAddress));
- const beforeTransferAirdropBudgetHolderBalance = new BigNumber(await token.balanceOf(budgetHolderAddress));
-
- logger.debug("initialBalance:", initialBalance.toString(10),
- "\nairdropBudgetAmount:", airdropBudgetAmountInWei.toString(10),
- "\nairdropAddress:", airdropAddress);
-
- assert.equal(initialBalance.gte(airdropBudgetAmountInWei), true, "insufficent balance to transfer amount to budgetHolderAddress");
-
- const TransferObject = new TransferKlass({
- sender_address: fromAddress,
- sender_passphrase: fromPassphrase,
- airdrop_contract_address: airdropAddress,
- amount: airdropBudgetAmountInWei,
- gas_price: constants.gasUsed,
- chain_id: constants.chainId,
- options: constants.optionsReceipt
- });
- const transferToAirdropBudgetHolderResult = await TransferObject.perform();
- logger.debug("=======transferToAirdropBudgetHolderResult=======");
- logger.debug(transferToAirdropBudgetHolderResult);
- assert.equal(transferToAirdropBudgetHolderResult.isSuccess(), true);
- // verify if the transaction receipt is valid
- await utils.verifyTransactionReceipt(transferToAirdropBudgetHolderResult);
- // verify if the transaction was actually mined
- await utils.verifyIfMined(airdropOstUsd, transferToAirdropBudgetHolderResult.data.transaction_hash);
-
- const afterTransferAirdropBudgetHolderBalance = new BigNumber(await token.balanceOf(budgetHolderAddress));
- assert.equal((beforeTransferAirdropBudgetHolderBalance.plus(airdropBudgetAmountInWei)).equals( afterTransferAirdropBudgetHolderBalance), true);
-
- // set transaction hash
- transferToAirdropBudgetHolderTransactionHash = transferToAirdropBudgetHolderResult.data.transaction_hash;
- return transferToAirdropBudgetHolderTransactionHash;
-}
-
-/**
- * Utitlity function get user airdrop balance
- *
- * @param {string} airdropAddress - airdrop address
- * @param {Array} userAddressArray - user address array
- *
- * @return {Object} - formatted response
- */
-async function getUserAirdropBalanceFromCache(airdropAddress, userAddressArray) {
- // Get cache value
- const UserBalanceObject = new UserBalanceKlass({
- chain_id: constants.chainId,
- airdrop_contract_address: airdropAddress,
- user_addresses: userAddressArray
- });
- const airdropBalanceResult = await UserBalanceObject.perform();
- const zeroAmount = {
- totalAirdropAmount: '0',
- totalAirdropUsedAmount: '0',
- balanceAirdropAmount: '0'
- };
- var responseData = {};
- if (airdropBalanceResult.isSuccess()) {
- responseData = airdropBalanceResult.data;
- }
- var data = {};
- for (var i = userAddressArray.length - 1; i >= 0; i--) {
- if(responseData[userAddressArray[i]]) {
- data[userAddressArray[i]] = responseData[userAddressArray[i]];
- } else {
- data[userAddressArray[i]] = zeroAmount;
- }
- }
- return responseHelper.successWithData(data);
-}
-
-/**
- * Utitlity function get user airdrop balance form DB, bypass cache layer
- *
- * @param {string} airdropAddress - airdrop address
- * @param {Array} userAddressArray - user address array
- *
- * @return {Object} - formatted response
- */
-async function getUserAirdropBalanceFromDB(airdropAddress, userAddressArray) {
-
- const airDropIdResponse = await getAirdropIdFromAirdropAddress(airdropAddress);
- if (airDropIdResponse.isSuccess()) {
- const airdropId = airDropIdResponse.data.airdropId;
- const userAirdropDetailModel = new UserAirdropDetailKlass();
-
- const queryResponse = await userAirdropDetailModel.getByUserAddresses(airdropId, userAddressArray);
-
- var responseData = {};
- if (queryResponse.isSuccess()) {
- responseData = queryResponse.data;
- }
- var data = {};
- for (var i = userAddressArray.length - 1; i >= 0; i--) {
- if(responseData[userAddressArray[i]]) {
- data[userAddressArray[i]] = responseData[userAddressArray[i]];
- } else {
- data[userAddressArray[i]] = {
- totalAirdropAmount: '0',
- totalAirdropUsedAmount: '0',
- balanceAirdropAmount: '0'
- };
- }
- }
- return responseHelper.successWithData(data);
- }
- return airDropIdResponse;
-}
-
-/**
- * Utitlity function to compare the airdrop balances from DB and cache
- *
- * @param {Object} dbBalance - airdrop balance from DB
- * @param {Object} cacheBalance - airdrop balance from cache
- *
- */
-function validateDBandCacheAirdropBalances(dbBalance, cacheBalance) {
-
- const compare = function(obj1, obj2) {
- assert.equal(obj1.totalAirdropAmount, obj2.totalAirdropAmount);
- assert.equal(obj1.totalAirdropUsedAmount, obj2.totalAirdropUsedAmount);
- assert.equal(obj1.balanceAirdropAmount, obj2.balanceAirdropAmount);
- };
-
- const dbUserKeys = Object.keys(dbBalance);
- const cacheUserKeys = Object.keys(cacheBalance);
- assert.equal(dbUserKeys.length, cacheUserKeys.length);
- for (var i = dbUserKeys.length - 1; i >= 0; i--) {
- const dbObject = dbBalance[dbUserKeys[i]];
- const cacheObject = cacheBalance[cacheUserKeys[i]];
- assert.isDefined(dbObject);
- assert.isDefined(cacheObject);
- compare(dbObject, cacheObject);
- }
-}
-
-/**
- * Utitlity function to get balance of address from contract
- *
- * @param {Object} token - token
- * @param {string} address - address whose balances need to be found
- *
- */
-async function getBalanceFromContract(token, address) {
- var balances = {};
- for (var i = address.length - 1; i >= 0; i--) {
- const addressKey = address[i];
- balances[addressKey] = new BigNumber(await token.balanceOf(addressKey));
- }
- return balances;
-}
-
-/**
- * Utitlity function to get balance of address from cache
- *
- * @param {Object} token - token
- * @param {string} address - address whose balances need to be found
- *
- */
-async function getBalanceFromCache(tokenObj, address) {
- var balances = {};
- for (var i = address.length - 1; i >= 0; i--) {
- const addressKey = address[i];
- const balance = await tokenObj.getBalanceOf(addressKey);
- assert.equal(balance.isSuccess(), true);
- balances[addressKey] = new BigNumber(balance.data.balance);
- }
- return balances;
-}
-
-/**
- * Utitlity function to compare balances from cache and contract
- *
- * @param {Object} contractBalances - balances from contract
- * @param {Object} cacheBalance - balances from cache
- *
- */
-
-function validateContractAndCacheBalance(cacheBalance, contractBalances) {
- const contractKeys = Object.keys(cacheBalance);
- const cacheKeys = Object.keys(contractBalances);
- assert.equal(contractKeys.length, cacheKeys.length);
- for (var i = contractKeys.length - 1; i >= 0; i--) {
- const balanceFromContract = contractBalances[contractKeys[i]];
- const balanceFromCache = cacheBalance[contractKeys[i]];
- assert.isDefined(balanceFromContract);
- assert.isDefined(balanceFromCache);
- assert.equal(balanceFromCache.equals(balanceFromContract), true);
- }
-}
-
-/**
- * Utitlity function to validate if airdrop was transfered successfully
- *
- * @param {string} accountAddress - user address
- * @param {Object} initialAirdropBalance - Initial airdrop balance
- * @param {Object} currentAirdropBalance - Current airdrop balance
- * @param {BigNumber} airdropAmountTransfered - estimated airdrop amount that was transfered
- */
-function validateAirdropTransferSuccess(accountAddress, initialAirdropBalance, currentAirdropBalance, airdropAmountTransfered) {
-
- const initialAirdropBalanceData = initialAirdropBalance.data[accountAddress];
- const currentAirdropBalanceData = currentAirdropBalance.data[accountAddress];
-
- assert.isDefined(initialAirdropBalanceData);
- assert.isDefined(currentAirdropBalanceData);
-
- const intialTotalAirdropAmount = new BigNumber(initialAirdropBalanceData.totalAirdropAmount);
- const initialTotalAirdropUsedAmount = new BigNumber(initialAirdropBalanceData.totalAirdropUsedAmount);
- const initialBalanceAirdropAmount = new BigNumber(initialAirdropBalanceData.balanceAirdropAmount);
-
- const totalAirdropAmount = new BigNumber(currentAirdropBalanceData.totalAirdropAmount);
- const totalAirdropUsedAmount = new BigNumber(currentAirdropBalanceData.totalAirdropUsedAmount);
- const balanceAirdropAmount = new BigNumber(currentAirdropBalanceData.balanceAirdropAmount);
-
- assert.equal(intialTotalAirdropAmount.equals(totalAirdropAmount), true);
- assert.equal((initialTotalAirdropUsedAmount.plus(airdropAmountTransfered)).equals(totalAirdropUsedAmount), true);
- assert.equal((initialBalanceAirdropAmount.minus(airdropAmountTransfered)).equals(balanceAirdropAmount), true);
-}
-
-function validateTransferSuccess(
- estimatedTokenAmount,
- estimatedCommissionTokenAmount,
- estimatedAirdropUsed,
- spenderAddress,
- beneficiary,
- commissionBeneficiary,
- airdropBudgetHolder,
- initialBalances,
- currentBalances) {
-
- assert.isDefined(estimatedTokenAmount);
- assert.isDefined(estimatedCommissionTokenAmount);
- assert.isDefined(estimatedAirdropUsed);
- assert.isDefined(spenderAddress);
- assert.isDefined(beneficiary);
- assert.isDefined(commissionBeneficiary);
- assert.isDefined(airdropBudgetHolder);
- assert.isDefined(initialBalances);
- assert.isDefined(currentBalances);
-
- const estimatedTotalAmount = estimatedTokenAmount.plus(estimatedCommissionTokenAmount);
- const actualTransferAmount = estimatedTotalAmount.minus(estimatedAirdropUsed);
- const calculatedBenficiaryAmount = initialBalances[beneficiary].plus(estimatedTokenAmount);
- const calculatedCommisionAmount = initialBalances[commissionBeneficiary].plus(estimatedCommissionTokenAmount);
- const calculatedSpenderAmount = initialBalances[spenderAddress].minus(actualTransferAmount);
- const calculatesBugdetHolderAmount = initialBalances[airdropBudgetHolder].minus(estimatedAirdropUsed);
-
- assert.equal(calculatedBenficiaryAmount.equals(currentBalances[beneficiary]), true);
- assert.equal(calculatedCommisionAmount.equals(currentBalances[commissionBeneficiary]), true);
- assert.equal(calculatedSpenderAmount.equals(currentBalances[spenderAddress]), true);
- assert.equal(calculatesBugdetHolderAmount.equals(currentBalances[airdropBudgetHolder]), true);
-}
-
-/**
- * Utitlity function to populate the cache of all test accounts
- *
- */
-async function populateCache() {
- // Populate Cache
- await brandedTokenObject.getBalanceOf(constants.account1);
- await brandedTokenObject.getBalanceOf(constants.account2);
- await brandedTokenObject.getBalanceOf(constants.account3);
- await brandedTokenObject.getBalanceOf(constants.account4);
- await brandedTokenObject.getBalanceOf(constants.account5);
- await brandedTokenObject.getBalanceOf(constants.airdropBudgetHolder);
-}
-// Tests starts here
-describe('Airdrop Pay', function() {
-
- it('should pass the initial checks', async function() {
- // eslint-disable-next-line no-invalid-this
- this.timeout(500000);
-
- // check if the address required for the testing are defined.
- assert.isDefined(constants.deployer);
- assert.isDefined(constants.ops);
- assert.isDefined(constants.account1);
- assert.isDefined(constants.workerAccount1);
- assert.isDefined(constants.airdropBudgetHolder);
-
- assert.notEqual(constants.deployer, constants.ops);
- assert.notEqual(constants.deployer, constants.account1);
- assert.notEqual(constants.ops, constants.account1);
-
- // set worker
- logger.debug("============= Set worker =============");
- const currentBlockNumber = await web3Provider.eth.getBlockNumber();
- await setWorker(constants.workerAccount1, new BigNumber(currentBlockNumber).plus(100000000000));
-
- // Set Price Oracle
- logger.debug("============= Set Price Oracle =============");
- await setPriceOracle(airdropOstUsd, constants.currencyUSD, constants.priceOracles.OST.USD);
-
- // set accepted margin
- logger.debug("============= Set accepted margin =============");
- await setAcceptedMargin(airdropOstUsd, constants.currencyUSD, 50);
-
- // set balance for account 1 (Spender)
- logger.debug("============= Set account 1 balance =============");
- await setBalance(TC5, constants.account1, constants.account1InitialBrandedTokenBalance);
-
- // reset balance for account 2 to 100
- logger.debug("============= Set account 2 balance =============");
- await setBalance(TC5, constants.account2, '100');
-
- // reset balance for account 3 to 0
- logger.debug("============= Set account 3 balance =============");
- await setBalance(TC5, constants.account3, '0');
-
- // reset balance for account 4 to 0
- logger.debug("============= Set account 4 balance =============");
- await setBalance(TC5, constants.account4, '0');
-
- // reset balance of account airdropBudgetHolder to 0
- logger.debug("============= Set airdropBudgetHolder balance =============");
- await setBalance(TC5, constants.airdropBudgetHolder, '0');
-
- // Do Airdrop Setup if setup was not done
- logger.debug("============= Do Airdrop Setup if setup was not done =============");
- await registerAirdrop(constants.airdropOstUsdAddress);
-
- // Populate Cache
- populateCache();
-
- });
-
- it('AirdropManager: transfer branded token from reserve to airdropBudgetHolder and approve airdrop contract', async function() {
- // eslint-disable-next-line no-invalid-this
- this.timeout(100000);
-
- const address = [
- constants.account1,
- constants.airdropBudgetHolder
- ];
- const initalBalancesFromContract = await getBalanceFromContract(TC5, address);
- const initalBalancesCache = await getBalanceFromCache(brandedTokenObject, address);
- validateContractAndCacheBalance(initalBalancesFromContract, initalBalancesCache);
-
-
- // transfer amount
- await transferTokenToAirdropBugetHolder(TC5,
- constants.airdropOstUsdAddress,
- constants.account1,
- constants.accountPassphrase1,
- constants.airdropBudgetHolder,
- constants.airdropBudgetBrandedTokenBalance);
-
- const balanceFromContract = await getBalanceFromContract(TC5, address);
- const balancesFromCache = await getBalanceFromCache(brandedTokenObject, address);
- validateContractAndCacheBalance(balanceFromContract, balancesFromCache);
-
- // approve
- const ApproveObject = new ApproveKlass({
- airdrop_contract_address: constants.airdropOstUsdAddress,
- airdrop_budget_holder_passphrase: constants.airdropBudgetHolderPassphrase,
- gas_price: constants.gasUsed,
- chain_id: constants.chainId,
- options: constants.optionsReceipt
- });
- const approveToAirdropBudgetHolderResult = await ApproveObject.perform();
- logger.debug("=======approveToAirdropBudgetHolderResult=======");
- logger.debug(approveToAirdropBudgetHolderResult);
-
- assert.equal(approveToAirdropBudgetHolderResult.isSuccess(), true);
- // verify if the transaction receipt is valid
- await utils.verifyTransactionReceipt(approveToAirdropBudgetHolderResult);
- // verify if the transaction was actually mined
- await utils.verifyIfMined(airdropOstUsd, approveToAirdropBudgetHolderResult.data.transaction_hash);
- });
-
-
- it('AirdropManager: batch allocate to airdrop users and check user balance', async function() {
- // eslint-disable-next-line no-invalid-this
- this.timeout(10000);
-
- var airdropUsers = constants.airdropUsers;
- airdropUsers[constants.account2] = {airdropAmount: '100000000000000000000', expiryTimestamp: 0};
-
- // checks for cache and DB consistency
- const beforeAllocationBalanceFromDB = await getUserAirdropBalanceFromDB(constants.airdropOstUsdAddress, Object.keys(airdropUsers));
- const beforeAllocationBalanceFromCache = await getUserAirdropBalanceFromCache(constants.airdropOstUsdAddress, Object.keys(airdropUsers));
- validateDBandCacheAirdropBalances(beforeAllocationBalanceFromDB.data, beforeAllocationBalanceFromCache.data);
-
- const BatchAllocatorObject = new BatchAllocatorKlass({
- airdrop_contract_address: constants.airdropOstUsdAddress,
- transaction_hash: transferToAirdropBudgetHolderTransactionHash,
- airdrop_users: airdropUsers,
- chain_id: constants.chainId
- });
- const batchAllocateAirdropAmountResult = await BatchAllocatorObject.perform();
-
- assert.equal(batchAllocateAirdropAmountResult.isSuccess(), true);
- var airdropAllocationProofDetailModel = new airdropAllocationProofDetailKlass();
- var result = await airdropAllocationProofDetailModel.getByTransactionHash(transferToAirdropBudgetHolderTransactionHash);
- var airdropAllocationProofDetailRecord = result[0];
- // airdrop_allocated_amount is less than or equal to airdrop_amount
- assert.equal(new BigNumber(airdropAllocationProofDetailRecord.airdrop_allocated_amount).lte(new BigNumber(airdropAllocationProofDetailRecord.airdrop_amount)), true);
-
-
- // checks for cache and DB consistency
- const afterAllocationBalanceFromDB = await getUserAirdropBalanceFromDB(constants.airdropOstUsdAddress, Object.keys(airdropUsers));
- const afterAllocationBalanceFromCache = await getUserAirdropBalanceFromCache(constants.airdropOstUsdAddress, Object.keys(airdropUsers));
- validateDBandCacheAirdropBalances(afterAllocationBalanceFromDB.data, afterAllocationBalanceFromCache.data);
-
- // check if the airdrop balance reflects the proper value.
- const allUserKeys = Object.keys(airdropUsers);
- for (var i = allUserKeys.length - 1; i >= 0; i--) {
- const userKey = allUserKeys[i];
- const initialTotalAirdropAmount = new BigNumber(beforeAllocationBalanceFromDB.data[userKey].totalAirdropAmount);
- const initialTotalAirdropUsedAmount = new BigNumber(beforeAllocationBalanceFromDB.data[userKey].totalAirdropUsedAmount);
- const initialBalanceAirdropAmount = new BigNumber(beforeAllocationBalanceFromDB.data[userKey].balanceAirdropAmount);
-
- const totalAirdropAmount = new BigNumber(afterAllocationBalanceFromDB.data[userKey].totalAirdropAmount);
- const totalAirdropUsedAmount = new BigNumber(afterAllocationBalanceFromDB.data[userKey].totalAirdropUsedAmount);
- const balanceAirdropAmount = new BigNumber(afterAllocationBalanceFromDB.data[userKey].balanceAirdropAmount);
-
- assert.equal((initialTotalAirdropAmount.plus(new BigNumber(airdropUsers[userKey].airdropAmount))).equals(totalAirdropAmount), true);
-
- assert.equal(initialTotalAirdropUsedAmount.equals(totalAirdropUsedAmount), true);
- assert.equal(initialTotalAirdropUsedAmount.equals(0), true);
-
- assert.equal((initialBalanceAirdropAmount.plus(new BigNumber(airdropUsers[userKey].airdropAmount))).equals(balanceAirdropAmount), true);
- }
- });
-
-
- it('should fail when worker is not whitelisted', async function() {
- // eslint-disable-next-line no-invalid-this
- this.timeout(100000);
-
- // Populate Cache
- populateCache();
-
- const beneficiary = constants.account3
- , commissionAmount = new BigNumber(airdropOstUsd.toWei('0.9'))
- , commissionBeneficiary = constants.account4
- , currency = constants.currencyUSD
- , transferAmount = new BigNumber(airdropOstUsd.toWei('1.18'))
- , spenderAddress = constants.account2
- , spenderPassphrase = constants.accountPassphrase2
- , airdropBudgetHolder = constants.airdropBudgetHolder
- ;
-
- // checks for account balance cache and DB consistency
- logger.debug("============ Validating consistency for account balance form cache and contract =============");
- const address = [
- spenderAddress,
- beneficiary,
- commissionBeneficiary,
- airdropBudgetHolder
- ];
- const initalBalancesFromContract = await getBalanceFromContract(TC5, address);
- const initalBalancesCache = await getBalanceFromCache(brandedTokenObject, address);
- validateContractAndCacheBalance(initalBalancesFromContract, initalBalancesCache);
-
-
- // checks for airdrop balance cache and DB consistency
- logger.debug("============ Validating consistency for airdrop balance form cache and DB =============");
- const airdropUserAddress = [spenderAddress];
- const initialAirdropBalanceFromDB = await getUserAirdropBalanceFromDB(constants.airdropOstUsdAddress, airdropUserAddress);
- const initialAirdropBalanceFromCache = await getUserAirdropBalanceFromCache(constants.airdropOstUsdAddress, airdropUserAddress);
- validateDBandCacheAirdropBalances(initialAirdropBalanceFromDB.data, initialAirdropBalanceFromCache.data);
-
- const UserBalanceObject = new UserBalanceKlass({
- chain_id: constants.chainId,
- airdrop_contract_address: constants.airdropOstUsdAddress,
- user_addresses: [spenderAddress]
- });
- const airdropBalanceResult = await UserBalanceObject.perform();
- assert.equal(airdropBalanceResult.isSuccess(), true);
- const availableAirdropBalance = new BigNumber(airdropBalanceResult.data[spenderAddress].balanceAirdropAmount);
-
- const estimatedValues = await airdropOstUsd.getPricePointAndCalculatedAmounts(
- transferAmount,
- commissionAmount,
- currency);
- assert.equal(estimatedValues.isSuccess(), true);
-
- const estimatedTokenAmount = new BigNumber(estimatedValues.data.tokenAmount);
- const estimatedCommissionTokenAmount = new BigNumber(estimatedValues.data.commissionTokenAmount);
- const intendedPricePoint = estimatedValues.data.pricePoint;
-
- const estimatedTotalAmount = new BigNumber(0).plus(estimatedTokenAmount).plus(estimatedCommissionTokenAmount);
-
- const estimatedAirdropUsed = BigNumber.min(estimatedTotalAmount, availableAirdropBalance);
- logger.debug("============ estimatedAirdropUsed ============");
- logger.debug(estimatedAirdropUsed);
-
- // Approve account1 for transfer
- const accountApproveResponse = await TC5.approve(
- spenderAddress,
- spenderPassphrase,
- constants.airdropOstUsdAddress,
- estimatedTotalAmount.plus(100),
- constants.gasUsed);
-
- logger.debug("============spender approving to contract=============");
- logger.debug(accountApproveResponse);
- var worker1Balance = await web3Provider.eth.getBalance(constants.workerAccount1);
- logger.debug("\nconstants.workerAccount1.balance: ", worker1Balance);
-
- const PayObject = new PayKlass({
- airdrop_contract_address: constants.airdropOstUsdAddress,
- chain_id: constants.chainId,
- sender_worker_address: constants.ops,
- sender_worker_passphrase: constants.opsPassphrase,
- beneficiary_address: beneficiary,
- transfer_amount: transferAmount.toString(10),
- commission_beneficiary_address: commissionBeneficiary,
- commission_amount: commissionAmount.toString(10),
- currency: currency,
- intended_price_point: intendedPricePoint,
- spender: spenderAddress,
- gas_price: constants.gasUsed,
- options: constants.optionsReceipt
- });
- const payResponse = await PayObject.perform();
-
- assert.equal(payResponse.isFailure(), true);
- logger.debug("============airdrop.pay response=============");
- logger.debug(payResponse);
-
-
- // checks for account balance cache and DB consistency
- logger.debug("============ Validating consistency for account balance form cache and contract after pay =============");
- const balanceFromContract = await getBalanceFromContract(TC5, address);
- const balancesFromCache = await getBalanceFromCache(brandedTokenObject, address);
- validateContractAndCacheBalance(balanceFromContract, balancesFromCache);
- //check if the initial and current balances are reverted properly
- validateContractAndCacheBalance(initalBalancesFromContract, balanceFromContract);
-
- // checks for airdrop balance cache and DB consistency
- logger.debug("============ Validating consistency for airdrop balance form cache and DB after pay =============");
- const airdropBalanceFromDB = await getUserAirdropBalanceFromDB(constants.airdropOstUsdAddress, airdropUserAddress);
- const airdropBalanceFromCache = await getUserAirdropBalanceFromCache(constants.airdropOstUsdAddress, airdropUserAddress);
- validateDBandCacheAirdropBalances(airdropBalanceFromDB.data, airdropBalanceFromCache.data);
- // validate if the airdrop transfer was reverted properly
- validateDBandCacheAirdropBalances(initialAirdropBalanceFromDB.data, airdropBalanceFromDB.data);
-
- });
-
- it('should pass when transfer amount is less than available airdrop amount', async function() {
- // eslint-disable-next-line no-invalid-this
- this.timeout(100000);
-
- // Populate Cache
- populateCache();
-
- const beneficiary = constants.account3
- , commissionAmount = new BigNumber(airdropOstUsd.toWei('0.7'))
- , commissionBeneficiary = constants.account4
- , currency = constants.currencyUSD
- , transferAmount = new BigNumber(airdropOstUsd.toWei('1.91'))
- , spenderAddress = constants.account2
- , spenderPassphrase = constants.accountPassphrase2
- , airdropBudgetHolder = constants.airdropBudgetHolder
- ;
-
- // checks for account balance cache and DB consistency
- logger.debug("============ Validating consistency for account balance form cache and contract =============");
- const address = [
- spenderAddress,
- beneficiary,
- commissionBeneficiary,
- airdropBudgetHolder
- ];
- const initalBalancesFromContract = await getBalanceFromContract(TC5, address);
- const initalBalancesCache = await getBalanceFromCache(brandedTokenObject, address);
- validateContractAndCacheBalance(initalBalancesFromContract, initalBalancesCache);
-
-
- // checks for airdrop balance cache and DB consistency
- logger.debug("============ Validating consistency for airdrop balance form cache and DB =============");
- const airdropUserAddress = [spenderAddress];
- const initialAirdropBalanceFromDB = await getUserAirdropBalanceFromDB(constants.airdropOstUsdAddress, airdropUserAddress);
- const initialAirdropBalanceFromCache = await getUserAirdropBalanceFromCache(constants.airdropOstUsdAddress, airdropUserAddress);
- validateDBandCacheAirdropBalances(initialAirdropBalanceFromDB.data, initialAirdropBalanceFromCache.data);
-
- const UserBalanceObject = new UserBalanceKlass({
- chain_id: constants.chainId,
- airdrop_contract_address: constants.airdropOstUsdAddress,
- user_addresses: [spenderAddress]
- });
- const airdropBalanceResult = await UserBalanceObject.perform();
- assert.equal(airdropBalanceResult.isSuccess(), true);
- const availableAirdropBalance = new BigNumber(airdropBalanceResult.data[spenderAddress].balanceAirdropAmount);
-
- const estimatedValues = await airdropOstUsd.getPricePointAndCalculatedAmounts(
- transferAmount,
- commissionAmount,
- currency);
- assert.equal(estimatedValues.isSuccess(), true);
-
- const estimatedTokenAmount = new BigNumber(estimatedValues.data.tokenAmount);
- const estimatedCommissionTokenAmount = new BigNumber(estimatedValues.data.commissionTokenAmount);
- const intendedPricePoint = estimatedValues.data.pricePoint;
-
- const estimatedTotalAmount = new BigNumber(0).plus(estimatedTokenAmount).plus(estimatedCommissionTokenAmount);
-
- const estimatedAirdropUsed = BigNumber.min(estimatedTotalAmount, availableAirdropBalance);
- logger.debug("============ estimatedAirdropUsed ============");
- logger.debug(estimatedAirdropUsed);
- // here we make sure that airdrop amount used will be greater than 0
- assert.equal(estimatedAirdropUsed.gt(0), true);
- // Approve account1 for transfer
- const accountApproveResponse = await TC5.approve(
- spenderAddress,
- spenderPassphrase,
- constants.airdropOstUsdAddress,
- estimatedTotalAmount.plus(100),
- constants.gasUsed);
-
- logger.debug("============spender approving to contract=============");
- logger.debug(accountApproveResponse);
- var worker1Balance = await web3Provider.eth.getBalance(constants.workerAccount1);
- logger.debug("\nconstants.workerAccount1.balance: ", worker1Balance);
-
- const PayObject = new PayKlass({
- airdrop_contract_address: constants.airdropOstUsdAddress,
- chain_id: constants.chainId,
- sender_worker_address: constants.workerAccount1,
- sender_worker_passphrase: constants.workerAccountPassphrase1,
- beneficiary_address: beneficiary,
- transfer_amount: transferAmount.toString(10),
- commission_beneficiary_address: commissionBeneficiary,
- commission_amount: commissionAmount.toString(10),
- currency: currency,
- intended_price_point: intendedPricePoint,
- spender: spenderAddress,
- gas_price: constants.gasUsed,
- options: constants.optionsReceipt
- });
- const payResponse = await PayObject.perform();
-
- assert.equal(payResponse.isSuccess(), true);
- logger.debug("============airdrop.pay response=============");
- logger.debug(payResponse);
-
- // verify if the transaction receipt is valid
- utils.verifyTransactionReceipt(payResponse);
- // verify if the transaction is actually mined
- await utils.verifyIfMined(airdropOstUsd, payResponse.data.transaction_hash);
-
-
- // checks for account balance cache and DB consistency
- logger.debug("============ Validating consistency for account balance form cache and contract after pay =============");
- const balanceFromContract = await getBalanceFromContract(TC5, address);
- const balancesFromCache = await getBalanceFromCache(brandedTokenObject, address);
- validateContractAndCacheBalance(balanceFromContract, balancesFromCache);
- //check if the transfer was propre
- validateTransferSuccess(
- estimatedTokenAmount,
- estimatedCommissionTokenAmount,
- estimatedAirdropUsed,
- spenderAddress,
- beneficiary,
- commissionBeneficiary,
- airdropBudgetHolder,
- initalBalancesFromContract,
- balanceFromContract);
-
- // checks for airdrop balance cache and DB consistency
- logger.debug("============ Validating consistency for airdrop balance form cache and DB after pay =============");
- const airdropBalanceFromDB = await getUserAirdropBalanceFromDB(constants.airdropOstUsdAddress, airdropUserAddress);
- const airdropBalanceFromCache = await getUserAirdropBalanceFromCache(constants.airdropOstUsdAddress, airdropUserAddress);
- validateDBandCacheAirdropBalances(airdropBalanceFromDB.data, airdropBalanceFromCache.data);
- // validate if the airdrop transfer was proper
- validateAirdropTransferSuccess(
- spenderAddress,
- initialAirdropBalanceFromDB,
- airdropBalanceFromDB,
- estimatedAirdropUsed);
-
- });
-
- // This is with an assumption that pervious test was passed and due to that constants.account3 has some balance
- it('should pass when airdrop amount is 0', async function() {
- // eslint-disable-next-line no-invalid-this
- this.timeout(100000);
-
- // Populate Cache
- populateCache();
-
- const beneficiary = constants.account1
- , commissionAmount = new BigNumber(airdropOstUsd.toWei('0.0000000001'))
- , commissionBeneficiary = constants.account4
- , currency = constants.currencyUSD
- , transferAmount = new BigNumber(airdropOstUsd.toWei('0.000000033'))
- , spenderAddress = constants.account3
- , spenderPassphrase = constants.accountPassphrase3
- , airdropBudgetHolder = constants.airdropBudgetHolder
- ;
-
- // checks for account balance cache and DB consistency
- logger.debug("============ Validating consistency for account balance form cache and contract =============");
- const address = [
- spenderAddress,
- beneficiary,
- commissionBeneficiary,
- airdropBudgetHolder
- ];
- const initalBalancesFromContract = await getBalanceFromContract(TC5, address);
- const initalBalancesCache = await getBalanceFromCache(brandedTokenObject, address);
- validateContractAndCacheBalance(initalBalancesFromContract, initalBalancesCache);
-
-
- // checks for airdrop balance cache and DB consistency
- logger.debug("============ Validating consistency for airdrop balance form cache and DB =============");
- const airdropUserAddress = [spenderAddress];
- const initialAirdropBalanceFromDB = await getUserAirdropBalanceFromDB(constants.airdropOstUsdAddress, airdropUserAddress);
- const initialAirdropBalanceFromCache = await getUserAirdropBalanceFromCache(constants.airdropOstUsdAddress, airdropUserAddress);
- validateDBandCacheAirdropBalances(initialAirdropBalanceFromDB.data, initialAirdropBalanceFromCache.data);
-
- const UserBalanceObject = new UserBalanceKlass({
- chain_id: constants.chainId,
- airdrop_contract_address: constants.airdropOstUsdAddress,
- user_addresses: [spenderAddress]
- });
- const airdropBalanceResult = await UserBalanceObject.perform();
- assert.equal(airdropBalanceResult.isSuccess(), true);
- // this line is to make sure that the airdropBalance is not availalbe for the user. This is because this user was never allocated airdrop.
- assert.isUndefined(airdropBalanceResult.data[spenderAddress]);
- const availableAirdropBalance = new BigNumber(0);
-
- const estimatedValues = await airdropOstUsd.getPricePointAndCalculatedAmounts(
- transferAmount,
- commissionAmount,
- currency);
- assert.equal(estimatedValues.isSuccess(), true);
-
- const estimatedTokenAmount = new BigNumber(estimatedValues.data.tokenAmount);
- const estimatedCommissionTokenAmount = new BigNumber(estimatedValues.data.commissionTokenAmount);
- const intendedPricePoint = estimatedValues.data.pricePoint;
-
- const estimatedTotalAmount = new BigNumber(0).plus(estimatedTokenAmount).plus(estimatedCommissionTokenAmount);
-
- const estimatedAirdropUsed = BigNumber.min(estimatedTotalAmount, availableAirdropBalance);
- logger.debug("============ estimatedAirdropUsed ============");
- logger.debug(estimatedAirdropUsed);
- // Here we make sure that the airdrop amount is 0;
- assert.equal(estimatedAirdropUsed.equals(0), true);
- // Approve account1 for transfer
- const accountApproveResponse = await TC5.approve(
- spenderAddress,
- spenderPassphrase,
- constants.airdropOstUsdAddress,
- estimatedTotalAmount.plus(100),
- constants.gasUsed);
-
- logger.debug("============spender approving to contract=============");
- logger.debug(accountApproveResponse);
- var worker1Balance = await web3Provider.eth.getBalance(constants.workerAccount1);
- logger.debug("\nconstants.workerAccount1.balance: ", worker1Balance);
-
- const PayObject = new PayKlass({
- airdrop_contract_address: constants.airdropOstUsdAddress,
- chain_id: constants.chainId,
- sender_worker_address: constants.workerAccount1,
- sender_worker_passphrase: constants.workerAccountPassphrase1,
- beneficiary_address: beneficiary,
- transfer_amount: transferAmount.toString(10),
- commission_beneficiary_address: commissionBeneficiary,
- commission_amount: commissionAmount.toString(10),
- currency: currency,
- intended_price_point: intendedPricePoint,
- spender: spenderAddress,
- gas_price: constants.gasUsed,
- options: constants.optionsReceipt
- });
- const payResponse = await PayObject.perform();
- assert.equal(payResponse.isSuccess(), true);
- logger.debug("============airdrop.pay response=============");
- logger.debug(payResponse);
-
- // verify if the transaction receipt is valid
- utils.verifyTransactionReceipt(payResponse);
- // verify if the transaction is actually mined
- await utils.verifyIfMined(airdropOstUsd, payResponse.data.transaction_hash);
-
-
- // checks for account balance cache and DB consistency
- logger.debug("============ Validating consistency for account balance form cache and contract after pay =============");
- const balanceFromContract = await getBalanceFromContract(TC5, address);
- const balancesFromCache = await getBalanceFromCache(brandedTokenObject, address);
- validateContractAndCacheBalance(balanceFromContract, balancesFromCache);
- //check if the transfer was propre
- validateTransferSuccess(
- estimatedTokenAmount,
- estimatedCommissionTokenAmount,
- estimatedAirdropUsed,
- spenderAddress,
- beneficiary,
- commissionBeneficiary,
- airdropBudgetHolder,
- initalBalancesFromContract,
- balanceFromContract);
-
- // checks for airdrop balance cache and DB consistency
- logger.debug("============ Validating consistency for airdrop balance form cache and DB after pay =============");
- const airdropBalanceFromDB = await getUserAirdropBalanceFromDB(constants.airdropOstUsdAddress, airdropUserAddress);
- const airdropBalanceFromCache = await getUserAirdropBalanceFromCache(constants.airdropOstUsdAddress, airdropUserAddress);
- validateDBandCacheAirdropBalances(airdropBalanceFromDB.data, airdropBalanceFromCache.data);
- // validate if the airdrop transfer was proper
- validateAirdropTransferSuccess(
- spenderAddress,
- initialAirdropBalanceFromDB,
- airdropBalanceFromDB,
- estimatedAirdropUsed);
- });
-
- it('should pass when all airdrop amount is used and partial user balance is used', async function() {
- // eslint-disable-next-line no-invalid-this
- this.timeout(100000);
-
- // Populate Cache
- populateCache();
- const spenderAddress = constants.account2
- , spenderPassphrase = constants.accountPassphrase2
- ;
- const UserBalanceObject = new UserBalanceKlass({
- chain_id: constants.chainId,
- airdrop_contract_address: constants.airdropOstUsdAddress,
- user_addresses: [spenderAddress]
- });
- const airdropBalanceResult = await UserBalanceObject.perform();
- assert.equal(airdropBalanceResult.isSuccess(), true);
-
- const availableAirdropBalance = new BigNumber(airdropBalanceResult.data[spenderAddress].balanceAirdropAmount);
- const partialAmount = new BigNumber(10);
-
- const beneficiary = constants.account3
- , commissionAmount = partialAmount
- , commissionBeneficiary = constants.account4
- , currency = constants.currencyUSD
- , transferAmount = availableAirdropBalance.div(6).floor()
- , airdropBudgetHolder = constants.airdropBudgetHolder
- ;
-
- // checks for account balance cache and DB consistency
- logger.debug("============ Validating consistency for account balance form cache and contract =============");
- const address = [
- spenderAddress,
- beneficiary,
- commissionBeneficiary,
- airdropBudgetHolder
- ];
- const initalBalancesFromContract = await getBalanceFromContract(TC5, address);
- const initalBalancesCache = await getBalanceFromCache(brandedTokenObject, address);
- validateContractAndCacheBalance(initalBalancesFromContract, initalBalancesCache);
-
- // checks for airdrop balance cache and DB consistency
- logger.debug("============ Validating consistency for airdrop balance form cache and DB =============");
- const airdropUserAddress = [spenderAddress];
- const initialAirdropBalanceFromDB = await getUserAirdropBalanceFromDB(constants.airdropOstUsdAddress, airdropUserAddress);
- const initialAirdropBalanceFromCache = await getUserAirdropBalanceFromCache(constants.airdropOstUsdAddress, airdropUserAddress);
- validateDBandCacheAirdropBalances(initialAirdropBalanceFromDB.data, initialAirdropBalanceFromCache.data);
-
- const estimatedValues = await airdropOstUsd.getPricePointAndCalculatedAmounts(
- transferAmount,
- commissionAmount,
- currency);
- assert.equal(estimatedValues.isSuccess(), true);
-
- const estimatedTokenAmount = new BigNumber(estimatedValues.data.tokenAmount);
- const estimatedCommissionTokenAmount = new BigNumber(estimatedValues.data.commissionTokenAmount);
- const intendedPricePoint = estimatedValues.data.pricePoint;
-
- const estimatedTotalAmount = new BigNumber(0).plus(estimatedTokenAmount).plus(estimatedCommissionTokenAmount);
-
- const estimatedAirdropUsed = BigNumber.min(estimatedTotalAmount, availableAirdropBalance);
- logger.debug("============ estimatedAirdropUsed ============");
- logger.debug(estimatedAirdropUsed);
- // here we make sure that airdrop amount used will be greater than 0
- assert.equal(estimatedAirdropUsed.gt(0), true);
- // Approve account1 for transfer
- const accountApproveResponse = await TC5.approve(
- spenderAddress,
- spenderPassphrase,
- constants.airdropOstUsdAddress,
- estimatedTotalAmount.plus(100),
- constants.gasUsed);
-
- logger.debug("============spender approving to contract=============");
- logger.debug(accountApproveResponse);
- var worker1Balance = await web3Provider.eth.getBalance(constants.workerAccount1);
- logger.debug("\nconstants.workerAccount1.balance: ", worker1Balance);
-
- const PayObject = new PayKlass({
- airdrop_contract_address: constants.airdropOstUsdAddress,
- chain_id: constants.chainId,
- sender_worker_address: constants.workerAccount1,
- sender_worker_passphrase: constants.workerAccountPassphrase1,
- beneficiary_address: beneficiary,
- transfer_amount: transferAmount.toString(10),
- commission_beneficiary_address: commissionBeneficiary,
- commission_amount: commissionAmount.toString(10),
- currency: currency,
- intended_price_point: intendedPricePoint,
- spender: spenderAddress,
- gas_price: constants.gasUsed,
- options: constants.optionsReceipt
- });
- const payResponse = await PayObject.perform();
-
- assert.equal(payResponse.isSuccess(), true);
- logger.debug("============airdrop.pay response=============");
- logger.debug(payResponse);
-
- // verify if the transaction receipt is valid
- utils.verifyTransactionReceipt(payResponse);
- // verify if the transaction is actually mined
- await utils.verifyIfMined(airdropOstUsd, payResponse.data.transaction_hash);
-
-
- // checks for account balance cache and DB consistency
- logger.debug("============ Validating consistency for account balance form cache and contract after pay =============");
- const balanceFromContract = await getBalanceFromContract(TC5, address);
- const balancesFromCache = await getBalanceFromCache(brandedTokenObject, address);
- validateContractAndCacheBalance(balanceFromContract, balancesFromCache);
- //check if the transfer was propre
- validateTransferSuccess(
- estimatedTokenAmount,
- estimatedCommissionTokenAmount,
- estimatedAirdropUsed,
- spenderAddress,
- beneficiary,
- commissionBeneficiary,
- airdropBudgetHolder,
- initalBalancesFromContract,
- balanceFromContract);
-
- // checks for airdrop balance cache and DB consistency
- logger.debug("============ Validating consistency for airdrop balance form cache and DB after pay =============");
- const airdropBalanceFromDB = await getUserAirdropBalanceFromDB(constants.airdropOstUsdAddress, airdropUserAddress);
- const airdropBalanceFromCache = await getUserAirdropBalanceFromCache(constants.airdropOstUsdAddress, airdropUserAddress);
- validateDBandCacheAirdropBalances(airdropBalanceFromDB.data, airdropBalanceFromCache.data);
- // validate if the airdrop transfer was proper
- validateAirdropTransferSuccess(
- spenderAddress,
- initialAirdropBalanceFromDB,
- airdropBalanceFromDB,
- estimatedAirdropUsed);
-
- });
-
-
-});
\ No newline at end of file
diff --git a/mocha_test/services/pricer/accepted_margins.js b/mocha_test/services/pricer/accepted_margins.js
deleted file mode 100644
index a17cc36..0000000
--- a/mocha_test/services/pricer/accepted_margins.js
+++ /dev/null
@@ -1,114 +0,0 @@
-/* global describe, it */
-
-const chai = require('chai')
- , assert = chai.assert;
-
-const rootPrefix = "../../.."
- , constants = require(rootPrefix + '/mocha_test/lib/constants')
- , utils = require(rootPrefix+'/mocha_test/lib/utils')
- , pricer = require(rootPrefix + '/lib/contract_interact/pricer')
- , pricerOstUsd = new pricer(constants.pricerOstUsdAddress, constants.chainId)
-;
-
-
-describe('Get accepted margins', function() {
-
- it('should pass the initial address checks', function() {
-
- assert.isDefined(constants.deployer);
- assert.isDefined(constants.ops);
- assert.isDefined(constants.account1);
- assert.notEqual(constants.deployer, constants.ops);
- assert.notEqual(constants.deployer, constants.account1);
- assert.notEqual(constants.ops, constants.account1);
-
- });
-
- it('should return 0 when margin was not set for given currency', async function() {
- // eslint-disable-next-line no-invalid-this
- this.timeout(100000);
-
- const amResult = await pricerOstUsd.acceptedMargins("ABC");
- assert.equal(amResult.isSuccess(), true);
- assert.equal(0, amResult.data.acceptedMargins);
-
- });
-
- it('should return error when margin when currency is blank', async function() {
- // eslint-disable-next-line no-invalid-this
- this.timeout(100000);
-
- const amResult = await pricerOstUsd.acceptedMargins(constants.currencyBlank);
- assert.equal(amResult.isFailure(), true);
-
- });
-
- it('should return the accepted margin as 50, 100 and 300', async function() {
- // eslint-disable-next-line no-invalid-this
- this.timeout(100000);
-
- // set the accepted margin to 50
- const response1 = await pricerOstUsd.setAcceptedMargin(
- constants.ops,
- constants.opsPassphrase,
- constants.currencyUSD,
- 50,
- constants.gasUsed,
- constants.optionsReceipt);
-
- // verify if the transaction receipt is valid
- utils.verifyTransactionReceipt(response1);
-
- // verify if the transaction has was actually mined
- await utils.verifyIfMined(pricerOstUsd, response1.data.transaction_hash);
-
- // verify if the accepted margin is set to 50
- const amResult1 = await pricerOstUsd.acceptedMargins(constants.currencyUSD);
- assert.equal(amResult1.isSuccess(), true);
- assert.equal(50, amResult1.data.acceptedMargins);
-
- // set the accepted margin to 300
- const response2 = await pricerOstUsd.setAcceptedMargin(
- constants.ops,
- constants.opsPassphrase,
- constants.currencyUSD,
- 300,
- constants.gasUsed,
- constants.optionsReceipt);
-
- // verify if the transaction receipt is valid
- utils.verifyTransactionReceipt(response2);
-
- // verify if the transaction has was actually mined
- await utils.verifyIfMined(pricerOstUsd, response2.data.transaction_hash);
-
- // verify if the accepted margin is set to 300
- const amResult2 = await pricerOstUsd.acceptedMargins(constants.currencyUSD);
- assert.equal(amResult2.isSuccess(), true);
- assert.equal(300, amResult2.data.acceptedMargins);
-
- // set the accepted margin to 100
- const response3 = await pricerOstUsd.setAcceptedMargin(
- constants.ops,
- constants.opsPassphrase,
- constants.currencyEUR,
- 100,
- constants.gasUsed,
- constants.optionsReceipt);
-
- // verify if the transaction receipt is valid
- utils.verifyTransactionReceipt(response3);
-
- // verify if the transaction has was actually mined
- await utils.verifyIfMined(pricerOstUsd, response3.data.transaction_hash);
-
- // verify if the accepted margin is set to 100
- const amResult3 = await pricerOstUsd.acceptedMargins(constants.currencyEUR);
- assert.equal(amResult3.isSuccess(), true);
- assert.equal(100, amResult3.data.acceptedMargins);
-
- });
-
-});
-
-
diff --git a/mocha_test/services/pricer/base_currency.js b/mocha_test/services/pricer/base_currency.js
deleted file mode 100644
index 04b61b4..0000000
--- a/mocha_test/services/pricer/base_currency.js
+++ /dev/null
@@ -1,33 +0,0 @@
-
-/* global describe, it */
-
-const chai = require('chai')
- , assert = chai.assert;
-
-const rootPrefix = "../../.."
- , constants = require(rootPrefix + '/mocha_test/lib/constants')
- , pricer = require(rootPrefix + '/lib/contract_interact/pricer')
- , pricerOstUsd = new pricer(constants.pricerOstUsdAddress, constants.chainId)
- , pricerOstEur = new pricer(constants.pricerOstEurAddress, constants.chainId)
- , pricerOstUsd10Decimal = new pricer(constants.pricerOstUsd10DecimalAddress, constants.chainId)
-;
-
-describe('Get base currency', function() {
-
- it('should return correct base currency (OST)', async function() {
-
- const pricerOstUsdResult = await pricerOstUsd.baseCurrency();
- assert.equal(pricerOstUsdResult.isSuccess(), true);
- assert.equal(pricerOstUsdResult.data.symbol, 'OST');
-
- const pricerOstEurResult = await pricerOstEur.baseCurrency();
- assert.equal(pricerOstEurResult.isSuccess(), true);
- assert.equal(pricerOstEurResult.data.symbol, 'OST');
-
- const pricerOstUsd10Result = await pricerOstUsd10Decimal.baseCurrency();
- assert.equal(pricerOstUsd10Result.isSuccess(), true);
- assert.equal(pricerOstUsd10Result.data.symbol, 'OST');
-
- });
-
-});
diff --git a/mocha_test/services/pricer/branded_token.js b/mocha_test/services/pricer/branded_token.js
deleted file mode 100644
index 4c27b2e..0000000
--- a/mocha_test/services/pricer/branded_token.js
+++ /dev/null
@@ -1,34 +0,0 @@
-
-/* global describe, it */
-
-const chai = require('chai')
- , assert = chai.assert;
-
-const rootPrefix = "../../.."
- , constants = require(rootPrefix + '/mocha_test/lib/constants')
- , pricer = require(rootPrefix + '/lib/contract_interact/pricer')
- , pricerOstUsd = new pricer(constants.pricerOstUsdAddress, constants.chainId)
- , pricerOstEur = new pricer(constants.pricerOstEurAddress, constants.chainId)
- , pricerOstUsd10Decimal = new pricer(constants.pricerOstUsd10DecimalAddress, constants.chainId)
-;
-
-describe('Get branded token', function() {
-
- it('should return correct branded token', async function() {
-
- const pricerOstUsdResult = await pricerOstUsd.brandedToken();
- assert.equal(pricerOstUsdResult.isSuccess(), true);
- assert.equal(pricerOstUsdResult.data.brandedToken, constants.TC5Address);
-
- const pricerOstEurResult = await pricerOstEur.brandedToken();
- assert.equal(pricerOstEurResult.isSuccess(), true);
- assert.equal(pricerOstEurResult.data.brandedToken, constants.TC2Address);
-
- const pricerOstUsd10Result = await pricerOstUsd10Decimal.brandedToken();
- assert.equal(pricerOstUsd10Result.isSuccess(), true);
- assert.equal(pricerOstUsd10Result.data.brandedToken, constants.TC3Address);
-
- });
-
-});
-
diff --git a/mocha_test/services/pricer/conversion_rate.js b/mocha_test/services/pricer/conversion_rate.js
deleted file mode 100644
index 547608c..0000000
--- a/mocha_test/services/pricer/conversion_rate.js
+++ /dev/null
@@ -1,49 +0,0 @@
-
-/* global describe, it */
-
-const chai = require('chai')
- , assert = chai.assert;
-
-const rootPrefix = "../../.."
- , constants = require(rootPrefix + '/mocha_test/lib/constants')
- , pricer = require(rootPrefix + '/lib/contract_interact/pricer')
- , pricerOstUsd = new pricer(constants.pricerOstUsdAddress, constants.chainId)
- , pricerOstEur = new pricer(constants.pricerOstEurAddress, constants.chainId)
- , pricerOstUsd10Decimal = new pricer(constants.pricerOstUsd10DecimalAddress, constants.chainId)
-;
-
-describe('Get conversion rate', function() {
-
- it('should return correct conversion rate decimals', async function() {
-
- const pricerOstUsdResult = await pricerOstUsd.conversionRateDecimals();
- assert.equal(pricerOstUsdResult.isSuccess(), true);
- assert.equal(pricerOstUsdResult.data.conversionRateDecimals, 5);
-
- const pricerOstEurResult = await pricerOstEur.conversionRateDecimals();
- assert.equal(pricerOstEurResult.isSuccess(), true);
- assert.equal(pricerOstEurResult.data.conversionRateDecimals, 5);
-
- const pricerOstUsd10Result = await pricerOstUsd10Decimal.conversionRateDecimals();
- assert.equal(pricerOstUsd10Result.isSuccess(), true);
- assert.equal(pricerOstUsd10Result.data.conversionRateDecimals, 5);
-
- });
-
- it('should return correct conversion rate', async function() {
-
- const pricerOstUsdResult = await pricerOstUsd.conversionRate();
- assert.equal(pricerOstUsdResult.isSuccess(), true);
- assert.equal(pricerOstUsdResult.data.conversionRate, 5 * (10**5));
-
- const pricerOstEurResult = await pricerOstEur.conversionRate();
- assert.equal(pricerOstEurResult.isSuccess(), true);
- assert.equal(pricerOstEurResult.data.conversionRate, 2 * (10**5));
-
- const pricerOstUsd10Result = await pricerOstUsd10Decimal.conversionRate();
- assert.equal(pricerOstUsd10Result.isSuccess(), true);
- assert.equal(pricerOstUsd10Result.data.conversionRate, 3 * (10**5));
-
- });
-
-});
diff --git a/mocha_test/services/pricer/decimals.js b/mocha_test/services/pricer/decimals.js
deleted file mode 100644
index 3017d84..0000000
--- a/mocha_test/services/pricer/decimals.js
+++ /dev/null
@@ -1,33 +0,0 @@
-
-/* global describe, it */
-
-const chai = require('chai')
- , assert = chai.assert;
-
-const rootPrefix = "../../.."
- , constants = require(rootPrefix + '/mocha_test/lib/constants')
- , pricer = require(rootPrefix + '/lib/contract_interact/pricer')
- , pricerOstUsd = new pricer(constants.pricerOstUsdAddress, constants.chainId)
- , pricerOstEur = new pricer(constants.pricerOstEurAddress, constants.chainId)
- , pricerOstUsd10Decimal = new pricer(constants.pricerOstUsd10DecimalAddress, constants.chainId)
-;
-
-describe('Get decimals', function() {
-
- it('should return correct decimals', async function() {
-
- const pricerOstUsdResult = await pricerOstUsd.decimals();
- assert.equal(pricerOstUsdResult.isSuccess(), true);
- assert.equal(pricerOstUsdResult.data.decimals, 18);
-
- const pricerOstEurResult = await pricerOstEur.decimals();
- assert.equal(pricerOstEurResult.isSuccess(), true);
- assert.equal(pricerOstEurResult.data.decimals, 18);
-
- const pricerOstUsd10Result = await pricerOstUsd10Decimal.decimals();
- assert.equal(pricerOstUsd10Result.isSuccess(), true);
- assert.equal(pricerOstUsd10Result.data.decimals, 10);
-
- });
-
-});
diff --git a/mocha_test/services/pricer/get_price_point.js b/mocha_test/services/pricer/get_price_point.js
deleted file mode 100644
index a52c8a9..0000000
--- a/mocha_test/services/pricer/get_price_point.js
+++ /dev/null
@@ -1,133 +0,0 @@
-
-/* global describe, it */
-
-const chai = require('chai')
- , assert = chai.assert;
-
-const rootPrefix = "../../.."
- , constants = require(rootPrefix + '/mocha_test/lib/constants')
- , utils = require(rootPrefix+'/mocha_test/lib/utils')
- , pricer = require(rootPrefix + '/lib/contract_interact/pricer')
- , pricerOstUsd = new pricer(constants.pricerOstUsdAddress, constants.chainId)
-;
-
-describe('Get price point', function() {
-
- it('should pass the initial address checks', function() {
-
- assert.isDefined(constants.deployer);
- assert.isDefined(constants.ops);
- assert.isDefined(constants.account1);
- assert.notEqual(constants.deployer, constants.ops);
- assert.notEqual(constants.deployer, constants.account1);
- assert.notEqual(constants.ops, constants.account1);
-
- });
-
- it('should get failure when currency is blank', async function() {
- // eslint-disable-next-line no-invalid-this
- this.timeout(100000);
- const pricePoint = await pricerOstUsd.getPricePoint(constants.currencyINR);
- assert.equal(pricePoint.isFailure(), true);
-
- });
-
-
- it('should get failure when currency is does not exists in system', async function() {
- // eslint-disable-next-line no-invalid-this
- this.timeout(100000);
- const pricePoint = await pricerOstUsd.getPricePoint("ABC");
- assert.equal(pricePoint.isFailure(), true);
-
- });
-
-
- it('should get correct price oracle address after set', async function() {
- // eslint-disable-next-line no-invalid-this
- this.timeout(100000);
-
- // set price oracle 1
- const response = await pricerOstUsd.setPriceOracle(
- constants.ops,
- constants.opsPassphrase,
- constants.currencyEUR,
- constants.priceOracles.OST.EUR,
- constants.gasUsed,
- constants.optionsReceipt);
-
- // verify if the transaction receipt is valid
- utils.verifyTransactionReceipt(response);
-
- // verify if the transaction has was actually mined
- await utils.verifyIfMined(pricerOstUsd, response.data.transaction_hash);
-
- // verify if its set
- const poResult = await pricerOstUsd.priceOracles(constants.currencyEUR);
- assert.equal(poResult.isSuccess(), true);
- assert.equal(poResult.data.priceOracles, constants.priceOracles.OST.EUR);
-
-
- // set price oracle 2
- const response2 = await pricerOstUsd.setPriceOracle(
- constants.ops,
- constants.opsPassphrase,
- constants.currencyUSD,
- constants.priceOracles.OST.USD,
- constants.gasUsed,
- constants.optionsReceipt);
-
- // verify if the transaction receipt is valid
- utils.verifyTransactionReceipt(response2);
-
- // verify if the transaction has was actually mined
- await utils.verifyIfMined(pricerOstUsd, response2.data.transaction_hash);
-
- const poResult2 = await pricerOstUsd.priceOracles(constants.currencyUSD);
- assert.equal(poResult2.isSuccess(), true);
- assert.equal(poResult2.data.priceOracles, constants.priceOracles.OST.USD);
-
- const pricePoint1 = await pricerOstUsd.getPricePoint(constants.currencyUSD);
- assert.equal(pricePoint1.isSuccess(), true);
- assert.equal(pricePoint1.data.pricePoint, pricerOstUsd.toWei('0.5'));
-
- const pricePoint2 = await pricerOstUsd.getPricePoint(constants.currencyEUR);
- assert.equal(pricePoint2.isSuccess(), true);
- assert.equal(pricePoint2.data.pricePoint, pricerOstUsd.toWei('0.2'));
-
- });
-
-
- it('should get correct price oracle address after unset', async function() {
- // eslint-disable-next-line no-invalid-this
- this.timeout(100000);
-
- // unset price oracle
- const response = await pricerOstUsd.unsetPriceOracle(
- constants.ops,
- constants.opsPassphrase,
- constants.currencyUSD,
- constants.gasUsed,
- constants.optionsReceipt);
-
- // verify if the transaction receipt is valid
- utils.verifyTransactionReceipt(response);
-
- // verify if the transaction has was actually mined
- await utils.verifyIfMined(pricerOstUsd, response.data.transaction_hash);
-
- const poResult = await pricerOstUsd.priceOracles(constants.currencyUSD);
- assert.equal(poResult.isSuccess(), true);
- assert.equal(poResult.data.priceOracles, 0x0);
-
- const pricePoint1 = await pricerOstUsd.getPricePoint(constants.currencyUSD);
- assert.equal(pricePoint1.isFailure(), true);
-
- // price point for OST/EUR will remain the same
- const pricePoint2 = await pricerOstUsd.getPricePoint(constants.currencyEUR);
- assert.equal(pricePoint2.isSuccess(), true);
- assert.equal(pricePoint2.data.pricePoint, pricerOstUsd.toWei('0.2'));
-
- });
-
-});
-
diff --git a/mocha_test/services/pricer/get_pricepoint_and_calculated_amounts.js b/mocha_test/services/pricer/get_pricepoint_and_calculated_amounts.js
deleted file mode 100644
index a1565a6..0000000
--- a/mocha_test/services/pricer/get_pricepoint_and_calculated_amounts.js
+++ /dev/null
@@ -1,170 +0,0 @@
-
-/* global describe, it */
-
-const chai = require('chai')
- , assert = chai.assert;
-
-const rootPrefix = "../../.."
- , constants = require(rootPrefix + '/mocha_test/lib/constants')
- , utils = require(rootPrefix+'/mocha_test/lib/utils')
- , pricer = require(rootPrefix + '/lib/contract_interact/pricer')
- , pricerOstUsd = new pricer(constants.pricerOstUsdAddress, constants.chainId)
- , pricerOstEur = new pricer(constants.pricerOstEurAddress, constants.chainId)
-;
-
-
-describe('Get price point and calculated amounts', function() {
-
- it('should pass the initial address checks', async function() {
- // eslint-disable-next-line no-invalid-this
- this.timeout(100000);
-
- assert.isDefined(constants.deployer);
- assert.isDefined(constants.ops);
- assert.isDefined(constants.account1);
- assert.notEqual(constants.deployer, constants.ops);
- assert.notEqual(constants.deployer, constants.account1);
- assert.notEqual(constants.ops, constants.account1);
-
- // set price oracle
- const response1 = await pricerOstUsd.setPriceOracle(
- constants.ops,
- constants.opsPassphrase,
- constants.currencyUSD,
- constants.priceOracles.OST.USD,
- constants.gasUsed,
- constants.optionsReceipt);
-
- // verify if the transaction receipt is valid
- utils.verifyTransactionReceipt(response1);
-
- // verify if the transaction has was actually mined
- await utils.verifyIfMined(pricerOstUsd, response1.data.transaction_hash);
-
- // verify if its set
- const poResult1 = await pricerOstUsd.priceOracles(constants.currencyUSD);
- assert.equal(poResult1.isSuccess(), true);
- assert.equal(constants.priceOracles.OST.USD, poResult1.data.priceOracles);
-
- // set price oracle
- const response2 = await pricerOstEur.setPriceOracle(
- constants.ops,
- constants.opsPassphrase,
- constants.currencyEUR,
- constants.priceOracles.OST.EUR,
- constants.gasUsed,
- constants.optionsReceipt);
-
- // verify if the transaction receipt is valid
- utils.verifyTransactionReceipt(response2);
-
- // verify if the transaction has was actually mined
- await utils.verifyIfMined(pricerOstEur, response1.data.transaction_hash);
-
- // verify if its set
- const poResult2 = await pricerOstEur.priceOracles(constants.currencyEUR);
- assert.equal(poResult2.isSuccess(), true);
- assert.equal(constants.priceOracles.OST.EUR, poResult2.data.priceOracles);
-
- });
-
-
- it('should fail when currency is 0', async function() {
-
- const response = await pricerOstUsd.getPricePointAndCalculatedAmounts(
- pricerOstUsd.toWei('1'),
- pricerOstUsd.toWei('0.5'),
- constants.currencyBlank);
- assert.equal(response.isFailure(), true);
-
- });
-
- it('should fail when price point is 0', async function() {
-
- const response = await pricerOstUsd.getPricePointAndCalculatedAmounts(
- pricerOstUsd.toWei('1'),
- pricerOstUsd.toWei('0.5'),
- constants.currencyINR);
- assert.equal(response.isFailure(), true);
-
- });
-
-
- it('should pass when all parameters are valid and conversion rate is 5', async function() {
-
- const pricePointData = await pricerOstUsd.getPricePoint(constants.currencyUSD);
- assert.equal(pricePointData.isSuccess(), true);
- const pricePoint = pricePointData.data.pricePoint;
-
- const decimalData = await pricerOstUsd.decimals();
- assert.equal(decimalData.isSuccess(), true);
- const decimal = decimalData.data.decimals;
-
- const conversionRateData = await pricerOstUsd.conversionRate();
- assert.equal(conversionRateData.isSuccess(), true);
-
- const conversionRateDecimalsData = await pricerOstUsd.conversionRateDecimals();
- assert.equal(conversionRateDecimalsData.isSuccess(), true);
-
- const conversionRate = conversionRateData.data.conversionRate;
- const conversionRateDecimals = conversionRateDecimalsData.data.conversionRateDecimals;
-
- const conversionFactor = conversionRate/(10**conversionRateDecimals);
-
- const amount = pricerOstUsd.toWei('1')
- , commissionAmount = pricerOstUsd.toWei('0.5')
- , calculatedAmount = (amount*conversionFactor*(10**decimal))/pricePoint
- , calculatedCommisionAmount = (commissionAmount*conversionFactor*(10**decimal))/pricePoint;
-
- const result = await pricerOstUsd.getPricePointAndCalculatedAmounts(
- amount,
- commissionAmount,
- constants.currencyUSD);
- assert.equal(result.isSuccess(), true);
-
- assert.equal(result.data.pricePoint, pricePoint);
- assert.equal(result.data.tokenAmount, calculatedAmount);
- assert.equal(result.data.commissionTokenAmount, calculatedCommisionAmount);
-
- });
-
-
- it('should pass when all parameters are valid and conversion rate is 2', async function() {
-
- const pricePointData = await pricerOstEur.getPricePoint(constants.currencyEUR);
- assert.equal(pricePointData.isSuccess(), true);
- const pricePoint = pricePointData.data.pricePoint;
-
- const decimalData = await pricerOstEur.decimals();
- assert.equal(decimalData.isSuccess(), true);
- const decimal = decimalData.data.decimals;
-
- const conversionRateData = await pricerOstEur.conversionRate();
- assert.equal(conversionRateData.isSuccess(), true);
-
- const conversionRateDecimalsData = await pricerOstEur.conversionRateDecimals();
- assert.equal(conversionRateDecimalsData.isSuccess(), true);
-
- const conversionRate = conversionRateData.data.conversionRate;
- const conversionRateDecimals = conversionRateDecimalsData.data.conversionRateDecimals;
-
- const conversionFactor = conversionRate/(10**conversionRateDecimals);
-
- const amount = pricerOstEur.toWei('1')
- , commissionAmount = pricerOstEur.toWei('0.5')
- , calculatedAmount = (amount*conversionFactor*(10**decimal))/pricePoint
- , calculatedCommisionAmount = (commissionAmount*conversionFactor*(10**decimal))/pricePoint;
-
- const result = await pricerOstEur.getPricePointAndCalculatedAmounts(
- amount,
- commissionAmount,
- constants.currencyEUR);
- assert.equal(result.isSuccess(), true);
-
- assert.equal(result.data.pricePoint, pricePoint);
- assert.equal(result.data.tokenAmount, calculatedAmount);
- assert.equal(result.data.commissionTokenAmount, calculatedCommisionAmount);
-
- });
-
-});
diff --git a/mocha_test/services/pricer/pay.js b/mocha_test/services/pricer/pay.js
deleted file mode 100644
index 84c54e2..0000000
--- a/mocha_test/services/pricer/pay.js
+++ /dev/null
@@ -1,1366 +0,0 @@
-/* global describe, it */
-
-const chai = require('chai')
- , assert = chai.assert;
-
-const rootPrefix = "../../.."
- , constants = require(rootPrefix + '/mocha_test/lib/constants')
- , BigNumber = require('bignumber.js')
- , utils = require(rootPrefix+'/mocha_test/lib/utils')
- , pricer = require(rootPrefix + '/lib/contract_interact/pricer')
- , pricerOstUsd = new pricer(constants.pricerOstUsdAddress, constants.chainId)
- , pricerOstEur = new pricer(constants.pricerOstEurAddress, constants.chainId)
- , mockToken = require(rootPrefix + '/lib/contract_interact/EIP20TokenMock')
- , TC5 = new mockToken(constants.TC5Address)
- , BrandedTokenKlass = require(rootPrefix + '/lib/contract_interact/branded_token')
- , brandedTokenObj = new BrandedTokenKlass(constants.TC5Address, constants.chainId)
-;
-
-async function getAmountFromCache(address) {
-
- const resp = await brandedTokenObj.getBalanceOf(address);
-
- return new BigNumber(resp.data.balance);
-}
-
-describe('Pay', function() {
-
- it('should pass the initial checks', async function() {
- // eslint-disable-next-line no-invalid-this
- this.timeout(300000);
-
- assert.isDefined(constants.deployer);
- assert.isDefined(constants.ops);
- assert.isDefined(constants.account1);
- assert.notEqual(constants.deployer, constants.ops);
- assert.notEqual(constants.deployer, constants.account1);
- assert.notEqual(constants.ops, constants.account1);
-
- // set accepted margin
- const amResponse = await pricerOstUsd.setAcceptedMargin(
- constants.ops,
- constants.opsPassphrase,
- constants.currencyUSD,
- 50,
- constants.gasUsed,
- constants.optionsReceipt);
-
- // verify if the transaction receipt is valid
- utils.verifyTransactionReceipt(amResponse);
-
- // verify if the transaction has was actually mined
- await utils.verifyIfMined(pricerOstUsd, amResponse.data.transaction_hash);
-
- // verify if its set
- const amResult = await pricerOstUsd.acceptedMargins(constants.currencyUSD);
- assert.equal(amResult.isSuccess(), true);
- assert.equal(50, amResult.data.acceptedMargins);
-
- // set price oracle
- const spoResponse = await pricerOstUsd.setPriceOracle(
- constants.ops,
- constants.opsPassphrase,
- constants.currencyUSD,
- constants.priceOracles.OST.USD,
- constants.gasUsed,
- constants.optionsReceipt);
-
- // verify if the transaction receipt is valid
- utils.verifyTransactionReceipt(spoResponse);
-
- // verify if the transaction has was actually mined
- await utils.verifyIfMined(pricerOstUsd, spoResponse.data.transaction_hash);
-
- // verify if its set
- const poResult = await pricerOstUsd.priceOracles(constants.currencyUSD);
- assert.equal(poResult.isSuccess(), true);
- assert.equal(constants.priceOracles.OST.USD, poResult.data.priceOracles);
- const setBalResp = await TC5.setBalance(
- constants.ops,
- constants.opsPassphrase,
- constants.account1,
- pricerOstUsd.toWei('1000'),
- constants.gasUsed);
-
- const account1Balance = await TC5.balanceOf(constants.account1);
- assert.equal(account1Balance, pricerOstUsd.toWei('1000'));
-
- await TC5.setBalance(
- constants.ops,
- constants.opsPassphrase,
- constants.account2,
- pricerOstUsd.toWei('0'),
- constants.gasUsed);
-
- const account2Balance = await TC5.balanceOf(constants.account2);
- assert.equal(account2Balance, pricerOstUsd.toWei('0'));
-
- await TC5.setBalance(
- constants.ops,
- constants.opsPassphrase,
- constants.account3,
- pricerOstUsd.toWei('0'),
- constants.gasUsed);
-
- const account3Balance = await TC5.balanceOf(constants.account3);
- assert.equal(account3Balance, pricerOstUsd.toWei('0'));
-
- await TC5.setBalance(
- constants.ops,
- constants.opsPassphrase,
- constants.account4,
- pricerOstUsd.toWei('0'),
- constants.gasUsed);
-
- const account4Balance = await TC5.balanceOf(constants.account4);
- assert.equal(account4Balance, pricerOstUsd.toWei('0'));
-
- // populate cache
- const brandedToken = new BrandedTokenKlass(constants.TC5Address, constants.chainId);
- brandedToken.getBalanceOf(constants.account1);
- brandedToken.getBalanceOf(constants.account2);
- brandedToken.getBalanceOf(constants.account3);
- brandedToken.getBalanceOf(constants.account4);
-
- });
-
- it('should pass when all parameters are valid', async function() {
- // eslint-disable-next-line no-invalid-this
- this.timeout(100000);
-
- const initialAccount1Balance = new BigNumber(await TC5.balanceOf(constants.account1))
- , initialAccount3Balance = new BigNumber(await TC5.balanceOf(constants.account3))
- , initialAccount4Balance = new BigNumber(await TC5.balanceOf(constants.account4));
-
- // Cache check
- const initialAccount1BalanceCache = await getAmountFromCache(constants.account1)
- , initialAccount3BalanceCache = await getAmountFromCache(constants.account3)
- , initialAccount4BalanceCache = await getAmountFromCache(constants.account4);
-
- assert.equal(initialAccount1Balance.toNumber(), initialAccount1BalanceCache.toNumber(), "account1: Actual and cacheValue mismatch");
- assert.equal(initialAccount3Balance.toNumber(), initialAccount3BalanceCache.toNumber(), "account3: Actual and cacheValue mismatch");
- assert.equal(initialAccount4Balance.toNumber(), initialAccount4BalanceCache.toNumber(), "account4: Actual and cacheValue mismatch");
-
- const beneficiary = constants.account3
- , commissionAmount = new BigNumber(pricerOstUsd.toWei('2'))
- , commissionBeneficiary = constants.account4
- , currency = constants.currencyUSD
- , transferAmount = new BigNumber(pricerOstUsd.toWei('7'))
- ;
-
- const acceptedMarginData = await pricerOstUsd.acceptedMargins(currency);
- assert.equal(acceptedMarginData.isSuccess(), true);
-
- const estimatedValues = await pricerOstUsd.getPricePointAndCalculatedAmounts(
- transferAmount,
- commissionAmount,
- currency);
-
- assert.equal(estimatedValues.isSuccess(), true);
-
- const estimatedTokenAmount = new BigNumber(estimatedValues.data.tokenAmount);
- const estimatedCommissionTokenAmount = new BigNumber(estimatedValues.data.commissionTokenAmount);
-
- const intendedPricePoint = estimatedValues.data.pricePoint;
-
- const estimatedTotalAmount = new BigNumber(0).plus(estimatedTokenAmount).plus(estimatedCommissionTokenAmount);
-
- await TC5.approve(
- constants.account1,
- constants.accountPassphrase1,
- constants.pricerOstUsdAddress,
- estimatedTotalAmount,
- constants.gasUsed);
-
- const payResponse = await pricerOstUsd.pay(
- constants.account1,
- constants.accountPassphrase1,
- beneficiary,
- transferAmount,
- commissionBeneficiary,
- commissionAmount,
- currency,
- intendedPricePoint,
- constants.gasUsed,
- constants.optionsReceipt);
-
- // verify if the transaction receipt is valid
- utils.verifyTransactionReceipt(payResponse);
-
- // verify if the transaction has was actually mined
- await utils.verifyIfMined(pricerOstUsd, payResponse.data.transaction_hash);
-
- const account1Balance = new BigNumber(await TC5.balanceOf(constants.account1))
- , account3Balance = new BigNumber(await TC5.balanceOf(constants.account3))
- , account4Balance = new BigNumber(await TC5.balanceOf(constants.account4));
-
- assert.equal(
- new BigNumber(0).plus(initialAccount1Balance)
- .minus(estimatedTokenAmount)
- .minus(estimatedCommissionTokenAmount)
- .toNumber(), account1Balance.toNumber());
-
- assert.equal(
- new BigNumber(0).plus(initialAccount3Balance)
- .plus(estimatedTokenAmount)
- .toNumber(), account3Balance.toNumber());
-
- assert.equal(
- new BigNumber(0).plus(initialAccount4Balance)
- .plus(estimatedCommissionTokenAmount)
- .toNumber(), account4Balance.toNumber());
-
- // Cache check
- const finalAccount1BalanceCache = await getAmountFromCache(constants.account1)
- , finalAccount3BalanceCache = await getAmountFromCache(constants.account3)
- , finalAccount4BalanceCache = await getAmountFromCache(constants.account4);
-
- assert.equal(account1Balance.toNumber(), finalAccount1BalanceCache.toNumber(), "account1: Actual and cacheValue mismatch after test");
- assert.equal(account3Balance.toNumber(), finalAccount3BalanceCache.toNumber(), "account3: Actual and cacheValue mismatch after test");
- assert.equal(account4Balance.toNumber(), finalAccount4BalanceCache.toNumber(), "account4: Actual and cacheValue mismatch after test");
-
- });
-
-
- it('should fail when sender balance is less than the amount being transfered', async function() {
- // eslint-disable-next-line no-invalid-this
- this.timeout(100000);
-
- const initialAccount1Balance = new BigNumber(await TC5.balanceOf(constants.account1))
- , initialAccount3Balance = new BigNumber(await TC5.balanceOf(constants.account3))
- , initialAccount4Balance = new BigNumber(await TC5.balanceOf(constants.account4));
-
- const initialAccount1BalanceCache = await getAmountFromCache(constants.account1)
- , initialAccount3BalanceCache = await getAmountFromCache(constants.account3)
- , initialAccount4BalanceCache = await getAmountFromCache(constants.account4)
- ;
-
- assert.equal(initialAccount1Balance.toNumber(), initialAccount1BalanceCache.toNumber(), "account1: Actual and cacheValue mismatch");
- assert.equal(initialAccount3Balance.toNumber(), initialAccount3BalanceCache.toNumber(), "account3: Actual and cacheValue mismatch");
- assert.equal(initialAccount4Balance.toNumber(), initialAccount4BalanceCache.toNumber(), "account4: Actual and cacheValue mismatch");
-
- const beneficiary = constants.account3
- , commissionAmount = new BigNumber(pricerOstUsd.toWei('100000'))
- , commissionBeneficiary = constants.account4
- , currency = constants.currencyUSD
- , transferAmount = new BigNumber(pricerOstUsd.toWei('5000'))
- ;
-
- const acceptedMarginData = await pricerOstUsd.acceptedMargins(currency);
- assert.equal(acceptedMarginData.isSuccess(), true);
-
- const estimatedValues = await pricerOstUsd.getPricePointAndCalculatedAmounts(
- transferAmount,
- commissionAmount,
- currency);
- assert.equal(estimatedValues.isSuccess(), true);
-
- const estimatedTokenAmount = new BigNumber(estimatedValues.data.tokenAmount);
- const estimatedCommissionTokenAmount = new BigNumber(estimatedValues.data.commissionTokenAmount);
- const intendedPricePoint = estimatedValues.data.pricePoint;
- const estimatedMargin = new BigNumber(acceptedMarginData.data.acceptedMargins);
-
- const total = estimatedTokenAmount.plus(estimatedCommissionTokenAmount).plus(estimatedMargin);
-
- await TC5.approve(
- constants.account1,
- constants.accountPassphrase1,
- constants.pricerOstUsdAddress,
- total,
- constants.gasUsed);
-
- const payResponse = await pricerOstUsd.pay(
- constants.account1,
- constants.accountPassphrase1,
- beneficiary,
- transferAmount,
- commissionBeneficiary,
- commissionAmount,
- currency,
- intendedPricePoint,
- constants.gasUsed,
- constants.optionsReceipt);
-
- assert.equal(payResponse.isFailure(), true, "Low balance check");
-
- const account1Balance = new BigNumber(await TC5.balanceOf(constants.account1))
- , account3Balance = new BigNumber(await TC5.balanceOf(constants.account3))
- , account4Balance = new BigNumber(await TC5.balanceOf(constants.account4));
-
- assert.equal(initialAccount1Balance.toNumber(), account1Balance.toNumber());
- assert.equal(initialAccount3Balance.toNumber(), account3Balance.toNumber());
- assert.equal(initialAccount4Balance.toNumber(), account4Balance.toNumber());
-
- // Cache check
- const finalAccount1BalanceCache = await getAmountFromCache(constants.account1)
- , finalAccount3BalanceCache = await getAmountFromCache(constants.account3)
- , finalAccount4BalanceCache = await getAmountFromCache(constants.account4);
-
- assert.equal(account1Balance.toNumber(), finalAccount1BalanceCache.toNumber(), "account1: Actual and cacheValue mismatch after test");
- assert.equal(account3Balance.toNumber(), finalAccount3BalanceCache.toNumber(), "account3: Actual and cacheValue mismatch after test");
- assert.equal(account4Balance.toNumber(), finalAccount4BalanceCache.toNumber(), "account4: Actual and cacheValue mismatch after test");
-
- });
-
-
- it('should fail when sender has approved less amount than the amount being transfered', async function() {
- // eslint-disable-next-line no-invalid-this
- this.timeout(100000);
-
- const initialAccount1Balance = new BigNumber(await TC5.balanceOf(constants.account1))
- , initialAccount3Balance = new BigNumber(await TC5.balanceOf(constants.account3))
- , initialAccount4Balance = new BigNumber(await TC5.balanceOf(constants.account4));
-
- // Cache check
- const initialAccount1BalanceCache = await getAmountFromCache(constants.account1)
- , initialAccount3BalanceCache = await getAmountFromCache(constants.account3)
- , initialAccount4BalanceCache = await getAmountFromCache(constants.account4);
-
- assert.equal(initialAccount1Balance.toNumber(), initialAccount1BalanceCache.toNumber(), "account1: Actual and cacheValue mismatch");
- assert.equal(initialAccount3Balance.toNumber(), initialAccount3BalanceCache.toNumber(), "account3: Actual and cacheValue mismatch");
- assert.equal(initialAccount4Balance.toNumber(), initialAccount4BalanceCache.toNumber(), "account4: Actual and cacheValue mismatch");
-
- const beneficiary = constants.account3
- , commissionAmount = new BigNumber(pricerOstUsd.toWei('5'))
- , commissionBeneficiary = constants.account4
- , currency = constants.currencyUSD
- , transferAmount = new BigNumber(pricerOstUsd.toWei('12'))
- ;
-
- const acceptedMarginData = await pricerOstUsd.acceptedMargins(currency);
- assert.equal(acceptedMarginData.isSuccess(), true);
-
- const estimatedValues = await pricerOstUsd.getPricePointAndCalculatedAmounts(
- transferAmount,
- commissionAmount,
- currency);
- assert.equal(estimatedValues.isSuccess(), true);
-
- const estimatedTokenAmount = new BigNumber(estimatedValues.data.tokenAmount);
- const estimatedCommissionTokenAmount = new BigNumber(estimatedValues.data.commissionTokenAmount);
- const intendedPricePoint = estimatedValues.data.pricePoint;
- const estimatedMargin = new BigNumber(acceptedMarginData.data.acceptedMargins);
-
- const total = estimatedTokenAmount
- .plus(estimatedCommissionTokenAmount)
- .minus(estimatedMargin)
- .minus(new BigNumber(100));
-
- await TC5.approve(
- constants.account1,
- constants.accountPassphrase1,
- constants.pricerOstUsdAddress,
- total,
- constants.gasUsed);
-
- const payResponse = await pricerOstUsd.pay(
- constants.account1,
- constants.accountPassphrase1,
- beneficiary,
- transferAmount,
- commissionBeneficiary,
- commissionAmount,
- currency,
- intendedPricePoint,
- constants.gasUsed,
- constants.optionsReceipt);
-
- assert.equal(payResponse.isFailure(), true);
-
- const account1Balance = new BigNumber(await TC5.balanceOf(constants.account1))
- , account3Balance = new BigNumber(await TC5.balanceOf(constants.account3))
- , account4Balance = new BigNumber(await TC5.balanceOf(constants.account4));
-
- assert.equal(initialAccount1Balance.toNumber(), account1Balance.toNumber());
- assert.equal(initialAccount3Balance.toNumber(), account3Balance.toNumber());
- assert.equal(initialAccount4Balance.toNumber(), account4Balance.toNumber());
-
- // Cache check
- const finalAccount1BalanceCache = await getAmountFromCache(constants.account1)
- , finalAccount3BalanceCache = await getAmountFromCache(constants.account3)
- , finalAccount4BalanceCache = await getAmountFromCache(constants.account4);
-
- assert.equal(account1Balance.toNumber(), finalAccount1BalanceCache.toNumber(), "account1: Actual and cacheValue mismatch after test");
- assert.equal(account3Balance.toNumber(), finalAccount3BalanceCache.toNumber(), "account3: Actual and cacheValue mismatch after test");
- assert.equal(account4Balance.toNumber(), finalAccount4BalanceCache.toNumber(), "account4: Actual and cacheValue mismatch after test");
-
- });
-
-
- it('should fail when beneficiary address is 0', async function() {
- // eslint-disable-next-line no-invalid-this
- this.timeout(100000);
-
- const initialAccount1Balance = new BigNumber(await TC5.balanceOf(constants.account1))
- , initialAccount3Balance = new BigNumber(await TC5.balanceOf(constants.account3))
- , initialAccount4Balance = new BigNumber(await TC5.balanceOf(constants.account4));
-
- // Cache check
- const initialAccount1BalanceCache = await getAmountFromCache(constants.account1)
- , initialAccount3BalanceCache = await getAmountFromCache(constants.account3)
- , initialAccount4BalanceCache = await getAmountFromCache(constants.account4);
-
- assert.equal(initialAccount1Balance.toNumber(), initialAccount1BalanceCache.toNumber(), "account1: Actual and cacheValue mismatch");
- assert.equal(initialAccount3Balance.toNumber(), initialAccount3BalanceCache.toNumber(), "account3: Actual and cacheValue mismatch");
- assert.equal(initialAccount4Balance.toNumber(), initialAccount4BalanceCache.toNumber(), "account4: Actual and cacheValue mismatch");
-
- const beneficiary = 0
- , commissionAmount = new BigNumber(pricerOstUsd.toWei('5'))
- , commissionBeneficiary = constants.account4
- , currency = constants.currencyUSD
- , transferAmount = new BigNumber(pricerOstUsd.toWei('7'))
- ;
-
- const acceptedMarginData = await pricerOstUsd.acceptedMargins(currency);
- assert.equal(acceptedMarginData.isSuccess(), true);
-
- const estimatedValues = await pricerOstUsd.getPricePointAndCalculatedAmounts(
- transferAmount,
- commissionAmount,
- currency);
- assert.equal(estimatedValues.isSuccess(), true);
-
- const estimatedTokenAmount = new BigNumber(estimatedValues.data.tokenAmount);
- const estimatedCommissionTokenAmount = new BigNumber(estimatedValues.data.commissionTokenAmount);
- const estimatedMargin = new BigNumber(acceptedMarginData.data.acceptedMargins);
- const intendedPricePoint = estimatedValues.data.pricePoint;
-
- const total = estimatedTokenAmount
- .plus(estimatedCommissionTokenAmount)
- .plus(estimatedMargin);
-
- await TC5.approve(
- constants.account1,
- constants.accountPassphrase1,
- constants.pricerOstUsdAddress,
- total,
- constants.gasUsed);
-
- const payResponse = await pricerOstUsd.pay(
- constants.account1,
- constants.accountPassphrase1,
- beneficiary,
- transferAmount,
- commissionBeneficiary,
- commissionAmount,
- currency,
- intendedPricePoint,
- constants.gasUsed,
- constants.optionsReceipt);
-
- assert.equal(payResponse.isFailure(), true);
-
- const account1Balance = new BigNumber(await TC5.balanceOf(constants.account1))
- , account3Balance = new BigNumber(await TC5.balanceOf(constants.account3))
- , account4Balance = new BigNumber(await TC5.balanceOf(constants.account4));
-
- assert.equal(initialAccount1Balance.toNumber(), account1Balance.toNumber());
- assert.equal(initialAccount3Balance.toNumber(), account3Balance.toNumber());
- assert.equal(initialAccount4Balance.toNumber(), account4Balance.toNumber());
-
- // Cache check
- const finalAccount1BalanceCache = await getAmountFromCache(constants.account1)
- , finalAccount3BalanceCache = await getAmountFromCache(constants.account3)
- , finalAccount4BalanceCache = await getAmountFromCache(constants.account4)
- ;
-
- assert.equal(account1Balance.toNumber(), finalAccount1BalanceCache.toNumber(), "account1: Actual and cacheValue mismatch after test");
- assert.equal(account3Balance.toNumber(), finalAccount3BalanceCache.toNumber(), "account3: Actual and cacheValue mismatch after test");
- assert.equal(account4Balance.toNumber(), finalAccount4BalanceCache.toNumber(), "account4: Actual and cacheValue mismatch after test");
-
- });
-
-
- it('should fail when currency is not available in pricer', async function() {
- // eslint-disable-next-line no-invalid-this
- this.timeout(100000);
-
- const initialAccount1Balance = new BigNumber(await TC5.balanceOf(constants.account1))
- , initialAccount3Balance = new BigNumber(await TC5.balanceOf(constants.account3))
- , initialAccount4Balance = new BigNumber(await TC5.balanceOf(constants.account4));
-
- // Cache check
- const initialAccount1BalanceCache = await getAmountFromCache(constants.account1)
- , initialAccount3BalanceCache = await getAmountFromCache(constants.account3)
- , initialAccount4BalanceCache = await getAmountFromCache(constants.account4)
- ;
-
- assert.equal(initialAccount1Balance.toNumber(), initialAccount1BalanceCache.toNumber(), "account1: Actual and cacheValue mismatch");
- assert.equal(initialAccount3Balance.toNumber(), initialAccount3BalanceCache.toNumber(), "account3: Actual and cacheValue mismatch");
- assert.equal(initialAccount4Balance.toNumber(), initialAccount4BalanceCache.toNumber(), "account4: Actual and cacheValue mismatch");
-
- const beneficiary = constants.account3
- , commissionAmount = new BigNumber(pricerOstUsd.toWei('10'))
- , commissionBeneficiary = constants.account4
- , currency = constants.currencyUSD
- , transferAmount = new BigNumber(pricerOstUsd.toWei('5'))
- ;
-
- const acceptedMarginData = await pricerOstUsd.acceptedMargins(currency);
- assert.equal(acceptedMarginData.isSuccess(), true);
-
- const estimatedValues = await pricerOstUsd.getPricePointAndCalculatedAmounts(
- transferAmount,
- commissionAmount,
- currency);
- assert.equal(estimatedValues.isSuccess(), true);
-
- const estimatedTokenAmount = new BigNumber(estimatedValues.data.tokenAmount);
- const estimatedCommissionTokenAmount = new BigNumber(estimatedValues.data.commissionTokenAmount);
- const estimatedMargin = new BigNumber(acceptedMarginData.data.acceptedMargins);
- const intendedPricePoint = estimatedValues.data.pricePoint;
-
- const total = estimatedTokenAmount
- .plus(estimatedCommissionTokenAmount)
- .plus(estimatedMargin);
-
- await TC5.approve(
- constants.account1,
- constants.accountPassphrase1,
- constants.pricerOstUsdAddress,
- total,
- constants.gasUsed);
-
- const payResponse = await pricerOstUsd.pay(
- constants.account1,
- constants.accountPassphrase1,
- beneficiary,
- transferAmount,
- commissionBeneficiary,
- commissionAmount,
- constants.currencyINR,
- intendedPricePoint,
- constants.gasUsed,
- constants.optionsReceipt);
-
- assert.equal(payResponse.isFailure(), true);
-
- const account1Balance = new BigNumber(await TC5.balanceOf(constants.account1))
- , account3Balance = new BigNumber(await TC5.balanceOf(constants.account3))
- , account4Balance = new BigNumber(await TC5.balanceOf(constants.account4));
-
- assert.equal(initialAccount1Balance.toNumber(), account1Balance.toNumber());
- assert.equal(initialAccount3Balance.toNumber(), account3Balance.toNumber());
- assert.equal(initialAccount4Balance.toNumber(), account4Balance.toNumber());
-
- // Cache check
- const finalAccount1BalanceCache = await getAmountFromCache(constants.account1)
- , finalAccount3BalanceCache = await getAmountFromCache(constants.account3)
- , finalAccount4BalanceCache = await getAmountFromCache(constants.account4);
-
- assert.equal(account1Balance.toNumber(), finalAccount1BalanceCache.toNumber(), "account1: Actual and cacheValue mismatch after test");
- assert.equal(account3Balance.toNumber(), finalAccount3BalanceCache.toNumber(), "account3: Actual and cacheValue mismatch after test");
- assert.equal(account4Balance.toNumber(), finalAccount4BalanceCache.toNumber(), "account4: Actual and cacheValue mismatch after test");
-
- });
-
-
- it('should fail when commision amount is not 0 and commision beneficiary address is 0', async function() {
- // eslint-disable-next-line no-invalid-this
- this.timeout(100000);
-
- const initialAccount1Balance = new BigNumber(await TC5.balanceOf(constants.account1))
- , initialAccount3Balance = new BigNumber(await TC5.balanceOf(constants.account3))
- , initialAccount4Balance = new BigNumber(await TC5.balanceOf(constants.account4));
-
- // Cache check
- const initialAccount1BalanceCache = await getAmountFromCache(constants.account1)
- , initialAccount3BalanceCache = await getAmountFromCache(constants.account3)
- , initialAccount4BalanceCache = await getAmountFromCache(constants.account4);
-
- assert.equal(initialAccount1Balance.toNumber(), initialAccount1BalanceCache.toNumber(), "account1: Actual and cacheValue mismatch");
- assert.equal(initialAccount3Balance.toNumber(), initialAccount3BalanceCache.toNumber(), "account3: Actual and cacheValue mismatch");
- assert.equal(initialAccount4Balance.toNumber(), initialAccount4BalanceCache.toNumber(), "account4: Actual and cacheValue mismatch");
-
- const beneficiary = constants.account1
- , commissionAmount = new BigNumber(pricerOstUsd.toWei('10'))
- , commissionBeneficiary = 0
- , currency = constants.currencyUSD
- , transferAmount = new BigNumber(pricerOstUsd.toWei('5'))
- ;
-
- const acceptedMarginData = await pricerOstUsd.acceptedMargins(currency);
- assert.equal(acceptedMarginData.isSuccess(), true);
-
- const estimatedValues = await pricerOstUsd.getPricePointAndCalculatedAmounts(
- transferAmount,
- commissionAmount,
- currency);
- assert.equal(estimatedValues.isSuccess(), true);
-
- const estimatedTokenAmount = new BigNumber(estimatedValues.data.tokenAmount);
- const estimatedCommissionTokenAmount = new BigNumber(estimatedValues.data.commissionTokenAmount);
- const estimatedMargin = new BigNumber(acceptedMarginData.data.acceptedMargins);
- const intendedPricePoint = estimatedValues.data.pricePoint;
-
- const total = estimatedTokenAmount
- .plus(estimatedCommissionTokenAmount)
- .plus(estimatedMargin);
-
- await TC5.approve(
- constants.account1,
- constants.accountPassphrase1,
- constants.pricerOstUsdAddress,
- total,
- constants.gasUsed);
-
- const payResponse = await pricerOstUsd.pay(
- constants.account1,
- constants.accountPassphrase1,
- beneficiary,
- transferAmount,
- commissionBeneficiary,
- commissionAmount,
- currency,
- intendedPricePoint,
- constants.gasUsed,
- constants.optionsReceipt);
-
- assert.equal(payResponse.isFailure(), true);
-
- const account1Balance = new BigNumber(await TC5.balanceOf(constants.account1))
- , account3Balance = new BigNumber(await TC5.balanceOf(constants.account3))
- , account4Balance = new BigNumber(await TC5.balanceOf(constants.account4));
-
- assert.equal(initialAccount1Balance.toNumber(), account1Balance.toNumber());
- assert.equal(initialAccount3Balance.toNumber(), account3Balance.toNumber());
- assert.equal(initialAccount4Balance.toNumber(), account4Balance.toNumber());
-
- // Cache check
- const finalAccount1BalanceCache = await getAmountFromCache(constants.account1)
- , finalAccount3BalanceCache = await getAmountFromCache(constants.account3)
- , finalAccount4BalanceCache = await getAmountFromCache(constants.account4);
-
- assert.equal(account1Balance.toNumber(), finalAccount1BalanceCache.toNumber(), "account1: Actual and cacheValue mismatch after test");
- assert.equal(account3Balance.toNumber(), finalAccount3BalanceCache.toNumber(), "account3: Actual and cacheValue mismatch after test");
- assert.equal(account4Balance.toNumber(), finalAccount4BalanceCache.toNumber(), "account4: Actual and cacheValue mismatch after test");
-
- });
-
- it('should fail when intendedPricePoint is more than the acceptable margin of current price point', async function() {
- // eslint-disable-next-line no-invalid-this
- this.timeout(100000);
-
- const initialAccount1Balance = new BigNumber(await TC5.balanceOf(constants.account1))
- , initialAccount3Balance = new BigNumber(await TC5.balanceOf(constants.account3))
- , initialAccount4Balance = new BigNumber(await TC5.balanceOf(constants.account4));
-
- // Cache check
- const initialAccount1BalanceCache = await getAmountFromCache(constants.account1)
- , initialAccount3BalanceCache = await getAmountFromCache(constants.account3)
- , initialAccount4BalanceCache = await getAmountFromCache(constants.account4)
- ;
-
- assert.equal(initialAccount1Balance.toNumber(), initialAccount1BalanceCache.toNumber(), "account1: Actual and cacheValue mismatch");
- assert.equal(initialAccount3Balance.toNumber(), initialAccount3BalanceCache.toNumber(), "account3: Actual and cacheValue mismatch");
- assert.equal(initialAccount4Balance.toNumber(), initialAccount4BalanceCache.toNumber(), "account4: Actual and cacheValue mismatch");
-
- const beneficiary = constants.account3
- , commissionAmount = new BigNumber(pricerOstUsd.toWei('10'))
- , commissionBeneficiary = constants.account4
- , currency = constants.currencyUSD
- , transferAmount = new BigNumber(pricerOstUsd.toWei('5'))
- ;
-
- const acceptedMarginData = await pricerOstUsd.acceptedMargins(currency);
- assert.equal(acceptedMarginData.isSuccess(), true);
-
- const estimatedValues = await pricerOstUsd.getPricePointAndCalculatedAmounts(
- transferAmount,
- commissionAmount,
- currency);
- assert.equal(estimatedValues.isSuccess(), true);
-
- const estimatedTokenAmount = new BigNumber(estimatedValues.data.tokenAmount);
- const estimatedCommissionTokenAmount = new BigNumber(estimatedValues.data.commissionTokenAmount);
- const estimatedMargin = new BigNumber(acceptedMarginData.data.acceptedMargins);
- const intendedPricePoint = estimatedValues.data.pricePoint;
-
- const total = estimatedTokenAmount.plus(estimatedCommissionTokenAmount).plus(estimatedMargin);
-
- await TC5.approve(
- constants.account1,
- constants.accountPassphrase1,
- constants.pricerOstUsdAddress,
- total,
- constants.gasUsed);
-
- const changedPricePoint = new BigNumber(intendedPricePoint)
- .plus(estimatedMargin)
- .plus(new BigNumber(1));
-
- const payResponse = await pricerOstUsd.pay(
- constants.account1,
- constants.accountPassphrase1,
- beneficiary,
- transferAmount,
- commissionBeneficiary,
- commissionAmount,
- currency,
- changedPricePoint,
- constants.gasUsed,
- constants.optionsReceipt);
-
- assert.equal(payResponse.isFailure(), true);
-
- const account1Balance = new BigNumber(await TC5.balanceOf(constants.account1))
- , account3Balance = new BigNumber(await TC5.balanceOf(constants.account3))
- , account4Balance = new BigNumber(await TC5.balanceOf(constants.account4));
-
- assert.equal(initialAccount1Balance.toNumber(), account1Balance.toNumber());
- assert.equal(initialAccount3Balance.toNumber(), account3Balance.toNumber());
- assert.equal(initialAccount4Balance.toNumber(), account4Balance.toNumber());
-
- // Cache check
- const finalAccount1BalanceCache = await getAmountFromCache(constants.account1)
- , finalAccount3BalanceCache = await getAmountFromCache(constants.account3)
- , finalAccount4BalanceCache = await getAmountFromCache(constants.account4)
- ;
-
- assert.equal(account1Balance.toNumber(), finalAccount1BalanceCache.toNumber(), "account1: Actual and cacheValue mismatch after test");
- assert.equal(account3Balance.toNumber(), finalAccount3BalanceCache.toNumber(), "account3: Actual and cacheValue mismatch after test");
- assert.equal(account4Balance.toNumber(), finalAccount4BalanceCache.toNumber(), "account4: Actual and cacheValue mismatch after test");
-
- });
-
-
- it('should fail when intendedPricePoint is less than the acceptable margin of current price point', async function() {
- // eslint-disable-next-line no-invalid-this
- this.timeout(200000);
-
- const initialAccount1Balance = new BigNumber(await TC5.balanceOf(constants.account1))
- , initialAccount3Balance = new BigNumber(await TC5.balanceOf(constants.account3))
- , initialAccount4Balance = new BigNumber(await TC5.balanceOf(constants.account4));
-
- // Cache check
- const initialAccount1BalanceCache = await getAmountFromCache(constants.account1)
- , initialAccount3BalanceCache = await getAmountFromCache(constants.account3)
- , initialAccount4BalanceCache = await getAmountFromCache(constants.account4);
-
- assert.equal(initialAccount1Balance.toNumber(), initialAccount1BalanceCache.toNumber(), "account1: Actual and cacheValue mismatch");
- assert.equal(initialAccount3Balance.toNumber(), initialAccount3BalanceCache.toNumber(), "account3: Actual and cacheValue mismatch");
- assert.equal(initialAccount4Balance.toNumber(), initialAccount4BalanceCache.toNumber(), "account4: Actual and cacheValue mismatch");
-
- const beneficiary = constants.account3
- , commissionAmount = new BigNumber(pricerOstUsd.toWei('10'))
- , commissionBeneficiary = constants.account4
- , currency = constants.currencyUSD
- , transferAmount = new BigNumber(pricerOstUsd.toWei('5'))
- ;
-
- const acceptedMarginData = await pricerOstUsd.acceptedMargins(currency);
- assert.equal(acceptedMarginData.isSuccess(), true);
-
- const estimatedValues = await pricerOstUsd.getPricePointAndCalculatedAmounts(
- transferAmount,
- commissionAmount,
- currency);
- assert.equal(estimatedValues.isSuccess(), true);
-
- const estimatedTokenAmount = new BigNumber(estimatedValues.data.tokenAmount);
- const estimatedCommissionTokenAmount = new BigNumber(estimatedValues.data.commissionTokenAmount);
- const estimatedMargin = new BigNumber(acceptedMarginData.data.acceptedMargins);
- const intendedPricePoint = estimatedValues.data.pricePoint;
-
- const total = estimatedTokenAmount
- .plus(estimatedCommissionTokenAmount)
- .plus(estimatedMargin);
-
- await TC5.approve(
- constants.account1,
- constants.accountPassphrase1,
- constants.pricerOstUsdAddress,
- total,
- constants.gasUsed);
-
- const changedPricePoint = new BigNumber(intendedPricePoint)
- .minus(estimatedMargin)
- .minus(new BigNumber(1));
-
- const payResponse = await pricerOstUsd.pay(
- constants.account1,
- constants.accountPassphrase1,
- beneficiary,
- transferAmount,
- commissionBeneficiary,
- commissionAmount,
- currency,
- changedPricePoint,
- constants.gasUsed,
- constants.optionsReceipt);
-
- assert.equal(payResponse.isFailure(), true);
-
- const account1Balance = new BigNumber(await TC5.balanceOf(constants.account1))
- , account3Balance = new BigNumber(await TC5.balanceOf(constants.account3))
- , account4Balance = new BigNumber(await TC5.balanceOf(constants.account4));
-
- assert.equal(initialAccount1Balance.toNumber(), account1Balance.toNumber());
- assert.equal(initialAccount3Balance.toNumber(), account3Balance.toNumber());
- assert.equal(initialAccount4Balance.toNumber(), account4Balance.toNumber());
-
- // Cache check
- const finalAccount1BalanceCache = await getAmountFromCache(constants.account1)
- , finalAccount3BalanceCache = await getAmountFromCache(constants.account3)
- , finalAccount4BalanceCache = await getAmountFromCache(constants.account4);
-
- assert.equal(account1Balance.toNumber(), finalAccount1BalanceCache.toNumber(), "account1: Actual and cacheValue mismatch after test");
- assert.equal(account3Balance.toNumber(), finalAccount3BalanceCache.toNumber(), "account3: Actual and cacheValue mismatch after test");
- assert.equal(account4Balance.toNumber(), finalAccount4BalanceCache.toNumber(), "account4: Actual and cacheValue mismatch after test");
-
- });
-
-
- it('should fail when price point is 0 and currency is not blank', async function() {
- // eslint-disable-next-line no-invalid-this
- this.timeout(100000);
-
- const initialAccount1Balance = new BigNumber(await TC5.balanceOf(constants.account1))
- , initialAccount3Balance = new BigNumber(await TC5.balanceOf(constants.account3))
- , initialAccount4Balance = new BigNumber(await TC5.balanceOf(constants.account4));
-
- // Cache check
- const initialAccount1BalanceCache = await getAmountFromCache(constants.account1)
- , initialAccount3BalanceCache = await getAmountFromCache(constants.account3)
- , initialAccount4BalanceCache = await getAmountFromCache(constants.account4);
-
- assert.equal(initialAccount1Balance.toNumber(), initialAccount1BalanceCache.toNumber(), "account1: Actual and cacheValue mismatch");
- assert.equal(initialAccount3Balance.toNumber(), initialAccount3BalanceCache.toNumber(), "account3: Actual and cacheValue mismatch");
- assert.equal(initialAccount4Balance.toNumber(), initialAccount4BalanceCache.toNumber(), "account4: Actual and cacheValue mismatch");
-
- const beneficiary = constants.account3
- , commissionAmount = new BigNumber(pricerOstUsd.toWei('10'))
- , commissionBeneficiary = constants.account4
- , currency = constants.currencyUSD
- , transferAmount = new BigNumber(pricerOstUsd.toWei('5'))
- ;
-
- const acceptedMarginData = await pricerOstUsd.acceptedMargins(currency);
- assert.equal(acceptedMarginData.isSuccess(), true);
-
- const estimatedValues = await pricerOstUsd.getPricePointAndCalculatedAmounts(
- transferAmount,
- commissionAmount,
- currency);
- assert.equal(estimatedValues.isSuccess(), true);
-
- const estimatedTokenAmount = new BigNumber(estimatedValues.data.tokenAmount);
- const estimatedCommissionTokenAmount = new BigNumber(estimatedValues.data.commissionTokenAmount);
- const estimatedMargin = new BigNumber(acceptedMarginData.data.acceptedMargins);
- const intendedPricePoint = estimatedValues.data.pricePoint;
-
- const total = estimatedTokenAmount
- .plus(estimatedCommissionTokenAmount)
- .plus(estimatedMargin);
-
- await TC5.approve(
- constants.account1,
- constants.accountPassphrase1,
- constants.pricerOstUsdAddress,
- total,
- constants.gasUsed);
-
- const payResponse = await pricerOstUsd.pay(
- constants.account1,
- constants.accountPassphrase1,
- beneficiary,
- transferAmount,
- commissionBeneficiary,
- commissionAmount,
- constants.currencyINR,
- intendedPricePoint,
- constants.gasUsed,
- constants.optionsReceipt);
-
- assert.equal(payResponse.isFailure(), true);
-
- const account1Balance = new BigNumber(await TC5.balanceOf(constants.account1))
- , account3Balance = new BigNumber(await TC5.balanceOf(constants.account3))
- , account4Balance = new BigNumber(await TC5.balanceOf(constants.account4));
-
- assert.equal(initialAccount1Balance.toNumber(), account1Balance.toNumber());
- assert.equal(initialAccount3Balance.toNumber(), account3Balance.toNumber());
- assert.equal(initialAccount4Balance.toNumber(), account4Balance.toNumber());
-
- // Cache check
- const finalAccount1BalanceCache = await getAmountFromCache(constants.account1)
- , finalAccount3BalanceCache = await getAmountFromCache(constants.account3)
- , finalAccount4BalanceCache = await getAmountFromCache(constants.account4);
-
- assert.equal(account1Balance.toNumber(), finalAccount1BalanceCache.toNumber(), "account1: Actual and cacheValue mismatch after test");
- assert.equal(account3Balance.toNumber(), finalAccount3BalanceCache.toNumber(), "account3: Actual and cacheValue mismatch after test");
- assert.equal(account4Balance.toNumber(), finalAccount4BalanceCache.toNumber(), "account4: Actual and cacheValue mismatch after test");
-
- });
-
-
- it('should pass when all parameters are valid and commission beneficiary address, commissionAmount is 0', async function() {
- // eslint-disable-next-line no-invalid-this
- this.timeout(100000);
-
- const initialAccount1Balance = new BigNumber(await TC5.balanceOf(constants.account1))
- , initialAccount3Balance = new BigNumber(await TC5.balanceOf(constants.account3))
- , initialAccount4Balance = new BigNumber(await TC5.balanceOf(constants.account4));
-
- // Cache check
- const initialAccount1BalanceCache = await getAmountFromCache(constants.account1)
- , initialAccount3BalanceCache = await getAmountFromCache(constants.account3)
- , initialAccount4BalanceCache = await getAmountFromCache(constants.account4);
-
- assert.equal(initialAccount1Balance.toNumber(), initialAccount1BalanceCache.toNumber(), "account1: Actual and cacheValue mismatch");
- assert.equal(initialAccount3Balance.toNumber(), initialAccount3BalanceCache.toNumber(), "account3: Actual and cacheValue mismatch");
- assert.equal(initialAccount4Balance.toNumber(), initialAccount4BalanceCache.toNumber(), "account4: Actual and cacheValue mismatch");
-
- const beneficiary = constants.account3
- , commissionAmount = new BigNumber(pricerOstUsd.toWei('0'))
- , commissionBeneficiary = constants.account4
- , currency = constants.currencyUSD
- , transferAmount = new BigNumber(pricerOstUsd.toWei('5'))
- ;
-
- const acceptedMarginData = await pricerOstUsd.acceptedMargins(currency);
- assert.equal(acceptedMarginData.isSuccess(), true);
-
- const estimatedValues = await pricerOstUsd.getPricePointAndCalculatedAmounts(
- transferAmount,
- commissionAmount,
- currency);
- assert.equal(estimatedValues.isSuccess(), true);
- assert.equal(estimatedValues.data.commissionTokenAmount, 0);
-
- const estimatedTokenAmount = new BigNumber(estimatedValues.data.tokenAmount);
- const estimatedMargin = new BigNumber(acceptedMarginData.data.acceptedMargins);
- const intendedPricePoint = estimatedValues.data.pricePoint;
-
- const total = estimatedTokenAmount.plus(estimatedMargin);
-
- await TC5.approve(
- constants.account1,
- constants.accountPassphrase1,
- constants.pricerOstUsdAddress,
- total,
- constants.gasUsed);
-
- const payResponse = await pricerOstUsd.pay(
- constants.account1,
- constants.accountPassphrase1,
- beneficiary,
- transferAmount,
- commissionBeneficiary,
- commissionAmount,
- currency,
- intendedPricePoint,
- constants.gasUsed,
- constants.optionsReceipt);
-
- // verify if the transaction receipt is valid
- utils.verifyTransactionReceipt(payResponse);
-
- // verify if the transaction has was actually mined
- await utils.verifyIfMined(pricerOstUsd, payResponse.data.transaction_hash);
-
- const account1Balance = new BigNumber(await TC5.balanceOf(constants.account1))
- , account3Balance = new BigNumber(await TC5.balanceOf(constants.account3))
- , account4Balance = new BigNumber(await TC5.balanceOf(constants.account4));
-
- assert.equal(initialAccount1Balance.minus(estimatedTokenAmount).toNumber(), account1Balance.toNumber());
- assert.equal(initialAccount3Balance.plus(estimatedTokenAmount).toNumber(), account3Balance.toNumber());
- assert.equal(initialAccount4Balance.toNumber(), account4Balance.toNumber());
-
- // Cache check
- const finalAccount1BalanceCache = await getAmountFromCache(constants.account1)
- , finalAccount3BalanceCache = await getAmountFromCache(constants.account3)
- , finalAccount4BalanceCache = await getAmountFromCache(constants.account4);
-
- assert.equal(account1Balance.toNumber(), finalAccount1BalanceCache.toNumber(), "account1: Actual and cacheValue mismatch after test");
- assert.equal(account3Balance.toNumber(), finalAccount3BalanceCache.toNumber(), "account3: Actual and cacheValue mismatch after test");
- assert.equal(account4Balance.toNumber(), finalAccount4BalanceCache.toNumber(), "account4: Actual and cacheValue mismatch after test");
-
- });
-
-
- it('should pass when all parameters are valid and currency is blank (BT Transfer)', async function() {
- // eslint-disable-next-line no-invalid-this
- this.timeout(100000);
-
- const initialAccount1Balance = new BigNumber(await TC5.balanceOf(constants.account1))
- , initialAccount3Balance = new BigNumber(await TC5.balanceOf(constants.account3))
- , initialAccount4Balance = new BigNumber(await TC5.balanceOf(constants.account4));
-
- // Cache check
- const initialAccount1BalanceCache = await getAmountFromCache(constants.account1)
- , initialAccount3BalanceCache = await getAmountFromCache(constants.account3)
- , initialAccount4BalanceCache = await getAmountFromCache(constants.account4);
-
- assert.equal(initialAccount1Balance.toNumber(), initialAccount1BalanceCache.toNumber(), "account1: Actual and cacheValue mismatch");
- assert.equal(initialAccount3Balance.toNumber(), initialAccount3BalanceCache.toNumber(), "account3: Actual and cacheValue mismatch");
- assert.equal(initialAccount4Balance.toNumber(), initialAccount4BalanceCache.toNumber(), "account4: Actual and cacheValue mismatch");
-
- const beneficiary = constants.account3
- , commissionAmount = new BigNumber(pricerOstUsd.toWei('5'))
- , commissionBeneficiary = constants.account4
- , currency = constants.currencyBlank
- , transferAmount = new BigNumber(pricerOstUsd.toWei('10'))
- ;
-
- const intendedPricePoint = 0;
-
- const total = transferAmount.plus(commissionAmount);
-
- await TC5.approve(
- constants.account1,
- constants.accountPassphrase1,
- constants.pricerOstUsdAddress,
- total,
- constants.gasUsed);
-
- const payResponse = await pricerOstUsd.pay(
- constants.account1,
- constants.accountPassphrase1,
- beneficiary,
- transferAmount,
- commissionBeneficiary,
- commissionAmount,
- currency,
- intendedPricePoint,
- constants.gasUsed,
- constants.optionsReceipt);
-
- // verify if the transaction receipt is valid
- utils.verifyTransactionReceipt(payResponse);
-
- // verify if the transaction has was actually mined
- await utils.verifyIfMined(pricerOstUsd, payResponse.data.transaction_hash);
-
- const account1Balance = new BigNumber(await TC5.balanceOf(constants.account1))
- , account3Balance = new BigNumber(await TC5.balanceOf(constants.account3))
- , account4Balance = new BigNumber(await TC5.balanceOf(constants.account4));
-
- assert.equal(initialAccount1Balance.minus(total).toNumber(), account1Balance.toNumber());
- assert.equal(initialAccount3Balance.plus(transferAmount).toNumber(), account3Balance.toNumber());
- assert.equal(initialAccount4Balance.plus(commissionAmount).toNumber(), account4Balance.toNumber());
-
- // Cache check
- const finalAccount1BalanceCache = await getAmountFromCache(constants.account1)
- , finalAccount3BalanceCache = await getAmountFromCache(constants.account3)
- , finalAccount4BalanceCache = await getAmountFromCache(constants.account4);
-
- assert.equal(account1Balance.toNumber(), finalAccount1BalanceCache.toNumber(), "account1: Actual and cacheValue mismatch after test");
- assert.equal(account3Balance.toNumber(), finalAccount3BalanceCache.toNumber(), "account3: Actual and cacheValue mismatch after test");
- assert.equal(account4Balance.toNumber(), finalAccount4BalanceCache.toNumber(), "account4: Actual and cacheValue mismatch after test");
- });
-
-
- it('should fail when intended price point is 0', async function() {
- // eslint-disable-next-line no-invalid-this
- this.timeout(100000);
-
- const initialAccount1Balance = new BigNumber(await TC5.balanceOf(constants.account1))
- , initialAccount3Balance = new BigNumber(await TC5.balanceOf(constants.account3))
- , initialAccount4Balance = new BigNumber(await TC5.balanceOf(constants.account4));
-
- // Cache check
- const initialAccount1BalanceCache = await getAmountFromCache(constants.account1)
- , initialAccount3BalanceCache = await getAmountFromCache(constants.account3)
- , initialAccount4BalanceCache = await getAmountFromCache(constants.account4);
-
- assert.equal(initialAccount1Balance.toNumber(), initialAccount1BalanceCache.toNumber(), "account1: Actual and cacheValue mismatch");
- assert.equal(initialAccount3Balance.toNumber(), initialAccount3BalanceCache.toNumber(), "account3: Actual and cacheValue mismatch");
- assert.equal(initialAccount4Balance.toNumber(), initialAccount4BalanceCache.toNumber(), "account4: Actual and cacheValue mismatch");
-
- const beneficiary = constants.account3
- , commissionAmount = new BigNumber(pricerOstUsd.toWei('10'))
- , commissionBeneficiary = constants.account4
- , currency = constants.currencyUSD
- , transferAmount = new BigNumber(pricerOstUsd.toWei('5'))
- ;
-
- const acceptedMarginData = await pricerOstUsd.acceptedMargins(currency);
- assert.equal(acceptedMarginData.isSuccess(), true);
-
- const estimatedValues = await pricerOstUsd.getPricePointAndCalculatedAmounts(
- transferAmount,
- commissionAmount,
- currency);
- assert.equal(estimatedValues.isSuccess(), true);
-
- const estimatedTokenAmount = new BigNumber(estimatedValues.data.tokenAmount);
- const estimatedCommissionTokenAmount = new BigNumber(estimatedValues.data.commissionTokenAmount);
- const estimatedMargin = new BigNumber(acceptedMarginData.data.acceptedMargins);
-
- const total = estimatedTokenAmount.plus(estimatedCommissionTokenAmount).plus(estimatedMargin);
-
- await TC5.approve(
- constants.account1,
- constants.accountPassphrase1,
- constants.pricerOstUsdAddress,
- total,
- constants.gasUsed);
-
- const payResponse = await pricerOstUsd.pay(
- constants.account1,
- constants.accountPassphrase1,
- beneficiary,
- transferAmount,
- commissionBeneficiary,
- commissionAmount,
- constants.currencyUSD,
- 0,
- constants.gasUsed,
- constants.optionsReceipt);
-
- assert.equal(payResponse.isFailure(), true, "intendedPricePoint 0 cheek");
-
- const account1Balance = new BigNumber(await TC5.balanceOf(constants.account1))
- , account3Balance = new BigNumber(await TC5.balanceOf(constants.account3))
- , account4Balance = new BigNumber(await TC5.balanceOf(constants.account4));
-
- assert.equal(initialAccount1Balance.toNumber(), account1Balance.toNumber());
- assert.equal(initialAccount3Balance.toNumber(), account3Balance.toNumber());
- assert.equal(initialAccount4Balance.toNumber(), account4Balance.toNumber());
-
- // Cache check
- const finalAccount1BalanceCache = await getAmountFromCache(constants.account1)
- , finalAccount3BalanceCache = await getAmountFromCache(constants.account3)
- , finalAccount4BalanceCache = await getAmountFromCache(constants.account4);
-
- assert.equal(account1Balance.toNumber(), finalAccount1BalanceCache.toNumber(), "account1: Actual and cacheValue mismatch after test");
- assert.equal(account3Balance.toNumber(), finalAccount3BalanceCache.toNumber(), "account3: Actual and cacheValue mismatch after test");
- assert.equal(account4Balance.toNumber(), finalAccount4BalanceCache.toNumber(), "account4: Actual and cacheValue mismatch after test");
-
- });
-
-
- it('should pass for interaction layer test when return type is uuid', async function() {
-
- // eslint-disable-next-line no-invalid-this
- this.timeout(100000);
-
- const beneficiary = constants.account3
- , commissionAmount = new BigNumber(pricerOstUsd.toWei('2'))
- , commissionBeneficiary = constants.account4
- , currency = constants.currencyUSD
- , transferAmount = new BigNumber(pricerOstUsd.toWei('7'))
- ;
-
- const acceptedMarginData = await pricerOstUsd.acceptedMargins(currency);
- assert.equal(acceptedMarginData.isSuccess(), true);
-
- const estimatedValues = await pricerOstUsd.getPricePointAndCalculatedAmounts(
- transferAmount,
- commissionAmount,
- currency);
-
- assert.equal(estimatedValues.isSuccess(), true);
-
- const estimatedTokenAmount = new BigNumber(estimatedValues.data.tokenAmount);
- const estimatedCommissionTokenAmount = new BigNumber(estimatedValues.data.commissionTokenAmount);
-
- const intendedPricePoint = estimatedValues.data.pricePoint;
-
- const estimatedTotalAmount = new BigNumber(0).plus(estimatedTokenAmount).plus(estimatedCommissionTokenAmount);
-
- await TC5.approve(
- constants.account1,
- constants.accountPassphrase1,
- constants.pricerOstUsdAddress,
- estimatedTotalAmount,
- constants.gasUsed);
-
- const payResponse = await pricerOstUsd.pay(
- constants.account1,
- constants.accountPassphrase1,
- beneficiary,
- transferAmount,
- commissionBeneficiary,
- commissionAmount,
- currency,
- intendedPricePoint,
- constants.gasUsed,
- constants.optionsUUID);
-
- // verify if the transaction receipt is valid
- // we will not verify if it got mined as its just interaction layer testing
- utils.verifyTransactionUUID(payResponse);
-
- });
-
- it('should pass for interaction layer test when return type is txHash', async function() {
-
- // eslint-disable-next-line no-invalid-this
- this.timeout(100000);
-
- const beneficiary = constants.account3
- , commissionAmount = new BigNumber(pricerOstUsd.toWei('2'))
- , commissionBeneficiary = constants.account4
- , currency = constants.currencyUSD
- , transferAmount = new BigNumber(pricerOstUsd.toWei('7'))
- ;
-
- const acceptedMarginData = await pricerOstUsd.acceptedMargins(currency);
- assert.equal(acceptedMarginData.isSuccess(), true);
-
- const estimatedValues = await pricerOstUsd.getPricePointAndCalculatedAmounts(
- transferAmount,
- commissionAmount,
- currency);
-
- assert.equal(estimatedValues.isSuccess(), true);
-
- const estimatedTokenAmount = new BigNumber(estimatedValues.data.tokenAmount);
- const estimatedCommissionTokenAmount = new BigNumber(estimatedValues.data.commissionTokenAmount);
-
- const intendedPricePoint = estimatedValues.data.pricePoint;
-
- const estimatedTotalAmount = new BigNumber(0).plus(estimatedTokenAmount).plus(estimatedCommissionTokenAmount);
-
- await TC5.approve(
- constants.account1,
- constants.accountPassphrase1,
- constants.pricerOstUsdAddress,
- estimatedTotalAmount,
- constants.gasUsed);
-
- const payResponse = await pricerOstUsd.pay(
- constants.account1,
- constants.accountPassphrase1,
- beneficiary,
- transferAmount,
- commissionBeneficiary,
- commissionAmount,
- currency,
- intendedPricePoint,
- constants.gasUsed,
- constants.optionsHash);
-
- // verify if the transaction hash is valid
- // we will not verify if it got mined as its just interaction layer testing
- utils.verifyTransactionHash(payResponse);
-
- });
-
- it('should pass for interaction layer test when return type is txReceipt', async function() {
-
- // eslint-disable-next-line no-invalid-this
- this.timeout(100000);
-
- const beneficiary = constants.account3
- , commissionAmount = new BigNumber(pricerOstUsd.toWei('2'))
- , commissionBeneficiary = constants.account4
- , currency = constants.currencyUSD
- , transferAmount = new BigNumber(pricerOstUsd.toWei('7'))
- ;
-
- const acceptedMarginData = await pricerOstUsd.acceptedMargins(currency);
- assert.equal(acceptedMarginData.isSuccess(), true);
-
- const estimatedValues = await pricerOstUsd.getPricePointAndCalculatedAmounts(
- transferAmount,
- commissionAmount,
- currency);
-
- assert.equal(estimatedValues.isSuccess(), true);
-
- const estimatedTokenAmount = new BigNumber(estimatedValues.data.tokenAmount);
- const estimatedCommissionTokenAmount = new BigNumber(estimatedValues.data.commissionTokenAmount);
-
- const intendedPricePoint = estimatedValues.data.pricePoint;
-
- const estimatedTotalAmount = new BigNumber(0).plus(estimatedTokenAmount).plus(estimatedCommissionTokenAmount);
-
- await TC5.approve(
- constants.account1,
- constants.accountPassphrase1,
- constants.pricerOstUsdAddress,
- estimatedTotalAmount,
- constants.gasUsed);
-
- const payResponse = await pricerOstUsd.pay(
- constants.account1,
- constants.accountPassphrase1,
- beneficiary,
- transferAmount,
- commissionBeneficiary,
- commissionAmount,
- currency,
- intendedPricePoint,
- constants.gasUsed,
- constants.optionsReceipt);
-
- // verify if the transaction receipt is valid.
- // We will not check here if the value is really set as its just interaction layer testing.
- utils.verifyTransactionReceipt(payResponse);
-
- });
-
-
- it('should fail when sender has insufficient balance (BT Transfer)', async function() {
- // eslint-disable-next-line no-invalid-this
- this.timeout(100000);
-
- const initialAccount1Balance = new BigNumber(await TC5.balanceOf(constants.account1))
- , initialAccount3Balance = new BigNumber(await TC5.balanceOf(constants.account3))
- , initialAccount4Balance = new BigNumber(await TC5.balanceOf(constants.account4));
-
- // Cache check
- const initialAccount1BalanceCache = await getAmountFromCache(constants.account1)
- , initialAccount3BalanceCache = await getAmountFromCache(constants.account3)
- , initialAccount4BalanceCache = await getAmountFromCache(constants.account4);
-
- assert.equal(initialAccount1Balance.toNumber(), initialAccount1BalanceCache.toNumber(), "account1: Actual and cacheValue mismatch");
- assert.equal(initialAccount3Balance.toNumber(), initialAccount3BalanceCache.toNumber(), "account3: Actual and cacheValue mismatch");
- assert.equal(initialAccount4Balance.toNumber(), initialAccount4BalanceCache.toNumber(), "account4: Actual and cacheValue mismatch");
-
- const beneficiary = constants.account3
- , commissionAmount = new BigNumber(pricerOstUsd.toWei('0.1'))
- , commissionBeneficiary = constants.account4
- , currency = constants.currencyBlank
- , transferAmount = new BigNumber(pricerOstUsd.toWei('50000'))
- ;
-
- const intendedPricePoint = 0;
-
- const total = transferAmount.plus(commissionAmount);
-
- await TC5.approve(
- constants.account1,
- constants.accountPassphrase1,
- constants.pricerOstUsdAddress,
- total,
- constants.gasUsed);
-
- const payResponse = await pricerOstUsd.pay(
- constants.account1,
- constants.accountPassphrase1,
- beneficiary,
- transferAmount,
- commissionBeneficiary,
- commissionAmount,
- currency,
- intendedPricePoint,
- constants.gasUsed,
- constants.optionsReceipt);
-
- assert.equal(payResponse.isFailure(), true, "insufficient balance cheek");
-
- const account1Balance = new BigNumber(await TC5.balanceOf(constants.account1))
- , account3Balance = new BigNumber(await TC5.balanceOf(constants.account3))
- , account4Balance = new BigNumber(await TC5.balanceOf(constants.account4));
-
- assert.equal(initialAccount1Balance.toNumber(), account1Balance.toNumber());
- assert.equal(initialAccount3Balance.toNumber(), account3Balance.toNumber());
- assert.equal(initialAccount4Balance.toNumber(), account4Balance.toNumber());
-
- // Cache check
- const finalAccount1BalanceCache = await getAmountFromCache(constants.account1)
- , finalAccount3BalanceCache = await getAmountFromCache(constants.account3)
- , finalAccount4BalanceCache = await getAmountFromCache(constants.account4);
-
- assert.equal(account1Balance.toNumber(), finalAccount1BalanceCache.toNumber(), "account1: Actual and cacheValue mismatch after test");
- assert.equal(account3Balance.toNumber(), finalAccount3BalanceCache.toNumber(), "account3: Actual and cacheValue mismatch after test");
- assert.equal(account4Balance.toNumber(), finalAccount4BalanceCache.toNumber(), "account4: Actual and cacheValue mismatch after test");
- });
-
-});
-
-
diff --git a/mocha_test/services/pricer/price_oracles.js b/mocha_test/services/pricer/price_oracles.js
deleted file mode 100644
index db7c42e..0000000
--- a/mocha_test/services/pricer/price_oracles.js
+++ /dev/null
@@ -1,126 +0,0 @@
-
-/* global describe, it */
-
-const chai = require('chai')
- , assert = chai.assert;
-
-const rootPrefix = "../../.."
- , constants = require(rootPrefix + '/mocha_test/lib/constants')
- , utils = require(rootPrefix+'/mocha_test/lib/utils')
- , pricer = require(rootPrefix + '/lib/contract_interact/pricer')
- , pricerOstUsd = new pricer(constants.pricerOstUsdAddress, constants.chainId)
-;
-
-describe('Get price oracles', function() {
-
- it('should fail when currency is blank', async function() {
- // eslint-disable-next-line no-invalid-this
- this.timeout(100000);
-
- const poResult = await pricerOstUsd.priceOracles(constants.currencyBlank);
- assert.equal(poResult.isFailure(), true);
-
- });
-
- it('should return 0x0 when currency is not set', async function() {
- // eslint-disable-next-line no-invalid-this
- this.timeout(100000);
-
- const poResult = await pricerOstUsd.priceOracles("ABC");
- assert.equal(poResult.isSuccess(), true);
- assert.equal(poResult.data.priceOracles, 0x0);
-
- });
-
- it('should return correct price oracles (after set)', async function() {
- // eslint-disable-next-line no-invalid-this
- this.timeout(100000);
-
- // set price oracle
- const setResponse = await pricerOstUsd.setPriceOracle(
- constants.ops,
- constants.opsPassphrase,
- constants.currencyUSD,
- constants.priceOracles.OST.USD,
- constants.gasUsed,
- constants.optionsReceipt);
-
- // verify if the transaction receipt is valid
- utils.verifyTransactionReceipt(setResponse);
-
- // verify if the transaction has was actually mined
- await utils.verifyIfMined(pricerOstUsd, setResponse.data.transaction_hash);
-
- // set price oracle
- const setResponse1 = await pricerOstUsd.setPriceOracle(
- constants.ops,
- constants.opsPassphrase,
- constants.currencyEUR,
- constants.priceOracles.OST.EUR,
- constants.gasUsed,
- constants.optionsReceipt);
-
- // verify if the transaction receipt is valid
- utils.verifyTransactionReceipt(setResponse);
-
- // verify if the transaction has was actually mined
- await utils.verifyIfMined(pricerOstUsd, setResponse.data.transaction_hash);
-
- // verify result
- const poResult1 = await pricerOstUsd.priceOracles(constants.currencyUSD);
- assert.equal(poResult1.isSuccess(), true);
- assert.equal(poResult1.data.priceOracles, constants.priceOracles.OST.USD);
-
- // verify result
- const poResult2 = await pricerOstUsd.priceOracles(constants.currencyEUR);
- assert.equal(poResult2.isSuccess(), true);
- assert.equal(poResult2.data.priceOracles, constants.priceOracles.OST.EUR);
-
- });
-
- it('should return 0x0 (after unset)', async function() {
- // eslint-disable-next-line no-invalid-this
- this.timeout(100000);
-
- // unset price oracle
- const unsetResponse = await pricerOstUsd.unsetPriceOracle(
- constants.ops,
- constants.opsPassphrase,
- constants.currencyUSD,
- constants.gasUsed,
- constants.optionsReceipt);
-
- // verify if the transaction receipt is valid
- utils.verifyTransactionReceipt(unsetResponse);
-
- // verify if the transaction has was actually mined
- await utils.verifyIfMined(pricerOstUsd, unsetResponse.data.transaction_hash);
-
- // unset price oracle
- const unsetResponse1 = await pricerOstUsd.unsetPriceOracle(
- constants.ops,
- constants.opsPassphrase,
- constants.currencyEUR,
- constants.gasUsed,
- constants.optionsReceipt);
-
- // verify if the transaction receipt is valid
- utils.verifyTransactionReceipt(unsetResponse1);
-
- // verify if the transaction has was actually mined
- await utils.verifyIfMined(pricerOstUsd, unsetResponse1.data.transaction_hash);
-
- // verify result
- const poResult1 = await pricerOstUsd.priceOracles(constants.currencyUSD);
- assert.equal(poResult1.isSuccess(), true);
- assert.equal(poResult1.data.priceOracles, 0x0);
-
- // verify result
- const poResult2 = await pricerOstUsd.priceOracles(constants.currencyEUR);
- assert.equal(poResult2.isSuccess(), true);
- assert.equal(poResult2.data.priceOracles, 0x0);
-
- });
-
-});
-
diff --git a/mocha_test/services/pricer/set_accepted_margin.js b/mocha_test/services/pricer/set_accepted_margin.js
deleted file mode 100644
index 092301f..0000000
--- a/mocha_test/services/pricer/set_accepted_margin.js
+++ /dev/null
@@ -1,280 +0,0 @@
-/* global describe, it */
-
-/*eslint-disable */
-const chai = require('chai')
- , assert = chai.assert;
-
-const rootPrefix = "../../.."
- , constants = require(rootPrefix + '/mocha_test/lib/constants')
- , pricer = require(rootPrefix + '/lib/contract_interact/pricer')
- , utils = require(rootPrefix+'/mocha_test/lib/utils')
- , pricerOstUsd = new pricer(constants.pricerOstUsdAddress, constants.chainId)
-;
-/*eslint-enable */
-
-describe('Set accepted margins', function() {
-
- it('should pass the initial address checks', async function() {
-
- // eslint-disable-next-line no-invalid-this
- this.timeout(100000);
-
- assert.isDefined(constants.deployer);
- assert.isDefined(constants.ops);
- assert.isDefined(constants.account1);
- assert.notEqual(constants.deployer, constants.ops);
- assert.notEqual(constants.deployer, constants.account1);
- assert.notEqual(constants.ops, constants.account1);
-
- // set the accepted margin to 30
- const response = await pricerOstUsd.setAcceptedMargin(
- constants.ops,
- constants.opsPassphrase,
- constants.currencyUSD,
- 30,
- constants.gasUsed,
- constants.optionsReceipt);
-
- // verify if the transaction receipt is valid
- utils.verifyTransactionReceipt(response);
-
- // verify if the transaction has was actually mined
- await utils.verifyIfMined(pricerOstUsd, response.data.transaction_hash);
-
- // verify if value is changed
- const amResult = await pricerOstUsd.acceptedMargins(constants.currencyUSD);
- assert.equal(amResult.isSuccess(), true);
- assert.equal(30, amResult.data.acceptedMargins);
-
- });
-
- it('should pass for interaction layer test when return type is uuid', async function() {
-
- // eslint-disable-next-line no-invalid-this
- this.timeout(100000);
-
- // set the accepted margin to 50
- const response = await pricerOstUsd.setAcceptedMargin(
- constants.ops,
- constants.opsPassphrase,
- constants.currencyUSD,
- 50,
- constants.gasUsed,
- constants.optionsUUID);
-
- // verify if the transaction receipt is valid
- // we will not verify if it got mined as its just interaction layer testing
- utils.verifyTransactionUUID(response);
-
- });
-
- it('should pass for interaction layer test when return type is txHash', async function() {
-
- // eslint-disable-next-line no-invalid-this
- this.timeout(100000);
-
- // set the accepted margin to 150
- const response = await pricerOstUsd.setAcceptedMargin(
- constants.ops,
- constants.opsPassphrase,
- constants.currencyUSD,
- 150,
- constants.gasUsed,
- constants.optionsHash);
-
- // verify if the transaction hash is valid
- // we will not verify if it got mined as its just interaction layer testing
- utils.verifyTransactionHash(response);
-
- });
-
- it('should pass for interaction layer test when return type is txReceipt', async function() {
-
- // eslint-disable-next-line no-invalid-this
- this.timeout(100000);
-
- // set the accepted margin to 70
- const response = await pricerOstUsd.setAcceptedMargin(
- constants.ops,
- constants.opsPassphrase,
- constants.currencyUSD,
- 70,
- constants.gasUsed,
- constants.optionsReceipt);
-
- // verify if the transaction receipt is valid.
- // We will not check here if the value is really set as its just interaction layer testing.
- utils.verifyTransactionReceipt(response);
-
- });
-
-
- it('should fail when currency is blank', async function() {
-
- // set the accepted margin to 3
- const response = await pricerOstUsd.setAcceptedMargin(
- constants.ops,
- constants.opsPassphrase,
- constants.currencyBlank,
- 3,
- constants.gasUsed,
- constants.optionsReceipt);
-
- // verify if the response is failure
- assert.equal(response.isFailure(), true);
-
- });
-
-
- it('should fail when gas amount is 0', async function() {
-
- // set the accepted margin to 3
- const response = await pricerOstUsd.setAcceptedMargin(
- constants.ops,
- constants.opsPassphrase,
- constants.currencyUSD,
- 3,
- 0,
- constants.optionsReceipt);
-
- // verify if the response is failure
- assert.equal(response.isFailure(), true);
-
- });
-
- it('should fail when sender address is 0', async function() {
-
- // set the accepted margin to 3
- const response = await pricerOstUsd.setAcceptedMargin(
- 0,
- constants.opsPassphrase,
- constants.currencyUSD,
- 3,
- constants.gasUsed,
- constants.optionsReceipt);
-
- // verify if the response is failure
- assert.equal(response.isFailure(), true);
-
- });
-
-
- it('should fail when accepted margin is negative', async function() {
-
- // set the accepted margin to -30
- const response = await pricerOstUsd.setAcceptedMargin(
- 0,
- constants.opsPassphrase,
- constants.currencyUSD,
- -30,
- constants.gasUsed,
- constants.optionsReceipt);
-
- // verify if the response is failure
- assert.equal(response.isFailure(), true);
-
- });
-
-
- it('should fail when sender is not ops', async function() {
- // eslint-disable-next-line no-invalid-this
- this.timeout(200000);
-
- // set the accepted margin to 3
- const response1 = await pricerOstUsd.setAcceptedMargin(
- constants.ops,
- constants.opsPassphrase,
- constants.currencyUSD,
- 3,
- constants.gasUsed,
- constants.optionsReceipt);
-
- // verify if the transaction receipt is valid
- utils.verifyTransactionReceipt(response1);
-
- // verify if the transaction has was actually mined
- await utils.verifyIfMined(pricerOstUsd, response1.data.transaction_hash);
-
- // verify if the accepted margin is set to 3
- const amResult1 = await pricerOstUsd.acceptedMargins(constants.currencyUSD);
- assert.equal(amResult1.isSuccess(), true);
- assert.equal(3, amResult1.data.acceptedMargins);
-
- // set the accepted margin to 8
- const response2 = await pricerOstUsd.setAcceptedMargin(
- constants.deployer,
- constants.deployerPassphrase,
- constants.currencyUSD,
- 8,
- constants.gasUsed,
- constants.optionsReceipt);
-
- // verify if the response is failure
- assert.equal(response2.isFailure(), true);
-
- // verify if the accepted margin is still set to 3
- const amResult2 = await pricerOstUsd.acceptedMargins(constants.currencyUSD);
- assert.equal(amResult2.isSuccess(), true);
- assert.equal(3, amResult2.data.acceptedMargins);
-
- });
-
-
- it('should pass when margin is 0', async function() {
-
- // eslint-disable-next-line no-invalid-this
- this.timeout(100000);
-
- // set the accepted margin to 0
- const response = await pricerOstUsd.setAcceptedMargin(
- constants.ops,
- constants.opsPassphrase,
- constants.currencyUSD,
- 0,
- constants.gasUsed,
- constants.optionsReceipt);
-
- // verify if the transaction receipt is valid
- utils.verifyTransactionReceipt(response);
-
- // verify if the transaction has was actually mined
- await utils.verifyIfMined(pricerOstUsd, response.data.transaction_hash);
-
- // verify if the accepted margin is set to 0
- const amResult = await pricerOstUsd.acceptedMargins(constants.currencyUSD);
- assert.equal(amResult.isSuccess(), true);
- assert.equal(0, amResult.data.acceptedMargins);
-
- });
-
-
- it('should pass when margin is 50', async function() {
-
- // eslint-disable-next-line no-invalid-this
- this.timeout(100000);
-
- // set the accepted margin to 50
- const response = await pricerOstUsd.setAcceptedMargin(
- constants.ops,
- constants.opsPassphrase,
- constants.currencyUSD,
- 50,
- constants.gasUsed,
- constants.optionsReceipt);
-
- // verify if the transaction receipt is valid
- utils.verifyTransactionReceipt(response);
-
- // verify if the transaction has was actually mined
- await utils.verifyIfMined(pricerOstUsd, response.data.transaction_hash);
-
- // verify if the accepted margin is set to 50
- const amResult = await pricerOstUsd.acceptedMargins(constants.currencyUSD);
- assert.equal(amResult.isSuccess(), true);
- assert.equal(50, amResult.data.acceptedMargins);
-
- });
-
-});
-
-
diff --git a/mocha_test/services/pricer/set_price_oracle.js b/mocha_test/services/pricer/set_price_oracle.js
deleted file mode 100644
index 8a3156e..0000000
--- a/mocha_test/services/pricer/set_price_oracle.js
+++ /dev/null
@@ -1,312 +0,0 @@
-
-/* global describe, it */
-
-const chai = require('chai')
- , assert = chai.assert;
-
-const rootPrefix = "../../.."
- , constants = require(rootPrefix + '/mocha_test/lib/constants')
- , utils = require(rootPrefix+'/mocha_test/lib/utils')
- , pricer = require(rootPrefix + '/lib/contract_interact/pricer')
- , pricerOstUsd = new pricer(constants.pricerOstUsdAddress, constants.chainId)
- , pricerOstEur = new pricer(constants.pricerOstEurAddress, constants.chainId)
- , pricerOstUsd10Decimal = new pricer(constants.pricerOstUsd10DecimalAddress, constants.chainId)
-;
-
-describe('Set price oracle', function() {
-
- it('should pass the initial address checks', async function() {
- // eslint-disable-next-line no-invalid-this
- this.timeout(100000);
- assert.isDefined(constants.deployer);
- assert.isDefined(constants.ops);
- assert.isDefined(constants.account1);
- assert.notEqual(constants.deployer, constants.ops);
- assert.notEqual(constants.deployer, constants.account1);
- assert.notEqual(constants.ops, constants.account1);
-
- // unset the price oracle
- await pricerOstUsd.unsetPriceOracle(
- constants.ops,
- constants.opsPassphrase,
- constants.currencyUSD,
- constants.gasUsed,
- constants.optionsReceipt);
-
- // verify if value is changed
- const poResult1 = await pricerOstUsd.priceOracles(constants.currencyUSD);
- assert.equal(poResult1.isSuccess(), true);
- assert.equal(0x0, poResult1.data.priceOracles);
-
- // unset the price oracle
- await pricerOstEur.unsetPriceOracle(
- constants.ops,
- constants.opsPassphrase,
- constants.currencyEUR,
- constants.gasUsed,
- constants.optionsReceipt);
-
- // verify if value is changed
- const poResult2 = await pricerOstEur.priceOracles(constants.currencyEUR);
- assert.equal(poResult2.isSuccess(), true);
- assert.equal(0x0, poResult2.data.priceOracles);
-
- });
-
-
- it('should fail when sender is not ops', async function() {
- // eslint-disable-next-line no-invalid-this
- this.timeout(100000);
-
- // set price oracle
- const setResponse = await pricerOstUsd.setPriceOracle(
- constants.deployer,
- constants.deployerPassphrase,
- constants.currencyUSD,
- constants.priceOracles.OST.USD,
- constants.gasUsed,
- constants.optionsReceipt);
-
- // check if the response is failure
- assert.equal(setResponse.isFailure(), true);
-
- // verify if its not set
- const poResult2 = await pricerOstUsd.priceOracles(constants.currencyUSD);
- assert.equal(poResult2.isSuccess(), true);
- assert.equal(0x0, poResult2.data.priceOracles);
-
- });
-
-
- it('should fail when currency is blank', async function() {
-
- // set price oracle
- const response = await pricerOstUsd.setPriceOracle(
- constants.ops,
- constants.opsPassphrase,
- constants.currencyBlank,
- constants.priceOracles.OST.USD,
- constants.gasUsed,
- constants.optionsReceipt);
-
- // check if the response is failure
- assert.equal(response.isFailure(), true);
-
- });
-
-
- it('should fail when oracleAddress is 0', async function() {
-
- // set price oracle
- const response = await pricerOstUsd.setPriceOracle(
- constants.ops,
- constants.opsPassphrase,
- constants.currencyUSD,
- 0,
- constants.gasUsed,
- constants.optionsReceipt);
-
- // check if the response is failure
- assert.equal(response.isFailure(), true);
-
- });
-
-
- it('should fail when gas amount is 0', async function() {
-
- // set price oracle
- const response = await pricerOstUsd.setPriceOracle(
- constants.ops,
- constants.opsPassphrase,
- constants.currencyUSD,
- constants.priceOracles.OST.USD,
- 0,
- constants.optionsReceipt);
-
- // check if the response is failure
- assert.equal(response.isFailure(), true);
-
- });
-
-
- it('should fail when sender address is 0', async function() {
-
- // set price oracle
- const response = await pricerOstUsd.setPriceOracle(
- 0,
- constants.opsPassphrase,
- constants.currencyUSD,
- constants.priceOracles.OST.USD,
- constants.gasUsed,
- constants.optionsReceipt);
-
- // check if the response is failure
- assert.equal(response.isFailure(), true);
-
- });
-
-
- it('should fail when price oracle has different quote currency', async function() {
- // eslint-disable-next-line no-invalid-this
- this.timeout(100000);
-
- // set price oracle
- const response = await pricerOstUsd.setPriceOracle(
- constants.ops,
- constants.opsPassphrase,
- constants.currencyUSD,
- constants.priceOracles.ETH.USD,
- constants.gasUsed,
- constants.optionsReceipt);
-
- // check if the response is failure
- assert.equal(response.isFailure(), true);
-
- // verify if its not set
- const poResult = await pricerOstUsd.priceOracles(constants.currencyUSD);
- assert.equal(poResult.isSuccess(), true);
- assert.notEqual(poResult.data.priceOracles, constants.priceOracles.ETH.USD);
-
- });
-
-
- it('should fail when price oracle has different decimal', async function() {
- // eslint-disable-next-line no-invalid-this
- this.timeout(100000);
-
- // set price oracle
- const response = await pricerOstUsd10Decimal.setPriceOracle(
- constants.ops,
- constants.opsPassphrase,
- constants.currencyUSD,
- constants.priceOracles.OST.USD,
- constants.gasUsed,
- constants.optionsReceipt);
-
- // check if the response is failure
- assert.equal(response.isFailure(), true);
-
- // verify if its not set
- const poResult = await pricerOstUsd.priceOracles(constants.currencyUSD);
- assert.equal(poResult.isSuccess(), true);
- assert.equal(poResult.data.priceOracles, 0x0);
-
- });
-
-
- it('should pass when OST/USD price oracle is set', async function() {
- // eslint-disable-next-line no-invalid-this
- this.timeout(100000);
-
- // set price oracle
- const response = await pricerOstUsd.setPriceOracle(
- constants.ops,
- constants.opsPassphrase,
- constants.currencyUSD,
- constants.priceOracles.OST.USD,
- constants.gasUsed,
- constants.optionsReceipt);
-
- // verify if the transaction receipt is valid
- utils.verifyTransactionReceipt(response);
-
- // verify if the transaction has was actually mined
- await utils.verifyIfMined(pricerOstUsd, response.data.transaction_hash);
-
- // verify if its set
- const poResult = await pricerOstUsd.priceOracles(constants.currencyUSD);
- assert.equal(poResult.isSuccess(), true);
- assert.equal(poResult.data.priceOracles, constants.priceOracles.OST.USD);
-
- });
-
-
- it('should pass when OST/EUR price oracle is set', async function() {
- // eslint-disable-next-line no-invalid-this
- this.timeout(100000);
-
- // set price oracle
- const response = await pricerOstUsd.setPriceOracle(
- constants.ops,
- constants.opsPassphrase,
- constants.currencyEUR,
- constants.priceOracles.OST.EUR,
- constants.gasUsed,
- constants.optionsReceipt);
-
- // verify if the transaction receipt is valid
- utils.verifyTransactionReceipt(response);
-
- // verify if the transaction has was actually mined
- await utils.verifyIfMined(pricerOstUsd, response.data.transaction_hash);
-
- // verify if its set
- const poResult = await pricerOstUsd.priceOracles(constants.currencyEUR);
- assert.equal(poResult.isSuccess(), true);
- assert.equal(poResult.data.priceOracles, constants.priceOracles.OST.EUR);
-
- });
-
-
- it('should pass for interaction layer test when return type is uuid', async function() {
-
- // eslint-disable-next-line no-invalid-this
- this.timeout(100000);
-
- // set price oracle
- const response = await pricerOstUsd.setPriceOracle(
- constants.ops,
- constants.opsPassphrase,
- constants.currencyEUR,
- constants.priceOracles.OST.EUR,
- constants.gasUsed,
- constants.optionsUUID);
-
- // verify if the transaction receipt is valid
- // we will not verify if it got mined as its just interaction layer testing
- utils.verifyTransactionUUID(response);
-
- });
-
- it('should pass for interaction layer test when return type is txHash', async function() {
-
- // eslint-disable-next-line no-invalid-this
- this.timeout(100000);
-
- // set price oracle
- const response = await pricerOstUsd.setPriceOracle(
- constants.ops,
- constants.opsPassphrase,
- constants.currencyEUR,
- constants.priceOracles.OST.EUR,
- constants.gasUsed,
- constants.optionsHash);
-
- // verify if the transaction hash is valid
- // we will not verify if it got mined as its just interaction layer testing
- utils.verifyTransactionHash(response);
-
- });
-
- it('should pass for interaction layer test when return type is txReceipt', async function() {
-
- // eslint-disable-next-line no-invalid-this
- this.timeout(100000);
-
- // set price oracle
- const response = await pricerOstUsd.setPriceOracle(
- constants.ops,
- constants.opsPassphrase,
- constants.currencyEUR,
- constants.priceOracles.OST.EUR,
- constants.gasUsed,
- constants.optionsReceipt);
-
- // verify if the transaction receipt is valid.
- // We will not check here if the value is really set as its just interaction layer testing.
- utils.verifyTransactionReceipt(response);
-
- });
-
-});
-
diff --git a/mocha_test/services/pricer/unset_price_oracle.js b/mocha_test/services/pricer/unset_price_oracle.js
deleted file mode 100644
index 013b2f7..0000000
--- a/mocha_test/services/pricer/unset_price_oracle.js
+++ /dev/null
@@ -1,254 +0,0 @@
-/* global describe, it */
-
-const chai = require('chai')
- , assert = chai.assert;
-
-const rootPrefix = "../../.."
- , constants = require(rootPrefix + '/mocha_test/lib/constants')
- , utils = require(rootPrefix+'/mocha_test/lib/utils')
- , pricer = require(rootPrefix + '/lib/contract_interact/pricer')
- , pricerOstUsd = new pricer(constants.pricerOstUsdAddress, constants.chainId)
-;
-
-
-describe('Unset price oracle', function() {
-
- it('should pass the initial address checks', function() {
- assert.isDefined(constants.deployer);
- assert.isDefined(constants.ops);
- assert.isDefined(constants.account1);
- assert.notEqual(constants.deployer, constants.ops);
- assert.notEqual(constants.deployer, constants.account1);
- assert.notEqual(constants.ops, constants.account1);
- });
-
- it('should fail when sender is not ops', async function() {
- // eslint-disable-next-line no-invalid-this
- this.timeout(100000);
-
- // set the price oracle
- const response = await pricerOstUsd.setPriceOracle(
- constants.ops,
- constants.opsPassphrase,
- constants.currencyUSD,
- constants.priceOracles.OST.USD,
- constants.gasUsed,
- constants.optionsReceipt);
-
- // verify if the transaction receipt is valid
- utils.verifyTransactionReceipt(response);
-
- // verify if the transaction has was actually mined
- await utils.verifyIfMined(pricerOstUsd, response.data.transaction_hash);
-
- // verify if value is changed
- const poResult1 = await pricerOstUsd.priceOracles(constants.currencyUSD);
- assert.equal(poResult1.isSuccess(), true);
- assert.equal(poResult1.data.priceOracles, constants.priceOracles.OST.USD);
-
- // unset the price oracle
- const response2 = await pricerOstUsd.unsetPriceOracle(
- constants.deployer,
- constants.deployerPassphrase,
- constants.currencyUSD,
- constants.gasUsed,
- constants.optionsReceipt);
-
- // verify if it failed
- assert.equal(response2.isFailure(), true);
-
- // verify if value is changed
- const poResult2 = await pricerOstUsd.priceOracles(constants.currencyUSD);
- assert.equal(poResult2.isSuccess(), true);
- assert.equal(poResult2.data.priceOracles, constants.priceOracles.OST.USD);
-
- });
-
-
- it('should fail when currency is blank', async function() {
-
- // unset the price oracle
- const response = await pricerOstUsd.unsetPriceOracle(
- constants.ops,
- constants.opsPassphrase,
- constants.currencyBlank,
- constants.gasUsed,
- constants.optionsReceipt);
-
- // verify if it failed
- assert.equal(response.isFailure(), true);
-
- });
-
-
- it('should fail when gas amount is 0', async function() {
-
- // unset the price oracle
- const response = await pricerOstUsd.unsetPriceOracle(
- constants.ops,
- constants.opsPassphrase,
- constants.currencyUSD,
- 0,
- constants.optionsReceipt);
-
- // verify if it failed
- assert.equal(response.isFailure(), true);
-
- });
-
- it('should fail when sender address is 0', async function() {
-
- // unset the price oracle
- const response = await pricerOstUsd.unsetPriceOracle(
- 0,
- constants.opsPassphrase,
- constants.currencyUSD,
- constants.gasUsed,
- constants.optionsReceipt);
-
- // verify if it failed
- assert.equal(response.isFailure(), true);
-
- });
-
- // it('should fail when price oracle was not set prior', async function() {
- // this.timeout(100000);
- // const result = await pricerOstUsd.unsetPriceOracle(
- // constants.ops,
- // constants.opsPassphrase,
- // constants.currencyINR,
- // constants.gasUsed);
- // const poResult = await pricerOstUsd.priceOracles(constants.currencyINR);
- // assert.equal(poResult, 0x0);
- // });
-
-
- it('should pass when price oracle was set prior', async function() {
- // eslint-disable-next-line no-invalid-this
- this.timeout(200000);
-
- // set the price oracle
- const setResponse = await pricerOstUsd.setPriceOracle(
- constants.ops,
- constants.opsPassphrase,
- constants.currencyUSD,
- constants.priceOracles.OST.USD,
- constants.gasUsed,
- constants.optionsReceipt);
-
- // verify if the transaction receipt is valid
- utils.verifyTransactionReceipt(setResponse);
-
- // verify if the transaction has was actually mined
- await utils.verifyIfMined(pricerOstUsd, setResponse.data.transaction_hash);
-
- // verify if value is changed
- const poResult1 = await pricerOstUsd.priceOracles(constants.currencyUSD);
- assert.equal(poResult1.isSuccess(), true);
- assert.equal(poResult1.data.priceOracles, constants.priceOracles.OST.USD);
-
- // unset the price oracle
- const unsetResponse = await pricerOstUsd.unsetPriceOracle(
- constants.ops,
- constants.opsPassphrase,
- constants.currencyUSD,
- constants.gasUsed,
- constants.optionsReceipt);
-
- // verify if the transaction receipt is valid
- utils.verifyTransactionReceipt(unsetResponse);
-
- // verify if the transaction has was actually mined
- await utils.verifyIfMined(pricerOstUsd, unsetResponse.data.transaction_hash);
-
- // verify if value is changed
- const poResult2 = await pricerOstUsd.priceOracles(constants.currencyUSD);
- assert.equal(poResult2.isSuccess(), true);
- assert.equal(poResult2.data.priceOracles, 0x0);
-
- });
-
-
- it('should pass for interaction layer test when return type is uuid', async function() {
-
- // eslint-disable-next-line no-invalid-this
- this.timeout(100000);
-
- // unset the price oracle
- const unsetResponse = await pricerOstUsd.unsetPriceOracle(
- constants.ops,
- constants.opsPassphrase,
- constants.currencyUSD,
- constants.gasUsed,
- constants.optionsUUID);
-
- // verify if the transaction receipt is valid
- // we will not verify if it got mined as its just interaction layer testing
- utils.verifyTransactionUUID(unsetResponse);
-
- });
-
- it('should pass for interaction layer test when return type is txHash', async function() {
-
- // eslint-disable-next-line no-invalid-this
- this.timeout(100000);
-
- // unset the price oracle
- const unsetResponse = await pricerOstUsd.unsetPriceOracle(
- constants.ops,
- constants.opsPassphrase,
- constants.currencyUSD,
- constants.gasUsed,
- constants.optionsHash);
-
- // verify if the transaction hash is valid
- // we will not verify if it got mined as its just interaction layer testing
- utils.verifyTransactionHash(unsetResponse);
-
- });
-
- it('should pass for interaction layer test when return type is txReceipt', async function() {
-
- // eslint-disable-next-line no-invalid-this
- this.timeout(100000);
-
- // set the price oracle
- const setResponse = await pricerOstUsd.setPriceOracle(
- constants.ops,
- constants.opsPassphrase,
- constants.currencyUSD,
- constants.priceOracles.OST.USD,
- constants.gasUsed,
- constants.optionsReceipt);
-
- // verify if the transaction receipt is valid
- utils.verifyTransactionReceipt(setResponse);
-
- // verify if the transaction has was actually mined
- await utils.verifyIfMined(pricerOstUsd, setResponse.data.transaction_hash);
-
- // verify if value is changed
- const poResult1 = await pricerOstUsd.priceOracles(constants.currencyUSD);
- assert.equal(poResult1.isSuccess(), true);
- assert.equal(poResult1.data.priceOracles, constants.priceOracles.OST.USD);
-
- // eslint-disable-next-line no-invalid-this
- this.timeout(100000);
-
- // unset the price oracle
- const unsetResponse = await pricerOstUsd.unsetPriceOracle(
- constants.ops,
- constants.opsPassphrase,
- constants.currencyUSD,
- constants.gasUsed,
- constants.optionsReceipt);
-
- // verify if the transaction receipt is valid.
- // We will not check here if the value is really set as its just interaction layer testing.
- utils.verifyTransactionReceipt(unsetResponse);
-
- });
-
-});
-
-
diff --git a/mocha_test/services/workers/_is_worker.js b/mocha_test/services/workers/_is_worker.js
deleted file mode 100644
index 215aa94..0000000
--- a/mocha_test/services/workers/_is_worker.js
+++ /dev/null
@@ -1,33 +0,0 @@
-/* global describe, it */
-
-const chai = require('chai')
- , assert = chai.assert;
-
-const rootPrefix = "../../.."
- , constants = require(rootPrefix + '/mocha_test/lib/constants')
- , openstPayment = require(rootPrefix + '/index')
- , IsWorkerKlass = openstPayment.services.workers.isWorker
- , apiErrorConfig = require(rootPrefix + '/config/api_error_config')
-;
-
-describe('Is worker', function() {
- // Success mode is tested in `set_worker.js`
-
- it('should fail when worker address is not valid', async function() {
-
- // eslint-disable-next-line no-invalid-this
- this.timeout(100000);
-
- const IsWorkerObject = new IsWorkerKlass({
- workers_contract_address: constants.workersContractAddress,
- worker_address: 0,
- chain_id: constants.chainId
- });
- const response = await IsWorkerObject.perform();
-
- // confirm failure reponse and message
- assert.equal(response.isFailure(), true);
- assert.equal(response.toHash().err.msg, apiErrorConfig['invalid_api_params'].message);
-
- });
-});
diff --git a/mocha_test/services/workers/_remove_worker.js b/mocha_test/services/workers/_remove_worker.js
deleted file mode 100644
index 2033c29..0000000
--- a/mocha_test/services/workers/_remove_worker.js
+++ /dev/null
@@ -1,162 +0,0 @@
-/* global describe, it */
-
-const chai = require('chai')
- , assert = chai.assert;
-
-const rootPrefix = "../../.."
- , constants = require(rootPrefix + '/mocha_test/lib/constants')
- , utils = require(rootPrefix+'/mocha_test/lib/utils')
- , workersModule = require(rootPrefix + '/lib/contract_interact/workers')
- , workers = new workersModule(constants.workersContractAddress, constants.chainId)
- , apiErrorConfig = require(rootPrefix + '/config/api_error_config')
-;
-
-describe('Remove worker', function() {
-
- it('should pass the initial address checks', function() {
-
- assert.isDefined(constants.deployer);
- assert.isDefined(constants.ops);
- assert.notEqual(constants.deployer, constants.ops);
-
- });
-
- it('should fail when gasPrice is null', async function() {
-
- // eslint-disable-next-line no-invalid-this
- this.timeout(100000);
-
- // set worker
- const response = await workers.removeWorker(
- constants.ops,
- constants.opsPassphrase,
- constants.workerAccount1,
- 0,
- constants.optionsReceipt);
-
- // confirm failure reponse and message
- assert.equal(response.isFailure(), true);
- assert.equal(response.toHash().err.msg, apiErrorConfig['invalid_api_params'].message);
-
- });
-
- it('should fail when senderAddress is not valid', async function() {
-
- // eslint-disable-next-line no-invalid-this
- this.timeout(100000);
-
- // set worker
- const response = await workers.removeWorker(
- 0,
- constants.opsPassphrase,
- constants.workerAccount1,
- constants.gasUsed,
- constants.optionsReceipt);
-
- // confirm failure reponse and message
- assert.equal(response.isFailure(), true);
- assert.equal(response.toHash().err.msg, apiErrorConfig['invalid_api_params'].message);
-
- });
-
- it('should fail when workerAddress is not valid', async function() {
-
- // eslint-disable-next-line no-invalid-this
- this.timeout(100000);
-
- // set worker
- const response = await workers.removeWorker(
- constants.ops,
- constants.opsPassphrase,
- 0,
- constants.gasUsed,
- constants.optionsReceipt);
-
- // confirm failure reponse and message
- assert.equal(response.isFailure(), true);
- assert.equal(response.toHash().err.msg, apiErrorConfig['invalid_api_params'].message);
-
- });
-
- it('should succeed', async function() {
-
- // eslint-disable-next-line no-invalid-this
- this.timeout(100000);
-
- // set worker
- const response = await workers.removeWorker(
- constants.ops,
- constants.opsPassphrase,
- constants.workerAccount1,
- constants.gasUsed,
- constants.optionsReceipt);
-
- // verify if the transaction receipt is valid
- utils.verifyTransactionReceipt(response);
-
- // verify if the transaction has was actually mined
- await utils.verifyIfMined(workers, response.data.transaction_hash);
-
- // confirm that worker is not a worker
- const isWorkerAfter = await workers.isWorker(constants.workerAccount1);
- assert.equal(isWorkerAfter.isSuccess(), true);
- assert.equal(isWorkerAfter.data.isValid, false);
-
- });
-
- it('should pass for interaction layer test when return type is uuid', async function() {
-
- // eslint-disable-next-line no-invalid-this
- this.timeout(100000);
-
- // set worker
- const response = await workers.removeWorker(
- constants.ops,
- constants.opsPassphrase,
- constants.workerAccount1,
- constants.gasUsed,
- constants.optionsUUID);
-
- // verify transaction UUID
- // we will not verify if it got mined as its just interaction layer testing
- utils.verifyTransactionUUID(response);
-
- });
-
- it('should pass for interaction layer test when return type is txHash', async function() {
-
- // eslint-disable-next-line no-invalid-this
- this.timeout(100000);
-
- // set worker
- const response = await workers.removeWorker(
- constants.ops,
- constants.opsPassphrase,
- constants.workerAccount1,
- constants.gasUsed,
- constants.optionsHash);
-
- // verify transaction hash
- utils.verifyTransactionHash(response);
-
- });
-
- it('should pass for interaction layer test when return type is txReceipt', async function() {
-
- // eslint-disable-next-line no-invalid-this
- this.timeout(100000);
-
- // set worker
- const response = await workers.removeWorker(
- constants.ops,
- constants.opsPassphrase,
- constants.workerAccount1,
- constants.gasUsed,
- constants.optionsReceipt);
-
- // verify transaction receipt
- utils.verifyTransactionReceipt(response);
-
- });
-
-});
diff --git a/mocha_test/services/workers/_set_worker.js b/mocha_test/services/workers/_set_worker.js
deleted file mode 100644
index ee25764..0000000
--- a/mocha_test/services/workers/_set_worker.js
+++ /dev/null
@@ -1,348 +0,0 @@
-/* global describe, it */
-
-const chai = require('chai')
- , assert = chai.assert;
-
-const rootPrefix = "../../.."
- , constants = require(rootPrefix + '/mocha_test/lib/constants')
- , BigNumber = require('bignumber.js')
- , utils = require(rootPrefix+'/mocha_test/lib/utils')
- , web3Provider = require(rootPrefix + '/lib/web3/providers/ws')
- , openstPayment = require(rootPrefix + '/index')
- , SetWorkerKlass = openstPayment.services.workers.setWorker
- , IsWorkerKlass = openstPayment.services.workers.isWorker
- , apiErrorConfig = require(rootPrefix + '/config/api_error_config')
-;
-
-describe('Set worker', function() {
-
- it('should pass the initial address checks', function() {
-
- assert.isDefined(constants.deployer);
- assert.isDefined(constants.ops);
- assert.isDefined(constants.account1);
-
- });
-
- it('should fail when gasPrice is null', async function() {
-
- // eslint-disable-next-line no-invalid-this
- this.timeout(100000);
-
- const currentBlockNumber = await web3Provider.eth.getBlockNumber()
- , deactivationHeight = new BigNumber(currentBlockNumber).plus(10000)
- ;
-
- // set worker
- var SetWorkerObject = new SetWorkerKlass({
- workers_contract_address: constants.workersContractAddress,
- sender_address: constants.ops,
- sender_passphrase: constants.opsPassphrase,
- worker_address: constants.workerAccount1,
- deactivation_height: deactivationHeight.toString(10),
- gas_price: 0,
- chain_id: constants.chainId,
- options: constants.optionsReceipt
- });
- const response = await SetWorkerObject.perform();
-
- // confirm failure reponse and message
- assert.equal(response.isFailure(), true);
- assert.equal(response.toHash().err.msg, apiErrorConfig['invalid_api_params'].message);
-
- });
-
- it('should fail when senderAddress is not valid', async function() {
-
- // eslint-disable-next-line no-invalid-this
- this.timeout(100000);
-
- const currentBlockNumber = await web3Provider.eth.getBlockNumber()
- , deactivationHeight = new BigNumber(currentBlockNumber).plus(10000)
- ;
-
- // set worker
- var SetWorkerObject = new SetWorkerKlass({
- workers_contract_address: constants.workersContractAddress,
- sender_address: 0,
- sender_passphrase: constants.opsPassphrase,
- worker_address: constants.workerAccount1,
- deactivation_height: deactivationHeight.toString(10),
- gas_price: constants.gasUsed,
- chain_id: constants.chainId,
- options: constants.optionsReceipt
- });
- const response = await SetWorkerObject.perform();
- // confirm failure reponse and message
- assert.equal(response.isFailure(), true);
- assert.equal(response.toHash().err.msg, apiErrorConfig['invalid_api_params'].message);
-
- });
-
- it('should fail when workerAddress is not valid', async function() {
-
- // eslint-disable-next-line no-invalid-this
- this.timeout(100000);
-
- const currentBlockNumber = await web3Provider.eth.getBlockNumber()
- , deactivationHeight = new BigNumber(currentBlockNumber).plus(10000)
- ;
-
- // set worker
- var SetWorkerObject = new SetWorkerKlass({
- workers_contract_address: constants.workersContractAddress,
- sender_address: constants.ops,
- sender_passphrase: constants.opsPassphrase,
- worker_address: 0,
- deactivation_height: deactivationHeight.toString(10),
- gas_price: constants.gasUsed,
- chain_id: constants.chainId,
- options: constants.optionsReceipt
- });
- const response = await SetWorkerObject.perform();
-
- // confirm failure reponse and message
- assert.equal(response.isFailure(), true);
- assert.equal(response.toHash().err.msg, apiErrorConfig['invalid_api_params'].message);
-
- });
-
- it('should fail when deactivationHeight is not present', async function() {
-
- // eslint-disable-next-line no-invalid-this
- this.timeout(100000);
-
- const currentBlockNumber = await web3Provider.eth.getBlockNumber()
- , deactivationHeight = new BigNumber(currentBlockNumber).plus(10000)
- ;
-
- // set worker
- var SetWorkerObject = new SetWorkerKlass({
- workers_contract_address: constants.workersContractAddress,
- sender_address: constants.ops,
- sender_passphrase: constants.opsPassphrase,
- worker_address: constants.workerAccount1,
- deactivation_height: null,
- gas_price: constants.gasUsed,
- chain_id: constants.chainId,
- options: constants.optionsReceipt
- });
- const response = await SetWorkerObject.perform();
-
- // confirm failure reponse and message
- assert.equal(response.isFailure(), true);
- assert.equal(response.toHash().err.msg, apiErrorConfig['invalid_api_params'].message);
-
- });
-
- it('should fail when deactivationHeight is not a number', async function() {
-
- // eslint-disable-next-line no-invalid-this
- this.timeout(100000);
-
- const currentBlockNumber = await web3Provider.eth.getBlockNumber()
- , deactivationHeight = new BigNumber(currentBlockNumber).plus(10000)
- ;
-
- // set worker
- var SetWorkerObject = new SetWorkerKlass({
- workers_contract_address: constants.workersContractAddress,
- sender_address: constants.ops,
- sender_passphrase: constants.opsPassphrase,
- worker_address: constants.workerAccount1,
- deactivation_height: 'NaN',
- gas_price: constants.gasUsed,
- chain_id: constants.chainId,
- options: constants.optionsReceipt
- });
- const response = await SetWorkerObject.perform();
- // confirm failure reponse and message
- assert.equal(response.isFailure(), true);
- assert.equal(response.toHash().err.msg, apiErrorConfig['invalid_api_params'].message);
-
- });
-
- it('should fail when deactivationHeight is less than 0', async function() {
-
- // eslint-disable-next-line no-invalid-this
- this.timeout(100000);
-
- const currentBlockNumber = await web3Provider.eth.getBlockNumber()
- , deactivationHeight = new BigNumber(currentBlockNumber).plus(10000)
- ;
-
- // set worker
- var SetWorkerObject = new SetWorkerKlass({
- workers_contract_address: constants.workersContractAddress,
- sender_address: constants.ops,
- sender_passphrase: constants.opsPassphrase,
- worker_address: constants.workerAccount1,
- deactivation_height: -1,
- gas_price: constants.gasUsed,
- chain_id: constants.chainId,
- options: constants.optionsReceipt
- });
- const response = await SetWorkerObject.perform();
- // confirm failure reponse and message
- assert.equal(response.isFailure(), true);
- assert.equal(response.toHash().err.msg, apiErrorConfig['invalid_api_params'].message);
-
- });
-
- it('should fail when deactivationHeight is not an integer', async function() {
-
- // eslint-disable-next-line no-invalid-this
- this.timeout(100000);
-
- const currentBlockNumber = await web3Provider.eth.getBlockNumber()
- , deactivationHeight = new BigNumber(currentBlockNumber).plus(10000)
- ;
-
- // set worker
- var SetWorkerObject = new SetWorkerKlass({
- workers_contract_address: constants.workersContractAddress,
- sender_address: constants.ops,
- sender_passphrase: constants.opsPassphrase,
- worker_address: constants.workerAccount1,
- deactivation_height: 0.1,
- gas_price: constants.gasUsed,
- chain_id: constants.chainId,
- options: constants.optionsReceipt
- });
- const response = await SetWorkerObject.perform();
- // confirm failure reponse and message
- assert.equal(response.isFailure(), true);
- assert.equal(response.toHash().err.msg, apiErrorConfig['invalid_api_params'].message);
-
- });
-
- it('should succeed', async function() {
-
- // eslint-disable-next-line no-invalid-this
- this.timeout(100000);
-
- const currentBlockNumber = await web3Provider.eth.getBlockNumber()
- , deactivationHeight = new BigNumber(currentBlockNumber).plus(10000)
- ;
-
- // confirm that worker is not a worker
- var IsWorkerObject = new IsWorkerKlass({
- workers_contract_address: constants.workersContractAddress,
- worker_address: constants.workerAccount1,
- chain_id: constants.chainId
- });
- const isWorkerBefore = await IsWorkerObject.perform();
- assert.equal(isWorkerBefore.isSuccess(), true);
- assert.equal(isWorkerBefore.data.isValid, false);
-
- // set worker
- var SetWorkerObject = new SetWorkerKlass({
- workers_contract_address: constants.workersContractAddress,
- sender_address: constants.ops,
- sender_passphrase: constants.opsPassphrase,
- worker_address: constants.workerAccount1,
- deactivation_height: deactivationHeight.toString(10),
- gas_price: constants.gasUsed,
- chain_id: constants.chainId,
- options: constants.optionsReceipt
- });
- const response = await SetWorkerObject.perform();
-
- // verify if the transaction receipt is valid
- utils.verifyTransactionReceipt(response);
-
- // confirm that worker is a worker
- var IsWorkerObject = new IsWorkerKlass({
- workers_contract_address: constants.workersContractAddress,
- worker_address: constants.workerAccount1,
- chain_id: constants.chainId
- });
- const isWorkerAfter = await IsWorkerObject.perform();
- assert.equal(isWorkerAfter.isSuccess(), true);
- assert.equal(isWorkerAfter.data.isValid, true);
-
- });
-
- it('should pass interaction layer test when return type is uuid', async function() {
-
- // eslint-disable-next-line no-invalid-this
- this.timeout(100000);
-
- const currentBlockNumber = await web3Provider.eth.getBlockNumber()
- , deactivationHeight = new BigNumber(currentBlockNumber).plus(10000)
- ;
-
- // set worker
- var SetWorkerObject = new SetWorkerKlass({
- workers_contract_address: constants.workersContractAddress,
- sender_address: constants.ops,
- sender_passphrase: constants.opsPassphrase,
- worker_address: constants.workerAccount1,
- deactivation_height: deactivationHeight.toString(10),
- gas_price: constants.gasUsed,
- chain_id: constants.chainId,
- options: constants.optionsUUID
- });
- const response = await SetWorkerObject.perform();
-
- // verify transaction UUID
- // we will not verify if it got mined as its just interaction layer testing
- utils.verifyTransactionUUID(response);
-
- });
-
- it('should pass interaction layer test when return type is txHash', async function() {
-
- // eslint-disable-next-line no-invalid-this
- this.timeout(100000);
-
- const currentBlockNumber = await web3Provider.eth.getBlockNumber()
- , deactivationHeight = new BigNumber(currentBlockNumber).plus(10000)
- ;
-
- // set worker
- var SetWorkerObject = new SetWorkerKlass({
- workers_contract_address: constants.workersContractAddress,
- sender_address: constants.ops,
- sender_passphrase: constants.opsPassphrase,
- worker_address: constants.workerAccount1,
- deactivation_height: deactivationHeight.toString(10),
- gas_price: constants.gasUsed,
- chain_id: constants.chainId,
- options: constants.optionsHash
- });
- const response = await SetWorkerObject.perform();
-
- // verify transaction hash
- utils.verifyTransactionHash(response);
-
- });
-
- it('should pass interaction layer test when return type is txReceipt', async function() {
-
- // eslint-disable-next-line no-invalid-this
- this.timeout(100000);
-
- const currentBlockNumber = await web3Provider.eth.getBlockNumber()
- , deactivationHeight = new BigNumber(currentBlockNumber).plus(10000)
- ;
-
- // set worker
- var SetWorkerObject = new SetWorkerKlass({
- workers_contract_address: constants.workersContractAddress,
- sender_address: constants.ops,
- sender_passphrase: constants.opsPassphrase,
- worker_address: constants.workerAccount1,
- deactivation_height: deactivationHeight.toString(10),
- gas_price: constants.gasUsed,
- chain_id: constants.chainId,
- options: constants.optionsReceipt
- });
- const response = await SetWorkerObject.perform();
-
- // verify transaction receipt
- utils.verifyTransactionReceipt(response);
-
- });
-
-});
diff --git a/mocha_test/services/workers/remove.js b/mocha_test/services/workers/remove.js
deleted file mode 100644
index 2dbd08a..0000000
--- a/mocha_test/services/workers/remove.js
+++ /dev/null
@@ -1,137 +0,0 @@
-/* global describe, it */
-
-const chai = require('chai')
- , assert = chai.assert;
-
-const rootPrefix = "../../.."
- , constants = require(rootPrefix + '/mocha_test/lib/constants')
- , utils = require(rootPrefix+'/mocha_test/lib/utils')
- , workersModule = require(rootPrefix + '/lib/contract_interact/workers')
- , workers = new workersModule(constants.workersContractAddress, constants.chainId)
- , web3Provider = require(rootPrefix + '/lib/web3/providers/ws')
- , apiErrorConfig = require(rootPrefix + '/config/api_error_config')
-;
-
-describe('Remove', function() {
-
- it('should pass the initial address checks', function() {
-
- assert.isDefined(constants.deployer);
- assert.isDefined(constants.ops);
- assert.notEqual(constants.deployer, constants.ops);
-
- });
-
- it('should fail when gasPrice is null', async function() {
-
- // eslint-disable-next-line no-invalid-this
- this.timeout(100000);
-
- // set worker
- const response = await workers.remove(
- constants.ops,
- constants.opsPassphrase,
- 0,
- constants.optionsReceipt);
-
- // confirm failure reponse and message
- assert.equal(response.isFailure(), true);
- assert.equal(response.toHash().err.msg, apiErrorConfig['invalid_api_params'].message);
-
- });
-
- it('should fail when senderAddress is not valid', async function() {
-
- // eslint-disable-next-line no-invalid-this
- this.timeout(100000);
-
- // set worker
- const response = await workers.remove(
- 0,
- constants.opsPassphrase,
- constants.gasUsed,
- constants.optionsReceipt);
-
- // confirm failure reponse and message
- assert.equal(response.isFailure(), true);
- assert.equal(response.toHash().err.msg, apiErrorConfig['invalid_api_params'].message);
-
- });
-
- it('should succeed', async function() {
-
- // eslint-disable-next-line no-invalid-this
- this.timeout(100000);
-
- // set worker
- const response = await workers.remove(
- constants.ops,
- constants.opsPassphrase,
- constants.gasUsed,
- constants.optionsReceipt);
-
- // verify if the transaction receipt is valid
- utils.verifyTransactionReceipt(response);
-
- // verify if the transaction has was actually mined
- await utils.verifyIfMined(workers, response.data.transaction_hash);
-
- // confirm worker address has no code
- const getCodeResult = await web3Provider.eth.getCode(constants.workersContractAddress);
- assert.equal(getCodeResult, '0x');
-
- });
-
- it('should pass for interaction layer test when return type is uuid', async function() {
-
- // eslint-disable-next-line no-invalid-this
- this.timeout(100000);
-
- // set worker
- const response = await workers.remove(
- constants.ops,
- constants.opsPassphrase,
- constants.gasUsed,
- constants.optionsUUID);
-
- // verify transaction UUID
- // we will not verify if it got mined as its just interaction layer testing
- utils.verifyTransactionUUID(response);
-
- });
-
- it('should pass for interaction layer test when return type is txHash', async function() {
-
- // eslint-disable-next-line no-invalid-this
- this.timeout(100000);
-
- // set worker
- const response = await workers.remove(
- constants.ops,
- constants.opsPassphrase,
- constants.gasUsed,
- constants.optionsHash);
-
- // verify transaction hash
- utils.verifyTransactionHash(response);
-
- });
-
- it('should pass for interaction layer test when return type is txReceipt', async function() {
-
- // eslint-disable-next-line no-invalid-this
- this.timeout(100000);
-
- // set worker
- const response = await workers.remove(
- constants.ops,
- constants.opsPassphrase,
- constants.gasUsed,
- constants.optionsReceipt);
-
- // verify transaction receipt
- utils.verifyTransactionReceipt(response);
-
- });
-
-});
diff --git a/package.json b/package.json
index 4d8a433..f73b967 100644
--- a/package.json
+++ b/package.json
@@ -1,53 +1,36 @@
{
- "name": "@openstfoundation/openst-payments",
- "version": "1.0.8",
- "description": "Payment infrastructure on top of the OpenST network.",
+ "name": "@openstfoundation/openst-contracts",
+ "version": "1.0.0",
+ "description": "",
"keywords": [
"openst",
"OST",
- "simpletoken",
- "Payment"
+ "simpletoken"
],
"homepage": "https://openst.org",
"author": "OpenST Foundation Ltd.",
"license": "LGPL-3.0",
"repository": {
"type": "git",
- "url": "https://github.com/OpenSTFoundation/openst-payments.git"
+ "url": "https://github.com/OpenSTFoundation/openst-contracts.git"
},
"bugs": {
- "url": "https://github.com/OpenSTFoundation/openst-payments/issues"
- },
- "scripts": {
- "make-docs": "node_modules/.bin/jsdoc -c .jsdoc.json"
- },
- "dependencies": {
- "@openstfoundation/openst-base": "0.9.1",
- "@openstfoundation/openst-cache": "1.0.4",
- "@openstfoundation/openst-notification": "1.0.2",
- "@openstfoundation/openst-storage": "1.0.0",
- "bignumber.js": "4.1.0",
- "mustache": "2.3.0",
- "mysql": "2.14.1",
- "shortid": "2.2.8",
- "web3": "1.0.0-beta.33"
+ "url": "https://github.com/OpenSTFoundation/openst-contracts/issues"
},
+ "scripts": {},
"devDependencies": {
- "abi-decoder": "1.0.9",
- "eslint-config-google": "^0.9.1",
- "eslint-config-standard": "^11.0.0-beta.0",
- "eslint-plugin-import": "^2.8.0",
- "eslint-plugin-node": "^5.2.1",
- "eslint-plugin-promise": "^3.6.0",
- "eslint-plugin-standard": "^3.0.1",
- "ethereumjs-testrpc": "6.0.3",
- "ganache-cli": "6.0.3",
- "truffle": "^4.1.8",
- "ink-docstrap": "1.3.2",
- "jsdoc-route-plugin": "0.1.0",
- "jsdoc": "3.5.5",
- "mocha": "5.0.0",
- "solc": "0.4.19",
- "chai": "4.1.2"
+ "abi-decoder": "1.2.0",
+ "assert": "1.4.1",
+ "bignumber.js": "4.1.0",
+ "bn.js": "4.11.8",
+ "eslint": "5.5.0",
+ "eslint-config-airbnb-base": "13.1.0",
+ "eslint-plugin-import": "2.14.0",
+ "ethereumjs-util": "5.2.0",
+ "ganache-cli": "6.1.8",
+ "solc": "0.4.23",
+ "solidity-coverage": "0.5.11",
+ "truffle": "5.0.0-beta.0",
+ "web3": "1.0.0-beta.36"
}
}
diff --git a/services/airdrop_management/approve.js b/services/airdrop_management/approve.js
deleted file mode 100644
index d97b258..0000000
--- a/services/airdrop_management/approve.js
+++ /dev/null
@@ -1,230 +0,0 @@
-"use strict";
-
-/**
- *
- * This is a utility file which would be used for executing approve by airdrop budget holder.
- *
- * @module services/airdrop_management/approve
- *
- */
-
-const rootPrefix = '../..'
- , responseHelper = require(rootPrefix + '/lib/formatter/response')
- , airdropContractInteract = require(rootPrefix + '/lib/contract_interact/airdrop')
- , brandedTokenContractInteract = require(rootPrefix + '/lib/contract_interact/branded_token')
- , BigNumber = require('bignumber.js')
- , basicHelper = require(rootPrefix + '/helpers/basic_helper')
- , logger = require(rootPrefix + '/helpers/custom_console_logger')
- , AirdropModelCacheKlass = require(rootPrefix + '/lib/cache_management/airdrop_model')
- , paramErrorConfig = require(rootPrefix + '/config/param_error_config')
- , apiErrorConfig = require(rootPrefix + '/config/api_error_config')
-;
-
-const errorConfig = {
- param_error_config: paramErrorConfig,
- api_error_config: apiErrorConfig
-};
-
-/**
- * Constructor to create object of approve
- *
- * @constructor
- *
- * @param {object} params -
- * @param {string} params.airdrop_contract_address - airdrop contract address
- * @param {string} params.airdrop_budget_holder_passphrase - airdropBudgetHolder Passphrase
- * @param {string} params.gas_price - gas price
- * @param {number} params.chain_id - chain Id
- * @param {object} params.options - options
- *
- * @return {object}
- *
- */
-const ApproveKlass = function(params) {
- const oThis = this;
- params = params || {};
- logger.debug("=========Approve.params=========");
- // Don't log passphrase
- logger.debug(params.airdrop_contract_address, params.gas_price, params.chain_id, params.options);
- oThis.airdropContractAddress = params.airdrop_contract_address;
- oThis.airdropBudgetHolderPassphrase = params.airdrop_budget_holder_passphrase;
- oThis.gasPrice = params.gas_price;
- oThis.chainId = params.chain_id;
- oThis.options = params.options;
-
- oThis.airdropBudgetHolder = null;
- oThis.brandedTokenContractAddress = null;
- oThis.amount = null;
- oThis.brandedTokenObject = null;
-};
-
-ApproveKlass.prototype = {
-
- /**
- * Perform approve by airdrop budget holder to contract
- *
- * @return {promise}
- *
- */
- perform: async function () {
-
- const oThis = this;
-
- try {
- var r = null;
-
- r = await oThis.validateParams();
- logger.debug("\n=========Approve.validateParams.result=========");
- logger.debug(r);
- if(r.isFailure()) return r;
-
- r = oThis.doApprove();
- logger.debug("\n=========Approve.doApprove.result=========");
- logger.debug(r);
- return r;
- } catch(err) {
- let errorParams = {
- internal_error_identifier: 's_am_a_perform_1',
- api_error_identifier: 'unhandled_api_error',
- error_config: errorConfig,
- debug_options: { err: err }
- };
- logger.error(err.message);
- return responseHelper.error(errorParams)
- }
-
- },
-
- /**
- * Validate params
- *
- * @return {promise}
- *
- */
- validateParams: function(){
- const oThis = this;
- return new Promise(async function (onResolve, onReject) {
-
- if (!basicHelper.isAddressValid(oThis.airdropContractAddress)) {
- let errorParams = {
- internal_error_identifier: 's_am_a_validateParams_1',
- api_error_identifier: 'invalid_api_params',
- error_config: errorConfig,
- params_error_identifiers: ['airdrop_contract_address_invalid'],
- debug_options: {}
- };
- return onResolve(responseHelper.paramValidationError(errorParams));
- }
-
- // Check if airdropContractAddress is registered or not
- const airdropModelCacheObject = new AirdropModelCacheKlass({useObject: true, contractAddress: oThis.airdropContractAddress})
- , airdropModelCacheResponse = await airdropModelCacheObject.fetch()
- ;
- oThis.airdropRecord = airdropModelCacheResponse.data[oThis.airdropContractAddress];
- if (!oThis.airdropRecord){
- let errorParams = {
- internal_error_identifier: 's_am_a_validateParams_2',
- api_error_identifier: 'invalid_api_params',
- error_config: errorConfig,
- params_error_identifiers: ['unregistered_airdrop_contract'],
- debug_options: {}
- };
- return onResolve(responseHelper.paramValidationError(errorParams));
- }
-
- var airdropContractInteractObject = new airdropContractInteract(oThis.airdropContractAddress, oThis.chainId);
- var result = await airdropContractInteractObject.brandedToken();
- oThis.brandedTokenContractAddress = result.data.brandedToken;
- if (!basicHelper.isAddressValid(oThis.brandedTokenContractAddress)) {
- let errorParams = {
- internal_error_identifier: 's_am_a_validateParams_3',
- api_error_identifier: 'invalid_api_params',
- error_config: errorConfig,
- params_error_identifiers: ['branded_token_address_invalid'],
- debug_options: {}
- };
- return onResolve(responseHelper.paramValidationError(errorParams));
- }
-
- result = await airdropContractInteractObject.airdropBudgetHolder();
- oThis.airdropBudgetHolderAddress = result.data.airdropBudgetHolder;
- if (!basicHelper.isAddressValid(oThis.airdropBudgetHolderAddress)) {
- let errorParams = {
- internal_error_identifier: 's_am_a_validateParams_4',
- api_error_identifier: 'invalid_api_params',
- error_config: errorConfig,
- params_error_identifiers: ['airdrop_budget_holder_invalid'],
- debug_options: {}
- };
- return onResolve(responseHelper.paramValidationError(errorParams));
- }
-
- oThis.brandedTokenObject = new brandedTokenContractInteract(oThis.brandedTokenContractAddress, oThis.chainId);
- //result = await oThis.brandedTokenObject.getBalanceOf(oThis.airdropBudgetHolderAddress);
- oThis.amount = '250000000000000000000000'; //result.data.balance;
- const amountInBigNumber = new BigNumber(oThis.amount);
- if (amountInBigNumber.isNaN() || !amountInBigNumber.isInteger()){
- let errorParams = {
- internal_error_identifier: 's_am_a_validateParams_5',
- api_error_identifier: 'invalid_api_params',
- error_config: errorConfig,
- params_error_identifiers: ['invalid_amount'],
- debug_options: {}
- };
- return onResolve(responseHelper.paramValidationError(errorParams));
- }
-
- if (!basicHelper.isValidChainId(oThis.chainId)) {
- let errorParams = {
- internal_error_identifier: 's_am_a_validateParams_6',
- api_error_identifier: 'invalid_api_params',
- error_config: errorConfig,
- params_error_identifiers: ['invalid_chain_id'],
- debug_options: {}
- };
- return onResolve(responseHelper.paramValidationError(errorParams));
- }
-
- if (!oThis.gasPrice) {
- let errorParams = {
- internal_error_identifier: 's_am_a_validateParams_7',
- api_error_identifier: 'invalid_api_params',
- error_config: errorConfig,
- params_error_identifiers: ['gas_price_invalid'],
- debug_options: {}
- };
- return onResolve(responseHelper.paramValidationError(errorParams));
- }
-
- return onResolve(responseHelper.successWithData({}));
-
- });
-
- },
-
- /**
- * Perform Approve to airdrop budget holder
- *
- * @return {promise}
- *
- */
- doApprove: async function(){
- const oThis = this;
- return new Promise(async function (onResolve, onReject) {
- // Approve to budget holder
- const approveByBudgetHolderResponse = await oThis.brandedTokenObject.approveByBudgetHolder(oThis.airdropBudgetHolderAddress,
- oThis.airdropBudgetHolderPassphrase,
- oThis.airdropContractAddress,
- oThis.amount,
- oThis.gasPrice,
- oThis.options);
- logger.debug("\n=========Transfer.doApprove.response=========");
- logger.debug(approveByBudgetHolderResponse);
- return onResolve(approveByBudgetHolderResponse);
- });
-
- }
-
-};
-
-module.exports = ApproveKlass;
\ No newline at end of file
diff --git a/services/airdrop_management/batch_allocator.js b/services/airdrop_management/batch_allocator.js
deleted file mode 100644
index c0c032b..0000000
--- a/services/airdrop_management/batch_allocator.js
+++ /dev/null
@@ -1,353 +0,0 @@
-"use strict";
-
-/**
- *
- * This is a utility file which would be used for allocating amount to airdrop users.
- *
- * @module services/airdrop_management/batch_allocator
- *
- */
-
-const rootPrefix = '../..'
- , responseHelper = require(rootPrefix + '/lib/formatter/response')
- , userAirdropDetailKlass = require(rootPrefix + '/app/models/user_airdrop_detail')
- , airdropAllocationProofDetailKlass = require(rootPrefix + '/app/models/airdrop_allocation_proof_detail')
- , airdropConstants = require(rootPrefix + '/lib/global_constant/airdrop')
- , BigNumber = require('bignumber.js')
- , basicHelper = require(rootPrefix + '/helpers/basic_helper')
- , logger = require(rootPrefix + '/helpers/custom_console_logger')
- , userAirdropDetailCacheKlass = require(rootPrefix + '/lib/cache_multi_management/user_airdrop_detail')
- , AirdropModelCacheKlass = require(rootPrefix + '/lib/cache_management/airdrop_model')
- , paramErrorConfig = require(rootPrefix + '/config/param_error_config')
- , apiErrorConfig = require(rootPrefix + '/config/api_error_config')
-;
-
-const errorConfig = {
- param_error_config: paramErrorConfig,
- api_error_config: apiErrorConfig
-};
-
-/**
- * Constructor to create object of batch allocator
- *
- * @constructor
- *
- * @param {object} params -
- * @param {string} params.airdrop_contract_address - airdrop contract address
- * @param {string} params.transaction_hash - airdrop transfer transactio hash
- * @param {object} params.airdrop_users - {userAddress: {airdropAmount: amountInWei, expiryTimestamp: 0}}
- * @param {number} params.chain_id - chain ID
- *
- * @return {object}
- */
-const BatchAllocatorKlass = function(params) {
- const oThis = this;
- params = params || {};
- logger.debug("\n=========batchAllocator.params=========");
- logger.debug(params);
- oThis.airdropContractAddress = params.airdrop_contract_address;
- oThis.transactionHash = params.transaction_hash;
- oThis.airdropUsers = params.airdrop_users;
- oThis.chainId = params.chain_id;
-
- // New Variables
- oThis.airdropRecord = null;
- oThis.airdropAllocationProofDetailRecord = null;
- oThis.tableFields = ['user_address', 'airdrop_id', 'airdrop_amount', 'expiry_timestamp'];
- oThis.bulkInsertData = [];
- oThis.totalInputAirdropAmount = new BigNumber(0);
- oThis.totalAmountAfterAllocatingInputAmount = new BigNumber(0);
- oThis.userAddresses = [];
-};
-
-BatchAllocatorKlass.prototype = {
-
- /**
- * Perform batch allocation to airdrop users
- *
- * @return {promise}
- *
- */
- perform: async function () {
-
- const oThis = this;
-
- try {
-
- var r = null;
-
- r = await oThis.validateParams();
- logger.debug("\n=========batchAllocator.validateParams.result=========");
- logger.debug(r);
- if(r.isFailure()) return r;
-
- r = await oThis.allocateAirdropAmountToUsers();
- logger.debug("\n=========batchAllocator.allocateAirdropAmountToUsers.result=========");
- logger.debug(r);
- return r;
-
- } catch(err){
- let errorParams = {
- internal_error_identifier: 's_am_ba_perform_1',
- api_error_identifier: 'unhandled_api_error',
- error_config: errorConfig,
- debug_options: { err: err }
- };
- logger.error(err.message);
- return responseHelper.error(errorParams)
- }
- },
-
- /**
- * Validate params
- *
- * @return {promise}
- *
- */
- validateParams: function() {
- const oThis = this;
- return new Promise(async function (onResolve, onReject) {
-
- if (!basicHelper.isAddressValid(oThis.airdropContractAddress)) {
- let errorParams = {
- internal_error_identifier: 's_am_ba_validateParams_1',
- api_error_identifier: 'invalid_api_params',
- error_config: errorConfig,
- params_error_identifiers: ['airdrop_contract_address_invalid'],
- debug_options: {}
- };
- return onResolve(responseHelper.paramValidationError(errorParams));
- }
-
- if (!basicHelper.isTxHashValid(oThis.transactionHash)) {
- let errorParams = {
- internal_error_identifier: 's_am_ba_validateParams_2',
- api_error_identifier: 'invalid_api_params',
- error_config: errorConfig,
- params_error_identifiers: ['invalid_transaction_hash'],
- debug_options: {}
- };
- return onResolve(responseHelper.paramValidationError(errorParams));
- }
-
- // Check if airdropContractAddress is registered or not
- const airdropModelCacheObject = new AirdropModelCacheKlass({useObject: true, contractAddress: oThis.airdropContractAddress})
- , airdropModelCacheResponse = await airdropModelCacheObject.fetch()
- ;
- oThis.airdropRecord = airdropModelCacheResponse.data[oThis.airdropContractAddress];
- if (!oThis.airdropRecord) {
- let errorParams = {
- internal_error_identifier: 's_am_ba_validateParams_3',
- api_error_identifier: 'db_get_failed',
- error_config: errorConfig,
- debug_options: {}
- };
- return onResolve(responseHelper.error(errorParams));
- }
- var airdropAllocationProofDetailModel = new airdropAllocationProofDetailKlass();
- const result = await airdropAllocationProofDetailModel.getByTransactionHash(oThis.transactionHash);
- oThis.airdropAllocationProofDetailRecord = result[0];
- if (!oThis.airdropAllocationProofDetailRecord) {
- let errorParams = {
- internal_error_identifier: 's_am_ba_validateParams_4',
- api_error_identifier: 'db_get_failed',
- error_config: errorConfig,
- debug_options: {}
- };
- logger.error('%Error - Invalid transactionHash. Given airdropAllocationProofDetailRecord is not present in DB')
- return onResolve(responseHelper.error(errorParams));
- }
-
- if (new BigNumber(oThis.airdropAllocationProofDetailRecord.airdrop_allocated_amount).gte(new BigNumber(oThis.airdropAllocationProofDetailRecord.airdrop_amount))) {
- let errorParams = {
- internal_error_identifier: 's_am_ba_validateParams_5',
- api_error_identifier: 'invalid_amount',
- error_config: errorConfig,
- debug_options: {}
- };
- return onResolve(responseHelper.error(errorParams));
- }
-
- if(!oThis.airdropUsers || !(typeof oThis.airdropUsers === "object")) {
- let errorParams = {
- internal_error_identifier: 's_am_ba_validateParams_6',
- api_error_identifier: 'invalid_object',
- error_config: errorConfig,
- debug_options: {}
- };
- return onResolve(responseHelper.error(errorParams));
- }
-
- const batchSize = Object.keys(oThis.airdropUsers).length;
- if (batchSize > airdropConstants.batchSize()) {
- let errorParams = {
- internal_error_identifier: 's_am_ba_validateParams_7',
- api_error_identifier: 'airdrop_batch_size_exceeded',
- error_config: errorConfig,
- debug_options: { batchSize: batchSize }
- };
- return onResolve(responseHelper.error(errorParams));
- }
-
- var value = null
- , userAddress = ''
- , userAirdropAmount = 0
- , expiryTimestamp = 0
- , insertData = []
- ;
- for (var userAddress in oThis.airdropUsers) {
- value = oThis.airdropUsers[userAddress];
-
- if (!basicHelper.isAddressValid(userAddress)) {
- let errorParams = {
- internal_error_identifier: 's_am_ba_validateParams_8',
- api_error_identifier: 'invalid_api_params',
- error_config: errorConfig,
- params_error_identifiers: ['invalid_user_address'],
- debug_options: { userAddress: userAddress }
- };
- return onResolve(responseHelper.paramValidationError(errorParams));
- }
-
- userAirdropAmount = new BigNumber(value.airdropAmount);
- if (userAirdropAmount.isNaN() || !userAirdropAmount.isInteger()) {
- let errorParams = {
- internal_error_identifier: 's_am_ba_validateParams_9',
- api_error_identifier: 'invalid_api_params',
- error_config: errorConfig,
- params_error_identifiers: ['airdrop_amount_invalid'],
- debug_options: { userAddress: userAddress }
- };
- return onResolve(responseHelper.paramValidationError(errorParams));
- }
-
- if (userAirdropAmount.lte(0)) {
- let errorParams = {
- internal_error_identifier: 's_am_ba_validateParams_10',
- api_error_identifier: 'invalid_api_params',
- error_config: errorConfig,
- params_error_identifiers: ['airdrop_amount_invalid'],
- debug_options: { userAddress: userAddress }
- };
- return onResolve(responseHelper.paramValidationError(errorParams));
- }
-
- expiryTimestamp = new BigNumber(value.expiryTimestamp);
- if (expiryTimestamp.isNaN() || !expiryTimestamp.isInteger()) {
- let errorParams = {
- internal_error_identifier: 's_am_ba_validateParams_11',
- api_error_identifier: 'timestamp_invalid',
- error_config: errorConfig,
- debug_options: { userAddress: userAddress }
- };
- return onResolve(responseHelper.error(errorParams));
- }
-
- oThis.totalInputAirdropAmount = oThis.totalInputAirdropAmount.plus(userAirdropAmount);
- insertData = [
- userAddress,
- oThis.airdropRecord.id,
- userAirdropAmount.toString(10),
- expiryTimestamp.toNumber()
- ];
- oThis.userAddresses.push(userAddress);
- oThis.bulkInsertData.push(insertData);
- }
-
- // Calculate totalAmountToAllocate after adding input amount
- oThis.totalAmountAfterAllocatingInputAmount = (new BigNumber(oThis.airdropAllocationProofDetailRecord.airdrop_allocated_amount)).
- plus(oThis.totalInputAirdropAmount);
- const airdropAmountBigNumber = new BigNumber(oThis.airdropAllocationProofDetailRecord.airdrop_amount);
- if (oThis.totalAmountAfterAllocatingInputAmount.gt(airdropAmountBigNumber)) {
- let errorParams = {
- internal_error_identifier: 's_am_ba_validateParams_12',
- api_error_identifier: 'invalid_amount',
- error_config: errorConfig,
- debug_options: {}
- };
- return onResolve(responseHelper.error(errorParams));
- }
-
- if (!basicHelper.isValidChainId(oThis.chainId)) {
- let errorParams = {
- internal_error_identifier: 's_am_ba_validateParams_14',
- api_error_identifier: 'invalid_api_params',
- error_config: errorConfig,
- params_error_identifiers: ['invalid_chain_id'],
- debug_options: {}
- };
- return onResolve(responseHelper.paramValidationError(errorParams));
- }
-
- return onResolve(responseHelper.successWithData({}));
-
- });
-
- },
-
- /**
- * Allocate airdrop amount to users
- *
- * @return {promise}
- *
- */
- allocateAirdropAmountToUsers: async function() {
- const oThis = this;
-
- return new Promise(async function (onResolve, onReject) {
- try {
- // Allocate and update Amount in db
- var airdropAllocationProofDetailModel = new airdropAllocationProofDetailKlass();
- var r = await airdropAllocationProofDetailModel.updateAllocatedAmount(
- oThis.airdropAllocationProofDetailRecord.id,
- oThis.totalAmountAfterAllocatingInputAmount.toString(10)
- );
-
- logger.debug("=========allocateAirdropAmountToUsers.airdropAllocationProofDetailModel===========");
- logger.debug(r);
- if(r.isFailure()) return r;
- var userAirdropDetailModel = new userAirdropDetailKlass();
- await userAirdropDetailModel.insertMultiple(oThis.tableFields, oThis.bulkInsertData).fire();
- oThis.clearCache();
- return onResolve(responseHelper.successWithData({}));
-
- } catch(err){
- // If it fails rollback allocated amount
- r = await airdropAllocationProofDetailModel.updateAllocatedAmount(
- oThis.airdropAllocationProofDetailRecord.id,
- (oThis.totalAmountAfterAllocatingInputAmount.minus(oThis.totalInputAirdropAmount)).toString(10)
- );
- logger.debug("=========allocateAirdropAmountToUsers.airdropAllocationProofDetailModel===========");
- logger.debug(r);
-
- let errorParams = {
- internal_error_identifier: 'l_am_ba_vp_13',
- api_error_identifier: 'unhandled_api_error',
- error_config: errorConfig,
- debug_options: { err: err, transactionHash: oThis.transactionHash }
- };
- return onResolve(responseHelper.error(errorParams));
- }
-
- });
-
- },
-
- /**
- *
- * Clear all users cache
- *
- */
- clearCache: async function() {
- const oThis = this;
- const userAirdropDetailCacheKlassObject = new userAirdropDetailCacheKlass({
- chainId: oThis.chainId,
- airdropId: oThis.airdropRecord.id,
- userAddresses: oThis.userAddresses
- });
- await userAirdropDetailCacheKlassObject.clear();
- }
-
-};
-
-module.exports = BatchAllocatorKlass;
\ No newline at end of file
diff --git a/services/airdrop_management/pay.js b/services/airdrop_management/pay.js
deleted file mode 100644
index 802b1fa..0000000
--- a/services/airdrop_management/pay.js
+++ /dev/null
@@ -1,183 +0,0 @@
-"use strict";
-
-/**
- *
- * This class would be used for executing airdrop pay.
- *
- * @module services/airdrop/pay
- *
- */
-
-const rootPrefix = '../..'
- , responseHelper = require(rootPrefix + '/lib/formatter/response')
- , basicHelper = require(rootPrefix + '/helpers/basic_helper')
- , logger = require(rootPrefix + '/helpers/custom_console_logger')
- , AirdropContractInteractKlass = require(rootPrefix + '/lib/contract_interact/airdrop')
- , paramErrorConfig = require(rootPrefix + '/config/param_error_config')
- , apiErrorConfig = require(rootPrefix + '/config/api_error_config')
-;
-
-const errorConfig = {
- param_error_config: paramErrorConfig,
- api_error_config: apiErrorConfig
-};
-
-/**
- * Constructor to create object of airdrop PayKlass
- *
- * @params {object} params -
- * @param {string} params.airdrop_contract_address - airdrop contract address
- * @param {number} params.chain_id - chain Id
- * @param {string} params.sender_worker_address - address of worker
- * @param {string} params.sender_worker_passphrase - passphrase of worker
- * @param {string} params.beneficiary_address - address of beneficiary account
- * @param {bignumber} params.transfer_amount - transfer amount (in wei)
- * @param {string} params.commission_beneficiary_address - address of commision beneficiary account
- * @param {bignumber} params.commission_amount - commission amount (in wei)
- * @param {string} params.currency - quote currency
- * @param {bignumber} params.intended_price_point - price point at which the pay is intended (in wei)
- * @param {string} params.spender - User address
- * @param {string} params.gas_price - gas price
- * @param {object} params.options - for params like returnType, tag.
- *
- * @constructor
- *
- */
-const PayKlass = function (params) {
- const oThis = this;
- params = params || {};
- logger.debug("=======PayKlass.params=======");
- logger.debug(params.airdrop_contract_address, params.chain_id, params.sender_worker_address, params.beneficiary_address,
- params.transfer_amount, params.commission_beneficiary_address, params.commission_amount, params.currency, params.intended_price_point,
- params.spender, params.gas_price, params.options);
-
- oThis.airdropContractAddress = params.airdrop_contract_address;
- oThis.chainId = params.chain_id;
- oThis.senderWorkerAddress = params.sender_worker_address;
- oThis.senderWorkerPassphrase = params.sender_worker_passphrase;
- oThis.beneficiaryAddress = params.beneficiary_address;
- oThis.transferAmount = params.transfer_amount;
- oThis.commissionBeneficiaryAddress = params.commission_beneficiary_address;
- oThis.commissionAmount = params.commission_amount;
- oThis.currency = params.currency;
- oThis.intendedPricePoint = params.intended_price_point;
- oThis.spender = params.spender;
- oThis.gasPrice = params.gas_price;
- oThis.options = params.options;
-};
-
-PayKlass.prototype = {
-
- /**
- * Perform method
- *
- * @return {promise}
- *
- */
- perform: async function () {
- const oThis = this
- ;
-
- try {
- var r = null;
-
- r = await oThis.validateParams();
- logger.debug("=======PayKlass.validateParams.result=======");
- logger.debug(r);
- if (r.isFailure()) return r;
-
- r = await oThis.pay();
- logger.debug("=======PayKlass.pay.result=======");
- logger.debug(r);
-
- return r;
-
- } catch (err) {
- let errorParams = {
- internal_error_identifier: 's_a_p_perform_1',
- api_error_identifier: 'unhandled_api_error',
- error_config: errorConfig,
- debug_options: { err: err }
- };
- logger.error(err.message);
- return responseHelper.error(errorParams);
- }
-
- },
-
- /**
- * Validation of params
- *
- * @return {result}
- *
- */
- validateParams: function () {
- const oThis = this
- ;
- if (!basicHelper.isAddressValid(oThis.airdropContractAddress)) {
- let errorParams = {
- internal_error_identifier: 's_a_p_validateParams_1',
- api_error_identifier: 'invalid_api_params',
- error_config: errorConfig,
- params_error_identifiers: ['airdrop_contract_address_invalid'],
- debug_options: {}
- };
- return responseHelper.paramValidationError(errorParams);
- }
-
- if (!oThis.gasPrice) {
- let errorParams = {
- internal_error_identifier: 's_a_p_validateParams_2',
- api_error_identifier: 'invalid_api_params',
- error_config: errorConfig,
- params_error_identifiers: ['gas_price_invalid'],
- debug_options: {}
- };
- return responseHelper.paramValidationError(errorParams);
- }
-
- if (!basicHelper.isValidChainId(oThis.chainId)) {
- let errorParams = {
- internal_error_identifier: 's_a_p_validateParams_3',
- api_error_identifier: 'invalid_api_params',
- error_config: errorConfig,
- params_error_identifiers: ['chain_id_invalid'],
- debug_options: {}
- };
- return responseHelper.error(errorParams);
- }
-
- return responseHelper.successWithData({});
- },
-
- /**
- * Airdrop pay
- *
- * @return {promise}
- *
- */
- pay: function () {
- const oThis = this
- ;
- const AirdropContractInteractObject = new AirdropContractInteractKlass(
- oThis.airdropContractAddress,
- oThis.chainId
- );
- return AirdropContractInteractObject.pay(
- oThis.senderWorkerAddress,
- oThis.senderWorkerPassphrase,
- oThis.beneficiaryAddress,
- oThis.transferAmount,
- oThis.commissionBeneficiaryAddress,
- oThis.commissionAmount,
- oThis.currency,
- oThis.intendedPricePoint,
- oThis.spender,
- oThis.gasPrice,
- oThis.options
- );
- }
-
-};
-
-module.exports = PayKlass;
\ No newline at end of file
diff --git a/services/airdrop_management/post_airdrop_pay.js b/services/airdrop_management/post_airdrop_pay.js
deleted file mode 100644
index b1c9701..0000000
--- a/services/airdrop_management/post_airdrop_pay.js
+++ /dev/null
@@ -1,129 +0,0 @@
-"use strict";
-
-/**
- *
- * This class would be used for executing airdrop postAirdropPay.
- *
- * @module services/airdrop_management/post_airdrop_pay
- *
- */
-
-const rootPrefix = '../..'
- , responseHelper = require(rootPrefix + '/lib/formatter/response')
- , helper = require(rootPrefix + '/lib/contract_interact/helper')
- , logger = require(rootPrefix + '/helpers/custom_console_logger')
- , AirdropContractInteractKlass = require(rootPrefix + '/lib/contract_interact/airdrop')
- , paramErrorConfig = require(rootPrefix + '/config/param_error_config')
- , apiErrorConfig = require(rootPrefix + '/config/api_error_config')
-;
-
-const errorConfig = {
- param_error_config: paramErrorConfig,
- api_error_config: apiErrorConfig
-};
-
-/**
- * Constructor to create object of airdrop PostPayKlass
- *
- * @params {object} params -
- * @param {string} params.beneficiaryAddress - beneficiary address
- * @param {string} params.commissionBeneficiaryAddress - commission beneficiary address
- * @param {string} params.spender - spender address
- * @param {string} params.brandedTokenAddress - branded token address
- * @param {string} params.contractAddress - contractAddress address
- * @param {string} params.airdropBudgetHolder - airdrop budget holder address
- * @param {number} params.totalAmount - total amount that was debited from spender account
- * @param {number} params.airdropAmountToUse - airdrop amount that was used in the transaction
- * @param {number} params.chainId - chain id
- * @params {object} decodedEvents - decoded events from receipt
- * @param {number} status - transactions status (0 => failure, 1 => success)
- *
- * @constructor
- *
- */
-const PostPayKlass = function (params, decodedEvents, status) {
-
- const oThis = this;
- params = params || {};
-
- oThis.postAirdropPayParams = params;
- oThis.decodedEvents = decodedEvents;
- oThis.status = status;
-
-};
-
-PostPayKlass.prototype = {
-
- /**
- * Perform method
- *
- * @return {promise}
- *
- */
- perform: async function () {
- const oThis = this
- ;
-
- try {
-
- if (!oThis.decodedEvents) {
- let errorParams = {
- internal_error_identifier: 's_a_pap_perform_1',
- api_error_identifier: 'invalid_api_params',
- error_config: errorConfig,
- params_error_identifiers: ['invalid_decoded_events'],
- debug_options: {}
- };
- return Promise.resolve(responseHelper.paramValidationError(errorParams));
- }
-
- const validationResponse = helper.validatePostAirdropPayParams(oThis.postAirdropPayParams);
- if (validationResponse.isFailure()) return Promise.resolve(validationResponse);
-
- return Promise.resolve(await oThis.postAirdropPay());
-
- } catch (err) {
- let errorParams = {
- internal_error_identifier: 's_a_pap_perform_2',
- api_error_identifier: 'unhandled_api_error',
- error_config: errorConfig,
- debug_options: { err: err }
- };
- logger.error("services/airdrop_management/post_airdrop_pay.js:perform inside catch ", err);
- return Promise.resolve(responseHelper.error(errorParams));
- }
-
- },
-
-
- /**
- * Post airdrop pay
- *
- * @return {promise}
- *
- */
- postAirdropPay: function () {
- const oThis = this
- ;
-
- try {
- const AirdropContractInteractObject = new AirdropContractInteractKlass(
- oThis.postAirdropPayParams.contractAddress,
- oThis.postAirdropPayParams.chainId
- );
- return AirdropContractInteractObject.postAirdropPay(oThis.postAirdropPayParams, oThis.decodedEvents, oThis.status);
- } catch (err) {
- let errorParams = {
- internal_error_identifier: 's_a_pap_postAirdropPay_1',
- api_error_identifier: 'unhandled_api_error',
- error_config: errorConfig,
- debug_options: { err: err }
- };
- logger.error("services/airdrop_management/postAirdropPay.js:perform inside catch ", err);
- return Promise.resolve(responseHelper.error(errorParams));
- }
- }
-
-};
-
-module.exports = PostPayKlass;
\ No newline at end of file
diff --git a/services/airdrop_management/register.js b/services/airdrop_management/register.js
deleted file mode 100644
index 78ca978..0000000
--- a/services/airdrop_management/register.js
+++ /dev/null
@@ -1,203 +0,0 @@
-"use strict";
-
-/**
- *
- * This class would be used for executing airdrop register.
- *
- * @module services/airdrop_management/register
- *
- */
-
-const rootPrefix = '../..'
- , responseHelper = require(rootPrefix + '/lib/formatter/response')
- , airdropKlass = require(rootPrefix + '/app/models/airdrop')
- , airdropContractInteract = require(rootPrefix + '/lib/contract_interact/airdrop')
- , basicHelper = require(rootPrefix + '/helpers/basic_helper')
- , logger = require(rootPrefix + '/helpers/custom_console_logger')
- , AirdropModelCacheKlass = require(rootPrefix + '/lib/cache_management/airdrop_model')
- , paramErrorConfig = require(rootPrefix + '/config/param_error_config')
- , apiErrorConfig = require(rootPrefix + '/config/api_error_config')
-;
-
-const errorConfig = {
- param_error_config: paramErrorConfig,
- api_error_config: apiErrorConfig
-};
-
-/**
- * Constructor to create object of register
- *
- * @constructor
- *
- * @params {object} params -
- * @param {string} params.airdrop_contract_address - airdrop contract address
- * @param {number} params.chain_id - chain Id
- *
- * @return {Object}
- *
- */
-const RegisterKlass = function (params) {
- const oThis = this;
- params = params || {};
- logger.debug("=======register.params=======");
- logger.debug(params);
-
- oThis.airdropContractAddress = params.airdrop_contract_address;
- oThis.chainId = params.chain_id;
-
-};
-
-RegisterKlass.prototype = {
-
- /**
- * Perform method
- *
- * @return {promise}
- *
- */
- perform: async function () {
-
- const oThis = this
- ;
- try {
- var r = null;
-
- r = await oThis.validateParams();
- logger.debug("=======register.validateParams.result=======");
- logger.debug(r);
- if (r.isFailure()) return r;
-
- r = await oThis.runRegister();
- logger.debug("=======register.runRegister.result=======");
- logger.debug(r);
- return r;
- } catch(err) {
- let errorParams = {
- internal_error_identifier: 's_am_r_perform_1',
- api_error_identifier: 'unhandled_api_error',
- error_config: errorConfig,
- debug_options: { err: err }
- };
- return responseHelper.error(errorParams);
- }
-
- },
-
- /**
- * Validation of params
- *
- * @return {promise}
- *
- */
- validateParams: function () {
- const oThis = this;
- return new Promise(async function (onResolve, onReject) {
-
- if (!basicHelper.isAddressValid(oThis.airdropContractAddress)) {
- let errorParams = {
- internal_error_identifier: 's_am_r_validateParams_1',
- api_error_identifier: 'invalid_api_params',
- error_config: errorConfig,
- params_error_identifiers: ['airdrop_contract_address_invalid'],
- debug_options: {}
- };
- return onResolve(responseHelper.paramValidationError(errorParams));
- }
-
- if (!basicHelper.isValidChainId(oThis.chainId)) {
- let errorParams = {
- internal_error_identifier: 's_am_r_validateParams_2',
- api_error_identifier: 'invalid_api_params',
- error_config: errorConfig,
- params_error_identifiers: ['chain_id_invalid'],
- debug_options: {}
- };
- return onResolve(responseHelper.paramValidationError(errorParams));
- }
-
- const airdropContractInteractObject = new airdropContractInteract(oThis.airdropContractAddress, oThis.chainId);
- var result = await airdropContractInteractObject.airdropBudgetHolder();
- const airdropBudgetHolderAddress = result.data.airdropBudgetHolder;
- if (!basicHelper.isAddressValid(airdropBudgetHolderAddress)) {
- let errorParams = {
- internal_error_identifier: 's_am_r_validateParams_3',
- api_error_identifier: 'invalid_api_params',
- error_config: errorConfig,
- params_error_identifiers: ['airdrop_contract_address_invalid'],
- debug_options: {}
- };
- return onResolve(responseHelper.paramValidationError(errorParams));
- }
-
- // Check if airdropContractAddress is registered or not
- const airdropModelCacheObject = new AirdropModelCacheKlass({useObject: true, contractAddress: oThis.airdropContractAddress})
- , airdropModelCacheResponse = await airdropModelCacheObject.fetch()
- , airdropRecord = airdropModelCacheResponse.data[oThis.airdropContractAddress];
- ;
- if (airdropRecord) {
- let errorParams = {
- internal_error_identifier: 's_am_r_validateParams_4',
- api_error_identifier: 'invalid_api_params',
- error_config: errorConfig,
- params_error_identifiers: ['airdrop_contract_already_registered'],
- debug_options: {}
- };
- return onResolve(responseHelper.paramValidationError(errorParams));
- }
-
- if (!basicHelper.isValidChainId(oThis.chainId)) {
- let errorParams = {
- internal_error_identifier: 's_am_r_validateParams_5',
- api_error_identifier: 'invalid_api_params',
- error_config: errorConfig,
- params_error_identifiers: ['chain_id_invalid'],
- debug_options: {}
- };
- return onResolve(responseHelper.paramValidationError(errorParams));
- }
-
- return onResolve(responseHelper.successWithData({}));
- });
- },
-
- /**
- * Run the register
- *
- * @return {promise}
- *
- */
- runRegister: function () {
- const oThis = this
- ;
-
- return new Promise(async function (onResolve, onReject) {
- try {
- const airdropModelObject = {
- contract_address: oThis.airdropContractAddress
- };
- logger.debug("========register.runRegister.airdropModelObject=======");
- logger.debug(airdropModelObject);
- var airdropModel = new airdropKlass();
- const insertedRecord = await airdropModel.create(airdropModelObject);
- logger.debug("========register.runRegister.insertedRecord=======");
- logger.debug(insertedRecord);
- const airdropModelCacheObject = new AirdropModelCacheKlass({useObject: true, contractAddress: oThis.airdropContractAddress});
- await airdropModelCacheObject.clear();
- return onResolve(responseHelper.successWithData({insertId: insertedRecord.insertId}));
- } catch (err) {
- let errorParams = {
- internal_error_identifier: 's_am_r_runRegister_1',
- api_error_identifier: 'unhandled_api_error',
- error_config: errorConfig,
- debug_options: { err: err }
- };
- return onResolve(responseHelper.error(errorParams));
- }
- });
-
- }
-
-};
-
-module.exports = RegisterKlass;
-
diff --git a/services/airdrop_management/set_accepted_margin.js b/services/airdrop_management/set_accepted_margin.js
deleted file mode 100644
index 639393b..0000000
--- a/services/airdrop_management/set_accepted_margin.js
+++ /dev/null
@@ -1,204 +0,0 @@
-"use strict";
-
-/**
- *
- * This class would be used for executing worker is_worker.
- *
- * @module services/airdrop_management/set_accepted_margin
- *
- */
-const rootPrefix = '../..'
- , responseHelper = require(rootPrefix + '/lib/formatter/response')
- , basicHelper = require(rootPrefix + '/helpers/basic_helper')
- , logger = require(rootPrefix + '/helpers/custom_console_logger')
- , helper = require(rootPrefix + '/lib/contract_interact/helper')
- , AirdropContractInteractKlass = require(rootPrefix + '/lib/contract_interact/airdrop')
- , BigNumber = require('bignumber.js')
- , paramErrorConfig = require(rootPrefix + '/config/param_error_config')
- , apiErrorConfig = require(rootPrefix + '/config/api_error_config')
-;
-
-const errorConfig = {
- param_error_config: paramErrorConfig,
- api_error_config: apiErrorConfig
-};
-
-/**
- * Constructor to create object of SetAcceptedMarginKlass
- *
- * @constructor
- *
- * @param {object} - params
- * @param {string} params.airdrop_contract_address - airdrop contract address
- * @param {number} params.chain_id - chain id
- * @param {string} params.sender_address - address of sender
- * @param {string} params.sender_passphrase - passphrase of sender
- * @param {string} params.currency - quote currency
- * @param {bignumber} params.accepted_margin - accepted margin for the given currency (in wei)
- * @param {bignumber} params.gas_price - gas price
- * @param {object} params.options - for params like returnType, tag.
- *
- * @return {Object}
- *
- */
-const SetAcceptedMarginKlass = function (params) {
- const oThis = this;
- params = params || {};
- logger.debug("=======SetAcceptedMarginKlass.params=======");
- // Don't log passphrase
- logger.debug(params.airdrop_contract_address, params.chain_id, params.sender_address, params.currency,
- params.accepted_margin, params.gas_price, params.options);
-
- oThis.airdropContractAddress = params.airdrop_contract_address;
- oThis.chainId = params.chain_id;
- oThis.senderAddress = params.sender_address;
- oThis.senderPassphrase = params.sender_passphrase;
- oThis.currency = params.currency;
- oThis.acceptedMargin = params.accepted_margin;
- oThis.gasPrice = params.gas_price;
- oThis.options = params.options;
-};
-
-SetAcceptedMarginKlass.prototype = {
-
- /**
- * Perform method
- *
- * @return {promise}
- *
- */
- perform: async function () {
- const oThis = this
- ;
- try {
- var r = null;
-
- r = await oThis.validateParams();
- logger.debug("=======SetAcceptedMarginKlass.validateParams.result=======");
- logger.debug(r);
- if (r.isFailure()) return r;
-
- r = await oThis.setAcceptedMargin();
- logger.debug("=======SetAcceptedMarginKlass.setAcceptedMargin.result=======");
- logger.debug(r);
-
- return r;
-
- } catch (err) {
- let errorParams = {
- internal_error_identifier: 's_w_sam_perform_1',
- api_error_identifier: 'unhandled_api_error',
- error_config: errorConfig,
- debug_options: { err: err }
- };
- return responseHelper.error(errorParams);
- }
-
- },
-
- /**
- * Validation of params
- *
- * @return {result}
- *
- */
- validateParams: function () {
- const oThis = this
- ;
- if (!helper.isValidCurrency(oThis.currency, false)) {
- let errorParams = {
- internal_error_identifier: 's_am_sam_validateParams_1',
- api_error_identifier: 'invalid_api_params',
- error_config: errorConfig,
- params_error_identifiers: ['invalid_currency'],
- debug_options: {}
- };
- return responseHelper.paramValidationError(errorParams);
- }
-
- if (!oThis.gasPrice) {
- let errorParams = {
- internal_error_identifier: 's_am_sam_validateParams_2',
- api_error_identifier: 'invalid_api_params',
- error_config: errorConfig,
- params_error_identifiers: ['gas_price_invalid'],
- debug_options: {}
- };
- return responseHelper.paramValidationError(errorParams);
- }
-
- const acceptedMargin = new BigNumber(oThis.acceptedMargin);
-
- if (acceptedMargin.isNaN() || !acceptedMargin.isInteger() || acceptedMargin.lt(0)) {
- let errorParams = {
- internal_error_identifier: 's_am_sam_validateParams_3',
- api_error_identifier: 'invalid_api_params',
- error_config: errorConfig,
- params_error_identifiers: ['accepted_margin_invalid'],
- debug_options: {}
- };
- return responseHelper.paramValidationError(errorParams);
- }
-
- if (!basicHelper.isAddressValid(oThis.senderAddress)) {
- let errorParams = {
- internal_error_identifier: 's_am_sam_validateParams_4',
- api_error_identifier: 'invalid_api_params',
- error_config: errorConfig,
- params_error_identifiers: ['invalid_sender_address'],
- debug_options: {}
- };
- return responseHelper.paramValidationError(errorParams);
- }
-
- if (!oThis.gasPrice) {
- let errorParams = {
- internal_error_identifier: 's_am_sam_validateParams_5',
- api_error_identifier: 'invalid_api_params',
- error_config: errorConfig,
- params_error_identifiers: ['gas_price_invalid'],
- debug_options: {}
- };
- return responseHelper.paramValidationError(errorParams);
- }
-
- if (!basicHelper.isValidChainId(oThis.chainId)) {
- let errorParams = {
- internal_error_identifier: 's_am_sam_validateParams_6',
- api_error_identifier: 'invalid_api_params',
- error_config: errorConfig,
- params_error_identifiers: ['chain_id_invalid'],
- debug_options: {}
- };
- return responseHelper.paramValidationError(errorParams);
- }
-
- return responseHelper.successWithData({});
- },
-
- /**
- * Set accepted margin value in airdrop contract
- *
- * @return {promise}
- *
- */
- setAcceptedMargin: function () {
- const oThis = this
- ;
- const AirdropContractInteractObject = new AirdropContractInteractKlass(
- oThis.airdropContractAddress,
- oThis.chainId
- );
- return AirdropContractInteractObject.setAcceptedMargin(
- oThis.senderAddress,
- oThis.senderPassphrase,
- oThis.currency,
- oThis.acceptedMargin,
- oThis.gasPrice,
- oThis.options
- );
- }
-
-};
-
-module.exports = SetAcceptedMarginKlass;
\ No newline at end of file
diff --git a/services/airdrop_management/set_price_oracle.js b/services/airdrop_management/set_price_oracle.js
deleted file mode 100644
index 77173a4..0000000
--- a/services/airdrop_management/set_price_oracle.js
+++ /dev/null
@@ -1,191 +0,0 @@
-"use strict";
-
-/**
- *
- * This class would be used for executing worker is_worker.
- *
- * @module services/airdrop_management/set_price_oracle
- *
- */
-const rootPrefix = '../..'
- , responseHelper = require(rootPrefix + '/lib/formatter/response')
- , basicHelper = require(rootPrefix + '/helpers/basic_helper')
- , logger = require(rootPrefix + '/helpers/custom_console_logger')
- , helper = require(rootPrefix + '/lib/contract_interact/helper')
- , AirdropContractInteractKlass = require(rootPrefix + '/lib/contract_interact/airdrop')
- , paramErrorConfig = require(rootPrefix + '/config/param_error_config')
- , apiErrorConfig = require(rootPrefix + '/config/api_error_config')
-;
-
-const errorConfig = {
- param_error_config: paramErrorConfig,
- api_error_config: apiErrorConfig
-};
-
-/**
- * Constructor to create object of register
- *
- * @constructor
- *
- * @param {object} - params
- * @param {string} params.airdrop_contract_address - airdrop contract address
- * @param {number} params.chain_id - chain id
- * @param {string} params.sender_address - address of sender
- * @param {string} params.sender_passphrase - passphrase of sender
- * @param {string} params.currency - quote currency
- * @param {string} params.address - address of price oracle
- * @param {bignumber} params.gas_price - gas price
- * @param {object} params.options - for params like returnType, tag.
- *
- * @return {Object}
- *
- */
-const SetPriceOracleKlass = function (params) {
- const oThis = this;
- params = params || {};
- logger.debug("=======SetPriceOracleKlass.params=======");
- // Don't log passphrase
- logger.debug(params.airdrop_contract_address, params.chain_id, params.sender_address, params.currency,
- params.price_oracle_contract_address, params.gas_price, params.options);
-
- oThis.airdropContractAddress = params.airdrop_contract_address;
- oThis.chainId = params.chain_id;
- oThis.senderAddress = params.sender_address;
- oThis.senderPassphrase = params.sender_passphrase;
- oThis.currency = params.currency;
- oThis.priceOracleContractAddress = params.price_oracle_contract_address;
- oThis.gasPrice = params.gas_price;
- oThis.options = params.options;
-};
-
-SetPriceOracleKlass.prototype = {
-
- /**
- * Perform method
- *
- * @return {promise}
- *
- */
- perform: async function () {
- const oThis = this
- ;
- try {
- var r = null;
-
- r = await oThis.validateParams();
- logger.debug("=======SetPriceOracleKlass.validateParams.result=======");
- logger.debug(r);
- if (r.isFailure()) return r;
-
- r = await oThis.setPriceOracle();
- logger.debug("=======SetPriceOracleKlass.setPriceOracle.result=======");
- logger.debug(r);
-
- return r;
-
- } catch (err) {
- let errorParams = {
- internal_error_identifier: 's_w_spo_perform_1',
- api_error_identifier: 'unhandled_api_error',
- error_config: errorConfig,
- debug_options: { err: err }
- };
- logger.error(err.message);
- return responseHelper.error(errorParams);
- }
-
- },
-
- /**
- * Validation of params
- *
- * @return {result}
- *
- */
- validateParams: function () {
- const oThis = this
- ;
- if (!helper.isValidCurrency(oThis.currency, false)) {
- let errorParams = {
- internal_error_identifier: 's_am_spo_validateParams_1',
- api_error_identifier: 'invalid_api_params',
- error_config: errorConfig,
- params_error_identifiers: ['currency_invalid'],
- debug_options: {}
- };
- return responseHelper.paramValidationError(errorParams);
- }
-
- if (!oThis.gasPrice) {
- let errorParams = {
- internal_error_identifier: 's_am_spo_validateParams_2',
- api_error_identifier: 'invalid_api_params',
- error_config: errorConfig,
- params_error_identifiers: ['gas_price_invalid'],
- debug_options: {}
- };
- return responseHelper.paramValidationError(errorParams);
- }
-
- if (!basicHelper.isAddressValid(oThis.priceOracleContractAddress)) {
- let errorParams = {
- internal_error_identifier: 's_am_spo_validateParams_3',
- api_error_identifier: 'invalid_api_params',
- error_config: errorConfig,
- params_error_identifiers: ['price_oracle_address_invalid'],
- debug_options: {}
- };
- return responseHelper.paramValidationError(errorParams);
- }
-
- if (!basicHelper.isAddressValid(oThis.senderAddress)) {
- let errorParams = {
- internal_error_identifier: 's_am_spo_validateParams_4',
- api_error_identifier: 'invalid_api_params',
- error_config: errorConfig,
- params_error_identifiers: ['invalid_sender_address'],
- debug_options: {}
- };
- return responseHelper.paramValidationError(errorParams);
- }
-
- if (!basicHelper.isValidChainId(oThis.chainId)) {
- let errorParams = {
- internal_error_identifier: 's_am_spo_validateParams_5',
- api_error_identifier: 'invalid_api_params',
- error_config: errorConfig,
- params_error_identifiers: ['chain_id_invalid'],
- debug_options: {}
- };
- return responseHelper.paramValidationError(errorParams);
- }
-
- return responseHelper.successWithData({});
- },
-
- /**
- * set price oracle contract address in airdrop contract
- *
- * @return {promise}
- *
- */
- setPriceOracle: function () {
- const oThis = this
- ;
- const AirdropContractInteractObject = new AirdropContractInteractKlass(
- oThis.airdropContractAddress,
- oThis.chainId
- );
- return AirdropContractInteractObject.setPriceOracle(
- oThis.senderAddress,
- oThis.senderPassphrase,
- oThis.currency,
- oThis.priceOracleContractAddress,
- oThis.gasPrice,
- oThis.options
- );
- }
-
-};
-
-module.exports = SetPriceOracleKlass;
\ No newline at end of file
diff --git a/services/airdrop_management/transfer.js b/services/airdrop_management/transfer.js
deleted file mode 100644
index 4813ed5..0000000
--- a/services/airdrop_management/transfer.js
+++ /dev/null
@@ -1,291 +0,0 @@
-"use strict";
-
-/**
- *
- * This is a utility file which would be used for executing transfer amount to airdrop budget holder.
- *
- * @module services/airdrop_management/transfer
- *
- */
-
-const rootPrefix = '../..'
- , responseHelper = require(rootPrefix + '/lib/formatter/response')
- , airdropAllocationProofDetailKlass = require(rootPrefix + '/app/models/airdrop_allocation_proof_detail')
- , airdropContractInteract = require(rootPrefix + '/lib/contract_interact/airdrop')
- , brandedTokenContractInteract = require(rootPrefix + '/lib/contract_interact/branded_token')
- , BigNumber = require('bignumber.js')
- , basicHelper = require(rootPrefix + '/helpers/basic_helper')
- , logger = require(rootPrefix + '/helpers/custom_console_logger')
- , AirdropModelCacheKlass = require(rootPrefix + '/lib/cache_management/airdrop_model')
- , BrandedTokenKlass = require(rootPrefix + '/lib/contract_interact/branded_token')
- , paramErrorConfig = require(rootPrefix + '/config/param_error_config')
- , apiErrorConfig = require(rootPrefix + '/config/api_error_config')
-;
-
-const errorConfig = {
- param_error_config: paramErrorConfig,
- api_error_config: apiErrorConfig
-};
-
-/**
- * Constructor to create object of transfer
- *
- * @constructor
- *
- * @params {object} - params
- * @param {string} sender_address - sender address
- * @param {string} sender_passphrase - sender Passphrase
- * @param {string} airdrop_contract_address - airdrop contract address
- * @param {string} amount - amount in wei
- * @param {string} gas_price - gas price
- * @param {number} chain_id - chain Id
- * @param {object} options - options
- *
- * @return {object}
- *
- */
-const TransferKlass = function(params) {
- const oThis = this;
- params = params || {};
- logger.debug("\n=========Transfer params=========");
- // Don't log passphrase
- logger.debug(params.sender_address, params.airdrop_contract_address, params.amount, params.gas_price, params.chain_id, params.options);
-
- oThis.senderAddress = params.sender_address;
- oThis.senderPassphrase = params.sender_passphrase;
- oThis.airdropContractAddress = params.airdrop_contract_address;
- oThis.amount = params.amount;
- oThis.gasPrice = params.gas_price;
- oThis.chainId = params.chain_id;
- oThis.options = params.options;
- oThis.airdropBudgetHolder = null;
- oThis.brandedTokenContractAddress = null;
-
-};
-
-TransferKlass.prototype = {
-
- /**
- * Perform method
- *
- * @return {promise}
- *
- */
- perform: async function () {
-
- const oThis = this;
-
- try {
- var r = null;
-
- r = await oThis.validateParams();
- logger.debug("\n=========Transfer.validateParams.result=========");
- logger.debug(r);
- if(r.isFailure()) return r;
-
- r = oThis.doTransfer();
- logger.debug("\n=========Transfer.doTransfer.result=========");
- logger.debug(r);
- return r;
- } catch(err) {
- let errorParams = {
- internal_error_identifier: 's_am_t_perform_1',
- api_error_identifier: 'unhandled_api_error',
- error_config: errorConfig,
- debug_options: { err: err }
- };
- logger.error(err.message);
- return responseHelper.error(errorParams);
- }
-
- },
-
- /**
- * validation of params
- *
- * @return {promise}
- *
- */
- validateParams: function() {
- const oThis = this;
- return new Promise(async function (onResolve, onReject) {
-
- if (!basicHelper.isAddressValid(oThis.senderAddress)) {
- let errorParams = {
- internal_error_identifier: 's_am_t_validateParams_1',
- api_error_identifier: 'invalid_api_params',
- error_config: errorConfig,
- params_error_identifiers: ['invalid_sender_address'],
- debug_options: {}
- };
- return onResolve(responseHelper.paramValidationError(errorParams));
- }
-
- if (!basicHelper.isAddressValid(oThis.airdropContractAddress)) {
- let errorParams = {
- internal_error_identifier: 's_am_t_validateParams_2',
- api_error_identifier: 'invalid_api_params',
- error_config: errorConfig,
- params_error_identifiers: ['airdrop_contract_address_invalid'],
- debug_options: {}
- };
- return onResolve(responseHelper.paramValidationError(errorParams));
- }
-
- // Check if airdropContractAddress is registered or not
-
- const airdropModelCacheObject = new AirdropModelCacheKlass({useObject: true, contractAddress: oThis.airdropContractAddress})
- , airdropModelCacheResponse = await airdropModelCacheObject.fetch()
- ;
- oThis.airdropRecord = airdropModelCacheResponse.data[oThis.airdropContractAddress];
- if (!oThis.airdropRecord){
- let errorParams = {
- internal_error_identifier: 's_am_t_validateParams_3',
- api_error_identifier: 'invalid_api_params',
- error_config: errorConfig,
- params_error_identifiers: ['airdrop_contract_address_invalid'],
- debug_options: {}
- };
- return onResolve(responseHelper.paramValidationError(errorParams));
- }
-
- const airdropContractInteractObject = new airdropContractInteract(oThis.airdropContractAddress, oThis.chainId);
- var result = await airdropContractInteractObject.brandedToken();
- oThis.brandedTokenContractAddress = result.data.brandedToken;
- logger.debug("\n==========transfer.validateParams.brandedToken===========");
- logger.debug("\nairdropContractInteractObject.brandedToken():", result,"\noThis.brandedTokenContractAddress:", oThis.brandedTokenContractAddress);
- if (!basicHelper.isAddressValid(oThis.brandedTokenContractAddress)) {
- let errorParams = {
- internal_error_identifier: 's_am_t_validateParams_4',
- api_error_identifier: 'invalid_api_params',
- error_config: errorConfig,
- params_error_identifiers: ['branded_token_address_invalid'],
- debug_options: {}
- };
- return onResolve(responseHelper.paramValidationError(errorParams));
- }
-
- result = await airdropContractInteractObject.airdropBudgetHolder();
- oThis.airdropBudgetHolderAddress = result.data.airdropBudgetHolder;
- if (!basicHelper.isAddressValid(oThis.brandedTokenContractAddress)) {
- let errorParams = {
- internal_error_identifier: 's_am_t_validateParams_5',
- api_error_identifier: 'invalid_api_params',
- error_config: errorConfig,
- params_error_identifiers: ['airdrop_budget_holder_invalid'],
- debug_options: {}
- };
- return onResolve(responseHelper.paramValidationError(errorParams));
- }
-
- const amountInBigNumber = new BigNumber(oThis.amount);
- if (amountInBigNumber.isNaN() || !amountInBigNumber.isInteger()){
- let errorParams = {
- internal_error_identifier: 's_am_t_validateParams_6',
- api_error_identifier: 'invalid_api_params',
- error_config: errorConfig,
- params_error_identifiers: ['invalid_amount'],
- debug_options: {}
- };
- return onResolve(responseHelper.paramValidationError(errorParams));
- }
-
- if (!basicHelper.isValidChainId(oThis.chainId)) {
- let errorParams = {
- internal_error_identifier: 's_am_t_validateParams_7',
- api_error_identifier: 'invalid_api_params',
- error_config: errorConfig,
- params_error_identifiers: ['chain_id_invalid'],
- debug_options: {}
- };
- return onResolve(responseHelper.paramValidationError(errorParams));
- }
-
- const brandedTokenObject = new BrandedTokenKlass(oThis.brandedTokenContractAddress, oThis.chainId);
- const senderBalanceResponse = await brandedTokenObject.getBalanceOf(oThis.senderAddress);
-
- if (senderBalanceResponse.isFailure()) {
- let errorParams = {
- internal_error_identifier: 's_am_t_validateParams_8',
- api_error_identifier: 'get_balance_failed',
- error_config: errorConfig,
- debug_options: {}
- };
- return onResolve(responseHelper.error(errorParams));
- }
-
- const senderBalance = new BigNumber(senderBalanceResponse.data.balance);
- //logger.debug("senderBalance: "+senderBalance.toString(10), "amount to transfer: "+amountInBigNumber);
- if (senderBalance.lt(amountInBigNumber)){
- let errorParams = {
- internal_error_identifier: 's_am_t_validateParams_9',
- api_error_identifier: 'insufficient_funds',
- error_config: errorConfig,
- debug_options: { senderBalance: senderBalance.toString(10), amountInBigNumber: amountInBigNumber.toString(10) }
- };
- return onResolve(responseHelper.error(errorParams));
- }
-
- if (!oThis.gasPrice) {
- let errorParams = {
- internal_error_identifier: 's_am_t_validateParams_10',
- api_error_identifier: 'invalid_api_params',
- error_config: errorConfig,
- params_error_identifiers: ['gas_price_invalid'],
- debug_options: {}
- };
- return onResolve(responseHelper.paramValidationError(errorParams));
- }
-
- if (!basicHelper.isValidChainId(oThis.chainId)) {
- let errorParams = {
- internal_error_identifier: 's_am_t_validateParams_11',
- api_error_identifier: 'invalid_api_params',
- error_config: errorConfig,
- params_error_identifiers: ['chain_id_invalid'],
- debug_options: {}
- };
- return onResolve(responseHelper.paramValidationError(errorParams));
- }
-
- return onResolve(responseHelper.successWithData({}));
-
- });
-
- },
-
- /**
- * Transfer amount to airdrop budget holder
- *
- * @return {promise}
- *
- */
- doTransfer: async function() {
- const oThis = this;
-
- return new Promise(async function (onResolve, onReject) {
- // BrandedToken transfer
- logger.debug("\n==========doTransfer.oThis.brandedTokenContractAddress===========");
- logger.debug(oThis.brandedTokenContractAddress);
- var brandedTokenObject = new brandedTokenContractInteract(oThis.brandedTokenContractAddress, oThis.chainId);
- const transactionResponse = await brandedTokenObject.transferToAirdropBudgetHolder(oThis.senderAddress,
- oThis.senderPassphrase,
- oThis.airdropBudgetHolderAddress,
- oThis.amount,
- oThis.gasPrice,
- oThis.options);
- if (transactionResponse.isSuccess()){
- var airdropAllocationProofDetailModel = new airdropAllocationProofDetailKlass();
- const airdropAllocationProofDetailCreateResult = await airdropAllocationProofDetailModel.createRecord(transactionResponse.data.transaction_hash, oThis.amount, 0);
- if (airdropAllocationProofDetailCreateResult.isFailure()) {
- return onResolve(airdropAllocationProofDetailCreateResult);
- }
- }
- return onResolve(transactionResponse);
- });
- }
-
-};
-
-module.exports = TransferKlass;
-
diff --git a/services/airdrop_management/user_balance.js b/services/airdrop_management/user_balance.js
deleted file mode 100644
index 63cb84a..0000000
--- a/services/airdrop_management/user_balance.js
+++ /dev/null
@@ -1,185 +0,0 @@
-"use strict";
-
-/**
- *
- * This class would be used for calculating user airdrop balance.
- *
- * @module services/airdrop_management/user_balance
- *
- */
-
-const rootPrefix = '../..'
- , responseHelper = require(rootPrefix + '/lib/formatter/response')
- , basicHelper = require(rootPrefix + '/helpers/basic_helper')
- , logger = require(rootPrefix + '/helpers/custom_console_logger')
- , userAirdropDetailCacheKlass = require(rootPrefix + '/lib/cache_multi_management/user_airdrop_detail')
- , AirdropModelCacheKlass = require(rootPrefix + '/lib/cache_management/airdrop_model')
- , paramErrorConfig = require(rootPrefix + '/config/param_error_config')
- , apiErrorConfig = require(rootPrefix + '/config/api_error_config')
-;
-
-const errorConfig = {
- param_error_config: paramErrorConfig,
- api_error_config: apiErrorConfig
-};
-
-/**
- * Constructor to create object of userBalance
- *
- * @constructor
- *
- * @param {object} params -
- * @param {number} chain_id - chain Id
- * @param {string} airdrop_contract_address - airdrop contract address
- * @param {array} user_addresses - Array of user addressed
- *
- * @return {object}
- *
- */
-const AirdropUserBalanceKlass = function(params) {
- const oThis = this;
- params = params || {};
- logger.debug("=======user_balance.params=======");
- logger.debug(params);
-
- oThis.airdropContractAddress = params.airdrop_contract_address;
- oThis.chainId = params.chain_id;
- oThis.userAddresses = params.user_addresses;
-
- oThis.airdropRecord = null;
-
-};
-
-AirdropUserBalanceKlass.prototype = {
-
- /**
- * Perform method
- *
- * @return {promise}
- *
- */
- perform: async function () {
-
- const oThis = this;
-
- try {
- var r = null;
-
- r = await oThis.validateParams();
- logger.debug("=======userBalance.validateParams.result=======");
- logger.debug(r);
- if(r.isFailure()) return r;
-
- r = await oThis.getUserAirdropBalance();
- logger.debug("=======userBalance.getUserAirdropBalance.result=======");
- logger.debug(r);
- return r;
- } catch(err) {
- let errorParams = {
- internal_error_identifier: 's_am_ub_perform_1',
- api_error_identifier: 'unhandled_api_error',
- error_config: errorConfig,
- debug_options: { err: err }
- };
- return responseHelper.error(errorParams);
- }
-
- },
-
- /**
- * Validation of params
- *
- * @return {promise}
- *
- */
- validateParams: function(){
- const oThis = this;
- return new Promise(async function (onResolve, onReject) {
-
- if (!basicHelper.isAddressValid(oThis.airdropContractAddress)) {
- let errorParams = {
- internal_error_identifier: 's_am_ub_validateParams_1',
- api_error_identifier: 'invalid_api_params',
- error_config: errorConfig,
- params_error_identifiers: ['airdrop_contract_address_invalid'],
- debug_options: {}
- };
- return onResolve(responseHelper.paramValidationError(errorParams));
- }
-
- if (!basicHelper.isValidChainId(oThis.chainId)) {
- let errorParams = {
- internal_error_identifier: 's_am_ub_validateParams_2',
- api_error_identifier: 'invalid_api_params',
- error_config: errorConfig,
- params_error_identifiers: ['chain_id_invalid'],
- debug_options: {}
- };
- return onResolve(responseHelper.paramValidationError(errorParams));
- }
-
- // if address already present
- const airdropModelCacheObject = new AirdropModelCacheKlass({useObject: true, contractAddress: oThis.airdropContractAddress})
- , airdropModelCacheResponse = await airdropModelCacheObject.fetch()
- ;
- oThis.airdropRecord = airdropModelCacheResponse.data[oThis.airdropContractAddress];
- if (!oThis.airdropRecord){
- let errorParams = {
- internal_error_identifier: 's_am_ub_validateParams_3',
- api_error_identifier: 'invalid_api_params',
- error_config: errorConfig,
- params_error_identifiers: ['airdrop_contract_address_invalid'],
- debug_options: {}
- };
- return onResolve(responseHelper.paramValidationError(errorParams));
- }
-
- if (!basicHelper.isValidChainId(oThis.chainId)) {
- let errorParams = {
- internal_error_identifier: 's_am_ub_validateParams_4',
- api_error_identifier: 'invalid_api_params',
- error_config: errorConfig,
- params_error_identifiers: ['chain_id_invalid'],
- debug_options: {}
- };
- return onResolve(responseHelper.paramValidationError(errorParams));
- }
-
- return onResolve(responseHelper.successWithData({}));
- });
-
- },
-
- /**
- * Run the register
- *
- * @return {promise}
- *
- */
- getUserAirdropBalance: function() {
- const oThis = this;
- return new Promise(async function (onResolve, onReject) {
- try {
- const userAirdropDetailCacheKlassObject = new userAirdropDetailCacheKlass({
- chainId: oThis.chainId,
- airdropId: oThis.airdropRecord.id,
- userAddresses: oThis.userAddresses
- });
- return onResolve(await userAirdropDetailCacheKlassObject.fetch());
- } catch(err){
- let errorParams = {
- internal_error_identifier: 'l_am_ub_getUserAirdropBalance_4',
- api_error_identifier: 'get_balance_failed',
- error_config: errorConfig,
- debug_options: { err: err }
- };
- return onResolve(responseHelper.error(errorParams));
- }
- });
-
- }
-
-};
-
-module.exports = AirdropUserBalanceKlass;
-
diff --git a/services/deploy/airdrop.js b/services/deploy/airdrop.js
deleted file mode 100644
index 3238b75..0000000
--- a/services/deploy/airdrop.js
+++ /dev/null
@@ -1,203 +0,0 @@
-"use strict";
-
-/**
- *
- * This class would be used for deploying airdrop contract.
- *
- * @module services/deploy/airdrop
- *
- */
-
-const rootPrefix = '../..'
- , responseHelper = require(rootPrefix + '/lib/formatter/response')
- , basicHelper = require(rootPrefix + '/helpers/basic_helper')
- , logger = require(rootPrefix + '/helpers/custom_console_logger')
- , DeployerKlass = require(rootPrefix + '/services/deploy/deployer')
- , web3Provider = require(rootPrefix + '/lib/web3/providers/rpc')
- , gasLimitGlobalConstant = require(rootPrefix + '/lib/global_constant/gas_limit')
- , paramErrorConfig = require(rootPrefix + '/config/param_error_config')
- , apiErrorConfig = require(rootPrefix + '/config/api_error_config')
-;
-
-const errorConfig = {
- param_error_config: paramErrorConfig,
- api_error_config: apiErrorConfig
-};
-
-/**
- * Constructor to create object of airdrop
- *
- * @constructor
- *
- * @param {object} params -
- * @param {string} params.branded_token_contract_address - branded token contract address
- * @param {string} params.base_currency - base currency
- * @param {string} params.worker_contract_address - worker contract address
- * @param {string} params.airdrop_budget_holder - airdrop budget holder address
- * @param {string} params.gas_price - gas price
- * @param {object} params.options - deployment options e.g. {returnType: 'txReceipt'}
- *
- * @return {object}
- *
- */
-const DeployAirdropKlass = function (params) {
- const oThis = this;
- params = params || {};
- logger.debug("=======DeployAirdropKlass.params=======");
- logger.debug(params);
-
- oThis.contractName = 'airdrop';
- oThis.brandedTokenContractAddress = params.branded_token_contract_address;
- oThis.baseCurrency = params.base_currency;
- oThis.workerContractAddress = params.worker_contract_address;
- oThis.airdropBudgetHolder = params.airdrop_budget_holder;
- oThis.gasPrice = params.gas_price;
- oThis.options = params.options;
-
- oThis.constructorArgs = [];
-};
-
-DeployAirdropKlass.prototype = {
-
- /**
- * Perform method
- *
- * @return {promise}
- *
- */
- perform: async function () {
- const oThis = this
- ;
- try {
- var r = null;
-
- r = await oThis.validateParams();
- logger.debug("=======DeployAirdropKlass.validateParams.result=======");
- logger.debug(r);
- if (r.isFailure()) return r;
-
- r = await oThis.deploy();
- logger.debug("=======DeployAirdropKlass.setOps.result=======");
- logger.debug(r);
-
- return r;
-
- } catch (err) {
- let errorParams = {
- internal_error_identifier: 's_d_a_perform_1',
- api_error_identifier: 'unhandled_api_error',
- error_config: errorConfig,
- debug_options: { err: err }
- };
- return responseHelper.error(errorParams);
- }
-
- },
-
- /**
- * Validation of params
- *
- * @return {result}
- *
- */
- validateParams: function () {
- const oThis = this
- ;
-
- if (!oThis.gasPrice) {
- let errorParams = {
- internal_error_identifier: 's_d_a_validateParams_1',
- api_error_identifier: 'invalid_api_params',
- error_config: errorConfig,
- params_error_identifiers: ['gas_price_invalid'],
- debug_options: {}
- };
- return responseHelper.paramValidationError(errorParams);
- }
-
- if (!oThis.options) {
- let errorParams = {
- internal_error_identifier: 's_d_a_validateParams_2',
- api_error_identifier: 'invalid_api_params',
- error_config: errorConfig,
- params_error_identifiers: ['invalid_options'],
- debug_options: {}
- };
- return responseHelper.paramValidationError(errorParams);
- }
-
- if (!basicHelper.isAddressValid(oThis.brandedTokenContractAddress)) {
- let errorParams = {
- internal_error_identifier: 's_d_a_validateParams_3',
- api_error_identifier: 'invalid_api_params',
- error_config: errorConfig,
- params_error_identifiers: ['branded_token_address_invalid'],
- debug_options: {}
- };
- return responseHelper.paramValidationError(errorParams);
- }
-
- if (!basicHelper.isAddressValid(oThis.workerContractAddress)) {
- let errorParams = {
- internal_error_identifier: 's_d_a_validateParams_4',
- api_error_identifier: 'invalid_api_params',
- error_config: errorConfig,
- params_error_identifiers: ['invalid_worker_address'],
- debug_options: {}
- };
- return responseHelper.paramValidationError(errorParams);
- }
-
- if (!oThis.baseCurrency) {
- let errorParams = {
- internal_error_identifier: 's_d_a_validateParams_5',
- api_error_identifier: 'invalid_api_params',
- error_config: errorConfig,
- params_error_identifiers: ['base_currency_invalid'],
- debug_options: {}
- };
- return responseHelper.paramValidationError(errorParams);
- }
-
- if (!basicHelper.isAddressValid(oThis.airdropBudgetHolder)) {
- let errorParams = {
- internal_error_identifier: 's_d_a_validateParams_6',
- api_error_identifier: 'invalid_api_params',
- error_config: errorConfig,
- params_error_identifiers: ['airdrop_budget_holder_invalid'],
- debug_options: {}
- };
- return responseHelper.paramValidationError(errorParams);
- }
-
- return responseHelper.successWithData({});
- },
-
- /**
- * deploy
- *
- * @return {promise}
- *
- */
- deploy: function () {
- const oThis = this
- ;
- oThis.constructorArgs = [
- oThis.brandedTokenContractAddress,
- web3Provider.utils.asciiToHex(oThis.baseCurrency),
- oThis.workerContractAddress,
- oThis.airdropBudgetHolder
- ];
- const DeployerObject = new DeployerKlass({
- contract_name: oThis.contractName,
- constructor_args: oThis.constructorArgs,
- gas_price: oThis.gasPrice,
- gas_limit: gasLimitGlobalConstant.deployAirdrop(),
- options: oThis.options
- });
- return DeployerObject.perform();
- }
-
-};
-
-module.exports = DeployAirdropKlass;
\ No newline at end of file
diff --git a/services/deploy/deployer.js b/services/deploy/deployer.js
deleted file mode 100644
index 6ebe322..0000000
--- a/services/deploy/deployer.js
+++ /dev/null
@@ -1,315 +0,0 @@
-"use strict";
-
-/**
- * This is script for deploying any contract.
- *
- * @module services/deploy/deployer
- */
-
-const uuid = require('uuid')
- , rootPrefix = '../..'
- , web3Provider = require(rootPrefix + '/lib/web3/providers/ws')
- , coreConstants = require(rootPrefix + '/config/core_constants')
- , coreAddresses = require(rootPrefix + '/config/core_addresses')
- , logger = require(rootPrefix + '/helpers/custom_console_logger')
- , responseHelper = require(rootPrefix + '/lib/formatter/response')
- , basicHelper = require(rootPrefix + '/helpers/basic_helper')
- , deployerName = 'deployer'
- , gasLimitGlobalConstant = require(rootPrefix + '/lib/global_constant/gas_limit')
- , paramErrorConfig = require(rootPrefix + '/config/param_error_config')
- , apiErrorConfig = require(rootPrefix + '/config/api_error_config')
-;
-
-const errorConfig = {
- param_error_config: paramErrorConfig,
- api_error_config: apiErrorConfig
-};
-
-/**
- * Constructor to create object of deployer
- *
- * @params {object} params -
- * @param {string} params.contract_name - name of contract
- * @param {object} params.constructor_args - contract deployment constructor arguments
- * @param {string} params.gas_price - gas price
- * @param {string} params.gas_limit - gas limit
- * @param {object} params.options - deployment options
- *
- * @constructor
- *
- */
-const DeployerKlass = function(params) {
- const oThis = this;
- params = params || {};
- logger.debug("\n=========deployer params=========");
- logger.debug(params);
-
- oThis.contractName = params.contract_name;
- oThis.constructorArgs = params.constructor_args;
- oThis.gasPrice = params.gas_price;
- oThis.gasLimit = params.gas_limit || gasLimitGlobalConstant.default();
- oThis.options = params.options;
-};
-
-DeployerKlass.prototype = {
-
- /**
- * Perform method
- *
- * @return {promise} - returns a promise which resolves to an object of kind Result
- *
- */
- perform: async function () {
-
- const oThis = this;
-
- try {
- var r = null;
-
- r = await oThis.validateParams();
- logger.debug("\n=========Deployer.validateParams.result=========");
- logger.debug(r);
- if(r.isFailure()) return r;
-
- r = oThis.deploy();
- logger.debug("\n=========Deployer.deploy.result=========");
- logger.debug(r);
- return r;
- } catch(err) {
- let errorParams = {
- internal_error_identifier: 's_am_ub_perform_1',
- api_error_identifier: 'unhandled_api_error',
- error_config: errorConfig,
- debug_options: { err: err }
- };
- return responseHelper.error(errorParams);
- }
-
- },
-
- /**
- * Validate deploy parameters
- *
- * @return {result} - returns object of kind Result
- *
- */
- validateParams: function() {
-
- const oThis = this;
-
- if (!oThis.contractName) {
- logger.error("Error: Contract name is mandatory");
- let errorParams = {
- internal_error_identifier: 'l_d_1',
- api_error_identifier: 'invalid_api_params',
- error_config: errorConfig,
- params_error_identifiers: ['contract_name_invalid'],
- debug_options: {}
- };
- return responseHelper.paramValidationError(errorParams);
- }
-
- if (!oThis.gasPrice) {
- let errorParams = {
- internal_error_identifier: 'l_d_2',
- api_error_identifier: 'invalid_api_params',
- error_config: errorConfig,
- params_error_identifiers: ['gas_price_invalid'],
- debug_options: {}
- };
- logger.error("%Error - Gas price is mandatory");
- return responseHelper.paramValidationError(errorParams);
- }
-
- if (!oThis.gasLimit) {
- let errorParams = {
- internal_error_identifier: 'l_d_3',
- api_error_identifier: 'invalid_api_params',
- error_config: errorConfig,
- params_error_identifiers: ['gas_limit_invalid'],
- debug_options: {}
- };
- logger.error("%Error - Gas limit is mandatory");
- return responseHelper.paramValidationError(errorParams);
- }
-
- const deployerAddress = coreAddresses.getAddressForUser(deployerName);
- if (!deployerAddress) {
- let errorParams = {
- internal_error_identifier: 'l_d_4',
- api_error_identifier: 'invalid_api_params',
- error_config: errorConfig,
- params_error_identifiers: ['deployer_invalid'],
- debug_options: {}
- };
- logger.error("%Error - Deployer address is invalid");
- return responseHelper.paramValidationError(errorParams);
- }
-
- const deployerAddrPassphrase = coreAddresses.getPassphraseForUser(deployerName);
- if (!deployerAddrPassphrase) {
- let errorParams = {
- internal_error_identifier: 'l_d_5',
- api_error_identifier: 'invalid_deployer_passphrase',
- error_config: errorConfig,
- debug_options: {}
- };
- logger.error("Error: Deployer passphrase is invalid");
- return responseHelper.error(errorParams);
- }
-
- return responseHelper.successWithData({});
-
- },
-
- /**
- * Deploy contract
- *
- * @return {promise} - returns a promise which resolves to an object of kind Result
- *
- */
- deploy: function() {
-
- const oThis = this;
-
- return new Promise(function (onResolve, onReject) {
-
- logger.debug("Contract name: " + oThis.contractName);
- logger.debug("Gas price: " + oThis.gasPrice);
- logger.debug("Constructor arguments: " + oThis.constructorArgs);
-
- const txUUID = uuid.v4();
- const returnType = basicHelper.getReturnType(oThis.options.returnType);
-
- const asyncPerform = function () {
-
- const deployerAddress = coreAddresses.getAddressForUser(deployerName);
- const deployerAddrPassphrase = coreAddresses.getPassphraseForUser(deployerName);
-
- const contractAbi = coreAddresses.getAbiForContract(oThis.contractName);
- const contractBin = coreAddresses.getBinForContract(oThis.contractName);
-
- const txParams = {
- from: deployerAddress,
- data: (web3Provider.utils.isHexStrict(contractBin) ? "" : "0x") + contractBin,
- gasPrice: oThis.gasPrice,
- gas: oThis.gasLimit
- };
-
- if (oThis.constructorArgs) {
- txParams.arguments = oThis.constructorArgs;
- }
-
- var contract = new web3Provider.eth.Contract(
- contractAbi,
- null,
- txParams
- );
-
- // this is needed since the contract object
- //contract.setProvider(web3Provider.currentProvider);
-
- // Unlock account
- web3Provider.eth.personal.unlockAccount(
- deployerAddress,
- deployerAddrPassphrase)
- .then(function() {
- const encodeABI = contract.deploy(txParams).encodeABI();
- txParams.data = encodeABI;
-
- web3Provider.eth.sendTransaction(txParams)
- .on('transactionHash', function(transactionHash) {
- logger.debug(`Transaction hash received for ${txUUID} :${transactionHash}`);
- if (basicHelper.isReturnTypeTxHash(returnType)) {
- return onResolve(
- responseHelper.successWithData(
- {
- transaction_uuid: txUUID,
- transaction_hash: transactionHash,
- transaction_receipt: {}
- }));
- }
- })
- .on('receipt', function(receipt) {
-
- const contractAddress = receipt.contractAddress;
- web3Provider.eth.getCode(contractAddress).then(function(code) {
- if (code.length <= 2) {
- if (basicHelper.isReturnTypeTxReceipt(returnType)) {
- let errorParams = {
- internal_error_identifier: 'l_d_6',
- api_error_identifier: 'contract_deploy_failed',
- error_config: errorConfig,
- debug_options: {}
- };
- return onResolve(responseHelper.error(errorParams));
- }
- } else if (basicHelper.isReturnTypeTxReceipt(returnType)) {
- logger.debug(`Contract deployment success: ${txUUID}`);
- return onResolve(
- responseHelper.successWithData(
- {
- transaction_uuid: txUUID,
- transaction_hash: receipt.transactionHash,
- transaction_receipt: receipt
- }));
- }
- })
- .catch(function(reason) {
- logger.error("%Error - Contract deployment failed. Reason", reason);
- if (basicHelper.isReturnTypeTxReceipt(returnType)) {
- let errorParams = {
- internal_error_identifier: 'l_d_7',
- api_error_identifier: 'unhandled_api_error',
- error_config: errorConfig,
- debug_options: {}
- };
- return onResolve(responseHelper.error(errorParams));
- }
- });
- })
- .catch(function(reason) {
- if (basicHelper.isReturnTypeTxReceipt(returnType)) {
- logger.error("%Error - Contract deployment failed. Reason: ", reason);
- let errorParams = {
- internal_error_identifier: 'l_d_8',
- api_error_identifier: 'unhandled_api_error',
- error_config: errorConfig,
- debug_options: {}
- };
- return onResolve(responseHelper.error(errorParams));
- }
- });
- })
- .catch(function(reason) {
- let errorParams = {
- internal_error_identifier: 'l_d_5',
- api_error_identifier: 'unhandled_api_error',
- error_config: errorConfig,
- debug_options: {}
- };
- logger.error('%Error - Transaction failed. Reason:', reason);
- return onResolve(responseHelper.error(errorParams));
- });
-
- };
- if (basicHelper.isReturnTypeUUID(returnType)) {
- asyncPerform();
- return onResolve(
- responseHelper.successWithData(
- {
- transaction_uuid: txUUID,
- transaction_hash: "",
- transaction_receipt: {}
- }));
- } else {
- return asyncPerform();
- }
-
- });
- }
-
-};
-
-module.exports = DeployerKlass;
-
diff --git a/services/deploy/workers.js b/services/deploy/workers.js
deleted file mode 100644
index 09b7941..0000000
--- a/services/deploy/workers.js
+++ /dev/null
@@ -1,143 +0,0 @@
-"use strict";
-
-/**
- *
- * This class would be used for deploying worker contract.
- *
- * @module services/deploy/worker
- *
- */
-
-const rootPrefix = '../..'
- , responseHelper = require(rootPrefix + '/lib/formatter/response')
- , logger = require(rootPrefix + '/helpers/custom_console_logger')
- , DeployerKlass = require(rootPrefix + '/services/deploy/deployer')
- , gasLimitGlobalConstant = require(rootPrefix + '/lib/global_constant/gas_limit')
- , paramErrorConfig = require(rootPrefix + '/config/param_error_config')
- , apiErrorConfig = require(rootPrefix + '/config/api_error_config')
-;
-
-const errorConfig = {
- param_error_config: paramErrorConfig,
- api_error_config: apiErrorConfig
-};
-
-/**
- * Constructor to create object of worker
- *
- * @param {object} params -
- * @param {string} params.gas_price - gas price
- * @param {number} params.chain_id - chain id
- * @param {object} params.options - deployment options e.g. {returnType: 'txReceipt'}
- *
- * @constructor
- *
- */
-const DeployWorkerKlass = function (params) {
- const oThis = this;
- params = params || {};
- logger.debug("=======DeployWorkerKlass.params=======");
- // Don't log passphrase
- logger.debug(params);
-
- oThis.contractName = 'workers';
- oThis.gasPrice = params.gas_price;
- oThis.options = params.options;
-
- oThis.constructorArgs = [];
-};
-
-DeployWorkerKlass.prototype = {
-
- /**
- * Perform method
- *
- * @return {promise}
- *
- */
- perform: async function () {
- const oThis = this
- ;
- try {
- var r = null;
-
- r = await oThis.validateParams();
- logger.debug("=======DeployWorkerKlass.validateParams.result=======");
- logger.debug(r);
- if (r.isFailure()) return r;
-
- r = await oThis.deploy();
- logger.debug("=======DeployWorkerKlass.setOps.result=======");
- logger.debug(r);
-
- return r;
-
- } catch (err) {
- let errorParams = {
- internal_error_identifier: 's_d_w_perform_1',
- api_error_identifier: 'unhandled_api_error',
- error_config: errorConfig,
- debug_options: { err: err }
- };
- return responseHelper.error(errorParams);
- }
-
- },
-
- /**
- * Validation of params
- *
- * @return {result}
- *
- */
- validateParams: function () {
- const oThis = this
- ;
-
- if (!oThis.gasPrice) {
- let errorParams = {
- internal_error_identifier: 's_d_w_validateParams_1',
- api_error_identifier: 'invalid_api_params',
- error_config: errorConfig,
- params_error_identifiers: ['gas_price_invalid'],
- debug_options: {}
- };
- return responseHelper.paramValidationError(errorParams);
- }
-
- if (!oThis.options) {
- let errorParams = {
- internal_error_identifier: 's_d_w_validateParams_2',
- api_error_identifier: 'invalid_api_params',
- error_config: errorConfig,
- params_error_identifiers: ['invalid_options'],
- debug_options: {}
- };
- return responseHelper.paramValidationError(errorParams);
- }
-
- return responseHelper.successWithData({});
- },
-
- /**
- * deploy
- *
- * @return {promise}
- *
- */
- deploy: function () {
- const oThis = this
- ;
- const DeployerObject = new DeployerKlass({
- contract_name: oThis.contractName,
- constructor_args: oThis.constructorArgs,
- gas_price: oThis.gasPrice,
- gas_limit: gasLimitGlobalConstant.deployWorker(),
- options: oThis.options
- });
- return DeployerObject.perform();
- }
-
-};
-
-module.exports = DeployWorkerKlass;
\ No newline at end of file
diff --git a/services/manifest.js b/services/manifest.js
deleted file mode 100644
index 2a5dcd8..0000000
--- a/services/manifest.js
+++ /dev/null
@@ -1,89 +0,0 @@
-"use strict";
-
-/**
- * Service manifest
- *
- * @module services/manifest
- */
-
-const rootPrefix = ".."
-
- , deployWorkers = require(rootPrefix + '/services/deploy/workers')
- , deployAirdrop = require(rootPrefix + '/services/deploy/airdrop')
-
- , register = require(rootPrefix + '/services/airdrop_management/register')
- , setAcceptedMargin = require(rootPrefix + '/services/airdrop_management/set_accepted_margin')
- , setPriceOracle = require(rootPrefix + '/services/airdrop_management/set_price_oracle')
- , transfer = require(rootPrefix + '/services/airdrop_management/transfer')
- , approve = require(rootPrefix + '/services/airdrop_management/approve')
- , batchAllocator = require(rootPrefix + '/services/airdrop_management/batch_allocator')
- , userBalance = require(rootPrefix + '/services/airdrop_management/user_balance')
- , pay = require(rootPrefix + '/services/airdrop_management/pay')
- , postAirdropPay = require(rootPrefix + '/services/airdrop_management/post_airdrop_pay')
-
- , setWorker = require(rootPrefix + '/services/workers/set_worker')
- , isWorker = require(rootPrefix + '/services/workers/is_worker')
-
- , getOps = require(rootPrefix + "/services/ops_managed/get_ops")
- , setOps = require(rootPrefix + "/services/ops_managed/set_ops")
-;
-
-/**
- * Service Manifest Constructor
- *
- * @constructor
- */
-const ServiceManifestKlass = function() {};
-
-ServiceManifestKlass.prototype = {
-
- /**
- * deploy any contract
- *
- * @constant {object}
- */
- deploy: {
- workers: deployWorkers,
- airdrop: deployAirdrop
- },
-
- /**
- * Ops Managed related services
- *
- * @constant {object}
- */
- opsManaged: {
- getOps: getOps,
- setOps: setOps
- },
-
- /**
- * workers
- *
- * @constant {object}
- */
- workers: {
- setWorker: setWorker,
- isWorker: isWorker
- },
-
- /**
- * airdrop Manager
- *
- * @constant {object}
- */
- airdropManager: {
- registerAirdrop: register,
- setPriceOracle: setPriceOracle,
- setAcceptedMargin: setAcceptedMargin,
- transfer: transfer,
- approve: approve,
- batchAllocator: batchAllocator,
- userBalance: userBalance,
- pay: pay,
- postAirdropPay: postAirdropPay
- },
-
-};
-
-module.exports = new ServiceManifestKlass();
\ No newline at end of file
diff --git a/services/ops_managed/get_ops.js b/services/ops_managed/get_ops.js
deleted file mode 100644
index 1a6cae5..0000000
--- a/services/ops_managed/get_ops.js
+++ /dev/null
@@ -1,152 +0,0 @@
-"use strict";
-
-/**
- *
- * This class would be used for executing getOps.
- *
- * @module services/ops_managed/get_ops
- *
- */
-
-const rootPrefix = '../..'
- , responseHelper = require(rootPrefix + '/lib/formatter/response')
- , basicHelper = require(rootPrefix + '/helpers/basic_helper')
- , logger = require(rootPrefix + '/helpers/custom_console_logger')
- , OpsManagedContractInteractKlass = require(rootPrefix + '/lib/contract_interact/ops_managed_contract')
- , paramErrorConfig = require(rootPrefix + '/config/param_error_config')
- , apiErrorConfig = require(rootPrefix + '/config/api_error_config')
-;
-
-const errorConfig = {
- param_error_config: paramErrorConfig,
- api_error_config: apiErrorConfig
-};
-
-/**
- * Constructor to create object of get_ops
- *
- * @constructor
- *
- * @param {object} params -
- * @param {string} params.contract_address - contract address
- * @param {string} params.gas_price - gas price
- * @param {object} params.chain_id - chain id
- *
- * @return {object}
- *
- */
-const GetOpsKlass = function (params) {
- const oThis = this;
- params = params || {};
- logger.debug("=======GetOpsKlass.params=======");
- logger.debug(params);
-
- oThis.contractAddress = params.contract_address;
- oThis.chainId = params.chain_id;
- oThis.gasPrice = params.gas_price;
-
-};
-
-GetOpsKlass.prototype = {
-
- /**
- * Perform method
- *
- * @return {promise}
- *
- */
- perform: async function () {
- const oThis = this
- ;
- try {
- var r = null;
-
- r = await oThis.validateParams();
- logger.debug("=======GetOpsKlass.validateParams.result=======");
- logger.debug(r);
- if (r.isFailure()) return r;
-
- r = await oThis.getOps();
- logger.debug("=======GetOpsKlass.getOps.result=======");
- logger.debug(r);
-
- return r;
-
- } catch (err) {
- let errorParams = {
- internal_error_identifier: 's_om_go_perform_1',
- api_error_identifier: 'unhandled_api_error',
- error_config: errorConfig,
- debug_options: { err: err }
- };
- return responseHelper.error(errorParams);
- }
-
- },
-
- /**
- * Validation of params
- *
- * @return {promise}
- *
- */
- validateParams: function () {
- const oThis = this
- ;
- if (!basicHelper.isAddressValid(oThis.contractAddress)) {
- let errorParams = {
- internal_error_identifier: 's_om_go_validateParams_1',
- api_error_identifier: 'invalid_api_params',
- error_config: errorConfig,
- params_error_identifiers: ['invalid_contract_address'],
- debug_options: {}
- };
- return responseHelper.paramValidationError(errorParams);
- }
-
- if (!oThis.gasPrice) {
- let errorParams = {
- internal_error_identifier: 's_om_go_validateParams_2',
- api_error_identifier: 'invalid_api_params',
- error_config: errorConfig,
- params_error_identifiers: ['gas_price_invalid'],
- debug_options: {}
- };
- return responseHelper.paramValidationError(errorParams);
- }
-
- if (!basicHelper.isValidChainId(oThis.chainId)) {
- let errorParams = {
- internal_error_identifier: 's_om_go_validateParams_3',
- api_error_identifier: 'invalid_api_params',
- error_config: errorConfig,
- params_error_identifiers: ['chain_id_invalid'],
- debug_options: {}
- };
- return responseHelper.paramValidationError(errorParams);
- }
-
- return responseHelper.successWithData({});
- },
-
- /**
- * get Ops
- *
- * @return {promise}
- *
- */
- getOps: function () {
- const oThis = this
- ;
-
- const OpsManagedContractInteractObject = new OpsManagedContractInteractKlass(
- oThis.contractAddress,
- oThis.gasPrice,
- oThis.chainId
- );
- return OpsManagedContractInteractObject.getOpsAddress();
- }
-
-};
-
-module.exports = GetOpsKlass;
\ No newline at end of file
diff --git a/services/ops_managed/set_ops.js b/services/ops_managed/set_ops.js
deleted file mode 100644
index d444d74..0000000
--- a/services/ops_managed/set_ops.js
+++ /dev/null
@@ -1,166 +0,0 @@
-"use strict";
-
-/**
- *
- * This class would be used for executing setOps.
- *
- * @module services/ops_managed/set_ops
- *
- */
-
-const rootPrefix = '../..'
- , responseHelper = require(rootPrefix + '/lib/formatter/response')
- , basicHelper = require(rootPrefix + '/helpers/basic_helper')
- , logger = require(rootPrefix + '/helpers/custom_console_logger')
- , OpsManagedContractInteractKlass = require(rootPrefix + '/lib/contract_interact/ops_managed_contract')
- , paramErrorConfig = require(rootPrefix + '/config/param_error_config')
- , apiErrorConfig = require(rootPrefix + '/config/api_error_config')
-;
-
-const errorConfig = {
- param_error_config: paramErrorConfig,
- api_error_config: apiErrorConfig
-};
-
-/**
- * Constructor to create object of set_ops
- *
- * @constructor
- *
- * @params {object} params -
- * @param {string} params.contract_address - contract address
- * @param {string} params.gas_price - gas price
- * @param {number} params.chain_id - chain id
- * @param {string} params.deployer_address - deployer address
- * @param {string} params.deployer_passphrase - deployer passphrase
- * @param {string} params.ops_address - ops addresses
- * @param {object} params.options - options
- *
- * @return {object}
- *
- */
-const SetOpsKlass = function (params) {
- const oThis = this;
- params = params || {};
- logger.debug("=======GetOpsKlass.params=======");
- // Don't log passphrase
- logger.debug(params.contract_address, params.gas_price, params.chain_id, params.deployer_address, params.ops_address, params.options);
-
- oThis.contractAddress = params.contract_address;
- oThis.gasPrice = params.gas_price;
- oThis.chainId = params.chain_id;
- oThis.deployerAddress = params.deployer_address;
- oThis.deployerPassphrase = params.deployer_passphrase;
- oThis.opsAddress = params.ops_address;
- oThis.options = params.options;
-
-};
-
-SetOpsKlass.prototype = {
-
- /**
- * Perform method
- *
- * @return {promise}
- *
- */
- perform: async function () {
- const oThis = this
- ;
- try {
- var r = null;
-
- r = await oThis.validateParams();
- logger.debug("=======SetOpsKlass.validateParams.result=======");
- logger.debug(r);
- if (r.isFailure()) return r;
-
- r = await oThis.setOps();
- logger.debug("=======SetOpsKlass.setOps.result=======");
- logger.debug(r);
-
- return r;
-
- } catch (err) {
- let errorParams = {
- internal_error_identifier: 's_om_go_perform_1',
- api_error_identifier: 'unhandled_api_error',
- error_config: errorConfig,
- debug_options: { err: err }
- };
- return responseHelper.error(errorParams);
- }
-
- },
-
- /**
- * Validation of params
- *
- * @return {result}
- *
- */
- validateParams: function () {
- const oThis = this
- ;
- if (!basicHelper.isAddressValid(oThis.contractAddress)) {
- let errorParams = {
- internal_error_identifier: 's_om_go_validateParams_1',
- api_error_identifier: 'invalid_api_params',
- error_config: errorConfig,
- params_error_identifiers: ['invalid_contract_address'],
- debug_options: {}
- };
- return responseHelper.paramValidationError(errorParams);
- }
-
- if (!oThis.gasPrice) {
- let errorParams = {
- internal_error_identifier: 's_om_go_validateParams_2',
- api_error_identifier: 'invalid_api_params',
- error_config: errorConfig,
- params_error_identifiers: ['gas_price_invalid'],
- debug_options: {}
- };
- return responseHelper.paramValidationError(errorParams);
- }
-
- if (!basicHelper.isValidChainId(oThis.chainId)) {
- let errorParams = {
- internal_error_identifier: 's_om_go_validateParams_3',
- api_error_identifier: 'invalid_api_params',
- error_config: errorConfig,
- params_error_identifiers: ['chain_id_invalid'],
- debug_options: {}
- };
- return responseHelper.paramValidationError(errorParams);
- }
-
- return responseHelper.successWithData({});
- },
-
- /**
- * set Ops
- *
- * @return {promise}
- *
- */
- setOps: function () {
- const oThis = this
- ;
-
- const OpsManagedContractInteractObject = new OpsManagedContractInteractKlass(
- oThis.contractAddress,
- oThis.gasPrice,
- oThis.chainId
- );
- return OpsManagedContractInteractObject.setOpsAddress(
- oThis.deployerAddress,
- oThis.deployerPassphrase,
- oThis.opsAddress,
- oThis.options
- );
- }
-
-};
-
-module.exports = SetOpsKlass;
\ No newline at end of file
diff --git a/services/workers/is_worker.js b/services/workers/is_worker.js
deleted file mode 100644
index 100e8a0..0000000
--- a/services/workers/is_worker.js
+++ /dev/null
@@ -1,139 +0,0 @@
-"use strict";
-
-/**
- *
- * This class would be used for executing worker is_worker.
- *
- * @module services/workers/is_worker
- *
- */
-
-const rootPrefix = '../..'
- , responseHelper = require(rootPrefix + '/lib/formatter/response')
- , basicHelper = require(rootPrefix + '/helpers/basic_helper')
- , logger = require(rootPrefix + '/helpers/custom_console_logger')
- , WorkersContractInteractKlass = require(rootPrefix + '/lib/contract_interact/workers')
- , paramErrorConfig = require(rootPrefix + '/config/param_error_config')
- , apiErrorConfig = require(rootPrefix + '/config/api_error_config')
-;
-
-const errorConfig = {
- param_error_config: paramErrorConfig,
- api_error_config: apiErrorConfig
-};
-
-/**
- * Constructor to create object of register
- *
- * @constructor
- *
- * @params {object} params -
- * @param {string} params.workers_contract_address - contract address of workers
- * @param {string} params.worker_address - worker address
- * @param {object} params.chain_id - chain id
- *
- * @return {Object}
- *
- */
-const IsWorkerKlass = function (params) {
- const oThis = this;
- params = params || {};
- logger.debug("=======IsWorkerKlass.params=======");
- logger.debug(params);
-
- oThis.workersContractAddress = params.workers_contract_address;
- oThis.workerAddress = params.worker_address;
- oThis.chainId = params.chain_id;
-
-};
-
-IsWorkerKlass.prototype = {
-
- /**
- * Perform method
- *
- * @return {promise}
- *
- */
- perform: async function () {
- const oThis = this
- ;
- try {
- var r = null;
-
- r = await oThis.validateParams();
- logger.debug("=======IsWorkerKlass.validateParams.result=======");
- logger.debug(r);
- if (r.isFailure()) return r;
-
- r = await oThis.isWorker();
- logger.debug("=======IsWorkerKlass.setWorker.result=======");
- logger.debug(r);
-
- return r;
-
- } catch (err) {
- let errorParams = {
- internal_error_identifier: 's_w_iw_perform_1',
- api_error_identifier: 'unhandled_api_error',
- error_config: errorConfig,
- debug_options: { err: err }
- };
- return responseHelper.error(errorParams);
- }
-
- },
-
- /**
- * Validation of params
- *
- * @return {result}
- *
- */
- validateParams: function () {
- const oThis = this
- ;
- if (!basicHelper.isAddressValid(oThis.workerAddress)) {
- let errorParams = {
- internal_error_identifier: 's_w_iw_validateParams_1',
- api_error_identifier: 'invalid_api_params',
- error_config: errorConfig,
- params_error_identifiers: ['invalid_worker_address'],
- debug_options: {}
- };
- return responseHelper.paramValidationError(errorParams);
- }
-
- if (!basicHelper.isValidChainId(oThis.chainId)) {
- let errorParams = {
- internal_error_identifier: 's_w_iw_validateParams_2',
- api_error_identifier: 'invalid_api_params',
- error_config: errorConfig,
- params_error_identifiers: ['chain_id_invalid'],
- debug_options: {}
- };
- return responseHelper.paramValidationError(errorParams);
- }
-
- return responseHelper.successWithData({});
- },
-
- /**
- * is Worker
- *
- * @return {promise}
- *
- */
- isWorker: function () {
- const oThis = this
- ;
- const workersContractInteractObject = new WorkersContractInteractKlass(
- oThis.workersContractAddress,
- oThis.chainId
- );
- return workersContractInteractObject.isWorker(oThis.workerAddress);
- }
-
-};
-
-module.exports = IsWorkerKlass;
\ No newline at end of file
diff --git a/services/workers/set_worker.js b/services/workers/set_worker.js
deleted file mode 100644
index 49afd03..0000000
--- a/services/workers/set_worker.js
+++ /dev/null
@@ -1,221 +0,0 @@
-"use strict";
-
-/**
- *
- * This class would be used for executing airdrop register.
- *
- * @module services/workers/set_worker
- *
- */
-
-const rootPrefix = '../..'
- , responseHelper = require(rootPrefix + '/lib/formatter/response')
- , basicHelper = require(rootPrefix + '/helpers/basic_helper')
- , logger = require(rootPrefix + '/helpers/custom_console_logger')
- , BigNumber = require('bignumber.js')
- , WorkersContractInteractKlass = require(rootPrefix + '/lib/contract_interact/workers')
- , paramErrorConfig = require(rootPrefix + '/config/param_error_config')
- , apiErrorConfig = require(rootPrefix + '/config/api_error_config')
-;
-
-const errorConfig = {
- param_error_config: paramErrorConfig,
- api_error_config: apiErrorConfig
-};
-
-/**
- * Constructor to create object of register
- *
- * @constructor
- *
- * @param {object} params -
- * @param {string} params.workers_contract_address - contract address of workers
- * @param {string} params.sender_address - address of sender
- * @param {string} params.sender_passphrase - passphrase of sender
- * @param {string} params.worker_address - worker address
- * @param {number} params.deactivation_height - block number till which the worker is valid
- * @param {bignumber} params.gas_price - gas price
- * @param {number} params.chain_id - chain id
- * @param {object} params.options - for params like returnType, tag.
- *
- * @return {object}
- *
- */
-const SetWorkerKlass = function (params) {
- const oThis = this;
- params = params || {};
- logger.debug("=======SetWorkerKlass.params=======");
- // Don't log passphrase
- logger.debug(params.workers_contract_address, params.sender_address, params.worker_address, params.deactivation_height, params.gas_price, params.chain_id, params.options);
-
- oThis.workersContractAddress = params.workers_contract_address;
- oThis.senderAddress = params.sender_address;
- oThis.senderPassphrase = params.sender_passphrase;
- oThis.workerAddress = params.worker_address;
- oThis.deactivationHeight = params.deactivation_height;
- oThis.gasPrice = params.gas_price;
- oThis.chainId = params.chain_id;
- oThis.options = params.options
-
-};
-
-SetWorkerKlass.prototype = {
-
- /**
- * Perform method
- *
- * @return {promise}
- *
- */
- perform: async function () {
- const oThis = this
- ;
-
- try {
- var r = null;
-
- r = await oThis.validateParams();
- logger.debug("=======SetWorkerKlass.validateParams.result=======");
- logger.debug(r);
- if (r.isFailure()) return r;
-
- r = await oThis.setWorker();
- logger.debug("=======SetWorkerKlass.setWorker.result=======");
- logger.debug(r);
-
- return r;
-
- } catch (err) {
- let errorParams = {
- internal_error_identifier: 's_w_sw_perform_1',
- api_error_identifier: 'unhandled_api_error',
- error_config: errorConfig,
- debug_options: { err: err }
- };
- return responseHelper.error(errorParams);
- }
-
- },
-
- /**
- * Validation of params
- *
- * @return {result}
- *
- */
- validateParams: function () {
- const oThis = this;
- if (!basicHelper.isAddressValid(oThis.workersContractAddress)) {
- let errorParams = {
- internal_error_identifier: 's_w_sw_validateParams_1',
- api_error_identifier: 'invalid_api_params',
- error_config: errorConfig,
- params_error_identifiers: ['invalid_worker_address'],
- debug_options: {}
- };
- return responseHelper.paramValidationError(errorParams);
- }
- if (!oThis.gasPrice) {
- let errorParams = {
- internal_error_identifier: 's_w_sw_validateParams_2',
- api_error_identifier: 'invalid_api_params',
- error_config: errorConfig,
- params_error_identifiers: ['gas_price_invalid'],
- debug_options: {}
- };
- return responseHelper.paramValidationError(errorParams);
- }
- if (!basicHelper.isAddressValid(oThis.senderAddress)) {
- let errorParams = {
- internal_error_identifier: 's_w_sw_validateParams_3',
- api_error_identifier: 'invalid_api_params',
- error_config: errorConfig,
- params_error_identifiers: ['invalid_sender_address'],
- debug_options: {}
- };
- return responseHelper.paramValidationError(errorParams);
- }
- if (!basicHelper.isAddressValid(oThis.workerAddress)) {
- let errorParams = {
- internal_error_identifier: 's_w_sw_validateParams_4',
- api_error_identifier: 'invalid_api_params',
- error_config: errorConfig,
- params_error_identifiers: ['invalid_worker_address'],
- debug_options: {}
- };
- return responseHelper.paramValidationError(errorParams);
- }
- if (!oThis.deactivationHeight) {
- let errorParams = {
- internal_error_identifier: 's_w_sw_validateParams_5',
- api_error_identifier: 'invalid_api_params',
- error_config: errorConfig,
- params_error_identifiers: ['deactivation_height_invalid'],
- debug_options: {}
- };
- return responseHelper.paramValidationError(errorParams);
- }
- const deactivationHeight = new BigNumber(oThis.deactivationHeight);
- if (deactivationHeight.isNaN() || deactivationHeight.lt(0) || !deactivationHeight.isInteger()) {
- let errorParams = {
- internal_error_identifier: 's_w_sw_validateParams_6',
- api_error_identifier: 'invalid_api_params',
- error_config: errorConfig,
- params_error_identifiers: ['deactivation_height_invalid'],
- debug_options: {}
- };
- return responseHelper.paramValidationError(errorParams);
- }
-
- if (!oThis.gasPrice) {
- let errorParams = {
- internal_error_identifier: 's_w_sw_validateParams_7',
- api_error_identifier: 'invalid_api_params',
- error_config: errorConfig,
- params_error_identifiers: ['gas_price_invalid'],
- debug_options: {}
- };
- return responseHelper.paramValidationError(errorParams);
- }
-
- if (!basicHelper.isValidChainId(oThis.chainId)) {
- let errorParams = {
- internal_error_identifier: 's_w_sw_validateParams_8',
- api_error_identifier: 'invalid_api_params',
- error_config: errorConfig,
- params_error_identifiers: ['chain_id_invalid'],
- debug_options: {}
- };
- return responseHelper.paramValidationError(errorParams);
- }
-
- return responseHelper.successWithData({});
- },
-
- /**
- * Set Worker
- *
- * @return {promise}
- *
- */
- setWorker: function () {
- const oThis = this
- ;
-
- const workersContractInteractObject = new WorkersContractInteractKlass(
- oThis.workersContractAddress,
- oThis.chainId
- );
- return workersContractInteractObject.setWorker(
- oThis.senderAddress,
- oThis.senderPassphrase,
- oThis.workerAddress,
- oThis.deactivationHeight.toString(10),
- oThis.gasPrice,
- oThis.options
- );
- }
-
-};
-
-module.exports = SetWorkerKlass;
\ No newline at end of file
diff --git a/test/contracts/airdrop/airdrop_utils.js b/test/contracts/airdrop/airdrop_utils.js
deleted file mode 100644
index d8bf3cb..0000000
--- a/test/contracts/airdrop/airdrop_utils.js
+++ /dev/null
@@ -1,70 +0,0 @@
-// Copyright 2018 OpenST Ltd.
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-//
-// ----------------------------------------------------------------------------
-// Test: airdrop_utils.js
-//
-// http://www.simpletoken.org/
-//
-// ----------------------------------------------------------------------------
-
-const Utils = require('../../lib/utils.js'),
- BigNumber = require('bignumber.js'),
- Workers = artifacts.require('./Workers.sol'),
- Airdrop = artifacts.require('./Airdrop.sol'),
- EIP20TokenMock = artifacts.require('./EIP20TokenMock.sol'),
- PriceOracle = artifacts.require('./PriceOracleMock.sol'),
- web3 = require('../../lib/web3') ;
-
-const ost = 'OST',
- abc = 'ABC'
- ;
-
-/// @dev Export common requires
-module.exports.utils = Utils;
-module.exports.bigNumber = BigNumber;
-
-/// @dev Export constants
-module.exports.currencies = {
- ost : ost,
- abc : abc
-}
-
-/// @dev Deploy
-module.exports.deployAirdrop = async (artifacts, accounts) => {
-
- const conversionRate = 101,
- conversionRateDecimals = 1,
- token = await EIP20TokenMock.new(conversionRate, conversionRateDecimals, ost, 'name', 18),
- TOKEN_DECIMALS = 18,
- opsAddress = accounts[1],
- worker = accounts[2],
- airdropBudgetHolder = accounts[3],
- workers = await Workers.new(),
- airdrop = await Airdrop.new(token.address, ost, workers.address, airdropBudgetHolder),
- abcPrice = new BigNumber(20 * 10**18),
- abcPriceOracle = await PriceOracle.new(ost, abc, abcPrice)
- ;
-
- assert.ok(await workers.setOpsAddress(opsAddress));
- assert.ok(await airdrop.setOpsAddress(opsAddress));
- let blockNumber = await web3.eth.getBlockNumber();
- assert.ok(await workers.setWorker(worker, blockNumber + 1000, { from: opsAddress }));
- assert.ok(await airdrop.setPriceOracle(abc, abcPriceOracle.address, { from: opsAddress }));
-
- return {
- token : token,
- airdrop : airdrop
- };
-};
diff --git a/test/contracts/airdrop/base.js b/test/contracts/airdrop/base.js
deleted file mode 100644
index 763d275..0000000
--- a/test/contracts/airdrop/base.js
+++ /dev/null
@@ -1,35 +0,0 @@
-// Copyright 2018 OpenST Ltd.
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-//
-// ----------------------------------------------------------------------------
-// Test: base.js
-//
-// http://www.simpletoken.org/
-//
-// ----------------------------------------------------------------------------
-
-const airdropUtils = require('./airdrop_utils.js'),
- constructor = require('./constructor.js'),
- payAirdrop = require('./pay_airdrop.js')
- ;
-
-contract('Airdrop', function(accounts) {
- describe('Constructor', async () => constructor.perform(accounts));
- describe('PayAirdrop', async () => payAirdrop.perform(accounts));
- after(async () => {
- airdropUtils.utils.printGasStatistics();
- airdropUtils.utils.clearReceipts();
- });
-
-});
diff --git a/test/contracts/airdrop/constructor.js b/test/contracts/airdrop/constructor.js
deleted file mode 100644
index 8e1dd6a..0000000
--- a/test/contracts/airdrop/constructor.js
+++ /dev/null
@@ -1,59 +0,0 @@
-// Copyright 2018 OpenST Ltd.
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-//
-// ----------------------------------------------------------------------------
-// Test: constructor.js
-//
-// http://www.simpletoken.org/
-//
-// ----------------------------------------------------------------------------
-
-const airdropUtils = require('./airdrop_utils.js'),
- Airdrop = artifacts.require('./Airdrop.sol'),
- EIP20TokenMock = artifacts.require('./EIP20TokenMock.sol')
- ;
-
-///
-/// Test stories
-///
-/// fails to deploy if workers is null
-/// fails to deploy if airdropBudgetHolder is null
-/// successfully deploys
-
-module.exports.perform = (accounts) => {
- const workers = accounts[2],
- airdropBudgetHolder = accounts[3]
- ;
-
- var token = null;
-
- before(async () => {
- token = await EIP20TokenMock.new(1, 0, airdropUtils.currencies.ost, 'name', 18);
- });
-
- it('fails to deploy if workers is null', async () => {
- await airdropUtils.utils.expectThrow(Airdrop.new(token.address, airdropUtils.currencies.ost, 0, airdropBudgetHolder));
- });
-
- it('fails to deploy if airdropBudgetHolder is null', async () => {
- await airdropUtils.utils.expectThrow(Airdrop.new(token.address, airdropUtils.currencies.ost, workers, 0));
- });
-
- it('successfully deploys', async () => {
- var airdrop = await Airdrop.new(token.address, airdropUtils.currencies.ost, workers, airdropBudgetHolder);
- assert.equal(await airdrop.workers.call(), workers);
- assert.equal(await airdrop.airdropBudgetHolder.call(), airdropBudgetHolder);
- airdropUtils.utils.logTransaction(airdrop.transactionHash, 'Airdrop.constructor');
- });
-}
\ No newline at end of file
diff --git a/test/contracts/airdrop/pay_airdrop.js b/test/contracts/airdrop/pay_airdrop.js
deleted file mode 100644
index 98df0de..0000000
--- a/test/contracts/airdrop/pay_airdrop.js
+++ /dev/null
@@ -1,167 +0,0 @@
-// Copyright 2018 OpenST Ltd.
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-//
-// ----------------------------------------------------------------------------
-// Test: pay_airdrop.js
-//
-// http://www.simpletoken.org/
-//
-// ----------------------------------------------------------------------------
-
-const airdropUtils = require('./airdrop_utils.js');
-
-///
-/// Test stories
-///
-/// fails to airdrop and pay if msg.sender is not an active worker
-/// fails to airdrop and pay if spender is null
-/// fails to airdrop and pay if beneficiary data is not valid
-/// fails to airdrop and pay if unable to perfrom airdrop transfer to spender
-/// fails to airdrop and pay if unable to perform transfers
-/// successfully airdrops and pays
-/// when currency is not empty
-/// fails to airdrop and pay if unable to validate margin and calculate BT amount
-/// successfully airdrops and pays
-
-module.exports.perform = (accounts) => {
- const opsAddress = accounts[1],
- worker = accounts[2],
- airdropBudgetHolder = accounts[3],
- beneficiary = accounts[4],
- transferAmount = new airdropUtils.bigNumber(5 * 10**18),
- commissionBeneficiary = accounts[5],
- commissionAmount = new airdropUtils.bigNumber(1.25 * 10**18),
- spender = accounts[6],
- airdropAmount = new airdropUtils.bigNumber(10 * 10**18)
- ;
-
- var contracts = null,
- token = null,
- airdrop = null,
- response = null
- ;
-
- before(async () => {
- contracts = await airdropUtils.deployAirdrop(artifacts, accounts);
- token = contracts.token;
- airdrop = contracts.airdrop;
-
- await token.setBalance(airdropBudgetHolder, airdropAmount);
- });
-
- it('fails to airdrop and pay if msg.sender is not an active worker', async () => {
- await airdropUtils.utils.expectThrow(airdrop.payAirdrop.call(beneficiary, transferAmount, commissionBeneficiary, commissionAmount,
- '', 0, spender, airdropAmount, { from: opsAddress }));
- });
-
- it('fails to airdrop and pay if spender is null', async () => {
- await airdropUtils.utils.expectThrow(airdrop.payAirdrop.call(beneficiary, transferAmount, commissionBeneficiary, commissionAmount,
- '', 0, 0, airdropAmount, { from: worker }));
- });
-
- it('fails to airdrop and pay if isValidBeneficiaryData returns false', async () => {
- // transferAmount == 0
- await airdropUtils.utils.expectThrow(airdrop.payAirdrop.call(beneficiary, 0, commissionBeneficiary, commissionAmount,
- '', 0, spender, airdropAmount, { from: worker }));
- });
-
- it('fails to airdrop and pay if unable to perfrom airdrop transfer to spender', async () => {
- await airdropUtils.utils.expectThrow(airdrop.payAirdrop.call(beneficiary, transferAmount, commissionBeneficiary, commissionAmount,
- '', 0, spender, airdropAmount, { from: worker }));
- });
-
- it('fails to airdrop and pay if unable to perform transfers', async () => {
- await token.approve(airdrop.address, airdropAmount, { from: airdropBudgetHolder });
- await airdropUtils.utils.expectThrow(airdrop.payAirdrop.call(beneficiary, transferAmount, commissionBeneficiary, commissionAmount,
- '', 0, spender, airdropAmount, { from: worker }));
- });
-
- it('successfully airdrops and pays', async () => {
- await token.approve(airdrop.address, transferAmount.plus(commissionAmount), { from: spender });
- var returns = await airdrop.payAirdrop.call(beneficiary, transferAmount, commissionBeneficiary, commissionAmount,
- '', 0, spender, airdropAmount, { from: worker });
- var totalPaid = returns[0]
- , airdropUsed = returns[1];
- assert.equal((totalPaid).toNumber(), transferAmount.plus(commissionAmount).toNumber());
-
-
- response = await airdrop.payAirdrop(beneficiary, transferAmount, commissionBeneficiary, commissionAmount,
- '', 0, spender, airdropAmount, { from: worker });
- assert.equal(await token.balanceOf.call(spender), 0);
- // Airdrop only uses as much of the airdrop amount as required to cover total paid
- assert.equal((await token.allowance.call(airdropBudgetHolder, airdrop.address)).toNumber(), airdropAmount.minus(totalPaid).toNumber());
- assert.equal((await token.balanceOf.call(beneficiary)).toNumber(), transferAmount.toNumber());
- assert.equal((await token.balanceOf.call(commissionBeneficiary)).toNumber(), commissionAmount.toNumber());
- // transferAmount == tokenAmount when currency is null
- // commissionAmount == commissionTokenAmount when currency is null
- checkAirdropPaymentEvent(response.logs[0], beneficiary, transferAmount, commissionBeneficiary, commissionAmount, '', 0, spender, airdropUsed);
- airdropUtils.utils.logResponse(response, 'Airdrop.payAirdrop: ' + totalPaid);
- });
-
- context('when currency is not empty', async () => {
- before(async () => {
- // reset balances and approvals
- await token.setBalance(airdropBudgetHolder, airdropAmount);
- await token.setBalance(spender, 0);
- await token.setBalance(beneficiary, 0);
- await token.setBalance(commissionBeneficiary, 0);
- await token.approve(airdrop.address, airdropAmount, { from: airdropBudgetHolder });
- });
-
- it('fails to airdrop and pay if unable to validate margin and calculate BT amount', async () => {
- // intendedPricePoint == 0
- await airdropUtils.utils.expectThrow(airdrop.payAirdrop.call(beneficiary, transferAmount, commissionBeneficiary, commissionAmount,
- airdropUtils.currencies.abc, 0, spender, airdropAmount, { from: worker }));
- });
-
- it('successfully airdrops and pays', async () => {
- response = await airdrop.getPricePointAndCalculatedAmounts.call(transferAmount, commissionAmount, airdropUtils.currencies.abc);
- var intendedPricePoint = response[0];
- var tokenAmount = response[1];
- var commissionTokenAmount = response[2];
- await token.approve(airdrop.address, tokenAmount.plus(commissionTokenAmount), { from: spender });
-
- var returns = await airdrop.payAirdrop.call(beneficiary, transferAmount, commissionBeneficiary, commissionAmount,
- airdropUtils.currencies.abc, intendedPricePoint, spender, airdropAmount, { from: worker });
- var totalPaid = returns[0]
- , airdropUsed = returns[1];
- assert.equal((totalPaid).toNumber(), tokenAmount.plus(commissionTokenAmount).toNumber());
-
- response = await airdrop.payAirdrop(beneficiary, transferAmount, commissionBeneficiary, commissionAmount,
- airdropUtils.currencies.abc, intendedPricePoint, spender, airdropAmount, { from: worker });
- assert.equal(await token.balanceOf.call(spender), 0);
- // Airdrop only uses as much of the airdrop amount as required to cover total paid
- assert.equal((await token.allowance.call(airdropBudgetHolder, airdrop.address)).toNumber(), airdropAmount.minus(totalPaid).toNumber());
- assert.equal((await token.balanceOf.call(beneficiary)).toNumber(), tokenAmount.toNumber());
- assert.equal((await token.balanceOf.call(commissionBeneficiary)).toNumber(), commissionTokenAmount.toNumber());
- checkAirdropPaymentEvent(response.logs[0], beneficiary, tokenAmount, commissionBeneficiary, commissionTokenAmount,
- airdropUtils.currencies.abc, intendedPricePoint, spender, airdropUsed);
- airdropUtils.utils.logResponse(response, 'Airdrop.payAirdrop (currency): ' + totalPaid);
- });
- });
-}
-
-function checkAirdropPaymentEvent(event, _beneficiary, _tokenAmount, _commissionBeneficiary, _commissionTokenAmount, _currency, _actualPricePoint, _spender, _airdropUsed) {
- assert.equal(event.event, 'AirdropPayment');
- assert.equal(event.args._beneficiary, _beneficiary);
- assert.equal(event.args._tokenAmount.toNumber(), _tokenAmount);
- assert.equal(event.args._commissionBeneficiary, _commissionBeneficiary);
- assert.equal(event.args._commissionTokenAmount.toNumber(), _commissionTokenAmount);
- if (_currency) {
- assert.equal(web3.toAscii(event.args._currency), _currency);
- }
- assert.equal(event.args._actualPricePoint.toNumber(), _actualPricePoint);
- assert.equal(event.args._spender, _spender);
- assert.equal(event.args._airdropUsed.toNumber(), _airdropUsed);
-}
diff --git a/test/contracts/pricer/base.js b/test/contracts/pricer/base.js
deleted file mode 100644
index f0afce8..0000000
--- a/test/contracts/pricer/base.js
+++ /dev/null
@@ -1,49 +0,0 @@
-// Copyright 2018 OpenST Ltd.
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-//
-// ----------------------------------------------------------------------------
-// Test: base.js
-//
-// http://www.simpletoken.org/
-//
-// ----------------------------------------------------------------------------
-
-const pricerUtils = require('./pricer_utils.js'),
- constructor = require('./constructor.js'),
- properties = require('./properties.js'),
- set_price_oracle = require('./set_price_oracle.js'),
- unset_price_oracle = require('./unset_price_oracle.js'),
- set_accepted_margin = require('./set_accepted_margin.js'),
- get_price_point = require('./get_price_point.js'),
- get_price_point_and_calculated_amounts = require('./get_price_point_and_calculated_amounts.js'),
- pay = require('./pay.js')
- ;
-
-contract('Pricer', function(accounts) {
- // TODO: include PricerMock that wraps getBTAmountFromCurrencyValue and isPricePointInRange
- // by public functions to enable testing OR make them public functions
- describe('Constructor', async () => constructor.perform());
- describe('Properties', async () => properties.perform(accounts));
- describe('SetPriceOracle', async () => set_price_oracle.perform(accounts));
- describe('UnsetPriceOracle', async () => unset_price_oracle.perform(accounts));
- describe('SetAcceptedMargin', async () => set_accepted_margin.perform(accounts));
- describe('GetPricePoint', async () => get_price_point.perform(accounts));
- describe('GetPricePointAndCalculatedAmounts', async () => get_price_point_and_calculated_amounts.perform(accounts));
- describe('Pay', async () => pay.perform(accounts));
- after(async () => {
- pricerUtils.utils.printGasStatistics();
- pricerUtils.utils.clearReceipts();
- });
-
-});
diff --git a/test/contracts/pricer/constructor.js b/test/contracts/pricer/constructor.js
deleted file mode 100644
index aaca9ce..0000000
--- a/test/contracts/pricer/constructor.js
+++ /dev/null
@@ -1,55 +0,0 @@
-// Copyright 2018 OpenST Ltd.
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-//
-// ----------------------------------------------------------------------------
-// Test: constructor.js
-//
-// http://www.simpletoken.org/
-//
-// ----------------------------------------------------------------------------
-
-const pricerUtils = require('./pricer_utils.js'),
- Pricer = artifacts.require('./Pricer.sol'),
- EIP20TokenMock = artifacts.require('./EIP20TokenMock.sol')
- ;
-
-///
-/// Test stories
-///
-/// fails to deploy if brandedToken is null
-/// fails to deploy if baseCurrency is empty
-/// successfully deploys
-
-module.exports.perform = () => {
- var token = null,
- response = null
- ;
-
- before(async () => {
- token = await EIP20TokenMock.new(1, 0, pricerUtils.currencies.ost, 'name', 18);
- });
-
- it('fails to deploy if brandedToken is null', async () => {
- await pricerUtils.utils.expectThrow(Pricer.new(0, pricerUtils.currencies.ost));
- });
-
- it('fails to deploy if baseCurrency is empty', async () => {
- await pricerUtils.utils.expectThrow(Pricer.new(token.address, ''));
- });
-
- it('successfully deploys', async () => {
- response = await Pricer.new(token.address, pricerUtils.currencies.ost);
- pricerUtils.utils.logTransaction(response.transactionHash, 'Pricer.constructor');
- });
-}
diff --git a/test/contracts/pricer/get_price_point.js b/test/contracts/pricer/get_price_point.js
deleted file mode 100644
index 5c4b947..0000000
--- a/test/contracts/pricer/get_price_point.js
+++ /dev/null
@@ -1,60 +0,0 @@
-// Copyright 2018 OpenST Ltd.
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-//
-// ----------------------------------------------------------------------------
-// Test: get_price_point.js
-//
-// http://www.simpletoken.org/
-//
-// ----------------------------------------------------------------------------
-
-const pricerUtils = require('./pricer_utils.js');
-
-///
-/// Test stories
-///
-/// fails if priceOracle is not set
-/// successfully returns price from priceOracle
-
-module.exports.perform = (accounts) => {
- const opsAddress = accounts[1],
- abcPrice = new pricerUtils.bigNumber(20 * 10**18),
- xyzPrice = new pricerUtils.bigNumber(10 * 10**18)
- ;
-
- var contracts = null,
- pricer = null,
- abcPriceOracle = null,
- xyzPriceOracle = null,
- response = null
- ;
-
- before(async () => {
- contracts = await pricerUtils.deployPricer(artifacts, accounts);
- pricer = contracts.pricer;
- abcPriceOracle = contracts.abcPriceOracle;
- xyzPriceOracle = contracts.xyzPriceOracle;
- await pricer.setPriceOracle(pricerUtils.currencies.abc, abcPriceOracle.address, { from: opsAddress });
- await pricer.setPriceOracle(pricerUtils.currencies.xyz, xyzPriceOracle.address, { from: opsAddress });
- });
-
- it('fails if priceOracle is not set', async () => {
- await pricerUtils.utils.expectThrow(pricer.getPricePoint.call(pricerUtils.currencies.ost));
- });
-
- it('successfully returns price from priceOracle', async () => {
- assert.equal((await pricer.getPricePoint.call(pricerUtils.currencies.abc)).toNumber(), abcPrice);
- assert.equal((await pricer.getPricePoint.call(pricerUtils.currencies.xyz)).toNumber(), xyzPrice);
- });
-}
diff --git a/test/contracts/pricer/get_price_point_and_calculated_amounts.js b/test/contracts/pricer/get_price_point_and_calculated_amounts.js
deleted file mode 100644
index 8d9dd2e..0000000
--- a/test/contracts/pricer/get_price_point_and_calculated_amounts.js
+++ /dev/null
@@ -1,95 +0,0 @@
-// Copyright 2018 OpenST Ltd.
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-//
-// ----------------------------------------------------------------------------
-// Test: get_price_point_and_calculated_amounts.js
-//
-// http://www.simpletoken.org/
-//
-// ----------------------------------------------------------------------------
-
-const pricerUtils = require('./pricer_utils.js'),
- PriceOracle = artifacts.require('./PriceOracleMock.sol')
- ;
-
-///
-/// Test stories
-///
-/// fails to get pricePoint and calculated amounts if currency is empty
-/// fails to get pricePoint and calculated amounts if priceOracle is not set
-/// successfully gets pricePoints and calculated amounts
-/// when oracle returns 0 for price
-/// fails to get pricePoint and calculated amounts
-
-module.exports.perform = (accounts) => {
- const opsAddress = accounts[1],
- abcPrice = new pricerUtils.bigNumber(20 * 10**18),
- xyzPrice = new pricerUtils.bigNumber(10 * 10**18),
- transferAmount = new pricerUtils.bigNumber(5 * 10**18),
- commissionAmount = new pricerUtils.bigNumber(1.25 * 10**18)
- ;
-
- var contracts = null,
- pricer = null,
- abcPriceOracle = null,
- xyzPriceOracle = null
- ;
-
- before(async () => {
- contracts = await pricerUtils.deployPricer(artifacts, accounts);
- pricer = contracts.pricer;
- abcPriceOracle = contracts.abcPriceOracle;
- xyzPriceOracle = contracts.xyzPriceOracle;
- await pricer.setPriceOracle(pricerUtils.currencies.abc, abcPriceOracle.address, { from: opsAddress });
- await pricer.setPriceOracle(pricerUtils.currencies.xyz, xyzPriceOracle.address, { from: opsAddress });
- });
-
- it('fails to get pricePoint and calculated amounts if currency is empty', async () => {
- await pricerUtils.utils.expectThrow(pricer.getPricePointAndCalculatedAmounts.call(
- transferAmount, commissionAmount, ''));
- });
-
- it('fails to get pricePoint and calculated amounts if priceOracle is not set', async () => {
- await pricerUtils.utils.expectThrow(pricer.getPricePointAndCalculatedAmounts.call(
- transferAmount, commissionAmount, pricerUtils.currencies.ost));
- });
-
- it('successfully gets pricePoints and calculated amounts', async () => {
- var returns = await pricer.getPricePointAndCalculatedAmounts.call(
- transferAmount, commissionAmount, pricerUtils.currencies.abc);
- assert.equal(returns[0].toNumber(), abcPrice.toNumber());
- assert.equal(returns[1].toNumber(), new pricerUtils.bigNumber(2.525 * 10**18));
- assert.equal(returns[2].toNumber(), new pricerUtils.bigNumber(0.63125 * 10**18));
-
- var returns = await pricer.getPricePointAndCalculatedAmounts.call(
- transferAmount, commissionAmount, pricerUtils.currencies.xyz);
- assert.equal(returns[0].toNumber(), xyzPrice.toNumber());
- assert.equal(returns[1].toNumber(), new pricerUtils.bigNumber(5.05 * 10**18));
- assert.equal(returns[2].toNumber(), new pricerUtils.bigNumber(1.2625 * 10**18));
- });
-
- context('when oracle returns 0 for price', async () => {
- var zeroPriceOracle = null;
-
- before(async () => {
- zeroPriceOracle = await PriceOracle.new(pricerUtils.currencies.ost, 'OOO', 0);
- await pricer.setPriceOracle('OOO', zeroPriceOracle.address, { from: opsAddress });
- });
-
- it('fails to get pricePoint and calculated amounts if pricePoint is 0', async () => {
- await pricerUtils.utils.expectThrow(pricer.getPricePointAndCalculatedAmounts.call(
- transferAmount, commissionAmount, 'OOO'));
- });
- });
-}
\ No newline at end of file
diff --git a/test/contracts/pricer/pay.js b/test/contracts/pricer/pay.js
deleted file mode 100644
index 73339db..0000000
--- a/test/contracts/pricer/pay.js
+++ /dev/null
@@ -1,208 +0,0 @@
-// Copyright 2018 OpenST Ltd.
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-//
-// ----------------------------------------------------------------------------
-// Test: pay.js
-//
-// http://www.simpletoken.org/
-//
-// ----------------------------------------------------------------------------
-
-const pricerUtils = require('./pricer_utils.js');
-
-///
-/// Test stories
-///
-/// fails to pay if beneficiary is null
-/// fails to pay if _transferAmount is 0
-/// fails to pay if _commissionAmount > 0 and _commissionBeneficiary is null
-/// successfully pays
-/// when currency is not empty
-/// fails to pay if pricePoint is not > 0
-/// fails to pay if pricePoint is not in range
-/// successfully pays
-/// when an accepted margin is set
-/// fails to pay if currentPricePoint is below intendedPricePoint range
-/// fails to pay if currentPricePoint is above intendedPricePoint range
-/// successfully pays
-
-module.exports.perform = (accounts) => {
- const opsAddress = accounts[1],
- abcPrice = new pricerUtils.bigNumber(20 * 10**18),
- transferAmount = new pricerUtils.bigNumber(5 * 10**18),
- commissionAmount = new pricerUtils.bigNumber(1.25 * 10**18),
- beneficiary = accounts[2],
- commissionBeneficiary = accounts[3]
- ;
-
- var contracts = null,
- token = null,
- pricer = null,
- abcPriceOracle = null,
- response = null,
- intendedPricePoint = null,
- convertedTokenTransferAmount = null
- ;
-
- before(async () => {
- contracts = await pricerUtils.deployPricer(artifacts, accounts);
- token = contracts.token;
- pricer = contracts.pricer;
- abcPriceOracle = contracts.abcPriceOracle;
- await pricer.setPriceOracle(pricerUtils.currencies.abc, abcPriceOracle.address, { from: opsAddress });
- intendedPricePoint = await pricer.getPricePoint.call(pricerUtils.currencies.abc);
- await token.setBalance(accounts[0], new pricerUtils.bigNumber(100 * 10**18));
- });
-
- it('fails to pay if beneficiary is null', async () => {
- await token.approve(pricer.address, transferAmount.plus(commissionAmount));
- await pricerUtils.utils.expectThrow(pricer.pay.call(
- 0, transferAmount, commissionBeneficiary, commissionAmount, '', intendedPricePoint));
- });
-
- it('fails to pay if _transferAmount is 0', async () => {
- await token.approve(pricer.address, transferAmount.plus(commissionAmount));
- await pricerUtils.utils.expectThrow(pricer.pay.call(
- beneficiary, 0, commissionBeneficiary, commissionAmount, '', intendedPricePoint));
- });
-
- it('fails to pay if _commissionAmount > 0 and _commissionBeneficiary is null', async () => {
- await token.approve(pricer.address, transferAmount.plus(commissionAmount));
- await pricerUtils.utils.expectThrow(pricer.pay.call(
- beneficiary, transferAmount, 0, commissionAmount, '', intendedPricePoint));
- });
-
- it('successfully pays', async () => {
- // without commission
- await token.setBalance(beneficiary, 0);
- assert.equal(await token.balanceOf.call(beneficiary), 0);
-
- await token.approve(pricer.address, transferAmount);
- assert.ok(await pricer.pay.call(beneficiary, transferAmount, 0, 0, '', 0));
- response = await pricer.pay(beneficiary, transferAmount, 0, 0, '', 0);
- assert.equal((await token.balanceOf(beneficiary)).toNumber(), transferAmount);
- // When currency is blank, transferAmount is equal to tokenAmount
- checkPaymentEvent(response.logs[0], beneficiary, transferAmount, 0, 0, '', 0);
- pricerUtils.utils.logResponse(response, 'Pricer.pay: ' + transferAmount);
-
- // with commission
- // reset token balances to 0
- await token.setBalance(beneficiary, 0);
- await token.setBalance(commissionBeneficiary, 0);
-
- assert.equal(await token.balanceOf.call(beneficiary), 0);
- assert.equal(await token.balanceOf.call(commissionBeneficiary), 0);
- await token.approve(pricer.address, transferAmount.plus(commissionAmount));
- assert.ok(await pricer.pay.call(beneficiary, transferAmount, commissionBeneficiary, commissionAmount, '', 0));
- response = await pricer.pay(beneficiary, transferAmount, commissionBeneficiary, commissionAmount, '', 0);
- assert.equal((await token.balanceOf(beneficiary)).toNumber(), transferAmount);
- assert.equal((await token.balanceOf(commissionBeneficiary)).toNumber(), commissionAmount);
- // When currency is blank, transferAmount is equal to tokenAmount
- checkPaymentEvent(response.logs[0], beneficiary, transferAmount, commissionBeneficiary, commissionAmount, '', 0);
- pricerUtils.utils.logResponse(response, 'Pricer.pay (commission): ' + transferAmount.plus(commissionAmount));
- });
-
- context('when currency is not empty', async () => {
- it('fails to pay if pricePoint is not > 0', async () => {
- await pricerUtils.utils.expectThrow(pricer.pay.call(
- beneficiary, transferAmount, 0, 0, pricerUtils.currencies.xyz, intendedPricePoint));
- });
-
- it('fails to pay if pricePoint is not in range', async () => {
- await pricerUtils.utils.expectThrow(pricer.pay.call(
- beneficiary, transferAmount, 0, 0, pricerUtils.currencies.abc, intendedPricePoint.plus(1)));
- });
-
- it('successfully pays', async () => {
- // reset token balances to 0
- await token.setBalance(beneficiary, 0);
- assert.equal(await token.balanceOf.call(beneficiary), 0);
-
- // get amount of tokens from currency value
- var calculatedResponse = (await pricer.getPricePointAndCalculatedAmounts.call(
- transferAmount, commissionAmount, pricerUtils.currencies.abc));
-
- convertedTokenTransferAmount = calculatedResponse[1];
-
- await token.approve(pricer.address, convertedTokenTransferAmount);
- assert.ok(await pricer.pay.call(beneficiary, transferAmount, 0, 0, pricerUtils.currencies.abc, intendedPricePoint));
- response = await pricer.pay(beneficiary, transferAmount, 0, 0, pricerUtils.currencies.abc, intendedPricePoint);
- assert.equal((await token.balanceOf(beneficiary)).toNumber(), convertedTokenTransferAmount);
-
- checkPaymentEvent(response.logs[0], beneficiary, convertedTokenTransferAmount, 0, 0, pricerUtils.currencies.abc, intendedPricePoint);
- pricerUtils.utils.logResponse(response, 'Pricer.pay (currency): ' + convertedTokenTransferAmount);
- });
-
- context('when an accepted margin is set', async () => {
- var margin = 10,
- offset = margin + 1
- ;
-
- before(async () => {
- // reset token balances to 0
- await token.setBalance(beneficiary, 0);
- assert.equal(await token.balanceOf.call(beneficiary), 0);
-
- // approve Pricer to transfer tokens
- var calculatedResponse = (await pricer.getPricePointAndCalculatedAmounts.call(
- transferAmount, commissionAmount, pricerUtils.currencies.abc));
- convertedTokenTransferAmount = calculatedResponse[1];
- await token.approve(pricer.address, convertedTokenTransferAmount);
-
- // set accepted margin
- await pricer.setAcceptedMargin(pricerUtils.currencies.abc, margin, { from: opsAddress });
- });
-
- // currentPricePoint: 2000000000000000000
- // intendedPricePoint range: 20000000000000000001 - 20000000000000000021
- it('fails to pay if currentPricePoint is below intendedPricePoint range', async () => {
- intendedPricePoint = abcPrice.plus(offset);
- await pricerUtils.utils.expectThrow(pricer.pay.call(beneficiary, transferAmount, 0, 0, pricerUtils.currencies.abc, intendedPricePoint));
- });
-
- // currentPricePoint: 2000000000000000000
- // intendedPricePoint range: 1999999999999999979 - 1999999999999999999
- it('fails to pay if currentPricePoint is above intendedPricePoint range', async () => {
- intendedPricePoint = abcPrice.minus(offset);
- await pricerUtils.utils.expectThrow(pricer.pay.call(beneficiary, transferAmount, 0, 0, pricerUtils.currencies.abc, intendedPricePoint));
- });
-
- // currentPricePoint: 2000000000000000000
- // intendedPricePoint range: 1999999999999999979 - 2000000000000000000
- it('successfully pays', async () => {
- intendedPricePoint = abcPrice.minus(margin);
- assert.ok(await pricer.pay.call(beneficiary, transferAmount, 0, 0, pricerUtils.currencies.abc, intendedPricePoint));
- response = await pricer.pay(beneficiary, transferAmount, 0, 0, pricerUtils.currencies.abc, intendedPricePoint);
- assert.equal((await token.balanceOf(beneficiary)).toNumber(), convertedTokenTransferAmount);
-
- checkPaymentEvent(response.logs[0], beneficiary, convertedTokenTransferAmount, 0, 0, pricerUtils.currencies.abc, intendedPricePoint);
- pricerUtils.utils.logResponse(response, 'Pricer.pay (margin): ' + convertedTokenTransferAmount);
- });
- });
-
- });
-
-}
-
-function checkPaymentEvent(event, _beneficiary, _tokenAmount, _commissionBeneficiary, _commissionTokenAmount, _currency, _intendedPricePoint) {
- assert.equal(event.event, 'Payment');
- assert.equal(event.args._beneficiary, _beneficiary);
- assert.equal(event.args._tokenAmount.toNumber(), _tokenAmount);
- assert.equal(event.args._commissionBeneficiary, _commissionBeneficiary);
- assert.equal(event.args._commissionTokenAmount.toNumber(), _commissionTokenAmount);
- if (_currency) {
- assert.equal(web3.toAscii(event.args._currency), _currency);
- }
- assert.equal(event.args._intendedPricePoint.toNumber(), _intendedPricePoint);
-}
diff --git a/test/contracts/pricer/pricer_utils.js b/test/contracts/pricer/pricer_utils.js
deleted file mode 100644
index 823ffdb..0000000
--- a/test/contracts/pricer/pricer_utils.js
+++ /dev/null
@@ -1,67 +0,0 @@
-// Copyright 2018 OpenST Ltd.
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-//
-// ----------------------------------------------------------------------------
-// Test: pricerUtils.js
-//
-// http://www.simpletoken.org/
-//
-// ----------------------------------------------------------------------------
-
-const Utils = require('../../lib/utils.js'),
- BigNumber = require('bignumber.js'),
- Pricer = artifacts.require('./Pricer.sol'),
- EIP20TokenMock = artifacts.require('./EIP20TokenMock.sol'),
- PriceOracle = artifacts.require('./PriceOracleMock.sol')
- ;
-
-const ost = 'OST',
- abc = 'ABC',
- xyz = 'XYZ'
- ;
-
-/// @dev Export common requires
-module.exports.utils = Utils;
-module.exports.bigNumber = BigNumber;
-
-/// @dev Export constants
-module.exports.currencies = {
- ost : ost,
- abc : abc,
- xyz : xyz
-}
-
-/// @dev Deploy
-module.exports.deployPricer = async (artifacts, accounts) => {
- const conversionRate = 101,
- conversionRateDecimals = 1,
- token = await EIP20TokenMock.new(conversionRate, conversionRateDecimals, ost, 'name', 18),
- TOKEN_DECIMALS = 18,
- opsAddress = accounts[1],
- pricer = await Pricer.new(token.address, ost),
- abcPrice = new BigNumber(20 * 10**18),
- xyzPrice = new BigNumber(10 * 10**18),
- abcPriceOracle = await PriceOracle.new(ost, abc, abcPrice),
- xyzPriceOracle = await PriceOracle.new(ost, xyz, xyzPrice)
- ;
-
- assert.ok(await pricer.setOpsAddress(opsAddress));
-
- return {
- token : token,
- pricer : pricer,
- abcPriceOracle : abcPriceOracle,
- xyzPriceOracle : xyzPriceOracle
- };
-};
diff --git a/test/contracts/pricer/properties.js b/test/contracts/pricer/properties.js
deleted file mode 100644
index a185e47..0000000
--- a/test/contracts/pricer/properties.js
+++ /dev/null
@@ -1,68 +0,0 @@
-// Copyright 2018 OpenST Ltd.
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-//
-// ----------------------------------------------------------------------------
-// Test: properties.js
-//
-// http://www.simpletoken.org/
-//
-// ----------------------------------------------------------------------------
-
-const pricerUtils = require('./pricer_utils.js');
-
-///
-/// Test stories
-///
-/// has brandedToken
-/// has baseCurrency
-/// has decimals
-/// has conversionRate
-
-module.exports.perform = (accounts) => {
- const TOKEN_DECIMALS = 18,
- conversionRate = 101,
- conversionRateDecimals = 1
- ;
-
- var contracts = null,
- token = null,
- pricer = null
- ;
-
- before(async () => {
- contracts = await pricerUtils.deployPricer(artifacts, accounts);
- token = contracts.token;
- pricer = contracts.pricer;
- });
-
- it('has brandedToken', async () => {
- assert.equal(await pricer.brandedToken.call(), token.address);
- });
-
- it('has baseCurrency', async () => {
- assert.equal(web3.toAscii(await pricer.baseCurrency.call()), pricerUtils.currencies.ost);
- });
-
- it('has decimals', async () => {
- assert.equal((await pricer.decimals.call()).toNumber(), TOKEN_DECIMALS);
- });
-
- it('has conversionRate', async () => {
- assert.equal((await pricer.conversionRate.call()).toNumber(), conversionRate);
- });
-
- it('has conversionRateDecimals', async () => {
- assert.equal((await pricer.conversionRateDecimals.call()).toNumber(), conversionRateDecimals);
- });
-}
diff --git a/test/contracts/pricer/set_accepted_margin.js b/test/contracts/pricer/set_accepted_margin.js
deleted file mode 100644
index 14c381f..0000000
--- a/test/contracts/pricer/set_accepted_margin.js
+++ /dev/null
@@ -1,81 +0,0 @@
-// Copyright 2018 OpenST Ltd.
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-//
-// ----------------------------------------------------------------------------
-// Test: set_accepted_margin.js
-//
-// http://www.simpletoken.org/
-//
-// ----------------------------------------------------------------------------
-
-const pricerUtils = require('./pricer_utils.js');
-
-///
-/// Test stories
-///
-/// fails to set acceptedMargin by non-ops
-/// successfully sets acceptedMargin
-
-module.exports.perform = (accounts) => {
- const opsAddress = accounts[1];
-
- var contracts = null,
- pricer = null,
- abcPriceOracle = null,
- acceptedMargin = null,
- response = null
- ;
-
- before(async () => {
- contracts = await pricerUtils.deployPricer(artifacts, accounts);
- pricer = contracts.pricer;
- abcPriceOracle = contracts.abcPriceOracle;
- await pricer.setPriceOracle(pricerUtils.currencies.abc, abcPriceOracle.address, { from: opsAddress });
- });
-
- it('fails to set acceptedMargin by non-ops', async () => {
- acceptedMargin = 1;
- await pricerUtils.utils.expectThrow(pricer.setAcceptedMargin.call(pricerUtils.currencies.abc, acceptedMargin));
- });
-
- it('successfully sets acceptedMargin', async () => {
- // Sets accepted margin multiple times to show range of gas usages
- acceptedMargin = new pricerUtils.bigNumber(0);
- assert.ok(await pricer.setAcceptedMargin.call(pricerUtils.currencies.abc, acceptedMargin, { from: opsAddress }));
- response = await pricer.setAcceptedMargin(pricerUtils.currencies.abc, acceptedMargin, { from: opsAddress });
- assert.equal((await pricer.acceptedMargins.call(pricerUtils.currencies.abc)).toNumber(), acceptedMargin.toNumber());
- checkAcceptedMarginSetEvent(response.logs[0], pricerUtils.currencies.abc, acceptedMargin);
- pricerUtils.utils.logResponse(response, 'Pricer.setAcceptedMargin: ' + acceptedMargin);
-
- acceptedMargin = new pricerUtils.bigNumber(1);
- assert.ok(await pricer.setAcceptedMargin.call(pricerUtils.currencies.abc, acceptedMargin, { from: opsAddress }));
- response = await pricer.setAcceptedMargin(pricerUtils.currencies.abc, acceptedMargin, { from: opsAddress });
- assert.equal((await pricer.acceptedMargins.call(pricerUtils.currencies.abc)).toNumber(), acceptedMargin.toNumber());
- checkAcceptedMarginSetEvent(response.logs[0], pricerUtils.currencies.abc, acceptedMargin);
- pricerUtils.utils.logResponse(response, 'Pricer.setAcceptedMargin: ' + acceptedMargin);
-
- acceptedMargin = new pricerUtils.bigNumber(7.778 * 10**17); // 10**17 to ease readability in gas usage output
- assert.ok(await pricer.setAcceptedMargin.call(pricerUtils.currencies.abc, acceptedMargin, { from: opsAddress }));
- response = await pricer.setAcceptedMargin(pricerUtils.currencies.abc, acceptedMargin, { from: opsAddress });
- assert.equal((await pricer.acceptedMargins.call(pricerUtils.currencies.abc)).toNumber(), acceptedMargin.toNumber());
- checkAcceptedMarginSetEvent(response.logs[0], pricerUtils.currencies.abc, acceptedMargin);
- pricerUtils.utils.logResponse(response, 'Pricer.setAcceptedMargin: ' + acceptedMargin);
- });
-}
-
-function checkAcceptedMarginSetEvent(event, _currency, _acceptedMargin) {
- assert.equal(event.event, 'AcceptedMarginSet');
- assert.equal(web3.toAscii(event.args._currency), _currency);
- assert.equal(event.args._acceptedMargin.toNumber(), _acceptedMargin);
-}
diff --git a/test/contracts/pricer/set_price_oracle.js b/test/contracts/pricer/set_price_oracle.js
deleted file mode 100644
index 525f447..0000000
--- a/test/contracts/pricer/set_price_oracle.js
+++ /dev/null
@@ -1,94 +0,0 @@
-// Copyright 2018 OpenST Ltd.
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-//
-// ----------------------------------------------------------------------------
-// Test: set_price_oracle.js
-//
-// http://www.simpletoken.org/
-//
-// ----------------------------------------------------------------------------
-
-const pricerUtils = require('./pricer_utils.js'),
- PriceOracle = artifacts.require('./PriceOracleMock.sol')
- ;
-
-///
-/// Test stories
-///
-/// fails to set priceOracle by non-ops
-/// fails to set priceOracle if oracleAddress is null
-/// fails to set priceOracle if currency is empty
-/// fails to set priceOracle if oracle baseCurrency does not match pricer baseCurrency
-/// fails to set priceOracle if oracle quoteCurrency does not match currency
-/// successfully sets priceOracles
-
-module.exports.perform = (accounts) => {
- const opsAddress = accounts[1];
-
- var contracts = null,
- pricer = null,
- abcPriceOracle = null,
- xyzPriceOracle = null,
- response = null
- ;
-
- before(async () => {
- contracts = await pricerUtils.deployPricer(artifacts, accounts);
- pricer = contracts.pricer;
- abcPriceOracle = contracts.abcPriceOracle;
- xyzPriceOracle = contracts.xyzPriceOracle;
- });
-
- it('fails to set priceOracle by non-ops', async () => {
- await pricerUtils.utils.expectThrow(pricer.setPriceOracle.call(pricerUtils.currencies.abc, abcPriceOracle.address));
- });
-
- it('fails to set priceOracle if oracleAddress is null', async () => {
- await pricerUtils.utils.expectThrow(pricer.setPriceOracle.call(pricerUtils.currencies.abc, 0, { from: opsAddress }));
- });
-
- it('fails to set priceOracle if currency is empty', async () => {
- await pricerUtils.utils.expectThrow(pricer.setPriceOracle.call('', abcPriceOracle.address, { from: opsAddress }));
- });
-
- it('fails to set priceOracle if oracle baseCurrency does not match pricer baseCurrency', async () => {
- var inappositeOracle = await PriceOracle.new(pricerUtils.currencies.abc, pricerUtils.currencies.ost, 1);
- await pricerUtils.utils.expectThrow(pricer.setPriceOracle.call(
- pricerUtils.currencies.abc, inappositeOracle.address, { from: opsAddress }));
- });
-
- it('fails to set priceOracle if oracle quoteCurrency does not match currency', async () => {
- await pricerUtils.utils.expectThrow(pricer.setPriceOracle.call(pricerUtils.currencies.xyz, abcPriceOracle.address));
- });
-
- it('successfully sets priceOracles', async () => {
- assert.ok(await pricer.setPriceOracle.call(pricerUtils.currencies.abc, abcPriceOracle.address, { from: opsAddress }));
- response = await pricer.setPriceOracle(pricerUtils.currencies.abc, abcPriceOracle.address, { from: opsAddress });
- assert.equal(await pricer.priceOracles.call(pricerUtils.currencies.abc), abcPriceOracle.address);
- checkPriceOracleSetEvent(response.logs[0], pricerUtils.currencies.abc, abcPriceOracle.address);
- pricerUtils.utils.logResponse(response, 'Pricer.setPriceOracle: ' + pricerUtils.currencies.abc);
-
- assert.ok(await pricer.setPriceOracle.call(pricerUtils.currencies.xyz, xyzPriceOracle.address, { from: opsAddress }));
- response = await pricer.setPriceOracle(pricerUtils.currencies.xyz, xyzPriceOracle.address, { from: opsAddress });
- assert.equal(await pricer.priceOracles.call(pricerUtils.currencies.xyz), xyzPriceOracle.address);
- checkPriceOracleSetEvent(response.logs[0], pricerUtils.currencies.xyz, xyzPriceOracle.address);
- pricerUtils.utils.logResponse(response, 'Pricer.setPriceOracle: ' + pricerUtils.currencies.xyz);
- });
-}
-
-function checkPriceOracleSetEvent(event, _currency, _address) {
- assert.equal(event.event, 'PriceOracleSet');
- assert.equal(web3.toAscii(event.args._currency), _currency);
- assert.equal(event.args._address, _address);
-}
diff --git a/test/contracts/pricer/unset_price_oracle.js b/test/contracts/pricer/unset_price_oracle.js
deleted file mode 100644
index c5ef625..0000000
--- a/test/contracts/pricer/unset_price_oracle.js
+++ /dev/null
@@ -1,73 +0,0 @@
-// Copyright 2018 OpenST Ltd.
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-//
-// ----------------------------------------------------------------------------
-// Test: unset_price_oracle.js
-//
-// http://www.simpletoken.org/
-//
-// ----------------------------------------------------------------------------
-
-const pricerUtils = require('./pricer_utils.js');
-
-///
-/// Test stories
-///
-/// fails to unset priceOracle by non-ops
-/// fails to unset priceOracle if not already set
-/// successfully unsets priceOracle
-
-module.exports.perform = (accounts) => {
- const opsAddress = accounts[1];
-
- var contracts = null,
- pricer = null,
- abcPriceOracle = null,
- xyzPriceOracle = null,
- response = null
- ;
-
- before(async () => {
- contracts = await pricerUtils.deployPricer(artifacts, accounts);
- pricer = contracts.pricer;
- abcPriceOracle = contracts.abcPriceOracle;
- xyzPriceOracle = contracts.xyzPriceOracle;
- await pricer.setPriceOracle(pricerUtils.currencies.abc, abcPriceOracle.address, { from: opsAddress });
- await pricer.setPriceOracle(pricerUtils.currencies.xyz, xyzPriceOracle.address, { from: opsAddress });
- });
-
- it('fails to set priceOracle by non-ops', async () => {
- await pricerUtils.utils.expectThrow(pricer.unsetPriceOracle.call(pricerUtils.currencies.abc));
- });
-
- it('successfully unsets priceOracle', async () => {
- assert.ok(await pricer.unsetPriceOracle.call(pricerUtils.currencies.abc, { from: opsAddress }));
- response = await pricer.unsetPriceOracle(pricerUtils.currencies.abc, { from: opsAddress });
- assert.equal(await pricer.priceOracles.call(pricerUtils.currencies.abc), 0);
- checkPriceOracleUnsetEvent(response.logs[0], pricerUtils.currencies.abc);
- pricerUtils.utils.logResponse(response, 'Pricer.unsetPriceOracle: ' + pricerUtils.currencies.abc);
-
- // confirm EUR priceOracle unaffected
- assert.equal(await pricer.priceOracles.call(pricerUtils.currencies.xyz), xyzPriceOracle.address);
- });
-
- it('fails to unset priceOracle if not already set', async () => {
- await pricerUtils.utils.expectThrow(pricer.unsetPriceOracle.call(pricerUtils.currencies.abc, { from: opsAddress }));
- });
-}
-
-function checkPriceOracleUnsetEvent(event, _currency) {
- assert.equal(event.event, 'PriceOracleUnset');
- assert.equal(web3.toAscii(event.args._currency), _currency);
-}
diff --git a/test/contracts/workers/base.js b/test/contracts/workers/base.js
deleted file mode 100644
index 8ff248a..0000000
--- a/test/contracts/workers/base.js
+++ /dev/null
@@ -1,37 +0,0 @@
-// Copyright 2018 OpenST Ltd.
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-//
-// ----------------------------------------------------------------------------
-// Test: base.js
-//
-// http://www.simpletoken.org/
-//
-// ----------------------------------------------------------------------------
-
-const workersUtils = require('./workers_utils.js'),
- setIsWorker = require('./set_is_worker.js');
- removeWorker = require('./remove_worker.js');
- remove = require('./remove.js')
- ;
-
-contract('Workers', function(accounts) {
- describe('Set/IsWorker', async () => setIsWorker.perform(accounts));
- describe('RemoveWorker', async () => removeWorker.perform(accounts));
- describe('Remove', async () => remove.perform(accounts));
-
- after(async () => {
- workersUtils.utils.printGasStatistics();
- workersUtils.utils.clearReceipts();
- });
-});
diff --git a/test/contracts/workers/remove.js b/test/contracts/workers/remove.js
deleted file mode 100644
index 282c3c3..0000000
--- a/test/contracts/workers/remove.js
+++ /dev/null
@@ -1,84 +0,0 @@
-// Copyright 2018 OpenST Ltd.
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-//
-// ----------------------------------------------------------------------------
-// Test: remove.js
-//
-// http://www.simpletoken.org/
-//
-// ----------------------------------------------------------------------------
-
-const workersUtils = require('./workers_utils.js'),
- Workers = artifacts.require('./Workers.sol'),
- web3 = require('../../lib/web3') ;
-
-
-///
-/// Test stories
-///
-/// fails to remove when sender is neither opsAddress nor adminAddress
-/// successfully removes when sender is opsAddress
-/// successfully removes when sender is adminAddress
-
-module.exports.perform = (accounts) => {
- const opsAddress = accounts[1],
- adminAddress = accounts[2]
- ;
-
- var workers = null,
- response = null
- ;
-
- beforeEach(async () => {
-
- workers = await Workers.new();
- assert.ok(await workers.setOpsAddress(opsAddress));
- assert.ok(await workers.setAdminAddress(adminAddress));
-
- });
-
- it('fails to remove when sender is neither opsAddress nor adminAddress', async () => {
-
- await workersUtils.utils.expectThrow(workers.remove.call({from: accounts[3]}));
-
- });
-
- it('successfully removes when sender is opsAddress', async () => {
-
- // call remove
- assert.ok(await workers.remove.call({from: opsAddress}));
- response = await workers.remove({from: opsAddress});
- workersUtils.utils.logResponse(response, 'Workers.remove (ops)');
-
- // check if contract is removed
- let code = await web3.eth.getCode(workers.address);
- assert.equal(code, 0x0);
-
- });
-
- it('successfully removes when sender is adminAddress', async () => {
-
- // call remove from admin address
- assert.ok(await workers.remove.call({from: adminAddress}));
- response = await workers.remove({from: adminAddress});
- workersUtils.utils.logResponse(response, 'Workers.remove (admin)');
-
- // check if contract is removed
- let code = await web3.eth.getCode(workers.address);
- assert.equal(code, 0x0);
-
- });
-}
-
-
diff --git a/test/contracts/workers/remove_worker.js b/test/contracts/workers/remove_worker.js
deleted file mode 100644
index aabfc4d..0000000
--- a/test/contracts/workers/remove_worker.js
+++ /dev/null
@@ -1,104 +0,0 @@
-// Copyright 2018 OpenST Ltd.
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-//
-// ----------------------------------------------------------------------------
-// Test: remove_workers.js
-//
-// http://www.simpletoken.org/
-//
-// ----------------------------------------------------------------------------
-
-const workersUtils = require('./workers_utils.js'),
- Workers = artifacts.require('./Workers.sol'),
- web3 = require('../../lib/web3') ;
-
-///
-/// Test stories
-///
-/// fails to remove worker if sender is not opsAddress
-/// fails to remove worker if worker was not set
-/// pass to remove worker
-
-module.exports.perform = (accounts) => {
- const opsAddress = accounts[1],
- worker1Address = accounts[2],
- worker2Address = accounts[3],
- worker3Address = accounts[4],
- height1 = new workersUtils.bigNumber(500),
- height2 = new workersUtils.bigNumber(1000)
- ;
-
- var workers = null,
- deactivationHeight = null
- ;
-
- before(async () => {
- workers = await Workers.new();
- assert.ok(await workers.setOpsAddress(opsAddress));
-
- // set worker 1
- let blockNumber = await web3.eth.getBlockNumber();
- deactivationHeight = blockNumber + height1.toNumber();
- await workers.setWorker(worker1Address, deactivationHeight, {from: opsAddress});
- blockNumber = await web3.eth.getBlockNumber();
- // set worker 2
- deactivationHeight = blockNumber + height2.toNumber();
- await workers.setWorker(worker2Address, deactivationHeight, {from: opsAddress});
-
- });
-
-
- it('fails to remove worker if sender is not opsAddress', async () => {
-
- await workersUtils.utils.expectThrow(workers.removeWorker.call(worker1Address, {from: accounts[5]}));
-
- });
-
-
- it('fails to remove worker if worker was not set', async () => {
-
- assert.equal(await workers.removeWorker.call(worker3Address, {from: opsAddress}), false);
- response = await workers.removeWorker(worker3Address, {from: opsAddress});
- assert.equal(await workers.isWorker.call(worker3Address), false);
- workersUtils.checkWorkerRemovedEvent(response.logs[0], worker3Address, false);
- workersUtils.utils.logResponse(response, 'Workers.removeWorker (never set)');
-
- });
-
-
- it('pass to remove worker', async () => {
-
- assert.equal(await workers.removeWorker.call(worker1Address, {from: opsAddress}), true);
- response = await workers.removeWorker(worker1Address, {from: opsAddress});
- assert.equal(await workers.isWorker.call(worker1Address), false);
- workersUtils.checkWorkerRemovedEvent(response.logs[0], worker1Address, true);
- workersUtils.utils.logResponse(response, 'Workers.removeWorker (w1)');
-
- assert.equal(await workers.removeWorker.call(worker2Address, {from: opsAddress}), true);
- response = await workers.removeWorker(worker2Address, {from: opsAddress});
- assert.equal(await workers.isWorker.call(worker2Address), false);
- workersUtils.checkWorkerRemovedEvent(response.logs[0], worker2Address, true);
- workersUtils.utils.logResponse(response, 'Workers.removeWorker (w2)');
-
- assert.equal(await workers.removeWorker.call(worker2Address, {from: opsAddress}), false);
- response = await workers.removeWorker(worker2Address, {from: opsAddress});
- assert.equal(await workers.isWorker.call(worker2Address), false);
- workersUtils.checkWorkerRemovedEvent(response.logs[0], worker2Address, false);
- workersUtils.utils.logResponse(response, 'Workers.removeWorker (w1 again)');
-
- });
-
-}
-
-
diff --git a/test/contracts/workers/set_is_worker.js b/test/contracts/workers/set_is_worker.js
deleted file mode 100644
index 2403535..0000000
--- a/test/contracts/workers/set_is_worker.js
+++ /dev/null
@@ -1,184 +0,0 @@
-// Copyright 2018 OpenST Ltd.
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-//
-// ----------------------------------------------------------------------------
-// Test: set_is_worker.js
-//
-// http://www.simpletoken.org/
-//
-// ----------------------------------------------------------------------------
-
-const workersUtils = require('./workers_utils.js'),
- Workers = artifacts.require('./Workers.sol'),
- web3 = require('../../lib/web3') ;
-
-///
-/// Test stories
-///
-/// fails to set worker if worker address is 0
-/// fails to set worker if _deactivationHeight is equal to current block number
-/// fails to set worker if _deactivationHeight is less than current block number
-/// fails to set worker if sender is not opsAddress
-/// pass to set worker if worker is not already set
-/// pass to set worker if worker was already set
-/// pass to set worker at higher deactivation height if worker was already set to a lower deactivation height
-/// pass to set worker at lower deactivation height if worker was already set to a higher deactivation height
-/// validate expiry
-
-module.exports.perform = (accounts) => {
- const opsAddress = accounts[1],
- worker1Address = accounts[2],
- worker2Address = accounts[3],
- worker3Address = accounts[4],
- height1 = new workersUtils.bigNumber(500),
- height2 = new workersUtils.bigNumber(1000)
- ;
-
- var workers = null,
- deactivationHeight = null
- ;
-
- before(async () => {
-
- workers = await Workers.new();
- assert.ok(await workers.setOpsAddress(opsAddress));
-
- });
-
-
- it('fails to set worker if worker address is 0', async () => {
-
- await workersUtils.utils.expectThrow(workers.setWorker.call(0, height1, {from: opsAddress}));
-
- });
-
-
- it('fails to set worker if deactivation height is equal to current block number', async () => {
-
- let blockNumber = await web3.eth.getBlockNumber();
- deactivationHeight = blockNumber;
- // calling this will not throw any execption
- assert.ok(await workers.setWorker.call(worker1Address, deactivationHeight, {from: opsAddress}));
-
- // Executing this will throw exception
- await workersUtils.utils.expectThrow(workers.setWorker(worker1Address, blockNumber, {from: opsAddress}));
-
- // Verify if the worker1 is not active
- assert.equal(await workers.isWorker.call(worker1Address), false);
-
- });
-
-
- it('fails to set worker if deactivation height is less than current block number', async () => {
-
- let blockNumber = await web3.eth.getBlockNumber();
- await workersUtils.utils.expectThrow(workers.setWorker.call(worker1Address, blockNumber - 1, {from: opsAddress}));
- await workersUtils.utils.expectThrow(workers.setWorker(worker1Address, blockNumber - 1, {from: opsAddress}));
- // Verify if the worker1 is not active
- assert.equal(await workers.isWorker.call(worker1Address), false);
-
- });
-
-
- it('pass to set worker if deactivation height is equal to current block number + 1', async () => {
-
- let blockNumber = await web3.eth.getBlockNumber();
- deactivationHeight = blockNumber + 1;
- assert.ok(await workers.setWorker.call(worker1Address, deactivationHeight, {from: opsAddress}));
- response = await workers.setWorker(worker1Address, deactivationHeight, {from: opsAddress});
- assert.equal(await workers.isWorker.call(worker1Address), true);
- workersUtils.checkWorkerSetEvent(response.logs[0], deactivationHeight, 0);
- workersUtils.utils.logResponse(response, 'Workers.setWorker: w1, blockNumber + 1');
-
- });
-
-
- it('fails to set worker if sender is not opsAddress', async () => {
-
- let blockNumber = await web3.eth.getBlockNumber();
- deactivationHeight = blockNumber + height1.toNumber();
- await workersUtils.utils.expectThrow(workers.setWorker.call(worker1Address, deactivationHeight, {from: accounts[5]}));
-
- });
-
-
- it('pass to set worker if worker is not already set', async () => {
-
- let blockNumber = await web3.eth.getBlockNumber();
- deactivationHeight = blockNumber + height1.toNumber();
- assert.ok(await workers.setWorker.call(worker1Address, deactivationHeight, {from: opsAddress}));
- response = await workers.setWorker(worker1Address, deactivationHeight, {from: opsAddress});
- assert.equal(await workers.isWorker.call(worker1Address), true);
- workersUtils.checkWorkerSetEvent(response.logs[0], deactivationHeight, height1.toNumber() - 1);
- workersUtils.utils.logResponse(response, 'Workers.setWorker: w1, ' + deactivationHeight);
- blockNumber = await web3.eth.getBlockNumber();
- deactivationHeight = blockNumber + height2.toNumber();
- assert.ok(await workers.setWorker.call(worker2Address, deactivationHeight, {from: opsAddress}));
- response = await workers.setWorker(worker2Address, deactivationHeight, {from: opsAddress});
- assert.equal(await workers.isWorker.call(worker2Address), true);
- workersUtils.checkWorkerSetEvent(response.logs[0], deactivationHeight, height2.toNumber() - 1);
- workersUtils.utils.logResponse(response, 'Workers.setWorker: w2, ' + deactivationHeight);
-
- });
-
-
- it('pass to set worker if worker was already set', async () => {
-
- let blockNumber = await web3.eth.getBlockNumber();
- deactivationHeight = blockNumber + height2.toNumber();
- assert.ok(await workers.setWorker.call(worker1Address, deactivationHeight, {from: opsAddress}));
- response = await workers.setWorker(worker1Address, deactivationHeight, {from: opsAddress});
- assert.equal(await workers.isWorker.call(worker1Address), true);
- workersUtils.checkWorkerSetEvent(response.logs[0], deactivationHeight, height2.toNumber() - 1);
- workersUtils.utils.logResponse(response, 'Workers.setWorker: w1, ' + deactivationHeight);
-
- });
-
-
- it('pass to set worker at lower deactivation height if worker was already set to a higher deactivation height', async () => {
-
- // update worker with lower deactivation height
- let blockNumber = await web3.eth.getBlockNumber();
- deactivationHeight = blockNumber + height1.toNumber();
- assert.ok(await workers.setWorker.call(worker1Address, deactivationHeight, {from: opsAddress}));
- response = await workers.setWorker(worker1Address, deactivationHeight, {from: opsAddress});
- assert.equal(await workers.isWorker.call(worker1Address), true);
- workersUtils.checkWorkerSetEvent(response.logs[0], deactivationHeight, height1.toNumber() - 1);
- workersUtils.utils.logResponse(response, 'Workers.setWorker: w1, ' + deactivationHeight);
-
- });
-
-
- it('validate expiry', async () => {
-
- // set a worker with expiration height of 30
- var height = 30;
- let blockNumber = await web3.eth.getBlockNumber();
- deactivationHeight = blockNumber + height;
- assert.ok(await workers.setWorker.call(worker3Address, deactivationHeight, {from: opsAddress}));
- response = await workers.setWorker(worker3Address, deactivationHeight, {from: opsAddress});
- assert.equal(await workers.isWorker.call(worker3Address), true);
- for (var i = height - 1; i >= 0; i--) {
- // Perform random transaction to increase block number. In this case using removeWorker for worker1Address
- response = await workers.removeWorker(worker1Address, {from: opsAddress});
- assert.equal(await workers.isWorker.call(worker3Address), i > 0);
- }
- //Do one more time to confirm.
- response = await workers.removeWorker(worker1Address, {from: opsAddress});
- assert.equal(await workers.isWorker.call(worker3Address), false);
-
- });
-}
-
-
diff --git a/test/contracts/workers/workers_utils.js b/test/contracts/workers/workers_utils.js
deleted file mode 100644
index 18d234a..0000000
--- a/test/contracts/workers/workers_utils.js
+++ /dev/null
@@ -1,45 +0,0 @@
-// Copyright 2018 OpenST Ltd.
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-//
-// ----------------------------------------------------------------------------
-// Test: pricer_utils.js
-//
-// http://www.simpletoken.org/
-//
-// ----------------------------------------------------------------------------
-
-const Utils = require('../../lib/utils.js'),
- BigNumber = require('bignumber.js'),
- Workers = artifacts.require('./Workers.sol')
- ;
-
-
-/// @dev Export common requires
-module.exports.utils = Utils;
-module.exports.bigNumber = BigNumber;
-
-function checkWorkerSetEvent(event, deactivationHeight, remainingHeight) {
- assert.equal(event.event, 'WorkerSet');
- assert.equal(event.args._deactivationHeight.toNumber(), deactivationHeight);
- assert.equal(event.args._remainingHeight.toNumber(), remainingHeight);
-}
-module.exports.checkWorkerSetEvent = checkWorkerSetEvent;
-
-function checkWorkerRemovedEvent(event, worker, existed) {
- assert.equal(event.event, 'WorkerRemoved');
- assert.equal(event.args._worker, worker);
- assert.equal(event.args._existed, existed);
-}
-module.exports.checkWorkerRemovedEvent = checkWorkerRemovedEvent;
-
diff --git a/test/lib/event_decoder.js b/test/lib/event_decoder.js
deleted file mode 100644
index 902b3b3..0000000
--- a/test/lib/event_decoder.js
+++ /dev/null
@@ -1,89 +0,0 @@
-"use strict";
-
-const web3EventsDecoder = function () {};
-
-web3EventsDecoder.prototype = {
-
- getFormattedEvents: function(eventsData) {
- var formattedEvents = {};
-
- var eventDataValues = {};
-
- for (var i = 0; i < eventsData.length; i++) {
- var currEvent = eventsData[i]
- , currEventName = currEvent.name
- , currEventAddr = currEvent.address
- , currEventParams = currEvent.events;
-
- formattedEvents[currEventName] = {address: currEventAddr};
-
- for (var j = 0; j < currEventParams.length; j++) {
- var p = currEventParams[j];
- formattedEvents[currEventName][p.name] = p.value;
- }
-
- }
-
- return formattedEvents;
- },
-
- // decode logs from a transaction receipt
- perform: function(txReceipt, contractAddr, contractAbi) {
- //logger.debug(txReceipt);
- //logger.debug(contractAddr);
- //logger.debug(contractAbi);
- var decodedEvents = [];
-
- // Transaction receipt not found
- if (!txReceipt) {
- console.error(" Transaction receipt was not found.");
- return;
- }
-
- // Block not yet mined
- if (!txReceipt.blockNumber) {
- console.error(" Transaction not yet mined. Please try after some time. ");
- return;
- }
-
- const toAddr = txReceipt.to;
-
- // if the address is a known address
- if ( txReceipt.logs.length > 0) {
-
- var abiDecoder = require('abi-decoder')
- , relevantLogs = [];
-
- for (var i = 0; i < txReceipt.logs.length; i++) {
-
- var currContractAddrFromReciept = txReceipt.logs[i].address;
-
- console.debug('**** contract address: ' + txReceipt.logs[i].address + ' at log index(' + i + ') in TxHash: ' + txReceipt.transactionHash + '');
-
- if (!currContractAddrFromReciept) {
- console.error('**** No contract found for contract address: ' + txReceipt.logs[i].address + ' at log index(' + i + ') in TxHash: ' + txReceipt.transactionHash + '');
- continue;
- }
-
- // ABI not found
- if (!contractAbi) {
- console.error("ABI not found for contract: "+contractAddr);
- return;
- }
-
- relevantLogs.push(txReceipt.logs[i]);
- abiDecoder.addABI(contractAbi);
- }
-
- if(relevantLogs.length > 0) {
- decodedEvents = abiDecoder.decodeLogs(relevantLogs);
- }
-
- }
-
- return this.getFormattedEvents(decodedEvents);
- }
-
-};
-
-module.exports = new web3EventsDecoder();
\ No newline at end of file
diff --git a/test/lib/utils.js b/test/lib/utils.js
deleted file mode 100644
index 0622d3c..0000000
--- a/test/lib/utils.js
+++ /dev/null
@@ -1,141 +0,0 @@
-// Copyright 2017 OST.com Ltd.
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-//
-// ----------------------------------------------------------------------------
-// Test: lib/utils.js
-//
-// http://www.simpletoken.org/
-//
-// ----------------------------------------------------------------------------
-
-const Assert = require('assert');
-
-const NullAddress = "0x0000000000000000000000000000000000000000";
-const rootPrefix = '../..'
- , logger = require(rootPrefix + '/helpers/custom_console_logger'),
- web3 = require('./web3');
-;
-/*
- * Tracking Gas Usage
- */
-
-const receipts = [];
-
-module.exports.logResponse = (response, description) => {
- receipts.push({
- receipt: response.receipt,
- description: description,
- response: response
- });
-};
-
-module.exports.logReceipt = (receipt, description) => {
- receipts.push({
- receipt: receipt,
- description: description,
- response: null
- })
-};
-
-module.exports.logTransaction = async (hash, description) => {
- const receipt = await web3.eth.getTransactionReceipt(hash)
- await this.logReceipt(receipt, description)
-};
-
-module.exports.printGasStatistics = () => {
- var totalGasUsed = 0;
-
- logger.debug(" -----------------------------------------------------");
- logger.debug(" Report gas usage\n");
-
- for (i = 0; i < receipts.length; i++) {
- const entry = receipts[i];
-
- totalGasUsed += entry.receipt.gasUsed;
-
- logger.debug(" " + entry.description.padEnd(45) + entry.receipt.gasUsed)
- }
-
- logger.debug(" -----------------------------------------------------");
- logger.debug(" " + "Total gas logged: ".padEnd(45) + totalGasUsed + "\n")
-};
-
-module.exports.clearReceipts = () => {
- receipts.splice(0, receipts.length);
-};
-
-
-/*
- * General event checks
- */
-module.exports.expectNoEvents = (result) => {
- Assert.equal(result.receipt.logs.length, 0, "expected empty array of logs")
-};
-
-/*
- * Basic Ethereum checks
- */
-
-/// @dev Compare to null address
-module.exports.isNullAddress = function (address) {
- Assert.strictEqual(typeof address, 'string', `address must be of type 'string'`);
- return (address == NullAddress);
-};
-
-/// @dev Expect failure from invalid opcode or out of gas,
-/// but returns error instead
-module.exports.expectThrow = async (promise) => {
- try {
- await promise;
- } catch (error) {
- const invalidOpcode = error.message.search('invalid opcode') > -1;
-
- const outOfGas = error.message.search('out of gas') > -1;
-
- // Latest TestRPC has trouble with require
- const revertInstead = error.message.search('revert') > -1;
-
- Assert(invalidOpcode || outOfGas || revertInstead, `Expected throw, but got ${error} instead`);
-
- return;
- }
-
- Assert(false, "Did not throw as expected");
-};
-
-/// @dev Get account balance
-module.exports.getBalance = function (address) {
- return new Promise(function (resolve, reject) {
- web3.eth.getBalance(address, function (error, result) {
- if (error) {
- reject(error);
- } else {
- resolve(result);
- }
- })
- })
-};
-
-/// @dev Get gas price
-module.exports.getGasPrice = function () {
- return new Promise(function (resolve, reject) {
- web3.eth.getGasPrice(function (error, result) {
- if (error) {
- reject(error);
- } else {
- resolve(result);
- }
- })
- })
-};
\ No newline at end of file
diff --git a/test/lib/web3.js b/test/lib/web3.js
deleted file mode 100644
index aac9fa7..0000000
--- a/test/lib/web3.js
+++ /dev/null
@@ -1,7 +0,0 @@
-"use strict";
-
-
-const Web3 = require('web3'),
- web3 = new Web3(new Web3.providers.HttpProvider("http://localhost:8545"));
-
-module.exports = web3;
diff --git a/test/multisigwallet/confirm_transaction.js b/test/multisigwallet/confirm_transaction.js
new file mode 100644
index 0000000..5e01ae4
--- /dev/null
+++ b/test/multisigwallet/confirm_transaction.js
@@ -0,0 +1,156 @@
+// Copyright 2018 OpenST Ltd.
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+//
+// ----------------------------------------------------------------------------
+// Test: MultiSigWallet::confirmTransaction
+//
+// http://www.simpletoken.org/
+//
+// ----------------------------------------------------------------------------
+
+const BN = require('bn.js');
+const utils = require('../test_lib/utils.js');
+const { Event } = require('../test_lib/event_decoder.js');
+const { AccountProvider } = require('../test_lib/utils.js');
+const { MultiSigWalletUtils } = require('./utils.js');
+
+
+contract('MultiSigWallet::confirmTransaction', async () => {
+ contract('Negative Tests', async (accounts) => {
+ const accountProvider = new AccountProvider(accounts);
+
+ it('Reverts if non-registered wallet calls.', async () => {
+ const helper = await new MultiSigWalletUtils(
+ { accountProvider, walletCount: 2, required: 2 },
+ );
+
+ const transactionID = await helper.submitAddWallet(
+ accountProvider.get(), 0,
+ );
+
+ await utils.expectRevert(
+ helper.multisig().confirmTransaction(
+ transactionID,
+ { from: accountProvider.get() },
+ ),
+ 'Should revert as non-registered wallet calls.',
+ 'Only wallet is allowed to call.',
+ );
+ });
+
+ it('Reverts if transaction ID to confirm does not exist.', async () => {
+ const helper = await new MultiSigWalletUtils(
+ { accountProvider, walletCount: 1, required: 1 },
+ );
+
+ const nonExistingTransactionID = 11;
+
+ await utils.expectRevert(
+ helper.multisig().confirmTransaction(
+ nonExistingTransactionID,
+ { from: helper.wallet(0) },
+ ),
+ 'Should revert as transaction does not exist.',
+ 'Transaction does not exist.',
+ );
+ });
+
+ it('Reverts if the wallet has already confirmed the transaction.', async () => {
+ const helper = await new MultiSigWalletUtils(
+ { accountProvider, walletCount: 2, required: 2 },
+ );
+
+ const transactionID = await helper.submitAddWallet(
+ accountProvider.get(), 0,
+ );
+
+ await utils.expectRevert(
+ helper.multisig().confirmTransaction(
+ transactionID,
+ { from: helper.wallet(0) },
+ ),
+ 'Should revert as wallet has already confirmed the transaction.',
+ 'Transaction is confirmed by the wallet.',
+ );
+ });
+ });
+
+ contract('Events', async (accounts) => {
+ const accountProvider = new AccountProvider(accounts);
+
+ it('Emits TransactionConfirmed once wallet confirms transaction.', async () => {
+ const helper = await new MultiSigWalletUtils(
+ { accountProvider, walletCount: 3, required: 3 },
+ );
+
+ const transactionID = await helper.submitAddWallet(
+ accountProvider.get(), 0,
+ );
+
+ const transactionResponse = await helper.multisig().confirmTransaction(
+ transactionID,
+ { from: helper.wallet(1) },
+ );
+
+ const events = Event.decodeTransactionResponse(
+ transactionResponse,
+ );
+
+ assert.strictEqual(
+ events.length,
+ 1,
+ );
+
+ // The first emitted event should be 'TransactionConfirmed'.
+ Event.assertEqual(events[0], {
+ name: 'TransactionConfirmed',
+ args: {
+ _transactionID: new BN(transactionID),
+ _wallet: helper.wallet(1),
+ },
+ });
+ });
+ });
+
+ contract('Storage', async (accounts) => {
+ const accountProvider = new AccountProvider(accounts);
+
+ it('Checks that transaction is confirmed by the wallet after '
+ + 'successfull call.', async () => {
+ const helper = await new MultiSigWalletUtils(
+ { accountProvider, walletCount: 2, required: 2 },
+ );
+
+ const transactionID = await helper.submitAddWallet(
+ accountProvider.get(), 0,
+ );
+
+ assert.isNotOk(
+ (await helper.multisig().transactions.call(transactionID)).executed,
+ 'Transaction should not be confirmed because of '
+ + '2-wallets-2-required setup.',
+ );
+
+ await helper.multisig().confirmTransaction(
+ transactionID, { from: helper.wallet(1) },
+ );
+
+ assert.isOk(
+ (await helper.multisig().transactions.call(transactionID)).executed,
+ 'Transaction should be confirmed because two wallets '
+ + 'has confirmed it.',
+ );
+ });
+ });
+});
diff --git a/test/multisigwallet/constructor.js b/test/multisigwallet/constructor.js
new file mode 100644
index 0000000..aa47874
--- /dev/null
+++ b/test/multisigwallet/constructor.js
@@ -0,0 +1,99 @@
+// Copyright 2018 OpenST Ltd.
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+
+const utils = require('../test_lib/utils.js');
+const { AccountProvider } = require('../test_lib/utils.js');
+
+const MultiSigWallet = artifacts.require('MultiSigWallet');
+
+contract('MultiSigWallet::constructor', async () => {
+ contract('Negative Tests', async (accounts) => {
+ const accountProvider = new AccountProvider(accounts);
+
+ it('Reverts if wallets array contains null address.', async () => {
+ const registeredWallet0 = accountProvider.get();
+ const nullWallet = utils.NULL_ADDRESS;
+
+ const walletsWithNull = [registeredWallet0, nullWallet];
+
+ await utils.expectRevert(
+ MultiSigWallet.new(walletsWithNull, 1),
+ 'Should revert as wallets array contains null address.',
+ 'Wallet address is 0.',
+ );
+ });
+
+ it('Reverts if wallets array contains duplicate entries.', async () => {
+ const registeredWallet0 = accountProvider.get();
+ const walletsWithDuplicate = [registeredWallet0, registeredWallet0];
+
+ await utils.expectRevert(
+ MultiSigWallet.new(walletsWithDuplicate, 1),
+ 'Should revert as wallets array contains duplicate entry.',
+ 'Duplicate wallet address.',
+ );
+ });
+ });
+
+ contract('Storage', async (accounts) => {
+ const accountProvider = new AccountProvider(accounts);
+
+ it('Checks that passed arguments are set correctly.', async () => {
+ const required = 2;
+ const registeredWallet0 = accountProvider.get();
+ const registeredWallet1 = accountProvider.get();
+
+ const wallets = [registeredWallet0, registeredWallet1];
+
+ const multisig = await MultiSigWallet.new(wallets, required);
+
+ assert.isOk(
+ (await multisig.required.call()).eqn(required),
+ );
+
+ assert.isOk(
+ (await multisig.walletCount.call()).eqn(2),
+ );
+
+ assert.strictEqual(
+ await multisig.wallets.call(0),
+ registeredWallet0,
+ );
+
+ assert.strictEqual(
+ await multisig.wallets.call(1),
+ registeredWallet1,
+ );
+
+ assert.isOk(
+ await multisig.isWallet.call(registeredWallet0),
+ );
+
+ assert.isOk(
+ await multisig.isWallet.call(registeredWallet1),
+ );
+
+ assert.isOk(
+ (await multisig.required.call()).eqn(required),
+ 'After submitting a transaction, the transaction count is '
+ + 'incremented by one, hence it should be equal to 1',
+ );
+
+ assert.isOk(
+ (await multisig.transactionCount.call()).eqn(0),
+ );
+ });
+ });
+});
diff --git a/test/multisigwallet/execute_transaction.js b/test/multisigwallet/execute_transaction.js
new file mode 100644
index 0000000..08d4ff1
--- /dev/null
+++ b/test/multisigwallet/execute_transaction.js
@@ -0,0 +1,265 @@
+// Copyright 2018 OpenST Ltd.
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+//
+// ----------------------------------------------------------------------------
+// Test: MultiSigWallet::executeTransaction
+//
+// http://www.simpletoken.org/
+//
+// ----------------------------------------------------------------------------
+
+const BN = require('bn.js');
+const utils = require('../test_lib/utils.js');
+const { Event } = require('../test_lib/event_decoder.js');
+const { AccountProvider } = require('../test_lib/utils.js');
+const { MultiSigWalletUtils } = require('./utils.js');
+
+const MultiSigWalletDouble = artifacts.require('MultiSigWalletDouble');
+
+contract('MultiSigWallet::executeTransaction', async () => {
+ contract('Negative Tests', async (accounts) => {
+ const accountProvider = new AccountProvider(accounts);
+
+ it('Reverts if non-registered wallet calls.', async () => {
+ const helper = await new MultiSigWalletUtils(
+ { accountProvider, walletCount: 2, required: 2 },
+ );
+
+ const transactionID = await helper.submitAddWallet(
+ accountProvider.get(), 0,
+ );
+
+ await utils.expectRevert(
+ helper.multisig().executeTransaction(
+ transactionID,
+ { from: accountProvider.get() },
+ ),
+ 'Should revert as non-registered wallet calls.',
+ 'Only wallet is allowed to call.',
+ );
+ });
+
+ it('Reverts if transaction ID does not exist.', async () => {
+ const helper = await new MultiSigWalletUtils(
+ { accountProvider, walletCount: 2, required: 2 },
+ );
+
+ const nonExistingTransactionID = 11;
+
+ await utils.expectRevert(
+ helper.multisig().executeTransaction(
+ nonExistingTransactionID,
+ { from: helper.wallet(0) },
+ ),
+ 'Should revert as transaction ID does not exist.',
+ 'Transaction does not exist.',
+ );
+ });
+
+ it('Reverts if execution requested by wallet that did not confirmed.', async () => {
+ const helper = await new MultiSigWalletUtils(
+ { accountProvider, walletCount: 2, required: 2 },
+ );
+
+ const transactionID = await helper.submitAddWallet(
+ accountProvider.get(), 0,
+ );
+
+ await utils.expectRevert(
+ helper.multisig().executeTransaction(
+ transactionID,
+ { from: helper.wallet(1) },
+ ),
+ );
+ });
+
+ it('Reverts if the transaction was already executed.', async () => {
+ const helper = await new MultiSigWalletUtils(
+ { accountProvider, walletCount: 1, required: 1 },
+ );
+
+ const transactionID = await helper.submitAddWallet(
+ accountProvider.get(), 0,
+ );
+
+ await utils.expectRevert(
+ helper.multisig().executeTransaction(
+ transactionID,
+ { from: helper.wallet(0) },
+ ),
+ );
+ });
+ });
+
+ contract('Events', async (accounts) => {
+ const accountProvider = new AccountProvider(accounts);
+
+ it('Emits TransactionExecutionSucceeded on successfull execution.', async () => {
+ const required = 1;
+
+ const registeredWallet0 = accountProvider.get();
+
+ const wallets = [registeredWallet0];
+
+ const multisigDouble = await MultiSigWalletDouble.new(
+ wallets, required,
+ );
+
+ await multisigDouble.makeFooThrow();
+
+ const transactionID = await multisigDouble.submitFoo.call(
+ { from: registeredWallet0 },
+ );
+
+ await multisigDouble.submitFoo(
+ { from: registeredWallet0 },
+ );
+
+ await multisigDouble.makeFooNotThrow();
+ const transactionResponse = await multisigDouble.executeTransaction(transactionID);
+
+ const events = Event.decodeTransactionResponse(
+ transactionResponse,
+ );
+
+ assert.strictEqual(
+ events.length,
+ 1,
+ );
+
+ // The first emitted event should be 'TransactionExecutionSucceeded'.
+ Event.assertEqual(events[0], {
+ name: 'TransactionExecutionSucceeded',
+ args: {
+ _transactionID: new BN(transactionID),
+ },
+ });
+ });
+
+ it('Emits TransactionExecutionFailed on failure.', async () => {
+ const required = 1;
+
+ const registeredWallet0 = accountProvider.get();
+
+ const wallets = [registeredWallet0];
+
+ const multisigDouble = await MultiSigWalletDouble.new(
+ wallets, required,
+ );
+
+ await multisigDouble.makeFooThrow();
+
+ const transactionID = await multisigDouble.submitFoo.call(
+ { from: registeredWallet0 },
+ );
+
+ await multisigDouble.submitFoo(
+ { from: registeredWallet0 },
+ );
+
+ const transactionResponse = await multisigDouble.executeTransaction(
+ transactionID,
+ { from: registeredWallet0 },
+ );
+
+ const events = Event.decodeTransactionResponse(
+ transactionResponse,
+ );
+
+ assert.strictEqual(
+ events.length,
+ 1,
+ );
+
+ // The first emitted event should be 'TransactionExecutionFailed'.
+ Event.assertEqual(events[0], {
+ name: 'TransactionExecutionFailed',
+ args: {
+ _transactionID: new BN(transactionID),
+ },
+ });
+ });
+ });
+
+ contract('Execution', async (accounts) => {
+ const accountProvider = new AccountProvider(accounts);
+
+ it('Checks that request passes successfully.', async () => {
+ const required = 1;
+
+ const registeredWallet0 = accountProvider.get();
+
+ const wallets = [registeredWallet0];
+
+ const multisigDouble = await MultiSigWalletDouble.new(
+ wallets, required,
+ );
+
+ await multisigDouble.makeFooThrow();
+
+ const transactionID = await multisigDouble.submitFoo.call(
+ { from: registeredWallet0 },
+ );
+
+ await multisigDouble.submitFoo(
+ { from: registeredWallet0 },
+ );
+
+ await multisigDouble.makeFooNotThrow();
+
+ await multisigDouble.executeTransaction(
+ transactionID,
+ { from: registeredWallet0 },
+ );
+
+ assert.isOk(
+ (await multisigDouble.transactions.call(transactionID)).executed,
+ 'Transaction should pass as foo is set to succeed.',
+ );
+ });
+
+ it('Checks that request fails.', async () => {
+ const required = 1;
+
+ const registeredWallet0 = accountProvider.get();
+
+ const wallets = [registeredWallet0];
+
+ const multisigDouble = await MultiSigWalletDouble.new(
+ wallets, required,
+ );
+
+ await multisigDouble.makeFooThrow();
+
+ const transactionID = await multisigDouble.submitFoo.call(
+ { from: registeredWallet0 },
+ );
+
+ await multisigDouble.submitFoo(
+ { from: registeredWallet0 },
+ );
+
+ await multisigDouble.executeTransaction(
+ transactionID,
+ { from: registeredWallet0 },
+ );
+
+ assert.isNotOk(
+ (await multisigDouble.transactions.call(transactionID)).executed,
+ 'Transaction should not be executed in this stage '
+ + 'as foo is set to throw.',
+ );
+ });
+ });
+});
diff --git a/test/multisigwallet/is_transaction_confirmed.js b/test/multisigwallet/is_transaction_confirmed.js
new file mode 100644
index 0000000..039ae36
--- /dev/null
+++ b/test/multisigwallet/is_transaction_confirmed.js
@@ -0,0 +1,97 @@
+// Copyright 2018 OpenST Ltd.
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+const utils = require('../test_lib/utils.js');
+const { AccountProvider } = require('../test_lib/utils.js');
+const { MultiSigWalletUtils } = require('./utils.js');
+
+contract('MultiSigWallet::isTransactionConfirmed', async (accounts) => {
+ const accountProvider = new AccountProvider(accounts);
+
+ it('Reverts if transaction ID does not exist.', async () => {
+ const helper = await new MultiSigWalletUtils(
+ { accountProvider, walletCount: 1, required: 1 },
+ );
+
+ const nonExistingTransactionID = 11;
+
+ await utils.expectRevert(
+ helper.multisig().isTransactionConfirmed.call(
+ nonExistingTransactionID,
+ { from: helper.wallet(0) },
+ ),
+ 'Should revert as transaction ID does not exist.',
+ 'Transaction does not exist.',
+ );
+ });
+
+ it('Checks transaction confirmation status for 1-wallet-1-required setup.', async () => {
+ const helper = await new MultiSigWalletUtils(
+ { accountProvider, walletCount: 1, required: 1 },
+ );
+
+ const transactionID = await helper.submitAddWallet(
+ accountProvider.get(), 0,
+ );
+
+ assert.isOk(
+ await helper.multisig().isTransactionConfirmed.call(transactionID),
+ 'Because of required being 1 the transaction would be immediately '
+ + 'confirmed by the submitter.',
+ );
+ });
+
+ it('Checks transaction confirmation status for 2-wallets-2-required setup.', async () => {
+ const helper = await new MultiSigWalletUtils(
+ { accountProvider, walletCount: 2, required: 2 },
+ );
+
+ const addWalletTransactionID = await helper.submitAddWallet(
+ accountProvider.get(), 0,
+ );
+
+ assert.isNotOk(
+ await helper.multisig().isTransactionConfirmed.call(addWalletTransactionID),
+ 'Because of required being 2 the transaction is not yet confirmed.',
+ );
+
+ await helper.multisig().confirmTransaction(
+ addWalletTransactionID,
+ { from: helper.wallet(1) },
+ );
+
+ assert.isOk(
+ await helper.multisig().isTransactionConfirmed.call(addWalletTransactionID),
+ 'Transaction should be confirmed because the submitter confirms '
+ + 'the transaction in the same call, and second wallet has just '
+ + 'confirmed it',
+ );
+
+ const replaceWalletTransactionID = await helper.submitReplaceWallet(
+ 1, accountProvider.get(), 0,
+ );
+
+ await helper.multisig().confirmTransaction(
+ replaceWalletTransactionID,
+ { from: helper.wallet(1) },
+ );
+
+ assert.isOk(
+ await helper.multisig().isTransactionConfirmed.call(addWalletTransactionID),
+ 'Despite that the wallet that has confirmed the transaction '
+ + 'was replaced with the one that has not yet confirmed it, '
+ + 'function returns true because the transaction was executed',
+ );
+ });
+});
diff --git a/test/multisigwallet/revoke_confirmation.js b/test/multisigwallet/revoke_confirmation.js
new file mode 100644
index 0000000..6282481
--- /dev/null
+++ b/test/multisigwallet/revoke_confirmation.js
@@ -0,0 +1,174 @@
+// Copyright 2018 OpenST Ltd.
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+//
+// ----------------------------------------------------------------------------
+// Test: MultiSigWallet::revokeConfirmation
+//
+// http://www.simpletoken.org/
+//
+// ----------------------------------------------------------------------------
+
+const BN = require('bn.js');
+const utils = require('../test_lib/utils.js');
+const { Event } = require('../test_lib/event_decoder.js');
+const { AccountProvider } = require('../test_lib/utils.js');
+const { MultiSigWalletUtils } = require('./utils.js');
+
+contract('MultiSigWallet::revokeConfirmation', async () => {
+ contract('Negative Tests', async (accounts) => {
+ const accountProvider = new AccountProvider(accounts);
+
+ it('Reverts if non-registered wallet calls.', async () => {
+ const helper = await new MultiSigWalletUtils(
+ { accountProvider, walletCount: 2, required: 2 },
+ );
+
+ const transactionID = await helper.submitAddWallet(
+ accountProvider.get(), 0,
+ );
+
+ await utils.expectRevert(
+ helper.multisig().revokeConfirmation(
+ transactionID,
+ {
+ from: accountProvider.get(),
+ },
+ ),
+ 'Should revert as non-registered wallet calls.',
+ 'Only wallet is allowed to call.',
+ );
+ });
+
+ it('Reverts if transaction ID does not exist.', async () => {
+ const helper = await new MultiSigWalletUtils(
+ { accountProvider, walletCount: 1, required: 1 },
+ );
+
+ const nonExistingTransactionID = 11;
+
+ await utils.expectRevert(
+ helper.multisig().revokeConfirmation(
+ nonExistingTransactionID,
+ { from: helper.wallet(0) },
+ ),
+ 'Should revert as transaction ID does not exist.',
+ 'Transaction does not exist.',
+ );
+ });
+
+ it('Reverts if revocation request was not confirmed by caller wallet.', async () => {
+ const helper = await new MultiSigWalletUtils(
+ { accountProvider, walletCount: 2, required: 2 },
+ );
+
+ const transactionID = await helper.submitAddWallet(
+ accountProvider.get(), 0,
+ );
+
+ await utils.expectRevert(
+ helper.multisig().revokeConfirmation(
+ transactionID,
+ { from: helper.wallet(1) },
+ ),
+ 'Should revert as caller wallet did not confirm the transaction.',
+ 'Transaction is not confirmed by the wallet.',
+ );
+ });
+
+ it('Reverts if revocation is requested for already executed transaction.', async () => {
+ const helper = await new MultiSigWalletUtils(
+ { accountProvider, walletCount: 1, required: 1 },
+ );
+
+ const transactionID = await helper.submitAddWallet(
+ accountProvider.get(), 0,
+ );
+
+ await utils.expectRevert(
+ helper.multisig().revokeConfirmation(
+ transactionID,
+ { from: helper.wallet(0) },
+ ),
+ );
+ });
+ });
+
+ contract('Events', async (accounts) => {
+ const accountProvider = new AccountProvider(accounts);
+
+ it('Emits TransactionConfirmationRevoked on successfull revocation.', async () => {
+ const helper = await new MultiSigWalletUtils(
+ { accountProvider, walletCount: 2, required: 2 },
+ );
+
+ const transactionID = await helper.submitAddWallet(
+ accountProvider.get(), 0,
+ );
+
+ const transactionResponse = await helper.multisig().revokeConfirmation(
+ transactionID,
+ { from: helper.wallet(0) },
+ );
+
+ const events = Event.decodeTransactionResponse(
+ transactionResponse,
+ );
+
+ assert.strictEqual(
+ events.length,
+ 1,
+ );
+
+ // The first emitted event should be 'TransactionConfirmationRevoked'.
+ Event.assertEqual(events[0], {
+ name: 'TransactionConfirmationRevoked',
+ args: {
+ _transactionID: new BN(0),
+ _wallet: helper.wallet(0),
+ },
+ });
+ });
+ });
+
+ contract('Storage', async (accounts) => {
+ const accountProvider = new AccountProvider(accounts);
+
+ it('Checks that wallet confirmation flag is cleared.', async () => {
+ const helper = await new MultiSigWalletUtils(
+ { accountProvider, walletCount: 2, required: 2 },
+ );
+
+ const transactionID = await helper.submitAddWallet(
+ accountProvider.get(), 0,
+ );
+
+ assert.isOk(
+ await helper.multisig().confirmations(
+ transactionID, helper.wallet(0),
+ ),
+ );
+
+ await helper.multisig().revokeConfirmation(
+ transactionID,
+ { from: helper.wallet(0) },
+ );
+
+ assert.isNotOk(
+ await helper.multisig().confirmations(
+ transactionID, helper.wallet(0),
+ ),
+ );
+ });
+ });
+});
diff --git a/test/multisigwallet/submit_add_wallet.js b/test/multisigwallet/submit_add_wallet.js
new file mode 100644
index 0000000..1f629fc
--- /dev/null
+++ b/test/multisigwallet/submit_add_wallet.js
@@ -0,0 +1,303 @@
+// Copyright 2018 OpenST Ltd.
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+const BN = require('bn.js');
+const web3 = require('../test_lib/web3.js');
+const utils = require('../test_lib/utils.js');
+const { Event } = require('../test_lib/event_decoder');
+const { AccountProvider } = require('../test_lib/utils.js');
+const { MultiSigWalletUtils } = require('./utils.js');
+
+function generateAddWalletData(wallet) {
+ return web3.eth.abi.encodeFunctionCall(
+ {
+ name: 'addWallet',
+ type: 'function',
+ inputs: [{
+ type: 'address',
+ name: '',
+ }],
+ },
+ [wallet],
+ );
+}
+
+contract('MultiSigWallet::submitAddWallet', async () => {
+ contract('Negative Tests', async (accounts) => {
+ const accountProvider = new AccountProvider(accounts);
+
+ it('Reverts if non-registered wallet calls.', async () => {
+ const helper = await new MultiSigWalletUtils(
+ { accountProvider, walletCount: 1, required: 1 },
+ );
+
+ await utils.expectRevert(
+ helper.multisig().submitAddWallet(
+ accountProvider.get(),
+ { from: accountProvider.get() },
+ ),
+ 'Should revert as non-registered wallet calls.',
+ 'Only wallet is allowed to call.',
+ );
+ });
+
+ it('Reverts if a null wallet is submitted for addition.', async () => {
+ const helper = await new MultiSigWalletUtils(
+ { accountProvider, walletCount: 1, required: 1 },
+ );
+
+ await utils.expectRevert(
+ helper.multisig().submitAddWallet(
+ utils.NULL_ADDRESS,
+ { from: helper.wallet(0) },
+ ),
+ 'Should revert as the submitted wallet is null.',
+ 'Wallet address is null.',
+ );
+ });
+
+ it('Reverts if the submitted wallet already exists.', async () => {
+ const helper = await new MultiSigWalletUtils(
+ { accountProvider, walletCount: 2, required: 2 },
+ );
+
+ await utils.expectRevert(
+ helper.multisig().submitAddWallet(
+ helper.wallet(1),
+ { from: helper.wallet(0) },
+ ),
+ 'Should revert as the submitted wallet already exists.',
+ 'Wallet exists.',
+ );
+ });
+ });
+
+ contract('Events', async (accounts) => {
+ const accountProvider = new AccountProvider(accounts);
+
+ it('Emits WalletAdditionSubmitted, TransactionConfirmed '
+ + 'TransactionExecutionSucceeded events.', async () => {
+ const helper = await new MultiSigWalletUtils(
+ { accountProvider, walletCount: 1, required: 1 },
+ );
+
+ const walletToAdd = accountProvider.get();
+ const transactionResponse = await helper.multisig().submitAddWallet(
+ walletToAdd,
+ { from: helper.wallet(0) },
+ );
+
+ const events = Event.decodeTransactionResponse(
+ transactionResponse,
+ );
+
+ assert.strictEqual(
+ events.length,
+ 3,
+ 'As the requirement is 1, transaction would be executed '
+ + 'afterwards, hence WalletAdditionSubmitted, '
+ + 'TransactionConfirmed and TransactionExecutionSucceeded '
+ + 'would be emitted.',
+ );
+
+
+ // The first emitted event should be 'WalletAdditionSubmitted'.
+ Event.assertEqual(events[0], {
+ name: 'WalletAdditionSubmitted',
+ args: {
+ _transactionID: new BN(0),
+ _wallet: walletToAdd,
+ },
+ });
+
+ // The second emitted event should be 'TransactionConfirmed',
+ // because the wallet that submitted a new wallet addition request
+ // should confirm it afterwards in the same call.
+ Event.assertEqual(events[1], {
+ name: 'TransactionConfirmed',
+ args: {
+ _transactionID: new BN(0),
+ _wallet: helper.wallet(0),
+ },
+ });
+
+ // The third emitted event should be
+ // 'TransactionExecutionSucceeded', because of the setup
+ // 1-wallet-1-requirement.
+ Event.assertEqual(events[2], {
+ name: 'TransactionExecutionSucceeded',
+ args: {
+ _transactionID: new BN(0),
+ },
+ });
+ });
+
+ it('Emits WalletAdditionSubmitted and TransactionConfirmed.', async () => {
+ const helper = await new MultiSigWalletUtils(
+ { accountProvider, walletCount: 2, required: 2 },
+ );
+
+ const walletToAdd = accountProvider.get();
+ const transactionResponse = await helper.multisig().submitAddWallet(
+ walletToAdd,
+ { from: helper.wallet(0) },
+ );
+
+ const events = Event.decodeTransactionResponse(
+ transactionResponse,
+ );
+
+ assert.strictEqual(
+ events.length,
+ 2,
+ 'As the requirement is 2, transaction would not be executed '
+ + 'afterwards, hence WalletAdditionSubmitted and '
+ + 'TransactionConfirmed would be only emitted.',
+ );
+
+
+ // The first emitted event should be 'WalletAdditionSubmitted'.
+ Event.assertEqual(events[0], {
+ name: 'WalletAdditionSubmitted',
+ args: {
+ _transactionID: new BN(0),
+ _wallet: walletToAdd,
+ },
+ });
+
+ // The second emitted event should be 'TransactionConfirmed',
+ // because the wallet that submitted a new wallet addition request
+ // should confirm it afterwards in the same call.
+ Event.assertEqual(events[1], {
+ name: 'TransactionConfirmed',
+ args: {
+ _transactionID: new BN(0),
+ _wallet: helper.wallet(0),
+ },
+ });
+ });
+ });
+
+ contract('Storage', async (accounts) => {
+ const accountProvider = new AccountProvider(accounts);
+
+ it('Checks state in case of 1-wallet-1-required.', async () => {
+ const helper = await new MultiSigWalletUtils(
+ { accountProvider, walletCount: 1, required: 1 },
+ );
+
+ const walletToAdd = accountProvider.get();
+ const transactionID = await helper.submitAddWallet(
+ walletToAdd, 0,
+ );
+
+ assert.isOk(
+ await helper.multisig().isWallet.call(walletToAdd),
+ 'Newly submitted wallet would be added because of '
+ + '1-wallet-1-required condition.',
+ );
+
+ assert.strictEqual(
+ await helper.multisig().wallets.call(0),
+ helper.wallet(0),
+ );
+
+ assert.strictEqual(
+ await helper.multisig().wallets.call(1),
+ walletToAdd,
+ );
+
+ assert.isOk(
+ (await helper.multisig().transactionCount.call()).eqn(1),
+ 'Transaction count should be increased by one.',
+ );
+
+ assert.isOk(
+ await helper.multisig().confirmations.call(
+ transactionID, helper.wallet(0),
+ ),
+ );
+
+ const transaction = await helper.multisig().transactions.call(transactionID);
+
+ assert.strictEqual(
+ transaction.destination,
+ helper.multisig().address,
+ );
+
+ assert.strictEqual(
+ transaction.data,
+ generateAddWalletData(walletToAdd),
+ );
+
+ assert.isOk(
+ transaction.executed,
+ );
+ });
+
+ it('Checks state in case of 2-wallets-2-required.', async () => {
+ const helper = await new MultiSigWalletUtils(
+ { accountProvider, walletCount: 2, required: 2 },
+ );
+
+ const walletToAdd = accountProvider.get();
+ const transactionID = await helper.submitAddWallet(
+ walletToAdd, 0,
+ );
+
+ assert.isNotOk(
+ await helper.multisig().isWallet.call(walletToAdd),
+ 'Newly submitted wallet would *not* be added because of '
+ + '2-wallet-1-required condition.',
+ );
+
+ assert.strictEqual(
+ await helper.multisig().wallets.call(0),
+ helper.wallet(0),
+ );
+
+ assert.strictEqual(
+ await helper.multisig().wallets.call(1),
+ helper.wallet(1),
+ );
+
+ assert.isOk(
+ (await helper.multisig().transactionCount.call()).eqn(1),
+ 'Transaction count should be increased by one.',
+ );
+
+ assert.isOk(
+ await helper.multisig().confirmations.call(
+ transactionID, helper.wallet(0),
+ ),
+ );
+
+ const transaction = await helper.multisig().transactions.call(transactionID);
+
+ assert.strictEqual(
+ transaction.destination,
+ helper.multisig().address,
+ );
+
+ assert.strictEqual(
+ transaction.data,
+ generateAddWalletData(walletToAdd),
+ );
+
+ assert.isNotOk(
+ transaction.executed,
+ );
+ });
+ });
+});
diff --git a/test/multisigwallet/submit_remove_wallet.js b/test/multisigwallet/submit_remove_wallet.js
new file mode 100644
index 0000000..ff089f1
--- /dev/null
+++ b/test/multisigwallet/submit_remove_wallet.js
@@ -0,0 +1,335 @@
+// Copyright 2018 OpenST Ltd.
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+const BN = require('bn.js');
+const web3 = require('../test_lib/web3.js');
+const utils = require('../test_lib/utils.js');
+const { Event } = require('../test_lib/event_decoder');
+const { AccountProvider } = require('../test_lib/utils.js');
+const { MultiSigWalletUtils } = require('./utils.js');
+
+function generateRemoveWalletData(wallet) {
+ return web3.eth.abi.encodeFunctionCall(
+ {
+ name: 'removeWallet',
+ type: 'function',
+ inputs: [{
+ type: 'address',
+ name: '',
+ }],
+ },
+ [wallet],
+ );
+}
+
+contract('MultiSigWallet::submitReplaceWallet', async () => {
+ contract('Negative Tests', async (accounts) => {
+ const accountProvider = new AccountProvider(accounts);
+
+ it('Reverts if non-registered wallet calls.', async () => {
+ const helper = await new MultiSigWalletUtils(
+ { accountProvider, walletCount: 1, required: 1 },
+ );
+
+ await utils.expectRevert(
+ helper.multisig().submitRemoveWallet(
+ accountProvider.get(),
+ { from: accountProvider.get() },
+ ),
+ 'Should revert as non-registered wallet calls.',
+ 'Only wallet is allowed to call.',
+ );
+ });
+
+ it('Reverts if wallet to remove does not exist.', async () => {
+ const helper = await new MultiSigWalletUtils(
+ { accountProvider, walletCount: 1, required: 1 },
+ );
+
+ await utils.expectRevert(
+ helper.multisig().submitRemoveWallet(
+ accountProvider.get(),
+ { from: helper.wallet(0) },
+ ),
+ 'Should revert as wallet to remove does not exist.',
+ 'Wallet does not exist.',
+ );
+ });
+
+ it('Reverts if last wallet is going to be removed.', async () => {
+ const helper = await new MultiSigWalletUtils(
+ { accountProvider, walletCount: 1, required: 1 },
+ );
+
+ await utils.expectRevert(
+ helper.multisig().submitRemoveWallet(
+ helper.wallet(0),
+ {
+ from: helper.wallet(0),
+ },
+ ),
+ 'Should revert as last wallet is submitted for removal',
+ 'Last wallet cannot be submitted for removal.',
+ );
+ });
+ });
+
+ contract('Events', async (accounts) => {
+ const accountProvider = new AccountProvider(accounts);
+
+ it('Emits WalletRemovalSubmitted, TransactionConfirmed '
+ + 'TransactionExecutionSucceeded events.', async () => {
+ const helper = await new MultiSigWalletUtils(
+ { accountProvider, walletCount: 2, required: 1 },
+ );
+
+ const transactionResponse = await helper.multisig().submitRemoveWallet(
+ helper.wallet(1),
+ { from: helper.wallet(0) },
+ );
+
+ const events = Event.decodeTransactionResponse(
+ transactionResponse,
+ );
+
+ assert.strictEqual(
+ events.length,
+ 3,
+ 'As requirement is 1, transaction would be executed '
+ + 'afterwards, hence WalletRemovalSubmitted, '
+ + 'TransactionConfirmed and TransactionExecutionSucceeded '
+ + 'would be emitted.',
+ );
+
+
+ // The first emitted event should be 'WalletRemovalSubmitted'.
+ Event.assertEqual(events[0], {
+ name: 'WalletRemovalSubmitted',
+ args: {
+ _transactionID: new BN(0),
+ _wallet: helper.wallet(1),
+ },
+ });
+
+ // The second emitted event should be 'TransactionConfirmed',
+ // because the wallet that submitted a wallet removal request
+ // should confirm it afterwards.
+ Event.assertEqual(events[1], {
+ name: 'TransactionConfirmed',
+ args: {
+ _transactionID: new BN(0),
+ _wallet: helper.wallet(0),
+ },
+ });
+
+ // The third emitted event should be
+ // 'TransactionExecutionSucceeded', because of the setup
+ // 2-wallet-1-requirement.
+ Event.assertEqual(events[2], {
+ name: 'TransactionExecutionSucceeded',
+ args: {
+ _transactionID: new BN(0),
+ },
+ });
+ });
+
+ it('Emits WalletRemovalSubmitted and TransactionConfirmed.', async () => {
+ const helper = await new MultiSigWalletUtils(
+ { accountProvider, walletCount: 3, required: 2 },
+ );
+
+ const transactionResponse = await helper.multisig().submitRemoveWallet(
+ helper.wallet(1),
+ { from: helper.wallet(0) },
+ );
+
+ const events = Event.decodeTransactionResponse(
+ transactionResponse,
+ );
+
+ assert.strictEqual(
+ events.length,
+ 2,
+ 'As requirement is 2, transaction would not be executed '
+ + 'afterwards, hence only WalletRemovalSubmitted and '
+ + 'TransactionConfirmed would be emitted.',
+ );
+
+ // The first emitted event should be 'WalletRemovalSubmitted'.
+ Event.assertEqual(events[0], {
+ name: 'WalletRemovalSubmitted',
+ args: {
+ _transactionID: new BN(0),
+ _wallet: helper.wallet(1),
+ },
+ });
+
+ // The second emitted event should be 'TransactionConfirmed',
+ // because the wallet that submitted a wallet removal request
+ // should confirm it afterwards.
+ Event.assertEqual(events[1], {
+ name: 'TransactionConfirmed',
+ args: {
+ _transactionID: new BN(0),
+ _wallet: helper.wallet(0),
+ },
+ });
+ });
+ });
+
+ contract('Storage', async (accounts) => {
+ const accountProvider = new AccountProvider(accounts);
+
+ it('Checks state in case of 2-wallets-1-required.', async () => {
+ const helper = await new MultiSigWalletUtils(
+ { accountProvider, walletCount: 2, required: 1 },
+ );
+
+ const transactionID = await helper.submitRemoveWallet(1, 0);
+
+ assert.isNotOk(
+ await helper.multisig().isWallet.call(helper.wallet(1)),
+ 'Wallet will be removed because of 2-wallets-1-required '
+ + 'setup.',
+ );
+
+ assert.isOk(
+ (await helper.multisig().walletCount.call()).eqn(1),
+ );
+
+ assert.strictEqual(
+ await helper.multisig().wallets.call(0),
+ helper.wallet(0),
+ );
+
+ assert.isOk(
+ (await helper.multisig().required.call()).eqn(1),
+ );
+
+ assert.isOk(
+ await helper.multisig().confirmations(
+ transactionID, helper.wallet(0),
+ ),
+ );
+
+ assert.isOk(
+ (await helper.multisig().transactionCount.call()).eqn(1),
+ );
+
+ const transaction = await helper.multisig().transactions.call(transactionID);
+
+ assert.strictEqual(
+ transaction.destination,
+ helper.multisig().address,
+ );
+
+ assert.strictEqual(
+ transaction.data,
+ generateRemoveWalletData(helper.wallet(1)),
+ );
+
+ assert.strictEqual(
+ transaction.executed,
+ true,
+ );
+ });
+
+ it('Checks state in case of 3-wallets-2-required.', async () => {
+ const helper = await new MultiSigWalletUtils(
+ { accountProvider, walletCount: 3, required: 2 },
+ );
+
+ const transactionID = await helper.submitRemoveWallet(1, 0);
+
+ assert.isOk(
+ await helper.multisig().isWallet.call(helper.wallet(1)),
+ 'Wallet will not be removed because of 3-wallets-2-required '
+ + 'setup.',
+ );
+
+ assert.isOk(
+ (await helper.multisig().walletCount.call()).eqn(3),
+ );
+
+ assert.strictEqual(
+ await helper.multisig().wallets.call(0),
+ helper.wallet(0),
+ );
+
+ assert.strictEqual(
+ await helper.multisig().wallets.call(1),
+ helper.wallet(1),
+ );
+
+ assert.strictEqual(
+ await helper.multisig().wallets.call(2),
+ helper.wallet(2),
+ );
+
+ assert.isOk(
+ (await helper.multisig().required.call()).eqn(2),
+ );
+
+ assert.isOk(
+ await helper.multisig().confirmations(
+ transactionID, helper.wallet(0),
+ ),
+ );
+
+ assert.isOk(
+ (await helper.multisig().transactionCount.call()).eqn(1),
+ );
+
+ const transaction = await helper.multisig().transactions.call(transactionID);
+
+ assert.strictEqual(
+ transaction.destination,
+ helper.multisig().address,
+ );
+
+ assert.strictEqual(
+ transaction.data,
+ generateRemoveWalletData(helper.wallet(1)),
+ );
+
+ assert.strictEqual(
+ transaction.executed,
+ false,
+ );
+ });
+
+ it('Checks that requirement is adjusted after removal.', async () => {
+ const helper = await new MultiSigWalletUtils(
+ { accountProvider, walletCount: 2, required: 2 },
+ );
+
+ const transactionID = await helper.submitRemoveWallet(1, 0);
+
+ assert.isOk(
+ (await helper.multisig().required.call()).eqn(2),
+ );
+
+ await helper.multisig().confirmTransaction(
+ transactionID,
+ { from: helper.wallet(1) },
+ );
+
+ assert.isOk(
+ (await helper.multisig().required.call()).eqn(1),
+ 'After removing the wallet the required should be updated '
+ + 'to max wallet count, in this case 1.',
+ );
+ });
+ });
+});
diff --git a/test/multisigwallet/submit_replace_wallet.js b/test/multisigwallet/submit_replace_wallet.js
new file mode 100644
index 0000000..0caba44
--- /dev/null
+++ b/test/multisigwallet/submit_replace_wallet.js
@@ -0,0 +1,367 @@
+// Copyright 2018 OpenST Ltd.
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+const BN = require('bn.js');
+const web3 = require('../test_lib/web3.js');
+const utils = require('../test_lib/utils.js');
+const { Event } = require('../test_lib/event_decoder');
+const { AccountProvider } = require('../test_lib/utils.js');
+const { MultiSigWalletUtils } = require('./utils.js');
+
+function generateReplaceWalletData(oldWallet, newWallet) {
+ return web3.eth.abi.encodeFunctionCall(
+ {
+ name: 'replaceWallet',
+ type: 'function',
+ inputs: [
+ {
+ type: 'address',
+ name: '',
+ },
+ {
+ type: 'address',
+ name: '',
+ }],
+ },
+ [oldWallet, newWallet],
+ );
+}
+
+contract('MultiSigWallet::submitReplaceWallet', async () => {
+ contract('Negative Tests', async (accounts) => {
+ const accountProvider = new AccountProvider(accounts);
+
+ it('Reverts if non-registered wallet calls.', async () => {
+ const helper = await new MultiSigWalletUtils(
+ { accountProvider, walletCount: 2, required: 1 },
+ );
+
+ await utils.expectRevert(
+ helper.multisig().submitReplaceWallet(
+ helper.wallet(1),
+ accountProvider.get(),
+ { from: accountProvider.get() },
+ ),
+ 'Should revert as non-registered wallet calls.',
+ 'Only wallet is allowed to call.',
+ );
+ });
+
+ it('Reverts if old wallet to replace does not exist.', async () => {
+ const helper = await new MultiSigWalletUtils(
+ { accountProvider, walletCount: 2, required: 1 },
+ );
+
+ await utils.expectRevert(
+ helper.multisig().submitReplaceWallet(
+ accountProvider.get(),
+ accountProvider.get(),
+ { from: helper.wallet(0) },
+ ),
+ 'Should revert as old wallet to replace does not exist.',
+ 'Wallet does not exist.',
+ );
+ });
+
+ it('Reverts if new wallet to add is null.', async () => {
+ const helper = await new MultiSigWalletUtils(
+ { accountProvider, walletCount: 2, required: 1 },
+ );
+
+ await utils.expectRevert(
+ helper.multisig().submitReplaceWallet(
+ helper.wallet(1),
+ utils.NULL_ADDRESS,
+ { from: helper.wallet(0) },
+ ),
+ 'Should revert as new wallet to add is null.',
+ 'Wallet address is null.',
+ );
+ });
+
+ it('Reverts if new wallet to add already exists.', async () => {
+ const helper = await new MultiSigWalletUtils(
+ { accountProvider, walletCount: 2, required: 1 },
+ );
+
+ await utils.expectRevert(
+ helper.multisig().submitReplaceWallet(
+ helper.wallet(1),
+ helper.wallet(1),
+ { from: helper.wallet(0) },
+ ),
+ 'Should revert as new wallet to add already exists.',
+ 'Wallet exists.',
+ );
+ });
+ });
+
+ contract('Events', async (accounts) => {
+ const accountProvider = new AccountProvider(accounts);
+
+ it('Emits WalletReplacementSubmitted, TransactionConfirmed '
+ + 'TransactionExecutionSucceeded events.', async () => {
+ const helper = await new MultiSigWalletUtils(
+ { accountProvider, walletCount: 2, required: 1 },
+ );
+
+ const newWalletForReplacement = accountProvider.get();
+ const transactionResponse = await helper.multisig().submitReplaceWallet(
+ helper.wallet(1),
+ newWalletForReplacement,
+ { from: helper.wallet(0) },
+ );
+
+ const events = Event.decodeTransactionResponse(
+ transactionResponse,
+ );
+
+ assert.strictEqual(
+ events.length,
+ 3,
+ 'As requirement is 1, transaction would be executed '
+ + 'afterwards, hence WalletReplacementSubmitted, '
+ + 'TransactionConfirmed and TransactionExecutionSucceeded '
+ + 'would be emitted.',
+ );
+
+ // The first emitted event should be 'WalletReplacementSubmitted'.
+ Event.assertEqual(events[0], {
+ name: 'WalletReplacementSubmitted',
+ args: {
+ _transactionID: new BN(0),
+ _oldWallet: helper.wallet(1),
+ _newWallet: newWalletForReplacement,
+ },
+ });
+
+ // The second emitted event should be 'TransactionConfirmed', as
+ // the wallet that submits transaction confirms afterwards.
+ Event.assertEqual(events[1], {
+ name: 'TransactionConfirmed',
+ args: {
+ _transactionID: new BN(0),
+ _wallet: helper.wallet(0),
+ },
+ });
+
+ // The third emitted event should be 'TransactionExecutionSucceeded'
+ // as requirement is 1, hence transaction would be executed
+ // afterwards.
+ Event.assertEqual(events[2], {
+ name: 'TransactionExecutionSucceeded',
+ args: {
+ _transactionID: new BN(0),
+ },
+ });
+ });
+
+ it('Emits WalletReplacementSubmitted and TransactionConfirmed.', async () => {
+ const helper = await new MultiSigWalletUtils(
+ { accountProvider, walletCount: 2, required: 2 },
+ );
+
+ const newWalletToReplace = accountProvider.get();
+ const transactionResponse = await helper.multisig().submitReplaceWallet(
+ helper.wallet(1),
+ newWalletToReplace,
+ { from: helper.wallet(0) },
+ );
+
+ const events = Event.decodeTransactionResponse(
+ transactionResponse,
+ );
+
+ assert.strictEqual(
+ events.length,
+ 2,
+ 'As requirement is 2, transaction would not be executed '
+ + 'afterwards, hence only WalletReplacementSubmitted and '
+ + 'TransactionConfirmed would be emitted.',
+ );
+
+ // The first emitted event should be 'WalletReplacementSubmitted'.
+ Event.assertEqual(events[0], {
+ name: 'WalletReplacementSubmitted',
+ args: {
+ _transactionID: new BN(0),
+ _oldWallet: helper.wallet(1),
+ _newWallet: newWalletToReplace,
+ },
+ });
+
+ // The second emitted event should be 'TransactionConfirmed', as
+ // the wallet that submits transaction confirms afterwards.
+ Event.assertEqual(events[1], {
+ name: 'TransactionConfirmed',
+ args: {
+ _transactionID: new BN(0),
+ _wallet: helper.wallet(0),
+ },
+ });
+ });
+ });
+
+ contract('Storage', async (accounts) => {
+ const accountProvider = new AccountProvider(accounts);
+
+ it('Checks state in case of 2-wallets-1-required.', async () => {
+ const helper = await new MultiSigWalletUtils(
+ { accountProvider, walletCount: 2, required: 1 },
+ );
+
+ const newWalletForReplacement = accountProvider.get();
+ const transactionID = await helper.submitReplaceWallet(
+ 1, newWalletForReplacement, 0,
+ );
+
+ assert.isOk(
+ await helper.multisig().isWallet.call(newWalletForReplacement),
+ 'Wallet replacement should happen immediately, because of '
+ + '2-wallets-1-required setup.',
+ );
+
+ assert.isNotOk(
+ await helper.multisig().isWallet.call(helper.wallet(1)),
+ 'Wallet replacement should happen immediately, because of '
+ + '2-wallets-1-required setup.',
+ );
+
+ assert.isOk(
+ (await helper.multisig().walletCount.call()).eqn(2),
+ 'Wallet count should not change during replace.',
+ );
+
+ assert.strictEqual(
+ await helper.multisig().wallets.call(0),
+ helper.wallet(0),
+ );
+
+ assert.strictEqual(
+ await helper.multisig().wallets.call(1),
+ newWalletForReplacement,
+ );
+
+ assert.isOk(
+ (await helper.multisig().required.call()).eqn(1),
+ 'Required number of confirmation should stay unchanged.',
+ );
+
+ assert.isOk(
+ (await helper.multisig().transactionCount.call()).eqn(1),
+ 'Transaction count should be increased by one.',
+ );
+
+ assert.strictEqual(
+ await helper.multisig().confirmations.call(
+ transactionID, helper.wallet(0),
+ ),
+ true,
+ );
+
+ const transaction = await helper.multisig().transactions.call(transactionID);
+
+ assert.strictEqual(
+ transaction.destination,
+ helper.multisig().address,
+ );
+
+ assert.strictEqual(
+ transaction.data,
+ generateReplaceWalletData(
+ helper.wallet(1), newWalletForReplacement,
+ ),
+ );
+
+ assert.strictEqual(
+ transaction.executed,
+ true,
+ );
+ });
+
+ it('Checks state in case of 2-wallets-2-required.', async () => {
+ const helper = await new MultiSigWalletUtils(
+ { accountProvider, walletCount: 2, required: 2 },
+ );
+
+ const newWalletForReplacement = accountProvider.get();
+ const transactionID = await helper.submitReplaceWallet(
+ 1, newWalletForReplacement, 0,
+ );
+
+ assert.isOk(
+ await helper.multisig().isWallet.call(helper.wallet(1)),
+ 'Wallet replacement should not happen immediately, because of '
+ + '2-wallets-2-required setup.',
+ );
+
+ assert.isNotOk(
+ await helper.multisig().isWallet.call(newWalletForReplacement),
+ 'Wallet replacement should not happen immediately, because of '
+ + '2-wallets-2-required setup.',
+ );
+
+ assert.isOk(
+ (await helper.multisig().walletCount.call()).eqn(2),
+ 'Wallet count should not change during replace.',
+ );
+
+ assert.strictEqual(
+ await helper.multisig().wallets.call(0),
+ helper.wallet(0),
+ );
+
+ assert.strictEqual(
+ await helper.multisig().wallets.call(1),
+ helper.wallet(1),
+ );
+
+ assert.isOk(
+ (await helper.multisig().required.call()).eqn(2),
+ 'Required number of confirmation should stay unchanged.',
+ );
+
+ assert.isOk(
+ (await helper.multisig().transactionCount.call()).eqn(1),
+ 'Transaction count should be increased by one.',
+ );
+
+ assert.strictEqual(
+ await helper.multisig().confirmations.call(
+ transactionID, helper.wallet(0),
+ ),
+ true,
+ );
+
+ const transaction = await helper.multisig().transactions.call(transactionID);
+
+ assert.strictEqual(
+ transaction.destination,
+ helper.multisig().address,
+ );
+
+ assert.strictEqual(
+ transaction.data,
+ generateReplaceWalletData(
+ helper.wallet(1), newWalletForReplacement,
+ ),
+ );
+
+ assert.strictEqual(
+ transaction.executed,
+ false,
+ );
+ });
+ });
+});
diff --git a/test/multisigwallet/submit_requirement_change.js b/test/multisigwallet/submit_requirement_change.js
new file mode 100644
index 0000000..4c6f718
--- /dev/null
+++ b/test/multisigwallet/submit_requirement_change.js
@@ -0,0 +1,317 @@
+// Copyright 2018 OpenST Ltd.
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+//
+// ----------------------------------------------------------------------------
+// Test: MultiSigWallet::submitRequirementChange
+//
+// http://www.simpletoken.org/
+//
+// ----------------------------------------------------------------------------
+
+const BN = require('bn.js');
+const web3 = require('../test_lib/web3.js');
+const utils = require('../test_lib/utils.js');
+const { Event } = require('../test_lib/event_decoder');
+const { AccountProvider } = require('../test_lib/utils.js');
+const { MultiSigWalletUtils } = require('./utils.js');
+
+
+function generateRequirementChangeData(required) {
+ return web3.eth.abi.encodeFunctionCall(
+ {
+ name: 'changeRequirement',
+ type: 'function',
+ inputs: [{
+ type: 'uint256',
+ name: '',
+ }],
+ },
+ [required],
+ );
+}
+
+contract('MultiSigWallet::submitRequirementChange', async () => {
+ contract('Negative Tests', async (accounts) => {
+ const accountProvider = new AccountProvider(accounts);
+
+ it('Reverts if non-registered wallet calls.', async () => {
+ const helper = await new MultiSigWalletUtils(
+ { accountProvider, walletCount: 2, required: 1 },
+ );
+
+
+ await utils.expectRevert(
+ helper.multisig().submitRequirementChange(
+ 2,
+ { from: accountProvider.get() },
+ ),
+ 'Should revert as non-registered wallet calls.',
+ 'Only wallet is allowed to call.',
+ );
+ });
+
+ it('Should revert if new requirement equal to 0.', async () => {
+ const helper = await new MultiSigWalletUtils(
+ { accountProvider, walletCount: 1, required: 1 },
+ );
+
+ await utils.expectRevert(
+ helper.multisig().submitRequirementChange(
+ 0,
+ { from: helper.wallet(0) },
+ ),
+ 'Should revert as new requirement is 0.',
+ 'Requirement validity not fulfilled.',
+ );
+ });
+
+ it('Should revert if new requirement is bigger than wallets count.', async () => {
+ const helper = await new MultiSigWalletUtils(
+ { accountProvider, walletCount: 1, required: 1 },
+ );
+
+ await utils.expectRevert(
+ helper.multisig().submitRequirementChange(
+ 2,
+ { from: helper.wallet(0) },
+ ),
+ 'Should revert as new requirement is 2 and wallet counts is 1.',
+ 'Requirement validity not fulfilled.',
+ );
+ });
+ });
+
+ contract('Events', async (accounts) => {
+ const accountProvider = new AccountProvider(accounts);
+
+ it('Emits RequirementChangeSubmitted, TransactionConfirmed '
+ + 'TransactionExecutionSucceeded events.', async () => {
+ const helper = await new MultiSigWalletUtils(
+ { accountProvider, walletCount: 2, required: 1 },
+ );
+
+ const newRequired = 2;
+
+ const transactionResponse = await helper.multisig().submitRequirementChange(
+ newRequired,
+ { from: helper.wallet(0) },
+ );
+
+ const events = Event.decodeTransactionResponse(
+ transactionResponse,
+ );
+
+ assert.strictEqual(
+ events.length,
+ 3,
+ 'As requirement is 1, transaction would be executed '
+ + 'afterwards, hence RequirementChangeSubmitted, '
+ + 'TransactionConfirmed and TransactionExecutionSucceeded '
+ + 'would be emitted.',
+ );
+
+ // The first emitted event should be 'RequirementChangeSubmitted'.
+ Event.assertEqual(events[0], {
+ name: 'RequirementChangeSubmitted',
+ args: {
+ _transactionID: new BN(0),
+ _required: new BN(newRequired),
+ },
+ });
+
+ // The second emitted event should be 'TransactionConfirmed', as
+ // the wallet that submits transaction confirms afterwards.
+ Event.assertEqual(events[1], {
+ name: 'TransactionConfirmed',
+ args: {
+ _transactionID: new BN(0),
+ _wallet: helper.wallet(0),
+ },
+ });
+
+ // The third emitted event should be 'TransactionExecutionSucceeded'
+ // as requirement is 1, hence transaction would be executed
+ // afterwards.
+ Event.assertEqual(events[2], {
+ name: 'TransactionExecutionSucceeded',
+ args: {
+ _transactionID: new BN(0),
+ },
+ });
+ });
+
+ it('Emits RequirementChangeSubmitted and TransactionConfirmed.', async () => {
+ const helper = await new MultiSigWalletUtils(
+ { accountProvider, walletCount: 3, required: 2 },
+ );
+
+ const newRequired = 3;
+
+ const transactionResponse = await helper.multisig().submitRequirementChange(
+ newRequired,
+ { from: helper.wallet(0) },
+ );
+
+ const events = Event.decodeTransactionResponse(
+ transactionResponse,
+ );
+
+ assert.strictEqual(
+ events.length,
+ 2,
+ 'As requirement is 2, transaction would not be executed '
+ + 'afterwards, hence RequirementChangeSubmitted and '
+ + 'TransactionConfirmed would be emitted.',
+ );
+
+ // The first emitted event should be 'RequirementChangeSubmitted'.
+ Event.assertEqual(events[0], {
+ name: 'RequirementChangeSubmitted',
+ args: {
+ _transactionID: new BN(0),
+ _required: new BN(newRequired),
+ },
+ });
+
+ // The second emitted event should be 'TransactionConfirmed', as
+ // the wallet that submits transaction confirms afterwards.
+ Event.assertEqual(events[1], {
+ name: 'TransactionConfirmed',
+ args: {
+ _transactionID: new BN(0),
+ _wallet: helper.wallet(0),
+ },
+ });
+ });
+ });
+
+ contract('Storage', async (accounts) => {
+ const accountProvider = new AccountProvider(accounts);
+
+ it('Checks state in case of 2-wallets-1-required.', async () => {
+ const helper = await new MultiSigWalletUtils(
+ { accountProvider, walletCount: 2, required: 1 },
+ );
+
+ const newRequired = 2;
+
+ const transactionID = await helper.submitRequirementChange(
+ newRequired,
+ 0,
+ );
+
+ assert.isOk(
+ (await helper.multisig().required.call()).eqn(newRequired),
+ 'As required is equal to 1, the transaction would be '
+ + 'executed in the same call.',
+ );
+
+ assert.isOk(
+ await helper.multisig().confirmations(
+ transactionID, helper.wallet(0),
+ ),
+ 'Submitter should also confirm.',
+ );
+
+ assert.isNotOk(
+ await helper.multisig().confirmations(
+ transactionID, helper.wallet(1),
+ ),
+ 'Non submitter should not confirm.',
+ );
+
+ assert.isOk(
+ (await helper.multisig().transactionCount.call()).eqn(1),
+ 'Transaction count should be increased by one.',
+ );
+
+ const transaction = await helper.multisig().transactions.call(transactionID);
+
+ assert.strictEqual(
+ transaction.destination,
+ helper.multisig().address,
+ );
+
+ assert.strictEqual(
+ transaction.data,
+ generateRequirementChangeData(newRequired),
+ );
+
+ assert.strictEqual(
+ transaction.executed,
+ true,
+ );
+ });
+
+ it('Checks state in case of 3-wallets-2-required.', async () => {
+ const helper = await new MultiSigWalletUtils(
+ { accountProvider, walletCount: 3, required: 2 },
+ );
+
+ const required = 2;
+ const newRequired = 3;
+
+ const transactionID = await helper.submitRequirementChange(
+ newRequired, 0,
+ );
+
+ assert.isOk(
+ (await helper.multisig().required.call()).eqn(required),
+ 'As required is equal to 2, the transaction would not be '
+ + 'executed in the same call.',
+ );
+
+ assert.isOk(
+ await helper.multisig().confirmations(
+ transactionID, helper.wallet(0),
+ ),
+ 'Submitter should also confirm.',
+ );
+
+ assert.isNotOk(
+ await helper.multisig().confirmations(
+ transactionID, helper.wallet(1),
+ ),
+ 'Non submitter should not confirm.',
+ );
+
+ assert.isNotOk(
+ await helper.multisig().confirmations(transactionID, helper.wallet(2)),
+ 'Non submitter should not confirm.',
+ );
+
+ assert.isOk(
+ (await helper.multisig().transactionCount.call()).eqn(1),
+ 'Transaction count should be increased by one.',
+ );
+
+ const transaction = await helper.multisig().transactions.call(transactionID);
+
+ assert.strictEqual(
+ transaction.destination,
+ helper.multisig().address,
+ );
+
+ assert.strictEqual(
+ transaction.data,
+ generateRequirementChangeData(newRequired),
+ );
+
+ assert.strictEqual(
+ transaction.executed,
+ false,
+ );
+ });
+ });
+});
diff --git a/test/multisigwallet/utils.js b/test/multisigwallet/utils.js
new file mode 100644
index 0000000..4d4de4f
--- /dev/null
+++ b/test/multisigwallet/utils.js
@@ -0,0 +1,112 @@
+// Copyright 2018 OST.com Ltd.
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+const MultiSigWallet = artifacts.require('MultiSigWallet');
+
+class MultiSigWalletUtils {
+ constructor({ accountProvider, walletCount, required }) {
+ return (
+ async () => {
+ assert(walletCount > 0);
+ assert(required > 0);
+
+ this._accountProvider = accountProvider;
+ this._required = required;
+ this._walletCount = walletCount;
+
+ this._wallets = [];
+
+ for (let i = 0; i < walletCount; i += 1) {
+ this._wallets.push(this._accountProvider.get());
+ }
+
+ this._multisig = await MultiSigWallet.new(this._wallets, this._required);
+
+ return this;
+ })();
+ }
+
+ multisig() {
+ return this._multisig;
+ }
+
+ wallet(index) {
+ assert(index < this._wallets.length);
+ assert(index >= 0);
+
+ return this._wallets[index];
+ }
+
+ async submitAddWallet(walletToAdd, fromWalletIndex) {
+ const transactionID = await this._multisig.submitAddWallet.call(
+ walletToAdd,
+ { from: this.wallet(fromWalletIndex) },
+ );
+
+ await this._multisig.submitAddWallet(
+ walletToAdd,
+ { from: this.wallet(fromWalletIndex) },
+ );
+
+ return transactionID;
+ }
+
+ async submitRemoveWallet(walletToRemoveIndex, fromWalletIndex) {
+ const transactionID = await this._multisig.submitRemoveWallet.call(
+ this.wallet(walletToRemoveIndex),
+ { from: this.wallet(fromWalletIndex) },
+ );
+
+ await this._multisig.submitRemoveWallet(
+ this.wallet(walletToRemoveIndex),
+ { from: this.wallet(fromWalletIndex) },
+ );
+
+ return transactionID;
+ }
+
+ async submitReplaceWallet(oldWalletIndex, newWallet, fromWalletIndex) {
+ const transactionID = await this._multisig.submitReplaceWallet.call(
+ this.wallet(oldWalletIndex),
+ newWallet,
+ { from: this.wallet(fromWalletIndex) },
+ );
+
+ await this._multisig.submitReplaceWallet(
+ this.wallet(oldWalletIndex),
+ newWallet,
+ { from: this.wallet(fromWalletIndex) },
+ );
+
+ return transactionID;
+ }
+
+ async submitRequirementChange(newRequired, fromWalletIndex) {
+ const transactionID = await this._multisig.submitRequirementChange.call(
+ newRequired,
+ { from: this.wallet(fromWalletIndex) },
+ );
+
+ await this._multisig.submitRequirementChange(
+ newRequired,
+ { from: this.wallet(fromWalletIndex) },
+ );
+
+ return transactionID;
+ }
+}
+
+module.exports = {
+ MultiSigWalletUtils,
+};
diff --git a/test/test_lib/RevertProxy.sol b/test/test_lib/RevertProxy.sol
new file mode 100644
index 0000000..ec7fbda
--- /dev/null
+++ b/test/test_lib/RevertProxy.sol
@@ -0,0 +1,118 @@
+pragma solidity ^0.4.23;
+
+// Copyright 2018 OpenST Ltd.
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+import "truffle/Assert.sol";
+import "truffle/DeployedAddresses.sol";
+
+/**
+ * @title A proxy contract to catch and test for reverts in other contracts.
+ *
+ * @notice Use this contract as a proxy between the test contract and the
+ * contract under test. It will catch reverts and return false if it
+ * caught one.
+ *
+ * @dev An important caveat here is to recognize the contract caller,
+ * msg.sender. If you add a proxy in between, then msg.sender will be the
+ * proxy, which could break authorization and permissioning algorithms. If
+ * your authorization system allows you to change the owner, you can get
+ * around this constraint by setting the proxy to be the contract owner.
+ * It’s also important to know that this only tests throw's at this
+ * particular level.
+ * It would be prudent to also ensure there isn’t anything faulty in the
+ * proxy by creating a second test as a control. This test should be
+ * called with the appropriate gas and use the proxy to test a function
+ * where _no_ throw occurs, just to make sure the proxy is setup and
+ * working as intended.
+ * Because a throw essentially uses up all gas, one must make doubly sure
+ * they catch the throw and not a legitimate out-of-gas (OOG) error. As
+ * well, take care to manage sending Ether through the proxy (for tests
+ * that require it) as that can be difficult as well.
+ *
+ * See also test/core/TestAuxiliaryStake.sol
+ *
+ * Usage:
+ * contract TestThrower {
+ * function testThrow() {
+ * Thrower thrower = new Thrower();
+ * // Set Thrower as the contract to forward requests to the target.
+ * RevertProxy revertProxy = new RevertProxy(address(thrower));
+ *
+ * // Prime the proxy.
+ * Thrower(address(revertProxy)).doThrow();
+ * // Execute the call that is supposed to revert.
+ * // r will be false if it reverted. r will be true if it didn't.
+ * // Make sure you send enough gas for your contract method.
+ * bool r = revertProxy.execute.gas(200000)();
+ *
+ * Assert.isFalse(r, “Should be false, as it should revert");
+ * }
+ * }
+ *
+ * Inspired by:
+ * https://truffleframework.com/tutorials/testing-for-throws-in-solidity-tests.
+ */
+contract RevertProxy {
+
+ /* Public Variables */
+
+ /** target is the address of the contract under test. */
+ address public target;
+
+ /** data stores the call data that will be sent to the method under test. */
+ bytes public data;
+
+ /* Constructor */
+
+ /**
+ * @param _target The address where the executed calls will be sent to.
+ */
+ constructor (address _target) public {
+ target = _target;
+ }
+
+ /* Public Functions */
+
+ /**
+ * @notice Updates the target of the proxy so that all subsequent execute
+ * calls will be made to the new target.
+ *
+ * @param _newTarget The address of the contract where to send all execute
+ * calls to.
+ */
+ function updateTarget(address _newTarget) public {
+ target = _newTarget;
+ }
+
+ /**
+ * @notice The fallback function stores the call data so that a call to the
+ * execute function will use the correct call data.
+ */
+ function() external payable {
+ data = msg.data;
+ }
+
+ /**
+ * @notice This will make the call to the target with the call data primed
+ * in the fallback function.
+ *
+ * @return `true` if the call was successful and did not revert, `false` if
+ * it reverted.
+ */
+ function execute() external returns (bool) {
+ // solium-disable-next-line security/no-low-level-calls
+ return target.call(data);
+ }
+}
diff --git a/test/test_lib/event_decoder.js b/test/test_lib/event_decoder.js
new file mode 100644
index 0000000..bfc7857
--- /dev/null
+++ b/test/test_lib/event_decoder.js
@@ -0,0 +1,75 @@
+// Copyright 2018 OpenST Ltd.
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+const web3 = require('../test_lib/web3.js');
+
+class Event {
+ static decodeTransactionResponse(transactionResponse) {
+ const events = [];
+
+ assert.isOk(Object.prototype.hasOwnProperty.call(
+ transactionResponse, 'logs',
+ ));
+
+ const { logs } = transactionResponse;
+
+ for (let i = 0; i < logs.length; i += 1) {
+ events.push({
+ name: logs[i].event,
+ args: logs[i].args,
+ });
+ }
+
+ return events;
+ }
+
+ static assertEqual(actual, expected) {
+ assert.strictEqual(actual.name, expected.name);
+ Object.keys(expected.args).forEach((key) => {
+ if (key !== '0' && key !== '1' && key !== '__length__') {
+ assert.isOk(Object.hasOwnProperty.call(actual.args, key));
+ if (web3.utils.isBN(expected.args[key])) {
+ assert.isOk(web3.utils.isBN(actual.args[key]));
+ assert.isOk(expected.args[key].eq(actual.args[key]));
+ } else {
+ assert.strictEqual(actual.args[key], expected.args[key]);
+ }
+ }
+ });
+
+ Object.keys(actual.args).forEach((key) => {
+ if (Number.isNaN(Number.parseInt(key, 10)) && key !== '__length__') {
+ assert.isOk(Object.hasOwnProperty.call(expected.args, key));
+ }
+ });
+ }
+
+ static assertEqualMulti(actualList, expectedList) {
+ assert.strictEqual(
+ actualList.length,
+ expectedList.length,
+ 'Length of actual event list and expected ones should be equal.',
+ );
+
+ for (let i = 0; i < actualList.lengh; i += 1) {
+ const actual = actualList[i];
+ const expected = expectedList[i];
+ this.assertEqual(actual, expected);
+ }
+ }
+}
+
+module.exports = {
+ Event,
+};
diff --git a/test/test_lib/utils.js b/test/test_lib/utils.js
new file mode 100644
index 0000000..d97d3ea
--- /dev/null
+++ b/test/test_lib/utils.js
@@ -0,0 +1,95 @@
+// Copyright 2018 OST.com Ltd.
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+const assert = require('assert');
+const web3 = require('./web3.js');
+
+const NULL_ADDRESS = '0x0000000000000000000000000000000000000000';
+
+module.exports.NULL_ADDRESS = NULL_ADDRESS;
+
+module.exports.isNullAddress = address => address === NULL_ADDRESS;
+
+/**
+ * Asserts that a call or transaction reverts.
+ *
+ * @param {promise} promise The call or transaction.
+ * @param {string} expectedMessage Optional. If given, the revert message will
+ * be checked to contain this string.
+ *
+ * @throws Will fail an assertion if the call or transaction is not reverted.
+ */
+module.exports.expectRevert = async (
+ promise, displayMessage, expectedRevertMessage,
+) => {
+ try {
+ await promise;
+ } catch (error) {
+ assert(
+ error.message.search('revert') > -1,
+ `The contract should revert. Instead: ${error.message}`,
+ );
+
+ if (expectedRevertMessage !== undefined) {
+ if (error.reason !== undefined) {
+ assert(
+ expectedRevertMessage === error.reason,
+ `\nThe contract should revert with:\n\t"${expectedRevertMessage}" `
+ + `\ninstead received:\n\t"${error.reason}"\n`,
+ );
+ } else {
+ assert(
+ error.message.search(expectedRevertMessage) > -1,
+ `\nThe contract should revert with:\n\t"${expectedRevertMessage}" `
+ + `\ninstead received:\n\t"${error.message}"\n`,
+ );
+ }
+ }
+
+ return;
+ }
+
+ assert(false, displayMessage);
+};
+
+module.exports.advanceBlock = () => new Promise((resolve, reject) => {
+ web3.currentProvider.send({
+ jsonrpc: '2.0',
+ method: 'evm_mine',
+ id: new Date().getTime(),
+ }, (err) => {
+ if (err) {
+ return reject(err);
+ }
+
+ const newBlockHash = web3.eth.getBlock('latest').hash;
+
+ return resolve(newBlockHash);
+ });
+});
+
+/** Receives accounts list and gives away each time one. */
+module.exports.AccountProvider = class AccountProvider {
+ constructor(accounts) {
+ this.accounts = accounts;
+ this.index = 0;
+ }
+
+ get() {
+ assert(this.index < this.accounts.length);
+ const account = this.accounts[this.index];
+ this.index += 1;
+ return account;
+ }
+};
diff --git a/test/test_lib/web3.js b/test/test_lib/web3.js
new file mode 100644
index 0000000..80be2e2
--- /dev/null
+++ b/test/test_lib/web3.js
@@ -0,0 +1,22 @@
+// Copyright 2018 OpenST Ltd.
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+
+const Web3 = require('web3');
+
+const web3 = new Web3(
+ new Web3.providers.WebsocketProvider('ws://localhost:8545'),
+);
+
+module.exports = web3;
diff --git a/test/token_holder/constructor.js b/test/token_holder/constructor.js
new file mode 100644
index 0000000..7099423
--- /dev/null
+++ b/test/token_holder/constructor.js
@@ -0,0 +1,98 @@
+// Copyright 2018 OpenST Ltd.
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+
+const utils = require('../test_lib/utils.js');
+const { AccountProvider } = require('../test_lib/utils.js');
+
+const TokenHolder = artifacts.require('TokenHolder');
+
+contract('TokenHolder::constructor', async () => {
+ contract('Negative Tests', async (accounts) => {
+ const accountProvider = new AccountProvider(accounts);
+
+ it('Reverts if token address is null.', async () => {
+ const required = 1;
+ const registeredWallet0 = accountProvider.get();
+
+ const wallets = [registeredWallet0];
+
+ const tokenAddress = utils.NULL_ADDRESS;
+ const tokenRulesAddress = accountProvider.get();
+
+ await utils.expectRevert(
+ TokenHolder.new(
+ tokenAddress,
+ tokenRulesAddress,
+ wallets,
+ required,
+ ),
+ 'Should revert as token address is null.',
+ 'Token contract address is null.',
+ );
+ });
+
+ it('Reverts if token rules is null.', async () => {
+ const required = 1;
+ const registeredWallet0 = accountProvider.get();
+
+ const wallets = [registeredWallet0];
+
+ const tokenAddress = accountProvider.get();
+ const tokenRulesAddress = utils.NULL_ADDRESS;
+
+ await utils.expectRevert(
+ TokenHolder.new(
+ tokenAddress,
+ tokenRulesAddress,
+ wallets,
+ required,
+ ),
+ 'Should revert as token rules address is null.',
+ 'TokenRules contract address is null.',
+ );
+ });
+ });
+
+ contract('Storage', async (accounts) => {
+ const accountProvider = new AccountProvider(accounts);
+
+ it('Checks that passed arguments are set correctly.', async () => {
+ const required = 1;
+ const registeredWallet0 = accountProvider.get();
+
+ const wallets = [registeredWallet0];
+
+ const tokenAddress = accountProvider.get();
+ const tokenRulesAddress = accountProvider.get();
+
+ const tokenHolder = await TokenHolder.new(
+ tokenAddress,
+ tokenRulesAddress,
+ wallets,
+ required,
+ );
+
+ assert.strictEqual(
+ (await tokenHolder.token.call()),
+ tokenAddress,
+ );
+
+ assert.strictEqual(
+ (await tokenHolder.tokenRules.call()),
+ tokenRulesAddress,
+ );
+ });
+ });
+});
diff --git a/test/token_holder/execute_rule.js b/test/token_holder/execute_rule.js
new file mode 100644
index 0000000..a75b81f
--- /dev/null
+++ b/test/token_holder/execute_rule.js
@@ -0,0 +1,757 @@
+// Copyright 2018 OpenST Ltd.
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+const BN = require('bn.js');
+const EthUtils = require('ethereumjs-util');
+const web3 = require('../test_lib/web3.js');
+const Utils = require('../test_lib/utils.js');
+const { Event } = require('../test_lib/event_decoder');
+const { AccountProvider } = require('../test_lib/utils.js');
+
+const TokenHolder = artifacts.require('TokenHolder');
+const MockRule = artifacts.require('MockRule');
+const TokenRulesMock = artifacts.require('TokenRulesMock');
+const EIP20TokenMock = artifacts.require('EIP20TokenMock');
+
+const ephemeralPrivateKey1 = '0xa8225c01ceeaf01d7bc7c1b1b929037bd4050967c5730c0b854263121b8399f3';
+const ephemeralKeyAddress1 = '0x62502C4DF73935D0D10054b0Fb8cC036534C6fb0';
+
+const ephemeralPrivateKey2 = '0x634011a05b2f48e2d19aba49a9dbc12766bf7dbd6111ed2abb2621c92e8cfad9';
+
+function generateMockRulePassActionData(value) {
+ return web3.eth.abi.encodeFunctionCall(
+ {
+ name: 'pass',
+ type: 'function',
+ inputs: [
+ {
+ type: 'address',
+ name: 'value',
+ },
+ ],
+ },
+ [value],
+ );
+}
+
+function generateMockRulePassPayableActionData(value) {
+ return web3.eth.abi.encodeFunctionCall(
+ {
+ name: 'passPayable',
+ type: 'function',
+ inputs: [
+ {
+ type: 'address',
+ name: 'value',
+ },
+ ],
+ },
+ [value],
+ );
+}
+
+function generateMockRuleFailActionData(value) {
+ return web3.eth.abi.encodeFunctionCall(
+ {
+ name: 'fail',
+ type: 'function',
+ inputs: [
+ {
+ type: 'address',
+ name: 'value',
+ },
+ ],
+ },
+ [value],
+ );
+}
+
+function generateExecuteRuleCallPrefix() {
+ return web3.eth.abi.encodeFunctionSignature({
+ name: 'executeRule',
+ type: 'function',
+ inputs: [
+ {
+ type: 'address', name: '',
+ },
+ {
+ type: 'bytes', name: '',
+ },
+ {
+ type: 'uint256', name: '',
+ },
+ {
+ type: 'uint8', name: '',
+ },
+ {
+ type: 'bytes32', name: '',
+ },
+ {
+ type: 'bytes32', name: '',
+ },
+ ],
+ });
+}
+
+function getExecuteRuleExTxHash(
+ tokenHolderAddress, ruleAddress, ruleData, nonce,
+) {
+ return web3.utils.soliditySha3(
+ {
+ t: 'bytes1', v: '0x19',
+ },
+ {
+ t: 'bytes1', v: '0x0',
+ },
+ {
+ t: 'address', v: tokenHolderAddress,
+ },
+ {
+ t: 'address', v: ruleAddress,
+ },
+ {
+ t: 'uint8', v: 0,
+ },
+ {
+ t: 'bytes32', v: web3.utils.keccak256(ruleData),
+ },
+ {
+ t: 'uint256', v: nonce,
+ },
+ {
+ t: 'uint8', v: 0,
+ },
+ {
+ t: 'uint8', v: 0,
+ },
+ {
+ t: 'uint8', v: 0,
+ },
+ {
+ t: 'bytes4', v: generateExecuteRuleCallPrefix(),
+ },
+ {
+ t: 'uint8', v: 0,
+ },
+ {
+ t: 'bytes32', v: '0x0',
+ },
+ );
+}
+
+function getExecuteRuleExTxData(
+ _tokenHolderAddress, _ruleAddress, _ruleData, _nonce, _ephemeralKey,
+) {
+ const msgHash = getExecuteRuleExTxHash(
+ _tokenHolderAddress, _ruleAddress, _ruleData, _nonce,
+ );
+
+ const rsv = EthUtils.ecsign(
+ EthUtils.toBuffer(msgHash),
+ EthUtils.toBuffer(_ephemeralKey),
+ );
+
+ return { msgHash, rsv };
+}
+
+async function createTokenHolder(
+ accountProvider, _ephemeralKeyAddress, _spendingLimit, _deltaExpirationHeight,
+) {
+ const token = await EIP20TokenMock.new(1, 1, 'OST', 'Open Simple Token', 1);
+ const tokenRules = await TokenRulesMock.new();
+ const required = 1;
+ const registeredWallet0 = accountProvider.get();
+ const wallets = [registeredWallet0];
+
+ const tokenHolder = await TokenHolder.new(
+ token.address,
+ tokenRules.address,
+ wallets,
+ required,
+ );
+
+ const blockNumber = await web3.eth.getBlockNumber();
+
+ await tokenHolder.submitAuthorizeSession(
+ _ephemeralKeyAddress,
+ _spendingLimit,
+ blockNumber + _deltaExpirationHeight,
+ { from: registeredWallet0 },
+ );
+
+ return {
+ tokenHolder,
+ registeredWallet0,
+ };
+}
+
+async function preparePassRule(
+ accountProvider, tokenHolder, nonce, ephemeralKey,
+) {
+ const mockRule = await MockRule.new();
+ const mockRuleValue = accountProvider.get();
+ const mockRulePassActionData = generateMockRulePassActionData(
+ mockRuleValue,
+ );
+
+ const { msgHash, rsv } = getExecuteRuleExTxData(
+ tokenHolder.address,
+ mockRule.address,
+ mockRulePassActionData,
+ nonce,
+ ephemeralKey,
+ );
+
+ return {
+ mockRule,
+ mockRuleValue,
+ mockRulePassActionData,
+ msgHash,
+ rsv,
+ };
+}
+
+async function preparePassPayableRule(
+ accountProvider, tokenHolder, nonce, ephemeralKey,
+) {
+ const mockRule = await MockRule.new();
+ const mockRuleValue = accountProvider.get();
+ const mockRulePassActionData = generateMockRulePassPayableActionData(
+ mockRuleValue,
+ );
+
+ const { msgHash, rsv } = getExecuteRuleExTxData(
+ tokenHolder.address,
+ mockRule.address,
+ mockRulePassActionData,
+ nonce,
+ ephemeralKey,
+ );
+
+ return {
+ mockRule,
+ mockRuleValue,
+ mockRulePassActionData,
+ msgHash,
+ rsv,
+ };
+}
+
+async function prepareFailRule(
+ accountProvider, tokenHolder, nonce, ephemeralKey,
+) {
+ const mockRule = await MockRule.new();
+ const mockRuleValue = accountProvider.get();
+ const mockRuleFailActionData = generateMockRuleFailActionData(
+ mockRuleValue,
+ );
+
+ const { msgHash, rsv } = getExecuteRuleExTxData(
+ tokenHolder.address,
+ mockRule.address,
+ mockRuleFailActionData,
+ nonce,
+ ephemeralKey,
+ );
+
+ return {
+ mockRule,
+ mockRuleValue,
+ mockRuleFailActionData,
+ msgHash,
+ rsv,
+ };
+}
+
+contract('TokenHolder::executeRule', async () => {
+ contract('Negative Tests', async (accounts) => {
+ const accountProvider = new AccountProvider(accounts);
+
+ it('Reverts if ExTx is signed with non-authorized key.', async () => {
+ const spendingLimit = 10;
+ const deltaExpirationHeight = 50;
+
+ const { tokenHolder } = await createTokenHolder(
+ accountProvider,
+ ephemeralKeyAddress1,
+ spendingLimit,
+ deltaExpirationHeight,
+ );
+
+ const nonce = 1;
+ const {
+ mockRule,
+ mockRulePassActionData,
+ rsv,
+ } = await preparePassRule(
+ accountProvider,
+ tokenHolder,
+ nonce,
+ ephemeralPrivateKey2,
+ );
+
+ await Utils.expectRevert(
+ tokenHolder.executeRule(
+ mockRule.address,
+ mockRulePassActionData,
+ nonce,
+ rsv.v,
+ EthUtils.bufferToHex(rsv.r),
+ EthUtils.bufferToHex(rsv.s),
+ ),
+ 'Should revert as ExTx is signed with non-authorized key.',
+ 'Ephemeral key is not active.',
+ );
+ });
+
+ it('Reverts if ExTx is signed with authorized but expired key.', async () => {
+ const spendingLimit = 10;
+ const deltaExpirationHeight = 10;
+ const { tokenHolder } = await createTokenHolder(
+ accountProvider,
+ ephemeralKeyAddress1,
+ spendingLimit,
+ deltaExpirationHeight,
+ );
+
+ const nonce = 1;
+ const {
+ mockRule,
+ mockRulePassActionData,
+ rsv,
+ } = await preparePassRule(
+ accountProvider,
+ tokenHolder,
+ nonce,
+ ephemeralPrivateKey2,
+ );
+
+ for (let i = 0; i < deltaExpirationHeight; i += 1) {
+ // eslint-disable-next-line no-await-in-loop
+ await Utils.advanceBlock();
+ }
+
+ await Utils.expectRevert(
+ tokenHolder.executeRule(
+ mockRule.address,
+ mockRulePassActionData,
+ nonce,
+ rsv.v,
+ EthUtils.bufferToHex(rsv.r),
+ EthUtils.bufferToHex(rsv.s),
+ ),
+ 'Should revert as transaction is signed with expired key.',
+ 'Ephemeral key is not active.',
+ );
+ });
+
+ it('Reverts if transaction signed with revoked key.', async () => {
+ const spendingLimit = 10;
+ const deltaExpirationHeight = 50;
+ const {
+ tokenHolder,
+ registeredWallet0,
+ } = await createTokenHolder(
+ accountProvider,
+ ephemeralKeyAddress1,
+ spendingLimit,
+ deltaExpirationHeight,
+ );
+
+ await tokenHolder.revokeSession(
+ ephemeralKeyAddress1,
+ { from: registeredWallet0 },
+ );
+
+ const keyData = await tokenHolder.ephemeralKeys(
+ ephemeralKeyAddress1,
+ );
+
+ assert.isOk(
+ // AuthorizationStatus.REVOKED == 2
+ keyData.status.eqn(2),
+ 'Because of 1-wallet-1-required setup key should be revoked.',
+ );
+
+ const nonce = 1;
+ const {
+ mockRule,
+ mockRulePassActionData,
+ rsv,
+ } = await preparePassRule(
+ accountProvider,
+ tokenHolder,
+ nonce,
+ ephemeralPrivateKey1,
+ );
+
+ await Utils.expectRevert(
+ tokenHolder.executeRule(
+ mockRule.address,
+ mockRulePassActionData,
+ nonce,
+ rsv.v,
+ EthUtils.bufferToHex(rsv.r),
+ EthUtils.bufferToHex(rsv.s),
+ ),
+ 'Should revert as transaction is signed with revoked key.',
+ 'Ephemeral key is not active.',
+ );
+ });
+
+ it('Reverts if ExTx is signed with a wrong nonce.', async () => {
+ const spendingLimit = 10;
+ const deltaExpirationHeight = 50;
+ const { tokenHolder } = await createTokenHolder(
+ accountProvider,
+ ephemeralKeyAddress1,
+ spendingLimit,
+ deltaExpirationHeight,
+ );
+
+ // Correct nonce is 1.
+ const invalidNonce0 = 0;
+ const {
+ mockRule: mockRule0,
+ mockRulePassActionData: mockRulePassActionData0,
+ rsv: rsv0,
+ } = await preparePassRule(
+ accountProvider,
+ tokenHolder,
+ invalidNonce0,
+ ephemeralPrivateKey1,
+ );
+
+ await Utils.expectRevert(
+ tokenHolder.executeRule(
+ mockRule0.address,
+ mockRulePassActionData0,
+ invalidNonce0,
+ rsv0.v,
+ EthUtils.bufferToHex(rsv0.r),
+ EthUtils.bufferToHex(rsv0.s),
+ ),
+ 'Should revert as ExTx is signed with a wrong nonce.',
+ 'The next nonce is not provided.',
+ );
+
+ // correct nonce is 1.
+ const invalidNonce2 = 2;
+ const {
+ mockRule: mockRule2,
+ mockRulePassActionData: mockRulePassActionData2,
+ rsv: rsv2,
+ } = await preparePassRule(
+ accountProvider,
+ tokenHolder,
+ invalidNonce2,
+ ephemeralPrivateKey1,
+ );
+
+ await Utils.expectRevert(
+ tokenHolder.executeRule(
+ mockRule2.address,
+ mockRulePassActionData2,
+ invalidNonce2,
+ rsv2.v,
+ EthUtils.bufferToHex(rsv2.r),
+ EthUtils.bufferToHex(rsv2.s),
+ ),
+ 'Should revert as ExTx is signed with a wrong nonce.',
+ 'The next nonce is not provided.',
+ );
+ });
+ });
+
+ contract('Events', async (accounts) => {
+ const accountProvider = new AccountProvider(accounts);
+
+ it('Emits RuleExecuted event with successful execution status.', async () => {
+ const spendingLimit = 10;
+ const deltaExpirationHeight = 50;
+ const { tokenHolder } = await createTokenHolder(
+ accountProvider,
+ ephemeralKeyAddress1,
+ spendingLimit,
+ deltaExpirationHeight,
+ );
+
+ const nonce = 1;
+ const {
+ mockRule,
+ mockRulePassActionData,
+ msgHash,
+ rsv,
+ } = await preparePassRule(
+ accountProvider,
+ tokenHolder,
+ nonce,
+ ephemeralPrivateKey1,
+ );
+
+ const transactionResponse = await tokenHolder.executeRule(
+ mockRule.address,
+ mockRulePassActionData,
+ nonce,
+ rsv.v,
+ EthUtils.bufferToHex(rsv.r),
+ EthUtils.bufferToHex(rsv.s),
+ );
+
+ const events = Event.decodeTransactionResponse(
+ transactionResponse,
+ );
+
+ assert.strictEqual(
+ events.length,
+ 1,
+ );
+
+ const passCallPrefix = await mockRule.PASS_CALLPREFIX.call();
+ Event.assertEqual(events[0], {
+ name: 'RuleExecuted',
+ args: {
+ _to: mockRule.address,
+ _functionSelector: passCallPrefix,
+ _ephemeralKey: ephemeralKeyAddress1,
+ _nonce: new BN(nonce),
+ _messageHash: msgHash,
+ _status: true,
+ },
+ });
+ });
+
+ it('Emits RuleExecuted event with failed execution status.', async () => {
+ const spendingLimit = 10;
+ const deltaExpirationHeight = 50;
+ const { tokenHolder } = await createTokenHolder(
+ accountProvider,
+ ephemeralKeyAddress1,
+ spendingLimit,
+ deltaExpirationHeight,
+ );
+
+ const nonce = 1;
+ const {
+ mockRule,
+ mockRuleFailActionData,
+ msgHash,
+ rsv,
+ } = await prepareFailRule(
+ accountProvider,
+ tokenHolder,
+ nonce,
+ ephemeralPrivateKey1,
+ );
+
+ const transactionResponse = await tokenHolder.executeRule(
+ mockRule.address,
+ mockRuleFailActionData,
+ nonce,
+ rsv.v,
+ EthUtils.bufferToHex(rsv.r),
+ EthUtils.bufferToHex(rsv.s),
+ );
+
+ const events = Event.decodeTransactionResponse(
+ transactionResponse,
+ );
+
+ assert.strictEqual(
+ events.length,
+ 1,
+ );
+
+ Event.assertEqual(events[0], {
+ name: 'RuleExecuted',
+ args: {
+ _to: mockRule.address,
+ _functionSelector: await mockRule.FAIL_CALLPREFIX.call(),
+ _ephemeralKey: ephemeralKeyAddress1,
+ _nonce: new BN(nonce),
+ _messageHash: msgHash,
+ // We should check against false here, however
+ // current version of web3 returns null for false values
+ // in event log. After updating web3, this test might
+ // fail and we should use false (as intended).
+ _status: null,
+ },
+ });
+ });
+ });
+
+ contract('Rule Executed', async (accounts) => {
+ const accountProvider = new AccountProvider(accounts);
+
+ it('Checks that rule is actually executed.', async () => {
+ const spendingLimit = 10;
+ const deltaExpirationHeight = 50;
+ const { tokenHolder } = await createTokenHolder(
+ accountProvider,
+ ephemeralKeyAddress1,
+ spendingLimit,
+ deltaExpirationHeight,
+ );
+
+ const nonce = 1;
+ const {
+ mockRule,
+ mockRuleValue,
+ mockRulePassActionData,
+ rsv,
+ } = await preparePassRule(
+ accountProvider,
+ tokenHolder,
+ nonce,
+ ephemeralPrivateKey1,
+ );
+
+ await tokenHolder.executeRule(
+ mockRule.address,
+ mockRulePassActionData,
+ nonce,
+ rsv.v,
+ EthUtils.bufferToHex(rsv.r),
+ EthUtils.bufferToHex(rsv.s),
+ );
+
+ assert.strictEqual(
+ (await mockRule.value.call()),
+ mockRuleValue,
+ );
+ });
+
+ it('Checks that payable rule is actually executed.', async () => {
+ const spendingLimit = 10;
+ const deltaExpirationHeight = 50;
+ const { tokenHolder } = await createTokenHolder(
+ accountProvider,
+ ephemeralKeyAddress1,
+ spendingLimit,
+ deltaExpirationHeight,
+ );
+
+ const nonce = 1;
+ const {
+ mockRule,
+ mockRuleValue,
+ mockRulePassActionData,
+ rsv,
+ } = await preparePassPayableRule(
+ accountProvider,
+ tokenHolder,
+ nonce,
+ ephemeralPrivateKey1,
+ );
+
+ const payableValue = 111;
+ await tokenHolder.executeRule(
+ mockRule.address,
+ mockRulePassActionData,
+ nonce,
+ rsv.v,
+ EthUtils.bufferToHex(rsv.r),
+ EthUtils.bufferToHex(rsv.s),
+ {
+ value: payableValue,
+ },
+ );
+
+ assert.strictEqual(
+ (await mockRule.value.call()),
+ mockRuleValue,
+ );
+
+ assert.isOk(
+ (await mockRule.receivedPayableAmount.call()).eqn(payableValue),
+ );
+ });
+ });
+
+ contract('Returned Execution Status', async (accounts) => {
+ const accountProvider = new AccountProvider(accounts);
+
+ it('Checks that return value is true in case of successfull execution.', async () => {
+ const spendingLimit = 10;
+ const deltaExpirationHeight = 50;
+ const { tokenHolder } = await createTokenHolder(
+ accountProvider,
+ ephemeralKeyAddress1,
+ spendingLimit,
+ deltaExpirationHeight,
+ );
+
+ const nonce = 1;
+ const {
+ mockRule,
+ mockRulePassActionData,
+ rsv,
+ } = await preparePassRule(
+ accountProvider,
+ tokenHolder,
+ nonce,
+ ephemeralPrivateKey1,
+ );
+
+ const executionStatus = await tokenHolder.executeRule.call(
+ mockRule.address,
+ mockRulePassActionData,
+ nonce,
+ rsv.v,
+ EthUtils.bufferToHex(rsv.r),
+ EthUtils.bufferToHex(rsv.s),
+ );
+
+ assert.isOk(
+ executionStatus,
+ );
+ });
+
+ it('Checks that return value is true in case of failing execution.', async () => {
+ const spendingLimit = 10;
+ const deltaExpirationHeight = 50;
+ const { tokenHolder } = await createTokenHolder(
+ accountProvider,
+ ephemeralKeyAddress1,
+ spendingLimit,
+ deltaExpirationHeight,
+ );
+
+ const nonce = 1;
+ const {
+ mockRule,
+ mockRuleFailActionData,
+ rsv,
+ } = await prepareFailRule(
+ accountProvider,
+ tokenHolder,
+ nonce,
+ ephemeralPrivateKey1,
+ );
+
+ const executionStatus = await tokenHolder.executeRule.call(
+ mockRule.address,
+ mockRuleFailActionData,
+ nonce,
+ rsv.v,
+ EthUtils.bufferToHex(rsv.r),
+ EthUtils.bufferToHex(rsv.s),
+ );
+
+ assert.isNotOk(
+ executionStatus,
+ );
+ });
+ });
+});
diff --git a/test/token_holder/revoke_session.js b/test/token_holder/revoke_session.js
new file mode 100644
index 0000000..71b8d24
--- /dev/null
+++ b/test/token_holder/revoke_session.js
@@ -0,0 +1,201 @@
+// Copyright 2018 OpenST Ltd.
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+const web3 = require('../test_lib/web3.js');
+const utils = require('../test_lib/utils.js');
+const { Event } = require('../test_lib/event_decoder');
+const { AccountProvider } = require('../test_lib/utils.js');
+
+const TokenHolder = artifacts.require('TokenHolder');
+
+async function createTokenHolder(
+ accountProvider,
+) {
+ const required = 1;
+
+ const registeredWallet0 = accountProvider.get();
+
+ const wallets = [registeredWallet0];
+
+ const tokenAddress = accountProvider.get();
+ const tokenRulesAddress = accountProvider.get();
+
+ const tokenHolder = await TokenHolder.new(
+ tokenAddress, tokenRulesAddress, wallets, required,
+ );
+
+ return {
+ tokenHolder,
+ registeredWallet0,
+ };
+}
+
+async function prepareTokenHolder(
+ accountProvider, ephemeralKey,
+) {
+ const {
+ tokenHolder,
+ registeredWallet0,
+ } = await createTokenHolder(accountProvider);
+
+ const spendingLimit = 1;
+ const expirationHeight = (await web3.eth.getBlockNumber()) + 10;
+
+ await tokenHolder.submitAuthorizeSession(
+ ephemeralKey,
+ spendingLimit,
+ expirationHeight,
+ {
+ from: registeredWallet0,
+ },
+ );
+
+ return {
+ tokenHolder,
+ registeredWallet0,
+ };
+}
+
+contract('TokenHolder::revokeSession', async () => {
+ contract('Negative Tests', async (accounts) => {
+ const accountProvider = new AccountProvider(accounts);
+
+ it('Reverts if non-registered wallet calls.', async () => {
+ const ephemeralKey = '0x62502C4DF73935D0D10054b0Fb8cC036534C6fb0';
+
+ const {
+ tokenHolder,
+ } = await prepareTokenHolder(accountProvider, ephemeralKey);
+
+ await utils.expectRevert(
+ tokenHolder.revokeSession(
+ ephemeralKey,
+ {
+ from: accountProvider.get(),
+ },
+ ),
+ 'Should revert as non-registered wallet calls.',
+ 'Only wallet is allowed to call.',
+ );
+ });
+
+ it('Reverts if key to revoke does not exist.', async () => {
+ const {
+ tokenHolder,
+ registeredWallet0,
+ } = await createTokenHolder(accountProvider);
+
+ const ephemeralKey = '0x62502C4DF73935D0D10054b0Fb8cC036534C6fb0';
+
+ await utils.expectRevert(
+ tokenHolder.revokeSession(
+ ephemeralKey,
+ { from: registeredWallet0 },
+ ),
+ 'Should revert as key to revoke does not exist.',
+ 'Key is not authorized.',
+ );
+ });
+
+ it('Reverts if key to revoke is already revoked.', async () => {
+ const ephemeralKey = '0x62502C4DF73935D0D10054b0Fb8cC036534C6fb0';
+
+ const {
+ tokenHolder,
+ registeredWallet0,
+ } = await prepareTokenHolder(accountProvider, ephemeralKey);
+
+ await tokenHolder.revokeSession(
+ ephemeralKey,
+ { from: registeredWallet0 },
+ );
+
+ await utils.expectRevert(
+ tokenHolder.revokeSession(
+ ephemeralKey,
+ { from: registeredWallet0 },
+ ),
+ 'Should revert as key to revoke was already revoked.',
+ 'Key is not authorized.',
+ );
+ });
+ });
+
+ contract('Events', async (accounts) => {
+ const accountProvider = new AccountProvider(accounts);
+
+ it('Emits SessionRevoked event.', async () => {
+ const ephemeralKey = '0x62502C4DF73935D0D10054b0Fb8cC036534C6fb0';
+
+ const {
+ tokenHolder,
+ registeredWallet0,
+ } = await prepareTokenHolder(accountProvider, ephemeralKey);
+
+ const transactionResponse = await tokenHolder.revokeSession(
+ ephemeralKey,
+ { from: registeredWallet0 },
+ );
+
+ const events = Event.decodeTransactionResponse(
+ transactionResponse,
+ );
+
+ assert.strictEqual(
+ events.length,
+ 1,
+ );
+
+ // The only emitted event should be 'SessionRevoked'.
+ Event.assertEqual(events[0], {
+ name: 'SessionRevoked',
+ args: {
+ _ephemeralKey: ephemeralKey,
+ },
+ });
+ });
+ });
+
+ contract('Storage', async (accounts) => {
+ const accountProvider = new AccountProvider(accounts);
+
+ it('Checks that key is revoked after successfull revocation.', async () => {
+ const ephemeralKey = '0x62502C4DF73935D0D10054b0Fb8cC036534C6fb0';
+
+ const {
+ tokenHolder,
+ registeredWallet0,
+ } = await prepareTokenHolder(accountProvider, ephemeralKey);
+
+ let keyData = await tokenHolder.ephemeralKeys.call(ephemeralKey);
+
+ assert.isOk(
+ // TokenHolder.AuthorizationStatus.AUTHORIZED == 1
+ keyData.status.eqn(1),
+ );
+
+ await tokenHolder.revokeSession(
+ ephemeralKey,
+ { from: registeredWallet0 },
+ );
+
+ keyData = await tokenHolder.ephemeralKeys.call(ephemeralKey);
+
+ assert.isOk(
+ // TokenHolder.AuthorizationStatus.REVOKED == 2
+ keyData.status.eqn(2),
+ );
+ });
+ });
+});
diff --git a/test/token_holder/submit_authorize_session.js b/test/token_holder/submit_authorize_session.js
new file mode 100644
index 0000000..851adb7
--- /dev/null
+++ b/test/token_holder/submit_authorize_session.js
@@ -0,0 +1,515 @@
+// Copyright 2018 OpenST Ltd.
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+const BN = require('bn.js');
+const web3 = require('../test_lib/web3.js');
+const Utils = require('../test_lib/utils.js');
+const { Event } = require('../test_lib/event_decoder');
+const { TokenHolderUtils } = require('./utils.js');
+const { AccountProvider } = require('../test_lib/utils.js');
+
+const TokenHolder = artifacts.require('TokenHolder');
+
+function generateSubmitAuthorizeSessionData(
+ ephemeralKey, spendingLimit, expirationHeight,
+) {
+ return web3.eth.abi.encodeFunctionCall(
+ {
+ name: 'authorizeSession',
+ type: 'function',
+ inputs: [
+ {
+ type: 'address',
+ name: '',
+ },
+ {
+ type: 'uint256',
+ name: '',
+ },
+ {
+ type: 'uint256',
+ name: '',
+ },
+ ],
+ },
+ [ephemeralKey, spendingLimit, expirationHeight],
+ );
+}
+
+async function createTokenHolder(
+ accountProvider,
+) {
+ const required = 1;
+
+ const registeredWallet0 = accountProvider.get();
+
+ const wallets = [registeredWallet0];
+
+ const tokenAddress = accountProvider.get();
+ const tokenRulesAddress = accountProvider.get();
+
+ const tokenHolder = await TokenHolder.new(
+ tokenAddress, tokenRulesAddress, wallets, required,
+ );
+
+ return {
+ tokenHolder,
+ registeredWallet0,
+ };
+}
+
+contract('TokenHolder::submitAuthorizeSession', async () => {
+ contract('Negative Tests', async (accounts) => {
+ const accountProvider = new AccountProvider(accounts);
+
+ it('Reverts if non-registered wallet calls.', async () => {
+ const {
+ tokenHolder,
+ } = await createTokenHolder(accountProvider);
+
+ const ephemeralKey = '0x62502C4DF73935D0D10054b0Fb8cC036534C6fb0';
+ const spendingLimit = 1;
+ const expirationHeight = (await web3.eth.getBlockNumber()) + 10;
+
+ await Utils.expectRevert(
+ tokenHolder.submitAuthorizeSession(
+ ephemeralKey,
+ spendingLimit,
+ expirationHeight,
+ { from: accountProvider.get() },
+ ),
+ 'Should revert as non-registered wallet calls.',
+ 'Only wallet is allowed to call.',
+ );
+ });
+
+ it('Reverts if key to authorize is null.', async () => {
+ const {
+ tokenHolder,
+ registeredWallet0,
+ } = await createTokenHolder(accountProvider);
+
+ const spendingLimit = 1;
+ const expirationHeight = (await web3.eth.getBlockNumber()) + 10;
+
+ await Utils.expectRevert(
+ tokenHolder.submitAuthorizeSession(
+ Utils.NULL_ADDRESS,
+ spendingLimit,
+ expirationHeight,
+ { from: registeredWallet0 },
+ ),
+ 'Should revert as key to authorize is null.',
+ 'Key address is null.',
+ );
+ });
+
+ it('Reverts if key to authorize already was authorized.', async () => {
+ const {
+ tokenHolder,
+ registeredWallet0,
+ } = await createTokenHolder(accountProvider);
+
+ const ephemeralKey = '0x62502C4DF73935D0D10054b0Fb8cC036534C6fb0';
+ const spendingLimit = 1;
+ const expirationHeight = (await web3.eth.getBlockNumber()) + 10;
+
+ await tokenHolder.submitAuthorizeSession(
+ ephemeralKey,
+ spendingLimit,
+ expirationHeight,
+ { from: registeredWallet0 },
+ );
+
+ await Utils.expectRevert(
+ tokenHolder.submitAuthorizeSession(
+ ephemeralKey,
+ spendingLimit,
+ expirationHeight,
+ { from: registeredWallet0 },
+ ),
+ 'Should revert as key to authorize was already authorized.',
+ 'Key exists.',
+ );
+ });
+
+ it('Reverts if key to authorize is in revoked state.', async () => {
+ const {
+ tokenHolder,
+ registeredWallet0,
+ } = await createTokenHolder(accountProvider);
+
+ const ephemeralKey = '0x62502C4DF73935D0D10054b0Fb8cC036534C6fb0';
+ const spendingLimit = 1;
+ const expirationHeight = (await web3.eth.getBlockNumber()) + 10;
+
+ await tokenHolder.submitAuthorizeSession(
+ ephemeralKey,
+ spendingLimit,
+ expirationHeight,
+ { from: registeredWallet0 },
+ );
+
+ await tokenHolder.revokeSession(
+ ephemeralKey,
+ { from: registeredWallet0 },
+ );
+
+ await Utils.expectRevert(
+ tokenHolder.submitAuthorizeSession(
+ ephemeralKey,
+ spendingLimit,
+ expirationHeight,
+ { from: registeredWallet0 },
+ ),
+ 'Should revert as key to authorize was revoked.',
+ 'Key exists.',
+ );
+ });
+
+ it('Reverts if key to authorize has expired.', async () => {
+ const {
+ tokenHolder,
+ registeredWallet0,
+ } = await createTokenHolder(accountProvider);
+
+ const ephemeralKey = '0x62502C4DF73935D0D10054b0Fb8cC036534C6fb0';
+ const spendingLimit = 1;
+ const expirationHeightDelta = 10;
+ const blockNumber = await web3.eth.getBlockNumber();
+ const expirationHeight = blockNumber + expirationHeightDelta;
+
+ await tokenHolder.submitAuthorizeSession(
+ ephemeralKey,
+ spendingLimit,
+ expirationHeight,
+ { from: registeredWallet0 },
+ );
+
+ for (let i = 0; i < expirationHeightDelta; i += 1) {
+ // eslint-disable-next-line no-await-in-loop
+ await Utils.advanceBlock();
+ }
+
+ // Checking that key has expired.
+ assert.isOk(
+ (await tokenHolder.ephemeralKeys.call(ephemeralKey))
+ .expirationHeight <= (await web3.eth.getBlockNumber()),
+ );
+
+ await Utils.expectRevert(
+ tokenHolder.submitAuthorizeSession(
+ ephemeralKey,
+ spendingLimit,
+ expirationHeight,
+ {
+ from: registeredWallet0,
+ },
+ ),
+ 'Should revert as key to submit has already expired.',
+ 'Key exists.',
+ );
+ });
+
+ it('Expiration height is less or equal to the block number', async () => {
+ const {
+ tokenHolder,
+ registeredWallet0,
+ } = await createTokenHolder(accountProvider);
+
+ const ephemeralKey = '0x62502C4DF73935D0D10054b0Fb8cC036534C6fb0';
+ const spendingLimit = 10;
+
+ await Utils.expectRevert(
+ tokenHolder.submitAuthorizeSession(
+ ephemeralKey,
+ spendingLimit,
+ (await web3.eth.getBlockNumber()),
+ { from: registeredWallet0 },
+ ),
+ 'Should revert as expiration heigh is less than equal to the '
+ + ' current block height',
+ 'Expiration height is lte to the current block height.',
+ );
+ });
+ });
+
+ contract('Events', async (accounts) => {
+ const accountProvider = new AccountProvider(accounts);
+
+ // Because of 1-wallet-1-required the submitted authorization
+ // request is going to be executed immediately, hence 3 events.
+ it('Emits SessionAuthorizationSubmitted, TransactionConfirmed '
+ + 'TransactionExecutionSucceeded events.', async () => {
+ const required = 1;
+
+ const registeredWallet0 = accountProvider.get();
+
+ const wallets = [registeredWallet0];
+
+ const token = accountProvider.get();
+ const tokenRules = accountProvider.get();
+
+ const tokenHolder = await TokenHolder.new(
+ token, tokenRules, wallets, required,
+ );
+
+ const ephemeralKey = '0x62502C4DF73935D0D10054b0Fb8cC036534C6fb0';
+ const spendingLimit = 1;
+ const expirationHeight = await web3.eth.getBlockNumber() + 50;
+
+ const transactionResponse = await tokenHolder.submitAuthorizeSession(
+ ephemeralKey,
+ spendingLimit,
+ expirationHeight,
+ { from: registeredWallet0 },
+ );
+
+ const events = Event.decodeTransactionResponse(
+ transactionResponse,
+ );
+
+ assert.strictEqual(
+ events.length,
+ 3,
+ 'As the requirement is 1, transaction would be executed '
+ + 'afterwards, hence SessionAuthorizationSubmitted, '
+ + 'TransactionConfirmed and TransactionExecutionSucceeded '
+ + 'would be emitted.',
+ );
+
+ // The first emitted event should be 'SessionAuthorizationSubmitted'.
+ Event.assertEqual(events[0], {
+ name: 'SessionAuthorizationSubmitted',
+ args: {
+ _transactionID: new BN(0),
+ _ephemeralKey: ephemeralKey,
+ _spendingLimit: new BN(spendingLimit),
+ _expirationHeight: new BN(expirationHeight),
+ },
+ });
+
+ // The second emitted event should be 'TransactionConfirmed',
+ // because the wallet that submitted a session authorization request
+ // should confirm it afterwards in the same call.
+ Event.assertEqual(events[1], {
+ name: 'TransactionConfirmed',
+ args: {
+ _transactionID: new BN(0),
+ _wallet: registeredWallet0,
+ },
+ });
+
+ // The third emitted event should be
+ // 'TransactionExecutionSucceeded', because of the setup
+ // 1-wallet-1-requirement.
+ Event.assertEqual(events[2], {
+ name: 'TransactionExecutionSucceeded',
+ args: {
+ _transactionID: new BN(0),
+ },
+ });
+ });
+
+ // Because of 2-wallet-2-required the submitted authorization
+ // request is *not* going to be executed immediately, hence 2 events.
+ it('Emits SessionAuthorizationSubmitted and TransactionConfirmed', async () => {
+ const required = 2;
+
+ const registeredWallet0 = accountProvider.get();
+ const registeredWallet1 = accountProvider.get();
+
+ const wallets = [registeredWallet0, registeredWallet1];
+
+ const token = accountProvider.get();
+ const tokenRules = accountProvider.get();
+
+ const tokenHolder = await TokenHolder.new(
+ token, tokenRules, wallets, required,
+ );
+
+ const ephemeralKey = '0x62502C4DF73935D0D10054b0Fb8cC036534C6fb0';
+ const spendingLimit = 1;
+ const expirationHeight = await web3.eth.getBlockNumber() + 50;
+
+ const transactionResponse = await tokenHolder.submitAuthorizeSession(
+ ephemeralKey,
+ spendingLimit,
+ expirationHeight,
+ { from: registeredWallet0 },
+ );
+
+ const events = Event.decodeTransactionResponse(
+ transactionResponse,
+ );
+
+ assert.strictEqual(
+ events.length,
+ 2,
+ 'As the requirement is 2, transaction would not be executed '
+ + 'afterwards, hence SessionAuthorizationSubmitted and '
+ + 'TransactionConfirmed would be emitted.',
+ );
+
+ // The first emitted event should be 'SessionAuthorizationSubmitted'.
+ Event.assertEqual(events[0], {
+ name: 'SessionAuthorizationSubmitted',
+ args: {
+ _transactionID: new BN(0),
+ _ephemeralKey: ephemeralKey,
+ _spendingLimit: new BN(spendingLimit),
+ _expirationHeight: new BN(expirationHeight),
+ },
+ });
+
+ // The second emitted event should be 'TransactionConfirmed',
+ // because the wallet that submitted a session authorization request
+ // should confirm it afterwards in the same call.
+ Event.assertEqual(events[1], {
+ name: 'TransactionConfirmed',
+ args: {
+ _transactionID: new BN(0),
+ _wallet: registeredWallet0,
+ },
+ });
+ });
+ });
+
+ contract('Storage', async (accounts) => {
+ const accountProvider = new AccountProvider(accounts);
+
+ it('Checks states in case of 1-wallet-1-required.', async () => {
+ const required = 1;
+
+ const registeredWallet0 = accountProvider.get();
+
+ const wallets = [registeredWallet0];
+
+ const token = accountProvider.get();
+ const tokenRules = accountProvider.get();
+
+ const tokenHolder = await TokenHolder.new(
+ token, tokenRules, wallets, required,
+ );
+
+ const ephemeralKey = '0x62502C4DF73935D0D10054b0Fb8cC036534C6fb0';
+ const spendingLimit = 1;
+ const expirationHeight = await web3.eth.getBlockNumber() + 50;
+
+ const transactionID = await TokenHolderUtils.submitAuthorizeSession(
+ tokenHolder,
+ ephemeralKey,
+ spendingLimit,
+ expirationHeight,
+ { from: registeredWallet0 },
+ );
+
+ const keyData = await tokenHolder.ephemeralKeys.call(ephemeralKey);
+
+ assert.isOk(
+ keyData.spendingLimit.eqn(spendingLimit),
+ );
+
+ assert.isOk(
+ keyData.nonce.eqn(0),
+ );
+
+ assert.isOk(
+ keyData.expirationHeight.eqn(expirationHeight),
+ );
+
+ assert.isOk(
+ // TokenHolder.AuthorizationStatus.AUTHORIZED == 1
+ keyData.status.eqn(1),
+ );
+
+ const transaction = await tokenHolder.transactions.call(
+ transactionID,
+ );
+
+ assert.strictEqual(
+ transaction.destination,
+ tokenHolder.address,
+ );
+
+ assert.strictEqual(
+ transaction.data,
+ generateSubmitAuthorizeSessionData(
+ ephemeralKey, spendingLimit, expirationHeight,
+ ),
+ );
+
+ assert.isOk(
+ transaction.executed,
+ );
+ });
+
+ it('Checks states in case of 2-walleta-2-required.', async () => {
+ const required = 2;
+
+ const registeredWallet0 = accountProvider.get();
+ const registeredWallet1 = accountProvider.get();
+
+ const wallets = [registeredWallet0, registeredWallet1];
+
+ const token = accountProvider.get();
+ const tokenRules = accountProvider.get();
+
+ const tokenHolder = await TokenHolder.new(
+ token, tokenRules, wallets, required,
+ );
+
+ const ephemeralKey = '0x62502C4DF73935D0D10054b0Fb8cC036534C6fb0';
+ const spendingLimit = 1;
+ const expirationHeight = await web3.eth.getBlockNumber() + 50;
+
+ const transactionID = await TokenHolderUtils.submitAuthorizeSession(
+ tokenHolder,
+ ephemeralKey,
+ spendingLimit,
+ expirationHeight,
+ {
+ from: registeredWallet0,
+ },
+ );
+
+ const keyData = await tokenHolder.ephemeralKeys.call(ephemeralKey);
+
+ assert.isOk(
+ // TokenHolder.AuthorizationStatus.NOT_AUTHORIZED == 0
+ keyData.status.eqn(0),
+ );
+
+ const transaction = await tokenHolder.transactions.call(
+ transactionID,
+ );
+
+ assert.strictEqual(
+ transaction.destination,
+ tokenHolder.address,
+ );
+
+ assert.strictEqual(
+ transaction.data,
+ generateSubmitAuthorizeSessionData(
+ ephemeralKey, spendingLimit, expirationHeight,
+ ),
+ );
+
+ assert.isNotOk(
+ transaction.executed,
+ );
+ });
+ });
+});
diff --git a/test/token_holder/utils.js b/test/token_holder/utils.js
new file mode 100644
index 0000000..a9663dc
--- /dev/null
+++ b/test/token_holder/utils.js
@@ -0,0 +1,21 @@
+
+
+class TokenHolderUtils {
+ static async submitAuthorizeSession(
+ tokenHolder, ephemeralKey, spendingLimit, expirationHeight, options,
+ ) {
+ const transactionID = await tokenHolder.submitAuthorizeSession.call(
+ ephemeralKey, spendingLimit, expirationHeight, options,
+ );
+
+ await tokenHolder.submitAuthorizeSession(
+ ephemeralKey, spendingLimit, expirationHeight, options,
+ );
+
+ return transactionID;
+ }
+}
+
+module.exports = {
+ TokenHolderUtils,
+};
diff --git a/test/token_rules/add_global_constraint.js b/test/token_rules/add_global_constraint.js
new file mode 100644
index 0000000..4a7b621
--- /dev/null
+++ b/test/token_rules/add_global_constraint.js
@@ -0,0 +1,143 @@
+// Copyright 2018 OpenST Ltd.
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+const Utils = require('../test_lib/utils.js');
+const { Event } = require('../test_lib/event_decoder');
+const { AccountProvider } = require('../test_lib/utils');
+const TokenRulesUtils = require('./utils.js');
+
+contract('TokenRules::addGlobalConstraint', async () => {
+ contract('Negative Tests', async (accounts) => {
+ const accountProvider = new AccountProvider(accounts);
+
+ it('Reverts if non-organization address is adding constraint.', async () => {
+ const {
+ tokenRules,
+ } = await TokenRulesUtils.createTokenEconomy(accountProvider);
+
+ const constraintAddress = accountProvider.get();
+
+ const nonOrganizationAddress = accountProvider.get();
+
+ await Utils.expectRevert(
+ tokenRules.addGlobalConstraint(
+ constraintAddress,
+ { from: nonOrganizationAddress },
+ ),
+ 'Should revert as non-organization address is adding constraint.',
+ 'Only organization is allowed to call.',
+ );
+ });
+
+ it('Reverts if null address is added as a constraint.', async () => {
+ const {
+ tokenRules,
+ organizationAddress,
+ } = await TokenRulesUtils.createTokenEconomy(accountProvider);
+
+ const constraintAddress = Utils.NULL_ADDRESS;
+
+ await Utils.expectRevert(
+ tokenRules.addGlobalConstraint(
+ constraintAddress,
+ { from: organizationAddress },
+ ),
+ 'Should revert as constraint\'s address to add is null.',
+ 'Constraint to add is null.',
+ );
+ });
+
+ it('Reverts if constraint to add already exists.', async () => {
+ const {
+ tokenRules,
+ organizationAddress,
+ } = await TokenRulesUtils.createTokenEconomy(accountProvider);
+
+ const constraintAddress = accountProvider.get();
+ const existingConstraintAddress = constraintAddress;
+
+ await tokenRules.addGlobalConstraint(
+ constraintAddress,
+ { from: organizationAddress },
+ );
+
+ await Utils.expectRevert(
+ tokenRules.addGlobalConstraint(
+ existingConstraintAddress,
+ { from: organizationAddress },
+ ),
+ 'Should revert as constraint to add already exists.',
+ 'Constraint to add already exists.',
+ );
+ });
+ });
+
+ contract('Events', async (accounts) => {
+ const accountProvider = new AccountProvider(accounts);
+
+ it('Emits GlobalConstraintAdded when adding constraint.', async () => {
+ const {
+ tokenRules,
+ organizationAddress,
+ } = await TokenRulesUtils.createTokenEconomy(accountProvider);
+
+ const constraintAddress = accountProvider.get();
+
+ const transactionResponse = await tokenRules.addGlobalConstraint(
+ constraintAddress,
+ { from: organizationAddress },
+ );
+
+ const events = Event.decodeTransactionResponse(
+ transactionResponse,
+ );
+
+ assert.strictEqual(
+ events.length,
+ 1,
+ 'Only GlobalConstraintAdded should be emitted.',
+ );
+
+ Event.assertEqual(events[0], {
+ name: 'GlobalConstraintAdded',
+ args: {
+ _globalConstraintAddress: constraintAddress,
+ },
+ });
+ });
+ });
+
+ contract('Storage', async (accounts) => {
+ const accountProvider = new AccountProvider(accounts);
+ it('Checks that constraint exists after adding.', async () => {
+ const {
+ tokenRules,
+ organizationAddress,
+ } = await TokenRulesUtils.createTokenEconomy(accountProvider);
+
+ const constraintAddress = accountProvider.get();
+
+ await tokenRules.addGlobalConstraint(
+ constraintAddress,
+ { from: organizationAddress },
+ );
+
+ assert.isOk(
+ await TokenRulesUtils.constraintExists(
+ tokenRules, constraintAddress,
+ ),
+ );
+ });
+ });
+});
diff --git a/test/token_rules/allow_transfers.js b/test/token_rules/allow_transfers.js
new file mode 100644
index 0000000..765032a
--- /dev/null
+++ b/test/token_rules/allow_transfers.js
@@ -0,0 +1,39 @@
+// Copyright 2018 OpenST Ltd.
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+const TokenRulesUtils = require('./utils.js');
+const { AccountProvider } = require('../test_lib/utils');
+
+contract('TokenRules::allowTransfers', async (accounts) => {
+ const accountProvider = new AccountProvider(accounts);
+ it('Checks that transfer is allowed.', async () => {
+ const {
+ tokenRules,
+ } = await TokenRulesUtils.createTokenEconomy(accountProvider);
+
+ const tokenHolder = accountProvider.get();
+
+ assert.isNotOk(
+ await tokenRules.allowedTransfers.call(tokenHolder),
+ );
+
+ await tokenRules.allowTransfers(
+ { from: tokenHolder },
+ );
+
+ assert.isOk(
+ await tokenRules.allowedTransfers.call(tokenHolder),
+ );
+ });
+});
diff --git a/test/token_rules/check_global_constraints.js b/test/token_rules/check_global_constraints.js
new file mode 100644
index 0000000..0cbb16d
--- /dev/null
+++ b/test/token_rules/check_global_constraints.js
@@ -0,0 +1,125 @@
+// Copyright 2018 OpenST Ltd.
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+const utils = require('../test_lib/utils.js');
+const { AccountProvider } = require('../test_lib/utils');
+const TokenRulesUtils = require('./utils.js');
+
+const PassingConstraint = artifacts.require('TokenRulesPassingGlobalConstraint.sol');
+const FailingConstraint = artifacts.require('TokenRulesFailingGlobalConstraint.sol');
+
+
+contract('TokenRules::checkGlobalConstraints', async () => {
+ contract('Negative Tests', async (accounts) => {
+ const accountProvider = new AccountProvider(accounts);
+
+ it('Reverts if transfersTo and transfersAmount array lengths are not equal.', async () => {
+ const {
+ tokenRules,
+ organizationAddress,
+ } = await TokenRulesUtils.createTokenEconomy(accountProvider);
+
+ const transferTo0 = accountProvider.get();
+ const transfersTo = [transferTo0];
+ const transfersAmount = [];
+
+ await utils.expectRevert(
+ tokenRules.checkGlobalConstraints.call(
+ accountProvider.get(),
+ transfersTo,
+ transfersAmount,
+ { from: organizationAddress },
+ ),
+ 'Should revert as transfers "to" and "amount" arrays length '
+ + 'are not equal.',
+ '\'to\' and \'amount\' transfer arrays\' lengths are not equal.',
+ );
+ });
+ });
+ contract('Checking Constraints', async (accounts) => {
+ const accountProvider = new AccountProvider(accounts);
+
+ it('Passes if 2 registered constraints are passing.', async () => {
+ const {
+ tokenRules,
+ organizationAddress,
+ } = await TokenRulesUtils.createTokenEconomy(accountProvider);
+
+ const transferTo0 = accountProvider.get();
+ const transfersTo = [transferTo0];
+ const transfersAmount = [10];
+
+ const passingConstraint1 = await PassingConstraint.new();
+ const passingConstraint2 = await PassingConstraint.new();
+
+ await tokenRules.addGlobalConstraint(
+ passingConstraint1.address,
+ { from: organizationAddress },
+ );
+
+ await tokenRules.addGlobalConstraint(
+ passingConstraint2.address,
+ { from: organizationAddress },
+ );
+
+ const status = await tokenRules.checkGlobalConstraints.call(
+ accountProvider.get(),
+ transfersTo,
+ transfersAmount,
+ { from: organizationAddress },
+ );
+
+ assert.isOk(
+ status,
+ 'Should pass, as two registered constraints are passing.',
+ );
+ });
+
+ it('Fails if there is 1 passing and 1 failing constraint.', async () => {
+ const {
+ tokenRules,
+ organizationAddress,
+ } = await TokenRulesUtils.createTokenEconomy(accountProvider);
+
+ const transferTo0 = accountProvider.get();
+ const transfersTo = [transferTo0];
+ const transfersAmount = [10];
+
+ const passingConstraint1 = await PassingConstraint.new();
+ const failingConstraint1 = await FailingConstraint.new();
+
+ await tokenRules.addGlobalConstraint(
+ passingConstraint1.address,
+ { from: organizationAddress },
+ );
+
+ await tokenRules.addGlobalConstraint(
+ failingConstraint1.address,
+ { from: organizationAddress },
+ );
+
+ const status = await tokenRules.checkGlobalConstraints.call(
+ accountProvider.get(),
+ transfersTo,
+ transfersAmount,
+ { from: organizationAddress },
+ );
+
+ assert.isNotOk(
+ status,
+ 'Should fail, as there is 1 failing constraint and 1 passing.',
+ );
+ });
+ });
+});
diff --git a/test/token_rules/constructor.js b/test/token_rules/constructor.js
new file mode 100644
index 0000000..0bdabc8
--- /dev/null
+++ b/test/token_rules/constructor.js
@@ -0,0 +1,66 @@
+// Copyright 2018 OpenST Ltd.
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+const utils = require('../test_lib/utils.js');
+const { AccountProvider } = require('../test_lib/utils');
+
+const TokenRules = artifacts.require('TokenRules');
+
+contract('TokenRules::constructor', async () => {
+ contract('Negative Tests', async (accounts) => {
+ const accountProvider = new AccountProvider(accounts);
+
+ it('Reverts if organization address is null.', async () => {
+ const organization = utils.NULL_ADDRESS;
+ const token = accountProvider.get();
+
+ await utils.expectRevert(
+ TokenRules.new(organization, token),
+ 'Should revert as organization address is null.',
+ 'Organization address is null.',
+ );
+ });
+ it('Reverts if token is null.', async () => {
+ const organization = accountProvider.get();
+ const token = utils.NULL_ADDRESS;
+
+ await utils.expectRevert(
+ TokenRules.new(organization, token),
+ 'Should revert as token is null.',
+ 'Token address is null.',
+ );
+ });
+ });
+
+ contract('Storage', async (accounts) => {
+ const accountProvider = new AccountProvider(accounts);
+
+ it('Checks that passed arguments are set correctly.', async () => {
+ const organization = accountProvider.get();
+ const token = accountProvider.get();
+
+ const tokenRules = await TokenRules.new(organization, token);
+
+ assert.strictEqual(
+ (await tokenRules.organization.call()),
+ organization,
+ );
+
+ assert.strictEqual(
+ (await tokenRules.token.call()),
+ token,
+ );
+ });
+ });
+});
diff --git a/test/token_rules/disallow_transfers.js b/test/token_rules/disallow_transfers.js
new file mode 100644
index 0000000..4ce7d96
--- /dev/null
+++ b/test/token_rules/disallow_transfers.js
@@ -0,0 +1,43 @@
+// Copyright 2018 OpenST Ltd.
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+const TokenRulesUtils = require('./utils.js');
+const { AccountProvider } = require('../test_lib/utils');
+
+contract('TokenRules::disallowTransfers', async (accounts) => {
+ const accountProvider = new AccountProvider(accounts);
+ it('Checks that transfer is disallowed.', async () => {
+ const {
+ tokenRules,
+ } = await TokenRulesUtils.createTokenEconomy(accountProvider);
+
+ const tokenHolder = accountProvider.get();
+
+ await tokenRules.allowTransfers(
+ { from: tokenHolder },
+ );
+
+ assert.isOk(
+ await tokenRules.allowedTransfers.call(tokenHolder),
+ );
+
+ await tokenRules.disallowTransfers(
+ { from: tokenHolder },
+ );
+
+ assert.isNotOk(
+ await tokenRules.allowedTransfers.call(tokenHolder),
+ );
+ });
+});
diff --git a/test/token_rules/execute_transfers.js b/test/token_rules/execute_transfers.js
new file mode 100644
index 0000000..b2fc63e
--- /dev/null
+++ b/test/token_rules/execute_transfers.js
@@ -0,0 +1,267 @@
+// Copyright 2018 OpenST Ltd.
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+const BN = require('bn.js');
+const utils = require('../test_lib/utils.js');
+const { AccountProvider } = require('../test_lib/utils');
+const TokenRulesUtils = require('./utils.js');
+
+const PassingConstraint = artifacts.require('TokenRulesPassingGlobalConstraint.sol');
+const FailingConstraint = artifacts.require('TokenRulesFailingGlobalConstraint.sol');
+
+async function happyPath(accountProvider) {
+ const {
+ tokenRules,
+ organizationAddress,
+ token,
+ } = await TokenRulesUtils.createTokenEconomy(accountProvider);
+
+ const passingConstraint1 = await PassingConstraint.new();
+
+ await tokenRules.addGlobalConstraint(
+ passingConstraint1.address,
+ { from: organizationAddress },
+ );
+
+ const ruleAddress0 = accountProvider.get();
+ await tokenRules.registerRule(
+ 'ruleName0',
+ ruleAddress0,
+ 'ruleAbi0',
+ { from: organizationAddress },
+ );
+ await token.setBalance(ruleAddress0, 100);
+
+ const tokenHolder = accountProvider.get();
+ const spendingLimit = 100;
+ await token.setBalance(tokenHolder, 100);
+ await token.approve(
+ tokenRules.address,
+ spendingLimit,
+ { from: tokenHolder },
+ );
+
+ await tokenRules.allowTransfers(
+ { from: tokenHolder },
+ );
+
+ const transferTo0 = accountProvider.get();
+ const transferAmount0 = 1;
+
+ const transfersTo = [transferTo0];
+ const transfersAmount = [transferAmount0];
+
+ return {
+ tokenRules,
+ organizationAddress,
+ token,
+ passingConstraint1,
+ tokenHolder,
+ ruleAddress0,
+ transfersTo,
+ transfersAmount,
+ };
+}
+
+contract('TokenRules::executeTransfers', async () => {
+ contract('Negative Tests', async (accounts) => {
+ const accountProvider = new AccountProvider(accounts);
+ it('Reverts if non-registered rule calls.', async () => {
+ const {
+ tokenRules,
+ tokenHolder,
+ transfersTo,
+ transfersAmount,
+ } = await happyPath(accountProvider);
+
+ const nonRegisteredRuleAddress = accountProvider.get();
+
+ await utils.expectRevert(
+ tokenRules.executeTransfers(
+ tokenHolder,
+ transfersTo,
+ transfersAmount,
+ {
+ from: nonRegisteredRuleAddress,
+ },
+ ),
+ 'Should revert as non registered rule is calling.',
+ 'Only registered rule is allowed to call.',
+ );
+ });
+
+ it('Reverts if "from" account has not allowed transfers.', async () => {
+ const {
+ tokenRules,
+ tokenHolder,
+ ruleAddress0,
+ transfersTo,
+ transfersAmount,
+ } = await happyPath(accountProvider);
+
+ await tokenRules.disallowTransfers(
+ { from: tokenHolder },
+ );
+
+ await utils.expectRevert(
+ tokenRules.executeTransfers(
+ tokenHolder,
+ transfersTo,
+ transfersAmount,
+ { from: ruleAddress0 },
+ ),
+ 'Should revert as "from" account has not allowed transfers.',
+ 'Transfers from the address are not allowed.',
+ );
+ });
+
+ it('Reverts if transfersTo and transferAmount array lengths are not equal.', async () => {
+ const {
+ tokenRules,
+ tokenHolder,
+ ruleAddress0,
+ } = await happyPath(accountProvider);
+
+ const transferTo0 = accountProvider.get();
+ const transfersTo = [transferTo0];
+ const transfersAmount = [];
+
+ await utils.expectRevert(
+ tokenRules.executeTransfers(
+ tokenHolder,
+ transfersTo,
+ transfersAmount,
+ { from: ruleAddress0 },
+ ),
+ 'Should revert as transfers "to" and "amount" arrays length '
+ + 'are not equal.',
+ '\'to\' and \'amount\' transfer arrays\' lengths are not equal.',
+ );
+ });
+
+ it('Reverts if constraints do not fulfill.', async () => {
+ const {
+ tokenRules,
+ organizationAddress,
+ tokenHolder,
+ ruleAddress0,
+ transfersTo,
+ transfersAmount,
+ } = await happyPath(accountProvider);
+
+ const failingConstraint1 = await FailingConstraint.new();
+
+ await tokenRules.addGlobalConstraint(
+ failingConstraint1.address,
+ { from: organizationAddress },
+ );
+
+ await utils.expectRevert(
+ tokenRules.executeTransfers(
+ tokenHolder,
+ transfersTo,
+ transfersAmount,
+ { from: ruleAddress0 },
+ ),
+ 'Should revert as one of the constraints will fail.',
+ 'Constraints not fullfilled.',
+ );
+ });
+ });
+
+ contract('Execution Validity', async (accounts) => {
+ const accountProvider = new AccountProvider(accounts);
+
+ it('Checks that token transferFrom function is called.', async () => {
+ const {
+ tokenRules,
+ token,
+ tokenHolder,
+ ruleAddress0,
+ transfersTo,
+ transfersAmount,
+ } = await happyPath(accountProvider);
+
+ // For test validity perspective array should not be empty.
+ assert(transfersTo.length !== 0);
+
+ const tokenHolderInitialBalance = await token.balanceOf(tokenHolder);
+ const transfersToInitialBalances = [];
+ let transfersAmountSum = new BN(0);
+ for (let i = 0; i < transfersTo.length; i += 1) {
+ // eslint-disable-next-line no-await-in-loop
+ const initialBalance = await token.balanceOf.call(transfersTo[i]);
+ transfersToInitialBalances.push(initialBalance);
+
+ transfersAmountSum = transfersAmountSum.add(new BN(transfersAmount[i]));
+ }
+
+ // For test validity perspective, we should not fail in this case.
+ assert(tokenHolderInitialBalance.gte(transfersAmountSum));
+
+ await tokenRules.executeTransfers(
+ tokenHolder,
+ transfersTo,
+ transfersAmount,
+ { from: ruleAddress0 },
+ );
+
+ assert.strictEqual(
+ (await token.balanceOf(tokenHolder)).cmp(
+ tokenHolderInitialBalance.sub(transfersAmountSum),
+ ),
+ 0,
+ );
+
+ for (let i = 0; i < transfersTo.length; i += 1) {
+ // eslint-disable-next-line no-await-in-loop
+ const balance = await token.balanceOf.call(transfersTo[i]);
+
+ assert.strictEqual(
+ balance.cmp(
+ transfersToInitialBalances[i].add(
+ new BN(transfersAmount[i]),
+ ),
+ ),
+ 0,
+ );
+ }
+ });
+
+ it('Checks that at the end TokenRules disallow transfers.', async () => {
+ const {
+ tokenRules,
+ tokenHolder,
+ ruleAddress0,
+ transfersTo,
+ transfersAmount,
+ } = await happyPath(accountProvider);
+
+ await tokenRules.allowTransfers(
+ { from: tokenHolder },
+ );
+
+ await tokenRules.executeTransfers(
+ tokenHolder,
+ transfersTo,
+ transfersAmount,
+ { from: ruleAddress0 },
+ );
+
+ assert.isNotOk(
+ await tokenRules.allowedTransfers.call(tokenHolder),
+ );
+ });
+ });
+});
diff --git a/test/token_rules/register_rule.js b/test/token_rules/register_rule.js
new file mode 100644
index 0000000..3e398ab
--- /dev/null
+++ b/test/token_rules/register_rule.js
@@ -0,0 +1,277 @@
+// Copyright 2018 OpenST Ltd.
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+const web3 = require('../test_lib/web3.js');
+const utils = require('../test_lib/utils.js');
+const { Event } = require('../test_lib/event_decoder');
+const { AccountProvider } = require('../test_lib/utils');
+const TokenRulesUtils = require('./utils.js');
+
+
+contract('TokenRules::registerRule', async () => {
+ contract('Negative Tests', async (accounts) => {
+ const accountProvider = new AccountProvider(accounts);
+
+ it('Reverts if non-organization address calls.', async () => {
+ const {
+ tokenRules,
+ } = await TokenRulesUtils.createTokenEconomy(accountProvider);
+
+ const ruleName = 'A';
+ const ruleAddress = accountProvider.get();
+ const ruleAbi = `Rule abi of ${ruleName}`;
+
+ const nonOrganizationAddress = accountProvider.get();
+
+ await utils.expectRevert(
+ tokenRules.registerRule(
+ ruleName,
+ ruleAddress,
+ ruleAbi,
+ { from: nonOrganizationAddress },
+ ),
+ 'Should revert as non-organization address calls.',
+ 'Only organization is allowed to call.',
+ );
+ });
+ it('Reverts if rule name is empty.', async () => {
+ const {
+ tokenRules,
+ organizationAddress,
+ } = await TokenRulesUtils.createTokenEconomy(accountProvider);
+
+ const ruleName = '';
+ const ruleAddress = accountProvider.get();
+ const ruleAbi = `Rule abi of ${ruleName}`;
+
+ await utils.expectRevert(
+ tokenRules.registerRule(
+ ruleName,
+ ruleAddress,
+ ruleAbi,
+ { from: organizationAddress },
+ ),
+ 'Should revert as rule name is empty.',
+ 'Rule name is empty.',
+ );
+ });
+ it('Reverts if a rule with the same name already registered.', async () => {
+ const {
+ tokenRules,
+ organizationAddress,
+ } = await TokenRulesUtils.createTokenEconomy(accountProvider);
+
+ const aRuleName = 'A';
+ const aRuleAddress = accountProvider.get();
+ const aRuleAbi = `Rule abi of ${aRuleName}`;
+
+ const bRuleName = aRuleName;
+ const bRuleAddress = accountProvider.get();
+ const bRuleAbi = 'Rule abi of B';
+
+ await tokenRules.registerRule(
+ aRuleName,
+ aRuleAddress,
+ aRuleAbi,
+ { from: organizationAddress },
+ );
+
+ await utils.expectRevert(
+ tokenRules.registerRule(
+ bRuleName,
+ bRuleAddress,
+ bRuleAbi,
+ { from: organizationAddress },
+ ),
+ 'Should revert as a rule with the same name already registered.',
+ 'Rule with the specified name already exists.',
+ );
+ });
+ it('Reverts if rule address is null.', async () => {
+ const {
+ tokenRules,
+ organizationAddress,
+ } = await TokenRulesUtils.createTokenEconomy(accountProvider);
+
+ const ruleName = 'A';
+ const ruleAddress = utils.NULL_ADDRESS;
+ const ruleAbi = `Rule abi of ${ruleName}`;
+
+ await utils.expectRevert(
+ tokenRules.registerRule(
+ ruleName,
+ ruleAddress,
+ ruleAbi,
+ { from: organizationAddress },
+ ),
+ 'Should revert as rule address is null.',
+ 'Rule address is null.',
+ );
+ });
+
+ it('Reverts if rule with the same address already registered.', async () => {
+ const {
+ tokenRules,
+ organizationAddress,
+ } = await TokenRulesUtils.createTokenEconomy(accountProvider);
+
+ const aRuleName = 'A';
+ const aRuleAddress = accountProvider.get();
+ const aRuleAbi = `Rule abi of ${aRuleName}`;
+
+ const bRuleName = 'B';
+ const bRuleAddress = aRuleAddress;
+ const bRuleAbi = `Rule abi of ${bRuleName}`;
+
+ await tokenRules.registerRule(
+ aRuleName,
+ aRuleAddress,
+ aRuleAbi,
+ { from: organizationAddress },
+ );
+
+ await utils.expectRevert(
+ tokenRules.registerRule(
+ bRuleName,
+ bRuleAddress,
+ bRuleAbi,
+ { from: organizationAddress },
+ ),
+ 'Should revert as rule with the specified address already registered.',
+ 'Rule with the specified address already exists.',
+ );
+ });
+
+ it('Reverts if rule ABI is empty.', async () => {
+ const {
+ tokenRules,
+ organizationAddress,
+ } = await TokenRulesUtils.createTokenEconomy(accountProvider);
+
+ const ruleName = 'A';
+ const ruleAddress = accountProvider.get();
+ const ruleAbi = '';
+
+ await utils.expectRevert(
+ tokenRules.registerRule(
+ ruleName,
+ ruleAddress,
+ ruleAbi,
+ { from: organizationAddress },
+ ),
+ 'Should revert as rule ABI is empty.',
+ 'Rule ABI is empty.',
+ );
+ });
+ });
+
+ contract('Events', async (accounts) => {
+ const accountProvider = new AccountProvider(accounts);
+
+ it('Emits RuleRegistered event on registering rule.', async () => {
+ const {
+ tokenRules,
+ organizationAddress,
+ } = await TokenRulesUtils.createTokenEconomy(accountProvider);
+
+ const aRuleName = 'A';
+ const aRuleAddress = accountProvider.get();
+ const aRuleAbi = `Rule abi of ${aRuleName}`;
+
+ const transactionResponse = await tokenRules.registerRule(
+ aRuleName,
+ aRuleAddress,
+ aRuleAbi,
+ { from: organizationAddress },
+ );
+
+ const events = Event.decodeTransactionResponse(
+ transactionResponse,
+ );
+
+ assert.strictEqual(
+ events.length,
+ 1,
+ 'Only RuleRegistered event should be emitted.',
+ );
+
+ Event.assertEqual(events[0], {
+ name: 'RuleRegistered',
+ args: {
+ _ruleName: aRuleName,
+ _ruleAddress: aRuleAddress,
+ },
+ });
+ });
+ });
+
+ contract('Storage', async (accounts) => {
+ const accountProvider = new AccountProvider(accounts);
+
+ it('Checks that rule exists after registration.', async () => {
+ const {
+ tokenRules,
+ organizationAddress,
+ } = await TokenRulesUtils.createTokenEconomy(accountProvider);
+
+ const aRuleName = 'A';
+ const aRuleAddress = accountProvider.get();
+ const aRuleAbi = `Rule abi of ${aRuleName}`;
+
+ await tokenRules.registerRule(
+ aRuleName,
+ aRuleAddress,
+ aRuleAbi,
+ { from: organizationAddress },
+ );
+
+ const ruleIndexByAddress = await tokenRules.rulesByAddress.call(
+ aRuleAddress,
+ );
+ const ruleIndexByNameHash = await tokenRules.rulesByNameHash.call(
+ web3.utils.soliditySha3(aRuleName),
+ );
+
+ assert.isOk(
+ ruleIndexByAddress.exists,
+ );
+
+ assert.isOk(
+ ruleIndexByNameHash.exists,
+ );
+
+ assert.strictEqual(
+ ruleIndexByAddress.index.cmp(ruleIndexByNameHash.index),
+ 0,
+ );
+
+ const rule = await tokenRules.rules.call(ruleIndexByAddress.index);
+
+ assert.strictEqual(
+ rule.ruleName,
+ aRuleName,
+ );
+
+ assert.strictEqual(
+ rule.ruleAddress,
+ aRuleAddress,
+ );
+
+ assert.strictEqual(
+ rule.ruleAbi,
+ aRuleAbi,
+ );
+ });
+ });
+});
diff --git a/test/token_rules/remove_global_constraint.js b/test/token_rules/remove_global_constraint.js
new file mode 100644
index 0000000..b7d995e
--- /dev/null
+++ b/test/token_rules/remove_global_constraint.js
@@ -0,0 +1,142 @@
+// Copyright 2018 OpenST Ltd.
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+const utils = require('../test_lib/utils.js');
+const { Event } = require('../test_lib/event_decoder');
+const { AccountProvider } = require('../test_lib/utils');
+const TokenRulesUtils = require('./utils.js');
+
+async function prepareTokenRules(accountProvider) {
+ const {
+ tokenRules,
+ organizationAddress,
+ } = await TokenRulesUtils.createTokenEconomy(accountProvider);
+
+ const constraintAddress0 = accountProvider.get();
+
+ await tokenRules.addGlobalConstraint(
+ constraintAddress0,
+ { from: organizationAddress },
+ );
+
+ return {
+ tokenRules,
+ organizationAddress,
+ constraintAddress0,
+ };
+}
+
+contract('TokenRules::removeGlobalConstraint', async () => {
+ contract('Negative Tests', async (accounts) => {
+ const accountProvider = new AccountProvider(accounts);
+
+ it('Reverts if non-organization address is removing constraint.', async () => {
+ const {
+ tokenRules,
+ constraintAddress0,
+ } = await prepareTokenRules(accountProvider);
+
+ const nonOrganizationAddress = accountProvider.get();
+
+ await utils.expectRevert(
+ tokenRules.removeGlobalConstraint(
+ constraintAddress0,
+ { from: nonOrganizationAddress },
+ ),
+ 'Should revert as non organization address calls.',
+ 'Only organization is allowed to call.',
+ );
+ });
+
+ it('Reverts if constraint to remove does not exist.', async () => {
+ const {
+ tokenRules,
+ organizationAddress,
+ } = await prepareTokenRules(accountProvider);
+
+ const nonExistingConstraintAddress = accountProvider.get();
+
+ await utils.expectRevert(
+ tokenRules.removeGlobalConstraint(
+ nonExistingConstraintAddress,
+ { from: organizationAddress },
+ ),
+ 'Should revert as constraint to remove does not exist.',
+ 'Constraint to remove does not exist.',
+ );
+ });
+ });
+
+ contract('Events', async (accounts) => {
+ const accountProvider = new AccountProvider(accounts);
+
+ it('Emits GlobalConstraintRemoved on removing global constraint.', async () => {
+ const {
+ tokenRules,
+ organizationAddress,
+ constraintAddress0,
+ } = await prepareTokenRules(accountProvider);
+
+ const transactionResponse = await tokenRules.removeGlobalConstraint(
+ constraintAddress0,
+ { from: organizationAddress },
+ );
+
+ const events = Event.decodeTransactionResponse(
+ transactionResponse,
+ );
+
+ assert.strictEqual(
+ events.length,
+ 1,
+ );
+
+ Event.assertEqual(events[0], {
+ name: 'GlobalConstraintRemoved',
+ args: {
+ _globalConstraintAddress: constraintAddress0,
+ },
+ });
+ });
+ });
+
+ contract('Storage', async (accounts) => {
+ const accountProvider = new AccountProvider(accounts);
+
+ it('Checks that constraint does not exist after removing.', async () => {
+ const {
+ tokenRules,
+ organizationAddress,
+ constraintAddress0,
+ } = await prepareTokenRules(accountProvider);
+
+ assert.isOk(
+ await TokenRulesUtils.constraintExists(
+ tokenRules, constraintAddress0,
+ ),
+ );
+
+ await tokenRules.removeGlobalConstraint(
+ constraintAddress0,
+ { from: organizationAddress },
+ );
+
+ assert.isNotOk(
+ await TokenRulesUtils.constraintExists(
+ tokenRules, organizationAddress,
+ ),
+ );
+ });
+ });
+});
diff --git a/test/token_rules/utils.js b/test/token_rules/utils.js
new file mode 100644
index 0000000..829ba7e
--- /dev/null
+++ b/test/token_rules/utils.js
@@ -0,0 +1,67 @@
+// Copyright 2018 OST.com Ltd.
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+const EIP20TokenMock = artifacts.require('EIP20TokenMock');
+const TokenRules = artifacts.require('TokenRules');
+
+/**
+ * Creates an EIP20 instance to be used during TokenRules::executeTransfers
+ * function's testing with the following defaults:
+ * - conversionRate: 1
+ * - conversionRateDecimals: 1
+ * - symbol: 'OST'
+ * - name: 'Open Simple Token'
+ * - decimals: 1
+ */
+module.exports.createEIP20Token = async () => {
+ const token = await EIP20TokenMock.new(
+ 1, 1, 'OST', 'Open Simple Token', 1,
+ );
+
+ return token;
+};
+
+/** Returns true if the specified constraint exists, otherwise false. */
+module.exports.constraintExists = async (tokenRules, constraintAddress) => {
+ const constraintCount = await tokenRules.globalConstraintCount.call();
+
+ for (let i = 0; i < constraintCount; i += 1) {
+ // eslint-disable-next-line no-await-in-loop
+ const c = await tokenRules.globalConstraints.call(i);
+ if (c === constraintAddress) {
+ return true;
+ }
+ }
+
+ return false;
+};
+
+/**
+ * Creates and returns the tuple:
+ * (tokenRules, organizationAddress, token)
+ */
+module.exports.createTokenEconomy = async (accountProvider) => {
+ const organizationAddress = accountProvider.get();
+ const token = await this.createEIP20Token();
+
+ const tokenRules = await TokenRules.new(
+ organizationAddress, token.address,
+ );
+
+ return {
+ tokenRules,
+ organizationAddress,
+ token,
+ };
+};
diff --git a/test/transfer_rule/constructor.js b/test/transfer_rule/constructor.js
new file mode 100644
index 0000000..f5937de
--- /dev/null
+++ b/test/transfer_rule/constructor.js
@@ -0,0 +1,46 @@
+// Copyright 2018 OpenST Ltd.
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+const web3 = require('../test_lib/web3.js');
+const utils = require('../test_lib/utils.js');
+const { AccountProvider } = require('../test_lib/utils.js');
+
+const TransferRule = artifacts.require('TransferRule');
+const tokenRulesMock = artifacts.require('TokenRulesMock');
+
+
+contract('TransferRule::constructor', async () => {
+ contract('Negative tests for input parameters:', async (accounts) => {
+
+ const accountProvider = new AccountProvider(accounts);
+
+ it('fails when tokenrules address is null.', async () => {
+
+ await utils.expectRevert(TransferRule.new(utils.NULL_ADDRESS),
+ 'Should revert as token rule address is null',
+ 'Token rules address is null.');
+
+ });
+
+ contract('Positive test cases', async (accounts) => {
+ it('sucessfully initializes when passed arguments are set correctly.', async () => {
+
+ const tokenRulesMockInstance = await tokenRulesMock.new();
+
+ assert.ok(await TransferRule.new(tokenRulesMockInstance.address));
+
+ });
+ });
+ });
+});
\ No newline at end of file
diff --git a/test/transfer_rule/transfer_from.js b/test/transfer_rule/transfer_from.js
new file mode 100644
index 0000000..8cafcd1
--- /dev/null
+++ b/test/transfer_rule/transfer_from.js
@@ -0,0 +1,57 @@
+// Copyright 2018 OpenST Ltd.
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+const utils = require('../test_lib/utils.js');
+const { AccountProvider } = require('../test_lib/utils.js');
+
+const TransferRule = artifacts.require('TransferRule');
+const tokenRulesMock = artifacts.require('TokenRulesMock');
+
+contract('TransferRule::transferFrom', async () => {
+ contract('Negative tests for input parameters:', async (accounts) => {
+ const accountProvider = new AccountProvider(accounts);
+
+ it('Reverts when Token rules address is incorrect.', async () => {
+ const fromUser = accountProvider.get();
+ const toUser = accountProvider.get();
+ const amount = 10;
+ const incorrectTokenRulesAddress = accountProvider.get();
+
+ const transferRuleInstance = await TransferRule.new(incorrectTokenRulesAddress);
+ await utils.expectRevert(
+ transferRuleInstance.transferFrom.call(fromUser, toUser, amount),
+ );
+ });
+ });
+
+ contract('Storage', async (accounts) => {
+ const accountProvider = new AccountProvider(accounts);
+
+ it('Validates successful transfer.', async () => {
+ const fromUser = accountProvider.get();
+ const toUser = accountProvider.get();
+ const amount = 10;
+
+ const tokenRulesMockInstance = await tokenRulesMock.new();
+
+ const transferRuleInstance = await TransferRule.new(tokenRulesMockInstance.address);
+ assert.equal(await transferRuleInstance.transferFrom.call(fromUser, toUser, amount), true, 'transferFrom method failed');
+ await transferRuleInstance.transferFrom(fromUser, toUser, amount);
+
+ assert.equal(await tokenRulesMockInstance.from.call(), fromUser, 'From address not set correctly');
+ assert.equal(await tokenRulesMockInstance.transferTo.call(0), toUser, 'To address not set correctly');
+ assert.equal(await tokenRulesMockInstance.transferAmount.call(0), amount, 'Amount is not set correctly');
+ });
+ });
+});
diff --git a/contracts/compile.sh b/tools/compile.sh
old mode 100644
new mode 100755
similarity index 100%
rename from contracts/compile.sh
rename to tools/compile.sh
diff --git a/tools/deploy/EIP20TokenMock.js b/tools/deploy/EIP20TokenMock.js
deleted file mode 100644
index fb89fbc..0000000
--- a/tools/deploy/EIP20TokenMock.js
+++ /dev/null
@@ -1,144 +0,0 @@
-"use strict";
-
-/**
- * This is script for deploying Pricer contract on any chain.
- *
- * Prerequisite:
- *
- * Deployer Address
- *
- *
- *
- * @module tools/deploy/EIP20TokenMock
- */
-
-const openSTStorage = require('@openstfoundation/openst-storage');
-
-const readline = require('readline')
- , rootPrefix = '../..'
- , prompts = readline.createInterface(process.stdin, process.stdout)
- , logger = require(rootPrefix + '/helpers/custom_console_logger')
- , Deployer = require(rootPrefix + '/services/deploy/deployer')
- , BigNumber = require('bignumber.js')
- , helper = require(rootPrefix + "/tools/deploy/helper")
- , gasLimitGlobalConstant = require(rootPrefix + '/lib/global_constant/gas_limit')
- , dynamodbConnectionParams = require(rootPrefix + '/config/dynamoDB')
- , ddbServiceObj = new openSTStorage.Dynamodb(dynamodbConnectionParams)
- , autoScalingServiceObj = require(rootPrefix + '/lib/auto_scaling_service')
-;
-
-/**
- * It is the main performer method of this deployment script
- *
- * @param {Array} arguments
- *
- * @return {}
- */
-
-
-async function performer(argv) {
-
- if (argv.length < 7) {
- logger.error("Invalid arguments !!!");
- process.exit(0);
- }
- //argv[2] => uint256 conversionFactor;
- //argv[3] => string symbol;
- //argv[4] => string name;
- //argv[5] => uint8 decimals;
- //argv[6] => hex gasPrice;
- //argv[7] => string travis;
- //argv[8] => string File name where contract address needs to write;
- const conversionFactor = argv[2].trim();
- const symbol = argv[3].trim();
- const name = argv[4].trim();
- const decimals = argv[5].trim();
- const gasPrice = argv[6].trim();
- var isTravisCIEnabled = false;
- if (argv[7] !== undefined) {
- isTravisCIEnabled = argv[7].trim() === 'travis';
- }
- const fileForContractAddress = (argv[8] !== undefined) ? argv[8].trim() : '';
-
-
- const conversionDecimals = 5;
- const conversionRate = (new BigNumber(String(conversionFactor))).mul((new BigNumber(10)).toPower(conversionDecimals));
- if (!conversionRate.modulo(1).equals(0)){
- logger.error('Exiting deployment scripts. Invalid conversion factor');
- process.exit(1);
- }
-
-
- logger.debug("conversionFactor: " + conversionFactor);
- logger.debug("conversionRate: " + conversionRate);
- logger.debug("conversionDecimals: " + conversionDecimals);
- logger.debug("symbol: " + symbol);
- logger.debug("name: " + name);
- logger.debug("decimals: " + decimals);
- logger.debug("gasPrice: " + gasPrice);
- logger.debug("Travis CI enabled Status: " + isTravisCIEnabled);
-
- if (isTravisCIEnabled === false ) {
- await new Promise(
- function (onResolve, onReject) {
- prompts.question("Please verify all above details. Do you want to proceed? [Y/N]", function (intent) {
- if (intent === 'Y') {
- logger.debug('Great! Proceeding deployment.');
- prompts.close();
- onResolve();
- } else {
- logger.error('Exiting deployment scripts. Change the enviroment variables and re-run.');
- process.exit(1);
- }
- });
- }
- );
- } else {
- prompts.close();
- }
-
- const contractName = 'eip20tokenmock'
- , options = {returnType: "txReceipt"}
- ;
-
- var constructorArgs = [
- conversionRate,
- conversionDecimals,
- symbol,
- name,
- decimals
- ];
-
- const deployerInstance = new Deployer({
- contract_name: contractName,
- constructor_args: constructorArgs,
- gas_price: gasPrice,
- gas_limit: gasLimitGlobalConstant.default(),
- options: options
- });
-
- const deployResult = await deployerInstance.perform();
-
- if (deployResult.isSuccess()) {
- const contractAddress = deployResult.data.transaction_receipt.contractAddress;
- logger.win("contractAddress: " + contractAddress);
-
- logger.debug('*** Allocating shard for Token balance');
-
- await new openSTStorage.TokenBalanceModel({
- ddb_service: ddbServiceObj,
- auto_scaling: autoScalingServiceObj,
- erc20_contract_address: contractAddress
- }).allocate();
-
- if (fileForContractAddress !== '') {
- await helper.writeContractAddressToFile(fileForContractAddress, contractAddress);
- }
- }
- process.exit(0);
-}
-
-
-
-// example: node ../tools/deploy/EIP20TokenMock.js 5 DKN deepeshCoin 18 0x12A05F200 travis bt.txt
-performer(process.argv);
diff --git a/tools/deploy/airdrop.js b/tools/deploy/airdrop.js
deleted file mode 100644
index 147f7ab..0000000
--- a/tools/deploy/airdrop.js
+++ /dev/null
@@ -1,182 +0,0 @@
-"use strict";
-
-/**
- * This is script for deploying Pricer contract on any chain.
- *
- * Prerequisite:
- *
- * Deployer Address
- *
- *
- * These are the following steps:
- *
- * Deploy Airdrop contract
- *
- *
- *
- * @module tools/deploy/pricer
- */
-
-const readline = require('readline')
- , rootPrefix = '../..'
- , coreAddresses = require(rootPrefix + '/config/core_addresses')
- , prompts = readline.createInterface(process.stdin, process.stdout)
- , logger = require(rootPrefix + '/helpers/custom_console_logger')
- , returnTypes = require(rootPrefix + "/lib/global_constant/return_types")
- , helper = require(rootPrefix + "/tools/deploy/helper")
- , openstPayment = require(rootPrefix + '/index')
- , SetOpsKlass = openstPayment.services.opsManaged.setOps
- , GetOpsKlass = openstPayment.services.opsManaged.getOps
- , DeployAirdropKlass = openstPayment.services.deploy.airdrop
-;
-
-// Different addresses used for deployment
-const deployerName = "deployer"
- , deployerAddress = coreAddresses.getAddressForUser(deployerName)
- , deployerPassphrase = coreAddresses.getPassphraseForUser(deployerName)
-;
-
-const opsName = "ops";
-const opsAddress = coreAddresses.getAddressForUser(opsName);
-
-
-/**
- * Validation Method
- *
- * @param {Array} arguments
- *
- * @return {}
- */
-function validate(argv) {
- if (!argv[2]) {
- logger.error("brandedTokenAddress is mandatory!");
- process.exit(0);
- }
- if (!argv[3]) {
- logger.error("Base currency is mandatory!");
- process.exit(0);
- }
- if (!argv[4]) {
- logger.error("Worker Contract Address is mandatory!");
- process.exit(0);
- }
- if (!argv[5]) {
- logger.error("airdropbudgetholder is mandatory!");
- process.exit(0);
- }
- if (!argv[6]) {
- logger.error("gas price is mandatory!");
- process.exit(0);
- }
- if (!argv[7]) {
- logger.error("chainId is mandatory!");
- process.exit(0);
- }
-}
-
-/**
- * It is the main performer method of this deployment script
- *
- * @param {Array} arguments
- *
- * @return {}
- */
-async function performer(argv) {
-
- validate(argv);
- const brandedTokenAddress = argv[2].trim();
- const baseCurrency = argv[3].trim();
- const workerContractAddress = argv[4].trim();
- const airdropBudgetHolder = argv[5].trim();
- const gasPrice = argv[6].trim();
- const chainId = argv[7].trim();
- var isTravisCIEnabled = false;
- if (argv[8] !== undefined) {
- isTravisCIEnabled = argv[8].trim() === 'travis';
- }
- const fileForContractAddress = (argv[9] !== undefined) ? argv[9].trim() : '';
-
- logger.debug("Deployer Address: " + deployerAddress);
- logger.debug("Ops Address: " + opsAddress);
- logger.debug("Branded Token Address: " + brandedTokenAddress);
- logger.debug("Base currency: " + baseCurrency);
- logger.debug("Worker Contract Address: " + workerContractAddress);
- logger.debug("Airdrop Budget Holder: " + airdropBudgetHolder);
- logger.debug("Gas price: " + gasPrice);
- logger.debug("chainId: " + chainId);
- logger.debug("Travis CI enabled Status: " + isTravisCIEnabled);
- logger.debug("File to write For ContractAddress: "+fileForContractAddress);
-
- if (isTravisCIEnabled === false ) {
- await new Promise(
- function (onResolve, onReject) {
- prompts.question("Please verify all above details. Do you want to proceed? [Y/N]", function (intent) {
- if (intent === 'Y') {
- logger.debug('Great! Proceeding deployment.');
- prompts.close();
- onResolve();
- } else {
- logger.error('Exiting deployment scripts. Change the enviroment variables and re-run.');
- process.exit(1);
- }
- });
- }
- );
- } else {
- prompts.close();
- }
-
- const deployOptions = {returnType: returnTypes.transactionReceipt()}
- ;
- const DeployAirdropObject = new DeployAirdropKlass({
- branded_token_contract_address: brandedTokenAddress,
- base_currency: baseCurrency,
- worker_contract_address: workerContractAddress,
- airdrop_budget_holder: airdropBudgetHolder,
- gas_price: gasPrice,
- options: deployOptions
- });
- const deployResult = await DeployAirdropObject.perform();
-
- if (deployResult.isSuccess()) {
- const contractAddress = deployResult.data.transaction_receipt.contractAddress;
- logger.win("contractAddress: " + contractAddress);
- if (fileForContractAddress !== '') {
- helper.writeContractAddressToFile(fileForContractAddress, contractAddress);
- }
-
- const setOpsOptions = {
- returnType: returnTypes.transactionReceipt(),
- tag: ''
- };
- logger.debug("Setting Ops Address to: " + opsAddress);
- const SetOpsObject = new SetOpsKlass({
- contract_address: contractAddress,
- gas_price: gasPrice,
- chain_id: chainId,
- deployer_address: deployerAddress,
- deployer_passphrase: deployerPassphrase,
- ops_address: opsAddress,
- options: setOpsOptions
- });
- var setOpsResult = await SetOpsObject.perform();
- logger.debug(setOpsResult);
-
- const GetOpsObject = new GetOpsKlass({
- contract_address: contractAddress,
- gas_price: gasPrice,
- chain_id: chainId
- });
- const getOpsResult = await GetOpsObject.perform();
- const contractOpsAddress = getOpsResult.data.opsAddress;
- logger.debug("Ops Address Set to: " + contractOpsAddress);
-
- } else {
- logger.error("Error deploying contract");
- logger.error(deployResult);
- }
- process.exit(0);
-}
-
-// node tools/deploy/airdrop.js brandedTokenContractAddress baseCurrency workerContractAddress airdropBudgetHolder gasPrice chainId
-performer(process.argv);
diff --git a/tools/deploy/helper.js b/tools/deploy/helper.js
deleted file mode 100644
index fa9f67c..0000000
--- a/tools/deploy/helper.js
+++ /dev/null
@@ -1,217 +0,0 @@
-"use strict";
-
-/**
- * This is utility class for deploying contract
- *
- * Ref: {@link module:tools/deploy/DeployHelper}
- *
- * @module tools/deploy/helper
- */
-
-const rootPrefix = '../..'
- , coreConstants = require(rootPrefix + '/config/core_constants')
- , gasPrice = coreConstants.OST_VALUE_GAS_PRICE
- , gasLimit = coreConstants.OST_VALUE_GAS_LIMIT // this is taken by default if no value is passed from outside
- , coreAddresses = require(rootPrefix + '/config/core_addresses')
- , logger = require(rootPrefix + '/helpers/custom_console_logger')
- , web3EventsFormatter = require(rootPrefix + '/lib/web3/events/formatter')
- , populateEnvVars = require(rootPrefix + "/mocha_test/lib/populate_env_vars.js")
- , fs = require('fs')
- , Path = require('path');
-
-const _private = {
-
- /**
- * Wait for Transaction to be included in block
- *
- * @param {Web3} web3Provider - It could be value chain or utility chain provider
- * @param {String} transactionHash - Hash for which receipt is required.
- *
- * @return {Promise}
- */
- getReceipt: function (web3Provider, transactionHash) {
- return new Promise(function (onResolve, onReject) {
-
- var txSetInterval = null;
-
- var handleResponse = function (response) {
- if (response) {
- clearInterval(txSetInterval);
- onResolve(response);
- } else {
- logger.debug('Waiting for ' + transactionHash + ' to be included in block.');
- }
- };
-
- txSetInterval = setInterval(
- function () {
- web3Provider.eth.getTransactionReceipt(transactionHash).then(handleResponse);
- },
- 5000
- );
-
- });
- }
-
-};
-
-/**
- * Deploy Helper class to perform deploy
- *
- * @exports tools/deploy/DeployHelper
- */
-const deployHelper = {
-
- /**
- * Method deploys contract
- *
- * @param {String} contractName - Contract Name to be deployed
- * @param {Web3} web3Provider - Web3 Provider object
- * @param {String} contractAbi - Contract Abi to be deployed
- * @param {String} contractBin - Contract Bin file to be deployed
- * @param {String} deployerName - Deployer name
- * @param {Object} [customOptions] - Custom options for value/utility chain
- * @param {Object} [constructorArgs] - Arguments to be passed while deploying contract
- *
- * @async
- * @method perform
- * @return {Promise}
- *
- */
- perform: async function (contractName,
- web3Provider,
- contractAbi,
- contractBin,
- deployerName,
- customOptions,
- constructorArgs) {
-
- const deployerAddr = coreAddresses.getAddressForUser(deployerName)
- , deployerAddrPassphrase = coreAddresses.getPassphraseForUser(deployerName);
-
- var options = {
- from: deployerAddr,
- gas: gasLimit,
- data: (web3Provider.utils.isHexStrict(contractBin) ? "" : "0x") + contractBin,
- gasPrice: gasPrice
- };
-
- Object.assign(options, customOptions);
-
- if (constructorArgs) {
- options.arguments = constructorArgs;
- }
-
- var contract = new web3Provider.eth.Contract(
- contractAbi,
- null, // since addr is not known yet
- options
- );
- // this is needed since the contract object
- //contract.setProvider(web3Provider.currentProvider);
-
- const deploy = function () {
- const encodeABI = contract.deploy(options).encodeABI();
- options.data = encodeABI;
-
- return new Promise(function (onResolve, onReject) {
- web3Provider.eth.sendTransaction(options)
- .on('transactionHash', onResolve)
- .on('error', onReject);
- });
- };
-
- logger.debug("Unlocking address: " + deployerAddr);
- logger.debug("Unlocking!!!");
-
- logger.debug("deployerAddr: "+deployerAddr);
-
- await web3Provider.eth.personal.unlockAccount(deployerAddr, deployerAddrPassphrase);
-
- logger.debug("Deploying contract " + contractName);
-
- var deployFailedReason = null;
- const transactionReceipt = await deploy().then(
- function (transactionHash) {
- return _private.getReceipt(web3Provider, transactionHash);
- }
- ).catch(reason => {
- deployFailedReason = reason;
- logger.debug( deployFailedReason );
- return null;
- });
-
- if ( deployFailedReason ) {
- return Promise.reject( deployFailedReason );
- }
-
- logger.debug("deploy transactionReceipt ::", transactionReceipt);
-
- const contractAddress = transactionReceipt.contractAddress;
-
- const code = await web3Provider.eth.getCode(contractAddress);
-
- if (code.length <= 2) {
- return Promise.reject("Contract deployment failed. Invalid code length for contract: " + contractName);
- }
-
- // Print summary
- logger.debug("Contract Address: " + contractAddress);
- logger.debug("Gas used: " + transactionReceipt.gasUsed);
-
- return Promise.resolve({
- receipt: transactionReceipt,
- contractAddress: contractAddress
- });
- },
-
- assertEvent: async function (formattedTransactionReceipt, eventName) {
- var formattedEvents = await web3EventsFormatter.perform(formattedTransactionReceipt);
- var eventData = formattedEvents[eventName];
- if (eventData === undefined || eventData == '') {
- logger.error("Event: " + eventName + " is not found");
- logger.debug(" eventData ");
- logger.debug(eventData);
- process.exit(0);
- } else {
- logger.win(" event: " + eventName + " is present in Reciept.");
- }
- },
-
- updateEnvContractAddress: function (type, contractAddress) {
- return new Promise(
- function (onResolve, onReject) {
- logger.step("Updating Source file open_st_env_vars");
- populateEnvVars.renderAndPopulate(type, contractAddress);
- onResolve();
- })
- .then(function () {
- logger.win("set_env_vars.sh updated.");
- })
- .catch(function (reason) {
- logger.error("Failed to populate set_env_vars.sh file!");
- logger.error(reason);
- process.exit(1);
- });
- },
-
- /**
- * Write contract address to file based on parameter
- *
- * @param {String} fileName - file name
- * @param {Hex} contractAddress - contract Address
- *
- * @return {}
- */
- writeContractAddressToFile: function(fileName, contractAddress) {
- // Write contract address to file
- if ( fileName !== '') {
- logger.debug("Writing to file: ", fileName, "contract address: ", contractAddress);
- fs.writeFileSync(Path.join(__dirname, '/' + fileName), contractAddress);
- }
- }
-
-
-};
-
-module.exports = deployHelper;
diff --git a/tools/deploy/pricer.js b/tools/deploy/pricer.js
deleted file mode 100644
index 2c3bcb1..0000000
--- a/tools/deploy/pricer.js
+++ /dev/null
@@ -1,186 +0,0 @@
-/**
- * This is script for deploying Pricer contract on any chain.
- *
- * Prerequisite:
- *
- * Deployer Address
- *
- *
- * These are the following steps:
- *
- * Deploy Pricer contract
- *
- *
- *
- * @module tools/deploy/pricer
- */
-
-const readline = require('readline')
- , rootPrefix = '../..'
- , web3Provider = require(rootPrefix + '/lib/web3/providers/ws')
- , prompts = readline.createInterface(process.stdin, process.stdout)
- , logger = require(rootPrefix + '/helpers/custom_console_logger')
- , Deployer = require(rootPrefix + '/services/deploy/deployer')
- , coreAddresses = require(rootPrefix + '/config/core_addresses')
- , returnTypes = require(rootPrefix + "/lib/global_constant/return_types")
- , helper = require(rootPrefix + "/tools/deploy/helper")
- , openstPayment = require(rootPrefix + '/index')
- , SetOpsKlass = openstPayment.services.opsManaged.setOps
- , GetOpsKlass = openstPayment.services.opsManaged.getOps
- , gasLimitGlobalConstant = require(rootPrefix + '/lib/global_constant/gas_limit')
-;
-
-// Different addresses used for deployment
-const deployerName = "deployer"
- , deployerAddress = coreAddresses.getAddressForUser(deployerName)
- , deployerPassphrase = coreAddresses.getPassphraseForUser(deployerName)
-;
-
-// Set Ops Address
-const opsName = "ops"
- , opsAddress = coreAddresses.getAddressForUser(opsName)
-;
-
-
-/**
- * Validation Method
- *
- * @param {Array} arguments
- *
- * @return {}
- */
-function validate(argv) {
- if (!argv[2]) {
- logger.error("Mandatory Param is missing! ( brandedTokenAddress)");
- process.exit(0);
- }
-
- if (!argv[3]) {
- logger.error("Base currency is mandatory!");
- process.exit(0);
- }
- if (!argv[4]) {
- logger.error("Gas Price is mandatory!");
- process.exit(0);
- }
- if (!argv[5]) {
- logger.error("Chain Id is mandatory!");
- process.exit(0);
- }
-}
-
-/**
- * It is the main performer method of this deployment script
- *
- * @param {Array} arguments
- *
- * @return {}
- */
-async function performer(argv) {
-
- // logger.debug("argv[0]: " + argv[0]);
- // logger.debug("argv[1]: " + argv[1]);
- // logger.debug("argv[2]: " + argv[2]);
- // logger.debug("argv[3]: " + argv[3]);
- // logger.debug("argv[4]: " + argv[4]);
- // logger.debug("argv[5]: " + argv[5]);
- // logger.debug("argv[6]: " + argv[6]);
- // logger.debug("argv[7]: " + argv[7]);
-
- validate(argv);
- const brandedTokenAddress = argv[2].trim();
- const baseCurrency = argv[3].trim();
- const gasPrice = argv[4].trim();
- const chainId = argv[5].trim();
- var isTravisCIEnabled = false;
- if (argv[6] !== undefined) {
- isTravisCIEnabled = argv[6].trim() === 'travis';
- }
- const fileForContractAddress = (argv[7] !== undefined) ? argv[7].trim() : '';
-
- logger.debug("Branded Token Address: " + brandedTokenAddress);
- logger.debug("Base currency: " + baseCurrency);
- logger.debug("Gas price: " + gasPrice);
- logger.debug("Chain id: " + chainId);
- logger.debug("Travis CI enabled Status: " + isTravisCIEnabled);
- logger.debug("File to write For ContractAddress: "+fileForContractAddress);
- if (isTravisCIEnabled === false ) {
- await new Promise(
- function (onResolve, onReject) {
- prompts.question("Please verify all above details. Do you want to proceed? [Y/N]", function (intent) {
- if (intent === 'Y') {
- logger.debug('Great! Proceeding deployment.');
- prompts.close();
- onResolve();
- } else {
- logger.error('Exiting deployment scripts. Change the enviroment variables and re-run.');
- process.exit(1);
- }
- });
- }
- );
- } else {
- prompts.close();
- }
-
- const constructorArgs = [
- brandedTokenAddress,
- web3Provider.utils.asciiToHex(baseCurrency)
- ];
-
- const contractName = 'pricer'
- , deployOptions = {returnType: returnTypes.transactionReceipt()};
- ;
-
- const deployerInstance = new Deployer({
- contract_name: contractName,
- constructor_args: constructorArgs,
- gas_price: gasPrice,
- gas_limit: gasLimitGlobalConstant.default(),
- options: deployOptions
- });
- const deployResult = await deployerInstance.perform();
-
- if (deployResult.isSuccess()) {
-
- const contractAddress = deployResult.data.transaction_receipt.contractAddress;
- logger.win("contractAddress: " + contractAddress);
- if (fileForContractAddress !== '') {
- helper.writeContractAddressToFile(fileForContractAddress, contractAddress);
- }
-
- const setOpsOptions = {
- returnType: returnTypes.transactionReceipt(),
- tag: ''
- }
- logger.debug("Setting Ops Address to: " + opsAddress);
- const SetOpsObject = new SetOpsKlass({
- contract_address: contractAddress,
- gas_price: gasPrice,
- chain_id: chainId,
- deployer_address: deployerAddress,
- deployer_passphrase: deployerPassphrase,
- ops_address: opsAddress,
- options: setOpsOptions
- });
- var setOpsResult = await SetOpsObject.perform();
- logger.debug(setOpsResult);
-
- const GetOpsObject = new GetOpsKlass({
- contract_address: contractAddress,
- gas_price: gasPrice,
- chain_id: chainId
- });
- const getOpsResult = await GetOpsObject.perform();
- const contractOpsAddress = getOpsResult.data.opsAddress;
- logger.debug("Ops Address Set to: " + contractOpsAddress);
-
- } else {
- logger.error("Error deploying contract");
- logger.error(deployResult);
- }
-
- process.exit(0);
-}
-
-performer(process.argv);
diff --git a/tools/deploy/workers.js b/tools/deploy/workers.js
deleted file mode 100644
index 4f714f8..0000000
--- a/tools/deploy/workers.js
+++ /dev/null
@@ -1,93 +0,0 @@
-"use strict";
-
-/**
- * This is script for deploying Workers contract on any chain.
- *
- * Prerequisite:
- *
- * Deployer Address
- *
- *
- * These are the following steps:
- *
- * Deploy Workers contract
- *
- *
- *
- * @module tools/deploy/workers
- */
-
-const readline = require('readline')
- , rootPrefix = '../..'
- , prompts = readline.createInterface(process.stdin, process.stdout)
- , logger = require(rootPrefix + '/helpers/custom_console_logger')
- , helper = require(rootPrefix + "/tools/deploy/helper")
- , SetWorkerAndOpsKlass = require(rootPrefix + '/lib/set_worker_and_ops')
- , setWorkerOps = new SetWorkerAndOpsKlass()
-;
-
-/**
- * It is the main performer method of this deployment script
- *
- * Example:
- * node tools/deploy/worker.js gasPrice chainId
- *
- * @return {}
- */
-async function performer(argv) {
-
- if (!argv[2]) {
- logger.error("Gas Price is mandatory!");
- process.exit(0);
- }
- if (!argv[3]) {
- logger.error("chainId is mandatory!");
- process.exit(0);
- }
-
- const gasPrice = argv[2].trim()
- , chainId = argv[3].trim()
- ;
- var isTravisCIEnabled = false;
- if (argv[4] !== undefined) {
- isTravisCIEnabled = argv[4].trim() === 'travis';
- }
-
- const fileForContractAddress = (argv[5] !== undefined) ? argv[5].trim() : '';
-
- logger.debug("Gas price: " + gasPrice);
- logger.debug("chainId: " + chainId);
- logger.debug("Travis CI enabled Status: " + isTravisCIEnabled);
- logger.debug("File to write For ContractAddress: "+fileForContractAddress);
-
- if (isTravisCIEnabled === false ) {
- await new Promise(
- function (onResolve, onReject) {
- prompts.question("Please verify all above details. Do you want to proceed? [Y/N]", function (intent) {
- if (intent === 'Y') {
- logger.debug('Great! Proceeding deployment.');
- prompts.close();
- onResolve();
- } else {
- logger.error('Exiting deployment scripts. Change the enviroment variables and re-run.');
- process.exit(1);
- }
- });
- }
- );
- } else {
- prompts.close();
- }
-
- var response = await setWorkerOps.perform({gasPrice: gasPrice, chainId: chainId});
- logger.debug("**** Deployment Response", response);
- if (response.isSuccess() && fileForContractAddress !== '') {
- helper.writeContractAddressToFile(fileForContractAddress, response.data.workerContractAddress);
- }
-
- process.exit(0);
-
-}
-
-// node tools/deploy/workers.js gasPrice chainId
-performer(process.argv);
diff --git a/tools/dynamo_db_init.js b/tools/dynamo_db_init.js
deleted file mode 100644
index 179e782..0000000
--- a/tools/dynamo_db_init.js
+++ /dev/null
@@ -1,39 +0,0 @@
-"use strict";
-/**
- * Dynamo DB init
- *
- * @module tools/dynamo_db_init
- */
-const openSTStorage = require('@openstfoundation/openst-storage')
-;
-
-const rootPrefix = '..'
- , logger = require(rootPrefix + '/helpers/custom_console_logger')
- , ddbServiceObj = require(rootPrefix + '/lib/dynamo_db_service')
- , autoScalingServiceObj = require(rootPrefix + '/lib/auto_scaling_service')
-;
-
-/**
- * Dynamo db init
- *
- * @constructor
- */
-const DynamoDBInit = function () {};
-
-DynamoDBInit.prototype = {
- perform: async function () {
- // run migrations
- logger.info('* Running DynamoDB initial migrations for shard management.');
- let shardMgmtObj = ddbServiceObj.shardManagement();
- await shardMgmtObj.runShardMigration(ddbServiceObj, null);
-
- // createAndRegisterShard
- logger.info('* Creating and registering shard for token balance model.');
- await new openSTStorage.TokenBalanceModel({
- ddb_service: ddbServiceObj,
- auto_scaling: autoScalingServiceObj,
- }).createAndRegisterShard('tokenBalancesShard1')
- }
-};
-
-new DynamoDBInit().perform();
\ No newline at end of file
diff --git a/tools/runGanacheCli.sh b/tools/runGanacheCli.sh
new file mode 100755
index 0000000..a90aed2
--- /dev/null
+++ b/tools/runGanacheCli.sh
@@ -0,0 +1,5 @@
+#!/bin/bash
+ganache-cli \
+--accounts=100 \
+--defaultBalanceEther=100 \
+--gasLimit 0xfffffffffff
diff --git a/tools/runTestRpc.sh b/tools/runTestRpc.sh
deleted file mode 100644
index fad9494..0000000
--- a/tools/runTestRpc.sh
+++ /dev/null
@@ -1,2 +0,0 @@
-#!/bin/bash
-testrpc --account="0x8fbbbaceff30d4eea3e2ffa2dfedc3c053f78c1f53103e4ddc31309e6b1d5ea0,10000000000000000000000000000000" --account="0x8fbbbaceff30d4eea3e2ffa2dfedc3c053f78c1f53103e4ddc31309e6b1d5ea1,10000000000000000000000000000000" --account="0x8fbbbaceff30d4eea3e2ffa2dfedc3c053f78c1f53103e4ddc31309e6b1d5ea2,10000000000000000000000000000000" --account="0x8fbbbaceff30d4eea3e2ffa2dfedc3c053f78c1f53103e4ddc31309e6b1d5ea3,10000000000000000000000000000000" --account="0x8fbbbaceff30d4eea3e2ffa2dfedc3c053f78c1f53103e4ddc31309e6b1d5ea4,10000000000000000000000000000000" --account="0x8fbbbaceff30d4eea3e2ffa2dfedc3c053f78c1f53103e4ddc31309e6b1d5ea5,10000000000000000000000000000000" --account="0x8fbbbaceff30d4eea3e2ffa2dfedc3c053f78c1f53103e4ddc31309e6b1d5ea6,10000000000000000000000000000000" --account="0x8fbbbaceff30d4eea3e2ffa2dfedc3c053f78c1f53103e4ddc31309e6b1d5ea7,10000000000000000000000000000000" --account="0x8fbbbaceff30d4eea3e2ffa2dfedc3c053f78c1f53103e4ddc31309e6b1d5ea8,10000000000000000000000000000000" --account="0x8fbbbaceff30d4eea3e2ffa2dfedc3c053f78c1f53103e4ddc31309e6b1d5ea9,0" --account="0x8fbbbaceff30d4eea3e2ffa2dfedc3c053f78c1f53103e4ddc31309e6b1d5eb0,10000000000000000000000000000000" --account="0x8fbbbaceff30d4eea3e2ffa2dfedc3c053f78c1f53103e4ddc31309e6b1d5eb1,10000000000000000000000000000000" --account="0x8fbbbaceff30d4eea3e2ffa2dfedc3c053f78c1f53103e4ddc31309e6b1d5eb2,10000000000000000000000000000000" --account="0x8fbbbaceff30d4eea3e2ffa2dfedc3c053f78c1f53103e4ddc31309e6b1d5eb3,10000000000000000000000000000000" --account="0x8fbbbaceff30d4eea3e2ffa2dfedc3c053f78c1f53103e4ddc31309e6b1d5eb4,10000000000000000000000000000000" --account="0x8fbbbaceff30d4eea3e2ffa2dfedc3c053f78c1f53103e4ddc31309e6b1d5eb5,10000000000000000000000000000000" --account="0x8fbbbaceff30d4eea3e2ffa2dfedc3c053f78c1f53103e4ddc31309e6b1d5eb6,10000000000000000000000000000000" --account="0x8fbbbaceff30d4eea3e2ffa2dfedc3c053f78c1f53103e4ddc31309e6b1d5eb7,10000000000000000000000000000000" --account="0x8fbbbaceff30d4eea3e2ffa2dfedc3c053f78c1f53103e4ddc31309e6b1d5eb8,10000000000000000000000000000000" --account="0x8fbbbaceff30d4eea3e2ffa2dfedc3c053f78c1f53103e4ddc31309e6b1d5eb9,10000000000000000000000000000000" --gasLimit 12000000
diff --git a/truffle-config.js b/truffle-config.js
deleted file mode 100644
index a6330d6..0000000
--- a/truffle-config.js
+++ /dev/null
@@ -1,4 +0,0 @@
-module.exports = {
- // See
- // to customize your Truffle configuration!
-};
diff --git a/truffle.js b/truffle.js
index 2083abb..4842a17 100644
--- a/truffle.js
+++ b/truffle.js
@@ -1,18 +1,27 @@
module.exports = {
- networks: {
- development: {
- host: "localhost",
- port: 8545,
- network_id: "*" // Match any network id
- }
- },
- solc: {
- optimizer: {
- enabled: true,
- // set to same number of runs as openst-platform
- // so that integration tests on openst-protocol
- // give accurate gas measurements
- runs: 200
- }
- }
+ networks: {
+ development: {
+ host: 'localhost',
+ network_id: '*',
+ port: 8545,
+ gas: 12000000,
+ gasPrice: 0x01,
+ },
+ },
+ coverage: {
+ host: 'localhost',
+ network_id: '*',
+ port: 8555, // <-- If you change this, also set the port option in .solcover.js.
+ gas: 0xfffffffffff, // <-- Use this high gas value
+ gasPrice: 0x01, // <-- Use this low gas price
+ },
+ solc: {
+ optimizer: {
+ enabled: true,
+ // set to same number of runs as openst-platform
+ // so that integration tests
+ // give accurate gas measurements
+ runs: 200,
+ },
+ },
};