<commit_before>var utils = require("../js/utils");
var fixtures = require("../js/fixtures");

var bigRat = require('big-rational');

var isMist = false;

require('es6-promise').polyfill();

if (typeof web3 === 'undefined') {
    var web3 = require('ethereum.js');
    window.web3 = web3;
}

try {
    web3.setProvider(new web3.providers.HttpProvider());

    try {
        var m = web3.eth.getStorageAt(fixtures.addresses.etherex, "0x5");
    }
    catch (e) {
        web3.setProvider(new web3.providers.HttpProvider('http://localhost:8545'));
        isMist = true;
    }

    var ContractABI = web3.eth.contract(fixtures.contract_desc);
    var contract = new ContractABI(fixtures.addresses.etherex);

    // console.log("CLIENT", web3.version.client);
    // console.log("CONTRACT", contract);
}
catch(e) {
    console.log("Some ethereum.js error", String(e));
}

web3.padDecimal = function (string, chars) {
    string = web3.fromDecimal(string).substr(2);
    return Array(chars - string.length + 1).join("0") + string;
};

var EthereumClient = function() {

    // Loading methods

    this.loadAddresses = function(success, failure) {
        var loadPromise = new Promise(function (resolve, reject) {
            try {
                var accounts = web3.eth.accounts;

                if (!accounts || accounts.length == 0)
                    reject("No accounts were found on this Ethereum node.");

                resolve(accounts);
            }
            catch (e) {
                reject("Unable to load addresses, are you running an Ethereum node? Please load this URL in AlethZero, or with a cpp-ethereum node with JSONRPC enabled running alongside a regular browser.");
                // reject("Error loading accounts: " + String(e));
            }
        });

        loadPromise.then(function (accounts) {
            success(accounts);
        }, function (e) {
            failure(String(e));
        });
    };

    this.loadMarkets = function(user, success, failure) {
        try {
            var last = _.parseInt(contract.call().get_last_market_id().toString());

            // console.log("LAST MARKET ID: ", last);

            if (!last && !isMist) {
                failure("No market found, seems like contracts are missing.");
                return;
            }

            var markets = [];

            var favs = localStorage.getItem('favorites');
            var favorites = JSON.parse(favs);

            if (!favorites || typeof(favorites) != 'object')
                favorites = [];
            // console.log('FAVORITES', favorites);

            for (var i = 1; i < last + 1; i++) {
                try {
                    var market = contract.call().get_market(i);
                    // console.log("Market from ABI:", market);

                    var id = _.parseInt(market[0].toString());
                    var name = web3.toAscii(web3.fromDecimal(market[1].toString()));
                    var address = web3.fromDecimal(market[2]);
                    var decimals = _.parseInt(market[3].toString());
                    var precision = _.parseInt(market[4].toString());
                    var minimum = _.parseInt(market[5].toString());
                    if (market[6] == 1)
                        var lastPrice = null;
                    else
                        var lastPrice = parseFloat(bigRat(market[6].toString()).divide(bigRat(Math.pow(10, market[4].toString().length - 1))).toDecimal());
                    var owner = web3.fromDecimal(market[7]);
                    var block = _.parseInt(market[8].toString());
                    var total_trades = _.parseInt(market[9].toString());

                    // console.log(id, name, address, decimals, precision, minimum, lastPrice, owner, block, total_trades);

                    var SubContractABI = web3.eth.contract(fixtures.sub_contract_desc);
                    var subcontract = new SubContractABI(address);
                    var balance = subcontract.call().balance(user.addresses[0]).toString();

                    var favorite = false;
                    if (favorites.length > 0 && _.indexOf(favorites, id) >= 0)
                        var favorite = true;

                    markets.push({
                        id: id,
                        name: name,
                        address: address,
                        decimals: decimals,
                        minimum: minimum,
                        precision: precision,
                        lastPrice: lastPrice,
                        owner: owner,
                        block: block,
                        total_trades: total_trades,
                        balance: _.parseInt(balance),
                        favorite: favorite
                    });
                }
                catch(e) {
                    failure("Unable to load market " + i + ": " + String(e));
                }
            }

            if (markets)
                success(markets);
            else
                failure("No market to load.")
        }
        catch (e) {
            if (isMist)
                success("Skipping...");
            failure("Unable to load markets: " + String(e));
        }
    };

    this.loadTrades = function(flux, market, progress, success, failure) {
        try {
            // Set defaultBlock to 'pending' trade IDs
            web3.eth.defaultBlock = 'pending';

            var trade_ids = contract.call().get_trade_ids(market.id);

            if (!trade_ids || trade_ids.length == 0) {
                failure("No trades found");
                return;
            }

            var total = trade_ids.length;
            // console.log("TOTAL TRADES: ", total);

            var tradePromises = [];

            for (var i = 0; i < total; i++) {
                var tradePromise = new Promise(function (resolve, reject) {
                    var id = trade_ids[i];
                    var p = i;

                    var trade = contract.call().get_trade(id);
                    // console.log("Trade from ABI:", trade);

                    try {
                        var id = web3.fromDecimal(trade[0]);
                        var ref = trade[7];

                        // Resolve on filled trades
                        if (id == "0x0" || ref == "0"){
                            resolve({});
                            return;
                        }

                        var status = 'mined';

                        // Set defaultBlock to -1 to check mined status
                        web3.eth.defaultBlock = 'latest';

                        var tradeExists = web3.eth.getStorageAt(fixtures.addresses.etherex, web3.fromDecimal(ref));

                        if (tradeExists == "0x")
                            status = 'pending';
                        else
                            status = 'mined';

                        var type = _.parseInt(trade[1].toString());
                        var marketid = _.parseInt(trade[2].toString());
                        var amountPrecision = Math.pow(10, market.decimals);
                        var precision = market.precision;

                        // console.log("Loading trade " + id + " for market " + market.name);

                        var amount = bigRat(trade[3].toString()).divide(amountPrecision).valueOf();
                        var price = bigRat(trade[4].toString()).divide(precision).valueOf();

                        // Update progress
                        progress({percent: (p + 1) / total * 100 });

                        resolve({
                            id: id,
                            type: type == 1 ? 'buys' : 'sells',
                            price: price,
                            amount: amount,
                            total: amount * price,
                            owner: web3.fromDecimal(trade[5].toString()),<commit_msg>fix pending trades status<commit_after>var utils = require("../js/utils");
var fixtures = require("../js/fixtures");

var bigRat = require('big-rational');

var isMist = false;

require('es6-promise').polyfill();

if (typeof web3 === 'undefined') {
    var web3 = require('ethereum.js');
    window.web3 = web3;
}

try {
    web3.setProvider(new web3.providers.HttpProvider());

    try {
        var m = web3.eth.getStorageAt(fixtures.addresses.etherex, "0x5");
    }
    catch (e) {
        web3.setProvider(new web3.providers.HttpProvider('http://localhost:8545'));
        isMist = true;
    }

    var ContractABI = web3.eth.contract(fixtures.contract_desc);
    var contract = new ContractABI(fixtures.addresses.etherex);

    // console.log("CLIENT", web3.version.client);
    // console.log("CONTRACT", contract);
}
catch(e) {
    console.log("Some ethereum.js error", String(e));
}

web3.padDecimal = function (string, chars) {
    string = web3.fromDecimal(string).substr(2);
    return Array(chars - string.length + 1).join("0") + string;
};

var EthereumClient = function() {

    // Loading methods

    this.loadAddresses = function(success, failure) {
        var loadPromise = new Promise(function (resolve, reject) {
            try {
                var accounts = web3.eth.accounts;

                if (!accounts || accounts.length == 0)
                    reject("No accounts were found on this Ethereum node.");

                resolve(accounts);
            }
            catch (e) {
                reject("Unable to load addresses, are you running an Ethereum node? Please load this URL in AlethZero, or with a cpp-ethereum node with JSONRPC enabled running alongside a regular browser.");
                // reject("Error loading accounts: " + String(e));
            }
        });

        loadPromise.then(function (accounts) {
            success(accounts);
        }, function (e) {
            failure(String(e));
        });
    };

    this.loadMarkets = function(user, success, failure) {
        try {
            var last = _.parseInt(contract.call().get_last_market_id().toString());

            // console.log("LAST MARKET ID: ", last);

            if (!last && !isMist) {
                failure("No market found, seems like contracts are missing.");
                return;
            }

            var markets = [];

            var favs = localStorage.getItem('favorites');
            var favorites = JSON.parse(favs);

            if (!favorites || typeof(favorites) != 'object')
                favorites = [];
            // console.log('FAVORITES', favorites);

            for (var i = 1; i < last + 1; i++) {
                try {
                    var market = contract.call().get_market(i);
                    // console.log("Market from ABI:", market);

                    var id = _.parseInt(market[0].toString());
                    var name = web3.toAscii(web3.fromDecimal(market[1].toString()));
                    var address = web3.fromDecimal(market[2]);
                    var decimals = _.parseInt(market[3].toString());
                    var precision = _.parseInt(market[4].toString());
                    var minimum = _.parseInt(market[5].toString());
                    if (market[6] == 1)
                        var lastPrice = null;
                    else
                        var lastPrice = parseFloat(bigRat(market[6].toString()).divide(bigRat(Math.pow(10, market[4].toString().length - 1))).toDecimal());
                    var owner = web3.fromDecimal(market[7]);
                    var block = _.parseInt(market[8].toString());
                    var total_trades = _.parseInt(market[9].toString());

                    // console.log(id, name, address, decimals, precision, minimum, lastPrice, owner, block, total_trades);

                    var SubContractABI = web3.eth.contract(fixtures.sub_contract_desc);
                    var subcontract = new SubContractABI(address);
                    var balance = subcontract.call().balance(user.addresses[0]).toString();

                    var favorite = false;
                    if (favorites.length > 0 && _.indexOf(favorites, id) >= 0)
                        var favorite = true;

                    markets.push({
                        id: id,
                        name: name,
                        address: address,
                        decimals: decimals,
                        minimum: minimum,
                        precision: precision,
                        lastPrice: lastPrice,
                        owner: owner,
                        block: block,
                        total_trades: total_trades,
                        balance: _.parseInt(balance),
                        favorite: favorite
                    });
                }
                catch(e) {
                    failure("Unable to load market " + i + ": " + String(e));
                }
            }

            if (markets)
                success(markets);
            else
                failure("No market to load.")
        }
        catch (e) {
            if (isMist)
                success("Skipping...");
            failure("Unable to load markets: " + String(e));
        }
    };

    this.loadTrades = function(flux, market, progress, success, failure) {
        try {
            // Set defaultBlock to 'pending' trade IDs
            web3.eth.defaultBlock = 'pending';

            var trade_ids = contract.call().get_trade_ids(market.id);

            if (!trade_ids || trade_ids.length == 0) {
                failure("No trades found");
                return;
            }

            var total = trade_ids.length;
            // console.log("TOTAL TRADES: ", total);

            var tradePromises = [];

            for (var i = 0; i < total; i++) {
                var tradePromise = new Promise(function (resolve, reject) {
                    var id = trade_ids[i];
                    var p = i;

                    var trade = contract.call().get_trade(id);
                    // console.log("Trade from ABI:", trade);

                    try {
                        var id = web3.fromDecimal(trade[0]);
                        var ref = trade[7];

                        // Resolve on filled trades
                        if (id == "0x0" || ref == "0"){
                            resolve({});
                            return;
                        }

                        var status = 'mined';

                        var tradeExists = web3.eth.getStorageAt(fixtures.addresses.etherex, web3.fromDecimal(ref), 'latest');

                        if (tradeExists == "0x00")
                            status = 'pending';
                        else
                            status = 'mined';

                        var type = _.parseInt(trade[1].toString());
                        var marketid = _.parseInt(trade[2].toString());
                        var amountPrecision = Math.pow(10, market.decimals);
                        var precision = market.precision;

                        // console.log("Loading trade " + id + " for market " + market.name);

                        var amount = bigRat(trade[3].toString()).divide(amountPrecision).valueOf();
                        var price = bigRat(trade[4].toString()).divide(precision).valueOf();

                        // Update progress
                        progress({percent: (p + 1) / total * 100 });

                        resolve({
                            id: id,
                            type: type == 1 ? 'buys' : 'sells',
                            price: price,
                            amount: amount,
                            total: amount * price,
                            owner: web3.fromDecimal(trade[5].toString()),
{'fraction_non_alphanumeric': 0.11965270295962989, 'fraction_numerical': 0.009886558083528741, 'mean_word_length': 1.3457707744908578, 'pattern_counts': {'":': 2, '<': 7, '<?xml version=': 0, '>': 7, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '3090268', 'n_tokens_mistral': 4180, 'n_tokens_neox': 3828, 'n_words': 919}