"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());
    });
};
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 };
    }
};
var __read = (this && this.__read) || function (o, n) {
    var m = typeof Symbol === "function" && o[Symbol.iterator];
    if (!m) return o;
    var i = m.call(o), r, ar = [], e;
    try {
        while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);
    }
    catch (error) { e = { error: error }; }
    finally {
        try {
            if (r && !r.done && (m = i["return"])) m.call(i);
        }
        finally { if (e) throw e.error; }
    }
    return ar;
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.coalesceModuleAddress = exports.getTypeFromExternalAddress = exports.getExternalAddressFromType = exports.isValidAptosType = exports.getForeignAssetAddress = exports.getAssetFullyQualifiedType = exports.generateSignAndSubmitScript = exports.generateSignAndSubmitEntryFunction = void 0;
var utils_1 = require("ethers/lib/utils");
var js_sha3_1 = require("js-sha3");
var utils_2 = require("../utils");
var aptos_1 = require("aptos");
/**
 * Generate, sign, and submit a transaction calling the given entry function with the given
 * arguments. Prevents transaction submission and throws if the transaction fails.
 *
 * This is separated from `generateSignAndSubmitScript` because it makes use of `AptosClient`'s
 * `generateTransaction` which pulls ABIs from the node and uses them to encode arguments
 * automatically.
 * @param client Client used to transfer data to/from Aptos node
 * @param sender Account that will submit transaction
 * @param payload Payload containing unencoded fully qualified entry function, types, and arguments
 * @param opts Override default transaction options
 * @returns Data from transaction after is has been successfully submitted to mempool
 */
var generateSignAndSubmitEntryFunction = function (client, sender, payload, opts) {
    // overwriting `max_gas_amount` and `gas_unit_price` defaults
    // rest of defaults are defined here: https://aptos-labs.github.io/ts-sdk-doc/classes/AptosClient.html#generateTransaction
    var customOpts = Object.assign({
        gas_unit_price: "100",
        max_gas_amount: "30000",
    }, opts);
    return client
        .generateTransaction(sender.address(), payload, customOpts)
        .then(function (rawTx) {
        return signAndSubmitTransaction(client, sender, rawTx);
    });
};
exports.generateSignAndSubmitEntryFunction = generateSignAndSubmitEntryFunction;
/**
 * Generate, sign, and submit a transaction containing given bytecode. Prevents transaction
 * submission and throws if the transaction fails.
 *
 * Unlike `generateSignAndSubmitEntryFunction`, this function must construct a `RawTransaction`
 * manually because `generateTransaction` does not have support for scripts for which there are
 * no corresponding on-chain ABIs. Type/argument encoding is left to the caller.
 * @param client Client used to transfer data to/from Aptos node
 * @param sender Account that will submit transaction
 * @param payload Payload containing compiled bytecode and encoded types/arguments
 * @param opts Override default transaction options
 * @returns Data from transaction after is has been successfully submitted to mempool
 */
var generateSignAndSubmitScript = function (client, sender, payload, opts) { return __awaiter(void 0, void 0, void 0, function () {
    var customOpts, _a, sequenceNumber, chainId, rawTx;
    return __generator(this, function (_b) {
        switch (_b.label) {
            case 0:
                customOpts = Object.assign({
                    gas_unit_price: "100",
                    max_gas_amount: "30000",
                }, opts);
                return [4 /*yield*/, Promise.all([
                        client.getAccount(sender.address()),
                        client.getChainId(),
                    ])];
            case 1:
                _a = __read.apply(void 0, [_b.sent(), 2]), sequenceNumber = _a[0].sequence_number, chainId = _a[1];
                rawTx = new aptos_1.TxnBuilderTypes.RawTransaction(aptos_1.TxnBuilderTypes.AccountAddress.fromHex(sender.address()), BigInt(sequenceNumber), payload, BigInt(customOpts.max_gas_amount), BigInt(customOpts.gas_unit_price), BigInt(Math.floor(Date.now() / 1000) + 10), new aptos_1.TxnBuilderTypes.ChainId(chainId));
                // sign & submit transaction
                return [2 /*return*/, signAndSubmitTransaction(client, sender, rawTx)];
        }
    });
}); };
exports.generateSignAndSubmitScript = generateSignAndSubmitScript;
/**
 * Derives the fully qualified type of the asset defined by the given origin chain and address.
 * @param tokenBridgeAddress Address of token bridge (32 bytes)
 * @param originChain Chain ID of chain that original asset is from
 * @param originAddress Native address of asset; if origin chain ID is 22 (Aptos), this is the
 * asset's fully qualified type
 * @returns The fully qualified type on Aptos for the given asset
 */
var getAssetFullyQualifiedType = function (tokenBridgeAddress, originChain, originAddress) {
    // native asset
    if (originChain === utils_2.CHAIN_ID_APTOS) {
        // originAddress should be of form address::module::type
        if (!exports.isValidAptosType(originAddress)) {
            console.error("Invalid qualified type");
            return null;
        }
        return utils_2.ensureHexPrefix(originAddress);
    }
    // non-native asset, derive unique address
    var wrappedAssetAddress = exports.getForeignAssetAddress(tokenBridgeAddress, originChain, originAddress);
    return wrappedAssetAddress
        ? utils_2.ensureHexPrefix(wrappedAssetAddress) + "::coin::T"
        : null;
};
exports.getAssetFullyQualifiedType = getAssetFullyQualifiedType;
/**
 * Derive the module address for an asset defined by the given origin chain and address.
 * @param tokenBridgeAddress Address of token bridge (32 bytes)
 * @param originChain Chain ID of chain that original asset is from
 * @param originAddress Native address of asset
 * @returns The module address for the given asset
 */
var getForeignAssetAddress = function (tokenBridgeAddress, originChain, originAddress) {
    if (originChain === utils_2.CHAIN_ID_APTOS) {
        return null;
    }
    // from https://github.com/aptos-labs/aptos-core/blob/25696fd266498d81d346fe86e01c330705a71465/aptos-move/framework/aptos-framework/sources/account.move#L90-L95
    var DERIVE_RESOURCE_ACCOUNT_SCHEME = Buffer.alloc(1);
    DERIVE_RESOURCE_ACCOUNT_SCHEME.writeUInt8(255);
    var chain = Buffer.alloc(2);
    chain.writeUInt16BE(originChain);
    return js_sha3_1.sha3_256(Buffer.concat([
        utils_2.hex(utils_1.hexZeroPad(utils_2.ensureHexPrefix(tokenBridgeAddress), 32)),
        chain,
        Buffer.from("::", "ascii"),
        utils_2.hex(utils_1.hexZeroPad(utils_2.ensureHexPrefix(originAddress), 32)),
        DERIVE_RESOURCE_ACCOUNT_SCHEME,
    ]));
};
exports.getForeignAssetAddress = getForeignAssetAddress;
/**
 * Test if given string is a valid fully qualified type of moduleAddress::moduleName::structName.
 * @param str String to test
 * @returns Whether or not given string is a valid type
 */
var isValidAptosType = function (str) {
    return /^(0x)?[0-9a-fA-F]+::\w+::\w+$/.test(str);
};
exports.isValidAptosType = isValidAptosType;
/**
 * Hashes the given type. Because fully qualified types are a concept unique to Aptos, this
 * output acts as the address on other chains.
 * @param fullyQualifiedType Fully qualified type on Aptos
 * @returns External address corresponding to given type
 */
var getExternalAddressFromType = function (fullyQualifiedType) {
    // hash the type so it fits into 32 bytes
    return js_sha3_1.sha3_256(fullyQualifiedType);
};
exports.getExternalAddressFromType = getExternalAddressFromType;
/**
 * Given a hash, returns the fully qualified type by querying the corresponding TypeInfo.
 * @param client Client used to transfer data to/from Aptos node
 * @param tokenBridgeAddress Address of token bridge
 * @param fullyQualifiedTypeHash Hash of fully qualified type
 * @returns The fully qualified type associated with the given hash
 */
function getTypeFromExternalAddress(client, tokenBridgeAddress, fullyQualifiedTypeHash) {
    return __awaiter(this, void 0, void 0, function () {
        var state, handle, typeInfo, moduleName, structName, _a;
        return __generator(this, function (_b) {
            switch (_b.label) {
                case 0:
                    // get handle
                    tokenBridgeAddress = utils_2.ensureHexPrefix(tokenBridgeAddress);
                    return [4 /*yield*/, client.getAccountResource(tokenBridgeAddress, tokenBridgeAddress + "::state::State")];
                case 1:
                    state = (_b.sent()).data;
                    handle = state.native_infos.handle;
                    _b.label = 2;
                case 2:
                    _b.trys.push([2, 4, , 5]);
                    return [4 /*yield*/, client.getTableItem(handle, {
                            key_type: tokenBridgeAddress + "::token_hash::TokenHash",
                            value_type: "0x1::type_info::TypeInfo",
                            key: { hash: fullyQualifiedTypeHash },
                        })];
                case 3:
                    typeInfo = _b.sent();
                    if (!typeInfo) {
                        return [2 /*return*/, null];
                    }
                    moduleName = Buffer.from(typeInfo.module_name.substring(2), "hex").toString("ascii");
                    structName = Buffer.from(typeInfo.struct_name.substring(2), "hex").toString("ascii");
                    return [2 /*return*/, typeInfo.account_address + "::" + moduleName + "::" + structName];
                case 4:
                    _a = _b.sent();
                    return [2 /*return*/, null];
                case 5: return [2 /*return*/];
            }
        });
    });
}
exports.getTypeFromExternalAddress = getTypeFromExternalAddress;
/**
 * Returns module address from given fully qualified type/module address.
 * @param str FQT or module address
 * @returns Module address
 */
var coalesceModuleAddress = function (str) {
    return str.split("::")[0];
};
exports.coalesceModuleAddress = coalesceModuleAddress;
/**
 * Simulates given raw transaction and either returns the resulting transaction that was submitted
 * to the mempool, or throws if it fails.
 * @param client Client used to transfer data to/from Aptos node
 * @param sender Account that will submit transaction
 * @param rawTx Raw transaction to sign & submit
 * @returns Transaction data
 */
var signAndSubmitTransaction = function (client, sender, rawTx) { return __awaiter(void 0, void 0, void 0, function () {
    return __generator(this, function (_a) {
        switch (_a.label) {
            case 0: 
            // simulate transaction
            return [4 /*yield*/, client.simulateTransaction(sender, rawTx).then(function (sims) {
                    return sims.forEach(function (tx) {
                        if (!tx.success) {
                            throw new Error("Transaction failed: " + tx.vm_status + "\n" + JSON.stringify(tx, null, 2));
                        }
                    });
                })];
            case 1:
                // simulate transaction
                _a.sent();
                // sign & submit transaction
                return [2 /*return*/, client
                        .signTransaction(sender, rawTx)
                        .then(function (signedTx) { return client.submitTransaction(signedTx); })
                        .then(function (pendingTx) { return client.waitForTransactionWithResult(pendingTx.hash); })];
        }
    });
}); };
