Organizing scripts: floBlockchainAPI v2.2.0

- converted XMLHttpRequest to fetch request
This commit is contained in:
sairajzero 2022-02-27 20:38:14 +05:30
parent 3cb6c3f60c
commit 10fa130229

View File

@ -6637,8 +6637,8 @@
</script> </script>
<script id="floCrypto" version="2.2.0"> <script id="floCrypto" version="2.2.0">
/* FLO Crypto Operators*/
'use strict'; 'use strict';
(function(GLOBAL) { (function(GLOBAL) {
const floCrypto = GLOBAL.floCrypto = { const floCrypto = GLOBAL.floCrypto = {
@ -6977,442 +6977,441 @@
})(typeof global !== "undefined" ? global : window); })(typeof global !== "undefined" ? global : window);
</script> </script>
<script id="floBlockchainAPI" version="2.1.1a"> <script id="floBlockchainAPI" version="2.2.0">
/* FLO Blockchain Operator to send/receive data from blockchain using API calls*/ /* FLO Blockchain Operator to send/receive data from blockchain using API calls*/
const floBlockchainAPI = { 'use strict';
(function(GLOBAL) {
const floBlockchainAPI = GLOBAL.floBlockchainAPI = {
util: { util: {
serverList: floGlobals.apiURL[floGlobals.blockchain].slice(0), serverList: floGlobals.apiURL[floGlobals.blockchain].slice(0),
curPos: floCrypto.randInt(0, floGlobals.apiURL[floGlobals.blockchain].length - 1), curPos: floCrypto.randInt(0, floGlobals.apiURL[floGlobals.blockchain].length - 1),
fetch_retry: function(apicall, rm_flosight) { fetch_retry: function(apicall, rm_flosight) {
return new Promise((resolve, reject) => { return new Promise((resolve, reject) => {
let i = this.serverList.indexOf(rm_flosight) let i = this.serverList.indexOf(rm_flosight)
if (i != -1) this.serverList.splice(i, 1); if (i != -1) this.serverList.splice(i, 1);
this.curPos = floCrypto.randInt(0, this.serverList.length - 1); this.curPos = floCrypto.randInt(0, this.serverList.length - 1);
this.fetch_api(apicall) this.fetch_api(apicall)
.then(result => resolve(result)) .then(result => resolve(result))
.catch(error => reject(error)); .catch(error => reject(error));
}) })
}, },
fetch_api: function(apicall) { fetch_api: function(apicall) {
return new Promise((resolve, reject) => { return new Promise((resolve, reject) => {
if (this.serverList.length === 0) if (this.serverList.length === 0)
reject("No floSight server working"); reject("No floSight server working");
else { else {
let flosight = this.serverList[this.curPos]; let flosight = this.serverList[this.curPos];
fetch(flosight + apicall).then(response => { fetch(flosight + apicall).then(response => {
if (response.ok) if (response.ok)
response.json().then(data => resolve(data)); response.json().then(data => resolve(data));
else { else {
this.fetch_retry(apicall, flosight)
.then(result => resolve(result))
.catch(error => reject(error));
}
}).catch(error => {
this.fetch_retry(apicall, flosight) this.fetch_retry(apicall, flosight)
.then(result => resolve(result)) .then(result => resolve(result))
.catch(error => reject(error)); .catch(error => reject(error));
} })
}).catch(error => { }
this.fetch_retry(apicall, flosight) })
.then(result => resolve(result)) },
.catch(error => reject(error));
}) current: function() {
} return this.serverList[this.curPos];
}) }
}, },
current: function() { //Promised function to get data from API
return this.serverList[this.curPos]; promisedAPI: function(apicall) {
} return new Promise((resolve, reject) => {
}, //console.log(apicall);
this.util.fetch_api(apicall)
.then(result => resolve(result))
.catch(error => reject(error));
});
},
//Promised function to get data from API //Get balance for the given Address
promisedAPI: function(apicall) { getBalance: function(addr) {
return new Promise((resolve, reject) => { return new Promise((resolve, reject) => {
//console.log(apicall); this.promisedAPI(`api/addr/${addr}/balance`)
this.util.fetch_api(apicall) .then(balance => resolve(parseFloat(balance)))
.then(result => resolve(result)) .catch(error => reject(error));
.catch(error => reject(error)); });
}); },
},
//Get balance for the given Address //Write Data into blockchain
getBalance: function(addr) { writeData: function(senderAddr, data, privKey, receiverAddr = floGlobals.adminID, strict_utxo = true) {
return new Promise((resolve, reject) => { return new Promise((resolve, reject) => {
this.promisedAPI(`api/addr/${addr}/balance`) if (typeof data != "string")
.then(balance => resolve(parseFloat(balance))) data = JSON.stringify(data);
.catch(error => reject(error)); this.sendTx(senderAddr, receiverAddr, floGlobals.sendAmt, privKey, data, strict_utxo)
}); .then(txid => resolve(txid))
}, .catch(error => reject(error));
});
},
//Write Data into blockchain //Send Tx to blockchain
writeData: function(senderAddr, data, privKey, receiverAddr = floGlobals.adminID, strict_utxo = true) { sendTx: function(senderAddr, receiverAddr, sendAmt, privKey, floData = '', strict_utxo = true) {
return new Promise((resolve, reject) => { return new Promise((resolve, reject) => {
if (typeof data != "string") if (!floCrypto.validateASCII(floData))
data = JSON.stringify(data); return reject("Invalid FLO_Data: only printable ASCII characters are allowed");
this.sendTx(senderAddr, receiverAddr, floGlobals.sendAmt, privKey, data, strict_utxo) else if (!floCrypto.validateAddr(senderAddr))
.then(txid => resolve(txid)) return reject(`Invalid address : ${senderAddr}`);
.catch(error => reject(error)); else if (!floCrypto.validateAddr(receiverAddr))
}); return reject(`Invalid address : ${receiverAddr}`);
}, else if (privKey.length < 1 || !floCrypto.verifyPrivKey(privKey, senderAddr))
return reject("Invalid Private key!");
else if (typeof sendAmt !== 'number' || sendAmt <= 0)
return reject(`Invalid sendAmt : ${sendAmt}`);
//Send Tx to blockchain //get unconfirmed tx list
sendTx: function(senderAddr, receiverAddr, sendAmt, privKey, floData = '', strict_utxo = true) { this.promisedAPI(`api/addr/${senderAddr}`).then(result => {
return new Promise((resolve, reject) => { this.readTxs(senderAddr, 0, result.unconfirmedTxApperances).then(result => {
if (!floCrypto.validateASCII(floData)) let unconfirmedSpent = {};
return reject("Invalid FLO_Data: only printable ASCII characters are allowed"); for (let tx of result.items)
else if (!floCrypto.validateAddr(senderAddr)) if (tx.confirmations == 0)
return reject(`Invalid address : ${senderAddr}`); for (let vin of tx.vin)
else if (!floCrypto.validateAddr(receiverAddr)) if (vin.addr === senderAddr) {
return reject(`Invalid address : ${receiverAddr}`); if (Array.isArray(unconfirmedSpent[vin.txid]))
else if (privKey.length < 1 || !floCrypto.verifyPrivKey(privKey, senderAddr)) unconfirmedSpent[vin.txid].push(vin.vout);
return reject("Invalid Private key!"); else
else if (typeof sendAmt !== 'number' || sendAmt <= 0) unconfirmedSpent[vin.txid] = [vin.vout];
return reject(`Invalid sendAmt : ${sendAmt}`); }
//get utxos list
//get unconfirmed tx list this.promisedAPI(`api/addr/${senderAddr}/utxo`).then(utxos => {
this.promisedAPI(`api/addr/${senderAddr}`).then(result => { //form/construct the transaction data
this.readTxs(senderAddr, 0, result.unconfirmedTxApperances).then(result => { var trx = bitjs.transaction();
let unconfirmedSpent = {}; var utxoAmt = 0.0;
for (let tx of result.items) var fee = floGlobals.fee;
if (tx.confirmations == 0) for (var i = utxos.length - 1;
for (let vin of tx.vin) (i >= 0) && (utxoAmt < sendAmt + fee); i--) {
if (vin.addr === senderAddr) { //use only utxos with confirmations (strict_utxo mode)
if (Array.isArray(unconfirmedSpent[vin.txid])) if (utxos[i].confirmations || !strict_utxo) {
unconfirmedSpent[vin.txid].push(vin.vout); if (utxos[i].txid in unconfirmedSpent && unconfirmedSpent[utxos[i].txid].includes(utxos[i].vout))
else continue; //A transaction has already used this utxo, but is unconfirmed.
unconfirmedSpent[vin.txid] = [vin.vout]; trx.addinput(utxos[i].txid, utxos[i].vout, utxos[i].scriptPubKey);
} utxoAmt += utxos[i].amount;
//get utxos list };
this.promisedAPI(`api/addr/${senderAddr}/utxo`).then(utxos => { }
//form/construct the transaction data if (utxoAmt < sendAmt + fee)
var trx = bitjs.transaction(); reject("Insufficient FLO balance!");
var utxoAmt = 0.0; else {
var fee = floGlobals.fee; trx.addoutput(receiverAddr, sendAmt);
for (var i = utxos.length - 1; var change = utxoAmt - sendAmt - fee;
(i >= 0) && (utxoAmt < sendAmt + fee); i--) { if (change > 0)
//use only utxos with confirmations (strict_utxo mode) trx.addoutput(senderAddr, change);
if (utxos[i].confirmations || !strict_utxo) { trx.addflodata(floData.replace(/\n/g, ' '));
if (utxos[i].txid in unconfirmedSpent && unconfirmedSpent[utxos[i].txid].includes(utxos[i].vout)) var signedTxHash = trx.sign(privKey, 1);
continue; //A transaction has already used this utxo, but is unconfirmed. this.broadcastTx(signedTxHash)
trx.addinput(utxos[i].txid, utxos[i].vout, utxos[i].scriptPubKey); .then(txid => resolve(txid))
utxoAmt += utxos[i].amount; .catch(error => reject(error))
}; }
} }).catch(error => reject(error))
if (utxoAmt < sendAmt + fee)
reject("Insufficient FLO balance!");
else {
trx.addoutput(receiverAddr, sendAmt);
var change = utxoAmt - sendAmt - fee;
if (change > 0)
trx.addoutput(senderAddr, change);
trx.addflodata(floData.replace(/\n/g, ' '));
var signedTxHash = trx.sign(privKey, 1);
this.broadcastTx(signedTxHash)
.then(txid => resolve(txid))
.catch(error => reject(error))
}
}).catch(error => reject(error)) }).catch(error => reject(error))
}).catch(error => reject(error)) }).catch(error => reject(error))
}).catch(error => reject(error)) });
}); },
},
//merge all UTXOs of a given floID into a single UTXO //merge all UTXOs of a given floID into a single UTXO
mergeUTXOs: function(floID, privKey, floData = '') { mergeUTXOs: function(floID, privKey, floData = '') {
return new Promise((resolve, reject) => { return new Promise((resolve, reject) => {
if (!floCrypto.validateAddr(floID)) if (!floCrypto.validateAddr(floID))
return reject(`Invalid floID`); return reject(`Invalid floID`);
if (!floCrypto.verifyPrivKey(privKey, floID)) if (!floCrypto.verifyPrivKey(privKey, floID))
return reject("Invalid Private Key"); return reject("Invalid Private Key");
if (!floCrypto.validateASCII(floData)) if (!floCrypto.validateASCII(floData))
return reject("Invalid FLO_Data: only printable ASCII characters are allowed"); return reject("Invalid FLO_Data: only printable ASCII characters are allowed");
var trx = bitjs.transaction(); var trx = bitjs.transaction();
var utxoAmt = 0.0; var utxoAmt = 0.0;
var fee = floGlobals.fee; var fee = floGlobals.fee;
this.promisedAPI(`api/addr/${floID}/utxo`).then(utxos => { this.promisedAPI(`api/addr/${floID}/utxo`).then(utxos => {
for (var i = utxos.length - 1; i >= 0; i--) for (var i = utxos.length - 1; i >= 0; i--)
if (utxos[i].confirmations) { if (utxos[i].confirmations) {
trx.addinput(utxos[i].txid, utxos[i].vout, utxos[i].scriptPubKey); trx.addinput(utxos[i].txid, utxos[i].vout, utxos[i].scriptPubKey);
utxoAmt += utxos[i].amount; utxoAmt += utxos[i].amount;
}
trx.addoutput(floID, utxoAmt - fee);
trx.addflodata(floData.replace(/\n/g, ' '));
var signedTxHash = trx.sign(privKey, 1);
this.broadcastTx(signedTxHash)
.then(txid => resolve(txid))
.catch(error => reject(error))
}).catch(error => reject(error))
})
},
/**Write data into blockchain from (and/or) to multiple floID
* @param {Array} senderPrivKeys List of sender private-keys
* @param {string} data FLO data of the txn
* @param {Array} receivers List of receivers
* @param {boolean} preserveRatio (optional) preserve ratio or equal contribution
* @return {Promise}
*/
writeDataMultiple: function(senderPrivKeys, data, receivers = [floGlobals.adminID], preserveRatio = true) {
return new Promise((resolve, reject) => {
if (!Array.isArray(senderPrivKeys))
return reject("Invalid senderPrivKeys: SenderPrivKeys must be Array");
if (!preserveRatio) {
let tmp = {};
let amount = (floGlobals.sendAmt * receivers.length) / senderPrivKeys.length;
senderPrivKeys.forEach(key => tmp[key] = amount);
senderPrivKeys = tmp;
}
if (!Array.isArray(receivers))
return reject("Invalid receivers: Receivers must be Array");
else {
let tmp = {};
let amount = floGlobals.sendAmt;
receivers.forEach(floID => tmp[floID] = amount);
receivers = tmp
}
if (typeof data != "string")
data = JSON.stringify(data);
this.sendTxMultiple(senderPrivKeys, receivers, data)
.then(txid => resolve(txid))
.catch(error => reject(error))
})
},
/**Send Tx from (and/or) to multiple floID
* @param {Array or Object} senderPrivKeys List of sender private-key (optional: with coins to be sent)
* @param {Object} receivers List of receivers with respective amount to be sent
* @param {string} floData FLO data of the txn
* @return {Promise}
*/
sendTxMultiple: function(senderPrivKeys, receivers, floData = '') {
return new Promise((resolve, reject) => {
if (!floCrypto.validateASCII(floData))
return reject("Invalid FLO_Data: only printable ASCII characters are allowed");
let senders = {},
preserveRatio;
//check for argument validations
try {
let invalids = {
InvalidSenderPrivKeys: [],
InvalidSenderAmountFor: [],
InvalidReceiverIDs: [],
InvalidReceiveAmountFor: []
}
let inputVal = 0,
outputVal = 0;
//Validate sender privatekeys (and send amount if passed)
//conversion when only privateKeys are passed (preserveRatio mode)
if (Array.isArray(senderPrivKeys)) {
senderPrivKeys.forEach(key => {
try {
if (!key)
invalids.InvalidSenderPrivKeys.push(key);
else {
let floID = floCrypto.getFloID(key);
senders[floID] = {
wif: key
}
}
} catch (error) {
invalids.InvalidSenderPrivKeys.push(key)
} }
}) trx.addoutput(floID, utxoAmt - fee);
preserveRatio = true;
}
//conversion when privatekeys are passed with send amount
else {
for (let key in senderPrivKeys) {
try {
if (!key)
invalids.InvalidSenderPrivKeys.push(key);
else {
if (typeof senderPrivKeys[key] !== 'number' || senderPrivKeys[key] <= 0)
invalids.InvalidSenderAmountFor.push(key);
else
inputVal += senderPrivKeys[key];
let floID = floCrypto.getFloID(key);
senders[floID] = {
wif: key,
coins: senderPrivKeys[key]
}
}
} catch (error) {
invalids.InvalidSenderPrivKeys.push(key)
}
}
preserveRatio = false;
}
//Validate the receiver IDs and receive amount
for (let floID in receivers) {
if (!floCrypto.validateAddr(floID))
invalids.InvalidReceiverIDs.push(floID);
if (typeof receivers[floID] !== 'number' || receivers[floID] <= 0)
invalids.InvalidReceiveAmountFor.push(floID);
else
outputVal += receivers[floID];
}
//Reject if any invalids are found
for (let i in invalids)
if (!invalids[i].length)
delete invalids[i];
if (Object.keys(invalids).length)
return reject(invalids);
//Reject if given inputVal and outputVal are not equal
if (!preserveRatio && inputVal != outputVal)
return reject(`Input Amount (${inputVal}) not equal to Output Amount (${outputVal})`);
} catch (error) {
return reject(error)
}
//Get balance of senders
let promises = [];
for (let floID in senders)
promises.push(this.getBalance(floID));
Promise.all(promises).then(results => {
let totalBalance = 0,
totalFee = floGlobals.fee,
balance = {};
//Divide fee among sender if not for preserveRatio
if (!preserveRatio)
var dividedFee = totalFee / Object.keys(senders).length;
//Check if balance of each sender is sufficient enough
let insufficient = [];
for (let floID in senders) {
balance[floID] = parseFloat(results.shift());
if (isNaN(balance[floID]) || (preserveRatio && balance[floID] <= totalFee) ||
(!preserveRatio && balance[floID] < senders[floID].coins + dividedFee))
insufficient.push(floID);
totalBalance += balance[floID];
}
if (insufficient.length)
return reject({
InsufficientBalance: insufficient
})
//Calculate totalSentAmount and check if totalBalance is sufficient
let totalSendAmt = totalFee;
for (floID in receivers)
totalSendAmt += receivers[floID];
if (totalBalance < totalSendAmt)
return reject("Insufficient total Balance");
//Get the UTXOs of the senders
let promises = [];
for (floID in senders)
promises.push(this.promisedAPI(`api/addr/${floID}/utxo`));
Promise.all(promises).then(results => {
let wifSeq = [];
var trx = bitjs.transaction();
for (floID in senders) {
let utxos = results.shift();
let sendAmt;
if (preserveRatio) {
let ratio = (balance[floID] / totalBalance);
sendAmt = totalSendAmt * ratio;
} else
sendAmt = senders[floID].coins + dividedFee;
let wif = senders[floID].wif;
let utxoAmt = 0.0;
for (let i = utxos.length - 1;
(i >= 0) && (utxoAmt < sendAmt); i--) {
if (utxos[i].confirmations) {
trx.addinput(utxos[i].txid, utxos[i].vout, utxos[i].scriptPubKey);
wifSeq.push(wif);
utxoAmt += utxos[i].amount;
}
}
if (utxoAmt < sendAmt)
return reject("Insufficient balance:" + floID);
let change = (utxoAmt - sendAmt);
if (change > 0)
trx.addoutput(floID, change);
}
for (floID in receivers)
trx.addoutput(floID, receivers[floID]);
trx.addflodata(floData.replace(/\n/g, ' ')); trx.addflodata(floData.replace(/\n/g, ' '));
for (let i = 0; i < wifSeq.length; i++) var signedTxHash = trx.sign(privKey, 1);
trx.signinput(i, wifSeq[i], 1);
var signedTxHash = trx.serialize();
this.broadcastTx(signedTxHash) this.broadcastTx(signedTxHash)
.then(txid => resolve(txid)) .then(txid => resolve(txid))
.catch(error => reject(error)) .catch(error => reject(error))
}).catch(error => reject(error)) }).catch(error => reject(error))
}).catch(error => reject(error)) })
}) },
},
//Broadcast signed Tx in blockchain using API /**Write data into blockchain from (and/or) to multiple floID
broadcastTx: function(signedTxHash) { * @param {Array} senderPrivKeys List of sender private-keys
return new Promise((resolve, reject) => { * @param {string} data FLO data of the txn
var request = new XMLHttpRequest(); * @param {Array} receivers List of receivers
var url = this.util.serverList[this.util.curPos] + 'api/tx/send'; * @param {boolean} preserveRatio (optional) preserve ratio or equal contribution
console.log(url); * @return {Promise}
if (signedTxHash.length < 1) */
reject("Empty Signature"); writeDataMultiple: function(senderPrivKeys, data, receivers = [floGlobals.adminID], preserveRatio = true) {
else { return new Promise((resolve, reject) => {
var params = `{"rawtx":"${signedTxHash}"}`; if (!Array.isArray(senderPrivKeys))
request.open('POST', url, true); return reject("Invalid senderPrivKeys: SenderPrivKeys must be Array");
//Send the proper header information along with the request if (!preserveRatio) {
request.setRequestHeader('Content-type', 'application/json'); let tmp = {};
request.onload = function() { let amount = (floGlobals.sendAmt * receivers.length) / senderPrivKeys.length;
if (request.readyState == 4 && request.status == 200) { senderPrivKeys.forEach(key => tmp[key] = amount);
console.log(request.response); senderPrivKeys = tmp;
resolve(JSON.parse(request.response).txid.result);
} else
reject(request.responseText);
} }
request.send(params); if (!Array.isArray(receivers))
} return reject("Invalid receivers: Receivers must be Array");
}) else {
}, let tmp = {};
let amount = floGlobals.sendAmt;
receivers.forEach(floID => tmp[floID] = amount);
receivers = tmp
}
if (typeof data != "string")
data = JSON.stringify(data);
this.sendTxMultiple(senderPrivKeys, receivers, data)
.then(txid => resolve(txid))
.catch(error => reject(error))
})
},
getTx: function(txid) { /**Send Tx from (and/or) to multiple floID
return new Promise((resolve, reject) => { * @param {Array or Object} senderPrivKeys List of sender private-key (optional: with coins to be sent)
this.promisedAPI(`api/tx/${txid}`) * @param {Object} receivers List of receivers with respective amount to be sent
.then(response => resolve(response)) * @param {string} floData FLO data of the txn
.catch(error => reject(error)) * @return {Promise}
}) */
}, sendTxMultiple: function(senderPrivKeys, receivers, floData = '') {
return new Promise((resolve, reject) => {
if (!floCrypto.validateASCII(floData))
return reject("Invalid FLO_Data: only printable ASCII characters are allowed");
let senders = {},
preserveRatio;
//check for argument validations
try {
let invalids = {
InvalidSenderPrivKeys: [],
InvalidSenderAmountFor: [],
InvalidReceiverIDs: [],
InvalidReceiveAmountFor: []
}
let inputVal = 0,
outputVal = 0;
//Validate sender privatekeys (and send amount if passed)
//conversion when only privateKeys are passed (preserveRatio mode)
if (Array.isArray(senderPrivKeys)) {
senderPrivKeys.forEach(key => {
try {
if (!key)
invalids.InvalidSenderPrivKeys.push(key);
else {
let floID = floCrypto.getFloID(key);
senders[floID] = {
wif: key
}
}
} catch (error) {
invalids.InvalidSenderPrivKeys.push(key)
}
})
preserveRatio = true;
}
//conversion when privatekeys are passed with send amount
else {
for (let key in senderPrivKeys) {
try {
if (!key)
invalids.InvalidSenderPrivKeys.push(key);
else {
if (typeof senderPrivKeys[key] !== 'number' || senderPrivKeys[key] <= 0)
invalids.InvalidSenderAmountFor.push(key);
else
inputVal += senderPrivKeys[key];
let floID = floCrypto.getFloID(key);
senders[floID] = {
wif: key,
coins: senderPrivKeys[key]
}
}
} catch (error) {
invalids.InvalidSenderPrivKeys.push(key)
}
}
preserveRatio = false;
}
//Validate the receiver IDs and receive amount
for (let floID in receivers) {
if (!floCrypto.validateAddr(floID))
invalids.InvalidReceiverIDs.push(floID);
if (typeof receivers[floID] !== 'number' || receivers[floID] <= 0)
invalids.InvalidReceiveAmountFor.push(floID);
else
outputVal += receivers[floID];
}
//Reject if any invalids are found
for (let i in invalids)
if (!invalids[i].length)
delete invalids[i];
if (Object.keys(invalids).length)
return reject(invalids);
//Reject if given inputVal and outputVal are not equal
if (!preserveRatio && inputVal != outputVal)
return reject(`Input Amount (${inputVal}) not equal to Output Amount (${outputVal})`);
} catch (error) {
return reject(error)
}
//Get balance of senders
let promises = [];
for (let floID in senders)
promises.push(this.getBalance(floID));
Promise.all(promises).then(results => {
let totalBalance = 0,
totalFee = floGlobals.fee,
balance = {};
//Divide fee among sender if not for preserveRatio
if (!preserveRatio)
var dividedFee = totalFee / Object.keys(senders).length;
//Check if balance of each sender is sufficient enough
let insufficient = [];
for (let floID in senders) {
balance[floID] = parseFloat(results.shift());
if (isNaN(balance[floID]) || (preserveRatio && balance[floID] <= totalFee) ||
(!preserveRatio && balance[floID] < senders[floID].coins + dividedFee))
insufficient.push(floID);
totalBalance += balance[floID];
}
if (insufficient.length)
return reject({
InsufficientBalance: insufficient
})
//Calculate totalSentAmount and check if totalBalance is sufficient
let totalSendAmt = totalFee;
for (floID in receivers)
totalSendAmt += receivers[floID];
if (totalBalance < totalSendAmt)
return reject("Insufficient total Balance");
//Get the UTXOs of the senders
let promises = [];
for (floID in senders)
promises.push(this.promisedAPI(`api/addr/${floID}/utxo`));
Promise.all(promises).then(results => {
let wifSeq = [];
var trx = bitjs.transaction();
for (floID in senders) {
let utxos = results.shift();
let sendAmt;
if (preserveRatio) {
let ratio = (balance[floID] / totalBalance);
sendAmt = totalSendAmt * ratio;
} else
sendAmt = senders[floID].coins + dividedFee;
let wif = senders[floID].wif;
let utxoAmt = 0.0;
for (let i = utxos.length - 1;
(i >= 0) && (utxoAmt < sendAmt); i--) {
if (utxos[i].confirmations) {
trx.addinput(utxos[i].txid, utxos[i].vout, utxos[i].scriptPubKey);
wifSeq.push(wif);
utxoAmt += utxos[i].amount;
}
}
if (utxoAmt < sendAmt)
return reject("Insufficient balance:" + floID);
let change = (utxoAmt - sendAmt);
if (change > 0)
trx.addoutput(floID, change);
}
for (floID in receivers)
trx.addoutput(floID, receivers[floID]);
trx.addflodata(floData.replace(/\n/g, ' '));
for (let i = 0; i < wifSeq.length; i++)
trx.signinput(i, wifSeq[i], 1);
var signedTxHash = trx.serialize();
this.broadcastTx(signedTxHash)
.then(txid => resolve(txid))
.catch(error => reject(error))
}).catch(error => reject(error))
}).catch(error => reject(error))
})
},
//Read Txs of Address between from and to //Broadcast signed Tx in blockchain using API
readTxs: function(addr, from, to) { broadcastTx: function(signedTxHash) {
return new Promise((resolve, reject) => { return new Promise((resolve, reject) => {
this.promisedAPI(`api/addrs/${addr}/txs?from=${from}&to=${to}`) if (signedTxHash.length < 1)
.then(response => resolve(response)) return reject("Empty Signature");
.catch(error => reject(error)) var url = this.util.serverList[this.util.curPos] + 'api/tx/send';
}); fetch(url, {
}, method: "POST",
headers: {
'Content-Type': 'application/json'
},
body: `{"rawtx":"${signedTxHash}"}`
}).then(response => {
if (response.ok)
response.json().then(data => resolve(data.txid.result));
else
response.text().then(data => resolve(data));
}).catch(error => reject(error));
})
},
//Read All Txs of Address (newest first) getTx: function(txid) {
readAllTxs: function(addr) { return new Promise((resolve, reject) => {
return new Promise((resolve, reject) => { this.promisedAPI(`api/tx/${txid}`)
this.promisedAPI(`api/addrs/${addr}/txs?from=0&to=1`).then(response => { .then(response => resolve(response))
this.promisedAPI(`api/addrs/${addr}/txs?from=0&to=${response.totalItems}0`) .catch(error => reject(error))
.then(response => resolve(response.items)) })
.catch(error => reject(error)); },
}).catch(error => reject(error))
});
},
/*Read flo Data from txs of given Address //Read Txs of Address between from and to
options can be used to filter data readTxs: function(addr, from, to) {
limit : maximum number of filtered data (default = 1000, negative = no limit) return new Promise((resolve, reject) => {
ignoreOld : ignore old txs (default = 0) this.promisedAPI(`api/addrs/${addr}/txs?from=${from}&to=${to}`)
sentOnly : filters only sent data .then(response => resolve(response))
receivedOnly: filters only received data .catch(error => reject(error))
pattern : filters data that with JSON pattern });
filter : custom filter funtion for floData (eg . filter: d => {return d[0] == '$'}) },
tx : (boolean) resolve tx data or not (resolves an Array of Object with tx details)
sender : flo-id(s) of sender //Read All Txs of Address (newest first)
receiver : flo-id(s) of receiver readAllTxs: function(addr) {
*/ return new Promise((resolve, reject) => {
readData: function(addr, options = {}) { this.promisedAPI(`api/addrs/${addr}/txs?from=0&to=1`).then(response => {
options.limit = options.limit || 0; this.promisedAPI(`api/addrs/${addr}/txs?from=0&to=${response.totalItems}0`)
options.ignoreOld = options.ignoreOld || 0; .then(response => resolve(response.items))
if (typeof options.sender === "string") options.sender = [options.sender]; .catch(error => reject(error));
if (typeof options.receiver === "string") options.receiver = [options.receiver]; }).catch(error => reject(error))
return new Promise((resolve, reject) => { });
this.promisedAPI(`api/addrs/${addr}/txs?from=0&to=1`).then(response => { },
var newItems = response.totalItems - options.ignoreOld;
this.promisedAPI(`api/addrs/${addr}/txs?from=0&to=${newItems*2}`).then(response => { /*Read flo Data from txs of given Address
options can be used to filter data
limit : maximum number of filtered data (default = 1000, negative = no limit)
ignoreOld : ignore old txs (default = 0)
sentOnly : filters only sent data
receivedOnly: filters only received data
pattern : filters data that with JSON pattern
filter : custom filter funtion for floData (eg . filter: d => {return d[0] == '$'})
tx : (boolean) resolve tx data or not (resolves an Array of Object with tx details)
sender : flo-id(s) of sender
receiver : flo-id(s) of receiver
*/
readData: function(addr, options = {}) {
options.limit = options.limit || 0;
options.ignoreOld = options.ignoreOld || 0;
if (typeof options.sender === "string") options.sender = [options.sender];
if (typeof options.receiver === "string") options.receiver = [options.receiver];
return new Promise((resolve, reject) => {
this.promisedAPI(`api/addrs/${addr}/txs?from=0&to=1`).then(response => {
var newItems = response.totalItems - options.ignoreOld;
this.promisedAPI(`api/addrs/${addr}/txs?from=0&to=${newItems*2}`).then(response => {
if (options.limit <= 0) if (options.limit <= 0)
options.limit = response.items.length; options.limit = response.items.length;
var filteredData = []; var filteredData = [];
for (let i = 0; i < (response.totalItems - options.ignoreOld) && filteredData.length < options.limit; i++) { for (let i = 0; i < (response.totalItems - options.ignoreOld) &&
filteredData.length < options.limit; i++) {
if (options.pattern) { if (options.pattern) {
try { try {
let jsonContent = JSON.parse(response.items[i].floData); let jsonContent = JSON.parse(response.items[i].floData);
@ -7476,14 +7475,15 @@
data: filteredData data: filteredData
}); });
}).catch(error => { }).catch(error => {
reject(error);
});
}).catch(error => {
reject(error); reject(error);
}); });
}).catch(error => {
reject(error);
}); });
}); }
} }
} })(typeof global !== "undefined" ? global : window);
</script> </script>
<script id="compactIDB" version="2.0.1"> <script id="compactIDB" version="2.0.1">
/* Compact IndexedDB operations */ /* Compact IndexedDB operations */