aboutsummaryrefslogtreecommitdiff
path: root/src/js/arching-kaos-stellar-network.js
blob: f3e1d940d735f6de4999d189664e499f2ad2af58 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225

function getNumberOfTrustlinesAndRenderThem(json){
    var number = json._embedded.records[0].accounts.authorized;
    var stats = document.querySelector('.stellar-network').querySelector('summary');
    var small = document.createElement("span");
    small.innerText = ' (' + number + ')';
    stats.appendChild(small);
    archingKaosLog("Loading trustlines... Found "+number+"!");
    progressPlaceholder.value++;
    stellarParticipants=number;
}
function renderStellarAddressesAndProceed(json){
    var stats = document.querySelector('.stellar-network');
    json._embedded.records.forEach(r=>{
        var p = document.createElement("div");
        p.className = "stellar-address";
        p.innerText = r.account_id;
        console.log(r);
        p.id = r.account_id;
        holders.push(r.account_id);
        progressPlaceholder.max++;
        checkAddressForConfigurationVariable(r.account_id);
        stats.appendChild(p);
    })
    if (json._links.next) getHolders(json._links.next.href);
}
function renderConfigurationIPNSLinkAndProceed(json, stellarAddress){
    var cnf = document.createElement("p");
    if(document.querySelector("#stellar-data-config-not-found")){
        document.querySelector("#stellar-data-config-not-found").hidden = true;
    }
    cnf.innerText = atob(json.value)
    document.querySelector('#'+stellarAddress).appendChild(cnf)
    document.querySelector('#'+stellarAddress).style="color: #3dbb3d;"
    stellarNetworkConfiguredAddresses += 1;
    getConfiguration(atob(json.value),stellarAddress)
}

/*
 * Get Trustlines for ARCHINGKAOS asset
 * Returns DOM element with number of trustlines
 */
function getTrustlines(){
    archingKaosLog("Loading trustlines...");
    archingKaosFetchJSON(getTrustlinesURL(), getNumberOfTrustlinesAndRenderThem);
}

/*
 * Get addresses that trust the asset
 * Limit is 200 addresses cause horizon API limitations.
 *
 * Returns div DOM elements for each found address, embedding
 * the address both in innerText and in id of the div.
 */
// var lastPage = '';
function getHolders(a=0){
    var doIt = true
    archingKaosLog("Searching holders...");
    var url = '';
    if ( a === 0 ) {
        url=getHoldersOfActiveAssetURL();
    } else {
        if ( lastPage === '' ) {
            url = a;
        } else {
            if ( a !== lastPage ) {
                url = a;
            } else {
                doIt = false;
            }
        }
    }
    lastPage=url;
    if (doIt) {
        archingKaosFetchJSON(url, renderStellarAddressesAndProceed);
    }
    archingKaosLog("Searching holders... Done!");
}

function getStellarConfigurationVariableURL(stellarAddress){
    return activeSettings.horizonAddresses[activeSettings.horizonSelectedAddress]+
        'accounts/'+
        stellarAddress+
        '/data/'+
        activeSettings.stellarConfigVars[activeSettings.stellarDefaultConfig];
}

/*
 * Function that checks the address' variable 'config' to see
 * if it's set up.
 *
 * Returns the IPNS link in the DOM as p element and proceeds to
 * get nickname from the variables
 */
function checkAddressForConfigurationVariable(stellarAddress) {
    archingKaosLog("Checking configuration for "+ stellarAddress+ "...");
    archingKaosFetchJSON(getStellarConfigurationVariableURL(stellarAddress), renderConfigurationIPNSLinkAndProceed, stellarAddress);
    progressPlaceholder.value++;
}

/*
 * We now connect our client to horizon
 */
var server = new StellarSdk.Server(activeSettings.horizonAddresses[activeSettings.horizonSelectedAddress]);
// We ask for the 'a' stellar address the balances
function letme(a){
    server.accounts()
    .accountId(a)
    .call().then(function(r){ const L = r; putit(r); });
}
// We print them
function putit(i){
    var ta=document.querySelector("#stellar-balances-table");
    for (b in i.balances) {
        var row = document.createElement("tr");
        x = i.balances[b];
        var amount = document.createElement("td");
        var assetCode = document.createElement("td");
        amount.innerText = x.balance;
        assetCode.innerText = ( x.asset_code && x.asset_code != "undefined" ? x.asset_code : 'XLM');
        row.appendChild(assetCode);
        row.appendChild(amount);
        ta.appendChild(row);
        progressPlaceholder.max++;
        progressPlaceholder.value++;
        if(document.querySelector("#stellar-balances-not-found")) document.querySelector("#stellar-balances-not-found").hidden = true;
    }
}
// We also search for a config file and display it
/*
 * Seeks to find an IPNS link under the 'config' variable of an i Stellar
 * Address.
 *
 * Outputs found value if any under #stellar-data-config
 * Adds to progressPlaceholder.
 * Moves on to retrieve the found link 
 *
 */
async function fetchAKIDFromClientWallet(stellarAddress){
    archingKaosLog("Loading your profile...");
    fetch(getStellarConfigurationVariableURL(stellarAddress), {
        method:'GET',
        headers:{
            Accept: 'application/json'
        }
    }).then(response=>{
        if(response.ok){
            response.json().then(json=>{
                var cnf = document.createElement("p");
                cnf.innerText = atob(json.value);
                document.querySelector('#stellar-data-config').appendChild(cnf);
                progressPlaceholder.max++;
                progressPlaceholder.value++;
                getConfiguration(atob(json.value),stellarAddress);
            })
        }
    })
}

// var stellar_connection_status = 0;

// Put it there. in the field
function putKeyToField(k){
    let base = document.querySelector("#stellar-freigher-connect-address-button");
    stellar_connection_status = 1;
    fetchAKIDFromClientWallet(k);
    base.innerText=k;
    base.onclick='';
}

// TODO: Clarify which parts of here will be needed
//function showStellar(){
//    if (stellar_connection_status === 1 ){
//        document.querySelector("#stellar-balances-link").hidden=false;
//        document.querySelector("#stellar-data-config-link").hidden=false;
//        document.querySelector("#arching-kaos-id-link").hidden=false;
//        document.querySelector("#mypage-section-link").hidden=false;
//    }
//}
// TODO: (follow up) eg below
// Hide stellar stuff if no freighter
//if (!window.freighterApi.isConnected()) {
//    document.querySelector("#stellar-freigher-connect-address-button").hidden=true;
//}
//
//function hideStellar(){
//    document.querySelector("#stellar-balances-link").hidden=true;
//    document.querySelector("#stellar-data-config-link").hidden=true;
//    document.querySelector("#arching-kaos-id-link").hidden=true;
//    document.querySelector("#mypage-section-link").hidden=true;
//}
//
//hideStellar();

// That's how we get the publicKey
const retrievePublicKey = async () => {
    let publicKey = "";
    let error = "";
    try {
        publicKey = await window.freighterApi.getPublicKey()
        .then(publicKey => {putKeyToField(publicKey);letme(publicKey)});
    } catch (e) {
        error = e;
    }
    if (error) {
        return error;
    }
    return publicKey;
};

// Function that initiates the connection with the Wallet ( we just read )
function connect(){
    if ( stellar_connection_status === 1 ){
        showStellar();
    } else {
        const result = retrievePublicKey();
    }
}

function scanStellarNetworkForPeers(){
    getTrustlines();
    getHolders();
}

// vim: tabstop=4 shiftwidth=4 expandtab softtabstop=4