"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.transferFromTerra = exports.transferFromSolana = exports.transferFromEth = void 0;
const spl_token_1 = require("@solana/spl-token");
const web3_js_1 = require("@solana/web3.js");
const terra_js_1 = require("@terra-money/terra.js");
const ethers_contracts_1 = require("../ethers-contracts");
const solana_1 = require("../solana");
const wasm_1 = require("../solana/wasm");
const utils_1 = require("../utils");
function transferFromEth(tokenBridgeAddress, signer, tokenAddress, tokenID, recipientChain, recipientAddress, overrides = {}) {
    return __awaiter(this, void 0, void 0, function* () {
        const recipientChainId = utils_1.coalesceChainId(recipientChain);
        //TODO: should we check if token attestation exists on the target chain
        const token = ethers_contracts_1.NFTImplementation__factory.connect(tokenAddress, signer);
        yield (yield token.approve(tokenBridgeAddress, tokenID, overrides)).wait();
        const bridge = ethers_contracts_1.NFTBridge__factory.connect(tokenBridgeAddress, signer);
        const v = yield bridge.transferNFT(tokenAddress, tokenID, recipientChainId, recipientAddress, utils_1.createNonce(), overrides);
        const receipt = yield v.wait();
        return receipt;
    });
}
exports.transferFromEth = transferFromEth;
function transferFromSolana(connection, bridgeAddress, tokenBridgeAddress, payerAddress, fromAddress, mintAddress, targetAddress, targetChain, originAddress, originChain, originTokenId) {
    return __awaiter(this, void 0, void 0, function* () {
        const originChainId = originChain ? utils_1.coalesceChainId(originChain) : undefined;
        const nonce = utils_1.createNonce().readUInt32LE(0);
        const transferIx = yield solana_1.getBridgeFeeIx(connection, bridgeAddress, payerAddress);
        const { transfer_native_ix, transfer_wrapped_ix, approval_authority_address, } = yield wasm_1.importNftWasm();
        const approvalIx = spl_token_1.Token.createApproveInstruction(spl_token_1.TOKEN_PROGRAM_ID, new web3_js_1.PublicKey(fromAddress), new web3_js_1.PublicKey(approval_authority_address(tokenBridgeAddress)), new web3_js_1.PublicKey(payerAddress), [], Number(1));
        let messageKey = web3_js_1.Keypair.generate();
        const isSolanaNative = originChain === undefined || originChain === utils_1.CHAIN_ID_SOLANA;
        if (!isSolanaNative && (!originAddress || !originTokenId)) {
            throw new Error("originAddress and originTokenId are required when specifying originChain");
        }
        const ix = solana_1.ixFromRust(isSolanaNative
            ? transfer_native_ix(tokenBridgeAddress, bridgeAddress, payerAddress, messageKey.publicKey.toString(), fromAddress, mintAddress, nonce, targetAddress, utils_1.coalesceChainId(targetChain))
            : transfer_wrapped_ix(tokenBridgeAddress, bridgeAddress, payerAddress, messageKey.publicKey.toString(), fromAddress, payerAddress, originChainId, // checked by isSolanaNative
            originAddress, // checked by throw
            originTokenId, // checked by throw
            nonce, targetAddress, utils_1.coalesceChainId(targetChain)));
        const transaction = new web3_js_1.Transaction().add(transferIx, approvalIx, ix);
        const { blockhash } = yield connection.getRecentBlockhash();
        transaction.recentBlockhash = blockhash;
        transaction.feePayer = new web3_js_1.PublicKey(payerAddress);
        transaction.partialSign(messageKey);
        return transaction;
    });
}
exports.transferFromSolana = transferFromSolana;
function transferFromTerra(walletAddress, tokenBridgeAddress, tokenAddress, tokenID, recipientChain, recipientAddress) {
    return __awaiter(this, void 0, void 0, function* () {
        const recipientChainId = utils_1.coalesceChainId(recipientChain);
        const nonce = Math.round(Math.random() * 100000);
        return [
            new terra_js_1.MsgExecuteContract(walletAddress, tokenAddress, {
                approve: {
                    spender: tokenBridgeAddress,
                    token_id: tokenID,
                },
            }, {}),
            new terra_js_1.MsgExecuteContract(walletAddress, tokenBridgeAddress, {
                initiate_transfer: {
                    contract_addr: tokenAddress,
                    token_id: tokenID,
                    recipient_chain: recipientChainId,
                    recipient: Buffer.from(recipientAddress).toString("base64"),
                    nonce: nonce,
                },
            }, {}),
        ];
    });
}
exports.transferFromTerra = transferFromTerra;
