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());
    });
};
import { Keypair, PublicKey, Transaction } from "@solana/web3.js";
import { MsgExecuteContract } from "@terra-money/terra.js";
import { bigIntToBytes, decodeAddress, getApplicationAddress, makeApplicationCallTxnFromObject, makePaymentTxnWithSuggestedParamsFromObject, OnApplicationComplete, } from "algosdk";
import { isNativeDenom, stringToByte32Hex } from "..";
import { getMessageFee, optin } from "../algorand";
import { Bridge__factory } from "../ethers-contracts";
import { getBridgeFeeIx, ixFromRust } from "../solana";
import { importTokenWasm } from "../solana/wasm";
import { textToHexString, textToUint8Array, uint8ArrayToHex } from "../utils";
import { safeBigIntToNumber } from "../utils/bigint";
import { createNonce } from "../utils/createNonce";
import { ALPH_TOKEN_ID, DUST_AMOUNT, isHexString } from "@alephium/web3";
import { AttestToken } from "../alephium-contracts/ts/scripts";
function normalizeString(str) {
    if (isHexString(str) && str.length === 64) {
        return str;
    }
    return stringToByte32Hex(str);
}
export 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().toString('hex');
        return 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,
            tokens: localTokenId === ALPH_TOKEN_ID
                ? []
                : [{ id: localTokenId, amount: BigInt(1) }, { id: ALPH_TOKEN_ID, amount: DUST_AMOUNT * BigInt(2) }]
        });
    });
}
export function attestFromEth(tokenBridgeAddress, signer, tokenAddress, overrides = {}) {
    return __awaiter(this, void 0, void 0, function* () {
        const bridge = Bridge__factory.connect(tokenBridgeAddress, signer);
        const v = yield bridge.attestToken(tokenAddress, createNonce(), overrides);
        const receipt = yield v.wait();
        return receipt;
    });
}
export function attestFromTerra(tokenBridgeAddress, walletAddress, asset) {
    return __awaiter(this, void 0, void 0, function* () {
        const nonce = Math.round(Math.random() * 100000);
        const isNativeAsset = isNativeDenom(asset);
        return new MsgExecuteContract(walletAddress, tokenBridgeAddress, {
            create_asset_meta: {
                asset_info: isNativeAsset
                    ? {
                        native_token: { denom: asset },
                    }
                    : {
                        token: {
                            contract_addr: asset,
                        },
                    },
                nonce: nonce,
            },
        });
    });
}
export function attestFromSolana(connection, bridgeAddress, tokenBridgeAddress, payerAddress, mintAddress) {
    return __awaiter(this, void 0, void 0, function* () {
        const nonce = createNonce().readUInt32LE(0);
        const transferIx = yield getBridgeFeeIx(connection, bridgeAddress, payerAddress);
        const { attest_ix } = yield importTokenWasm();
        const messageKey = Keypair.generate();
        const ix = ixFromRust(attest_ix(tokenBridgeAddress, bridgeAddress, payerAddress, messageKey.publicKey.toString(), mintAddress, nonce));
        const transaction = new Transaction().add(transferIx, ix);
        const { blockhash } = yield connection.getRecentBlockhash();
        transaction.recentBlockhash = blockhash;
        transaction.feePayer = new PublicKey(payerAddress);
        transaction.partialSign(messageKey);
        return transaction;
    });
}
/**
 * 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
 */
export function attestFromAlgorand(client, tokenBridgeId, bridgeId, senderAddr, assetId) {
    return __awaiter(this, void 0, void 0, function* () {
        const tbAddr = getApplicationAddress(tokenBridgeId);
        const decTbAddr = decodeAddress(tbAddr).publicKey;
        const aa = uint8ArrayToHex(decTbAddr);
        const txs = [];
        // "attestFromAlgorand::emitterAddr"
        const { addr: emitterAddr, txs: emitterOptInTxs } = yield optin(client, senderAddr, bridgeId, BigInt(0), aa);
        txs.push(...emitterOptInTxs);
        let wormhole = false;
        let creatorAcctInfo = false;
        let creatorAddr = "";
        const bPgmName = textToUint8Array("attestToken");
        if (assetId !== BigInt(0)) {
            const assetInfo = yield client
                .getAssetByID(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 optin(client, senderAddr, tokenBridgeId, assetId, textToHexString("native"));
            creatorAddr = result.addr;
            txs.push(...result.txs);
        }
        const suggParams = yield client.getTransactionParams().do();
        const firstTxn = makeApplicationCallTxnFromObject({
            from: senderAddr,
            appIndex: safeBigIntToNumber(tokenBridgeId),
            onComplete: OnApplicationComplete.NoOpOC,
            appArgs: [textToUint8Array("nop")],
            suggestedParams: suggParams,
        });
        txs.push({ tx: firstTxn, signer: null });
        const mfee = yield getMessageFee(client, bridgeId);
        if (mfee > BigInt(0)) {
            const feeTxn = makePaymentTxnWithSuggestedParamsFromObject({
                from: senderAddr,
                suggestedParams: suggParams,
                to: getApplicationAddress(tokenBridgeId),
                amount: mfee,
            });
            txs.push({ tx: feeTxn, signer: null });
        }
        let accts = [
            emitterAddr,
            creatorAddr,
            getApplicationAddress(bridgeId),
        ];
        if (creatorAcctInfo) {
            accts.push(creatorAcctInfo["address"]);
        }
        let appTxn = makeApplicationCallTxnFromObject({
            appArgs: [bPgmName, bigIntToBytes(assetId, 8)],
            accounts: accts,
            appIndex: safeBigIntToNumber(tokenBridgeId),
            foreignApps: [safeBigIntToNumber(bridgeId)],
            foreignAssets: [safeBigIntToNumber(assetId)],
            from: senderAddr,
            onComplete: OnApplicationComplete.NoOpOC,
            suggestedParams: suggParams,
        });
        if (mfee > BigInt(0)) {
            appTxn.fee *= 3;
        }
        else {
            appTxn.fee *= 2;
        }
        txs.push({ tx: appTxn, signer: null });
        return txs;
    });
}
