"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.attestFromAlgorand = exports.attestFromSolana = exports.attestFromTerra = exports.attestFromEth = exports.attestFromAlph = void 0;
const web3_js_1 = require("@solana/web3.js");
const terra_js_1 = require("@terra-money/terra.js");
const algosdk_1 = require("algosdk");
const __1 = require("..");
const algorand_1 = require("../algorand");
const ethers_contracts_1 = require("../ethers-contracts");
const solana_1 = require("../solana");
const wasm_1 = require("../solana/wasm");
const utils_1 = require("../utils");
const bigint_1 = require("../utils/bigint");
const createNonce_1 = require("../utils/createNonce");
const web3_1 = require("@alephium/web3");
const scripts_1 = require("../alephium-contracts/ts/scripts");
function normalizeString(str) {
    if (web3_1.isHexString(str) && str.length === 64) {
        return str;
    }
    return web3_1.binToHex(utils_1.utf8StringTo32Bytes(str));
}
function attestFromAlph(signerProvider, tokenBridgeId, localTokenId, decimals, symbol, name, payer, messageFee, consistencyLevel, nonce) {
    return __awaiter(this, void 0, void 0, function* () {
        const nonceHex = (typeof nonce !== "undefined") ? nonce : createNonce_1.createNonce().toString('hex');
        return scripts_1.AttestToken.execute(signerProvider, {
            initialFields: {
                payer: payer,
                tokenBridge: tokenBridgeId,
                localTokenId: localTokenId,
                decimals: BigInt(decimals),
                symbol: normalizeString(symbol),
                name: normalizeString(name),
                nonce: nonceHex,
                consistencyLevel: BigInt(consistencyLevel)
            },
            attoAlphAmount: messageFee + (localTokenId === web3_1.ALPH_TOKEN_ID ? web3_1.DUST_AMOUNT : web3_1.DUST_AMOUNT * BigInt(2)),
            tokens: [{ id: localTokenId, amount: BigInt(1) }]
        });
    });
}
exports.attestFromAlph = attestFromAlph;
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 = __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 attestFromSolana(connection, bridgeAddress, tokenBridgeAddress, payerAddress, mintAddress) {
    return __awaiter(this, void 0, void 0, function* () {
        const nonce = createNonce_1.createNonce().readUInt32LE(0);
        const transferIx = yield solana_1.getBridgeFeeIx(connection, bridgeAddress, payerAddress);
        const { attest_ix } = yield wasm_1.importTokenWasm();
        const messageKey = web3_js_1.Keypair.generate();
        const ix = solana_1.ixFromRust(attest_ix(tokenBridgeAddress, bridgeAddress, payerAddress, messageKey.publicKey.toString(), mintAddress, nonce));
        const transaction = new web3_js_1.Transaction().add(transferIx, ix);
        const { blockhash } = yield connection.getRecentBlockhash();
        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_1.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 wormhole = false;
        let creatorAcctInfo = false;
        let creatorAddr = "";
        const bPgmName = utils_1.textToUint8Array("attestToken");
        if (assetId !== BigInt(0)) {
            const assetInfo = yield client
                .getAssetByID(bigint_1.safeBigIntToNumber(assetId))
                .do();
            creatorAddr = assetInfo.params.creator;
            creatorAcctInfo = yield client.accountInformation(creatorAddr).do();
            wormhole = creatorAcctInfo["auth-addr"] === tbAddr;
        }
        else {
            wormhole = false;
        }
        if (!wormhole) {
            // "notWormhole"
            const result = yield algorand_1.optin(client, senderAddr, tokenBridgeId, assetId, utils_1.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_1.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;
