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 { fromB64, normalizeSuiAddress, normalizeSuiObjectId, TransactionBlock, } from "@mysten/sui.js";
export const publishCoin = (coreBridgePackageId, tokenBridgePackageId, vaa, signerAddress) => __awaiter(void 0, void 0, void 0, function* () {
    const build = getCoinBuildOutput(coreBridgePackageId, tokenBridgePackageId, vaa);
    return publishPackage(build, signerAddress);
});
export const getCoinBuildOutput = (coreBridgePackageId, tokenBridgePackageId, vaa) => {
    const bytecode = "oRzrCwYAAAAKAQAIAggOAxYWBCwEBTAoB1iGAQjeAWAGvgLlAQqjBAUMqAQWAAMBCgELAgQAAAIAAgECAAMCDAEAAQAGAAEAAQgIAQEMAgkFBgADBwMEAQIDAgEHAggABwgBAAEIAAMJAAoCBwgBAQsCAQkAAQYIAQEFAQsCAQgAAgkABQRDT0lOCVR4Q29udGV4dBFXcmFwcGVkQXNzZXRTZXR1cARjb2luDmNyZWF0ZV93cmFwcGVkC2R1bW15X2ZpZWxkBGluaXQUcHJlcGFyZV9yZWdpc3RyYXRpb24PcHVibGljX3RyYW5zZmVyBnNlbmRlcgh0cmFuc2Zlcgp0eF9jb250ZXh0AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAjVFfai/LOUUAUvqTWa3Rh8p5xhe/wYJfCRRBlwG9pGyCgLhAd8B" +
        Buffer.from(vaa, "hex").toString("base64").replace(/\=+$/, "") +
        "ACAQUBAAAAAAEJCwAHAAoBOAALAS4RAjgBAgA=";
    return {
        modules: [bytecode],
        dependencies: [
            normalizeSuiAddress("0x1"),
            normalizeSuiAddress("0x2"),
            tokenBridgePackageId,
            coreBridgePackageId,
        ],
    };
};
export const publishPackage = (buildOutput, signerAddress) => __awaiter(void 0, void 0, void 0, function* () {
    // Publish contracts
    const tx = new TransactionBlock();
    const [upgradeCap] = tx.publish({
        modules: buildOutput.modules.map((m) => Array.from(fromB64(m))),
        dependencies: buildOutput.dependencies.map((d) => normalizeSuiObjectId(d)),
    });
    // Transfer upgrade capability to recipient
    tx.transferObjects([upgradeCap], tx.pure(signerAddress));
    return tx;
});
