From 5b42700f694457247241efcb0f84624d27ed2ed1 Mon Sep 17 00:00:00 2001 From: nickkelly1 Date: Tue, 12 Nov 2024 16:13:53 -0600 Subject: [PATCH] chore: lint --- packages/extension-bridge/README.md | 4 +- .../extension-bridge/src/apis/onMessage.ts | 4 +- .../extension-bridge/src/apis/sendMessage.ts | 8 +- packages/extension-bridge/src/bridge.ts | 8 +- packages/extension-bridge/src/internal.ts | 32 ++-- packages/extension-bridge/src/stream.ts | 12 +- packages/extension-bridge/src/types.ts | 8 +- .../src/window/apis/onMessage.ts | 4 +- .../src/window/apis/sendMessage.ts | 8 +- .../extension-bridge/src/window/internal.ts | 16 +- packages/hw-wallets/src/index.ts | 8 +- .../hw-wallets/src/ledger/bitcoin/index.ts | 30 ++-- .../hw-wallets/src/ledger/ethereum/index.ts | 18 +- .../hw-wallets/src/ledger/ledgerConnect.ts | 6 +- .../hw-wallets/src/ledger/solana/index.ts | 8 +- .../hw-wallets/src/ledger/substrate/index.ts | 12 +- .../hw-wallets/src/ledger/substrate/utils.ts | 2 +- .../hw-wallets/src/trezor/bitcoin/index.ts | 6 +- .../hw-wallets/src/trezor/ethereum/index.ts | 6 +- .../hw-wallets/src/trezor/solana/index.ts | 2 +- packages/keyring/src/index.ts | 56 +++---- packages/keyring/src/utils.ts | 2 +- packages/keyring/tests/generate.test.ts | 16 +- packages/keyring/tests/lock.test.ts | 2 +- packages/keyring/tests/sign.test.ts | 34 ++-- packages/request/src/index.ts | 2 +- packages/request/src/libs/events.ts | 6 +- packages/request/src/libs/middleware.ts | 2 +- packages/request/src/libs/noClient.ts | 2 +- packages/request/src/libs/reconnectingWS.ts | 22 +-- packages/request/src/libs/rpcClient.ts | 4 +- packages/request/src/libs/wsClient.ts | 8 +- packages/request/tests/request.test.ts | 4 +- packages/signers/bitcoin/src/index.ts | 6 +- .../signers/bitcoin/tests/generate.test.ts | 8 +- packages/signers/bitcoin/tests/sign.test.ts | 4 +- packages/signers/ethereum/src/index.ts | 4 +- packages/signers/ethereum/src/utils.ts | 4 +- .../signers/ethereum/tests/encrypt.test.ts | 2 +- .../signers/ethereum/tests/generate.test.ts | 8 +- packages/signers/ethereum/tests/sign.test.ts | 2 +- packages/signers/kadena/src/index.ts | 6 +- packages/signers/kadena/src/libs/ed25519.ts | 2 +- .../signers/kadena/tests/generate.test.ts | 8 +- packages/signers/kadena/tests/sign.test.ts | 2 +- packages/signers/polkadot/src/index.ts | 28 ++-- .../signers/polkadot/tests/generate.test.ts | 18 +- packages/signers/polkadot/tests/sign.test.ts | 6 +- packages/storage/src/local-forage.ts | 2 +- packages/storage/tests/dummyDriver.js | 6 +- packages/swap/src/common/estimateGasList.ts | 4 +- packages/swap/src/index.ts | 18 +- .../swap/src/providers/changelly/index.ts | 154 ++++++++--------- .../swap/src/providers/changelly/supported.ts | 2 +- packages/swap/src/providers/jupiter/index.ts | 120 ++++++------- packages/swap/src/providers/oneInch/index.ts | 18 +- packages/swap/src/providers/paraswap/index.ts | 26 +-- packages/swap/src/providers/rango/index.ts | 158 +++++++++--------- packages/swap/src/providers/zerox/index.ts | 18 +- packages/swap/src/types/index.ts | 4 +- packages/swap/src/utils/approvals.ts | 10 +- packages/swap/src/utils/common.ts | 6 +- packages/swap/src/utils/solana.ts | 40 ++--- packages/swap/tests/changelly.test.ts | 16 +- packages/swap/tests/jupiter.test.ts | 18 +- packages/swap/tests/oneInch.test.ts | 20 +-- packages/swap/tests/paraswap.test.ts | 24 +-- packages/swap/tests/rango.test.ts | 8 +- packages/swap/tests/swap.test.ts | 26 +-- packages/swap/tests/swapToken.test.ts | 4 +- packages/swap/tests/zerox.test.ts | 28 ++-- packages/types/src/index.ts | 10 +- packages/utils/src/encrypt.ts | 23 +-- packages/utils/src/index.ts | 2 +- packages/utils/src/units.ts | 12 +- 75 files changed, 624 insertions(+), 623 deletions(-) diff --git a/packages/extension-bridge/README.md b/packages/extension-bridge/README.md index 61f1b75d8..d476852d6 100644 --- a/packages/extension-bridge/README.md +++ b/packages/extension-bridge/README.md @@ -36,7 +36,7 @@ button.addEventListener("click", async () => { const res = await sendMessage( "get-selection", { ignoreCasing: true }, - "content-script" + "content-script", ); console.log(res); // > "The brown fox is alive and well" }); @@ -57,7 +57,7 @@ onMessage("get-selection", async (message) => { const { selection } = await sendMessage( "get-preferences", { sync: false }, - "background" + "background", ); return calculateSelection(data.ignoreCasing, selection); }); diff --git a/packages/extension-bridge/src/apis/onMessage.ts b/packages/extension-bridge/src/apis/onMessage.ts index 3358f42fb..b75d6ea91 100644 --- a/packages/extension-bridge/src/apis/onMessage.ts +++ b/packages/extension-bridge/src/apis/onMessage.ts @@ -10,10 +10,10 @@ import { onMessageListeners } from "../internal"; export function onMessage< Data extends JsonValue, - K extends DataTypeKey | string + K extends DataTypeKey | string, >( messageID: K, - callback: OnMessageCallback, GetReturnType> + callback: OnMessageCallback, GetReturnType>, ): void { onMessageListeners.set(messageID, callback); } diff --git a/packages/extension-bridge/src/apis/sendMessage.ts b/packages/extension-bridge/src/apis/sendMessage.ts index ecc754ba1..7d97275c2 100644 --- a/packages/extension-bridge/src/apis/sendMessage.ts +++ b/packages/extension-bridge/src/apis/sendMessage.ts @@ -24,11 +24,11 @@ import { parseEndpoint } from "../utils"; */ export async function sendMessage< ReturnType extends JsonValue, - K extends DataTypeKey | string + K extends DataTypeKey | string, >( messageID: K, data: GetDataType, - destination: Destination = "background" + destination: Destination = "background", ) { const endpoint = typeof destination === "string" ? parseEndpoint(destination) : destination; @@ -36,13 +36,13 @@ export async function sendMessage< if (!endpoint.context) throw new TypeError( - `${errFn} Destination must be any one of known destinations` + `${errFn} Destination must be any one of known destinations`, ); if (context === "background") { const { context: dest, tabId: destTabId } = endpoint; if (dest !== "background" && !destTabId) throw new TypeError( - `${errFn} When sending messages from background page, use @tabId syntax to target specific tab` + `${errFn} When sending messages from background page, use @tabId syntax to target specific tab`, ); } diff --git a/packages/extension-bridge/src/bridge.ts b/packages/extension-bridge/src/bridge.ts index d40fbc156..a26503d2c 100644 --- a/packages/extension-bridge/src/bridge.ts +++ b/packages/extension-bridge/src/bridge.ts @@ -35,12 +35,12 @@ onMessage<{ channel: string; streamId: string }, string>( }; readyup(); - }) + }), ); async function openStream( channel: string, - destination: RuntimeContext | Endpoint | string + destination: RuntimeContext | Endpoint | string, ): Promise { if (openStreams.has(channel)) throw new Error("webext-bridge: A Stream is already open at this channel"); @@ -58,11 +58,11 @@ async function openStream( function onOpenStreamChannel( channel: string, - callback: (stream: Stream) => void + callback: (stream: Stream) => void, ): void { if (onOpenStreamCallbacks.has(channel)) throw new Error( - "webext-bridge: This channel has already been claimed. Stream allows only one-on-one communication" + "webext-bridge: This channel has already been claimed. Stream allows only one-on-one communication", ); onOpenStreamCallbacks.set(channel, callback); diff --git a/packages/extension-bridge/src/internal.ts b/packages/extension-bridge/src/internal.ts index 867d4d312..d03931377 100644 --- a/packages/extension-bridge/src/internal.ts +++ b/packages/extension-bridge/src/internal.ts @@ -14,12 +14,12 @@ import { hasAPI, parseEndpoint, getBackgroundPageType } from "./utils"; export const context: RuntimeContext = hasAPI("devtools") ? "devtools" : hasAPI("tabs") - ? getBackgroundPageType() - : hasAPI("extension") - ? "content-script" - : typeof document !== "undefined" - ? "window" - : null; + ? getBackgroundPageType() + : hasAPI("extension") + ? "content-script" + : typeof document !== "undefined" + ? "window" + : null; const runtimeId: string = uuid(); export const openTransactions = new Map< @@ -51,7 +51,7 @@ export const allowWindowMessaging = (nsps: string): void => { namespace = nsps; }; const handleInboundMessage = async ( - message: IInternalMessage + message: IInternalMessage, ): Promise => { const { transactionId, messageID, messageType } = message; @@ -63,7 +63,7 @@ const handleInboundMessage = async ( const dehydratedErr = err as Record; const errCtr = self[dehydratedErr.name] as any; const hydratedErr = new (typeof errCtr === "function" ? errCtr : Error)( - dehydratedErr.message + dehydratedErr.message, ); Object.keys(dehydratedErr).forEach((prop) => { hydratedErr[prop] = dehydratedErr[prop]; @@ -93,7 +93,7 @@ const handleInboundMessage = async ( } else { noHandlerFoundError = true; throw new Error( - `[webext-bridge] No handler registered in '${context}' to accept messages with id '${messageID}'` + `[webext-bridge] No handler registered in '${context}' to accept messages with id '${messageID}'`, ); } } catch (error) { @@ -128,7 +128,7 @@ const handleInboundMessage = async ( const initIntercoms = () => { if (context === null) throw new Error( - "Unable to detect runtime context i.e webext-bridge can't figure out what to do" + "Unable to detect runtime context i.e webext-bridge can't figure out what to do", ); if (context === "window" || context === "content-script") @@ -245,7 +245,7 @@ const initIntercoms = () => { initIntercoms(); export const routeMessage = ( - message: IInternalMessage + message: IInternalMessage, ): void | Promise => { const { origin, destination } = message; if (message.hops.includes(runtimeId)) return; @@ -275,7 +275,7 @@ export const routeMessage = ( routeMessageThroughWindow(window, message); } else if ( ["devtools", "content-script", "popup", "options", "new-window"].includes( - context + context, ) ) { if (destination.context === "background") message.destination = null; @@ -320,7 +320,7 @@ export const routeMessage = ( // eslint-disable-next-line @typescript-eslint/no-empty-function const assertInternalMessage: (x: unknown) => asserts x = ( - _msg: any + _msg: any, ): asserts _msg is IInternalMessage => { // todo }; @@ -373,7 +373,7 @@ const routeMessageThroughWindow = (win: Window, msg: IInternalMessage) => { context, payload: msg, }, - "*" + "*", ); }; win.postMessage( @@ -383,7 +383,7 @@ const routeMessageThroughWindow = (win: Window, msg: IInternalMessage) => { context, }, "*", - [channel.port2] + [channel.port2], ); }; @@ -393,7 +393,7 @@ function ensureNamespaceSet() { 'webext-bridge uses window.postMessage to talk with other "window"(s), for message routing and stuff,' + "which is global/conflicting operation in case there are other scripts using webext-bridge. " + "Call Bridge#setNamespace(nsps) to isolate your app. Example: setNamespace('com.facebook.react-devtools'). " + - "Make sure to use same namespace across all your scripts whereever window.postMessage is likely to be used`" + "Make sure to use same namespace across all your scripts whereever window.postMessage is likely to be used`", ); } } diff --git a/packages/extension-bridge/src/stream.ts b/packages/extension-bridge/src/stream.ts index c438b1822..259e31eb1 100644 --- a/packages/extension-bridge/src/stream.ts +++ b/packages/extension-bridge/src/stream.ts @@ -74,7 +74,7 @@ class Stream { public send(msg?: JsonValue): void { if (this.isClosed) throw new Error( - "Attempting to send a message over closed stream. Use stream.onClose() to keep an eye on stream status" + "Attempting to send a message over closed stream. Use stream.onClose() to keep an eye on stream status", ); sendMessage( @@ -84,7 +84,7 @@ class Stream { streamTransfer: msg, action: "transfer", }, - this.internalInfo.endpoint + this.internalInfo.endpoint, ); } @@ -106,7 +106,7 @@ class Stream { streamTransfer: null, action: "close", }, - this.internalInfo.endpoint + this.internalInfo.endpoint, ); } @@ -115,7 +115,7 @@ class Stream { * @param callback */ public onMessage( - callback: (msg?: T) => void + callback: (msg?: T) => void, ): HybridUnsubscriber { return this.getDisposable("message", callback); } @@ -125,7 +125,7 @@ class Stream { * @param callback */ public onClose( - callback: (msg?: T) => void + callback: (msg?: T) => void, ): HybridUnsubscriber { return this.getDisposable("closed", callback); } @@ -140,7 +140,7 @@ class Stream { private getDisposable( event: string, - callback: () => void + callback: () => void, ): HybridUnsubscriber { const off = this.emitter.on(event, callback); diff --git a/packages/extension-bridge/src/types.ts b/packages/extension-bridge/src/types.ts index 9ea2bdcf8..21df6ee55 100644 --- a/packages/extension-bridge/src/types.ts +++ b/packages/extension-bridge/src/types.ts @@ -23,7 +23,7 @@ export interface IBridgeMessage { } export type OnMessageCallback = ( - message: IBridgeMessage + message: IBridgeMessage, ) => R | Promise; export interface IInternalMessage { @@ -61,7 +61,7 @@ declare const ProtocolWithReturnSymbol: unique symbol; export interface ProtocolWithReturn< Data extends JsonValue, - Return extends JsonValue + Return extends JsonValue, > { data: Data; return: Return; @@ -84,7 +84,7 @@ export type DataTypeKey = keyof ProtocolMap; export type GetDataType< K extends DataTypeKey | string, - Fallback extends JsonValue + Fallback extends JsonValue, > = K extends DataTypeKey ? ProtocolMap[K] extends ProtocolWithReturn ? Data @@ -93,7 +93,7 @@ export type GetDataType< export type GetReturnType< K extends DataTypeKey | string, - Fallback extends JsonValue + Fallback extends JsonValue, > = K extends DataTypeKey ? ProtocolMap[K] extends ProtocolWithReturn ? Return diff --git a/packages/extension-bridge/src/window/apis/onMessage.ts b/packages/extension-bridge/src/window/apis/onMessage.ts index 3e6b4cd4d..6f57ce2f5 100644 --- a/packages/extension-bridge/src/window/apis/onMessage.ts +++ b/packages/extension-bridge/src/window/apis/onMessage.ts @@ -10,10 +10,10 @@ import { onMessageListeners } from "../internal"; export function onMessage< Data extends JsonValue, - K extends DataTypeKey | string + K extends DataTypeKey | string, >( messageID: K, - callback: OnMessageCallback, GetReturnType> + callback: OnMessageCallback, GetReturnType>, ): void { onMessageListeners.set(messageID, callback); } diff --git a/packages/extension-bridge/src/window/apis/sendMessage.ts b/packages/extension-bridge/src/window/apis/sendMessage.ts index a72b80d4a..a94462846 100644 --- a/packages/extension-bridge/src/window/apis/sendMessage.ts +++ b/packages/extension-bridge/src/window/apis/sendMessage.ts @@ -24,11 +24,11 @@ import { parseEndpoint } from "../utils"; */ export async function sendMessage< ReturnType extends JsonValue, - K extends DataTypeKey | string + K extends DataTypeKey | string, >( messageID: K, data: GetDataType, - destination: Destination = "background" + destination: Destination = "background", ) { const endpoint = typeof destination === "string" ? parseEndpoint(destination) : destination; @@ -36,14 +36,14 @@ export async function sendMessage< if (!endpoint.context) throw new TypeError( - `${errFn} Destination must be any one of known destinations` + `${errFn} Destination must be any one of known destinations`, ); if (context === "background") { const { context: dest, tabId: destTabId } = endpoint; if (dest !== "background" && !destTabId) throw new TypeError( - `${errFn} When sending messages from background page, use @tabId syntax to target specific tab` + `${errFn} When sending messages from background page, use @tabId syntax to target specific tab`, ); } diff --git a/packages/extension-bridge/src/window/internal.ts b/packages/extension-bridge/src/window/internal.ts index d73c828a8..74474a0c4 100644 --- a/packages/extension-bridge/src/window/internal.ts +++ b/packages/extension-bridge/src/window/internal.ts @@ -42,7 +42,7 @@ export const allowWindowMessaging = (nsps: string): void => { namespace = nsps; }; const handleInboundMessage = async ( - message: IInternalMessage + message: IInternalMessage, ): Promise => { const { transactionId, messageID, messageType } = message; @@ -54,7 +54,7 @@ const handleInboundMessage = async ( const dehydratedErr = err as Record; const errCtr = self[dehydratedErr.name] as any; const hydratedErr = new (typeof errCtr === "function" ? errCtr : Error)( - dehydratedErr.message + dehydratedErr.message, ); Object.keys(dehydratedErr).forEach((prop) => { hydratedErr[prop] = dehydratedErr[prop]; @@ -84,7 +84,7 @@ const handleInboundMessage = async ( } else { noHandlerFoundError = true; throw new Error( - `[webext-bridge] No handler registered in '${context}' to accept messages with id '${messageID}'` + `[webext-bridge] No handler registered in '${context}' to accept messages with id '${messageID}'`, ); } } catch (error) { @@ -123,7 +123,7 @@ const initIntercoms = () => { initIntercoms(); export const routeMessage = ( - message: IInternalMessage + message: IInternalMessage, ): void | Promise => { const { origin, destination } = message; @@ -191,7 +191,7 @@ export const routeMessage = ( // eslint-disable-next-line @typescript-eslint/no-empty-function const assertInternalMessage: (x: unknown) => asserts x = ( - _msg: any + _msg: any, ): asserts _msg is IInternalMessage => { // todo }; @@ -243,7 +243,7 @@ const routeMessageThroughWindow = (win: Window, msg: IInternalMessage) => { context, payload: msg, }, - "*" + "*", ); }; win.postMessage( @@ -253,7 +253,7 @@ const routeMessageThroughWindow = (win: Window, msg: IInternalMessage) => { context, }, "*", - [channel.port2] + [channel.port2], ); }; @@ -263,7 +263,7 @@ function ensureNamespaceSet() { 'webext-bridge uses window.postMessage to talk with other "window"(s), for message routing and stuff,' + "which is global/conflicting operation in case there are other scripts using webext-bridge. " + "Call Bridge#setNamespace(nsps) to isolate your app. Example: setNamespace('com.facebook.react-devtools'). " + - "Make sure to use same namespace across all your scripts whereever window.postMessage is likely to be used`" + "Make sure to use same namespace across all your scripts whereever window.postMessage is likely to be used`", ); } } diff --git a/packages/hw-wallets/src/index.ts b/packages/hw-wallets/src/index.ts index a0501f47f..e293f0d0a 100644 --- a/packages/hw-wallets/src/index.ts +++ b/packages/hw-wallets/src/index.ts @@ -45,7 +45,7 @@ class HWwalletManager { async #initialize( wallet: HWwalletType, - network: NetworkNames + network: NetworkNames, ): Promise { if (!this.providers[network]) { this.providers[network] = this.#getProvider(wallet, network); @@ -56,7 +56,7 @@ class HWwalletManager { async getAddress(options: getAddressRequest): Promise { await this.#initialize(options.wallet, options.networkName); return (this.providers[options.networkName] as HWWalletProvider).getAddress( - options + options, ); } @@ -77,7 +77,7 @@ class HWwalletManager { async getSupportedPaths(options: isConnectedRequest): Promise { return this.#getProvider( options.wallet, - options.networkName + options.networkName, ).getSupportedPaths(); } @@ -99,7 +99,7 @@ class HWwalletManager { async close(): Promise { return Promise.all( - Object.values(this.providers).map((p) => (p as HWWalletProvider).close()) + Object.values(this.providers).map((p) => (p as HWWalletProvider).close()), ).then(); } diff --git a/packages/hw-wallets/src/ledger/bitcoin/index.ts b/packages/hw-wallets/src/ledger/bitcoin/index.ts index 42b2d649d..220462f33 100644 --- a/packages/hw-wallets/src/ledger/bitcoin/index.ts +++ b/packages/hw-wallets/src/ledger/bitcoin/index.ts @@ -54,7 +54,7 @@ class LedgerBitcoin implements HWWalletProvider { }); } else { return Promise.reject( - new Error("ledger-bitcoin: webusb is not supported") + new Error("ledger-bitcoin: webusb is not supported"), ); } } @@ -71,14 +71,14 @@ class LedgerBitcoin implements HWWalletProvider { if (!this.HDNodes[options.pathType.basePath]) { const rootPub = await connection.getWalletPublicKey( options.pathType.basePath, - { format: this.isSegwit ? "bech32" : "legacy" } + { format: this.isSegwit ? "bech32" : "legacy" }, ); hdKey.publicKey = Buffer.from(rootPub.publicKey, "hex"); hdKey.chainCode = Buffer.from(rootPub.chainCode, "hex"); this.HDNodes[options.pathType.basePath] = hdKey; } const pubkey = this.HDNodes[options.pathType.basePath].derive( - `m/${options.pathIndex}` + `m/${options.pathIndex}`, ).publicKey; return { address: bufferToHex(pubkey), @@ -89,7 +89,7 @@ class LedgerBitcoin implements HWWalletProvider { return connection .getWalletPublicKey( options.pathType.path.replace(`{index}`, options.pathIndex), - { format: this.isSegwit ? "bech32" : "legacy" } + { format: this.isSegwit ? "bech32" : "legacy" }, ) .then((res) => { hdKey.publicKey = Buffer.from(res.publicKey, "hex"); @@ -105,20 +105,20 @@ class LedgerBitcoin implements HWWalletProvider { if (options.type === "bip322-simple") { if (!options.psbtTx) { return Promise.reject( - new Error("ledger-bitcoin: psbt not set for message signing") + new Error("ledger-bitcoin: psbt not set for message signing"), ); } const client = new AppClient(this.transport as any); const fpr = await client.getMasterFingerprint(); const accountPath = options.pathType.path.replace( `{index}`, - options.pathIndex + options.pathIndex, ); const pathElems: number[] = pathStringToArray(accountPath); const rootPath = pathElems.slice(0, -2); const accountRootPubkey = await client.getExtendedPubkey( pathArrayToString(rootPath), - false + false, ); options.psbtTx.data.inputs[0].bip32Derivation[0].masterFingerprint = Buffer.from(fpr, "hex"); @@ -127,7 +127,7 @@ class LedgerBitcoin implements HWWalletProvider { globalXpub: [ { extendedPubkey: Buffer.from( - bs58.decode(accountRootPubkey) + bs58.decode(accountRootPubkey), ).subarray(0, -4), masterFingerprint: Buffer.from(fpr, "hex"), path: accountPath, @@ -138,13 +138,13 @@ class LedgerBitcoin implements HWWalletProvider { "wpkh(@0/**)", `[${fpr}/${pathArrayToString(rootPath).replace( "m/", - "" - )}]${accountRootPubkey}` + "", + )}]${accountRootPubkey}`, ); const sigs = await client.signPsbt( options.psbtTx.toBase64(), accountPolicy, - null + null, ); options.psbtTx.updateInput(0, { partialSig: [sigs[0][1]], @@ -156,13 +156,13 @@ class LedgerBitcoin implements HWWalletProvider { return connection .signMessage( options.pathType.path.replace(`{index}`, options.pathIndex), - options.message.toString("hex") + options.message.toString("hex"), ) .then((result) => { const v = result.v + 27 + 4; const signature = Buffer.from( v.toString(16) + result.r + result.s, - "hex" + "hex", ); return bufferToHex(signature); }); @@ -185,13 +185,13 @@ class LedgerBitcoin implements HWWalletProvider { transactionOptions.psbtTx.txInputs[idx].index, transactionOptions.psbtTx.data.inputs[idx].witnessScript ? transactionOptions.psbtTx.data.inputs[idx].witnessScript.toString( - "hex" + "hex", ) : undefined, undefined, ]), associatedKeysets: transactionOptions.rawTxs.map(() => - options.pathType.path.replace(`{index}`, options.pathIndex) + options.pathType.path.replace(`{index}`, options.pathIndex), ), outputScriptHex: serializeTransactionOutputs({ outputs: txOutputs, diff --git a/packages/hw-wallets/src/ledger/ethereum/index.ts b/packages/hw-wallets/src/ledger/ethereum/index.ts index 5fa8a2155..588c692a4 100644 --- a/packages/hw-wallets/src/ledger/ethereum/index.ts +++ b/packages/hw-wallets/src/ledger/ethereum/index.ts @@ -42,7 +42,7 @@ class LedgerEthereum implements HWWalletProvider { }); } else { return Promise.reject( - new Error("ledger-ethereum: webusb is not supported") + new Error("ledger-ethereum: webusb is not supported"), ); } } @@ -59,7 +59,7 @@ class LedgerEthereum implements HWWalletProvider { const rootPub = await connection.getAddress( options.pathType.basePath, options.confirmAddress, - true + true, ); const hdKey = new HDKey(); hdKey.publicKey = Buffer.from(rootPub.publicKey, "hex"); @@ -67,7 +67,7 @@ class LedgerEthereum implements HWWalletProvider { this.HDNodes[options.pathType.basePath] = hdKey; } const pubkey = this.HDNodes[options.pathType.basePath].derive( - `m/${options.pathIndex}` + `m/${options.pathIndex}`, ).publicKey; return { address: bufferToHex(publicToAddress(pubkey, true)), @@ -78,7 +78,7 @@ class LedgerEthereum implements HWWalletProvider { return connection .getAddress( options.pathType.path.replace(`{index}`, options.pathIndex), - options.confirmAddress + options.confirmAddress, ) .then((res) => ({ address: res.address.toLowerCase(), @@ -91,7 +91,7 @@ class LedgerEthereum implements HWWalletProvider { return connection .signPersonalMessage( options.pathType.path.replace(`{index}`, options.pathIndex), - options.message.toString("hex") + options.message.toString("hex"), ) .then((result) => `0x${result.r}${result.s}${result.v.toString(16)}`); } @@ -110,13 +110,13 @@ class LedgerEthereum implements HWWalletProvider { const resolution = await ledgerService.resolveTransaction( msgToSign, {}, - {} + {}, ); return connection .signTransaction( options.pathType.path.replace(`{index}`, options.pathIndex), msgToSign, - resolution + resolution, ) .then((result) => { if ((tx as LegacyTransaction).gasPrice) { @@ -125,13 +125,13 @@ class LedgerEthereum implements HWWalletProvider { return toRpcSig( rv - cv, hexToBuffer(result.r), - hexToBuffer(result.s) + hexToBuffer(result.s), ); } return toRpcSig( BigInt(`0x${result.v}`), hexToBuffer(result.r), - hexToBuffer(result.s) + hexToBuffer(result.s), ); }); } diff --git a/packages/hw-wallets/src/ledger/ledgerConnect.ts b/packages/hw-wallets/src/ledger/ledgerConnect.ts index c5f6fa102..e04b11a50 100644 --- a/packages/hw-wallets/src/ledger/ledgerConnect.ts +++ b/packages/hw-wallets/src/ledger/ledgerConnect.ts @@ -8,7 +8,7 @@ import { ledgerAppNames } from "../configs"; function connect( this: LedgerEthereum | LedgerSubstrate, - networkName: NetworkNames + networkName: NetworkNames, ): Promise { const appName = ledgerAppNames[networkName] ? ledgerAppNames[networkName] @@ -19,9 +19,9 @@ function connect( .then(() => true) .catch(() => { throw new Error( - `Make sure you have ${appName} App installed on your ledger` + `Make sure you have ${appName} App installed on your ledger`, ); - }) + }), ) .catch((e) => { if (e.message === "DeviceOnDashboardExpected") { diff --git a/packages/hw-wallets/src/ledger/solana/index.ts b/packages/hw-wallets/src/ledger/solana/index.ts index 9430036ed..51970c8e9 100644 --- a/packages/hw-wallets/src/ledger/solana/index.ts +++ b/packages/hw-wallets/src/ledger/solana/index.ts @@ -39,7 +39,7 @@ class LedgerSolana implements HWWalletProvider { }); } else { return Promise.reject( - new Error("ledger-solana: webusb is not supported") + new Error("ledger-solana: webusb is not supported"), ); } } @@ -53,7 +53,7 @@ class LedgerSolana implements HWWalletProvider { return connection .getAddress( options.pathType.path.replace(`{index}`, options.pathIndex), - false + false, ) .then((res) => ({ address: bufferToHex(res.address), @@ -66,7 +66,7 @@ class LedgerSolana implements HWWalletProvider { return connection .signOffchainMessage( options.pathType.path.replace(`{index}`, options.pathIndex), - options.message + options.message, ) .then((result) => bufferToHex(result.signature)); } @@ -76,7 +76,7 @@ class LedgerSolana implements HWWalletProvider { return connection .signTransaction( options.pathType.path.replace(`{index}`, options.pathIndex), - (options.transaction as SolSignTransaction).solTx + (options.transaction as SolSignTransaction).solTx, ) .then((result) => bufferToHex(result.signature)); } diff --git a/packages/hw-wallets/src/ledger/substrate/index.ts b/packages/hw-wallets/src/ledger/substrate/index.ts index 1df9ccf32..33693ca34 100644 --- a/packages/hw-wallets/src/ledger/substrate/index.ts +++ b/packages/hw-wallets/src/ledger/substrate/index.ts @@ -29,7 +29,7 @@ class LedgerSubstrate implements HWWalletProvider { if (!LedgerApps[this.network]) throw new Error("ledger-substrate: Invalid network name"); const pathValues = bip32ToAddressNList( - options.pathType.path.replace(`{index}`, options.pathIndex) + options.pathType.path.replace(`{index}`, options.pathIndex), ); if (pathValues.length < 3) throw new Error("ledger-substrate: Invalid path"); @@ -42,7 +42,7 @@ class LedgerSubstrate implements HWWalletProvider { this.transport = await webUsbTransport.create(); } else { return Promise.reject( - new Error("ledger-substrate: webusb is not supported") + new Error("ledger-substrate: webusb is not supported"), ); } } @@ -53,7 +53,7 @@ class LedgerSubstrate implements HWWalletProvider { this.validatePathAndNetwork(options); const app = LedgerApps[this.network]; const pathValues = bip32ToAddressNList( - options.pathType.path.replace(`{index}`, options.pathIndex) + options.pathType.path.replace(`{index}`, options.pathIndex), ); const connection = app(this.transport); return connection @@ -61,7 +61,7 @@ class LedgerSubstrate implements HWWalletProvider { pathValues[0], pathValues[1], pathValues[2], - options.confirmAddress + options.confirmAddress, ) .then((res) => ({ address: res.address, @@ -93,7 +93,7 @@ class LedgerSubstrate implements HWWalletProvider { async signTransaction(options: SignTransactionRequest): Promise { this.validatePathAndNetwork(options); const pathValues = bip32ToAddressNList( - options.pathType.path.replace(`{index}`, options.pathIndex) + options.pathType.path.replace(`{index}`, options.pathIndex), ); const app = LedgerApps[this.network]; const tx = options.transaction as ExtrinsicPayload; @@ -103,7 +103,7 @@ class LedgerSubstrate implements HWWalletProvider { pathValues[0], pathValues[1], pathValues[2], - u8aToBuffer(tx.toU8a(true)) + u8aToBuffer(tx.toU8a(true)), ) .then((result) => { if (result.error_message !== "No errors") diff --git a/packages/hw-wallets/src/ledger/substrate/utils.ts b/packages/hw-wallets/src/ledger/substrate/utils.ts index c996f4c7a..bb7a6e958 100644 --- a/packages/hw-wallets/src/ledger/substrate/utils.ts +++ b/packages/hw-wallets/src/ledger/substrate/utils.ts @@ -1,7 +1,7 @@ const bip32Like = (path: string): boolean => { if (path === "m/") return true; return /^m(((\/[0-9]+h)+|(\/[0-9]+H)+|(\/[0-9]+')*)((\/[0-9]+)*))$/.test( - path + path, ); }; const HARDENED = 0x80000000; diff --git a/packages/hw-wallets/src/trezor/bitcoin/index.ts b/packages/hw-wallets/src/trezor/bitcoin/index.ts index 28156c76d..a8f1d69e3 100644 --- a/packages/hw-wallets/src/trezor/bitcoin/index.ts +++ b/packages/hw-wallets/src/trezor/bitcoin/index.ts @@ -58,7 +58,7 @@ class TrezorEthereum implements HWWalletProvider { this.HDNodes[options.pathType.basePath] = hdKey; } const pubkey = this.HDNodes[options.pathType.basePath].derive( - `m/${options.pathIndex}` + `m/${options.pathIndex}`, ).publicKey; return { address: bufferToHex(pubkey), @@ -95,7 +95,7 @@ class TrezorEthereum implements HWWalletProvider { async signTransaction(options: SignTransactionRequest): Promise { const transactionOptions = options.transaction as BTCSignTransaction; const addressN = getHDPath( - options.pathType.path.replace(`{index}`, options.pathIndex) + options.pathType.path.replace(`{index}`, options.pathIndex), ); return TrezorConnect.signTransaction({ coin: TrezorNetworkConfigs[this.network].symbol, @@ -114,7 +114,7 @@ class TrezorEthereum implements HWWalletProvider { amount: out.value, address: out.address, script_type: "PAYTOADDRESS", - } as any) + }) as any, ), }).then((res) => { if (!res.success) throw new Error((res.payload as any).error as string); diff --git a/packages/hw-wallets/src/trezor/ethereum/index.ts b/packages/hw-wallets/src/trezor/ethereum/index.ts index 0ec432f3c..4b2152f36 100644 --- a/packages/hw-wallets/src/trezor/ethereum/index.ts +++ b/packages/hw-wallets/src/trezor/ethereum/index.ts @@ -57,7 +57,7 @@ class TrezorEthereum implements HWWalletProvider { this.HDNodes[options.pathType.basePath] = hdKey; } const pubkey = this.HDNodes[options.pathType.basePath].derive( - `m/${options.pathIndex}` + `m/${options.pathIndex}`, ).publicKey; return { address: bufferToHex(publicToAddress(pubkey, true)), @@ -113,7 +113,7 @@ class TrezorEthereum implements HWWalletProvider { return toRpcSig( rv - cv, hexToBuffer(result.payload.r), - hexToBuffer(result.payload.s) + hexToBuffer(result.payload.s), ); }); } @@ -131,7 +131,7 @@ class TrezorEthereum implements HWWalletProvider { return toRpcSig( BigInt(result.payload.v), hexToBuffer(result.payload.r), - hexToBuffer(result.payload.s) + hexToBuffer(result.payload.s), ); }); } diff --git a/packages/hw-wallets/src/trezor/solana/index.ts b/packages/hw-wallets/src/trezor/solana/index.ts index c5bf51eec..bfa048568 100644 --- a/packages/hw-wallets/src/trezor/solana/index.ts +++ b/packages/hw-wallets/src/trezor/solana/index.ts @@ -69,7 +69,7 @@ class TrezorSolana implements HWWalletProvider { return TrezorConnect.solanaSignTransaction({ path: options.pathType.path.replace(`{index}`, options.pathIndex), serializedTx: (options.transaction as SolSignTransaction).solTx.toString( - "hex" + "hex", ), }).then((result) => result.payload.signature); } diff --git a/packages/keyring/src/index.ts b/packages/keyring/src/index.ts index 83932447e..260033116 100644 --- a/packages/keyring/src/index.ts +++ b/packages/keyring/src/index.ts @@ -58,11 +58,11 @@ class KeyRing { { strength = configs.MNEMONIC_STRENGTH, mnemonic = generateMnemonic(strength), - }: { strength?: number; mnemonic?: string } = {} + }: { strength?: number; mnemonic?: string } = {}, ): Promise { assert( !(await this.#storage.get(configs.STORAGE_KEYS.ENCRYPTED_MNEMONIC)), - Errors.KeyringErrors.MnemonicExists + Errors.KeyringErrors.MnemonicExists, ); assert(password, Errors.KeyringErrors.NoPassword); const entropy = hexToBuffer(mnemonicToEntropy(mnemonic)); @@ -94,7 +94,7 @@ class KeyRing { async #getMnemonic(password: string): Promise { const encrypted = await this.#storage.get( - configs.STORAGE_KEYS.ENCRYPTED_MNEMONIC + configs.STORAGE_KEYS.ENCRYPTED_MNEMONIC, ); assert(encrypted, Errors.KeyringErrors.NotInitialized); const decryptedEntropy = await decrypt(encrypted, password); @@ -132,7 +132,7 @@ class KeyRing { } else { keypair = await this.#signers[key.signerType].generate( this.#mnemonic, - pathParser(key.basePath, nextIndex, key.signerType) + pathParser(key.basePath, nextIndex, key.signerType), ); } return { @@ -157,7 +157,7 @@ class KeyRing { const existingKeys = await this.getKeysObject(); assert( !existingKeys[keyRecord.address], - Errors.KeyringErrors.AddressExists + Errors.KeyringErrors.AddressExists, ); existingKeys[keyRecord.address] = keyRecord; await this.#storage.set(configs.STORAGE_KEYS.KEY_INFO, existingKeys); @@ -172,15 +172,15 @@ class KeyRing { this.#resetTimeout(); assert( !Object.values(HWwalletType).includes( - options.walletType as unknown as HWwalletType + options.walletType as unknown as HWwalletType, ), - Errors.KeyringErrors.CannotUseKeyring + Errors.KeyringErrors.CannotUseKeyring, ); let keypair: KeyPair; if (options.walletType === WalletType.privkey) { const pubKey = (await this.getKeysArray()).find( (i) => - i.basePath === options.basePath && i.pathIndex === options.pathIndex + i.basePath === options.basePath && i.pathIndex === options.pathIndex, ).publicKey; keypair = { privateKey: this.#privkeys[options.pathIndex.toString()], @@ -189,7 +189,7 @@ class KeyRing { } else { keypair = await this.#signers[options.signerType].generate( this.#mnemonic, - pathParser(options.basePath, options.pathIndex, options.signerType) + pathParser(options.basePath, options.pathIndex, options.signerType), ); } return this.#signers[options.signerType].sign(msgHash, keypair); @@ -200,17 +200,17 @@ class KeyRing { this.#resetTimeout(); assert( !Object.values(HWwalletType).includes( - options.walletType as unknown as HWwalletType + options.walletType as unknown as HWwalletType, ), - Errors.KeyringErrors.CannotUseKeyring + Errors.KeyringErrors.CannotUseKeyring, ); assert( options.signerType === SignerType.secp256k1, - Errors.KeyringErrors.EnckryptDecryptNotSupported + Errors.KeyringErrors.EnckryptDecryptNotSupported, ); const keypair = await this.#signers[options.signerType].generate( this.#mnemonic, - pathParser(options.basePath, options.pathIndex, options.signerType) + pathParser(options.basePath, options.pathIndex, options.signerType), ); return ( this.#signers[options.signerType] as EthereumSigner @@ -219,27 +219,27 @@ class KeyRing { async ethereumDecrypt( encryptedMessage: string, - options: SignOptions + options: SignOptions, ): Promise { assert(!this.#isLocked, Errors.KeyringErrors.Locked); this.#resetTimeout(); assert( !Object.values(HWwalletType).includes( - options.walletType as unknown as HWwalletType + options.walletType as unknown as HWwalletType, ), - Errors.KeyringErrors.CannotUseKeyring + Errors.KeyringErrors.CannotUseKeyring, ); assert( options.signerType === SignerType.secp256k1, - Errors.KeyringErrors.EnckryptDecryptNotSupported + Errors.KeyringErrors.EnckryptDecryptNotSupported, ); const keypair = await this.#signers[options.signerType].generate( this.#mnemonic, - pathParser(options.basePath, options.pathIndex, options.signerType) + pathParser(options.basePath, options.pathIndex, options.signerType), ); return (this.#signers[options.signerType] as EthereumSigner).decrypt( encryptedMessage, - keypair + keypair, ); } @@ -264,7 +264,7 @@ class KeyRing { async renameAccount( address: string, - newName: string + newName: string, ): Promise { const existingKeys = await this.getKeysObject(); assert(existingKeys[address], Errors.KeyringErrors.AddressDoesntExists); @@ -280,17 +280,17 @@ class KeyRing { assert(existingKeys[address], Errors.KeyringErrors.AddressDoesntExists); assert( existingKeys[address].walletType !== WalletType.mnemonic, - Errors.KeyringErrors.CantRemoveMnemonicAddress + Errors.KeyringErrors.CantRemoveMnemonicAddress, ); delete existingKeys[address]; await this.#storage.set(configs.STORAGE_KEYS.KEY_INFO, existingKeys); } async #getPrivateKeys( - keyringPassword: string + keyringPassword: string, ): Promise> { const encrypted = await this.#storage.get( - configs.STORAGE_KEYS.ENCRYPTED_PRIVKEYS + configs.STORAGE_KEYS.ENCRYPTED_PRIVKEYS, ); if (!encrypted) return {}; const decrypted = await decrypt(encrypted, keyringPassword); @@ -300,14 +300,14 @@ class KeyRing { async #setPrivateKey( pathIndex: string, privKey: string, - keyringPassword: string + keyringPassword: string, ): Promise { const allKeys = await this.#getPrivateKeys(keyringPassword); assert(!allKeys[pathIndex], Errors.KeyringErrors.AddressExists); allKeys[pathIndex] = privKey; const encrypted = await encrypt( Buffer.from(JSON.stringify(allKeys), "utf-8"), - keyringPassword + keyringPassword, ); await this.#storage.set(configs.STORAGE_KEYS.ENCRYPTED_PRIVKEYS, encrypted); this.#privkeys = allKeys; @@ -315,7 +315,7 @@ class KeyRing { async addKeyPair( keyPair: KeyPairAdd, - keyringPassword: string + keyringPassword: string, ): Promise { const existingKeys = await this.getKeysObject(); assert(!existingKeys[keyPair.address], Errors.KeyringErrors.AddressExists); @@ -330,7 +330,7 @@ class KeyRing { await this.#setPrivateKey( kpAcc.pathIndex.toString(), keyPair.privateKey, - keyringPassword + keyringPassword, ); await this.#saveKeyRecord(kpAcc); return kpAcc; @@ -339,7 +339,7 @@ class KeyRing { async reset(): Promise { this.lock(); const resetPromises = Object.values(configs.STORAGE_KEYS).map((name) => - this.#storage.remove(name) + this.#storage.remove(name), ); await Promise.all(resetPromises); } diff --git a/packages/keyring/src/utils.ts b/packages/keyring/src/utils.ts index 43a584417..9bbca8da7 100644 --- a/packages/keyring/src/utils.ts +++ b/packages/keyring/src/utils.ts @@ -3,7 +3,7 @@ import { SignerType } from "@enkryptcom/types"; export const pathParser = ( basePath: string, index: number, - type: SignerType + type: SignerType, ): string => { if ( [SignerType.ecdsa, SignerType.ed25519, SignerType.sr25519].includes(type) && diff --git a/packages/keyring/tests/generate.test.ts b/packages/keyring/tests/generate.test.ts index 490af18ac..99de1e8c5 100644 --- a/packages/keyring/tests/generate.test.ts +++ b/packages/keyring/tests/generate.test.ts @@ -28,10 +28,10 @@ describe("Keyring create tests", () => { expect(pair.signerType).equals(SignerType.ed25519kda); expect(pair.pathIndex).equals(0); expect(pair.address).equals( - "0xd75b971cc4846f543caa92e9bf07bf2f4cee87774f4ba8db2fde5c3dacaed03f" + "0xd75b971cc4846f543caa92e9bf07bf2f4cee87774f4ba8db2fde5c3dacaed03f", ); keyring.lock(); - } + }, ); it( "keyring should generate secp256k1btc keys", @@ -52,10 +52,10 @@ describe("Keyring create tests", () => { expect(pair.signerType).equals(SignerType.secp256k1btc); expect(pair.pathIndex).equals(0); expect(pair.address).equals( - "0x03a8b8b68bec95d27f8a8d78712717bd18f605d95fa64f2b05d2325f873b457c82" + "0x03a8b8b68bec95d27f8a8d78712717bd18f605d95fa64f2b05d2325f873b457c82", ); keyring.lock(); - } + }, ); it("keyring should generate sr25519 keys", { timeout: 20_000 }, async () => { const memStorage = new MemoryStorage(); @@ -73,7 +73,7 @@ describe("Keyring create tests", () => { expect(pair.signerType).equals(SignerType.sr25519); expect(pair.pathIndex).equals(0); expect(pair.address).equals( - "5DfhGyQdFobKM8NsWvEeAKk5EQQgYe9AydgJ7rMB6E1EqRzV" + "5DfhGyQdFobKM8NsWvEeAKk5EQQgYe9AydgJ7rMB6E1EqRzV", ); keyring.lock(); }); @@ -93,7 +93,7 @@ describe("Keyring create tests", () => { expect(pair.signerType).equals(SignerType.ecdsa); expect(pair.pathIndex).equals(0); expect(pair.address).equals( - "5GKyBtzbxKU1qjhZrKpMiwtJj7o6jJcXbKQVtYq74DCPerXN" + "5GKyBtzbxKU1qjhZrKpMiwtJj7o6jJcXbKQVtYq74DCPerXN", ); }); it("keyring should generate ed25519 keys", { timeout: 20_000 }, async () => { @@ -112,7 +112,7 @@ describe("Keyring create tests", () => { expect(pair.signerType).equals(SignerType.ed25519); expect(pair.pathIndex).equals(0); expect(pair.address).equals( - "5DFJF7tY4bpbpcKPJcBTQaKuCDEPCpiz8TRjpmLeTtweqmXL" + "5DFJF7tY4bpbpcKPJcBTQaKuCDEPCpiz8TRjpmLeTtweqmXL", ); }); it("keyring should generate ethereum keys", { timeout: 20_000 }, async () => { @@ -164,6 +164,6 @@ describe("Keyring create tests", () => { expect(tryToDelete).equals(true); const deletedAccount = (await keyring.getKeysObject())[pair.address]; expect(deletedAccount).equals(undefined); - } + }, ); }); diff --git a/packages/keyring/tests/lock.test.ts b/packages/keyring/tests/lock.test.ts index 643c49177..949cd4086 100644 --- a/packages/keyring/tests/lock.test.ts +++ b/packages/keyring/tests/lock.test.ts @@ -21,6 +21,6 @@ describe("Keyring locking tests", () => { res(); }); expect(keyring.isLocked()).to.be.equals(true); - } + }, ); }); diff --git a/packages/keyring/tests/sign.test.ts b/packages/keyring/tests/sign.test.ts index 30ae778bb..fde49ff61 100644 --- a/packages/keyring/tests/sign.test.ts +++ b/packages/keyring/tests/sign.test.ts @@ -26,7 +26,7 @@ describe("Keyring signing test", () => { walletType: WalletType.mnemonic, }); expect(keyRecord.address).to.be.equal( - "0xf24ff3a9cf04c71dbc94d0b566f7a27b94566cac" + "0xf24ff3a9cf04c71dbc94d0b566f7a27b94566cac", ); const keyRecord2 = await keyring.addKeyPair( { @@ -38,25 +38,25 @@ describe("Keyring signing test", () => { "0x03330102972e476d0a0c8004d7329641760ac01ab695058b2134ada99737f89b97", signerType: SignerType.secp256k1, }, - password + password, ); expect(keyRecord2.address).to.be.equal( - "0x7763488dceb716cb2d8656e65c5846a4b9df1b5d" + "0x7763488dceb716cb2d8656e65c5846a4b9df1b5d", ); const message = "abcd"; const msgToSign = keccak256( - `\x19Ethereum Signed Message:\n${message.length}${message}` + `\x19Ethereum Signed Message:\n${message.length}${message}`, ); keccak256(`\x19Ethereum Signed Message:\n${message.length}${message}`); const sig = await keyring.sign(msgToSign, keyRecord); expect(sig).to.be.equal( - `0xc0cd7923162bbcf6065ca563f69eb44503ac67e9edb9870f8651ff926c9a007c5d26b90e29819915df9cda30e974722edf69c6d1f69a02b76716b74db57767d71b` + `0xc0cd7923162bbcf6065ca563f69eb44503ac67e9edb9870f8651ff926c9a007c5d26b90e29819915df9cda30e974722edf69c6d1f69a02b76716b74db57767d71b`, ); const sig2 = await keyring.sign(msgToSign, keyRecord2); expect(sig2).to.be.equal( - `0x85242cbd5c409001f7c3412b2c0e21e0207ae83547d28abca32324a4ea2cff892bb38d060d51cea045abd7391ffef9eb1fab8b2d50f949a6c1904c6b9e0da2cb1b` + `0x85242cbd5c409001f7c3412b2c0e21e0207ae83547d28abca32324a4ea2cff892bb38d060d51cea045abd7391ffef9eb1fab8b2d50f949a6c1904c6b9e0da2cb1b`, ); }); it( @@ -76,17 +76,17 @@ describe("Keyring signing test", () => { walletType: WalletType.mnemonic, }); expect(keyRecord.address).to.be.equal( - "5GfqwuBBRBSioJY1UYSheSQfcVdX8V4CoBmFpu1JTNRqnUkk" + "5GfqwuBBRBSioJY1UYSheSQfcVdX8V4CoBmFpu1JTNRqnUkk", ); const message = "abcd"; const sig = await keyring.sign( u8aToHex(u8aWrapBytes(stringToU8a(message))), - keyRecord + keyRecord, ); expect(sig).to.be.equal( - `0x55fef6ded518726c589c1eb524f9a6d53e5853e3f94e1d425d018424373604d2769800c174adc6d4ee75b09f4037037495438cbcfed4c77dfbdeeef7d38e0707` + `0x55fef6ded518726c589c1eb524f9a6d53e5853e3f94e1d425d018424373604d2769800c174adc6d4ee75b09f4037037495438cbcfed4c77dfbdeeef7d38e0707`, ); - } + }, ); it("keyring should sign raw keypairs", { timeout: 10_000 }, async () => { @@ -106,10 +106,10 @@ describe("Keyring signing test", () => { "0x03330102972e476d0a0c8004d7329641760ac01ab695058b2134ada99737f89b97", signerType: SignerType.secp256k1, }, - password + password, ); expect(keyRecord.address).to.be.equal( - "0x7763488dceb716cb2d8656e65c5846a4b9df1b5d" + "0x7763488dceb716cb2d8656e65c5846a4b9df1b5d", ); const keyRecord2 = await keyring.addKeyPair( { @@ -121,24 +121,24 @@ describe("Keyring signing test", () => { "0x03ed026faba30429c9c0bd1968e413ee92ad4784bedc48851f3b1bbaae0585f749", signerType: SignerType.secp256k1, }, - password + password, ); expect(keyRecord2.address).to.be.equal( - "0x3777583a1E946863FeAB8826B4c0ebb0a7D14c1B" + "0x3777583a1E946863FeAB8826B4c0ebb0a7D14c1B", ); const message = "abcd"; const msgToSign = keccak256( - `\x19Ethereum Signed Message:\n${message.length}${message}` + `\x19Ethereum Signed Message:\n${message.length}${message}`, ); keccak256(`\x19Ethereum Signed Message:\n${message.length}${message}`); const sig = await keyring.sign(msgToSign, keyRecord); expect(sig).to.be.equal( - `0x85242cbd5c409001f7c3412b2c0e21e0207ae83547d28abca32324a4ea2cff892bb38d060d51cea045abd7391ffef9eb1fab8b2d50f949a6c1904c6b9e0da2cb1b` + `0x85242cbd5c409001f7c3412b2c0e21e0207ae83547d28abca32324a4ea2cff892bb38d060d51cea045abd7391ffef9eb1fab8b2d50f949a6c1904c6b9e0da2cb1b`, ); const sig2 = await keyring.sign(msgToSign, keyRecord2); expect(sig2).to.be.equal( - `0xd84d309ef3f850325ff1758e3a25b9f5eb458101a42c876c8f072a4c429c46417e83711dcfca20fb09a83f54454c8d88bad70456c06f89622ba8cdd90910ae0b1b` + `0xd84d309ef3f850325ff1758e3a25b9f5eb458101a42c876c8f072a4c429c46417e83711dcfca20fb09a83f54454c8d88bad70456c06f89622ba8cdd90910ae0b1b`, ); }); }); diff --git a/packages/request/src/index.ts b/packages/request/src/index.ts index f0236bf1c..df381037d 100644 --- a/packages/request/src/index.ts +++ b/packages/request/src/index.ts @@ -7,7 +7,7 @@ import NoClient from "./libs/noClient"; export default ( url: string, middlewares: MiddlewareFunction[], - options?: any + options?: any, ): RequestClass => { if (!url) { return new NoClient(url, middlewares); diff --git a/packages/request/src/libs/events.ts b/packages/request/src/libs/events.ts index d6f5dbcc2..891bee156 100644 --- a/packages/request/src/libs/events.ts +++ b/packages/request/src/libs/events.ts @@ -44,13 +44,13 @@ export interface WebSocketEventMap { export interface WebSocketEventListenerMap { close: ( - event: CloseEvent + event: CloseEvent, ) => void | { handleEvent: (localEvent: CloseEvent) => void }; error: ( - event: ErrorEvent + event: ErrorEvent, ) => void | { handleEvent: (localEvent: ErrorEvent) => void }; message: ( - event: MessageEvent + event: MessageEvent, ) => void | { handleEvent: (localEvent: MessageEvent) => void }; open: (event: Event) => void | { handleEvent: (localEvent: Event) => void }; } diff --git a/packages/request/src/libs/middleware.ts b/packages/request/src/libs/middleware.ts index 407111de6..1dc577846 100644 --- a/packages/request/src/libs/middleware.ts +++ b/packages/request/src/libs/middleware.ts @@ -18,7 +18,7 @@ class Middleware { executeMiddleware(req: RPCRequestType, res: CallbackFunction, done): void { this.middlewares.reduceRight( (_done, next) => () => next(req, res, _done), - done + done, )(req, res); } diff --git a/packages/request/src/libs/noClient.ts b/packages/request/src/libs/noClient.ts index 01480a311..83d2bafe4 100644 --- a/packages/request/src/libs/noClient.ts +++ b/packages/request/src/libs/noClient.ts @@ -34,7 +34,7 @@ class RPCClient extends EventEmitter implements RequestClass { this.middleware .run(req, callback) .then(() => - reject(new Error(`${req.method} no implemented on noClient`)) + reject(new Error(`${req.method} no implemented on noClient`)), ); }); } diff --git a/packages/request/src/libs/reconnectingWS.ts b/packages/request/src/libs/reconnectingWS.ts index 1bb7f8f09..2ac3c711a 100644 --- a/packages/request/src/libs/reconnectingWS.ts +++ b/packages/request/src/libs/reconnectingWS.ts @@ -97,7 +97,7 @@ export default class ReconnectingWebSocket { constructor( url: UrlProvider, protocols?: string | string[], - options: Options = {} + options: Options = {}, ) { this._url = url; this._protocols = protocols; @@ -293,7 +293,7 @@ export default class ReconnectingWebSocket { */ public addEventListener( type: T, - listener: Events.WebSocketEventListenerMap[T] + listener: Events.WebSocketEventListenerMap[T], ): void { if (this._listeners[type]) { // @ts-ignore @@ -318,12 +318,12 @@ export default class ReconnectingWebSocket { */ public removeEventListener( type: T, - listener: Events.WebSocketEventListenerMap[T] + listener: Events.WebSocketEventListenerMap[T], ): void { if (this._listeners[type]) { // @ts-ignore this._listeners[type] = this._listeners[type].filter( - (l) => l !== listener + (l) => l !== listener, ); } } @@ -420,7 +420,7 @@ export default class ReconnectingWebSocket { this._connectTimeout = setTimeout( () => this._handleTimeout(), - connectionTimeout + connectionTimeout, ); }); } @@ -452,7 +452,7 @@ export default class ReconnectingWebSocket { private _callEventListener( event: Events.WebSocketEventMap[T], - listener: Events.WebSocketEventListenerMap[T] + listener: Events.WebSocketEventListenerMap[T], ) { if ("handleEvent" in listener) { // @ts-ignore @@ -481,7 +481,7 @@ export default class ReconnectingWebSocket { this.onopen(event); } this._listeners.open.forEach((listener) => - this._callEventListener(event, listener) + this._callEventListener(event, listener), ); }; @@ -492,7 +492,7 @@ export default class ReconnectingWebSocket { this.onmessage(event); } this._listeners.message.forEach((listener) => - this._callEventListener(event, listener) + this._callEventListener(event, listener), ); }; @@ -500,7 +500,7 @@ export default class ReconnectingWebSocket { this._debug("error event", event.message); this._disconnect( undefined, - event.message === "TIMEOUT" ? "timeout" : undefined + event.message === "TIMEOUT" ? "timeout" : undefined, ); if (this.onerror) { @@ -508,7 +508,7 @@ export default class ReconnectingWebSocket { } this._debug("exec error listeners"); this._listeners.error.forEach((listener) => - this._callEventListener(event, listener) + this._callEventListener(event, listener), ); this._connect(); @@ -526,7 +526,7 @@ export default class ReconnectingWebSocket { this.onclose(event); } this._listeners.close.forEach((listener) => - this._callEventListener(event, listener) + this._callEventListener(event, listener), ); }; diff --git a/packages/request/src/libs/rpcClient.ts b/packages/request/src/libs/rpcClient.ts index b2e741f39..e3616a783 100644 --- a/packages/request/src/libs/rpcClient.ts +++ b/packages/request/src/libs/rpcClient.ts @@ -36,7 +36,7 @@ class RPCClient extends EventEmitter implements RequestClass { return Promise.reject(new Error(response.statusText)); } return Promise.reject(new Error(`unknown error: ${response.status}`)); - }) + }), ); } @@ -56,7 +56,7 @@ class RPCClient extends EventEmitter implements RequestClass { this.middleware .run(req, callback) .then(() => - this.client.request(req.method, req.params).then(resolve, reject) + this.client.request(req.method, req.params).then(resolve, reject), ); }); } diff --git a/packages/request/src/libs/wsClient.ts b/packages/request/src/libs/wsClient.ts index 4c372afa1..2502e3711 100644 --- a/packages/request/src/libs/wsClient.ts +++ b/packages/request/src/libs/wsClient.ts @@ -25,7 +25,7 @@ class WSClient extends EventEmitter implements RequestClass { constructor( url: string, middlewares: MiddlewareFunction[], - wsOptions: WSOptions = {} + wsOptions: WSOptions = {}, ) { super(); this.queue = {}; @@ -64,7 +64,7 @@ class WSClient extends EventEmitter implements RequestClass { }; this.ws.onclose = (event) => { this.client.rejectAllPendingRequests( - `Connection is closed (${event.reason}).` + `Connection is closed (${event.reason}).`, ); }; this.ws.onopen = () => { @@ -98,8 +98,8 @@ class WSClient extends EventEmitter implements RequestClass { }, (error) => { reject(error); - } - ) + }, + ), ); }); } diff --git a/packages/request/tests/request.test.ts b/packages/request/tests/request.test.ts index 66f7f3312..2a03f22cd 100644 --- a/packages/request/tests/request.test.ts +++ b/packages/request/tests/request.test.ts @@ -15,7 +15,7 @@ describe("Request calls test", () => { expect(chainId).to.equal("0x1"); await request.request({ method: "eth_wrongMethod" }).catch((e) => { expect(e.message).to.be.equal( - "the method eth_wrongMethod does not exist/is not available" + "the method eth_wrongMethod does not exist/is not available", ); }); const blockNumber = await request.request({ @@ -50,7 +50,7 @@ describe("Middleware calls", () => { [middleware1, middleware2], { headers: { "User-Agent": " Mozilla/5.0" }, - } + }, ); const requesters = [rpcRequest, wsRequest]; it("middlewares should respond", { timeout: 3_000 }, async () => { diff --git a/packages/signers/bitcoin/src/index.ts b/packages/signers/bitcoin/src/index.ts index 8d1ae3d39..0504e0d9e 100644 --- a/packages/signers/bitcoin/src/index.ts +++ b/packages/signers/bitcoin/src/index.ts @@ -19,12 +19,12 @@ export class BitcoinSigner implements SignerInterface { async verify( msgHash: string, sig: string, - publicKey: string + publicKey: string, ): Promise { return verify( hexToBuffer(sig), hexToBuffer(msgHash), - hexToBuffer(publicKey) + hexToBuffer(publicKey), ); } @@ -40,7 +40,7 @@ export class BitcoinSigner implements SignerInterface { !this.verify( bufferToHex(msgHashBuffer), bufferToHex(signature), - keyPair.publicKey + keyPair.publicKey, ) ) { throw new Error(Errors.SigningErrors.UnableToVerify); diff --git a/packages/signers/bitcoin/tests/generate.test.ts b/packages/signers/bitcoin/tests/generate.test.ts index 4c7d6505e..9c17e3604 100644 --- a/packages/signers/bitcoin/tests/generate.test.ts +++ b/packages/signers/bitcoin/tests/generate.test.ts @@ -8,19 +8,19 @@ describe("Ethreum address generate", () => { const bitcoinSigner = new BitcoinSigner(); let keypair = await bitcoinSigner.generate(MNEMONIC, "m/44'/0'/0'/0/0"); expect(keypair.address).equals( - "0x03472412900c9f4ce53b0aa251e269979ba4f28912d8029b7556cb8397b14db45a" + "0x03472412900c9f4ce53b0aa251e269979ba4f28912d8029b7556cb8397b14db45a", ); keypair = await bitcoinSigner.generate(MNEMONIC, "m/44'/0'/0'/0/1"); expect(keypair.address).equals( - "0x0344fc4582db2073485156fd17a58f933bebabfc6ba67d0b1ed656acbfdd1e0ee9" + "0x0344fc4582db2073485156fd17a58f933bebabfc6ba67d0b1ed656acbfdd1e0ee9", ); keypair = await bitcoinSigner.generate(MNEMONIC, "m/49'/0'/0'/0/3"); expect(keypair.address).equals( - "0x02a2f83bc8a62a71679b957806901fbea35edb936165ebfd5184305d2d17a74d25" + "0x02a2f83bc8a62a71679b957806901fbea35edb936165ebfd5184305d2d17a74d25", ); keypair = await bitcoinSigner.generate(MNEMONIC, "m/49'/0'/0'/0/12"); expect(keypair.address).equals( - "0x035f9ee3234dc049f65825073db81af3f9a120d8b2d86602d405ac60c7f406a8e4" + "0x035f9ee3234dc049f65825073db81af3f9a120d8b2d86602d405ac60c7f406a8e4", ); }); }); diff --git a/packages/signers/bitcoin/tests/sign.test.ts b/packages/signers/bitcoin/tests/sign.test.ts index 56281d20e..996e93b91 100644 --- a/packages/signers/bitcoin/tests/sign.test.ts +++ b/packages/signers/bitcoin/tests/sign.test.ts @@ -18,8 +18,8 @@ describe("Ethreum signing", () => { Buffer.concat([ hexToBuffer(f.signature), Buffer.from([f.recoveryId]), - ]) - ) + ]), + ), ); }); }); diff --git a/packages/signers/ethereum/src/index.ts b/packages/signers/ethereum/src/index.ts index 9b92c1b3d..c44392d96 100644 --- a/packages/signers/ethereum/src/index.ts +++ b/packages/signers/ethereum/src/index.ts @@ -29,14 +29,14 @@ export class EthereumSigner implements SignerInterface { async verify( msgHash: string, sig: string, - publicKey: string + publicKey: string, ): Promise { const sigdecoded = fromRpcSig(sig as `0x${string}`); const rpubkey = ecrecover( hexToBuffer(msgHash), sigdecoded.v, sigdecoded.r, - sigdecoded.s + sigdecoded.s, ); return bufferToHex(rpubkey) === publicKey; } diff --git a/packages/signers/ethereum/src/utils.ts b/packages/signers/ethereum/src/utils.ts index f95e80508..5bbbfb0aa 100644 --- a/packages/signers/ethereum/src/utils.ts +++ b/packages/signers/ethereum/src/utils.ts @@ -21,7 +21,7 @@ const naclDecrypt = ({ case "x25519-xsalsa20-poly1305": { const recieverPrivateKeyUint8Array = naclDecodeHex(privateKey); const recieverEncryptionPrivateKey = naclBox.keyPair.fromSecretKey( - recieverPrivateKeyUint8Array + recieverPrivateKeyUint8Array, ).secretKey; const nonce = decodeBase64(encryptedData.nonce); const ciphertext = decodeBase64(encryptedData.ciphertext); @@ -30,7 +30,7 @@ const naclDecrypt = ({ ciphertext, nonce, ephemPublicKey, - recieverEncryptionPrivateKey + recieverEncryptionPrivateKey, ); let output; try { diff --git a/packages/signers/ethereum/tests/encrypt.test.ts b/packages/signers/ethereum/tests/encrypt.test.ts index f597aedde..2c1de5824 100644 --- a/packages/signers/ethereum/tests/encrypt.test.ts +++ b/packages/signers/ethereum/tests/encrypt.test.ts @@ -27,7 +27,7 @@ describe("Ethreum encrypt", () => { it("it should decrypt", async () => { const ethereumSigner = new EthereumSigner(); const encryptedMessage = bufferToHex( - Buffer.from(JSON.stringify(encryptedData), "utf8") + Buffer.from(JSON.stringify(encryptedData), "utf8"), ); const decrypted = await ethereumSigner.decrypt(encryptedMessage, ecpair); expect(decrypted).equals(secretMessage); diff --git a/packages/signers/ethereum/tests/generate.test.ts b/packages/signers/ethereum/tests/generate.test.ts index bdb81e2b8..384198c07 100644 --- a/packages/signers/ethereum/tests/generate.test.ts +++ b/packages/signers/ethereum/tests/generate.test.ts @@ -8,19 +8,19 @@ describe("Ethreum address generate", () => { const ethreumSigner = new EthereumSigner(); let keypair = await ethreumSigner.generate(MNEMONIC, "m/44'/60'/0'/0/0"); expect(keypair.address).equals( - "0x4dcccf58c6573eb896250b0c9647a40c1673af44" + "0x4dcccf58c6573eb896250b0c9647a40c1673af44", ); keypair = await ethreumSigner.generate(MNEMONIC, "m/44'/60'/0'/0/1"); expect(keypair.address).equals( - "0xf4a950dac2cf3a8101e375550eeb79a53b74335c" + "0xf4a950dac2cf3a8101e375550eeb79a53b74335c", ); keypair = await ethreumSigner.generate(MNEMONIC, "m/44'/60'/0'/1"); expect(keypair.address).equals( - "0xd49dfba8172c8230baaf3797aba628fa6e28275a" + "0xd49dfba8172c8230baaf3797aba628fa6e28275a", ); keypair = await ethreumSigner.generate(MNEMONIC, "m/44'/200625'/0'/0/0"); expect(keypair.address).equals( - "0xa2d4f37035a61641ec4c8b46efee2363ed3fef20" + "0xa2d4f37035a61641ec4c8b46efee2363ed3fef20", ); }); }); diff --git a/packages/signers/ethereum/tests/sign.test.ts b/packages/signers/ethereum/tests/sign.test.ts index 5af106b03..515fd6493 100644 --- a/packages/signers/ethereum/tests/sign.test.ts +++ b/packages/signers/ethereum/tests/sign.test.ts @@ -16,7 +16,7 @@ describe("Ethreum signing", () => { const ethreumSigner = new EthereumSigner(); const signature = await ethreumSigner.sign(echash, ecpair); expect(signature).equals( - "0x99e71a99cb2270b8cac5254f9e99b6210c6c10224a1579cf389ef88b20a1abe9129ff05af364204442bdb53ab6f18a99ab48acc9326fa689f228040429e3ca661b" + "0x99e71a99cb2270b8cac5254f9e99b6210c6c10224a1579cf389ef88b20a1abe9129ff05af364204442bdb53ab6f18a99ab48acc9326fa689f228040429e3ca661b", ); }); }); diff --git a/packages/signers/kadena/src/index.ts b/packages/signers/kadena/src/index.ts index 05d14c6bc..79a739cdc 100644 --- a/packages/signers/kadena/src/index.ts +++ b/packages/signers/kadena/src/index.ts @@ -21,19 +21,19 @@ export class KadenaSigner implements SignerInterface { async verify( msgHash: string, sig: string, - publicKey: string + publicKey: string, ): Promise { return tweetSign.detached.verify( hexToBuffer(msgHash), hexToBuffer(sig), - hexToBuffer(publicKey) + hexToBuffer(publicKey), ); } async sign(msgHash: string, keyPair: KeyPair): Promise { const sig = tweetSign.detached( hexToBuffer(msgHash), - hexToBuffer(keyPair.privateKey) + hexToBuffer(keyPair.privateKey), ); return bufferToHex(sig); } diff --git a/packages/signers/kadena/src/libs/ed25519.ts b/packages/signers/kadena/src/libs/ed25519.ts index 8670c82c4..2fdb00dd6 100644 --- a/packages/signers/kadena/src/libs/ed25519.ts +++ b/packages/signers/kadena/src/libs/ed25519.ts @@ -71,7 +71,7 @@ const derivePath = (path: Path, seed: Hex, offset = HARDENED_OFFSET): Keys => { return segments.reduce( (parentKeys, segment) => CKDPriv(parentKeys, segment + offset), - { key, chainCode } + { key, chainCode }, ); }; diff --git a/packages/signers/kadena/tests/generate.test.ts b/packages/signers/kadena/tests/generate.test.ts index a082f682d..11920aa49 100644 --- a/packages/signers/kadena/tests/generate.test.ts +++ b/packages/signers/kadena/tests/generate.test.ts @@ -12,25 +12,25 @@ describe("Kadena address generate", () => { // Act & Assert let keypair = await kadenaSigner.generate(MNEMONIC, "m/44'/626'/0"); expect(keypair.address).equals( - "0x8910d3f54c8dff9fce85da39a4e2c194ffc73dd4182e47d0ddbf9883d6aaff06" + "0x8910d3f54c8dff9fce85da39a4e2c194ffc73dd4182e47d0ddbf9883d6aaff06", ); // Act & Assert keypair = await kadenaSigner.generate(MNEMONIC, "m/44'/626'/1"); expect(keypair.address).equals( - "0x3beae80c42b00b2847e27f3c35da801c728d5f22fb31647c2271c50c80179077" + "0x3beae80c42b00b2847e27f3c35da801c728d5f22fb31647c2271c50c80179077", ); // Act & Assert keypair = await kadenaSigner.generate(MNEMONIC, "m/44'/626'/2"); expect(keypair.address).equals( - "0x9a5881272654d58195b7e09c4630c7ec4081065dade87d6f7c394bf0858cd306" + "0x9a5881272654d58195b7e09c4630c7ec4081065dade87d6f7c394bf0858cd306", ); // Act & Assert keypair = await kadenaSigner.generate(MNEMONIC, "m/44'/626'/3"); expect(keypair.address).equals( - "0x94e167fd2fd2dc741fa0ce820a7c57857786dd60505f28de6a15dfe73934b5e9" + "0x94e167fd2fd2dc741fa0ce820a7c57857786dd60505f28de6a15dfe73934b5e9", ); }); }); diff --git a/packages/signers/kadena/tests/sign.test.ts b/packages/signers/kadena/tests/sign.test.ts index 8bc4e0ab7..9c880efe8 100644 --- a/packages/signers/kadena/tests/sign.test.ts +++ b/packages/signers/kadena/tests/sign.test.ts @@ -50,7 +50,7 @@ describe("Kadena signing", () => { const verifyResult = await kadenaSigner.verify( msgHash, signature, - keypair.publicKey + keypair.publicKey, ); // Assert diff --git a/packages/signers/polkadot/src/index.ts b/packages/signers/polkadot/src/index.ts index ae2fdf8a6..91c47bed8 100644 --- a/packages/signers/polkadot/src/index.ts +++ b/packages/signers/polkadot/src/index.ts @@ -38,17 +38,17 @@ export class PolkadotSigner implements SignerInterface { async generate( mnemonic: string, derivationPath = "", - options: SignOptions = { onlyJS: false } + options: SignOptions = { onlyJS: false }, ): Promise { await waitReady(); const { path, phrase, password } = keyExtractSuri( - `${mnemonic}${derivationPath}` + `${mnemonic}${derivationPath}`, ); const seed = mnemonicToMiniSecret( phrase, password, undefined, - options.onlyJS + options.onlyJS, ); let pair: KeyPair; switch (this.type) { @@ -56,14 +56,14 @@ export class PolkadotSigner implements SignerInterface { pair = keyFromPath( secp256k1PairFromSeed(seed, options.onlyJS), path, - "ecdsa" + "ecdsa", ); break; case SignerType.ed25519: pair = keyFromPath( ed25519PairFromSeed(seed, options.onlyJS), path, - "ed25519" + "ed25519", ); break; case SignerType.sr25519: @@ -85,7 +85,7 @@ export class PolkadotSigner implements SignerInterface { async verify( msgHash: string, sig: string, - publicKey: string + publicKey: string, ): Promise { await waitReady(); const rpubkey = signatureVerify(msgHash, sig, publicKey); @@ -95,7 +95,7 @@ export class PolkadotSigner implements SignerInterface { async sign( msgHash: string, keyPair: KRKeyPair, - options: SignOptions = { onlyJS: false } + options: SignOptions = { onlyJS: false }, ): Promise { const msgHashBuffer = hexToBuffer(msgHash); let sig: Buffer; @@ -107,15 +107,15 @@ export class PolkadotSigner implements SignerInterface { switch (this.type) { case SignerType.ecdsa: sig = Buffer.from( - secp256k1Sign(msgHashBuffer, pair, "blake2", options.onlyJS) + secp256k1Sign(msgHashBuffer, pair, "blake2", options.onlyJS), ); assert( this.verify( bufferToHex(msgHashBuffer), bufferToHex(sig), - bufferToHex(pair.publicKey) + bufferToHex(pair.publicKey), ), - Errors.SigningErrors.UnableToVerify + Errors.SigningErrors.UnableToVerify, ); return bufferToHex(sig); case SignerType.ed25519: @@ -124,9 +124,9 @@ export class PolkadotSigner implements SignerInterface { this.verify( bufferToHex(msgHashBuffer), bufferToHex(sig), - bufferToHex(pair.publicKey) + bufferToHex(pair.publicKey), ), - Errors.SigningErrors.UnableToVerify + Errors.SigningErrors.UnableToVerify, ); return bufferToHex(sig); case SignerType.sr25519: @@ -135,9 +135,9 @@ export class PolkadotSigner implements SignerInterface { this.verify( bufferToHex(msgHashBuffer), bufferToHex(sig), - bufferToHex(pair.publicKey) + bufferToHex(pair.publicKey), ), - Errors.SigningErrors.UnableToVerify + Errors.SigningErrors.UnableToVerify, ); return bufferToHex(sig); default: diff --git a/packages/signers/polkadot/tests/generate.test.ts b/packages/signers/polkadot/tests/generate.test.ts index 51c66e7f0..a21ce993d 100644 --- a/packages/signers/polkadot/tests/generate.test.ts +++ b/packages/signers/polkadot/tests/generate.test.ts @@ -16,15 +16,15 @@ describe("Polkadot Address generate", () => { for (const bool of [true, false]) { let keypair = await signer.generate(MNEMONIC, "//0", { onlyJS: bool }); expect(keypair.address).equals( - "5FqSRmrJGMEdb5xk58k6x9RUw7Ri9oEKckDApupjMDysDrZL" + "5FqSRmrJGMEdb5xk58k6x9RUw7Ri9oEKckDApupjMDysDrZL", ); keypair = await signer.generate(MNEMONIC, "//1", { onlyJS: bool }); expect(keypair.address).equals( - "5F2NJSfSZ1ZtUiHXKc3XLKY6SwU3Y1jVw4CD2mKW4okBHNnx" + "5F2NJSfSZ1ZtUiHXKc3XLKY6SwU3Y1jVw4CD2mKW4okBHNnx", ); keypair = await signer.generate(MNEMONIC, "//0//0", { onlyJS: bool }); expect(keypair.address).equals( - "5GKwdnFRMxHP8hTjPY39eF88oCzoUQURawFpx2sJhCMCP15D" + "5GKwdnFRMxHP8hTjPY39eF88oCzoUQURawFpx2sJhCMCP15D", ); } const list = [ @@ -88,15 +88,15 @@ describe("Polkadot Address generate", () => { for (const bool of [true, false]) { let keypair = await signer.generate(PHRASE, "//Alice", { onlyJS: bool }); expect(keypair.address).equals( - "5C7C2Z5sWbytvHpuLTvzKunnnRwQxft1jiqrLD5rhucQ5S9X" + "5C7C2Z5sWbytvHpuLTvzKunnnRwQxft1jiqrLD5rhucQ5S9X", ); keypair = await signer.generate(PHRASE, "//0", { onlyJS: bool }); expect(keypair.address).equals( - "5EYLKPDaH7gGuon5vesr5QX8S9c22wYvgWwdRoGj3FykwoE8" + "5EYLKPDaH7gGuon5vesr5QX8S9c22wYvgWwdRoGj3FykwoE8", ); keypair = await signer.generate(PHRASE, "", { onlyJS: bool }); expect(keypair.address).equals( - "5GKyBtzbxKU1qjhZrKpMiwtJj7o6jJcXbKQVtYq74DCPerXN" + "5GKyBtzbxKU1qjhZrKpMiwtJj7o6jJcXbKQVtYq74DCPerXN", ); } }); @@ -105,15 +105,15 @@ describe("Polkadot Address generate", () => { for (const bool of [true, false]) { let keypair = await signer.generate(PHRASE, "//Alice", { onlyJS: bool }); expect(keypair.address).equals( - "5FA9nQDVg267DEd8m1ZypXLBnvN7SFxYwV7ndqSYGiN9TTpu" + "5FA9nQDVg267DEd8m1ZypXLBnvN7SFxYwV7ndqSYGiN9TTpu", ); keypair = await signer.generate(PHRASE, "//0", { onlyJS: bool }); expect(keypair.address).equals( - "5HrCphkqYygSXWt9rHebqaqbfEYekhzjyjQNjZiPxpb3XsKY" + "5HrCphkqYygSXWt9rHebqaqbfEYekhzjyjQNjZiPxpb3XsKY", ); keypair = await signer.generate(PHRASE, "", { onlyJS: bool }); expect(keypair.address).equals( - "5DFJF7tY4bpbpcKPJcBTQaKuCDEPCpiz8TRjpmLeTtweqmXL" + "5DFJF7tY4bpbpcKPJcBTQaKuCDEPCpiz8TRjpmLeTtweqmXL", ); } }); diff --git a/packages/signers/polkadot/tests/sign.test.ts b/packages/signers/polkadot/tests/sign.test.ts index 325028ca4..933d5027f 100644 --- a/packages/signers/polkadot/tests/sign.test.ts +++ b/packages/signers/polkadot/tests/sign.test.ts @@ -17,7 +17,7 @@ describe("Polkadot signers", () => { const keypair = await signer.generate(MNEMONIC, "", { onlyJS: bool }); const signature = await signer.sign(MSG_HASH, keypair, { onlyJS: bool }); expect(signature).equals( - "0x44d27f74c8f35bf816f701e1081a12359235d99f22a95fac2b6f9614ecf06cfe11d1dc62c0ef85545953b51b48dc9b0786f70d9e0fdd97439055ec2bda1b703d00" + "0x44d27f74c8f35bf816f701e1081a12359235d99f22a95fac2b6f9614ecf06cfe11d1dc62c0ef85545953b51b48dc9b0786f70d9e0fdd97439055ec2bda1b703d00", ); } }); @@ -27,7 +27,7 @@ describe("Polkadot signers", () => { const keypair = await signer.generate(MNEMONIC, "", { onlyJS: bool }); const signature = await signer.sign(MSG_HASH, keypair, { onlyJS: bool }); expect(keypair.address).equals( - "5E4Vd2pQCSLLWxHhXVSH1Kc9TQdpAXdjLfWtSKgsY3A9AXM4" + "5E4Vd2pQCSLLWxHhXVSH1Kc9TQdpAXdjLfWtSKgsY3A9AXM4", ); expect(signature.length).equals(130); } @@ -38,7 +38,7 @@ describe("Polkadot signers", () => { const keypair = await signer.generate(MNEMONIC, "", { onlyJS: bool }); const signature = await signer.sign(MSG_HASH, keypair, { onlyJS: bool }); expect(signature).equals( - "0x35aacb42a86c330228515ddc6ea286c10feae2d7cf60ca7c4949663ee95159e5e3ec4a9597fc643d90711ef01e0f712610e93bce3388c175d71baf363bc7f002" + "0x35aacb42a86c330228515ddc6ea286c10feae2d7cf60ca7c4949663ee95159e5e3ec4a9597fc643d90711ef01e0f712610e93bce3388c175d71baf363bc7f002", ); } }); diff --git a/packages/storage/src/local-forage.ts b/packages/storage/src/local-forage.ts index 8558b8990..8c8d04505 100644 --- a/packages/storage/src/local-forage.ts +++ b/packages/storage/src/local-forage.ts @@ -11,7 +11,7 @@ export class LocalForage implements BrowserStorageArea { drivers: Array = [ LocalForageLib.INDEXEDDB, LocalForageLib.LOCALSTORAGE, - ] + ], ) { this.namespace = namespace; this.storage = LocalForageLib.createInstance({ diff --git a/packages/storage/tests/dummyDriver.js b/packages/storage/tests/dummyDriver.js index 5e5672a18..e8bbde12f 100644 --- a/packages/storage/tests/dummyDriver.js +++ b/packages/storage/tests/dummyDriver.js @@ -333,7 +333,7 @@ function _serialize(value, callback) { } catch (e) { window.console.error( "Couldn't convert value into a JSON " + "string: ", - value + value, ); callback(e); @@ -356,7 +356,7 @@ function _deserialize(value) { const serializedString = value.substring(TYPE_SERIALIZED_MARKER_LENGTH); const type = value.substring( SERIALIZED_MARKER_LENGTH, - TYPE_SERIALIZED_MARKER_LENGTH + TYPE_SERIALIZED_MARKER_LENGTH, ); // Fill the string into a ArrayBuffer. @@ -423,7 +423,7 @@ function executeCallback(promise, callback) { }, (error) => { callback(error); - } + }, ); } } diff --git a/packages/swap/src/common/estimateGasList.ts b/packages/swap/src/common/estimateGasList.ts index d1e0471b3..736718d59 100644 --- a/packages/swap/src/common/estimateGasList.ts +++ b/packages/swap/src/common/estimateGasList.ts @@ -24,7 +24,7 @@ const supportedNetworks: { const useStandardEstimate = ( transactions: EVMTransaction[], - network: SupportedNetworkName + network: SupportedNetworkName, ): Promise<{ isError?: boolean; errorMessage?: string; @@ -101,7 +101,7 @@ const useStandardEstimate = ( const estimateEVMGasList = ( transactions: EVMTransaction[], - network: SupportedNetworkName + network: SupportedNetworkName, ): Promise<{ isError?: boolean; errorMessage?: string; diff --git a/packages/swap/src/index.ts b/packages/swap/src/index.ts index 1c4a9d1bf..d38b21253 100644 --- a/packages/swap/src/index.ts +++ b/packages/swap/src/index.ts @@ -103,12 +103,12 @@ class Swap extends EventEmitter { private async init() { if (TOKEN_LISTS[this.network]) { this.tokenList = await fetch(TOKEN_LISTS[this.network]).then((res) => - res.json() + res.json(), ); } this.topTokenInfo = await fetch(TOP_TOKEN_INFO_LIST).then((res) => - res.json() + res.json(), ); // TODO: use network type instead? @@ -134,7 +134,7 @@ class Swap extends EventEmitter { } await Promise.all( - this.providers.map((Provider) => Provider.init(this.tokenList.all)) + this.providers.map((Provider) => Provider.init(this.tokenList.all)), ); const allFromTokens: ProviderFromTokenResponse = {}; [...this.providers].reverse().forEach((p) => { @@ -144,7 +144,7 @@ class Swap extends EventEmitter { all: Object.values(allFromTokens).sort(sortNativeToFront), top: this.tokenList.top.filter((topt) => !!allFromTokens[topt.address]), trending: this.tokenList.trending.filter( - (trendt) => !!allFromTokens[trendt.address] + (trendt) => !!allFromTokens[trendt.address], ), }; const native = this.fromTokens.all.shift(); @@ -199,7 +199,7 @@ class Swap extends EventEmitter { */ async getQuotes( options: getQuoteOptions, - context?: { signal?: AbortSignal } + context?: { signal?: AbortSignal }, ): Promise { const response = await Promise.all( this.providers.map((provider) => @@ -210,14 +210,14 @@ class Swap extends EventEmitter { infiniteApproval: this.evmOptions.infiniteApproval, walletIdentifier: this.walletId, }, - context + context, ) .then((res) => { if (!res) return res; this.emit(Events.QuoteUpdate, res.toTokenAmount); return res; - }) - ) + }), + ), ); // Sort by the dest token amount i.e. best offer first return response @@ -227,7 +227,7 @@ class Swap extends EventEmitter { getSwap( quote: SwapQuote, - context?: { signal?: AbortSignal } + context?: { signal?: AbortSignal }, ): Promise { const provider = this.providers.find((p) => p.name === quote.provider); return provider.getSwap(quote, context); diff --git a/packages/swap/src/providers/changelly/index.ts b/packages/swap/src/providers/changelly/index.ts index 926630f0a..16cd5fcc6 100644 --- a/packages/swap/src/providers/changelly/index.ts +++ b/packages/swap/src/providers/changelly/index.ts @@ -94,7 +94,7 @@ if (DEBUG) { now.getMilliseconds().toString().padStart(3, "0"); console.info( `\x1b[90m${ymdhms}\x1b[0m \x1b[32mChangellySwapProvider.${context}\x1b[0m: ${message}`, - ...args + ...args, ); }; } else { @@ -137,7 +137,7 @@ class Changelly extends ProviderClass { if (!Changelly.isSupported(this.network)) { debug( "init", - `Enkrypt does not support Changelly on this network network=${this.network}` + `Enkrypt does not support Changelly on this network network=${this.network}`, ); return; } @@ -153,7 +153,7 @@ class Changelly extends ProviderClass { /** List of changelly blockchain names */ const supportedChangellyNames = new Set( - Object.values(supportedNetworks).map((s) => s.changellyName) + Object.values(supportedNetworks).map((s) => s.changellyName), ); this.changellyList.forEach((cur) => { @@ -191,20 +191,20 @@ class Changelly extends ProviderClass { this.setTicker( cur.token, changellyToNetwork[cur.blockchain], - cur.ticker + cur.ticker, ); }); debug( "init", - `Finished initialising this.changellyList.length=${this.changellyList.length}` + `Finished initialising this.changellyList.length=${this.changellyList.length}`, ); } private setTicker( token: TokenType, network: SupportedNetworkName, - ticker: string + ticker: string, ) { this.contractToTicker[`${network}-${token.address}`] = ticker; } @@ -228,7 +228,7 @@ class Changelly extends ProviderClass { private async changellyRequest( method: string, params: any, - context?: { signal?: AbortSignal } + context?: { signal?: AbortSignal }, ): Promise> { const signal = context?.signal; const aborter = new AbortController(); @@ -238,7 +238,7 @@ class Changelly extends ProviderClass { } function onTimeout() { aborter.abort( - new Error(`Changelly API request timed out ${BASE_URL} ${method}`) + new Error(`Changelly API request timed out ${BASE_URL} ${method}`), ); } function cleanup() { @@ -280,14 +280,14 @@ class Changelly extends ProviderClass { const response = await this.changellyRequest( "validateAddress", - params + params, ); if (response.error) { console.warn( `Error validating address with via Changelly` + ` code=${String(response.error.code)}` + - ` message=${String(response.error.message)}` + ` message=${String(response.error.message)}`, ); return false; } @@ -296,7 +296,7 @@ class Changelly extends ProviderClass { console.warn( 'Unexpected response to "validateAddress" call to Changelly.' + ` Expected a response.result.result to be a boolean` + - ` but received response: ${JSON.stringify(response)}` + ` but received response: ${JSON.stringify(response)}`, ); return false; } @@ -307,7 +307,7 @@ class Changelly extends ProviderClass { `Changelly validateAddress result` + ` address=${address}` + ` ticker=${ticker}` + - ` isValid=${isValid}` + ` isValid=${isValid}`, ); return isValid; } @@ -323,7 +323,7 @@ class Changelly extends ProviderClass { async getMinMaxAmount( options: { fromToken: TokenType; toToken: TokenTypeTo }, - context?: { signal?: AbortSignal } + context?: { signal?: AbortSignal }, ): Promise { const { fromToken, toToken } = options; const signal = context?.signal; @@ -341,7 +341,7 @@ class Changelly extends ProviderClass { from: this.getTicker(fromToken, this.network), to: this.getTicker( toToken as TokenType, - toToken.networkInfo.name as SupportedNetworkName + toToken.networkInfo.name as SupportedNetworkName, ), }; @@ -349,7 +349,7 @@ class Changelly extends ProviderClass { await this.changellyRequest( "getFixRate", params, - { signal } + { signal }, ); if (response.error) { @@ -360,7 +360,7 @@ class Changelly extends ProviderClass { ` toToken=${toToken.symbol} (${params.to})` + ` took=${(Date.now() - startedAt).toLocaleString()}ms` + ` code=${String(response.error.code)}` + - ` message=${String(response.error.message)}` + ` message=${String(response.error.message)}`, ); return emptyResponse; } @@ -378,7 +378,7 @@ class Changelly extends ProviderClass { `Successfully got min and max of swap pair` + ` fromToken=${fromToken.symbol} (${params.from})` + ` toToken=${toToken.symbol} (${params.to})` + - ` took=${(Date.now() - startedAt).toLocaleString()}ms` + ` took=${(Date.now() - startedAt).toLocaleString()}ms`, ); return minMax; } catch (err) { @@ -388,7 +388,7 @@ class Changelly extends ProviderClass { ` fromToken=${fromToken.symbol}` + ` toToken=${toToken.symbol}` + ` took=${(Date.now() - startedAt).toLocaleString()}ms` + - ` err=${String(err)}` + ` err=${String(err)}`, ); return emptyResponse; } @@ -397,7 +397,7 @@ class Changelly extends ProviderClass { async getQuote( options: getQuoteOptions, meta: QuoteMetaOptions, - context?: { signal?: AbortSignal } + context?: { signal?: AbortSignal }, ): Promise { const signal = context?.signal; @@ -411,18 +411,18 @@ class Changelly extends ProviderClass { ` fromAddress=${options.fromAddress}` + ` toAddress=${options.toAddress}` + ` fromNetwork=${this.network}` + - ` toNetwork=${options.toToken.networkInfo.name}` + ` toNetwork=${options.toToken.networkInfo.name}`, ); if ( !Changelly.isSupported( - options.toToken.networkInfo.name as SupportedNetworkName + options.toToken.networkInfo.name as SupportedNetworkName, ) ) { debug( "getQuote", `No swap: Enkrypt does not support Changelly on the destination network` + - ` dstNetwork=${options.toToken.networkInfo.name}` + ` dstNetwork=${options.toToken.networkInfo.name}`, ); return null; } @@ -431,7 +431,7 @@ class Changelly extends ProviderClass { debug( "getQuote", `No swap: Enkrypt does not support Changelly on the source network` + - ` srcNetwork=${this.network}` + ` srcNetwork=${this.network}`, ); return null; } @@ -441,7 +441,7 @@ class Changelly extends ProviderClass { "getQuote", `No swap: Failed to find ticker for src token` + ` srcToken=${options.fromToken.symbol}` + - ` srcNetwork=${this.network}` + ` srcNetwork=${this.network}`, ); return null; } @@ -449,14 +449,14 @@ class Changelly extends ProviderClass { if ( !this.getTicker( options.toToken as TokenType, - options.toToken.networkInfo.name as SupportedNetworkName + options.toToken.networkInfo.name as SupportedNetworkName, ) ) { debug( "getQuote", `No swap: Failed to find ticker for dst token` + ` dstToken=${options.toToken.symbol}` + - ` dstNetwork=${options.toToken.networkInfo.name}` + ` dstNetwork=${options.toToken.networkInfo.name}`, ); return null; } @@ -481,7 +481,7 @@ class Changelly extends ProviderClass { ` fromToken=${options.fromToken.symbol}` + ` toToken=${options.toToken.symbol}` + ` minimumFrom=${minMax.minimumFrom.toString()}` + - ` maximumFrom=${minMax.maximumFrom.toString()}` + ` maximumFrom=${minMax.maximumFrom.toString()}`, ); return null; } @@ -493,11 +493,11 @@ class Changelly extends ProviderClass { from: this.getTicker(options.fromToken, this.network), to: this.getTicker( options.toToken as TokenType, - options.toToken.networkInfo.name as SupportedNetworkName + options.toToken.networkInfo.name as SupportedNetworkName, ), amountFrom: fromBase( quoteRequestAmount.toString(), - options.fromToken.decimals + options.fromToken.decimals, ), }; @@ -505,7 +505,7 @@ class Changelly extends ProviderClass { await this.changellyRequest( "getFixRateForAmount", params, - { signal } + { signal }, ); debug("getQuote", `Received Changelly swap response`); @@ -518,7 +518,7 @@ class Changelly extends ProviderClass { ` toToken=${options.toToken.symbol} (${params.to})` + ` took=${(Date.now() - startedAt).toLocaleString()}ms` + ` code=${String(response.error.code)}` + - ` message=${String(response.error.message)}` + ` message=${String(response.error.message)}`, ); return null; } @@ -531,7 +531,7 @@ class Changelly extends ProviderClass { ` toToken=${options.toToken.symbol} (${params.to})` + ` took=${(Date.now() - startedAt).toLocaleString()}ms` + ` code=${String(response.error.code)}` + - ` message=${String(response.error.message)}` + ` message=${String(response.error.message)}`, ); return null; } @@ -543,7 +543,7 @@ class Changelly extends ProviderClass { ` fromToken=${options.fromToken.symbol} (${params.from})` + ` toToken=${options.toToken.symbol} (${params.to})` + ` took=${(Date.now() - startedAt).toLocaleString()}ms` + - ` count=${response.result.length}ms` + ` count=${response.result.length}ms`, ); } @@ -560,7 +560,7 @@ class Changelly extends ProviderClass { try { toTokenAmountBase = toBase( firstChangellyFixRateQuote.amountTo, - options.toToken.decimals + options.toToken.decimals, ); } catch (err) { console.warn( @@ -568,13 +568,13 @@ class Changelly extends ProviderClass { ` decimals than the token has, attempting to trim trailing decimals...` + ` amountTo=${firstChangellyFixRateQuote.amountTo}` + ` toTokenDecimals=${options.toToken.decimals}` + - ` err=${String(err)}` + ` err=${String(err)}`, ); const original = firstChangellyFixRateQuote.amountTo; // eslint-disable-next-line no-use-before-define const [success, fixed] = fixBaseAndTrimDecimals( original, - options.toToken.decimals + options.toToken.decimals, ); if (!success) throw err; const rounded = (BigInt(fixed) - BigInt(1)).toString(); @@ -588,7 +588,7 @@ class Changelly extends ProviderClass { ` options.toToken.decimals=${options.toToken.decimals}` + ` options.toToken.symbol=${options.toToken.symbol}` + ` options.toToken.name=${options.toToken.name}` + - ` options.toToken.address=${options.toToken.address}` + ` options.toToken.address=${options.toToken.address}`, ); } @@ -597,7 +597,7 @@ class Changelly extends ProviderClass { try { networkFeeBase = toBase( firstChangellyFixRateQuote.networkFee, - options.toToken.decimals + options.toToken.decimals, ); } catch (err) { console.warn( @@ -605,13 +605,13 @@ class Changelly extends ProviderClass { ` decimals than the token has, attempting to trim trailing decimals...` + ` networkFee=${firstChangellyFixRateQuote.networkFee}` + ` toTokenDecimals=${options.toToken.decimals}` + - ` err=${String(err)}` + ` err=${String(err)}`, ); const original = firstChangellyFixRateQuote.networkFee; // eslint-disable-next-line no-use-before-define const [success, fixed] = fixBaseAndTrimDecimals( original, - options.toToken.decimals + options.toToken.decimals, ); if (!success) throw err; const rounded = (BigInt(fixed) + BigInt(1)).toString(); @@ -625,7 +625,7 @@ class Changelly extends ProviderClass { ` options.toToken.decimals=${options.toToken.decimals}` + ` options.toToken.symbol=${options.toToken.symbol}` + ` options.toToken.name=${options.toToken.name}` + - ` options.toToken.address=${options.toToken.address}` + ` options.toToken.address=${options.toToken.address}`, ); } @@ -654,7 +654,7 @@ class Changelly extends ProviderClass { debug( "getQuote", `Successfully retrieved quote from Changelly via "getFixRateForAmount"` + - ` took=${(Date.now() - startedAt).toLocaleString()}ms` + ` took=${(Date.now() - startedAt).toLocaleString()}ms`, ); return providerQuoteResponse; @@ -663,7 +663,7 @@ class Changelly extends ProviderClass { `Errored getting quotes from Changelly via "getFixRateForAmount",` + ` returning no quotes` + ` took=${(Date.now() - startedAt).toLocaleString()}ms` + - ` err=${String(err)}` + ` err=${String(err)}`, ); return null; } @@ -671,7 +671,7 @@ class Changelly extends ProviderClass { async getSwap( quote: SwapQuote, - context?: { signal?: AbortSignal } + context?: { signal?: AbortSignal }, ): Promise { const signal = context?.signal; @@ -682,20 +682,20 @@ class Changelly extends ProviderClass { debug( "getSwap", `Enkrypt does not support Changelly on the source network, returning no swap` + - ` srcNetwork=${this.network}` + ` srcNetwork=${this.network}`, ); return null; } if ( !Changelly.isSupported( - quote.options.toToken.networkInfo.name as SupportedNetworkName + quote.options.toToken.networkInfo.name as SupportedNetworkName, ) ) { debug( "getSwap", `Enkrypt does not support Changelly on the destination network, returning no swap` + - ` dstNetwork=${quote.options.toToken.networkInfo.name}` + ` dstNetwork=${quote.options.toToken.networkInfo.name}`, ); return null; } @@ -705,13 +705,13 @@ class Changelly extends ProviderClass { from: this.getTicker(quote.options.fromToken, this.network), to: this.getTicker( quote.options.toToken as TokenType, - quote.options.toToken.networkInfo.name as SupportedNetworkName + quote.options.toToken.networkInfo.name as SupportedNetworkName, ), refundAddress: quote.options.fromAddress, address: quote.options.toAddress, amountFrom: fromBase( quote.options.amount.toString(), - quote.options.fromToken.decimals + quote.options.fromToken.decimals, ), rateId: quote.meta.changellyQuoteId, }; @@ -720,7 +720,7 @@ class Changelly extends ProviderClass { await this.changellyRequest( "createFixTransaction", params, - { signal } + { signal }, ); if (response.error) { @@ -730,7 +730,7 @@ class Changelly extends ProviderClass { ` toToken=${quote.options.toToken.symbol} (${params.to})` + ` took=${(Date.now() - startedAt).toLocaleString()}ms` + ` code=${String(response.error.code)}` + - ` message=${String(response.error.message)}` + ` message=${String(response.error.message)}`, ); return null; } @@ -740,7 +740,7 @@ class Changelly extends ProviderClass { `Changelly "createFixTransaction" response contains no id, returning no swap` + ` fromToken=${quote.options.fromToken.symbol} (${params.from})` + ` toToken=${quote.options.toToken.symbol} (${params.to})` + - ` took=${(Date.now() - startedAt).toLocaleString()}ms` + ` took=${(Date.now() - startedAt).toLocaleString()}ms`, ); return null; } @@ -770,7 +770,7 @@ class Changelly extends ProviderClass { } const accurateGasEstimate = await estimateEVMGasList( [transaction], - this.network + this.network, ); if (accurateGasEstimate) { if (accurateGasEstimate.isError) return null; @@ -798,7 +798,7 @@ class Changelly extends ProviderClass { ` latestBlockHash=${latestBlockHash.blockhash}` + ` lastValidBlockHeight=${latestBlockHash.lastValidBlockHeight}` + ` payinAddress=${changellyFixedRateTx.payinAddress}` + - ` lamports=${BigInt(quote.options.amount.toString())}` + ` lamports=${BigInt(quote.options.amount.toString())}`, ); versionedTx = new VersionedTransaction( new TransactionMessage({ @@ -811,7 +811,7 @@ class Changelly extends ProviderClass { lamports: BigInt(quote.options.amount.toString()), }), ], - }).compileToV0Message() + }).compileToV0Message(), ); } else { // Swapping from a token on SOL @@ -826,13 +826,13 @@ class Changelly extends ProviderClass { const walletAta = getSPLAssociatedTokenAccountPubkey( wallet, mint, - tokenProgramId + tokenProgramId, ); const payin = new PublicKey(changellyFixedRateTx.payinAddress); const payinAta = getSPLAssociatedTokenAccountPubkey( payin, mint, - tokenProgramId + tokenProgramId, ); const amount = BigInt(quote.options.amount.toString()); debug( @@ -846,7 +846,7 @@ class Changelly extends ProviderClass { ` payinAta=${payinAta.toBase58()}` + ` latestBlockHash=${latestBlockHash.blockhash}` + ` lastValidBlockHeight=${latestBlockHash.lastValidBlockHeight}` + - ` amount=${amount}` + ` amount=${amount}`, ); // If the ATA account doesn't exist we need create it @@ -858,12 +858,12 @@ class Changelly extends ProviderClass { if (payinAtaExists) { debug( "getSwap", - `Payin ATA already exists. No need to create it.` + `Payin ATA already exists. No need to create it.`, ); } else { debug("getSwap", `Payin ATA does not exist. Need to create it.`); const extraRentFee = await conn.getMinimumBalanceForRentExemption( - SPL_TOKEN_ATA_ACCOUNT_SIZE_BYTES + SPL_TOKEN_ATA_ACCOUNT_SIZE_BYTES, ); const instruction = getCreateAssociatedTokenAccountIdempotentInstruction({ @@ -878,7 +878,7 @@ class Changelly extends ProviderClass { instructions.push(instruction); additionalNativeFees = additionalNativeFees.add( - toBN(extraRentFee) + toBN(extraRentFee), ); } @@ -886,7 +886,7 @@ class Changelly extends ProviderClass { const recentFees = await conn.getRecentPrioritizationFees(); // Sort by fee amount ascending so we can get the median recentFees.sort( - (a, b) => a.prioritizationFee - b.prioritizationFee + (a, b) => a.prioritizationFee - b.prioritizationFee, ); const recentFeeCount = recentFees.length; let recentFeeCountWithoutZeroes = 0; @@ -932,7 +932,7 @@ class Changelly extends ProviderClass { ` recentFeeMax=${recentFeeMax}` + ` recentFeeMean=${recentFeeMean}` + ` recentFeeMedian=${recentFeeMedian}` + - ` recentFeeMinAvg=${recentFeeMinAvg}` + ` recentFeeMinAvg=${recentFeeMinAvg}`, ); } else { debug( @@ -946,12 +946,12 @@ class Changelly extends ProviderClass { ` recentFeeMax=${recentFeeMax}` + ` recentFeeMean=${recentFeeMean}` + ` recentFeeMedian=${recentFeeMedian}` + - ` recentFeeMinAvg=${recentFeeMinAvg}` + ` recentFeeMinAvg=${recentFeeMinAvg}`, ); instructions.unshift( ComputeBudgetProgram.setComputeUnitPrice({ microLamports: recentFeeMinAvg, - }) + }), ); } @@ -962,8 +962,8 @@ class Changelly extends ProviderClass { /** owner */ wallet, /** amount */ amount, /** multiSigners */ [], - /** programId */ tokenProgramId - ) + /** programId */ tokenProgramId, + ), ); versionedTx = new VersionedTransaction( @@ -971,7 +971,7 @@ class Changelly extends ProviderClass { payerKey: wallet, recentBlockhash: latestBlockHash.blockhash, instructions, - }).compileToV0Message() + }).compileToV0Message(), ); } @@ -1004,7 +1004,7 @@ class Changelly extends ProviderClass { try { baseToAmount = toBase( changellyFixedRateTx.amountExpectedTo, - quote.options.toToken.decimals + quote.options.toToken.decimals, ); } catch (err) { console.warn( @@ -1012,13 +1012,13 @@ class Changelly extends ProviderClass { ` decimals than the token has, attempting to trim trailing decimals...` + ` amountExpectedTo=${changellyFixedRateTx.amountExpectedTo}` + ` toTokenDecimals=${quote.options.toToken.decimals}` + - ` err=${String(err)}` + ` err=${String(err)}`, ); const original = changellyFixedRateTx.amountExpectedTo; // eslint-disable-next-line no-use-before-define const [success, fixed] = fixBaseAndTrimDecimals( original, - quote.options.toToken.decimals + quote.options.toToken.decimals, ); if (!success) throw err; const rounded = (BigInt(fixed) - BigInt(1)).toString(); @@ -1032,7 +1032,7 @@ class Changelly extends ProviderClass { ` quote.options.toToken.decimals=${quote.options.toToken.decimals}` + ` quote.options.toToken.symbol=${quote.options.toToken.symbol}` + ` quote.options.toToken.name=${quote.options.toToken.name}` + - ` quote.options.toToken.address=${quote.options.toToken.address}` + ` quote.options.toToken.address=${quote.options.toToken.address}`, ); } @@ -1045,7 +1045,7 @@ class Changelly extends ProviderClass { slippage: quote.meta.slippage || DEFAULT_SLIPPAGE, fee, getStatusObject: async ( - options: StatusOptions + options: StatusOptions, ): Promise => ({ options: { ...options, @@ -1057,14 +1057,14 @@ class Changelly extends ProviderClass { debug( "getSwap", `Successfully extracted Changelly swap transaction via "createFixTransaction"` + - ` took=${(Date.now() - startedAt).toLocaleString()}ms` + ` took=${(Date.now() - startedAt).toLocaleString()}ms`, ); return retResponse; } catch (err) { console.warn( `Errored processing Changelly swap response, returning no swap` + ` took=${(Date.now() - startedAt).toLocaleString()}ms` + - ` err=${String(err)}` + ` err=${String(err)}`, ); return null; } @@ -1076,7 +1076,7 @@ class Changelly extends ProviderClass { }; const response = await this.changellyRequest( "getStatus", - params + params, ); if (response.error || !response.result) return TransactionStatus.pending; @@ -1099,7 +1099,7 @@ class Changelly extends ProviderClass { function fixBaseAndTrimDecimals( value: string, - decimals: number + decimals: number, ): [success: boolean, fixed: string] { const original = value; const parts = original.split("."); diff --git a/packages/swap/src/providers/changelly/supported.ts b/packages/swap/src/providers/changelly/supported.ts index 73b2a4f4c..0ff55132d 100644 --- a/packages/swap/src/providers/changelly/supported.ts +++ b/packages/swap/src/providers/changelly/supported.ts @@ -74,7 +74,7 @@ const supportedNetworks: { }; export const supportedNetworksSet = new Set( - Object.keys(supportedNetworks) + Object.keys(supportedNetworks), ) as unknown as Set; export default supportedNetworks; diff --git a/packages/swap/src/providers/jupiter/index.ts b/packages/swap/src/providers/jupiter/index.ts index ed2753b2a..ef92eb65d 100644 --- a/packages/swap/src/providers/jupiter/index.ts +++ b/packages/swap/src/providers/jupiter/index.ts @@ -115,7 +115,7 @@ const JUPITER_API_URL = "https://quote-api.jup.ag/v6/"; * Manages referral fees */ const JUPITER_REFERRAL_VAULT_PUBKEY = new PublicKey( - "45ruCyfdRkWpRNGEqWzjCiXRHkZs8WXCLQ67Pnpye7Hp" + "45ruCyfdRkWpRNGEqWzjCiXRHkZs8WXCLQ67Pnpye7Hp", ); /** @@ -124,7 +124,7 @@ const JUPITER_REFERRAL_VAULT_PUBKEY = new PublicKey( * Program targetted by instructions */ const JUPITER_REFERRAL_PROGRAM_PUBKEY = new PublicKey( - "REFER4ZgmyYx9c6He5XfaTMiGfdLwRnkV4RPp9t9iF3" + "REFER4ZgmyYx9c6He5XfaTMiGfdLwRnkV4RPp9t9iF3", ); /** @@ -155,7 +155,7 @@ if (DEBUG) { now.getMilliseconds().toString().padStart(3, "0"); console.info( `\x1b[90m${ymdhms}\x1b[0m \x1b[32mJupiterSwapProvider.${context}\x1b[0m: ${message}`, - ...args + ...args, ); }; } else { @@ -264,7 +264,7 @@ export class Jupiter extends ProviderClass { private async querySwapInfo( options: getQuoteOptions, meta: QuoteMetaOptions, - context?: { signal?: AbortSignal } + context?: { signal?: AbortSignal }, ): Promise<{ jupiterQuote: JupiterQuoteResponse; jupiterSwap: JupiterSwapResponse; @@ -316,17 +316,17 @@ export class Jupiter extends ProviderClass { const referrerATAPubkey = getJupiterReferrerAssociatedTokenAccount( referrerPubkey, - srcMint + srcMint, ); const referrerATAExists = await solAccountExists( this.conn, - referrerATAPubkey + referrerATAPubkey, ); /** Jupiter API requires an integer for slippage bps so we must round */ const slippageBps = Math.round( - 100 * parseFloat(meta.slippage || DEFAULT_SLIPPAGE) + 100 * parseFloat(meta.slippage || DEFAULT_SLIPPAGE), ); const quote = await getJupiterQuote( @@ -337,14 +337,14 @@ export class Jupiter extends ProviderClass { slippageBps, referralFeeBps: feeBps, }, - { signal } + { signal }, ); const dstTokenProgramId = await getTokenProgramOfMint(this.conn, dstMint); const dstATAPubkey = getSPLAssociatedTokenAccountPubkey( toPubkey, dstMint, - dstTokenProgramId + dstTokenProgramId, ); const swap = await getJupiterSwap( @@ -354,11 +354,11 @@ export class Jupiter extends ProviderClass { referrerATAPubkey, dstATAPubkey, }, - { signal } + { signal }, ); let tx = VersionedTransaction.deserialize( - Buffer.from(swap.swapTransaction, "base64") + Buffer.from(swap.swapTransaction, "base64"), ); const srcTokenProgramId = await getTokenProgramOfMint(this.conn, srcMint); @@ -374,12 +374,12 @@ export class Jupiter extends ProviderClass { "querySwapInfo", `Referrer ATA already exists. No need to record additional rent fees.` + ` ATA pubkey: ${referrerATAPubkey.toBase58()},` + - ` Source mint: ${srcMint.toBase58()}` + ` Source mint: ${srcMint.toBase58()}`, ); } else { // The referral fee ATA account needs to be created or else we can't receive fees for this transaction const extraRentFees = await this.conn.getMinimumBalanceForRentExemption( - JUPITER_REFERRAL_ATA_ACCOUNT_SIZE_BYTES + JUPITER_REFERRAL_ATA_ACCOUNT_SIZE_BYTES, ); // Get the instruction that creates the Jupiter referral ATA account @@ -402,7 +402,7 @@ export class Jupiter extends ProviderClass { `Referrer ATA does not exist. Updating transaction with instruction to create it.` + ` Referral ATA pubkey: ${referrerATAPubkey.toBase58()},` + ` Rent: ${extraRentFees} lamports,` + - ` Total Rent: ${extraRentFees} lamports` + ` Total Rent: ${extraRentFees} lamports`, ); } @@ -414,11 +414,11 @@ export class Jupiter extends ProviderClass { "querySwapInfo", `Wallet destination mint ATA already exists. No need to record additional rent fees.` + ` ATA pubkey: ${dstATAPubkey.toBase58()},` + - ` Destination mint: ${dstMint.toBase58()}` + ` Destination mint: ${dstMint.toBase58()}`, ); } else { const extraRentFee = await this.conn.getMinimumBalanceForRentExemption( - SPL_TOKEN_ATA_ACCOUNT_SIZE_BYTES + SPL_TOKEN_ATA_ACCOUNT_SIZE_BYTES, ); const instruction = getCreateAssociatedTokenAccountIdempotentInstruction({ @@ -441,7 +441,7 @@ export class Jupiter extends ProviderClass { ` ATA pubkey: ${dstATAPubkey.toBase58()},` + ` Destination mint: ${dstMint.toBase58()},` + ` Rent: ${extraRentFee} lamports,` + - ` Total rent: ${rentFees} lamports` + ` Total rent: ${rentFees} lamports`, ); } @@ -449,7 +449,7 @@ export class Jupiter extends ProviderClass { tx = await insertInstructionsAtStartOfTransaction( this.conn, tx, - extraInstructions + extraInstructions, ); } @@ -469,13 +469,13 @@ export class Jupiter extends ProviderClass { async getQuote( options: getQuoteOptions, meta: QuoteMetaOptions, - context?: { signal?: AbortSignal } + context?: { signal?: AbortSignal }, ): Promise { if (options.toToken.networkInfo.name !== SupportedNetworkName.Solana) { debug( "getQuote", `ignoring quote request to network ${options.toToken.networkInfo.name},` + - ` cross network swaps not supported` + ` cross network swaps not supported`, ); return null; } @@ -491,11 +491,11 @@ export class Jupiter extends ProviderClass { debug( "getQuote", - `Quote inAmount: ${jupiterQuote.inAmount} ${options.fromToken.symbol}` + `Quote inAmount: ${jupiterQuote.inAmount} ${options.fromToken.symbol}`, ); debug( "getQuote", - `Quote outAmount: ${jupiterQuote.outAmount} ${options.toToken.symbol}` + `Quote outAmount: ${jupiterQuote.outAmount} ${options.toToken.symbol}`, ); const result: ProviderQuoteResponse = { @@ -503,7 +503,7 @@ export class Jupiter extends ProviderClass { toTokenAmount: toBN( Math.floor((1 - feePercentage) * Number(jupiterQuote.outAmount)) .toFixed(10) - .replace(/\.?0+$/, "") + .replace(/\.?0+$/, ""), ), totalGaslimit: computeBudget, additionalNativeFees: toBN(rentFees), @@ -527,7 +527,7 @@ export class Jupiter extends ProviderClass { async getSwap( quote: SwapQuote, - context?: { signal?: AbortSignal } + context?: { signal?: AbortSignal }, ): Promise { const { feePercentage, jupiterQuote, base64SwapTransaction, rentFees } = await this.querySwapInfo(quote.options, quote.meta, context); @@ -543,11 +543,11 @@ export class Jupiter extends ProviderClass { debug( "getSwap", - `Quote inAmount: ${jupiterQuote.inAmount} ${quote.options.fromToken.symbol}` + `Quote inAmount: ${jupiterQuote.inAmount} ${quote.options.fromToken.symbol}`, ); debug( "getSwap", - `Quote outAmount: ${jupiterQuote.outAmount} ${quote.options.toToken.symbol}` + `Quote outAmount: ${jupiterQuote.outAmount} ${quote.options.toToken.symbol}`, ); const result: ProviderSwapResponse = { @@ -556,14 +556,14 @@ export class Jupiter extends ProviderClass { toTokenAmount: toBN( Math.floor((1 - feePercentage) * Number(jupiterQuote.outAmount)) .toFixed(10) - .replace(/\.?0+$/, "") + .replace(/\.?0+$/, ""), ), additionalNativeFees: toBN(rentFees), provider: this.name, slippage: quote.meta.slippage, fee: feePercentage, getStatusObject: async ( - options: StatusOptions + options: StatusOptions, ): Promise => ({ options, provider: this.name, @@ -576,7 +576,7 @@ export class Jupiter extends ProviderClass { async getStatus(options: StatusOptions): Promise { if (options.transactionHashes.length !== 1) { throw new TypeError( - `JupiterSwap.getStatus: Expected one transaction hash but got ${options.transactionHashes.length}` + `JupiterSwap.getStatus: Expected one transaction hash but got ${options.transactionHashes.length}`, ); } const [txhash] = options.transactionHashes; @@ -630,8 +630,8 @@ async function getJupiterTokens(abortable?: { // Failed after too many attempts throw new Error( `Failed to get Jupiter tokens after ${backoffi} retries: ${String( - errRef?.err ?? "???" - )}` + errRef?.err ?? "???", + )}`, ); } @@ -667,7 +667,7 @@ async function getJupiterTokens(abortable?: { try { debug( "getJupiterTokens", - `Initiating HTTP request for Jupiter tokens ${url}` + `Initiating HTTP request for Jupiter tokens ${url}`, ); const res = await fetch(url, { signal: aborter.signal, @@ -679,7 +679,7 @@ async function getJupiterTokens(abortable?: { let msg = await res .text() .catch( - (err: Error) => `Failed to decode response text: ${String(err)}` + (err: Error) => `Failed to decode response text: ${String(err)}`, ); const msglen = msg.length; if (msglen > 512 + 7 + 3 + msglen.toString().length) { @@ -700,14 +700,14 @@ async function getJupiterTokens(abortable?: { throw new Error( `Failed to get Jupiter tokens, HTTP response returned not-ok status ${ res.status - } ${res.statusText || ""}: ${msg}` + } ${res.statusText || ""}: ${msg}`, ); } tokens = (await res.json()) as JupiterTokenInfo[]; if (!tokens) { throw new Error( - "Failed to get Jupiter tokens: something went wrong and result is falsy" + "Failed to get Jupiter tokens: something went wrong and result is falsy", ); } @@ -719,7 +719,7 @@ async function getJupiterTokens(abortable?: { "getJupiterTokens", `Failed to get Jupiter tokens on attempt ${backoffi + 1}/${ backoff.length - }: ${String(err)}` + }: ${String(err)}`, ); errRef ??= { err: err as Error }; } finally { @@ -751,14 +751,14 @@ async function getJupiterQuote( }, abortable?: { signal?: AbortSignal; - } + }, ): Promise { const { srcMint, dstMint, amount, slippageBps, referralFeeBps } = params; if (slippageBps != null) { if (!Number.isSafeInteger(slippageBps)) { throw new TypeError( - `Invalid slippageBps: ${slippageBps} must be a safe integer` + `Invalid slippageBps: ${slippageBps} must be a safe integer`, ); } if (slippageBps < 0) { @@ -769,12 +769,12 @@ async function getJupiterQuote( if (referralFeeBps != null) { if (!Number.isSafeInteger(referralFeeBps)) { throw new TypeError( - `Invalid referralFeeBps: ${referralFeeBps} must be a safe integer` + `Invalid referralFeeBps: ${referralFeeBps} must be a safe integer`, ); } if (referralFeeBps < 0) { throw new TypeError( - `Invalid referralFeeBps: ${referralFeeBps} must be >= 0` + `Invalid referralFeeBps: ${referralFeeBps} must be >= 0`, ); } } @@ -806,8 +806,8 @@ async function getJupiterQuote( // Failed after too many attempts throw new Error( `Failed to get Jupiter quote after ${backoffi} retries at url ${url}: ${String( - errRef?.err ?? "???" - )}` + errRef?.err ?? "???", + )}`, ); } @@ -815,7 +815,7 @@ async function getJupiterQuote( // Previous request failed, wait before retrying debug( "getJupiterQuote", - `Retrying ${url} after ${backoff[backoffi]}ms...` + `Retrying ${url} after ${backoff[backoffi]}ms...`, ); await sleep(backoff[backoffi], abortable); } @@ -846,7 +846,7 @@ async function getJupiterQuote( try { debug( "getJupiterQuote", - `Initiating HTTP request for Jupiter quote ${url}` + `Initiating HTTP request for Jupiter quote ${url}`, ); const res = await fetch(url, { signal: aborter.signal, @@ -858,7 +858,7 @@ async function getJupiterQuote( let msg = await res .text() .catch( - (err: Error) => `Failed to decode response text: ${String(err)}` + (err: Error) => `Failed to decode response text: ${String(err)}`, ); const msglen = msg.length; if (msglen > 512 + 7 + 3 + msglen.toString().length) { @@ -879,14 +879,14 @@ async function getJupiterQuote( throw new Error( `Failed to get Jupiter quote, HTTP response returned not-ok status ${ res.status - } ${res.statusText || ""} at url ${url}: ${msg}` + } ${res.statusText || ""} at url ${url}: ${msg}`, ); } quote = (await res.json()) as JupiterQuoteResponse; if (!quote) { throw new Error( - `Failed to get Jupiter quote at url ${url}, something went wrong and result is falsy` + `Failed to get Jupiter quote at url ${url}, something went wrong and result is falsy`, ); } @@ -897,7 +897,7 @@ async function getJupiterQuote( console.warn( `[getJupiterQuote] Failed to get Jupiter quote on attempt ${ backoffi + 1 - }/${backoff.length}: ${String(err)}` + }/${backoff.length}: ${String(err)}`, ); errRef ??= { err: err as Error }; } finally { @@ -927,7 +927,7 @@ async function getJupiterSwap( }, abortable?: { signal?: AbortSignal; - } + }, ): Promise { const { signerPubkey, dstATAPubkey, quote, referrerATAPubkey } = params; @@ -952,8 +952,8 @@ async function getJupiterSwap( // Failed after too many attempts throw new Error( `Failed to get Jupiter swap after ${backoffi} retries at url ${url}: ${String( - errRef?.err ?? "???" - )}` + errRef?.err ?? "???", + )}`, ); } @@ -961,7 +961,7 @@ async function getJupiterSwap( // Previous request failed, wait before retrying debug( "getJupiterSwap", - `Retrying ${url} after ${backoff[backoffi]}ms...` + `Retrying ${url} after ${backoff[backoffi]}ms...`, ); await sleep(backoff[backoffi], abortable); } @@ -992,7 +992,7 @@ async function getJupiterSwap( try { debug( "getJupiterSwap", - `Initiating HTTP request for Jupiter swap ${url}` + `Initiating HTTP request for Jupiter swap ${url}`, ); const res = await fetch(url, { signal: aborter.signal, @@ -1009,7 +1009,7 @@ async function getJupiterSwap( let msg = await res .text() .catch( - (err: Error) => `Failed to decode response text: ${String(err)}` + (err: Error) => `Failed to decode response text: ${String(err)}`, ); const msglen = msg.length; if (msglen > 512 + 7 + 3 + msglen.toString().length) { @@ -1030,7 +1030,7 @@ async function getJupiterSwap( throw new Error( `Failed to get Jupiter swap, HTTP response returned not-ok status ${ res.status - } ${res.statusText || ""} at url ${url}: ${msg}` + } ${res.statusText || ""} at url ${url}: ${msg}`, ); } @@ -1038,7 +1038,7 @@ async function getJupiterSwap( if (!quote) { throw new Error( - `Failed to get Jupiter swap at url ${url}, something went wrong and result is falsy` + `Failed to get Jupiter swap at url ${url}, something went wrong and result is falsy`, ); } @@ -1049,7 +1049,7 @@ async function getJupiterSwap( "getJupiterSwap", `Failed to get Jupiter swap on attempt ${backoffi + 1}/${ backoff.length - }: ${String(err)}` + }: ${String(err)}`, ); errRef ??= { err: err as Error }; } finally { @@ -1072,7 +1072,7 @@ async function getJupiterSwap( */ function getJupiterReferrerAssociatedTokenAccount( referrerPubkey: PublicKey, - mintPubkey: PublicKey + mintPubkey: PublicKey, ): PublicKey { /** `feeAccount` section of https://station.jup.ag/api-v6/post-swap */ const referrerAccountSeeds = [ @@ -1083,7 +1083,7 @@ function getJupiterReferrerAssociatedTokenAccount( ]; const [referrerATAPubkey] = PublicKey.findProgramAddressSync( referrerAccountSeeds, - JUPITER_REFERRAL_PROGRAM_PUBKEY + JUPITER_REFERRAL_PROGRAM_PUBKEY, ); return referrerATAPubkey; } @@ -1179,7 +1179,7 @@ function getJupiterInitialiseReferralTokenAccountInstruction(params: { function sleep( duration: number, - abortable?: { signal?: AbortSignal } + abortable?: { signal?: AbortSignal }, ): Promise { if (abortable.signal.aborted) return Promise.reject(abortable.signal.reason); if (duration <= 0) return Promise.resolve(); diff --git a/packages/swap/src/providers/oneInch/index.ts b/packages/swap/src/providers/oneInch/index.ts index 231ce0ca9..d5b931219 100644 --- a/packages/swap/src/providers/oneInch/index.ts +++ b/packages/swap/src/providers/oneInch/index.ts @@ -131,7 +131,7 @@ class OneInch extends ProviderClass { static isSupported(network: SupportedNetworkName) { return Object.keys(supportedNetworks).includes( - network as unknown as string + network as unknown as string, ); } @@ -155,11 +155,11 @@ class OneInch extends ProviderClass { private getOneInchSwap( options: getQuoteOptions, meta: QuoteMetaOptions, - accurateEstimate: boolean + accurateEstimate: boolean, ): Promise { if ( !OneInch.isSupported( - options.toToken.networkInfo.name as SupportedNetworkName + options.toToken.networkInfo.name as SupportedNetworkName, ) || this.network !== options.toToken.networkInfo.name ) @@ -179,7 +179,7 @@ class OneInch extends ProviderClass { return fetch( `${BASE_URL}${ supportedNetworks[this.network].chainId - }/swap?${params.toString()}` + }/swap?${params.toString()}`, ) .then((res) => res.json()) .then(async (response: OneInchResponseType) => { @@ -222,7 +222,7 @@ class OneInch extends ProviderClass { if (accurateEstimate) { const accurateGasEstimate = await estimateEVMGasList( transactions, - this.network + this.network, ); if (accurateGasEstimate) { if (accurateGasEstimate.isError) return null; @@ -245,7 +245,7 @@ class OneInch extends ProviderClass { getQuote( options: getQuoteOptions, - meta: QuoteMetaOptions + meta: QuoteMetaOptions, ): Promise { return this.getOneInchSwap(options, meta, false).then(async (res) => { if (!res) return null; @@ -262,7 +262,7 @@ class OneInch extends ProviderClass { totalGaslimit: res.transactions.reduce( (total: number, curVal: EVMTransaction) => total + toBN(curVal.gasLimit).toNumber(), - 0 + 0, ), minMax: await this.getMinMaxAmount(), }; @@ -284,7 +284,7 @@ class OneInch extends ProviderClass { slippage: quote.meta.slippage || DEFAULT_SLIPPAGE, fee: feeConfig * 100, getStatusObject: async ( - options: StatusOptions + options: StatusOptions, ): Promise => ({ options, provider: this.name, @@ -296,7 +296,7 @@ class OneInch extends ProviderClass { getStatus(options: StatusOptions): Promise { const promises = options.transactionHashes.map((hash) => - this.web3eth.getTransactionReceipt(hash) + this.web3eth.getTransactionReceipt(hash), ); return Promise.all(promises).then((receipts) => { // eslint-disable-next-line no-restricted-syntax diff --git a/packages/swap/src/providers/paraswap/index.ts b/packages/swap/src/providers/paraswap/index.ts index a1170502b..956b2cc19 100644 --- a/packages/swap/src/providers/paraswap/index.ts +++ b/packages/swap/src/providers/paraswap/index.ts @@ -120,7 +120,7 @@ class ParaSwap extends ProviderClass { static isSupported(network: SupportedNetworkName) { return Object.keys(supportedNetworks).includes( - network as unknown as string + network as unknown as string, ); } @@ -144,11 +144,11 @@ class ParaSwap extends ProviderClass { private getParaswapSwap( options: getQuoteOptions, meta: QuoteMetaOptions, - accurateEstimate: boolean + accurateEstimate: boolean, ): Promise { if ( !ParaSwap.isSupported( - options.toToken.networkInfo.name as SupportedNetworkName + options.toToken.networkInfo.name as SupportedNetworkName, ) || this.network !== options.toToken.networkInfo.name ) @@ -173,7 +173,7 @@ class ParaSwap extends ProviderClass { ( parseFloat(meta.slippage ? meta.slippage : DEFAULT_SLIPPAGE) * 10 ).toString(), - 10 + 10, ).toString(), deadline: Math.floor(Date.now() / 1000) + 300, partnerAddress: feeConfig ? feeConfig.referrer : "", @@ -193,7 +193,7 @@ class ParaSwap extends ProviderClass { "Content-Type": "application/json", }, body, - } + }, ) .then((res) => res.json()) .then(async (response: ParaswapResponseType) => { @@ -225,7 +225,7 @@ class ParaSwap extends ProviderClass { if (accurateEstimate) { const accurateGasEstimate = await estimateEVMGasList( transactions, - this.network + this.network, ); if (accurateGasEstimate) { if (accurateGasEstimate.isError) return null; @@ -237,10 +237,10 @@ class ParaSwap extends ProviderClass { return { transactions, toTokenAmount: toBN( - (meta.priceRoute as ParaswpQuoteResponse).destAmount + (meta.priceRoute as ParaswpQuoteResponse).destAmount, ), fromTokenAmount: toBN( - (meta.priceRoute as ParaswpQuoteResponse).srcAmount + (meta.priceRoute as ParaswpQuoteResponse).srcAmount, ), }; }) @@ -252,11 +252,11 @@ class ParaSwap extends ProviderClass { getQuote( options: getQuoteOptions, - meta: QuoteMetaOptions + meta: QuoteMetaOptions, ): Promise { if ( !ParaSwap.isSupported( - options.toToken.networkInfo.name as SupportedNetworkName + options.toToken.networkInfo.name as SupportedNetworkName, ) || this.network !== options.toToken.networkInfo.name ) @@ -313,7 +313,7 @@ class ParaSwap extends ProviderClass { transactions.reduce( (total: number, curVal: EVMTransaction) => total + toBN(curVal.gasLimit).toNumber(), - 0 + 0, ) + toBN(GAS_LIMITS.swap).toNumber(), minMax: await this.getMinMaxAmount(), }; @@ -339,7 +339,7 @@ class ParaSwap extends ProviderClass { slippage: quote.meta.slippage || DEFAULT_SLIPPAGE, fee: feeConfig * 100, getStatusObject: async ( - options: StatusOptions + options: StatusOptions, ): Promise => ({ options, provider: this.name, @@ -351,7 +351,7 @@ class ParaSwap extends ProviderClass { getStatus(options: StatusOptions): Promise { const promises = options.transactionHashes.map((hash) => - this.web3eth.getTransactionReceipt(hash) + this.web3eth.getTransactionReceipt(hash), ); return Promise.all(promises).then((receipts) => { // eslint-disable-next-line no-restricted-syntax diff --git a/packages/swap/src/providers/rango/index.ts b/packages/swap/src/providers/rango/index.ts index 3218d963e..f750043ad 100644 --- a/packages/swap/src/providers/rango/index.ts +++ b/packages/swap/src/providers/rango/index.ts @@ -96,7 +96,7 @@ if (DEBUG) { now.getMilliseconds().toString().padStart(3, "0"); console.info( `\x1b[90m${ymdhms}\x1b[0m \x1b[32mRangoSwapProvider.${context}\x1b[0m: ${message}`, - ...args + ...args, ); }; } else { @@ -261,7 +261,7 @@ Object.freeze(supportedNetworks); /** Enkrypt supported network name -> network info */ const supportedNetworkInfoByName = new Map( - Object.entries(supportedNetworks) + Object.entries(supportedNetworks), ) as unknown as Map; /** Rango blockchain name -> network info & enkrypt network name */ @@ -275,7 +275,7 @@ const supportedNetworkByRangoBlockchain = new Map< info: networkInfo, name: supportedNetwork as unknown as SupportedNetworkName, }, - ]) + ]), ); type RangoEnkryptToken = { @@ -404,7 +404,7 @@ class Rango extends ProviderClass { "init", "Rango meta" + ` tokens.length=${rangoMeta.tokens.length}` + - ` blockchains.length=${rangoMeta.blockchains.length}` + ` blockchains.length=${rangoMeta.blockchains.length}`, ); const supportedNetworkInfo = supportedNetworkInfoByName.get(this.network); @@ -442,14 +442,14 @@ class Rango extends ProviderClass { static findRangoBlockchainForSupportedNetwork( supportedNetworkInfo: SupportedNetworkInfo, - rangoBlockchains: ReadonlyArray + rangoBlockchains: ReadonlyArray, ): undefined | BlockchainMeta { const matchingRangoBlockchain = rangoBlockchains.find( (rangoBlockchain: BlockchainMeta) => rangoChainIdsEq( rangoBlockchain.chainId, - supportedNetworkInfo.rangoChainId - ) + supportedNetworkInfo.rangoChainId, + ), ); return matchingRangoBlockchain; @@ -460,7 +460,7 @@ class Rango extends ProviderClass { */ static isNetworkSupported( supportedNetworkName: SupportedNetworkName, - rangoBlockchains: ReadonlyArray + rangoBlockchains: ReadonlyArray, ): boolean { const supportedNetworkInfo = supportedNetworkInfoByName.get(supportedNetworkName); @@ -472,7 +472,7 @@ class Rango extends ProviderClass { return this.isNetworkSupportedByRango( supportedNetworkInfo, - rangoBlockchains + rangoBlockchains, ); } @@ -481,7 +481,7 @@ class Rango extends ProviderClass { */ static isNetworkSupportedByRango( supportedNetworkInfo: SupportedNetworkInfo, - rangoBlockchains: ReadonlyArray + rangoBlockchains: ReadonlyArray, ): boolean { if (!rangoBlockchains.length) { // Rango didn't give us anything so just assume Rango supports this network @@ -494,7 +494,7 @@ class Rango extends ProviderClass { // Find the rango blockchain that corresponds to this enkrypt network, if exists const matchingRangoBlockchain = this.findRangoBlockchainForSupportedNetwork( supportedNetworkInfo, - rangoBlockchains + rangoBlockchains, ); // Supported if @@ -513,7 +513,7 @@ class Rango extends ProviderClass { for (let i = 0, len = tokens.length; i < len; i++) { const token = tokens[i]; const supportedNetwork = supportedNetworkByRangoBlockchain.get( - token.blockchain + token.blockchain, ); // Unrecognised network (Rango supports it but we don't) @@ -566,14 +566,14 @@ class Rango extends ProviderClass { */ private getRangoTokenSymbol( token: TokenType, - rangoBlockchain: BlockchainMeta + rangoBlockchain: BlockchainMeta, ): string | undefined { const { tokensByBlockchainAddress } = this.rangoMeta; if (this.isNativeToken(token.address)) return token.symbol; if (token.address == null) { console.warn( `Cannot get Rango token symbol: Token address is not defined` + - ` for token ${token.name} (${token.symbol}) - ${token.address}` + ` for token ${token.name} (${token.symbol}) - ${token.address}`, ); return undefined; } @@ -599,7 +599,7 @@ class Rango extends ProviderClass { options: getQuoteOptions, meta: QuoteMetaOptions, accurateEstimate: boolean, - abortable?: { signal?: AbortSignal } + abortable?: { signal?: AbortSignal }, ): Promise { const { blockchains } = this.rangoMeta; const startedAt = Date.now(); @@ -612,7 +612,7 @@ class Rango extends ProviderClass { ` fromToken=${options.fromToken.symbol}` + ` toToken=${options.toToken.symbol}` + ` fromAddress=${options.fromAddress}` + - ` toAddress=${options.toAddress}` + ` toAddress=${options.toAddress}`, ); try { @@ -627,27 +627,27 @@ class Rango extends ProviderClass { "getRangoSwap", "No swap:" + ` Enkrypt does not support Rango swap on the source network` + - ` fromNetwork=${this.network}` + ` fromNetwork=${this.network}`, ); } // We must support Rango on the destination network const toNetworkInfo = supportedNetworkInfoByName.get( - options.toToken.networkInfo.name as SupportedNetworkName + options.toToken.networkInfo.name as SupportedNetworkName, ); if (!toNetworkInfo) { debug( "getRangoSwap", "No swap:" + ` Enkrypt does not support Rango swap on the destination network` + - ` fromNetwork=${this.network}` + ` fromNetwork=${this.network}`, ); } // Rango must support the source network const fromRangoBlockchain = Rango.findRangoBlockchainForSupportedNetwork( fromNetworkInfo, - blockchains + blockchains, ); if (!fromRangoBlockchain?.enabled) { debug( @@ -656,7 +656,7 @@ class Rango extends ProviderClass { ` Rango does not support swap on the source network` + ` fromNetwork=${this.network}` + ` fromBlockchain=${fromRangoBlockchain.name}` + - ` enabled=${fromRangoBlockchain.enabled}` + ` enabled=${fromRangoBlockchain.enabled}`, ); return null; } @@ -665,7 +665,7 @@ class Rango extends ProviderClass { // Rango must support the destination network const toRangoBlockchain = Rango.findRangoBlockchainForSupportedNetwork( toNetworkInfo, - blockchains + blockchains, ); if (!toRangoBlockchain?.enabled) { debug( @@ -674,7 +674,7 @@ class Rango extends ProviderClass { ` Rango does not support swap on the destination network` + ` toNetwork=${options.toToken.networkInfo.name}` + ` toBlockchain=${toRangoBlockchain.name}` + - ` enabled=${toRangoBlockchain.enabled}` + ` enabled=${toRangoBlockchain.enabled}`, ); return null; } @@ -687,7 +687,7 @@ class Rango extends ProviderClass { "getRangoSwap", `Rango block chains ids` + ` fromRangoBlockchain=${fromRangoBlockchainName}` + - ` toRangoBlockchain=${toRangoBlockchainName}` + ` toRangoBlockchain=${toRangoBlockchainName}`, ); const fromTokenAddress = options.fromToken.address; @@ -696,13 +696,13 @@ class Rango extends ProviderClass { /** Source token symbol */ const fromRangoTokenSymbol = this.getRangoTokenSymbol( options.fromToken, - fromRangoBlockchain + fromRangoBlockchain, ); /** Destination token symbol */ const toRangoTokenSymbol = this.getRangoTokenSymbol( options.toToken, - toRangoBlockchain + toRangoBlockchain, ); // If we can't get symbols for the tokens then we don't support them @@ -711,7 +711,7 @@ class Rango extends ProviderClass { "getRangoSwap", `No swap: No symbol for src token or dst token` + ` fromTokenSymbol=${fromRangoTokenSymbol}` + - ` toTokenSymbol=${toRangoTokenSymbol}` + ` toTokenSymbol=${toRangoTokenSymbol}`, ); return null; } @@ -757,7 +757,7 @@ class Rango extends ProviderClass { ` toAddress=${options.toAddress}` + ` amount=${options.amount.toString()}` + ` slippage=${slippage}` + - ` referrerFee=${params.referrerFee}` + ` referrerFee=${params.referrerFee}`, ); const rangoSwapResponse = await rangoClient.swap(params, abortable); debug("getRangoSwap", `Received quote from rango sdk`); @@ -792,7 +792,7 @@ class Rango extends ProviderClass { debug( "getRangoSwap", - `Additional non-network source fees ${additionalNativeFees.toString()}` + `Additional non-network source fees ${additionalNativeFees.toString()}`, ); // Fill in gas values, add approval transactions, etc @@ -832,7 +832,7 @@ class Rango extends ProviderClass { // Get accurate gas limits for each transactions const accurateGasEstimate = await estimateEVMGasList( transactions, - this.network + this.network, ); if (accurateGasEstimate) { @@ -863,32 +863,32 @@ class Rango extends ProviderClass { if (rangoSwapResponse.tx.serializedMessage) { debug( "getRangoSwap", - `Deserializing Solana legacy unsigned transaction` + `Deserializing Solana legacy unsigned transaction`, ); // Legacy transaction, not signed (we can modify it) // > When serialized message appears, there is no need for other fields and you just sign and send it // @see (2024-09-17) https://docs.rango.exchange/api-integration/main-api-multi-step/sample-transactions#solana-sample-transaction-test legacyTx = SolanaLegacyTransaction.from( - rangoSwapResponse.tx.serializedMessage + rangoSwapResponse.tx.serializedMessage, ); } else { debug( "getRangoSwap", - `Constructing Solana legacy signed transaction` + `Constructing Solana legacy signed transaction`, ); // Legacy transaction signed by Rango, we cannot alter this transaction // Since the recent block hash gets signed too, this transaction will need to be consumed quickly const msg = extractTransactionMessageFromSignedRangoTransaction( - rangoSwapResponse.tx + rangoSwapResponse.tx, ); legacyTx = SolanaLegacyTransaction.populate( - msg.compileToLegacyMessage() + msg.compileToLegacyMessage(), ); } debug( "getRangoSwap", - "Extracting third party Rango signatures..." + "Extracting third party Rango signatures...", ); const thirdPartySignatures = extractSignaturesFromRangoTransaction(rangoSwapResponse.tx); @@ -897,7 +897,7 @@ class Rango extends ProviderClass { debug("getRangoSwap", "Checking Rango signatures..."); const signaturesAreValid = checkSolanaLegacyTransactionSignatures( legacyTx, - thirdPartySignatures + thirdPartySignatures, ); if (!signaturesAreValid) { let warnMsg = `Rango Solana signed legacy transaction has invalid Rango signatures,`; @@ -910,7 +910,7 @@ class Rango extends ProviderClass { const sig = thirdPartySignatures[tpsigi]; warnMsg += ` sig[${tpsigi}].pubkey=${sig.pubkey}`; warnMsg += ` sig[${tpsigi}].signature=0x${Buffer.from( - sig.signature + sig.signature, ).toString("hex")}`; } warnMsg += ` fromRangoBlockchain=${fromRangoBlockchainName}`; @@ -934,7 +934,7 @@ class Rango extends ProviderClass { conn, legacyTx, thirdPartySignatures.length > 0, - abortable + abortable, ); if (!statusResult.succeeds) { let warnMsg = `Failed to simulate Rango Solana`; @@ -974,33 +974,33 @@ class Rango extends ProviderClass { if (rangoSwapResponse.tx.serializedMessage) { debug( "getRangoSwap", - `Deserializing Solana versioned unsigned transaction` + `Deserializing Solana versioned unsigned transaction`, ); // Versioned transaction, not signed (we can modify it) // > When serialized message appears, there is no need for other fields and you just sign and send it // @see (2024-09-17) https://docs.rango.exchange/api-integration/main-api-multi-step/sample-transactions#solana-sample-transaction-test const bytes = new Uint8Array( - rangoSwapResponse.tx.serializedMessage + rangoSwapResponse.tx.serializedMessage, ); versionedTx = VersionedTransaction.deserialize(bytes); } else { debug( "getRangoSwap", - `Constructing Solana versioned signed transaction` + `Constructing Solana versioned signed transaction`, ); // Versioned transaction signed by Rango, we cannot alter this transaction // Since the recent block hash gets signed too, this transaction will need to be consumed quickly const msg = extractTransactionMessageFromSignedRangoTransaction( - rangoSwapResponse.tx + rangoSwapResponse.tx, ); versionedTx = new VersionedTransaction( - msg.compileToV0Message() + msg.compileToV0Message(), ); } debug( "getRangoSwap", - "Extracting third party Rango signatures..." + "Extracting third party Rango signatures...", ); const thirdPartySignatures = extractSignaturesFromRangoTransaction(rangoSwapResponse.tx); @@ -1012,12 +1012,12 @@ class Rango extends ProviderClass { ` signatures=${thirdPartySignatures.length}`, ` pubkeys=${thirdPartySignatures .map(({ pubkey }) => pubkey) - .join(",")}` + .join(",")}`, ); const signaturesAreValid = checkSolanaVersionedTransactionSignatures( versionedTx, - thirdPartySignatures + thirdPartySignatures, ); if (!signaturesAreValid) { let warnMsg = `Rango Solana signed versioned transaction has invalid Rango signatures,`; @@ -1030,7 +1030,7 @@ class Rango extends ProviderClass { const sig = thirdPartySignatures[tpsigi]; warnMsg += ` sig[${tpsigi}].pubkey=${sig.pubkey}`; warnMsg += ` sig[${tpsigi}].signature=0x${Buffer.from( - sig.signature + sig.signature, ).toString("hex")}`; } warnMsg += ` fromRangoBlockchain=${fromRangoBlockchainName}`; @@ -1054,7 +1054,7 @@ class Rango extends ProviderClass { conn, versionedTx, thirdPartySignatures.length > 0, - abortable + abortable, ); if (!statusResult.succeeds) { let warnMsg = `Failed to simulate Rango Solana`; @@ -1083,7 +1083,7 @@ class Rango extends ProviderClass { to: options.toToken.address, kind: "versioned", serialized: Buffer.from(versionedTx.serialize()).toString( - "base64" + "base64", ), thirdPartySignatures, }; @@ -1092,7 +1092,7 @@ class Rango extends ProviderClass { default: rangoSwapResponse.tx.txType satisfies never; throw new Error( - `Unhandled Rango Solana transaction type: ${rangoSwapResponse.tx.txType}` + `Unhandled Rango Solana transaction type: ${rangoSwapResponse.tx.txType}`, ); } @@ -1110,7 +1110,7 @@ class Rango extends ProviderClass { default: { throw new Error( - `Unhandled Rango transaction type: ${rangoSwapResponse.tx.type}` + `Unhandled Rango transaction type: ${rangoSwapResponse.tx.type}`, ); } } @@ -1125,7 +1125,7 @@ class Rango extends ProviderClass { debug( "getRangoSwap", - `Done took=${(Date.now() - startedAt).toLocaleString()}ms` + `Done took=${(Date.now() - startedAt).toLocaleString()}ms`, ); return result; @@ -1133,7 +1133,7 @@ class Rango extends ProviderClass { if (!abortable?.signal?.aborted) { console.error( `Error getting Rango swap, returning empty response (no swap)`, - err + err, ); } return null; @@ -1143,7 +1143,7 @@ class Rango extends ProviderClass { async getQuote( options: getQuoteOptions, meta: QuoteMetaOptions, - abortable?: { signal: AbortSignal } + abortable?: { signal: AbortSignal }, ): Promise { const res = await this.getRangoSwap(options, meta, false, abortable); if (!res) return null; @@ -1154,7 +1154,7 @@ class Rango extends ProviderClass { totalGaslimit = res.networkTransactions.transactions.reduce( (total: number, curVal: EVMTransaction) => total + toBN(curVal.gasLimit).toNumber(), - 0 + 0, ); break; } @@ -1167,8 +1167,8 @@ class Rango extends ProviderClass { const tx = res.networkTransactions.transactions[i]; totalGaslimit += extractComputeBudget( VersionedTransaction.deserialize( - Buffer.from(tx.serialized, "base64") - ) + Buffer.from(tx.serialized, "base64"), + ), ); } break; @@ -1199,13 +1199,13 @@ class Rango extends ProviderClass { async getSwap( quote: SwapQuote, - abortable?: { signal: AbortSignal } + abortable?: { signal: AbortSignal }, ): Promise { const res = await this.getRangoSwap( quote.options, quote.meta, true, - abortable + abortable, ); if (!res) return null; const feeConfig = @@ -1219,7 +1219,7 @@ class Rango extends ProviderClass { slippage: quote.meta.slippage || DEFAULT_SLIPPAGE, fee: feeConfig * 100, getStatusObject: async ( - options: StatusOptions + options: StatusOptions, ): Promise => ({ options: { ...options, @@ -1244,7 +1244,7 @@ class Rango extends ProviderClass { RangoTransactionStatus.FAILED, RangoTransactionStatus.SUCCESS, ].includes( - this.transactionsStatus.find((t) => t.hash === transactionHash)?.status + this.transactionsStatus.find((t) => t.hash === transactionHash)?.status, ); if (requestId && !isAlreadySuccessOrFailed) { @@ -1294,8 +1294,8 @@ class Rango extends ProviderClass { // Get status of EVM transactions const receipts = await Promise.all( transactionHashes.map((hash) => - (this.web3 as Web3Eth).getTransactionReceipt(hash) - ) + (this.web3 as Web3Eth).getTransactionReceipt(hash), + ), ); for (let i = 0, len = receipts.length; i < len; i++) { @@ -1340,7 +1340,7 @@ async function isSolanaAddressAsync(address: string): Promise { } function getIsAddressAsync( - network: SupportedNetworkName + network: SupportedNetworkName, ): (address: string) => Promise { switch (network) { case SupportedNetworkName.Solana: @@ -1352,7 +1352,7 @@ function getIsAddressAsync( function sleep( duration: number, - abortable?: { signal?: AbortSignal } + abortable?: { signal?: AbortSignal }, ): Promise { if (abortable?.signal?.aborted) return Promise.reject(abortable.signal.reason); @@ -1387,7 +1387,7 @@ async function fetchRangoSwaplist(abortable?: { if (retryidx >= retries.length) { throw new Error( `Failed to fetch Rango swaplists after ${retries.length}` + - ` retries: ${String(errref?.err ?? "???")}` + ` retries: ${String(errref?.err ?? "???")}`, ); } const waitMs = retries[retryidx]; @@ -1423,13 +1423,13 @@ async function fetchRangoSwaplist(abortable?: { let msg = await res .text() .catch( - (err: Error) => `! Failed to decode response text: ${String(err)}` + (err: Error) => `! Failed to decode response text: ${String(err)}`, ); const len = msg.length; if (len > 512 + 10 + len.toString().length) msg = `${msg.slice(0, 512)}... (512/${len})`; throw new Error( - `Failed to fetch Rango swaplists with ${res.status} ${res.statusText} ${url} ${msg}` + `Failed to fetch Rango swaplists with ${res.status} ${res.statusText} ${url} ${msg}`, ); } const json = await res.json(); @@ -1452,7 +1452,7 @@ async function fetchRangoSwaplist(abortable?: { } function extractSignaturesFromRangoTransaction( - rangoSolanaTx: RangoSolanaTransaction + rangoSolanaTx: RangoSolanaTransaction, ): { /** Base58 public key */ pubkey: string; @@ -1485,7 +1485,7 @@ function extractSignaturesFromRangoTransaction( } function extractTransactionMessageFromSignedRangoTransaction( - rangoSolanaTx: RangoSolanaTransaction + rangoSolanaTx: RangoSolanaTransaction, ): TransactionMessage { // Extract instructions const apiInstructions = rangoSolanaTx.instructions; @@ -1529,7 +1529,7 @@ function checkSolanaLegacyTransactionSignatures( pubkey: string; /** Uint8 byte array */ signature: number[]; - }[] + }[], ): boolean { if (thirdPartySignatures.length === 0) return true; @@ -1541,7 +1541,7 @@ function checkSolanaLegacyTransactionSignatures( const sig = thirdPartySignatures[tpsigi]; clonedTx.addSignature( new PublicKey(sig.pubkey), - Buffer.from(sig.signature) + Buffer.from(sig.signature), ); } const rangoSignaturesAreValid = clonedTx.verifySignatures(false); @@ -1555,7 +1555,7 @@ function checkSolanaVersionedTransactionSignatures( pubkey: string; /** Uint8 byte array */ signature: number[]; - }[] + }[], ): boolean { if (thirdPartySignatures.length === 0) return true; @@ -1567,7 +1567,7 @@ function checkSolanaVersionedTransactionSignatures( try { clonedTx.addSignature( new PublicKey(sig.pubkey), - Buffer.from(sig.signature) + Buffer.from(sig.signature), ); } catch (err) { // Does this happen? @@ -1588,7 +1588,7 @@ async function checkExpectedSolanaLegacyTransactionStatus( conn: Connection, legacyTx: SolanaLegacyTransaction, signed: boolean, - abortable?: { signal?: AbortSignal } + abortable?: { signal?: AbortSignal }, ): Promise< | { succeeds: true; error?: undefined } | { succeeds: false; error: TransactionError } @@ -1612,7 +1612,7 @@ async function checkExpectedSolanaLegacyTransactionStatus( debug( "checkExpectedSolanaLegacyTransactionStatus", `Retrying Rango Solana unsigned legacy transaction simulation` + - ` with updated block hash ${latestBlockHash.blockhash}...` + ` with updated block hash ${latestBlockHash.blockhash}...`, ); legacyTx.recentBlockhash = latestBlockHash.blockhash; abortable?.signal?.throwIfAborted(); @@ -1645,7 +1645,7 @@ async function checkExpectedSolanaVersionedTransactionStatus( conn: Connection, versionedTx: VersionedTransaction, signed: boolean, - abortable?: { signal?: AbortSignal } + abortable?: { signal?: AbortSignal }, ): Promise< | { succeeds: true; error?: undefined } | { succeeds: false; error: TransactionError } @@ -1668,7 +1668,7 @@ async function checkExpectedSolanaVersionedTransactionStatus( debug( "checkExpectedSolanaVersionedTransactionStatus", `Retrying Rango Solana unsigned versioned transaction simulation` + - ` with updated block hash ${latestBlockHash.blockhash}...` + ` with updated block hash ${latestBlockHash.blockhash}...`, ); versionedTx.message.recentBlockhash = latestBlockHash.blockhash; } diff --git a/packages/swap/src/providers/zerox/index.ts b/packages/swap/src/providers/zerox/index.ts index 24706a365..552243e8a 100644 --- a/packages/swap/src/providers/zerox/index.ts +++ b/packages/swap/src/providers/zerox/index.ts @@ -113,7 +113,7 @@ class ZeroX extends ProviderClass { static isSupported(network: SupportedNetworkName) { return Object.keys(supportedNetworks).includes( - network as unknown as string + network as unknown as string, ); } @@ -137,11 +137,11 @@ class ZeroX extends ProviderClass { private getZeroXSwap( options: getQuoteOptions, meta: QuoteMetaOptions, - accurateEstimate: boolean + accurateEstimate: boolean, ): Promise { if ( !ZeroX.isSupported( - options.toToken.networkInfo.name as SupportedNetworkName + options.toToken.networkInfo.name as SupportedNetworkName, ) || this.network !== options.toToken.networkInfo.name ) @@ -167,7 +167,7 @@ class ZeroX extends ProviderClass { return fetch( `${BASE_URL}${ supportedNetworks[this.network].chainId - }/swap/v1/quote?${params.toString()}` + }/swap/v1/quote?${params.toString()}`, ) .then((res) => res.json()) .then(async (response: ZeroXResponseType) => { @@ -199,7 +199,7 @@ class ZeroX extends ProviderClass { if (accurateEstimate) { const accurateGasEstimate = await estimateEVMGasList( transactions, - this.network + this.network, ); if (accurateGasEstimate) { if (accurateGasEstimate.isError) return null; @@ -222,7 +222,7 @@ class ZeroX extends ProviderClass { getQuote( options: getQuoteOptions, - meta: QuoteMetaOptions + meta: QuoteMetaOptions, ): Promise { return this.getZeroXSwap(options, meta, false).then(async (res) => { if (!res) return null; @@ -239,7 +239,7 @@ class ZeroX extends ProviderClass { totalGaslimit: res.transactions.reduce( (total: number, curVal: EVMTransaction) => total + toBN(curVal.gasLimit).toNumber(), - 0 + 0, ), minMax: await this.getMinMaxAmount(), }; @@ -261,7 +261,7 @@ class ZeroX extends ProviderClass { slippage: quote.meta.slippage || DEFAULT_SLIPPAGE, fee: feeConfig * 100, getStatusObject: async ( - options: StatusOptions + options: StatusOptions, ): Promise => ({ options, provider: this.name, @@ -273,7 +273,7 @@ class ZeroX extends ProviderClass { getStatus(options: StatusOptions): Promise { const promises = options.transactionHashes.map((hash) => - this.web3eth.getTransactionReceipt(hash) + this.web3eth.getTransactionReceipt(hash), ); return Promise.all(promises).then((receipts) => { // eslint-disable-next-line no-restricted-syntax diff --git a/packages/swap/src/types/index.ts b/packages/swap/src/types/index.ts index 3f3d63b07..48dc702a7 100644 --- a/packages/swap/src/types/index.ts +++ b/packages/swap/src/types/index.ts @@ -278,12 +278,12 @@ export abstract class ProviderClass { abstract getQuote( options: getQuoteOptions, meta: QuoteMetaOptions, - context?: { signal?: AbortSignal } + context?: { signal?: AbortSignal }, ): Promise; abstract getSwap( quote: SwapQuote, - context?: { signal?: AbortSignal } + context?: { signal?: AbortSignal }, ): Promise; abstract getStatus(options: StatusOptions): Promise; diff --git a/packages/swap/src/utils/approvals.ts b/packages/swap/src/utils/approvals.ts index 9c8bbe164..ca33dc119 100644 --- a/packages/swap/src/utils/approvals.ts +++ b/packages/swap/src/utils/approvals.ts @@ -18,7 +18,7 @@ const getAllowance = (options: { }): Promise => { const contract = new options.web3eth.Contract( Erc20abi as any, - options.contract + options.contract, ); return contract.methods.allowance(options.owner, options.spender).call(); }; @@ -87,7 +87,7 @@ const getAllowanceTransactions = async (options: { owner: options.fromAddress, spender: options.spender, web3eth: options.web3eth, - }) + }), ); if (approvedAmount.lt(options.amount)) { // `spender` isn't approved for enough @@ -101,7 +101,7 @@ const getAllowanceTransactions = async (options: { ? TOKEN_AMOUNT_INFINITY_AND_BEYOND : options.amount.toString(), contract: options.fromToken.address, - }) + }), ); } else { // `spender` is approved for some, but not enough @@ -113,7 +113,7 @@ const getAllowanceTransactions = async (options: { spender: options.spender, value: "0", contract: options.fromToken.address, - }) + }), ); // Request approval for `spender` transactions.push( @@ -124,7 +124,7 @@ const getAllowanceTransactions = async (options: { ? TOKEN_AMOUNT_INFINITY_AND_BEYOND : options.amount.toString(), contract: options.fromToken.address, - }) + }), ); } } diff --git a/packages/swap/src/utils/common.ts b/packages/swap/src/utils/common.ts index 82592a081..e0a39a0fa 100644 --- a/packages/swap/src/utils/common.ts +++ b/packages/swap/src/utils/common.ts @@ -26,11 +26,11 @@ export const sortByRank = (x: { rank?: number }, y: { rank?: number }) => { export const sortNativeToFront = ( x: { address: string }, - y: { address: string } + y: { address: string }, ) => // eslint-disable-next-line no-nested-ternary x.address === NATIVE_TOKEN_ADDRESS ? -1 : y.address === NATIVE_TOKEN_ADDRESS - ? 1 - : 0; + ? 1 + : 0; diff --git a/packages/swap/src/utils/solana.ts b/packages/swap/src/utils/solana.ts index 183924da0..e0e43aa3f 100644 --- a/packages/swap/src/utils/solana.ts +++ b/packages/swap/src/utils/solana.ts @@ -17,7 +17,7 @@ import { * @see https://solscan.io/account/TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA */ export const TOKEN_PROGRAM_ID = new PublicKey( - "TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA" + "TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA", ); /** @@ -26,7 +26,7 @@ export const TOKEN_PROGRAM_ID = new PublicKey( * @see https://solscan.io/account/TokenzQdBNbLqP5VEhdkAS6EPFLC1PHnBqCXEpPxuEb */ export const TOKEN_2022_PROGRAM_ID = new PublicKey( - "TokenzQdBNbLqP5VEhdkAS6EPFLC1PHnBqCXEpPxuEb" + "TokenzQdBNbLqP5VEhdkAS6EPFLC1PHnBqCXEpPxuEb", ); /** @@ -37,7 +37,7 @@ export const TOKEN_2022_PROGRAM_ID = new PublicKey( * @see https://solscan.io/account/ATokenGPvbdGVxr1b2hvZbsiqW5xWH25efTNsLJA8knL */ export const ASSOCIATED_TOKEN_PROGRAM_ID = new PublicKey( - "ATokenGPvbdGVxr1b2hvZbsiqW5xWH25efTNsLJA8knL" + "ATokenGPvbdGVxr1b2hvZbsiqW5xWH25efTNsLJA8knL", ); export const SPL_TOKEN_ATA_ACCOUNT_SIZE_BYTES = 165; @@ -58,7 +58,7 @@ export const WRAPPED_SOL_ADDRESS = * transaction failure. */ export function extractComputeBudget( - tx: VersionedTransaction + tx: VersionedTransaction, ): undefined | number { // extract the compute budget @@ -80,7 +80,7 @@ export function extractComputeBudget( pubkey: tx.message.staticAccountKeys[accountKeyIndex], isSigner: tx.message.isAccountSigner(accountKeyIndex), isWritable: tx.message.isAccountWritable(accountKeyIndex), - }) + }), ); // Decompile the instruction @@ -124,7 +124,7 @@ export function extractComputeBudget( export async function insertInstructionsAtStartOfTransaction( conn: Connection, tx: VersionedTransaction, - instructions: TransactionInstruction[] + instructions: TransactionInstruction[], ): Promise { if (instructions.length === 0) return tx; @@ -144,7 +144,7 @@ export async function insertInstructionsAtStartOfTransaction( // We can also use the lookup accounts when re-compiling the transaction. const lookupAccountsCount = tx.message.addressTableLookups.length; const addressLookupTableAccounts: AddressLookupTableAccount[] = new Array( - lookupAccountsCount + lookupAccountsCount, ); for (let i = 0; i < lookupAccountsCount; i++) { @@ -153,7 +153,7 @@ export async function insertInstructionsAtStartOfTransaction( const addressLookupTableAccount = result.value; if (addressLookupTableAccount == null) throw new Error( - `Failed to get address lookup table for ${lookup.accountKey}` + `Failed to get address lookup table for ${lookup.accountKey}`, ); // debug( // "insertInstructionsAtStartOfTransaction", @@ -165,7 +165,7 @@ export async function insertInstructionsAtStartOfTransaction( // Decompile the transaction message so we can modify it const decompiledTransactionMessage = TransactionMessage.decompile( tx.message, - { addressLookupTableAccounts } + { addressLookupTableAccounts }, ); // Insert our instruction to create an account directly after compute budget @@ -212,7 +212,7 @@ export async function insertInstructionsAtStartOfTransaction( // Switch to using this modified transaction // debug("insertInstructionsAtStartOfTransaction", `Re-compiling transaction`); const modifiedTx = new VersionedTransaction( - decompiledTransactionMessage.compileToV0Message(addressLookupTableAccounts) + decompiledTransactionMessage.compileToV0Message(addressLookupTableAccounts), ); return modifiedTx; @@ -227,14 +227,14 @@ export async function insertInstructionsAtStartOfTransaction( */ export async function getTokenProgramOfMint( conn: Connection, - mint: PublicKey + mint: PublicKey, ): Promise { // debug("getTokenProgramOfMint", `Checking mint account of ${mint.toBase58()}`); const srcMintAcc = await conn.getAccountInfo(mint); if (srcMintAcc == null) { throw new Error( - `There is no SPL token account at address ${mint.toBase58()}` + `There is no SPL token account at address ${mint.toBase58()}`, ); } @@ -246,7 +246,7 @@ export async function getTokenProgramOfMint( throw new Error( `Mint address is not a valid SPL token, must either have owner` + ` TOKEN_PROGRAM_ID (${TOKEN_PROGRAM_ID.toBase58()})` + - ` or TOKEN_2022_PROGRAM_ID (${TOKEN_2022_PROGRAM_ID.toBase58()})` + ` or TOKEN_2022_PROGRAM_ID (${TOKEN_2022_PROGRAM_ID.toBase58()})`, ); } } @@ -258,12 +258,12 @@ export function getSPLAssociatedTokenAccountPubkey( wallet: PublicKey, mint: PublicKey, /** Either the SPL token program or the 2022 SPL token program */ - tokenProgramId: PublicKey + tokenProgramId: PublicKey, ): PublicKey { const SEED = [wallet.toBuffer(), tokenProgramId.toBuffer(), mint.toBuffer()]; const [associatedTokenAddress] = PublicKey.findProgramAddressSync( SEED, - ASSOCIATED_TOKEN_PROGRAM_ID + ASSOCIATED_TOKEN_PROGRAM_ID, ); return associatedTokenAddress; } @@ -286,7 +286,7 @@ export function createAssociatedTokenAccountIdempotentInstruction( owner: PublicKey, mint: PublicKey, programId = TOKEN_PROGRAM_ID, - associatedTokenProgramId = ASSOCIATED_TOKEN_PROGRAM_ID + associatedTokenProgramId = ASSOCIATED_TOKEN_PROGRAM_ID, ): TransactionInstruction { // eslint-disable-next-line no-use-before-define return buildAssociatedTokenAccountInstruction( @@ -296,7 +296,7 @@ export function createAssociatedTokenAccountIdempotentInstruction( mint, Buffer.from([1]), programId, - associatedTokenProgramId + associatedTokenProgramId, ); } @@ -307,7 +307,7 @@ export function buildAssociatedTokenAccountInstruction( mint: PublicKey, instructionData: Buffer, programId = TOKEN_PROGRAM_ID, - associatedTokenProgramId = ASSOCIATED_TOKEN_PROGRAM_ID + associatedTokenProgramId = ASSOCIATED_TOKEN_PROGRAM_ID, ): TransactionInstruction { const keys = [ { pubkey: payer, isSigner: true, isWritable: true }, @@ -415,7 +415,7 @@ export function isValidSolanaAddress(address: string): boolean { } export async function isValidSolanaAddressAsync( - address: string + address: string, ): Promise { return isValidSolanaAddress(address); } @@ -431,7 +431,7 @@ export async function isValidSolanaAddressAsync( */ export async function solAccountExists( conn: Connection, - address: PublicKey + address: PublicKey, ): Promise { const account = await conn.getAccountInfo(address, "max"); const exists = account != null; diff --git a/packages/swap/tests/changelly.test.ts b/packages/swap/tests/changelly.test.ts index 103c690f2..474325017 100644 --- a/packages/swap/tests/changelly.test.ts +++ b/packages/swap/tests/changelly.test.ts @@ -35,12 +35,12 @@ describe("Changelly Provider", () => { toToken, toAddress, }, - { infiniteApproval: true, walletIdentifier: WalletIdentifier.enkrypt } + { infiniteApproval: true, walletIdentifier: WalletIdentifier.enkrypt }, ); expect(quote?.provider).to.be.eq(ProviderName.changelly); expect(quote?.quote.meta.infiniteApproval).to.be.eq(true); expect(quote?.quote.meta.walletIdentifier).to.be.eq( - WalletIdentifier.enkrypt + WalletIdentifier.enkrypt, ); expect(quote?.fromTokenAmount.gte(amountUSDT)).to.be.eq(true); expect(quote?.toTokenAmount.gtn(0)).to.be.eq(true); @@ -48,12 +48,10 @@ describe("Changelly Provider", () => { expect(swap?.transactions.length).to.be.eq(1); expect( - (swap?.transactions[0] as EVMTransaction).data.startsWith("0xa9059cbb") + (swap?.transactions[0] as EVMTransaction).data.startsWith("0xa9059cbb"), ).to.be.eq(true); const status = await changelly.getStatus( - ( - await swap!.getStatusObject({ transactionHashes: [] }) - ).options + (await swap!.getStatusObject({ transactionHashes: [] })).options, ); expect(status).to.be.eq("pending"); }); @@ -62,13 +60,13 @@ describe("Changelly Provider", () => { await init; const toTokens = changelly.getToTokens(); expect( - Object.values(toTokens[SupportedNetworkName.Polkadot]).length + Object.values(toTokens[SupportedNetworkName.Polkadot]).length, ).to.be.eq(1); expect( - Object.values(toTokens[SupportedNetworkName.Bitcoin]).length + Object.values(toTokens[SupportedNetworkName.Bitcoin]).length, ).to.be.eq(1); expect( - Object.values(toTokens[SupportedNetworkName.EthereumClassic]).length + Object.values(toTokens[SupportedNetworkName.EthereumClassic]).length, ).to.be.eq(1); }); diff --git a/packages/swap/tests/jupiter.test.ts b/packages/swap/tests/jupiter.test.ts index 04935b5d8..89c051f10 100644 --- a/packages/swap/tests/jupiter.test.ts +++ b/packages/swap/tests/jupiter.test.ts @@ -58,12 +58,12 @@ describe("Jupiter Provider", () => { toToken, toAddress, }, - { infiniteApproval: true, walletIdentifier: WalletIdentifier.enkrypt } + { infiniteApproval: true, walletIdentifier: WalletIdentifier.enkrypt }, ); expect(quote!.provider).to.be.eq(ProviderName.jupiter); expect(quote!.quote.meta.infiniteApproval).to.be.eq(true); expect(quote!.quote.meta.walletIdentifier).to.be.eq( - WalletIdentifier.enkrypt + WalletIdentifier.enkrypt, ); expect(quote!.fromTokenAmount.toString()).to.be.eq(amount.toString()); expect(quote!.toTokenAmount.gtn(0)).to.be.eq(true); @@ -74,8 +74,8 @@ describe("Jupiter Provider", () => { const tx = VersionedTransaction.deserialize( Buffer.from( (swap.transactions[0] as SolanaTransaction).serialized, - "base64" - ) + "base64", + ), ); // Decode the transaction and check some facts about it @@ -85,13 +85,13 @@ describe("Jupiter Provider", () => { for (let i = 0, len = tx.message.addressTableLookups.length; i < len; i++) { const addressTableLookup = tx.message.addressTableLookups[i]; const result = await conn.getAddressLookupTable( - addressTableLookup.accountKey + addressTableLookup.accountKey, ); const addressLookupTableAccount = result.value; // eslint-disable-next-line no-unused-expressions expect( addressLookupTableAccount, - "Address lookup table account not found" + "Address lookup table account not found", ).to.be.ok; addressLookupTableAccounts.push(addressLookupTableAccount!); } @@ -114,7 +114,7 @@ describe("Jupiter Provider", () => { // eslint-disable-next-line no-unused-expressions expect( computeBudget == null, - "Multiple SetComputeUnitLimit instructions found in the same transaction" + "Multiple SetComputeUnitLimit instructions found in the same transaction", ).to.be.ok; const command = ComputeBudgetInstruction.decodeSetComputeUnitLimit(instruction); @@ -125,7 +125,7 @@ describe("Jupiter Provider", () => { // eslint-disable-next-line no-unused-expressions expect( priorityRate == null, - "Multiple SetComputeUnitPrice instructions found in the same transaction" + "Multiple SetComputeUnitPrice instructions found in the same transaction", ).to.be.ok; const command = ComputeBudgetInstruction.decodeSetComputeUnitPrice(instruction); @@ -142,7 +142,7 @@ describe("Jupiter Provider", () => { expect( decompiledMessage.payerKey.toBase58(), - "Payer key is not the from address" + "Payer key is not the from address", ).to.equal(fromAddress); }); }); diff --git a/packages/swap/tests/oneInch.test.ts b/packages/swap/tests/oneInch.test.ts index d58d657c2..e79eea317 100644 --- a/packages/swap/tests/oneInch.test.ts +++ b/packages/swap/tests/oneInch.test.ts @@ -34,12 +34,12 @@ describe("OneInch Provider", () => { toToken, toAddress, }, - { infiniteApproval: true, walletIdentifier: WalletIdentifier.enkrypt } + { infiniteApproval: true, walletIdentifier: WalletIdentifier.enkrypt }, ); expect(quote?.provider).to.be.eq(ProviderName.oneInch); expect(quote?.quote.meta.infiniteApproval).to.be.eq(true); expect(quote?.quote.meta.walletIdentifier).to.be.eq( - WalletIdentifier.enkrypt + WalletIdentifier.enkrypt, ); expect(quote?.fromTokenAmount.toString()).to.be.eq(amount.toString()); expect(quote?.toTokenAmount.gtn(0)).to.be.eq(true); @@ -50,11 +50,11 @@ describe("OneInch Provider", () => { expect((swap?.transactions[0] as EVMTransaction).data).to.be.eq( `0x095ea7b3000000000000000000000000${ONEINCH_APPROVAL_ADDRESS.replace( "0x", - "" - )}${TOKEN_AMOUNT_INFINITY_AND_BEYOND.replace("0x", "")}` + "", + )}${TOKEN_AMOUNT_INFINITY_AND_BEYOND.replace("0x", "")}`, ); expect(swap?.transactions[1].to).to.be.eq(ONEINCH_APPROVAL_ADDRESS); - } + }, ); it( @@ -69,7 +69,7 @@ describe("OneInch Provider", () => { toToken, toAddress, }, - { infiniteApproval: false, walletIdentifier: WalletIdentifier.enkrypt } + { infiniteApproval: false, walletIdentifier: WalletIdentifier.enkrypt }, ); expect(quote?.quote.meta.infiniteApproval).to.be.eq(false); const swap = await oneInch.getSwap(quote!.quote); @@ -77,12 +77,12 @@ describe("OneInch Provider", () => { expect((swap?.transactions[0] as EVMTransaction).data).to.be.eq( `0x095ea7b3000000000000000000000000${ONEINCH_APPROVAL_ADDRESS.replace( "0x", - "" + "", )}00000000000000000000000000000000000000000000000${numberToHex( - amount - ).replace("0x", "")}` + amount, + ).replace("0x", "")}`, ); expect(swap?.transactions[1].to).to.be.eq(ONEINCH_APPROVAL_ADDRESS); - } + }, ); }); diff --git a/packages/swap/tests/paraswap.test.ts b/packages/swap/tests/paraswap.test.ts index 9eb9fa52a..413dac6e5 100644 --- a/packages/swap/tests/paraswap.test.ts +++ b/packages/swap/tests/paraswap.test.ts @@ -34,12 +34,12 @@ describe("Paraswap Provider", () => { toToken, toAddress, }, - { infiniteApproval: true, walletIdentifier: WalletIdentifier.enkrypt } + { infiniteApproval: true, walletIdentifier: WalletIdentifier.enkrypt }, ); expect(quote?.provider).to.be.eq(ProviderName.paraswap); expect(quote?.quote.meta.infiniteApproval).to.be.eq(true); expect(quote?.quote.meta.walletIdentifier).to.be.eq( - WalletIdentifier.enkrypt + WalletIdentifier.enkrypt, ); expect(quote?.fromTokenAmount.toString()).to.be.eq(amount.toString()); expect(quote?.toTokenAmount.gtn(0)).to.be.eq(true); @@ -50,13 +50,13 @@ describe("Paraswap Provider", () => { expect((swap?.transactions[0] as EVMTransaction).data).to.be.eq( `0x095ea7b3000000000000000000000000${PARASWAP_APPROVAL_ADDRESS.replace( "0x", - "" - )}${TOKEN_AMOUNT_INFINITY_AND_BEYOND.replace("0x", "")}` + "", + )}${TOKEN_AMOUNT_INFINITY_AND_BEYOND.replace("0x", "")}`, ); expect(swap?.transactions[1].to).to.be.eq( - "0x6a000f20005980200259b80c5102003040001068" + "0x6a000f20005980200259b80c5102003040001068", ); - } + }, ); it( @@ -71,7 +71,7 @@ describe("Paraswap Provider", () => { toToken, toAddress, }, - { infiniteApproval: false, walletIdentifier: WalletIdentifier.enkrypt } + { infiniteApproval: false, walletIdentifier: WalletIdentifier.enkrypt }, ); expect(quote?.quote.meta.infiniteApproval).to.be.eq(false); const swap = await paraSwap.getSwap(quote!.quote); @@ -79,14 +79,14 @@ describe("Paraswap Provider", () => { expect((swap?.transactions[0] as EVMTransaction).data).to.be.eq( `0x095ea7b3000000000000000000000000${PARASWAP_APPROVAL_ADDRESS.replace( "0x", - "" + "", )}00000000000000000000000000000000000000000000000${numberToHex( - amount - ).replace("0x", "")}` + amount, + ).replace("0x", "")}`, ); expect(swap?.transactions[1].to).to.be.eq( - "0x6a000f20005980200259b80c5102003040001068" + "0x6a000f20005980200259b80c5102003040001068", ); - } + }, ); }); diff --git a/packages/swap/tests/rango.test.ts b/packages/swap/tests/rango.test.ts index b7e9f2e14..5b8d45645 100644 --- a/packages/swap/tests/rango.test.ts +++ b/packages/swap/tests/rango.test.ts @@ -34,12 +34,12 @@ describe("Rango Provider", () => { toToken, toAddress, }, - { infiniteApproval: true, walletIdentifier: WalletIdentifier.enkrypt } + { infiniteApproval: true, walletIdentifier: WalletIdentifier.enkrypt }, ); expect(quote?.provider).to.be.eq(ProviderName.rango); expect(quote?.quote.meta.infiniteApproval).to.be.eq(true); expect(quote?.quote.meta.walletIdentifier).to.be.eq( - WalletIdentifier.enkrypt + WalletIdentifier.enkrypt, ); expect(quote?.fromTokenAmount.toString()).to.be.eq(localAmount.toString()); expect(quote?.toTokenAmount.gtn(0)).to.be.eq(true); @@ -62,12 +62,12 @@ describe("Rango Provider", () => { toToken, toAddress, }, - { infiniteApproval: true, walletIdentifier: WalletIdentifier.enkrypt } + { infiniteApproval: true, walletIdentifier: WalletIdentifier.enkrypt }, ); expect(quote?.provider).to.be.eq(ProviderName.rango); expect(quote?.quote.meta.infiniteApproval).to.be.eq(true); expect(quote?.quote.meta.walletIdentifier).to.be.eq( - WalletIdentifier.enkrypt + WalletIdentifier.enkrypt, ); expect(quote?.fromTokenAmount.toString()).to.be.eq(amount.toString()); expect(quote?.toTokenAmount.gtn(0)).to.be.eq(true); diff --git a/packages/swap/tests/swap.test.ts b/packages/swap/tests/swap.test.ts index 85214c08b..b1ccd28ec 100644 --- a/packages/swap/tests/swap.test.ts +++ b/packages/swap/tests/swap.test.ts @@ -42,15 +42,15 @@ describe("Swap", () => { const toTokens = enkryptSwap.getToTokens(); expect(toTokens.all[SupportedNetworkName.Bitcoin].length).to.be.eq(1); expect(toTokens.all[SupportedNetworkName.Bitcoin][0].address).to.be.eq( - NATIVE_TOKEN_ADDRESS + NATIVE_TOKEN_ADDRESS, ); expect(toTokens.all[SupportedNetworkName.Polkadot].length).to.be.eq(1); expect(toTokens.all[SupportedNetworkName.Ethereum].length).to.be.gt(4000); expect(toTokens.all[SupportedNetworkName.Ethereum][0].address).to.be.eq( - NATIVE_TOKEN_ADDRESS + NATIVE_TOKEN_ADDRESS, ); expect(toTokens.top[SupportedNetworkName.Bitcoin][0].address).to.be.eq( - NATIVE_TOKEN_ADDRESS + NATIVE_TOKEN_ADDRESS, ); }); @@ -68,18 +68,18 @@ describe("Swap", () => { }); expect(quotes?.length).to.be.gte(3); const oneInceQuote = quotes.find( - (q) => q.provider === ProviderName.oneInch + (q) => q.provider === ProviderName.oneInch, ); const paraswapQuote = quotes.find( - (q) => q.provider === ProviderName.paraswap + (q) => q.provider === ProviderName.paraswap, ); const changellyQuote = quotes.find( - (q) => q.provider === ProviderName.changelly + (q) => q.provider === ProviderName.changelly, ); const zeroxQuote = quotes.find((q) => q.provider === ProviderName.zerox); if (quotes?.length > 3) { const rangoQuote = quotes.find( - (q) => q.provider === ProviderName.rango + (q) => q.provider === ProviderName.rango, ); expect(rangoQuote!.provider).to.be.eq(ProviderName.rango); } @@ -89,12 +89,12 @@ describe("Swap", () => { expect(paraswapQuote!.provider).to.be.eq(ProviderName.paraswap); const swapOneInch = await enkryptSwap.getSwap(oneInceQuote!.quote); expect(swapOneInch?.fromTokenAmount.toString()).to.be.eq( - amountUSDT.toString() + amountUSDT.toString(), ); expect(swapOneInch?.transactions.length).to.be.eq(2); const swapChangelly = await enkryptSwap.getSwap(changellyQuote!.quote); if (swapChangelly) expect(swapChangelly?.transactions.length).to.be.eq(1); - } + }, ); it( @@ -111,13 +111,13 @@ describe("Swap", () => { }); expect(quotes?.length).to.be.gte(4); const oneInceQuote = quotes.find( - (q) => q.provider === ProviderName.oneInch + (q) => q.provider === ProviderName.oneInch, ); const paraswapQuote = quotes.find( - (q) => q.provider === ProviderName.paraswap + (q) => q.provider === ProviderName.paraswap, ); const changellyQuote = quotes.find( - (q) => q.provider === ProviderName.changelly + (q) => q.provider === ProviderName.changelly, ); const zeroxQuote = quotes.find((q) => q.provider === ProviderName.zerox); // const rangoQuote = quotes.find((q) => q.provider === ProviderName.rango); @@ -126,6 +126,6 @@ describe("Swap", () => { expect(oneInceQuote!.provider).to.be.eq(ProviderName.oneInch); expect(paraswapQuote!.provider).to.be.eq(ProviderName.paraswap); // expect(rangoQuote!.provider).to.be.eq(ProviderName.rango); - } + }, ); }); diff --git a/packages/swap/tests/swapToken.test.ts b/packages/swap/tests/swapToken.test.ts index 3dbd8b9c2..3c1a3d202 100644 --- a/packages/swap/tests/swapToken.test.ts +++ b/packages/swap/tests/swapToken.test.ts @@ -7,10 +7,10 @@ describe("SwapToken", () => { it("it should convert", async () => { const token = new SwapToken(fromToken); expect(token.toRaw("1526.652").toString()).to.be.eq( - "1526652000000000000000" + "1526652000000000000000", ); expect( - token.toReadable(toBN("1526652000000000000000")).toString() + token.toReadable(toBN("1526652000000000000000")).toString(), ).to.be.eq("1526.652"); }); }); diff --git a/packages/swap/tests/zerox.test.ts b/packages/swap/tests/zerox.test.ts index e7373be80..7986d64a4 100644 --- a/packages/swap/tests/zerox.test.ts +++ b/packages/swap/tests/zerox.test.ts @@ -25,10 +25,10 @@ describe("Zerox Provider", () => { if (process.env.CI) { // We need at-least one test otherwise vitest reports failure - it('No ZeroX swap tests in CI', function() { - expect(true).toBeTruthy() - }) - return + it("No ZeroX swap tests in CI", function () { + expect(true).toBeTruthy(); + }); + return; } it( @@ -43,12 +43,12 @@ describe("Zerox Provider", () => { toToken, toAddress: fromAddress, }, - { infiniteApproval: true, walletIdentifier: WalletIdentifier.enkrypt } + { infiniteApproval: true, walletIdentifier: WalletIdentifier.enkrypt }, ); expect(quote?.provider).to.be.eq(ProviderName.zerox); expect(quote?.quote.meta.infiniteApproval).to.be.eq(true); expect(quote?.quote.meta.walletIdentifier).to.be.eq( - WalletIdentifier.enkrypt + WalletIdentifier.enkrypt, ); expect(quote?.fromTokenAmount.toString()).to.be.eq(amount.toString()); expect(quote?.toTokenAmount.gtn(0)).to.be.eq(true); @@ -59,11 +59,11 @@ describe("Zerox Provider", () => { expect((swap?.transactions[0] as EVMTransaction).data).to.be.eq( `0x095ea7b3000000000000000000000000${ZEROX_APPROVAL.replace( "0x", - "" - )}${TOKEN_AMOUNT_INFINITY_AND_BEYOND.replace("0x", "")}` + "", + )}${TOKEN_AMOUNT_INFINITY_AND_BEYOND.replace("0x", "")}`, ); expect(swap?.transactions[1].to).to.be.eq(ZEROX_APPROVAL); - } + }, ); it( @@ -78,7 +78,7 @@ describe("Zerox Provider", () => { toToken, toAddress: fromAddress, }, - { infiniteApproval: false, walletIdentifier: WalletIdentifier.enkrypt } + { infiniteApproval: false, walletIdentifier: WalletIdentifier.enkrypt }, ); expect(quote?.quote.meta.infiniteApproval).to.be.eq(false); const swap = await zerox.getSwap(quote!.quote); @@ -86,12 +86,12 @@ describe("Zerox Provider", () => { expect((swap?.transactions[0] as EVMTransaction).data).to.be.eq( `0x095ea7b3000000000000000000000000${ZEROX_APPROVAL.replace( "0x", - "" + "", )}00000000000000000000000000000000000000000000000${numberToHex( - amount - ).replace("0x", "")}` + amount, + ).replace("0x", "")}`, ); expect(swap?.transactions[1].to).to.be.eq(ZEROX_APPROVAL); - } + }, ); }); diff --git a/packages/types/src/index.ts b/packages/types/src/index.ts index 0865c8f9d..e93fe1d48 100644 --- a/packages/types/src/index.ts +++ b/packages/types/src/index.ts @@ -94,18 +94,18 @@ interface SignerInterface { sign: ( msgHash: string, keypair: KeyPair, - options?: unknown + options?: unknown, ) => Promise; verify: ( msgHash: string, sig: string, publicKey: string, - options?: unknown + options?: unknown, ) => Promise; generate: ( mnemonic: string, path: string, - options?: unknown + options?: unknown, ) => Promise; } const Errors = { @@ -123,7 +123,7 @@ interface EncryptedData { } interface BrowserStorageArea { get( - keys?: null | string | string[] | Record + keys?: null | string | string[] | Record, ): Promise>; set(items: Record): Promise; remove(keys: string | string[]): Promise; @@ -153,7 +153,7 @@ type NextFunction = () => void; type MiddlewareFunction = ( payload: RPCRequestType, response: CallbackFunction, - next: NextFunction + next: NextFunction, ) => void; interface OnMessageResponse { diff --git a/packages/utils/src/encrypt.ts b/packages/utils/src/encrypt.ts index 5d151d7d6..0f51738f6 100644 --- a/packages/utils/src/encrypt.ts +++ b/packages/utils/src/encrypt.ts @@ -25,7 +25,7 @@ const runCipherBuffer = (cipher: Cipher | Decipher, data: Buffer): Buffer => export const encrypt = async ( msg: Buffer, - password: string + password: string, ): Promise => { const sparams = { ...{ @@ -40,12 +40,12 @@ export const encrypt = async ( sparams.n, sparams.p, sparams.r, - sparams.dklen + sparams.dklen, ); const cipher = createCipheriv( sparams.cipher, derivedKey.slice(0, 16), - sparams.iv + sparams.iv, ); const ciphertext = runCipherBuffer(cipher, msg); const mac = keccak256( @@ -53,8 +53,8 @@ export const encrypt = async ( Buffer.concat([ Buffer.from(derivedKey.slice(16, 32)), Buffer.from(ciphertext), - ]) - ) + ]), + ), ); return { ciphertext: bufferToHex(ciphertext), @@ -67,7 +67,7 @@ export const encrypt = async ( export const decrypt = async ( encryptedData: EncryptedData, - password: string + password: string, ): Promise => { const sparams = { ...{ @@ -85,18 +85,21 @@ export const decrypt = async ( sparams.n, sparams.p, sparams.r, - sparams.dklen + sparams.dklen, ); const mac = keccak256( bufferToHex( - Buffer.concat([Buffer.from(derivedKey.slice(16, 32)), sparams.ciphertext]) - ) + Buffer.concat([ + Buffer.from(derivedKey.slice(16, 32)), + sparams.ciphertext, + ]), + ), ); if (mac !== sparams.mac) throw new Error(Errors.OtherErrors.WrongPassword); const decipher = createDecipheriv( sparams.cipher, derivedKey.slice(0, 16), - sparams.iv + sparams.iv, ); return runCipherBuffer(decipher, sparams.ciphertext); }; diff --git a/packages/utils/src/index.ts b/packages/utils/src/index.ts index 6890e660d..e1cfb5e68 100644 --- a/packages/utils/src/index.ts +++ b/packages/utils/src/index.ts @@ -20,7 +20,7 @@ const hexToBuffer = (hex: string): Buffer => stripHexPrefix(hex).length % 2 === 1 ? `0${stripHexPrefix(hex)}` : stripHexPrefix(hex), - "hex" + "hex", ); export { diff --git a/packages/utils/src/units.ts b/packages/utils/src/units.ts index 284b46019..24360788f 100644 --- a/packages/utils/src/units.ts +++ b/packages/utils/src/units.ts @@ -25,7 +25,7 @@ const numberToString = (arg: any) => { if (typeof arg === "string") { if (!arg.match(/^-?[0-9.]+$/)) { throw new Error( - `while converting number to string, invalid number value '${arg}', should be a number matching (^-?[0-9.]+).` + `while converting number to string, invalid number value '${arg}', should be a number matching (^-?[0-9.]+).`, ); } return arg; @@ -44,7 +44,7 @@ const numberToString = (arg: any) => { return arg.toString(10); } throw new Error( - `while converting number to string, invalid number value '${arg}' type ${typeof arg}.` + `while converting number to string, invalid number value '${arg}' type ${typeof arg}.`, ); }; @@ -54,7 +54,7 @@ const numberToString = (arg: any) => { const fromBase = ( weiInput: string, decimals: number, - optionsInput?: any + optionsInput?: any, ): string => { let wei = toBN(weiInput); const negative = wei.lt(zero); @@ -104,7 +104,7 @@ const toBase = (etherInput: string, decimals: number): string => { if (ether === ".") { throw new Error( - `[ethjs-unit] while converting number ${etherInput} to wei, invalid value` + `[ethjs-unit] while converting number ${etherInput} to wei, invalid value`, ); } @@ -112,7 +112,7 @@ const toBase = (etherInput: string, decimals: number): string => { const comps = ether.split("."); if (comps.length > 2) { throw new Error( - `[ethjs-unit] while converting number ${etherInput} to wei, too many decimal points` + `[ethjs-unit] while converting number ${etherInput} to wei, too many decimal points`, ); } @@ -127,7 +127,7 @@ const toBase = (etherInput: string, decimals: number): string => { } if (fraction.length > baseLength) { throw new Error( - `[ethjs-unit] while converting number ${etherInput} to wei, too many decimal places` + `[ethjs-unit] while converting number ${etherInput} to wei, too many decimal places`, ); }