"use strict";
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.WalletConnectAdapter = exports.WalletConnectWalletName = void 0;
const tronwallet_abstract_adapter_1 = require("@tronweb3/tronwallet-abstract-adapter");
const tronwallet_abstract_adapter_2 = require("@tronweb3/tronwallet-abstract-adapter");
const walletconnect_tron_1 = require("@tronweb3/walletconnect-tron");
exports.WalletConnectWalletName = 'WalletConnect';
const NETWORK = Object.keys(tronwallet_abstract_adapter_2.ChainNetwork);
const validThemeVariables = [
    '--w3m-font-family',
    '--w3m-accent',
    '--w3m-color-mix',
    '--w3m-color-mix-strength',
    '--w3m-font-size-master',
    '--w3m-border-radius-master',
    '--w3m-z-index',
    '--w3m-qr-color',
];
class WalletConnectAdapter extends tronwallet_abstract_adapter_1.Adapter {
    constructor(config) {
        var _a, _b;
        super();
        this.name = exports.WalletConnectWalletName;
        this.url = 'https://walletconnect.org';
        this.icon = 'data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iMzAwIiBoZWlnaHQ9IjMwMCIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIj48cGF0aCBkPSJtNjEuNDM4NTQsOTQuMDAzOGM0OC45MTEyMywtNDcuODg4MTcgMTI4LjIxMTk5LC00Ny44ODgxNyAxNzcuMTIzMjEsMGw1Ljg4NjU1LDUuNzYzNDJjMi40NDU1NiwyLjM5NDQxIDIuNDQ1NTYsNi4yNzY1MSAwLDguNjcwOTJsLTIwLjEzNjcsMTkuNzE1NWMtMS4yM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3YzIuNDQ1NTYsLTIuMzk0NDEgNi40MTA2LC0yLjM5NDQxIDguODU2MTYsMGw1Ny4zNTQ5OCw1Ni4xNTUzNWMwLjYxMTM5LDAuNTk4NjEgMS42MDI2NSwwLjU5ODYxIDIuMjE0MDQsMGMwLjAwMDAxLDAgMC4wMDAwMiwtMC4wMDAwMSAwLjAwMDAzLC0wLjAwMDAybDU3LjM1MjEsLTU2LjE1NTMzYzIuNDQ1NSwtMi4zOTQ0NyA2LjQxMDU0LC0yLjM5NDU2IDguODU2MTYsLTAuMDAwMmMwLjAwMDAzLDAuMDAwMDMgMC4wMDAwNywwLjAwMDA3IDAuMDAwMSwwLjAwMDFsNTcuMzU0OSw1Ni4xNTU0M2MwLjYxMTM5LDAuNTk4NiAxLjYwMjY1LDAuNTk4NiAyLjIxNDA0LDBsNTcuMzUzOTgsLTU2LjE1NDMyYzIuNDQ1NTYsLTIuMzk0NDEgNi40MTA2LC0yLjM5NDQxIDguODU2MTYsMHoiIGZpbGw9IiMzYjk5ZmMiIGlkPSJzdmdfMSIvPjwvc3ZnPg==';
        this._readyState = tronwallet_abstract_adapter_1.WalletReadyState.Found;
        this._state = tronwallet_abstract_adapter_1.AdapterState.Disconnect;
        this._disconnected = () => {
            const wallet = this._wallet;
            if (wallet) {
                wallet.off('disconnected', this._disconnected);
                wallet.off('accountsChanged', this._accountsChanged);
                this._address = null;
                this._state = tronwallet_abstract_adapter_1.AdapterState.Disconnect;
                this.emit('disconnect');
                this.emit('stateChanged', this._state);
            }
        };
        this._accountsChanged = (curAddr) => {
            const preAddress = this.address;
            this._address = (curAddr === null || curAddr === void 0 ? void 0 : curAddr[0]) || '';
            this.emit('accountsChanged', this.address || '', preAddress || '');
        };
        config = Object.assign({}, config);
        if (!config || typeof config !== 'object') {
            throw new Error(`[WalletconnectAdapter] config is required.`);
        }
        if (!config.network) {
            console.error(`[WalletconnectAdapter] config.network must be one of ${NETWORK.join()} or a chainID such as 0x2b6653dc. Use Nile network instead.`);
            config.network = 'Nile';
        }
        if (!config.options) {
            throw new Error(`[WalletconnectAdapter] config.options is required.`);
        }
        const themeVariables = {};
        if ((_a = config.web3ModalConfig) === null || _a === void 0 ? void 0 : _a.themeVariables) {
            Object.entries(config.web3ModalConfig.themeVariables).forEach(([k, v]) => {
                const w3mKey = k.replace('--wcm-', '--w3m-');
                if (validThemeVariables.includes(w3mKey)) {
                    // @ts-ignore
                    themeVariables[w3mKey] = v;
                }
            });
        }
        config.themeMode = config.themeMode || ((_b = config.web3ModalConfig) === null || _b === void 0 ? void 0 : _b.themeMode);
        config.themeVariables = config.themeVariables || themeVariables;
        Reflect.deleteProperty(config, 'web3ModalConfig');
        this._connecting = false;
        this._wallet = null;
        this._address = null;
        this._config = config;
    }
    get address() {
        return this._address;
    }
    get readyState() {
        return this._readyState;
    }
    get state() {
        return this._state;
    }
    /**
     * Currently unused for WalletConnectAdapter.
     */
    get connecting() {
        return this._connecting;
    }
    connect() {
        return __awaiter(this, void 0, void 0, function* () {
            try {
                if (this.connected)
                    return;
                if (this.state === tronwallet_abstract_adapter_1.AdapterState.NotFound)
                    throw new tronwallet_abstract_adapter_1.WalletNotFoundError();
                this._connecting = true;
                let address;
                try {
                    if (this._wallet) {
                        ({ address } = yield this._wallet.connect());
                    }
                    else {
                        this._wallet = new walletconnect_tron_1.WalletConnectWallet(Object.assign(Object.assign({}, this._config), { network: walletconnect_tron_1.WalletConnectChainID[this._config.network] ||
                                `tron:${this._config.network}` }));
                        ({ address } = yield this._wallet.connect());
                    }
                }
                catch (error) {
                    if (error.constructor.name === 'Web3ModalError')
                        throw new tronwallet_abstract_adapter_1.WalletWindowClosedError();
                    throw new tronwallet_abstract_adapter_1.WalletConnectionError(error === null || error === void 0 ? void 0 : error.message, error);
                }
                this._wallet.on('disconnect', this._disconnected);
                this._wallet.on('accountsChanged', this._accountsChanged);
                this._address = address || '';
                this._state = tronwallet_abstract_adapter_1.AdapterState.Connected;
                this.emit('stateChanged', this._state);
                this.emit('connect', address);
            }
            catch (error) {
                this.emit('error', error);
                throw error;
            }
            finally {
                // this._connecting = false;
            }
        });
    }
    disconnect() {
        return __awaiter(this, void 0, void 0, function* () {
            if (this.state === tronwallet_abstract_adapter_1.AdapterState.NotFound) {
                return;
            }
            const wallet = this._wallet;
            if (wallet) {
                wallet.off('disconnect', this._disconnected);
                wallet.off('accountsChanged', this._accountsChanged);
                this._address = null;
                try {
                    yield wallet.disconnect();
                }
                catch (error) {
                    this.emit('error', new tronwallet_abstract_adapter_1.WalletDisconnectionError(error === null || error === void 0 ? void 0 : error.message, error));
                }
            }
            this._state = tronwallet_abstract_adapter_1.AdapterState.Disconnect;
            this.emit('disconnect');
            this.emit('stateChanged', this._state);
        });
    }
    signTransaction(transaction) {
        return __awaiter(this, void 0, void 0, function* () {
            if (this.state !== tronwallet_abstract_adapter_1.AdapterState.Connected)
                throw new tronwallet_abstract_adapter_1.WalletDisconnectedError();
            try {
                const wallet = this._wallet;
                if (!wallet)
                    throw new tronwallet_abstract_adapter_1.WalletDisconnectedError();
                try {
                    return yield wallet.signTransaction(transaction);
                }
                catch (error) {
                    throw new tronwallet_abstract_adapter_1.WalletSignTransactionError(error === null || error === void 0 ? void 0 : error.message, error);
                }
            }
            catch (error) {
                this.emit('error', error);
                throw error;
            }
        });
    }
    signMessage(message) {
        return __awaiter(this, void 0, void 0, function* () {
            try {
                const wallet = this._wallet;
                if (!wallet)
                    throw new tronwallet_abstract_adapter_1.WalletDisconnectedError();
                try {
                    return yield wallet.signMessage(message);
                }
                catch (error) {
                    throw new tronwallet_abstract_adapter_1.WalletSignMessageError(error === null || error === void 0 ? void 0 : error.message, error);
                }
            }
            catch (error) {
                this.emit('error', error);
                throw error;
            }
        });
    }
    /**
     * Get WalletConnect connection status.
     * Address is not empty if the WalletConnectWallet is connected.
     * @returns {object} status
     * @property {string} status.address - connected address
     */
    getConnectionStatus() {
        return __awaiter(this, void 0, void 0, function* () {
            if (!this._wallet || !this.connected) {
                return { address: '' };
            }
            try {
                return yield this._wallet.checkConnectStatus();
            }
            catch (e) {
                this._address = null;
                this._state = tronwallet_abstract_adapter_1.AdapterState.Disconnect;
                return { address: '' };
            }
        });
    }
}
exports.WalletConnectAdapter = WalletConnectAdapter;
//# sourceMappingURL=adapter.js.map