"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.WrappedMeta = exports.getWrappedMeta = exports.deriveWrappedMetaKey = exports.deriveWrappedMintKey = void 0;
const web3_js_1 = require("@solana/web3.js");
const connect_sdk_1 = require("@wormhole-foundation/connect-sdk");
const connect_sdk_solana_1 = require("@wormhole-foundation/connect-sdk-solana");
function deriveWrappedMintKey(tokenBridgeProgramId, tokenChain, tokenAddress) {
    if (tokenChain == (0, connect_sdk_1.toChainId)('Solana')) {
        throw new Error('tokenChain == CHAIN_ID_SOLANA does not have wrapped mint key');
    }
    return connect_sdk_solana_1.utils.deriveAddress([
        Buffer.from('wrapped'),
        (() => {
            const buf = Buffer.alloc(2);
            buf.writeUInt16BE(tokenChain);
            return buf;
        })(),
        tokenAddress,
    ], tokenBridgeProgramId);
}
exports.deriveWrappedMintKey = deriveWrappedMintKey;
function deriveWrappedMetaKey(tokenBridgeProgramId, mint) {
    return connect_sdk_solana_1.utils.deriveAddress([Buffer.from('meta'), new web3_js_1.PublicKey(mint).toBuffer()], tokenBridgeProgramId);
}
exports.deriveWrappedMetaKey = deriveWrappedMetaKey;
async function getWrappedMeta(connection, tokenBridgeProgramId, mint, commitment) {
    return connection
        .getAccountInfo(deriveWrappedMetaKey(tokenBridgeProgramId, mint), commitment)
        .then((info) => WrappedMeta.deserialize(connect_sdk_solana_1.utils.getAccountData(info)));
}
exports.getWrappedMeta = getWrappedMeta;
class WrappedMeta {
    chain;
    tokenAddress;
    originalDecimals;
    lastUpdatedSequence;
    constructor(chain, tokenAddress, originalDecimals, lastUpdatedSequence) {
        this.chain = chain;
        this.tokenAddress = tokenAddress;
        this.originalDecimals = originalDecimals;
        this.lastUpdatedSequence = lastUpdatedSequence;
    }
    static deserialize(data) {
        if (data.length !== 35 && data.length !== 43) {
            throw new Error(`invalid wrapped meta length: ${data.length}`);
        }
        const chain = data.readUInt16LE(0);
        const tokenAddress = data.subarray(2, 34);
        const originalDecimals = data.readUInt8(34);
        const lastUpdatedSequence = data.length === 43 ? data.readBigUInt64LE(35) : undefined;
        return new WrappedMeta(chain, tokenAddress, originalDecimals, lastUpdatedSequence);
    }
}
exports.WrappedMeta = WrappedMeta;
//# sourceMappingURL=wrapped.js.map