"use strict";
var __assign = (this && this.__assign) || function () {
    __assign = Object.assign || function(t) {
        for (var s, i = 1, n = arguments.length; i < n; i++) {
            s = arguments[i];
            for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
                t[p] = s[p];
        }
        return t;
    };
    return __assign.apply(this, arguments);
};
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;
};
var __spreadArray = (this && this.__spreadArray) || function (to, from) {
    for (var i = 0, il = from.length, j = to.length; i < il; i++, j++)
        to[j] = from[i];
    return to;
};
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.transferFromAptos = exports.transferNearFromNear = exports.transferTokenFromNear = exports.transferFromAlgorand = exports.transferFromSolana = exports.transferNativeSol = exports.transferFromXpla = exports.transferFromInjective = exports.transferFromTerra = exports.transferFromEthNative = exports.transferFromEth = exports.approveEth = exports.getAllowanceEth = void 0;
var spl_token_1 = require("@solana/spl-token");
var web3_js_1 = require("@solana/web3.js");
var terra_js_1 = require("@terra-money/terra.js");
var sdk_ts_1 = require("@injectivelabs/sdk-ts");
var algosdk_1 = require("algosdk");
var bn_js_1 = __importDefault(require("bn.js"));
var terra_1 = require("../terra");
var __1 = require("..");
var algorand_1 = require("../algorand");
var bridge_1 = require("../bridge");
var ethers_contracts_1 = require("../ethers-contracts");
var tokenBridge_1 = require("../solana/tokenBridge");
var utils_1 = require("../utils");
var cosmwasm_1 = require("../cosmwasm");
var xpla_js_1 = require("@xpla/xpla.js");
var aptos_1 = require("../aptos");
function getAllowanceEth(tokenBridgeAddress, tokenAddress, signer) {
    return __awaiter(this, void 0, void 0, function () {
        var token, signerAddress, allowance;
        return __generator(this, function (_a) {
            switch (_a.label) {
                case 0:
                    token = ethers_contracts_1.TokenImplementation__factory.connect(tokenAddress, signer);
                    return [4 /*yield*/, signer.getAddress()];
                case 1:
                    signerAddress = _a.sent();
                    return [4 /*yield*/, token.allowance(signerAddress, tokenBridgeAddress)];
                case 2:
                    allowance = _a.sent();
                    return [2 /*return*/, allowance];
            }
        });
    });
}
exports.getAllowanceEth = getAllowanceEth;
function approveEth(tokenBridgeAddress, tokenAddress, signer, amount, overrides) {
    if (overrides === void 0) { overrides = {}; }
    return __awaiter(this, void 0, void 0, function () {
        var token;
        return __generator(this, function (_a) {
            switch (_a.label) {
                case 0:
                    token = ethers_contracts_1.TokenImplementation__factory.connect(tokenAddress, signer);
                    return [4 /*yield*/, token.approve(tokenBridgeAddress, amount, overrides)];
                case 1: return [4 /*yield*/, (_a.sent()).wait()];
                case 2: return [2 /*return*/, _a.sent()];
            }
        });
    });
}
exports.approveEth = approveEth;
function transferFromEth(tokenBridgeAddress, signer, tokenAddress, amount, recipientChain, recipientAddress, relayerFee, overrides, payload) {
    if (relayerFee === void 0) { relayerFee = 0; }
    if (overrides === void 0) { overrides = {}; }
    if (payload === void 0) { payload = null; }
    return __awaiter(this, void 0, void 0, function () {
        var recipientChainId, bridge, v, _a, receipt;
        return __generator(this, function (_b) {
            switch (_b.label) {
                case 0:
                    recipientChainId = utils_1.coalesceChainId(recipientChain);
                    bridge = ethers_contracts_1.Bridge__factory.connect(tokenBridgeAddress, signer);
                    if (!(payload === null)) return [3 /*break*/, 2];
                    return [4 /*yield*/, bridge.transferTokens(tokenAddress, amount, recipientChainId, recipientAddress, relayerFee, utils_1.createNonce(), overrides)];
                case 1:
                    _a = _b.sent();
                    return [3 /*break*/, 4];
                case 2: return [4 /*yield*/, bridge.transferTokensWithPayload(tokenAddress, amount, recipientChainId, recipientAddress, utils_1.createNonce(), payload, overrides)];
                case 3:
                    _a = _b.sent();
                    _b.label = 4;
                case 4:
                    v = _a;
                    return [4 /*yield*/, v.wait()];
                case 5:
                    receipt = _b.sent();
                    return [2 /*return*/, receipt];
            }
        });
    });
}
exports.transferFromEth = transferFromEth;
function transferFromEthNative(tokenBridgeAddress, signer, amount, recipientChain, recipientAddress, relayerFee, overrides, payload) {
    if (relayerFee === void 0) { relayerFee = 0; }
    if (overrides === void 0) { overrides = {}; }
    if (payload === void 0) { payload = null; }
    return __awaiter(this, void 0, void 0, function () {
        var recipientChainId, bridge, v, _a, receipt;
        return __generator(this, function (_b) {
            switch (_b.label) {
                case 0:
                    recipientChainId = utils_1.coalesceChainId(recipientChain);
                    bridge = ethers_contracts_1.Bridge__factory.connect(tokenBridgeAddress, signer);
                    if (!(payload === null)) return [3 /*break*/, 2];
                    return [4 /*yield*/, bridge.wrapAndTransferETH(recipientChainId, recipientAddress, relayerFee, utils_1.createNonce(), __assign(__assign({}, overrides), { value: amount }))];
                case 1:
                    _a = _b.sent();
                    return [3 /*break*/, 4];
                case 2: return [4 /*yield*/, bridge.wrapAndTransferETHWithPayload(recipientChainId, recipientAddress, utils_1.createNonce(), payload, __assign(__assign({}, overrides), { value: amount }))];
                case 3:
                    _a = _b.sent();
                    _b.label = 4;
                case 4:
                    v = _a;
                    return [4 /*yield*/, v.wait()];
                case 5:
                    receipt = _b.sent();
                    return [2 /*return*/, receipt];
            }
        });
    });
}
exports.transferFromEthNative = transferFromEthNative;
function transferFromTerra(walletAddress, tokenBridgeAddress, tokenAddress, amount, recipientChain, recipientAddress, relayerFee, payload) {
    if (relayerFee === void 0) { relayerFee = "0"; }
    if (payload === void 0) { payload = null; }
    return __awaiter(this, void 0, void 0, function () {
        var recipientChainId, nonce, isNativeAsset, mk_initiate_transfer;
        var _a;
        return __generator(this, function (_b) {
            recipientChainId = utils_1.coalesceChainId(recipientChain);
            nonce = Math.round(Math.random() * 100000);
            isNativeAsset = terra_1.isNativeDenom(tokenAddress);
            mk_initiate_transfer = function (info) {
                return payload
                    ? {
                        initiate_transfer_with_payload: {
                            asset: {
                                amount: amount,
                                info: info,
                            },
                            recipient_chain: recipientChainId,
                            recipient: Buffer.from(recipientAddress).toString("base64"),
                            fee: relayerFee,
                            nonce: nonce,
                            payload: payload,
                        },
                    }
                    : {
                        initiate_transfer: {
                            asset: {
                                amount: amount,
                                info: info,
                            },
                            recipient_chain: recipientChainId,
                            recipient: Buffer.from(recipientAddress).toString("base64"),
                            fee: relayerFee,
                            nonce: nonce,
                        },
                    };
            };
            return [2 /*return*/, isNativeAsset
                    ? [
                        new terra_js_1.MsgExecuteContract(walletAddress, tokenBridgeAddress, {
                            deposit_tokens: {},
                        }, (_a = {}, _a[tokenAddress] = amount, _a)),
                        new terra_js_1.MsgExecuteContract(walletAddress, tokenBridgeAddress, mk_initiate_transfer({
                            native_token: {
                                denom: tokenAddress,
                            },
                        }), {}),
                    ]
                    : [
                        new terra_js_1.MsgExecuteContract(walletAddress, tokenAddress, {
                            increase_allowance: {
                                spender: tokenBridgeAddress,
                                amount: amount,
                                expires: {
                                    never: {},
                                },
                            },
                        }, {}),
                        new terra_js_1.MsgExecuteContract(walletAddress, tokenBridgeAddress, mk_initiate_transfer({
                            token: {
                                contract_addr: tokenAddress,
                            },
                        }), {}),
                    ]];
        });
    });
}
exports.transferFromTerra = transferFromTerra;
/**
 * Creates the necessary messages to transfer an asset
 * @param walletAddress Address of the Inj wallet
 * @param tokenBridgeAddress Address of the token bridge contract
 * @param tokenAddress Address of the token being transferred
 * @param amount Amount of token to be transferred
 * @param recipientChain Destination chain
 * @param recipientAddress Destination wallet address
 * @param relayerFee Relayer fee
 * @param payload Optional payload
 * @returns Transfer messages to be sent on chain
 */
function transferFromInjective(walletAddress, tokenBridgeAddress, tokenAddress, amount, recipientChain, recipientAddress, relayerFee, payload) {
    if (relayerFee === void 0) { relayerFee = "0"; }
    if (payload === void 0) { payload = null; }
    return __awaiter(this, void 0, void 0, function () {
        var recipientChainId, nonce, isNativeAsset, mk_action, mk_initiate_transfer;
        return __generator(this, function (_a) {
            recipientChainId = utils_1.coalesceChainId(recipientChain);
            nonce = Math.round(Math.random() * 100000);
            isNativeAsset = cosmwasm_1.isNativeDenomInjective(tokenAddress);
            mk_action = payload
                ? "initiate_transfer_with_payload"
                : "initiate_transfer";
            mk_initiate_transfer = function (info) {
                return payload
                    ? {
                        asset: {
                            amount: amount,
                            info: info,
                        },
                        recipient_chain: recipientChainId,
                        recipient: Buffer.from(recipientAddress).toString("base64"),
                        fee: relayerFee,
                        nonce: nonce,
                        payload: payload,
                    }
                    : {
                        asset: {
                            amount: amount,
                            info: info,
                        },
                        recipient_chain: recipientChainId,
                        recipient: Buffer.from(recipientAddress).toString("base64"),
                        fee: relayerFee,
                        nonce: nonce,
                    };
            };
            return [2 /*return*/, isNativeAsset
                    ? [
                        sdk_ts_1.MsgExecuteContract.fromJSON({
                            contractAddress: tokenBridgeAddress,
                            sender: walletAddress,
                            msg: {},
                            action: "deposit_tokens",
                            funds: { denom: tokenAddress, amount: amount },
                        }),
                        sdk_ts_1.MsgExecuteContract.fromJSON({
                            contractAddress: tokenBridgeAddress,
                            sender: walletAddress,
                            msg: mk_initiate_transfer({ native_token: { denom: tokenAddress } }),
                            action: mk_action,
                        }),
                    ]
                    : [
                        sdk_ts_1.MsgExecuteContract.fromJSON({
                            contractAddress: tokenAddress,
                            sender: walletAddress,
                            msg: {
                                spender: tokenBridgeAddress,
                                amount: amount,
                                expires: {
                                    never: {},
                                },
                            },
                            action: "increase_allowance",
                        }),
                        sdk_ts_1.MsgExecuteContract.fromJSON({
                            contractAddress: tokenBridgeAddress,
                            sender: walletAddress,
                            msg: mk_initiate_transfer({ token: { contract_addr: tokenAddress } }),
                            action: mk_action,
                        }),
                    ]];
        });
    });
}
exports.transferFromInjective = transferFromInjective;
function transferFromXpla(walletAddress, tokenBridgeAddress, tokenAddress, amount, recipientChain, recipientAddress, relayerFee, payload) {
    var _a;
    if (relayerFee === void 0) { relayerFee = "0"; }
    if (payload === void 0) { payload = null; }
    var recipientChainId = utils_1.coalesceChainId(recipientChain);
    var nonce = Math.round(Math.random() * 100000);
    var isNativeAsset = cosmwasm_1.isNativeDenomXpla(tokenAddress);
    var createInitiateTransfer = function (info) {
        return payload
            ? {
                initiate_transfer_with_payload: {
                    asset: {
                        amount: amount,
                        info: info,
                    },
                    recipient_chain: recipientChainId,
                    recipient: Buffer.from(recipientAddress).toString("base64"),
                    fee: relayerFee,
                    nonce: nonce,
                    payload: payload,
                },
            }
            : {
                initiate_transfer: {
                    asset: {
                        amount: amount,
                        info: info,
                    },
                    recipient_chain: recipientChainId,
                    recipient: Buffer.from(recipientAddress).toString("base64"),
                    fee: relayerFee,
                    nonce: nonce,
                },
            };
    };
    return isNativeAsset
        ? [
            new xpla_js_1.MsgExecuteContract(walletAddress, tokenBridgeAddress, {
                deposit_tokens: {},
            }, (_a = {}, _a[tokenAddress] = amount, _a)),
            new xpla_js_1.MsgExecuteContract(walletAddress, tokenBridgeAddress, createInitiateTransfer({
                native_token: {
                    denom: tokenAddress,
                },
            }), {}),
        ]
        : [
            new xpla_js_1.MsgExecuteContract(walletAddress, tokenAddress, {
                increase_allowance: {
                    spender: tokenBridgeAddress,
                    amount: amount,
                    expires: {
                        never: {},
                    },
                },
            }, {}),
            new xpla_js_1.MsgExecuteContract(walletAddress, tokenBridgeAddress, createInitiateTransfer({
                token: {
                    contract_addr: tokenAddress,
                },
            }), {}),
        ];
}
exports.transferFromXpla = transferFromXpla;
function transferNativeSol(connection, bridgeAddress, tokenBridgeAddress, payerAddress, amount, targetAddress, targetChain, relayerFee, payload, commitment) {
    if (relayerFee === void 0) { relayerFee = BigInt(0); }
    if (payload === void 0) { payload = null; }
    return __awaiter(this, void 0, void 0, function () {
        var rentBalance, payerPublicKey, ancillaryKeypair, createAncillaryAccountIx, initialBalanceTransferIx, initAccountIx, approvalIx, message, nonce, tokenBridgeTransferIx, closeAccountIx, blockhash, transaction;
        return __generator(this, function (_a) {
            switch (_a.label) {
                case 0: return [4 /*yield*/, spl_token_1.getMinimumBalanceForRentExemptAccount(connection, commitment)];
                case 1:
                    rentBalance = _a.sent();
                    payerPublicKey = new web3_js_1.PublicKey(payerAddress);
                    ancillaryKeypair = web3_js_1.Keypair.generate();
                    createAncillaryAccountIx = web3_js_1.SystemProgram.createAccount({
                        fromPubkey: payerPublicKey,
                        newAccountPubkey: ancillaryKeypair.publicKey,
                        lamports: rentBalance,
                        space: spl_token_1.ACCOUNT_SIZE,
                        programId: spl_token_1.TOKEN_PROGRAM_ID,
                    });
                    initialBalanceTransferIx = web3_js_1.SystemProgram.transfer({
                        fromPubkey: payerPublicKey,
                        lamports: amount,
                        toPubkey: ancillaryKeypair.publicKey,
                    });
                    initAccountIx = spl_token_1.createInitializeAccountInstruction(ancillaryKeypair.publicKey, spl_token_1.NATIVE_MINT, payerPublicKey);
                    approvalIx = tokenBridge_1.createApproveAuthoritySignerInstruction(tokenBridgeAddress, ancillaryKeypair.publicKey, payerPublicKey, amount);
                    message = web3_js_1.Keypair.generate();
                    nonce = utils_1.createNonce().readUInt32LE(0);
                    tokenBridgeTransferIx = payload !== null
                        ? tokenBridge_1.createTransferNativeWithPayloadInstruction(tokenBridgeAddress, bridgeAddress, payerAddress, message.publicKey, ancillaryKeypair.publicKey, spl_token_1.NATIVE_MINT, nonce, amount, Buffer.from(targetAddress), utils_1.coalesceChainId(targetChain), payload)
                        : tokenBridge_1.createTransferNativeInstruction(tokenBridgeAddress, bridgeAddress, payerAddress, message.publicKey, ancillaryKeypair.publicKey, spl_token_1.NATIVE_MINT, nonce, amount, relayerFee, Buffer.from(targetAddress), utils_1.coalesceChainId(targetChain));
                    closeAccountIx = spl_token_1.createCloseAccountInstruction(ancillaryKeypair.publicKey, //account to close
                    payerPublicKey, //Remaining funds destination
                    payerPublicKey //authority
                    );
                    return [4 /*yield*/, connection.getLatestBlockhash(commitment)];
                case 2:
                    blockhash = (_a.sent()).blockhash;
                    transaction = new web3_js_1.Transaction();
                    transaction.recentBlockhash = blockhash;
                    transaction.feePayer = payerPublicKey;
                    transaction.add(createAncillaryAccountIx, initialBalanceTransferIx, initAccountIx, approvalIx, tokenBridgeTransferIx, closeAccountIx);
                    transaction.partialSign(message, ancillaryKeypair);
                    return [2 /*return*/, transaction];
            }
        });
    });
}
exports.transferNativeSol = transferNativeSol;
function transferFromSolana(connection, bridgeAddress, tokenBridgeAddress, payerAddress, fromAddress, mintAddress, amount, targetAddress, targetChain, originAddress, originChain, fromOwnerAddress, relayerFee, payload, commitment) {
    if (relayerFee === void 0) { relayerFee = BigInt(0); }
    if (payload === void 0) { payload = null; }
    return __awaiter(this, void 0, void 0, function () {
        var originChainId, nonce, approvalIx, message, isSolanaNative, tokenBridgeTransferIx, transaction, blockhash;
        return __generator(this, function (_a) {
            switch (_a.label) {
                case 0:
                    originChainId = originChain
                        ? utils_1.coalesceChainId(originChain)
                        : undefined;
                    if (fromOwnerAddress === undefined) {
                        fromOwnerAddress = payerAddress;
                    }
                    nonce = utils_1.createNonce().readUInt32LE(0);
                    approvalIx = tokenBridge_1.createApproveAuthoritySignerInstruction(tokenBridgeAddress, fromAddress, fromOwnerAddress, amount);
                    message = web3_js_1.Keypair.generate();
                    isSolanaNative = originChainId === undefined || originChainId === utils_1.CHAIN_ID_SOLANA;
                    if (!isSolanaNative && !originAddress) {
                        return [2 /*return*/, Promise.reject("originAddress is required when specifying originChain")];
                    }
                    tokenBridgeTransferIx = isSolanaNative
                        ? payload !== null
                            ? tokenBridge_1.createTransferNativeWithPayloadInstruction(tokenBridgeAddress, bridgeAddress, payerAddress, message.publicKey, fromAddress, mintAddress, nonce, amount, targetAddress, utils_1.coalesceChainId(targetChain), payload)
                            : tokenBridge_1.createTransferNativeInstruction(tokenBridgeAddress, bridgeAddress, payerAddress, message.publicKey, fromAddress, mintAddress, nonce, amount, relayerFee, targetAddress, utils_1.coalesceChainId(targetChain))
                        : payload !== null
                            ? tokenBridge_1.createTransferWrappedWithPayloadInstruction(tokenBridgeAddress, bridgeAddress, payerAddress, message.publicKey, fromAddress, fromOwnerAddress, originChainId, originAddress, nonce, amount, targetAddress, utils_1.coalesceChainId(targetChain), payload)
                            : tokenBridge_1.createTransferWrappedInstruction(tokenBridgeAddress, bridgeAddress, payerAddress, message.publicKey, fromAddress, fromOwnerAddress, originChainId, originAddress, nonce, amount, relayerFee, targetAddress, utils_1.coalesceChainId(targetChain));
                    transaction = new web3_js_1.Transaction().add(approvalIx, tokenBridgeTransferIx);
                    return [4 /*yield*/, connection.getLatestBlockhash(commitment)];
                case 1:
                    blockhash = (_a.sent()).blockhash;
                    transaction.recentBlockhash = blockhash;
                    transaction.feePayer = new web3_js_1.PublicKey(payerAddress);
                    transaction.partialSign(message);
                    return [2 /*return*/, transaction];
            }
        });
    });
}
exports.transferFromSolana = transferFromSolana;
/**
 * Transfers an asset from Algorand to a receiver on another chain
 * @param client AlgodV2 client
 * @param tokenBridgeId Application ID of the token bridge
 * @param bridgeId Application ID of the core bridge
 * @param sender Sending account
 * @param assetId Asset index
 * @param qty Quantity to transfer
 * @param receiver Receiving account
 * @param chain Reeiving chain
 * @param fee Transfer fee
 * @param payload payload for payload3 transfers
 * @returns Sequence number of confirmation
 */
function transferFromAlgorand(client, tokenBridgeId, bridgeId, senderAddr, assetId, qty, receiver, chain, fee, payload) {
    if (payload === void 0) { payload = null; }
    return __awaiter(this, void 0, void 0, function () {
        var recipientChainId, tokenAddr, applAddr, txs, _a, emitterAddr, emitterOptInTxs, creator, creatorAcctInfo, wormhole, assetInfo, authAddr, params, msgFee, payTxn, bNat, result, _b, payTxn, bOptin, txn, t, accounts, t_1, t_2, args, acTxn;
        return __generator(this, function (_c) {
            switch (_c.label) {
                case 0:
                    recipientChainId = utils_1.coalesceChainId(chain);
                    tokenAddr = algosdk_1.getApplicationAddress(tokenBridgeId);
                    applAddr = bridge_1.getEmitterAddressAlgorand(tokenBridgeId);
                    txs = [];
                    return [4 /*yield*/, algorand_1.optin(client, senderAddr, bridgeId, BigInt(0), applAddr)];
                case 1:
                    _a = _c.sent(), emitterAddr = _a.addr, emitterOptInTxs = _a.txs;
                    txs.push.apply(txs, __spreadArray([], __read(emitterOptInTxs)));
                    wormhole = false;
                    if (!(assetId !== BigInt(0))) return [3 /*break*/, 4];
                    return [4 /*yield*/, client
                            .getAssetByID(utils_1.safeBigIntToNumber(assetId))
                            .do()];
                case 2:
                    assetInfo = _c.sent();
                    creator = assetInfo["params"]["creator"];
                    return [4 /*yield*/, client.accountInformation(creator).do()];
                case 3:
                    creatorAcctInfo = _c.sent();
                    authAddr = creatorAcctInfo["auth-addr"];
                    if (authAddr === tokenAddr) {
                        wormhole = true;
                    }
                    _c.label = 4;
                case 4: return [4 /*yield*/, client.getTransactionParams().do()];
                case 5:
                    params = _c.sent();
                    return [4 /*yield*/, algorand_1.getMessageFee(client, bridgeId)];
                case 6:
                    msgFee = _c.sent();
                    if (msgFee > 0) {
                        payTxn = algosdk_1.makePaymentTxnWithSuggestedParamsFromObject({
                            from: senderAddr,
                            suggestedParams: params,
                            to: algosdk_1.getApplicationAddress(tokenBridgeId),
                            amount: msgFee,
                        });
                        txs.push({ tx: payTxn, signer: null });
                    }
                    if (!!wormhole) return [3 /*break*/, 8];
                    bNat = Buffer.from("native", "binary").toString("hex");
                    return [4 /*yield*/, algorand_1.optin(client, senderAddr, tokenBridgeId, assetId, bNat)];
                case 7:
                    result = _c.sent();
                    creator = result.addr;
                    txs.push.apply(txs, __spreadArray([], __read(result.txs)));
                    _c.label = 8;
                case 8:
                    _b = assetId !== BigInt(0);
                    if (!_b) return [3 /*break*/, 10];
                    return [4 /*yield*/, algorand_1.assetOptinCheck(client, assetId, creator)];
                case 9:
                    _b = !(_c.sent());
                    _c.label = 10;
                case 10:
                    if (_b) {
                        payTxn = algosdk_1.makePaymentTxnWithSuggestedParamsFromObject({
                            from: senderAddr,
                            to: creator,
                            amount: 100000,
                            suggestedParams: params,
                        });
                        txs.push({ tx: payTxn, signer: null });
                        bOptin = utils_1.textToUint8Array("optin");
                        txn = algosdk_1.makeApplicationCallTxnFromObject({
                            from: senderAddr,
                            appIndex: utils_1.safeBigIntToNumber(tokenBridgeId),
                            onComplete: algosdk_1.OnApplicationComplete.NoOpOC,
                            appArgs: [bOptin, algosdk_1.bigIntToBytes(assetId, 8)],
                            foreignAssets: [utils_1.safeBigIntToNumber(assetId)],
                            accounts: [creator],
                            suggestedParams: params,
                        });
                        txn.fee *= 2;
                        txs.push({ tx: txn, signer: null });
                    }
                    t = algosdk_1.makeApplicationCallTxnFromObject({
                        from: senderAddr,
                        appIndex: utils_1.safeBigIntToNumber(tokenBridgeId),
                        onComplete: algosdk_1.OnApplicationComplete.NoOpOC,
                        appArgs: [utils_1.textToUint8Array("nop")],
                        suggestedParams: params,
                    });
                    txs.push({ tx: t, signer: null });
                    accounts = [];
                    if (assetId === BigInt(0)) {
                        t_1 = algosdk_1.makePaymentTxnWithSuggestedParamsFromObject({
                            from: senderAddr,
                            to: creator,
                            amount: qty,
                            suggestedParams: params,
                        });
                        txs.push({ tx: t_1, signer: null });
                        accounts = [emitterAddr, creator, creator];
                    }
                    else {
                        t_2 = algosdk_1.makeAssetTransferTxnWithSuggestedParamsFromObject({
                            from: senderAddr,
                            to: creator,
                            suggestedParams: params,
                            amount: qty,
                            assetIndex: utils_1.safeBigIntToNumber(assetId),
                        });
                        txs.push({ tx: t_2, signer: null });
                        accounts = [emitterAddr, creator, creatorAcctInfo["address"]];
                    }
                    args = [
                        utils_1.textToUint8Array("sendTransfer"),
                        algosdk_1.bigIntToBytes(assetId, 8),
                        algosdk_1.bigIntToBytes(qty, 8),
                        utils_1.hexToUint8Array(receiver),
                        algosdk_1.bigIntToBytes(recipientChainId, 8),
                        algosdk_1.bigIntToBytes(fee, 8),
                    ];
                    if (payload !== null) {
                        args.push(payload);
                    }
                    acTxn = algosdk_1.makeApplicationCallTxnFromObject({
                        from: senderAddr,
                        appIndex: utils_1.safeBigIntToNumber(tokenBridgeId),
                        onComplete: algosdk_1.OnApplicationComplete.NoOpOC,
                        appArgs: args,
                        foreignApps: [utils_1.safeBigIntToNumber(bridgeId)],
                        foreignAssets: [utils_1.safeBigIntToNumber(assetId)],
                        accounts: accounts,
                        suggestedParams: params,
                    });
                    acTxn.fee *= 2;
                    txs.push({ tx: acTxn, signer: null });
                    return [2 /*return*/, txs];
            }
        });
    });
}
exports.transferFromAlgorand = transferFromAlgorand;
function transferTokenFromNear(provider, account, coreBridge, tokenBridge, assetId, qty, receiver, chain, fee, payload) {
    if (payload === void 0) { payload = ""; }
    return __awaiter(this, void 0, void 0, function () {
        var isWrapped, messageFee, options, bal, bank;
        return __generator(this, function (_a) {
            switch (_a.label) {
                case 0:
                    isWrapped = __1.getIsWrappedAssetNear(tokenBridge, assetId);
                    return [4 /*yield*/, utils_1.callFunctionNear(provider, coreBridge, "message_fee", {})];
                case 1:
                    messageFee = _a.sent();
                    chain = utils_1.coalesceChainId(chain);
                    if (!isWrapped) return [3 /*break*/, 2];
                    return [2 /*return*/, [
                            {
                                contractId: tokenBridge,
                                methodName: "send_transfer_wormhole_token",
                                args: {
                                    token: assetId,
                                    amount: qty.toString(10),
                                    receiver: utils_1.uint8ArrayToHex(receiver),
                                    chain: chain,
                                    fee: fee.toString(10),
                                    payload: payload,
                                    message_fee: messageFee,
                                },
                                attachedDeposit: new bn_js_1.default(messageFee + 1),
                                gas: new bn_js_1.default("100000000000000"),
                            },
                        ]];
                case 2:
                    options = [];
                    return [4 /*yield*/, utils_1.callFunctionNear(provider, assetId, "storage_balance_of", {
                            account_id: tokenBridge,
                        })];
                case 3:
                    bal = _a.sent();
                    if (bal === null) {
                        // Looks like we have to stake some storage for this asset
                        // for the token bridge...
                        options.push({
                            contractId: assetId,
                            methodName: "storage_deposit",
                            args: { account_id: tokenBridge, registration_only: true },
                            gas: new bn_js_1.default("100000000000000"),
                            attachedDeposit: new bn_js_1.default("2000000000000000000000"), // 0.002 NEAR
                        });
                    }
                    if (!(messageFee > 0)) return [3 /*break*/, 5];
                    return [4 /*yield*/, utils_1.callFunctionNear(provider, tokenBridge, "bank_balance", {
                            acct: account,
                        })];
                case 4:
                    bank = _a.sent();
                    if (!bank[0]) {
                        options.push({
                            contractId: tokenBridge,
                            methodName: "register_bank",
                            args: {},
                            gas: new bn_js_1.default("100000000000000"),
                            attachedDeposit: new bn_js_1.default("2000000000000000000000"), // 0.002 NEAR
                        });
                    }
                    if (bank[1] < messageFee) {
                        options.push({
                            contractId: tokenBridge,
                            methodName: "fill_bank",
                            args: {},
                            gas: new bn_js_1.default("100000000000000"),
                            attachedDeposit: new bn_js_1.default(messageFee),
                        });
                    }
                    _a.label = 5;
                case 5:
                    options.push({
                        contractId: assetId,
                        methodName: "ft_transfer_call",
                        args: {
                            receiver_id: tokenBridge,
                            amount: qty.toString(10),
                            msg: JSON.stringify({
                                receiver: utils_1.uint8ArrayToHex(receiver),
                                chain: chain,
                                fee: fee.toString(10),
                                payload: payload,
                                message_fee: messageFee,
                            }),
                        },
                        attachedDeposit: new bn_js_1.default(1),
                        gas: new bn_js_1.default("100000000000000"),
                    });
                    return [2 /*return*/, options];
            }
        });
    });
}
exports.transferTokenFromNear = transferTokenFromNear;
function transferNearFromNear(provider, coreBridge, tokenBridge, qty, receiver, chain, fee, payload) {
    if (payload === void 0) { payload = ""; }
    return __awaiter(this, void 0, void 0, function () {
        var messageFee;
        return __generator(this, function (_a) {
            switch (_a.label) {
                case 0: return [4 /*yield*/, utils_1.callFunctionNear(provider, coreBridge, "message_fee", {})];
                case 1:
                    messageFee = _a.sent();
                    return [2 /*return*/, {
                            contractId: tokenBridge,
                            methodName: "send_transfer_near",
                            args: {
                                receiver: utils_1.uint8ArrayToHex(receiver),
                                chain: utils_1.coalesceChainId(chain),
                                fee: fee.toString(10),
                                payload: payload,
                                message_fee: messageFee,
                            },
                            attachedDeposit: new bn_js_1.default(qty.toString(10)).add(new bn_js_1.default(messageFee)),
                            gas: new bn_js_1.default("100000000000000"),
                        }];
            }
        });
    });
}
exports.transferNearFromNear = transferNearFromNear;
/**
 * Transfer an asset on Aptos to another chain.
 * @param tokenBridgeAddress Address of token bridge
 * @param fullyQualifiedType Full qualified type of asset to transfer
 * @param amount Amount to send to recipient
 * @param recipientChain Target chain
 * @param recipient Recipient's address on target chain
 * @param relayerFee Fee to pay relayer
 * @param payload Payload3 data, leave undefined for basic token transfers
 * @returns Transaction payload
 */
function transferFromAptos(tokenBridgeAddress, fullyQualifiedType, amount, recipientChain, recipient, relayerFee, payload) {
    if (relayerFee === void 0) { relayerFee = "0"; }
    if (payload === void 0) { payload = ""; }
    if (payload) {
        // Currently unsupported
        return aptos_1.transferTokensWithPayload(tokenBridgeAddress, fullyQualifiedType, amount, recipientChain, recipient, relayerFee, utils_1.createNonce().readUInt32LE(0), payload);
    }
    return aptos_1.transferTokens(tokenBridgeAddress, fullyQualifiedType, amount, recipientChain, recipient, relayerFee, utils_1.createNonce().readUInt32LE(0));
}
exports.transferFromAptos = transferFromAptos;
