mirror of
https://github.com/orionprotocol/sdk.git
synced 2026-03-17 00:31:34 +03:00
Merge remote-tracking branch 'origin/main' into feat/platform-fees
# Conflicts: # package.json
This commit is contained in:
786
package-lock.json
generated
786
package-lock.json
generated
File diff suppressed because it is too large
Load Diff
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@orionprotocol/sdk",
|
||||
"version": "0.19.58-rc1",
|
||||
"version": "0.19.58-rc2",
|
||||
"description": "Orion Protocol SDK",
|
||||
"main": "./lib/index.cjs",
|
||||
"module": "./lib/index.js",
|
||||
@@ -113,4 +113,5 @@
|
||||
"overrides": {
|
||||
"tsconfig-paths": "^4.0.0"
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -130,19 +130,19 @@ const getHistory = async (units: Unit[], address: string, limit = 1000) => {
|
||||
asset: string
|
||||
sender: string
|
||||
secretHash: string
|
||||
receiver: string | undefined
|
||||
secret: string | undefined
|
||||
receiver?: string | undefined
|
||||
secret?: string | undefined
|
||||
timestamp: TargetItem['timestamp'] & SourceItem['timestamp']
|
||||
expiration: TargetItem['expiration'] & SourceItem['expiration']
|
||||
transactions: TargetItem['transactions'] & SourceItem['transactions']
|
||||
lockOrder: AggItem['lockOrder'] | undefined
|
||||
redeemOrder: AggItem['redeemOrder'] | undefined
|
||||
lockOrder?: AggItem['lockOrder'] | undefined
|
||||
redeemOrder?: AggItem['redeemOrder'] | undefined
|
||||
amountToReceive: SourceItem['amountToReceive']
|
||||
amountToSpend: SourceItem['amountToSpend']
|
||||
status: {
|
||||
source: SourceItem['state']
|
||||
target: TargetItem['state'] | undefined
|
||||
aggregator: AggItem['status'] | undefined
|
||||
source?: SourceItem['state'] | undefined
|
||||
target?: TargetItem['state'] | undefined
|
||||
aggregator?: AggItem['status'] | undefined
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -1,78 +1,267 @@
|
||||
import type { ethers } from 'ethers';
|
||||
import {
|
||||
type AtomicSwap, type SupportedChainId,
|
||||
type Unit, INTERNAL_PROTOCOL_PRECISION
|
||||
import { ethers } from 'ethers';
|
||||
import type {
|
||||
Unit, AtomicSwapLocal, SupportedChainId, TransactionInfo, AtomicSwap, RedeemOrder
|
||||
} from '../../index.js';
|
||||
import getHistoryExt from './getHistory.js';
|
||||
import { INTERNAL_PROTOCOL_PRECISION, TxStatus, TxType } from '../../index.js';
|
||||
import getHistory from './getHistory.js';
|
||||
import swapExt from './swap.js';
|
||||
|
||||
import { BigNumber } from 'bignumber.js';
|
||||
import generateSecret from '../../utils/generateSecret.js';
|
||||
import { isPresent } from 'ts-is-present';
|
||||
import { invariant } from '../../utils/invariant.js';
|
||||
import { simpleFetch } from 'simple-typed-fetch';
|
||||
|
||||
export const SECONDS_IN_DAY = 60 * 60 * 24;
|
||||
export const EXPIRATION_DAYS = 4;
|
||||
|
||||
type ExternalAtomicsData = Awaited<ReturnType<typeof getHistory>>;
|
||||
export default class Bridge {
|
||||
readonly EXTERNAL_ATOMICS_DATA_CACHE_TIME_MS = 5 * 1000; // 5 seconds
|
||||
private externalAtomicSwaps: Partial<Record<string, { // wallet address -> data
|
||||
lastUpdate: number
|
||||
data: ExternalAtomicsData
|
||||
}>> = {};
|
||||
|
||||
readonly ADDRESS_TO_ASSET_CACHE_TIME_MS = 5 * 60 * 1000; // 5 minutes
|
||||
private addressToAsset: {
|
||||
lastUpdate: number
|
||||
data: Partial<Record<string, Partial<Record<SupportedChainId, string>>>>
|
||||
} = { lastUpdate: 0, data: {} };
|
||||
|
||||
constructor(
|
||||
private readonly unitsArray: Unit[],
|
||||
) {}
|
||||
|
||||
async getMergedHistory(
|
||||
externalStoredAtomicSwaps: AtomicSwap[],
|
||||
walletAddress: string,
|
||||
registerRedeemOrder(
|
||||
secretHash: string,
|
||||
redeemOrder: RedeemOrder,
|
||||
) {
|
||||
const bridgeHistory = await this.getHistory(walletAddress);
|
||||
|
||||
return Object.values(bridgeHistory).map((atomicSwap) => {
|
||||
if (atomicSwap === undefined) throw new Error('No atomic swap');
|
||||
|
||||
const {
|
||||
secretHash,
|
||||
amountToReceive,
|
||||
amountToSpend,
|
||||
targetChainId,
|
||||
asset,
|
||||
sourceChainId,
|
||||
sender,
|
||||
transactions,
|
||||
expiration,
|
||||
creationDate,
|
||||
} = atomicSwap;
|
||||
|
||||
const localSwap = externalStoredAtomicSwaps.find(
|
||||
(swap) => secretHash === swap.secretHash,
|
||||
);
|
||||
|
||||
const amount = amountToReceive ?? amountToSpend ?? 0;
|
||||
|
||||
// Checking if transaction hash from blockchain is different from the same in local storage
|
||||
// and changing it to the correct one
|
||||
|
||||
let assetName = asset;
|
||||
|
||||
// LEGACY. Some old atomic swaps have address instead of asset name. Here we handle this case
|
||||
if (asset.includes('0x')) {
|
||||
assetName = '—'; // We don't want to display address even if we can't find asset name
|
||||
const senderCached = this.externalAtomicSwaps[redeemOrder.sender];
|
||||
const receiverCached = this.externalAtomicSwaps[redeemOrder.receiver];
|
||||
if (senderCached !== undefined) {
|
||||
const atomic = senderCached.data[secretHash];
|
||||
if (atomic !== undefined) {
|
||||
atomic.redeemOrder = redeemOrder;
|
||||
}
|
||||
|
||||
return {
|
||||
localSwap,
|
||||
sourceNetwork: sourceChainId,
|
||||
targetNetwork: targetChainId,
|
||||
amount: new BigNumber(amount)
|
||||
.multipliedBy(new BigNumber(10).pow(INTERNAL_PROTOCOL_PRECISION))
|
||||
.toString(),
|
||||
walletAddress: sender,
|
||||
secretHash,
|
||||
lockTransactionHash: transactions?.lock,
|
||||
refundTransactionHash: transactions?.refund,
|
||||
asset: assetName,
|
||||
expiration:
|
||||
expiration?.lock ?? creationDate.getTime() + 60 * 60 * 24 * 4, // Or default 4 days
|
||||
creationDate: creationDate.getTime(),
|
||||
redeemOrder: atomicSwap.redeemOrder,
|
||||
};
|
||||
});
|
||||
}
|
||||
if (receiverCached !== undefined) {
|
||||
const atomic = receiverCached.data[secretHash];
|
||||
if (atomic !== undefined) {
|
||||
atomic.redeemOrder = redeemOrder;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
getHistory(address: string, limit = 1000) {
|
||||
return getHistoryExt(this.unitsArray, address, limit);
|
||||
async getCombinedAddressToAsset() {
|
||||
const { lastUpdate, data } = this.addressToAsset;
|
||||
const cacheIsExpired = lastUpdate + this.EXTERNAL_ATOMICS_DATA_CACHE_TIME_MS < Date.now();
|
||||
if (!cacheIsExpired) return data;
|
||||
const addressToAssetData: Partial<Record<string, Partial<Record<SupportedChainId, string>>>> = {};
|
||||
await Promise.all(this.unitsArray.map(async (unit) => {
|
||||
const { blockchainService, chainId } = unit;
|
||||
const { assetToAddress } = await simpleFetch(blockchainService.getInfo)();
|
||||
Object.entries(assetToAddress).forEach(([asset, address]) => {
|
||||
if (address !== undefined) {
|
||||
const assetRecord = addressToAssetData[address];
|
||||
if (assetRecord !== undefined) {
|
||||
assetRecord[chainId] = asset;
|
||||
} else {
|
||||
addressToAssetData[address] = {
|
||||
[chainId]: asset,
|
||||
};
|
||||
}
|
||||
}
|
||||
});
|
||||
}));
|
||||
this.addressToAsset = {
|
||||
lastUpdate: Date.now(),
|
||||
data: addressToAssetData,
|
||||
}
|
||||
return addressToAssetData;
|
||||
}
|
||||
|
||||
async combineLocalAndExternalData(
|
||||
walletAddress: string,
|
||||
localAtomicSwaps: AtomicSwapLocal[],
|
||||
transactions: TransactionInfo[],
|
||||
) {
|
||||
// Prepare transactions data
|
||||
const byTxHashMap = new Map<string, TransactionInfo>();
|
||||
type BridgeTxs = {
|
||||
lockTx?: TransactionInfo | undefined
|
||||
redeemTx?: TransactionInfo | undefined
|
||||
refundTx?: TransactionInfo | undefined
|
||||
};
|
||||
const bySecretHashMap = new Map<string, BridgeTxs>();
|
||||
transactions.forEach((tx) => {
|
||||
if (tx.hash !== undefined) byTxHashMap.set(tx.hash, tx);
|
||||
if (tx.payload) {
|
||||
const { type, data } = tx.payload;
|
||||
if (type === TxType.BRIDGE_LOCK || type === TxType.BRIDGE_REDEEM || type === TxType.BRIDGE_REFUND) {
|
||||
const item = bySecretHashMap.get(data.secretHash);
|
||||
bySecretHashMap.set(data.secretHash, {
|
||||
...item,
|
||||
lockTx: type === TxType.BRIDGE_LOCK ? tx : item?.lockTx,
|
||||
redeemTx: type === TxType.BRIDGE_REDEEM ? tx : item?.redeemTx,
|
||||
refundTx: type === TxType.BRIDGE_REFUND ? tx : item?.refundTx,
|
||||
});
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
// Combine local data and external data
|
||||
const bridgeHistory = await this.getHistory(walletAddress);
|
||||
const combinedAddressToAsset = await this.getCombinedAddressToAsset();
|
||||
const atomicSwapsMap = new Map<string, AtomicSwap>();
|
||||
Object.values(bridgeHistory)
|
||||
.filter(isPresent)
|
||||
.forEach((atomicHistoryItem) => {
|
||||
const { lock, redeem, refund } = atomicHistoryItem.transactions ?? {};
|
||||
const lockTx = lock !== undefined
|
||||
? {
|
||||
hash: lock,
|
||||
status: TxStatus.SETTLED,
|
||||
}
|
||||
: undefined;
|
||||
const redeemTx = redeem !== undefined
|
||||
? {
|
||||
hash: redeem,
|
||||
status: TxStatus.SETTLED,
|
||||
}
|
||||
: undefined;
|
||||
const refundTx = refund !== undefined
|
||||
? {
|
||||
hash: refund,
|
||||
status: TxStatus.SETTLED,
|
||||
}
|
||||
: undefined;
|
||||
|
||||
let redeemExpired = false;
|
||||
|
||||
// If redeem order is expired
|
||||
if (atomicHistoryItem.redeemOrder) {
|
||||
const currentTime = Date.now();
|
||||
if (currentTime > atomicHistoryItem.redeemOrder.expiration) redeemExpired = true;
|
||||
}
|
||||
|
||||
const assetName = combinedAddressToAsset[atomicHistoryItem.asset]?.[atomicHistoryItem.sourceChainId];
|
||||
|
||||
const amount = atomicHistoryItem.amountToReceive ?? atomicHistoryItem.amountToSpend;
|
||||
|
||||
invariant(atomicHistoryItem.expiration?.lock, 'Lock expiration must be defined');
|
||||
atomicSwapsMap.set(atomicHistoryItem.secretHash, {
|
||||
...atomicHistoryItem,
|
||||
walletAddress: atomicHistoryItem.sender,
|
||||
creationDate: atomicHistoryItem.creationDate.getTime(),
|
||||
assetName,
|
||||
lockTx,
|
||||
amount: amount !== undefined ? amount.toString() : undefined,
|
||||
redeemTx,
|
||||
refundTx,
|
||||
lockExpiration: atomicHistoryItem.expiration.lock,
|
||||
redeemExpired,
|
||||
});
|
||||
});
|
||||
localAtomicSwaps.forEach((atomic) => {
|
||||
const atomicInMap = atomicSwapsMap.get(atomic.secretHash);
|
||||
|
||||
const { liquidityMigrationTxHash, redeemSettlement, secretHash } = atomic;
|
||||
|
||||
const secretHashTxs = bySecretHashMap.get(secretHash);
|
||||
let redeemTx: TransactionInfo | undefined;
|
||||
if (redeemSettlement) {
|
||||
if (redeemSettlement.type === 'own_tx') {
|
||||
redeemTx = secretHashTxs?.redeemTx;
|
||||
} else if (redeemSettlement.result) {
|
||||
redeemTx = {
|
||||
status: redeemSettlement.result.value === 'success' ? TxStatus.SETTLED : TxStatus.FAILED,
|
||||
}
|
||||
} else if (redeemSettlement.requestedAt !== undefined) {
|
||||
redeemTx = {
|
||||
status: TxStatus.PENDING,
|
||||
}
|
||||
}
|
||||
}
|
||||
const liquidityMigrationTx = liquidityMigrationTxHash !== undefined ? byTxHashMap.get(liquidityMigrationTxHash) : undefined;
|
||||
const amount = atomic.amount !== undefined
|
||||
? new BigNumber(atomic.amount).div(10 ** INTERNAL_PROTOCOL_PRECISION).toString()
|
||||
: undefined;
|
||||
if (atomicInMap) { // Merge local and backend data
|
||||
atomicSwapsMap.set(atomic.secretHash, {
|
||||
...atomicInMap,
|
||||
...atomic,
|
||||
lockExpiration: atomicInMap.lockExpiration,
|
||||
targetChainId: atomicInMap.targetChainId,
|
||||
sourceChainId: atomicInMap.sourceChainId,
|
||||
amount: atomicInMap.amount ?? amount,
|
||||
lockTx: atomicInMap.lockTx ?? secretHashTxs?.lockTx,
|
||||
redeemTx: atomicInMap.redeemTx ?? redeemTx,
|
||||
refundTx: atomicInMap.refundTx ?? secretHashTxs?.refundTx,
|
||||
liquidityMigrationTx: atomicInMap.liquidityMigrationTx ?? liquidityMigrationTx,
|
||||
});
|
||||
} else {
|
||||
invariant(atomic.targetChainId, 'Target chain id is not defined');
|
||||
invariant(atomic.sourceChainId, 'Source chain id is not defined');
|
||||
invariant(atomic.lockExpiration, 'Lock expiration is not defined');
|
||||
|
||||
atomicSwapsMap.set(atomic.secretHash, {
|
||||
...atomic,
|
||||
sourceChainId: atomic.sourceChainId,
|
||||
targetChainId: atomic.targetChainId,
|
||||
lockExpiration: atomic.lockExpiration,
|
||||
lockTx: secretHashTxs?.lockTx,
|
||||
redeemTx,
|
||||
refundTx: secretHashTxs?.refundTx,
|
||||
liquidityMigrationTx,
|
||||
});
|
||||
}
|
||||
});
|
||||
return atomicSwapsMap;
|
||||
}
|
||||
|
||||
makeAtomicSwap(
|
||||
walletAddress: string,
|
||||
networkFrom: SupportedChainId,
|
||||
networkTo: SupportedChainId,
|
||||
amount: string,
|
||||
asset: string,
|
||||
env?: string | undefined,
|
||||
) {
|
||||
const secret = generateSecret();
|
||||
const secretHash = ethers.utils.keccak256(secret);
|
||||
const lockExpiration = Date.now() + SECONDS_IN_DAY * EXPIRATION_DAYS * 1000;
|
||||
|
||||
return {
|
||||
sourceChainId: networkFrom,
|
||||
targetChainId: networkTo,
|
||||
amount,
|
||||
walletAddress,
|
||||
secret,
|
||||
secretHash,
|
||||
assetName: asset,
|
||||
creationDate: Date.now(),
|
||||
lockExpiration,
|
||||
env,
|
||||
};
|
||||
}
|
||||
|
||||
async getHistory(address: string, limit = 1000) {
|
||||
const cachedData = this.externalAtomicSwaps[address];
|
||||
let data: ExternalAtomicsData | undefined;
|
||||
if (cachedData !== undefined) {
|
||||
const cacheIsExpired = cachedData.lastUpdate + this.EXTERNAL_ATOMICS_DATA_CACHE_TIME_MS < Date.now();
|
||||
if (!cacheIsExpired) data = cachedData.data;
|
||||
}
|
||||
|
||||
if (data === undefined) {
|
||||
data = await getHistory(this.unitsArray, address, limit);
|
||||
this.externalAtomicSwaps[address] = {
|
||||
lastUpdate: Date.now(),
|
||||
data,
|
||||
};
|
||||
}
|
||||
return data;
|
||||
}
|
||||
|
||||
swap(
|
||||
|
||||
315
src/Unit/Exchange/generateSwapCalldata.ts
Normal file
315
src/Unit/Exchange/generateSwapCalldata.ts
Normal file
@@ -0,0 +1,315 @@
|
||||
import type { ExchangeWithGenericSwap } from '@orionprotocol/contracts/lib/ethers-v5/Exchange.js';
|
||||
import { UniswapV3Pool__factory, ERC20__factory, SwapExecutor__factory, CurveRegistry__factory } from '@orionprotocol/contracts/lib/ethers-v5/index.js';
|
||||
import { BigNumber, ethers, type BigNumberish } from 'ethers';
|
||||
import { concat, defaultAbiCoder, type BytesLike } from 'ethers/lib/utils.js';
|
||||
import { safeGet, SafeArray } from '../../utils/safeGetters.js';
|
||||
import type Unit from '../index.js';
|
||||
import { simpleFetch } from 'simple-typed-fetch';
|
||||
import type { PromiseOrValue } from '@orionprotocol/contracts/lib/ethers-v5/common.js';
|
||||
|
||||
const EXECUTOR_SWAP_FUNCTION = "func_70LYiww"
|
||||
|
||||
export type Factory = "UniswapV2" | "UniswapV3" | "Curve" | "OrionV2" | "OrionV3"
|
||||
|
||||
const exchangeToType: Partial<Record<string, Factory>> = {
|
||||
'SPOOKYSWAP': 'UniswapV2',
|
||||
'PANCAKESWAP': 'UniswapV2',
|
||||
'UNISWAP': 'UniswapV2',
|
||||
'QUICKSWAP': 'UniswapV2',
|
||||
'ORION_POOL': 'UniswapV2',
|
||||
'CHERRYSWAP': 'UniswapV2',
|
||||
'OKXSWAP': 'UniswapV2',
|
||||
'INTERNAL_POOL_V2': 'UniswapV2',
|
||||
'INTERNAL_POOL_V3': "OrionV3",
|
||||
'INTERNAL_POOL_V3_0_01': "OrionV3",
|
||||
'INTERNAL_POOL_V3_0_05': "OrionV3",
|
||||
'INTERNAL_POOL_V3_0_3': "OrionV3",
|
||||
'INTERNAL_POOL_V3_1_0': "OrionV3",
|
||||
'CURVE': "Curve",
|
||||
'CURVE_FACTORY': "Curve",
|
||||
}
|
||||
|
||||
export type SwapInfo = {
|
||||
pool: string,
|
||||
assetIn: string,
|
||||
assetOut: string,
|
||||
factory: string
|
||||
}
|
||||
|
||||
export type CallParams = {
|
||||
isMandatory?: boolean,
|
||||
target?: string,
|
||||
gaslimit?: BigNumber,
|
||||
value?: BigNumber
|
||||
}
|
||||
|
||||
export type GenerateSwapCalldataParams = {
|
||||
amount: BigNumberish,
|
||||
minReturnAmount: BigNumberish,
|
||||
receiverAddress: string,
|
||||
path: ArrayLike<SwapInfo>,
|
||||
unit: Unit
|
||||
}
|
||||
|
||||
export default async function generateSwapCalldata({
|
||||
amount,
|
||||
minReturnAmount,
|
||||
receiverAddress,
|
||||
path: path_,
|
||||
unit
|
||||
}: GenerateSwapCalldataParams
|
||||
): Promise<{ calldata: string, swapDescription: ExchangeWithGenericSwap.SwapDescriptionStruct }> {
|
||||
if (path_ == undefined || path_.length == 0) {
|
||||
throw new Error(`Empty path`);
|
||||
}
|
||||
const wethAddress = safeGet(unit.contracts, "WETH")
|
||||
const curveRegistryAddress = safeGet(unit.contracts, "curveRegistry")
|
||||
const {assetToAddress, swapExecutorContractAddress, exchangeContractAddress} = await simpleFetch(unit.blockchainService.getInfo)();
|
||||
let path = SafeArray.from(path_).map((swapInfo) => {
|
||||
swapInfo.assetIn = safeGet(assetToAddress, swapInfo.assetIn);
|
||||
swapInfo.assetOut = safeGet(assetToAddress, swapInfo.assetOut);
|
||||
return swapInfo;
|
||||
})
|
||||
const factory = path.first().factory
|
||||
if (!path.every(swapInfo => swapInfo.factory === factory)) {
|
||||
throw new Error(`Supporting only swaps with single factory`);
|
||||
}
|
||||
|
||||
const swapDescription: ExchangeWithGenericSwap.SwapDescriptionStruct = {
|
||||
srcToken: path.first().assetIn,
|
||||
dstToken: path.last().assetOut,
|
||||
srcReceiver: swapExecutorContractAddress,
|
||||
dstReceiver: receiverAddress,
|
||||
amount: amount,
|
||||
minReturnAmount: minReturnAmount,
|
||||
flags: 0
|
||||
}
|
||||
|
||||
const exchangeToNativeDecimals = async (token: PromiseOrValue<string>) => {
|
||||
token = await token
|
||||
let decimals = 18
|
||||
if (token !== ethers.constants.AddressZero) {
|
||||
const contract = ERC20__factory.connect(token, unit.provider)
|
||||
decimals = await contract.decimals()
|
||||
}
|
||||
return BigNumber.from(amount).mul(BigNumber.from(10).pow(decimals)).div(BigNumber.from(10).pow(8))
|
||||
}
|
||||
const amountNativeDecimals = await exchangeToNativeDecimals(swapDescription.srcToken);
|
||||
|
||||
path = SafeArray.from(path_).map((swapInfo) => {
|
||||
if (swapInfo.assetIn == ethers.constants.AddressZero) swapInfo.assetIn = wethAddress
|
||||
if (swapInfo.assetOut == ethers.constants.AddressZero) swapInfo.assetOut = wethAddress
|
||||
return swapInfo;
|
||||
});
|
||||
|
||||
|
||||
let calldata: string
|
||||
switch (exchangeToType[factory]) {
|
||||
case "OrionV2": {
|
||||
swapDescription.srcReceiver = path.first().pool
|
||||
calldata = await generateUni2Calls(exchangeContractAddress, path);
|
||||
break;
|
||||
}
|
||||
case "UniswapV2": {
|
||||
swapDescription.srcReceiver = path.first().pool
|
||||
calldata = await generateUni2Calls(exchangeContractAddress, path);
|
||||
break;
|
||||
}
|
||||
case "UniswapV3": {
|
||||
calldata = await generateUni3Calls(amountNativeDecimals, exchangeContractAddress, path, unit.provider)
|
||||
break;
|
||||
}
|
||||
case "OrionV3": {
|
||||
calldata = await generateOrion3Calls(amountNativeDecimals, exchangeContractAddress, path, unit.provider)
|
||||
break;
|
||||
}
|
||||
case "Curve": {
|
||||
calldata = await generateCurveStableSwapCalls(
|
||||
amountNativeDecimals,
|
||||
exchangeContractAddress,
|
||||
swapExecutorContractAddress,
|
||||
path,
|
||||
unit.provider,
|
||||
curveRegistryAddress
|
||||
);
|
||||
break;
|
||||
}
|
||||
default: {
|
||||
throw new Error(`Factory ${factory} is not supported`)
|
||||
}
|
||||
}
|
||||
return { swapDescription, calldata }
|
||||
}
|
||||
|
||||
export async function generateUni2Calls(
|
||||
exchangeAddress: string,
|
||||
path: SafeArray<SwapInfo>
|
||||
) {
|
||||
const executorInterface = SwapExecutor__factory.createInterface()
|
||||
const calls: BytesLike[] = []
|
||||
if (path.length > 1) {
|
||||
for (let i = 0; i < path.length - 1; ++i) {
|
||||
const currentSwap = path.get(i)
|
||||
const nextSwap = path.get(i + 1)
|
||||
|
||||
const calldata = executorInterface.encodeFunctionData("swapUniV2", [
|
||||
currentSwap.pool,
|
||||
currentSwap.assetIn,
|
||||
currentSwap.assetOut,
|
||||
defaultAbiCoder.encode(["uint256"], [concat(["0x03", nextSwap.pool])]),
|
||||
]
|
||||
)
|
||||
calls.push(addCallParams(calldata))
|
||||
}
|
||||
}
|
||||
const lastSwap = path.last();
|
||||
const calldata = executorInterface.encodeFunctionData("swapUniV2", [
|
||||
lastSwap.pool,
|
||||
lastSwap.assetIn,
|
||||
lastSwap.assetOut,
|
||||
defaultAbiCoder.encode(["uint256"], [concat(["0x03", exchangeAddress])]),
|
||||
])
|
||||
calls.push(addCallParams(calldata))
|
||||
|
||||
return generateCalls(calls)
|
||||
}
|
||||
|
||||
async function generateUni3Calls(
|
||||
amount: BigNumberish,
|
||||
exchangeContractAddress: string,
|
||||
path: SafeArray<SwapInfo>,
|
||||
provider: ethers.providers.JsonRpcProvider
|
||||
) {
|
||||
const encodedPools: BytesLike[] = []
|
||||
for (const swap of path) {
|
||||
const pool = UniswapV3Pool__factory.connect(swap.pool, provider)
|
||||
const token0 = await pool.token0()
|
||||
const zeroForOne = token0.toLowerCase() === swap.assetIn.toLowerCase()
|
||||
const unwrapWETH = swap.assetOut === ethers.constants.AddressZero
|
||||
|
||||
let encodedPool = ethers.utils.solidityPack(["uint256"], [pool.address])
|
||||
encodedPool = ethers.utils.hexDataSlice(encodedPool, 1)
|
||||
let firstByte = 0
|
||||
if (unwrapWETH) firstByte += 32
|
||||
if (!zeroForOne) firstByte += 128
|
||||
const encodedFirstByte = ethers.utils.solidityPack(["uint8"], [firstByte])
|
||||
encodedPool = ethers.utils.hexlify(ethers.utils.concat([encodedFirstByte, encodedPool]))
|
||||
encodedPools.push(encodedPool)
|
||||
}
|
||||
const executorInterface = SwapExecutor__factory.createInterface()
|
||||
let calldata = executorInterface.encodeFunctionData("uniswapV3SwapTo", [encodedPools, exchangeContractAddress, amount])
|
||||
calldata = addCallParams(calldata)
|
||||
|
||||
return generateCalls([calldata])
|
||||
}
|
||||
|
||||
async function generateOrion3Calls(
|
||||
amount: BigNumberish,
|
||||
exchangeContractAddress: string,
|
||||
path: SafeArray<SwapInfo>,
|
||||
provider: ethers.providers.JsonRpcProvider
|
||||
) {
|
||||
const encodedPools: BytesLike[] = []
|
||||
for (const swap of path) {
|
||||
const pool = UniswapV3Pool__factory.connect(swap.pool, provider)
|
||||
const token0 = await pool.token0()
|
||||
const zeroForOne = token0.toLowerCase() === swap.assetIn.toLowerCase()
|
||||
const unwrapWETH = swap.assetOut === ethers.constants.AddressZero
|
||||
|
||||
let encodedPool = ethers.utils.solidityPack(["uint256"], [pool.address])
|
||||
encodedPool = ethers.utils.hexDataSlice(encodedPool, 1)
|
||||
let firstByte = 0
|
||||
if (unwrapWETH) firstByte += 32
|
||||
if (!zeroForOne) firstByte += 128
|
||||
const encodedFirstByte = ethers.utils.solidityPack(["uint8"], [firstByte])
|
||||
encodedPool = ethers.utils.hexlify(ethers.utils.concat([encodedFirstByte, encodedPool]))
|
||||
encodedPools.push(encodedPool)
|
||||
}
|
||||
const executorInterface = SwapExecutor__factory.createInterface()
|
||||
let calldata = executorInterface.encodeFunctionData("orionV3SwapTo", [encodedPools, exchangeContractAddress, amount])
|
||||
calldata = addCallParams(calldata)
|
||||
|
||||
return generateCalls([calldata])
|
||||
}
|
||||
|
||||
async function generateCurveStableSwapCalls(
|
||||
amount: BigNumberish,
|
||||
exchangeContractAddress: string,
|
||||
executorAddress: string,
|
||||
path: SafeArray<SwapInfo>,
|
||||
provider: ethers.providers.JsonRpcProvider,
|
||||
curveRegistry: string
|
||||
) {
|
||||
if (path.length > 1) {
|
||||
throw new Error("Supporting only single stable swap on curve")
|
||||
}
|
||||
const executorInterface = SwapExecutor__factory.createInterface()
|
||||
const registry = CurveRegistry__factory.connect(curveRegistry, provider)
|
||||
|
||||
const swap = path.first()
|
||||
const firstToken = ERC20__factory.connect(swap.assetIn, provider)
|
||||
const { pool, assetIn, assetOut } = swap
|
||||
const [i, j,] = await registry.get_coin_indices(pool, assetIn, assetOut)
|
||||
|
||||
const executorAllowance = await firstToken.allowance(executorAddress, swap.pool)
|
||||
const calls: BytesLike[] = []
|
||||
if (executorAllowance.lt(amount)) {
|
||||
const calldata = addCallParams(
|
||||
executorInterface.encodeFunctionData("safeApprove", [
|
||||
swap.assetIn,
|
||||
swap.pool,
|
||||
ethers.constants.MaxUint256
|
||||
])
|
||||
)
|
||||
calls.push(calldata)
|
||||
}
|
||||
let calldata = executorInterface.encodeFunctionData("curveSwapStableAmountIn", [
|
||||
pool,
|
||||
assetOut,
|
||||
i,
|
||||
j,
|
||||
amount,
|
||||
0,
|
||||
exchangeContractAddress])
|
||||
|
||||
calldata = addCallParams(calldata)
|
||||
calls.push(calldata)
|
||||
|
||||
return generateCalls(calls)
|
||||
}
|
||||
|
||||
// Adds additional byte to single swap with settings
|
||||
function addCallParams(
|
||||
calldata: BytesLike,
|
||||
callParams?: CallParams
|
||||
) {
|
||||
let firstByte = 0
|
||||
if (callParams) {
|
||||
if (callParams.value !== undefined) {
|
||||
firstByte += 16 // 00010000
|
||||
const encodedValue = ethers.utils.solidityPack(["uint128"], [callParams.value])
|
||||
calldata = ethers.utils.hexlify(ethers.utils.concat([encodedValue, calldata]))
|
||||
}
|
||||
if (callParams.target !== undefined) {
|
||||
firstByte += 32 // 00100000
|
||||
const encodedAddress = ethers.utils.solidityPack(["address"], [callParams.target])
|
||||
calldata = ethers.utils.hexlify(ethers.utils.concat([encodedAddress, calldata]))
|
||||
}
|
||||
if (callParams.gaslimit !== undefined) {
|
||||
firstByte += 64 // 01000000
|
||||
const encodedGaslimit = ethers.utils.solidityPack(["uint32"], [callParams.gaslimit])
|
||||
calldata = ethers.utils.hexlify(ethers.utils.concat([encodedGaslimit, calldata]))
|
||||
}
|
||||
if (callParams.isMandatory !== undefined) firstByte += 128 // 10000000
|
||||
}
|
||||
|
||||
const encodedFirstByte = ethers.utils.solidityPack(["uint8"], [firstByte])
|
||||
calldata = ethers.utils.hexlify(ethers.utils.concat([encodedFirstByte, calldata]))
|
||||
return calldata
|
||||
}
|
||||
|
||||
|
||||
async function generateCalls(calls: BytesLike[]) {
|
||||
const executorInterface = SwapExecutor__factory.createInterface()
|
||||
return "0x" + executorInterface.encodeFunctionData(EXECUTOR_SWAP_FUNCTION, [ethers.constants.AddressZero, calls]).slice(74)
|
||||
}
|
||||
@@ -1,8 +1,8 @@
|
||||
import type Unit from '../index.js';
|
||||
import deposit, { type DepositParams } from './deposit.js';
|
||||
import getSwapInfo, { type GetSwapInfoParams } from './getSwapInfo.js';
|
||||
import type { SwapLimitParams } from './swapLimit.js';
|
||||
import swapLimit from './swapLimit.js';
|
||||
import generateSwapCalldata, { type GenerateSwapCalldataParams } from './generateSwapCalldata.js';
|
||||
import swapLimit, {type SwapLimitParams} from './swapLimit.js';
|
||||
import swapMarket, { type SwapMarketParams } from './swapMarket.js';
|
||||
import withdraw, { type WithdrawParams } from './withdraw.js';
|
||||
|
||||
@@ -11,6 +11,7 @@ type PureSwapLimitParams = Omit<SwapLimitParams, 'unit'>
|
||||
type PureDepositParams = Omit<DepositParams, 'unit'>
|
||||
type PureWithdrawParams = Omit<WithdrawParams, 'unit'>
|
||||
type PureGetSwapMarketInfoParams = Omit<GetSwapInfoParams, 'blockchainService' | 'aggregator'>
|
||||
type PureGenerateSwapCalldataParams = Omit<GenerateSwapCalldataParams, 'unit'>
|
||||
|
||||
export default class Exchange {
|
||||
private readonly unit: Unit;
|
||||
@@ -54,4 +55,11 @@ export default class Exchange {
|
||||
unit: this.unit,
|
||||
});
|
||||
}
|
||||
|
||||
public generateSwapCalldata(params: PureGenerateSwapCalldataParams) {
|
||||
return generateSwapCalldata({
|
||||
...params,
|
||||
unit: this.unit
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
@@ -32,6 +32,8 @@ export default class Unit {
|
||||
|
||||
public readonly config: VerboseUnitConfig;
|
||||
|
||||
public readonly contracts: Record<string, string>;
|
||||
|
||||
constructor(config: KnownConfig | VerboseUnitConfig) {
|
||||
if ('env' in config) {
|
||||
const staticConfig = envs[config.env];
|
||||
@@ -42,7 +44,6 @@ export default class Unit {
|
||||
|
||||
const networkConfig = staticConfig.networks[config.chainId];
|
||||
if (!networkConfig) throw new Error(`Invalid chainId: ${config.chainId}. Available chainIds: ${Object.keys(staticConfig.networks).join(', ')}`);
|
||||
|
||||
this.config = {
|
||||
chainId: config.chainId,
|
||||
nodeJsonRpc: networkConfig.rpc ?? chainConfig.rpc,
|
||||
@@ -64,9 +65,10 @@ export default class Unit {
|
||||
}
|
||||
const chainInfo = chains[config.chainId];
|
||||
if (!chainInfo) throw new Error('Chain info is required');
|
||||
|
||||
|
||||
this.chainId = config.chainId;
|
||||
this.networkCode = chainInfo.code;
|
||||
this.contracts = chainInfo.contracts
|
||||
const intNetwork = parseInt(this.chainId, 10);
|
||||
if (Number.isNaN(intNetwork)) throw new Error('Invalid chainId (not a number)' + this.chainId);
|
||||
this.provider = new ethers.providers.StaticJsonRpcProvider(this.config.nodeJsonRpc, intNetwork);
|
||||
|
||||
@@ -5,8 +5,12 @@
|
||||
"label": "Ethereum Mainnet",
|
||||
"shortName": "ETH",
|
||||
"code": "eth",
|
||||
"rpc": "https://trade.orionprotocol.io/rpc",
|
||||
"baseCurrencyName": "ETH"
|
||||
"rpc": "https://trade.orionprotocol.io/eth-mainnet/rpc",
|
||||
"baseCurrencyName": "ETH",
|
||||
"contracts": {
|
||||
"WETH": "0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2",
|
||||
"curveRegistry": "0x90E00ACe148ca3b23Ac1bC8C240C2a7Dd9c2d7f5"
|
||||
}
|
||||
},
|
||||
"56": {
|
||||
"chainId": "56",
|
||||
@@ -15,7 +19,11 @@
|
||||
"shortName": "BSC",
|
||||
"code": "bsc",
|
||||
"rpc": "https://bsc-dataseed.binance.org/",
|
||||
"baseCurrencyName": "BNB"
|
||||
"baseCurrencyName": "BNB",
|
||||
"contracts": {
|
||||
"WETH": "0xbb4CdB9CBd36B01bD1cBaEBF2De08d9173bc095c",
|
||||
"curveRegistry": ""
|
||||
}
|
||||
},
|
||||
"97": {
|
||||
"chainId": "97",
|
||||
@@ -23,8 +31,12 @@
|
||||
"label": "Binance Smart Chain Testnet",
|
||||
"shortName": "BSC-Testnet",
|
||||
"code": "bsc",
|
||||
"rpc": "https://bsc-stage.node.orionprotocol.io/",
|
||||
"baseCurrencyName": "BNB"
|
||||
"rpc": "https://data-seed-prebsc-1-s1.bnbchain.org:8545/",
|
||||
"baseCurrencyName": "BNB",
|
||||
"contracts": {
|
||||
"WETH": "0x23eE96bEaAB62abE126AA192e677c52bB7d274F0",
|
||||
"curveRegistry": "0x8845b36C3DE93379F468590FFa102D4aF8C49A6c"
|
||||
}
|
||||
},
|
||||
"3": {
|
||||
"chainId": "3",
|
||||
@@ -33,7 +45,11 @@
|
||||
"shortName": "ETH-Ropsten",
|
||||
"code": "eth",
|
||||
"rpc": "https://testing.orionprotocol.io/eth-ropsten/rpc",
|
||||
"baseCurrencyName": "ETH"
|
||||
"baseCurrencyName": "ETH",
|
||||
"contracts": {
|
||||
"WETH": "",
|
||||
"curveRegistry": ""
|
||||
}
|
||||
},
|
||||
"5": {
|
||||
"chainId": "5",
|
||||
@@ -42,7 +58,11 @@
|
||||
"shortName": "ETH-Goerli",
|
||||
"code": "eth",
|
||||
"rpc": "https://testing.orionprotocol.io/eth-goerli/rpc",
|
||||
"baseCurrencyName": "ETH"
|
||||
"baseCurrencyName": "ETH",
|
||||
"contracts": {
|
||||
"WETH": "",
|
||||
"curveRegistry": ""
|
||||
}
|
||||
},
|
||||
"421613": {
|
||||
"chainId": "421613",
|
||||
@@ -51,7 +71,11 @@
|
||||
"shortName": "Arbitrum Goerli",
|
||||
"code": "arb",
|
||||
"rpc": "https://goerli-rollup.arbitrum.io/rpc",
|
||||
"baseCurrencyName": "ETH"
|
||||
"baseCurrencyName": "ETH",
|
||||
"contracts": {
|
||||
"WETH": "",
|
||||
"curveRegistry": ""
|
||||
}
|
||||
},
|
||||
"4002": {
|
||||
"chainId": "4002",
|
||||
@@ -59,8 +83,12 @@
|
||||
"label": "Fantom Testnet",
|
||||
"shortName": "FTM-Testnet",
|
||||
"code": "ftm",
|
||||
"rpc": "https://testing.orionprotocol.io/ftm-testnet/rpc",
|
||||
"baseCurrencyName": "FTM"
|
||||
"rpc": "https://rpc.testnet.fantom.network/",
|
||||
"baseCurrencyName": "FTM",
|
||||
"contracts": {
|
||||
"WETH": "",
|
||||
"curveRegistry": ""
|
||||
}
|
||||
},
|
||||
"250": {
|
||||
"chainId": "250",
|
||||
@@ -69,7 +97,11 @@
|
||||
"shortName": "FTM",
|
||||
"code": "ftm",
|
||||
"rpc": "https://rpcapi.fantom.network/",
|
||||
"baseCurrencyName": "FTM"
|
||||
"baseCurrencyName": "FTM",
|
||||
"contracts": {
|
||||
"WETH": "",
|
||||
"curveRegistry": ""
|
||||
}
|
||||
},
|
||||
"137": {
|
||||
"chainId": "137",
|
||||
@@ -78,7 +110,11 @@
|
||||
"code": "polygon",
|
||||
"baseCurrencyName": "MATIC",
|
||||
"rpc": "https://polygon-rpc.com/",
|
||||
"explorer": "https://polygonscan.com/"
|
||||
"explorer": "https://polygonscan.com/",
|
||||
"contracts": {
|
||||
"WETH": "",
|
||||
"curveRegistry": ""
|
||||
}
|
||||
},
|
||||
"80001": {
|
||||
"chainId": "80001",
|
||||
@@ -87,7 +123,11 @@
|
||||
"code": "polygon",
|
||||
"baseCurrencyName": "MATIC",
|
||||
"rpc": "https://rpc-mumbai.matic.today",
|
||||
"explorer": "https://mumbai.polygonscan.com/"
|
||||
"explorer": "https://mumbai.polygonscan.com/",
|
||||
"contracts": {
|
||||
"WETH": "",
|
||||
"curveRegistry": ""
|
||||
}
|
||||
},
|
||||
"66": {
|
||||
"chainId": "66",
|
||||
@@ -96,7 +136,11 @@
|
||||
"shortName": "OKC",
|
||||
"code": "okc",
|
||||
"rpc": "https://exchainrpc.okex.org/",
|
||||
"baseCurrencyName": "OKT"
|
||||
"baseCurrencyName": "OKT",
|
||||
"contracts": {
|
||||
"WETH": "",
|
||||
"curveRegistry": ""
|
||||
}
|
||||
},
|
||||
"65": {
|
||||
"chainId": "65",
|
||||
@@ -105,7 +149,11 @@
|
||||
"shortName": "OKC-Testnet",
|
||||
"code": "okc",
|
||||
"rpc": "https://exchaintestrpc.okex.org/",
|
||||
"baseCurrencyName": "OKT"
|
||||
"baseCurrencyName": "OKT",
|
||||
"contracts": {
|
||||
"WETH": "",
|
||||
"curveRegistry": ""
|
||||
}
|
||||
},
|
||||
"56303": {
|
||||
"chainId": "56303",
|
||||
@@ -114,6 +162,10 @@
|
||||
"code": "drip",
|
||||
"baseCurrencyName": "DRIP",
|
||||
"rpc": "testnet.1d.rip",
|
||||
"explorer": "https://explorer-testnet.1d.rip/"
|
||||
"explorer": "https://explorer-testnet.1d.rip/",
|
||||
"contracts": {
|
||||
"WETH": "",
|
||||
"curveRegistry": ""
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -10,6 +10,7 @@ export const pureChainInfoPayloadSchema = z.object({
|
||||
explorer: z.string(),
|
||||
rpc: z.string(),
|
||||
baseCurrencyName: z.string(),
|
||||
contracts: z.record(z.string(), z.string())
|
||||
});
|
||||
|
||||
export const pureChainInfoSchema = z.record(
|
||||
|
||||
@@ -503,6 +503,12 @@ class AggregatorWS {
|
||||
minAmountIn: json.ma,
|
||||
path: json.ps,
|
||||
exchanges: json.e,
|
||||
exchangeContractPath: json.eps.map((path) => ({
|
||||
pool: path.p,
|
||||
assetIn: path.ai,
|
||||
assetOut: path.ao,
|
||||
factory: path.f,
|
||||
})),
|
||||
poolOptimal: json.po,
|
||||
...(json.oi) && {
|
||||
orderInfo: {
|
||||
|
||||
@@ -33,6 +33,12 @@ const swapInfoSchemaBase = baseMessageSchema.extend({
|
||||
}).optional(),
|
||||
as: alternativeSchema.array(),
|
||||
anm: z.record(z.string()).optional(), // address to ERC20 names
|
||||
eps: z.array(z.object({
|
||||
p: z.string(), // pool address
|
||||
ai: z.string().toUpperCase(), // asset in
|
||||
ao: z.string().toUpperCase(), // asset out
|
||||
f: z.string().toUpperCase(), // factory
|
||||
}))
|
||||
});
|
||||
|
||||
const swapInfoSchemaByAmountIn = swapInfoSchemaBase.extend({
|
||||
|
||||
@@ -34,7 +34,7 @@ const sourceAtomicHistorySchemaItem = baseAtomicHistoryItem.extend({
|
||||
expiration: z.object({
|
||||
lock: z.number().optional(),
|
||||
}).optional(),
|
||||
state: z.enum(['BEFORE-LOCK', 'LOCKED', 'REFUNDED', 'CLAIMED']),
|
||||
state: z.enum(['BEFORE-LOCK', 'LOCKED', 'REFUNDED', 'CLAIMED']).optional(),
|
||||
targetChainId: z.number(),
|
||||
transactions: z.object({
|
||||
lock: z.string().optional(),
|
||||
@@ -51,7 +51,7 @@ const targetAtomicHistorySchemaItem = baseAtomicHistoryItem.extend({
|
||||
expiration: z.object({
|
||||
redeem: z.number().optional(),
|
||||
}).optional(),
|
||||
state: z.enum(['BEFORE-REDEEM', 'REDEEMED']),
|
||||
state: z.enum(['BEFORE-REDEEM', 'REDEEMED']).optional(),
|
||||
transactions: z.object({
|
||||
redeem: z.string().optional(),
|
||||
}).optional(),
|
||||
|
||||
@@ -11,6 +11,7 @@ const infoSchema = z.object({
|
||||
chainId: z.number(),
|
||||
chainName: z.string(),
|
||||
exchangeContractAddress: z.string(),
|
||||
swapExecutorContractAddress: z.string(),
|
||||
oracleContractAddress: z.string(),
|
||||
matcherAddress: z.string(),
|
||||
orderFeePercent: z.number(),
|
||||
|
||||
164
src/types.ts
164
src/types.ts
@@ -3,6 +3,7 @@ import type { BigNumber } from 'bignumber.js';
|
||||
import type subOrderStatuses from './constants/subOrderStatuses.js';
|
||||
import type positionStatuses from './constants/positionStatuses.js';
|
||||
import type { knownEnvs } from './config/schemas/index.js';
|
||||
import type getHistory from './Orion/bridge/getHistory.js';
|
||||
|
||||
export type DeepPartial<T> = T extends object ? {
|
||||
[P in keyof T]?: DeepPartial<T[P]>;
|
||||
@@ -164,6 +165,13 @@ export type SwapInfoAlternative = {
|
||||
availableAmountOut?: number | undefined
|
||||
}
|
||||
|
||||
type ExchangeContractPath = {
|
||||
pool: string
|
||||
assetIn: string
|
||||
assetOut: string
|
||||
factory: string
|
||||
}
|
||||
|
||||
export type SwapInfoBase = {
|
||||
swapRequestId: string
|
||||
assetIn: string
|
||||
@@ -174,6 +182,7 @@ export type SwapInfoBase = {
|
||||
minAmountOut: number
|
||||
|
||||
path: string[]
|
||||
exchangeContractPath: ExchangeContractPath[]
|
||||
exchanges?: string[] | undefined
|
||||
poolOptimal: boolean
|
||||
|
||||
@@ -283,36 +292,149 @@ export type RedeemOrder = {
|
||||
claimReceiver: string
|
||||
}
|
||||
|
||||
export type AtomicSwap = {
|
||||
export interface AtomicSwapLocal {
|
||||
secret: string
|
||||
secretHash: string
|
||||
|
||||
walletAddress: string
|
||||
env?: string | undefined
|
||||
|
||||
sourceNetwork?: SupportedChainId
|
||||
targetNetwork?: SupportedChainId
|
||||
sourceChainId?: SupportedChainId | undefined
|
||||
targetChainId?: SupportedChainId | undefined
|
||||
|
||||
amount?: string
|
||||
asset?: string
|
||||
amount?: string | undefined
|
||||
assetName?: string | undefined
|
||||
|
||||
creationDate?: number
|
||||
expiration?: number
|
||||
liquidityMigrationTxHash?: string | undefined
|
||||
lockTransactionHash?: string | undefined
|
||||
refundTransactionHash?: string | undefined
|
||||
|
||||
lockTransactionHash?: string
|
||||
redeemTransactionHash?: string
|
||||
refundTransactionHash?: string
|
||||
liquidityMigrationTxHash?: string
|
||||
|
||||
redeemOrder?: RedeemOrder
|
||||
creationDate?: number | undefined
|
||||
lockExpiration?: number | undefined
|
||||
placingOrderError?: string | undefined
|
||||
redeemSettlement?: {
|
||||
type: 'own_tx'
|
||||
} | {
|
||||
type: 'orion_tx'
|
||||
requestedAt?: number
|
||||
result?: {
|
||||
timestamp: number
|
||||
value: 'success' | 'failed'
|
||||
}
|
||||
} | undefined
|
||||
}
|
||||
|
||||
export type ExternalStorage = {
|
||||
bridge: {
|
||||
getAtomicSwaps: () => AtomicSwap[]
|
||||
setAtomicSwaps: (atomics: AtomicSwap[]) => void
|
||||
addAtomicSwap: (atomic: AtomicSwap) => void
|
||||
updateAtomicSwap: (secretHash: string, atomic: Partial<AtomicSwap>) => void
|
||||
removeAtomicSwaps: (secretHashes: string[]) => void
|
||||
export enum TxStatus {
|
||||
QUEUED = 'queued',
|
||||
SIGN_FAILED = 'sign_failed',
|
||||
GAS_ESTIMATING = 'gas_estimating',
|
||||
ESTIMATE_GAS_FAILED = 'estimate_gas_failed',
|
||||
CANCELLED = 'cancelled',
|
||||
PENDING = 'pending',
|
||||
FAILED = 'failed',
|
||||
SETTLED = 'settled',
|
||||
SIGNING = 'signing',
|
||||
UNKNOWN = 'unknown',
|
||||
}
|
||||
|
||||
export enum TxType {
|
||||
SWAP_THROUGH_ORION_POOL = 'SWAP_THROUGH_ORION_POOL',
|
||||
DEPOSIT = 'DEPOSIT',
|
||||
WITHDRAW = 'WITHDRAW',
|
||||
BRIDGE_LOCK = 'BRIDGE_LOCK',
|
||||
BRIDGE_REDEEM = 'BRIDGE_REDEEM',
|
||||
BRIDGE_REFUND = 'BRIDGE_REFUND',
|
||||
LIQUIDITY_MIGRATION = 'LIQUIDITY_MIGRATION',
|
||||
REDEEM_TWO_ATOMICS = 'REDEEM_TWO_ATOMICS',
|
||||
}
|
||||
|
||||
export type TxDepositOrWithdrawPayload = {
|
||||
type: TxType.DEPOSIT | TxType.WITHDRAW
|
||||
data: {
|
||||
asset: string
|
||||
amount: string
|
||||
}
|
||||
};
|
||||
|
||||
export type TxSwapThroughOrionPoolPayload = {
|
||||
type: TxType.SWAP_THROUGH_ORION_POOL
|
||||
data: {
|
||||
side: 'buy' | 'sell'
|
||||
assetIn: string
|
||||
assetOut: string
|
||||
amount: string
|
||||
price: string
|
||||
}
|
||||
};
|
||||
|
||||
export type TxBridgePayload = {
|
||||
type: TxType.BRIDGE_LOCK | TxType.BRIDGE_REDEEM | TxType.BRIDGE_REFUND
|
||||
data: {
|
||||
secretHash: string
|
||||
}
|
||||
}
|
||||
|
||||
export type TxLiquidityMigrationPayload = {
|
||||
type: TxType.LIQUIDITY_MIGRATION
|
||||
data: {
|
||||
source: SupportedChainId
|
||||
target: SupportedChainId
|
||||
pair: string
|
||||
pairAddress: string
|
||||
assetA: {
|
||||
amount: string
|
||||
secretHash: string
|
||||
secret: string
|
||||
}
|
||||
assetB: {
|
||||
amount: string
|
||||
secretHash: string
|
||||
secret: string
|
||||
}
|
||||
expiration: number
|
||||
env?: string
|
||||
}
|
||||
}
|
||||
|
||||
export type TxRedeemTwoAtomicsPayload = {
|
||||
type: TxType.REDEEM_TWO_ATOMICS
|
||||
data: {
|
||||
secretHash1: string
|
||||
secretHash2: string
|
||||
}
|
||||
}
|
||||
|
||||
export type TransactionInfo = {
|
||||
id?: string
|
||||
status?: TxStatus
|
||||
hash?: string
|
||||
payload?: TxDepositOrWithdrawPayload
|
||||
| TxSwapThroughOrionPoolPayload
|
||||
| TxBridgePayload
|
||||
| TxLiquidityMigrationPayload
|
||||
| TxRedeemTwoAtomicsPayload
|
||||
}
|
||||
|
||||
type BridgeHistory = Awaited<ReturnType<typeof getHistory>>;
|
||||
|
||||
type BridgeHistoryItem = NonNullable<BridgeHistory[string]>;
|
||||
|
||||
export type AtomicSwap = Partial<
|
||||
Omit<BridgeHistoryItem, 'creationDate' | 'expiration' | 'secret'>
|
||||
> & Partial<
|
||||
Omit<AtomicSwapLocal, 'creationDate' | 'expiration' | 'secret'>
|
||||
> & {
|
||||
sourceChainId: SupportedChainId
|
||||
targetChainId: SupportedChainId
|
||||
lockExpiration: number
|
||||
secretHash: string
|
||||
walletAddress: string
|
||||
secret?: string | undefined
|
||||
|
||||
creationDate?: number | undefined
|
||||
redeemExpired?: boolean | undefined
|
||||
|
||||
lockTx?: TransactionInfo | undefined
|
||||
redeemTx?: TransactionInfo | undefined
|
||||
refundTx?: TransactionInfo | undefined
|
||||
liquidityMigrationTx?: TransactionInfo | undefined
|
||||
}
|
||||
|
||||
18
src/utils/invariant.ts
Normal file
18
src/utils/invariant.ts
Normal file
@@ -0,0 +1,18 @@
|
||||
export function invariant<T = unknown>(
|
||||
condition: T,
|
||||
errorMessage?: ((condition: T) => string) | string,
|
||||
): asserts condition {
|
||||
if (condition) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (typeof errorMessage === 'undefined') {
|
||||
throw new Error('Invariant failed');
|
||||
}
|
||||
|
||||
if (typeof errorMessage === 'string') {
|
||||
throw new Error(errorMessage);
|
||||
}
|
||||
|
||||
throw new Error(errorMessage(condition));
|
||||
}
|
||||
60
src/utils/safeGetters.ts
Normal file
60
src/utils/safeGetters.ts
Normal file
@@ -0,0 +1,60 @@
|
||||
export class SafeArray<T> extends Array<T> {
|
||||
|
||||
public static override from<T>(array: ArrayLike<T>): SafeArray<T> {
|
||||
return new SafeArray(array);
|
||||
}
|
||||
|
||||
constructor(array: ArrayLike<T>) {
|
||||
super(array.length);
|
||||
for (const index in array) {
|
||||
const value = array[index]
|
||||
if (value === undefined) {
|
||||
throw new Error("Array passed to constructor has undefined values")
|
||||
}
|
||||
this[index] = value
|
||||
}
|
||||
}
|
||||
|
||||
public toArray(): T[] {
|
||||
return [...this];
|
||||
}
|
||||
|
||||
public override map<U>(callbackfn: (value: T, index: number, array: T[]) => U, thisArg?: any): SafeArray<U> {
|
||||
return new SafeArray(super.map(callbackfn, thisArg));
|
||||
}
|
||||
|
||||
public override filter(callbackfn: (value: T, index: number, array: T[]) => boolean, thisArg?: any): SafeArray<T> {
|
||||
return new SafeArray(super.filter(callbackfn, thisArg));
|
||||
}
|
||||
|
||||
public get<T>(this: SafeArray<T>, index: number): T {
|
||||
const value = this.at(index);
|
||||
if (value === undefined) {
|
||||
throw new Error(`Element at index ${index} is undefined.`)
|
||||
}
|
||||
return value
|
||||
}
|
||||
|
||||
public last<T>(this: SafeArray<T>): T {
|
||||
return this.get(this.length - 1)
|
||||
}
|
||||
|
||||
public first<T>(this: SafeArray<T>): T {
|
||||
return this.get(0)
|
||||
}
|
||||
}
|
||||
|
||||
export function safeGet<V>(obj: Partial<Record<string, V>>, key: string, errorMessage?: string) {
|
||||
const value = obj[key];
|
||||
if (value === undefined) throw new Error(`Key '${key.toString()}' not found in object. Available keys: ${Object.keys(obj).join(', ')}.${errorMessage ? ` ${errorMessage}` : ''}`);
|
||||
return value;
|
||||
}
|
||||
|
||||
const prefix = 'Requirement not met';
|
||||
|
||||
export function must(condition: unknown, message?: string | (() => string)): asserts condition {
|
||||
if (condition) return;
|
||||
const provided = typeof message === 'function' ? message() : message;
|
||||
const value = provided ? `${prefix}: ${provided}` : prefix;
|
||||
throw new Error(value);
|
||||
}
|
||||
Reference in New Issue
Block a user