// ==UserScript==
// @name         GMGN-Get-Holders
// @namespace    http://tampermonkey.net/
// @version      2024-10-19
// @description  try to take over the world!
// @author       You
// @match        https://gmgn.ai/sol/token/*
// @icon         https://www.google.com/s2/favicons?sz=64&domain=gmgn.ai
// @grant        none
// ==/UserScript==


function funcDownload(content, filename) {
    console.log('begin download');
    // 创建隐藏的可下载链接
    let eleLink = document.createElement('a');
    eleLink.download = filename;
    eleLink.style.display = 'none';
    // 字符内容转变成blob地址
    let blob = new Blob([content]);
    eleLink.href = URL.createObjectURL(blob);
    // 触发点击
    document.body.appendChild(eleLink);
    eleLink.click();
    // 然后移除
    document.body.removeChild(eleLink);
}


function sleep(sleepdelay) {
    return new Promise((resolve, reject) => {
        setTimeout(() => {
            resolve(sleepdelay);
        }, sleepdelay);
    })
}
var number_chars_obj = {
    "k": 3,
    "m": 6,
    "b": 9,
    "t": 12,
    "p": 15
};


var number_chars_arr = ["k", "m", "b", "t", "p"];

function get_thead_arr_holders() {

    // let titlearr = _thead.innerText.trim().split(/\r?\n/);
    let titlearr = ['Maker', 'SOL', 'Owned_per', 'Owned_amount', 'Buy_counts', 'Sell_counts'];
    return titlearr;
}



var pre_timestamp = -1;
var now_timestamp = -1;
async function get_tbody_data_holders() {

    let div_has_tran_table = document.querySelector("div.chakra-tabs__tab-panels.css-2zi8qu");
    let tbody = div_has_tran_table.querySelector("tbody.g-table-tbody");

    let arr_tbody_trs;
    arr_tbody_trs = Array.from(tbody.children);
    arr_tbody_trs.shift();


    for (let i = 0; i < arr_tbody_trs.length; i++) {

        let arr_tds;
        arr_tds = Array.from(arr_tbody_trs[i].children);

        let tdtexts = [];
        // if (arr_tds.length != 10) {
        //     continue;
        // }
        for (let i = 0; i < arr_tds.length; i++) {
            if (i == 0) {
                // trader
                let a_element = arr_tds[i].querySelector("a");
                let str_trader = a_element.href.split('/').pop();
                tdtexts[0] = str_trader;
                 

            }
            else if (i == 1) {
                //sol balance   

                let str_balance = arr_tds[i].innerText.trim().replace(/[,]/g, "").trim();
                str_balance = str_balance.replace(/\s+/g, "");

                str_balance = str_balance.toLowerCase();
                let float_balance;

                float_balance = parseFloat(str_balance);
                for (let number_char of number_chars_arr) {
                    if (str_balance.indexOf(number_char) != -1) {
                        float_balance = parseFloat(str_balance) * 10 ** number_chars_obj[number_char];
                    }
                }
                tdtexts[1] = float_balance;
               

            } else if (i == 2) {
                // old bought
                // Owned%

                let str_owned = "0";
          
                let float_sol = 0;

                let arr_owned_sol = arr_tds[i].children[0].children;
              
                str_owned = arr_owned_sol[0].innerText.trim().toLowerCase();
                str_owned = str_owned.replace(/[%]/g, "").trim();
               
                float_sol = parseFloat(str_owned);
                tdtexts[2] = float_sol;
              
              


            } else if (i == 3) {
                // sold
                // inflow/Amount
         
                let str_token_amount = "0";
                let float_token_amount = 0;

                let arr_sol_amount = arr_tds[i].children[0].children;
           
                str_token_amount = arr_sol_amount[1].innerText.trim().toLowerCase();
             
                float_token_amount = parseFloat(str_token_amount);
                for (let number_char of number_chars_arr) {
                    if (str_token_amount.indexOf(number_char) != -1) {
                        float_sol = parseFloat(str_token_amount) * 10 ** number_chars_obj[number_char];
                    }
                }
                tdtexts[3] = float_token_amount;
             




            } else if (i == 4) {
                // pnl
                continue;

           
 
            } else if (i == 5) {
               // Avg Cost/Sold
                continue;
            }
            else if (i == 6) {
                // Buy/Sell

            

              
              let  str_buysell_counts = arr_tds[i].innerText.trim().toLowerCase();
                str_buysell_counts = str_buysell.replace(/[\s+]/g, "").trim();
 
               let arr_buysell_counts = str_buysell_counts.split("/");

               let str_buy_counts = arr_buysell_counts[0];
             let   str_sell_counts =arr_buysell_counts[1];

             let   float_buy_counts = parseFloat(str_buy_counts);
             let    float_sell_counts = parseFloat(str_sell_counts);

                for (let number_char of number_chars_arr) {
                    if (str_buy_counts.indexOf(number_char) != -1) {
                        float_buy_counts = parseFloat(str_buy_counts) * 10 ** number_chars_obj[number_char];
                    }
                    if (str_sell_counts.indexOf(number_char) != -1) {
                        float_sell_counts = parseFloat(str_sell_counts) * 10 ** number_chars_obj[number_char];
                    }

                }

                tdtexts[4] = float_buy_counts;
                tdtexts[5] = float_sell_counts;

                continue

            }  else if (i == 7) {
                // Last Active
                continue

            }

        }
        res_data_get_holders.push(tdtexts);

    }


}

function save_resdata_holders() {
    console.log("enter save_resdata_holders");
    res_data_get_holders.forEach((val, index, arr) => { arr[index] = val.join() + "\n" });
    let urlpathname = window.location.pathname.slice(1).split('/');
    urlpathname = urlpathname.pop()

    funcDownload(res_data_get_holders.join(""), urlpathname + "_top_gmgn_sol" + "_" + parseInt(Date.now() / 1000) + ".csv");
    res_data_get_holders = [];

}
function autoScroll_holders() {
    console.log("enter autoScroll_holders");

    let interval;
    let scroll_times = 15;

    let div_has_tran_table = document.querySelector("div.chakra-tabs__tab-panels.css-2zi8qu");
    let tbody = div_has_tran_table.querySelector("div.css-1o2kb31 tbody.g-table-tbody");


    async function down() {
        interval = setInterval(async () => {

            let tbodytrs;

            if (scroll_times > 0) {

                await sleep(150);
                tbodytrs = tbody.children;
                tbodytrs[tbodytrs.length - 1].scrollIntoView({ behavior: "smooth", block: "start" });


            } else {
                clearInterval(interval);
                await get_tbody_data_holders();
                save_resdata_holders();
                return;

            }
            scroll_times--;


            tbodytrs = tbody.children;
            if (tbodytrs.length == 101) {
                clearInterval(interval);
                await get_tbody_data_holders();
                save_resdata_holders();
                return;

            }

            await sleep(300);
        }, 1200)

    }

    down()

}



var res_data_get_holders = [];
var sTop = 0;

// window.addEventListener('load', async () => {

(async function () {
    console.log("enter load");
    await sleep(6000);
    console.log("create button");

    var mydivbox = document.createElement("div");


    var button_holders = document.createElement("button");//创建 获取 holders 一个按钮
    button_holders.className = "tam-mybutton-gettran"
    button_holders.textContent = "holder"; //按钮内容
    button_holders.style.width = "90px"; //按钮宽度
    button_holders.style.height = "30px"; //按钮高度
    button_holders.style.align = "center"; //文本居中
    button_holders.style.color = "blue"; //按钮文字颜色
    button_holders.style.background = "#045710"; //按钮底色
    button_holders.style.border = "1px solid #045710"; //边框属性

    
    var button_toptrader = document.createElement("button");//创建 获取 top trader 一个按钮
    button_toptrader.className = "tam-mybutton-gettran"
    button_toptrader.textContent = "top"; //按钮内容
    button_toptrader.style.width = "90px"; //按钮宽度
    button_toptrader.style.height = "30px"; //按钮高度
    button_toptrader.style.align = "center"; //文本居中
    button_toptrader.style.color = "blue"; //按钮文字颜色
    button_toptrader.style.background = "#717171"; //按钮底色
    button_toptrader.style.border = "1px solid #717171"; //边框属性

    mydivbox.appendChild(button_toptrader);    
    mydivbox.appendChild(button_holders);

    mydivbox.style.position = "fixed";
    mydivbox.style.top = "80px";
    mydivbox.style.right = "40px";
    document.body.appendChild(mydivbox);

    button_holders.addEventListener("click", clickButton_get_holders); //监听按钮点击事件

    async function clickButton_get_holders() {
        res_data_get_holders = [];

        console.log("enter clickButton_get_holders res_data_get_holders=", res_data_get_holders);
        let div_chakra_tabs = document.querySelector('[role="tablist"]');
        let arr_buttons_chakra = Array.from(div_chakra_tabs.querySelectorAll("button"));
        let button_holders = undefined;
        for (let button of arr_buttons_chakra) {
            if (button.innerText.includes("Holders")) {
                button_holders = button;
                break;
            }
        }
        if (button_holders == undefined) {
            console.log("no button_holders");
            return;
        }
        await button_holders.click();
        await sleep(7000);

        let div_has_tran_table;
        let _tbody;
        let _thead;

    
        div_has_tran_table = document.querySelector("div.chakra-tabs__tab-panels.css-2zi8qu");
        _thead = div_has_tran_table.querySelector("div.css-1o2kb31 thead.g-table-thead");
        _tbody = div_has_tran_table.querySelector("div.css-1o2kb31 tbody.g-table-tbody");
        
        let arr_th = _thead.querySelectorAll("th");
        let click_USD_holder = arr_th[1].querySelector("div.css-1szs8yo");
        if (click_USD_holder.innerText.includes("USD")) {
            await click_USD_holder.click();
            await sleep(4000);
        }


        let titlearr = get_thead_arr_holders();
        res_data_get_holders.push(titlearr);
        autoScroll_holders();

    }

})();




