// ==UserScript==
// @name         GMGN Token Traders Monitor
// @namespace    http://tampermonkey.net/
// @version      0.3
// @description  Monitor GMGN token traders API and log response
// @author       Grok
// @match        https://gmgn.ai/sol/token/*
// @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);
    })
}

function timestampToString(timestamp) {
    if (!timestamp) return '';
    const date = new Date(timestamp * 1000);
    return date.toLocaleString('zh-CN', {
        year: 'numeric',
        month: '2-digit',
        day: '2-digit',
        hour: '2-digit',
        minute: '2-digit',
        second: '2-digit',
        hour12: false
    }).replace(/\//g, '-');
}
var arr_json_res_data = [];
function clickButton_get_toptrader() {
    console.log("load clickButton_get_toptrader ");
    var originalXhrOpen = XMLHttpRequest.prototype.open;
    var old_open = XMLHttpRequest.prototype.open;

    let str_token_address = window.location.pathname.slice(1).split('/').pop();
    str_token_address = str_token_address.split('?')[0];

    XMLHttpRequest.prototype.open = function (method, url) {
        if (url.includes(`/vas/api/v1/token_traders/sol/${str_token_address}`)) {
            console.log('Matched target API in XHR:', url);
            this.addEventListener('load', function () {
                try {
                    const response = JSON.parse(this.responseText);
                    if (response.code === 0 && response.data && response.data.list) {
                        arr_json_res_data = response.data.list;
                        console.log('Original Data:', arr_json_res_data);
                        funcDownload(JSON.stringify(arr_json_res_data), `top_trader_gmgn_${str_token_address}.json`);

                        XMLHttpRequest.prototype.open = old_open;
                        originalXhrOpen = null;


                    } else {
                        console.log('No valid list data found in response');
                    }
                } catch (err) {
                    console.error('XHR JSON parse error:', err);
                    console.log('XHR Raw Response:', this.responseText);
                }
            });
        }
        originalXhrOpen.apply(this, arguments);


    };
    // const observer = new MutationObserver((mutations) => {
    //     console.log('DOM changed, mutations:', mutations.length);
    // });
    // observer.observe(document.body, { childList: true, subtree: true });

    console.log('Script initialized');



}


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

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

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

    mydivbox.appendChild(button_get_toptrader);

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



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


})();

