@swapkit/helpers
Advanced tools
Comparing version 0.0.0-nightly-20240724130444 to 0.0.0-nightly-20240806215520
@@ -5,13 +5,13 @@ { | ||
"dependencies": { | ||
"@swapkit/tokens": "0.0.0-nightly-20240724130444", | ||
"picocolors": "1.0.1", | ||
"zod": "3.23.8" | ||
"@swapkit/contracts": "1.0.4", | ||
"@swapkit/tokens": "0.0.0-nightly-20240806215520", | ||
"picocolors": "1.0.1" | ||
}, | ||
"devDependencies": { | ||
"@swapkit/toolbox-cosmos": "0.0.0-nightly-20240724130444", | ||
"@swapkit/toolbox-evm": "0.0.0-nightly-20240724130444", | ||
"@swapkit/toolbox-solana": "0.0.0-nightly-20240724130444", | ||
"@swapkit/toolbox-radix": "0.0.0-nightly-20240724130444", | ||
"@swapkit/toolbox-substrate": "0.0.0-nightly-20240724130444", | ||
"@swapkit/toolbox-utxo": "0.0.0-nightly-20240724130444" | ||
"@swapkit/toolbox-cosmos": "0.0.0-nightly-20240806215520", | ||
"@swapkit/toolbox-evm": "0.0.0-nightly-20240806215520", | ||
"@swapkit/toolbox-solana": "0.0.0-nightly-20240806215520", | ||
"@swapkit/toolbox-radix": "0.0.0-nightly-20240806215520", | ||
"@swapkit/toolbox-substrate": "0.0.0-nightly-20240806215520", | ||
"@swapkit/toolbox-utxo": "0.0.0-nightly-20240806215520" | ||
}, | ||
@@ -41,3 +41,3 @@ "files": [ | ||
"types": "./src/index.ts", | ||
"version": "0.0.0-nightly-20240724130444" | ||
"version": "0.0.0-nightly-20240806215520" | ||
} |
@@ -54,2 +54,19 @@ import { describe, expect, test } from "bun:test"; | ||
}); | ||
test("find asset by chain and radix resource", async () => { | ||
const assetByChainAndContract = await findAssetBy({ | ||
chain: Chain.Radix, | ||
contract: "resource_rdx1t580qxc7upat7lww4l2c4jckacafjeudxj5wpjrrct0p3e82sq4y75", | ||
}); | ||
expect(assetByChainAndContract?.toUpperCase()).toBe( | ||
"XRD.XWBTC-resource_rdx1t580qxc7upat7lww4l2c4jckacafjeudxj5wpjrrct0p3e82sq4y75".toUpperCase(), | ||
); | ||
}); | ||
test("find asset by radix identifier", async () => { | ||
const assetByChainAndContract = await findAssetBy({ | ||
identifier: "XRD.XRD", | ||
}); | ||
expect(assetByChainAndContract?.toUpperCase()).toBe("XRD.XRD".toUpperCase()); | ||
}); | ||
}); |
@@ -262,3 +262,5 @@ import { AssetValue } from "../modules/assetValue.ts"; | ||
export async function findAssetBy( | ||
params: { chain: EVMChain; contract: string } | { identifier: `${Chain}.${string}` }, | ||
params: | ||
| { chain: EVMChain | Chain.Radix; contract: string } | ||
| { identifier: `${Chain}.${string}` }, | ||
) { | ||
@@ -265,0 +267,0 @@ const tokenPackages = await import("@swapkit/tokens"); |
@@ -5,109 +5,17 @@ import { SwapKitError } from "../modules/swapKitError"; | ||
type WithChain<T extends {}> = T & { chain: Chain }; | ||
type WithAffiliate<T extends {}> = T & { | ||
affiliateAddress?: string; | ||
affiliateBasisPoints?: number; | ||
}; | ||
function addAffiliate(memo: string, { affiliateAddress, affiliateBasisPoints }: WithAffiliate<{}>) { | ||
const affiliatePart = affiliateAddress ? `:${affiliateAddress}:${affiliateBasisPoints || 0}` : ""; | ||
return `${memo}${affiliatePart}`; | ||
} | ||
function getPoolIdentifier({ | ||
chain, | ||
symbol, | ||
}: { | ||
chain: Chain; | ||
symbol: string; | ||
}) { | ||
switch (chain) { | ||
case Chain.Bitcoin: | ||
case Chain.Dogecoin: | ||
case Chain.Litecoin: | ||
return chain.slice(0, 1).toLowerCase(); | ||
case Chain.BitcoinCash: | ||
return "c"; | ||
default: | ||
return `${chain}.${symbol}`; | ||
} | ||
} | ||
export function getMemoForLeaveAndBond({ | ||
type, | ||
address, | ||
}: { | ||
type: MemoType.BOND | MemoType.LEAVE; | ||
address: string; | ||
}) { | ||
export function getMemoForLeaveAndBond({ type, address }: BondOrLeaveParams) { | ||
return `${type}:${address}`; | ||
} | ||
export function getMemoForUnbond({ | ||
address, | ||
unbondAmount, | ||
}: { | ||
address: string; | ||
unbondAmount: number; | ||
}) { | ||
export function getMemoForUnbond({ address, unbondAmount }: UnbondParams) { | ||
return `${MemoType.UNBOND}:${address}:${unbondAmount}`; | ||
} | ||
export function getMemoForNameRegister({ | ||
name, | ||
chain, | ||
address, | ||
owner, | ||
}: { | ||
name: string; | ||
chain: string; | ||
address: string; | ||
owner?: string; | ||
}) { | ||
const baseMemo = `${MemoType.NAME_REGISTER}:${name}:${chain}:${address}`; | ||
const ownerAssignmentOrChangePart = owner ? `:${owner}` : ""; | ||
return `${baseMemo}${ownerAssignmentOrChangePart}`; | ||
/** | ||
* Deposit | ||
*/ | ||
export function getMemoForRunePoolDeposit(affiliate?: WithAffiliate<{}>) { | ||
return addAffiliate(MemoType.RUNEPOOL_DEPOSIT, affiliate); | ||
} | ||
export function getMemoForNamePreferredAssetRegister({ | ||
name, | ||
chain, | ||
asset, | ||
payout, | ||
owner, | ||
}: { | ||
name: string; | ||
chain: Chain; | ||
asset: string; | ||
payout: string; | ||
owner: string; | ||
}) { | ||
const memo = [name, chain, payout, owner, asset].join(":"); | ||
return `${MemoType.NAME_REGISTER}:${memo}`; | ||
} | ||
export function getMemoForLoan( | ||
memoType: MemoType.OPEN_LOAN | MemoType.CLOSE_LOAN, | ||
{ | ||
asset, | ||
address, | ||
minAmount, | ||
...affiliate | ||
}: WithAffiliate<{ | ||
address: string; | ||
asset: string; | ||
minAmount?: string; | ||
}>, | ||
) { | ||
const baseMemo = `${memoType}:${asset}:${address}`; | ||
const minAmountPart = minAmount ? `:${minAmount}` : ""; | ||
return addAffiliate(`${baseMemo}${minAmountPart}`, affiliate); | ||
} | ||
export function getMemoForSaverDeposit({ | ||
@@ -132,4 +40,3 @@ chain, | ||
const poolIdentifier = getPoolIdentifier({ chain, symbol }); | ||
const hasAffiliateInfo = !!affiliate.affiliateAddress; | ||
const addressPart = address ? `:${address}` : hasAffiliateInfo ? ":" : ""; | ||
const addressPart = address ? `:${address}:` : ":"; | ||
@@ -139,2 +46,5 @@ return addAffiliate(`${MemoType.DEPOSIT}:${poolIdentifier}${addressPart}`, affiliate); | ||
/** | ||
* Withdraw | ||
*/ | ||
export function getMemoForSaverWithdraw({ | ||
@@ -154,9 +64,3 @@ chain, | ||
targetAsset, | ||
}: { | ||
chain: Chain; | ||
symbol: string; | ||
ticker: string; | ||
basisPoints: number; | ||
targetAsset?: string; | ||
}) { | ||
}: WithdrawParams) { | ||
const shortenedSymbol = | ||
@@ -169,6 +73,2 @@ chain === "ETH" && ticker !== "ETH" ? `${ticker}-${symbol.slice(-3)}` : symbol; | ||
export function getMemoForRunePoolDeposit() { | ||
return `${MemoType.RUNEPOOL_DEPOSIT}`; | ||
} | ||
export function getMemoForRunePoolWithdraw({ | ||
@@ -182,49 +82,107 @@ basisPoints, | ||
/** | ||
* @deprecated - Use separate functions per each memo type like getMemoForDeposit, getMemoForWithdraw, etc. | ||
* TNS | ||
*/ | ||
export type MemoOptions<T extends MemoType> = { | ||
[MemoType.BOND]: { address: string }; | ||
[MemoType.LEAVE]: { address: string }; | ||
[MemoType.CLOSE_LOAN]: { address: string; asset: string; minAmount?: string }; | ||
[MemoType.OPEN_LOAN]: { address: string; asset: string; minAmount?: string }; | ||
[MemoType.UNBOND]: { address: string; unbondAmount: number }; | ||
[MemoType.DEPOSIT]: WithChain<{ | ||
symbol: string; | ||
address?: string; | ||
singleSide?: boolean; | ||
}>; | ||
[MemoType.WITHDRAW]: WithChain<{ | ||
ticker: string; | ||
symbol: string; | ||
basisPoints: number; | ||
targetAssetString?: string; | ||
singleSide?: boolean; | ||
}>; | ||
[MemoType.NAME_REGISTER]: { name: string; chain: string; address: string }; | ||
[MemoType.RUNEPOOL_DEPOSIT]: {}; | ||
[MemoType.RUNEPOOL_WITHDRAW]: { | ||
basisPoints: number; | ||
affiliateAddress?: string; | ||
affiliateBasisPoints?: number; | ||
}; | ||
}[T]; | ||
export function getMemoForNameRegister({ name, chain, address, owner }: NameRegisterParams) { | ||
const baseMemo = `${MemoType.NAME_REGISTER}:${name}:${chain}:${address}`; | ||
const ownerAssignmentOrChangePart = owner ? `:${owner}` : ""; | ||
return `${baseMemo}${ownerAssignmentOrChangePart}`; | ||
} | ||
export function getMemoForNamePreferredAssetRegister({ | ||
name, | ||
chain, | ||
asset, | ||
payout, | ||
owner, | ||
}: PreferredAssetRegisterParams) { | ||
return `${MemoType.NAME_REGISTER}:${name}:${chain}:${payout}:${owner}:${asset}`; | ||
} | ||
export function getMemoForLoan( | ||
memoType: MemoType.OPEN_LOAN | MemoType.CLOSE_LOAN, | ||
{ | ||
asset, | ||
address, | ||
minAmount, | ||
...affiliate | ||
}: WithAffiliate<{ address: string; asset: string; minAmount?: string }>, | ||
) { | ||
const baseMemo = `${memoType}:${asset}:${address}`; | ||
const minAmountPart = minAmount ? `:${minAmount}` : ""; | ||
return addAffiliate(`${baseMemo}${minAmountPart}`, affiliate); | ||
} | ||
/** | ||
* Internal helpers | ||
*/ | ||
function addAffiliate( | ||
memo: string, | ||
{ affiliateAddress, affiliateBasisPoints }: WithAffiliate<{}> = {}, | ||
) { | ||
const affiliatedMemo = `${memo}${affiliateAddress ? `:${affiliateAddress}:${affiliateBasisPoints || 0}` : ""}`; | ||
return affiliatedMemo.endsWith(":") ? affiliatedMemo.slice(0, -1) : affiliatedMemo; | ||
} | ||
function getPoolIdentifier({ | ||
chain, | ||
symbol, | ||
}: { | ||
chain: Chain; | ||
symbol: string; | ||
}) { | ||
switch (chain) { | ||
case Chain.Bitcoin: | ||
case Chain.Dogecoin: | ||
case Chain.Litecoin: | ||
return chain.slice(0, 1).toLowerCase(); | ||
case Chain.BitcoinCash: | ||
return "c"; | ||
default: | ||
return `${chain}.${symbol}`; | ||
} | ||
} | ||
type WithAffiliate<T extends {}> = T & { | ||
affiliateAddress?: string; | ||
affiliateBasisPoints?: number; | ||
}; | ||
type BondOrLeaveParams = { type: MemoType.BOND | MemoType.LEAVE; address: string }; | ||
type UnbondParams = { address: string; unbondAmount: number }; | ||
type NameRegisterParams = { name: string; chain: string; address: string; owner?: string }; | ||
type PreferredAssetRegisterParams = { | ||
name: string; | ||
chain: Chain; | ||
asset: string; | ||
payout: string; | ||
owner: string; | ||
}; | ||
type WithdrawParams = { | ||
chain: Chain; | ||
symbol: string; | ||
ticker: string; | ||
basisPoints: number; | ||
targetAsset?: string; | ||
}; | ||
/** | ||
* @deprecated - Use separate functions per each memo type like getMemoForDeposit, getMemoForWithdraw, etc. | ||
*/ | ||
export const getMemoFor = <T extends MemoType>(memoType: T, options: MemoOptions<T>) => { | ||
export const getMemoFor = <T extends MemoType>(memoType: T, options: NotWorth) => { | ||
switch (memoType) { | ||
case MemoType.LEAVE: | ||
case MemoType.BOND: { | ||
const { address } = options as MemoOptions<MemoType.BOND>; | ||
return getMemoForLeaveAndBond({ type: memoType, address }); | ||
return getMemoForLeaveAndBond({ type: memoType, address: options?.address }); | ||
} | ||
case MemoType.UNBOND: { | ||
const { address, unbondAmount } = options as MemoOptions<MemoType.UNBOND>; | ||
return getMemoForUnbond({ address, unbondAmount }); | ||
return getMemoForUnbond({ address: options?.address, unbondAmount: options?.unbondAmount }); | ||
} | ||
case MemoType.NAME_REGISTER: { | ||
return getMemoForNameRegister(options as MemoOptions<MemoType.NAME_REGISTER>); | ||
return getMemoForNameRegister(options); | ||
} | ||
@@ -234,7 +192,7 @@ | ||
case MemoType.CLOSE_LOAN: { | ||
return getMemoForLoan(memoType, options as MemoOptions<MemoType.OPEN_LOAN>); | ||
return getMemoForLoan(memoType, options); | ||
} | ||
case MemoType.DEPOSIT: { | ||
const { chain, symbol, address, singleSide } = options as MemoOptions<MemoType.DEPOSIT>; | ||
const { chain, symbol, address, singleSide } = options; | ||
@@ -256,3 +214,3 @@ if (singleSide) { | ||
singleSide, | ||
} = options as MemoOptions<MemoType.WITHDRAW>; | ||
} = options; | ||
@@ -259,0 +217,0 @@ if (singleSide) { |
@@ -0,1 +1,2 @@ | ||
export * from "@swapkit/contracts"; | ||
export * from "./types/index.ts"; | ||
@@ -2,0 +3,0 @@ |
@@ -579,28 +579,28 @@ import { describe, expect, test } from "bun:test"; | ||
// TODO enable when BE fixes case sensitivity | ||
// const thor = AssetValue.from({ asset: "ETH.THOR" }); | ||
// expect(thor).toEqual( | ||
// expect.objectContaining({ | ||
// address: "0xa5f2211b9b8170f694421f2046281775e8468044", | ||
// chain: Chain.Ethereum, | ||
// decimal: 18, | ||
// isGasAsset: false, | ||
// isSynthetic: false, | ||
// symbol: "THOR-0xa5f2211b9b8170f694421f2046281775e8468044", | ||
// ticker: "THOR", | ||
// }), | ||
// ); | ||
const thor = AssetValue.from({ asset: "ETH.THOR" }); | ||
expect(thor).toEqual( | ||
expect.objectContaining({ | ||
address: "0xa5f2211b9b8170f694421f2046281775e8468044", | ||
chain: Chain.Ethereum, | ||
decimal: 18, | ||
isGasAsset: false, | ||
isSynthetic: false, | ||
symbol: "THOR-0xa5f2211b9b8170f694421f2046281775e8468044", | ||
ticker: "THOR", | ||
}), | ||
); | ||
// const vthor = AssetValue.from({ asset: "ETH.vTHOR" }); | ||
// expect(vthor).toEqual( | ||
// expect.objectContaining({ | ||
// address: "0x815c23eca83261b6ec689b60cc4a58b54bc24d8d", | ||
// chain: Chain.Ethereum, | ||
// decimal: 18, | ||
// isGasAsset: false, | ||
// isSynthetic: false, | ||
// symbol: "vTHOR-0x815c23eca83261b6ec689b60cc4a58b54bc24d8d", | ||
// ticker: "vTHOR", | ||
// }), | ||
// ); | ||
// FIXME: just some casing? is it safe to change | ||
// const vthor = AssetValue.from({ asset: "ETH.vTHOR" }); | ||
// expect(vthor).toEqual( | ||
// expect.objectContaining({ | ||
// address: "0x815c23eca83261b6ec689b60cc4a58b54bc24d8d", | ||
// chain: Chain.Ethereum, | ||
// decimal: 18, | ||
// isGasAsset: false, | ||
// isSynthetic: false, | ||
// symbol: "vTHOR-0x815c23eca83261b6ec689b60cc4a58b54bc24d8d", | ||
// ticker: "vTHOR", | ||
// }), | ||
// ); | ||
@@ -607,0 +607,0 @@ const arbAsset = AssetValue.from({ chain: Chain.Arbitrum }); |
@@ -1,2 +0,2 @@ | ||
type Options = { | ||
type Options = Parameters<typeof fetch>[1] & { | ||
headers?: Record<string, string>; | ||
@@ -7,3 +7,4 @@ apiKey?: string; | ||
responseHandler?: (response: NotWorth) => NotWorth; | ||
[key: string]: NotWorth; | ||
searchParams?: Record<string, string>; | ||
json?: unknown; | ||
}; | ||
@@ -22,10 +23,28 @@ | ||
async function fetchWithConfig(url: string, options: Options = {}) { | ||
async function fetchWithConfig(url: string, options: Options) { | ||
const { apiKey, ...config } = clientConfig; | ||
const headers = { ...defaultRequestHeaders, ...config.headers, ...options.headers }; | ||
const { searchParams, json, body } = options; | ||
const headers = { | ||
...defaultRequestHeaders, | ||
...config.headers, | ||
...options.headers, | ||
...(json ? { "Content-Type": "application/json" } : {}), | ||
} as Record<string, string>; | ||
const bodyToSend = json ? JSON.stringify(json) : body; | ||
const urlInstance = new URL(url); | ||
if (searchParams) { | ||
urlInstance.search = new URLSearchParams(searchParams).toString(); | ||
} | ||
if (apiKey) headers["x-api-key"] = apiKey; | ||
try { | ||
const response = await fetch(url, { ...config, ...options, headers }); | ||
const response = await fetch(urlInstance.toString(), { | ||
...config, | ||
...options, | ||
body: bodyToSend, | ||
headers, | ||
}); | ||
const body = await response.json(); | ||
@@ -32,0 +51,0 @@ |
@@ -60,2 +60,3 @@ const errorCodes = { | ||
core_transaction_user_rejected: 10315, | ||
core_transaction_failed: 10316, | ||
/** | ||
@@ -114,2 +115,3 @@ * Wallets | ||
api_v2_invalid_response: 50001, | ||
api_v2_server_error: 50002, | ||
/** | ||
@@ -116,0 +118,0 @@ * Toolboxes |
@@ -49,10 +49,2 @@ import type { Chain, CosmosChain, EVMChain, UTXOChain } from "./chains.ts"; | ||
chainflipBrokerUrl?: string; | ||
/** | ||
* @optional for setting the chainflip radix dapp config | ||
*/ | ||
radixDappConfig?: { | ||
dAppDefinitionAddress: string; | ||
applicationName: string; | ||
applicationVersion: string; | ||
}; | ||
}; | ||
@@ -59,0 +51,0 @@ |
@@ -1,4 +0,1 @@ | ||
export * from "./abis/erc20"; | ||
export * from "./abis/mayaEvmVaults"; | ||
export * from "./abis/tcEthVault"; | ||
export * from "./chains"; | ||
@@ -5,0 +2,0 @@ export * from "./commonTypes"; |
@@ -1,2 +0,114 @@ | ||
import { z } from "zod"; | ||
export enum ErrorCode { | ||
unknownError = "unknownError", | ||
test_error = "test_error", | ||
providerDetailsError = "providerDetailsError", | ||
blockHeaderNotFound = "blockHeaderNotFound", | ||
blockHashNotFoundAtHeight = "blockHashNotFoundAtHeight", | ||
blockHashNotFoundAtHash = "blockHashNotFoundAtHash", | ||
txHashMissing = "txHashMissing", | ||
assetValueMissingInfo = "assetValueMissingInfo", | ||
invalidAsset = "invalidAsset", | ||
blockIsRequired = "blockIsRequired", | ||
currentBlockHeaderNotFound = "currentBlockHeaderNotFound", | ||
failedToRetrieveBalance = "failedToRetrieveBalance", | ||
failedToRetrieveBlock = "failedToRetrieveBlock", | ||
failedToRetrieveFees = "failedToRetrieveFees", | ||
notImplementedBCH = "notImplementedBCH", | ||
notImplementedDoge = "notImplementedDoge", | ||
noPoolsFound = "noPoolsFound", | ||
noVaultsFound = "noVaultsFound", | ||
noTxFound = "noTxFound", | ||
noInputCoinFound = "noInputCoinFound", | ||
noBlockDataFound = "noBlockDataFound", | ||
multipleCosmosMessages = "multipleCosmosMessages", | ||
heightOrHashNotProvided = "heightOrHashNotProvided", | ||
unknownDenom = "unknownDenom", | ||
invalidBlockHeight = "invalidBlockHeight", | ||
timestampExtrinsicNoArgumentsForBlock = "timestampExtrinsicNoArgumentsForBlock", | ||
timestampExtrinsicNoTimestampForBlock = "timestampExtrinsicNoTimestampForBlock", | ||
noTimestampExtrinsicForHash = "noTimestampExtrinsicForHash", | ||
timestampExtrinsicNoArgumentsForHash = "timestampExtrinsicNoArgumentsForHash", | ||
txMemoUndefined = "txMemoUndefined", | ||
txMemoIncorrect = "txMemoIncorrect", | ||
txTypeNotFound = "txTypeNotFound", | ||
txNoMessage = "txNoMessage", | ||
txNotFound = "txNotFound", | ||
txReceiptNotFound = "txReceiptNotFound", | ||
txParsingError = "txParsingError", | ||
blockNotFound = "blockNotFound", | ||
balanceNotFound = "balanceNotFound", | ||
configError = "configError", | ||
noQuoteResponse = "noQuoteResponse", | ||
noPoolAssetsFound = "noPoolAssetsFound", | ||
noThorchainPools = "noThorchainPools", | ||
noMayachainPools = "noMayachainPools", | ||
invalidAffiliateFee = "invalidAffiliateFee", | ||
invalidBuyAssetAddress = "invalidBuyAssetAddress", | ||
invalidSellAssetAddress = "invalidSellAssetAddress", | ||
invalidSourceAddress = "invalidSourceAddress", | ||
invalidDestinationAddress = "invalidDestinationAddress", | ||
sourceAddressIsSmartContract = "sourceAddressIsSmartContract", | ||
destinationAddressIsSmartContract = "destinationAddressIsSmartContract", | ||
invalidChainId = "invalidChainId", | ||
unsupportedChainId = "unsupportedChainId", | ||
unsupportedEVMChainId = "unsupportedEVMChainId", | ||
noWhitelistTokens = "noWhitelistTokens", | ||
failedFetchGasPrice = "failedFetchGasPrice", | ||
failedToCreateDepositChannel = "failedToCreateDepositChannel", | ||
noProviderDetailsFound = "noProviderDetailsFound", | ||
noTokenListsFound = "noTokenListsFound", | ||
tokenNotFound = "tokenNotFound", | ||
tokenPriceNotFound = "tokenPriceNotFound", | ||
swapAmountTooSmall = "swapAmountTooSmall", | ||
legsArrayIsEmpty = "legsArrayIsEmpty", | ||
failedToFetchQuoteForLeg = "failedToFetchQuoteForLeg", | ||
noBlockHeaderFound = "noBlockHeaderFound", | ||
failedToSimulateSwap = "failedToSimulateSwap", | ||
addressScreeningFailed = "addressScreeningFailed", | ||
noLiquidtyProvidersFound = "noLiquidtyProvidersFound", | ||
noSaversFound = "noSaversFound", | ||
noInboundAddressesFound = "noInboundAddressesFound", | ||
noInboundAddressFoundForChain = "noInboundAddressFoundForChain", | ||
noLastBlocksFound = "noLastBlocksFound", | ||
noVersionFound = "noVersionFound", | ||
noConstantsFound = "noConstantsFound", | ||
noMimirsFound = "noMimirsFound", | ||
noRoutesFound = "noRoutesFound", | ||
quoteNotFound = "quoteNotFound", | ||
ledgerSignFailed = "ledgerSignFailed", | ||
ledgerFetchSwapFailed = "ledgerFetchSwapFailed", | ||
failedToFetchTx = "failedToFetchTx", | ||
failedBuildTransactionDetails = "failedBuildTransactionDetails", | ||
noLegsForRoute = "noLegsForRoute", | ||
noRouterAddressFound = "noRouterAddressFound", | ||
noAggregatorAddressFound = "noAggregatorAddressFound", | ||
noContractInstanceFound = "noContractInstanceFound", | ||
noContractAddressFound = "noContractAddressFound", | ||
invalidAffiliate = "invalidAffiliate", | ||
providerNotfound = "No provider found", | ||
noRecordFound = "No Record found", | ||
slippageTooLow = "Slippage too low", | ||
tradingHalted = "tradingHalted", | ||
noWrappedGasAsset = "noWrappedGasAsset", | ||
aggregatorAddressNotFound = "aggregatorAddressNotFound", | ||
routerAddressNotFound = "routerAddressNotFound", | ||
dummyAddressNotFound = "dummyAddressNotFound", | ||
trackerError = "trackerError", | ||
noOhlcvDataFound = "noOhlcvDataFound", | ||
noTradingPairs = "noTradingPairs", | ||
noLoanPositionFound = "noLoanPositionFound", | ||
noLendingAvailability = "noLendingAvailability", | ||
lendingRepayTooSmall = "lendingRepayTooSmall", | ||
missingState = "missingState", | ||
ledgerSwapNotFound = "ledgerSwapNotFound", | ||
ledgerSwapNotReadyForTracking = "ledgerSwapNotReadyForTracking", | ||
errorEstimatingGas = "errorEstimatingGas", | ||
apiKeyInvalid = "apiKeyInvalid", | ||
apiKeyFailedToUpdate = "apiKeyFailedToUpdate", | ||
apiKeyExpired = "apiKeyExpired", | ||
unauthorized = "unauthorized", | ||
failedToCreateMemo = "failedToCreateMemo", | ||
radixIncorrectInstructions = "radixIncorrectInstructions", | ||
invalidAddressForChain = "invalidAddressForChain", | ||
} | ||
@@ -8,74 +120,2 @@ export enum WarningCodeEnum { | ||
export const EVMTransactionDetailsParamsSchema = z.array( | ||
z.union([ | ||
z.string(), | ||
z.number(), | ||
z.array(z.string()), | ||
z | ||
.object({ | ||
from: z.string(), | ||
value: z.string(), | ||
}) | ||
.describe("Parameters to pass to the contract method"), | ||
]), | ||
); | ||
export type EVMTransactionDetailsParams = z.infer<typeof EVMTransactionDetailsParamsSchema>; | ||
export const EVMTransactionDetailsSchema = z.object({ | ||
contractAddress: z.string({ | ||
description: "Address of the contract to interact with", | ||
}), | ||
contractMethod: z.string({ | ||
description: "Name of the method to call", | ||
}), | ||
contractParams: EVMTransactionDetailsParamsSchema, | ||
// contractParamsStreaming: z.array( | ||
// z.string({ | ||
// description: | ||
// "If making a streaming swap through THORChain, parameters to pass to the contract method", | ||
// }), | ||
// ), | ||
contractParamNames: z.array( | ||
z.string({ | ||
description: "Names of the parameters to pass to the contract method", | ||
}), | ||
), | ||
approvalToken: z.optional( | ||
z.string({ | ||
description: "Address of the token to approve spending of", | ||
}), | ||
), | ||
approvalSpender: z.optional( | ||
z.string({ | ||
description: "Address of the spender to approve", | ||
}), | ||
), | ||
}); | ||
export type EVMTransactionDetails = z.infer<typeof EVMTransactionDetailsSchema>; | ||
export const EstimatedTimeSchema = z.object({ | ||
inbound: z.optional( | ||
z.number({ | ||
description: "Time to receive inbound asset in seconds", | ||
}), | ||
), | ||
swap: z.optional( | ||
z.number({ | ||
description: "Time to swap assets in seconds", | ||
}), | ||
), | ||
outbound: z.optional( | ||
z.number({ | ||
description: "Time to receive outbound asset in seconds", | ||
}), | ||
), | ||
total: z.number({ | ||
description: "Total time in seconds", | ||
}), | ||
}); | ||
export type EstimatedTime = z.infer<typeof EstimatedTimeSchema>; | ||
export enum ProviderName { | ||
@@ -94,3 +134,2 @@ CHAINFLIP = "CHAINFLIP", | ||
UNISWAP_V3 = "UNISWAP_V3", | ||
WOOFI_V2 = "WOOFI_V2", | ||
CAVIAR_V1 = "CAVIAR_V1", | ||
@@ -107,167 +146,1 @@ } | ||
} | ||
export const FeesSchema = z.array( | ||
z.object({ | ||
type: z.nativeEnum(FeeTypeEnum), | ||
amount: z.string(), | ||
asset: z.string(), | ||
chain: z.string(), | ||
protocol: z.nativeEnum(ProviderName), | ||
}), | ||
); | ||
export type Fees = z.infer<typeof FeesSchema>; | ||
export const RouteLegSchema = z.object({ | ||
sellAsset: z.string({ | ||
description: "Asset to sell", | ||
}), | ||
buyAsset: z.string({ | ||
description: "Asset to buy", | ||
}), | ||
provider: z.nativeEnum(ProviderName), | ||
sourceAddress: z.string({ | ||
description: "Source address", | ||
}), | ||
destinationAddress: z.string({ | ||
description: "Destination address", | ||
}), | ||
estimatedTime: EstimatedTimeSchema.optional(), | ||
affiliate: z | ||
.string({ | ||
description: "Affiliate address", | ||
}) | ||
.optional(), | ||
affiliateFee: z | ||
.number({ | ||
description: "Affiliate fee", | ||
}) | ||
.optional(), | ||
slipPercentage: z.number({ | ||
description: "Slippage as a percentage", | ||
}), | ||
}); | ||
export type RouteLeg = z.infer<typeof RouteLegSchema>; | ||
export const RouteLegWithoutAddressesSchema = RouteLegSchema.omit({ | ||
sourceAddress: true, | ||
destinationAddress: true, | ||
slipPercentage: true, | ||
}); | ||
export type RouteLegWithoutAddresses = z.infer<typeof RouteLegWithoutAddressesSchema>; | ||
export const RouteQuoteMetadataAssetSchema = z.object({ | ||
name: z.string({ | ||
description: "Asset name", | ||
}), | ||
price: z.number({ | ||
description: "Price in USD", | ||
}), | ||
image: z.string({ | ||
description: "Asset image", | ||
}), | ||
}); | ||
export type RouteQuoteMetadataAsset = z.infer<typeof RouteQuoteMetadataAssetSchema>; | ||
export const RouteQuoteMetadataSchema = z.object({ | ||
priceImpact: z.number({ | ||
description: "Price impact", | ||
}), | ||
assets: z.optional(z.array(RouteQuoteMetadataAssetSchema)), | ||
}); | ||
export const RouteQuoteWarningSchema = z.array( | ||
z.object({ | ||
code: z.nativeEnum(WarningCodeEnum), | ||
display: z.string(), | ||
tooltip: z.string().optional(), | ||
}), | ||
); | ||
const QuoteResponseRouteLegItem = z.object({ | ||
provider: z.nativeEnum(ProviderName), | ||
sellAsset: z.string({ | ||
description: "Asset to sell", | ||
}), | ||
sellAmount: z.string({ | ||
description: "Sell amount", | ||
}), | ||
buyAsset: z.string({ | ||
description: "Asset to buy", | ||
}), | ||
buyAmount: z.string({ | ||
description: "Buy amount", | ||
}), | ||
buyAmountMaxSlippage: z.string({ | ||
description: "Buy amount max slippage", | ||
}), | ||
fees: z.optional(FeesSchema), // TODO remove optionality | ||
}); | ||
const QuoteResponseRouteItem = z.object({ | ||
providers: z.array(z.nativeEnum(ProviderName)), | ||
sellAsset: z.string({ | ||
description: "Asset to sell", | ||
}), | ||
sellAmount: z.string({ | ||
description: "Sell amount", | ||
}), | ||
buyAsset: z.string({ | ||
description: "Asset to buy", | ||
}), | ||
expectedBuyAmount: z.string({ | ||
description: "Expected Buy amount", | ||
}), | ||
expectedBuyAmountMaxSlippage: z.string({ | ||
description: "Expected Buy amount max slippage", | ||
}), | ||
sourceAddress: z.string({ | ||
description: "Source address", | ||
}), | ||
destinationAddress: z.string({ | ||
description: "Destination address", | ||
}), | ||
targetAddress: z.optional( | ||
z.string({ | ||
description: "Target address", | ||
}), | ||
), | ||
expiration: z.optional( | ||
z.string({ | ||
description: "Expiration", | ||
}), | ||
), | ||
memo: z.optional( | ||
z.string({ | ||
description: "Memo", | ||
}), | ||
), | ||
evmTransactionDetails: z.optional(EVMTransactionDetailsSchema), | ||
transaction: z.optional(z.unknown()), // Can take many forms depending on the chains | ||
estimatedTime: z.optional(EstimatedTimeSchema), // TODO remove optionality | ||
totalSlippageBps: z.number({ | ||
description: "Total slippage in bps", | ||
}), | ||
legs: z.array(QuoteResponseRouteLegItem), | ||
warnings: RouteQuoteWarningSchema, | ||
meta: RouteQuoteMetadataSchema, | ||
}); | ||
export const QuoteResponseSchema = z.object({ | ||
quoteId: z.string({ | ||
description: "Quote ID", | ||
}), | ||
routes: z.array(QuoteResponseRouteItem), | ||
error: z.optional( | ||
z.string({ | ||
description: "Error message", | ||
}), | ||
), | ||
}); | ||
export type QuoteResponse = z.infer<typeof QuoteResponseSchema>; | ||
export type QuoteResponseRoute = z.infer<typeof QuoteResponseRouteItem>; | ||
export type QuoteResponseRouteLeg = z.infer<typeof QuoteResponseRouteLegItem>; |
import type { CovalentApiType, EthplorerApiType } from "@swapkit/toolbox-evm"; | ||
import type { BlockchairApiType } from "@swapkit/toolbox-utxo"; | ||
import { z } from "zod"; | ||
import type { AssetValue } from "../modules/assetValue"; | ||
import type { Chain, CosmosChain, UTXOChain } from "./chains"; | ||
import type { QuoteResponseRoute } from "./quotes"; | ||
@@ -22,3 +20,3 @@ type CovalentChains = | ||
export type GenericSwapParams = { | ||
export type GenericSwapParams<T = unknown> = { | ||
buyAsset?: AssetValue; | ||
@@ -28,6 +26,6 @@ sellAsset?: AssetValue; | ||
feeOptionKey?: FeeOption; | ||
route: QuoteResponseRoute; | ||
route: T; | ||
}; | ||
export type SwapParams<PluginNames = string, T = GenericSwapParams> = T & { | ||
export type SwapParams<PluginNames = string, R = unknown> = GenericSwapParams<R> & { | ||
pluginName?: PluginNames; | ||
@@ -70,79 +68,1 @@ }; | ||
} | ||
export const QuoteRequestSchema = z | ||
.object({ | ||
sellAsset: z.string({ | ||
description: "Asset to sell", | ||
}), | ||
buyAsset: z.string({ | ||
description: "Asset to buy", | ||
}), | ||
sellAmount: z | ||
.number({ | ||
description: "Amount of asset to sell", | ||
}) | ||
.refine((amount) => amount > 0, { | ||
message: "sellAmount must be greater than 0", | ||
path: ["sellAmount"], | ||
}), | ||
providers: z.optional( | ||
z.array( | ||
z.string({ | ||
description: "List of providers to use", | ||
}), | ||
), | ||
), | ||
sourceAddress: z.optional( | ||
z.string({ | ||
description: "Address to send asset from", | ||
}), | ||
), | ||
destinationAddress: z.optional( | ||
z.string({ | ||
description: "Address to send asset to", | ||
}), | ||
), | ||
slippage: z.optional( | ||
z.number({ | ||
description: "Slippage tolerance as a percentage. Default is 3%.", | ||
}), | ||
), | ||
affiliate: z.optional( | ||
z.string({ | ||
description: "Affiliate thorname", | ||
}), | ||
), | ||
affiliateFee: z.optional( | ||
z | ||
.number({ | ||
description: "Affiliate fee in basis points", | ||
}) | ||
.refine( | ||
(fee) => { | ||
return fee === Math.floor(fee) && fee >= 0; | ||
}, | ||
{ message: "affiliateFee must be a positive integer", path: ["affiliateFee"] }, | ||
), | ||
), | ||
allowSmartContractSender: z.optional( | ||
z.boolean({ | ||
description: "Allow smart contract as sender", | ||
}), | ||
), | ||
allowSmartContractReceiver: z.optional( | ||
z.boolean({ | ||
description: "Allow smart contract as recipient", | ||
}), | ||
), | ||
disableSecurityChecks: z.optional( | ||
z.boolean({ | ||
description: "Disable security checks", | ||
}), | ||
), | ||
}) | ||
.refine((data) => data.sellAsset !== data.buyAsset, { | ||
message: "Must be different", | ||
path: ["sellAsset", "buyAsset"], | ||
}); | ||
export type QuoteRequest = z.infer<typeof QuoteRequestSchema>; |
import type { CosmosWallets, ThorchainWallets } from "@swapkit/toolbox-cosmos"; | ||
import type { EVMWallets } from "@swapkit/toolbox-evm"; | ||
import type { RadixWallets } from "@swapkit/toolbox-radix"; | ||
import type { SolanaWallets } from "@swapkit/toolbox-solana"; | ||
import type { SolanaWallet } from "@swapkit/toolbox-solana"; | ||
import type { SubstrateWallets } from "@swapkit/toolbox-substrate"; | ||
@@ -65,9 +64,3 @@ import type { UTXOWallets } from "@swapkit/toolbox-utxo"; | ||
export type FullWallet = BaseWallet< | ||
EVMWallets & | ||
UTXOWallets & | ||
CosmosWallets & | ||
ThorchainWallets & | ||
SubstrateWallets & | ||
SolanaWallets & | ||
RadixWallets | ||
EVMWallets & UTXOWallets & CosmosWallets & ThorchainWallets & SubstrateWallets & SolanaWallet | ||
>; | ||
@@ -74,0 +67,0 @@ |
Sorry, the diff of this file is too big to display
Sorry, the diff of this file is not supported yet
License Policy Violation
LicenseThis package is not allowed per your license policy. Review the package's license to ensure compliance.
Found 1 instance in 1 package
License Policy Violation
LicenseThis package is not allowed per your license policy. Review the package's license to ensure compliance.
Found 1 instance in 1 package
10
200
313787
35
4188
+ Added@swapkit/contracts@1.0.4
+ Added@swapkit/contracts@1.0.4(transitive)
+ Added@swapkit/tokens@0.0.0-nightly-20240806215520(transitive)
- Removedzod@3.23.8
- Removed@swapkit/tokens@0.0.0-nightly-20240724130444(transitive)
- Removedzod@3.23.8(transitive)