diff --git a/packages/anchor-contrib/src/generateAccountParsers.ts b/packages/anchor-contrib/src/generateAccountParsers.ts index 5291a46b3..6081ccef5 100644 --- a/packages/anchor-contrib/src/generateAccountParsers.ts +++ b/packages/anchor-contrib/src/generateAccountParsers.ts @@ -17,12 +17,12 @@ export type AccountParsers = { * @param idl The IDL. */ export const generateAccountParsers = >( - idl: Idl + idl: Idl, ): AccountParsers => { const coder = new BorshAccountsCoder(idl); return generateAccountParsersFromCoder( idl.accounts?.map((a) => a.name), - coder + coder, ); }; @@ -35,7 +35,7 @@ export const generateAccountParsers = >( */ export const generateAccountParsersFromCoder = ( accountNames: string[] | undefined, - coder: AccountsCoder + coder: AccountsCoder, ): AccountParsers => { return (accountNames ?? []).reduce((parsers, account) => { parsers[camelCase(account) as keyof M] = (data: Buffer) => diff --git a/packages/anchor-contrib/src/types.ts b/packages/anchor-contrib/src/types.ts index 708a9ce87..656c223e8 100644 --- a/packages/anchor-contrib/src/types.ts +++ b/packages/anchor-contrib/src/types.ts @@ -50,7 +50,7 @@ type Context = Omit & { type MakeInstructionsNamespace< R extends InstructionsParsed, Ret, - Mk extends { [M in keyof R]: unknown } = { [M in keyof R]: unknown } + Mk extends { [M in keyof R]: unknown } = { [M in keyof R]: unknown }, > = { [M in keyof R]: (( ...args: [...R[M]["args"], Context] @@ -124,18 +124,18 @@ type TypeMap = { type DecodeType = T extends keyof TypeMap ? TypeMap[T] : T extends { defined: keyof Defined } - ? Defined[T["defined"]] - : T extends { option: { defined: keyof Defined } } - ? Defined[T["option"]["defined"]] | null - : T extends { option: keyof TypeMap } - ? TypeMap[T["option"]] | null - : T extends { vec: { defined: keyof Defined } } - ? Defined[T["vec"]["defined"]][] - : T extends { vec: keyof TypeMap } - ? TypeMap[T["vec"]][] - : T extends { array: [idlType: keyof TypeMap, size: number] } - ? TypeMap[T["array"][0]][] - : unknown; + ? Defined[T["defined"]] + : T extends { option: { defined: keyof Defined } } + ? Defined[T["option"]["defined"]] | null + : T extends { option: keyof TypeMap } + ? TypeMap[T["option"]] | null + : T extends { vec: { defined: keyof Defined } } + ? Defined[T["vec"]["defined"]][] + : T extends { vec: keyof TypeMap } + ? TypeMap[T["vec"]][] + : T extends { array: [idlType: keyof TypeMap, size: number] } + ? TypeMap[T["array"][0]][] + : unknown; type MakeArgs = { [K in keyof A]: A[K] extends IdlField @@ -169,7 +169,7 @@ export type AnchorProgram< Methods extends MakeInstructions< NonNullable["methods"], Defined - > = MakeInstructions["methods"], Defined> + > = MakeInstructions["methods"], Defined>, > = Omit< AProgram, "rpc" | "state" | "account" | "transaction" | "instruction" @@ -202,7 +202,7 @@ type AnchorTypeDefs = { export type AnchorDefined< T extends Idl, - D = Record + D = Record, > = AnchorTypeDefs, D>; export type AnchorAccounts = AnchorTypeDefs< @@ -219,7 +219,7 @@ export type AnchorTypes< T extends Idl, AccountMap = Record, D = Record, - DEF = AnchorDefined + DEF = AnchorDefined, > = { Defined: DEF; Accounts: AnchorAccounts; diff --git a/packages/anchor-contrib/src/utils/accounts.ts b/packages/anchor-contrib/src/utils/accounts.ts index 9c377bda7..a1959a7e7 100644 --- a/packages/anchor-contrib/src/utils/accounts.ts +++ b/packages/anchor-contrib/src/utils/accounts.ts @@ -40,7 +40,7 @@ export type AnchorAccountMap = { export const generateAnchorAccounts = ( programID: PublicKey, accounts: IdlTypeDef[], - coder: AccountsCoder + coder: AccountsCoder, ): AnchorAccountMap => { const parsers: Partial> = {}; accounts.forEach((account) => { diff --git a/packages/anchor-contrib/src/utils/coder.ts b/packages/anchor-contrib/src/utils/coder.ts index fbef3f50d..18de3c85c 100644 --- a/packages/anchor-contrib/src/utils/coder.ts +++ b/packages/anchor-contrib/src/utils/coder.ts @@ -110,20 +110,20 @@ export class SuperCoder { /** * Program IDL. */ - readonly idl: T["IDL"] + readonly idl: T["IDL"], ) { this.coder = new BorshCoder>(idl); this.eventParser = new EventParser(address, this.coder); this.accounts = generateAnchorAccounts( address, idl.accounts ?? [], - this.coder.accounts + this.coder.accounts, ); this.errorMap = generateErrorMap(idl); const accountsList = Object.values( - this.accounts + this.accounts, ) as AnchorAccount[]; const accountTypeDefs: Partial> = {}; accountsList.forEach((account) => { @@ -132,16 +132,18 @@ export class SuperCoder { this.accountParsers = generateAccountParsersFromCoder( idl.accounts?.map((acc) => acc.name), - this.coder.accounts + this.coder.accounts, ); this.accountTypeDefs = accountTypeDefs as AccountTypeDefMap; this.discriminators = accountsList.reduce( (acc, el) => ({ ...acc, [el.discriminator.toString("hex")]: el.name }), - {} + {}, ); this.discriminatorsByAccount = accountsList.reduce( (acc, el) => ({ ...acc, [el.name]: el.discriminator }), - {} as { [K in NonNullable[number]["name"]]: Buffer } + {} as { + [K in NonNullable[number]["name"]]: Buffer; + }, ); } @@ -169,7 +171,7 @@ export class SuperCoder { * @returns */ parseProgramLogEvents< - E extends T["Events"][keyof T["Events"]] = T["Events"][keyof T["Events"]] + E extends T["Events"][keyof T["Events"]] = T["Events"][keyof T["Events"]], >(logs?: string[]): readonly E[] { if (!logs) { return []; @@ -191,11 +193,11 @@ export class SuperCoder { encodeIX< K extends keyof T["Instructions"] & string = keyof T["Instructions"] & string, - I extends T["Instructions"][K] = T["Instructions"][K] + I extends T["Instructions"][K] = T["Instructions"][K], >( name: K, args: I["namedArgs"], - accounts: Accounts + accounts: Accounts, ): TransactionInstruction { const idlIx = this.idl.instructions.find((ix) => ix.name === name); if (!idlIx) { @@ -205,7 +207,7 @@ export class SuperCoder { const keys = InstructionNamespaceFactory.accountsArray( accounts, idlIx.accounts, - name + name, ); return new TransactionInstruction({ programId: this.address, @@ -250,21 +252,21 @@ export class SuperCoder { export const buildCoderMap = < P extends { [K in keyof P]: CoderAnchorTypes; - } + }, >( idls: { [K in keyof P]: Idl; }, addresses: { [K in keyof P]: PublicKey; - } + }, ): { [K in keyof P]: SuperCoder; } => { return mapValues( idls, (idl: P[K]["IDL"], k: K) => - new SuperCoder(addresses[k], idl) + new SuperCoder(addresses[k], idl), ) as unknown as { [K in keyof P]: SuperCoder; }; diff --git a/packages/anchor-contrib/src/utils/programs.ts b/packages/anchor-contrib/src/utils/programs.ts index e1ded504b..ca0d33551 100644 --- a/packages/anchor-contrib/src/utils/programs.ts +++ b/packages/anchor-contrib/src/utils/programs.ts @@ -20,12 +20,12 @@ import { makeAnchorProvider } from "./provider.js"; export const newProgram =

( idl: Idl, address: PublicKey, - provider: SaberProvider | ReadonlySaberProvider + provider: SaberProvider | ReadonlySaberProvider, ) => { return new Program( idl, address.toString(), - makeAnchorProvider(provider) + makeAnchorProvider(provider), ) as unknown as P; }; @@ -43,12 +43,12 @@ export const newProgramMap =

( }, addresses: { [K in keyof P]: PublicKey; - } + }, ): { [K in keyof P]: P[K]; } => { return mapValues(idls, (idl, k: keyof P) => - newProgram(idl, addresses[k], provider) + newProgram(idl, addresses[k], provider), ) as unknown as { [K in keyof P]: P[K]; }; diff --git a/packages/anchor-contrib/src/utils/provider.ts b/packages/anchor-contrib/src/utils/provider.ts index 6dcc725b2..d60bc89e4 100644 --- a/packages/anchor-contrib/src/utils/provider.ts +++ b/packages/anchor-contrib/src/utils/provider.ts @@ -43,7 +43,7 @@ export const AnchorProviderClass: AnchorProviderCtor & export type AnchorProviderCtor = new ( connection: Connection, wallet: Wallet, - opts: ConfirmOptions + opts: ConfirmOptions, ) => AnchorProvider; /** @@ -57,7 +57,7 @@ export type AnchorProviderCtor = new ( export const buildAnchorProvider = ( connection: Connection, wallet: Wallet, - opts: ConfirmOptions + opts: ConfirmOptions, ) => { return new AnchorProviderClass(connection, wallet, opts); }; @@ -68,7 +68,7 @@ export const buildAnchorProvider = ( * @returns */ export const makeReadonlySaberProvider = ( - anchorProvider: IAnchorProvider + anchorProvider: IAnchorProvider, ): ReadonlySaberProvider => { return new SolanaReadonlyProvider(anchorProvider.connection); }; @@ -79,7 +79,7 @@ export const makeReadonlySaberProvider = ( * @returns */ export const makeSaberProvider = ( - anchorProvider: AnchorProvider + anchorProvider: AnchorProvider, ): SaberProvider => { return SolanaProvider.init({ connection: anchorProvider.connection, @@ -94,11 +94,11 @@ export const makeSaberProvider = ( * @returns */ export const makeAnchorProvider = ( - saberProvider: ReadonlySaberProvider + saberProvider: ReadonlySaberProvider, ): AnchorProvider => { return buildAnchorProvider( saberProvider.connection, saberProvider.wallet, - saberProvider.opts + saberProvider.opts, ); }; diff --git a/packages/chai-solana/src/expectTXTable.ts b/packages/chai-solana/src/expectTXTable.ts index b767b1c0d..1d2a3d08b 100644 --- a/packages/chai-solana/src/expectTXTable.ts +++ b/packages/chai-solana/src/expectTXTable.ts @@ -50,7 +50,7 @@ export const expectTXTable = ( } = { verbosity: null, formatLogs: true, - } + }, ): Chai.PromisedAssertion => { if (tx === null) { throw new Error(); @@ -60,7 +60,7 @@ export const expectTXTable = ( const callStack = new Error().stack?.split("\n"); if (callStack) { const expectIndex = callStack.findIndex((l) => - l.includes(`at ${expectTXTable.name}`) + l.includes(`at ${expectTXTable.name}`), ); if (expectIndex > 0) { const targetLine = callStack[expectIndex + 1]; @@ -68,7 +68,7 @@ export const expectTXTable = ( const cwd = process.cwd(); // get the part of targetLine after cwd const targetLineAfterCwd = targetLine.substring( - targetLine.indexOf(cwd) + cwd.length + targetLine.indexOf(cwd) + cwd.length, ); if (targetLineAfterCwd.length > 0) { relativePath = targetLineAfterCwd.substring(1); @@ -85,7 +85,7 @@ export const expectTXTable = ( printTXTable( tx, simulation.value.logs, - `${msg ? msg + " " : ""}${relativePath ? `(${relativePath})` : ""}` + `${msg ? msg + " " : ""}${relativePath ? `(${relativePath})` : ""}`, ); } @@ -110,7 +110,7 @@ export const expectTXTable = ( const curLine = logs[i]; if (curLine) { const errorCode = curLine.match( - /Program log: Custom program error: (0x[0-9a-f]*)/ + /Program log: Custom program error: (0x[0-9a-f]*)/, ); if (errorCode && errorCode[1]) { const programIdMatch = lastLine.split(" "); @@ -118,7 +118,7 @@ export const expectTXTable = ( if (programIdMatch && programIdMatch[1]) { console.log( ` Program ${programIdMatch[1]} error:`, - Number(errorCode[1]) + Number(errorCode[1]), ); } } @@ -146,7 +146,7 @@ export const expectTXTable = ( */ export const assertTXSuccess = ( tx: TransactionEnvelope, - msg?: string + msg?: string, ): Chai.PromisedAssertion => { return expectTX(tx, msg).to.be.fulfilled; }; @@ -160,7 +160,7 @@ export const assertTXSuccess = ( export const assertTXThrows = ( tx: TransactionEnvelope, err: IdlErrorCode, - msg?: string + msg?: string, ): Chai.PromisedAssertion => { return expectTX(tx, msg).to.be.rejectedWith(matchError(err)); }; @@ -174,7 +174,7 @@ export const assertTXThrows = ( export const assertTXThrowsCode = ( tx: TransactionEnvelope, code: number, - msg?: string + msg?: string, ): Chai.PromisedAssertion => { return expectTX(tx, msg).to.be.rejectedWith(matchErrorCode(code)); }; diff --git a/packages/chai-solana/src/index.ts b/packages/chai-solana/src/index.ts index e5739e3e7..776f512da 100644 --- a/packages/chai-solana/src/index.ts +++ b/packages/chai-solana/src/index.ts @@ -30,7 +30,7 @@ export const chaiSolana: Chai.ChaiPlugin = (chai) => { const obj = this._obj as unknown; const equal: Chai.TokenAmountAssertion["equal"] = function ( value, - message + message, ) { const amount = value instanceof TokenAmount ? value.toU64() : value; const msgPrefix = message ? `${message}: ` : ""; @@ -50,7 +50,7 @@ export const chaiSolana: Chai.ChaiPlugin = (chai) => { address: myAmount.token.address, decimals: myAmount.token.decimals, network: myAmount.token.network, - } + }, ); } @@ -60,7 +60,7 @@ export const chaiSolana: Chai.ChaiPlugin = (chai) => { `${msgPrefix}expected #{this} to equal #{exp} but got #{act}`, `${msgPrefix}expected #{this} to not equal #{exp} but got #{act}`, otherAmt.format(), - myAmount.format() + myAmount.format(), ); }; return { @@ -71,7 +71,7 @@ export const chaiSolana: Chai.ChaiPlugin = (chai) => { equal(0); }, }; - } + }, ); chai.Assertion.addMethod( @@ -86,7 +86,7 @@ export const chaiSolana: Chai.ChaiPlugin = (chai) => { "expected #{this} to be a PublicKey or address string", "expected #{this} to not be a PublicKey or address string", true, - obj + obj, ); const key = obj as Address; @@ -101,9 +101,9 @@ export const chaiSolana: Chai.ChaiPlugin = (chai) => { `${msgPrefix}expected #{this} to equal #{exp} but got #{act}`, `${msgPrefix}expected #{this} to not equal #{act}`, otherKey.toString(), - myKey.toString() + myKey.toString(), ); - } + }, ); chai.Assertion.addMethod( @@ -118,7 +118,7 @@ export const chaiSolana: Chai.ChaiPlugin = (chai) => { `${msgPrefix}token mismatch: #{this} to equal #{exp} but got #{act}`, `${msgPrefix}token mismatch: expected #{this} to not equal #{act}`, myAmount.token, - other.token + other.token, ); this.assert( @@ -126,9 +126,9 @@ export const chaiSolana: Chai.ChaiPlugin = (chai) => { `${msgPrefix}expected #{this} to equal #{exp} but got #{act}`, `${msgPrefix}expected #{this} to not equal #{act}`, myAmount.toString(), - other.toString() + other.toString(), ); - } + }, ); }); }; diff --git a/packages/chai-solana/src/printInstructionLogs.ts b/packages/chai-solana/src/printInstructionLogs.ts index 0a0b5a3e1..5a404c37a 100644 --- a/packages/chai-solana/src/printInstructionLogs.ts +++ b/packages/chai-solana/src/printInstructionLogs.ts @@ -8,7 +8,7 @@ import { default as colors } from "colors/safe.js"; * @param logs */ export const formatInstructionLogsForConsole = ( - logs: readonly InstructionLogs[] + logs: readonly InstructionLogs[], ): string => logs .map((log, i) => { @@ -48,7 +48,7 @@ export const printSendTransactionError = (err: SendTransactionError) => { } catch (e) { console.warn( colors.yellow("Could not print logs due to error. Printing raw logs"), - e + e, ); console.log(err.logs?.join("\n")); } diff --git a/packages/chai-solana/src/utils.ts b/packages/chai-solana/src/utils.ts index d679bdfbf..e3a95f8dd 100644 --- a/packages/chai-solana/src/utils.ts +++ b/packages/chai-solana/src/utils.ts @@ -20,7 +20,7 @@ import { assert, expect } from "chai"; export const expectTX = ( tx: PromiseOrValue, msg?: string, - cb?: (receipt: TransactionReceipt) => Promise + cb?: (receipt: TransactionReceipt) => Promise, ): Chai.PromisedAssertion => { const handleReceipt = async (receipt: TransactionReceipt) => { await cb?.(receipt); @@ -37,7 +37,7 @@ export const expectTX = ( return await confirmTransactionLike(v); }) .then(handleReceipt), - msg + msg, ).eventually; } else if (tx) { return expect(confirmTransactionLike(tx).then(handleReceipt), msg) diff --git a/packages/option-utils/src/index.ts b/packages/option-utils/src/index.ts index dfd442f1b..4887b3b6a 100644 --- a/packages/option-utils/src/index.ts +++ b/packages/option-utils/src/index.ts @@ -28,7 +28,7 @@ export const mapN = ( return fn( ...(args as { [K in keyof T]: NonNullable; - }) + }), ); }; @@ -45,7 +45,7 @@ export const mapN = ( */ export const mapSome = ( obj: NonNullable | null | undefined, - fn: (obj: NonNullable) => U + fn: (obj: NonNullable) => U, ): U | null | undefined => (exists(obj) ? fn(obj) : obj); /** @@ -67,7 +67,7 @@ export const isNotNull = (value: TValue | null): value is TValue => { * @returns */ export const isNotUndefined = ( - value: TValue | undefined + value: TValue | undefined, ): value is TValue => { return value !== undefined; }; @@ -79,7 +79,7 @@ export const isNotUndefined = ( * @returns */ export const exists = ( - value: TValue | null | undefined + value: TValue | null | undefined, ): value is TValue => { return value !== null && value !== undefined; }; diff --git a/packages/solana-contrib/src/broadcaster/index.ts b/packages/solana-contrib/src/broadcaster/index.ts index e8e4bae35..a03535887 100644 --- a/packages/solana-contrib/src/broadcaster/index.ts +++ b/packages/solana-contrib/src/broadcaster/index.ts @@ -70,14 +70,14 @@ export interface BroadcastOptions export class SingleConnectionBroadcaster implements Broadcaster { constructor( readonly sendConnection: Connection, - readonly opts: ConfirmOptions = DEFAULT_PROVIDER_OPTIONS + readonly opts: ConfirmOptions = DEFAULT_PROVIDER_OPTIONS, ) {} /** * @inheritdoc */ async getLatestBlockhash( - commitment: Commitment = this.opts.commitment ?? "confirmed" + commitment: Commitment = this.opts.commitment ?? "confirmed", ): Promise { return await this.sendConnection.getLatestBlockhash(commitment); } @@ -86,7 +86,7 @@ export class SingleConnectionBroadcaster implements Broadcaster { * @inheritdoc */ async getRecentBlockhash( - commitment: Commitment = this.opts.commitment ?? "confirmed" + commitment: Commitment = this.opts.commitment ?? "confirmed", ): Promise { const result = await this.sendConnection.getLatestBlockhash(commitment); return result.blockhash; @@ -97,7 +97,7 @@ export class SingleConnectionBroadcaster implements Broadcaster { */ async broadcast( tx: Transaction, - { printLogs = true, ...opts }: BroadcastOptions = this.opts + { printLogs = true, ...opts }: BroadcastOptions = this.opts, ): Promise { if (tx.signatures.length === 0) { throw new Error("Transaction must be signed before broadcasting."); @@ -107,7 +107,7 @@ export class SingleConnectionBroadcaster implements Broadcaster { if (printLogs) { return new PendingTransaction( this.sendConnection, - await sendAndSpamRawTx(this.sendConnection, rawTx, opts, opts) + await sendAndSpamRawTx(this.sendConnection, rawTx, opts, opts), ); } @@ -115,7 +115,7 @@ export class SingleConnectionBroadcaster implements Broadcaster { // hide the logs of TX errors if printLogs = false return new PendingTransaction( this.sendConnection, - await sendAndSpamRawTx(this.sendConnection, rawTx, opts, opts) + await sendAndSpamRawTx(this.sendConnection, rawTx, opts, opts), ); }); } @@ -134,7 +134,7 @@ export class SingleConnectionBroadcaster implements Broadcaster { } = { commitment: this.opts.preflightCommitment ?? "confirmed", verifySigners: true, - } + }, ): Promise> { if (verifySigners && tx.signatures.length === 0) { throw new Error("Transaction must be signed before simulating."); @@ -142,7 +142,7 @@ export class SingleConnectionBroadcaster implements Broadcaster { return await simulateTransactionWithCommitment( this.sendConnection, tx, - commitment + commitment, ); } } @@ -153,15 +153,15 @@ export class SingleConnectionBroadcaster implements Broadcaster { export class MultipleConnectionBroadcaster implements Broadcaster { constructor( readonly connections: readonly Connection[], - readonly opts: ConfirmOptions = DEFAULT_PROVIDER_OPTIONS + readonly opts: ConfirmOptions = DEFAULT_PROVIDER_OPTIONS, ) {} async getLatestBlockhash( - commitment: Commitment = this.opts.preflightCommitment ?? "confirmed" + commitment: Commitment = this.opts.preflightCommitment ?? "confirmed", ): Promise { try { const result = await Promise.any( - this.connections.map((conn) => conn.getLatestBlockhash(commitment)) + this.connections.map((conn) => conn.getLatestBlockhash(commitment)), ); return result; } catch (e) { @@ -174,11 +174,11 @@ export class MultipleConnectionBroadcaster implements Broadcaster { } async getRecentBlockhash( - commitment: Commitment = this.opts.preflightCommitment ?? "confirmed" + commitment: Commitment = this.opts.preflightCommitment ?? "confirmed", ): Promise { try { const result = await Promise.any( - this.connections.map((conn) => conn.getLatestBlockhash(commitment)) + this.connections.map((conn) => conn.getLatestBlockhash(commitment)), ); return result.blockhash; } catch (e) { @@ -192,16 +192,16 @@ export class MultipleConnectionBroadcaster implements Broadcaster { private async _sendRawTransaction( encoded: Buffer, - options?: SendOptions & Pick + options?: SendOptions & Pick, ): Promise { try { return await Promise.any( this.connections.map(async (connection) => { return new PendingTransaction( connection, - await sendAndSpamRawTx(connection, encoded, options ?? this.opts) + await sendAndSpamRawTx(connection, encoded, options ?? this.opts), ); - }) + }), ); } catch (e) { if (e instanceof AggregateError) { @@ -222,7 +222,7 @@ export class MultipleConnectionBroadcaster implements Broadcaster { */ async broadcast( tx: Transaction, - { printLogs = true, ...opts }: BroadcastOptions = this.opts + { printLogs = true, ...opts }: BroadcastOptions = this.opts, ): Promise { if (tx.signatures.length === 0) { throw new Error("Transaction must be signed before broadcasting."); @@ -259,7 +259,7 @@ export class MultipleConnectionBroadcaster implements Broadcaster { commitment: this.opts.preflightCommitment ?? this.opts.commitment ?? "confirmed", verifySigners: true, - } + }, ): Promise> { if (verifySigners && tx.signatures.length === 0) { throw new Error("Transaction must be signed before simulating."); @@ -270,9 +270,9 @@ export class MultipleConnectionBroadcaster implements Broadcaster { return await simulateTransactionWithCommitment( connection, tx, - commitment + commitment, ); - }) + }), ); } catch (e) { if (e instanceof AggregateError) { diff --git a/packages/solana-contrib/src/broadcaster/sendAndSpamRawTx.ts b/packages/solana-contrib/src/broadcaster/sendAndSpamRawTx.ts index c5631f956..7d75c54a3 100644 --- a/packages/solana-contrib/src/broadcaster/sendAndSpamRawTx.ts +++ b/packages/solana-contrib/src/broadcaster/sendAndSpamRawTx.ts @@ -17,7 +17,7 @@ export const sendAndSpamRawTx = async ( { retryTimes = DEFAULT_RETRY_OPTIONS.retryTimes, retryInterval = DEFAULT_RETRY_OPTIONS.retryInterval, - }: TransactionRetryOptions = DEFAULT_RETRY_OPTIONS + }: TransactionRetryOptions = DEFAULT_RETRY_OPTIONS, ) => { const result = await connection.sendRawTransaction(rawTx, sendOptions); // if we could send the TX with preflight, let's spam it. diff --git a/packages/solana-contrib/src/broadcaster/tiered.ts b/packages/solana-contrib/src/broadcaster/tiered.ts index 9ac761be0..f4d469cb9 100644 --- a/packages/solana-contrib/src/broadcaster/tiered.ts +++ b/packages/solana-contrib/src/broadcaster/tiered.ts @@ -34,29 +34,29 @@ export class TieredBroadcaster implements Broadcaster { * Connections to send to in addition to the primary. */ readonly fallbackConnections: readonly Connection[], - readonly opts: ConfirmOptions = DEFAULT_PROVIDER_OPTIONS + readonly opts: ConfirmOptions = DEFAULT_PROVIDER_OPTIONS, ) { this.premiumBroadcaster = new SingleConnectionBroadcaster( primaryConnection, - opts + opts, ); } async getLatestBlockhash( - commitment: Commitment = this.opts.preflightCommitment ?? "confirmed" + commitment: Commitment = this.opts.preflightCommitment ?? "confirmed", ): Promise { return await this.premiumBroadcaster.getLatestBlockhash(commitment); } async getRecentBlockhash( - commitment: Commitment = this.opts.preflightCommitment ?? "confirmed" + commitment: Commitment = this.opts.preflightCommitment ?? "confirmed", ): Promise { return await this.premiumBroadcaster.getRecentBlockhash(commitment); } private async _sendRawTransaction( encoded: Buffer, - options?: SendOptions & Omit + options?: SendOptions & Omit, ): Promise { const pending = new PendingTransaction( this.primaryConnection, @@ -64,8 +64,8 @@ export class TieredBroadcaster implements Broadcaster { this.primaryConnection, encoded, options ?? this.opts, - options ?? DEFAULT_RETRY_OPTIONS - ) + options ?? DEFAULT_RETRY_OPTIONS, + ), ); void (async () => { await Promise.all( @@ -75,12 +75,12 @@ export class TieredBroadcaster implements Broadcaster { fc, encoded, options ?? this.opts, - options?.fallbackRetryOptions ?? DEFAULT_FALLBACK_RETRY_OPTIONS + options?.fallbackRetryOptions ?? DEFAULT_FALLBACK_RETRY_OPTIONS, ); } catch (e) { console.warn(`[Broadcaster] _sendRawTransaction error`, e); } - }) + }), ); })(); return pending; @@ -96,7 +96,7 @@ export class TieredBroadcaster implements Broadcaster { */ async broadcast( tx: Transaction, - { printLogs = true, ...opts }: BroadcastOptions = this.opts + { printLogs = true, ...opts }: BroadcastOptions = this.opts, ): Promise { if (tx.signatures.length === 0) { throw new Error("Transaction must be signed before broadcasting."); @@ -130,7 +130,7 @@ export class TieredBroadcaster implements Broadcaster { } = { commitment: this.opts.preflightCommitment ?? "confirmed", verifySigners: true, - } + }, ): Promise> { if (verifySigners && tx.signatures.length === 0) { throw new Error("Transaction must be signed before simulating."); diff --git a/packages/solana-contrib/src/computeBudget/index.ts b/packages/solana-contrib/src/computeBudget/index.ts index f3621519d..15b1fef3f 100644 --- a/packages/solana-contrib/src/computeBudget/index.ts +++ b/packages/solana-contrib/src/computeBudget/index.ts @@ -5,7 +5,7 @@ import { PublicKey } from "@solana/web3.js"; * Source: https://github.com/solana-labs/solana/blob/master/program-runtime/src/compute_budget.rs#L101 */ export const COMPUTE_BUDGET_PROGRAM = new PublicKey( - "ComputeBudget111111111111111111111111111111" + "ComputeBudget111111111111111111111111111111", ); export * from "./instructions.js"; diff --git a/packages/solana-contrib/src/computeBudget/instructions.ts b/packages/solana-contrib/src/computeBudget/instructions.ts index 2b3ba1436..ebdeb7cf6 100644 --- a/packages/solana-contrib/src/computeBudget/instructions.ts +++ b/packages/solana-contrib/src/computeBudget/instructions.ts @@ -9,7 +9,7 @@ import { RequestHeapFrameLayout, RequestUnitsLayout } from "./layouts.js"; */ export const requestComputeUnitsInstruction = ( units: number, - additionalFee: number + additionalFee: number, ): TransactionInstruction => { const data = Buffer.alloc(RequestUnitsLayout.span); RequestUnitsLayout.encode({ instruction: 0, units, additionalFee }, data); @@ -26,7 +26,7 @@ export const requestComputeUnitsInstruction = ( * size applies to each program executed, including all calls to CPIs. */ export const requestHeapFrameInstruction = ( - bytes: number + bytes: number, ): TransactionInstruction => { const data = Buffer.alloc(RequestHeapFrameLayout.span); RequestHeapFrameLayout.encode({ instruction: 1, bytes }, data); diff --git a/packages/solana-contrib/src/interfaces.ts b/packages/solana-contrib/src/interfaces.ts index 32f9a637b..ad96fb8c6 100644 --- a/packages/solana-contrib/src/interfaces.ts +++ b/packages/solana-contrib/src/interfaces.ts @@ -86,7 +86,7 @@ export interface Broadcaster { * @param commitment */ getLatestBlockhash( - commitment?: Commitment + commitment?: Commitment, ): Promise; /** @@ -103,7 +103,7 @@ export interface Broadcaster { */ broadcast: ( tx: Transaction, - opts?: BroadcastOptions + opts?: BroadcastOptions, ) => Promise; /** @@ -117,7 +117,7 @@ export interface Broadcaster { opts: { commitment?: Commitment; verifySigners?: boolean; - } + }, ): Promise>; } @@ -146,7 +146,7 @@ export interface TransactionSigner { */ signAndBroadcastTransaction( transaction: Transaction, - opts?: SignAndBroadcastOptions + opts?: SignAndBroadcastOptions, ): Promise; /** @@ -160,7 +160,7 @@ export interface TransactionSigner { sign: ( tx: Transaction, signers?: readonly (Signer | undefined)[], - opts?: ConfirmOptions + opts?: ConfirmOptions, ) => Promise; /** @@ -168,7 +168,7 @@ export interface TransactionSigner { */ signAll: ( reqs: readonly SendTxRequest[], - opts?: ConfirmOptions + opts?: ConfirmOptions, ) => Promise; } @@ -215,7 +215,7 @@ export interface Provider extends ReadonlyProvider { send: ( tx: Transaction, signers?: (Signer | undefined)[], - opts?: ConfirmOptions + opts?: ConfirmOptions, ) => Promise; /** @@ -223,7 +223,7 @@ export interface Provider extends ReadonlyProvider { */ sendAll: ( reqs: readonly SendTxRequest[], - opts?: ConfirmOptions + opts?: ConfirmOptions, ) => Promise; /** @@ -235,7 +235,7 @@ export interface Provider extends ReadonlyProvider { */ signAndBroadcastTransaction( transaction: Transaction, - opts?: SignAndBroadcastOptions + opts?: SignAndBroadcastOptions, ): Promise; /** @@ -249,7 +249,7 @@ export interface Provider extends ReadonlyProvider { simulate: ( tx: Transaction, signers?: (Signer | undefined)[], - opts?: ConfirmOptions + opts?: ConfirmOptions, ) => Promise>; } diff --git a/packages/solana-contrib/src/provider.ts b/packages/solana-contrib/src/provider.ts index cfaa6d1be..3f1c45bfc 100644 --- a/packages/solana-contrib/src/provider.ts +++ b/packages/solana-contrib/src/provider.ts @@ -48,7 +48,7 @@ export class SolanaReadonlyProvider implements ReadonlyProvider { constructor( readonly connection: Connection, readonly opts: ConfirmOptions = DEFAULT_PROVIDER_OPTIONS, - readonly publicKey: PublicKey = DEFAULT_READONLY_PUBLIC_KEY + readonly publicKey: PublicKey = DEFAULT_READONLY_PUBLIC_KEY, ) { this.wallet = { ...this.wallet, @@ -70,7 +70,7 @@ export class SolanaReadonlyProvider implements ReadonlyProvider { async getAccountInfo(accountId: PublicKey): Promise { const accountInfo = await this.connection.getAccountInfo( accountId, - this.opts.commitment + this.opts.commitment, ); if (!accountInfo) { return null; @@ -86,7 +86,7 @@ export const doSignAndBroadcastTransaction = async ( wallet: Pick, transaction: Transaction, broadcaster: Broadcaster, - opts?: SignAndBroadcastOptions + opts?: SignAndBroadcastOptions, ): Promise => { const tx = await wallet.signTransaction(transaction); if (opts?.signers && opts.signers.length > 0) { @@ -102,7 +102,7 @@ export class SolanaTransactionSigner implements TransactionSigner { constructor( readonly wallet: Wallet, readonly broadcaster: Broadcaster, - readonly preflightCommitment: Commitment = "confirmed" + readonly preflightCommitment: Commitment = "confirmed", ) {} get publicKey(): PublicKey { @@ -111,13 +111,13 @@ export class SolanaTransactionSigner implements TransactionSigner { async signAndBroadcastTransaction( transaction: Transaction, - opts?: SignAndBroadcastOptions | undefined + opts?: SignAndBroadcastOptions | undefined, ): Promise { return await doSignAndBroadcastTransaction( this.wallet, transaction, this.broadcaster, - opts + opts, ); } @@ -134,7 +134,7 @@ export class SolanaTransactionSigner implements TransactionSigner { signers: readonly (Signer | undefined)[] = [], opts: ConfirmOptions = { preflightCommitment: this.preflightCommitment, - } + }, ): Promise { const { blockhash, lastValidBlockHeight } = await this.broadcaster.getLatestBlockhash(opts.preflightCommitment); @@ -159,7 +159,7 @@ export class SolanaTransactionSigner implements TransactionSigner { reqs: readonly SendTxRequest[], opts: ConfirmOptions = { preflightCommitment: this.preflightCommitment, - } + }, ): Promise { const { blockhash, lastValidBlockHeight } = await this.broadcaster.getLatestBlockhash(opts.preflightCommitment); @@ -204,15 +204,15 @@ export class SolanaProvider extends SolanaReadonlyProvider implements Provider { readonly signer: TransactionSigner = new SolanaTransactionSigner( wallet, broadcaster, - opts.preflightCommitment - ) + opts.preflightCommitment, + ), ) { super(connection, opts); } async signAndBroadcastTransaction( transaction: Transaction, - opts?: SignAndBroadcastOptions + opts?: SignAndBroadcastOptions, ): Promise { return await this.signer.signAndBroadcastTransaction(transaction, opts); } @@ -248,7 +248,7 @@ export class SolanaProvider extends SolanaReadonlyProvider implements Provider { connection, new SingleConnectionBroadcaster(sendConnection, opts), wallet, - opts + opts, ); } @@ -281,7 +281,7 @@ export class SolanaProvider extends SolanaReadonlyProvider implements Provider { const firstBroadcastConnection = broadcastConnections[0]; invariant( firstBroadcastConnection, - "must have at least one broadcast connection" + "must have at least one broadcast connection", ); return new SolanaProvider( connection, @@ -289,7 +289,7 @@ export class SolanaProvider extends SolanaReadonlyProvider implements Provider { ? new TieredBroadcaster(connection, broadcastConnections, opts) : new SingleConnectionBroadcaster(firstBroadcastConnection, opts), wallet, - opts + opts, ); } @@ -304,7 +304,7 @@ export class SolanaProvider extends SolanaReadonlyProvider implements Provider { async send( tx: Transaction, signers: (Signer | undefined)[] = [], - opts: ConfirmOptions = this.opts + opts: ConfirmOptions = this.opts, ): Promise { const theTx = await this.signer.sign(tx, signers, opts); const pending = await this.broadcaster.broadcast(theTx, opts); @@ -317,7 +317,7 @@ export class SolanaProvider extends SolanaReadonlyProvider implements Provider { */ async sendAll( reqs: readonly SendTxRequest[], - opts: ConfirmOptions = this.opts + opts: ConfirmOptions = this.opts, ): Promise { const txs = await this.signer.signAll(reqs, opts); return await Promise.all( @@ -325,7 +325,7 @@ export class SolanaProvider extends SolanaReadonlyProvider implements Provider { const pending = await this.broadcaster.broadcast(tx, opts); await pending.wait(); return pending; - }) + }), ); } @@ -341,7 +341,7 @@ export class SolanaProvider extends SolanaReadonlyProvider implements Provider { async simulate( tx: Transaction, signers: (Signer | undefined)[] | undefined, - opts: ConfirmOptions = this.opts + opts: ConfirmOptions = this.opts, ): Promise> { let simTX = tx; if (signers !== undefined) { @@ -371,7 +371,7 @@ export interface AugmentedProvider extends Provider { */ newTX: ( instructions?: (TransactionInstruction | null | undefined | boolean)[], - signers?: Signer[] + signers?: Signer[], ) => TransactionEnvelope; /** @@ -421,7 +421,7 @@ export class SolanaAugmentedProvider implements AugmentedProvider { signAndBroadcastTransaction( transaction: Transaction, - opts?: SignAndBroadcastOptions + opts?: SignAndBroadcastOptions, ): Promise { return this.provider.signAndBroadcastTransaction(transaction, opts); } @@ -429,14 +429,14 @@ export class SolanaAugmentedProvider implements AugmentedProvider { send( tx: Transaction, signers?: (Signer | undefined)[] | undefined, - opts?: ConfirmOptions | undefined + opts?: ConfirmOptions | undefined, ): Promise { return this.provider.send(tx, signers, opts); } sendAll( reqs: readonly SendTxRequest[], - opts?: ConfirmOptions | undefined + opts?: ConfirmOptions | undefined, ): Promise { return this.provider.sendAll(reqs, opts); } @@ -444,7 +444,7 @@ export class SolanaAugmentedProvider implements AugmentedProvider { simulate( tx: Transaction, signers?: (Signer | undefined)[] | undefined, - opts?: ConfirmOptions | undefined + opts?: ConfirmOptions | undefined, ): Promise> { return this.provider.simulate(tx, signers, opts); } @@ -461,7 +461,7 @@ export class SolanaAugmentedProvider implements AugmentedProvider { */ newTX( instructions: (TransactionInstruction | null | undefined | boolean)[] = [], - signers: Signer[] = [] + signers: Signer[] = [], ): TransactionEnvelope { return TransactionEnvelope.create(this, instructions, signers); } @@ -473,11 +473,11 @@ export class SolanaAugmentedProvider implements AugmentedProvider { */ async requestAirdrop( lamports: number, - to: PublicKey = this.wallet.publicKey + to: PublicKey = this.wallet.publicKey, ): Promise { return new PendingTransaction( this.connection, - await this.connection.requestAirdrop(to, lamports) + await this.connection.requestAirdrop(to, lamports), ); } @@ -492,8 +492,8 @@ export class SolanaAugmentedProvider implements AugmentedProvider { this.connection, this.broadcaster, new SignerWallet(signer), - this.opts - ) + this.opts, + ), ); } } diff --git a/packages/solana-contrib/src/transaction/PendingTransaction.ts b/packages/solana-contrib/src/transaction/PendingTransaction.ts index 6dbabdbb2..027e9bba8 100644 --- a/packages/solana-contrib/src/transaction/PendingTransaction.ts +++ b/packages/solana-contrib/src/transaction/PendingTransaction.ts @@ -40,7 +40,7 @@ export class PendingTransaction { constructor( readonly connection: Connection, - readonly signature: TransactionSignature + readonly signature: TransactionSignature, ) {} /** @@ -107,7 +107,7 @@ export class PendingTransaction { retries: 5, minTimeout: 500, ...retryOpts, - } + }, ); if (!receipt) { throw new Error("transaction could not be confirmed"); @@ -123,11 +123,11 @@ export class PendingTransaction { * @returns */ async awaitSignatureConfirmation( - commitment: Finality = "confirmed" + commitment: Finality = "confirmed", ): Promise { const { value } = await this.connection.confirmTransaction( this.signature, - commitment + commitment, ); if (value.err) { throw value.err; @@ -156,7 +156,7 @@ export class PendingTransaction { blockhash, lastValidBlockHeight, }, - commitment + commitment, ) ).value; } else { @@ -167,7 +167,7 @@ export class PendingTransaction { if (value.err) { throw new Error( - `Transaction ${this.signature} failed (${JSON.stringify(value)})` + `Transaction ${this.signature} failed (${JSON.stringify(value)})`, ); } diff --git a/packages/solana-contrib/src/transaction/TransactionEnvelope.ts b/packages/solana-contrib/src/transaction/TransactionEnvelope.ts index 0e3f0d072..fe03c8407 100644 --- a/packages/solana-contrib/src/transaction/TransactionEnvelope.ts +++ b/packages/solana-contrib/src/transaction/TransactionEnvelope.ts @@ -34,7 +34,7 @@ import { export const PACKET_DATA_SIZE = 1280 - 40 - 8; const ASSOCIATED_TOKEN_PROGRAM_ID = new PublicKey( - "ATokenGPvbdGVxr1b2hvZbsiqW5xWH25efTNsLJA8knL" + "ATokenGPvbdGVxr1b2hvZbsiqW5xWH25efTNsLJA8knL", ); /** @@ -44,14 +44,14 @@ const ASSOCIATED_TOKEN_PROGRAM_ID = new PublicKey( */ const filterRequiredSigners = ( ixs: TransactionInstruction[], - signers: Signer[] + signers: Signer[], ): Signer[] => { // filter out the signers required for the transaction const requiredSigners = ixs.flatMap((ix) => - ix.keys.filter((k) => k.isSigner).map((k) => k.pubkey) + ix.keys.filter((k) => k.isSigner).map((k) => k.pubkey), ); return signers.filter((s) => - requiredSigners.find((rs) => rs.equals(s.publicKey)) + requiredSigners.find((rs) => rs.equals(s.publicKey)), ); }; @@ -81,7 +81,7 @@ export class TransactionEnvelope { /** * Optional signers of the transaction. */ - readonly signers: Signer[] = [] + readonly signers: Signer[] = [], ) {} /** @@ -93,7 +93,7 @@ export class TransactionEnvelope { ...instructions: (TransactionInstruction | null | undefined | boolean)[] ): TransactionEnvelope { this.instructions.unshift( - ...instructions.filter((ix): ix is TransactionInstruction => !!ix) + ...instructions.filter((ix): ix is TransactionInstruction => !!ix), ); return this; } @@ -107,7 +107,7 @@ export class TransactionEnvelope { ...instructions: (TransactionInstruction | null | undefined | boolean)[] ): TransactionEnvelope { this.instructions.push( - ...instructions.filter((ix): ix is TransactionInstruction => !!ix) + ...instructions.filter((ix): ix is TransactionInstruction => !!ix), ); return this; } @@ -199,7 +199,7 @@ export class TransactionEnvelope { * @returns A list of {@link Transaction}s. */ buildPartition( - feePayer: PublicKey = this.provider.wallet.publicKey + feePayer: PublicKey = this.provider.wallet.publicKey, ): Transaction[] { const partition = this.partition(); return partition.map((env) => env.build(feePayer)); @@ -225,14 +225,14 @@ export class TransactionEnvelope { let lastTXEnv: TransactionEnvelope = new TransactionEnvelope( this.provider, this.instructions.slice(0, 1), - this._filterRequiredSigners(this.instructions.slice(0, 1)) + this._filterRequiredSigners(this.instructions.slice(0, 1)), ); let lastEstimation: number = lastTXEnv.estimateSizeUnsafe(); const txs: TransactionEnvelope[] = []; this.instructions.slice(1).forEach((ix, i) => { if (lastEstimation > PACKET_DATA_SIZE) { throw new Error( - `cannot construct a valid partition: instruction ${i} is too large (${lastEstimation} > ${PACKET_DATA_SIZE})` + `cannot construct a valid partition: instruction ${i} is too large (${lastEstimation} > ${PACKET_DATA_SIZE})`, ); } const nextIXs = [...lastTXEnv.instructions, ix]; @@ -240,7 +240,7 @@ export class TransactionEnvelope { const nextTXEnv = new TransactionEnvelope( this.provider, nextIXs, - nextSigners + nextSigners, ); const nextEstimation = nextTXEnv.estimateSizeUnsafe(); @@ -251,7 +251,7 @@ export class TransactionEnvelope { lastTXEnv = new TransactionEnvelope( this.provider, nextIXs, - this._filterRequiredSigners(nextIXs) + this._filterRequiredSigners(nextIXs), ); lastEstimation = lastTXEnv.estimateSizeUnsafe(); } else { @@ -293,12 +293,12 @@ export class TransactionEnvelope { simulate( opts: TXEnvelopeSimulateOptions = { verifySigners: true, - } + }, ): Promise> { return this.provider.simulate( this.build(), opts.verifySigners ? this.signers : undefined, - opts + opts, ); } @@ -310,7 +310,7 @@ export class TransactionEnvelope { * @returns */ simulateUnchecked( - opts: ConfirmOptions + opts: ConfirmOptions, ): Promise> { return this.simulate({ ...opts, verifySigners: false }); } @@ -340,7 +340,7 @@ export class TransactionEnvelope { * @returns */ simulateTable( - opts?: TXEnvelopeSimulateOptions + opts?: TXEnvelopeSimulateOptions, ): Promise> { return this.simulate(opts).then((simulation) => { if (simulation?.value?.logs) { @@ -359,7 +359,7 @@ export class TransactionEnvelope { const signed = await this.provider.signer.sign( this.build(), this.signers, - opts + opts, ); return this.provider.broadcaster.broadcast(signed, opts); } @@ -379,7 +379,7 @@ export class TransactionEnvelope { return new TransactionEnvelope( this.provider, [...this.instructions, ...other.instructions], - [...this.signers, ...other.signers] + [...this.signers, ...other.signers], ); } @@ -392,7 +392,7 @@ export class TransactionEnvelope { ...new Set([ ...this.instructions .map((inst) => - inst.keys.filter((key) => key.isWritable).map((k) => k.pubkey) + inst.keys.filter((key) => key.isWritable).map((k) => k.pubkey), ) .reduce((acc, el) => acc.concat(el)), ]).values(), @@ -428,7 +428,7 @@ export class TransactionEnvelope { (k, i) => ` [${i}] ${k.pubkey.toString()} ${ k.isWritable ? "(mut)" : "" - } ${k.isSigner ? "(signer)" : ""}` + } ${k.isSigner ? "(signer)" : ""}`, ), ` Data (base64): ${ser.data.toString("base64")}`, ].join("\n"); @@ -449,7 +449,7 @@ export class TransactionEnvelope { static create( provider: Provider, instructions: (TransactionInstruction | null | undefined | boolean)[], - signers: Signer[] = [] + signers: Signer[] = [], ): TransactionEnvelope { const ixs = instructions.filter((ix): ix is TransactionInstruction => !!ix); return new TransactionEnvelope(provider, ixs, signers); @@ -495,7 +495,7 @@ export class TransactionEnvelope { rest.forEach((addedTX, i) => { if (lastEstimation > PACKET_DATA_SIZE) { throw new Error( - `cannot construct a valid partition: instruction ${i} is too large (${lastEstimation} > ${PACKET_DATA_SIZE})` + `cannot construct a valid partition: instruction ${i} is too large (${lastEstimation} > ${PACKET_DATA_SIZE})`, ); } const nextIXs = [...lastTXEnv.instructions, ...addedTX.instructions]; @@ -541,7 +541,7 @@ export class TransactionEnvelope { */ static async sendAll( txs: TransactionEnvelope[], - opts?: ConfirmOptions + opts?: ConfirmOptions, ): Promise { const firstTX = txs[0]; if (!firstTX) { @@ -550,7 +550,7 @@ export class TransactionEnvelope { const provider = firstTX.provider; return await provider.sendAll( txs.map((tx) => ({ tx: tx.build(), signers: tx.signers })), - opts + opts, ); } @@ -630,10 +630,10 @@ export class TransactionEnvelope { */ addAdditionalComputeBudget( units: number, - additionalFee: number + additionalFee: number, ): TransactionEnvelope { this.instructions.unshift( - requestComputeUnitsInstruction(units, additionalFee) + requestComputeUnitsInstruction(units, additionalFee), ); return this; } diff --git a/packages/solana-contrib/src/transaction/TransactionReceipt.ts b/packages/solana-contrib/src/transaction/TransactionReceipt.ts index f74576f74..6bd21e3dd 100644 --- a/packages/solana-contrib/src/transaction/TransactionReceipt.ts +++ b/packages/solana-contrib/src/transaction/TransactionReceipt.ts @@ -28,7 +28,7 @@ export type TransactionLike = * @returns */ export const confirmTransactionLike = async ( - tx: PromiseOrValue + tx: PromiseOrValue, ): Promise => { const ish = await valueAsPromise(tx); if (ish instanceof TransactionReceipt) { @@ -58,7 +58,7 @@ export class TransactionReceipt { /** * Raw response from web3.js */ - readonly response: TransactionResponse | VersionedTransactionResponse + readonly response: TransactionResponse | VersionedTransactionResponse, ) {} /** diff --git a/packages/solana-contrib/src/transaction/parseTransactionLogs.ts b/packages/solana-contrib/src/transaction/parseTransactionLogs.ts index c386f7f2f..4a0a9cfa0 100644 --- a/packages/solana-contrib/src/transaction/parseTransactionLogs.ts +++ b/packages/solana-contrib/src/transaction/parseTransactionLogs.ts @@ -67,7 +67,7 @@ export interface InstructionLogs { */ export const parseTransactionLogs = ( logs: string[] | null, - error: TransactionError | null + error: TransactionError | null, ): InstructionLogs[] => { let depth = 0; const prettyLogs: InstructionLogs[] = []; @@ -201,7 +201,7 @@ const formatLogEntryString = (entry: InstructionLogEntry) => { */ export const formatLogEntry = ( entry: InstructionLogEntry, - prefix = false + prefix = false, ): string => { const prefixString = prefix ? buildPrefix(entry.depth) : ""; return `${prefixString}${formatLogEntryString(entry)}`; @@ -212,7 +212,7 @@ export const formatLogEntry = ( * @param logs */ export const formatInstructionLogs = ( - logs: readonly InstructionLogs[] + logs: readonly InstructionLogs[], ): string => logs .map((log, i) => { diff --git a/packages/solana-contrib/src/transaction/programErr.ts b/packages/solana-contrib/src/transaction/programErr.ts index 59926e1e3..7ea35b533 100644 --- a/packages/solana-contrib/src/transaction/programErr.ts +++ b/packages/solana-contrib/src/transaction/programErr.ts @@ -108,7 +108,7 @@ export type ProgramError = { }; export function getTransactionInstructionError( - error?: TransactionError | null + error?: TransactionError | null, ): ProgramError | undefined { if (!error) { return; diff --git a/packages/solana-contrib/src/transaction/utils.ts b/packages/solana-contrib/src/transaction/utils.ts index 080f74005..d392acad7 100644 --- a/packages/solana-contrib/src/transaction/utils.ts +++ b/packages/solana-contrib/src/transaction/utils.ts @@ -30,7 +30,7 @@ export const RECENT_BLOCKHASH_STUB = */ export const buildStubbedTransaction = ( cluster: Cluster, - ixs: TransactionInstruction[] + ixs: TransactionInstruction[], ): Transaction => { const tx = new Transaction(); tx.recentBlockhash = RECENT_BLOCKHASH_STUB; @@ -64,7 +64,7 @@ export const serializeToBase64Unchecked = (tx: Transaction): string => */ export const generateInspectLinkFromBase64 = ( cluster: Cluster, - base64TX: string + base64TX: string, ): string => { return `https://${ cluster === "mainnet-beta" ? "" : `${cluster}.` @@ -79,7 +79,7 @@ export const generateInspectLinkFromBase64 = ( */ export const generateUncheckedInspectLink = ( cluster: Cluster, - tx: Transaction + tx: Transaction, ): string => { return generateInspectLinkFromBase64(cluster, serializeToBase64Unchecked(tx)); }; diff --git a/packages/solana-contrib/src/utils/instructions.ts b/packages/solana-contrib/src/utils/instructions.ts index 4e09b2eb7..9398df6e7 100644 --- a/packages/solana-contrib/src/utils/instructions.ts +++ b/packages/solana-contrib/src/utils/instructions.ts @@ -4,7 +4,7 @@ import { PublicKey, TransactionInstruction } from "@solana/web3.js"; * ID of the memo program. */ export const MEMO_PROGRAM_ID = new PublicKey( - "MemoSq4gqABAXKb96qnH8TysNcWxMyWCqXgDLGmfcHr" + "MemoSq4gqABAXKb96qnH8TysNcWxMyWCqXgDLGmfcHr", ); /** @@ -18,7 +18,7 @@ export const MEMO_PROGRAM_ID = new PublicKey( */ export const createMemoInstruction = ( text: string, - signers: readonly PublicKey[] = [] + signers: readonly PublicKey[] = [], ): TransactionInstruction => { return new TransactionInstruction({ programId: MEMO_PROGRAM_ID, diff --git a/packages/solana-contrib/src/utils/printAccountOwners.ts b/packages/solana-contrib/src/utils/printAccountOwners.ts index 25c952416..658c7d649 100644 --- a/packages/solana-contrib/src/utils/printAccountOwners.ts +++ b/packages/solana-contrib/src/utils/printAccountOwners.ts @@ -37,7 +37,7 @@ import { PublicKey } from "@solana/web3.js"; */ export async function printAccountOwners( connection: Connection, - plainObj: object + plainObj: object, ): Promise { try { if (typeof plainObj !== "object") { @@ -47,13 +47,13 @@ export async function printAccountOwners( const callStack = new Error().stack?.split("\n"); if (callStack) { let expectIndex = callStack.findIndex((l) => - l.includes(`at ${printAccountOwners.name}`) + l.includes(`at ${printAccountOwners.name}`), ); // debugAccountOwners in chai-solana wraps printAccountOwners // We need to get the caller of debugAccountOwners instead const debugAccountOwnersIndex = callStack.findIndex((l) => - l.includes(`at debugAccountOwners`) + l.includes(`at debugAccountOwners`), ); if (debugAccountOwnersIndex > expectIndex) { expectIndex = debugAccountOwnersIndex; @@ -72,7 +72,7 @@ export async function printAccountOwners( const cwd = maybeProcess.cwd?.() || "/"; // get the part of targetLine after cwd const targetLineAfterCwd = targetLine.substring( - targetLine.indexOf(cwd) + cwd.length + targetLine.indexOf(cwd) + cwd.length, ); if (targetLineAfterCwd.length > 0) { relativePath = targetLineAfterCwd.substring(1).replace(/\)$/, ""); @@ -88,7 +88,7 @@ export async function printAccountOwners( if (relativePath) { console.log( relativePath, - await _transformAccountOwners(plainObj, connection) + await _transformAccountOwners(plainObj, connection), ); } else { console.log(await _transformAccountOwners(plainObj, connection)); @@ -117,7 +117,7 @@ type MaybeProcess = { */ async function gracefulGetMultipleAccountsInfo( connection: Connection, - publicKeys: PublicKey[] + publicKeys: PublicKey[], ): ReturnType { try { // To be honest, the web3 internals aren't going to change that much. And if @@ -148,13 +148,13 @@ async function gracefulGetMultipleAccountsInfo( type PublicKeyBase58 = string; type GetMultipleAccountsArgs = [ PublicKeyBase58[], - { encoding: "base64"; commitment: "confirmed" } + { encoding: "base64"; commitment: "confirmed" }, ]; interface ConnectionWithGetMultipleAccounts { _rpcRequest?: ( method: "getMultipleAccounts", - args: GetMultipleAccountsArgs + args: GetMultipleAccountsArgs, ) => Promise< | undefined | { @@ -172,7 +172,7 @@ interface ConnectionWithGetMultipleAccounts { */ const _transformAccountOwners = async ( plainObjWithAddressesAndBignums: object, - connection: Connection + connection: Connection, ): Promise => { /* eslint-disable */ const result: any = {}; diff --git a/packages/solana-contrib/src/utils/printTXTable.ts b/packages/solana-contrib/src/utils/printTXTable.ts index ae7e5f523..0f95966ac 100644 --- a/packages/solana-contrib/src/utils/printTXTable.ts +++ b/packages/solana-contrib/src/utils/printTXTable.ts @@ -34,7 +34,7 @@ import { TransactionEnvelope } from "../index.js"; export const printTXTable = ( tx: TransactionEnvelope, transactionLogs: string[], - message: string + message: string, ) => { if (message && message !== "") { console.log(estimateTransactionSize(tx), message); @@ -90,7 +90,7 @@ export const printTXTable = ( mar: marginalInstructionSize( tx.provider, tx.instructions.slice(0, i), - instruction + instruction, ), cum: instructionsSize(tx.provider, tx.instructions.slice(0, i + 1)), programId: instruction.programId.toBase58(), @@ -112,7 +112,10 @@ export class TXSizeEstimationError extends Error { } export class EstimatedTXTooBigError extends Error { - constructor(readonly tx: Transaction, readonly size: number) { + constructor( + readonly tx: Transaction, + readonly size: number, + ) { super(`Transaction too large`); this.name = "EstimatedTXTooBigError"; } @@ -133,7 +136,7 @@ export class EstimatedTXTooBigError extends Error { * Returns 9999 if the transaction was unable to be built. */ export const estimateTransactionSize = ( - txEnvelope: TransactionEnvelope + txEnvelope: TransactionEnvelope, ): number => { const result = txEnvelope.estimateSize(); if ("size" in result) { @@ -142,7 +145,7 @@ export const estimateTransactionSize = ( if (result.error instanceof TXSizeEstimationError) { console.error( "Unknown error estimating transaction size", - result.error.underlyingError + result.error.underlyingError, ); return 9999; } @@ -164,22 +167,22 @@ const simpleInstruction = () => { const isolatedInstructionSize = ( randomProvider: Provider, - instruction: TransactionInstruction + instruction: TransactionInstruction, ): number => { return marginalInstructionSize( randomProvider, [simpleInstruction()], - instruction + instruction, ); }; const marginalInstructionSize = ( randomProvider: Provider, previousInstructions: TransactionInstruction[], - instruction: TransactionInstruction + instruction: TransactionInstruction, ): number => { const previousTxSize = instructionsSize( randomProvider, - previousInstructions.length ? previousInstructions : [simpleInstruction()] + previousInstructions.length ? previousInstructions : [simpleInstruction()], ); const biggerTxSize = instructionsSize(randomProvider, [ @@ -191,7 +194,7 @@ const marginalInstructionSize = ( }; const instructionsSize = ( randomProvider: Provider, - instructions: TransactionInstruction[] + instructions: TransactionInstruction[], ): number => { const instructionedTx = new TransactionEnvelope(randomProvider, [ ...instructions, diff --git a/packages/solana-contrib/src/utils/pubkeyCache.ts b/packages/solana-contrib/src/utils/pubkeyCache.ts index 108ce1201..bf19aca6f 100644 --- a/packages/solana-contrib/src/utils/pubkeyCache.ts +++ b/packages/solana-contrib/src/utils/pubkeyCache.ts @@ -44,7 +44,7 @@ const getOrCreatePublicKey = (pk: string): PublicKey => { * @returns */ export const getPublicKey = ( - pk: string | PublicKey | PublicKeyInitData + pk: string | PublicKey | PublicKeyInitData, ): PublicKey => { if (typeof pk === "string") { return getOrCreatePublicKey(pk); @@ -64,7 +64,7 @@ const gpaCache: Record = {}; */ const concatSeeds = (seeds: Array): Uint8Array => { return Uint8Array.from( - seeds.reduce((acc: number[], seed) => [...acc, ...seed], []) + seeds.reduce((acc: number[], seed) => [...acc, ...seed], []), ); }; @@ -76,7 +76,7 @@ const concatSeeds = (seeds: Array): Uint8Array => { */ export const getProgramAddress = ( seeds: Array, - programId: PublicKey + programId: PublicKey, ) => { const normalizedSeeds = concatSeeds(seeds); const cacheKey = `${normalizedSeeds.toString()}_${programId.toString()}`; diff --git a/packages/solana-contrib/src/utils/simulateTransactionWithCommitment.ts b/packages/solana-contrib/src/utils/simulateTransactionWithCommitment.ts index c447b39c5..ad631a012 100644 --- a/packages/solana-contrib/src/utils/simulateTransactionWithCommitment.ts +++ b/packages/solana-contrib/src/utils/simulateTransactionWithCommitment.ts @@ -13,7 +13,7 @@ import { SendTransactionError } from "@solana/web3.js"; export async function simulateTransactionWithCommitment( connection: Connection, transaction: Transaction, - commitment: Commitment = "confirmed" + commitment: Commitment = "confirmed", ): Promise> { const connectionInner = connection as Connection & { _rpcRequest: ( @@ -23,8 +23,8 @@ export async function simulateTransactionWithCommitment( { encoding: string; commitment: Commitment; - } - ] + }, + ], ) => Promise<{ error: Error; result: RpcResponseAndContext; @@ -50,7 +50,7 @@ export async function simulateTransactionWithCommitment( if (res.error) { throw new SendTransactionError( "failed to simulate transaction: " + res.error.message, - res.result.value.logs ?? undefined + res.result.value.logs ?? undefined, ); } return res.result; diff --git a/packages/solana-contrib/src/utils/txLink.ts b/packages/solana-contrib/src/utils/txLink.ts index 000306609..d0b988ed5 100644 --- a/packages/solana-contrib/src/utils/txLink.ts +++ b/packages/solana-contrib/src/utils/txLink.ts @@ -8,12 +8,12 @@ export enum ExplorerType { export function generateTXLink( signature: string, cluster: Cluster = "mainnet-beta", - explorerType: string = ExplorerType.SOLANA_EXPLORER + explorerType: string = ExplorerType.SOLANA_EXPLORER, ): string { switch (explorerType) { - case ExplorerType.SOLANA_EXPLORER: + case ExplorerType.SOLANA_EXPLORER as string: return `https://explorer.solana.com/tx/${signature}?cluster=${cluster}`; - case ExplorerType.SOLSCAN: + case ExplorerType.SOLSCAN as string: return `https://solscan.io/tx/${signature}?cluster=${cluster}`; default: throw new Error(`Explorer type ${explorerType} is not supported.`); diff --git a/packages/solana-contrib/src/wallet.ts b/packages/solana-contrib/src/wallet.ts index 1ad9368e6..caf92a1c7 100644 --- a/packages/solana-contrib/src/wallet.ts +++ b/packages/solana-contrib/src/wallet.ts @@ -24,7 +24,7 @@ export class SignerWallet implements Wallet { transactions.map((tx) => { tx.partialSign(this.signer); return tx; - }) + }), ); } @@ -41,7 +41,7 @@ export class SignerWallet implements Wallet { createProvider( connection: Connection, sendConnection?: Connection, - opts?: ConfirmOptions + opts?: ConfirmOptions, ): Provider { return SolanaProvider.load({ connection, diff --git a/packages/stableswap-sdk/src/calculator/amounts.ts b/packages/stableswap-sdk/src/calculator/amounts.ts index a55955da9..5ae241651 100644 --- a/packages/stableswap-sdk/src/calculator/amounts.ts +++ b/packages/stableswap-sdk/src/calculator/amounts.ts @@ -12,7 +12,7 @@ import { computeD, computeY } from "./curve.js"; * @returns */ export const calculateVirtualPrice = ( - exchange: IExchangeInfo + exchange: IExchangeInfo, ): Fraction | null => { const amount = exchange.lpTotalSupply; if (amount === undefined || amount.equalTo(0)) { @@ -23,9 +23,9 @@ export const calculateVirtualPrice = ( computeD( exchange.ampFactor, exchange.reserves[0].amount.raw, - exchange.reserves[1].amount.raw + exchange.reserves[1].amount.raw, ), - amount.raw + amount.raw, ); return price; }; @@ -38,7 +38,7 @@ export const calculateVirtualPrice = ( */ export const calculateEstimatedSwapOutputAmount = ( exchange: IExchangeInfo, - fromAmount: TokenAmount + fromAmount: TokenAmount, ): { [K in | "outputAmountBeforeFees" @@ -48,7 +48,7 @@ export const calculateEstimatedSwapOutputAmount = ( | "adminFee"]: TokenAmount; } => { const [fromReserves, toReserves] = fromAmount.token.equals( - exchange.reserves[0].amount.token + exchange.reserves[0].amount.token, ) ? [exchange.reserves[0], exchange.reserves[1]] : [exchange.reserves[1], exchange.reserves[0]]; @@ -71,29 +71,29 @@ export const calculateEstimatedSwapOutputAmount = ( computeY( amp, JSBI.add(fromReserves.amount.raw, fromAmount.raw), - computeD(amp, fromReserves.amount.raw, toReserves.amount.raw) - ) + computeD(amp, fromReserves.amount.raw, toReserves.amount.raw), + ), ); const outputAmountBeforeFees = new TokenAmount( toReserves.amount.token, - amountBeforeFees + amountBeforeFees, ); const fee = new TokenAmount( toReserves.amount.token, - exchange.fees.trade.asFraction.multiply(amountBeforeFees).toFixed(0) + exchange.fees.trade.asFraction.multiply(amountBeforeFees).toFixed(0), ); const adminFee = new TokenAmount( toReserves.amount.token, - exchange.fees.adminTrade.asFraction.multiply(fee.raw).toFixed(0) + exchange.fees.adminTrade.asFraction.multiply(fee.raw).toFixed(0), ); const lpFee = fee.subtract(adminFee); const outputAmount = new TokenAmount( toReserves.amount.token, - JSBI.subtract(amountBeforeFees, fee.raw) + JSBI.subtract(amountBeforeFees, fee.raw), ); return { @@ -160,8 +160,8 @@ export const calculateEstimatedWithdrawOneAmount = ({ d_0, JSBI.divide( JSBI.multiply(poolTokenAmount.raw, d_0), - exchange.lpTotalSupply.raw - ) + exchange.lpTotalSupply.raw, + ), ); const new_y = computeY(ampFactor, quoteReserves, d_1); @@ -169,27 +169,27 @@ export const calculateEstimatedWithdrawOneAmount = ({ // expected_base_amount = swap_base_amount * d_1 / d_0 - new_y; const expected_base_amount = JSBI.subtract( JSBI.divide(JSBI.multiply(baseReserves, d_1), d_0), - new_y + new_y, ); // expected_quote_amount = swap_quote_amount - swap_quote_amount * d_1 / d_0; const expected_quote_amount = JSBI.subtract( quoteReserves, - JSBI.divide(JSBI.multiply(quoteReserves, d_1), d_0) + JSBI.divide(JSBI.multiply(quoteReserves, d_1), d_0), ); // new_base_amount = swap_base_amount - expected_base_amount * fee / fee_denominator; const new_base_amount = new Fraction(baseReserves.toString(), 1).subtract( - normalizedTradeFee(fees, N_COINS, expected_base_amount) + normalizedTradeFee(fees, N_COINS, expected_base_amount), ); // new_quote_amount = swap_quote_amount - expected_quote_amount * fee / fee_denominator; const new_quote_amount = new Fraction(quoteReserves.toString(), 1).subtract( - normalizedTradeFee(fees, N_COINS, expected_quote_amount) + normalizedTradeFee(fees, N_COINS, expected_quote_amount), ); const dy = new_base_amount.subtract( computeY( ampFactor, JSBI.BigInt(new_quote_amount.toFixed(0)), - d_1 - ).toString() + d_1, + ).toString(), ); const dy_0 = JSBI.subtract(baseReserves, new_y); @@ -219,7 +219,7 @@ export const calculateEstimatedWithdrawOneAmount = ({ adminSwapFee: new TokenAmount(withdrawToken, adminSwapFee.toFixed(0)), adminWithdrawFee: new TokenAmount( withdrawToken, - adminWithdrawFee.toFixed(0) + adminWithdrawFee.toFixed(0), ), }; }; @@ -230,11 +230,11 @@ export const calculateEstimatedWithdrawOneAmount = ({ export const normalizedTradeFee = ( { trade }: Fees, n_coins: JSBI, - amount: JSBI + amount: JSBI, ): Fraction => { const adjustedTradeFee = new Fraction( n_coins, - JSBI.multiply(JSBI.subtract(n_coins, ONE), JSBI.BigInt(4)) + JSBI.multiply(JSBI.subtract(n_coins, ONE), JSBI.BigInt(4)), ); return new Fraction(amount, 1).multiply(trade).multiply(adjustedTradeFee); }; @@ -257,7 +257,7 @@ export const calculateEstimatedWithdrawAmount = ({ if (lpTotalSupply.equalTo(0)) { const zero = reserves.map((r) => new TokenAmount(r.amount.token, ZERO)) as [ TokenAmount, - TokenAmount + TokenAmount, ]; return { withdrawAmounts: zero, @@ -274,7 +274,7 @@ export const calculateEstimatedWithdrawAmount = ({ return [ new TokenAmount( amount.token, - JSBI.BigInt(baseAmount.subtract(fee).toFixed(0)) + JSBI.BigInt(baseAmount.subtract(fee).toFixed(0)), ), { beforeFees: JSBI.BigInt(baseAmount.toFixed(0)), @@ -283,16 +283,16 @@ export const calculateEstimatedWithdrawAmount = ({ ]; }) as [ [TokenAmount, { beforeFees: JSBI; fee: JSBI }], - [TokenAmount, { beforeFees: JSBI; fee: JSBI }] + [TokenAmount, { beforeFees: JSBI; fee: JSBI }], ]; return { withdrawAmountsBeforeFees: withdrawAmounts.map( - ([amt, { beforeFees }]) => new TokenAmount(amt.token, beforeFees) + ([amt, { beforeFees }]) => new TokenAmount(amt.token, beforeFees), ) as [TokenAmount, TokenAmount], withdrawAmounts: [withdrawAmounts[0][0], withdrawAmounts[1][0]], fees: withdrawAmounts.map( - ([amt, { fee }]) => new TokenAmount(amt.token, fee) + ([amt, { fee }]) => new TokenAmount(amt.token, fee), ) as [TokenAmount, TokenAmount], }; }; @@ -307,7 +307,7 @@ export const calculateEstimatedWithdrawAmount = ({ export const calculateEstimatedMintAmount = ( exchange: IExchangeInfo, depositAmountA: JSBI, - depositAmountB: JSBI + depositAmountB: JSBI, ): { mintAmountBeforeFees: TokenAmount; mintAmount: TokenAmount; @@ -329,7 +329,7 @@ export const calculateEstimatedMintAmount = ( const d1 = computeD( amp, JSBI.add(reserveA.amount.raw, depositAmountA), - JSBI.add(reserveB.amount.raw, depositAmountB) + JSBI.add(reserveB.amount.raw, depositAmountB), ); if (JSBI.lessThan(d1, d0)) { throw new Error("New D cannot be less than previous D"); @@ -337,7 +337,7 @@ export const calculateEstimatedMintAmount = ( const oldBalances = exchange.reserves.map((r) => r.amount.raw) as [ JSBI, - JSBI + JSBI, ]; const newBalances = [ JSBI.add(reserveA.amount.raw, depositAmountA), @@ -353,7 +353,7 @@ export const calculateEstimatedMintAmount = ( const fee = normalizedTradeFee( exchange.fees, N_COINS, - JSBI.BigInt(diffAbs.toFixed(0)) + JSBI.BigInt(diffAbs.toFixed(0)), ); return JSBI.subtract(newBalance, JSBI.BigInt(fee.toFixed(0))); }) as [JSBI, JSBI]; @@ -362,26 +362,26 @@ export const calculateEstimatedMintAmount = ( const lpSupply = exchange.lpTotalSupply; const mintAmountRaw = JSBI.divide( JSBI.multiply(lpSupply.raw, JSBI.subtract(d2, d0)), - d0 + d0, ); const mintAmount = new TokenAmount( exchange.lpTotalSupply.token, - mintAmountRaw + mintAmountRaw, ); const mintAmountRawBeforeFees = JSBI.divide( JSBI.multiply(lpSupply.raw, JSBI.subtract(d1, d0)), - d0 + d0, ); const fees = new TokenAmount( exchange.lpTotalSupply.token, - JSBI.subtract(mintAmountRawBeforeFees, mintAmountRaw) + JSBI.subtract(mintAmountRawBeforeFees, mintAmountRaw), ); const mintAmountBeforeFees = new TokenAmount( exchange.lpTotalSupply.token, - mintAmountRawBeforeFees + mintAmountRawBeforeFees, ); return { diff --git a/packages/stableswap-sdk/src/calculator/amounts.unit.test.ts b/packages/stableswap-sdk/src/calculator/amounts.unit.test.ts index 00304ebd7..64f828b75 100644 --- a/packages/stableswap-sdk/src/calculator/amounts.unit.test.ts +++ b/packages/stableswap-sdk/src/calculator/amounts.unit.test.ts @@ -57,7 +57,7 @@ const makeExchangeInfo = ( lpTotalSupply: JSBI.BigInt(200_000_000), tokenAAmount: JSBI.BigInt(100_000_000), tokenBAmount: JSBI.BigInt(100_000_000), - } + }, ): IExchangeInfo => ({ ampFactor: JSBI.BigInt(100), fees: ZERO_FEES, @@ -65,19 +65,19 @@ const makeExchangeInfo = ( reserves: [ { reserveAccount: new PublicKey( - "Es9vMFrzaCERmJfrF4H2FYD4KCoNkY11McCe8BenwNYB" + "Es9vMFrzaCERmJfrF4H2FYD4KCoNkY11McCe8BenwNYB", ), adminFeeAccount: new PublicKey( - "Es9vMFrzaCERmJfrF4H2FYD4KCoNkY11McCe8BenwNYB" + "Es9vMFrzaCERmJfrF4H2FYD4KCoNkY11McCe8BenwNYB", ), amount: new TokenAmount(exchange.tokens[0], tokenAAmount), }, { reserveAccount: new PublicKey( - "Es9vMFrzaCERmJfrF4H2FYD4KCoNkY11McCe8BenwNYB" + "Es9vMFrzaCERmJfrF4H2FYD4KCoNkY11McCe8BenwNYB", ), adminFeeAccount: new PublicKey( - "Es9vMFrzaCERmJfrF4H2FYD4KCoNkY11McCe8BenwNYB" + "Es9vMFrzaCERmJfrF4H2FYD4KCoNkY11McCe8BenwNYB", ), amount: new TokenAmount(exchange.tokens[1], tokenBAmount), }, @@ -93,7 +93,7 @@ const exchangeInfoWithFees = { const assertTokenAmounts = (actual: TokenAmount, expected: TokenAmount) => { expect(actual.equalTo(expected) && actual.token.equals(expected.token)).toBe( - true + true, ); }; @@ -114,7 +114,7 @@ describe("Calculated amounts", () => { lpTotalSupply: JSBI.BigInt(200_000_000), tokenAAmount: JSBI.BigInt(10_000_000), tokenBAmount: JSBI.BigInt(190_000_000), - }) + }), ); expect(result?.toFixed(4)).toBe("0.9801"); @@ -123,7 +123,7 @@ describe("Calculated amounts", () => { lpTotalSupply: JSBI.BigInt(200_000_000), tokenAAmount: JSBI.BigInt(190_000_000), tokenBAmount: JSBI.BigInt(10_000_000), - }) + }), ); expect(result2?.toFixed(4)).toBe("0.9801"); }); @@ -144,7 +144,7 @@ describe("Calculated amounts", () => { it("no fees", () => { const result = calculateEstimatedSwapOutputAmount( exchangeInfo, - new TokenAmount(exchange.tokens[0], JSBI.BigInt(10_000_000)) + new TokenAmount(exchange.tokens[0], JSBI.BigInt(10_000_000)), ); assertTokenAmounts(result.outputAmount, result.outputAmountBeforeFees); @@ -159,7 +159,7 @@ describe("Calculated amounts", () => { trade: new Percent(50, 100), }, }, - new TokenAmount(exchange.tokens[0], JSBI.BigInt(100)) + new TokenAmount(exchange.tokens[0], JSBI.BigInt(100)), ); // 50 percent fee @@ -179,7 +179,7 @@ describe("Calculated amounts", () => { }, }, JSBI.BigInt(100), - JSBI.BigInt(100) + JSBI.BigInt(100), ); assertTokenAmounts(result.mintAmount, result.mintAmountBeforeFees); @@ -195,20 +195,20 @@ describe("Calculated amounts", () => { }, }, JSBI.BigInt(100_000), - JSBI.BigInt(0) + JSBI.BigInt(0), ); assertTokenAmount(result.mintAmountBeforeFees, new BN(99_999)); // 3/4 because only half of the swapped amount (100 tokens) should have fees on it (so 1/4) const expectedMintAmount = JSBI.divide( JSBI.multiply(result.mintAmountBeforeFees.raw, JSBI.BigInt(3)), - JSBI.BigInt(4) + JSBI.BigInt(4), ); assertTokenAmount(result.mintAmount, expectedMintAmount); assertTokenAmount( result.fees, - JSBI.subtract(result.mintAmountBeforeFees.raw, expectedMintAmount) + JSBI.subtract(result.mintAmountBeforeFees.raw, expectedMintAmount), ); }); }); diff --git a/packages/stableswap-sdk/src/calculator/curve.ts b/packages/stableswap-sdk/src/calculator/curve.ts index 2517a20fd..8e0f8e2d3 100644 --- a/packages/stableswap-sdk/src/calculator/curve.ts +++ b/packages/stableswap-sdk/src/calculator/curve.ts @@ -23,7 +23,7 @@ const MAX_ITERS = 20; export const computeD = ( ampFactor: JSBI, amountA: JSBI, - amountB: JSBI + amountB: JSBI, ): JSBI => { const Ann = JSBI.multiply(ampFactor, N_COINS); // A*n^n const S = JSBI.add(amountA, amountB); // sum(x_i), a.k.a S @@ -46,11 +46,11 @@ export const computeD = ( const dNumerator = JSBI.multiply( d, - JSBI.add(JSBI.multiply(Ann, S), JSBI.multiply(dP, N_COINS)) + JSBI.add(JSBI.multiply(Ann, S), JSBI.multiply(dP, N_COINS)), ); const dDenominator = JSBI.add( JSBI.multiply(d, JSBI.subtract(Ann, ONE)), - JSBI.multiply(dP, JSBI.add(N_COINS, ONE)) + JSBI.multiply(dP, JSBI.add(N_COINS, ONE)), ); d = JSBI.divide(dNumerator, dDenominator); } @@ -73,11 +73,11 @@ export const computeY = (ampFactor: JSBI, x: JSBI, d: JSBI): JSBI => { JSBI.multiply( JSBI.multiply( d, // c = D ** (n + 1) / (n ** (2 * n) * prod' * A) - d + d, ), - d + d, ), - JSBI.multiply(N_COINS, JSBI.multiply(N_COINS, JSBI.multiply(x, Ann))) + JSBI.multiply(N_COINS, JSBI.multiply(N_COINS, JSBI.multiply(x, Ann))), ); let yPrev = ZERO; @@ -90,7 +90,7 @@ export const computeY = (ampFactor: JSBI, x: JSBI, d: JSBI): JSBI => { yPrev = y; y = JSBI.divide( JSBI.add(JSBI.multiply(y, y), c), - JSBI.add(JSBI.multiply(N_COINS, y), b) + JSBI.add(JSBI.multiply(N_COINS, y), b), ); } diff --git a/packages/stableswap-sdk/src/calculator/curve.unit.test.ts b/packages/stableswap-sdk/src/calculator/curve.unit.test.ts index e8f638c8c..973b5ecbc 100644 --- a/packages/stableswap-sdk/src/calculator/curve.unit.test.ts +++ b/packages/stableswap-sdk/src/calculator/curve.unit.test.ts @@ -11,74 +11,74 @@ describe("Calculator tests", () => { it("computeD", () => { assertBN( computeD(JSBI.BigInt(100), JSBI.BigInt(0), JSBI.BigInt(0)), - JSBI.BigInt(0) + JSBI.BigInt(0), ); assertBN( computeD( JSBI.BigInt(100), JSBI.BigInt(1000000000), - JSBI.BigInt(1000000000) + JSBI.BigInt(1000000000), ), - JSBI.BigInt(2000000000) + JSBI.BigInt(2000000000), ); assertBN( computeD(JSBI.BigInt(73), JSBI.BigInt(92), JSBI.BigInt(81)), - JSBI.BigInt(173) + JSBI.BigInt(173), ); assertBN( computeD(JSBI.BigInt(11503), JSBI.BigInt(28338), JSBI.BigInt(78889)), - JSBI.BigInt(107225) + JSBI.BigInt(107225), ); assertBN( computeD(JSBI.BigInt(8552), JSBI.BigInt(26), JSBI.BigInt(69321)), - JSBI.BigInt(66920) + JSBI.BigInt(66920), ); assertBN( computeD(JSBI.BigInt(496), JSBI.BigInt(62), JSBI.BigInt(68567)), - JSBI.BigInt(57447) + JSBI.BigInt(57447), ); assertBN( computeD( JSBI.BigInt("17653203515214796177"), JSBI.BigInt("13789683482691983066"), - JSBI.BigInt("3964443602730479576") + JSBI.BigInt("3964443602730479576"), ), - JSBI.BigInt("17754127085422462641") + JSBI.BigInt("17754127085422462641"), ); }); it("computeY", () => { assertBN( computeY(JSBI.BigInt(100), JSBI.BigInt(100), JSBI.BigInt(0)), - JSBI.BigInt(0) + JSBI.BigInt(0), ); assertBN( computeY(JSBI.BigInt(8), JSBI.BigInt(94), JSBI.BigInt(163)), - JSBI.BigInt(69) + JSBI.BigInt(69), ); assertBN( computeY( JSBI.BigInt(2137), JSBI.BigInt(905777403660), - JSBI.BigInt(830914146046) + JSBI.BigInt(830914146046), ), - JSBI.BigInt(490376033) + JSBI.BigInt(490376033), ); assertBN( computeY( JSBI.BigInt("17095344176474858097"), JSBI.BigInt(383), - JSBI.BigInt("2276818911077272163") + JSBI.BigInt("2276818911077272163"), ), - JSBI.BigInt("2276917873767753112") + JSBI.BigInt("2276917873767753112"), ); assertBN( computeY( JSBI.BigInt("7644937799120520965"), JSBI.BigInt("14818904982296505121"), - JSBI.BigInt("17480022366793075404") + JSBI.BigInt("17480022366793075404"), ), - JSBI.BigInt("2661117384496570284") + JSBI.BigInt("2661117384496570284"), ); }); }); diff --git a/packages/stableswap-sdk/src/calculator/price.ts b/packages/stableswap-sdk/src/calculator/price.ts index 493ce0bcb..a8014e2c5 100644 --- a/packages/stableswap-sdk/src/calculator/price.ts +++ b/packages/stableswap-sdk/src/calculator/price.ts @@ -21,24 +21,24 @@ export const calculateSwapPrice = (exchangeInfo: IExchangeInfo): Price => { 10_000, Math.min( 10 ** reserve0.token.decimals, - Math.floor(parseInt(reserve0.toU64().div(new BN(100)).toString())) - ) + Math.floor(parseInt(reserve0.toU64().div(new BN(100)).toString())), + ), ); const inputAmount = new TokenAmount(reserve0.token, inputAmountNum); const outputAmount = calculateEstimatedSwapOutputAmount( exchangeInfo, - inputAmount + inputAmount, ); const frac = outputAmount.outputAmountBeforeFees.asFraction.divide( - inputAmount.asFraction + inputAmount.asFraction, ); return new Price( reserve0.token, reserve1.token, frac.denominator, - frac.numerator + frac.numerator, ); }; diff --git a/packages/stableswap-sdk/src/constants.ts b/packages/stableswap-sdk/src/constants.ts index b5fbe22e1..640f88714 100644 --- a/packages/stableswap-sdk/src/constants.ts +++ b/packages/stableswap-sdk/src/constants.ts @@ -5,5 +5,5 @@ export const DEFAULT_TOKEN_DECIMALS = 6; export const ZERO_TS = 0; export const SWAP_PROGRAM_ID = new PublicKey( - "SSwpkEEcbUqx4vtoEByFjSkhKdCT862DNVb52nZg1UZ" + "SSwpkEEcbUqx4vtoEByFjSkhKdCT862DNVb52nZg1UZ", ); diff --git a/packages/stableswap-sdk/src/entities/exchange.ts b/packages/stableswap-sdk/src/entities/exchange.ts index 27c5834cc..a7d59a085 100644 --- a/packages/stableswap-sdk/src/entities/exchange.ts +++ b/packages/stableswap-sdk/src/entities/exchange.ts @@ -69,7 +69,7 @@ export const calculateAmpFactor = ( | "startRampTimestamp" | "stopRampTimestamp" >, - now = Date.now() / 1_000 + now = Date.now() / 1_000, ): JSBI => { const { initialAmpFactor, @@ -90,17 +90,17 @@ export const calculateAmpFactor = ( invariant( stopRampTimestamp >= startRampTimestamp, - "stop must be after start" + "stop must be after start", ); // Calculate how far we are along the ramp curve. const percent = now >= stopRampTimestamp ? 1 : now <= startRampTimestamp - ? 0 - : (now - startRampTimestamp) / (stopRampTimestamp - startRampTimestamp); + ? 0 + : (now - startRampTimestamp) / (stopRampTimestamp - startRampTimestamp); const diff = Math.floor( - parseFloat(targetAmpFactor.sub(initialAmpFactor).toString()) * percent + parseFloat(targetAmpFactor.sub(initialAmpFactor).toString()) * percent, ); return parseBigintIsh(initialAmpFactor.add(new BN(diff))); }; @@ -159,7 +159,7 @@ export const makeExchangeInfo = ({ export const loadExchangeInfo = async ( connection: Connection, exchange: IExchange, - swap: StableSwap + swap: StableSwap, ): Promise => { if (!exchange.programID.equals(swap.config.swapProgramID)) { throw new Error("Swap program id mismatch"); @@ -168,17 +168,17 @@ export const loadExchangeInfo = async ( const reserveA = await loadProgramAccount( connection, swap.state.tokenA.reserve, - swap.config.tokenProgramID + swap.config.tokenProgramID, ); const reserveB = await loadProgramAccount( connection, swap.state.tokenB.reserve, - swap.config.tokenProgramID + swap.config.tokenProgramID, ); const poolMint = await loadProgramAccount( connection, swap.state.poolTokenMint, - swap.config.tokenProgramID + swap.config.tokenProgramID, ); return makeExchangeInfo({ swap, @@ -254,7 +254,7 @@ export const loadExchangeInfoFromSwapAccount = async ( connection: Connection, swapAccount: PublicKey, tokenA: Token | undefined = undefined, - tokenB: Token | undefined = undefined + tokenB: Token | undefined = undefined, ): Promise => { const stableSwap = await StableSwap.load(connection, swapAccount); @@ -263,7 +263,7 @@ export const loadExchangeInfoFromSwapAccount = async ( (await Token.load(connection, stableSwap.state.tokenA.mint))?.info; if (!theTokenA) { throw new Error( - `Token ${stableSwap.state.tokenA.mint.toString()} not found` + `Token ${stableSwap.state.tokenA.mint.toString()} not found`, ); } @@ -272,7 +272,7 @@ export const loadExchangeInfoFromSwapAccount = async ( (await Token.load(connection, stableSwap.state.tokenB.mint))?.info; if (!theTokenB) { throw new Error( - `Token ${stableSwap.state.tokenB.mint.toString()} not found` + `Token ${stableSwap.state.tokenB.mint.toString()} not found`, ); } diff --git a/packages/stableswap-sdk/src/events.ts b/packages/stableswap-sdk/src/events.ts index 173441284..6f604cf67 100644 --- a/packages/stableswap-sdk/src/events.ts +++ b/packages/stableswap-sdk/src/events.ts @@ -30,7 +30,7 @@ const parseEventRaw = (type: string, msg: string): StableSwapEvent => { * @returns */ export const parseEventLogs = ( - logMessages?: string[] | null + logMessages?: string[] | null, ): readonly StableSwapEvent[] => { if (!logMessages) { return []; @@ -42,7 +42,7 @@ export const parseEventLogs = ( ...acc, parseEventRaw( logMessage.slice("Program log: Event: ".length), - nextLog + nextLog, ), ] : acc; diff --git a/packages/stableswap-sdk/src/instructions/admin.ts b/packages/stableswap-sdk/src/instructions/admin.ts index ec6b4f284..fb032a186 100644 --- a/packages/stableswap-sdk/src/instructions/admin.ts +++ b/packages/stableswap-sdk/src/instructions/admin.ts @@ -56,7 +56,7 @@ export const createAdminRampAInstruction = ({ targetAmp: targetAmp.toBuffer(), stopRampTS: Math.floor(stopRamp.getTime() / 1_000), }, - data + data, ); return buildInstruction({ config, @@ -84,7 +84,7 @@ export const createAdminStopRampAInstruction = ({ { instruction: AdminInstruction.STOP_RAMP_A, }, - data + data, ); data = data.slice(0, encodeLength); return buildInstruction({ @@ -113,7 +113,7 @@ export const createAdminPauseInstruction = ({ { instruction: AdminInstruction.PAUSE, }, - data + data, ); return buildInstruction({ config, @@ -141,7 +141,7 @@ export const createAdminUnpauseInstruction = ({ { instruction: AdminInstruction.UNPAUSE, }, - data + data, ); return buildInstruction({ config, @@ -172,7 +172,7 @@ export const createAdminSetFeeAccountInstruction = ({ { instruction: AdminInstruction.SET_FEE_ACCOUNT, }, - data + data, ); return buildInstruction({ config, @@ -200,7 +200,7 @@ export const createAdminApplyNewAdminInstruction = ({ { instruction: AdminInstruction.APPLY_NEW_ADMIN, }, - data + data, ); return buildInstruction({ config, @@ -234,7 +234,7 @@ export const createAdminCommitNewAdminInstruction = ({ { instruction: AdminInstruction.COMMIT_NEW_ADMIN, }, - data + data, ); return buildInstruction({ config, @@ -265,7 +265,7 @@ export const createAdminSetNewFeesInstruction = ({ instruction: AdminInstruction.SET_NEW_FEES, // InitializeSwap instruction fees: encodeFees(fees), }, - data + data, ); return buildInstruction({ config, diff --git a/packages/stableswap-sdk/src/instructions/swap.ts b/packages/stableswap-sdk/src/instructions/swap.ts index 87131ca9c..af2e1b098 100644 --- a/packages/stableswap-sdk/src/instructions/swap.ts +++ b/packages/stableswap-sdk/src/instructions/swap.ts @@ -223,7 +223,7 @@ export const initializeSwapInstructionRaw = ({ ampFactor: ampFactor.toBuffer(), fees, }, - data + data, ); return buildInstruction({ config, @@ -257,7 +257,7 @@ export const swapInstruction = ({ amountIn: amountIn.toBuffer(), minimumAmountOut: minimumAmountOut.toBuffer(), }, - data + data, ); const keys = [ { pubkey: config.swapAccount, isSigner: false, isWritable: false }, @@ -298,7 +298,7 @@ export const depositInstruction = ({ tokenAmountB: tokenAmountB.toBuffer(), minimumPoolTokenAmount: minimumPoolTokenAmount.toBuffer(), }, - data + data, ); const keys = [ { pubkey: config.swapAccount, isSigner: false, isWritable: false }, @@ -342,7 +342,7 @@ export const withdrawInstruction = ({ minimumTokenA: minimumTokenA.toBuffer(), minimumTokenB: minimumTokenB.toBuffer(), }, - data + data, ); const keys = [ @@ -385,7 +385,7 @@ export const withdrawOneInstruction = ({ poolTokenAmount: poolTokenAmount.toBuffer(), minimumTokenAmount: minimumTokenAmount.toBuffer(), }, - data + data, ); const keys = [ diff --git a/packages/stableswap-sdk/src/stable-swap.ts b/packages/stableswap-sdk/src/stable-swap.ts index 8cbdb1817..c3c969759 100644 --- a/packages/stableswap-sdk/src/stable-swap.ts +++ b/packages/stableswap-sdk/src/stable-swap.ts @@ -38,7 +38,7 @@ export function createSaberSwapInstruction( | "poolDestination" | "amountIn" | "minimumAmountOut" - > + >, ): TransactionInstruction { const adminDestination = args.poolDestination.equals(state.tokenA.reserve) ? state.tokenA.adminFeeAccount @@ -64,7 +64,7 @@ export function createSaberDepositInstruction( | "tokenAmountA" | "tokenAmountB" | "minimumPoolTokenAmount" - > + >, ): TransactionInstruction { return instructions.depositInstruction({ config: config, @@ -89,7 +89,7 @@ export function createSaberWithdrawInstruction( | "poolTokenAmount" | "minimumTokenA" | "minimumTokenB" - > + >, ): TransactionInstruction { return instructions.withdrawInstruction({ config: config, @@ -115,7 +115,7 @@ export function createSaberWithdrawOneInstruction( | "sourceAccount" | "poolTokenAmount" | "minimumTokenAmount" - > + >, ): TransactionInstruction { const [quoteTokenAccount, adminDestinationAccount] = args.baseTokenAccount.equals(state.tokenA.reserve) @@ -139,7 +139,7 @@ export class StableSwap implements StableSwapInfo { */ constructor( readonly config: StableSwapConfig, - readonly state: StableSwapState + readonly state: StableSwapState, ) {} /** @@ -148,10 +148,10 @@ export class StableSwap implements StableSwapInfo { * @return Number of lamports required */ static async getMinBalanceRentForExemptStableSwap( - connection: Connection + connection: Connection, ): Promise { return await connection.getMinimumBalanceForRentExemption( - StableSwapLayout.span + StableSwapLayout.span, ); } @@ -165,7 +165,7 @@ export class StableSwap implements StableSwapInfo { static async load( connection: Connection, swapAccount: PublicKey, - programID: PublicKey = SWAP_PROGRAM_ID + programID: PublicKey = SWAP_PROGRAM_ID, ): Promise { const data = await loadProgramAccount(connection, swapAccount, programID); const authority = getSwapAuthorityKey(swapAccount, programID); @@ -181,12 +181,12 @@ export class StableSwap implements StableSwapInfo { */ static async loadFromExchange( connection: Connection, - exchange: IExchange + exchange: IExchange, ): Promise { return StableSwap.load( connection, exchange.swapAccount, - exchange.programID + exchange.programID, ); } @@ -196,7 +196,7 @@ export class StableSwap implements StableSwapInfo { * @returns */ static async fromProgramAccount( - data: ProgramAccount + data: ProgramAccount, ): Promise { const [authority] = await findSwapAuthorityKey(data.publicKey); return StableSwap.fromProgramAccountWithAuthority(data, authority); @@ -219,7 +219,7 @@ export class StableSwap implements StableSwapInfo { */ static fromProgramAccountWithAuthority( data: ProgramAccount, - authority: PublicKey + authority: PublicKey, ): StableSwap { return new StableSwap( { @@ -228,7 +228,7 @@ export class StableSwap implements StableSwapInfo { tokenProgramID: TOKEN_PROGRAM_ID, authority, }, - data.account + data.account, ); } @@ -245,7 +245,7 @@ export class StableSwap implements StableSwapInfo { swapAccount: PublicKey, swapAccountData: Buffer, authority: PublicKey, - programID: PublicKey = SWAP_PROGRAM_ID + programID: PublicKey = SWAP_PROGRAM_ID, ): StableSwap { try { const state = decodeSwap(swapAccountData); @@ -259,7 +259,7 @@ export class StableSwap implements StableSwapInfo { tokenProgramID: TOKEN_PROGRAM_ID, authority, }, - state + state, ); } catch (e) { throw Error(e as string); @@ -285,7 +285,7 @@ export class StableSwap implements StableSwapInfo { | "poolDestination" | "amountIn" | "minimumAmountOut" - > + >, ): TransactionInstruction { return createSaberSwapInstruction(this, args); } @@ -303,7 +303,7 @@ export class StableSwap implements StableSwapInfo { | "tokenAmountA" | "tokenAmountB" | "minimumPoolTokenAmount" - > + >, ): TransactionInstruction { return createSaberDepositInstruction(this, args); } @@ -321,7 +321,7 @@ export class StableSwap implements StableSwapInfo { | "poolTokenAmount" | "minimumTokenA" | "minimumTokenB" - > + >, ): TransactionInstruction { return createSaberWithdrawInstruction(this, args); } @@ -338,7 +338,7 @@ export class StableSwap implements StableSwapInfo { | "sourceAccount" | "poolTokenAmount" | "minimumTokenAmount" - > + >, ): TransactionInstruction { return createSaberWithdrawOneInstruction(this, args); } @@ -353,7 +353,7 @@ export class StableSwap implements StableSwapInfo { */ export const findSwapAuthorityKey = ( swapAccount: PublicKey, - swapProgramID: PublicKey = SWAP_PROGRAM_ID + swapProgramID: PublicKey = SWAP_PROGRAM_ID, ): Promise<[PublicKey, number]> => PublicKey.findProgramAddress([swapAccount.toBuffer()], swapProgramID); @@ -366,7 +366,7 @@ export const findSwapAuthorityKey = ( */ export const findSwapAuthorityKeySync = ( swapAccount: PublicKey, - swapProgramID: PublicKey = SWAP_PROGRAM_ID + swapProgramID: PublicKey = SWAP_PROGRAM_ID, ): [PublicKey, number] => PublicKey.findProgramAddressSync([swapAccount.toBuffer()], swapProgramID); @@ -379,5 +379,5 @@ export const findSwapAuthorityKeySync = ( */ export const getSwapAuthorityKey = ( swapAccount: PublicKey, - swapProgramID: PublicKey = SWAP_PROGRAM_ID + swapProgramID: PublicKey = SWAP_PROGRAM_ID, ): PublicKey => getProgramAddress([swapAccount.toBuffer()], swapProgramID); diff --git a/packages/stableswap-sdk/src/state/fees.ts b/packages/stableswap-sdk/src/state/fees.ts index e47791732..6b57ff8d0 100644 --- a/packages/stableswap-sdk/src/state/fees.ts +++ b/packages/stableswap-sdk/src/state/fees.ts @@ -35,58 +35,58 @@ const recommendedFeesRaw = { export const RECOMMENDED_FEES: Fees = { trade: new Percent( recommendedFeesRaw.tradeFeeNumerator, - recommendedFeesRaw.tradeFeeDenominator + recommendedFeesRaw.tradeFeeDenominator, ), withdraw: new Percent( recommendedFeesRaw.withdrawFeeNumerator, - recommendedFeesRaw.withdrawFeeDenominator + recommendedFeesRaw.withdrawFeeDenominator, ), adminTrade: new Percent( recommendedFeesRaw.adminTradeFeeNumerator, - recommendedFeesRaw.adminTradeFeeDenominator + recommendedFeesRaw.adminTradeFeeDenominator, ), adminWithdraw: new Percent( recommendedFeesRaw.adminWithdrawFeeNumerator, - recommendedFeesRaw.adminWithdrawFeeDenominator + recommendedFeesRaw.adminWithdrawFeeDenominator, ), }; export const encodeFees = (fees: Fees): RawFees => ({ adminTradeFeeNumerator: new u64( - fees.adminTrade.numerator.toString() + fees.adminTrade.numerator.toString(), ).toBuffer(), adminTradeFeeDenominator: new u64( - fees.adminTrade.denominator.toString() + fees.adminTrade.denominator.toString(), ).toBuffer(), adminWithdrawFeeNumerator: new u64( - fees.adminWithdraw.numerator.toString() + fees.adminWithdraw.numerator.toString(), ).toBuffer(), adminWithdrawFeeDenominator: new u64( - fees.adminWithdraw.denominator.toString() + fees.adminWithdraw.denominator.toString(), ).toBuffer(), tradeFeeNumerator: new u64(fees.trade.numerator.toString()).toBuffer(), tradeFeeDenominator: new u64(fees.trade.denominator.toString()).toBuffer(), withdrawFeeNumerator: new u64(fees.withdraw.numerator.toString()).toBuffer(), withdrawFeeDenominator: new u64( - fees.withdraw.denominator.toString() + fees.withdraw.denominator.toString(), ).toBuffer(), }); export const decodeFees = (raw: RawFees): Fees => ({ adminTrade: new Percent( u64.fromBuffer(Buffer.from(raw.adminTradeFeeNumerator)).toString(), - u64.fromBuffer(Buffer.from(raw.adminTradeFeeDenominator)).toString() + u64.fromBuffer(Buffer.from(raw.adminTradeFeeDenominator)).toString(), ), adminWithdraw: new Percent( u64.fromBuffer(Buffer.from(raw.adminWithdrawFeeNumerator)).toString(), - u64.fromBuffer(Buffer.from(raw.adminWithdrawFeeDenominator)).toString() + u64.fromBuffer(Buffer.from(raw.adminWithdrawFeeDenominator)).toString(), ), trade: new Percent( u64.fromBuffer(Buffer.from(raw.tradeFeeNumerator)).toString(), - u64.fromBuffer(Buffer.from(raw.tradeFeeDenominator)).toString() + u64.fromBuffer(Buffer.from(raw.tradeFeeDenominator)).toString(), ), withdraw: new Percent( u64.fromBuffer(Buffer.from(raw.withdrawFeeNumerator)).toString(), - u64.fromBuffer(Buffer.from(raw.withdrawFeeDenominator)).toString() + u64.fromBuffer(Buffer.from(raw.withdrawFeeDenominator)).toString(), ), }); diff --git a/packages/stableswap-sdk/src/state/index.ts b/packages/stableswap-sdk/src/state/index.ts index a66967262..335fe9418 100644 --- a/packages/stableswap-sdk/src/state/index.ts +++ b/packages/stableswap-sdk/src/state/index.ts @@ -96,10 +96,10 @@ export const decodeSwap = (data: Buffer): StableSwapState => { const mintA = new PublicKey(stableSwapData.mintA); const mintB = new PublicKey(stableSwapData.mintB); const initialAmpFactor = u64.fromBuffer( - Buffer.from(stableSwapData.initialAmpFactor) + Buffer.from(stableSwapData.initialAmpFactor), ); const targetAmpFactor = u64.fromBuffer( - Buffer.from(stableSwapData.targetAmpFactor) + Buffer.from(stableSwapData.targetAmpFactor), ); const startRampTimestamp = stableSwapData.startRampTs; const stopRampTimestamp = stableSwapData.stopRampTs; diff --git a/packages/stableswap-sdk/src/state/layout.ts b/packages/stableswap-sdk/src/state/layout.ts index d7fff2334..20af615b7 100644 --- a/packages/stableswap-sdk/src/state/layout.ts +++ b/packages/stableswap-sdk/src/state/layout.ts @@ -29,7 +29,7 @@ export const FeesLayout = BufferLayout.struct( Uint64Layout("withdrawFeeNumerator"), Uint64Layout("withdrawFeeDenominator"), ], - "fees" + "fees", ); /** diff --git a/packages/stableswap-sdk/src/util/account.ts b/packages/stableswap-sdk/src/util/account.ts index fad2addc8..b0a3185ee 100644 --- a/packages/stableswap-sdk/src/util/account.ts +++ b/packages/stableswap-sdk/src/util/account.ts @@ -10,7 +10,7 @@ import type { Connection, PublicKey } from "@solana/web3.js"; export const loadProgramAccount = async ( connection: Connection, address: PublicKey, - programId: PublicKey + programId: PublicKey, ): Promise => { const accountInfo = await connection.getAccountInfo(address); if (accountInfo === null) { @@ -19,7 +19,7 @@ export const loadProgramAccount = async ( if (!accountInfo.owner.equals(programId)) { throw new Error( - `Invalid owner: expected ${programId.toBase58()}, found ${accountInfo.owner.toBase58()}` + `Invalid owner: expected ${programId.toBase58()}, found ${accountInfo.owner.toBase58()}`, ); } diff --git a/packages/stableswap-sdk/src/util/initialize.ts b/packages/stableswap-sdk/src/util/initialize.ts index 3e3590c1c..51a2af7b5 100644 --- a/packages/stableswap-sdk/src/util/initialize.ts +++ b/packages/stableswap-sdk/src/util/initialize.ts @@ -84,11 +84,11 @@ export interface InitializeNewStableSwapArgs export const initializeStableSwap = async ( provider: Provider, stableSwapAccount: Signer, - initializeSwapInstruction: InitializeSwapInstruction + initializeSwapInstruction: InitializeSwapInstruction, ): Promise => { if ( !stableSwapAccount.publicKey.equals( - initializeSwapInstruction.config.swapAccount + initializeSwapInstruction.config.swapAccount, ) ) { throw new Error("stable swap public key"); @@ -114,7 +114,7 @@ export const initializeStableSwap = async ( * @returns */ export const loadSwapFromInitializeArgs = ( - initializeArgs: InitializeSwapInstruction + initializeArgs: InitializeSwapInstruction, ): StableSwap => new StableSwap(initializeArgs.config, { isInitialized: true, @@ -207,7 +207,7 @@ export const createInitializeStableSwapInstructions = async ({ // Create authority and nonce const [authority, nonce] = await findSwapAuthorityKey( swapAccount, - swapProgramID + swapProgramID, ); // Create LP token mint @@ -215,10 +215,10 @@ export const createInitializeStableSwapInstructions = async ({ provider.connection, tokenAMint, TOKEN_PROGRAM_ID, - Keypair.generate() + Keypair.generate(), ).getMintInfo(); const mintBalanceNeeded = await SPLToken.getMinBalanceRentForExemptMint( - provider.connection + provider.connection, ); instructions.createLPTokenMint = await createInitMintInstructions({ provider, @@ -242,7 +242,7 @@ export const createInitializeStableSwapInstructions = async ({ if (lpAccount.instruction) { instructions.createInitialLPTokenAccount = new TransactionEnvelope( provider, - [lpAccount.instruction] + [lpAccount.instruction], ); } } else { @@ -362,7 +362,7 @@ const initializeSwapTokenInfo = async ({ adminFeeAccount: adminFeeAccount, }, instructions: createSwapTokenAccountInstructions.combine( - createAdminFeeAccountInstructions + createAdminFeeAccountInstructions, ), }; }; @@ -386,7 +386,7 @@ export const createInitializeStableSwapInstructionsRaw = async ({ }> => { // Allocate memory for the account const balanceNeeded = await StableSwap.getMinBalanceRentForExemptStableSwap( - provider.connection + provider.connection, ); return { balanceNeeded, @@ -453,7 +453,7 @@ export const deployNewSwap = async ({ * This is split into two transactions: setup and initialize, to ensure we are under the size limit. */ export const createInitializeNewSwapTx = async ( - args: InitializeNewStableSwapArgs + args: InitializeNewStableSwapArgs, ): Promise<{ swap: StableSwap; initializeArgs: InitializeSwapInstruction; @@ -480,7 +480,7 @@ export const createInitializeNewSwapTx = async ( return new TransactionEnvelope( provider, instructions[method].instructions.slice(), - instructions[method].signers.slice() + instructions[method].signers.slice(), ); }) .reduce((acc, tx) => acc.combine(tx)); @@ -492,7 +492,7 @@ export const createInitializeNewSwapTx = async ( return new TransactionEnvelope( provider, instructions[method].instructions.slice(), - instructions[method].signers.slice() + instructions[method].signers.slice(), ); }) .reduce((acc, tx) => acc.combine(tx)); @@ -500,7 +500,7 @@ export const createInitializeNewSwapTx = async ( const initializeSwap = new TransactionEnvelope( provider, instructions.initializeSwap.instructions.slice(), - instructions.initializeSwap.signers.slice() + instructions.initializeSwap.signers.slice(), ); const newSwap = loadSwapFromInitializeArgs(initializeArgs); diff --git a/packages/stableswap-sdk/src/util/initializeSimple.ts b/packages/stableswap-sdk/src/util/initializeSimple.ts index e28743d91..3cd1ae7cc 100644 --- a/packages/stableswap-sdk/src/util/initializeSimple.ts +++ b/packages/stableswap-sdk/src/util/initializeSimple.ts @@ -61,7 +61,7 @@ const initializeSwapTokenInfoSync = ({ adminFeeAccount: adminFeeAccount, }, instructions: createSwapTokenAccountInstructions.combine( - createAdminFeeAccountInstructions + createAdminFeeAccountInstructions, ), }; }; @@ -134,7 +134,7 @@ export const createInitializeStableSwapInstructionsSimple = async ({ const rentExemptTokenAccountBalance = await SPLToken.getMinBalanceRentForExemptAccount(provider.connection); const rentExemptMintBalance = await SPLToken.getMinBalanceRentForExemptMint( - provider.connection + provider.connection, ); // Create swap account if not specified @@ -204,7 +204,7 @@ export const createInitializeStableSwapInstructionsSimple = async ({ const seedPoolAccountsTX = new TransactionEnvelope( provider, [...seedPoolAccountsResult.instructions], - [...seedPoolAccountsResult.signers] + [...seedPoolAccountsResult.signers], ); const initializeSwapInstruction: InitializeSwapInstruction = { @@ -235,7 +235,7 @@ export const createInitializeStableSwapInstructionsSimple = async ({ const initializeSwap = new TransactionEnvelope( provider, [...initializeStableSwapInstructions], - [swapAccountSigner] + [swapAccountSigner], ); const instructions = { diff --git a/packages/stableswap-sdk/src/util/instructions.ts b/packages/stableswap-sdk/src/util/instructions.ts index ebe27eead..07617c75d 100644 --- a/packages/stableswap-sdk/src/util/instructions.ts +++ b/packages/stableswap-sdk/src/util/instructions.ts @@ -52,7 +52,7 @@ export const executeTxInstructions = async ( provider: Provider; payerSigner: Signer; options?: ConfirmOptions; - } + }, ): Promise => { console.log(`Running tx ${title}`); const txEnv = new TransactionEnvelope(provider, instructions.slice(), [ @@ -69,7 +69,7 @@ export const executeTxInstructions = async ( export const mergeInstructions = ( mut: MutableTransactionInstructions, - inst: TransactionInstructions + inst: TransactionInstructions, ): void => { mut.instructions.push(...inst.instructions); mut.signers.push(...inst.signers); diff --git a/packages/token-utils/src/ata.ts b/packages/token-utils/src/ata.ts index 8f47a7669..009f06e4d 100644 --- a/packages/token-utils/src/ata.ts +++ b/packages/token-utils/src/ata.ts @@ -32,7 +32,7 @@ export const getATAAddressSync = ({ }): PublicKey => { return getProgramAddress( [owner.toBuffer(), TOKEN_PROGRAM_ID.toBuffer(), mint.toBuffer()], - ASSOCIATED_TOKEN_PROGRAM_ID + ASSOCIATED_TOKEN_PROGRAM_ID, ); }; @@ -84,7 +84,7 @@ export const getATAAddressesSync = ({ } => { const result = Object.entries(mints).map( ( - args + args, ): { address: PublicKey; name: string; @@ -100,7 +100,7 @@ export const getATAAddressesSync = ({ name, mint, }; - } + }, ); const deduped = result.reduce( (acc, { address, name, mint }) => { @@ -113,7 +113,7 @@ export const getATAAddressesSync = ({ }, { accounts: {} } as { accounts: ATAMap; - } + }, ); return { accounts: deduped.accounts, diff --git a/packages/token-utils/src/common.ts b/packages/token-utils/src/common.ts index 55afe8bce..c13795a9e 100644 --- a/packages/token-utils/src/common.ts +++ b/packages/token-utils/src/common.ts @@ -31,13 +31,13 @@ export type { ProgramAccount } from "@saberhq/solana-contrib"; export const DEFAULT_TOKEN_DECIMALS = 6; export const SPL_SHARED_MEMORY_ID = new PublicKey( - "shmem4EWT2sPdVGvTZCzXXRAURL9G5vpPxNwSeKhHUL" + "shmem4EWT2sPdVGvTZCzXXRAURL9G5vpPxNwSeKhHUL", ); export async function createMint( provider: Provider, authority?: PublicKey, - decimals?: number + decimals?: number, ): Promise { if (authority === undefined) { authority = provider.wallet.publicKey; @@ -47,7 +47,7 @@ export async function createMint( provider, authority, mint.publicKey, - decimals + decimals, ); const tx = new Transaction(); @@ -69,11 +69,11 @@ export async function createMint( export async function createToken( provider: Provider, authority?: PublicKey, - decimals = 6 + decimals = 6, ): Promise { return Token.fromMint( await createMint(provider, authority, decimals), - decimals + decimals, ); } @@ -81,7 +81,7 @@ export async function createMintInstructions( provider: Provider, authority: PublicKey, mint: PublicKey, - decimals = 6 + decimals = 6, ): Promise { const instructions = [ SystemProgram.createAccount({ @@ -89,7 +89,7 @@ export async function createMintInstructions( newAccountPubkey: mint, space: MintLayout.span, lamports: await provider.connection.getMinimumBalanceForRentExemption( - MintLayout.span + MintLayout.span, ), programId: TOKEN_PROGRAM_ID, }), @@ -98,7 +98,7 @@ export async function createMintInstructions( mint, decimals, authority, - null + null, ), ]; return instructions; @@ -108,7 +108,7 @@ export async function createMintAndVault( provider: Provider, amount: BN, owner?: PublicKey, - decimals?: number + decimals?: number, ): Promise<[PublicKey, PublicKey]> { if (owner === undefined) { owner = provider.wallet.publicKey; @@ -121,22 +121,21 @@ export async function createMintAndVault( provider, provider.wallet.publicKey, mint.publicKey, - decimals + decimals, )), SystemProgram.createAccount({ fromPubkey: provider.wallet.publicKey, newAccountPubkey: vault.publicKey, space: 165, - lamports: await provider.connection.getMinimumBalanceForRentExemption( - 165 - ), + lamports: + await provider.connection.getMinimumBalanceForRentExemption(165), programId: TOKEN_PROGRAM_ID, }), SPLToken.createInitAccountInstruction( TOKEN_PROGRAM_ID, mint.publicKey, vault.publicKey, - owner + owner, ), SPLToken.createMintToInstruction( TOKEN_PROGRAM_ID, @@ -144,8 +143,8 @@ export async function createMintAndVault( vault.publicKey, provider.wallet.publicKey, [], - amount - ) + amount, + ), ); await provider.send(tx, [mint, vault]); return [mint.publicKey, vault.publicKey]; @@ -156,7 +155,7 @@ export async function createTokenAccountInstrs( newAccountPubkey: PublicKey, mint: PublicKey, owner: PublicKey, - lamports?: number + lamports?: number, ): Promise { if (lamports === undefined) { lamports = await provider.connection.getMinimumBalanceForRentExemption(165); @@ -173,7 +172,7 @@ export async function createTokenAccountInstrs( TOKEN_PROGRAM_ID, mint, newAccountPubkey, - owner + owner, ), ]; } @@ -181,7 +180,7 @@ export async function createTokenAccountInstrs( export async function createAccountRentExempt( provider: Provider, programId: PublicKey, - size: number + size: number, ): Promise { const acc = Keypair.generate(); const tx = new Transaction(); @@ -190,11 +189,10 @@ export async function createAccountRentExempt( fromPubkey: provider.wallet.publicKey, newAccountPubkey: acc.publicKey, space: size, - lamports: await provider.connection.getMinimumBalanceForRentExemption( - size - ), + lamports: + await provider.connection.getMinimumBalanceForRentExemption(size), programId, - }) + }), ); await provider.send(tx, [acc]); return acc; @@ -202,7 +200,7 @@ export async function createAccountRentExempt( export async function getMintInfo( provider: Provider, - addr: PublicKey + addr: PublicKey, ): Promise { const depositorAccInfo = await provider.getAccountInfo(addr); if (depositorAccInfo === null) { @@ -213,7 +211,7 @@ export async function getMintInfo( export async function getTokenAccount( provider: Provider, - addr: PublicKey + addr: PublicKey, ): Promise { const depositorAccInfo = await provider.getAccountInfo(addr); if (depositorAccInfo === null) { diff --git a/packages/token-utils/src/instructions/account.ts b/packages/token-utils/src/instructions/account.ts index 7a208efc2..25ade9944 100644 --- a/packages/token-utils/src/instructions/account.ts +++ b/packages/token-utils/src/instructions/account.ts @@ -79,10 +79,10 @@ export const buildCreateTokenAccountTX = ({ TOKEN_PROGRAM_ID, mint, tokenAccount, - owner + owner, ), ], - [accountSigner] + [accountSigner], ), }; }; diff --git a/packages/token-utils/src/instructions/ata.ts b/packages/token-utils/src/instructions/ata.ts index 6eb9c626b..9dfd017b9 100644 --- a/packages/token-utils/src/instructions/ata.ts +++ b/packages/token-utils/src/instructions/ata.ts @@ -104,8 +104,8 @@ export const getOrCreateATAs = async ({ name, mintKey, }; - } - ) + }, + ), ); const deduped = result.reduce( @@ -131,7 +131,7 @@ export const getOrCreateATAs = async ({ accounts: { [key in K]?: PublicKey }; createAccountInstructions: { [key in K]?: TransactionInstruction | null }; instructions: { [address: string]: TransactionInstruction }; - } + }, ); return { accounts: deduped.accounts, @@ -161,5 +161,5 @@ export const createATAInstruction = ({ mint, address, owner, - payer + payer, ); diff --git a/packages/token-utils/src/instructions/mint.ts b/packages/token-utils/src/instructions/mint.ts index 66a30a64f..649f24d1a 100644 --- a/packages/token-utils/src/instructions/mint.ts +++ b/packages/token-utils/src/instructions/mint.ts @@ -30,7 +30,7 @@ export const createInitMintInstructions = async ({ mintKP, decimals, rentExemptMintBalance: await SPLToken.getMinBalanceRentForExemptMint( - provider.connection + provider.connection, ), mintAuthority, freezeAuthority, @@ -73,10 +73,10 @@ export const createInitMintTX = ({ mintKP.publicKey, decimals, mintAuthority, - freezeAuthority + freezeAuthority, ), ], - [mintKP] + [mintKP], ); }; @@ -102,9 +102,9 @@ export const createMintToInstruction = ({ to, mintAuthorityKP.publicKey, [], - amount + amount, ), ], - [mintAuthorityKP] + [mintAuthorityKP], ); }; diff --git a/packages/token-utils/src/instructions/nft.ts b/packages/token-utils/src/instructions/nft.ts index 52231fe23..08077919a 100644 --- a/packages/token-utils/src/instructions/nft.ts +++ b/packages/token-utils/src/instructions/nft.ts @@ -8,7 +8,7 @@ import { createInitMintInstructions } from "./mint.js"; export const mintNFT = async ( provider: Provider, mintKP: Signer, - owner: PublicKey = provider.wallet.publicKey + owner: PublicKey = provider.wallet.publicKey, ): Promise => { // Temporary mint authority const tempMintAuthority = provider.wallet.publicKey; @@ -37,8 +37,8 @@ export const mintNFT = async ( address, tempMintAuthority, [], - new u64(1) - ) + new u64(1), + ), ); // Set mint authority of the NFT to NULL tx.instructions.push( @@ -48,8 +48,8 @@ export const mintNFT = async ( null, "MintTokens", tempMintAuthority, - [] - ) + [], + ), ); return tx; diff --git a/packages/token-utils/src/layout.ts b/packages/token-utils/src/layout.ts index f68b7f914..b1b3aa524 100644 --- a/packages/token-utils/src/layout.ts +++ b/packages/token-utils/src/layout.ts @@ -23,7 +23,7 @@ export { export const structLayout = ( fields: Layout[], property?: string | undefined, - decodePrefixes?: boolean | undefined + decodePrefixes?: boolean | undefined, ): BufferLayout.Structure => BufferLayout.struct(fields, property, decodePrefixes); diff --git a/packages/token-utils/src/price.ts b/packages/token-utils/src/price.ts index 277696c16..de340b4bd 100644 --- a/packages/token-utils/src/price.ts +++ b/packages/token-utils/src/price.ts @@ -18,7 +18,7 @@ export class Price extends UPrice { baseCurrency: Token, quoteCurrency: Token, denominator: BigintIsh, - numerator: BigintIsh + numerator: BigintIsh, ) { super(baseCurrency, quoteCurrency, denominator, numerator); } @@ -27,13 +27,13 @@ export class Price extends UPrice { baseCurrency: Token, quoteCurrency: Token, denominator: BigintIsh, - numerator: BigintIsh + numerator: BigintIsh, ): this { return new Price( baseCurrency, quoteCurrency, denominator, - numerator + numerator, ) as this; } @@ -42,7 +42,7 @@ export class Price extends UPrice { price.baseCurrency, price.quoteCurrency, price.denominator, - price.numerator + price.numerator, ); } } diff --git a/packages/token-utils/src/token.ts b/packages/token-utils/src/token.ts index 44e0e96fb..6b499003c 100644 --- a/packages/token-utils/src/token.ts +++ b/packages/token-utils/src/token.ts @@ -11,7 +11,7 @@ import type { TokenInfo } from "./tokenList.js"; * Magic value representing the raw, underlying Solana native asset. */ export const RAW_SOL_MINT = new PublicKey( - "RawSo11111111111111111111111111111111111112" + "RawSo11111111111111111111111111111111111112", ); /** @@ -123,7 +123,7 @@ export class Token implements UToken { static fromMint = ( mint: PublicKey | string, decimals: number, - opts: Partial> = {} + opts: Partial> = {}, ): Token => new Token({ ...opts, @@ -148,7 +148,7 @@ export class Token implements UToken { static load = async ( connection: Connection, mint: PublicKey, - info: Partial> = {} + info: Partial> = {}, ): Promise => { if (typeof info.decimals === "number") { return Token.fromMint(mint, info.decimals, info); @@ -170,7 +170,7 @@ export class Token implements UToken { */ export const tokensEqual = ( a: Token | undefined, - b: Token | undefined + b: Token | undefined, ): boolean => a !== undefined && b !== undefined && @@ -204,7 +204,7 @@ const wrappedSol = { * Creates a Token for all networks. */ export const makeTokenForAllNetworks = ( - token: Omit + token: Omit, ): TokenMap => ({ "mainnet-beta": new Token({ ...token, chainId: ChainId.MainnetBeta }), devnet: new Token({ ...token, chainId: ChainId.Devnet }), @@ -228,7 +228,7 @@ export const NETWORK_TO_CHAIN_ID = { }; export const CHAIN_ID_TO_NETWORK: { [E in ChainId]: Network } = Object.entries( - NETWORK_TO_CHAIN_ID + NETWORK_TO_CHAIN_ID, ).reduce((acc, [network, env]) => ({ ...acc, [env]: network }), {}) as { [E in ChainId]: Network; }; diff --git a/packages/token-utils/src/tokenAmount.ts b/packages/token-utils/src/tokenAmount.ts index eaa6cd214..50d37a2f7 100644 --- a/packages/token-utils/src/tokenAmount.ts +++ b/packages/token-utils/src/tokenAmount.ts @@ -57,7 +57,7 @@ export class TokenAmount extends UTokenAmount { divideByInteger(other: BigintIsh): TokenAmount { return new TokenAmount( this.token, - this.toU64().div(new BN(parseBigintIsh(other).toString())) + this.toU64().div(new BN(parseBigintIsh(other).toString())), ); } diff --git a/packages/token-utils/src/tokenList.ts b/packages/token-utils/src/tokenList.ts index bf7238efa..a39c4f0d3 100644 --- a/packages/token-utils/src/tokenList.ts +++ b/packages/token-utils/src/tokenList.ts @@ -24,7 +24,7 @@ export const ORIGIN_CHAINS = [ /** * Known origin chains. */ -export type OriginChain = typeof ORIGIN_CHAINS[number]; +export type OriginChain = (typeof ORIGIN_CHAINS)[number]; /** * Token extensions with additional information. diff --git a/packages/token-utils/src/tokenOwner.ts b/packages/token-utils/src/tokenOwner.ts index ec4894780..c6e7c542a 100644 --- a/packages/token-utils/src/tokenOwner.ts +++ b/packages/token-utils/src/tokenOwner.ts @@ -42,7 +42,7 @@ export class TokenOwner { */ async transfer( amount: TokenAmount, - to: PublicKey + to: PublicKey, ): Promise { return SPLToken.createTransferInstruction( TOKEN_PROGRAM_ID, @@ -50,7 +50,7 @@ export class TokenOwner { to, this.owner, [], - amount.toU64() + amount.toU64(), ); } @@ -62,7 +62,7 @@ export class TokenOwner { */ async transferChecked( amount: TokenAmount, - to: PublicKey + to: PublicKey, ): Promise { return SPLToken.createTransferCheckedInstruction( TOKEN_PROGRAM_ID, @@ -72,7 +72,7 @@ export class TokenOwner { this.owner, [], amount.toU64(), - amount.token.decimals + amount.token.decimals, ); } @@ -89,7 +89,7 @@ export class TokenOwner { to, this.owner, [], - amount.toU64() + amount.toU64(), ); } @@ -101,7 +101,7 @@ export class TokenOwner { */ async createATA( mint: PublicKey, - payer: PublicKey = this.owner + payer: PublicKey = this.owner, ): Promise { return SPLToken.createAssociatedTokenAccountInstruction( ASSOCIATED_TOKEN_PROGRAM_ID, @@ -109,7 +109,7 @@ export class TokenOwner { mint, await this.getATA(mint), this.owner, - payer + payer, ); } } diff --git a/packages/token-utils/src/tokenProvider.ts b/packages/token-utils/src/tokenProvider.ts index d60ff893d..9c19c0d2b 100644 --- a/packages/token-utils/src/tokenProvider.ts +++ b/packages/token-utils/src/tokenProvider.ts @@ -46,7 +46,7 @@ export class TokenAugmentedProvider this.provider, authority, mintKP.publicKey, - decimals + decimals, ); return { token: Token.fromMint(mintKP.publicKey, decimals), @@ -81,8 +81,8 @@ export class TokenAugmentedProvider destination, this.walletKey, [], - amount.toU64() - ) + amount.toU64(), + ), ); return txEnv; } @@ -203,7 +203,7 @@ export class TokenAugmentedProvider */ async loadToken( mint: PublicKey, - info: Partial> = {} + info: Partial> = {}, ): Promise { return Token.load(this.provider.connection, mint, info); } @@ -227,7 +227,7 @@ export class TokenAugmentedProvider destination, this.walletKey, [], - amount.toU64() + amount.toU64(), ), ]); } @@ -276,7 +276,7 @@ export class TokenAugmentedProvider * @returns */ async fetchTokenAccount( - address: PublicKey + address: PublicKey, ): Promise { const tokenAccountInfo = await this.getAccountInfo(address); if (tokenAccountInfo === null) { @@ -293,7 +293,7 @@ export class TokenAugmentedProvider */ async fetchATA( mint: PublicKey, - owner: PublicKey = this.walletKey + owner: PublicKey = this.walletKey, ): Promise { const taAddress = await getATAAddress({ mint, owner }); return await this.fetchTokenAccount(taAddress); diff --git a/packages/tuple-utils/src/fill.ts b/packages/tuple-utils/src/fill.ts index 87b5f4d19..861860647 100644 --- a/packages/tuple-utils/src/fill.ts +++ b/packages/tuple-utils/src/fill.ts @@ -5,7 +5,7 @@ import type { Tuple } from "./tuple.js"; */ export const tupleFill = ( value: V, - tuple: Tuple + tuple: Tuple, ): Tuple => { return tuple.map(() => value) as Tuple; }; diff --git a/packages/tuple-utils/src/map.ts b/packages/tuple-utils/src/map.ts index 122a215d9..636d6944c 100644 --- a/packages/tuple-utils/src/map.ts +++ b/packages/tuple-utils/src/map.ts @@ -8,7 +8,7 @@ import type { Tuple } from "./tuple.js"; */ export const tupleMapInner = ( mapFn: (v: T) => U, - tuple: Tuple, N> + tuple: Tuple, N>, ): Tuple, N> => { return tuple.map((v) => mapN(mapFn, v)) as Tuple, N>; }; diff --git a/packages/use-solana/src/adapters/ledger/core.ts b/packages/use-solana/src/adapters/ledger/core.ts index 0928748a6..cfa8f6717 100644 --- a/packages/use-solana/src/adapters/ledger/core.ts +++ b/packages/use-solana/src/adapters/ledger/core.ts @@ -22,7 +22,7 @@ async function ledgerSend( transport: Transport, instruction: number, p1: number, - payload: Buffer + payload: Buffer, ) { let p2 = 0; let payloadOffset = 0; @@ -36,7 +36,7 @@ async function ledgerSend( instruction, p1, p2 | P2_MORE, - chunk + chunk, ); if (reply.length !== 2) { throw new Error("Received unexpected reply payload"); @@ -58,7 +58,7 @@ function harden(n = 0) { export function getSolanaDerivationPath( account?: number, - change?: number + change?: number, ): Buffer { let length; if (account !== undefined) { @@ -93,7 +93,7 @@ export function getSolanaDerivationPath( export async function signTransaction( transport: Transport, transaction: Transaction, - derivationPath: Buffer = getSolanaDerivationPath() + derivationPath: Buffer = getSolanaDerivationPath(), ): Promise { const messageBytes = transaction.serializeMessage(); return signBytes(transport, messageBytes, derivationPath); @@ -102,7 +102,7 @@ export async function signTransaction( export async function signBytes( transport: Transport, bytes: Buffer, - derivationPath: Buffer = getSolanaDerivationPath() + derivationPath: Buffer = getSolanaDerivationPath(), ): Promise { const numPaths = Buffer.alloc(1); numPaths.writeUInt8(1, 0); @@ -116,13 +116,13 @@ export async function signBytes( export async function getPublicKey( transport: Transport, - derivationPath: Buffer = getSolanaDerivationPath() + derivationPath: Buffer = getSolanaDerivationPath(), ): Promise { const publicKeyBytes = await ledgerSend( transport, INS_GET_PUBKEY, P1_NON_CONFIRM, - derivationPath + derivationPath, ); return new PublicKey(publicKeyBytes); diff --git a/packages/use-solana/src/adapters/ledger/index.ts b/packages/use-solana/src/adapters/ledger/index.ts index cb9e2f55c..895cf5548 100644 --- a/packages/use-solana/src/adapters/ledger/index.ts +++ b/packages/use-solana/src/adapters/ledger/index.ts @@ -52,18 +52,18 @@ export class LedgerWalletAdapter extends EventEmitter implements WalletAdapter { transaction: Transaction, _connection: Connection, broadcaster: Broadcaster, - opts?: SignAndBroadcastOptions + opts?: SignAndBroadcastOptions, ): Promise { return await doSignAndBroadcastTransaction( this as ConnectedWallet, transaction, broadcaster, - opts + opts, ); } async signAllTransactions( - transactions: Transaction[] + transactions: Transaction[], ): Promise { const result: Transaction[] = []; for (let i = 0; i < transactions.length; i++) { @@ -85,7 +85,7 @@ export class LedgerWalletAdapter extends EventEmitter implements WalletAdapter { const signature = await signTransaction( this._transport, transaction, - this._derivationPath + this._derivationPath, ); transaction.addSignature(this._publicKey, signature); @@ -111,7 +111,7 @@ export class LedgerWalletAdapter extends EventEmitter implements WalletAdapter { this._derivationPath = getSolanaDerivationPath(account, change); this._publicKey = await getPublicKey( this._transport, - this._derivationPath + this._derivationPath, ); } else { this._publicKey = await getPublicKey(this._transport); @@ -155,7 +155,7 @@ export class LedgerWalletAdapter extends EventEmitter implements WalletAdapter { * @returns */ static async fetchAccountsForPaths( - paths: LedgerHDWalletPath[] + paths: LedgerHDWalletPath[], ): Promise { let transport: Transport | null = null; try { @@ -164,7 +164,7 @@ export class LedgerWalletAdapter extends EventEmitter implements WalletAdapter { for (const path of paths) { const derivationPath = getSolanaDerivationPath( path.account, - path.change + path.change, ); ret.push({ ...path, diff --git a/packages/use-solana/src/adapters/readonly/index.ts b/packages/use-solana/src/adapters/readonly/index.ts index 4aad04f04..810da6d2b 100644 --- a/packages/use-solana/src/adapters/readonly/index.ts +++ b/packages/use-solana/src/adapters/readonly/index.ts @@ -61,7 +61,7 @@ export class ReadonlyAdapter extends EventEmitter implements WalletAdapter { _transaction: Transaction, _connection: Connection, _broadcaster: Broadcaster, - _opts?: BroadcastOptions + _opts?: BroadcastOptions, ): Promise { throw new Error("readonly adapter cannot sign transactions"); } diff --git a/packages/use-solana/src/adapters/secret-key/index.ts b/packages/use-solana/src/adapters/secret-key/index.ts index 6c7c45582..26a57caf9 100644 --- a/packages/use-solana/src/adapters/secret-key/index.ts +++ b/packages/use-solana/src/adapters/secret-key/index.ts @@ -39,13 +39,13 @@ export class SecretKeyAdapter extends EventEmitter implements WalletAdapter { transaction: Transaction, _connection: Connection, broadcaster: Broadcaster, - opts?: SignAndBroadcastOptions + opts?: SignAndBroadcastOptions, ): Promise { return await doSignAndBroadcastTransaction( this as ConnectedWallet, transaction, broadcaster, - opts + opts, ); } @@ -80,7 +80,7 @@ export class SecretKeyAdapter extends EventEmitter implements WalletAdapter { throw new Error("Secret key missing."); } this._wallet = new SignerWallet( - Keypair.fromSecretKey(Uint8Array.from(secretKey)) + Keypair.fromSecretKey(Uint8Array.from(secretKey)), ); this._publicKey = this._wallet.publicKey; this._connected = true; diff --git a/packages/use-solana/src/adapters/solana.ts b/packages/use-solana/src/adapters/solana.ts index dbfba53a5..4a385fbd5 100644 --- a/packages/use-solana/src/adapters/solana.ts +++ b/packages/use-solana/src/adapters/solana.ts @@ -30,16 +30,16 @@ export class SolanaWalletAdapter implements WalletAdapter { EventEmitter & { signTransaction: (transaction: Transaction) => Promise; signAllTransactions: ( - transactions: Transaction[] + transactions: Transaction[], ) => Promise; - } + }, ) {} async signAndBroadcastTransaction( transaction: Transaction, connection: Connection, broadcaster: Broadcaster, - opts?: SignAndBroadcastOptions + opts?: SignAndBroadcastOptions, ): Promise { if (!transaction.feePayer) { transaction.feePayer = this.publicKey ?? undefined; @@ -62,7 +62,7 @@ export class SolanaWalletAdapter implements WalletAdapter { } const { signature } = await window.solana.signAndSendTransaction( transaction, - opts + opts, ); return new PendingTransaction(connection, signature); } @@ -96,7 +96,7 @@ export class SolanaWalletAdapter implements WalletAdapter { const signature = await this.adapter.sendTransaction( transaction, connection, - opts + opts, ); return new PendingTransaction(connection, signature); } @@ -104,7 +104,7 @@ export class SolanaWalletAdapter implements WalletAdapter { this as ConnectedWallet, transaction, broadcaster, - opts + opts, ); } @@ -117,7 +117,7 @@ export class SolanaWalletAdapter implements WalletAdapter { } async signAllTransactions( - transactions: Transaction[] + transactions: Transaction[], ): Promise { return this.adapter.signAllTransactions(transactions); } diff --git a/packages/use-solana/src/adapters/types.ts b/packages/use-solana/src/adapters/types.ts index 4b68fd6cc..e037d851e 100644 --- a/packages/use-solana/src/adapters/types.ts +++ b/packages/use-solana/src/adapters/types.ts @@ -33,7 +33,7 @@ export interface WalletAdapter transaction: Transaction, connection: Connection, broadcaster: Broadcaster, - opts?: SignAndBroadcastOptions + opts?: SignAndBroadcastOptions, ): Promise; } @@ -44,7 +44,7 @@ export type WalletOptions = WalletConnectWalletAdapterConfig; export type WalletAdapterBuilder = ( providerUrl: string, endpoint: string, - options?: WalletOptions + options?: WalletOptions, ) => WalletAdapter; /** @@ -93,13 +93,13 @@ export class WrappedWalletAdapter transaction: Transaction, connection: Connection, broadcaster: Broadcaster, - opts?: SignAndBroadcastOptions + opts?: SignAndBroadcastOptions, ): Promise { return this.adapter.signAndBroadcastTransaction( transaction, connection, broadcaster, - opts + opts, ); } diff --git a/packages/use-solana/src/context.tsx b/packages/use-solana/src/context.tsx index 9c6354082..ef856dfc3 100644 --- a/packages/use-solana/src/context.tsx +++ b/packages/use-solana/src/context.tsx @@ -25,13 +25,13 @@ import { useWalletInternal } from "./utils/useWalletInternal"; export interface UseSolana< WalletType extends WalletTypeEnum = typeof DefaultWalletType, - Connected extends boolean = boolean + Connected extends boolean = boolean, > extends ConnectionContext, UseWallet, UseProvider {} export interface UseSolanaArgs< - WalletType extends WalletTypeEnum = typeof DefaultWalletType + WalletType extends WalletTypeEnum = typeof DefaultWalletType, > extends Omit, Partial< Pick< @@ -52,16 +52,16 @@ export interface UseSolanaArgs< const defaultOnConnect = ( wallet: WalletAdapter, - provider: WalletProviderInfo + provider: WalletProviderInfo, ) => { console.log( - `Connected to ${provider.name} wallet: ${wallet.publicKey.toString()}` + `Connected to ${provider.name} wallet: ${wallet.publicKey.toString()}`, ); }; const defaultOnDisconnect = ( _wallet: WalletAdapter, - provider: WalletProviderInfo + provider: WalletProviderInfo, ) => { console.log(`Disconnected from ${provider.name} wallet`); }; @@ -140,7 +140,7 @@ type ProviderProps> = * @returns */ export const SolanaProvider = < - WalletType extends WalletTypeEnum = typeof DefaultWalletType + WalletType extends WalletTypeEnum = typeof DefaultWalletType, >({ children, ...args @@ -156,5 +156,5 @@ export const useSolana = >() => Solana as unknown as Container< UseSolana, UseSolanaArgs - > + >, ); diff --git a/packages/use-solana/src/error.ts b/packages/use-solana/src/error.ts index b63ec4e3c..e9d8bd40d 100644 --- a/packages/use-solana/src/error.ts +++ b/packages/use-solana/src/error.ts @@ -24,13 +24,13 @@ export abstract class UseSolanaDerivedError extends UseSolanaError { constructor( name: string, readonly description: string, - readonly originalError: unknown + readonly originalError: unknown, ) { super( name, `${description}: ${ originalError instanceof Error ? originalError.message : "unknown" - }` + }`, ); if (originalError instanceof Error) { this.stack = originalError.stack; @@ -44,11 +44,14 @@ export abstract class UseSolanaDerivedError extends UseSolanaError { export class WalletAutomaticConnectionError extends UseSolanaDerivedError { level = ErrorLevel.WARN; - constructor(originalError: unknown, readonly info: WalletProviderInfo) { + constructor( + originalError: unknown, + readonly info: WalletProviderInfo, + ) { super( "WalletAutomaticConnectionError", `Error attempting to automatically connect to wallet ${info.name}`, - originalError + originalError, ); } } @@ -59,11 +62,14 @@ export class WalletAutomaticConnectionError extends UseSolanaDerivedError { export class WalletDisconnectError extends UseSolanaDerivedError { level = ErrorLevel.WARN; - constructor(originalError: unknown, readonly info?: WalletProviderInfo) { + constructor( + originalError: unknown, + readonly info?: WalletProviderInfo, + ) { super( "WalletDisconnectError", `Error disconnecting wallet ${info?.name ?? "(unknown)"}`, - originalError + originalError, ); } } @@ -72,19 +78,19 @@ export class WalletDisconnectError extends UseSolanaDerivedError { * Thrown when a wallet activation errors. */ export class WalletActivateError< - WalletType extends WalletTypeEnum + WalletType extends WalletTypeEnum, > extends UseSolanaDerivedError { level = ErrorLevel.ERROR; constructor( originalError: unknown, readonly walletType: WalletType[keyof WalletType], - readonly walletArgs?: Record + readonly walletArgs?: Record, ) { super( "WalletActivateError", `Error activating wallet ${walletType as unknown as string}`, - originalError + originalError, ); } } diff --git a/packages/use-solana/src/hooks.ts b/packages/use-solana/src/hooks.ts index 2435d3bd4..7ce607bca 100644 --- a/packages/use-solana/src/hooks.ts +++ b/packages/use-solana/src/hooks.ts @@ -10,7 +10,7 @@ import type { ConnectionContext } from "./utils/useConnectionInternal"; * Gets the current Solana wallet. */ export function useWallet< - WalletType extends WalletTypeEnum = typeof DefaultWalletType + WalletType extends WalletTypeEnum = typeof DefaultWalletType, >(): UseSolana { const context = useSolana(); if (!context) { diff --git a/packages/use-solana/src/providers.ts b/packages/use-solana/src/providers.ts index a6279ddc7..05e7982b4 100644 --- a/packages/use-solana/src/providers.ts +++ b/packages/use-solana/src/providers.ts @@ -84,7 +84,7 @@ export const DEFAULT_WALLET_PROVIDERS: WalletProviderMap< new SolletWalletAdapter({ provider, network: network as WalletAdapterNetwork, - }) + }), ), isMobile: true, }, @@ -96,7 +96,7 @@ export const DEFAULT_WALLET_PROVIDERS: WalletProviderMap< new SolanaWalletAdapter( new SolletExtensionWalletAdapter({ network: network as WalletAdapterNetwork, - }) + }), ), isInstalled: () => window.sollet !== undefined, @@ -108,7 +108,7 @@ export const DEFAULT_WALLET_PROVIDERS: WalletProviderMap< makeAdapter: ( _provider: string, network: string, - options?: WalletOptions + options?: WalletOptions, ) => { if (!options) { throw new Error("WalletConnect options not provided"); @@ -119,7 +119,7 @@ export const DEFAULT_WALLET_PROVIDERS: WalletProviderMap< | WalletAdapterNetwork.Mainnet | WalletAdapterNetwork.Devnet, options: options["options"] as unknown, - }) + }), ); }, }, diff --git a/packages/use-solana/src/typings/window.d.ts b/packages/use-solana/src/typings/window.d.ts index f618c4df6..abbf3515d 100644 --- a/packages/use-solana/src/typings/window.d.ts +++ b/packages/use-solana/src/typings/window.d.ts @@ -15,7 +15,7 @@ export interface CoinbaseWalletProvider { signAllTransactions(transactions: Transaction[]): Promise; signAndSendTransaction( transaction: Transaction, - options?: SendOptions + options?: SendOptions, ): Promise<{ signature: TransactionSignature }>; signMessage(message: Uint8Array): Promise<{ signature: Uint8Array }>; connect(): Promise; @@ -63,7 +63,7 @@ export interface PhantomProvider { signAndSendTransaction( transaction: Transaction, - options?: SendOptions + options?: SendOptions, ): Promise<{ signature: TransactionSignature }>; signMessage(message: Uint8Array): Promise<{ signature: Uint8Array }>; @@ -118,7 +118,7 @@ declare global { toString(encoding: "base64"): string; }; }, - network?: "devnet" | "mainnet" + network?: "devnet" | "mainnet", ): Promise<{ signature: TransactionSignature }>; }; solong?: { diff --git a/packages/use-solana/src/utils/provider.ts b/packages/use-solana/src/utils/provider.ts index df19bce55..a2520ba26 100644 --- a/packages/use-solana/src/utils/provider.ts +++ b/packages/use-solana/src/utils/provider.ts @@ -25,20 +25,20 @@ export class WalletAdapterTransactionSigner extends SolanaTransactionSigner { readonly connection: Connection, override readonly wallet: ConnectedWallet, broadcaster: Broadcaster, - preflightCommitment: Commitment = "confirmed" + preflightCommitment: Commitment = "confirmed", ) { super(wallet, broadcaster, preflightCommitment); } override async signAndBroadcastTransaction( transaction: Transaction, - opts?: SignAndBroadcastOptions + opts?: SignAndBroadcastOptions, ): Promise { return await this.wallet.signAndBroadcastTransaction( transaction, this.connection, this.broadcaster, - opts + opts, ); } } @@ -54,7 +54,7 @@ export class WalletAdapterProvider extends SolanaProvider { connection: Connection, broadcaster: Broadcaster, override readonly wallet: ConnectedWallet, - opts: ConfirmOptions = DEFAULT_PROVIDER_OPTIONS + opts: ConfirmOptions = DEFAULT_PROVIDER_OPTIONS, ) { super( connection, @@ -65,8 +65,8 @@ export class WalletAdapterProvider extends SolanaProvider { connection, wallet, broadcaster, - opts.preflightCommitment - ) + opts.preflightCommitment, + ), ); } @@ -99,7 +99,7 @@ export class WalletAdapterProvider extends SolanaProvider { const firstBroadcastConnection = broadcastConnections[0]; invariant( firstBroadcastConnection, - "must have at least one broadcast connection" + "must have at least one broadcast connection", ); return new WalletAdapterProvider( connection, @@ -107,7 +107,7 @@ export class WalletAdapterProvider extends SolanaProvider { ? new TieredBroadcaster(connection, broadcastConnections, opts) : new SingleConnectionBroadcaster(firstBroadcastConnection, opts), wallet, - opts + opts, ); } } diff --git a/packages/use-solana/src/utils/useConnectionInternal.ts b/packages/use-solana/src/utils/useConnectionInternal.ts index dc86381f6..036920744 100644 --- a/packages/use-solana/src/utils/useConnectionInternal.ts +++ b/packages/use-solana/src/utils/useConnectionInternal.ts @@ -22,12 +22,12 @@ export interface ConnectionContext { setNetwork: (val: Network) => void | Promise; endpoint: string; setEndpoints: ( - endpoints: Omit + endpoints: Omit, ) => void | Promise; } const makeNetworkConfigMap = ( - partial: PartialNetworkConfigMap + partial: PartialNetworkConfigMap, ): NetworkConfigMap => Object.entries(DEFAULT_NETWORK_CONFIG_MAP).reduce( (acc, [k, v]) => ({ @@ -37,7 +37,7 @@ const makeNetworkConfigMap = ( ...partial[k as Network], }, }), - DEFAULT_NETWORK_CONFIG_MAP + DEFAULT_NETWORK_CONFIG_MAP, ); export interface ConnectionArgs { @@ -61,7 +61,7 @@ export const useConnectionInternal = ({ const [network, setNetwork] = usePersistedKVStore( "use-solana/network", defaultNetwork, - storageAdapter + storageAdapter, ); const configMap = makeNetworkConfigMap(networkConfigs); const config = configMap[network]; @@ -69,7 +69,7 @@ export const useConnectionInternal = ({ usePersistedKVStore>( `use-solana/rpc-endpoint/${network}`, config, - storageAdapter + storageAdapter, ); const connection = useMemo( @@ -79,7 +79,7 @@ export const useConnectionInternal = ({ commitment: connectionConfigArgs.commitment ?? commitment, wsEndpoint: endpointWs, }), - [commitment, connectionConfigArgs, endpoint, endpointWs] + [commitment, connectionConfigArgs, endpoint, endpointWs], ); const sendConnection = useMemo( () => @@ -88,7 +88,7 @@ export const useConnectionInternal = ({ commitment: connectionConfigArgs.commitment ?? commitment, wsEndpoint: endpointWs, }), - [commitment, connectionConfigArgs, endpoint, endpointWs] + [commitment, connectionConfigArgs, endpoint, endpointWs], ); return { diff --git a/packages/use-solana/src/utils/usePersistedKVStore.ts b/packages/use-solana/src/utils/usePersistedKVStore.ts index 7e959a6e7..99fe19c02 100644 --- a/packages/use-solana/src/utils/usePersistedKVStore.ts +++ b/packages/use-solana/src/utils/usePersistedKVStore.ts @@ -5,7 +5,7 @@ import type { StorageAdapter } from "../storage"; export function usePersistedKVStore( key: string, defaultState: T, - storageAdapter: StorageAdapter + storageAdapter: StorageAdapter, ): [T, (newState: T | null) => Promise] { const [state, setState] = useState(null); @@ -33,7 +33,7 @@ export function usePersistedKVStore( setState(newState); } }, - [state, defaultState, storageAdapter, key] + [state, defaultState, storageAdapter, key], ); return [state ?? defaultState, setLocalStorageState]; diff --git a/packages/use-solana/src/utils/useProviderInternal.ts b/packages/use-solana/src/utils/useProviderInternal.ts index b78dd4600..b5104a49d 100644 --- a/packages/use-solana/src/utils/useProviderInternal.ts +++ b/packages/use-solana/src/utils/useProviderInternal.ts @@ -67,7 +67,7 @@ export const useProviderInternal = ({ new SolanaReadonlyProvider(connection, { commitment, }), - [commitment, connection] + [commitment, connection], ); const connected = wallet?.connected; @@ -81,7 +81,7 @@ export const useProviderInternal = ({ broadcastConnections, wallet: wallet as ConnectedWallet, opts: confirmOptions, - }) + }), ) : null, [ @@ -91,7 +91,7 @@ export const useProviderInternal = ({ connection, broadcastConnections, confirmOptions, - ] + ], ); return { diff --git a/packages/use-solana/src/utils/useWalletInternal.ts b/packages/use-solana/src/utils/useWalletInternal.ts index 9f0f66949..5a39726cc 100644 --- a/packages/use-solana/src/utils/useWalletInternal.ts +++ b/packages/use-solana/src/utils/useWalletInternal.ts @@ -28,7 +28,7 @@ import { usePersistedKVStore } from "./usePersistedKVStore"; */ export interface UseWallet< WalletType extends WalletTypeEnum, - Connected extends boolean = boolean + Connected extends boolean = boolean, > { /** * Wallet. @@ -55,7 +55,7 @@ export interface UseWallet< */ activate: ( walletType: WalletType[keyof WalletType], - walletArgs?: Record + walletArgs?: Record, ) => Promise; /** * Disconnects the wallet and prevents auto-reconnect. @@ -66,11 +66,11 @@ export interface UseWallet< export interface UseWalletArgs> { onConnect: ( wallet: WalletAdapter, - provider: WalletProviderInfo + provider: WalletProviderInfo, ) => void; onDisconnect: ( wallet: WalletAdapter, - provider: WalletProviderInfo + provider: WalletProviderInfo, ) => void; onError: (err: UseSolanaError) => void; network: Network; @@ -86,7 +86,7 @@ interface WalletConfig> { } export const useWalletInternal = < - WalletType extends WalletTypeEnum + WalletType extends WalletTypeEnum, >({ onConnect, onDisconnect, @@ -128,7 +128,7 @@ export const useWalletInternal = < const adapter = provider.makeAdapter( provider.url, endpoint, - walletOptions + walletOptions, ); return [provider, new WrappedWalletAdapter(adapter)]; } @@ -161,7 +161,7 @@ export const useWalletInternal = < } } onError( - new WalletAutomaticConnectionError(e, walletProviderInfo) + new WalletAutomaticConnectionError(e, walletProviderInfo), ); } shouldTryConnect = false; @@ -215,7 +215,7 @@ export const useWalletInternal = < const activate = useCallback( async ( nextWalletType: WalletType[keyof WalletType], - nextWalletArgs?: Record + nextWalletArgs?: Record, ): Promise => { setWalletActivating(true); const nextWalletConfigStr = stringify({ @@ -231,15 +231,15 @@ export const useWalletInternal = < new WalletActivateError( e, nextWalletType, - nextWalletArgs - ) + nextWalletArgs, + ), ); } setWalletActivating(false); } await setWalletConfigStr(nextWalletConfigStr); }, - [onError, setWalletConfigStr, wallet, walletConfigStr] + [onError, setWalletConfigStr, wallet, walletConfigStr], ); const disconnect = useCallback(async () => { diff --git a/packages/wallet-adapter-icons/src/index.tsx b/packages/wallet-adapter-icons/src/index.tsx index 6681f2827..245be82cb 100644 --- a/packages/wallet-adapter-icons/src/index.tsx +++ b/packages/wallet-adapter-icons/src/index.tsx @@ -202,7 +202,7 @@ export const PHANTOM: React.FC> = (props) => ( ); export const COINBASE_WALLET: React.FC> = ( - props + props, ) => ( > = (props) => ( // https://upload.wikimedia.org/wikipedia/commons/5/55/Magnifying_glass_icon.svg export const MAGNIFYING_GLASS: React.FC> = ( - props + props, ) => ( > = (props) => ( ); export const WALLETCONNECT: React.FC> = ( - props + props, ) => (