diff --git a/package-lock.json b/package-lock.json index 031c3b18..ee9d77fb 100644 --- a/package-lock.json +++ b/package-lock.json @@ -38610,9 +38610,8 @@ "version": "1.3.0-beta.258", "license": "MIT", "dependencies": { - "ibantools": "^4.2.1", + "@dfx.swiss/core": "^0.1.1-beta.1", "jwt-decode": "^3.1.2", - "libphonenumber-js": "^1.10.39", "react": "^18.2.0", "typescript": "^4.9.3" } @@ -40545,9 +40544,8 @@ "@dfx.swiss/react": { "version": "file:packages/react", "requires": { - "ibantools": "^4.2.1", + "@dfx.swiss/core": "^0.1.1-beta.1", "jwt-decode": "^3.1.2", - "libphonenumber-js": "^1.10.39", "react": "^18.2.0", "typescript": "^4.9.3" }, diff --git a/packages/core/src/utils.ts b/packages/core/src/utils.ts index be5c8a13..2e337620 100644 --- a/packages/core/src/utils.ts +++ b/packages/core/src/utils.ts @@ -1,3 +1,5 @@ +import * as IbanTools from 'ibantools'; + type KeyType = { [K in keyof T]: T[K] extends U ? K : never; }[keyof T]; @@ -10,6 +12,19 @@ export class Utils { ); } + static createRules(rules: any): any { + for (const property in rules) { + if (rules[property] instanceof Array) { + rules[property] = rules[property].reduce((prev: any, curr: any) => Utils.updateObject(prev, curr), {}); + } + } + return rules; + } + + private static updateObject(obj?: any, update?: any): unknown { + return obj ? { ...obj, ...update } : undefined; + } + static formatAmount(amount?: number, decimals = 2): string { return amount?.toFixed(decimals).replace(/\B(?=(\d{3})+(?!\d))/g, ' ') ?? ''; } @@ -22,6 +37,10 @@ export class Utils { return r; } + static formatIban(iban?: string): string | null { + return IbanTools.friendlyFormatIBAN(iban); + } + static isJwt(jwt?: string): boolean { return jwt ? /^[A-Za-z0-9_-]{2,}(?:\.[A-Za-z0-9_-]{2,}){2}$/.test(jwt) : false; } @@ -32,4 +51,13 @@ export class Utils { .map((key) => `${key}=${encodeURIComponent(params[key] as string)}`) .join('&'); } + + static toBase64(file: File): Promise { + return new Promise((resolve, reject) => { + const reader = new FileReader(); + reader.readAsDataURL(file); + reader.onload = () => resolve(reader.result ? (reader.result as string) : undefined); + reader.onerror = (e) => reject(e); + }); + } } diff --git a/packages/react/package.json b/packages/react/package.json index 507eb5b5..a3e93194 100644 --- a/packages/react/package.json +++ b/packages/react/package.json @@ -21,9 +21,8 @@ "pack": "npm pack" }, "dependencies": { - "ibantools": "^4.2.1", + "@dfx.swiss/core": "^0.1.1-beta.1", "jwt-decode": "^3.1.2", - "libphonenumber-js": "^1.10.39", "react": "^18.2.0", "typescript": "^4.9.3" } diff --git a/packages/react/src/definitions/asset.ts b/packages/react/src/definitions/asset.ts index 8ac5d173..7b9f8519 100644 --- a/packages/react/src/definitions/asset.ts +++ b/packages/react/src/definitions/asset.ts @@ -1,36 +1,2 @@ -import { Blockchain } from './blockchain'; - -export const AssetUrl = { get: 'asset' }; - -export enum AssetType { - COIN = 'Coin', - TOKEN = 'Token', -} - -export enum AssetCategory { - PUBLIC = 'Public', - PRIVATE = 'Private', -} - -export interface Asset { - id: number; - name: string; - uniqueName: string; - description: string; - - buyable: boolean; - sellable: boolean; - cardBuyable: boolean; - cardSellable: boolean; - instantBuyable: boolean; - instantSellable: boolean; - - blockchain: Blockchain; - comingSoon: boolean; - sortOrder?: number; - chainId?: string; - decimals?: number; - explorerUrl?: string; - type: AssetType; - category: AssetCategory; -} +export { AssetUrl, AssetType, AssetCategory } from '@dfx.swiss/core'; +export type { Asset } from '@dfx.swiss/core'; diff --git a/packages/react/src/definitions/auth.ts b/packages/react/src/definitions/auth.ts index c4f71b20..9af285eb 100644 --- a/packages/react/src/definitions/auth.ts +++ b/packages/react/src/definitions/auth.ts @@ -1,45 +1,2 @@ -export const AuthUrl = { - signMessage: 'auth/signMessage', - auth: 'auth', - signIn: 'auth/signIn', - signUp: 'auth/signUp', - signInWithMail: 'auth/mail', - lnurl: 'lnurla', - lnurlStatus: 'lnurla/status', -}; - -export interface SignMessage { - message: string; -} - -export interface SignIn { - accessToken: string; -} - -export interface LnurlAuth { - k1: string; - lnurl: string; -} - -export type LnurlAuthStatus = - | { - isComplete: true; - accessToken: string; - } - | { isComplete: false }; - -export enum AuthWalletType { - METAMASK = 'MetaMask', - RABBY = 'Rabby', - WALLET_BROWSER = 'WalletBrowser', - TRUST = 'Trust', - PHANTOM = 'Phantom', - TRON_LINK = 'TronLink', - CLI = 'CLI', - LEDGER = 'Ledger', - BIT_BOX = 'BitBox', - TREZOR = 'Trezor', - ALBY = 'Alby', - WALLET_CONNECT = 'WalletConnect', - DFX_TARO = 'DfxTaro', -} +export { AuthUrl, AuthWalletType } from '@dfx.swiss/core'; +export type { SignMessage, SignIn, LnurlAuth, LnurlAuthStatus } from '@dfx.swiss/core'; diff --git a/packages/react/src/definitions/bank-account.ts b/packages/react/src/definitions/bank-account.ts index 19554a8f..d91d9c1f 100644 --- a/packages/react/src/definitions/bank-account.ts +++ b/packages/react/src/definitions/bank-account.ts @@ -1,16 +1,2 @@ -import { Fiat } from './fiat'; - -export const BankAccountUrl = { - get: 'bankAccount', - create: 'bankAccount', - update: (id: number) => `bankAccount/${id}`, -}; - -export interface BankAccount { - id: number; - iban: string; - active: boolean; - default: boolean; - label?: string; - preferredCurrency?: Fiat; -} +export { BankAccountUrl } from '@dfx.swiss/core'; +export type { BankAccount } from '@dfx.swiss/core'; diff --git a/packages/react/src/definitions/bank.ts b/packages/react/src/definitions/bank.ts index 7ec9778e..ad9370ec 100644 --- a/packages/react/src/definitions/bank.ts +++ b/packages/react/src/definitions/bank.ts @@ -1,10 +1,2 @@ -export const BankUrl = { - get: 'bank', -}; - -export interface Bank { - name: string; - iban: string; - bic: string; - currency: string; -} +export { BankUrl } from '@dfx.swiss/core'; +export type { Bank } from '@dfx.swiss/core'; diff --git a/packages/react/src/definitions/blockchain.ts b/packages/react/src/definitions/blockchain.ts index a7008019..7497661b 100644 --- a/packages/react/src/definitions/blockchain.ts +++ b/packages/react/src/definitions/blockchain.ts @@ -1,29 +1 @@ -export enum Blockchain { - BITCOIN = 'Bitcoin', - LIGHTNING = 'Lightning', - SPARK = 'Spark', - ARK = 'Ark', - FIRO = 'Firo', - MONERO = 'Monero', - ZANO = 'Zano', - INTERNET_COMPUTER = 'InternetComputer', - ETHEREUM = 'Ethereum', - SEPOLIA = 'Sepolia', - BINANCE_SMART_CHAIN = 'BinanceSmartChain', - OPTIMISM = 'Optimism', - ARBITRUM = 'Arbitrum', - POLYGON = 'Polygon', - BASE = 'Base', - GNOSIS = 'Gnosis', - HAQQ = 'Haqq', - LIQUID = 'Liquid', - ARWEAVE = 'Arweave', - CARDANO = 'Cardano', - RAILGUN = 'Railgun', - SOLANA = 'Solana', - TRON = 'Tron', - CITREA = 'Citrea', - CITREA_TESTNET = 'CitreaTestnet', - - DEFICHAIN = 'DeFiChain', -} +export { Blockchain } from '@dfx.swiss/core'; diff --git a/packages/react/src/definitions/blocked-iban.json b/packages/react/src/definitions/blocked-iban.json deleted file mode 100644 index 369516b4..00000000 --- a/packages/react/src/definitions/blocked-iban.json +++ /dev/null @@ -1 +0,0 @@ -["LT..37800000", "AT..14200200", "AT..20602099", "LT..60378000", "CH8008635008770000647"] diff --git a/packages/react/src/definitions/buy.ts b/packages/react/src/definitions/buy.ts index a710c35e..cfb9d0ae 100644 --- a/packages/react/src/definitions/buy.ts +++ b/packages/react/src/definitions/buy.ts @@ -1,61 +1,2 @@ -import { Asset } from './asset'; -import { Fees } from './fees'; -import { Fiat } from './fiat'; -import { PriceStep } from './price-step'; -import { FiatPaymentMethod, TransactionError } from './transaction'; - -export const BuyUrl = { - receive: 'buy/paymentInfos', - invoice: (txId: number) => `buy/paymentInfos/${txId}/invoice`, - confirm: (txId: number) => `buy/paymentInfos/${txId}/confirm`, -}; - -export interface Buy { - id: number; - uid: string; - timestamp: Date; - name: string; - street: string; - number: string; - zip: string; - city: string; - country: string; - iban?: string; - bic: string; - sepaInstant: boolean; - routeId: number; - remittanceInfo?: string; - fees: Fees; - minVolume: number; - maxVolume: number; - amount: number; - currency: Fiat; - feesTarget: Fees; - minVolumeTarget: number; - maxVolumeTarget: number; - exchangeRate: number; - priceSteps: PriceStep[]; - rate: number; - exactPrice: boolean; - estimatedAmount: number; - asset: Asset; - paymentRequest?: string; - paymentLink?: string; - isValid: boolean; - error?: TransactionError; - isPersonalIban?: boolean; -} - -export interface BuyPaymentInfo { - currency: Fiat; - amount?: number; - asset: Asset; - targetAmount?: number; - paymentMethod?: FiatPaymentMethod; - externalTransactionId?: string; - exactPrice?: boolean; -} - -export interface PdfDocument { - pdfData: string; -} +export { BuyUrl } from '@dfx.swiss/core'; +export type { Buy, BuyPaymentInfo, PdfDocument } from '@dfx.swiss/core'; diff --git a/packages/react/src/definitions/country.ts b/packages/react/src/definitions/country.ts index 36c5d831..fa144960 100644 --- a/packages/react/src/definitions/country.ts +++ b/packages/react/src/definitions/country.ts @@ -1,14 +1,2 @@ -export const CountryUrl = { get: 'country' }; - -export interface Country { - id: number; - symbol: string; - name: string; - locationAllowed: boolean; - kycAllowed: boolean; - nationalityAllowed: boolean; - bankAllowed: boolean; - cardAllowed: boolean; - cryptoAllowed: boolean; - kycOrganizationAllowed: boolean; -} +export { CountryUrl } from '@dfx.swiss/core'; +export type { Country } from '@dfx.swiss/core'; diff --git a/packages/react/src/definitions/error.ts b/packages/react/src/definitions/error.ts index 6ccbd4d8..cb9205e2 100644 --- a/packages/react/src/definitions/error.ts +++ b/packages/react/src/definitions/error.ts @@ -1,19 +1,2 @@ -export interface ApiError { - /** - * HTTP status code from the API response. - * A value of 0 indicates a network-level error (e.g., server unreachable, CORS, timeout). - */ - statusCode: number; - message: string; -} - -export class ApiException extends Error implements ApiError { - constructor( - public readonly statusCode: number, - message: string, - ) { - super(message); - this.name = 'ApiException'; - Object.setPrototypeOf(this, ApiException.prototype); - } -} +export { ApiException } from '@dfx.swiss/core'; +export type { ApiError } from '@dfx.swiss/core'; diff --git a/packages/react/src/definitions/fees.ts b/packages/react/src/definitions/fees.ts index 7ec492d8..3a9be4a2 100644 --- a/packages/react/src/definitions/fees.ts +++ b/packages/react/src/definitions/fees.ts @@ -1,13 +1 @@ -export interface Fees { - rate: number; - fixed: number; - min: number; - dfx: number; - bank: number; - bankFixed?: number; - bankPercent?: number; - network: number; - total: number; - networkStart?: number; - platform: number; -} +export type { Fees } from '@dfx.swiss/core'; diff --git a/packages/react/src/definitions/fiat.ts b/packages/react/src/definitions/fiat.ts index 3929119e..383ad97c 100644 --- a/packages/react/src/definitions/fiat.ts +++ b/packages/react/src/definitions/fiat.ts @@ -1,12 +1,2 @@ -export const FiatUrl = { get: 'fiat' }; - -export interface Fiat { - id: number; - name: string; - buyable: boolean; - sellable: boolean; - cardBuyable: boolean; - cardSellable: boolean; - instantBuyable: boolean; - instantSellable: boolean; -} +export { FiatUrl } from '@dfx.swiss/core'; +export type { Fiat } from '@dfx.swiss/core'; diff --git a/packages/react/src/definitions/file.ts b/packages/react/src/definitions/file.ts index 8e27bc48..3ce8200f 100644 --- a/packages/react/src/definitions/file.ts +++ b/packages/react/src/definitions/file.ts @@ -1,4 +1 @@ -export interface CustomFile { - data: Blob; - headers: Record; -} +export type { CustomFile } from '@dfx.swiss/core'; diff --git a/packages/react/src/definitions/jwt.ts b/packages/react/src/definitions/jwt.ts index cc37b2f2..2fd415aa 100644 --- a/packages/react/src/definitions/jwt.ts +++ b/packages/react/src/definitions/jwt.ts @@ -1,24 +1,2 @@ -import { Blockchain } from './blockchain'; - -export enum UserRole { - ACCOUNT = 'Account', - USER = 'User', - VIP = 'VIP', - BETA = 'Beta', - ADMIN = 'Admin', - SUPPORT = 'Support', - COMPLIANCE = 'Compliance', - KYC_CLIENT_COMPANY = 'KycClientCompany', - CUSTODY = 'Custody', - REALUNIT = 'RealUnit', -} - -export interface Jwt { - exp: number; - iat: number; - address: string; - user: number; - account: number; - role: UserRole; - blockchains: Blockchain[]; -} +export { UserRole } from '@dfx.swiss/core'; +export type { Jwt } from '@dfx.swiss/core'; diff --git a/packages/react/src/definitions/kyc.ts b/packages/react/src/definitions/kyc.ts index 9e60ba3d..a35e0c77 100644 --- a/packages/react/src/definitions/kyc.ts +++ b/packages/react/src/definitions/kyc.ts @@ -1,499 +1,67 @@ -import { Country } from './country'; -import { Language } from './language'; - -export const KycUrl = { - setName: 'user/name', - setData: 'user/data', - file: 'kyc/file', - base: `${process.env.REACT_APP_API_URL}/v2/kyc`, - tfa: `${process.env.REACT_APP_API_URL}/v2/kyc/2fa`, - checkTfa: 'kyc/2fa', - limit: `${process.env.REACT_APP_API_URL}/v2/kyc/limit`, - transfer: (client: string) => `${process.env.REACT_APP_API_URL}/v2/kyc/transfer?client=${encodeURIComponent(client)}`, -}; -export const KycLevel = { - Link: 10, - Sell: 20, - Completed: 50, -}; - -export enum AccountType { - PERSONAL = 'Personal', - ORGANIZATION = 'Organization', - SOLE_PROPRIETORSHIP = 'SoleProprietorship', -} - -export enum LegalEntity { - AG = 'AG', - GMBH = 'GmbH', - UG = 'UG', - GBR = 'GbR', - ASSOCIATION = 'Association', - FOUNDATION = 'Foundation', - LIFE_INSURANCE = 'LifeInsurance', - TRUST = 'Trust', - OTHER = 'Other', -} - -export enum SignatoryPower { - SINGLE = 'Single', - DOUBLE = 'Double', - NONE = 'None', -} - -// --- LEGACY --- // - -export enum KycStatus { - NA = 'NA', - CHATBOT = 'Chatbot', - ONLINE_ID = 'OnlineId', - VIDEO_ID = 'VideoId', - CHECK = 'Check', - COMPLETED = 'Completed', - REJECTED = 'Rejected', -} - -export enum KycState { - NA = 'NA', - FAILED = 'Failed', - REMINDED = 'Reminded', - REVIEW = 'Review', -} - -export interface UserName { - firstName: string; - lastName: string; -} - -export type UserData = KycContactData & KycPersonalData; - -// --- NEW --- // - -// info -export enum LimitPeriod { - DAY = 'Day', - MONTH = 'Month', - YEAR = 'Year', -} - -export interface TradingLimit { - limit: number; - period: LimitPeriod; -} - -export interface KycInfo { - kycLevel: number; - tradingLimit: TradingLimit; - language: Language; - kycSteps: KycStep[]; - kycClients: string[]; -} - -export interface KycSession extends KycInfo { - currentStep?: KycStepSession; -} - -// steps -export enum KycStepName { - // standard KYC - CONTACT_DATA = 'ContactData', - PERSONAL_DATA = 'PersonalData', - LEGAL_ENTITY = 'LegalEntity', - OWNER_DIRECTORY = 'OwnerDirectory', - NATIONALITY_DATA = 'NationalityData', - RECOMMENDATION = 'Recommendation', - COMMERCIAL_REGISTER = 'CommercialRegister', - SOLE_PROPRIETORSHIP_CONFIRMATION = 'SoleProprietorshipConfirmation', - SIGNATORY_POWER = 'SignatoryPower', - AUTHORITY = 'Authority', - BENEFICIAL_OWNER = 'BeneficialOwner', - OPERATIONAL_ACTIVITY = 'OperationalActivity', - IDENT = 'Ident', - FINANCIAL_DATA = 'FinancialData', - ADDITIONAL_DOCUMENTS = 'AdditionalDocuments', - RESIDENCE_PERMIT = 'ResidencePermit', - STATUTES = 'Statutes', - DFX_APPROVAL = 'DfxApproval', - - // additional features - PAYMENT_AGREEMENT = 'PaymentAgreement', - RECALL_AGREEMENT = 'RecallAgreement', - - // profile changes - PHONE_CHANGE = 'PhoneChange', - ADDRESS_CHANGE = 'AddressChange', - NAME_CHANGE = 'NameChange', -} - -export enum KycStepType { - // ident - AUTO = 'Auto', - VIDEO = 'Video', - MANUAL = 'Manual', - SUMSUB_AUTO = 'SumsubAuto', - SUMSUB_VIDEO = 'SumsubVideo', -} - -export enum KycStepStatus { - NOT_STARTED = 'NotStarted', - IN_PROGRESS = 'InProgress', - IN_REVIEW = 'InReview', - FAILED = 'Failed', - COMPLETED = 'Completed', - OUTDATED = 'Outdated', - DATA_REQUESTED = 'DataRequested', - ON_HOLD = 'OnHold', -} - -export enum UrlType { - BROWSER = 'Browser', - API = 'API', - TOKEN = 'Token', - NONE = 'None', -} - -export enum KycStepReason { - ACCOUNT_EXISTS = 'AccountExists', - ACCOUNT_MERGE_REQUESTED = 'AccountMergeRequested', -} - -export enum FileType { - NAME_CHECK = 'NameCheck', - USER_INFORMATION = 'UserInformation', - IDENTIFICATION = 'Identification', - USER_NOTES = 'UserNotes', - TRANSACTION_NOTES = 'TransactionNotes', - STOCK_REGISTER = 'StockRegister', - COMMERCIAL_REGISTER = 'CommercialRegister', - RESIDENCE_PERMIT = 'ResidencePermit', - ADDITIONAL_DOCUMENTS = 'AdditionalDocuments', - AUTHORITY = 'Authority', - ADDRESS_CHANGE = 'AddressChange', - NAME_CHANGE = 'NameChange', -} - -export interface KycAdditionalInfo { - accountHolder?: string; -} - -export interface KycSessionInfo { - url: string; - type: UrlType; - additionalInfo?: KycAdditionalInfo; -} - -export interface KycStepBase { - name: KycStepName; - type?: KycStepType; - status: KycStepStatus; - reason?: KycStepReason; - sequenceNumber: number; -} - -export interface KycStep extends KycStepBase { - isCurrent: boolean; -} - -export interface KycStepSession extends KycStepBase { - session?: KycSessionInfo; -} - -// personal data -export interface KycContactData { - mail: string; -} - -export interface KycAddress { - street: string; - houseNumber?: string; - city: string; - zip: string; - country: Country; -} - -export interface KycPersonalData { - accountType: AccountType; - firstName: string; - lastName: string; - phone: string; - address: KycAddress; - organizationName?: string; - organizationAddress?: KycAddress; -} - -export interface KycNationalityData { - country: Country; -} - -export interface KycRecommendationData { - key: string; -} - -export interface KycLegalEntityData extends KycFileData { - legalEntity: LegalEntity; -} - -export enum DocumentType { - IDCARD = 'IDCARD', - PASSPORT = 'PASSPORT', - DRIVERS_LICENSE = 'DRIVERS_LICENSE', - RESIDENCE_PERMIT = 'RESIDENCE_PERMIT', -} - -export enum GenderType { - MALE = 'Male', - FEMALE = 'Female', -} - -export interface KycManualIdentData { - firstName: string; - lastName: string; - birthName?: string; - birthday: Date; - nationality: Country; - birthplace?: string; - gender?: GenderType; - documentType: DocumentType; - documentNumber: string; - document: KycFileData; -} - -export interface KycSignatoryPowerData { - signatoryPower: SignatoryPower; -} - -export interface KycBeneficialData { - hasBeneficialOwners: boolean; - isAccountHolderInvolved: boolean; - managingDirector?: ContactPersonData; - beneficialOwners?: ContactPersonData[]; -} - -export interface ContactPersonData extends KycAddress { - firstName: string; - lastName: string; -} - -export interface KycOperationalData { - isOperational: boolean; - websiteUrl?: string; -} - -export interface KycFileData { - file: string; - fileName?: string; -} - -export interface KycChangeAddressData { - file: string; - fileName: string; - address: KycAddress; -} - -export interface KycChangeNameData { - file: string; - fileName: string; - firstName: string; - lastName: string; -} - -export interface KycChangePhoneData { - phone: string; -} - -export interface KycFile { - uid: string; - name: string; - type: FileType; - contentType: string; - content: any; -} - -export enum GoodsType { - TANGIBLE = 'Tangible', - VIRTUAL = 'Virtual', -} - -export enum GoodsCategory { - ELECTRONICS_COMPUTERS = 'ElectronicsComputers', - BOOKS_MUSIC_MOVIES = 'BooksMusicMovies', - HOME_GARDEN_TOOLS = 'HomeGardenTools', - CLOTHES_SHOES_BAGS = 'ClothesShoesBags', - TOYS_KIDS_BABY = 'ToysKidsBaby', - AUTOMOTIVE_ACCESSORIES = 'AutomotiveAccessories', - GAME_RECHARGE = 'GameRecharge', - ENTERTAINMENT_COLLECTION = 'EntertainmentCollection', - JEWELRY = 'Jewelry', - DOMESTIC_SERVICE = 'DomesticService', - BEAUTY_CARE = 'BeautyCare', - PHARMACY = 'Pharmacy', - SPORTS_OUTDOORS = 'SportsOutdoors', - FOOD_GROCERY_HEALTH_PRODUCTS = 'FoodGroceryHealthProducts', - PET_SUPPLIES = 'PetSupplies', - INDUSTRY_SCIENCE = 'IndustryScience', - OTHERS = 'Others', -} - -export enum StoreType { - ONLINE = 'Online', - PHYSICAL = 'Physical', - ONLINE_AND_PHYSICAL = 'OnlineAndPhysical', -} - -export enum MerchantCategory { - ACCOMMODATION_AND_FOOD_SERVICES = 'AccommodationAndFoodServices', - ADMINISTRATIVE_SUPPORT_WASTE_MANAGEMENT = 'AdministrativeSupportWasteManagement', - AGRICULTURE_FORESTRY_FISHING_HUNTING = 'AgricultureForestryFishingHunting', - ARTS_ENTERTAINMENT_RECREATION = 'ArtsEntertainmentRecreation', - CONSTRUCTION = 'Construction', - BROKER = 'Broker', - CRYPTO_ATM = 'CryptoATM', - CRYPTO_MINING = 'CryptoMining', - PROPRIETARY_CRYPTO_TRADERS = 'ProprietaryCryptoTraders', - ALGORITHM_CRYPTO_TRADERS = 'AlgorithmCryptoTraders', - P2P_MERCHANTS = 'P2PMerchants', - OTHER_DIGITAL_ASSET_SERVICES_PROVIDER = 'OtherDigitalAssetServicesProvider', - BANK = 'Bank', - NON_BANK_FINANCIAL_INSTITUTION = 'NonBankFinancialInstitution', - MONEY_SERVICES_BUSINESS_PAYMENT_SERVICE_PROVIDERS = 'MoneyServicesBusinessPaymentServiceProviders', - FAMILY_OFFICE = 'FamilyOffice', - PERSONAL_INVESTMENT_COMPANIES = 'PersonalInvestmentCompanies', - SUPERANNUATION_FUND = 'SuperannuationFund', - SOVEREIGN_WEALTH_FUND = 'SovereignWealthFund', - INVESTMENT_FUNDS = 'InvestmentFunds', - EDUCATIONAL_SERVICES = 'EducationalServices', - BETTING = 'Betting', - HEALTH_CARE_SOCIAL_ASSISTANCE = 'HealthCareSocialAssistance', - INFORMATION = 'Information', - GENERAL_WHOLESALERS = 'GeneralWholesalers', - MANAGEMENT_OF_COMPANIES_ENTERPRISES = 'ManagementOfCompaniesEnterprises', - PRECIOUS_STONES_PRECIOUS_METALS_DEALERS = 'PreciousStonesPreciousMetalsDealers', - CRUDE_OIL_NATURAL_GAS_DEALERS = 'CrudeOilNaturalGasDealers', - GENERAL_MANUFACTURING = 'GeneralManufacturing', - MARIJUANA = 'Marijuana', - MINING_EXTRACTION = 'MiningExtraction', - PAWN_SHOPS = 'PawnShops', - PROFESSIONAL_SERVICES = 'ProfessionalServices', - SCIENTIFIC_TECHNICAL_SERVICES = 'ScientificTechnicalServices', - PUBLIC_ADMINISTRATION = 'PublicAdministration', - REAL_ESTATE_RENTAL_LEASING = 'RealEstateRentalLeasing', - RETAIL_STORES_ELECTRONICS = 'RetailStoresElectronics', - RETAIL_STORES_FB = 'RetailStoresFB', - RETAIL_STORES_JEWELRY = 'RetailStoresJewelry', - RETAIL_TRADE_OTHERS = 'RetailTradeOthers', - SALE_OF_DRUGS_PHARMACEUTICAL_PRODUCTS = 'SaleOfDrugsPharmaceuticalProducts', - TOBACCO = 'Tobacco', - TRANSPORTATION_WAREHOUSING = 'TransportationWarehousing', - UTILITIES = 'Utilities', - OTHER_CRYPTO_WEB3_SERVICES = 'OtherCryptoWeb3Services', - OTHER = 'Other', -} - -export interface PaymentData { - name: string; - website?: string; - registrationNumber: string; - storeType: StoreType; - merchantCategory: MerchantCategory; - goodsType: GoodsType; - goodsCategory: GoodsCategory; - purpose: string; - contractAccepted: boolean; -} - -export interface RecallData { - accepted: boolean; -} - -// financial data -export enum QuestionType { - CONFIRMATION = 'Confirmation', - SINGLE_CHOICE = 'SingleChoice', - MULTIPLE_CHOICE = 'MultipleChoice', - TEXT = 'Text', -} - -export interface KycFinancialResponse { - key: string; - value: string; -} - -export interface KycFinancialResponses { - responses: KycFinancialResponse[]; -} - -export interface KycFinancialOption { - key: string; - text: string; -} - -export interface KycFinancialQuestion { - key: string; - type: QuestionType; - title: string; - description: string; - options?: KycFinancialOption[]; - conditions?: { - question: string; - response: string; - }[]; -} - -export interface KycFinancialQuestions extends KycFinancialResponses { - questions: KycFinancialQuestion[]; -} - -// 2FA -export enum TfaType { - APP = 'App', - MAIL = 'Mail', -} - -export enum TfaLevel { - BASIC = 'Basic', - STRICT = 'Strict', -} - -export interface TfaSetup { - type: TfaType; - secret: string; - uri: string; -} - -// limit -export enum Limit { - K_500 = 500000, - M_1 = 1000000, - M_5 = 5000000, - M_10 = 10000000, - M_15 = 15000000, - INFINITY = 1000000000, -} - -export enum InvestmentDate { - NOW = 'Now', - FUTURE = 'Future', -} - -export enum FundOrigin { - SAVINGS = 'Savings', - BUSINESS_PROFITS = 'BusinessProfits', - STOCK_GAINS = 'StockGains', - CRYPTO_GAINS = 'CryptoGains', - INHERITANCE = 'Inheritance', - OTHER = 'Other', -} - -export interface LimitRequest { - limit: Limit; - investmentDate: InvestmentDate; - fundOrigin: FundOrigin; - fundOriginText?: string; - documentProof?: string; - documentProofName?: string; -} - -// helpers -export function isStepDone(result: KycStepBase): boolean { - return [KycStepStatus.IN_REVIEW, KycStepStatus.ON_HOLD, KycStepStatus.COMPLETED].includes(result.status); -} +export { + buildKycUrl, + KycLevel, + AccountType, + LegalEntity, + SignatoryPower, + KycStatus, + KycState, + LimitPeriod, + KycStepName, + KycStepType, + KycStepStatus, + UrlType, + KycStepReason, + FileType, + DocumentType, + GenderType, + GoodsType, + GoodsCategory, + StoreType, + MerchantCategory, + QuestionType, + TfaType, + TfaLevel, + Limit, + InvestmentDate, + FundOrigin, + isStepDone, +} from '@dfx.swiss/core'; + +export type { + TradingLimit, + KycInfo, + KycSession, + KycAdditionalInfo, + KycSessionInfo, + KycStepBase, + KycStep, + KycStepSession, + KycContactData, + KycAddress, + KycPersonalData, + KycNationalityData, + KycRecommendationData, + KycLegalEntityData, + KycManualIdentData, + KycSignatoryPowerData, + KycBeneficialData, + ContactPersonData, + KycOperationalData, + KycFileData, + KycChangeAddressData, + KycChangeNameData, + KycChangePhoneData, + KycFile, + PaymentData, + RecallData, + KycFinancialResponse, + KycFinancialResponses, + KycFinancialOption, + KycFinancialQuestion, + KycFinancialQuestions, + TfaSetup, + LimitRequest, + UserName, + UserData, +} from '@dfx.swiss/core'; diff --git a/packages/react/src/definitions/language.ts b/packages/react/src/definitions/language.ts index cabd320b..e24b7e33 100644 --- a/packages/react/src/definitions/language.ts +++ b/packages/react/src/definitions/language.ts @@ -1,9 +1,2 @@ -export const LanguageUrl = { get: 'language' }; - -export interface Language { - id: number; - name: string; - symbol: string; - foreignName: string; - enable: boolean; -} +export { LanguageUrl } from '@dfx.swiss/core'; +export type { Language } from '@dfx.swiss/core'; diff --git a/packages/react/src/definitions/price-step.ts b/packages/react/src/definitions/price-step.ts index ae483a0f..3fc9682a 100644 --- a/packages/react/src/definitions/price-step.ts +++ b/packages/react/src/definitions/price-step.ts @@ -1,7 +1 @@ -export interface PriceStep { - source: string; - from: string; - to: string; - price: number; - timestamp: Date; -} +export type { PriceStep } from '@dfx.swiss/core'; diff --git a/packages/react/src/definitions/route.ts b/packages/react/src/definitions/route.ts index 84e022e2..288344a5 100644 --- a/packages/react/src/definitions/route.ts +++ b/packages/react/src/definitions/route.ts @@ -1,229 +1,34 @@ -import { Asset } from './asset'; -import { Blockchain } from './blockchain'; -import { Fiat } from './fiat'; - -export const PaymentRoutesUrl = { get: 'route' }; -export const PaymentLinksUrl = { - get: 'paymentLink', - create: 'paymentLink', - update: 'paymentLink', - assign: 'paymentLink/assign', - payment: 'paymentLink/payment', - userPaymentLinksConfig: 'paymentLink/config', - recipient: (route: string) => `paymentLink/recipient?id=${route}`, - stickers: 'paymentLink/stickers', - pos: 'paymentLink/pos', -}; - -export enum PaymentLinkStatus { - ACTIVE = 'Active', - INACTIVE = 'Inactive', -} - -export enum PaymentLinkMode { - SINGLE = 'Single', - MULTIPLE = 'Multiple', - PUBLIC = 'Public', -} - -export enum PaymentLinkPaymentStatus { - PENDING = 'Pending', - COMPLETED = 'Completed', - CANCELLED = 'Cancelled', - EXPIRED = 'Expired', -} - -export enum PaymentLinkPaymentMode { - SINGLE = 'Single', - MULTIPLE = 'Multiple', -} - -export enum PaymentStandardType { - OPEN_CRYPTO_PAY = 'OpenCryptoPay', - LIGHTNING_BOLT11 = 'LightningBolt11', - PAY_TO_ADDRESS = 'PayToAddress', -} - -export enum PaymentQuoteStatus { - ACTUAL = 'Actual', - CANCELLED = 'Cancelled', - EXPIRED = 'Expired', - - TX_RECEIVED = 'TxReceived', - TX_MEMPOOL = 'TxMempool', - TX_BLOCKCHAIN = 'TxBlockchain', - TX_COMPLETED = 'TxCompleted', - TX_FAILED = 'TxFailed', -} - -export enum MinCompletionStatus { - TX_RECEIVED = PaymentQuoteStatus.TX_RECEIVED, - TX_MEMPOOL = PaymentQuoteStatus.TX_MEMPOOL, - TX_BLOCKCHAIN = PaymentQuoteStatus.TX_BLOCKCHAIN, - TX_COMPLETED = PaymentQuoteStatus.TX_COMPLETED, -} - -export const PaymentLinkBlockchain = { - ARBITRUM: Blockchain.ARBITRUM, - BASE: Blockchain.BASE, - ETHEREUM: Blockchain.ETHEREUM, - LIGHTNING: Blockchain.LIGHTNING, - SPARK: Blockchain.SPARK, - ARK: Blockchain.ARK, - BITCOIN: Blockchain.BITCOIN, - FIRO: Blockchain.FIRO, - INTERNET_COMPUTER: Blockchain.INTERNET_COMPUTER, - MONERO: Blockchain.MONERO, - OPTIMISM: Blockchain.OPTIMISM, - POLYGON: Blockchain.POLYGON, - SOLANA: Blockchain.SOLANA, -} as const; - -export type PaymentLinkBlockchain = typeof PaymentLinkBlockchain[keyof typeof PaymentLinkBlockchain]; - -export interface MinAmount { - amount: number; - asset: string; -} - -export interface DepositDto { - id: number; - address: string; - blockchains: Blockchain[]; -} - -export interface BuyRoute { - id: number; - active: boolean; - iban: string; - asset: Asset; - bankUsage: string; - volume: number; - annualVolume: number; - fee: number; - minDeposits: MinAmount[]; - minFee: MinAmount; -} - -export interface SellRoute { - id: number; - active: boolean; - deposit: DepositDto; - iban: string; - currency: Fiat; - volume: number; - annualVolume: number; - fee: number; - minDeposits: MinAmount[]; - minFee: MinAmount; -} - -export interface SwapRoute { - id: number; - active: boolean; - asset: Asset; - deposit: DepositDto; - volume: number; - annualVolume: number; - fee: number; - minDeposits: MinAmount[]; - minFee: MinAmount; -} - -export interface PaymentRoutes { - buy: BuyRoute[]; - sell: SellRoute[]; - swap: SwapRoute[]; -} - -export type PaymentRoute = BuyRoute | SellRoute | SwapRoute; -export type PaymentRouteType = 'buy' | 'sell' | 'swap'; - -export interface PaymentLink { - id: string; - routeId: string; - externalId?: string; - label?: string; - recipient?: PaymentLinkRecipient; - status: PaymentLinkStatus; - mode: PaymentLinkMode; - payment?: PaymentLinkPayment; - config?: PaymentLinkConfig; - url: string; - lnurl: string; -} - -export interface PaymentLinkRecipient { - name?: string; - address?: PaymentLinkRecipientAddress; - phone?: string; - mail?: string; - website?: string; -} - -export interface PaymentLinkRecipientAddress { - street?: string; - houseNumber?: string; - city?: string; - zip?: string; - country?: string; -} - -export interface PaymentLinkPayment { - id: string; - externalId?: string; - status: PaymentLinkPaymentStatus; - amount: number; - currency: Fiat; - mode: PaymentLinkPaymentMode; - expiryDate: Date; - txCount: number; - url: string; - lnurl: string; -} - -export interface CreatePaymentLinkPayment { - mode: PaymentLinkPaymentMode; - amount: number; - externalId: string; - currency: Fiat; - expiryDate: Date; -} - -export interface CreatePaymentLink { - routeId?: number; - externalId?: string; - webhookUrl?: string; - recipient: PaymentLinkRecipient; - payment?: CreatePaymentLinkPayment; -} - -export interface UpdatePaymentLinkConfig { - standards?: PaymentStandardType[]; - blockchains?: PaymentLinkBlockchain[]; - minCompletionStatus?: MinCompletionStatus; - displayQr?: boolean; - recipient?: PaymentLinkRecipient; - paymentTimeout?: number; - cancellable?: boolean; -} - -export interface PaymentLinkConfig extends UpdatePaymentLinkConfig { - fee?: number; -} - -export interface UpdatePaymentLink { - status?: PaymentLinkStatus; - mode?: PaymentLinkMode; - label?: string; - webhookUrl?: string; - config?: UpdatePaymentLinkConfig; -} - -export interface AssignPaymentLink { - publicName: string; -} - -export interface PaymentLinkPos { - url: string; -} +export { + PaymentRoutesUrl, + PaymentLinksUrl, + PaymentLinkStatus, + PaymentLinkMode, + PaymentLinkPaymentStatus, + PaymentLinkPaymentMode, + PaymentStandardType, + PaymentQuoteStatus, + MinCompletionStatus, + PaymentLinkBlockchain, +} from '@dfx.swiss/core'; + +export type { + MinAmount, + DepositDto, + BuyRoute, + SellRoute, + SwapRoute, + PaymentRoutes, + PaymentRoute, + PaymentRouteType, + PaymentLink, + PaymentLinkRecipient, + PaymentLinkRecipientAddress, + PaymentLinkPayment, + CreatePaymentLinkPayment, + CreatePaymentLink, + UpdatePaymentLinkConfig, + PaymentLinkConfig, + UpdatePaymentLink, + AssignPaymentLink, + PaymentLinkPos, +} from '@dfx.swiss/core'; diff --git a/packages/react/src/definitions/sell.ts b/packages/react/src/definitions/sell.ts index a52e3cf5..c739cbad 100644 --- a/packages/react/src/definitions/sell.ts +++ b/packages/react/src/definitions/sell.ts @@ -1,84 +1,2 @@ -import { Asset } from './asset'; -import { Blockchain } from './blockchain'; -import { Fees } from './fees'; -import { Fiat } from './fiat'; -import { PriceStep } from './price-step'; -import { TransactionError } from './transaction'; - -export const SellUrl = { - receive: 'sell/paymentInfos', - confirm: 'sell/paymentInfos/:id/confirm' -}; - -// EIP-5792 wallet_sendCalls data for gasless transactions -export interface Eip5792Call { - to: string; - data: string; - value: string; -} - -export interface Eip5792Data { - paymasterUrl: string; - chainId: number; - calls: Eip5792Call[]; -} - -export interface UnsignedTx { - chainId: number; - from: string; - to: string; - data: string; - value: string; - nonce: number; - gasPrice: string; - gasLimit: string; - eip5792?: Eip5792Data; -} - -export interface Sell { - id: number; - uid: string; - timestamp: Date; - routeId: number; - depositAddress: string; - blockchain: Blockchain; - fees: Fees; - minVolume: number; - maxVolume: number; - amount: number; - asset: Asset; - feesTarget: Fees; - minVolumeTarget: number; - maxVolumeTarget: number; - exchangeRate: number; - priceSteps: PriceStep[]; - rate: number; - exactPrice: boolean; - estimatedAmount: number; - currency: Fiat; - beneficiary: Beneficiary; - paymentRequest?: string; - depositTx?: UnsignedTx; - isValid: boolean; - error?: TransactionError; -} - -export interface Beneficiary { - iban: string; - name: string; -} - -export interface SellPaymentInfo { - iban: string; - asset: Asset; - amount?: number; - currency: Fiat; - targetAmount?: number; - externalTransactionId?: string; - exactPrice?: boolean; -} - -export interface ConfirmSellData { - signedTxHex?: string; - txHash?: string; // Transaction hash from wallet_sendCalls -} +export { SellUrl } from '@dfx.swiss/core'; +export type { Eip5792Call, Eip5792Data, UnsignedTx, Sell, Beneficiary, SellPaymentInfo, ConfirmSellData } from '@dfx.swiss/core'; diff --git a/packages/react/src/definitions/session.ts b/packages/react/src/definitions/session.ts index 9ab7dead..72aa70d1 100644 --- a/packages/react/src/definitions/session.ts +++ b/packages/react/src/definitions/session.ts @@ -1,10 +1 @@ -import { Blockchain } from './blockchain'; -import { UserRole } from './jwt'; - -export interface Session { - address?: string; - user?: number; - account: number; - role: UserRole; - blockchains: Blockchain[]; -} +export type { Session } from '@dfx.swiss/core'; diff --git a/packages/react/src/definitions/settings.ts b/packages/react/src/definitions/settings.ts index 536bef5e..de55f8d6 100644 --- a/packages/react/src/definitions/settings.ts +++ b/packages/react/src/definitions/settings.ts @@ -1,8 +1,2 @@ -export const SettingsUrl = { infoBanner: 'setting/infoBanner' }; - -export interface InfoBanner { - de: string; - en: string; - fr: string; - it: string; -} +export { SettingsUrl } from '@dfx.swiss/core'; +export type { InfoBanner } from '@dfx.swiss/core'; diff --git a/packages/react/src/definitions/support.ts b/packages/react/src/definitions/support.ts index c8e2c238..8c687bf4 100644 --- a/packages/react/src/definitions/support.ts +++ b/packages/react/src/definitions/support.ts @@ -1,141 +1,21 @@ -import { Limit, InvestmentDate, FundOrigin } from './kyc'; - -export const SupportUrl = { - supportIssue: 'support/issue', - createMessage: (uid: string) => `support/issue/${uid}/message`, - getIssue: (uid: string, fromMessageId?: number) => - `support/issue/${uid}${fromMessageId ? `?fromMessageId=${fromMessageId}` : ''}`, - fetchFileData: (uid: string, messageId: number) => `support/issue/${uid}/message/${messageId}/file`, -}; - -export enum SupportIssueType { - GENERIC_ISSUE = 'GenericIssue', - TRANSACTION_ISSUE = 'TransactionIssue', - VERIFICATION_CALL = 'VerificationCall', - KYC_ISSUE = 'KycIssue', - LIMIT_REQUEST = 'LimitRequest', - PARTNERSHIP_REQUEST = 'PartnershipRequest', - NOTIFICATION_OF_CHANGES = 'NotificationOfChanges', - BUG_REPORT = 'BugReport', -} - -export enum SupportIssueReason { - // general - OTHER = 'Other', - - // support - DATA_REQUEST = 'DataRequest', - - // transaction issue - FUNDS_NOT_RECEIVED = 'FundsNotReceived', - TRANSACTION_MISSING = 'TransactionMissing', - - // verification call - REJECT_CALL = 'RejectCall', - REPEAT_CALL = 'RepeatCall', - - // notification of changes issue - NAME_CHANGED = 'NameChanged', - ADDRESS_CHANGED = 'AddressChanged', - CIVIL_STATUS_CHANGED = 'CivilStatusChanged', -} - -export enum SupportIssueState { - CREATED = 'Created', - PENDING = 'Pending', - COMPLETED = 'Completed', - CANCELED = 'Canceled', -} - -export enum SupportMessageStatus { - SENT = 'Sent', - RECEIVED = 'Received', - FAILED = 'Failed', -} - -// --- CORE INTERFACES --- // -export interface Reaction { - emoji: string; - users: string[]; -} - -export interface BlobContent { - data: any; - contentType: string; -} - -export interface DataFile { - file: string; - type: string; - size: number; - url: string; -} - -export interface SupportIssueTransaction { - uid: string; - url: string; -} - -export interface SupportIssueLimitRequest { - id: number; - limit: number; -} - -export interface SupportMessage { - id: number; - author?: string; // undefined for unsettled messages - created: Date; - message?: string; - fileName?: string; - - // frontend only fields - file?: DataFile; - status?: SupportMessageStatus; - replyTo?: number; - reactions?: Reaction[]; -} - -export interface SupportIssue { - uid: string; - state: SupportIssueState; - type: SupportIssueType; - reason: SupportIssueReason; - name: string; - created: Date; - messages: SupportMessage[]; - transaction?: SupportIssueTransaction; - limitRequest?: SupportIssueLimitRequest; -} - -// --- CREATE INTERFACES --- // - -export interface TransactionIssue { - id?: number; - uid?: string; - orderUid?: string; - senderIban?: string; - receiverIban?: string; - date?: Date; -} - -export interface LimitRequestIssue { - limit: Limit; - investmentDate: InvestmentDate; - fundOrigin: FundOrigin; - fundOriginText?: string; -} - -export interface CreateSupportMessage { - author?: string; - message?: string; - file?: string; - fileName?: string; -} - -export interface CreateSupportIssue extends CreateSupportMessage { - type: SupportIssueType; - reason: SupportIssueReason; - name: string; - transaction?: TransactionIssue; - limitRequest?: LimitRequestIssue; -} +export { + SupportUrl, + SupportIssueType, + SupportIssueReason, + SupportIssueState, + SupportMessageStatus, +} from '@dfx.swiss/core'; + +export type { + Reaction, + BlobContent, + DataFile, + SupportIssueTransaction, + SupportIssueLimitRequest, + SupportMessage, + SupportIssue, + TransactionIssue, + LimitRequestIssue, + CreateSupportMessage, + CreateSupportIssue, +} from '@dfx.swiss/core'; diff --git a/packages/react/src/definitions/swap.ts b/packages/react/src/definitions/swap.ts index a0e7c39d..9f27d5b3 100644 --- a/packages/react/src/definitions/swap.ts +++ b/packages/react/src/definitions/swap.ts @@ -1,51 +1,2 @@ -import { Asset } from './asset'; -import { Fees } from './fees'; -import { PriceStep } from './price-step'; -import { UnsignedTx } from './sell'; -import { TransactionError } from './transaction'; - -export const SwapUrl = { - receive: 'swap/paymentInfos', - confirm: 'swap/paymentInfos/:id/confirm' -}; - -export interface Swap { - id: number; - uid: string; - timestamp: Date; - routeId: number; - depositAddress: string; - sourceAsset: Asset; - targetAsset: Asset; - fees: Fees; - minVolume: number; - maxVolume: number; - amount: number; - feesTarget: Fees; - minVolumeTarget: number; - maxVolumeTarget: number; - exchangeRate: number; - priceSteps: PriceStep[]; - rate: number; - exactPrice: boolean; - estimatedAmount: number; - paymentRequest?: string; - depositTx?: UnsignedTx; - isValid: boolean; - error?: TransactionError; -} - -export interface SwapPaymentInfo { - sourceAsset: Asset; - amount?: number; - targetAsset: Asset; - targetAmount?: number; - receiverAddress?: string; - externalTransactionId?: string; - exactPrice?: boolean; -} - -export interface ConfirmSwapData { - signedTxHex?: string; - txHash?: string; // Transaction hash from wallet_sendCalls -} +export { SwapUrl } from '@dfx.swiss/core'; +export type { Swap, SwapPaymentInfo, ConfirmSwapData } from '@dfx.swiss/core'; diff --git a/packages/react/src/definitions/transaction.ts b/packages/react/src/definitions/transaction.ts index ea6d2ce1..4693284c 100644 --- a/packages/react/src/definitions/transaction.ts +++ b/packages/react/src/definitions/transaction.ts @@ -1,243 +1,28 @@ -export const TransactionUrl = { - get: 'transaction', - single: `transaction/single`, - detail: 'transaction/detail', - csv: 'transaction/detail/csv', - unassigned: 'transaction/unassigned', - target: 'transaction/target', - refund: (id: number) => `transaction/${id}/refund`, - bankRefund: (id: number) => `transaction/${id}/refund/bank`, - setTarget: (id: number) => `transaction/${id}/target`, - invoice: (id: number | string) => `transaction/${id}/invoice`, - receipt: (id: number) => `transaction/${id}/receipt`, -}; - -import { Asset } from './asset'; -import { Blockchain } from './blockchain'; -import { Fees } from './fees'; -import { Fiat } from './fiat'; -import { PriceStep } from './price-step'; - -export enum FiatPaymentMethod { - BANK = 'Bank', - INSTANT = 'Instant', - CARD = 'Card', -} - -export enum CryptoPaymentMethod { - CRYPTO = 'Crypto', -} - -export type PaymentMethod = FiatPaymentMethod | CryptoPaymentMethod; - -export enum TransactionError { - AMOUNT_TOO_LOW = 'AmountTooLow', - AMOUNT_TOO_HIGH = 'AmountTooHigh', - BANK_TRANSACTION_MISSING = 'BankTransactionMissing', - BANK_TRANSACTION_OR_VIDEO_MISSING = 'BankTransactionOrVideoMissing', - KYC_REQUIRED = 'KycRequired', - KYC_DATA_REQUIRED = 'KycDataRequired', - NAME_REQUIRED = 'NameRequired', - KYC_REQUIRED_INSTANT = 'KycRequiredInstant', - LIMIT_EXCEEDED = 'LimitExceeded', - NATIONALITY_NOT_ALLOWED = 'NationalityNotAllowed', - PAYMENT_METHOD_NOT_ALLOWED = 'PaymentMethodNotAllowed', - VIDEO_IDENT_REQUIRED = 'VideoIdentRequired', - IBAN_CURRENCY_MISMATCH = 'IbanCurrencyMismatch', - TRADING_NOT_ALLOWED = 'TradingNotAllowed', - RECOMMENDATION_REQUIRED = 'RecommendationRequired', - EMAIL_REQUIRED = 'EmailRequired', -} - -export enum TransactionType { - BUY = 'Buy', - SELL = 'Sell', - SWAP = 'Swap', - REFERRAL = 'Referral', -} - -export enum TransactionState { - CREATED = 'Created', - PROCESSING = 'Processing', - LIQUIDITY_PENDING = 'LiquidityPending', - CHECK_PENDING = 'CheckPending', - KYC_REQUIRED = 'KycRequired', - LIMIT_EXCEEDED = 'LimitExceeded', - FEE_TOO_HIGH = 'FeeTooHigh', - PRICE_UNDETERMINABLE = 'PriceUndeterminable', - PAYOUT_IN_PROGRESS = 'PayoutInProgress', - COMPLETED = 'Completed', - FAILED = 'Failed', - RETURN_PENDING = 'ReturnPending', - RETURNED = 'Returned', - UNASSIGNED = 'Unassigned', - WAITING_FOR_PAYMENT = 'WaitingForPayment', -} - -export enum TransactionFailureReason { - UNKNOWN = 'Unknown', - DAILY_LIMIT_EXCEEDED = 'DailyLimitExceeded', - MONTHLY_LIMIT_EXCEEDED = 'MonthlyLimitExceeded', - ANNUAL_LIMIT_EXCEEDED = 'AnnualLimitExceeded', - ACCOUNT_HOLDER_MISMATCH = 'AccountHolderMismatch', - KYC_REJECTED = 'KycRejected', - FRAUD_SUSPICION = 'FraudSuspicion', - SANCTION_SUSPICION = 'SanctionSuspicion', - MIN_DEPOSIT_NOT_REACHED = 'MinDepositNotReached', - ASSET_NOT_AVAILABLE = 'AssetNotAvailable', - ASSET_NOT_AVAILABLE_WITH_CHOSEN_BANK = 'AssetNotAvailableWithChosenBank', - STAKING_DISCONTINUED = 'StakingDiscontinued', - BANK_NOT_ALLOWED = 'BankNotAllowed', - PAYMENT_ACCOUNT_NOT_ALLOWED = 'PaymentAccountNotAllowed', - COUNTRY_NOT_ALLOWED = 'CountryNotAllowed', - INSTANT_PAYMENT = 'InstantPayment', - FEE_TOO_HIGH = 'FeeTooHigh', - RECEIVER_REJECTED = 'ReceiverRejected', - CHF_ABROAD_NOT_ALLOWED = 'ChfAbroadNotAllowed', - ASSET_KYC_NEEDED = 'AssetKycNeeded', - CARD_NAME_MISMATCH = 'CardNameMismatch', - USER_DELETED = 'UserDeleted', - VIDEO_IDENT_NEEDED = 'VideoIdentNeeded', - MISSING_LIQUIDITY = 'MissingLiquidity', - KYC_DATA_NEEDED = 'KycDataNeeded', - BANK_TX_NEEDED = 'BankTxNeeded', - MERGE_INCOMPLETE = 'MergeIncomplete', - PHONE_VERIFICATION_NEEDED = 'PhoneVerificationNeeded', - BANK_RELEASE_PENDING = 'BankReleasePending', - INPUT_NOT_CONFIRMED = 'InputNotConfirmed', -} - -export enum ExportType { - COMPACT = 'Compact', - COIN_TRACKING = 'CoinTracking', - CHAIN_REPORT = 'ChainReport', -} - -export enum ExportFormat { - CSV = 'csv', - JSON = 'json', -} - -export interface UnassignedTransaction { - id?: number; - uid: string; - orderUid: string; - type: TransactionType; - state: TransactionState; - inputAmount?: number; - inputAsset?: string; - inputAssetId?: number; - inputBlockchain?: Blockchain; - inputPaymentMethod?: PaymentMethod; - inputTxId?: string; - inputTxUrl?: string; - chargebackAmount?: number; - chargebackAsset?: string; - chargebackAssetId?: number; - chargebackTarget?: string; - chargeBackTxId?: string; - chargeBackTxUrl?: string; - chargebackDate?: Date; - date: Date; -} - -export interface NetworkStartTx { - txId: string; - txUrl: string; - amount: number; - exchangeRate: number; - asset: string; -} - -export interface Transaction extends UnassignedTransaction { - reason: TransactionFailureReason; - exchangeRate?: number; - priceSteps?: PriceStep[]; - rate?: number; - outputAmount?: number; - outputAsset?: string; - outputAssetId?: number; - outputBlockchain?: Blockchain; - outputPaymentMethod?: PaymentMethod; - outputTxId?: string; - outputTxUrl?: string; - fees?: Fees; - externalTransactionId?: string; - networkStartTx?: NetworkStartTx; -} - -export interface DetailTransaction extends Transaction { - sourceAccount?: string; - targetAccount?: string; -} - -export interface TransactionTarget { - id: number; - bankUsage: string; - asset: Asset; - address: string; -} - -export interface TransactionFilter { - buy?: boolean; - sell?: boolean; - staking?: boolean; - ref?: boolean; - lm?: boolean; -} - -export interface RefundFeeData { - dfx: number; - network: number; - bank: number; -} - -export interface RefundBankDetails { - name?: string; - address?: string; - houseNumber?: string; - zip?: string; - city?: string; - country?: string; - iban?: string; - bic?: string; -} - -export interface TransactionRefundData { - expiryDate: Date; - fee: RefundFeeData; - refundAmount: number; - refundAsset: Asset | Fiat; - inputAmount: number; - inputAsset: Asset | Fiat; - refundTarget?: string; - bankDetails?: RefundBankDetails; -} - -export interface TransactionHistoryQuery { - userAddress?: string; - from?: Date; - to?: Date; - format?: ExportFormat; - buy?: boolean; - sell?: boolean; - staking?: boolean; - ref?: boolean; - lm?: boolean; -} - -export interface CreditorData { - name: string; - address: string; - houseNumber?: string; - zip: string; - city: string; - country: string; -} - -export interface TransactionRefundTarget { - refundTarget?: string; - creditorData?: CreditorData; -} - -export type TransactionFilterKey = keyof TransactionFilter; +export { + TransactionUrl, + FiatPaymentMethod, + CryptoPaymentMethod, + TransactionError, + TransactionType, + TransactionState, + TransactionFailureReason, + ExportType, + ExportFormat, +} from '@dfx.swiss/core'; + +export type { + PaymentMethod, + UnassignedTransaction, + NetworkStartTx, + Transaction, + DetailTransaction, + TransactionTarget, + TransactionFilter, + RefundFeeData, + RefundBankDetails, + TransactionRefundData, + TransactionHistoryQuery, + CreditorData, + TransactionRefundTarget, + TransactionFilterKey, +} from '@dfx.swiss/core'; diff --git a/packages/react/src/definitions/user.ts b/packages/react/src/definitions/user.ts index fac3a642..d2e45b59 100644 --- a/packages/react/src/definitions/user.ts +++ b/packages/react/src/definitions/user.ts @@ -1,140 +1,15 @@ -import { Blockchain } from './blockchain'; -import { Country } from './country'; -import { Fiat } from './fiat'; -import { AccountType, TradingLimit } from './kyc'; -import { Language } from './language'; -import { TransactionFilterKey } from './transaction'; - -export const UserUrl = { - get: 'user', - ref: 'user/ref', - delete: 'user', - update: 'user', - updateMail: 'user/mail', - verifyMail: 'user/mail/verify', - addresses: 'user/addresses', - apiKey: 'user/apiKey', - apiFilter: 'user/apiFilter', - changeAddress: 'user/change', - specialCodes: 'user/specialCodes', - profile: 'user/profile', -}; - -export enum UserStatus { - NA = 'NA', - ACTIVE = 'Active', - BLOCKED = 'Blocked', -} - -export enum PhoneCallTime { - H_9_TO_10 = 'H9To10', - H_10_TO_11 = 'H10To11', - H_11_TO_12 = 'H11To12', - H_12_TO_13 = 'H12To13', - H_13_TO_14 = 'H13To14', - H_14_TO_15 = 'H14To15', - H_15_TO_16 = 'H15To16', - H_9_TO_16 = 'H9To16', -} - -export enum PhoneCallStatus { - UNAVAILABLE = 'Unavailable', - COMPLETED = 'Completed', - FAILED = 'Failed', -} - -export interface VolumeInformation { - total: number; - annual: number; -} - -export interface Volumes { - buy: VolumeInformation; - sell: VolumeInformation; - swap: VolumeInformation; -} - -export interface Referral { - code?: string; - commission: number; - volume: number; - credit: number; - paidCredit: number; - userCount: number; - activeUserCount: number; -} - -export interface UserAddress { - wallet: string; - label?: string; - address: string; - explorerUrl?: string; - blockchains: Blockchain[]; - volumes: Volumes; - refCode?: string; - apiKeyCT?: string; - apiFilterCT?: TransactionFilterKey[]; - isCustody: boolean; -} - -export interface UserKyc { - hash: string; - level: number; - dataComplete: boolean; - preferredPhoneTimes: PhoneCallTime[]; - phoneCallAccepted?: boolean; - phoneCallStatus?: PhoneCallStatus; -} - -export interface UserPaymentLink { - active: boolean; -} - -export interface User { - accountId: number; - accountType: AccountType; - mail?: string; - phone?: string; - language: Language; - currency: Fiat; - tradingLimit: TradingLimit; - kyc: UserKyc; - volumes: Volumes; - addresses: UserAddress[]; - disabledAddresses: UserAddress[]; - activeAddress?: UserAddress; - paymentLink: UserPaymentLink; - apiKeyCT: string; - apiFilterCT: TransactionFilterKey[]; -} - -export interface UpdateUser { - phone?: string; - language?: Language; - currency?: Fiat; - preferredPhoneTimes?: PhoneCallTime[]; - acceptCall?: boolean; -} - -export interface ApiKey { - key: string; - secret: string; -} - -export interface UserAddressInfo { - street?: string; - houseNumber?: string; - city?: string; - zip?: string; - country?: Country; -} - -export interface UserProfile { - accountType?: AccountType; - firstName?: string; - lastName?: string; - mail?: string; - phone?: string; - address?: UserAddressInfo; - organizationName?: string; -} +export { UserUrl, UserStatus, PhoneCallTime, PhoneCallStatus } from '@dfx.swiss/core'; + +export type { + VolumeInformation, + Volumes, + Referral, + UserAddress, + UserKyc, + UserPaymentLink, + User, + UpdateUser, + ApiKey, + UserAddressInfo, + UserProfile, +} from '@dfx.swiss/core'; diff --git a/packages/react/src/hooks/kyc.hook.ts b/packages/react/src/hooks/kyc.hook.ts index 1f153bb9..3171c9ff 100644 --- a/packages/react/src/hooks/kyc.hook.ts +++ b/packages/react/src/hooks/kyc.hook.ts @@ -1,5 +1,6 @@ import { useCallback, useMemo } from 'react'; import { + buildKycUrl, KycFileData, KycContactData, KycFinancialQuestions, @@ -11,7 +12,6 @@ import { KycSession, KycStepName, KycStepType, - KycUrl, LimitRequest, TfaSetup, UserData, @@ -85,7 +85,8 @@ export interface KycInterface { } export function useKyc(): KycInterface { - const { call: callApi } = useApi(); + const { call: callApi, defaultUrl } = useApi(); + const kycUrl = useMemo(() => buildKycUrl(defaultUrl), [defaultUrl]); // --- HELPER METHODS --- // const buildInit = useCallback(({ code, method, data, noJson }: CallConfig): RequestInit => { @@ -116,7 +117,7 @@ export function useKyc(): KycInterface { const setName = useCallback( async (data: UserName): Promise => { return callApi({ - url: KycUrl.setName, + url: kycUrl.setName, method: 'PUT', data, }); @@ -127,7 +128,7 @@ export function useKyc(): KycInterface { const setData = useCallback( async (data: UserData): Promise => { return callApi({ - url: KycUrl.setData, + url: kycUrl.setData, method: 'POST', data, }); @@ -137,14 +138,14 @@ export function useKyc(): KycInterface { const getKycInfo = useCallback( async (code: string): Promise => { - return call({ url: KycUrl.base, code, method: 'GET' }); + return call({ url: kycUrl.base, code, method: 'GET' }); }, [call], ); const continueKyc = useCallback( async (code: string, autoStep = true): Promise => { - const url = `${KycUrl.base}?autoStep=${autoStep.toString()}`; + const url = `${kycUrl.base}?autoStep=${autoStep.toString()}`; return call({ url, code, method: 'PUT' }); }, [call], @@ -156,7 +157,7 @@ export function useKyc(): KycInterface { type && params.set('type', type); sequence != null && params.set('sequence', `${sequence}`); - const url = `${KycUrl.base}/${name}?${params.toString()}`; + const url = `${kycUrl.base}/${name}?${params.toString()}`; return call({ url, code, method: 'GET' }); }, @@ -286,7 +287,7 @@ export function useKyc(): KycInterface { const getFile = useCallback( async (kycFileId: string): Promise => { return callApi({ - url: `${KycUrl.file}/${kycFileId}`, + url: `${kycUrl.file}/${kycFileId}`, method: 'GET', version: 'v2', }); @@ -303,7 +304,7 @@ export function useKyc(): KycInterface { const check2fa = useCallback( async (level?: TfaLevel): Promise => { - const url = level ? `${KycUrl.checkTfa}?level=${level}` : KycUrl.checkTfa; + const url = level ? `${kycUrl.checkTfa}?level=${level}` : kycUrl.checkTfa; return callApi({ url, version: 'v2', method: 'GET' }); }, [callApi], @@ -311,7 +312,7 @@ export function useKyc(): KycInterface { const setup2fa = useCallback( async (code: string, level?: TfaLevel): Promise => { - const url = level ? `${KycUrl.tfa}?level=${level}` : KycUrl.tfa; + const url = level ? `${kycUrl.tfa}?level=${level}` : kycUrl.tfa; return call({ url, code, method: 'POST' }); }, [call], @@ -319,28 +320,28 @@ export function useKyc(): KycInterface { const verify2fa = useCallback( async (code: string, token: string): Promise => { - return call({ url: `${KycUrl.tfa}/verify`, code, method: 'POST', data: { token } }); + return call({ url: `${kycUrl.tfa}/verify`, code, method: 'POST', data: { token } }); }, [call], ); const increaseLimit = useCallback( async (code: string, request: LimitRequest): Promise => { - return call({ url: KycUrl.limit, code, method: 'POST', data: request }); + return call({ url: kycUrl.limit, code, method: 'POST', data: request }); }, [call], ); const addTransferClient = useCallback( async (code: string, client: string): Promise => { - return call({ url: KycUrl.transfer(client), code, method: 'POST' }); + return call({ url: kycUrl.transfer(client), code, method: 'POST' }); }, [call], ); const removeTransferClient = useCallback( async (code: string, client: string): Promise => { - return call({ url: KycUrl.transfer(client), code, method: 'DELETE' }); + return call({ url: kycUrl.transfer(client), code, method: 'DELETE' }); }, [call], ); diff --git a/packages/react/src/hooks/sell.hook.ts b/packages/react/src/hooks/sell.hook.ts index 09312271..01d7fbb0 100644 --- a/packages/react/src/hooks/sell.hook.ts +++ b/packages/react/src/hooks/sell.hook.ts @@ -25,7 +25,7 @@ export function useSell(): SellInterface { const confirmSell = useCallback( async (id: number, data: ConfirmSellData): Promise => { - return call({ url: SellUrl.confirm.replace(':id', id.toString()), method: 'PUT', data }); + return call({ url: SellUrl.confirm(id), method: 'PUT', data }); }, [call], ); diff --git a/packages/react/src/hooks/swap.hook.ts b/packages/react/src/hooks/swap.hook.ts index 67341b3f..e015e7a1 100644 --- a/packages/react/src/hooks/swap.hook.ts +++ b/packages/react/src/hooks/swap.hook.ts @@ -45,7 +45,7 @@ export function useSwap(): SwapInterface { const confirmSwap = useCallback( async (id: number, data: ConfirmSwapData): Promise => { - return call({ url: SwapUrl.confirm.replace(':id', id.toString()), method: 'POST', data }); + return call({ url: SwapUrl.confirm(id), method: 'POST', data }); }, [call], ); diff --git a/packages/react/src/utils.ts b/packages/react/src/utils.ts index 2e337620..f34419ce 100644 --- a/packages/react/src/utils.ts +++ b/packages/react/src/utils.ts @@ -1,63 +1 @@ -import * as IbanTools from 'ibantools'; - -type KeyType = { - [K in keyof T]: T[K] extends U ? K : never; -}[keyof T]; - -export class Utils { - static groupBy(list: T[], key: KeyType): Map { - return list.reduce( - (map, item) => map.set(item[key] as U, (map.get(item[key] as U) ?? []).concat(item)), - new Map(), - ); - } - - static createRules(rules: any): any { - for (const property in rules) { - if (rules[property] instanceof Array) { - rules[property] = rules[property].reduce((prev: any, curr: any) => Utils.updateObject(prev, curr), {}); - } - } - return rules; - } - - private static updateObject(obj?: any, update?: any): unknown { - return obj ? { ...obj, ...update } : undefined; - } - - static formatAmount(amount?: number, decimals = 2): string { - return amount?.toFixed(decimals).replace(/\B(?=(\d{3})+(?!\d))/g, ' ') ?? ''; - } - - static formatAmountCrypto(amount: number, decimals = 5): string { - let r = (+amount.toPrecision(decimals)).toFixed(decimals); - if (r.match(/\./)) { - r = r.replace(/\.?0+$/, ''); - } - return r; - } - - static formatIban(iban?: string): string | null { - return IbanTools.friendlyFormatIBAN(iban); - } - - static isJwt(jwt?: string): boolean { - return jwt ? /^[A-Za-z0-9_-]{2,}(?:\.[A-Za-z0-9_-]{2,}){2}$/.test(jwt) : false; - } - - static buildQueryParams(params: { [key: string]: string | number | undefined }): string { - return Object.keys(params) - .filter((key) => params[key] !== undefined) - .map((key) => `${key}=${encodeURIComponent(params[key] as string)}`) - .join('&'); - } - - static toBase64(file: File): Promise { - return new Promise((resolve, reject) => { - const reader = new FileReader(); - reader.readAsDataURL(file); - reader.onload = () => resolve(reader.result ? (reader.result as string) : undefined); - reader.onerror = (e) => reject(e); - }); - } -} +export { Utils } from '@dfx.swiss/core'; diff --git a/packages/react/src/validations.ts b/packages/react/src/validations.ts index 0e218d26..3d14dfca 100644 --- a/packages/react/src/validations.ts +++ b/packages/react/src/validations.ts @@ -1,86 +1,2 @@ -import * as IbanTools from 'ibantools'; -import BlockedIbans from './definitions/blocked-iban.json'; -import PhoneNumber from 'libphonenumber-js'; -import { Country } from './definitions/country'; - -const regex = { - Mail: /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/, -}; - -export type RequiredRule = { - required: { value: boolean; message: string }; -}; - -export type PatternRule = { - pattern: { value: RegExp; message: string }; -}; - -export type CustomRule = { - validate: (value: any) => string | true; -}; - -export type ValidationRule = RequiredRule | PatternRule | CustomRule; - -class ValidationsClass { - public get Required(): RequiredRule { - return { - required: { - value: true, - message: 'required', - }, - }; - } - - public get Mail(): PatternRule { - return { - pattern: { - value: regex.Mail, - message: 'pattern', - }, - }; - } - - public get Phone(): CustomRule { - return this.Custom((number: string) => { - try { - if (number) { - if (!number.match(/^\+\d/)) return 'code_and_number'; - if (!PhoneNumber(number)?.isValid()) return 'pattern'; - } - - return true; - } catch { - return 'pattern'; - } - }); - } - - public Iban(countries: Country[]): CustomRule { - return this.Custom((iban: string) => { - iban = iban.split(' ').join(''); - - // check country - const allowedCountries = countries.map((c) => c.symbol.toLowerCase()); - if (iban.length >= 2 && !allowedCountries.find((c) => iban.toLowerCase().startsWith(c))) { - return 'iban_country_blocked'; - } - - // check blocked IBANs - const blockedIbans = BlockedIbans.map((i) => i.split(' ').join('').toLowerCase()); - if (blockedIbans.some((i) => iban.toLowerCase().match(i) != null)) { - return 'iban_blocked'; - } - - return IbanTools.validateIBAN(iban).valid ? true : 'pattern'; - }); - } - - public Custom(validator: (value: any) => true | string): CustomRule { - return { - validate: validator, - }; - } -} - -const Validations = new ValidationsClass(); -export default Validations; +export { Validations as default } from '@dfx.swiss/core'; +export type { RequiredRule, PatternRule, CustomRule, ValidationRule } from '@dfx.swiss/core'; diff --git a/packages/react/tsconfig.build.json b/packages/react/tsconfig.build.json index 73794dfa..cdcbe0a6 100644 --- a/packages/react/tsconfig.build.json +++ b/packages/react/tsconfig.build.json @@ -5,5 +5,8 @@ "outDir": "./dist", "rootDir": "./src", "jsx": "react-jsx" - } + }, + "references": [ + { "path": "../core/tsconfig.build.json" } + ] }