balancer / balancer-sdk Goto Github PK
View Code? Open in Web Editor NEWLicense: MIT License
License: MIT License
Receiving BalancerError: unsupported pool type
when querying for the pool with poolId 0x726e324c29a1e49309672b244bdc4ff62a270407000200000000000000000702
Here is the code:
import { BalancerSDK, Network } from '@balancer-labs/sdk'
const balancer = new BalancerSDK({
network: getBalancerNetwork(chainId),
rpcUrl: 'https://rpc.tenderly.co/fork/55dd21e2-51d6-4c10-bdc2-8f6140d93a47'
})
const getRewardsAPR = useCallback(async () => {
if (balancer && poolId) {
try {
const { pools } = balancer
console.log(pools, poolId)
const pool = await pools.find('0x726e324c29a1e49309672b244bdc4ff62a270407000200000000000000000702')
console.log('pool', pool)
if (pool) {
const apr = await pools.apr(pool)
console.log('apr', apr)
}
} catch (error) {
console.log(error)
setRewardsAPR('--')
}
}
}, [poolId, balancer])
I'm trying to get the BAL rewards APR for that specific pool
I updated balancer-labs/sdk
to v0.1.44
then upon running the app locally, i encountered an error
TypeScript error in /node_modules/@balancer-labs/sdk/dist/index.d.ts(5479,11)
',' expected. TS1005
5477 | }
5478 | type queryJoinParams = [
> 5479 | poolId: string,
| ^
5480 | sender: string,
5481 | recipient: string,
5482 | request: {
The coingecko is limiting the requests by 30 requests/min, and the full balancer-sdk test suit is surpassing this limit, so the Impermanent Loss tests that use coingecko historical prices requests are being skipped for now.
How should the swaps module interface look. Discuss and link related PRs here.
Hey team,
We've noticed that you're referencing a subgraph deployed on The Graph's hosted service in this repository. Just a heads-up: after June 12th, hosted service subgraph endpoints will no longer be available as the offering is being deprecated.
If you are the subgraph owner or maintainer, it's time to upgrade your subgraph to the network. This ensures everything keeps running smoothly and you get access to all the latest features and improvements. Here is a quick guide with all the upgrade steps.
If you're not the subgraph owner or maintainer, check Graph Explorer to see if the subgraph development team has already upgraded to the network. If you don’t find an upgraded subgraph, a friendly nudge to the subgraph development team would be greatly appreciated—it's a quick process that benefits everyone. Here's the upgrade guide with all the necessary steps for the subgraph development team.
Once the subgraph is upgraded to the network, you can create an API key and updated query URL in Subgraph Studio then update this repository to query from the new endpoint, https://api.studio.thegraph.com/query/<ID>/<SUBGRAPH_NAME>/<VERSION>
Need more support or have more questions? Feel free to reach out to [email protected]. We're here to help!
Cheers,
Paka
BETS/wstETH pool on mainnet is apparently not returning a bptPrice. Was working before apparently.
Fwd: Hi team, I wasn't able to get an answer from Discord, perhaps you could help,
We're facing the issue Error fetching token prices from coingecko with status 400 when fetching the SDK method balancer.pools.bptPrice(pool), is there a way to fix?
Depends on SOR and SG being updated with this new pool.
Tasks to be done after merge/release:
The frontend team cannot use Coingecko API Key without exposing it, so we need to find another way to fetch token prices for the SOR functionality.
Franz suggested to use the API:
the API does not offer a “getPriceForToken” option but rather gives you all token prices for a specific (or multiple) chains. I assume you only need current and not historical prices?
the return value for “getCurrentTokenPrices” are price and contract address
{
tokenGetCurrentPrices(chains: [MAINNET]) {
address
price
}
}
Description:
After upgrading the subgraphs endpoint from version v1.1.5 to v1.1.6-beta.23, this code snippet that refreshes a pool state periodically is no longer functioning as expected. Specifically, the example pool is never refreshed.
Code Snippet:
const balancerSDK = new BalancerSDK({ network: Network.MAINNET, rpcUrl: chainData.chainConfig.nodeEndpoint });
const pool = await balancerSDK.pools.find('0xb9debddf1d894c79d2b2d09f819ff9b856fca55200000000000000000000062a');
if (!pool) throw new Error('Pool not found');
const sleep = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms));
// Every 5 seconds, log rate weWETH / WETH
// eslint-disable-next-line no-constant-condition
while (true) {
await sleep(5_000);
// Refresh pool
await balancerSDK.data.poolsOnChain.refresh(pool);
const res = pool.calcSpotPrice('0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2', '0xcd5fe23c85820f7b72d0926fc9b05b43e359b7ee');
console.log(`timestamp: ${Date.now()} | rate = ${res}`);
}
Expected Behavior:
The pool state should be refreshed every 5 seconds, and the spot price should be logged correctly.
Actual Behavior:
After upgrading to v1.1.6-beta.23, the pool state is never refreshed, and the spot price remains unchanged.
Hey,
I'm trying to use the JavaScript balancer SDK to get a quote on a potential swap. But I'm always getting the error:
pt [BalancerError]: queryBatchSwapWithSor returned 0 amount
...
code: 'SWAP_ZERO_RETURN_AMOUNT'
I'm running on ganache. Here are my parameters:
{
tokensIn: '0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2',
tokensOut: '0x6B175474E89094C44Da98b954EedeAC495271d0F',
swapType: 'ExactIn',
amounts: '10000000000000000000',
fetchPools: { fetchPools: true, fetchOnChain: true }
}
(i've tried toggling fetchPools and fetchOnChain)
My initialization of the SDK:
const balancer = new BalancerSDK({
network: Network.MAINNET,
rpcUrl: `https://eth-mainnet.g.alchemy.com/v2/${config.ALCHEMY_API_KEY}`,
});
And where I call the actual function:
const getBalancerQuote = async (arr, payload) => {
payload = payload.toString() + "000000000000000000";
const fetchPoolsInput = {
fetchPools: true,
fetchOnChain: true,
};
const options = {
tokensIn: arr[0],
tokensOut: arr[1],
swapType: "ExactIn",
amounts: payload,
fetchPools: fetchPoolsInput,
};
const output = await balancer.swaps.queryBatchSwapWithSor(options);
return output;
};
Any suggestions? Thanks!
My code
import { BalancerSDK } from '@balancer-labs/sdk'
const balancer = new BalancerSDK({
network: 5, // Mainnet
rpcUrl: `https://eth-goerli.g.alchemy.com/v2/${process.env.ALCHEMY_API}`,
})
const { swaps } = balancer // Swaps module is abstracting SOR
// console.log(swaps)
// // const balancer = new BalancerSDK(config);
const balance = new BalancerSDK(balancer);
const pool = await balance.pools.find(poolId);
const main = async () => {
const spotPrice = await pool.calcSpotPrice(
ADDRESSES[network].DAI.address,
ADDRESSES[network].BAL.address
);
console.log(spotPrice);
}
After following the procedure on the docs I keep getting the error
node:internal/modules/cjs/loader:1144
const err = new Error(message);
^
Error: Cannot find module 'ethers'
Require stack:
- C:\Users\Lenovo\OneDrive - University of Lagos\Documents\Article Demo\Demo DEX Dapp\DEX\node_modules\@balancer-labs\sdk\dist\index.js
at Module._resolveFilename (node:internal/modules/cjs/loader:1144:15)
at Module._load (node:internal/modules/cjs/loader:985:27)
at Module.require (node:internal/modules/cjs/loader:1235:19)
at require (node:internal/modules/helpers:176:18)
at Object.<anonymous> (C:\Users\Lenovo\OneDrive - University of Lagos\Documents\Article Demo\Demo DEX Dapp\DEX\node_modules\@balancer-labs\sdk\dist\index.js:1:317)
as though ethers is not found in the node_module for the SDK.....
any solution pls
Currently encountering Error: Not Implemented - StablePhantom liquidity should all come from sub-pools.
when querying the APR for a specific pool
import { BalancerSDK, Network } from '@balancer-labs/sdk'
const balancer = new BalancerSDK({
network: getBalancerNetwork(chainId),
rpcUrl: 'https://rpc.tenderly.co/fork/55dd21e2-51d6-4c10-bdc2-8f6140d93a47'
})
const getRewardsAPR = useCallback(async () => {
if (balancer && poolId) {
try {
const { pools } = balancer
console.log(pools, poolId)
const pool = await pools.find('0x8159462d255c1d24915cb51ec361f700174cd99400000000000000000000075d')
console.log('pool', pool)
if (pool) {
const apr = await pools.apr(pool)
console.log('apr', apr)
}
} catch (error) {
console.log(error)
setRewardsAPR('--')
}
}
}, [poolId, balancer])
Expected result:
{
swapFees: 0,
tokenAprs: {
total: 156,
breakdown: { '0x3a58a54c066fdc0f2d55fc9c89f0415c92ebf3c4': 156 }
},
stakingApr: { min: 756, max: 756 },
rewardAprs: {
total: 277,
breakdown: { '0xc3c7d422809852031b44ab29eec9f1eff2a58756': 277 }
},
protocolApr: 0,
min: 1189,
max: 1189
}
How should the pools module interface look. Discuss and link related PRs here.
.
I try a demo code:
const balancer = new BalancerSDK({
network: 1, // Mainnet
rpcUrl: "https://my-eth-rpc" // rpc endpoint
})
const { swaps } = balancer // Swaps module is abstracting SOR
const pools = await swaps.fetchPools();
throws exception:
Unknown pool type: HighAmpComposableStable 0xea912e1afa137c15f1638142e32f978e92fbce390000000000000000000003b4
(anonymous function) onChainData.ts:58
bi onChainData.ts:56
getPools subgrap…oolDataService.ts:92
processTicksAndRejections task_queues:95
Async call from await
(anonymous function) poolCacher.ts:51
(anonymous function) tslib.es6.js:74
__awaiter tslib.es6.js:70
fetchPools poolCacher.ts:49
(anonymous function) wrapper.ts:73
(anonymous function) tslib.es6.js:74
__awaiter tslib.es6.js:70
fetchPools wrapper.ts:72
fetchPools swaps.module.ts:292
(anonymous function) app.ts:45
(anonymous function) app.ts:8
__awaiter app.ts:4
(anonymous function) app.ts:38
dispatch index.js:42
(anonymous function) router.js:425
dispatch index.js:42
(anonymous function) index.js:34
dispatch router.js:430
dispatch index.js:42
bodyParser index.js:78
processTicksAndRejections task_queues:95
Async call from await
dispatch index.js:42
(anonymous function) index.js:34
handleRequest application.js:186
handleRequest application.js:157
emit events:511
emit domain:489
parserOnIncoming _http_server:1105
parserOnHeadersComplete _http_common:119
Async call from HTTPINCOMINGMESSAGE
init inspector_async_hook:25
emitInitNative async_hooks:202
connectionListenerInternal _http_server:638
defaultTriggerAsyncIdScope async_hooks:465
connectionListener _http_server:611
emit events:511
emit domain:489
onconnection net:2095
callbackTrampoline async_hooks:130
Async call from TCPSERVERWRAP
init inspector_async_hook:25
emitInitNative async_hooks:202
createServerHandle net:1736
setupListenHandle net:1779
listenInCluster net:1860
Server.listen net:1948
listen application.js:88
(anonymous function) app.ts:469
Module._compile loader:1267
m._compile index.ts:1618
Module._extensions..js loader:1321
require.extensions.<computed> index.ts:1621
Module.load loader:1125
Module._load loader:965
executeUserEntryPoint run_main:83
phase4 bin.ts:649
bootstrap bin.ts:95
main bin.ts:55
(anonymous function) bin.ts:800
Module._compile loader:1267
Module._extensions..js loader:1321
Module.load loader:1125
Module._load loader:965
executeUserEntryPoint run_main:83
(anonymous function) run_main_module:23
Unknown pool type: HighAmpComposableStable 0x1d1b44a4c5a047bdc9b3f06842566e5ea9c1966d0000000000000000000003b3
(anonymous function) onChainData.ts:58
bi onChainData.ts:56
getPools subgrap…oolDataService.ts:92
processTicksAndRejections task_queues:95
Async call from await
(anonymous function) poolCacher.ts:51
(anonymous function) tslib.es6.js:74
__awaiter tslib.es6.js:70
fetchPools poolCacher.ts:49
(anonymous function) wrapper.ts:73
(anonymous function) tslib.es6.js:74
__awaiter tslib.es6.js:70
fetchPools wrapper.ts:72
fetchPools swaps.module.ts:292
(anonymous function) app.ts:45
(anonymous function) app.ts:8
__awaiter app.ts:4
(anonymous function) app.ts:38
dispatch index.js:42
(anonymous function) router.js:425
dispatch index.js:42
(anonymous function) index.js:34
dispatch router.js:430
dispatch index.js:42
bodyParser index.js:78
processTicksAndRejections task_queues:95
Async call from await
dispatch index.js:42
(anonymous function) index.js:34
handleRequest application.js:186
handleRequest application.js:157
emit events:511
emit domain:489
parserOnIncoming _http_server:1105
parserOnHeadersComplete _http_common:119
Async call from HTTPINCOMINGMESSAGE
init inspector_async_hook:25
emitInitNative async_hooks:202
connectionListenerInternal _http_server:638
defaultTriggerAsyncIdScope async_hooks:465
connectionListener _http_server:611
emit events:511
emit domain:489
onconnection net:2095
callbackTrampoline async_hooks:130
Async call from TCPSERVERWRAP
init inspector_async_hook:25
emitInitNative async_hooks:202
createServerHandle net:1736
setupListenHandle net:1779
listenInCluster net:1860
Server.listen net:1948
listen application.js:88
(anonymous function) app.ts:469
Module._compile loader:1267
m._compile index.ts:1618
Module._extensions..js loader:1321
require.extensions.<computed> index.ts:1621
Module.load loader:1125
Module._load loader:965
executeUserEntryPoint run_main:83
phase4 bin.ts:649
bootstrap bin.ts:95
main bin.ts:55
(anonymous function) bin.ts:800
Module._compile loader:1267
Module._extensions..js loader:1321
Module.load loader:1125
Module._load loader:965
executeUserEntryPoint run_main:83
(anonymous function) run_main_module:23
Error: fetchPools(): Error: Issue with multicall execution.
(anonymous function) poolCacher.ts:58
rejected tslib.es6.js:72
processTicksAndRejections task_queues:95
please help
The README first example (link is in reference) has a wrong typescript interface import
'ConfigSdk' needs to be 'BalancerSdkConfig'
Not Applicable
https://github.com/balancer-labs/balancer-sdk/tree/develop/balancer-js#getting-started
https://github.com/balancer/balancer-sdk/blob/develop/balancer-js/examples/pools/rewards/claim-pools-rewards.ts
Running the given example for Network.MAINNET
with a my Infura mainnet RPC returns the expected result 👍
However, changing the SDK config to Polygon results in an exception where I would at least expect an empty array when calling getClaimableRewardTokens(userAddress) 😢
const balancer = new BalancerSDK({
network: Network.POLYGON,
rpcUrl: `https://polygon-mainnet.infura.io/v3/XXX`,
});
const result = await balancer.claimService?.getClaimableRewardTokens("0x549c660ce2B988F588769d6AD87BE801695b2be3");
Result:
Uncaught (in promise) Error: missing revert data in call exception; Transaction reverted without a reason string [ See: https://links.ethers.org/v5-errors-CALL_EXCEPTION ] (data="0x", transaction={"to":"0xa1B2b503959aedD81512C37e9dce48164ec6a94d","data":"0x252dba42........
This is the line that throws the exception:
A few months ago we started pruning the subgraph at balancer-labs/balancer-polygon-v2 in order to increase the performance for the frontend, but that had unforeseen side effects for 3rd party integrations.
We've switched to a dual deployment model where balancer-labs/balancer-polygon-v2 has the full history and balancer-labs/balancer-polygon-prune-v2 is pruned. Unless any SDK feature relies on time travel queries further in the past than the last 24h, it might make sense to update the default polygon subgraph endpoint to the pruned one
We're integrating swaps through our FXMetaPool, a custom pool built on top of Balancer.
Our aim is to use the Balancer-SDK (js) to faciltate that as its integrated with the Balancer SOR (which we have added code handling of our custom pool).
To give some initial context: We have added handling of our pool type = "FX" in this file and that made our pool recognizable.
However despite numerous attempts, we are roadblocked in this line of code as it is throwing: reason: 'processing response error', code: 'SERVER_ERROR', body: '{"jsonrpc":"2.0","id":43,"error":{"code":-32000,"message":"execution reverted"}}'
I think having a standard guideline in SDK for adding support handling of built custom Balancer pools really helps the integration process.
We saw there are added support for custom pools (e.g: Element Finance).
It would be nice if there are guidelines we can follow to add support for our custom pool as well.
The file balancer-js/examples/swaps/swap.ts
is not working for v1.1.5 due to a function not defined error.
route = await swaps.buildRouteExactIn(
from,
to,
tokenIn,
tokenOut,
amountIn,
{
maxSlippage,
deadline,
}
);
getOnChainBalances on src/test/lib/mainnetPools.ts should update pool totalShares with current on chain data, but it's currently not updating.
try LINK - USDC on Polygon, all zero number
{
'1': 'MAINNET',
'3': 'ROPSTEN',
'4': 'RINKEBY',
'5': 'GÖRLI',
'10': 'OPTIMISM',
'42': 'KOVAN',
'100': 'GNOSIS',
'137': 'POLYGON',
'42161': 'ARBITRUM',
MAINNET: 1,
ROPSTEN: 3,
RINKEBY: 4,
GOERLI: 5,
'GÖRLI': 5,
OPTIMISM: 10,
KOVAN: 42,
GNOSIS: 100,
POLYGON: 137,
ARBITRUM: 42161
}
137
{
tokenAddresses: [],
swaps: [],
swapAmount: BigNumber { _hex: '0x00', _isBigNumber: true },
swapAmountForSwaps: BigNumber { _hex: '0x00', _isBigNumber: true },
tokenIn: '',
tokenInForSwaps: '',
tokenOut: '',
tokenOutFromSwaps: '',
returnAmount: BigNumber { _hex: '0x00', _isBigNumber: true },
returnAmountConsideringFees: BigNumber { _hex: '0x00', _isBigNumber: true },
returnAmountFromSwaps: BigNumber { _hex: '0x00', _isBigNumber: true },
marketSp: '0'
}
Hello,
I'm trying to make balancer-sdk work in a project that uses ethers v6 and I'm having issues with it because balancer-sdk uses ethers v5 (and it uses Interface
class under ethers.util
, in the latest versions it's ethers.Interface
).
Can you consider moving ethers to dependencies so balancer-sdk uses its own ethers
version?
Trying to fork GOERLI as instructed by the README in balancer-js, but the following error pops up.
npx hardhat --tsconfig tsconfig.testing.json --config hardhat.config.goerli.ts
node --fork $(grep ALCHEMY_URL_GOERLI .env | cut -d '=' -f2 | tail -1) --port 8
000
tail: option used in invalid context -- 1
Error HH308: Unrecognized positional argument ALCHEMY_URL_GOERLI
For more info go to https://hardhat.org/HH308 or run Hardhat with --show-stack-t
races
ALCHEMY_URL_GOERLI="https://eth-goerli.g.alchemy.com/v2 KEY
"
Doesn't work for mainnet also.
@RomualdH - in case you're using the SDK instead of the SOR directly, you can find the change here
Hi @brunoguerios, seems now the error is Error fetching token prices from coingecko with status 429
My snippet is:
price = await balancer.pools.bptPrice(
await balancer.pools.find('0x26cc136e9b8fd65466f193a8e5710661ed9a98270002000000000000000005ad')
)
Originally posted by @RomualdH in #548 (comment)
when I use balancer.swaps.fetchPools() I will get this error:
poolCacher.ts:58 Error: fetchPools(): Error: Issue with pool onchain data: Error: invalid BigNumber value (argument="value", value=undefined, code=INVALID_ARGUMENT, version=bignumber/5.7.0)
but there is no such error on mainnet
@johngrantuk need your help
Unable to do a joinPool or exitPool on the new Matic MaticX Composable Stable Pool.
import { BalancerSDK, Network } from '@balancer-labs/sdk';
const config = {
network: Network.POLYGON,
rpcUrl: `https://polygon-rpc.com`,
};
const balancer = new BalancerSDK(config);
const pool = await balancer.pools.find('0xb20fc01d21a50d2c734c4a1262b4404d41fa7bf000000000000000000000075c');
try {
const tokensIn = ['0x0000000000000000000000000000000000000000', '0xb20fc01d21a50d2c734c4a1262b4404d41fa7bf0', '0xfa68FB4628DFF1028CFEc22b4162FCcd0d45efb6'];
const amountsIn = ['0', '0', '10000000000'];
const slippage = '100';
const { to, data, minBPTOut } = pool.buildJoin(
'0x-user-public-address',
tokensIn,
amountsIn,
slippage
);
const priceImpact = await pool.calcPriceImpact(
amountsIn,
minBPTOut
);
await providerWithWallet.sendTransaction({
to,
data,
});
} catch (e) {
console.log(e)
}
Getting STABLE_INVARIANT_DIDNT_CONVERGE
error sometimes but not always, when we don't get the STABLE_INVARIANT_DIDNT_CONVERGE
error, getting BAL#103 INPUT_LENGTH_MISMATCH
when sending the transaction
A declarative, efficient, and flexible JavaScript library for building user interfaces.
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google ❤️ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.