Skip to content

Instantly share code, notes, and snippets.

@vibern0
Created August 8, 2024 11:01
Show Gist options
  • Save vibern0/c83f266ea43f447f6c9dde3733b79ff1 to your computer and use it in GitHub Desktop.
Save vibern0/c83f266ea43f447f6c9dde3733b79ff1 to your computer and use it in GitHub Desktop.

Revisions

  1. vibern0 created this gist Aug 8, 2024.
    55 changes: 55 additions & 0 deletions cow_get_quote.ts
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,55 @@
    export const getQuote = async (
    address: Address,
    amount: number,
    fromAssetTypeId: AssetTypeIdentifier,
    toAssetTypeId: AssetTypeIdentifier
    ) => {
    if (!amount) {
    throw new Error('Amount must be defined and bigger than 0');
    }

    if (fromAssetTypeId === toAssetTypeId) {
    throw new Error('You can not swap to the same token');
    }

    const fromAssetType = ASSET_TYPES_ENTITIES[fromAssetTypeId];

    if (!fromAssetType.swap) {
    throw new Error('Unsupported from token');
    }

    const toAssetType = ASSET_TYPES_ENTITIES[toAssetTypeId];

    if (!toAssetType.swap) {
    throw new Error('Unsupported to token');
    }

    const sellToken = fromAssetType.contractAddress
    ? fromAssetType.contractAddress
    : fromAssetType.include
    ? ASSET_TYPES_ENTITIES[fromAssetType.include].contractAddress
    : undefined;

    if (!sellToken) {
    throw new Error('Undefined sell token');
    }

    const buyToken = toAssetType.contractAddress
    ? toAssetType.contractAddress
    : toAssetType.include
    ? ASSET_TYPES_ENTITIES[toAssetType.include].contractAddress
    : undefined;

    if (!buyToken) {
    throw new Error('Undefined buy token');
    }

    return await orderBookApi.getQuote({
    sellToken,
    buyToken,
    from: address,
    receiver: address,
    sellAmountBeforeFee: (amount * 10 ** 18).toString(), // 0.4 WETH
    kind: OrderQuoteSideKindSell.SELL
    });
    };