"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 __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.attestFromSui = exports.attestFromAptos = exports.attestNearFromNear = exports.attestTokenFromNear = exports.attestFromAlgorand = exports.attestFromSolana = exports.attestFromXpla = exports.attestFromTerra = exports.attestFromEth = void 0;
const sui_js_1 = require("@mysten/sui.js");
const web3_js_1 = require("@solana/web3.js");
const terra_js_1 = require("@terra-money/terra.js");
const xpla_js_1 = require("@xpla/xpla.js");
const algosdk_1 = require("algosdk");
const bn_js_1 = __importDefault(require("bn.js"));
const _1 = require(".");
const algorand_1 = require("../algorand");
const aptos_1 = require("../aptos");
const cosmwasm_1 = require("../cosmwasm");
const ethers_contracts_1 = require("../ethers-contracts");
const solana_1 = require("../solana");
const tokenBridge_1 = require("../solana/tokenBridge");
const utils_1 = require("../sui/utils");
const terra_1 = require("../terra");
const utils_2 = require("../utils");
const bigint_1 = require("../utils/bigint");
const createNonce_1 = require("../utils/createNonce");
function attestFromEth(tokenBridgeAddress, signer, tokenAddress, overrides = {}) {
    return __awaiter(this, void 0, void 0, function* () {
        const bridge = ethers_contracts_1.Bridge__factory.connect(tokenBridgeAddress, signer);
        const v = yield bridge.attestToken(tokenAddress, createNonce_1.createNonce(), overrides);
        const receipt = yield v.wait();
        return receipt;
    });
}
exports.attestFromEth = attestFromEth;
function attestFromTerra(tokenBridgeAddress, walletAddress, asset) {
    return __awaiter(this, void 0, void 0, function* () {
        const nonce = Math.round(Math.random() * 100000);
        const isNativeAsset = terra_1.isNativeDenom(asset);
        return new terra_js_1.MsgExecuteContract(walletAddress, tokenBridgeAddress, {
            create_asset_meta: {
                asset_info: isNativeAsset
                    ? {
                        native_token: { denom: asset },
                    }
                    : {
                        token: {
                            contract_addr: asset,
                        },
                    },
                nonce: nonce,
            },
        });
    });
}
exports.attestFromTerra = attestFromTerra;
function attestFromXpla(tokenBridgeAddress, walletAddress, asset) {
    const nonce = Math.round(Math.random() * 100000);
    const isNativeAsset = cosmwasm_1.isNativeDenomXpla(asset);
    return new xpla_js_1.MsgExecuteContract(walletAddress, tokenBridgeAddress, {
        create_asset_meta: {
            asset_info: isNativeAsset
                ? {
                    native_token: { denom: asset },
                }
                : {
                    token: {
                        contract_addr: asset,
                    },
                },
            nonce: nonce,
        },
    });
}
exports.attestFromXpla = attestFromXpla;
function attestFromSolana(connection, bridgeAddress, tokenBridgeAddress, payerAddress, mintAddress, commitment) {
    return __awaiter(this, void 0, void 0, function* () {
        const nonce = createNonce_1.createNonce().readUInt32LE(0);
        const transferIx = yield solana_1.createBridgeFeeTransferInstruction(connection, bridgeAddress, payerAddress);
        const messageKey = web3_js_1.Keypair.generate();
        const attestIx = tokenBridge_1.createAttestTokenInstruction(tokenBridgeAddress, bridgeAddress, payerAddress, mintAddress, messageKey.publicKey, nonce);
        const transaction = new web3_js_1.Transaction().add(transferIx, attestIx);
        const { blockhash } = yield connection.getLatestBlockhash(commitment);
        transaction.recentBlockhash = blockhash;
        transaction.feePayer = new web3_js_1.PublicKey(payerAddress);
        transaction.partialSign(messageKey);
        return transaction;
    });
}
exports.attestFromSolana = attestFromSolana;
/**
 * Attest an already created asset
 * If you create a new asset on algorand and want to transfer it elsewhere,
 * you create an attestation for it on algorand... pass that vaa to the target chain..
 * submit it.. then you can transfer from algorand to that target chain
 * @param client An Algodv2 client
 * @param tokenBridgeId The ID of the token bridge
 * @param senderAcct The account paying fees
 * @param assetId The asset index
 * @returns Transaction ID
 */
function attestFromAlgorand(client, tokenBridgeId, bridgeId, senderAddr, assetId) {
    return __awaiter(this, void 0, void 0, function* () {
        const tbAddr = algosdk_1.getApplicationAddress(tokenBridgeId);
        const decTbAddr = algosdk_1.decodeAddress(tbAddr).publicKey;
        const aa = utils_2.uint8ArrayToHex(decTbAddr);
        const txs = [];
        // "attestFromAlgorand::emitterAddr"
        const { addr: emitterAddr, txs: emitterOptInTxs } = yield algorand_1.optin(client, senderAddr, bridgeId, BigInt(0), aa);
        txs.push(...emitterOptInTxs);
        let creatorAddr = "";
        let creatorAcctInfo;
        const bPgmName = utils_2.textToUint8Array("attestToken");
        if (assetId !== BigInt(0)) {
            const assetInfo = yield client
                .getAssetByID(bigint_1.safeBigIntToNumber(assetId))
                .do();
            creatorAcctInfo = yield client
                .accountInformation(assetInfo.params.creator)
                .do();
            if (creatorAcctInfo["auth-addr"] === tbAddr) {
                throw new Error("Cannot re-attest wormhole assets");
            }
        }
        const result = yield algorand_1.optin(client, senderAddr, tokenBridgeId, assetId, utils_2.textToHexString("native"));
        creatorAddr = result.addr;
        txs.push(...result.txs);
        const suggParams = yield client.getTransactionParams().do();
        const firstTxn = algosdk_1.makeApplicationCallTxnFromObject({
            from: senderAddr,
            appIndex: bigint_1.safeBigIntToNumber(tokenBridgeId),
            onComplete: algosdk_1.OnApplicationComplete.NoOpOC,
            appArgs: [utils_2.textToUint8Array("nop")],
            suggestedParams: suggParams,
        });
        txs.push({ tx: firstTxn, signer: null });
        const mfee = yield algorand_1.getMessageFee(client, bridgeId);
        if (mfee > BigInt(0)) {
            const feeTxn = algosdk_1.makePaymentTxnWithSuggestedParamsFromObject({
                from: senderAddr,
                suggestedParams: suggParams,
                to: algosdk_1.getApplicationAddress(tokenBridgeId),
                amount: mfee,
            });
            txs.push({ tx: feeTxn, signer: null });
        }
        let accts = [
            emitterAddr,
            creatorAddr,
            algosdk_1.getApplicationAddress(bridgeId),
        ];
        if (creatorAcctInfo) {
            accts.push(creatorAcctInfo["address"]);
        }
        let appTxn = algosdk_1.makeApplicationCallTxnFromObject({
            appArgs: [bPgmName, algosdk_1.bigIntToBytes(assetId, 8)],
            accounts: accts,
            appIndex: bigint_1.safeBigIntToNumber(tokenBridgeId),
            foreignApps: [bigint_1.safeBigIntToNumber(bridgeId)],
            foreignAssets: [bigint_1.safeBigIntToNumber(assetId)],
            from: senderAddr,
            onComplete: algosdk_1.OnApplicationComplete.NoOpOC,
            suggestedParams: suggParams,
        });
        if (mfee > BigInt(0)) {
            appTxn.fee *= 3;
        }
        else {
            appTxn.fee *= 2;
        }
        txs.push({ tx: appTxn, signer: null });
        return txs;
    });
}
exports.attestFromAlgorand = attestFromAlgorand;
function attestTokenFromNear(provider, coreBridge, tokenBridge, asset) {
    return __awaiter(this, void 0, void 0, function* () {
        const options = [];
        const messageFee = yield utils_2.callFunctionNear(provider, coreBridge, "message_fee");
        if (!_1.getIsWrappedAssetNear(tokenBridge, asset)) {
            const { isRegistered } = yield utils_2.hashAccount(provider, tokenBridge, asset);
            if (!isRegistered) {
                // The account has not been registered. The first user to attest a non-wormhole token pays for the space
                options.push({
                    contractId: tokenBridge,
                    methodName: "register_account",
                    args: { account: asset },
                    gas: new bn_js_1.default("100000000000000"),
                    attachedDeposit: new bn_js_1.default("2000000000000000000000"), // 0.002 NEAR
                });
            }
        }
        options.push({
            contractId: tokenBridge,
            methodName: "attest_token",
            args: { token: asset, message_fee: messageFee },
            attachedDeposit: new bn_js_1.default("3000000000000000000000").add(new bn_js_1.default(messageFee)),
            gas: new bn_js_1.default("100000000000000"),
        });
        return options;
    });
}
exports.attestTokenFromNear = attestTokenFromNear;
function attestNearFromNear(provider, coreBridge, tokenBridge) {
    return __awaiter(this, void 0, void 0, function* () {
        const messageFee = (yield utils_2.callFunctionNear(provider, coreBridge, "message_fee")) + 1;
        return {
            contractId: tokenBridge,
            methodName: "attest_near",
            args: { message_fee: messageFee },
            attachedDeposit: new bn_js_1.default(messageFee),
            gas: new bn_js_1.default("100000000000000"),
        };
    });
}
exports.attestNearFromNear = attestNearFromNear;
/**
 * Attest given token from Aptos.
 * @param tokenBridgeAddress Address of token bridge
 * @param tokenChain Origin chain ID
 * @param tokenAddress Address of token on origin chain
 * @returns Transaction payload
 */
function attestFromAptos(tokenBridgeAddress, tokenChain, tokenAddress) {
    return aptos_1.attestToken(tokenBridgeAddress, tokenChain, tokenAddress);
}
exports.attestFromAptos = attestFromAptos;
function attestFromSui(provider, coreBridgeStateObjectId, tokenBridgeStateObjectId, coinType, feeAmount = BigInt(0)) {
    return __awaiter(this, void 0, void 0, function* () {
        const metadata = yield provider.getCoinMetadata({ coinType });
        if (metadata === null || metadata.id === null) {
            throw new Error(`Coin metadata ID for type ${coinType} not found`);
        }
        const [coreBridgePackageId, tokenBridgePackageId] = yield Promise.all([
            utils_1.getPackageId(provider, coreBridgeStateObjectId),
            utils_1.getPackageId(provider, tokenBridgeStateObjectId),
        ]);
        const tx = new sui_js_1.TransactionBlock();
        const [feeCoin] = tx.splitCoins(tx.gas, [tx.pure(feeAmount)]);
        const [messageTicket] = tx.moveCall({
            target: `${tokenBridgePackageId}::attest_token::attest_token`,
            arguments: [
                tx.object(tokenBridgeStateObjectId),
                tx.object(metadata.id),
                tx.pure(createNonce_1.createNonce().readUInt32LE()),
            ],
            typeArguments: [coinType],
        });
        tx.moveCall({
            target: `${coreBridgePackageId}::publish_message::publish_message`,
            arguments: [
                tx.object(coreBridgeStateObjectId),
                feeCoin,
                messageTicket,
                tx.object(sui_js_1.SUI_CLOCK_OBJECT_ID),
            ],
        });
        return tx;
    });
}
exports.attestFromSui = attestFromSui;
