Merge Develop into Master

This commit is contained in:
Luis Fernando Molina committed 2021-08-05 13:07:45 +02:00
1 parent 2d7ed1d085
commit 2bb78c50fb
4223 files changed
+1207152 -16544

No files matched your search

@@ -0,0 +1,68 @@
function newGovernanceActionSwitch() {
let thisObject = {
executeAction: executeAction,
initialize: initialize,
finalize: finalize
}
return thisObject
function finalize() {
}
function initialize() {
/* Nothing to initialize since a Function Library does not hold any state. */
}
async function executeAction(action) {
switch (action.name) {
case 'Install Missing Assets':
{
UI.projects.governance.functionLibraries.assets.installMissingAssets(action.node, action.rootNodes)
break
}
case 'Install Missing Votes':
{
UI.projects.governance.functionLibraries.votingProgram.installMissingVotes(action.node, action.rootNodes)
break
}
case 'Install Missing Claims':
{
UI.projects.governance.functionLibraries.claimsProgram.installMissingClaims(action.node, action.rootNodes)
break
}
case 'Build Profile':
{
UI.projects.governance.functionLibraries.profileConstructor.buildProfile(action.node, action.rootNodes)
break
}
case 'Add Missing Plugin User Profiles':
{
UI.projects.governance.functionLibraries.pluginsFunctions.addMissingPluginUserProfiles(action.node, action.rootNodes)
}
break
case 'Add Missing Plugin Pools':
{
UI.projects.governance.functionLibraries.pluginsFunctions.addMissingPluginPools(action.node, action.rootNodes)
}
break
case 'Add Missing Plugin Features':
{
UI.projects.governance.functionLibraries.pluginsFunctions.addMissingPluginFeatures(action.node, action.rootNodes)
}
break
case 'Add Missing Plugin Assets':
{
UI.projects.governance.functionLibraries.pluginsFunctions.addMissingPluginAssets(action.node, action.rootNodes)
}
break
case 'Add Missing Plugin Positions':
{
UI.projects.governance.functionLibraries.pluginsFunctions.addMissingPluginPositions(action.node, action.rootNodes)
}
break
}
}
}
@@ -0,0 +1,192 @@
function newGovernanceFunctionLibraryAirdropProgram() {
let thisObject = {
calculate: calculate
}
return thisObject
function calculate(
pools,
userProfiles
) {
let programPoolTokenReward
/*
In order to be able to calculate the share of the Program Pool for each User Profile,
we need to accumulate all the Airdrop Power that each User Profile at their Program
node has, because with that Power is that each Program node gets a share of the pool.
*/
let accumulatedProgramPower = 0
/* Scan Pools Until finding the Pool for this program*/
for (let i = 0; i < pools.length; i++) {
let poolsNode = pools[i]
programPoolTokenReward = UI.projects.governance.utilities.pools.findPool(poolsNode, "Airdrop-Rewards")
if (programPoolTokenReward !== undefined) { break }
}
if (programPoolTokenReward === undefined || programPoolTokenReward === 0) { return }
for (let i = 0; i < userProfiles.length; i++) {
let userProfile = userProfiles[i]
if (userProfile.tokenPowerSwitch === undefined) { continue }
let program = UI.projects.governance.utilities.validations.onlyOneProgram(userProfile, "Airdrop Program")
if (program === undefined) { continue }
if (program.payload === undefined) { continue }
resetProgram(program)
}
for (let i = 0; i < userProfiles.length; i++) {
let userProfile = userProfiles[i]
if (userProfile.tokenPowerSwitch === undefined) { continue }
let program = UI.projects.governance.utilities.validations.onlyOneProgram(userProfile, "Airdrop Program")
if (program === undefined) { continue }
if (program.payload === undefined) { continue }
validateProgram(program, userProfile)
}
for (let i = 0; i < userProfiles.length; i++) {
let userProfile = userProfiles[i]
if (userProfile.tokenPowerSwitch === undefined) { continue }
let program = UI.projects.governance.utilities.validations.onlyOneProgram(userProfile, "Airdrop Program")
if (program === undefined) { continue }
if (program.payload === undefined) { continue }
if (program.payload.airdropProgram.isActive === false) { continue }
distributeProgram(program)
}
for (let i = 0; i < userProfiles.length; i++) {
let userProfile = userProfiles[i]
if (userProfile.tokenPowerSwitch === undefined) { continue }
let program = UI.projects.governance.utilities.validations.onlyOneProgram(userProfile, "Airdrop Program")
if (program === undefined) { continue }
if (program.payload === undefined) { continue }
if (program.payload.airdropProgram.isActive === false) { continue }
calculateProgram(program)
}
function resetProgram(node) {
if (node === undefined) { return }
if (node.payload === undefined) { return }
if (node.payload.airdropProgram === undefined) {
node.payload.airdropProgram = {
count: 0,
percentage: 0,
outgoingPower: 0,
ownPower: 0,
incomingPower: 0,
awarded: {
tokens: 0,
percentage: 0
}
}
} else {
node.payload.airdropProgram.count = 0
node.payload.airdropProgram.percentage = 0
node.payload.airdropProgram.outgoingPower = 0
node.payload.airdropProgram.ownPower = 0
node.payload.airdropProgram.incomingPower = 0
node.payload.airdropProgram.awarded = {
tokens: 0,
percentage: 0
}
}
}
function validateProgram(node, userProfile) {
/*
This program is not going to run unless the Profile has Tokens, and for
that users needs to execute the setup procedure of signing their Airdrop
username with their private key.
*/
if (
userProfile.payload.blockchainTokens === undefined
) {
node.payload.airdropProgram.isActive = false
userProfile.payload.uiObject.setErrorMessage("You need to setup this profile with the Profile Constructor, to access the Token Power of your account at the Blockchain.")
return
}
/*
Next thing to do is to validate if the airdrop user profile has a star at the Superalgos repository.
*/
let profileSignature = UI.projects.foundations.utilities.nodeConfig.loadConfigProperty(userProfile.payload, 'signature')
if (
profileSignature === undefined
) {
node.payload.airdropProgram.isActive = false
userProfile.payload.uiObject.setErrorMessage("You need to setup this profile with the Profile Constructor, and produce a signature of your Airdrop Username.")
return
}
node.payload.airdropProgram.isActive = true
}
function distributeProgram(programNode) {
if (programNode === undefined || programNode.payload === undefined) { return }
/*
Here we will convert Token Power into Airdrop Power.
As per system rules Airdrop Powar = 1000 SA Tokens.
*/
let programPower = 1000
programNode.payload.airdropProgram.ownPower = programPower
accumulatedProgramPower = accumulatedProgramPower + programPower
}
function calculateProgram(programNode) {
/*
Here we will calculate which share of the Program Pool this user will get in tokens.
To do that, we use the ownPower, to see which proportion of the accumulatedProgramPower
represents.
*/
if (programNode.payload === undefined) { return }
/*
If the accumulatedProgramPower is not grater the amount of tokens at the Program Pool, then
this user will get the exact amount of tokens from the pool as incomingPower he has.
If the accumulatedProgramPower is grater the amount of tokens at the Program Pool, then
the amount ot tokens to be received is a proportional to the share of incomingPower in accumulatedProgramPower.
*/
let totalPowerRewardRatio = accumulatedProgramPower / programPoolTokenReward
if (totalPowerRewardRatio < 1) { totalPowerRewardRatio = 1 }
if (programNode.tokensAwarded === undefined || programNode.tokensAwarded.payload === undefined) {
programNode.payload.uiObject.setErrorMessage("Tokens Awarded Node is needed in order for this Program to get Tokens from the Program Pool.")
return
}
programNode.payload.airdropProgram.awarded.tokens = programNode.payload.airdropProgram.ownPower / totalPowerRewardRatio
drawProgram(programNode)
}
function drawProgram(node) {
if (node.payload !== undefined) {
const ownPowerText = parseFloat(node.payload.airdropProgram.ownPower.toFixed(0)).toLocaleString('en')
node.payload.uiObject.statusAngleOffset = 0
node.payload.uiObject.statusAtAngle = false
node.payload.uiObject.setStatus(ownPowerText + ' Airdrop Power')
}
if (node.tokensAwarded !== undefined && node.tokensAwarded.payload !== undefined) {
const tokensAwardedText = parseFloat(node.payload.airdropProgram.awarded.tokens.toFixed(0)).toLocaleString('en')
const tokensAwardedBTC = ' ≃ ' + UI.projects.governance.utilities.conversions.estimateSATokensInBTC(node.payload.airdropProgram.awarded.tokens | 0) + ' BTC'
node.tokensAwarded.payload.uiObject.valueAngleOffset = 0
node.tokensAwarded.payload.uiObject.valueAtAngle = false
node.tokensAwarded.payload.uiObject.setValue(tokensAwardedText + ' SA Tokens' + tokensAwardedBTC)
node.tokensAwarded.payload.uiObject.statusAngleOffset = 0
node.tokensAwarded.payload.uiObject.statusAtAngle = false
node.tokensAwarded.payload.uiObject.setStatus('For creating your Superalgos profile!')
}
}
}
}
@@ -0,0 +1,121 @@
function newGovernanceFunctionLibraryAssets() {
let thisObject = {
installMissingAssets: installMissingAssets
}
return thisObject
function installMissingAssets(
node,
rootNodes
) {
let folderPath = UI.projects.foundations.utilities.nodeConfig.loadConfigProperty(node.payload, 'folderPath')
if (folderPath === undefined || folderPath === "") {
node.payload.uiObject.setErrorMessage("folderPath Config Property undefined.")
return
}
node.payload.uiObject.setInfoMessage("Hold on while we install all the assets inside the this path: " + folderPath + ". This might take a minute or two.")
httpRequest(undefined, 'DirContent' + '/' + folderPath, onResponse)
function onResponse(err, data) {
if (err.result !== GLOBAL.DEFAULT_OK_RESPONSE.result) {
console.log('Failed to get Directory Content from the Client')
return
}
let filePathArray = JSON.parse(data)
let totalAssets = 0
for (let i = 0; i < filePathArray.length; i++) {
let filePath = filePathArray[i]
if (filePath.indexOf('node_modules') >= 0) { continue }
let foldersArray = removeFirstFromArray(filePath.split('\\'))
totalAssets++
createNodesFromPath(node, foldersArray)
}
node.payload.uiObject.setInfoMessage("A total of : " + totalAssets + " assets have been installed.")
}
function removeFirstFromArray(array) {
/*
Don't want to use splice here because this will be used
recursivelly and can have problems because we will be
passing a pointer to the array at several branches.
*/
let newArray = []
for (let i = 1; i < array.length; i++) {
newArray.push(array[i])
}
return newArray
}
function createNodesFromPath(node, pathArray) {
if (node === undefined) { return }
if (node.payload === undefined) { return }
if (pathArray.length === 0) { return }
let nextItem = pathArray[0]
pathArray = removeFirstFromArray(pathArray)
let schemaDocument = getSchemaDocument(node)
if (schemaDocument === undefined) { return }
/*
Here we will check that the node corersponding to the next item does not already exist.
*/
let exist = false
if (schemaDocument.childrenNodesProperties !== undefined) {
for (let i = 0; i < schemaDocument.childrenNodesProperties.length; i++) {
let property = schemaDocument.childrenNodesProperties[i]
switch (property.type) {
case 'node': {
let childNode = node[property.name]
if (childNode !== undefined) {
let codeName = UI.projects.foundations.utilities.nodeConfig.loadConfigProperty(childNode.payload, 'codeName')
if (nextItem === codeName) {
exist = true
createNodesFromPath(childNode, pathArray)
}
}
}
break
case 'array': {
let propertyArray = node[property.name]
if (propertyArray !== undefined) {
for (let m = 0; m < propertyArray.length; m++) {
let childNode = propertyArray[m]
if (childNode !== undefined) {
let codeName = UI.projects.foundations.utilities.nodeConfig.loadConfigProperty(childNode.payload, 'codeName')
if (nextItem === codeName) {
exist = true
createNodesFromPath(childNode, pathArray)
}
}
}
}
break
}
}
}
}
if (exist === true) { return }
if (pathArray.length === 0) {
/*
The last element of the path is an Asset.
*/
let childNode = UI.projects.foundations.functionLibraries.uiObjectsFromNodes.addUIObject(node, 'Asset')
childNode.config = JSON.stringify({ codeName: nextItem })
childNode.name = nextItem
} else {
/*
All previous elements are an Asset Class.
*/
let childNode = UI.projects.foundations.functionLibraries.uiObjectsFromNodes.addUIObject(node, 'Asset Class')
childNode.config = JSON.stringify({ codeName: nextItem })
childNode.name = nextItem
createNodesFromPath(childNode, pathArray)
}
}
}
}
@@ -0,0 +1,595 @@
function newGovernanceFunctionLibraryClaimsProgram() {
let thisObject = {
calculate: calculate,
installMissingClaims: installMissingClaims
}
return thisObject
function calculate(
features,
assets,
positions,
userProfiles
) {
/* Claim Reset Follows */
for (let i = 0; i < assets.length; i++) {
let assetsNode = assets[i]
resetClaims(assetsNode)
}
/* Claim Reset Follows */
for (let i = 0; i < features.length; i++) {
let featuresNode = features[i]
resetClaims(featuresNode)
}
/* Claim Reset Follows */
for (let i = 0; i < positions.length; i++) {
let positionsNode = positions[i]
resetClaims(positionsNode)
}
/* Reset this Program */
for (let i = 0; i < userProfiles.length; i++) {
let userProfile = userProfiles[i]
if (userProfile.tokenPowerSwitch === undefined) { continue }
let program = UI.projects.governance.utilities.validations.onlyOneProgram(userProfile, "Claims Program")
if (program === undefined) { continue }
if (program.payload === undefined) { continue }
resetProgram(program)
}
/* Claim Count Follows */
for (let i = 0; i < userProfiles.length; i++) {
let userProfile = userProfiles[i]
if (userProfile.payload === undefined) { continue }
if (userProfile.tokenPowerSwitch === undefined) { continue }
let program = UI.projects.governance.utilities.validations.onlyOneProgram(userProfile, "Claims Program")
if (program === undefined) { continue }
if (program.payload === undefined) { continue }
userProfile.payload.claimsProgram = {
awarded: {
tokens: 0
},
count: 0
}
countProgram(program)
}
/* Claim Distribution Follows */
for (let i = 0; i < userProfiles.length; i++) {
let userProfile = userProfiles[i]
if (userProfile.payload === undefined) { continue }
if (userProfile.tokenPowerSwitch === undefined) { continue }
let program = UI.projects.governance.utilities.validations.onlyOneProgram(userProfile, "Claims Program")
if (program === undefined) { continue }
if (program.payload === undefined) { continue }
distributeProgram(program)
}
/* Claim Calculation Follows */
for (let i = 0; i < userProfiles.length; i++) {
let userProfile = userProfiles[i]
if (userProfile.payload === undefined) { continue }
if (userProfile.tokenPowerSwitch === undefined) { continue }
let program = UI.projects.governance.utilities.validations.onlyOneProgram(userProfile, "Claims Program")
if (program === undefined) { continue }
if (program.payload === undefined) { continue }
calculateProgram(program)
}
function resetClaims(node) {
if (node === undefined) { return }
if (node.payload === undefined) { return }
if (
node.type !== 'Asset Class' &&
node.type !== 'Feature Class' &&
node.type !== 'Position Class'
) {
if (
node.payload.votingProgram !== undefined &&
node.payload.votingProgram.votes !== undefined
) {
node.payload.claimsProgram = {
count: 0,
votes: 0
}
}
}
let schemaDocument = getSchemaDocument(node)
if (schemaDocument === undefined) { return }
if (schemaDocument.childrenNodesProperties !== undefined) {
for (let i = 0; i < schemaDocument.childrenNodesProperties.length; i++) {
let property = schemaDocument.childrenNodesProperties[i]
switch (property.type) {
case 'node': {
let childNode = node[property.name]
resetClaims(childNode)
}
break
case 'array': {
let propertyArray = node[property.name]
if (propertyArray !== undefined) {
for (let m = 0; m < propertyArray.length; m++) {
let childNode = propertyArray[m]
resetClaims(childNode)
}
}
break
}
}
}
}
}
function resetProgram(node) {
if (node === undefined) { return }
if (node.payload === undefined) { return }
node.payload.claimsProgram = {
count: 0,
awarded: {
tokens: 0,
percentage: 0
},
share: {
count: 0,
percentage: 0
}
}
let schemaDocument = getSchemaDocument(node)
if (schemaDocument === undefined) { return }
if (schemaDocument.childrenNodesProperties !== undefined) {
for (let i = 0; i < schemaDocument.childrenNodesProperties.length; i++) {
let property = schemaDocument.childrenNodesProperties[i]
switch (property.type) {
case 'node': {
let childNode = node[property.name]
resetProgram(childNode)
}
break
case 'array': {
let propertyArray = node[property.name]
if (propertyArray !== undefined) {
for (let m = 0; m < propertyArray.length; m++) {
let childNode = propertyArray[m]
resetProgram(childNode)
}
}
break
}
}
}
}
}
function countProgram(node) {
if (node === undefined) { return }
if (node.payload === undefined) { return }
if (
node.type !== 'Asset Claims Folder' &&
node.type !== 'Feature Claims Folder' &&
node.type !== 'Position Claims Folder' &&
node.type !== 'Claims Program'
) {
if (
node.payload.votingProgram !== undefined &&
node.payload.votingProgram.votes !== undefined &&
node.payload.votingProgram.votes > 0 &&
node.payload.referenceParent !== undefined &&
node.payload.referenceParent.payload !== undefined &&
node.payload.referenceParent.payload.votingProgram.votes !== undefined &&
node.payload.referenceParent.payload.votingProgram.votes > 0 &&
node.payload.referenceParent.payload.weight !== undefined &&
node.payload.referenceParent.payload.weight > 0 &&
node.payload.referenceParent.payload.claimsProgram.count !== undefined &&
node.payload.referenceParent.payload.claimsProgram.votes !== undefined
) {
node.payload.referenceParent.payload.claimsProgram.count++
node.payload.referenceParent.payload.claimsProgram.votes = node.payload.referenceParent.payload.claimsProgram.votes + node.payload.votingProgram.votes
}
}
let schemaDocument = getSchemaDocument(node)
if (schemaDocument === undefined) { return }
if (schemaDocument.childrenNodesProperties !== undefined) {
for (let i = 0; i < schemaDocument.childrenNodesProperties.length; i++) {
let property = schemaDocument.childrenNodesProperties[i]
switch (property.type) {
case 'node': {
let childNode = node[property.name]
countProgram(childNode)
}
break
case 'array': {
let propertyArray = node[property.name]
if (propertyArray !== undefined) {
for (let m = 0; m < propertyArray.length; m++) {
let childNode = propertyArray[m]
countProgram(childNode)
}
}
break
}
}
}
}
}
function distributeProgram(programNode) {
if (programNode === undefined || programNode.payload === undefined) { return }
/*
Here we will convert Token Power into programPower.
As per system rules programPower = tokensPower
*/
let programPower = programNode.payload.tokenPower
/*
The Own Power is the power generated by the same User Profile tokens, not inherited from others.
*/
programNode.payload.claimsProgram.ownPower = programPower
distributeProgramPower(programNode, programPower)
}
function distributeProgramPower(
node,
programPower,
percentage
) {
if (node === undefined) { return }
if (node.payload === undefined) { return }
if (
node.type !== 'Asset Claims Folder' &&
node.type !== 'Feature Claims Folder' &&
node.type !== 'Position Claims Folder' &&
node.type !== 'Claims Program'
) {
if (
node.payload.votingProgram !== undefined &&
node.payload.votingProgram.votes !== undefined &&
node.payload.votingProgram.votes > 0 &&
node.payload.referenceParent !== undefined &&
node.payload.referenceParent.payload !== undefined &&
node.payload.referenceParent.payload.votingProgram.votes !== undefined &&
node.payload.referenceParent.payload.votingProgram.votes > 0 &&
node.payload.referenceParent.payload.weight !== undefined &&
node.payload.referenceParent.payload.weight > 0 &&
node.payload.referenceParent.payload.claimsProgram.count !== undefined &&
node.payload.referenceParent.payload.claimsProgram.votes !== undefined
) {
/*
We will use the concept of Vote Reward Claims Ratio for the situation in which the
total votes in claims exeeds the amount of votes of the reward. When this happens
the Votes Rewards Claims Ratio will be used to redude the amount of tokens awarded
proportionally to how much was exeeded.
*/
let votesRatio = node.payload.referenceParent.payload.votingProgram.votes / node.payload.referenceParent.payload.claimsProgram.votes
if (votesRatio > 1) { votesRatio = 1 }
/*
Share Count means the amount to claims pointing to the same potential tokens reward.
*/
node.payload.claimsProgram.share.count = node.payload.referenceParent.payload.claimsProgram.count
node.payload.claimsProgram.share.percentage = node.payload.votingProgram.votes * 100 / node.payload.referenceParent.payload.claimsProgram.votes
node.payload.claimsProgram.awarded.tokens =
Math.min(
node.payload.votingProgram.votes / node.payload.referenceParent.payload.votingProgram.votes * node.payload.referenceParent.payload.tokens * votesRatio,
node.payload.votingProgram.votes,
programPower
)
node.payload.claimsProgram.awarded.percentage = node.payload.claimsProgram.awarded.tokens / node.payload.referenceParent.payload.tokens * 100
drawClaims(node)
drawProgramPower(node, programPower, percentage)
}
} else {
if (node.type === 'Claims Program') {
drawProgram(node)
} else {
drawProgramPower(node, programPower, percentage)
}
}
let schemaDocument = getSchemaDocument(node)
if (schemaDocument === undefined) { return }
if (schemaDocument.childrenNodesProperties === undefined) { return }
/*
Before distributing the claim power, we will calculate how the power
is going to be switched between all nodes. The first pass is about
scanning all sibling nodes to see which ones have a percentage defined
at their config, and check that all percentages don't add more than 100.
*/
let totalPercentage = 0
let totalNodesWithoutPercentage = 0
for (let i = 0; i < schemaDocument.childrenNodesProperties.length; i++) {
let property = schemaDocument.childrenNodesProperties[i]
switch (property.type) {
case 'node': {
let childNode = node[property.name]
if (childNode === undefined) { continue }
if (childNode.type === "Tokens Awarded") { continue }
let percentage = UI.projects.foundations.utilities.nodeConfig.loadConfigProperty(childNode.payload, 'percentage')
if (percentage !== undefined && isNaN(percentage) !== true) {
totalPercentage = totalPercentage + percentage
} else {
totalNodesWithoutPercentage++
}
}
break
case 'array': {
let propertyArray = node[property.name]
if (propertyArray !== undefined) {
for (let m = 0; m < propertyArray.length; m++) {
let childNode = propertyArray[m]
if (childNode === undefined) { continue }
if (childNode.type === "Tokens Awarded") { continue }
let percentage = UI.projects.foundations.utilities.nodeConfig.loadConfigProperty(childNode.payload, 'percentage')
if (percentage !== undefined && isNaN(percentage) !== true) {
totalPercentage = totalPercentage + percentage
} else {
totalNodesWithoutPercentage++
}
}
}
break
}
}
}
if (totalPercentage > 100) {
node.payload.uiObject.setErrorMessage('Claim Power Switching Error. Total Percentage of children nodes is grater that 100.')
return
}
let defaultPercentage = 0
if (totalNodesWithoutPercentage > 0) {
defaultPercentage = (100 - totalPercentage) / totalNodesWithoutPercentage
}
for (let i = 0; i < schemaDocument.childrenNodesProperties.length; i++) {
let property = schemaDocument.childrenNodesProperties[i]
switch (property.type) {
case 'node': {
let childNode = node[property.name]
if (childNode === undefined) { continue }
if (childNode.type === "Tokens Awarded") { continue }
let percentage = UI.projects.foundations.utilities.nodeConfig.loadConfigProperty(childNode.payload, 'percentage')
if (percentage === undefined || isNaN(percentage) === true) {
percentage = defaultPercentage
}
distributeProgramPower(childNode, programPower * percentage / 100, percentage)
}
break
case 'array': {
let propertyArray = node[property.name]
if (propertyArray !== undefined) {
for (let m = 0; m < propertyArray.length; m++) {
let childNode = propertyArray[m]
if (childNode === undefined) { continue }
if (childNode.type === "Tokens Awarded") { continue }
let percentage = UI.projects.foundations.utilities.nodeConfig.loadConfigProperty(childNode.payload, 'percentage')
if (percentage === undefined || isNaN(percentage) === true) {
percentage = defaultPercentage
}
distributeProgramPower(childNode, programPower * percentage / 100, percentage)
}
}
break
}
}
}
}
function calculateProgram(programNode) {
/*
Up to here, we have the tokens awarded for each claim. We need to consolidate all
of that into the Program Node, so that it can then be correctly placed at the Tokens Awarded Node.
*/
consolidate(programNode)
drawTokensAwarded(programNode)
function consolidate(node) {
if (node === undefined) { return }
if (node.payload === undefined) { return }
programNode.payload.claimsProgram.awarded.tokens = programNode.payload.claimsProgram.awarded.tokens + node.payload.claimsProgram.awarded.tokens
if (node.payload.claimsProgram.awarded.tokens > 0) {
programNode.payload.claimsProgram.count = programNode.payload.claimsProgram.count + 1
}
let schemaDocument = getSchemaDocument(node)
if (schemaDocument === undefined) { return }
if (schemaDocument.childrenNodesProperties !== undefined) {
for (let i = 0; i < schemaDocument.childrenNodesProperties.length; i++) {
let property = schemaDocument.childrenNodesProperties[i]
switch (property.type) {
case 'node': {
let childNode = node[property.name]
consolidate(childNode)
}
break
case 'array': {
let propertyArray = node[property.name]
if (propertyArray !== undefined) {
for (let m = 0; m < propertyArray.length; m++) {
let childNode = propertyArray[m]
consolidate(childNode)
}
}
break
}
}
}
}
}
}
function drawClaims(node) {
let status =
parseFloat(node.payload.claimsProgram.awarded.tokens.toFixed(0)).toLocaleString('en') +
' ' + 'SA Tokens Awarded' + ' - ' +
'From Reward: ' + node.payload.claimsProgram.awarded.percentage.toFixed(2) + '%' + ' - ' +
'Shared Between: ' + node.payload.claimsProgram.share.count + ' claims' + ' - ' +
'Share of Claims: ' + node.payload.claimsProgram.share.percentage.toFixed(2) + '%'
node.payload.uiObject.setStatus(status)
}
function drawProgram(node) {
if (node.payload !== undefined) {
const ownPowerText = parseFloat(node.payload.claimsProgram.ownPower.toFixed(0)).toLocaleString('en')
node.payload.uiObject.statusAngleOffset = 0
node.payload.uiObject.statusAtAngle = false
node.payload.uiObject.setStatus(ownPowerText + ' Claims Power')
}
}
function drawTokensAwarded(node) {
if (node.tokensAwarded !== undefined && node.tokensAwarded.payload !== undefined) {
const tokensAwardedText = parseFloat(node.payload.claimsProgram.awarded.tokens.toFixed(0)).toLocaleString('en')
const tokensAwardedBTC = ' ≃ ' + UI.projects.governance.utilities.conversions.estimateSATokensInBTC(node.payload.claimsProgram.awarded.tokens | 0) + ' BTC'
node.tokensAwarded.payload.uiObject.valueAngleOffset = 0
node.tokensAwarded.payload.uiObject.valueAtAngle = true
node.tokensAwarded.payload.uiObject.statusAngleOffset = 0
node.tokensAwarded.payload.uiObject.statusAtAngle = true
node.tokensAwarded.payload.uiObject.setValue(tokensAwardedText + ' SA Tokens' + tokensAwardedBTC)
node.tokensAwarded.payload.uiObject.setStatus('From ' + node.payload.claimsProgram.count + ' Claims.')
}
}
function drawProgramPower(node, programPower, percentage) {
const programPowerText = parseFloat(programPower).toLocaleString('en') + ' ' + 'Claim Power'
if (node.payload !== undefined) {
node.payload.uiObject.valueAngleOffset = 180
node.payload.uiObject.valueAtAngle = true
node.payload.uiObject.percentageAngleOffset = 180
node.payload.uiObject.percentageAtAngle = true
node.payload.uiObject.setValue(programPowerText)
if (percentage !== undefined) {
node.payload.uiObject.setPercentage(percentage.toFixed(2))
}
}
}
}
function installMissingClaims(node, rootNodes) {
if (node.payload === undefined) { return }
if (node.payload.referenceParent === undefined) {
node.payload.uiObject.setErrorMessage('To Install Missing Claims you need a Reference Parent')
return
}
scanNodeBranch(node, node.payload.referenceParent)
function scanNodeBranch(originNode, destinationNode) {
if (
destinationNode.type === 'Asset' ||
destinationNode.type === 'Feature' ||
destinationNode.type === 'Position'
) {
originNode.name = destinationNode.name + ' ' + destinationNode.type + ' ' + ' Claim'
} else {
originNode.name = destinationNode.name + ' ' + destinationNode.type
}
let schemaDocument = getSchemaDocument(destinationNode)
if (schemaDocument === undefined) { return }
if (schemaDocument.childrenNodesProperties !== undefined) {
for (let i = 0; i < schemaDocument.childrenNodesProperties.length; i++) {
let property = schemaDocument.childrenNodesProperties[i]
switch (property.type) {
case 'node': {
let destinationNodeChild = destinationNode[property.name]
let originNodeChildType = getOriginNodeChildType(destinationNodeChild)
let originNodeChild = UI.projects.foundations.utilities.children.findChildReferencingThisNode(originNode, destinationNodeChild)
if (originNodeChild === undefined) {
originNodeChild = UI.projects.foundations.functionLibraries.uiObjectsFromNodes.addUIObject(originNode, originNodeChildType)
}
UI.projects.foundations.functionLibraries.attachDetach.referenceAttachNode(originNodeChild, destinationNodeChild)
scanNodeBranch(originNodeChild, destinationNodeChild)
}
break
case 'array': {
let propertyArray = destinationNode[property.name]
if (propertyArray !== undefined) {
for (let m = 0; m < propertyArray.length; m++) {
let destinationNodeChild = propertyArray[m]
let originNodeChildType = getOriginNodeChildType(destinationNodeChild)
let originNodeChild = UI.projects.foundations.utilities.children.findChildReferencingThisNode(originNode, destinationNodeChild)
if (originNodeChild === undefined) {
originNodeChild = UI.projects.foundations.functionLibraries.uiObjectsFromNodes.addUIObject(originNode, originNodeChildType)
}
UI.projects.foundations.functionLibraries.attachDetach.referenceAttachNode(originNodeChild, destinationNodeChild)
scanNodeBranch(originNodeChild, destinationNodeChild)
}
}
break
}
}
}
}
}
function getOriginNodeChildType(destinationNode) {
let originNodeType
switch (destinationNode.type) {
case 'Asset Class': {
originNodeType = 'Asset Claims Folder'
break
}
case 'Feature Class': {
originNodeType = 'Feature Claims Folder'
break
}
case 'Position Class': {
originNodeType = 'Position Claims Folder'
break
}
case 'Asset': {
originNodeType = 'Asset Contribution Claim'
break
}
case 'Feature': {
originNodeType = 'Feature Contribution Claim'
break
}
case 'Position': {
originNodeType = 'Position Contribution Claim'
break
}
}
return originNodeType
}
}
}
@@ -0,0 +1,342 @@
function newGovernanceFunctionLibraryDelegationProgram() {
let thisObject = {
calculate: calculate
}
const MAX_GENERATIONS = 10
return thisObject
function calculate(
pools,
userProfiles
) {
/*
We will first reset all the delegate power, and then distribute it.
*/
for (let i = 0; i < userProfiles.length; i++) {
let userProfile = userProfiles[i]
if (userProfile.tokenPowerSwitch === undefined) { continue }
let program = UI.projects.governance.utilities.validations.onlyOneProgram(userProfile, "Delegation Program")
if (program === undefined) { continue }
if (program.payload === undefined) { continue }
resetProgram(program)
}
for (let i = 0; i < userProfiles.length; i++) {
let userProfile = userProfiles[i]
if (userProfile.tokenPowerSwitch === undefined) { continue }
let program = UI.projects.governance.utilities.validations.onlyOneProgram(userProfile, "Delegation Program")
if (program === undefined) { continue }
if (program.payload === undefined) { continue }
program.payload.delegationProgram.programPower = program.payload.tokenPower
distributeProgram(program)
}
/* Bonus Calculation is here */
UI.projects.governance.utilities.bonusProgram.run(
pools,
userProfiles,
"delegationProgram",
"Delegation-Bonus",
"Delegation Program"
)
function resetProgram(node) {
resetNode(node, 0)
function resetNode(node, generation) {
if (generation >= MAX_GENERATIONS) {
return
}
if (node === undefined) { return }
if (node.payload === undefined) { return }
if (node.payload.delegationProgram === undefined) {
node.payload.delegationProgram = {
programPower: 0,
ownPower: 0,
usedPower: 0
}
} else {
node.payload.delegationProgram.programPower = 0
node.payload.delegationProgram.ownPower = 0
node.payload.delegationProgram.usedPower = 0
}
if (node.type === 'User Profile') {
return
}
if (node.payload.referenceParent !== undefined) {
resetNode(node.payload.referenceParent, generation + 1)
return
}
let schemaDocument = getSchemaDocument(node)
if (schemaDocument === undefined) { return }
if (schemaDocument.childrenNodesProperties !== undefined) {
for (let i = 0; i < schemaDocument.childrenNodesProperties.length; i++) {
let property = schemaDocument.childrenNodesProperties[i]
switch (property.type) {
case 'node': {
let childNode = node[property.name]
resetNode(childNode, generation)
}
break
case 'array': {
let propertyArray = node[property.name]
if (propertyArray !== undefined) {
for (let m = 0; m < propertyArray.length; m++) {
let childNode = propertyArray[m]
resetNode(childNode, generation)
}
}
break
}
}
}
}
}
}
function distributeProgram(programNode) {
if (programNode.payload === undefined) { return }
/*
Here we will convert Token Power into programPower.
As per system rules programPower = tokensPower
*/
let programPower = programNode.payload.tokenPower
/*
The Own Power is the power generated by the same User Profile tokens, not inherited from others.
*/
programNode.payload.delegationProgram.ownPower = programPower
distributeProgramPower(programNode, programNode, programPower, undefined, 0)
function distributeProgramPower(
currentProgramNode,
node,
programPower,
percentage,
generation
) {
if (generation >= MAX_GENERATIONS) {
return
}
if (node === undefined) { return }
if (node.payload === undefined) { return }
if (node.payload.delegationProgram === undefined) { return }
node.payload.delegationProgram.programPower = node.payload.delegationProgram.programPower + programPower
drawPower(node, node.payload.delegationProgram.programPower, percentage)
/*
When we reach certain node types, we will halt the distribution, because these are targets for
delegate power.
*/
if (
node.type === 'User Profile'
) {
return
}
/*
If there is a reference parent defined, this means that the delegate power is
transfered to it and not distributed among children.
*/
if (
node.payload.referenceParent !== undefined &&
node.type === 'User Delegate'
) {
currentProgramNode.payload.delegationProgram.usedPower = currentProgramNode.payload.delegationProgram.usedPower + programPower
distributeProgramPower(
currentProgramNode,
node.payload.referenceParent,
programPower / 10,
undefined,
generation + 1
)
return
}
/*
If there is no reference parent we will redistribute delegate power among children.
*/
let schemaDocument = getSchemaDocument(node)
if (schemaDocument === undefined) { return }
if (schemaDocument.childrenNodesProperties !== undefined) {
/*
Before distributing the delegate power, we will calculate how the power
is going to be switched between all nodes. The first pass is about
scanning all sibling nodes to see which ones have a percentage defined
at their config, and check that all percentages don't add more than 100.
*/
let totalPercentage = 0
let totalNodesWithoutPercentage = 0
for (let i = 0; i < schemaDocument.childrenNodesProperties.length; i++) {
let property = schemaDocument.childrenNodesProperties[i]
switch (property.type) {
case 'node': {
let childNode = node[property.name]
if (childNode === undefined) { continue }
if (childNode.type === 'Tokens Bonus') { continue }
let percentage = UI.projects.foundations.utilities.nodeConfig.loadConfigProperty(childNode.payload, 'percentage')
if (percentage !== undefined && isNaN(percentage) !== true) {
totalPercentage = totalPercentage + percentage
} else {
totalNodesWithoutPercentage++
}
}
break
case 'array': {
let propertyArray = node[property.name]
if (propertyArray !== undefined) {
for (let m = 0; m < propertyArray.length; m++) {
let childNode = propertyArray[m]
if (childNode === undefined) { continue }
if (childNode.type === 'Tokens Bonus') { continue }
let percentage = UI.projects.foundations.utilities.nodeConfig.loadConfigProperty(childNode.payload, 'percentage')
if (percentage !== undefined && isNaN(percentage) !== true) {
totalPercentage = totalPercentage + percentage
} else {
totalNodesWithoutPercentage++
}
}
}
break
}
}
}
if (totalPercentage > 100) {
node.payload.uiObject.setErrorMessage('Delegate Power Switching Error. Total Percentage of children nodes is grater that 100.')
return
}
let defaultPercentage = 0
if (totalNodesWithoutPercentage > 0) {
defaultPercentage = (100 - totalPercentage) / totalNodesWithoutPercentage
}
/*
Here we do the actual distribution.
*/
for (let i = 0; i < schemaDocument.childrenNodesProperties.length; i++) {
let property = schemaDocument.childrenNodesProperties[i]
switch (property.type) {
case 'node': {
let childNode = node[property.name]
if (childNode === undefined) { continue }
if (childNode.type === 'Tokens Bonus') { continue }
let percentage = UI.projects.foundations.utilities.nodeConfig.loadConfigProperty(childNode.payload, 'percentage')
if (percentage === undefined || isNaN(percentage) === true) {
percentage = defaultPercentage
}
distributeProgramPower(
currentProgramNode,
childNode,
programPower * percentage / 100,
percentage,
generation
)
}
break
case 'array': {
let propertyArray = node[property.name]
if (propertyArray !== undefined) {
for (let m = 0; m < propertyArray.length; m++) {
let childNode = propertyArray[m]
if (childNode === undefined) { continue }
if (childNode.type === 'Tokens Bonus') { continue }
let percentage = UI.projects.foundations.utilities.nodeConfig.loadConfigProperty(childNode.payload, 'percentage')
if (percentage === undefined || isNaN(percentage) === true) {
percentage = defaultPercentage
}
distributeProgramPower(
currentProgramNode,
childNode,
programPower * percentage / 100,
percentage,
generation
)
}
}
break
}
}
}
}
}
}
function drawPower(node, programPower, percentage) {
if (node.payload !== undefined) {
if (node.type === 'Delegation Program') {
drawProgram(node)
if (percentage !== undefined) {
node.payload.uiObject.setPercentage(percentage.toFixed(2))
}
return
}
if (node.type === 'User Delegate') {
drawUserNode(node, programPower, percentage)
return
}
if (node.type === 'Delegate Power Switch') {
node.payload.uiObject.valueAngleOffset = 180
node.payload.uiObject.valueAtAngle = true
node.payload.uiObject.percentageAngleOffset = 180
node.payload.uiObject.percentageAtAngle = true
let powerType = 'Delegate Power'
const programPowerText = parseFloat(programPower.toFixed(0)).toLocaleString('en') + ' ' + powerType
node.payload.uiObject.setValue(programPowerText)
if (percentage !== undefined) {
node.payload.uiObject.setPercentage(percentage.toFixed(2))
}
}
}
function drawUserNode(node, programPower, percentage) {
if (node.payload !== undefined) {
const outgoingPowerText = parseFloat(programPower.toFixed(0)).toLocaleString('en')
node.payload.uiObject.valueAngleOffset = 180
node.payload.uiObject.valueAtAngle = true
node.payload.uiObject.setValue(outgoingPowerText + ' Delegate Power')
node.payload.uiObject.percentageAngleOffset = 180
node.payload.uiObject.percentageAtAngle = true
node.payload.uiObject.setPercentage(percentage)
if (node.payload.referenceParent !== undefined) {
node.payload.uiObject.statusAngleOffset = 0
node.payload.uiObject.statusAtAngle = true
node.payload.uiObject.setStatus(outgoingPowerText + ' ' + ' Outgoing Power')
}
}
}
function drawProgram(node) {
if (node.payload !== undefined) {
const ownPowerText = parseFloat(node.payload.delegationProgram.ownPower.toFixed(0)).toLocaleString('en')
node.payload.uiObject.statusAngleOffset = 0
node.payload.uiObject.statusAtAngle = false
node.payload.uiObject.setStatus(ownPowerText + ' Delegate Power')
}
}
}
}
}
@@ -0,0 +1,129 @@
function newGovernanceFunctionLibraryDistributionProcess() {
let thisObject = {
calculate: calculate
}
return thisObject
function calculate() {
let pools = UI.projects.foundations.spaces.designSpace.workspace.getHierarchyHeadsByNodeType('Pools')
let features = UI.projects.foundations.spaces.designSpace.workspace.getHierarchyHeadsByNodeType('Features')
let assets = UI.projects.foundations.spaces.designSpace.workspace.getHierarchyHeadsByNodeType('Assets')
let positions = UI.projects.foundations.spaces.designSpace.workspace.getHierarchyHeadsByNodeType('Positions')
let userProfiles = UI.projects.foundations.spaces.designSpace.workspace.getHierarchyHeadsByNodeType('User Profile')
/*
Here we are going to read the amount of tokens at the blockchain
and make a first round of distribution so that they can reach
all the defined Programs.
*/
UI.projects.governance.functionLibraries.tokenPower.calculateTokenPower(
userProfiles
)
/*
Here we will run the Delegation Program, so that all the tokens
that are going to be delegated, are transfered to the Delegate's User Profile.
*/
UI.projects.governance.functionLibraries.delegationProgram.calculate(
pools,
userProfiles
)
/*
Here we are going to do the distribution of the delegated tokens so that they
can also reach all the defined Programs.
*/
UI.projects.governance.functionLibraries.tokenPower.calculateDelegatedPower(
userProfiles
)
/*
Run the Voting Program
*/
UI.projects.governance.functionLibraries.votingProgram.calculate(
pools,
features,
assets,
positions,
userProfiles
)
/*
Now that we have all votes applied, we will calculate all weights
*/
UI.projects.governance.functionLibraries.weights.calculate(
pools,
features,
assets,
positions
)
/*
Let's see how the tokens to be distributed flows into pools, assets, features and positions.
*/
UI.projects.governance.functionLibraries.tokens.calculate(
pools
)
/*
Run the Referral Program
*/
UI.projects.governance.functionLibraries.referralProgram.calculate(
pools,
userProfiles
)
/*
Run the Support Program
*/
UI.projects.governance.functionLibraries.supportProgram.calculate(
pools,
userProfiles
)
/*
Run the Influencer Program
*/
UI.projects.governance.functionLibraries.influencerProgram.calculate(
pools,
userProfiles
)
/*
Run the Mentorship Program
*/
UI.projects.governance.functionLibraries.mentorshipProgram.calculate(
pools,
userProfiles
)
/*
Run the Staking Program
*/
UI.projects.governance.functionLibraries.stakingProgram.calculate(
pools,
userProfiles
)
/*
Run the Claims Program
*/
UI.projects.governance.functionLibraries.claimsProgram.calculate(
features,
assets,
positions,
userProfiles
)
/*
Run the Github Program
*/
UI.projects.governance.functionLibraries.githubProgram.calculate(
pools,
userProfiles
)
/*
Run the Airdrop Program
*/
UI.projects.governance.functionLibraries.airdropProgram.calculate(
pools,
userProfiles
)
/*
After all the programs were ran, we can calculate the tokens mining
calculation each profile.
*/
UI.projects.governance.functionLibraries.tokenMining.calculate(
userProfiles
)
}
}
@@ -0,0 +1,218 @@
function newGovernanceFunctionLibraryGithubProgram() {
let thisObject = {
calculate: calculate
}
return thisObject
function calculate(
pools,
userProfiles
) {
let programPoolTokenReward
/*
In order to be able to calculate the share of the Program Pool for each User Profile,
we need to accumulate all the Github Power that each User Profile at their Program
node has, because with that Power is that each Program node gets a share of the pool.
*/
let accumulatedProgramPower = 0
/* Scan Pools Until finding the Pool for this program*/
for (let i = 0; i < pools.length; i++) {
let poolsNode = pools[i]
programPoolTokenReward = UI.projects.governance.utilities.pools.findPool(poolsNode, "Github-Rewards")
if (programPoolTokenReward !== undefined) { break }
}
if (programPoolTokenReward === undefined || programPoolTokenReward === 0) { return }
for (let i = 0; i < userProfiles.length; i++) {
let userProfile = userProfiles[i]
if (userProfile.tokenPowerSwitch === undefined) { continue }
let program = UI.projects.governance.utilities.validations.onlyOneProgram(userProfile, "Github Program")
if (program === undefined) { continue }
if (program.payload === undefined) { continue }
resetProgram(program)
}
for (let i = 0; i < userProfiles.length; i++) {
let userProfile = userProfiles[i]
if (userProfile.tokenPowerSwitch === undefined) { continue }
let program = UI.projects.governance.utilities.validations.onlyOneProgram(userProfile, "Github Program")
if (program === undefined) { continue }
if (program.payload === undefined) { continue }
validateProgram(program, userProfile)
}
for (let i = 0; i < userProfiles.length; i++) {
let userProfile = userProfiles[i]
if (userProfile.tokenPowerSwitch === undefined) { continue }
let program = UI.projects.governance.utilities.validations.onlyOneProgram(userProfile, "Github Program")
if (program === undefined) { continue }
if (program.payload === undefined) { continue }
if (program.payload.githubProgram.isActive === false) { continue }
distributeProgram(program)
}
for (let i = 0; i < userProfiles.length; i++) {
let userProfile = userProfiles[i]
if (userProfile.tokenPowerSwitch === undefined) { continue }
let program = UI.projects.governance.utilities.validations.onlyOneProgram(userProfile, "Github Program")
if (program === undefined) { continue }
if (program.payload === undefined) { continue }
if (program.payload.githubProgram.isActive === false) { continue }
calculateProgram(program)
}
function resetProgram(node) {
if (node === undefined) { return }
if (node.payload === undefined) { return }
if (node.payload.githubProgram === undefined) {
node.payload.githubProgram = {
count: 0,
percentage: 0,
outgoingPower: 0,
ownPower: 0,
incomingPower: 0,
awarded: {
tokens: 0,
percentage: 0
}
}
} else {
node.payload.githubProgram.count = 0
node.payload.githubProgram.percentage = 0
node.payload.githubProgram.outgoingPower = 0
node.payload.githubProgram.ownPower = 0
node.payload.githubProgram.incomingPower = 0
node.payload.githubProgram.awarded = {
tokens: 0,
percentage: 0
}
}
}
function validateProgram(node, userProfile) {
/*
This program is not going to run unless the Profile has Tokens, and for
that users needs to execute the setup procedure of signing their Github
username with their private key.
*/
if (
userProfile.payload.blockchainTokens === undefined
) {
node.payload.githubProgram.isActive = false
userProfile.payload.uiObject.setErrorMessage("You need to setup this profile with the Profile Constructor, to access the Token Power of your account at the Blockchain.")
return
}
/*
Next thing to do is to validate if the github user profile has a star at the Superalgos repository.
*/
let profileSignature = UI.projects.foundations.utilities.nodeConfig.loadConfigProperty(userProfile.payload, 'signature')
if (
profileSignature === undefined
) {
node.payload.githubProgram.isActive = false
userProfile.payload.uiObject.setErrorMessage("You need to setup this profile with the Profile Constructor, and produce a signature of your Github Username.")
return
}
let githubUsername = profileSignature.message
node.payload.githubProgram.starsCount = UI.projects.governance.spaces.userProfileSpace.githubStars.get(githubUsername)
node.payload.githubProgram.watchersCount = UI.projects.governance.spaces.userProfileSpace.githubWatchers.get(githubUsername)
node.payload.githubProgram.forksCount = UI.projects.governance.spaces.userProfileSpace.githubForks.get(githubUsername)
node.payload.githubProgram.engagement = 0
if (node.payload.githubProgram.starsCount > 0) { node.payload.githubProgram.engagement = node.payload.githubProgram.engagement + node.payload.githubProgram.starsCount }
if (node.payload.githubProgram.watchersCount > 0) { node.payload.githubProgram.engagement = node.payload.githubProgram.engagement + node.payload.githubProgram.watchersCount }
if (node.payload.githubProgram.forksCount > 0) { node.payload.githubProgram.engagement = node.payload.githubProgram.engagement + node.payload.githubProgram.forksCount }
if (
node.payload.githubProgram.engagement > 0) {
node.payload.githubProgram.isActive = true
} else {
node.payload.githubProgram.isActive = false
}
}
function distributeProgram(programNode) {
if (programNode === undefined || programNode.payload === undefined) { return }
/*
Here we will convert Token Power into Github Power.
As per system rules Github Powar = 1200 SA Tokens.
*/
let programPower = 3000
programNode.payload.githubProgram.ownPower = programPower
accumulatedProgramPower = accumulatedProgramPower + programPower
}
function calculateProgram(programNode) {
/*
Here we will calculate which share of the Program Pool this user will get in tokens.
To do that, we use the ownPower, to see which proportion of the accumulatedProgramPower
represents.
*/
if (programNode.payload === undefined) { return }
/*
If the accumulatedProgramPower is not grater the amount of tokens at the Program Pool, then
this user will get the exact amount of tokens from the pool as incomingPower he has.
If the accumulatedProgramPower is grater the amount of tokens at the Program Pool, then
the amount ot tokens to be received is a proportional to the share of incomingPower in accumulatedProgramPower.
*/
let totalPowerRewardRatio = accumulatedProgramPower / programPoolTokenReward
if (totalPowerRewardRatio < 1) { totalPowerRewardRatio = 1 }
if (programNode.tokensAwarded === undefined || programNode.tokensAwarded.payload === undefined) {
programNode.payload.uiObject.setErrorMessage("Tokens Awarded Node is needed in order for this Program to get Tokens from the Program Pool.")
return
}
const MAX_ENGAGEMENT = 3
programNode.payload.githubProgram.awarded.tokens = programNode.payload.githubProgram.ownPower / totalPowerRewardRatio * programNode.payload.githubProgram.engagement / MAX_ENGAGEMENT
drawProgram(programNode)
}
function drawProgram(node) {
if (node.payload !== undefined) {
const ownPowerText = parseFloat(node.payload.githubProgram.ownPower.toFixed(0)).toLocaleString('en')
node.payload.uiObject.statusAngleOffset = 0
node.payload.uiObject.statusAtAngle = false
node.payload.uiObject.setStatus(ownPowerText + ' Github Power')
}
if (node.tokensAwarded !== undefined && node.tokensAwarded.payload !== undefined) {
const tokensAwardedText = parseFloat(node.payload.githubProgram.awarded.tokens.toFixed(0)).toLocaleString('en')
const tokensAwardedBTC = ' ≃ ' + UI.projects.governance.utilities.conversions.estimateSATokensInBTC(node.payload.githubProgram.awarded.tokens | 0) + ' BTC'
node.tokensAwarded.payload.uiObject.valueAngleOffset = 0
node.tokensAwarded.payload.uiObject.valueAtAngle = false
node.tokensAwarded.payload.uiObject.setValue(tokensAwardedText + ' SA Tokens' + tokensAwardedBTC)
node.tokensAwarded.payload.uiObject.statusAngleOffset = 0
node.tokensAwarded.payload.uiObject.statusAtAngle = false
let extraText = ''
if (node.payload.githubProgram.starsCount > 0) {
extraText = extraText + ' + 1 Star'
}
if (node.payload.githubProgram.watchersCount > 0) {
extraText = extraText + ' + 1 Watch'
}
if (node.payload.githubProgram.forksCount > 0) {
extraText = extraText + ' + 1 Fork'
}
node.tokensAwarded.payload.uiObject.setStatus('From' + extraText)
}
}
}
}
@@ -0,0 +1,31 @@
function newGovernanceFunctionLibraryInfluencerProgram() {
let thisObject = {
calculate: calculate
}
return thisObject
function calculate(
pools,
userProfiles
) {
UI.projects.governance.utilities.decendentProgram.run(
pools,
userProfiles,
"influencerProgram",
"Influencer-Rewards",
"Influencer Program",
"Influencer Power",
"userInfluencerers",
"User Influencerer"
)
UI.projects.governance.utilities.bonusProgram.run(
pools,
userProfiles,
"influencerProgram",
"Influencer-Bonus",
"Influencer Program"
)
}
}
@@ -0,0 +1,32 @@
function newGovernanceFunctionLibraryMentorshipProgram() {
let thisObject = {
calculate: calculate
}
return thisObject
function calculate(
pools,
userProfiles
) {
UI.projects.governance.utilities.decendentProgram.run(
pools,
userProfiles,
"mentorshipProgram",
"Mentorship-Rewards",
"Mentorship Program",
"Mentorship Power",
"userMentors",
"User Mentor"
)
UI.projects.governance.utilities.bonusProgram.run(
pools,
userProfiles,
"mentorshipProgram",
"Mentorship-Bonus",
"Mentorship Program"
)
}
}
@@ -0,0 +1,90 @@
function newGovernanceFunctionLibraryPluginsFunctions() {
let thisObject = {
addMissingPluginUserProfiles: addMissingPluginUserProfiles,
addMissingPluginPools: addMissingPluginPools,
addMissingPluginAssets: addMissingPluginAssets,
addMissingPluginFeatures: addMissingPluginFeatures,
addMissingPluginPositions: addMissingPluginPositionss
}
return thisObject
function addMissingPluginUserProfiles(node, rootNodes) {
let projectName = UI.projects.foundations.utilities.plugins.getProjectName(node)
if (projectName === "" || projectName === undefined) {
if (node.payload.parentNode !== undefined) {
node.payload.parentNode.payload.uiObject.setErrorMessage("Config codeName must have the name of the project.")
return
}
}
UI.projects.foundations.utilities.plugins.getPluginFileNames(projectName, 'User-Profiles', onNamesArrived)
function onNamesArrived(fileNames) {
UI.projects.foundations.utilities.plugins.addPluginFileIfNeeded(node, fileNames, 'User-Profiles', 'User Profile')
}
}
function addMissingPluginPools(node, rootNodes) {
let projectName = UI.projects.foundations.utilities.plugins.getProjectName(node)
if (projectName === "" || projectName === undefined) {
if (node.payload.parentNode !== undefined) {
node.payload.parentNode.payload.uiObject.setErrorMessage("Config codeName must have the name of the project.")
return
}
}
UI.projects.foundations.utilities.plugins.getPluginFileNames(projectName, 'Pools', onNamesArrived)
function onNamesArrived(fileNames) {
UI.projects.foundations.utilities.plugins.addPluginFileIfNeeded(node, fileNames, 'Pools', 'Pools')
}
}
function addMissingPluginAssets(node, rootNodes) {
let projectName = UI.projects.foundations.utilities.plugins.getProjectName(node)
if (projectName === "" || projectName === undefined) {
if (node.payload.parentNode !== undefined) {
node.payload.parentNode.payload.uiObject.setErrorMessage("Config codeName must have the name of the project.")
return
}
}
UI.projects.foundations.utilities.plugins.getPluginFileNames(projectName, 'Assets', onNamesArrived)
function onNamesArrived(fileNames) {
UI.projects.foundations.utilities.plugins.addPluginFileIfNeeded(node, fileNames, 'Assets', 'Assets')
}
}
function addMissingPluginFeatures(node, rootNodes) {
let projectName = UI.projects.foundations.utilities.plugins.getProjectName(node)
if (projectName === "" || projectName === undefined) {
if (node.payload.parentNode !== undefined) {
node.payload.parentNode.payload.uiObject.setErrorMessage("Config codeName must have the name of the project.")
return
}
}
UI.projects.foundations.utilities.plugins.getPluginFileNames(projectName, 'Features', onNamesArrived)
function onNamesArrived(fileNames) {
UI.projects.foundations.utilities.plugins.addPluginFileIfNeeded(node, fileNames, 'Features', 'Features')
}
}
function addMissingPluginPositionss(node, rootNodes) {
let projectName = UI.projects.foundations.utilities.plugins.getProjectName(node)
if (projectName === "" || projectName === undefined) {
if (node.payload.parentNode !== undefined) {
node.payload.parentNode.payload.uiObject.setErrorMessage("Config codeName must have the name of the project.")
return
}
}
UI.projects.foundations.utilities.plugins.getPluginFileNames(projectName, 'Positions', onNamesArrived)
function onNamesArrived(fileNames) {
UI.projects.foundations.utilities.plugins.addPluginFileIfNeeded(node, fileNames, 'Positions', 'Positions')
}
}
}
@@ -0,0 +1,94 @@
function newGovernanceFunctionLibraryProfileConstructor() {
let thisObject = {
buildProfile: buildProfile
}
return thisObject
function buildProfile(
node,
rootNodes
) {
/*
Some validations first...
*/
if (node.payload.referenceParent === undefined) {
node.payload.uiObject.setErrorMessage("You need to reference the node that contains the data to be signed.")
return
}
let data = UI.projects.foundations.utilities.nodeConfig.loadConfigProperty(node.payload, 'githubUsername')
if (data === undefined || data === "") {
node.payload.referenceParent.payload.uiObject.setErrorMessage("githubUsername config property missing.")
return
}
createNewAccount()
function createNewAccount() {
let params = {
method: 'createWalletAccount',
entropy: node.id + (new Date()).valueOf()
}
let url = 'WEB3' // we don't need to ask this to any specific superalgos node.
httpRequest(JSON.stringify(params), url, onResponse)
function onResponse(err, data) {
/* Lets check the result of the call through the http interface */
if (err.result !== GLOBAL.DEFAULT_OK_RESPONSE.result) {
node.payload.uiObject.setErrorMessage('Call via HTTP Interface failed.')
walletAccountNode.payload.uiObject.menu.internalClick('Delete UI Object')
return
}
let response = JSON.parse(data)
/* Lets check the result of the method call */
if (response.result !== GLOBAL.DEFAULT_OK_RESPONSE.result) {
node.payload.uiObject.setErrorMessage('Call to WEB3 Server failed. ' + response.error)
return
}
signUserProfileData(response.address, response.privateKey)
}
}
function signUserProfileData(address, privateKey) {
let request = {
url: 'WEB3',
params: {
method: "signData",
privateKey: privateKey,
data: data
}
}
httpRequest(JSON.stringify(request.params), request.url, onResponse)
function onResponse(err, data) {
/* Lets check the result of the call through the http interface */
if (err.result !== GLOBAL.DEFAULT_OK_RESPONSE.result) {
node.payload.uiObject.setErrorMessage('Call via HTTP Interface failed.')
return
}
let response = JSON.parse(data)
/* Lets check the result of the method call */
if (response.result !== GLOBAL.DEFAULT_OK_RESPONSE.result) {
node.payload.uiObject.setErrorMessage('Call to WEB3 Server failed. ' + response.error)
console.log('Call to WEB3 Server failed. ' + response.error)
return
}
UI.projects.foundations.utilities.nodeConfig.saveConfigProperty(node.payload.referenceParent.payload, 'signature', response.signature)
UI.projects.foundations.utilities.nodeConfig.saveConfigProperty(node.payload, 'address', address)
UI.projects.foundations.utilities.nodeConfig.saveConfigProperty(node.payload, 'privateKey', privateKey)
node.payload.uiObject.setInfoMessage("Profile Account has been successfully created.")
}
}
}
}
@@ -0,0 +1,31 @@
function newGovernanceFunctionLibraryReferralProgram() {
let thisObject = {
calculate: calculate
}
return thisObject
function calculate(
pools,
userProfiles
) {
UI.projects.governance.utilities.decendentProgram.run(
pools,
userProfiles,
"referralProgram",
"Referrals-Rewards",
"Referral Program",
"Referral Power",
"userReferrers",
"User Referrer"
)
UI.projects.governance.utilities.bonusProgram.run(
pools,
userProfiles,
"referralProgram",
"Referrals-Bonus",
"Referral Program"
)
}
}
@@ -0,0 +1,175 @@
function newGovernanceFunctionLibraryStakingProgram() {
let thisObject = {
calculate: calculate
}
return thisObject
function calculate(
pools,
userProfiles
) {
let programPoolTokenReward
/*
In order to be able to calculate the share of the Program Pool for each User Profile,
we need to accumulate all the Staking Power that each User Profile at their Program
node has, because with that Power is that each Program node gets a share of the pool.
*/
let accumulatedProgramPower = 0
/* Scan Pools Until finding the Pool for this program*/
for (let i = 0; i < pools.length; i++) {
let poolsNode = pools[i]
programPoolTokenReward = UI.projects.governance.utilities.pools.findPool(poolsNode, "Staking-Rewards")
if (programPoolTokenReward !== undefined) { break }
}
if (programPoolTokenReward === undefined || programPoolTokenReward === 0) { return }
for (let i = 0; i < userProfiles.length; i++) {
let userProfile = userProfiles[i]
if (userProfile.tokenPowerSwitch === undefined) { continue }
let program = UI.projects.governance.utilities.validations.onlyOneProgram(userProfile, "Staking Program")
if (program === undefined) { continue }
if (program.payload === undefined) { continue }
resetProgram(program)
}
for (let i = 0; i < userProfiles.length; i++) {
let userProfile = userProfiles[i]
if (userProfile.tokenPowerSwitch === undefined) { continue }
let program = UI.projects.governance.utilities.validations.onlyOneProgram(userProfile, "Staking Program")
if (program === undefined) { continue }
if (program.payload === undefined) { continue }
validateProgram(program, userProfile)
}
for (let i = 0; i < userProfiles.length; i++) {
let userProfile = userProfiles[i]
if (userProfile.tokenPowerSwitch === undefined) { continue }
let program = UI.projects.governance.utilities.validations.onlyOneProgram(userProfile, "Staking Program")
if (program === undefined) { continue }
if (program.payload === undefined) { continue }
if (program.payload.stakingProgram.isActive === false) { continue }
distributeProgram(program)
}
for (let i = 0; i < userProfiles.length; i++) {
let userProfile = userProfiles[i]
if (userProfile.tokenPowerSwitch === undefined) { continue }
let program = UI.projects.governance.utilities.validations.onlyOneProgram(userProfile, "Staking Program")
if (program === undefined) { continue }
if (program.payload === undefined) { continue }
if (program.payload.stakingProgram.isActive === false) { continue }
calculateProgram(program)
}
function resetProgram(node) {
if (node === undefined) { return }
if (node.payload === undefined) { return }
if (node.payload.stakingProgram === undefined) {
node.payload.stakingProgram = {
count: 0,
percentage: 0,
outgoingPower: 0,
ownPower: 0,
incomingPower: 0,
awarded: {
tokens: 0,
percentage: 0
}
}
} else {
node.payload.stakingProgram.count = 0
node.payload.stakingProgram.percentage = 0
node.payload.stakingProgram.outgoingPower = 0
node.payload.stakingProgram.ownPower = 0
node.payload.stakingProgram.incomingPower = 0
node.payload.stakingProgram.awarded = {
tokens: 0,
percentage: 0
}
}
}
function validateProgram(node, userProfile) {
/*
This program is not going to run unless the Profile has Tokens, and for
that users needs to execute the setup procedure of signing their Github
username with their private key.
*/
if (
userProfile.payload.blockchainTokens === undefined
) {
node.payload.stakingProgram.isActive = false
userProfile.payload.uiObject.setErrorMessage("You need to setup this profile with the Profile Constructor, to access the Token Power of your account at the Blockchain.")
return
}
node.payload.stakingProgram.isActive = true
}
function distributeProgram(programNode) {
if (programNode === undefined || programNode.payload === undefined) { return }
/*
Here we will convert Token Power into Staking Power.
As per system rules Staking Powar = tokensPower
*/
let programPower = programNode.payload.tokenPower
programNode.payload.stakingProgram.ownPower = programPower
accumulatedProgramPower = accumulatedProgramPower + programPower
}
function calculateProgram(programNode) {
/*
Here we will calculate which share of the Program Pool this user will get in tokens.
To do that, we use the ownPower, to see which proportion of the accumulatedProgramPower
represents.
*/
if (programNode.payload === undefined) { return }
/*
If the accumulatedProgramPower is not grater the amount of tokens at the Program Pool, then
this user will get the exact amount of tokens from the pool as incomingPower he has.
If the accumulatedProgramPower is grater the amount of tokens at the Program Pool, then
the amount ot tokens to be received is a proportional to the share of incomingPower in accumulatedProgramPower.
*/
let totalPowerRewardRatio = accumulatedProgramPower / programPoolTokenReward
if (totalPowerRewardRatio < 1) { totalPowerRewardRatio = 1 }
if (programNode.tokensAwarded === undefined || programNode.tokensAwarded.payload === undefined) {
programNode.payload.uiObject.setErrorMessage("Tokens Awarded Node is needed in order for this Program to get Tokens from the Program Pool.")
return
}
programNode.payload.stakingProgram.awarded.tokens = programNode.payload.stakingProgram.ownPower / totalPowerRewardRatio
drawProgram(programNode)
}
function drawProgram(node) {
if (node.payload !== undefined) {
const ownPowerText = parseFloat(node.payload.stakingProgram.ownPower.toFixed(0)).toLocaleString('en')
node.payload.uiObject.statusAngleOffset = 0
node.payload.uiObject.statusAtAngle = false
node.payload.uiObject.setStatus(ownPowerText + ' Staking Power')
}
if (node.tokensAwarded !== undefined && node.tokensAwarded.payload !== undefined) {
const tokensAwardedText = parseFloat(node.payload.stakingProgram.awarded.tokens.toFixed(0)).toLocaleString('en')
const tokensAwardedBTC = ' ≃ ' + UI.projects.governance.utilities.conversions.estimateSATokensInBTC(node.payload.stakingProgram.awarded.tokens | 0) + ' BTC'
node.tokensAwarded.payload.uiObject.valueAngleOffset = 0
node.tokensAwarded.payload.uiObject.valueAtAngle = false
node.tokensAwarded.payload.uiObject.setValue(tokensAwardedText + ' SA Tokens' + tokensAwardedBTC)
}
}
}
}
@@ -0,0 +1,31 @@
function newGovernanceFunctionLibrarySupportProgram() {
let thisObject = {
calculate: calculate
}
return thisObject
function calculate(
pools,
userProfiles
) {
UI.projects.governance.utilities.decendentProgram.run(
pools,
userProfiles,
"supportProgram",
"Support-Rewards",
"Support Program",
"Support Power",
"userSupporters",
"User Supporter"
)
UI.projects.governance.utilities.bonusProgram.run(
pools,
userProfiles,
"supportProgram",
"Support-Bonus",
"Support Program"
)
}
}
@@ -0,0 +1,181 @@
function newGovernanceFunctionLibraryTokenMining() {
let thisObject = {
calculate: calculate
}
return thisObject
function calculate(
userProfiles
) {
for (let i = 0; i < userProfiles.length; i++) {
let userProfile = userProfiles[i]
if (userProfile.tokenPowerSwitch === undefined) { continue }
resetTokensMined(userProfile)
}
for (let i = 0; i < userProfiles.length; i++) {
let userProfile = userProfiles[i]
if (userProfile.tokenPowerSwitch === undefined) { continue }
let program = UI.projects.governance.utilities.validations.onlyOneProgram(userProfile, "Referral Program")
if (program === undefined) { continue }
if (program.payload === undefined) { continue }
calculateProgram(userProfile, program, "referralProgram")
}
for (let i = 0; i < userProfiles.length; i++) {
let userProfile = userProfiles[i]
if (userProfile.tokenPowerSwitch === undefined) { continue }
let program = UI.projects.governance.utilities.validations.onlyOneProgram(userProfile, "Support Program")
if (program === undefined) { continue }
if (program.payload === undefined) { continue }
calculateProgram(userProfile, program, "supportProgram")
}
for (let i = 0; i < userProfiles.length; i++) {
let userProfile = userProfiles[i]
if (userProfile.tokenPowerSwitch === undefined) { continue }
let program = UI.projects.governance.utilities.validations.onlyOneProgram(userProfile, "Mentorship Program")
if (program === undefined) { continue }
if (program.payload === undefined) { continue }
calculateProgram(userProfile, program, "mentorshipProgram")
}
for (let i = 0; i < userProfiles.length; i++) {
let userProfile = userProfiles[i]
if (userProfile.tokenPowerSwitch === undefined) { continue }
let program = UI.projects.governance.utilities.validations.onlyOneProgram(userProfile, "Influencer Program")
if (program === undefined) { continue }
if (program.payload === undefined) { continue }
calculateProgram(userProfile, program, "influencerProgram")
}
for (let i = 0; i < userProfiles.length; i++) {
let userProfile = userProfiles[i]
if (userProfile.tokenPowerSwitch === undefined) { continue }
let program = UI.projects.governance.utilities.validations.onlyOneProgram(userProfile, "Claims Program")
if (program === undefined) { continue }
if (program.payload === undefined) { continue }
calculateProgram(userProfile, program, "claimsProgram")
}
for (let i = 0; i < userProfiles.length; i++) {
let userProfile = userProfiles[i]
if (userProfile.tokenPowerSwitch === undefined) { continue }
let program = UI.projects.governance.utilities.validations.onlyOneProgram(userProfile, "Voting Program")
if (program === undefined) { continue }
if (program.payload === undefined) { continue }
calculateProgram(userProfile, program, "votingProgram")
}
for (let i = 0; i < userProfiles.length; i++) {
let userProfile = userProfiles[i]
if (userProfile.tokenPowerSwitch === undefined) { continue }
let program = UI.projects.governance.utilities.validations.onlyOneProgram(userProfile, "Staking Program")
if (program === undefined) { continue }
if (program.payload === undefined) { continue }
calculateProgram(userProfile, program, "stakingProgram")
}
for (let i = 0; i < userProfiles.length; i++) {
let userProfile = userProfiles[i]
if (userProfile.tokenPowerSwitch === undefined) { continue }
let program = UI.projects.governance.utilities.validations.onlyOneProgram(userProfile, "Delegation Program")
if (program === undefined) { continue }
if (program.payload === undefined) { continue }
calculateProgram(userProfile, program, "delegationProgram")
}
for (let i = 0; i < userProfiles.length; i++) {
let userProfile = userProfiles[i]
if (userProfile.tokenPowerSwitch === undefined) { continue }
let program = UI.projects.governance.utilities.validations.onlyOneProgram(userProfile, "Github Program")
if (program === undefined) { continue }
if (program.payload === undefined) { continue }
calculateProgram(userProfile, program, "githubProgram")
}
for (let i = 0; i < userProfiles.length; i++) {
let userProfile = userProfiles[i]
if (userProfile.tokenPowerSwitch === undefined) { continue }
let program = UI.projects.governance.utilities.validations.onlyOneProgram(userProfile, "Airdrop Program")
if (program === undefined) { continue }
if (program.payload === undefined) { continue }
calculateProgram(userProfile, program, "airdropProgram")
}
for (let i = 0; i < userProfiles.length; i++) {
let userProfile = userProfiles[i]
if (userProfile.tokenPowerSwitch === undefined) { continue }
drawTokensMined(userProfile)
}
function resetTokensMined(userProfile) {
if (userProfile === undefined) { return }
if (userProfile.payload === undefined) { return }
if (userProfile.tokensMined === undefined) { return }
if (userProfile.tokensMined.payload.tokensMined === undefined) {
userProfile.tokensMined.payload.tokensMined = {
awarded: 0,
bonus: 0,
total: 0
}
} else {
userProfile.tokensMined.payload.tokensMined.awarded = 0
userProfile.tokensMined.payload.tokensMined.bonus = 0
userProfile.tokensMined.payload.tokensMined.total = 0
}
}
function calculateProgram(userProfile, programNode, programPropertyName) {
/*
Here we will look into the program node and add their token awarded and token bonus
to the subtotals at the Tokens Mined node.
*/
if (userProfile === undefined) { return }
if (userProfile.payload === undefined) { return }
if (userProfile.tokensMined === undefined) { return }
if (programNode.payload === undefined) { return }
if (programNode.payload[programPropertyName] === undefined) { return }
if (programNode.tokensAwarded !== undefined && programNode.payload[programPropertyName].awarded !== undefined) {
let awarded = programNode.payload[programPropertyName].awarded.tokens | 0
userProfile.tokensMined.payload.tokensMined.awarded = userProfile.tokensMined.payload.tokensMined.awarded + awarded
}
if (programNode.tokensBonus !== undefined && programNode.payload[programPropertyName].bonus !== undefined) {
let bonus = programNode.payload[programPropertyName].bonus.tokens | 0
userProfile.tokensMined.payload.tokensMined.bonus = userProfile.tokensMined.payload.tokensMined.bonus + bonus
}
userProfile.tokensMined.payload.tokensMined.total = userProfile.tokensMined.payload.tokensMined.awarded + userProfile.tokensMined.payload.tokensMined.bonus
}
function drawTokensMined(userProfile) {
if (userProfile === undefined) { return }
if (userProfile.payload === undefined) { return }
if (userProfile.tokensMined === undefined) { return }
const awarded = parseFloat(userProfile.tokensMined.payload.tokensMined.awarded.toFixed(0)).toLocaleString('en')
const bonus = parseFloat(userProfile.tokensMined.payload.tokensMined.bonus.toFixed(0)).toLocaleString('en')
const total = parseFloat(userProfile.tokensMined.payload.tokensMined.total.toFixed(0)).toLocaleString('en')
const tokensAwardedBTC = ' ≃ ' + UI.projects.governance.utilities.conversions.estimateSATokensInBTC(userProfile.tokensMined.payload.tokensMined.total | 0) + ' BTC'
userProfile.tokensMined.payload.uiObject.valueAngleOffset = 0
userProfile.tokensMined.payload.uiObject.valueAtAngle = true
userProfile.tokensMined.payload.uiObject.setStatus(awarded + ' Awarded + ' + bonus + ' Bonus')
userProfile.tokensMined.payload.uiObject.setValue(total + ' SA Tokens' + tokensAwardedBTC)
}
}
}
@@ -0,0 +1,309 @@
function newGovernanceFunctionLibraryTokenPower() {
let thisObject = {
calculateTokenPower: calculateTokenPower,
calculateDelegatedPower: calculateDelegatedPower
}
return thisObject
function calculateTokenPower(
userProfiles
) {
/*
We will first reset all the token and delegated power, and then distribute the token power to each Program.
*/
for (let i = 0; i < userProfiles.length; i++) {
let userProfile = userProfiles[i]
resetPower(userProfile)
}
for (let i = 0; i < userProfiles.length; i++) {
let userProfile = userProfiles[i]
distributeProfileTokenPower(userProfile)
}
}
function calculateDelegatedPower(
userProfiles
) {
/*
We will distribute the original Blockachain Power + the Delegated Power to each Program.
*/
for (let i = 0; i < userProfiles.length; i++) {
let userProfile = userProfiles[i]
distributeProfileDelegatedPower(userProfile)
}
}
function resetPower(node) {
if (node === undefined) { return }
if (node.payload === undefined) { return }
node.payload.tokenPower = 0
/*
When we reach certain node types, we will halt the distribution, because these are targets for
token power.
*/
if (
node.type === 'Referral Program' ||
node.type === 'Mentorship Program' ||
node.type === 'Support Program' ||
node.type === 'Influencer Program' ||
node.type === 'Voting Program' ||
node.type === 'Claims Program' ||
node.type === 'Staking Program' ||
node.type === 'Delegation Program' ||
node.type === 'Github Program' ||
node.type === 'Airdrop Program'
) { return }
/*
We will reset token power of children.
*/
let schemaDocument = getSchemaDocument(node)
if (schemaDocument === undefined) { return }
if (schemaDocument.childrenNodesProperties !== undefined) {
for (let i = 0; i < schemaDocument.childrenNodesProperties.length; i++) {
let property = schemaDocument.childrenNodesProperties[i]
switch (property.type) {
case 'node': {
let childNode = node[property.name]
resetPower(childNode)
}
break
case 'array': {
let propertyArray = node[property.name]
if (propertyArray !== undefined) {
for (let m = 0; m < propertyArray.length; m++) {
let childNode = propertyArray[m]
resetPower(childNode)
}
}
break
}
}
}
}
}
function distributeProfileTokenPower(userProfile) {
if (userProfile.payload === undefined) { return }
if (userProfile.payload.blockchainTokens === undefined) { return }
/*
The tokenPower is comming from blockchainTokens.
*/
let tokenPower = userProfile.payload.blockchainTokens
/*
Before we start we will do some validations:
*/
if (userProfile.tokenPowerSwitch === undefined) {
userProfile.payload.uiObject.setErrorMessage("You need to have a Token Power Switch child node.")
return
}
distributeTokenPower(
userProfile,
tokenPower,
undefined,
false
)
}
function distributeProfileDelegatedPower(userProfile) {
if (userProfile.payload === undefined) { return }
if (userProfile.payload.blockchainTokens === undefined) { return }
if (userProfile.payload.delegationProgram === undefined) { return }
/*
The Deletated Power is already accumilated at userProfile.payload.tokenPower
*/
let tokenPower = userProfile.payload.delegationProgram.programPower
/*
Before we start we will do some validations:
*/
if (userProfile.tokenPowerSwitch === undefined) {
userProfile.payload.uiObject.setErrorMessage("You need to have a Token Power Switch child node.")
return
}
distributeTokenPower(
userProfile,
tokenPower,
undefined,
true
)
}
function distributeTokenPower(
node,
tokenPower,
switchPercentage,
excludeDelegationProgram
) {
if (node === undefined) { return }
if (node.payload === undefined) { return }
node.payload.tokenPower = node.payload.tokenPower + tokenPower
drawTokenPower(node, node.payload.tokenPower, switchPercentage)
/*
When we reach certain node types, we will halt the distribution,
because these are targets for token power.
*/
if (
node.type === 'Referral Program' ||
node.type === 'Mentorship Program' ||
node.type === 'Support Program' ||
node.type === 'Influencer Program' ||
node.type === 'Voting Program' ||
node.type === 'Claims Program' ||
node.type === 'Staking Program' ||
node.type === 'Delegation Program' ||
node.type === 'Github Program' ||
node.type === 'Airdrop Program'
) { return }
/*
We will redistribute token power among children.
*/
let schemaDocument = getSchemaDocument(node)
if (schemaDocument === undefined) { return }
if (schemaDocument.childrenNodesProperties !== undefined) {
/*
Before distributing the token power, we will calculate how the power
is going to be switched between all nodes. The first pass is about
scanning all sibling nodes to see which ones have a percentage defined
at their config, and check that all percentages don't add more than 100.
*/
let totalPercentage = 0
let totalNodesWithoutPercentage = 0
for (let i = 0; i < schemaDocument.childrenNodesProperties.length; i++) {
let property = schemaDocument.childrenNodesProperties[i]
switch (property.type) {
case 'node': {
let childNode = node[property.name]
if (childNode === undefined) { continue }
if (childNode.type === "Delegation Program" && excludeDelegationProgram === true) { continue }
if (childNode.type === "Tokens Mined") { continue }
let percentage = getPercentage(childNode)
if (percentage !== undefined && isNaN(percentage) !== true) {
totalPercentage = totalPercentage + percentage
} else {
totalNodesWithoutPercentage++
}
}
break
case 'array': {
let propertyArray = node[property.name]
if (propertyArray !== undefined) {
for (let m = 0; m < propertyArray.length; m++) {
let childNode = propertyArray[m]
if (childNode === undefined) { continue }
if (childNode.type === "Delegation Program" && excludeDelegationProgram === true) { continue }
if (childNode.type === "Tokens Mined") { continue }
let percentage = getPercentage(childNode)
if (percentage !== undefined && isNaN(percentage) !== true) {
totalPercentage = totalPercentage + percentage
} else {
totalNodesWithoutPercentage++
}
}
}
break
}
}
}
if (totalPercentage > 100) {
node.payload.uiObject.setErrorMessage('Token Power Switching Error. Total Percentage of children nodes is grater that 100.')
return
}
let defaultPercentage = 0
if (totalNodesWithoutPercentage > 0) {
defaultPercentage = (100 - totalPercentage) / totalNodesWithoutPercentage
}
/*
Here we do the actual distribution.
*/
for (let i = 0; i < schemaDocument.childrenNodesProperties.length; i++) {
let property = schemaDocument.childrenNodesProperties[i]
switch (property.type) {
case 'node': {
let childNode = node[property.name]
if (childNode === undefined) { continue }
if (childNode.type === "Delegation Program" && excludeDelegationProgram === true) { continue }
if (childNode.type === "Tokens Mined") { continue }
let percentage = getPercentage(childNode)
if (percentage === undefined || isNaN(percentage) === true) {
percentage = defaultPercentage
}
distributeTokenPower(
childNode,
tokenPower * percentage / 100,
percentage,
excludeDelegationProgram
)
}
break
case 'array': {
let propertyArray = node[property.name]
if (propertyArray !== undefined) {
for (let m = 0; m < propertyArray.length; m++) {
let childNode = propertyArray[m]
if (childNode === undefined) { continue }
if (childNode.type === "Delegation Program" && excludeDelegationProgram === true) { continue }
if (childNode.type === "Tokens Mined") { continue }
let percentage = getPercentage(childNode)
if (percentage === undefined || isNaN(percentage) === true) {
percentage = defaultPercentage
}
distributeTokenPower(
childNode,
tokenPower * percentage / 100,
percentage,
excludeDelegationProgram
)
}
}
break
}
}
}
}
}
function getPercentage(node) {
return UI.projects.foundations.utilities.nodeConfig.loadConfigProperty(node.payload, 'percentage')
}
function drawTokenPower(node, tokenPower, percentage) {
if (node.payload !== undefined) {
if (node.type === 'User Profile') {
let incomingPower = node.payload.tokenPower - node.payload.blockchainTokens
const ownPowerText = parseFloat(node.payload.blockchainTokens.toFixed(0)).toLocaleString('en') + ' ' + 'Blockchain Power'
const incomingPowerText = parseFloat(incomingPower.toFixed(0)).toLocaleString('en') + ' ' + 'Incoming Delegated Power'
node.payload.uiObject.valueAngleOffset = 0
node.payload.uiObject.valueAtAngle = false
node.payload.uiObject.setStatus(ownPowerText + ' + ' + incomingPowerText)
return
}
const tokenPowerText = parseFloat(tokenPower.toFixed(0)).toLocaleString('en') + ' ' + 'Token Power'
node.payload.uiObject.valueAngleOffset = 180
node.payload.uiObject.valueAtAngle = true
node.payload.uiObject.setValue(tokenPowerText)
if (percentage !== undefined) {
node.payload.uiObject.percentageAngleOffset = 180
node.payload.uiObject.percentageAtAngle = true
node.payload.uiObject.setPercentage(percentage.toFixed(2))
}
}
}
}
@@ -0,0 +1,187 @@
function newGovernanceFunctionLibraryTokens() {
let thisObject = {
calculate: calculate
}
return thisObject
function calculate(
pools
) {
/*
We will reset all the token flows, and then distribute it.
*/
for (let i = 0; i < pools.length; i++) {
let poolsNode = pools[i]
poolsReset(poolsNode)
}
for (let i = 0; i < pools.length; i++) {
let poolsNode = pools[i]
poolsDistribute(poolsNode)
}
}
function poolsReset(pools) {
resetTokenFlow(pools)
}
function poolsDistribute(pools) {
if (pools.payload === undefined) { return }
let tokens = pools.payload.tokens
/* Check if this Pools has already been processed by it's reference child.*/
if (tokens !== undefined && tokens > 0) { return }
let confiTokens = UI.projects.foundations.utilities.nodeConfig.loadConfigProperty(pools.payload, 'tokens')
if (confiTokens !== undefined) {
tokens = confiTokens
distributeTokens(pools, tokens)
}
}
function resetTokenFlow(node) {
if (node === undefined) { return }
if (node.payload === undefined) { return }
node.payload.tokens = 0
/*
If there is a reference parent defined, this means that the token flow is
transfered to it and not distributed among children.
*/
if (node.payload.referenceParent !== undefined) {
resetTokenFlow(node.payload.referenceParent)
return
}
/*
When we reach certain node types, we will halt the distribution, because these are targets for
token flow.
*/
if (
node.type === 'Asset' ||
node.type === 'Feature'
) { return }
/*
If there is no reference parent we will redistribute token flow among children.
*/
let schemaDocument = getSchemaDocument(node)
if (schemaDocument === undefined) { return }
if (schemaDocument.childrenNodesProperties !== undefined) {
for (let i = 0; i < schemaDocument.childrenNodesProperties.length; i++) {
let property = schemaDocument.childrenNodesProperties[i]
switch (property.type) {
case 'node': {
if (node.type === 'Pools' && property.name === "votingProgram") {
let childNode = node[property.name]
resetTokenFlow(childNode)
}
}
break
case 'array': {
let propertyArray = node[property.name]
if (propertyArray !== undefined) {
for (let m = 0; m < propertyArray.length; m++) {
let childNode = propertyArray[m]
resetTokenFlow(childNode)
}
}
break
}
}
}
}
}
function distributeTokens(node, tokens) {
if (node === undefined) { return }
if (node.payload === undefined) { return }
/*
Let's get the schemaDocument first
*/
let schemaDocument = getSchemaDocument(node)
if (schemaDocument === undefined) { return }
/*
At hierarchy heads we will shouw how many tokens are comming in.
*/
if (
schemaDocument.isHierarchyHead === true
) {
drawTokenFlow(node, tokens)
}
/*
We will also have tokens at nodes with weight.
*/
if (
isNaN(node.payload.weight) !== true &&
node.payload.weight !== undefined &&
node.payload.weight !== 0
) {
node.payload.tokens = tokens * node.payload.weight
drawTokenFlow(node, node.payload.tokens, node.payload.weight)
}
/*
If there is a reference parent defined, this means that the token flow is
transfered to it and not distributed among children.
*/
if (node.payload.referenceParent !== undefined) {
distributeTokens(node.payload.referenceParent, node.payload.tokens)
return
}
/*
When we reach certain node types, we will halt the distribution, because these are targets for
token flow.
*/
if (
node.type === 'Asset' ||
node.type === 'Feature'
) { return }
if (schemaDocument.childrenNodesProperties !== undefined) {
for (let i = 0; i < schemaDocument.childrenNodesProperties.length; i++) {
let property = schemaDocument.childrenNodesProperties[i]
switch (property.type) {
case 'node': {
if (node.type === 'Pools' && property.name === "votingProgram") {
let childNode = node[property.name]
distributeTokens(childNode, tokens)
}
}
break
case 'array': {
let propertyArray = node[property.name]
if (propertyArray !== undefined) {
for (let m = 0; m < propertyArray.length; m++) {
let childNode = propertyArray[m]
distributeTokens(childNode, tokens)
}
}
break
}
}
}
}
}
function drawTokenFlow(node, tokens, weight) {
if (node.payload === undefined) { return }
tokens = tokens | 0
let status
if (weight !== undefined && weight !== 0) {
status = 'Reward: ' + tokens.toLocaleString('en')
+ ' ' + 'SA' + ' ≃ ' + UI.projects.governance.utilities.conversions.estimateSATokensInBTC(tokens | 0) + ' BTC ' + ' + Weight: ' + (weight * 100).toFixed(2) + " %"
node.payload.uiObject.statusAngleOffset = 0
node.payload.uiObject.statusAtAngle = true
node.payload.uiObject.setStatus(status)
} else {
status = 'Reward: ' + tokens.toLocaleString('en')
+ ' ' + 'SA' + ' ≃ ' + UI.projects.governance.utilities.conversions.estimateSATokensInBTC(tokens | 0) + ' BTC '
node.payload.uiObject.statusAngleOffset = 0
node.payload.uiObject.statusAtAngle = false
node.payload.uiObject.setStatus(status)
}
}
}
@@ -0,0 +1,633 @@
function newGovernanceFunctionLibraryVotingProgram() {
let thisObject = {
calculate: calculate,
installMissingVotes: installMissingVotes
}
const MAX_GENERATIONS = 10
return thisObject
function calculate(
pools,
features,
assets,
positions,
userProfiles
) {
/* Reset Votes at Pools */
for (let i = 0; i < pools.length; i++) {
let poolsNode = pools[i]
resetVotes(poolsNode)
}
/* Reset Votes at Features */
for (let i = 0; i < features.length; i++) {
let featuresNode = features[i]
resetVotes(featuresNode)
}
/* Reset Votes at Assets */
for (let i = 0; i < assets.length; i++) {
let assetsNode = assets[i]
resetVotes(assetsNode)
}
/* Reset Votes at Features */
for (let i = 0; i < positions.length; i++) {
let positionsNode = positions[i]
resetVotes(positionsNode)
}
/*
We will first reset all the voting power, and then distribute it.
*/
for (let i = 0; i < userProfiles.length; i++) {
let userProfile = userProfiles[i]
if (userProfile.tokenPowerSwitch === undefined) { continue }
let program = UI.projects.governance.utilities.validations.onlyOneProgram(userProfile, "Voting Program")
if (program === undefined) { continue }
if (program.payload === undefined) { continue }
resetVotes(program)
}
for (let i = 0; i < userProfiles.length; i++) {
let userProfile = userProfiles[i]
if (userProfile.tokenPowerSwitch === undefined) { continue }
let program = UI.projects.governance.utilities.validations.onlyOneProgram(userProfile, "Voting Program")
if (program === undefined) { continue }
if (program.payload === undefined) { continue }
distributeProgram(program)
}
/* Bonus Calculation is here */
UI.projects.governance.utilities.bonusProgram.run(
pools,
userProfiles,
"votingProgram",
"Voting-Bonus",
"Voting Program"
)
function resetVotes(node) {
resetNode(node, 0)
function resetNode(node, generation) {
if (generation >= MAX_GENERATIONS) {
return
}
if (node === undefined) { return }
if (node.payload === undefined) { return }
if (node.payload.votingProgram === undefined) {
node.payload.votingProgram = {
votes: 0,
ownPower: 0,
incomingPower: 0,
usedPower: 0
}
} else {
node.payload.votingProgram.votes = 0
node.payload.votingProgram.ownPower = 0
node.payload.votingProgram.incomingPower = 0
node.payload.votingProgram.usedPower = 0
}
/*
When we reach certain node types, we will halt the distribution, because these are targets for
voting power.
*/
if (
node.type === 'Position' ||
node.type === 'Asset' ||
node.type === 'Feature' ||
node.type === 'Pool' ||
node.type === 'Position Contribution Claim' ||
node.type === 'Asset Contribution Claim' ||
node.type === 'Feature Contribution Claim'
) { return }
/*
For Votes to Profiles there is a special treamtment that needs to be done
so that votes can flow from Profiles to the Program without being affected
by Percentages.
*/
switch (node.type) {
case 'User Profile Vote': {
if (node.payload.referenceParent !== undefined) {
resetNode(node.payload.referenceParent, generation + 1)
return
}
break
}
case 'User Profile': {
let program = UI.projects.governance.utilities.validations.onlyOneProgram(node, 'Voting Program')
if (program === undefined) { return }
if (program.payload === undefined) { return }
resetNode(program, generation)
return
}
}
/*
If there is a reference parent defined, this means that the voting power is
transfered to it and not distributed among children.
*/
if (
node.payload.referenceParent !== undefined &&
node.type !== 'Votes Switch' &&
node.type !== 'Claim Votes Switch' &&
node.type !== 'Weight Votes Switch'
) {
resetNode(node.payload.referenceParent, generation)
return
}
/*
Here we are inside the Voting Program, so we will crawl all it's children.
*/
let schemaDocument = getSchemaDocument(node)
if (schemaDocument === undefined) { return }
if (schemaDocument.childrenNodesProperties !== undefined) {
for (let i = 0; i < schemaDocument.childrenNodesProperties.length; i++) {
let property = schemaDocument.childrenNodesProperties[i]
if (node.type === 'User Profile' && property.name !== "votingProgram") { continue }
switch (property.type) {
case 'node': {
let childNode = node[property.name]
if (childNode === undefined) { continue }
if (childNode.type === 'Tokens Bonus') { continue }
resetNode(childNode, generation)
}
break
case 'array': {
let propertyArray = node[property.name]
if (propertyArray !== undefined) {
for (let m = 0; m < propertyArray.length; m++) {
let childNode = propertyArray[m]
if (childNode.type === 'Tokens Bonus') { continue }
resetNode(childNode, generation)
}
}
break
}
}
}
}
}
}
function distributeProgram(programNode) {
if (programNode.payload === undefined) { return }
/*
Transform Token Power into Votes
*/
let votes = programNode.payload.tokenPower
/*
Set this initial votes as own power
*/
programNode.payload.votingProgram.ownPower = votes
distributeProgramPower(programNode, programNode, votes, undefined, 0)
function distributeProgramPower(
currentProgramNode,
node,
votes,
percentage,
generation
) {
if (generation >= MAX_GENERATIONS) {
return
}
if (node === undefined) { return }
if (node.payload === undefined) { return }
if (node.payload.votingProgram === undefined) { return }
node.payload.votingProgram.votes = node.payload.votingProgram.votes + votes
if (node.type === 'Voting Program') {
node.payload.votingProgram.incomingPower = node.payload.votingProgram.votes - node.payload.votingProgram.ownPower
}
drawVotes(node, node.payload.votingProgram.votes, percentage)
/*
When we reach certain node types, we will halt the distribution, because these are targets for
voting power.
*/
if (
node.type === 'Position' ||
node.type === 'Asset' ||
node.type === 'Feature' ||
node.type === 'Pool' ||
node.type === 'Position Contribution Claim' ||
node.type === 'Asset Contribution Claim' ||
node.type === 'Feature Contribution Claim'
) { return }
/*
For Votes to Profiles there is a special treamtment that needs to be done
so that votes can flow from Profiles to the Program without being affected
by Percentages.
*/
switch (node.type) {
case 'User Profile Vote': {
if (node.payload.referenceParent !== undefined) {
currentProgramNode.payload.votingProgram.usedPower = currentProgramNode.payload.votingProgram.usedPower + votes
distributeProgramPower(
currentProgramNode,
node.payload.referenceParent,
votes / 10,
undefined,
generation + 1
)
}
return
}
case 'User Profile': {
let program = UI.projects.governance.utilities.validations.onlyOneProgram(node, 'Voting Program')
if (program === undefined) { return }
if (program.payload === undefined) { return }
distributeProgramPower(
currentProgramNode,
program,
votes,
undefined,
generation
)
return
}
}
/*
If there is a reference parent defined, this means that the voting power is
transfered to it and not distributed among children.
*/
if (
node.payload.referenceParent !== undefined &&
node.type !== 'Votes Switch' &&
node.type !== 'Claim Votes Switch' &&
node.type !== 'Weight Votes Switch'
) {
currentProgramNode.payload.votingProgram.usedPower = currentProgramNode.payload.votingProgram.usedPower + votes
distributeProgramPower(
currentProgramNode,
node.payload.referenceParent,
votes,
undefined,
generation
)
return
}
/*
Here we are inside the Voting Program, so we will crawl all it's children.
*/
let schemaDocument = getSchemaDocument(node)
if (schemaDocument === undefined) { return }
if (schemaDocument.childrenNodesProperties !== undefined) {
/*
Before distributing the voting power, we will calculate how the power
is going to be switched between all nodes. The first pass is about
scanning all sibling nodes to see which ones have a percentage defined
at their config, and check that all percentages don't add more than 100.
*/
let totalPercentage = 0
let totalNodesWithoutPercentage = 0
for (let i = 0; i < schemaDocument.childrenNodesProperties.length; i++) {
let property = schemaDocument.childrenNodesProperties[i]
switch (property.type) {
case 'node': {
let childNode = node[property.name]
if (childNode === undefined) { continue }
if (childNode.type === 'Tokens Bonus') { continue }
let percentage = UI.projects.foundations.utilities.nodeConfig.loadConfigProperty(childNode.payload, 'percentage')
if (percentage !== undefined && isNaN(percentage) !== true) {
totalPercentage = totalPercentage + percentage
} else {
totalNodesWithoutPercentage++
}
}
break
case 'array': {
let propertyArray = node[property.name]
if (propertyArray !== undefined) {
for (let m = 0; m < propertyArray.length; m++) {
let childNode = propertyArray[m]
if (childNode === undefined) { continue }
if (childNode.type === 'Tokens Bonus') { continue }
let percentage = UI.projects.foundations.utilities.nodeConfig.loadConfigProperty(childNode.payload, 'percentage')
if (percentage !== undefined && isNaN(percentage) !== true) {
totalPercentage = totalPercentage + percentage
} else {
totalNodesWithoutPercentage++
}
}
}
break
}
}
}
if (totalPercentage > 100) {
node.payload.uiObject.setErrorMessage('Voting Power Switching Error. Total Percentage of children nodes is grater that 100.')
return
}
let defaultPercentage = 0
if (totalNodesWithoutPercentage > 0) {
defaultPercentage = (100 - totalPercentage) / totalNodesWithoutPercentage
}
/*
Here we do the actual distribution.
*/
for (let i = 0; i < schemaDocument.childrenNodesProperties.length; i++) {
let property = schemaDocument.childrenNodesProperties[i]
switch (property.type) {
case 'node': {
let childNode = node[property.name]
if (childNode === undefined) { continue }
if (childNode.type === 'Tokens Bonus') { continue }
let percentage = UI.projects.foundations.utilities.nodeConfig.loadConfigProperty(childNode.payload, 'percentage')
if (percentage === undefined || isNaN(percentage) === true) {
percentage = defaultPercentage
}
distributeProgramPower(
currentProgramNode,
childNode,
votes * percentage / 100,
percentage,
generation
)
}
break
case 'array': {
let propertyArray = node[property.name]
if (propertyArray !== undefined) {
for (let m = 0; m < propertyArray.length; m++) {
let childNode = propertyArray[m]
if (childNode === undefined) { continue }
if (childNode.type === 'Tokens Bonus') { continue }
let percentage = UI.projects.foundations.utilities.nodeConfig.loadConfigProperty(childNode.payload, 'percentage')
if (percentage === undefined || isNaN(percentage) === true) {
percentage = defaultPercentage
}
distributeProgramPower(
currentProgramNode,
childNode,
votes * percentage / 100,
percentage,
generation
)
}
}
break
}
}
}
}
}
}
function drawVotes(node, votes, percentage) {
if (node.payload !== undefined) {
if (node.type === 'User Profile') {
return
}
if (node.type === 'Voting Program') {
drawProgram(node)
if (percentage !== undefined) {
node.payload.uiObject.setPercentage(percentage.toFixed(2))
}
return
}
if (node.type === 'User Profile Vote') {
drawUserNode(node, votes, percentage)
return
}
if (
node.type === 'Position' ||
node.type === 'Position Class' ||
node.type === 'Pool' ||
node.type === 'Tokens Switch' ||
node.type === 'Asset' ||
node.type === 'Asset Class' ||
node.type === 'Feature' ||
node.type === 'Feature Class' ||
node.type === 'Position Contribution Claim' ||
node.type === 'Asset Contribution Claim' ||
node.type === 'Feature Contribution Claim'
) {
node.payload.uiObject.valueAngleOffset = 0
node.payload.uiObject.valueAtAngle = false
node.payload.uiObject.percentageAngleOffset = 0
node.payload.uiObject.percentageAtAngle = false
} else {
node.payload.uiObject.valueAngleOffset = 180
node.payload.uiObject.valueAtAngle = true
node.payload.uiObject.percentageAngleOffset = 180
node.payload.uiObject.percentageAtAngle = true
}
let voteType = 'Voting Power'
if (
node.type.indexOf('Weight') >= 0 ||
node.type.indexOf('Pool') >= 0 ||
node.type.indexOf('Feature') >= 0 ||
node.type.indexOf('Asset') >= 0
) {
voteType = 'Weight Power'
}
if (node.type.indexOf('Claim') >= 0) {
voteType = 'Claim Support Power'
}
const votesText = parseFloat(votes.toFixed(0)).toLocaleString('en') + ' ' + voteType
node.payload.uiObject.valueAngleOffset = 0
node.payload.uiObject.valueAtAngle = true
node.payload.uiObject.setValue(votesText)
if (percentage !== undefined) {
node.payload.uiObject.setPercentage(percentage.toFixed(2))
}
}
function drawUserNode(node, votes, percentage) {
if (node.payload !== undefined) {
const outgoingPowerText = parseFloat(votes.toFixed(0)).toLocaleString('en')
node.payload.uiObject.valueAngleOffset = 180
node.payload.uiObject.valueAtAngle = true
node.payload.uiObject.setValue(outgoingPowerText + ' Voting Power')
node.payload.uiObject.percentageAngleOffset = 180
node.payload.uiObject.percentageAtAngle = true
node.payload.uiObject.setPercentage(percentage)
if (node.payload.referenceParent !== undefined) {
node.payload.uiObject.statusAngleOffset = 0
node.payload.uiObject.statusAtAngle = true
node.payload.uiObject.setStatus(outgoingPowerText + ' ' + ' Outgoing Power')
}
}
}
function drawProgram(node) {
if (node.payload === undefined) { return }
if (node.payload.votingProgram === undefined) { return }
if (node.payload.votingProgram.ownPower === undefined) { return }
if (node.payload.votingProgram.incomingPower === undefined) { return }
const ownPowerText = parseFloat(node.payload.votingProgram.ownPower.toFixed(0)).toLocaleString('en')
const incomingPowerText = parseFloat(node.payload.votingProgram.incomingPower.toFixed(0)).toLocaleString('en')
node.payload.uiObject.statusAngleOffset = 0
node.payload.uiObject.statusAtAngle = false
node.payload.uiObject.setStatus(ownPowerText + ' Own Power' + ' + ' + incomingPowerText + ' Incoming Voting Power')
}
}
}
function installMissingVotes(node, rootNodes) {
if (node.payload === undefined) { return }
if (node.payload.referenceParent === undefined) {
node.payload.uiObject.setErrorMessage('To install votes you need a Reference Parent')
return
}
scanNodeBranch(node, node.payload.referenceParent)
function scanNodeBranch(originNode, destinationNode) {
if (
destinationNode.type === 'Pool' ||
destinationNode.type === 'Asset' ||
destinationNode.type === 'Feature' ||
destinationNode.type === 'Position'
) {
originNode.name = destinationNode.name + ' ' + destinationNode.type + ' ' + ' Vote'
} else {
originNode.name = destinationNode.name
}
let schemaDocument = getSchemaDocument(destinationNode)
if (schemaDocument === undefined) { return }
if (schemaDocument.childrenNodesProperties !== undefined) {
for (let i = 0; i < schemaDocument.childrenNodesProperties.length; i++) {
let property = schemaDocument.childrenNodesProperties[i]
switch (property.type) {
case 'node': {
let destinationNodeChild = destinationNode[property.name]
let originNodeChildType = getOriginNodeChildType(destinationNodeChild)
let originNodeChild = UI.projects.foundations.utilities.children.findChildReferencingThisNode(originNode, destinationNodeChild)
if (originNodeChild === undefined) {
originNodeChild = UI.projects.foundations.functionLibraries.uiObjectsFromNodes.addUIObject(originNode, originNodeChildType)
}
UI.projects.foundations.functionLibraries.attachDetach.referenceAttachNode(originNodeChild, destinationNodeChild)
scanNodeBranch(originNodeChild, destinationNodeChild)
}
break
case 'array': {
let propertyArray = destinationNode[property.name]
if (propertyArray !== undefined) {
for (let m = 0; m < propertyArray.length; m++) {
let destinationNodeChild = propertyArray[m]
let originNodeChildType = getOriginNodeChildType(destinationNodeChild)
let originNodeChild = UI.projects.foundations.utilities.children.findChildReferencingThisNode(originNode, destinationNodeChild)
if (originNodeChild === undefined) {
originNodeChild = UI.projects.foundations.functionLibraries.uiObjectsFromNodes.addUIObject(originNode, originNodeChildType)
}
UI.projects.foundations.functionLibraries.attachDetach.referenceAttachNode(originNodeChild, destinationNodeChild)
scanNodeBranch(originNodeChild, destinationNodeChild)
}
}
break
}
}
}
}
}
function getOriginNodeChildType(destinationNode) {
let originNodeType
switch (destinationNode.type) {
case 'Pool Class': {
originNodeType = 'Weight Votes Switch'
break
}
case 'Asset Class': {
originNodeType = 'Weight Votes Switch'
break
}
case 'Feature Class': {
originNodeType = 'Weight Votes Switch'
break
}
case 'Position Class': {
originNodeType = 'Weight Votes Switch'
break
}
case 'Pool': {
originNodeType = 'Pool Weight Vote'
break
}
case 'Asset': {
originNodeType = 'Asset Weight Vote'
break
}
case 'Feature': {
originNodeType = 'Feature Weight Vote'
break
}
case 'Position': {
originNodeType = 'Position Weight Vote'
break
}
case 'Asset Claims Folder': {
originNodeType = 'Claim Votes Switch'
break
}
case 'Asset Contribution Claim': {
originNodeType = 'Asset Claim Vote'
break
}
case 'Feature Claims Folder': {
originNodeType = 'Claim Votes Switch'
break
}
case 'Feature Contribution Claim': {
originNodeType = 'Feature Claim Vote'
break
}
case 'Position Claims Folder': {
originNodeType = 'Claim Votes Switch'
break
}
case 'Position Contribution Claim': {
originNodeType = 'Position Claim Vote'
break
}
}
return originNodeType
}
}
}
@@ -0,0 +1,157 @@
function newGovernanceFunctionLibraryWeights() {
let thisObject = {
calculate: calculate
}
return thisObject
function calculate(
pools,
features,
assets,
positions
) {
/* Weight Calculation Follows */
for (let i = 0; i < assets.length; i++) {
let assetsNode = assets[i]
calculateForNode(assetsNode)
}
/* Weight Calculation Follows */
for (let i = 0; i < features.length; i++) {
let featuresNode = features[i]
calculateForNode(featuresNode)
}
/* Weight Calculation Follows */
for (let i = 0; i < positions.length; i++) {
let positionsNode = positions[i]
calculateForNode(positionsNode)
}
/* Weight Calculation Follows */
for (let i = 0; i < pools.length; i++) {
let poolsNode = pools[i]
calculateForNode(poolsNode)
}
}
function calculateForNode(node) {
let totalVotes = 0
countVotesAndResetWeights(node)
applyWeightCalculation(node)
function countVotesAndResetWeights(node) {
if (node === undefined) { return }
if (node.payload === undefined) { return }
if (
(node.type !== 'Pool Class' &&
node.type !== 'Asset Class' &&
node.type !== 'Feature Class' &&
node.type !== 'Position Class') ||
(
node.type === 'Asset Class' &&
node.payload.referenceParent !== undefined
) ||
(
node.type === 'Feature Class' &&
node.payload.referenceParent !== undefined
)
) {
if (
node.payload.votingProgram !== undefined &&
node.payload.votingProgram.votes !== undefined
) {
totalVotes = totalVotes + node.payload.votingProgram.votes
}
}
node.payload.weight = 0
/*
Now we will count the voting power of this node's children.
*/
let schemaDocument = getSchemaDocument(node)
if (schemaDocument === undefined) { return }
if (schemaDocument.childrenNodesProperties !== undefined) {
for (let i = 0; i < schemaDocument.childrenNodesProperties.length; i++) {
let property = schemaDocument.childrenNodesProperties[i]
switch (property.type) {
case 'node': {
let childNode = node[property.name]
countVotesAndResetWeights(childNode)
}
break
case 'array': {
let propertyArray = node[property.name]
if (propertyArray !== undefined) {
for (let m = 0; m < propertyArray.length; m++) {
let childNode = propertyArray[m]
countVotesAndResetWeights(childNode)
}
}
break
}
}
}
}
}
function applyWeightCalculation(node) {
if (node === undefined) { return }
if (node.payload === undefined) { return }
if (
(node.type !== 'Pool Class' &&
node.type !== 'Asset Class' &&
node.type !== 'Feature Class' &&
node.type !== 'Position Class') ||
(
node.type === 'Asset Class' &&
node.payload.referenceParent !== undefined
) ||
(
node.type === 'Feature Class' &&
node.payload.referenceParent !== undefined
)
) {
if (node.payload.votingProgram !== undefined) {
if (node.payload.votingProgram.votes !== undefined) {
node.payload.weight = node.payload.votingProgram.votes / totalVotes
}
}
}
/*
Now we will count the voting power of this node's children.
*/
let schemaDocument = getSchemaDocument(node)
if (schemaDocument === undefined) { return }
if (schemaDocument.childrenNodesProperties !== undefined) {
for (let i = 0; i < schemaDocument.childrenNodesProperties.length; i++) {
let property = schemaDocument.childrenNodesProperties[i]
switch (property.type) {
case 'node': {
let childNode = node[property.name]
applyWeightCalculation(childNode)
}
break
case 'array': {
let propertyArray = node[property.name]
if (propertyArray !== undefined) {
for (let m = 0; m < propertyArray.length; m++) {
let childNode = propertyArray[m]
applyWeightCalculation(childNode)
}
}
break
}
}
}
}
}
}
}
@@ -0,0 +1,6 @@
function newGovernanceGlobalsReports() {
let thisObject = {
REPORTS_SPACE_WIDTH: 1550
}
return thisObject
}
@@ -0,0 +1,113 @@
function newGovernanceReportsAirdrop() {
let thisObject = {
addHTML: addHTML,
initialize: initialize,
finalize: finalize
}
return thisObject
function initialize() {
}
function finalize() {
}
function addHTML(tabIndex, filters) {
/*
Parameters
*/
let table = 'airdrop'
let programName = 'Airdrop Program'
let programPropertyName = 'airdropProgram'
/*
Setup Filters
*/
let filtersObject
if (filters !== undefined) {
try {
filtersObject = JSON.parse(filters)
} catch (err) { }
}
/*
Other Variables
*/
let tableRecords = []
let tableRecordDefinition = {
"properties": [
{
"name": "name",
"label": "User Profile",
"type": "string",
"order": "ascending",
"textAlign": "left"
},
{
"name": "airdropPower",
"label": "Airdrop Power",
"type": "number",
"order": "descending",
"textAlign": "center",
"format": "2 decimals"
},
{
"name": "tokensAwarded",
"label": "Awarded",
"type": "number",
"order": "descending",
"textAlign": "center",
"format": "2 decimals"
}
]
}
/*
Here we get from the workspace all User Profiles.
*/
let userProfiles = UI.projects.foundations.spaces.designSpace.workspace.getHierarchyHeadsByNodeType('User Profile')
/*
Transform the result array into table records.
*/
for (let j = 0; j < userProfiles.length; j++) {
let userProfile = userProfiles[j]
if (userProfile.tokenPowerSwitch === undefined) { continue }
let program = UI.projects.governance.utilities.validations.onlyOneProgram(userProfile, programName)
if (program === undefined) { continue }
if (program.payload === undefined) { continue }
if (program.payload[programPropertyName] === undefined) { continue }
let tableRecord = {
"name": userProfile.name,
"airdropPower": program.payload[programPropertyName].ownPower | 0,
"tokensAwarded": program.payload[programPropertyName].awarded.tokens | 0
}
if (UI.projects.governance.utilities.filters.applyFilters(filters, filtersObject, tableRecord) === true) {
tableRecords.push(tableRecord)
}
}
/*
Get the sorting order for this table.
*/
let sortingOrder = UI.projects.governance.spaces.reportsSpace.tablesSortingOrders[table]
/*
Set the default sorting order for this table.
*/
if (sortingOrder === undefined) {
UI.projects.governance.spaces.reportsSpace.tablesSortingOrders[table] = {
property: 'tokensAwarded',
order: 'descending'
}
sortingOrder = UI.projects.governance.spaces.reportsSpace.tablesSortingOrders[table]
}
return UI.projects.governance.utilities.tables.addHTML(
table,
tableRecords,
tableRecordDefinition,
sortingOrder,
tabIndex
)
}
}
@@ -0,0 +1,27 @@
function newGovernanceReportsAssets() {
let thisObject = {
addHTML: addHTML,
initialize: initialize,
finalize: finalize
}
return thisObject
function initialize() {
}
function finalize() {
}
function addHTML(tabIndex, filters) {
return UI.projects.governance.utilities.commonTables.addHTML(
'assets',
'Asset',
'Assets',
tabIndex,
filters
)
}
}
@@ -0,0 +1,113 @@
function newGovernanceReportsClaims() {
let thisObject = {
addHTML: addHTML,
initialize: initialize,
finalize: finalize
}
return thisObject
function initialize() {
}
function finalize() {
}
function addHTML(tabIndex, filters) {
/*
Parameters
*/
let table = 'claims'
let programName = 'Claims Program'
let programPropertyName = 'claimsProgram'
/*
Setup Filters
*/
let filtersObject
if (filters !== undefined) {
try {
filtersObject = JSON.parse(filters)
} catch (err) { }
}
/*
Other Variables
*/
let tableRecords = []
let tableRecordDefinition = {
"properties": [
{
"name": "name",
"label": "User Profile",
"type": "string",
"order": "ascending",
"textAlign": "left"
},
{
"name": "ownPower",
"label": "Claims Power",
"type": "number",
"order": "descending",
"textAlign": "center",
"format": "2 decimals"
},
{
"name": "tokensAwarded",
"label": "Awarded",
"type": "number",
"order": "descending",
"textAlign": "center",
"format": "2 decimals"
}
]
}
/*
Here we get from the workspace all User Profiles.
*/
let userProfiles = UI.projects.foundations.spaces.designSpace.workspace.getHierarchyHeadsByNodeType('User Profile')
/*
Transform the result array into table records.
*/
for (let j = 0; j < userProfiles.length; j++) {
let userProfile = userProfiles[j]
if (userProfile.tokenPowerSwitch === undefined) { continue }
let program = UI.projects.governance.utilities.validations.onlyOneProgram(userProfile, programName)
if (program === undefined) { continue }
if (program.payload === undefined) { continue }
if (program.payload[programPropertyName] === undefined) { continue }
let tableRecord = {
"name": userProfile.name,
"ownPower": program.payload[programPropertyName].ownPower | 0,
"tokensAwarded": program.payload[programPropertyName].awarded.tokens | 0
}
if (UI.projects.governance.utilities.filters.applyFilters(filters, filtersObject, tableRecord) === true) {
tableRecords.push(tableRecord)
}
}
/*
Get the sorting order for this table.
*/
let sortingOrder = UI.projects.governance.spaces.reportsSpace.tablesSortingOrders[table]
/*
Set the default sorting order for this table.
*/
if (sortingOrder === undefined) {
UI.projects.governance.spaces.reportsSpace.tablesSortingOrders[table] = {
property: 'tokensAwarded',
order: 'descending'
}
sortingOrder = UI.projects.governance.spaces.reportsSpace.tablesSortingOrders[table]
}
return UI.projects.governance.utilities.tables.addHTML(
table,
tableRecords,
tableRecordDefinition,
sortingOrder,
tabIndex
)
}
}
@@ -0,0 +1,132 @@
function newGovernanceReportsCommmandInterface() {
let thisObject = {
command: undefined,
detectCommands: detectCommands,
initialize: initialize,
finalize: finalize
}
return thisObject
function initialize() {
}
function finalize() {
}
function detectCommands() {
if (detectGovCommands() === true) { return }
/* If we can not detect any gov or docs commands, then we assume the users is typing a filter */
}
function detectGovCommands() {
if (checkPRsCommand() === undefined) { return true }
if (checkPayCommand() === undefined) { return true }
function checkPRsCommand() {
if (UI.projects.governance.spaces.reportsSpace.commandInterface.command.toLowerCase() === 'gov.help gov.prs') {
UI.projects.education.spaces.docsSpace.navigateTo('Governance', 'Topic', 'Gov PRs Command')
return
}
if (UI.projects.governance.spaces.reportsSpace.commandInterface.command.indexOf('Gov.PRs') !== 0 && UI.projects.governance.spaces.reportsSpace.commandInterface.command.indexOf('gov.prs') !== 0) { return 'Not PRs Commands' }
/* Set up the commit message */
let message = UI.projects.governance.spaces.reportsSpace.commandInterface.command.trim().substring(UI.projects.governance.spaces.reportsSpace.commandInterface.command.indexOf(' ') + 1, UI.projects.governance.spaces.reportsSpace.commandInterface.command.length)
if (message.toLowerCase() === 'gov.prs') {
message = 'Automated PR merging process.'
}
/* Find the Username and Password */
let apisNode = UI.projects.foundations.spaces.designSpace.workspace.getHierarchyHeadByNodeType('APIs')
if (apisNode === undefined) {
UI.projects.education.spaces.docsSpace.navigateTo('Governance', 'Topic', 'Gov Error - Github Credentials Missing', 'Anchor Github Credentials Missing')
return
}
if (apisNode.githubAPI === undefined) {
UI.projects.education.spaces.docsSpace.navigateTo('Governance', 'Topic', 'Gov Error - Github Credentials Missing', 'Anchor Github Credentials Missing')
return
}
let config = JSON.parse(apisNode.githubAPI.config)
if (config.username === undefined || config.username === "") {
UI.projects.education.spaces.docsSpace.navigateTo('Governance', 'Topic', 'Gov Error - Github Credentials Missing', 'Anchor Github Credentials Missing')
return
}
if (config.token === undefined || config.token === "") {
UI.projects.education.spaces.docsSpace.navigateTo('Governance', 'Topic', 'Gov Error - Github Credentials Missing', 'Anchor Github Credentials Missing')
return
}
message = message.replaceAll('#', '_HASHTAG_')
message = message.replaceAll('/', '_SLASH_')
httpRequest(
undefined,
'Gov/PRs/' +
message + '/' +
config.username + '/' +
config.token + '/' +
UI.projects.education.spaces.docsSpace.currentBranch + '/' +
UI.projects.education.spaces.docsSpace.contributionsBranch
, onResponse)
UI.projects.education.spaces.docsSpace.navigateTo('Governance', 'Topic', 'Gov Message - Processing Pull Requests')
return
function onResponse(err, data) {
/* Lets check the result of the call through the http interface */
data = JSON.parse(data)
if (err.result === GLOBAL.DEFAULT_OK_RESPONSE.result && data.result === GLOBAL.DEFAULT_OK_RESPONSE.result) {
UI.projects.education.spaces.docsSpace.navigateTo('Governance', 'Topic', 'Gov Message - Pull Requests Processed')
} else {
UI.projects.education.spaces.docsSpace.navigateTo(
data.docs.project,
data.docs.category,
data.docs.type,
data.docs.anchor,
undefined,
data.docs.placeholder
)
}
}
}
function checkPayCommand() {
if (UI.projects.governance.spaces.reportsSpace.commandInterface.command.toLowerCase() === 'gov.help gov.pay') {
UI.projects.education.spaces.docsSpace.navigateTo('Governance', 'Topic', 'Gov Pay Command')
return
}
if (UI.projects.governance.spaces.reportsSpace.commandInterface.command.indexOf('Gov.Pay') !== 0 && UI.projects.governance.spaces.reportsSpace.commandInterface.command.indexOf('gov.pay') !== 0) { return 'Not Pay Commands' }
httpRequest(undefined, 'Gov/Pay/' + UI.projects.education.spaces.docsSpace.currentBranch, onResponse)
UI.projects.education.spaces.docsSpace.navigateTo('Governance', 'Topic', 'Gov Message - Paying to Contributors')
return
function onResponse(err, data) {
/* Lets check the result of the call through the http interface */
data = JSON.parse(data)
if (err.result === GLOBAL.DEFAULT_OK_RESPONSE.result && data.result === GLOBAL.CUSTOM_OK_RESPONSE.result) {
if (data.message.summary.changes + data.message.summary.deletions + data.message.summary.insertions > 0) {
UI.projects.education.spaces.docsSpace.navigateTo('Governance', 'Topic', 'Gov Message - Pay Done')
} else {
UI.projects.education.spaces.docsSpace.navigateTo('Governance', 'Topic', 'Gov Message - Pay Failed')
}
} else {
UI.projects.education.spaces.docsSpace.navigateTo(
data.docs.project,
data.docs.category,
data.docs.type,
data.docs.anchor,
undefined,
data.docs.placeholder
)
}
}
}
}
}
@@ -0,0 +1,113 @@
function newGovernanceReportsDelegation() {
let thisObject = {
addHTML: addHTML,
initialize: initialize,
finalize: finalize
}
return thisObject
function initialize() {
}
function finalize() {
}
function addHTML(tabIndex, filters) {
/*
Parameters
*/
let table = 'delegation'
let programName = 'Delegation Program'
let programPropertyName = 'delegationProgram'
/*
Setup Filters
*/
let filtersObject
if (filters !== undefined) {
try {
filtersObject = JSON.parse(filters)
} catch (err) { }
}
/*
Other Variables
*/
let tableRecords = []
let tableRecordDefinition = {
"properties": [
{
"name": "name",
"label": "User Profile",
"type": "string",
"order": "ascending",
"textAlign": "left"
},
{
"name": "ownPower",
"label": "Delegate Power",
"type": "number",
"order": "descending",
"textAlign": "center",
"format": "2 decimals"
},
{
"name": "tokensBonus",
"label": "Bonus",
"type": "number",
"order": "descending",
"textAlign": "center",
"format": "2 decimals"
}
]
}
/*
Here we get from the workspace all User Profiles.
*/
let userProfiles = UI.projects.foundations.spaces.designSpace.workspace.getHierarchyHeadsByNodeType('User Profile')
/*
Transform the result array into table records.
*/
for (let j = 0; j < userProfiles.length; j++) {
let userProfile = userProfiles[j]
if (userProfile.tokenPowerSwitch === undefined) { continue }
let program = UI.projects.governance.utilities.validations.onlyOneProgram(userProfile, programName)
if (program === undefined) { continue }
if (program.payload === undefined) { continue }
if (program.payload[programPropertyName] === undefined) { continue }
let tableRecord = {
"name": userProfile.name,
"ownPower": program.payload[programPropertyName].ownPower | 0,
"tokensBonus": program.payload[programPropertyName].bonus.tokens | 0
}
if (UI.projects.governance.utilities.filters.applyFilters(filters, filtersObject, tableRecord) === true) {
tableRecords.push(tableRecord)
}
}
/*
Get the sorting order for this table.
*/
let sortingOrder = UI.projects.governance.spaces.reportsSpace.tablesSortingOrders[table]
/*
Set the default sorting order for this table.
*/
if (sortingOrder === undefined) {
UI.projects.governance.spaces.reportsSpace.tablesSortingOrders[table] = {
property: 'tokensBonus',
order: 'descending'
}
sortingOrder = UI.projects.governance.spaces.reportsSpace.tablesSortingOrders[table]
}
return UI.projects.governance.utilities.tables.addHTML(
table,
tableRecords,
tableRecordDefinition,
sortingOrder,
tabIndex
)
}
}
@@ -0,0 +1,27 @@
function newGovernanceReportsFeatures() {
let thisObject = {
addHTML: addHTML,
initialize: initialize,
finalize: finalize
}
return thisObject
function initialize() {
}
function finalize() {
}
function addHTML(tabIndex, filters) {
return UI.projects.governance.utilities.commonTables.addHTML(
'features',
'Feature',
'Features',
tabIndex,
filters
)
}
}
@@ -0,0 +1,71 @@
function newGovernanceReportsFiltersHeader() {
let thisObject = {
addFilterHeader: addFilterHeader,
detectEnterOnFiltersBox: detectEnterOnFiltersBox,
setFocusOnFiltersBox: setFocusOnFiltersBox,
render: render,
initialize: initialize,
finalize: finalize
}
let lastFilters = ''
return thisObject
function initialize() {
}
function finalize() {
}
function render() {
let HTML = ''
HTML = HTML + '<div id="governance-search-page-div">'
HTML = HTML + '<center><img src="Images/superalgos-logo.png" class="governance-image-logo-search" width=400></center>'
HTML = HTML + '<center><div class="governance-font-normal governance-search-box"><input class="governance-filter-input" autocomplete="off" autocorrect="off" autocapitalize="off" spellcheck="false"></input></div></center>'
HTML = HTML + '</div>'
let docsContentDiv = document.getElementById('governance-content-div')
docsContentDiv.innerHTML = HTML + UI.projects.education.spaces.docsSpace.footer.addFooter()
UI.projects.governance.spaces.reportsSpace.filtersHeader.detectEnterOnFiltersBox()
UI.projects.governance.spaces.reportsSpace.filtersHeader.setFocusOnFiltersBox()
}
function addFilterHeader() {
let HTML = ''
// Logo & Search Box
HTML = HTML + '<div class="governance-report-page-header">'
HTML = HTML + '<div class="governance-image-logo-report-page"><img src="Images/superalgos-logo.png" width=200></div>'
HTML = HTML + '<div class="governance-report-page-box">'
HTML = HTML + '<input class="governance-filter-input" autocomplete="off" autocorrect="off" autocapitalize="off" spellcheck="false"></input>'
HTML = HTML + '</div>'
HTML = HTML + '</div>'
return HTML
}
function detectEnterOnFiltersBox() {
const element = document.getElementsByClassName("governance-filter-input")[0]
if (UI.projects.education.spaces.docsSpace.commandInterface.command !== undefined) {
element.value = UI.projects.education.spaces.docsSpace.commandInterface.command
}
element.addEventListener("keyup", function (event) {
if (event.key === "Enter" || event.keyCode === 13) {
lastFilters = element.value.trim()
UI.projects.governance.spaces.reportsSpace.reportsPage.render(undefined, lastFilters)
/*
UI.projects.education.spaces.docsSpace.commandInterface.command = element.value.trim()
UI.projects.education.spaces.docsSpace.commandInterface.detectCommands()
*/
}
});
}
function setFocusOnFiltersBox() {
const element = document.getElementsByClassName("governance-filter-input")[0]
element.value = lastFilters
element.focus()
}
}
@@ -0,0 +1,158 @@
function newGovernanceReportsFooter() {
let thisObject = {
addFooter: addFooter,
initialize: initialize,
finalize: finalize
}
return thisObject
function initialize() {
}
function finalize() {
}
function addFooter() {
let HTML = ''
HTML = HTML + '<div id="governance-footer" class="governance-node-html-footer-container">' // Container Starts
// Buttons Section
HTML = HTML + '<div class="governance-node-html-footer-table">'
HTML = HTML + '<div class="governance-footer-row">'
HTML = HTML + '<div class="governance-footer-cell style="white-space: nowrap; overflow-x: auto;" >' // white-space: nowrap; overflow-x: auto; prevents line breaks when combined with display: inline-block;" in the child elements
if (UI.projects.education.spaces.docsSpace.currentDocumentBeingRendered !== undefined) {
HTML = HTML + '<span style="float: right; display: inline-block;" onClick="UI.projects.education.spaces.docsSpace.sharePage()"><button>SHARE</button></span>'
}
HTML = HTML + '<span style="float: right; display: inline-block;" onClick="UI.projects.education.spaces.docsSpace.scrollToElement(\'governance-space-div\')"><button>TO TOP</button></span>'
if (UI.projects.education.spaces.docsSpace.previousDocumentBeingRendered !== undefined) {
HTML = HTML + '<span style="float: right; display: inline-block;" onClick="UI.projects.education.spaces.docsSpace.navigateTo(\'' + UI.projects.education.spaces.docsSpace.previousDocumentBeingRendered.project + '\', \'' + UI.projects.education.spaces.docsSpace.previousDocumentBeingRendered.category + '\', \'' + UI.projects.education.spaces.docsSpace.previousDocumentBeingRendered.type + '\')"><button>BACK</button></span>'
}
if (UI.projects.education.spaces.docsSpace.currentBookBeingRendered !== undefined) {
HTML = HTML + '<span style="float: right; display: inline-block;" onClick="UI.projects.education.spaces.docsSpace.navigateTo(\'' + UI.projects.education.spaces.docsSpace.currentBookBeingRendered.project + '\', \'' + UI.projects.education.spaces.docsSpace.currentBookBeingRendered.category + '\', \'' + UI.projects.education.spaces.docsSpace.currentBookBeingRendered.type + '\')"><button>TO BOOK</button></span>'
}
HTML = HTML + '<span style="float: right; display: inline-block;" onClick="UI.projects.education.spaces.docsSpace.navigateTo(\'' + 'Foundations' + '\', \'' + 'Book' + '\', \'' + 'Reviews' + '\')"><button>REVIEWS</button></span>'
HTML = HTML + '<span style="float: right; display: inline-block;" onClick="UI.projects.education.spaces.docsSpace.navigateTo(\'' + 'Foundations' + '\', \'' + 'Book' + '\', \'' + 'Community Data Mines' + '\')"><button>DATA MINES</button></span>'
HTML = HTML + '<span style="float: right; display: inline-block;" onClick="UI.projects.education.spaces.docsSpace.navigateTo(\'' + 'Foundations' + '\', \'' + 'Book' + '\', \'' + 'First Steps Tutorials' + '\')"><button>TUTORIALS</button></span>'
HTML = HTML + '<span style="float: right; display: inline-block;" onClick="UI.projects.education.spaces.docsSpace.navigateTo(\'' + 'Foundations' + '\', \'' + 'Book' + '\', \'' + 'User Manual' + '\')"><button>USER MANUAL</button></span>'
HTML = HTML + '</div>'
HTML = HTML + '</div>'
HTML = HTML + '</div>'
// GitHub Section
HTML = HTML + '<div class="governance-node-html-footer-table">'
HTML = HTML + '<div class="governance-footer-row">'
HTML = HTML + '<div class="governance-footer-cell" style="white-space: nowrap; overflow-x: auto; ">'
HTML = HTML + '<h3 style="display: inline-block;">Manage Your Superalgos Setup and Contributions!</h3>'
HTML = HTML + '</div>'
HTML = HTML + '</div>'
HTML = HTML + '</div>'
HTML = HTML + '<div class="governance-node-html-footer-table">'
HTML = HTML + '<div class="governance-footer-row">'
HTML = HTML + '<div class="governance-footer-cell">'
HTML = HTML + '<h4>About Your Deployment</h4>'
HTML = HTML + 'Superalgos may run from different branches in the repository. The <code class="governance-footer-code">Master</code> branch features the stable version, and the <code class="governance-footer-code">Develop</code> branch the version in development. Use the <code class="governance-footer-code">Plugins-Docs</code> branch to contribute plugins and to the Docs.'
HTML = HTML + '</div>'
HTML = HTML + '<div class="governance-footer-cell">'
HTML = HTML + '<h4>Choose the Current Branch</h4>'
HTML = HTML + 'You are currently running on the <code class="governance-footer-code">' + UI.projects.foundations.utilities.gitBranches.getBranchLabel(UI.projects.education.spaces.docsSpace.currentBranch) + '</code> branch. Switch to:'
HTML = HTML + '<ul>'
HTML = HTML + '<li><a href="#" onClick="UI.projects.education.spaces.docsSpace.changeCurrentBranch(\'master\')">Master</a></li>'
HTML = HTML + '<li><a href="#" onClick="UI.projects.education.spaces.docsSpace.changeCurrentBranch(\'develop\')">Develop</a></li>'
HTML = HTML + '<li><a href="#" onClick="UI.projects.education.spaces.docsSpace.changeCurrentBranch(\'plugins-docs\')">Plugins-Docs</a></li>'
HTML = HTML + '<li><a href="#" onClick="UI.projects.education.spaces.docsSpace.changeCurrentBranch(\'next-version\')">Next-Version</a></li>'
HTML = HTML + '</ul>'
HTML = HTML + '</div>'
HTML = HTML + '<div class="governance-footer-cell">'
HTML = HTML + '<h4>Contributions Branch</h4>'
HTML = HTML + 'You are currently contributing to the <code class="governance-footer-code">' + UI.projects.foundations.utilities.gitBranches.getBranchLabel(UI.projects.education.spaces.docsSpace.contributionsBranch) + '</code> branch. Switch to:'
HTML = HTML + '<ul>'
HTML = HTML + '<li><a href="#" onClick="UI.projects.education.spaces.docsSpace.changeContributionsBranch(\'master\')">Master</code></li>'
HTML = HTML + '<li><a href="#" onClick="UI.projects.education.spaces.docsSpace.changeContributionsBranch(\'develop\')">Develop</a></li>'
HTML = HTML + '<li><a href="#" onClick="UI.projects.education.spaces.docsSpace.changeContributionsBranch(\'plugins-docs\')">Plugins-Docs</a></li>'
HTML = HTML + '<li><a href="#" onClick="UI.projects.education.spaces.docsSpace.changeContributionsBranch(\'next-version\')">Next-Version</a></li>'
HTML = HTML + '</ul>'
HTML = HTML + '</ul>'
HTML = HTML + '</div>'
HTML = HTML + '</div>'
HTML = HTML + '</div>'
// Community Section
HTML = HTML + '<div class="governance-node-html-footer-table">'
HTML = HTML + '<div class="governance-footer-row">'
HTML = HTML + '<div class="governance-footer-cell" style="white-space: nowrap; overflow-x: auto; ">'
HTML = HTML + '<h3 style="display: inline-block;">Meet the Community and the Team!</h3>'
HTML = HTML + '</div>'
HTML = HTML + '</div>'
HTML = HTML + '</div>'
HTML = HTML + '<div class="governance-node-html-footer-table">'
HTML = HTML + '<div class="governance-footer-row">'
HTML = HTML + '<div class="governance-footer-cell">'
HTML = HTML + '<h4>Join the Conversation</h4>'
HTML = HTML + '<p>We have a new <a href="https://discord.gg/CGeKC6WQQb" target="_blank">Discord Server</a> with multiple channels, or you may join the original individual Telegram groups listed to the right.</p>'
HTML = HTML + '</div>'
HTML = HTML + '<div class="governance-footer-cell">'
HTML = HTML + '<h4>In Telegram</h4>'
HTML = HTML + '<ul>'
HTML = HTML + '<li><a href="https://t.me/superalgoscommunity" target="_blank">Community Group</a></li>'
HTML = HTML + '<li><a href="https://t.me/superalgossupport" target="_blank">Technical Support Group</a></li>'
HTML = HTML + '<li><a href="https://t.me/superalgosdevelop" target="_blank">Developers Group</a></li>'
HTML = HTML + '<li><a href="https://t.me/superalgosmachinelearning" target="_blank">Machine Learning Group</a></li>'
HTML = HTML + '<li><a href="https://t.me/superalgosdocs" target="_blank">Docs Group</a></li>'
HTML = HTML + '<li><a href="https://t.me/superalgosuxui" target="_blank">UX/UI Design Group</a></li>'
HTML = HTML + '<li><a href="https://t.me/superalgoscollaborations" target="_blank">Collaborations Group</a></li>'
HTML = HTML + '<li><a href="https://t.me/superalgoscodebase" target="_blank">Codebase Learning Group</a></li>'
HTML = HTML + '<li><a href="https://t.me/superalgos_es" target="_blank">Hablemos en Español!</a></li>'
HTML = HTML + '<li><a href="https://t.me/superalgos_ru" target="_blank">Говорим по русски!</a></li>'
HTML = HTML + '</ul>'
HTML = HTML + '</div>'
HTML = HTML + '<div class="governance-footer-cell">'
HTML = HTML + '<h4>Other Resources</h4>'
HTML = HTML + '<ul>'
HTML = HTML + '<li><a href="https://t.me/superalgos" target="_blank">Official Announcements</a></li>'
HTML = HTML + '<li><a href="https://superalgos.org" target="_blank">Features and Functionality</a></li>'
HTML = HTML + '<li><a href="https://github.com/Superalgos/Superalgos" target="_blank">Main Github Repository</a></li>'
HTML = HTML + '<li><a href="https://www.youtube.com/c/superalgos" target="_blank">Subscribe in YouTube</a></li>'
HTML = HTML + '<li><a href="https://twitter.com/superalgos" target="_blank">Follow us on Twitter</a></li>'
HTML = HTML + '<li><a href="https://www.facebook.com/superalgos" target="_blank">Connect on Facebook</a></li>'
HTML = HTML + '<li><a href="https://medium.com/Superalgos/" target="_blank">Read the Blog</a></li>'
HTML = HTML + '</ul>'
HTML = HTML + '</div>'
HTML = HTML + '</div>'
HTML = HTML + '<div class="governance-footer-row">'
HTML = HTML + '<div class="governance-footer-cell">'
HTML = HTML + '<img src="Images/superalgos-logo-white.png" width="200 px">'
HTML = HTML + '</div>'
HTML = HTML + '</div>'
HTML = HTML + '</div>'
HTML = HTML + '</div>' // Container Ends
return HTML
}
}
@@ -0,0 +1,140 @@
function newGovernanceReportsGithub() {
let thisObject = {
addHTML: addHTML,
initialize: initialize,
finalize: finalize
}
return thisObject
function initialize() {
}
function finalize() {
}
function addHTML(tabIndex, filters) {
/*
Parameters
*/
let table = 'github'
let programName = 'Github Program'
let programPropertyName = 'githubProgram'
/*
Setup Filters
*/
let filtersObject
if (filters !== undefined) {
try {
filtersObject = JSON.parse(filters)
} catch (err) { }
}
/*
Other Variables
*/
let tableRecords = []
let tableRecordDefinition = {
"properties": [
{
"name": "name",
"label": "User Profile",
"type": "string",
"order": "ascending",
"textAlign": "left"
},
{
"name": "githubPower",
"label": "Github Power",
"type": "number",
"order": "descending",
"textAlign": "center",
"format": "2 decimals"
},
{
"name": "stars",
"label": "Stars",
"type": "number",
"order": "descending",
"textAlign": "center",
"format": "integer"
},
{
"name": "watching",
"label": "Watching",
"type": "number",
"order": "descending",
"textAlign": "center",
"format": "integer"
},
{
"name": "forks",
"label": "Forks",
"type": "number",
"order": "descending",
"textAlign": "center",
"format": "integer"
},
{
"name": "tokensAwarded",
"label": "Awarded",
"type": "number",
"order": "descending",
"textAlign": "center",
"format": "2 decimals"
}
]
}
/*
Here we get from the workspace all User Profiles.
*/
let userProfiles = UI.projects.foundations.spaces.designSpace.workspace.getHierarchyHeadsByNodeType('User Profile')
/*
Transform the result array into table records.
*/
for (let j = 0; j < userProfiles.length; j++) {
let userProfile = userProfiles[j]
if (userProfile.tokenPowerSwitch === undefined) { continue }
let program = UI.projects.governance.utilities.validations.onlyOneProgram(userProfile, programName)
if (program === undefined) { continue }
if (program.payload === undefined) { continue }
if (program.payload[programPropertyName] === undefined) { continue }
let tableRecord = {
"name": userProfile.name,
"githubPower": program.payload[programPropertyName].ownPower | 0,
"stars": program.payload[programPropertyName].starsCount | 0,
"watching": program.payload[programPropertyName].watchersCount | 0,
"forks": program.payload[programPropertyName].forksCount | 0,
"tokensAwarded": program.payload[programPropertyName].awarded.tokens | 0
}
if (UI.projects.governance.utilities.filters.applyFilters(filters, filtersObject, tableRecord) === true) {
tableRecords.push(tableRecord)
}
}
/*
Get the sorting order for this table.
*/
let sortingOrder = UI.projects.governance.spaces.reportsSpace.tablesSortingOrders[table]
/*
Set the default sorting order for this table.
*/
if (sortingOrder === undefined) {
UI.projects.governance.spaces.reportsSpace.tablesSortingOrders[table] = {
property: 'tokensAwarded',
order: 'descending'
}
sortingOrder = UI.projects.governance.spaces.reportsSpace.tablesSortingOrders[table]
}
return UI.projects.governance.utilities.tables.addHTML(
table,
tableRecords,
tableRecordDefinition,
sortingOrder,
tabIndex
)
}
}
@@ -0,0 +1,27 @@
function newGovernanceReportsInfluencers() {
let thisObject = {
addHTML: addHTML,
initialize: initialize,
finalize: finalize
}
return thisObject
function initialize() {
}
function finalize() {
}
function addHTML(tabIndex, filters) {
return UI.projects.governance.utilities.decendentTables.addHTML(
'influencers',
'Influencer Program',
'influencerProgram',
tabIndex,
filters
)
}
}
@@ -0,0 +1,27 @@
function newGovernanceReportsMentors() {
let thisObject = {
addHTML: addHTML,
initialize: initialize,
finalize: finalize
}
return thisObject
function initialize() {
}
function finalize() {
}
function addHTML(tabIndex, filters) {
return UI.projects.governance.utilities.decendentTables.addHTML(
'mentors',
'Mentorship Program',
'mentorshipProgram',
tabIndex,
filters
)
}
}
@@ -0,0 +1,134 @@
function newGovernanceReportsMining() {
let thisObject = {
addHTML: addHTML,
initialize: initialize,
finalize: finalize
}
return thisObject
function initialize() {
}
function finalize() {
}
function addHTML(tabIndex, filters) {
/*
Setup Filters
*/
let filtersObject
if (filters !== undefined) {
try {
filtersObject = JSON.parse(filters)
} catch (err) { }
}
/*
Other Variables
*/
let tableRecords = []
let table = 'mining'
let tableRecordDefinition = {
"properties": [
{
"name": "name",
"label": "User Profile",
"type": "string",
"order": "ascending",
"textAlign": "left"
},
{
"name": "blockchainAccount",
"label": "Blockchain Account",
"type": "string",
"order": "ascending",
"textAlign": "center"
},
{
"name": "tokensAwarded",
"label": "Tokens Awarded",
"type": "number",
"order": "descending",
"textAlign": "center",
"format": "integer"
},
{
"name": "tokensBonus",
"label": "Tokens Bonus",
"type": "number",
"order": "descending",
"textAlign": "center",
"format": "integer"
},
{
"name": "tokensMined",
"label": "Tokens Mined",
"type": "number",
"order": "descending",
"textAlign": "center",
"format": "integer"
},
{
"name": "minedInBTC",
"label": "Mined In BTC",
"type": "number",
"order": "descending",
"textAlign": "center",
"format": "text"
}
]
}
/*
Here we get from the workspace all User Profiles.
*/
let userProfiles = UI.projects.foundations.spaces.designSpace.workspace.getHierarchyHeadsByNodeType('User Profile')
/*
Transform the result array into table records.
*/
for (let j = 0; j < userProfiles.length; j++) {
let userProfile = userProfiles[j]
if (userProfile.payload === undefined) { continue }
if (userProfile.tokensMined === undefined) { continue }
if (userProfile.tokensMined.payload === undefined) { continue }
if (userProfile.tokensMined.payload.tokensMined === undefined) { continue }
let tableRecord = {
"name": userProfile.name,
"blockchainAccount": userProfile.payload.blockchainAccount,
"tokensAwarded": userProfile.tokensMined.payload.tokensMined.awarded | 0,
"tokensBonus": userProfile.tokensMined.payload.tokensMined.bonus | 0,
"tokensMined": userProfile.tokensMined.payload.tokensMined.total | 0,
"minedInBTC": UI.projects.governance.utilities.conversions.estimateSATokensInBTC(userProfile.tokensMined.payload.tokensMined.total | 0)
}
if (UI.projects.governance.utilities.filters.applyFilters(filters, filtersObject, tableRecord) === true) {
tableRecords.push(tableRecord)
}
}
/*
Get the sorting order for this table.
*/
let sortingOrder = UI.projects.governance.spaces.reportsSpace.tablesSortingOrders[table]
/*
Set the default sorting order for this table.
*/
if (sortingOrder === undefined) {
UI.projects.governance.spaces.reportsSpace.tablesSortingOrders[table] = {
property: 'tokensMined',
order: 'descending'
}
sortingOrder = UI.projects.governance.spaces.reportsSpace.tablesSortingOrders[table]
}
return UI.projects.governance.utilities.tables.addHTML(
table,
tableRecords,
tableRecordDefinition,
sortingOrder,
tabIndex
)
}
}
@@ -0,0 +1,27 @@
function newGovernanceReportsPools() {
let thisObject = {
addHTML: addHTML,
initialize: initialize,
finalize: finalize
}
return thisObject
function initialize() {
}
function finalize() {
}
function addHTML(tabIndex, filters) {
return UI.projects.governance.utilities.commonTables.addHTML(
'pools',
'Pool',
'Pools',
tabIndex,
filters
)
}
}
@@ -0,0 +1,27 @@
function newGovernanceReportsPositions() {
let thisObject = {
addHTML: addHTML,
initialize: initialize,
finalize: finalize
}
return thisObject
function initialize() {
}
function finalize() {
}
function addHTML(tabIndex, filters) {
return UI.projects.governance.utilities.commonTables.addHTML(
'positions',
'Position',
'Positions',
tabIndex,
filters
)
}
}
@@ -0,0 +1,27 @@
function newGovernanceReportsReferrals() {
let thisObject = {
addHTML: addHTML,
initialize: initialize,
finalize: finalize
}
return thisObject
function initialize() {
}
function finalize() {
}
function addHTML(tabIndex, filters) {
return UI.projects.governance.utilities.decendentTables.addHTML(
'referrals',
'Referral Program',
'referralProgram',
tabIndex,
filters
)
}
}
@@ -0,0 +1,209 @@
function newGovernanceReportsReportsPage() {
let thisObject = {
render: render,
initialize: initialize,
finalize: finalize
}
let lastTabIndex
return thisObject
function initialize() {
}
function finalize() {
}
function render(tabIndex, filters) {
/* Setup tabIndex */
if (tabIndex === undefined) {
tabIndex = lastTabIndex
} else {
lastTabIndex = tabIndex
}
let resultsArary = []
let initialTime = new Date()
buildHTML()
function buildHTML() {
const tabs = [
'Profiles',
'Airdrop',
'Github',
'Referrals',
'Supporters',
'Mentors',
'Influencers',
'Claims',
'Votes',
'Staking',
'Delegation',
'Pools',
'Assets',
'Features',
'Positions',
'Mining'
]
let HTML = ''
HTML = HTML + '<section id="governance-report-page-div" class="governance-search-page-container">'
HTML = HTML + UI.projects.governance.spaces.reportsSpace.filtersHeader.addFilterHeader()
// Tabs
HTML = HTML + '<div class="governance-report-page-header-tabs-container">'
let checked = ' checked=""'
for (let i = 0; i < tabs.length; i++) {
let tab = tabs[i]
HTML = HTML + '<input id="governance-tab' + (i + 1) + '" type="radio" name="tabs"' + checked + '><label for="governance-tab' + (i + 1) + '">' + tab + '</label>'
checked = ''
}
// Results
HTML = HTML + '<div class="governance-search-result-content">'
let totalResults = new Map()
for (let i = 0; i < tabs.length; i++) {
let tab = tabs[i]
HTML = HTML + '<div id="content' + (i + 1) + '">'
HTML = HTML + '<p> ' + tab.toUpperCase() + '_TOTAL_RESULTS results (' + tab.toUpperCase() + '_TOTAL_SECONDS seconds)</p>'
let resultCounter = 0
switch (tab) {
case 'Profiles': {
let response = UI.projects.governance.spaces.reportsSpace.userProfiles.addHTML(1, filters)
HTML = HTML + response.HTML
resultCounter = response.resultCounter
break
}
case 'Airdrop': {
let response = UI.projects.governance.spaces.reportsSpace.airdrop.addHTML(2, filters)
HTML = HTML + response.HTML
resultCounter = response.resultCounter
break
}
case 'Github': {
let response = UI.projects.governance.spaces.reportsSpace.github.addHTML(3, filters)
HTML = HTML + response.HTML
resultCounter = response.resultCounter
break
}
case 'Referrals': {
let response = UI.projects.governance.spaces.reportsSpace.referrals.addHTML(4, filters)
HTML = HTML + response.HTML
resultCounter = response.resultCounter
break
}
case 'Supporters': {
let response = UI.projects.governance.spaces.reportsSpace.supports.addHTML(5, filters)
HTML = HTML + response.HTML
resultCounter = response.resultCounter
break
}
case 'Mentors': {
let response = UI.projects.governance.spaces.reportsSpace.mentors.addHTML(6, filters)
HTML = HTML + response.HTML
resultCounter = response.resultCounter
break
}
case 'Influencers': {
let response = UI.projects.governance.spaces.reportsSpace.influencers.addHTML(7, filters)
HTML = HTML + response.HTML
resultCounter = response.resultCounter
break
}
case 'Claims': {
let response = UI.projects.governance.spaces.reportsSpace.claims.addHTML(8, filters)
HTML = HTML + response.HTML
resultCounter = response.resultCounter
break
}
case 'Votes': {
let response = UI.projects.governance.spaces.reportsSpace.votes.addHTML(9, filters)
HTML = HTML + response.HTML
resultCounter = response.resultCounter
break
}
case 'Staking': {
let response = UI.projects.governance.spaces.reportsSpace.staking.addHTML(10, filters)
HTML = HTML + response.HTML
resultCounter = response.resultCounter
break
}
case 'Delegation': {
let response = UI.projects.governance.spaces.reportsSpace.delegation.addHTML(11, filters)
HTML = HTML + response.HTML
resultCounter = response.resultCounter
break
}
case 'Pools': {
let response = UI.projects.governance.spaces.reportsSpace.pools.addHTML(12, filters)
HTML = HTML + response.HTML
resultCounter = response.resultCounter
break
}
case 'Assets': {
let response = UI.projects.governance.spaces.reportsSpace.assets.addHTML(13, filters)
HTML = HTML + response.HTML
resultCounter = response.resultCounter
break
}
case 'Features': {
let response = UI.projects.governance.spaces.reportsSpace.features.addHTML(14, filters)
HTML = HTML + response.HTML
resultCounter = response.resultCounter
break
}
case 'Positions': {
let response = UI.projects.governance.spaces.reportsSpace.positions.addHTML(15, filters)
HTML = HTML + response.HTML
resultCounter = response.resultCounter
break
}
case 'Mining': {
let response = UI.projects.governance.spaces.reportsSpace.mining.addHTML(16, filters)
HTML = HTML + response.HTML
resultCounter = response.resultCounter
break
}
}
HTML = HTML + '</div>'
totalResults.set(tab, resultCounter)
}
// End Content
HTML = HTML + '</div>'
HTML = HTML + '</div>'
// End Section
HTML = HTML + '</section>'
// Total Seconds Calculation
let finalTime = new Date()
let totalSeconds = ((finalTime.valueOf() - initialTime.valueOf()) / 1000).toFixed(3)
for (let i = 0; i < tabs.length; i++) {
let tab = tabs[i]
HTML = HTML.replace(tab.toUpperCase() + '_TOTAL_SECONDS', totalSeconds)
let resultCounter = totalResults.get(tab)
HTML = HTML.replace(tab.toUpperCase() + '_TOTAL_RESULTS', resultCounter)
}
let docsContentDiv = document.getElementById('governance-content-div')
docsContentDiv.innerHTML = HTML + UI.projects.governance.spaces.reportsSpace.footer.addFooter()
UI.projects.governance.spaces.reportsSpace.filtersHeader.detectEnterOnFiltersBox()
UI.projects.governance.spaces.reportsSpace.filtersHeader.setFocusOnFiltersBox()
// If there is a tabIndex we will switch to that tab here.
if (tabIndex !== undefined) {
let tab = document.getElementById('governance-tab' + tabIndex)
tab.checked = true
}
}
}
}
@@ -0,0 +1,332 @@
function newGobernanceReportsSpace() {
const MODULE_NAME = 'Reports Space'
let thisObject = {
container: undefined,
sidePanelTab: undefined,
reportsPage: undefined,
footer: undefined,
filtersHeader: undefined,
userProfiles: undefined,
referrals: undefined,
supports: undefined,
mentors: undefined,
influencers: undefined,
claims: undefined,
votes: undefined,
staking: undefined,
delegations: undefined,
github: undefined,
airdrop: undefined,
pools: undefined,
assets: undefined,
features: undefined,
positions: undefined,
mining: undefined,
tablesSortingOrders: undefined,
changeTableSortingOrder,
physics: physics,
draw: draw,
getContainer: getContainer,
finalize: finalize,
initialize: initialize,
reset: reset
}
let browserResizedEventSubscriptionId
let openingEventSubscriptionId
let closingEventSubscriptionId
let isInitialized = false
return thisObject
function finalize() {
if (isInitialized === false) { return }
thisObject.container.finalize()
thisObject.container = undefined
canvas.eventHandler.stopListening(browserResizedEventSubscriptionId)
thisObject.sidePanelTab.container.eventHandler.stopListening(openingEventSubscriptionId)
thisObject.sidePanelTab.container.eventHandler.stopListening(closingEventSubscriptionId)
thisObject.sidePanelTab = undefined
UI.projects.foundations.spaces.sideSpace.deleteSidePanelTab('Governance', 'governance-tab', 'Gov', 'right')
thisObject.reportsPage.finalize()
thisObject.reportsPage = undefined
thisObject.footer.finalize()
thisObject.footer = undefined
thisObject.filtersHeader.finalize()
thisObject.filtersHeader = undefined
thisObject.userProfiles.finalize()
thisObject.userProfiles = undefined
thisObject.referrals.finalize()
thisObject.referrals = undefined
thisObject.supports.finalize()
thisObject.supports = undefined
thisObject.mentors.finalize()
thisObject.mentors = undefined
thisObject.influencers.finalize()
thisObject.influencers = undefined
thisObject.claims.finalize()
thisObject.claims = undefined
thisObject.votes.finalize()
thisObject.votes = undefined
thisObject.staking.finalize()
thisObject.staking = undefined
thisObject.delegation.finalize()
thisObject.delegation = undefined
thisObject.github.finalize()
thisObject.github = undefined
thisObject.airdrop.finalize()
thisObject.airdrop = undefined
thisObject.pools.finalize()
thisObject.pools = undefined
thisObject.assets.finalize()
thisObject.assets = undefined
thisObject.features.finalize()
thisObject.features = undefined
thisObject.positions.finalize()
thisObject.positions = undefined
thisObject.mining.finalize()
thisObject.mining = undefined
isInitialized = false
}
function initialize() {
/*
If the workspace is not related to governance, then we exit the Intialize Function
*/
let resultsArary = UI.projects.foundations.spaces.designSpace.workspace.getHierarchyHeadsByNodeType('User Profile')
if (resultsArary.length === 0) { return }
thisObject.container = newContainer()
thisObject.container.name = MODULE_NAME
thisObject.container.initialize()
thisObject.container.isClickeable = true
thisObject.container.isDraggeable = false
thisObject.container.detectMouseOver = true
thisObject.container.status = 'hidden'
resize()
thisObject.reportsPage = newGovernanceReportsReportsPage()
thisObject.footer = newGovernanceReportsFooter()
thisObject.filtersHeader = newGovernanceReportsFiltersHeader()
thisObject.userProfiles = newGovernanceReportsUserProfiles()
thisObject.referrals = newGovernanceReportsReferrals()
thisObject.supports = newGovernanceReportsSupports()
thisObject.influencers = newGovernanceReportsInfluencers()
thisObject.mentors = newGovernanceReportsMentors()
thisObject.claims = newGovernanceReportsClaims()
thisObject.votes = newGovernanceReportsVotes()
thisObject.staking = newGovernanceReportsStaking()
thisObject.delegation = newGovernanceReportsDelegation()
thisObject.github = newGovernanceReportsGithub()
thisObject.airdrop = newGovernanceReportsAirdrop()
thisObject.pools = newGovernanceReportsPools()
thisObject.assets = newGovernanceReportsAssets()
thisObject.features = newGovernanceReportsFeatures()
thisObject.positions = newGovernanceReportsPositions()
thisObject.mining = newGovernanceReportsMining()
thisObject.reportsPage.initialize()
thisObject.footer.initialize()
thisObject.filtersHeader.initialize()
thisObject.userProfiles.initialize()
thisObject.referrals.initialize()
thisObject.supports.initialize()
thisObject.mentors.initialize()
thisObject.influencers.initialize()
thisObject.claims.initialize()
thisObject.votes.initialize()
thisObject.staking.initialize()
thisObject.delegation.initialize()
thisObject.github.initialize()
thisObject.airdrop.initialize()
thisObject.pools.initialize()
thisObject.assets.initialize()
thisObject.features.initialize()
thisObject.positions.initialize()
thisObject.mining.initialize()
setupSidePanelTab()
thisObject.tablesSortingOrders = {}
isInitialized = true
function setupSidePanelTab() {
thisObject.sidePanelTab = UI.projects.foundations.spaces.sideSpace.createSidePanelTab(thisObject.container, 'Governance', 'governance-tab', 'Gov', 'right')
openingEventSubscriptionId = thisObject.sidePanelTab.container.eventHandler.listenToEvent('opening', onOpening)
closingEventSubscriptionId = thisObject.sidePanelTab.container.eventHandler.listenToEvent('closing', onClosing)
browserResizedEventSubscriptionId = canvas.eventHandler.listenToEvent('Browser Resized', resize)
}
}
function reset() {
finalize()
initialize()
}
function resize() {
thisObject.container.frame.width = UI.projects.governance.globals.reports.REPORTS_SPACE_WIDTH
thisObject.container.frame.height = browserCanvas.height // - TOP_SPACE_HEIGHT
thisObject.container.frame.position.x = browserCanvas.width
thisObject.container.frame.position.y = 0 // TOP_SPACE_HEIGHT
if (thisObject.sidePanelTab !== undefined) {
thisObject.sidePanelTab.resize()
}
}
function physics() {
if (isInitialized === false) { return }
docsAppDivPhysics()
function docsAppDivPhysics() {
let docsSpaceDiv = document.getElementById('governance-reports-space-div')
docsAppDivPosition = {
x: 0,
y: 0
}
docsAppDivPosition = thisObject.container.frame.frameThisPoint(docsAppDivPosition)
docsSpaceDiv.style = ' ' +
'overflow-y: scroll;' +
'overflow-x: hidden;' +
'position:fixed; top:' + docsAppDivPosition.y + 'px; ' +
'left:' + docsAppDivPosition.x + 'px; z-index:1; ' +
'width: ' + thisObject.container.frame.width + 'px;' +
'height: ' + thisObject.container.frame.height + 'px'
}
}
function getContainer(point, purpose) {
if (isInitialized === false) { return }
if (thisObject.sidePanelTab === undefined) { return }
let container
container = thisObject.sidePanelTab.getContainer(point, purpose)
if (container !== undefined) { return container }
if (thisObject.container.frame.isThisPointHere(point, true) === true) {
return thisObject.container
} else {
return undefined
}
}
function changeTableSortingOrder(table, property, order, tabIndex) {
thisObject.tablesSortingOrders[table].property = property
thisObject.tablesSortingOrders[table].order = order
thisObject.reportsPage.render(tabIndex)
}
function onOpening() {
thisObject.reportsPage.render()
}
function onClosing() {
}
function draw() {
if (CAN_SPACES_DRAW === false) { return }
if (isInitialized === false) { return }
borders()
}
function borders() {
let point1
let point2
let point3
let point4
point1 = {
x: 0,
y: 0
}
point2 = {
x: thisObject.container.frame.width,
y: 0
}
point3 = {
x: thisObject.container.frame.width,
y: thisObject.container.frame.height
}
point4 = {
x: 0,
y: thisObject.container.frame.height
}
point1 = thisObject.container.frame.frameThisPoint(point1)
point2 = thisObject.container.frame.frameThisPoint(point2)
point3 = thisObject.container.frame.frameThisPoint(point3)
point4 = thisObject.container.frame.frameThisPoint(point4)
browserCanvasContext.setLineDash([]) // Resets Line Dash
browserCanvasContext.beginPath()
browserCanvasContext.moveTo(point1.x, point1.y)
browserCanvasContext.lineTo(point2.x, point2.y)
browserCanvasContext.lineTo(point3.x, point3.y)
browserCanvasContext.lineTo(point4.x, point4.y)
browserCanvasContext.lineTo(point1.x, point1.y)
browserCanvasContext.closePath()
let opacity = 1
browserCanvasContext.fillStyle = 'rgba(' + UI_COLOR.LIGHT_GREY + ', ' + opacity + ''
browserCanvasContext.fill()
browserCanvasContext.strokeStyle = 'rgba(' + UI_COLOR.GREY + ', ' + opacity + ''
browserCanvasContext.lineWidth = 0.3
browserCanvasContext.stroke()
/* Shadow */
if (thisObject.container.status !== 'hidden') {
for (let i = 0; i <= 30; i++) {
opacity = 1 - (i / 300) - 0.95
browserCanvasContext.setLineDash([]) // Resets Line Dash
browserCanvasContext.beginPath()
browserCanvasContext.moveTo(point2.x + i, point2.y)
browserCanvasContext.lineTo(point3.x + i, point3.y)
browserCanvasContext.closePath()
browserCanvasContext.strokeStyle = 'rgba(' + UI_COLOR.BLACK + ', ' + opacity + ''
browserCanvasContext.lineWidth = 1
browserCanvasContext.stroke()
}
}
}
}
@@ -0,0 +1,113 @@
function newGovernanceReportsStaking() {
let thisObject = {
addHTML: addHTML,
initialize: initialize,
finalize: finalize
}
return thisObject
function initialize() {
}
function finalize() {
}
function addHTML(tabIndex, filters) {
/*
Parameters
*/
let table = 'staking'
let programName = 'Staking Program'
let programPropertyName = 'stakingProgram'
/*
Setup Filters
*/
let filtersObject
if (filters !== undefined) {
try {
filtersObject = JSON.parse(filters)
} catch (err) { }
}
/*
Other Variables
*/
let tableRecords = []
let tableRecordDefinition = {
"properties": [
{
"name": "name",
"label": "User Profile",
"type": "string",
"order": "ascending",
"textAlign": "left"
},
{
"name": "stakingPower",
"label": "Staking Power",
"type": "number",
"order": "descending",
"textAlign": "center",
"format": "2 decimals"
},
{
"name": "tokensAwarded",
"label": "Awarded",
"type": "number",
"order": "descending",
"textAlign": "center",
"format": "2 decimals"
}
]
}
/*
Here we get from the workspace all User Profiles.
*/
let userProfiles = UI.projects.foundations.spaces.designSpace.workspace.getHierarchyHeadsByNodeType('User Profile')
/*
Transform the result array into table records.
*/
for (let j = 0; j < userProfiles.length; j++) {
let userProfile = userProfiles[j]
if (userProfile.tokenPowerSwitch === undefined) { continue }
let program = UI.projects.governance.utilities.validations.onlyOneProgram(userProfile, programName)
if (program === undefined) { continue }
if (program.payload === undefined) { continue }
if (program.payload[programPropertyName] === undefined) { continue }
let tableRecord = {
"name": userProfile.name,
"stakingPower": program.payload[programPropertyName].ownPower | 0,
"tokensAwarded": program.payload[programPropertyName].awarded.tokens | 0
}
if (UI.projects.governance.utilities.filters.applyFilters(filters, filtersObject, tableRecord) === true) {
tableRecords.push(tableRecord)
}
}
/*
Get the sorting order for this table.
*/
let sortingOrder = UI.projects.governance.spaces.reportsSpace.tablesSortingOrders[table]
/*
Set the default sorting order for this table.
*/
if (sortingOrder === undefined) {
UI.projects.governance.spaces.reportsSpace.tablesSortingOrders[table] = {
property: 'tokensAwarded',
order: 'descending'
}
sortingOrder = UI.projects.governance.spaces.reportsSpace.tablesSortingOrders[table]
}
return UI.projects.governance.utilities.tables.addHTML(
table,
tableRecords,
tableRecordDefinition,
sortingOrder,
tabIndex
)
}
}
@@ -0,0 +1,27 @@
function newGovernanceReportsSupports() {
let thisObject = {
addHTML: addHTML,
initialize: initialize,
finalize: finalize
}
return thisObject
function initialize() {
}
function finalize() {
}
function addHTML(tabIndex, filters) {
return UI.projects.governance.utilities.decendentTables.addHTML(
'supports',
'Support Program',
'supportProgram',
tabIndex,
filters
)
}
}
@@ -0,0 +1,112 @@
function newGovernanceReportsUserProfiles() {
let thisObject = {
addHTML: addHTML,
initialize: initialize,
finalize: finalize
}
return thisObject
function initialize() {
}
function finalize() {
}
function addHTML(tabIndex, filters) {
/*
Setup Filters
*/
let filtersObject
if (filters !== undefined) {
try {
filtersObject = JSON.parse(filters)
} catch (err) { }
}
/*
Other Variables
*/
let tableRecords = []
let table = 'userProfiles'
let tableRecordDefinition = {
"properties": [
{
"name": "name",
"label": "User Profile",
"type": "string",
"order": "ascending",
"textAlign": "left"
},
{
"name": "blockchainPower",
"label": "Blockchain Power",
"type": "number",
"order": "descending",
"textAlign": "center",
"format": "2 decimals"
},
{
"name": "delegatedPower",
"label": "Delegated Power",
"type": "number",
"order": "descending",
"textAlign": "center",
"format": "2 decimals"
},
{
"name": "tokenPower",
"label": "Token Power",
"type": "number",
"order": "descending",
"textAlign": "center",
"format": "2 decimals"
}
]
}
/*
Here we get from the workspace all User Profiles.
*/
let userProfiles = UI.projects.foundations.spaces.designSpace.workspace.getHierarchyHeadsByNodeType('User Profile')
/*
Transform the result array into table records.
*/
for (let j = 0; j < userProfiles.length; j++) {
let userProfile = userProfiles[j]
let tableRecord = {
"name": userProfile.name,
"blockchainPower": userProfile.payload.blockchainTokens | 0,
"delegatedPower": userProfile.payload.tokenPower - userProfile.payload.blockchainTokens | 0,
"tokenPower": userProfile.payload.tokenPower | 0
}
if (UI.projects.governance.utilities.filters.applyFilters(filters, filtersObject, tableRecord) === true) {
tableRecords.push(tableRecord)
}
}
/*
Get the sorting order for this table.
*/
let sortingOrder = UI.projects.governance.spaces.reportsSpace.tablesSortingOrders[table]
/*
Set the default sorting order for this table.
*/
if (sortingOrder === undefined) {
UI.projects.governance.spaces.reportsSpace.tablesSortingOrders[table] = {
property: 'blockchainPower',
order: 'descending'
}
sortingOrder = UI.projects.governance.spaces.reportsSpace.tablesSortingOrders[table]
}
return UI.projects.governance.utilities.tables.addHTML(
table,
tableRecords,
tableRecordDefinition,
sortingOrder,
tabIndex
)
}
}
@@ -0,0 +1,122 @@
function newGovernanceReportsVotes() {
let thisObject = {
addHTML: addHTML,
initialize: initialize,
finalize: finalize
}
return thisObject
function initialize() {
}
function finalize() {
}
function addHTML(tabIndex, filters) {
/*
Parameters
*/
let table = 'votes'
let programName = 'Voting Program'
let programPropertyName = 'votingProgram'
/*
Setup Filters
*/
let filtersObject
if (filters !== undefined) {
try {
filtersObject = JSON.parse(filters)
} catch (err) { }
}
/*
Other Variables
*/
let tableRecords = []
let tableRecordDefinition = {
"properties": [
{
"name": "name",
"label": "User Profile",
"type": "string",
"order": "ascending",
"textAlign": "left"
},
{
"name": "ownPower",
"label": "Own Power",
"type": "number",
"order": "descending",
"textAlign": "center",
"format": "2 decimals"
},
{
"name": "incoming",
"label": "Incoming",
"type": "number",
"order": "descending",
"textAlign": "center",
"format": "2 decimals"
},
{
"name": "tokensBonus",
"label": "Bonus",
"type": "number",
"order": "descending",
"textAlign": "center",
"format": "2 decimals"
}
]
}
/*
Here we get from the workspace all User Profiles.
*/
let userProfiles = UI.projects.foundations.spaces.designSpace.workspace.getHierarchyHeadsByNodeType('User Profile')
/*
Transform the result array into table records.
*/
for (let j = 0; j < userProfiles.length; j++) {
let userProfile = userProfiles[j]
if (userProfile.tokenPowerSwitch === undefined) { continue }
let program = UI.projects.governance.utilities.validations.onlyOneProgram(userProfile, programName)
if (program === undefined) { continue }
if (program.payload === undefined) { continue }
if (program.payload[programPropertyName] === undefined) { continue }
let tableRecord = {
"name": userProfile.name,
"ownPower": program.payload[programPropertyName].ownPower | 0,
"incoming": program.payload[programPropertyName].incomingPower | 0,
"tokensBonus": program.payload[programPropertyName].bonus.tokens | 0
}
if (UI.projects.governance.utilities.filters.applyFilters(filters, filtersObject, tableRecord) === true) {
tableRecords.push(tableRecord)
}
}
/*
Get the sorting order for this table.
*/
let sortingOrder = UI.projects.governance.spaces.reportsSpace.tablesSortingOrders[table]
/*
Set the default sorting order for this table.
*/
if (sortingOrder === undefined) {
UI.projects.governance.spaces.reportsSpace.tablesSortingOrders[table] = {
property: 'tokensBonus',
order: 'descending'
}
sortingOrder = UI.projects.governance.spaces.reportsSpace.tablesSortingOrders[table]
}
return UI.projects.governance.utilities.tables.addHTML(
table,
tableRecords,
tableRecordDefinition,
sortingOrder,
tabIndex
)
}
}
@@ -0,0 +1,252 @@
function newGovernanceUserProfileSpace() {
const MODULE_NAME = 'User Profile Space'
let thisObject = {
githubStars: undefined,
githubWatchers: undefined,
githubForks: undefined,
container: undefined,
physics: physics,
draw: draw,
getContainer: getContainer,
finalize: finalize,
initialize: initialize
}
thisObject.container = newContainer()
thisObject.container.initialize(MODULE_NAME)
thisObject.container.isDraggeable = false
let waitingForResponses = 0
let timer = 0
thisObject.githubStars = new Map()
thisObject.githubWatchers = new Map()
thisObject.githubForks = new Map()
return thisObject
function initialize() {
/*
Here we will get a list of all github usernames who have a star or fork and are watching the
Superalgos Repository. This will later be used to know which user profiles are participating
at the Github Program.
*/
/*
If the workspace is not related to governance, then we exit the Intialize Function
*/
let resultsArary = UI.projects.foundations.spaces.designSpace.workspace.getHierarchyHeadsByNodeType('User Profile')
if (resultsArary.length === 0) { return }
/* Find the Username and Password */
let apisNode = UI.projects.foundations.spaces.designSpace.workspace.getHierarchyHeadByNodeType('APIs')
if (apisNode === undefined) {
UI.projects.education.spaces.docsSpace.navigateTo('Foundations', 'Topic', 'App Error - Github Credentials Missing', 'Anchor Github Credentials Missing')
UI.projects.education.spaces.docsSpace.sidePanelTab.open()
return
}
if (apisNode.githubAPI === undefined) {
UI.projects.education.spaces.docsSpace.navigateTo('Foundations', 'Topic', 'App Error - Github Credentials Missing', 'Anchor Github Credentials Missing')
UI.projects.education.spaces.docsSpace.sidePanelTab.open()
return
}
let config = JSON.parse(apisNode.githubAPI.config)
if (config.username === undefined || config.username === "") {
UI.projects.education.spaces.docsSpace.navigateTo('Foundations', 'Topic', 'App Error - Github Credentials Missing', 'Anchor Github Credentials Missing')
UI.projects.education.spaces.docsSpace.sidePanelTab.open()
return
}
if (config.token === undefined || config.token === "") {
UI.projects.education.spaces.docsSpace.navigateTo('Foundations', 'Topic', 'App Error - Github Credentials Missing', 'Anchor Github Credentials Missing')
UI.projects.education.spaces.docsSpace.sidePanelTab.open()
return
}
requestStars()
function requestStars() {
httpRequest(
undefined,
'Gov/getGithubStars/' +
'Superalgos' + '/' +
config.username + '/' +
config.token
, onGithubStarsResponse)
}
function requestWatchers() {
httpRequest(
undefined,
'Gov/getGithubWatchers/' +
'Superalgos' + '/' +
config.username + '/' +
config.token
, onGithubWatchersResponse)
}
function requestForks() {
httpRequest(
undefined,
'Gov/getGithubForks/' +
'Superalgos' + '/' +
config.username + '/' +
config.token
, onGithubForksResponse)
}
function onGithubStarsResponse(err, githubData) {
//console.log(githubData)
/* Lets check the result of the call through the http interface */
let githubStarsArray = JSON.parse(githubData)
for (let i = 0; i < githubStarsArray.length; i++) {
let githubUsername = githubStarsArray[i]
thisObject.githubStars.set(githubUsername, 1)
}
requestWatchers()
}
function onGithubWatchersResponse(err, githubData) {
//console.log(githubData)
/* Lets check the result of the call through the http interface */
let githubWatchersArray = JSON.parse(githubData)
for (let i = 0; i < githubWatchersArray.length; i++) {
let githubUsername = githubWatchersArray[i]
thisObject.githubWatchers.set(githubUsername, 1)
}
requestForks()
}
function onGithubForksResponse(err, githubData) {
//console.log(githubData)
/* Lets check the result of the call through the http interface */
let githubForksArray = JSON.parse(githubData)
for (let i = 0; i < githubForksArray.length; i++) {
let githubUsername = githubForksArray[i]
thisObject.githubForks.set(githubUsername, 1)
}
}
}
function finalize() {
thisObject.githubStars = undefined
thisObject.container.finalize()
thisObject.container = undefined
}
function getContainer(point) {
return undefined // since this space does not draw anything we return here
if (thisObject.container.frame.isThisPointHere(point, true) === true) {
thisObject.container.space = MODULE_NAME
return thisObject.container
} else {
return undefined
}
}
function physics() {
if (UI.projects.foundations.spaces.designSpace.workspace === undefined) { return }
/*
Here we will run the distribution process, that in turn will run all the programs.
*/
UI.projects.governance.functionLibraries.distributionProcess.calculate()
/*
Load the user profiles with Token Power.
*/
let userProfiles = UI.projects.foundations.spaces.designSpace.workspace.getHierarchyHeadsByNodeType('User Profile')
if (waitingForResponses !== 0) { return }
/*
We will get all the user Profiles tokens from the blockchain, making a call
every 5 seconds so as not to exceed the rate limit.
*/
for (let i = 0; i < userProfiles.length; i++) {
let userProfile = userProfiles[i]
if (userProfile.payload === undefined) { continue }
if (userProfile.payload.blockchainTokens === undefined) {
getBlockchainAccount(userProfile)
}
}
function getBlockchainAccount(userProfile) {
let signature = UI.projects.foundations.utilities.nodeConfig.loadConfigProperty(userProfile.payload, 'signature')
if (signature === undefined || signature === "") { return }
let request = {
url: 'WEB3',
params: {
method: "recoverAddress",
signature: JSON.stringify(signature)
}
}
httpRequest(JSON.stringify(request.params), request.url, onResponse)
function onResponse(err, data) {
/* Lets check the result of the call through the http interface */
if (err.result !== GLOBAL.DEFAULT_OK_RESPONSE.result) {
userProfile.payload.uiObject.setErrorMessage('Call via HTTP Interface failed.')
return
}
let response = JSON.parse(data)
/* Lets check the result of the method call */
if (response.result !== GLOBAL.DEFAULT_OK_RESPONSE.result) {
userProfile.payload.uiObject.setErrorMessage('Call to WEB3 Server failed. ' + response.error)
console.log('Call to WEB3 Server failed. ' + response.error)
return
}
let blockchainAccount = response.address
userProfile.payload.blockchainAccount = blockchainAccount
if (
blockchainAccount !== undefined &&
blockchainAccount !== "" &&
userProfile.payload.blockchainTokens === undefined
) {
waitingForResponses++
userProfile.payload.blockchainTokens = 0 // We need to set this value here so that the next call to BSCSCAN is not done more than once.
setTimeout(getBlockchainTokens, timer, userProfile, blockchainAccount)
timer = timer + 6000
}
}
}
function getBlockchainTokens(userProfile, blockchainAccount) {
console.log('blockchainAccount ', blockchainAccount)
const url = "https://api.bscscan.com/api?module=account&action=tokenbalance&contractaddress=0xfb981ed9a92377ca4d75d924b9ca06df163924fd&address=" + blockchainAccount + "&tag=latest&apikey=YourApiKeyToken"
fetch(url).then(function (response) {
return response.json();
}).then(function (data) {
console.log(data)
userProfile.payload.uiObject.setInfoMessage(data)
userProfile.payload.blockchainTokens = Number(data.result) / 1000000000000000000
waitingForResponses--
}).catch(function (err) {
const message = err.message + ' - ' + 'Can not access BSC SCAN servers.'
console.log(message)
userProfile.payload.uiObject.setErrorMessage(message, 1000)
waitingForResponses--
});
}
}
function draw() {
}
}
@@ -0,0 +1,159 @@
function newGovernanceUtilitiesBonusProgram() {
let thisObject = {
run: run
}
return thisObject
function run(
pools,
userProfiles,
programPropertyName,
programCodeName,
programNodeType
) {
let programPoolTokenReward
/*
In order to be able to calculate the share of the Program Pool for each User Profile,
we need to accumulate all the Bonus Power that each User Profile at their Program
node has, because with that Power is that each Program node gets a share of the pool.
*/
let accumulatedProgramPower = 0
/* Scan Pools Until finding the Pool for this program*/
for (let i = 0; i < pools.length; i++) {
let poolsNode = pools[i]
programPoolTokenReward = UI.projects.governance.utilities.pools.findPool(poolsNode, programCodeName)
if (programPoolTokenReward !== undefined) { break }
}
if (programPoolTokenReward === undefined || programPoolTokenReward === 0) { return }
for (let i = 0; i < userProfiles.length; i++) {
let userProfile = userProfiles[i]
if (userProfile.tokenPowerSwitch === undefined) { continue }
let program = UI.projects.governance.utilities.validations.onlyOneProgram(userProfile, programNodeType)
if (program === undefined) { continue }
if (program.payload === undefined) { continue }
resetProgram(program)
}
for (let i = 0; i < userProfiles.length; i++) {
let userProfile = userProfiles[i]
if (userProfile.tokenPowerSwitch === undefined) { continue }
let program = UI.projects.governance.utilities.validations.onlyOneProgram(userProfile, programNodeType)
if (program === undefined) { continue }
if (program.payload === undefined) { continue }
validateProgram(program, userProfile)
}
for (let i = 0; i < userProfiles.length; i++) {
let userProfile = userProfiles[i]
if (userProfile.tokenPowerSwitch === undefined) { continue }
let program = UI.projects.governance.utilities.validations.onlyOneProgram(userProfile, programNodeType)
if (program === undefined) { continue }
if (program.payload === undefined) { continue }
if (program.payload[programPropertyName].isActive === false) { continue }
distributeProgram(program)
}
for (let i = 0; i < userProfiles.length; i++) {
let userProfile = userProfiles[i]
if (userProfile.tokenPowerSwitch === undefined) { continue }
let program = UI.projects.governance.utilities.validations.onlyOneProgram(userProfile, programNodeType)
if (program === undefined) { continue }
if (program.payload === undefined) { continue }
if (program.payload[programPropertyName].isActive === false) { continue }
calculateProgram(program)
}
function resetProgram(node) {
if (node === undefined) { return }
if (node.payload === undefined) { return }
if (node.payload[programPropertyName] === undefined) {
node.payload[programPropertyName] = {
bonusPower: 0,
bonus: {
tokens: 0,
percentage: 0
}
}
} else {
node.payload[programPropertyName].bonusPower = 0
node.payload[programPropertyName].bonus = {
tokens: 0,
percentage: 0
}
}
}
function validateProgram(node, userProfile) {
/*
This program is not going to run unless the Profile has Tokens, and for
that users needs to execute the setup procedure of signing their Github
username with their private key.
*/
if (
userProfile.payload.blockchainTokens === undefined
) {
node.payload[programPropertyName].isActive = false
userProfile.payload.uiObject.setErrorMessage("You need to setup this profile with the Profile Constructor, to access the Token Power of your account at the Blockchain.")
return
}
}
function distributeProgram(programNode) {
if (programNode === undefined || programNode.payload === undefined) { return }
/*
To get into the Bonus Sub-Program we will use the usedPower previously calculated by the Program.
That means that only token power effectively used at the program (not just directed to it) will
be used to compute Bonuses.
*/
programNode.payload[programPropertyName].bonusPower = programNode.payload[programPropertyName].usedPower | 0
accumulatedProgramPower = accumulatedProgramPower + programNode.payload[programPropertyName].bonusPower
}
function calculateProgram(programNode) {
/*
Here we will calculate which share of the Program Pool this user will get in tokens.
To do that, we use the bonusPower, to see which proportion of the accumulatedProgramPower
represents.
*/
if (programNode.payload === undefined) { return }
/*
If the accumulatedProgramPower is not grater the amount of tokens at the Program Pool, then
this user will get the exact amount of tokens from the pool as incomingPower he has.
If the accumulatedProgramPower is grater the amount of tokens at the Program Pool, then
the amount ot tokens to be received is a proportional to the share of incomingPower in accumulatedProgramPower.
*/
let totalPowerRewardRatio = accumulatedProgramPower / programPoolTokenReward
if (totalPowerRewardRatio < 1) { totalPowerRewardRatio = 1 }
if (programNode.tokensBonus === undefined || programNode.tokensBonus.payload === undefined) {
programNode.payload.uiObject.setErrorMessage("Tokens Bonus Node is needed in order for this Program to get Tokens from the Bonus Program Pool.")
return
}
programNode.payload[programPropertyName].bonus.tokens = programNode.payload[programPropertyName].bonusPower / totalPowerRewardRatio
drawProgram(programNode)
}
function drawProgram(node) {
if (node.tokensBonus !== undefined && node.tokensBonus.payload !== undefined) {
const tokensBonusText = parseFloat(node.payload[programPropertyName].bonus.tokens.toFixed(0)).toLocaleString('en')
const tokensAwardedBTC = ' ≃ ' + UI.projects.governance.utilities.conversions.estimateSATokensInBTC(node.payload[programPropertyName].bonus.tokens | 0) + ' BTC'
node.tokensBonus.payload.uiObject.valueAngleOffset = 0
node.tokensBonus.payload.uiObject.valueAtAngle = true
node.tokensBonus.payload.uiObject.setValue(tokensBonusText + ' SA Tokens' + tokensAwardedBTC)
}
}
}
}
@@ -0,0 +1,126 @@
function newGovernanceUtilitiesCommonTables() {
let thisObject = {
addHTML: addHTML
}
return thisObject
function addHTML(
table,
nodeType,
hierarchyHeadsType,
tabIndex,
filters
) {
/*
Setup Filters
*/
let filtersObject
if (filters !== undefined) {
try {
filtersObject = JSON.parse(filters)
} catch (err) { }
}
let tableRecords = []
let tableRecordDefinition = {
"properties": [
{
"name": "name",
"label": "Name",
"type": "string",
"order": "ascending",
"textAlign": "left"
},
{
"name": "tokensReward",
"label": "Tokens Reward",
"type": "number",
"order": "descending",
"textAlign": "center",
"format": "integer"
},
{
"name": "rewardInBTC",
"label": "Reward In BTC",
"type": "number",
"order": "descending",
"textAlign": "center",
"format": "8 decimals"
},
{
"name": "weight",
"label": "Weight",
"type": "number",
"order": "descending",
"textAlign": "center",
"format": "percentage"
},
{
"name": "weightPower",
"label": "Weight Power",
"type": "number",
"order": "descending",
"textAlign": "center",
"format": "2 decimals"
}
]
}
/*
Here we get from the workspace all User Profiles.
*/
let nodes = UI.projects.foundations.spaces.designSpace.workspace.getNodesByTypeAndHierarchyHeadsType(nodeType, hierarchyHeadsType)
/*
Transform the result array into table records.
*/
for (let j = 0; j < nodes.length; j++) {
let node = nodes[j]
let name = ''
if (node.payload.parentNode !== undefined) {
if (node.payload.parentNode.payload.parentNode !== undefined) {
if (node.payload.parentNode.payload.parentNode.payload.parentNode !== undefined) {
if (node.payload.parentNode.payload.parentNode.payload.parentNode.payload.parentNode !== undefined) {
name = name + node.payload.parentNode.payload.parentNode.payload.parentNode.payload.parentNode.name + ' - '
}
name = name + node.payload.parentNode.payload.parentNode.payload.parentNode.name + ' - '
}
name = name + node.payload.parentNode.payload.parentNode.name + ' - '
}
name = name + node.payload.parentNode.name + ' - '
}
name = name + node.name
let tableRecord = {
"name": name,
"tokensReward": node.payload.tokens | 0,
"rewardInBTC": UI.projects.governance.utilities.conversions.estimateSATokensInBTC(node.payload.tokens | 0),
"weight": node.payload.weight,
"weightPower": node.payload.votingProgram.votes | 0
}
if (UI.projects.governance.utilities.filters.applyFilters(filters, filtersObject, tableRecord) === true) {
tableRecords.push(tableRecord)
}
}
/*
Get the sorting order for this table.
*/
let sortingOrder = UI.projects.governance.spaces.reportsSpace.tablesSortingOrders[table]
/*
Set the default sorting order for this table.
*/
if (sortingOrder === undefined) {
UI.projects.governance.spaces.reportsSpace.tablesSortingOrders[table] = {
property: 'tokensReward',
order: 'descending'
}
sortingOrder = UI.projects.governance.spaces.reportsSpace.tablesSortingOrders[table]
}
return UI.projects.governance.utilities.tables.addHTML(
table,
tableRecords,
tableRecordDefinition,
sortingOrder,
tabIndex
)
}
}
@@ -0,0 +1,14 @@
function newGovernanceUtilitiesConversions () {
let thisObject = {
estimateSATokensInBTC: estimateSATokensInBTC
}
return thisObject
function estimateSATokensInBTC(SATokens) {
const SA_BTC_BASELINE_EXCHANGE_RATE = 1.5 / 1000000
const BTC = SATokens * SA_BTC_BASELINE_EXCHANGE_RATE
return BTC.toFixed(3)
}
}
@@ -0,0 +1,430 @@
function newGovernanceUtilitiesDecendentProgram() {
/*
This Utility Module is intended to be used by all programs that have the
concept of Decendents, and when the program requires to compute recursively
all decendents.
*/
let thisObject = {
run: run
}
const MAX_GENERATIONS = 10
return thisObject
function run(
pools,
userProfiles,
programPropertyName,
programCodeName,
programNodeType,
programPowerName,
usersArrayPropertyName,
userNodeType
) {
/*
Here we will store the total amount of tokens that is going to be distributed among all participants
of the Program. This will come from a Pool that is configured wiht a codeName config property
with the value programCodeName
*/
let programPoolTokenReward
/*
In order to be able to calculate the share of the Program Pool for each User Profile,
we need to accumulate all the Icomming programPowerName that each User Profile at their Program
node has, because with that Incoming Power is that each Program node gets a share of
the pool.
*/
let accumulatedIncomingProgramPower = 0
/* Scan Pools Until finding the Pool for this program*/
for (let i = 0; i < pools.length; i++) {
let poolsNode = pools[i]
programPoolTokenReward = UI.projects.governance.utilities.pools.findPool(poolsNode, programCodeName)
if (programPoolTokenReward !== undefined) { break }
}
if (programPoolTokenReward === undefined || programPoolTokenReward === 0) { return }
/*
We will first reset all the program outgoingPower, and then distribute it.
*/
for (let i = 0; i < userProfiles.length; i++) {
let userProfile = userProfiles[i]
if (userProfile.tokenPowerSwitch === undefined) { continue }
let program = UI.projects.governance.utilities.validations.onlyOneProgram(userProfile, programNodeType)
if (program === undefined) { continue }
if (program.payload === undefined) { continue }
resetProgram(program)
}
for (let i = 0; i < userProfiles.length; i++) {
let userProfile = userProfiles[i]
if (userProfile.tokenPowerSwitch === undefined) { continue }
let program = UI.projects.governance.utilities.validations.onlyOneProgram(userProfile, programNodeType)
if (program === undefined) { continue }
if (program.payload === undefined) { continue }
validateProgram(program, userProfile)
}
for (let i = 0; i < userProfiles.length; i++) {
let userProfile = userProfiles[i]
if (userProfile.tokenPowerSwitch === undefined) { continue }
let program = UI.projects.governance.utilities.validations.onlyOneProgram(userProfile, programNodeType)
if (program === undefined) { continue }
if (program.payload === undefined) { continue }
if (program.payload[programPropertyName].isActive === false) { continue }
distributeProgram(program)
}
for (let i = 0; i < userProfiles.length; i++) {
let userProfile = userProfiles[i]
if (userProfile.tokenPowerSwitch === undefined) { continue }
let program = UI.projects.governance.utilities.validations.onlyOneProgram(userProfile, programNodeType)
if (program === undefined) { continue }
if (program.payload === undefined) { continue }
if (program.payload[programPropertyName].isActive === false) { continue }
calculateProgram(program)
}
function resetProgram(node) {
resetNode(node, 0)
function resetNode(node, generation) {
if (generation >= MAX_GENERATIONS) {
return
}
if (node === undefined) { return }
if (node.payload === undefined) { return }
if (node.payload[programPropertyName] === undefined) {
node.payload[programPropertyName] = {
count: 0,
percentage: 0,
outgoingPower: 0,
ownPower: 0,
incomingPower: 0,
usedPower: 0,
awarded: {
tokens: 0,
percentage: 0
}
}
} else {
node.payload[programPropertyName].count = 0
node.payload[programPropertyName].percentage = 0
node.payload[programPropertyName].outgoingPower = 0
node.payload[programPropertyName].ownPower = 0
node.payload[programPropertyName].incomingPower = 0
node.payload[programPropertyName].usedPower = 0
node.payload[programPropertyName].awarded = {
tokens: 0,
percentage: 0
}
}
if (
node.type === 'User Profile' &&
node.tokenPowerSwitch !== undefined
) {
resetNode(node.tokenPowerSwitch, generation)
return
}
if (
node.type === 'Token Power Switch' &&
node[programPropertyName] !== undefined
) {
resetNode(node[programPropertyName], generation)
return
}
if (
node.type === programNodeType &&
node[usersArrayPropertyName] !== undefined
) {
for (let i = 0; i < node[usersArrayPropertyName].length; i++) {
resetNode(node[usersArrayPropertyName][i], generation)
}
return
}
if (
node.type === userNodeType &&
node.payload.referenceParent !== undefined
) {
resetNode(node.payload.referenceParent, generation + 1)
return
}
}
}
function validateProgram(node, userProfile) {
/*
This program is not going to run unless the Profile has Tokens, and for
that users needs to execute the setup procedure of signing their Github
username with their private key.
*/
if (
userProfile.payload.blockchainTokens === undefined
) {
node.payload[programPropertyName].isActive = false
userProfile.payload.uiObject.setErrorMessage("You need to setup this profile with the Profile Constructor, to access the Token Power of your account at the Blockchain.")
return
}
/*
As per the system rules, the Program will not give tokens
to users that do not have their own user nodes set up, unless it has a big
amount of tokens (this last condition is for the edge case where a user it
at the top of the program pyramid.)
*/
if (
userProfile.payload.blockchainTokens < 1000000 &&
(node[usersArrayPropertyName] === undefined || hasUsersDefined(node[usersArrayPropertyName]) === false)
) {
node.payload[programPropertyName].isActive = false
node.payload.uiObject.setErrorMessage("In order to enable this program you need to add " + userNodeType + " nodes and reference a User Profile from each one.")
} else {
node.payload[programPropertyName].isActive = true
}
function hasUsersDefined(usersArray) {
if (usersArray === undefined) { return false }
for (let i = 0; i < usersArray.length; i++) {
let user = usersArray[i]
if (user.payload.referenceParent !== undefined) { return true }
}
return false
}
}
function distributeProgram(programNode) {
if (programNode === undefined || programNode.payload === undefined) { return }
/*
Here we will convert Token Power into programPower.
As per system rules programPower = tokensPower
*/
let programPower = programNode.payload.tokenPower
/*
We will also reseet the count of descendents from here.
*/
let count = 0
/*
The Own Power is the power generated by the same User Profile tokens, not inherited from others.
*/
programNode.payload[programPropertyName].ownPower = programPower
distributeProgramPower(programNode, programNode, programPower, count, undefined, 0)
function distributeProgramPower(
currentProgramNode,
node,
programPower,
count,
percentage,
generation
) {
if (generation >= MAX_GENERATIONS) {
return
}
if (node === undefined) { return }
if (node.payload === undefined) { return }
if (node.payload[programPropertyName] === undefined) { return }
switch (node.type) {
case programNodeType: {
/*
This is the point where we increase to our local count of descendents whatever it comes
at the count parameters. If we are processing the User Profile of this Program
then we will add zero, otherwise, 1.
*/
node.payload[programPropertyName].count = node.payload[programPropertyName].count + count
/*
The outgoingPower of this node will be accumulating all the programPower flowing
through it, no matter from where it comes.
*/
node.payload[programPropertyName].outgoingPower = node.payload[programPropertyName].outgoingPower + programPower
/*
We need to adjust the balance that holds the accumulationt of all incomingPower of all Program
nodes. To do this we will substratct the current incomingPower, bacause it is going to be recalculated
inmediatelly after this, and then we will add it again after the recalcualtion.
*/
accumulatedIncomingProgramPower = accumulatedIncomingProgramPower - node.payload[programPropertyName].incomingPower
/*
At any point in time, the incomingPower will be equal to the total of the outgoingPower minus
the ownPower. This is like this because the outgoingPower is the accumulation of all the
power flow that is leaving this node, which includes the ownPower. That means that if we
substract the ownPower, we will have the accumulation of all the incomingPower, which
means all the power coming from other User Profiles referencing this one.
*/
node.payload[programPropertyName].incomingPower = node.payload[programPropertyName].outgoingPower - node.payload[programPropertyName].ownPower
/*
Now that we have the incomingPower calculated again, we can add it again to the balance of all the incomingPower
of all Program nodes.
*/
accumulatedIncomingProgramPower = accumulatedIncomingProgramPower + node.payload[programPropertyName].incomingPower
if (node[usersArrayPropertyName] !== undefined) {
/*
Before distributing the program power, we will calculate how the power
is going to be switched between all nodes. The first pass is about
scanning all sibling nodes to see which ones have a percentage defined
at their config, and check that all percentages don't add more than 100.
*/
let totalPercentage = 0
let totalNodesWithoutPercentage = 0
for (let i = 0; i < node[usersArrayPropertyName].length; i++) {
let childNode = node[usersArrayPropertyName][i]
let percentage = UI.projects.foundations.utilities.nodeConfig.loadConfigProperty(childNode.payload, 'percentage')
if (percentage !== undefined && isNaN(percentage) !== true) {
totalPercentage = totalPercentage + percentage
} else {
totalNodesWithoutPercentage++
}
}
if (totalPercentage > 100) {
node.payload.uiObject.setErrorMessage('Program Power Switching Error. Total Percentage of children nodes is grater that 100.')
return
}
let defaultPercentage = 0
if (totalNodesWithoutPercentage > 0) {
defaultPercentage = (100 - totalPercentage) / totalNodesWithoutPercentage
}
/*
Here we do the actual distribution.
*/
for (let i = 0; i < node[usersArrayPropertyName].length; i++) {
let childNode = node[usersArrayPropertyName][i]
let percentage = UI.projects.foundations.utilities.nodeConfig.loadConfigProperty(childNode.payload, 'percentage')
if (percentage === undefined || isNaN(percentage) === true) {
percentage = defaultPercentage
}
distributeProgramPower(
currentProgramNode,
childNode,
programPower * percentage / 100,
0,
percentage,
generation
)
}
}
return
}
case userNodeType: {
let previousOutgoing = node.payload[programPropertyName].outgoingPower
node.payload[programPropertyName].outgoingPower = node.payload.parentNode.payload[programPropertyName].outgoingPower * percentage / 100
drawUserNode(node, percentage)
if (node.payload.referenceParent !== undefined) {
/*
We want to accumulate the usedPower, but to keep the right balance, everytime we add to it the outgoingPower
we need to substract the previous one, since this migth be executed at every user profile and also recurisvely.
*/
currentProgramNode.payload[programPropertyName].usedPower = currentProgramNode.payload[programPropertyName].usedPower - previousOutgoing
currentProgramNode.payload[programPropertyName].usedPower = currentProgramNode.payload[programPropertyName].usedPower + node.payload[programPropertyName].outgoingPower
distributeProgramPower(
currentProgramNode,
node.payload.referenceParent,
programPower / 10,
0,
undefined,
generation + 1
)
}
return
}
case 'User Profile': {
let program = UI.projects.governance.utilities.validations.onlyOneProgram(node, programNodeType)
if (program === undefined) { return }
if (program.payload === undefined) { return }
if (program.payload[programPropertyName].isActive === false) { return }
distributeProgramPower(
program,
program,
programPower,
0,
undefined,
generation)
return
}
}
}
}
function calculateProgram(programNode) {
/*
Here we will calculate which share of the Program Pool this user will get in tokens.
To do that, we use the incomingPower, to see which proportion of the accumulatedIncomingProgramPower
represents.
*/
if (programNode.payload === undefined) { return }
/*
If the accumulatedIncomingProgramPower is not grater the amount of tokens at the Program Pool, then
this user will get the exact amount of tokens from the pool as incomingPower he has.
If the accumulatedIncomingProgramPower is grater the amount of tokens at the Program Pool, then
the amount ot tokens to be received is a proportional to the share of incomingPower in accumulatedIncomingProgramPower.
*/
let totalPowerRewardRatio = accumulatedIncomingProgramPower / programPoolTokenReward
if (totalPowerRewardRatio < 1) { totalPowerRewardRatio = 1 }
if (programNode.tokensAwarded === undefined || programNode.tokensAwarded.payload === undefined) {
programNode.payload.uiObject.setErrorMessage("Tokens Awarded Node is needed in order for this Program to get Tokens from the Program Pool.")
return
}
programNode.payload[programPropertyName].awarded.tokens = programNode.payload[programPropertyName].incomingPower / totalPowerRewardRatio
drawProgram(programNode)
}
function drawUserNode(node, percentage) {
if (node.payload !== undefined) {
const outgoingPowerText = parseFloat(node.payload[programPropertyName].outgoingPower.toFixed(0)).toLocaleString('en')
node.payload.uiObject.valueAngleOffset = 180
node.payload.uiObject.valueAtAngle = true
node.payload.uiObject.setValue(outgoingPowerText + ' ' + programPowerName)
node.payload.uiObject.percentageAngleOffset = 180
node.payload.uiObject.percentageAtAngle = true
node.payload.uiObject.setPercentage(percentage)
node.payload.uiObject.statusAngleOffset = 0
node.payload.uiObject.statusAtAngle = true
node.payload.uiObject.setStatus(outgoingPowerText + ' ' + ' Outgoing Power')
}
}
function drawProgram(node) {
if (node.payload !== undefined) {
const ownPowerText = parseFloat(node.payload[programPropertyName].ownPower.toFixed(0)).toLocaleString('en')
const incomingPowerText = parseFloat(node.payload[programPropertyName].incomingPower.toFixed(0)).toLocaleString('en')
node.payload.uiObject.statusAngleOffset = 0
node.payload.uiObject.statusAtAngle = false
node.payload.uiObject.setStatus(ownPowerText + ' Own Power' + ' + ' + incomingPowerText + ' Incoming ' + programPowerName)
}
if (node.tokensAwarded !== undefined && node.tokensAwarded.payload !== undefined) {
const tokensAwardedText = parseFloat(node.payload[programPropertyName].awarded.tokens.toFixed(0)).toLocaleString('en')
const tokensAwardedBTC = ' ≃ ' + UI.projects.governance.utilities.conversions.estimateSATokensInBTC(node.payload[programPropertyName].awarded.tokens | 0) + ' BTC'
node.tokensAwarded.payload.uiObject.statusAngleOffset = 0
node.tokensAwarded.payload.uiObject.statusAtAngle = true
node.tokensAwarded.payload.uiObject.valueAngleOffset = 0
node.tokensAwarded.payload.uiObject.valueAtAngle = true
node.tokensAwarded.payload.uiObject.setValue(tokensAwardedText + ' SA Tokens' + tokensAwardedBTC)
node.tokensAwarded.payload.uiObject.setStatus('From ' + node.payload[programPropertyName].count + ' Descendants.')
}
}
}
}
@@ -0,0 +1,130 @@
function newGovernanceUtilitiesDecendentTables() {
let thisObject = {
addHTML: addHTML
}
return thisObject
function addHTML(
table,
programName,
programPropertyName,
tabIndex,
filters
) {
/*
Setup Filters
*/
let filtersObject
if (filters !== undefined) {
try {
filtersObject = JSON.parse(filters)
} catch (err) { }
}
/*
Other Variables
*/
let tableRecords = []
let tableRecordDefinition = {
"properties": [
{
"name": "name",
"label": "User Profile",
"type": "string",
"order": "ascending",
"textAlign": "left"
},
{
"name": "ownPower",
"label": "Own Power",
"type": "number",
"order": "descending",
"textAlign": "center",
"format": "2 decimals"
},
{
"name": "incoming",
"label": "Incoming",
"type": "number",
"order": "descending",
"textAlign": "center",
"format": "2 decimals"
},
{
"name": "tokensAwarded",
"label": "Awarded",
"type": "number",
"order": "descending",
"textAlign": "center",
"format": "2 decimals"
},
{
"name": "decendants",
"label": "Descendants",
"type": "number",
"order": "descending",
"textAlign": "center",
"format": "integer"
},
{
"name": "tokensBonus",
"label": "Bonus",
"type": "number",
"order": "descending",
"textAlign": "center",
"format": "2 decimals"
}
]
}
/*
Here we get from the workspace all User Profiles.
*/
let userProfiles = UI.projects.foundations.spaces.designSpace.workspace.getHierarchyHeadsByNodeType('User Profile')
/*
Transform the result array into table records.
*/
for (let j = 0; j < userProfiles.length; j++) {
let userProfile = userProfiles[j]
if (userProfile.tokenPowerSwitch === undefined) { continue }
let program = UI.projects.governance.utilities.validations.onlyOneProgram(userProfile, programName)
if (program === undefined) { continue }
if (program.payload === undefined) { continue }
if (program.payload[programPropertyName] === undefined) { continue }
let tableRecord = {
"name": userProfile.name,
"ownPower": program.payload[programPropertyName].ownPower | 0,
"incoming": program.payload[programPropertyName].incomingPower | 0,
"tokensAwarded": program.payload[programPropertyName].awarded.tokens | 0,
"decendants": program.payload[programPropertyName].awarded.count | 0,
"tokensBonus": program.payload[programPropertyName].bonus.tokens | 0
}
if (UI.projects.governance.utilities.filters.applyFilters(filters, filtersObject, tableRecord) === true) {
tableRecords.push(tableRecord)
}
}
/*
Get the sorting order for this table.
*/
let sortingOrder = UI.projects.governance.spaces.reportsSpace.tablesSortingOrders[table]
/*
Set the default sorting order for this table.
*/
if (sortingOrder === undefined) {
UI.projects.governance.spaces.reportsSpace.tablesSortingOrders[table] = {
property: 'tokensAwarded',
order: 'descending'
}
sortingOrder = UI.projects.governance.spaces.reportsSpace.tablesSortingOrders[table]
}
return UI.projects.governance.utilities.tables.addHTML(
table,
tableRecords,
tableRecordDefinition,
sortingOrder,
tabIndex
)
}
}
@@ -0,0 +1,37 @@
function newGovernanceUtilitiesFilters() {
let thisObject = {
applyFilters: applyFilters
}
return thisObject
function applyFilters(filters, filtersObject, tableRecord) {
/* Apply Filters */
let passedFilters = true
if (filtersObject !== undefined) {
for (var property in tableRecord) {
if (Object.prototype.hasOwnProperty.call(tableRecord, property)) {
let fiter = filtersObject[property]
if (fiter === undefined) { continue }
let value = tableRecord[property]
let condition = eval(fiter)
if (condition === false) {
passedFilters = false
}
}
}
} else {
/*
We will assume the filter is a string and that needs to be applied to the property name.
*/
if (
filters !== undefined &&
filters !== "" &&
tableRecord.name.indexOf(filters) < 0
) {
passedFilters = false
}
}
return passedFilters
}
}
+59
View File
@@ -0,0 +1,59 @@
function newGovernanceUtilitiesPools() {
let thisObject = {
findPool: findPool
}
return thisObject
function findPool(node, codeNameToFind) {
let tokens = undefined
findTokensAtPool(node, codeNameToFind)
return tokens
function findTokensAtPool(node, codeNameToFind) {
if (node === undefined) { return }
if (node.payload === undefined) { return }
if (tokens !== undefined) { return }
/*
This function allows us to find a Pool within a Pool hierarchy that
has a give codeName config property.
*/
if (
node.type === 'Pool'
) {
let codeName = UI.projects.foundations.utilities.nodeConfig.loadConfigProperty(node.payload, 'codeName')
if (codeName === codeNameToFind) {
tokens = node.payload.tokens
}
}
let schemaDocument = getSchemaDocument(node)
if (schemaDocument === undefined) { return }
if (schemaDocument.childrenNodesProperties !== undefined) {
for (let i = 0; i < schemaDocument.childrenNodesProperties.length; i++) {
let property = schemaDocument.childrenNodesProperties[i]
switch (property.type) {
case 'node': {
let childNode = node[property.name]
findTokensAtPool(childNode, codeNameToFind)
}
break
case 'array': {
let propertyArray = node[property.name]
if (propertyArray !== undefined) {
for (let m = 0; m < propertyArray.length; m++) {
let childNode = propertyArray[m]
findTokensAtPool(childNode, codeNameToFind)
}
}
break
}
}
}
}
}
}
}
+173
View File
@@ -0,0 +1,173 @@
function newGovernanceUtilitiesTables() {
let thisObject = {
addHTML: addHTML
}
return thisObject
function addHTML(
table,
tableRecords,
tableRecordDefinition,
sortingOrder,
tabIndex
) {
let HTML = ''
let resultCounter = 0
/*
Get the property type for the current sorting order.
*/
let propertyType
for (let i = 0; i < tableRecordDefinition.properties.length; i++) {
let property = tableRecordDefinition.properties[i]
if (property.name === sortingOrder.property) {
propertyType = property.type
break
}
}
/*
Apply the sorting order for this table.
*/
switch (propertyType) {
case 'string': {
switch (sortingOrder.order) {
case 'ascending': {
tableRecords.sort((a, b) => (a[sortingOrder.property].toLowerCase() > b[sortingOrder.property].toLowerCase()) ? 1 : -1)
break
}
case 'descending': {
tableRecords.sort((a, b) => (a[sortingOrder.property].toLowerCase() > b[sortingOrder.property].toLowerCase()) ? -1 : 1)
break
}
}
break
}
case 'number': {
switch (sortingOrder.order) {
case 'ascending': {
tableRecords.sort((a, b) => (a[sortingOrder.property] > b[sortingOrder.property]) ? 1 : -1)
break
}
case 'descending': {
tableRecords.sort((a, b) => (a[sortingOrder.property] > b[sortingOrder.property]) ? -1 : 1)
break
}
}
break
}
}
/*
Build the HTML
*/
let odd = false
const upArrow = '&uarr;'
const downArrow = '&darr;'
HTML = HTML + '<section id="governance-report-page-div" class="governance-search-result-content">'
HTML = HTML + '<table class="governance-info-table">'
HTML = HTML + '<thead>'
HTML = HTML + '<tr>'
for (let i = 0; i < tableRecordDefinition.properties.length; i++) {
let property = tableRecordDefinition.properties[i]
let newOrder
let orderArrow
/*
If the property is the one defining the order, then the new order will be
the opossite order.
*/
if (property.name === sortingOrder.property) {
if (sortingOrder.order === 'ascending') {
newOrder = 'descending'
orderArrow = upArrow
} else {
newOrder = 'ascending'
orderArrow = downArrow
}
} else {
orderArrow = ""
/*
If the property is not the current defininf the order, then the new order will
be the default order for that property.
*/
for (let i = 0; i < tableRecordDefinition.properties.length; i++) {
let propertyDefinition = tableRecordDefinition.properties[i]
if (property.name === propertyDefinition.name) {
newOrder = propertyDefinition.order
break
}
}
}
HTML = HTML + '<th>' + '<a href="#" onClick="UI.projects.governance.spaces.reportsSpace.changeTableSortingOrder(\'' + table + '\',\'' + property.name + '\',\'' + newOrder + '\',\'' + tabIndex + '\')">' + property.label + ' ' + orderArrow + '</a>' + '</th>'
}
HTML = HTML + '</tr>'
HTML = HTML + '<thead>'
HTML = HTML + '<tbody>'
for (let j = 0; j < tableRecords.length; j++) {
let textAligment = 'center'
let format = 'text'
let tableRecord = tableRecords[j]
if (odd === true) {
HTML = HTML + '<tr class="governance-info-table-alt-bg">'
odd = false
} else {
HTML = HTML + '<tr>'
odd = true
}
/*
Iterate through tableRecord properties.
*/
for (var property in tableRecord) {
if (Object.prototype.hasOwnProperty.call(tableRecord, property)) {
/*
Get Text Align and Format
*/
for (let i = 0; i < tableRecordDefinition.properties.length; i++) {
let propertyDefinition = tableRecordDefinition.properties[i]
if (property === propertyDefinition.name) {
textAligment = propertyDefinition.textAlign
format = propertyDefinition.format
break
}
}
let value = tableRecord[property]
switch (format) {
case 'text': {
break
}
case 'integer': {
value = parseFloat(value | 0).toLocaleString('en')
break
}
case '2 decimals': {
value = parseFloat(value | 2).toLocaleString('en')
break
}
case 'percentage': {
if (isNaN(value)) { value = 0 }
value = (value * 100).toFixed(2) + " %"
break
}
}
HTML = HTML + '<td style="text-align:' + textAligment + ';">' + value + '</td>'
}
}
resultCounter++
HTML = HTML + '</tr>'
}
HTML = HTML + '<tbody>'
HTML = HTML + '</table>'
HTML = HTML + '</section>'
return { HTML: HTML, resultCounter: resultCounter }
}
}
@@ -0,0 +1,23 @@
function newGovernanceUtilitiesValidations () {
let thisObject = {
onlyOneProgram: onlyOneProgram
}
return thisObject
function onlyOneProgram(userProfile, programNodeType) {
/*
Find all the nodes representing the current program.
*/
let programs = UI.projects.foundations.utilities.branches.nodeBranchToArray(userProfile, programNodeType)
if (programs !== undefined) {
if (programs.length > 1) {
userProfile.payload.uiObject.setErrorMessage('Only one ' + programNodeType + ' is allowed.')
return
}
if (programs.length === 1) {
return programs[0]
}
}
}
}