Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add typescript typings #7

Closed
beautyfree opened this issue Jul 20, 2021 · 7 comments · Fixed by #32
Closed

Add typescript typings #7

beautyfree opened this issue Jul 20, 2021 · 7 comments · Fixed by #32

Comments

@beautyfree
Copy link

No description provided.

@anasbenyaiche
Copy link

Hello guys, I wanted to ask if there is any TypeScript ?

@beautyfree
Copy link
Author

beautyfree commented Dec 1, 2021

@anasbenyaiche oh, really 😅 then the question should sound like do you plan to rewrite the code to typescript?

@anasbenyaiche
Copy link

it seems to take a while, no problem. Thank you anyway

@Harrish-Selvarajah
Copy link

Harrish-Selvarajah commented Jul 29, 2022

/*
      // @ts-ignore */
      

Added this to bypass the error for now, but the Transak team will have to provide us with the typings.

@ademidun
Copy link

ademidun commented Dec 18, 2022

Here's how I fixed this:

  1. Create a new file: src/@types/transak-sdk.d.ts
  2. Add the Following: [Transak Declaration File]
  3. Add the Following: [Use Transak Declaration File in component]

Transak Declaration File

declare module '@transak/transak-sdk' {
    export enum Foo {
        STAGING = "STAGING",
        PRODUCTION = "PRODUCTION"
    } 
    export interface Settings {
      apiKey: string;
      environment: string; // tried to set this to be ->  environment: 'STAGING' | 'PRODUCTION', but it gave error: 'string is not assignable to type 'STAGING' | 'PRODUCTION''
      defaultCryptoCurrency: string;
      themeColor: string;
      hostURL: string;
      widgetHeight: string;
      widgetWidth: string;
    }
  
    export interface EventData {
      [key: string]: any;
    }
  
    export interface OrderData {
      [key: string]: any;
    }
  
    export default class Transak {
      public readonly ALL_EVENTS = 'ALL_EVENTS';
      public readonly ERROR = 'TRANSAK_ERROR';
      public readonly EVENTS: {
        TRANSAK_ORDER_CANCELLED: "TRANSAK_ORDER_CANCELLED"
        TRANSAK_ORDER_CREATED: "TRANSAK_ORDER_CREATED"
        TRANSAK_ORDER_FAILED: "TRANSAK_ORDER_FAILED"
        TRANSAK_ORDER_SUCCESSFUL: "TRANSAK_ORDER_SUCCESSFUL"
        TRANSAK_WIDGET_CLOSE: "TRANSAK_WIDGET_CLOSE"
        TRANSAK_WIDGET_CLOSE_REQUEST: "TRANSAK_WIDGET_CLOSE_REQUEST"
        TRANSAK_WIDGET_INITIALISED: "TRANSAK_WIDGET_INITIALISED"
        TRANSAK_WIDGET_OPEN: "TRANSAK_WIDGET_OPEN"
      };
  
      constructor(settings: Settings);
  
      public init(): void;
      public on(event: string, callback: (data: EventData) => void): void;
      public close(): void;
    }
}

Use Transak Declaration File in component

import React, { useState } from 'react';
import transakSDK from "@transak/transak-sdk";

const settings = {
    apiKey: '',  // Your API Key
    environment: "STAGING", // STAGING/PRODUCTION
    defaultCryptoCurrency: 'ETH',
    themeColor: '000000', // App theme color
    hostURL: window.location.origin,
    widgetHeight: "700px",
    widgetWidth: "500px",
}


function BuySellCrypto() {


    function openTransak() {
        const transak = new transakSDK(settings);

        transak.init();

        console.log({transakSDK, transak})

        // To get all the events
        transak.on(transak.ALL_EVENTS, (data: any) => {
            console.log(data)
        });

        // This will trigger when the user closed the widget
        transak.on(transak.EVENTS.TRANSAK_WIDGET_CLOSE, (eventData: any) => {
            console.log(eventData);
            transak.close();
        });

        // This will trigger when the user marks payment is made.
        transak.on(transak.EVENTS.TRANSAK_ORDER_SUCCESSFUL, (orderData: any) => {
            console.log(orderData);
            window.alert("Payment Success")
            transak.close();
        });
    }
    return (
        <div className="BuySellCrypto">
            <h3>
                Let mainstream users buy crypto in your app

                Onboard more users to crypto and increase revenue through a simple developer integration.
            </h3>
            <button onClick={() => openTransak()}>
                Buy Crypto
            </button>
        </div>
    );
}

export default BuySellCrypto;

Fun fact, ChatGPT helped me get this answer. Although, I had to make some modifications.

I used the following code snippet and asked ChatGPT to make a declaration file for it:

https://github.com/Transak/Transak-widget-react-sample/blob/c666c6f9461a9551e846eed6d2aabda19300801e/src/App.js#L17-L18

Screen Shot 2022-12-18 at 2 35 38 PM
Screen Shot 2022-12-18 at 2 35 48 PM

Then we can use console.log to see what variables will be in our class.

const transak = new transakSDK(settings);
transak.init();
console.log({transakSDK, transak})

Screen Shot 2022-12-18 at 3 06 19 PM

@VladimirTambovtsev
Copy link

should we add generated ChatGPT typings to npm package @types/transak-sdk?😂

@andr3medeiros
Copy link

Extending @ademidun contribution:

declare module '@transak/transak-sdk' {
	interface Settings {
		apiKey: string;
		environment: 'STAGING' | 'PRODUCTION';
		defaultCryptoCurrency?: string;
		themeColor?: string;
		exchangeScreenTitle?: string;
		hideMenu?: boolean;
		disableWalletAddressForm?: boolean;
		isFeeCalculationHidden?: boolean;
		isDisableCrypto?: boolean;
		hostURL?: string;
		network?: string;
		networks?: string;
		walletAddress?: string;
		widgetHeight?: string;
		widgetWidth?: string;
		cryptoCurrencyCode?: string;
		fiatCurrency?: string;
	}

	type ModalPopupAllEvents = '*';

	type ModalPopupEvents =
		| 'TRANSAK_ORDER_CANCELLED'
		| 'TRANSAK_ORDER_CREATED'
		| 'TRANSAK_ORDER_FAILED'
		| 'TRANSAK_ORDER_SUCCESSFUL'
		| 'TRANSAK_WIDGET_CLOSE'
		| 'TRANSAK_WIDGET_CLOSE_REQUEST'
		| 'TRANSAK_WIDGET_INITIALISED'
		| 'TRANSAK_WIDGET_OPEN';

	type EventName = ModalPopupEvents | ModalPopupAllEvents;

	export default class Transak {
		public readonly ERROR = 'TRANSAK_ERROR';
		public readonly EVENTS: ModalPopupEvents;
		public readonly ALL_EVENTS: ModalPopupAllEvents;

		constructor(settings: Settings);

		public init(): void;
		public on<T extends EventName>(event: T, callback: (data: Event[T]) => void): void;
		public close(): void;
	}

	interface PaymentOptionField {
		name: string;
		value: string;
	}

	interface PaymentOption {
		currency: string;
		id: string;
		name: string;
		fields: PaymentOptionField[];
	}

	interface StatusHistory {
		status: string;
		createdAt: Date;
		message: string;
		isEmailSentToUser: boolean;
		partnerEventId: string;
	}

	interface Event {
		'*': EventData<'*', boolean | OrderDataStatus>;
		TRANSAK_WIDGET_INITIALISED: EventData<'TRANSAK_WIDGET_INITIALISED', boolean>;
		TRANSAK_WIDGET_OPEN: EventData<'TRANSAK_WIDGET_OPEN', boolean>;
		TRANSAK_ORDER_CREATED: EventData<'TRANSAK_ORDER_CREATED', OrderDataStatus>;
		TRANSAK_ORDER_SUCCESSFUL: EventData<'TRANSAK_ORDER_SUCCESSFUL', OrderDataStatus>;
		TRANSAK_ORDER_FAILED: EventData<'TRANSAK_ORDER_FAILED', OrderDataStatus>;
		TRANSAK_ORDER_CANCELLED: EventData<'TRANSAK_ORDER_CANCELLED', OrderDataStatus>;
		TRANSAK_WIDGET_CLOSE: EventData<'TRANSAK_WIDGET_CLOSE', boolean>;
		TRANSAK_WIDGET_CLOSE_REQUEST: EventData<'TRANSAK_WIDGET_CLOSE_REQUEST', boolean>;
	}

	interface Action {
		status: boolean;
	}

	// Couldn't confirm on that
	interface HTTPErrorResponse {
		error: TransakError;
	}

	interface TransakError {
		statusCode: number;
		name: string;
		message: string;
	}

	type EventStatus = 'PAYMENT_DONE_MARKED_BY_USER' | 'AWAITING_PAYMENT_FROM_USER' | 'PAYMENT_DONE_MARKED_BY_USER';

	type EventData<T extends EventName, D extends boolean | OrderDataStatus> = {
		eventName: T;
		status: D;
	};

	interface OrderDataStatus {
		id: string;
		walletAddress: string;
		createdAt: Date;
		status: EventStatus;
		fiatCurrency: string;
		userId: string;
		cryptoCurrency: string;
		isBuyOrSell: string;
		fiatAmount: number;
		amountPaid: number;
		paymentOptionId: string;
		walletLink: string;
		orderProcessingType: string;
		addressAdditionalData: boolean;
		network: string;
		conversionPrice: number;
		cryptoAmount: number;
		totalFeeInFiat: number;
		fiatAmountInUsd: number;
		referenceCode: number;
		paymentOptions: PaymentOption[];
		autoExpiresAt: Date;
		statusHistories: StatusHistory[];
	}
}

@debajitr debajitr linked a pull request Sep 28, 2023 that will close this issue
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging a pull request may close this issue.

7 participants
@beautyfree @andr3medeiros @ademidun @VladimirTambovtsev @Harrish-Selvarajah @anasbenyaiche and others