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());
    });
};
var __generator = (this && this.__generator) || function (thisArg, body) {
    var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
    return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
    function verb(n) { return function (v) { return step([n, v]); }; }
    function step(op) {
        if (f) throw new TypeError("Generator is already executing.");
        while (_) try {
            if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
            if (y = 0, t) op = [op[0] & 2, t.value];
            switch (op[0]) {
                case 0: case 1: t = op; break;
                case 4: _.label++; return { value: op[1], done: false };
                case 5: _.label++; y = op[1]; op = [0]; continue;
                case 7: op = _.ops.pop(); _.trys.pop(); continue;
                default:
                    if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
                    if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
                    if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
                    if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
                    if (t[2]) _.ops.pop();
                    _.trys.pop(); continue;
            }
            op = body.call(thisArg, _);
        } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
        if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
    }
};
import { addressFromContractId, binToHex, subContractId } from "@alephium/web3";
import { depositScript, destroyUnexecutedSequencesScript, remoteTokenPoolContract, updateRefundAddressScript, registerChainScript } from "../alephium/token_bridge";
import { bytes32ToUtf8String } from "../utils";
export function registerChain(signerProvider, tokenBridgeId, signedVAA, alphAmount) {
    return __awaiter(this, void 0, void 0, function () {
        var script, address;
        return __generator(this, function (_a) {
            switch (_a.label) {
                case 0:
                    script = registerChainScript();
                    return [4 /*yield*/, signerProvider.getSelectedAddress()];
                case 1:
                    address = _a.sent();
                    return [2 /*return*/, script.execute(signerProvider, {
                            initialFields: {
                                payer: address,
                                tokenBridge: tokenBridgeId,
                                vaa: Buffer.from(signedVAA).toString('hex'),
                                alphAmount: alphAmount
                            },
                            attoAlphAmount: alphAmount
                        })];
            }
        });
    });
}
export function deposit(signerProvider, tokenBridgeForChainId, amount) {
    return __awaiter(this, void 0, void 0, function () {
        var script, address;
        return __generator(this, function (_a) {
            switch (_a.label) {
                case 0:
                    script = depositScript();
                    return [4 /*yield*/, signerProvider.getSelectedAddress()];
                case 1:
                    address = _a.sent();
                    return [2 /*return*/, script.execute(signerProvider, {
                            initialFields: {
                                tokenBridgeForChain: tokenBridgeForChainId,
                                payer: address,
                                amount: amount
                            },
                            attoAlphAmount: amount
                        })];
            }
        });
    });
}
export function destroyUnexecutedSequenceContracts(signerProvider, tokenBridgeId, signedVAA) {
    return __awaiter(this, void 0, void 0, function () {
        var vaaHex, script;
        return __generator(this, function (_a) {
            vaaHex = Buffer.from(signedVAA).toString('hex');
            script = destroyUnexecutedSequencesScript();
            return [2 /*return*/, script.execute(signerProvider, {
                    initialFields: {
                        tokenBridge: tokenBridgeId,
                        vaa: vaaHex
                    }
                })];
        });
    });
}
export function updateRefundAddress(signerProvider, tokenBridgeId, signedVAA) {
    return __awaiter(this, void 0, void 0, function () {
        var vaaHex, script;
        return __generator(this, function (_a) {
            vaaHex = Buffer.from(signedVAA).toString('hex');
            script = updateRefundAddressScript();
            return [2 /*return*/, script.execute(signerProvider, {
                    initialFields: {
                        tokenBridge: tokenBridgeId,
                        vaa: vaaHex
                    }
                })];
        });
    });
}
export function zeroPad(value, byteLength) {
    var expectedLength = 2 * byteLength;
    if (value.length < expectedLength) {
        var prefix = Array(expectedLength - value.length).fill('0').join("");
        return prefix + value;
    }
    return value;
}
export function getAttestTokenHandlerId(tokenBridgeId, remoteChainId, groupIndex) {
    var pathHex = '00' + zeroPad(remoteChainId.toString(16), 2);
    return subContractId(tokenBridgeId, pathHex, groupIndex);
}
export function getTokenBridgeForChainId(tokenBridgeId, remoteChainId, groupIndex) {
    var pathHex = '01' + zeroPad(remoteChainId.toString(16), 2);
    return subContractId(tokenBridgeId, pathHex, groupIndex);
}
export function getTokenPoolId(tokenBridgeId, tokenChainId, tokenId, groupIndex) {
    if (tokenId.length !== 64) {
        throw new Error("Invalid token id " + tokenId + ", expect 32 bytes hex string");
    }
    var pathHex = '02' + zeroPad(tokenChainId.toString(16), 2) + tokenId;
    return subContractId(tokenBridgeId, pathHex, groupIndex);
}
export function getUnexecutedSequenceId(tokenBridgeForChainId, index, groupIndex) {
    var pathHex = zeroPad(index.toString(16), 8);
    return subContractId(tokenBridgeForChainId, pathHex, groupIndex);
}
export function contractExists(contractId, provider) {
    return __awaiter(this, void 0, void 0, function () {
        var address;
        return __generator(this, function (_a) {
            address = addressFromContractId(contractId);
            return [2 /*return*/, provider
                    .addresses
                    .getAddressesAddressGroup(address)
                    .then(function (_) { return true; })
                    .catch(function (e) {
                    if (e instanceof Error && e.message.indexOf("Group not found") !== -1) {
                        return false;
                    }
                    throw e;
                })];
        });
    });
}
function _getRemoteTokenInfo(contractState) {
    var tokenId = contractState.fields['bridgeTokenId'];
    var tokenChainId = Number(contractState.fields['tokenChainId']);
    var symbolHex = contractState.fields['symbol_'];
    var nameHex = contractState.fields['name_'];
    var decimals = Number(contractState.fields['decimals_']);
    return {
        tokenId: tokenId,
        tokenChainId: tokenChainId,
        symbol: bytes32ToUtf8String(Buffer.from(symbolHex, 'hex')),
        name: bytes32ToUtf8String(Buffer.from(nameHex, 'hex')),
        decimals: decimals
    };
}
export function getRemoteTokenInfoFromContractState(state) {
    var contract = remoteTokenPoolContract();
    return _getRemoteTokenInfo(contract.fromApiContractState(state));
}
export function getRemoteTokenInfo(address, groupIndex) {
    return __awaiter(this, void 0, void 0, function () {
        var contract, contractState;
        return __generator(this, function (_a) {
            switch (_a.label) {
                case 0:
                    contract = remoteTokenPoolContract();
                    return [4 /*yield*/, contract.fetchState(address, groupIndex)];
                case 1:
                    contractState = _a.sent();
                    return [2 /*return*/, _getRemoteTokenInfo(contractState)];
            }
        });
    });
}
export function stringToByte32Hex(str) {
    var encoder = new TextEncoder();
    var bytes = encoder.encode(str);
    if (bytes.length > 32) {
        throw new Error('string exceed 32 bytes');
    }
    return binToHex(bytes).padStart(64, '0');
}
function isConfirmed(txStatus) {
    return txStatus.type === 'Confirmed';
}
export function waitAlphTxConfirmed(provider, txId, confirmations) {
    return __awaiter(this, void 0, void 0, function () {
        var status;
        return __generator(this, function (_a) {
            switch (_a.label) {
                case 0: return [4 /*yield*/, provider.transactions.getTransactionsStatus({ txId: txId })];
                case 1:
                    status = _a.sent();
                    if (isConfirmed(status) && status.chainConfirmations >= confirmations) {
                        return [2 /*return*/, status];
                    }
                    return [4 /*yield*/, new Promise(function (r) { return setTimeout(r, 1000); })];
                case 2:
                    _a.sent();
                    return [2 /*return*/, waitAlphTxConfirmed(provider, txId, confirmations)];
            }
        });
    });
}
export var ALPHTokenInfo = {
    symbol: 'ALPH',
    name: 'ALPH',
    decimals: 18
};
export function getLocalTokenInfo(nodeProvider, localTokenId) {
    return __awaiter(this, void 0, void 0, function () {
        var groupIndex, contractAddress, contractState, symbol, name, decimals;
        return __generator(this, function (_a) {
            switch (_a.label) {
                case 0:
                    groupIndex = parseInt(localTokenId.slice(30, 32), 16);
                    contractAddress = addressFromContractId(localTokenId);
                    return [4 /*yield*/, nodeProvider.contracts.getContractsAddressState(contractAddress, { group: groupIndex })];
                case 1:
                    contractState = _a.sent();
                    if (contractState.fields.length < 4) {
                        throw new Error('Invalid token info');
                    }
                    if (contractState.fields[0].type !== 'ByteVec' ||
                        contractState.fields[1].type !== 'ByteVec' ||
                        contractState.fields[2].type !== 'U256') {
                        throw new Error('Invalid type of token contract fields');
                    }
                    symbol = bytes32ToUtf8String(Buffer.from(contractState.fields[0].value, 'hex'));
                    name = bytes32ToUtf8String(Buffer.from(contractState.fields[1].value, 'hex'));
                    decimals = Number(BigInt(contractState.fields[2].value));
                    return [2 /*return*/, { symbol: symbol, name: name, decimals: decimals }];
            }
        });
    });
}
