import {z} from 'zod' export type TransactionOperation = 'TRANSFER' | 'BURN' | 'CONTRACT_CALL' | 'PROGRAM_CALL' | 'SOROBAN_CALL' | 'MINT' | 'RAW' | 'TYPED_MESSAGE' | 'APPROVE' | 'ENABLE_ASSET' | 'CANTON_CALL'; export type TransferPeerPathType = 'VAULT_ACCOUNT' | 'EXCHANGE_ACCOUNT' | 'CONNECTED_ACCOUNT' | 'INTERNAL_WALLET' | 'EXTERNAL_WALLET' | 'CONTRACT' | 'NETWORK_CONNECTION' | 'FIAT_ACCOUNT' | 'COMPOUND' | 'GAS_STATION' | 'ONE_TIME_ADDRESS' | 'UNKNOWN' | 'END_USER_WALLET' | 'PROGRAM_CALL' | 'MULTI_DESTINATION' | 'OEC_PARTNER' | 'WALLET_POOL' | 'SOROBAN_CONTRACT'; export type TransferPeerPathSubType = 'BINANCE' | 'BINANCEUS' | 'BITFINEX' | 'BITHUMB' | 'BITMEX' | 'BITSO' | 'BITSTAMP' | 'BITTREX' | 'BLINC' | 'BYBIT' | 'CIRCLE' | 'COINBASEEXCHANGE' | 'COINBASEPRO' | 'COINMETRO' | 'COINSPRO' | 'CRYPTOCOM' | 'DERIBIT' | 'GEMINI' | 'HITBTC' | 'HUOBI' | 'INDEPENDENTRESERVE' | 'KORBIT' | 'KRAKEN' | 'KRAKENINTL' | 'KUCOIN' | 'LIQUID' | 'OKCOIN' | 'OKEX' | 'PAXOS' | 'POLONIEX' | 'External' | 'Internal' | 'VIRTUAL_ACCOUNT'; export type SourceTransferPeerPath = {type: TransferPeerPathType, subType?: TransferPeerPathSubType | undefined, id?: string | undefined, name?: string | undefined, walletId?: string | undefined, isCollateral?: boolean | undefined}; export type OneTimeAddress = {address: string, tag?: string | undefined}; export type DestinationTransferPeerPath = {type: TransferPeerPathType, subType?: TransferPeerPathSubType | undefined, id?: string | undefined, name?: string | undefined, walletId?: string | undefined, oneTimeAddress?: OneTimeAddress | undefined, isCollateral?: boolean | undefined}; export type TransactionRequestDestination = {amount?: string | undefined, destination?: DestinationTransferPeerPath | undefined, travelRuleMessageId?: string | undefined, customerRefId?: string | undefined}; export type SorobanCallData = {envelopeXdr: string}; export type ExtraParameters = {nodeControls?: ({[key: string]: unknown} | unknown) | undefined, rawMessageData?: ({[key: string]: unknown} | unknown) | undefined, contractCallData?: (string | unknown) | undefined, programCallData?: (string | unknown) | undefined, sorobanCallData?: (SorobanCallData | unknown) | undefined, inputsSelection?: ({[key: string]: unknown} | unknown) | undefined, allowBaseAssetAddress?: (boolean | unknown) | undefined, piiData?: ({[key: string]: unknown} | unknown) | undefined} | {[key: string]: unknown}; export type UtxoSelectionFilters = {includeAllLabels?: Array | undefined, includeAnyLabels?: Array | undefined, excludeAnyLabels?: Array | undefined, address?: string | undefined, minAmount?: string | undefined, maxAmount?: string | undefined}; export type UtxoInput = {txHash: string, index: number}; export type UtxoInputSelection = {inputsToSpend?: Array | undefined, inputsToExclude?: Array | undefined, fillFeeForSelectedInputs?: boolean | undefined}; export type UtxoSelectionParams = {selectionStrategy?: ('AMOUNT_ASC' | 'AMOUNT_DESC') | undefined, filters?: UtxoSelectionFilters | undefined, inputSelection?: UtxoInputSelection | undefined}; export type TravelRuleTransactionBlockchainInfo = {txHash?: string | undefined, origin?: string | undefined, destination?: string | undefined}; export type TravelRuleNaturalNameIdentifier = {primaryIdentifier?: string | undefined, secondaryIdentifier?: string | undefined, nameIdentifierType?: string | undefined}; export type TravelRuleNaturalPersonNameIdentifier = {nameIdentifier?: Array | undefined, localNameIdentifier?: Array | undefined, phoneticNameIdentifier?: Array | undefined}; export type TravelRuleGeographicAddress = {streetName?: string | undefined, townName?: string | undefined, country?: string | undefined, buildingNumber?: string | undefined, postCode?: string | undefined, addressType?: string | undefined, department?: string | undefined, subDepartment?: string | undefined, buildingName?: string | undefined, floor?: string | undefined, postBox?: string | undefined, room?: string | undefined, townLocationName?: string | undefined, districtName?: string | undefined, countrySubDivision?: string | undefined, addressLine?: Array | undefined}; export type TravelRuleNationalIdentification = {countryOfIssue?: string | undefined, nationalIdentifier?: string | undefined, nationalIdentifierType?: string | undefined, registrationAuthority?: string | undefined}; export type TravelRuleDateAndPlaceOfBirth = {dateOfBirth?: string | undefined, placeOfBirth?: string | undefined}; export type TravelRuleNaturalPerson = {name?: Array | undefined, geographicAddress?: Array | undefined, nationalIdentification?: TravelRuleNationalIdentification | undefined, dateAndPlaceOfBirth?: TravelRuleDateAndPlaceOfBirth | undefined, customerIdentification?: string | undefined, countryOfResidence?: string | undefined, customerNumber?: string | undefined}; export type TravelRuleLegalNameIdentifier = {legalPersonName: string, legalPersonNameIdentifierType: string}; export type TravelRuleLegalPersonNameIdentifier = {nameIdentifier?: Array | undefined, localNameIdentifier?: Array | undefined, phoneticNameIdentifier?: Array | undefined}; export type TravelRuleLegalPerson = {name?: TravelRuleLegalPersonNameIdentifier | undefined, geographicAddress?: Array | undefined, nationalIdentification?: TravelRuleNationalIdentification | undefined, customerIdentification?: string | undefined, customerNumber?: string | undefined, countryOfRegistration?: string | undefined}; export type TravelRulePerson = {naturalPerson?: TravelRuleNaturalPerson | undefined, legalPerson?: TravelRuleLegalPerson | undefined}; export type TravelRulePiiIVMS = {originatorPersons?: Array | undefined, beneficiaryPersons?: Array | undefined, accountNumber?: Array | undefined}; export type TravelRuleOwnershipProof = {type?: string | undefined, proof?: string | undefined, attestation?: string | undefined, address?: string | undefined, wallet_provider?: string | undefined, url?: string | undefined, did?: string | undefined, status?: string | undefined, confirmed?: boolean | undefined}; export type TravelRuleCreateTransactionRequest = {originatorVASPdid?: string | undefined, beneficiaryVASPdid?: string | undefined, originatorVASPname?: string | undefined, beneficiaryVASPname?: string | undefined, beneficiaryVASPwebsite?: string | undefined, transactionBlockchainInfo?: TravelRuleTransactionBlockchainInfo | undefined, originator: TravelRulePiiIVMS, beneficiary: TravelRulePiiIVMS, encrypted?: string | undefined, protocol?: ('IVMS101' | 'TRLight' | 'TRP' | 'OpenVASP' | 'GTR') | undefined, targetProtocol?: string | undefined, skipBeneficiaryDataValidation?: boolean | undefined, travelRuleBehavior?: boolean | undefined, originatorRef?: string | undefined, beneficiaryRef?: string | undefined, travelRuleBehaviorRef?: string | undefined, originatorProof?: TravelRuleOwnershipProof | undefined, beneficiaryProof?: TravelRuleOwnershipProof | undefined, beneficiaryDid?: string | undefined, originatorDid?: string | undefined, isNonCustodial?: boolean | undefined}; export type TransactionConfigurations = {expiresAfterSeconds?: number | undefined}; export type TransactionRequest = {operation?: TransactionOperation | undefined, note?: string | undefined, externalTxId?: string | undefined, feeCurrency?: string | undefined, assetId?: string | undefined, source?: SourceTransferPeerPath | undefined, destination?: DestinationTransferPeerPath | undefined, destinations?: Array | undefined, amount?: (string | number) | undefined, treatAsGrossAmount?: boolean | undefined, forceSweep?: boolean | undefined, feeLevel?: ('LOW' | 'MEDIUM' | 'HIGH') | undefined, fee?: (string | number) | undefined, priorityFee?: (string | number) | undefined, failOnLowFee?: boolean | undefined, maxFee?: string | undefined, maxTotalFee?: string | undefined, gasLimit?: (string | number) | undefined, gasPrice?: (string | number) | undefined, networkFee?: (string | number) | undefined, replaceTxByHash?: string | undefined, extraParameters?: ExtraParameters | undefined, utxoSelectionParams?: UtxoSelectionParams | undefined, customerRefId?: string | undefined, travelRuleMessage?: TravelRuleCreateTransactionRequest | undefined, travelRuleMessageId?: string | undefined, autoStaking?: boolean | undefined, networkStaking?: (string | number) | undefined, cpuStaking?: (string | number) | undefined, useGasless?: boolean | undefined, configurations?: TransactionConfigurations | undefined}; export type CreateApiTransactionsArgs = {'X-End-User-Wallet-Id'?: string | undefined, 'Idempotency-Key'?: string | undefined, body: TransactionRequest}; export type CreateApiTransactionsOptions = {baseUrl?: string | undefined, fetch?: typeof fetch | undefined}; export const systemMessageInfo = z.object({type: z.enum(["WARN", "BLOCK"]).optional(), message: z.string().optional()}); export const createTransactionResponse = z.object({id: z.string().optional(), status: z.string().optional(), systemMessages: z.array(systemMessageInfo).optional()}); export const validateResponse = async ( schema: { readonly '~standard': { readonly validate: (value: unknown) => ({ readonly value: Output; readonly issues?: undefined } | { readonly issues: ReadonlyArray<{ readonly message: string; readonly path?: ReadonlyArray | undefined }> }) | Promise<{ readonly value: Output; readonly issues?: undefined } | { readonly issues: ReadonlyArray<{ readonly message: string; readonly path?: ReadonlyArray | undefined }> }> } }, value: unknown ): Promise => { const result = await schema['~standard'].validate(value) if (result.issues !== undefined) { const detail = result.issues .map(({ message, path }) => path?.length ? `${path.map((segment) => String(typeof segment === 'object' ? segment.key : segment)).join('.')}: ${message}` : message ) .join('; ') throw new Error(`Response does not match the schema: ${detail}`, { cause: { issues: result.issues } }) } return result.value }; /** * Create a new transaction * * POST /transactions */ export const createApiTransactions = async (args: CreateApiTransactionsArgs, options?: CreateApiTransactionsOptions) => { const {baseUrl = "https://api.fireblocks.io/v1", fetch: fetchFn = fetch} = options ?? {} const query = new URLSearchParams() const headers = new Headers() headers.set('content-type', "application/json") headers.set('accept', "application/json") if (args['X-End-User-Wallet-Id'] != null) headers.set("X-End-User-Wallet-Id", String(args['X-End-User-Wallet-Id'])) if (args['Idempotency-Key'] != null) headers.set("Idempotency-Key", String(args['Idempotency-Key'])) const url = `${baseUrl.replace(/\/+$/, '')}/transactions${query.size > 0 ? `?${query}` : ''}` const res = await fetchFn(url, {method: "POST", headers, body: JSON.stringify(args.body)}) if (!res.ok) throw new Error(`Request failed with status ${res.status}`, {cause: {status: res.status, body: await res.text()}}) return validateResponse(createTransactionResponse, await res.json()) };