import { CONFIG, ChainContext, encoding, sha256, toChainId, } from "@wormhole-foundation/connect-sdk";
import { CosmwasmAddress } from "./address";
import { IBC_TRANSFER_PORT } from "./constants";
import { CosmwasmPlatform } from "./platform";
export class Gateway extends ChainContext {
    static chain = "Wormchain";
    static gatewayAddress = (network) => CONFIG[network].chains[Gateway.chain].contracts.gateway;
    static tokenBridgeAddress = (network) => CONFIG[network].chains[Gateway.chain].contracts.tokenBridge;
    static coreAddress = (network) => CONFIG[network].chains[Gateway.chain].contracts.coreBridge;
    // Get the wrapped version of an asset created on wormchain
    // for a given chain
    async getWrappedAsset(token) {
        const tb = await this.getTokenBridge();
        const wrappedAsset = new CosmwasmAddress(await tb.getWrappedAsset(token));
        // Encode the original address to base58 and add it
        // to the factory address for cw20 style factory token address
        const encodedAddress = encoding.b58.encode(wrappedAsset.toUniversalAddress().toUint8Array());
        const factoryAddress = `factory/${Gateway.gatewayAddress(this.network)}/${encodedAddress}`;
        return new CosmwasmAddress(factoryAddress);
    }
    // Gets the the source channel for outgoing transfers from wormchain
    static getGatewaySourceChannel(network, chain) {
        const channels = CosmwasmPlatform.getIbcChannels(network, chain);
        if (!channels)
            throw new Error("No channels configured for chain " + chain);
        if (!(Gateway.chain in channels))
            throw new Error("No channel configured for chain " + chain);
        return channels[Gateway.chain];
    }
    // derive the ics20 token denom from the
    // wrapped denom and destination channel
    static deriveIbcDenom(network, chain, denom) {
        // Otherwise compute the ibc address from the channel and denom
        const channel = this.getGatewaySourceChannel(network, chain);
        const hashData = encoding.bytes.encode(`${IBC_TRANSFER_PORT}/${channel}/${denom}`);
        const hash = encoding.hex.encode(sha256(hashData));
        return new CosmwasmAddress(`ibc/${hash.toUpperCase()}`);
    }
    static makeTransferMsg(chain, recipient, fee = 0n, payload, nonce) {
        // Address of recipient is b64 encoded Cosmos bech32 address
        const address = encoding.b64.encode(recipient.toUint8Array());
        const common = {
            chain: toChainId(chain),
            recipient: address,
            fee: fee.toString(),
            nonce: nonce ?? Math.round(Math.random() * 100000),
        };
        const msg = payload
            ? {
                gateway_transfer_with_payload: { ...common, payload: payload },
            }
            : { gateway_transfer: { ...common } };
        return msg;
    }
}
//# sourceMappingURL=gateway.js.map