diff --git a/src/wrapper.ts b/src/wrapper.ts index 1ecbd787..d2c518e3 100644 --- a/src/wrapper.ts +++ b/src/wrapper.ts @@ -15,12 +15,14 @@ export class SOR { gasPrice: BigNumber; // avg Balancer swap cost. Can be updated manually if required. swapCost: BigNumber = new BigNumber('100000'); + tokenCost; constructor(Provider: JsonRpcProvider, GasPrice: BigNumber) { this.isSubgraphFetched = false; this.isOnChainFetched = false; this.provider = Provider; this.gasPrice = GasPrice; + this.tokenCost = {}; } async fetchSubgraphPools() { @@ -54,6 +56,24 @@ export class SOR { this.isOnChainFetched = true; } + async setCostOutputToken(TokenOut: string, Cost: BigNumber = null) { + TokenOut = TokenOut.toLowerCase(); + + if (Cost === null) { + // This calculates the cost to make a swap which is used as an input to SOR to allow it to make gas efficient recommendations + const costOutputToken = await sor.getCostOutputToken( + TokenOut, + this.gasPrice, + this.swapCost, + this.provider + ); + + this.tokenCost[TokenOut] = costOutputToken; + } else { + this.tokenCost[TokenOut] = Cost; + } + } + async getSwaps( TokenIn: string, TokenOut: string, @@ -76,13 +96,10 @@ export class SOR { TokenIn = TokenIn.toLowerCase(); TokenOut = TokenOut.toLowerCase(); - // This calculates the cost to make a swap which is used as an input to SOR to allow it to make gas efficient recommendations - const costOutputToken = await sor.getCostOutputToken( - TokenOut, - this.gasPrice, - this.swapCost, - this.provider - ); + let costOutputToken = this.tokenCost[TokenOut]; + if (costOutputToken === undefined) { + costOutputToken = new BigNumber(0); + } // Retrieves all pools that contain both tokenIn & tokenOut, i.e. pools that can be used for direct swaps // Retrieves intermediate pools along with tokens that are contained in these. diff --git a/test/testScripts/example-simpleSwap.ts b/test/testScripts/example-simpleSwap.ts index 3df3652d..b509be70 100644 --- a/test/testScripts/example-simpleSwap.ts +++ b/test/testScripts/example-simpleSwap.ts @@ -31,6 +31,11 @@ async function simpleSwap() { let amountIn = new BigNumber('1000000'); // 1 USDC, Always pay attention to Token Decimals. i.e. In this case USDC has 6 decimals. const maxNoPools = 4; // This determines the max no of pools the SOR will use to swap. + // This calculates the cost to make a swap which is used as an input to SOR to allow it to make gas efficient recommendations. + // Can be set once and will be used for further swap calculations. + // Defaults to 0 if not called or can be set manually using: await SOR.setCostOutputToken(tokenOut, manualPriceBn) + await SOR.setCostOutputToken(tokenOut); + // If getSwaps is called after fetchSubgraphPools() but before fetchOnChainPools() then Subgraph balances are used. // These can potentially be innacurate. By default getSwaps will do a final check of swaps using on-chain info. let [swaps, amountOut] = await SOR.getSwaps(