@w3lib/solana-batch-call 0.4.0 → 0.6.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +45 -0
- package/README.md +343 -3
- package/dist/approvals.d.ts +129 -0
- package/dist/approvals.d.ts.map +1 -0
- package/dist/approvals.js +221 -0
- package/dist/approvals.js.map +1 -0
- package/dist/batchPlan.d.ts +52 -0
- package/dist/batchPlan.d.ts.map +1 -0
- package/dist/batchPlan.js +85 -0
- package/dist/batchPlan.js.map +1 -0
- package/dist/claim.d.ts +161 -0
- package/dist/claim.d.ts.map +1 -0
- package/dist/claim.js +197 -0
- package/dist/claim.js.map +1 -0
- package/dist/decode.d.ts +22 -0
- package/dist/decode.d.ts.map +1 -0
- package/dist/decode.js +187 -0
- package/dist/decode.js.map +1 -0
- package/dist/describe.d.ts +26 -0
- package/dist/describe.d.ts.map +1 -0
- package/dist/describe.js +58 -0
- package/dist/describe.js.map +1 -0
- package/dist/fees.d.ts +89 -0
- package/dist/fees.d.ts.map +1 -0
- package/dist/fees.js +166 -0
- package/dist/fees.js.map +1 -0
- package/dist/history.d.ts +125 -0
- package/dist/history.d.ts.map +1 -0
- package/dist/history.js +231 -0
- package/dist/history.js.map +1 -0
- package/dist/historyHelius.d.ts +52 -0
- package/dist/historyHelius.d.ts.map +1 -0
- package/dist/historyHelius.js +125 -0
- package/dist/historyHelius.js.map +1 -0
- package/dist/layout.d.ts +2 -0
- package/dist/layout.d.ts.map +1 -1
- package/dist/layout.js +2 -2
- package/dist/layout.js.map +1 -1
- package/dist/liquidity/orca.d.ts +6 -0
- package/dist/liquidity/orca.d.ts.map +1 -1
- package/dist/liquidity/orca.js +14 -3
- package/dist/liquidity/orca.js.map +1 -1
- package/dist/liquidity/raydiumClmm.d.ts +6 -0
- package/dist/liquidity/raydiumClmm.d.ts.map +1 -1
- package/dist/liquidity/raydiumClmm.js +12 -5
- package/dist/liquidity/raydiumClmm.js.map +1 -1
- package/dist/lp.d.ts +55 -15
- package/dist/lp.d.ts.map +1 -1
- package/dist/lp.js +98 -46
- package/dist/lp.js.map +1 -1
- package/dist/lpMath.d.ts +22 -0
- package/dist/lpMath.d.ts.map +1 -1
- package/dist/lpMath.js +21 -0
- package/dist/lpMath.js.map +1 -1
- package/dist/names.d.ts +68 -0
- package/dist/names.d.ts.map +1 -0
- package/dist/names.js +257 -0
- package/dist/names.js.map +1 -0
- package/dist/pools.d.ts +9 -0
- package/dist/pools.d.ts.map +1 -0
- package/dist/pools.js +45 -0
- package/dist/pools.js.map +1 -0
- package/dist/portfolio.d.ts +64 -0
- package/dist/portfolio.d.ts.map +1 -0
- package/dist/portfolio.js +57 -0
- package/dist/portfolio.js.map +1 -0
- package/dist/price.d.ts +90 -0
- package/dist/price.d.ts.map +1 -0
- package/dist/price.js +287 -0
- package/dist/price.js.map +1 -0
- package/dist/programs.d.ts +19 -0
- package/dist/programs.d.ts.map +1 -0
- package/dist/programs.js +175 -0
- package/dist/programs.js.map +1 -0
- package/dist/reclaim.d.ts +190 -0
- package/dist/reclaim.d.ts.map +1 -0
- package/dist/reclaim.js +399 -0
- package/dist/reclaim.js.map +1 -0
- package/dist/risk.d.ts +84 -0
- package/dist/risk.d.ts.map +1 -0
- package/dist/risk.js +211 -0
- package/dist/risk.js.map +1 -0
- package/dist/rpc.d.ts +2 -0
- package/dist/rpc.d.ts.map +1 -1
- package/dist/rpc.js +36 -10
- package/dist/rpc.js.map +1 -1
- package/dist/simulate.d.ts +106 -0
- package/dist/simulate.d.ts.map +1 -0
- package/dist/simulate.js +418 -0
- package/dist/simulate.js.map +1 -0
- package/dist/subpaths/approvals.d.ts +29 -0
- package/dist/subpaths/approvals.d.ts.map +1 -0
- package/dist/subpaths/approvals.js +30 -0
- package/dist/subpaths/approvals.js.map +1 -0
- package/dist/subpaths/claim.d.ts +31 -0
- package/dist/subpaths/claim.d.ts.map +1 -0
- package/dist/subpaths/claim.js +31 -0
- package/dist/subpaths/claim.js.map +1 -0
- package/dist/subpaths/fees.d.ts +23 -0
- package/dist/subpaths/fees.d.ts.map +1 -0
- package/dist/subpaths/fees.js +25 -0
- package/dist/subpaths/fees.js.map +1 -0
- package/dist/subpaths/history.d.ts +21 -0
- package/dist/subpaths/history.d.ts.map +1 -0
- package/dist/subpaths/history.js +22 -0
- package/dist/subpaths/history.js.map +1 -0
- package/dist/subpaths/lp.d.ts +2 -2
- package/dist/subpaths/lp.d.ts.map +1 -1
- package/dist/subpaths/lp.js +2 -2
- package/dist/subpaths/lp.js.map +1 -1
- package/dist/subpaths/names.d.ts +37 -0
- package/dist/subpaths/names.d.ts.map +1 -0
- package/dist/subpaths/names.js +27 -0
- package/dist/subpaths/names.js.map +1 -0
- package/dist/subpaths/price.d.ts +40 -0
- package/dist/subpaths/price.d.ts.map +1 -0
- package/dist/subpaths/price.js +43 -0
- package/dist/subpaths/price.js.map +1 -0
- package/dist/subpaths/reclaim.d.ts +34 -0
- package/dist/subpaths/reclaim.d.ts.map +1 -0
- package/dist/subpaths/reclaim.js +34 -0
- package/dist/subpaths/reclaim.js.map +1 -0
- package/dist/subpaths/risk.d.ts +28 -0
- package/dist/subpaths/risk.d.ts.map +1 -0
- package/dist/subpaths/risk.js +30 -0
- package/dist/subpaths/risk.js.map +1 -0
- package/dist/subpaths/simulate.d.ts +22 -0
- package/dist/subpaths/simulate.d.ts.map +1 -0
- package/dist/subpaths/simulate.js +23 -0
- package/dist/subpaths/simulate.js.map +1 -0
- package/dist/subpaths/swap.d.ts +22 -0
- package/dist/subpaths/swap.d.ts.map +1 -0
- package/dist/subpaths/swap.js +21 -0
- package/dist/subpaths/swap.js.map +1 -0
- package/dist/subpaths/write.d.ts +1 -1
- package/dist/subpaths/write.d.ts.map +1 -1
- package/dist/subpaths/write.js +1 -1
- package/dist/subpaths/write.js.map +1 -1
- package/dist/swap/amm.d.ts +20 -0
- package/dist/swap/amm.d.ts.map +1 -0
- package/dist/swap/amm.js +77 -0
- package/dist/swap/amm.js.map +1 -0
- package/dist/swap/clmmMath.d.ts +24 -0
- package/dist/swap/clmmMath.d.ts.map +1 -0
- package/dist/swap/clmmMath.js +82 -0
- package/dist/swap/clmmMath.js.map +1 -0
- package/dist/swap/common.d.ts +68 -0
- package/dist/swap/common.d.ts.map +1 -0
- package/dist/swap/common.js +65 -0
- package/dist/swap/common.js.map +1 -0
- package/dist/swap/cpmm.d.ts +28 -0
- package/dist/swap/cpmm.d.ts.map +1 -0
- package/dist/swap/cpmm.js +113 -0
- package/dist/swap/cpmm.js.map +1 -0
- package/dist/swap/index.d.ts +145 -0
- package/dist/swap/index.d.ts.map +1 -0
- package/dist/swap/index.js +349 -0
- package/dist/swap/index.js.map +1 -0
- package/dist/swap/orca.d.ts +50 -0
- package/dist/swap/orca.d.ts.map +1 -0
- package/dist/swap/orca.js +382 -0
- package/dist/swap/orca.js.map +1 -0
- package/dist/swap/raydiumClmm.d.ts +62 -0
- package/dist/swap/raydiumClmm.d.ts.map +1 -0
- package/dist/swap/raydiumClmm.js +447 -0
- package/dist/swap/raydiumClmm.js.map +1 -0
- package/dist/tradeCheck.d.ts +45 -0
- package/dist/tradeCheck.d.ts.map +1 -0
- package/dist/tradeCheck.js +131 -0
- package/dist/tradeCheck.js.map +1 -0
- package/dist/write/instructions.d.ts +9 -0
- package/dist/write/instructions.d.ts.map +1 -1
- package/dist/write/instructions.js +40 -1
- package/dist/write/instructions.js.map +1 -1
- package/dist/write/transaction.d.ts +23 -0
- package/dist/write/transaction.d.ts.map +1 -1
- package/dist/write/transaction.js +50 -0
- package/dist/write/transaction.js.map +1 -1
- package/package.json +66 -14
- package/src/approvals.ts +358 -0
- package/src/batchPlan.ts +137 -0
- package/src/claim.ts +323 -0
- package/src/decode.ts +202 -0
- package/src/describe.ts +77 -0
- package/src/fees.ts +259 -0
- package/src/history.ts +336 -0
- package/src/historyHelius.ts +136 -0
- package/src/layout.ts +2 -2
- package/src/liquidity/orca.ts +15 -5
- package/src/liquidity/raydiumClmm.ts +13 -5
- package/src/lp.ts +148 -59
- package/src/lpMath.ts +38 -0
- package/src/names.ts +329 -0
- package/src/pools.ts +43 -0
- package/src/portfolio.ts +124 -0
- package/src/price.ts +366 -0
- package/src/programs.ts +216 -0
- package/src/reclaim.ts +547 -0
- package/src/risk.ts +243 -0
- package/src/rpc.ts +39 -10
- package/src/simulate.ts +535 -0
- package/src/subpaths/approvals.ts +47 -0
- package/src/subpaths/claim.ts +53 -0
- package/src/subpaths/fees.ts +41 -0
- package/src/subpaths/history.ts +38 -0
- package/src/subpaths/lp.ts +5 -1
- package/src/subpaths/names.ts +45 -0
- package/src/subpaths/price.ts +62 -0
- package/src/subpaths/reclaim.ts +57 -0
- package/src/subpaths/risk.ts +36 -0
- package/src/subpaths/simulate.ts +37 -0
- package/src/subpaths/swap.ts +41 -0
- package/src/subpaths/write.ts +2 -0
- package/src/swap/amm.ts +88 -0
- package/src/swap/clmmMath.ts +96 -0
- package/src/swap/common.ts +113 -0
- package/src/swap/cpmm.ts +132 -0
- package/src/swap/index.ts +467 -0
- package/src/swap/orca.ts +397 -0
- package/src/swap/raydiumClmm.ts +464 -0
- package/src/tradeCheck.ts +166 -0
- package/src/write/instructions.ts +43 -1
- package/src/write/transaction.ts +62 -0
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 手续费估算(子路径 `@w3lib/solana-batch-call/fees`):三档优先费建议,一笔交易的花费(基础费 + 优先费 + 新建账户的押金)。
|
|
3
|
+
* 不放在主入口,不用时打包不会带上这部分代码;模拟交易的代码按需加载。
|
|
4
|
+
*
|
|
5
|
+
* ```ts
|
|
6
|
+
* import { getCostEstimate, getFeeEstimate } from '@w3lib/solana-batch-call/fees'
|
|
7
|
+
*
|
|
8
|
+
* await getFeeEstimate({ accounts: [pool] })
|
|
9
|
+
* await getCostEstimate({ feePayer: owner, instructions })
|
|
10
|
+
* ```
|
|
11
|
+
*/
|
|
12
|
+
import { estimateCost, estimateFees, type CostEstimate, type CostInput, type EstimateCostOptions, type EstimateFeesOptions, type PriorityFeeEstimate } from '../fees.js'
|
|
13
|
+
import { resolve, type ShortcutOptions } from '../shortcuts.js'
|
|
14
|
+
|
|
15
|
+
export {
|
|
16
|
+
estimateCost,
|
|
17
|
+
estimateFees,
|
|
18
|
+
type CostEstimate,
|
|
19
|
+
type CostInput,
|
|
20
|
+
type CreatedAccount,
|
|
21
|
+
type EstimateCostOptions,
|
|
22
|
+
type EstimateFeesOptions,
|
|
23
|
+
type FeeLevel,
|
|
24
|
+
type PriorityFeeEstimate,
|
|
25
|
+
} from '../fees.js'
|
|
26
|
+
|
|
27
|
+
export interface GetFeeEstimateOptions extends EstimateFeesOptions, ShortcutOptions {}
|
|
28
|
+
|
|
29
|
+
/** 当前的三档优先费建议(micro-lamports / 计算单元),节点参数与 getBalances 相同 */
|
|
30
|
+
export function getFeeEstimate(options: GetFeeEstimateOptions = {}): Promise<PriorityFeeEstimate> {
|
|
31
|
+
const { client, own } = resolve(options, ['accounts', 'percentiles', 'signal'])
|
|
32
|
+
return estimateFees(client, own)
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
export interface GetCostEstimateOptions extends EstimateCostOptions, ShortcutOptions {}
|
|
36
|
+
|
|
37
|
+
/** 一笔交易的花费(基础费 + 优先费 + 新建账户的押金),模拟一次、不发送 */
|
|
38
|
+
export function getCostEstimate(input: CostInput, options: GetCostEstimateOptions = {}): Promise<CostEstimate> {
|
|
39
|
+
const { client, own } = resolve(options, ['percentiles', 'level', 'priorityFee', 'fees', 'signal'])
|
|
40
|
+
return estimateCost(client, input, own)
|
|
41
|
+
}
|
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 交易历史(子路径 `@w3lib/solana-batch-call/history`):地址的交易整理成统一的 Activity(兑换、转账、授权、流动性、铸造、失败……),
|
|
3
|
+
* 数据源可换(默认节点:getSignaturesForAddress + getTransaction;可选 Helius 增强历史)。不放在主入口,不用时打包不会带上这部分代码。
|
|
4
|
+
*
|
|
5
|
+
* ```ts
|
|
6
|
+
* import { getHistory, heliusHistory } from '@w3lib/solana-batch-call/history'
|
|
7
|
+
*
|
|
8
|
+
* const page = await getHistory(address, { limit: 20 })
|
|
9
|
+
* const next = await getHistory(address, { cursor: page.nextCursor, types: ['swap'] })
|
|
10
|
+
* await getHistory(address, { source: [heliusHistory({ apiKey }), rpcHistory()] }) // 依次尝试
|
|
11
|
+
* ```
|
|
12
|
+
*/
|
|
13
|
+
import { history, type HistoryOptions, type HistoryPage } from '../history.js'
|
|
14
|
+
import { resolve, type ShortcutOptions } from '../shortcuts.js'
|
|
15
|
+
|
|
16
|
+
export {
|
|
17
|
+
MAX_HISTORY_LIMIT,
|
|
18
|
+
activityFromTransaction,
|
|
19
|
+
history,
|
|
20
|
+
rpcHistory,
|
|
21
|
+
type Activity,
|
|
22
|
+
type ActivityChange,
|
|
23
|
+
type ActivityType,
|
|
24
|
+
type HistoryContext,
|
|
25
|
+
type HistoryOptions,
|
|
26
|
+
type HistoryPage,
|
|
27
|
+
type HistorySource,
|
|
28
|
+
type RpcHistoryOptions,
|
|
29
|
+
} from '../history.js'
|
|
30
|
+
export { activityFromHelius, heliusHistory, type HeliusHistoryOptions } from '../historyHelius.js'
|
|
31
|
+
|
|
32
|
+
export interface GetHistoryOptions extends HistoryOptions, ShortcutOptions {}
|
|
33
|
+
|
|
34
|
+
/** 查地址的交易历史,节点参数与 getBalances 相同 */
|
|
35
|
+
export function getHistory(address: string, options: GetHistoryOptions = {}): Promise<HistoryPage> {
|
|
36
|
+
const { client, own } = resolve(options, ['limit', 'cursor', 'before', 'after', 'types', 'source', 'symbols', 'fetch', 'signal'])
|
|
37
|
+
return history(client, address, own)
|
|
38
|
+
}
|
package/src/subpaths/lp.ts
CHANGED
|
@@ -25,6 +25,7 @@ export {
|
|
|
25
25
|
type SolanaLpClmmPosition,
|
|
26
26
|
type SolanaLpPosition,
|
|
27
27
|
type SolanaLpProtocol,
|
|
28
|
+
type SolanaLpReward,
|
|
28
29
|
type SolanaLpToken,
|
|
29
30
|
type SolanaPriceSource,
|
|
30
31
|
} from '../lp.js'
|
|
@@ -38,15 +39,18 @@ export {
|
|
|
38
39
|
getMaxAmounts,
|
|
39
40
|
getMinAmounts,
|
|
40
41
|
getMintAmounts,
|
|
42
|
+
getRewardGrowthInside,
|
|
41
43
|
nearestUsableTick,
|
|
42
44
|
orcaSqrtPriceAtTick,
|
|
43
45
|
priceToTick,
|
|
44
46
|
raydiumSqrtPriceAtTick,
|
|
47
|
+
rewardGrowthGlobal,
|
|
45
48
|
sqrtPriceAtTick,
|
|
46
49
|
sqrtPriceToPrice,
|
|
47
50
|
tickAtSqrtPrice,
|
|
48
51
|
tickToPrice,
|
|
49
52
|
type ClmmProgram,
|
|
53
|
+
type RewardEmission,
|
|
50
54
|
type TickFeeData,
|
|
51
55
|
} from '../lpMath.js'
|
|
52
56
|
|
|
@@ -66,6 +70,6 @@ export interface GetLpPositionsOptions extends LpPositionsOptions, ShortcutOptio
|
|
|
66
70
|
*/
|
|
67
71
|
export function getLpPositions(owner: string, options: GetLpPositionsOptions = {}): Promise<SolanaLpPosition[]> {
|
|
68
72
|
// fetch 同时给节点请求(客户端配置)和查价用,与其他快捷函数一致
|
|
69
|
-
const { client, own } = resolve(options, ['protocols', 'mints', 'pools', 'includeClosed', 'prices', 'onPriceError', 'signal'])
|
|
73
|
+
const { client, own } = resolve(options, ['protocols', 'mints', 'pools', 'includeClosed', 'rewards', 'now', 'prices', 'onPriceError', 'signal'])
|
|
70
74
|
return lpPositions(client, owner, { ...own, ...(options.fetch ? { fetch: options.fetch } : {}) })
|
|
71
75
|
}
|
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 域名解析(子路径 `@w3lib/solana-batch-call/names`):SNS(Bonfida,`.sns`),名字 → 地址、地址 → 主域名。
|
|
3
|
+
* 不放在主入口,不用时打包不会带上这部分代码。
|
|
4
|
+
*
|
|
5
|
+
* ```ts
|
|
6
|
+
* import { getAddressNames, getNameAddresses } from '@w3lib/solana-batch-call/names'
|
|
7
|
+
*
|
|
8
|
+
* await getNameAddresses(['bonfida.sns', 'toly.sns'])
|
|
9
|
+
* await getAddressNames([wallet])
|
|
10
|
+
* ```
|
|
11
|
+
*/
|
|
12
|
+
import type { RequestOptions } from '../client.js'
|
|
13
|
+
import { lookupAddresses, resolveNames, type AddressName, type NamesOptions, type ResolvedName } from '../names.js'
|
|
14
|
+
import { resolve, type ShortcutOptions } from '../shortcuts.js'
|
|
15
|
+
|
|
16
|
+
export { NAME_PROGRAM_ID, SNS_ROOT_DOMAIN, lookupAddresses, resolveNames, snsDomainKey, type AddressName, type NameSource, type NamesOptions, type ResolvedName } from '../names.js'
|
|
17
|
+
|
|
18
|
+
export interface GetNamesOptions extends NamesOptions, ShortcutOptions {}
|
|
19
|
+
|
|
20
|
+
/**
|
|
21
|
+
* 名字 → 地址,节点参数与 getBalances 相同。
|
|
22
|
+
*
|
|
23
|
+
* ```ts
|
|
24
|
+
* await getNameAddresses(['bonfida.sns', 'toly.sns'])
|
|
25
|
+
* // [{ name: 'bonfida.sns', normalized: 'bonfida.sns', address: 'Fw1E…Lb1v', owner: 'Fw1E…Lb1v', source: 'owner', service: 'sns' }, …]
|
|
26
|
+
* ```
|
|
27
|
+
*/
|
|
28
|
+
export function getNameAddresses(names: readonly string[], options: GetNamesOptions = {}): Promise<ResolvedName[]> {
|
|
29
|
+
const { client, own } = resolve(options, ['legacySol', 'allowPda', 'signal'])
|
|
30
|
+
return resolveNames(client, names, own)
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
export interface GetAddressNamesOptions extends RequestOptions, ShortcutOptions {}
|
|
34
|
+
|
|
35
|
+
/**
|
|
36
|
+
* 地址 → 主域名(核对过属于这个地址)。
|
|
37
|
+
*
|
|
38
|
+
* ```ts
|
|
39
|
+
* await getAddressNames([wallet]) // [{ address: wallet, name: 'bonfida.sns', service: 'sns' }]
|
|
40
|
+
* ```
|
|
41
|
+
*/
|
|
42
|
+
export function getAddressNames(addresses: readonly string[], options: GetAddressNamesOptions = {}): Promise<AddressName[]> {
|
|
43
|
+
const { client, own } = resolve(options, ['signal'])
|
|
44
|
+
return lookupAddresses(client, addresses, own)
|
|
45
|
+
}
|
|
@@ -0,0 +1,62 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 价格(子路径 `@w3lib/solana-batch-call/price`):代币的美元价格(DefiLlama 当前 / 历史价格,没有收录的从链上 Raydium / Orca 池子算)、
|
|
3
|
+
* 组合价格源、地址的资产总值。不放在主入口,不用时打包不会带上这部分代码。
|
|
4
|
+
*
|
|
5
|
+
* ```ts
|
|
6
|
+
* import { NATIVE_MINT } from '@w3lib/solana-batch-call'
|
|
7
|
+
* import { getPortfolio, getTokenPrices } from '@w3lib/solana-batch-call/price'
|
|
8
|
+
*
|
|
9
|
+
* await getTokenPrices([NATIVE_MINT, USDC, newToken])
|
|
10
|
+
* await getPortfolio(owner, { tokens: [NATIVE_MINT, USDC, JUP] })
|
|
11
|
+
* ```
|
|
12
|
+
*/
|
|
13
|
+
import { portfolio, type Portfolio, type PortfolioOptions } from '../portfolio.js'
|
|
14
|
+
import { tokenPrices, type TokenPrice, type TokenPricesOptions } from '../price.js'
|
|
15
|
+
import { resolve, type ShortcutOptions } from '../shortcuts.js'
|
|
16
|
+
|
|
17
|
+
export { portfolio, type Portfolio, type PortfolioOptions, type PortfolioToken } from '../portfolio.js'
|
|
18
|
+
export {
|
|
19
|
+
STABLECOINS,
|
|
20
|
+
combinePrices,
|
|
21
|
+
defillamaPrices,
|
|
22
|
+
onchainPrices,
|
|
23
|
+
tokenPrices,
|
|
24
|
+
type DefillamaPriceOptions,
|
|
25
|
+
type OnchainPriceOptions,
|
|
26
|
+
type OnchainPriceProtocol,
|
|
27
|
+
type SolanaPriceSource,
|
|
28
|
+
type SolanaPriceSourceContext,
|
|
29
|
+
type TokenPrice,
|
|
30
|
+
type TokenPricesOptions,
|
|
31
|
+
} from '../price.js'
|
|
32
|
+
|
|
33
|
+
export interface GetTokenPricesOptions extends TokenPricesOptions, ShortcutOptions {}
|
|
34
|
+
|
|
35
|
+
/**
|
|
36
|
+
* 查代币的美元价格(SOL 用 NATIVE_MINT),节点参数与 getBalances 相同。
|
|
37
|
+
*
|
|
38
|
+
* ```ts
|
|
39
|
+
* await getTokenPrices([NATIVE_MINT, USDC])
|
|
40
|
+
* // [{ token: 'So111…112', native: true, price: 187.4, source: 'defillama' }, { token: USDC, native: false, price: 1, source: 'defillama' }]
|
|
41
|
+
* ```
|
|
42
|
+
*/
|
|
43
|
+
export function getTokenPrices(mints: readonly string[], options: GetTokenPricesOptions = {}): Promise<TokenPrice[]> {
|
|
44
|
+
// fetch 同时给节点请求(客户端配置)和查价用,与 getLpPositions 一致
|
|
45
|
+
const { client, own } = resolve(options, ['sources', 'onError', 'signal'])
|
|
46
|
+
return tokenPrices(client, mints, { ...own, ...(options.fetch ? { fetch: options.fetch } : {}) })
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
export interface GetPortfolioOptions extends PortfolioOptions, ShortcutOptions {}
|
|
50
|
+
|
|
51
|
+
/**
|
|
52
|
+
* 地址的资产总值:代币余额 × 价格,可选加上 LP 仓位(lp: true)。
|
|
53
|
+
*
|
|
54
|
+
* ```ts
|
|
55
|
+
* await getPortfolio(owner, { tokens: [NATIVE_MINT, USDC, JUP] }) // 指定代币:免费公共节点也能用
|
|
56
|
+
* await getPortfolio(owner, { provider: 'https://my-rpc…', lp: true }) // 全部持仓 + LP:需要支持 getTokenAccountsByOwner 的节点
|
|
57
|
+
* ```
|
|
58
|
+
*/
|
|
59
|
+
export function getPortfolio(owner: string, options: GetPortfolioOptions = {}): Promise<Portfolio> {
|
|
60
|
+
const { client, own } = resolve(options, ['tokens', 'sources', 'lp', 'minUsd', 'onPriceError', 'signal'])
|
|
61
|
+
return portfolio(client, owner, { ...own, ...(options.fetch ? { fetch: options.fetch } : {}) })
|
|
62
|
+
}
|
|
@@ -0,0 +1,57 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 账户回收(子路径 `@w3lib/solana-batch-call/reclaim`):扫描钱包里关闭后能退回租金(SOL)的账户并批量关闭:空的代币账户、垃圾币(销毁后关闭)、
|
|
3
|
+
* Wrapped SOL(解包)、已清空的 Orca Whirlpool / Raydium CLMM 仓位。给出每项和合计能拿回多少 lamports,发送前用 /simulate 模拟。
|
|
4
|
+
* 不放在主入口,不用时打包不会带上这部分代码;发送的代码按需加载。
|
|
5
|
+
*
|
|
6
|
+
* ```ts
|
|
7
|
+
* import { getReclaimable, reclaim } from '@w3lib/solana-batch-call/reclaim'
|
|
8
|
+
*
|
|
9
|
+
* const r = await getReclaimable(owner, { provider: 'https://my-rpc…' })
|
|
10
|
+
* r.totalLamports // 全部能拿回的 lamports
|
|
11
|
+
* const { simulation, results } = await reclaim(client, key, r.items.filter((i) => i.selected))
|
|
12
|
+
* ```
|
|
13
|
+
*/
|
|
14
|
+
import { reclaimable, type Reclaimable, type ReclaimQuery } from '../reclaim.js'
|
|
15
|
+
import { resolve, type ShortcutOptions } from '../shortcuts.js'
|
|
16
|
+
|
|
17
|
+
export {
|
|
18
|
+
buildReclaim,
|
|
19
|
+
reclaim,
|
|
20
|
+
reclaimable,
|
|
21
|
+
simulateReclaim,
|
|
22
|
+
type BuildReclaimOptions,
|
|
23
|
+
type JunkContext,
|
|
24
|
+
type ReclaimBlocker,
|
|
25
|
+
type ReclaimCall,
|
|
26
|
+
type ReclaimCallResult,
|
|
27
|
+
type ReclaimItem,
|
|
28
|
+
type ReclaimKind,
|
|
29
|
+
type ReclaimOptions,
|
|
30
|
+
type ReclaimPlan,
|
|
31
|
+
type ReclaimQuery,
|
|
32
|
+
type ReclaimResult,
|
|
33
|
+
type ReclaimSimulation,
|
|
34
|
+
type ReclaimSimulationOptions,
|
|
35
|
+
type Reclaimable,
|
|
36
|
+
} from '../reclaim.js'
|
|
37
|
+
export type { PlanSimulation } from '../batchPlan.js'
|
|
38
|
+
export { burnChecked, closeAccount, harvestWithheldTokensToMint } from '../write/instructions.js'
|
|
39
|
+
|
|
40
|
+
export interface GetReclaimableOptions extends ReclaimQuery, ShortcutOptions {}
|
|
41
|
+
|
|
42
|
+
/**
|
|
43
|
+
* 扫描钱包里能回收租金的账户,节点参数与 getBalances 相同。默认列出全部代币账户(需要支持 getTokenAccountsByOwner 的节点),
|
|
44
|
+
* 免费公共节点传 `mints` 只看指定代币的 ATA。
|
|
45
|
+
*
|
|
46
|
+
* ```ts
|
|
47
|
+
* const r = await getReclaimable(owner, { provider: 'https://my-rpc…' })
|
|
48
|
+
* // { totalLamports: '45862080', selectedLamports: '41302080',
|
|
49
|
+
* // items: [{ kind: 'empty-token', account, mint, lamports: '2039280', selected: true, reasons: ['empty'] },
|
|
50
|
+
* // { kind: 'junk-token', symbol: 'claim-rewards.xyz', lamports: '2039280', selected: true, reasons: ['no-price', 'spam-name'] }, …],
|
|
51
|
+
* // blocked: [{ kind: 'empty-token', blocker: 'frozen', … }] }
|
|
52
|
+
* ```
|
|
53
|
+
*/
|
|
54
|
+
export function getReclaimable(owner: string, options: GetReclaimableOptions = {}): Promise<Reclaimable> {
|
|
55
|
+
const { client, own } = resolve(options, ['mints', 'junk', 'positions', 'prices', 'maxJunkUsd', 'risk', 'isJunk', 'signal'])
|
|
56
|
+
return reclaimable(client, owner, { ...own, ...(options.fetch ? { fetch: options.fetch } : {}) })
|
|
57
|
+
}
|
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 代币风险检查(子路径 `@w3lib/solana-batch-call/risk`):mint 的增发 / 冻结权限,Token-2022 扩展里影响持有人的设置
|
|
3
|
+
* (转账手续费、永久授权、转账 hook、不可转让、默认冻结、可暂停、保密转账、mint 可关闭等),可选持币集中度;
|
|
4
|
+
* tradeChecks 在主网模拟“买入 → 卖出”判断能不能卖(用 /swap,不用时打包不会带上)。不放在主入口,不用时打包不会带上这部分代码。
|
|
5
|
+
*
|
|
6
|
+
* ```ts
|
|
7
|
+
* import { getTokenRisks, getTradeChecks } from '@w3lib/solana-batch-call/risk'
|
|
8
|
+
*
|
|
9
|
+
* const [risk] = await getTokenRisks([mint])
|
|
10
|
+
* if (risk.flags.includes('permanent-delegate')) alert('发行方可以转走你的代币')
|
|
11
|
+
* const [trade] = await getTradeChecks([mint], { owner: myAddress })
|
|
12
|
+
* if (trade.honeypot) alert('卖不出')
|
|
13
|
+
* ```
|
|
14
|
+
*/
|
|
15
|
+
import { tokenRisks, type SolanaTokenRisk, type TokenRisksOptions } from '../risk.js'
|
|
16
|
+
import { resolve, type ShortcutOptions } from '../shortcuts.js'
|
|
17
|
+
import { tradeChecks, type SolanaTradeCheck, type TradeCheckOptions } from '../tradeCheck.js'
|
|
18
|
+
|
|
19
|
+
export { parseRisk, tokenRisks, type SolanaTokenRisk, type TokenRisksOptions } from '../risk.js'
|
|
20
|
+
export { tradeChecks, type SolanaTradeCheck, type TradeCheckOptions, type TradeStage } from '../tradeCheck.js'
|
|
21
|
+
|
|
22
|
+
export interface GetTokenRisksOptions extends TokenRisksOptions, ShortcutOptions {}
|
|
23
|
+
|
|
24
|
+
/** 检查代币的风险(一次 getMultipleAccounts),节点参数与 getBalances 相同 */
|
|
25
|
+
export function getTokenRisks(mints: readonly string[], options: GetTokenRisksOptions = {}): Promise<SolanaTokenRisk[]> {
|
|
26
|
+
const { client, own } = resolve(options, ['concentration', 'signal'])
|
|
27
|
+
return tokenRisks(client, mints, own)
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
export interface GetTradeChecksOptions extends TradeCheckOptions, ShortcutOptions {}
|
|
31
|
+
|
|
32
|
+
/** 模拟买入再卖出,判断能不能交易,节点参数与 getBalances 相同 */
|
|
33
|
+
export function getTradeChecks(mints: readonly string[], options: GetTradeChecksOptions): Promise<SolanaTradeCheck[]> {
|
|
34
|
+
const { client, own } = resolve(options, ['owner', 'amount', 'amountFormatted', 'protocols', 'intermediates', 'pools', 'discover', 'signal'])
|
|
35
|
+
return tradeChecks(client, mints, own as TradeCheckOptions)
|
|
36
|
+
}
|
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 交易模拟(子路径 `@w3lib/solana-batch-call/simulate`):不签名、不发送,在主网模拟一笔交易,给出余额变化、授权变化(delegate / SetAuthority / 关闭账户)、
|
|
3
|
+
* 指令说明、程序错误、手续费和警告。输入可以是 base64 的交易,也可以直接是本库构建器的输出。不放在主入口,不用时打包不会带上这部分代码;价格、风险检查按需加载。
|
|
4
|
+
*
|
|
5
|
+
* ```ts
|
|
6
|
+
* import { buildSwap } from '@w3lib/solana-batch-call/swap'
|
|
7
|
+
* import { getSimulation } from '@w3lib/solana-batch-call/simulate'
|
|
8
|
+
*
|
|
9
|
+
* const plan = await getSwapQuote(owner, { tokenIn: NATIVE_MINT, tokenOut: USDC, amountInFormatted: '0.5' })
|
|
10
|
+
* const sim = await getSimulation(plan) // 或 getSimulation(base64Tx, { owner })
|
|
11
|
+
* if (!sim.success || sim.warnings.some((w) => w.severity === 'danger')) throw new Error(sim.error ?? sim.warnings[0].message)
|
|
12
|
+
* ```
|
|
13
|
+
*/
|
|
14
|
+
import { resolve, type ShortcutOptions } from '../shortcuts.js'
|
|
15
|
+
import { simulate, type SimulateInput, type SimulateOptions, type SimulationResult } from '../simulate.js'
|
|
16
|
+
|
|
17
|
+
export {
|
|
18
|
+
failureText,
|
|
19
|
+
simulate,
|
|
20
|
+
type ApprovalChange,
|
|
21
|
+
type ApprovalChangeKind,
|
|
22
|
+
type SimulateInput,
|
|
23
|
+
type SimulateOptions,
|
|
24
|
+
type SimulatedBalanceChange,
|
|
25
|
+
type SimulationResult,
|
|
26
|
+
type SimulationWarning,
|
|
27
|
+
type WarningSeverity,
|
|
28
|
+
} from '../simulate.js'
|
|
29
|
+
export { decodeInstruction, type DecodedInstruction } from '../decode.js'
|
|
30
|
+
|
|
31
|
+
export interface GetSimulationOptions extends SimulateOptions, ShortcutOptions {}
|
|
32
|
+
|
|
33
|
+
/** 模拟一笔交易,节点参数与 getBalances 相同 */
|
|
34
|
+
export function getSimulation(input: SimulateInput, options: GetSimulationOptions = {}): Promise<SimulationResult> {
|
|
35
|
+
const { client, own } = resolve(options, ['owner', 'signers', 'watch', 'step', 'prices', 'risk', 'fetch', 'signal'])
|
|
36
|
+
return simulate(client, input, own)
|
|
37
|
+
}
|
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 兑换(子路径 `@w3lib/solana-batch-call/swap`):在 Raydium CLMM、Orca Whirlpool、Raydium CPMM、Raydium AMM v4 的池子里找最好的路线
|
|
3
|
+
* (直接或经过 SOL / USDC / USDT 的两跳),本地报价并构建 / 发送兑换交易。不放在主入口,不用时打包不会带上这部分代码。不依赖各 DEX 的 SDK。
|
|
4
|
+
*
|
|
5
|
+
* ```ts
|
|
6
|
+
* import { NATIVE_MINT } from '@w3lib/solana-batch-call'
|
|
7
|
+
* import { getSwapQuote, swap } from '@w3lib/solana-batch-call/swap'
|
|
8
|
+
*
|
|
9
|
+
* const plan = await getSwapQuote(owner, { tokenIn: NATIVE_MINT, tokenOut: USDC, amountInFormatted: '0.5' })
|
|
10
|
+
* await swap(client, secretKey, { tokenIn: NATIVE_MINT, tokenOut: USDC, amountInFormatted: '0.5' }, { slippage: 0.01 })
|
|
11
|
+
* ```
|
|
12
|
+
*/
|
|
13
|
+
import { resolve, type ShortcutOptions } from '../shortcuts.js'
|
|
14
|
+
import { buildSwap, type SolanaSwapOptions, type SolanaSwapParams, type SolanaSwapPlan } from '../swap/index.js'
|
|
15
|
+
|
|
16
|
+
export {
|
|
17
|
+
SWAP_INTERMEDIATES,
|
|
18
|
+
SWAP_PROTOCOLS,
|
|
19
|
+
buildSwap,
|
|
20
|
+
swap,
|
|
21
|
+
type SolanaSwapHop,
|
|
22
|
+
type SolanaSwapOptions,
|
|
23
|
+
type SolanaSwapParams,
|
|
24
|
+
type SolanaSwapPlan,
|
|
25
|
+
type SolanaSwapProtocol,
|
|
26
|
+
type SolanaSwapResult,
|
|
27
|
+
type SolanaSwapRoute,
|
|
28
|
+
type SolanaSwapSendOptions,
|
|
29
|
+
type SolanaSwapStep,
|
|
30
|
+
type SolanaSwapStepResult,
|
|
31
|
+
} from '../swap/index.js'
|
|
32
|
+
export type { Instruction } from '../write/transaction.js'
|
|
33
|
+
export type { SignerInput, WriteResult, WriteStatus } from '../subpaths/write.js'
|
|
34
|
+
|
|
35
|
+
export interface GetSwapQuoteOptions extends SolanaSwapOptions, ShortcutOptions {}
|
|
36
|
+
|
|
37
|
+
/** 报价并构建兑换的指令(同 buildSwap),节点参数与 getBalances 相同 */
|
|
38
|
+
export function getSwapQuote(owner: string, params: SolanaSwapParams, options: GetSwapQuoteOptions = {}): Promise<SolanaSwapPlan> {
|
|
39
|
+
const { client, own } = resolve(options, ['slippage', 'native', 'protocols', 'intermediates', 'pools', 'discover', 'signal'])
|
|
40
|
+
return buildSwap(client, owner, params, own)
|
|
41
|
+
}
|
package/src/subpaths/write.ts
CHANGED
package/src/swap/amm.ts
ADDED
|
@@ -0,0 +1,88 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Raydium AMM v4 的兑换:swap_base_in_v2(指令 16,不需要 OpenBook 账户)。报价照搬程序(raydium-amm processor.rs):
|
|
3
|
+
* 手续费 = ceil(输入 × swap_fee_numerator / swap_fee_denominator),储备 = 金库余额 − need_take_pnl,恒定乘积向下取整。只支持 SPL Token
|
|
4
|
+
*/
|
|
5
|
+
import { TOKEN_PROGRAM_ID } from '../constants.js'
|
|
6
|
+
import { parseTokenAccount, type AccountInfo } from '../layout.js'
|
|
7
|
+
import { RAYDIUM_AMM_AUTHORITY, RAYDIUM_AMM_PROGRAM_ID } from '../lp.js'
|
|
8
|
+
import { Writer, r, w } from '../liquidity/common.js'
|
|
9
|
+
import type { Instruction } from '../write/transaction.js'
|
|
10
|
+
import { Bytes, UnsupportedPool, mulDivCeil, mulDivFloor, need, swapMint, type AccountGetter, type HopQuote, type SwapMint, type SwapPool } from './common.js'
|
|
11
|
+
|
|
12
|
+
const POOL_SIZE = 752
|
|
13
|
+
/**
|
|
14
|
+
* 只支持 SwapOnly(6,不再用 OpenBook 挂单,现在的池子基本都是):swap_base_in_v2 不带 OpenBook 账户,
|
|
15
|
+
* 还连着 OpenBook 的池子(Initialized 1、WaitingTrade 7)没有对照程序源码验证过能不能用,不报价,免得排第一后在链上失败
|
|
16
|
+
*/
|
|
17
|
+
const SWAP_STATUSES = new Set([6n])
|
|
18
|
+
|
|
19
|
+
interface AmmState {
|
|
20
|
+
address: string
|
|
21
|
+
status: bigint
|
|
22
|
+
swapFeeNumerator: bigint
|
|
23
|
+
swapFeeDenominator: bigint
|
|
24
|
+
needTakePnl0: bigint
|
|
25
|
+
needTakePnl1: bigint
|
|
26
|
+
openTime: bigint
|
|
27
|
+
vault0: string
|
|
28
|
+
vault1: string
|
|
29
|
+
mint0: string
|
|
30
|
+
mint1: string
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
/** AmmInfo(无判别符):status 0、fees.swap_fee 176 / 184、need_take_pnl_coin 192、need_take_pnl_pc 200、pool_open_time 224、vault 336 / 368、mint 400 / 432 */
|
|
34
|
+
export function parseAmmV4Pool(account: AccountInfo): AmmState | null {
|
|
35
|
+
if (account.owner !== RAYDIUM_AMM_PROGRAM_ID || account.data.length !== POOL_SIZE) return null
|
|
36
|
+
const b = new Bytes(account.data)
|
|
37
|
+
return {
|
|
38
|
+
address: account.address,
|
|
39
|
+
status: b.u64(0),
|
|
40
|
+
swapFeeNumerator: b.u64(176),
|
|
41
|
+
swapFeeDenominator: b.u64(184),
|
|
42
|
+
needTakePnl0: b.u64(192),
|
|
43
|
+
needTakePnl1: b.u64(200),
|
|
44
|
+
openTime: b.u64(224),
|
|
45
|
+
vault0: b.key(336),
|
|
46
|
+
vault1: b.key(368),
|
|
47
|
+
mint0: b.key(400),
|
|
48
|
+
mint1: b.key(432),
|
|
49
|
+
}
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
export function ammV4Pool(state: AmmState): SwapPool {
|
|
53
|
+
const mints = (get: AccountGetter): [SwapMint, SwapMint] => [
|
|
54
|
+
swapMint(state.mint0, need(get, state.mint0, 'Token mint')),
|
|
55
|
+
swapMint(state.mint1, need(get, state.mint1, 'Token mint')),
|
|
56
|
+
]
|
|
57
|
+
return {
|
|
58
|
+
protocol: 'raydium-amm',
|
|
59
|
+
address: state.address,
|
|
60
|
+
mint0: state.mint0,
|
|
61
|
+
mint1: state.mint1,
|
|
62
|
+
mints,
|
|
63
|
+
accounts: () => [state.vault0, state.vault1, state.mint0, state.mint1],
|
|
64
|
+
quote(get, amountIn, zeroForOne, env): HopQuote {
|
|
65
|
+
if (!SWAP_STATUSES.has(state.status)) throw new UnsupportedPool(`Swap is not allowed in pool status ${state.status}`)
|
|
66
|
+
if (env.timestamp < state.openTime) throw new UnsupportedPool('Pool is not open yet')
|
|
67
|
+
if (state.swapFeeDenominator === 0n) throw new UnsupportedPool('Invalid pool fees')
|
|
68
|
+
const [m0, m1] = mints(get)
|
|
69
|
+
if (m0.program !== TOKEN_PROGRAM_ID || m1.program !== TOKEN_PROGRAM_ID) throw new UnsupportedPool('AMM v4 supports only SPL Token mints')
|
|
70
|
+
const v0 = parseTokenAccount(need(get, state.vault0, 'Pool vault').data).amount
|
|
71
|
+
const v1 = parseTokenAccount(need(get, state.vault1, 'Pool vault').data).amount
|
|
72
|
+
if (v0 < state.needTakePnl0 || v1 < state.needTakePnl1) throw new UnsupportedPool('Pool vault is below the pending PnL')
|
|
73
|
+
const [reserveIn, reserveOut] = zeroForOne ? [v0 - state.needTakePnl0, v1 - state.needTakePnl1] : [v1 - state.needTakePnl1, v0 - state.needTakePnl0]
|
|
74
|
+
const fee = mulDivCeil(amountIn, state.swapFeeNumerator, state.swapFeeDenominator)
|
|
75
|
+
const afterFee = amountIn - fee
|
|
76
|
+
const out = afterFee > 0n ? mulDivFloor(reserveOut, afterFee, reserveIn + afterFee) : 0n
|
|
77
|
+
// 程序要求输出小于储备
|
|
78
|
+
return { amountIn, amountOut: out < reserveOut ? out : 0n, accounts: [] }
|
|
79
|
+
},
|
|
80
|
+
instruction(_get, owner, input, output, _zeroForOne, quote, minOut): Instruction {
|
|
81
|
+
return {
|
|
82
|
+
programId: RAYDIUM_AMM_PROGRAM_ID,
|
|
83
|
+
keys: [r(TOKEN_PROGRAM_ID), w(state.address), r(RAYDIUM_AMM_AUTHORITY), w(state.vault0), w(state.vault1), w(input), w(output), r(owner, true)],
|
|
84
|
+
data: new Writer().u8(16).u64(quote.amountIn).u64(minOut).build(),
|
|
85
|
+
}
|
|
86
|
+
},
|
|
87
|
+
}
|
|
88
|
+
}
|
|
@@ -0,0 +1,96 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 集中流动性兑换一步的计算(只做按输入数量兑换),照搬 Raydium CLMM(libraries/swap_math.rs、sqrt_price_math.rs、liquidity_math.rs)
|
|
3
|
+
* 和 Orca Whirlpool(math/swap_math.rs、token_math.rs)。两个程序“手续费从输入扣”时的公式和取整完全相同;Raydium 另有“手续费从输出扣”的池子
|
|
4
|
+
*/
|
|
5
|
+
import { U64_MAX, mulDivCeil } from './common.js'
|
|
6
|
+
|
|
7
|
+
const Q64 = 1n << 64n
|
|
8
|
+
export const FEE_RATE_DENOMINATOR = 1_000_000n
|
|
9
|
+
|
|
10
|
+
export class SwapMathError extends Error {}
|
|
11
|
+
|
|
12
|
+
/** 价格从 a 到 b(任意顺序)对应的 token0 数量:L · 2^64 · (hi − lo) / (lo · hi) */
|
|
13
|
+
export function amount0Delta(a: bigint, b: bigint, liquidity: bigint, roundUp: boolean): bigint {
|
|
14
|
+
const [lo, hi] = a < b ? [a, b] : [b, a]
|
|
15
|
+
if (lo === 0n) throw new SwapMathError('zero sqrt price')
|
|
16
|
+
const num = (liquidity * (hi - lo)) << 64n
|
|
17
|
+
const den = lo * hi
|
|
18
|
+
return roundUp ? (num + den - 1n) / den : num / den
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
/** 价格从 a 到 b 对应的 token1 数量:L · (hi − lo) / 2^64 */
|
|
22
|
+
export function amount1Delta(a: bigint, b: bigint, liquidity: bigint, roundUp: boolean): bigint {
|
|
23
|
+
const [lo, hi] = a < b ? [a, b] : [b, a]
|
|
24
|
+
const p = liquidity * (hi - lo)
|
|
25
|
+
return roundUp ? (p + Q64 - 1n) >> 64n : p >> 64n
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
/** 卖出 amount 后的 sqrt 价格(向不越过目标价格的方向取整):卖 token0 时价格下降,卖 token1 时上升 */
|
|
29
|
+
export function nextSqrtPriceFromInput(sqrtPrice: bigint, liquidity: bigint, amount: bigint, zeroForOne: boolean): bigint {
|
|
30
|
+
if (liquidity === 0n) throw new SwapMathError('zero liquidity')
|
|
31
|
+
if (amount === 0n) return sqrtPrice
|
|
32
|
+
if (zeroForOne) {
|
|
33
|
+
const num = liquidity << 64n
|
|
34
|
+
const den = num + amount * sqrtPrice
|
|
35
|
+
return mulDivCeil(num, sqrtPrice, den)
|
|
36
|
+
}
|
|
37
|
+
return sqrtPrice + (amount << 64n) / liquidity
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
export interface SwapStep {
|
|
41
|
+
/** 走到的 sqrt 价格 */
|
|
42
|
+
sqrtPrice: bigint
|
|
43
|
+
/** 计入价格变动的输入(不含手续费) */
|
|
44
|
+
amountIn: bigint
|
|
45
|
+
/** 给用户的输出(手续费从输出扣时已扣除) */
|
|
46
|
+
amountOut: bigint
|
|
47
|
+
feeAmount: bigint
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
/**
|
|
51
|
+
* 一步兑换:从当前价格向目标价格,最多用 remaining 个输入。
|
|
52
|
+
* feeOnInput(Orca 和 Raydium 的默认):输入先按费率扣手续费;否则(Raydium fee_on):输出按费率扣
|
|
53
|
+
*/
|
|
54
|
+
export function computeSwapStep(
|
|
55
|
+
sqrtCurrent: bigint,
|
|
56
|
+
sqrtTarget: bigint,
|
|
57
|
+
liquidity: bigint,
|
|
58
|
+
remaining: bigint,
|
|
59
|
+
feeRate: bigint,
|
|
60
|
+
zeroForOne: boolean,
|
|
61
|
+
feeOnInput: boolean,
|
|
62
|
+
program: 'raydium' | 'orca',
|
|
63
|
+
): SwapStep {
|
|
64
|
+
const amountForPrice = feeOnInput ? (remaining * (FEE_RATE_DENOMINATOR - feeRate)) / FEE_RATE_DENOMINATOR : remaining
|
|
65
|
+
// 走到目标价格需要的输入(向上取整)和得到的输出(向下取整);超过 u64 视为走不到
|
|
66
|
+
const inAtTarget = zeroForOne ? amount0Delta(sqrtTarget, sqrtCurrent, liquidity, true) : amount1Delta(sqrtCurrent, sqrtTarget, liquidity, true)
|
|
67
|
+
let sqrtNext: bigint
|
|
68
|
+
let amountIn: bigint
|
|
69
|
+
let amountOut: bigint
|
|
70
|
+
const outAtTarget = () => (zeroForOne ? amount1Delta(sqrtTarget, sqrtCurrent, liquidity, false) : amount0Delta(sqrtCurrent, sqrtTarget, liquidity, false))
|
|
71
|
+
let reached = inAtTarget <= U64_MAX && amountForPrice >= inAtTarget
|
|
72
|
+
// Raydium:目标价格处的输出超过 u64 也算走不到;Orca 照常走到目标(之后报错)
|
|
73
|
+
const out = reached ? outAtTarget() : 0n
|
|
74
|
+
if (reached && program === 'raydium' && out > U64_MAX) reached = false
|
|
75
|
+
if (reached) {
|
|
76
|
+
sqrtNext = sqrtTarget
|
|
77
|
+
amountIn = inAtTarget
|
|
78
|
+
amountOut = out
|
|
79
|
+
} else {
|
|
80
|
+
sqrtNext = nextSqrtPriceFromInput(sqrtCurrent, liquidity, amountForPrice, zeroForOne)
|
|
81
|
+
amountIn = zeroForOne ? amount0Delta(sqrtNext, sqrtCurrent, liquidity, true) : amount1Delta(sqrtCurrent, sqrtNext, liquidity, true)
|
|
82
|
+
amountOut = zeroForOne ? amount1Delta(sqrtNext, sqrtCurrent, liquidity, false) : amount0Delta(sqrtCurrent, sqrtNext, liquidity, false)
|
|
83
|
+
}
|
|
84
|
+
if (amountIn > U64_MAX || amountOut > U64_MAX) throw new SwapMathError('token amount exceeds u64')
|
|
85
|
+
if (zeroForOne ? sqrtNext < sqrtTarget : sqrtNext > sqrtTarget) throw new SwapMathError('price moved past the target')
|
|
86
|
+
let feeAmount: bigint
|
|
87
|
+
if (feeOnInput) {
|
|
88
|
+
feeAmount = sqrtNext !== sqrtTarget ? remaining - amountIn : mulDivCeil(amountIn, feeRate, FEE_RATE_DENOMINATOR - feeRate)
|
|
89
|
+
} else {
|
|
90
|
+
feeAmount = mulDivCeil(amountOut, feeRate, FEE_RATE_DENOMINATOR)
|
|
91
|
+
amountOut -= feeAmount
|
|
92
|
+
// 没走到目标价格:输入全部用掉(不足一个单位的零头归池子)
|
|
93
|
+
if (sqrtNext !== sqrtTarget) amountIn = remaining
|
|
94
|
+
}
|
|
95
|
+
return { sqrtPrice: sqrtNext, amountIn, amountOut, feeAmount }
|
|
96
|
+
}
|