New Case Study:See how Anthropic automated 95% of dependency reviews with Socket.Learn More
Socket
Sign inDemoInstall
Socket

@nimiq/fastspot-api

Package Overview
Dependencies
Maintainers
8
Versions
26
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

@nimiq/fastspot-api - npm Package Compare versions

Comparing version 1.9.0 to 2.0.0-beta.0

34

dist/api.d.ts

@@ -1,32 +0,8 @@

import { RequestAsset, SwapAsset, Estimate, PreSwap, ContractWithEstimate, Swap, Limits, UserLimits, AssetList, ReferralCodes } from './types';
import { RequestAsset, RequestAssetWithAmount, AssetId, Quote, Swap } from './types';
export declare function init(url: string, key: string, options?: Partial<{
referral?: ReferralCodes;
customFetch?: typeof fetch;
}>): void;
export declare function getEstimate(from: RequestAsset<SwapAsset>, to: SwapAsset): Promise<Estimate>;
export declare function getEstimate(from: SwapAsset, to: RequestAsset<SwapAsset>): Promise<Estimate>;
export declare function createSwap(from: RequestAsset<SwapAsset>, to: SwapAsset): Promise<PreSwap>;
export declare function createSwap(from: SwapAsset, to: RequestAsset<SwapAsset>): Promise<PreSwap>;
export declare function confirmSwap(swap: PreSwap, redeem: {
asset: SwapAsset.NIM | SwapAsset.BTC | SwapAsset.USDC | SwapAsset.USDC_MATIC;
address: string;
} | {
asset: SwapAsset.EUR;
kty: string;
crv: string;
x: string;
y?: string;
} | {
asset: SwapAsset.BTC_LN;
}, refund?: {
asset: SwapAsset.NIM | SwapAsset.BTC | SwapAsset.USDC | SwapAsset.USDC_MATIC;
address: string;
} | {
asset: SwapAsset.EUR;
}, uid?: string, kycToken?: string, oasisPrepareToken?: string): Promise<Swap>;
export declare function getSwap(id: string): Promise<PreSwap | Swap>;
export declare function cancelSwap(swap: PreSwap): Promise<PreSwap>;
export declare function getContract<T extends SwapAsset>(asset: T, address: string): Promise<ContractWithEstimate<T>>;
export declare function getLimits<T extends SwapAsset>(asset: T, address: string, kycUid?: string): Promise<Limits<T>>;
export declare function getUserLimits(uid: string, kycUid?: string): Promise<UserLimits>;
export declare function getAssets(): Promise<AssetList>;
export declare function createSwap(sell: RequestAsset<AssetId>, buy: RequestAssetWithAmount<AssetId>): Promise<Quote>;
export declare function createSwap(sell: RequestAssetWithAmount<AssetId>, buy: RequestAsset<AssetId>): Promise<Quote>;
export declare function provideFundingProof(swapId: string, contractId: string, proof: string): Promise<Swap>;
export declare function getSwap(id: string): Promise<Quote | Swap>;

305

dist/api.js

@@ -1,16 +0,14 @@

var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
import { SwapAsset, } from './types';
import { validateRequestPairs, convertFromData, convertToData, convertContract, convertSwap, convertLimits, convertUserLimits, coinsToUnits, } from './helpers';
import { validateRequestPairs,
// convertFromData,
// convertToData,
// convertContract,
convertSwap,
// convertLimits,
// convertUserLimits,
// coinsToUnits,
} from './helpers';
let API_URL;
let API_KEY;
let REFERRAL;
let FETCH;
// let REFERRAL: ReferralCodes | undefined;
export function init(url, key, options) {

@@ -21,153 +19,148 @@ if (!url || !key)

API_KEY = key;
REFERRAL = options === null || options === void 0 ? void 0 : options.referral;
FETCH = (options === null || options === void 0 ? void 0 : options.customFetch) || fetch;
// REFERRAL = referral;
}
function api(path, method, options) {
return __awaiter(this, void 0, void 0, function* () {
if (!API_URL || !API_KEY)
throw new Error('API URL and key not set, call init() first');
const response = yield FETCH(`${API_URL}${path}`, Object.assign({ method, headers: Object.assign({ 'Content-Type': 'application/json', 'X-FAST-ApiKey': API_KEY }, options === null || options === void 0 ? void 0 : options.headers) }, ((options === null || options === void 0 ? void 0 : options.body) ? { body: JSON.stringify(options.body) } : {})));
if (!response.ok) {
const error = yield response.json();
throw new Error(error.detail);
}
return response.json();
});
async function api(path, method, options) {
if (!API_URL || !API_KEY)
throw new Error('API URL and key not set, call init() first');
const response = await FETCH(`${API_URL}${path}`, Object.assign({ method, headers: Object.assign({ 'Content-Type': 'application/json', 'X-FAST-ApiKey': API_KEY }, options === null || options === void 0 ? void 0 : options.headers) }, ((options === null || options === void 0 ? void 0 : options.body) ? { body: JSON.stringify(options.body) } : {})));
if (!response.ok) {
const error = await response.json();
throw new Error(error.detail);
}
return response.json();
}
export function getEstimate(from, to) {
return __awaiter(this, void 0, void 0, function* () {
validateRequestPairs(from, to);
const result = yield api('/estimates', 'POST', {
body: {
from,
to,
includedFees: 'required',
},
});
const inputObject = result[0].from[0];
const outputObject = result[0].to[0];
if (!inputObject || !outputObject)
throw new Error('Insufficient market liquidity');
const estimate = {
from: convertFromData(inputObject),
to: convertToData(outputObject),
serviceFeePercentage: parseFloat(result[0].serviceFeePercentage),
direction: result[0].direction,
};
return estimate;
export async function createSwap(sell, buy) {
validateRequestPairs(sell, buy);
const headers = {};
// if (REFERRAL) {
// headers['X-S3-Partner-Code'] = REFERRAL.partnerCode;
// if (REFERRAL.refCode) headers['X-S3-Ref-Code'] = REFERRAL.refCode;
// }
const result = await api('/swap/create', 'POST', {
headers,
body: {
sell: [sell],
buy: [buy],
},
});
return convertSwap(result);
}
export function createSwap(from, to) {
return __awaiter(this, void 0, void 0, function* () {
validateRequestPairs(from, to);
const headers = {};
if (REFERRAL) {
headers['X-S3-Partner-Code'] = REFERRAL.partnerCode;
if (REFERRAL.refCode)
headers['X-S3-Ref-Code'] = REFERRAL.refCode;
}
const result = yield api('/swaps', 'POST', {
headers,
body: {
from,
to,
includedFees: 'required',
},
});
return convertSwap(result);
// export async function confirmSwap(
// swap: PreSwap,
// redeem: {
// asset: SwapAsset.NIM | SwapAsset.BTC | SwapAsset.USDC | SwapAsset.USDC_MATIC,
// address: string,
// } | {
// asset: SwapAsset.EUR,
// kty: string,
// crv: string,
// x: string,
// y?: string,
// },
// refund?: {
// asset: SwapAsset.NIM | SwapAsset.BTC | SwapAsset.USDC | SwapAsset.USDC_MATIC,
// address: string,
// } | {
// asset: SwapAsset.EUR,
// },
// uid?: string,
// kycToken?: string,
// oasisPrepareToken?: string,
// ): Promise<Swap> {
// const headers: Record<string, string> = {};
// if (kycToken) {
// if (!uid) throw new Error('UID is required when using kycToken');
// headers['X-S3-KYC-Token'] = kycToken;
// headers['X-S3-KYC-UID'] = uid;
// if (oasisPrepareToken) {
// headers['X-OASIS-Prepare-Token'] = oasisPrepareToken;
// }
// }
// const result = await api(`/swaps/${swap.id}`, 'POST', {
// headers,
// body: {
// confirm: true,
// beneficiary: redeem.asset === SwapAsset.EUR
// ? { [redeem.asset]: {
// kty: redeem.kty,
// crv: redeem.crv,
// x: redeem.x,
// ...(redeem.y ? { y: redeem.y } : {}),
// } }
// : { [redeem.asset]: redeem.address },
// ...(refund ? { refund: { [refund.asset]: 'address' in refund ? refund.address : '' } } : {}),
// ...(uid ? { uid } : {}),
// },
// }) as FastspotSwap;
// return convertSwap(result);
// }
export async function provideFundingProof(swapId, contractId, proof) {
const result = await api(`/swap/${swapId}`, 'PATCH', {
body: {
contracts: [{
id: contractId,
proof,
}],
},
});
return convertSwap(result);
}
export function confirmSwap(swap, redeem, refund, uid, kycToken, oasisPrepareToken) {
return __awaiter(this, void 0, void 0, function* () {
const headers = {};
if (kycToken) {
if (!uid)
throw new Error('UID is required when using kycToken');
headers['X-S3-KYC-Token'] = kycToken;
headers['X-S3-KYC-UID'] = uid;
if (oasisPrepareToken) {
headers['X-OASIS-Prepare-Token'] = oasisPrepareToken;
}
}
const result = yield api(`/swaps/${swap.id}`, 'POST', {
headers,
body: Object.assign(Object.assign({ confirm: true, beneficiary: redeem.asset === SwapAsset.EUR
? { [redeem.asset]: Object.assign({ kty: redeem.kty, crv: redeem.crv, x: redeem.x }, (redeem.y ? { y: redeem.y } : {})) }
: redeem.asset === SwapAsset.BTC_LN
? {}
: { [redeem.asset]: redeem.address } }, (refund ? { refund: { [refund.asset]: 'address' in refund ? refund.address : '' } } : {})), (uid ? { uid } : {})),
});
return convertSwap(result);
});
export async function getSwap(id) {
const result = await api(`/swap/${id}`, 'GET');
return convertSwap(result);
}
export function getSwap(id) {
return __awaiter(this, void 0, void 0, function* () {
const result = yield api(`/swaps/${id}`, 'GET');
return convertSwap(result);
});
}
export function cancelSwap(swap) {
return __awaiter(this, void 0, void 0, function* () {
const result = yield api(`/swaps/${swap.id}`, 'DELETE');
return convertSwap(result);
});
}
export function getContract(asset, address) {
return __awaiter(this, void 0, void 0, function* () {
const result = yield api(`/contracts/${asset}/${address}`, 'GET');
return {
contract: convertContract(result.contract),
from: convertFromData(result.info.from[0]),
to: convertToData(result.info.to[0]),
serviceFeePercentage: parseFloat(result.info.serviceFeePercentage),
direction: result.info.direction,
};
});
}
export function getLimits(asset, address, kycUid) {
return __awaiter(this, void 0, void 0, function* () {
const headers = {};
if (kycUid) {
headers['X-S3-KYC-UID'] = kycUid;
}
const result = yield api(`/limits/${asset}/${address}`, 'GET', { headers });
return convertLimits(result);
});
}
export function getUserLimits(uid, kycUid) {
return __awaiter(this, void 0, void 0, function* () {
const headers = {};
if (kycUid) {
headers['X-S3-KYC-UID'] = kycUid;
}
const result = yield api(`/limits/${uid}`, 'GET', { headers });
return convertUserLimits(result);
});
}
export function getAssets() {
return __awaiter(this, void 0, void 0, function* () {
const result = yield api('/assets', 'GET');
const records = {};
for (const record of result) {
try {
records[record.symbol] = {
asset: record.symbol,
name: record.name,
feePerUnit: coinsToUnits(record.symbol, record.feePerUnit, { treatUsdcAsMatic: true }),
limits: {
minimum: record.limits && record.limits.minimum
? coinsToUnits(record.symbol, record.limits.minimum)
: undefined,
maximum: record.limits && record.limits.maximum
? coinsToUnits(record.symbol, record.limits.maximum)
: undefined,
},
};
}
catch (error) {
console.warn(error.message, record); // eslint-disable-line no-console
}
}
return records;
});
}
// export async function cancelSwap(swap: PreSwap): Promise<PreSwap> {
// const result = await api(`/swaps/${swap.id}`, 'DELETE') as FastspotPreSwap;
// return convertSwap(result);
// }
// export async function getContract<T extends SwapAsset>(asset: T, address: string): Promise<ContractWithEstimate<T>> {
// const result = await api(`/contracts/${asset}/${address}`, 'GET') as FastspotContractWithEstimate<T>;
// return {
// contract: convertContract(result.contract),
// from: convertFromData(result.info.from[0]),
// to: convertToData(result.info.to[0]),
// serviceFeePercentage: parseFloat(result.info.serviceFeePercentage as string),
// direction: result.info.direction,
// };
// }
// export async function getLimits<T extends SwapAsset>(asset: T, address: string, kycUid?: string): Promise<Limits<T>> {
// const headers: Record<string, string> = {};
// if (kycUid) {
// headers['X-S3-KYC-UID'] = kycUid;
// }
// const result = await api(`/limits/${asset}/${address}`, 'GET', { headers }) as FastspotLimits<T>;
// return convertLimits(result);
// }
// export async function getUserLimits(uid: string, kycUid?: string): Promise<UserLimits> {
// const headers: Record<string, string> = {};
// if (kycUid) {
// headers['X-S3-KYC-UID'] = kycUid;
// }
// const result = await api(`/limits/${uid}`, 'GET', { headers }) as FastspotUserLimits;
// return convertUserLimits(result);
// }
// export async function getAssets(): Promise<AssetList> {
// const result = await api('/assets', 'GET') as FastspotAsset[];
// const records: Partial<AssetList> = {};
// for (const record of result) {
// try {
// records[record.symbol] = {
// asset: record.symbol,
// name: record.name,
// feePerUnit: coinsToUnits(record.symbol, record.feePerUnit, { treatUsdcAsMatic: true }),
// limits: {
// minimum: record.limits && record.limits.minimum
// ? coinsToUnits(record.symbol, record.limits.minimum)
// : undefined,
// maximum: record.limits && record.limits.maximum
// ? coinsToUnits(record.symbol, record.limits.maximum)
// : undefined,
// },
// };
// } catch (error: any) {
// console.warn(error.message, record); // eslint-disable-line no-console
// }
// }
// return records as AssetList;
// }

@@ -1,13 +0,12 @@

import { RequestAsset, SwapAsset, ReferenceAsset, PriceData, FastspotPrice, FastspotContract, FastspotPreSwap, FastspotSwap, FastspotLimits, FastspotUserLimits, Contract, PreSwap, Swap, Limits, UserLimits } from './types';
export declare function coinsToUnits(asset: SwapAsset | ReferenceAsset, value: string | number, options?: Partial<{
roundUp: boolean;
treatUsdcAsMatic: boolean;
}>): number;
export declare function convertFromData(from: FastspotPrice): PriceData;
export declare function convertToData(to: FastspotPrice): PriceData;
export declare function convertContract<T extends SwapAsset>(contract: FastspotContract<T>): Contract<T>;
import { RequestAsset, RequestAssetWithAmount, AssetId, Ticker, ReferenceAsset, FastspotQuote, FastspotSwap, Quote, Swap } from './types';
export declare function coinsToUnits(asset: Ticker | ReferenceAsset, value: string | number): number;
export declare function convertSellBuyData(data: {
asset: AssetId;
amount: string;
}): {
asset: AssetId;
amount: number;
};
export declare function convertSwap(swap: FastspotSwap): Swap;
export declare function convertSwap(swap: FastspotPreSwap): PreSwap;
export declare function convertLimits<T extends SwapAsset>(limits: FastspotLimits<T>): Limits<T>;
export declare function convertUserLimits(limits: FastspotUserLimits): UserLimits;
export declare function validateRequestPairs(from: SwapAsset | RequestAsset<SwapAsset>, to: SwapAsset | RequestAsset<SwapAsset>): boolean;
export declare function convertSwap(swap: FastspotQuote): Quote;
export declare function validateRequestPairs(sell: RequestAsset<AssetId> | RequestAssetWithAmount<AssetId>, buy: RequestAsset<AssetId> | RequestAssetWithAmount<AssetId>): boolean;

@@ -1,167 +0,107 @@

import { SwapAsset, Precision, } from './types';
export function coinsToUnits(asset, value, options = {}) {
import { AssetId, Ticker, Precision,
// Limits,
// UserLimits,
// HtlcDetails,
} from './types';
export function coinsToUnits(asset, value) {
let decimals = Precision[asset];
// Some fees for USDC are provided in MATIC, and must be converted accordingly
if ((asset === SwapAsset.USDC || asset === SwapAsset.USDC_MATIC) && options.treatUsdcAsMatic)
decimals = 18;
if (typeof decimals === 'undefined')
throw new Error(`Invalid asset ${asset}`);
const parts = value.toString().split('.');
parts[1] = (parts[1] || '').substring(0, decimals + 1).padEnd(decimals + 1, '0');
const units = parseInt(parts.join(''), 10) / 10;
if (options.roundUp) {
return Math.ceil(units);
if (typeof value === 'number') {
return value * Math.pow(10, decimals);
}
return Math.floor(units);
// Move the decimal point before parsing to number, to reduce inaccuracy due to floating point precision
const [coins, units] = value.split('.');
value = `${coins}${units.substring(0, decimals).padEnd(decimals, '0')}.${units.substring(decimals)}`;
return parseFloat(value);
}
export function convertFromData(from) {
const asset = from.symbol;
return Object.assign(Object.assign({ asset, amount: coinsToUnits(asset, from.amount), fee: coinsToUnits(asset, from.fundingNetworkFee.total, { roundUp: true }) }, (from.fundingNetworkFee.perUnit ? {
feePerUnit: coinsToUnits(asset, from.fundingNetworkFee.perUnit, { roundUp: true, treatUsdcAsMatic: true }),
} : {})), { serviceNetworkFee: coinsToUnits(asset, from.finalizeNetworkFee.total, { roundUp: true }), serviceEscrowFee: coinsToUnits(asset, from.operatingNetworkFee.total, { roundUp: true }) });
function assetToTicker(asset) {
switch (asset) {
case AssetId.NIM: return Ticker.NIM;
case AssetId.BTC: return Ticker.BTC;
case AssetId.BTC_LN: return Ticker.BTC;
case AssetId.USDC_MATIC: return Ticker.USDC;
case AssetId.EUR: return Ticker.EUR;
}
}
export function convertToData(to) {
const asset = to.symbol;
return Object.assign(Object.assign({ asset, amount: coinsToUnits(asset, to.amount), fee: coinsToUnits(asset, to.finalizeNetworkFee.total, { roundUp: true }) }, (to.finalizeNetworkFee.perUnit ? {
feePerUnit: coinsToUnits(asset, to.finalizeNetworkFee.perUnit, { roundUp: true, treatUsdcAsMatic: true }),
} : {})), { serviceNetworkFee: coinsToUnits(asset, to.fundingNetworkFee.total, { roundUp: true }), serviceEscrowFee: coinsToUnits(asset, to.operatingNetworkFee.total, { roundUp: true }) });
}
export function convertContract(contract) {
var _a;
let htlc;
switch (contract.asset) {
case SwapAsset.NIM:
htlc = Object.assign({}, contract.intermediary);
break;
case SwapAsset.BTC:
htlc = {
address: contract.intermediary.p2wsh,
script: contract.intermediary.scriptBytes,
};
break;
case SwapAsset.BTC_LN:
htlc = {
nodeId: contract.intermediary.nodeId,
};
break;
case SwapAsset.USDC:
case SwapAsset.USDC_MATIC:
htlc = {
address: contract.id.substring(0, 2) === '0x' ? contract.id : `0x${contract.id}`,
contract: contract.intermediary.address,
data: contract.intermediary.data,
};
break;
case SwapAsset.EUR:
htlc = {
address: contract.intermediary.contractId || contract.id,
// TODO: Parse clearing instructions if provided
};
break;
default: throw new Error(`Invalid asset ${contract.asset}`);
}
export function convertSellBuyData(data) {
const asset = data.asset;
return {
id: contract.id,
asset: contract.asset,
refundAddress: ((_a = contract.refund) === null || _a === void 0 ? void 0 : _a.address) || '',
redeemAddress: contract.asset === SwapAsset.EUR
? JSON.stringify(contract.recipient)
: contract.recipient.address,
amount: coinsToUnits(contract.asset, contract.amount),
timeout: contract.timeout,
direction: contract.direction,
status: contract.status,
htlc,
asset,
amount: coinsToUnits(assetToTicker(asset), data.amount),
};
}
export function convertSwap(swap) {
const inputObject = swap.info.from[0];
const outputObject = swap.info.to[0];
const preSwap = {
const inputObject = swap.sell[0];
const outputObject = swap.buy[0];
const quote = {
id: swap.id,
expires: Math.floor(swap.expires),
from: convertFromData(inputObject),
to: convertToData(outputObject),
sell: convertSellBuyData(inputObject),
buy: convertSellBuyData(outputObject),
status: swap.status,
serviceFeePercentage: parseFloat(swap.info.serviceFeePercentage),
direction: swap.info.direction,
fees: swap.fees.map((fee) => (Object.assign(Object.assign({}, fee), { amount: coinsToUnits(fee.asset, fee.amount) }))),
expiry: Math.floor(swap.expiry), // `result.expiry` can be a float timestamp
};
if ('contracts' in swap) {
const contracts = {};
for (const contract of swap.contracts) {
contracts[contract.asset] = convertContract(contract);
}
const fullSwap = Object.assign(Object.assign(Object.assign(Object.assign({}, preSwap), { hash: swap.hash }), (swap.secret ? { secret: swap.secret } : {})), { contracts });
// const contracts: Partial<Record<SwapAsset, Contract<SwapAsset>>> = {};
// for (const contract of swap.contracts) {
// contracts[contract.asset] = convertContract(contract);
// }
const fullSwap = Object.assign(Object.assign(Object.assign(Object.assign({}, quote), { hash: swap.hash }), (swap.preimage ? { preimage: swap.preimage } : {})), { contracts: swap.contracts });
return fullSwap;
}
return preSwap;
return quote;
}
export function convertLimits(limits) {
return {
asset: limits.asset,
daily: coinsToUnits(limits.asset, limits.daily),
dailyRemaining: coinsToUnits(limits.asset, limits.dailyRemaining),
monthly: coinsToUnits(limits.asset, limits.monthly),
monthlyRemaining: coinsToUnits(limits.asset, limits.monthlyRemaining),
perSwap: coinsToUnits(limits.asset, limits.swap),
current: coinsToUnits(limits.asset, limits.current),
reference: {
asset: limits.referenceAsset,
daily: coinsToUnits(limits.referenceAsset, limits.referenceDaily),
dailyRemaining: coinsToUnits(limits.referenceAsset, limits.referenceDailyRemaining),
monthly: coinsToUnits(limits.referenceAsset, limits.referenceMonthly),
monthlyRemaining: coinsToUnits(limits.referenceAsset, limits.referenceMonthlyRemaining),
perSwap: coinsToUnits(limits.referenceAsset, limits.referenceSwap),
current: coinsToUnits(limits.referenceAsset, limits.referenceCurrent),
},
};
}
export function convertUserLimits(limits) {
return {
asset: limits.asset,
daily: coinsToUnits(limits.asset, limits.daily),
dailyRemaining: coinsToUnits(limits.asset, limits.dailyRemaining),
monthly: coinsToUnits(limits.asset, limits.monthly),
monthlyRemaining: coinsToUnits(limits.asset, limits.monthlyRemaining),
perSwap: coinsToUnits(limits.asset, limits.swap),
current: coinsToUnits(limits.asset, limits.current),
};
}
export function validateRequestPairs(from, to) {
let fromAsset;
let toAsset;
if (typeof from === 'string') {
if (!Object.values(SwapAsset).includes(from)) {
throw new Error('Invalid FROM asset');
}
fromAsset = from;
// export function convertLimits<T extends SwapAsset>(limits: FastspotLimits<T>): Limits<T> {
// return {
// asset: limits.asset,
// daily: coinsToUnits(limits.asset, limits.daily),
// dailyRemaining: coinsToUnits(limits.asset, limits.dailyRemaining),
// monthly: coinsToUnits(limits.asset, limits.monthly),
// monthlyRemaining: coinsToUnits(limits.asset, limits.monthlyRemaining),
// perSwap: coinsToUnits(limits.asset, limits.swap),
// current: coinsToUnits(limits.asset, limits.current),
// reference: {
// asset: limits.referenceAsset,
// daily: coinsToUnits(limits.referenceAsset, limits.referenceDaily),
// dailyRemaining: coinsToUnits(limits.referenceAsset, limits.referenceDailyRemaining),
// monthly: coinsToUnits(limits.referenceAsset, limits.referenceMonthly),
// monthlyRemaining: coinsToUnits(limits.referenceAsset, limits.referenceMonthlyRemaining),
// perSwap: coinsToUnits(limits.referenceAsset, limits.referenceSwap),
// current: coinsToUnits(limits.referenceAsset, limits.referenceCurrent),
// },
// };
// }
// export function convertUserLimits(limits: FastspotUserLimits): UserLimits {
// return {
// asset: limits.asset,
// daily: coinsToUnits(limits.asset, limits.daily),
// dailyRemaining: coinsToUnits(limits.asset, limits.dailyRemaining),
// monthly: coinsToUnits(limits.asset, limits.monthly),
// monthlyRemaining: coinsToUnits(limits.asset, limits.monthlyRemaining),
// perSwap: coinsToUnits(limits.asset, limits.swap),
// current: coinsToUnits(limits.asset, limits.current),
// };
// }
export function validateRequestPairs(sell, buy) {
if (!Object.values(AssetId).includes(sell.asset)) {
throw new Error('Unknown SELL asset');
}
else {
if (Object.keys(from).length !== 1) {
throw new Error('Only one asset allowed for FROM');
}
if (!Object.values(SwapAsset).includes(Object.keys(from)[0])) {
throw new Error('Invalid FROM asset');
}
fromAsset = Object.keys(from)[0];
if (!Object.values(AssetId).includes(buy.asset)) {
throw new Error('Unknown BUY asset');
}
if (typeof to === 'string') {
if (!Object.values(SwapAsset).includes(to)) {
throw new Error('Invalid TO asset');
}
toAsset = to;
if (sell.asset === buy.asset) {
throw new Error('SELL and BUY assets must be different');
}
else {
if (Object.keys(to).length !== 1) {
throw new Error('Only one asset allowed for TO');
}
if (!Object.values(SwapAsset).includes(Object.keys(to)[0])) {
throw new Error('Invalid TO asset');
}
toAsset = Object.keys(to)[0];
if ((sell.asset === AssetId.BTC_LN && !sell.peer)
|| (buy.asset === AssetId.BTC_LN && !buy.peer)) {
throw new Error('For BTC_LN, peer is required');
}
if (fromAsset === toAsset) {
throw new Error('FROM and TO assets must be different');
if ('amount' in sell && 'amount' in buy) {
throw new Error('Only one side, either SELL or BUY, can have an amount');
}
if (!('amount' in sell) && !('amount' in buy)) {
throw new Error('One side, either SELL or BUY, must have an amount');
}
return true;
}

@@ -1,6 +0,18 @@

export declare enum SwapAsset {
export declare enum Asset {
NIM = "NIM",
BTC = "BTC",
USD = "USD",
EUR = "EUR"
}
export declare enum Ticker {
NIM = "NIM",
BTC = "BTC",
USDC = "USDC",
EUR = "EUR"
}
/** @deprecated */
export declare enum AssetId {
NIM = "NIM",
BTC = "BTC",
BTC_LN = "BTC_LN",
USDC = "USDC",
USDC_MATIC = "USDC_MATIC",

@@ -12,12 +24,6 @@ EUR = "EUR"

}
export declare type ReferralCodes = {
partnerCode: string;
refCode?: string;
};
export declare const Precision: {
readonly NIM: 5;
readonly BTC: 8;
readonly BTC_LN: 8;
readonly USDC: 6;
readonly USDC_MATIC: 6;
readonly EUR: 2;

@@ -27,65 +33,70 @@ readonly USD: 2;

export declare enum SwapStatus {
WAITING_FOR_CONFIRMATION = "waiting-for-confirmation",
WAITING_FOR_TRANSACTIONS = "waiting-for-transactions",
WAITING_FOR_REDEMPTION = "waiting-for-redemption",
FINISHED = "finished",
/** @deprecated */
EXPIRED_PENDING_CONFIRMATIONS = "expired-pending-confirmation",
EXPIRED_PENDING_CONFIRMATION = "expired-pending-confirmation",
EXPIRED_PENDING_TRANSACTIONS = "expired-pending-transactions",
CANCELLED = "cancelled",
INVALID = "invalid"
PENDING_CONFIRMATION = "PENDING_CONFIRMATION",
PENDING_DEPOSIT = "PENDING_DEPOSIT",
FINISHED = "FINISHED",
EXPIRED = "EXPIRED"
}
export declare enum ContractStatus {
PENDING = "pending",
FUNDED = "funded",
TIMEOUT_REACHED = "timeout-reached",
REFUNDED = "refunded",
REDEEMED = "redeemed"
PENDING = "PENDING",
REDEEMED = "REDEEMED"
}
export declare type FastspotAsset = {
symbol: SwapAsset;
type FastspotBaseNetwork = {
name: string;
feePerUnit: string;
limits?: {
minimum: string | null;
maximum: string | null;
};
software?: {
};
type FastspotLayer2Network = FastspotBaseNetwork & {
parent: {
name: string;
version: string | null;
network: 'test' | 'main';
syncBlockHeight: number;
};
provider?: {
url: string;
company: string | null;
engine: 'mock';
};
};
export declare type FastspotFee = {
perUnit?: string;
total: string;
totalIsIncluded: boolean;
type FastspotTokenNetwork = FastspotBaseNetwork & {
nativeAsset: string;
chainId: string;
};
export declare type FastspotPrice = {
symbol: SwapAsset;
type FastspotNetwork = FastspotBaseNetwork | FastspotLayer2Network | FastspotTokenNetwork;
export type FastspotAsset = {
/** @deprecated */
id: string;
ticker: Ticker;
network: FastspotNetwork;
decimals: number;
name: string;
asset: {
ticker: Asset;
name: string;
decimals: number;
};
alternativeIds: string[];
v1Symbol: string;
} & ({
contract: string;
htlc: string;
} | {});
declare enum FastspotFeeSource {
NETWORK = "NETWORK",
SERVICE = "SERVICE"
}
declare enum FastspotFeeType {
DEPOSIT_TRANSACTION = "DEPOSIT_TRANSACTION",
REDEMPTION_TRANSACTION = "REDEMPTION_TRANSACTION",
REFUND_TRANSACTION = "REFUND_TRANSACTION",
EXECUTION = "EXECUTION"
}
export type FastspotFee = {
asset: Ticker;
network: string;
amount: string;
fundingNetworkFee: FastspotFee;
operatingNetworkFee: FastspotFee;
finalizeNetworkFee: FastspotFee;
included: boolean;
source: FastspotFeeSource;
type: FastspotFeeType;
reason?: string;
};
export declare type FastspotEstimate = {
from: FastspotPrice[];
to: FastspotPrice[];
serviceFeePercentage: string | number;
direction: 'forward' | 'reverse';
};
export declare type FastspotContract<T extends SwapAsset> = {
export type FastspotContract<T extends AssetId> = {
id: string;
asset: T;
refund?: {
amount: string;
status: ContractStatus;
refundTarget: string | {
address: string;
} | null;
recipient: T extends SwapAsset.EUR ? {
recipient: string | (T extends AssetId.EUR ? {
kty: string;

@@ -97,70 +108,28 @@ crv: string;

address: string;
};
amount: number;
timeout: number;
direction: 'send' | 'receive';
status: ContractStatus;
}) | null;
expiry: number;
data: null;
};
export type FastspotQuote = {
id: string;
intermediary: T extends SwapAsset.NIM ? {
address: string;
timeoutBlock: number;
data: string;
} : T extends SwapAsset.BTC ? {
p2sh: string;
p2wsh: string;
scriptBytes: string;
} : T extends SwapAsset.BTC_LN ? {
nodeId: string;
status: SwapStatus;
sell: {
asset: AssetId;
amount: string;
hash: string;
request: string;
} : T extends SwapAsset.USDC | SwapAsset.USDC_MATIC ? {
address: string;
data?: string;
} : T extends SwapAsset.EUR ? {
contractId?: string;
} : never;
}[];
buy: {
asset: AssetId;
amount: string;
}[];
fees: FastspotFee[];
expiry: number;
};
export declare type FastspotContractWithEstimate<T extends SwapAsset> = {
contract: FastspotContract<T>;
info: FastspotEstimate;
};
export declare type FastspotPreSwap = {
id: string;
export type FastspotSwap = Omit<FastspotQuote, 'status'> & {
status: SwapStatus;
expires: number;
info: FastspotEstimate;
};
export declare type FastspotSwap = FastspotPreSwap & {
hash: string;
secret?: string;
contracts: FastspotContract<SwapAsset>[];
preimage?: string;
contracts: FastspotContract<AssetId>[];
};
export declare type FastspotLimits<T extends SwapAsset> = {
asset: T;
daily: string;
dailyRemaining: string;
monthly: string;
monthlyRemaining: string;
swap: string;
current: string;
referenceAsset: ReferenceAsset;
referenceDaily: string;
referenceDailyRemaining: string;
referenceMonthly: string;
referenceMonthlyRemaining: string;
referenceSwap: string;
referenceCurrent: string;
};
export declare type FastspotUserLimits = {
asset: ReferenceAsset;
daily: string;
dailyRemaining: string;
monthly: string;
monthlyRemaining: string;
swap: string;
current: string;
};
export declare type FastspotResult = FastspotAsset[] | FastspotEstimate[] | FastspotSwap | FastspotContractWithEstimate<SwapAsset> | FastspotLimits<SwapAsset> | FastspotUserLimits;
export declare type FastspotError = {
export type FastspotResult = FastspotAsset[] | FastspotQuote | FastspotSwap;
export type FastspotError = {
status: number;

@@ -171,104 +140,40 @@ type: string;

};
export declare type Asset = {
asset: SwapAsset;
name: string;
feePerUnit: number;
limits: {
minimum?: number;
maximum?: number;
};
export type RequestAsset<A extends AssetId> = {
asset: A;
} & (A extends AssetId.BTC_LN ? {
peer: string;
} : {
peer?: string;
});
export type RequestAssetWithAmount<A extends AssetId> = RequestAsset<A> & {
amount: string | number;
};
export declare type AssetList = {
[asset in SwapAsset]: Asset;
};
export declare type RequestAsset<K extends SwapAsset> = {
[P in K]: (Record<P, number> & Partial<Record<Exclude<K, P>, never>>) extends infer O ? {
[Q in keyof O]: O[Q];
} : never;
}[K];
export declare type PriceData = {
asset: SwapAsset;
export type Fee = {
asset: Ticker;
network: string;
amount: number;
fee: number;
feePerUnit?: number;
serviceNetworkFee: number;
serviceEscrowFee: number;
included: boolean;
source: FastspotFeeSource;
type: FastspotFeeType;
reason?: string;
};
export declare type Estimate = {
from: PriceData;
to: PriceData;
serviceFeePercentage: number;
direction: 'forward' | 'reverse';
};
export declare type NimHtlcDetails = {
address: string;
timeoutBlock: number;
data: string;
};
export declare type BtcHtlcDetails = {
address: string;
script: string;
};
export declare type BtcLnHtlcDetails = {
nodeId: string;
};
export declare type EurHtlcDetails = {
address: string;
};
export declare type UsdcHtlcDetails = {
address: string;
contract: string;
data?: string;
};
export declare type HtlcDetails = NimHtlcDetails | BtcHtlcDetails | BtcLnHtlcDetails | UsdcHtlcDetails | EurHtlcDetails;
export declare type Contract<T extends SwapAsset> = {
export type Quote = {
id: string;
asset: T;
refundAddress: string;
redeemAddress: string;
amount: number;
timeout: number;
direction: 'send' | 'receive';
status: ContractStatus;
htlc: T extends SwapAsset.NIM ? NimHtlcDetails : T extends SwapAsset.BTC ? BtcHtlcDetails : T extends SwapAsset.BTC_LN ? BtcLnHtlcDetails : T extends SwapAsset.USDC | SwapAsset.USDC_MATIC ? UsdcHtlcDetails : T extends SwapAsset.EUR ? EurHtlcDetails : never;
};
export declare type ContractWithEstimate<T extends SwapAsset> = Estimate & {
contract: Contract<T>;
};
export declare type PreSwap = Estimate & {
id: string;
expires: number;
status: SwapStatus;
sell: {
asset: AssetId;
amount: number;
};
buy: {
asset: AssetId;
amount: number;
};
fees: Fee[];
expiry: number;
};
export declare type Swap = PreSwap & {
export type Swap = Quote & {
hash: string;
secret?: string;
contracts: Partial<Record<SwapAsset, Contract<SwapAsset>>>;
preimage?: string;
contracts: FastspotContract<AssetId>[];
};
export declare type Limits<T extends SwapAsset> = {
asset: T;
daily: number;
dailyRemaining: number;
monthly: number;
monthlyRemaining: number;
perSwap: number;
current: number;
reference: {
asset: ReferenceAsset;
daily: number;
dailyRemaining: number;
monthly: number;
monthlyRemaining: number;
perSwap: number;
current: number;
};
};
export declare type UserLimits = {
asset: ReferenceAsset;
daily: number;
dailyRemaining: number;
monthly: number;
monthlyRemaining: number;
perSwap: number;
current: number;
};
export {};

@@ -1,10 +0,25 @@

export var SwapAsset;
(function (SwapAsset) {
SwapAsset["NIM"] = "NIM";
SwapAsset["BTC"] = "BTC";
SwapAsset["BTC_LN"] = "BTC_LN";
SwapAsset["USDC"] = "USDC";
SwapAsset["USDC_MATIC"] = "USDC_MATIC";
SwapAsset["EUR"] = "EUR";
})(SwapAsset || (SwapAsset = {}));
export var Asset;
(function (Asset) {
Asset["NIM"] = "NIM";
Asset["BTC"] = "BTC";
Asset["USD"] = "USD";
Asset["EUR"] = "EUR";
})(Asset || (Asset = {}));
export var Ticker;
(function (Ticker) {
Ticker["NIM"] = "NIM";
Ticker["BTC"] = "BTC";
Ticker["USDC"] = "USDC";
// USDC_e = 'USDC.e',
Ticker["EUR"] = "EUR";
})(Ticker || (Ticker = {}));
/** @deprecated */
export var AssetId;
(function (AssetId) {
AssetId["NIM"] = "NIM";
AssetId["BTC"] = "BTC";
AssetId["BTC_LN"] = "BTC_LN";
AssetId["USDC_MATIC"] = "USDC_MATIC";
AssetId["EUR"] = "EUR";
})(AssetId || (AssetId = {}));
export var ReferenceAsset;

@@ -14,9 +29,11 @@ (function (ReferenceAsset) {

})(ReferenceAsset || (ReferenceAsset = {}));
// export type ReferralCodes = {
// partnerCode: string,
// refCode?: string,
// };
export const Precision = {
[SwapAsset.NIM]: 5,
[SwapAsset.BTC]: 8,
[SwapAsset.BTC_LN]: 8,
[SwapAsset.USDC]: 6,
[SwapAsset.USDC_MATIC]: 6,
[SwapAsset.EUR]: 2,
[Ticker.NIM]: 5,
[Ticker.BTC]: 8,
[Ticker.USDC]: 6,
[Ticker.EUR]: 2,
[ReferenceAsset.USD]: 2,

@@ -26,20 +43,57 @@ };

(function (SwapStatus) {
SwapStatus["WAITING_FOR_CONFIRMATION"] = "waiting-for-confirmation";
SwapStatus["WAITING_FOR_TRANSACTIONS"] = "waiting-for-transactions";
SwapStatus["WAITING_FOR_REDEMPTION"] = "waiting-for-redemption";
SwapStatus["FINISHED"] = "finished";
/** @deprecated */
SwapStatus["EXPIRED_PENDING_CONFIRMATIONS"] = "expired-pending-confirmation";
SwapStatus["EXPIRED_PENDING_CONFIRMATION"] = "expired-pending-confirmation";
SwapStatus["EXPIRED_PENDING_TRANSACTIONS"] = "expired-pending-transactions";
SwapStatus["CANCELLED"] = "cancelled";
SwapStatus["INVALID"] = "invalid";
SwapStatus["PENDING_CONFIRMATION"] = "PENDING_CONFIRMATION";
SwapStatus["PENDING_DEPOSIT"] = "PENDING_DEPOSIT";
SwapStatus["FINISHED"] = "FINISHED";
SwapStatus["EXPIRED"] = "EXPIRED";
// WAITING_FOR_REDEMPTION = 'waiting-for-redemption',
// EXPIRED_PENDING_CONFIRMATION = 'expired-pending-confirmation',
// CANCELLED = 'cancelled',
// INVALID = 'invalid',
})(SwapStatus || (SwapStatus = {}));
export var ContractStatus;
(function (ContractStatus) {
ContractStatus["PENDING"] = "pending";
ContractStatus["FUNDED"] = "funded";
ContractStatus["TIMEOUT_REACHED"] = "timeout-reached";
ContractStatus["REFUNDED"] = "refunded";
ContractStatus["REDEEMED"] = "redeemed";
ContractStatus["PENDING"] = "PENDING";
// FUNDED = 'funded',
// TIMEOUT_REACHED = 'timeout-reached',
// REFUNDED = 'refunded',
ContractStatus["REDEEMED"] = "REDEEMED";
})(ContractStatus || (ContractStatus = {}));
var FastspotFeeSource;
(function (FastspotFeeSource) {
FastspotFeeSource["NETWORK"] = "NETWORK";
FastspotFeeSource["SERVICE"] = "SERVICE";
})(FastspotFeeSource || (FastspotFeeSource = {}));
var FastspotFeeType;
(function (FastspotFeeType) {
FastspotFeeType["DEPOSIT_TRANSACTION"] = "DEPOSIT_TRANSACTION";
FastspotFeeType["REDEMPTION_TRANSACTION"] = "REDEMPTION_TRANSACTION";
FastspotFeeType["REFUND_TRANSACTION"] = "REFUND_TRANSACTION";
FastspotFeeType["EXECUTION"] = "EXECUTION";
})(FastspotFeeType || (FastspotFeeType = {}));
// export type Limits<T extends SwapAsset> = {
// asset: T,
// daily: number,
// dailyRemaining: number,
// monthly: number,
// monthlyRemaining: number,
// perSwap: number,
// current: number,
// reference: {
// asset: ReferenceAsset,
// daily: number,
// dailyRemaining: number,
// monthly: number,
// monthlyRemaining: number,
// perSwap: number,
// current: number,
// },
// };
// export type UserLimits = {
// asset: ReferenceAsset,
// daily: number,
// dailyRemaining: number,
// monthly: number,
// monthlyRemaining: number,
// perSwap: number,
// current: number,
// };
{
"name": "@nimiq/fastspot-api",
"version": "1.9.0",
"version": "2.0.0-beta.0",
"description": "Typescript library to interact with the Fastspot API",

@@ -17,4 +17,4 @@ "repository": "git@github.com:nimiq/fastspot-api.git",

"devDependencies": {
"typescript": "^4.6.3"
"typescript": "^5.4.2"
}
}
SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc