@xyo-network/uniswap-v4-crypto-market-plugin 3.5.2

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.
Files changed (61) hide show
  1. package/LICENSE +165 -0
  2. package/README.md +13 -0
  3. package/dist/neutral/index.mjs +194 -0
  4. package/dist/neutral/index.mjs.map +1 -0
  5. package/dist/types/Config.d.ts +8 -0
  6. package/dist/types/Config.d.ts.map +1 -0
  7. package/dist/types/Plugin.d.ts +15 -0
  8. package/dist/types/Plugin.d.ts.map +1 -0
  9. package/dist/types/Witness.d.ts +19 -0
  10. package/dist/types/Witness.d.ts.map +1 -0
  11. package/dist/types/index.d.ts +5 -0
  12. package/dist/types/index.d.ts.map +1 -0
  13. package/dist/types/lib/UniswapV4ContractAddresses.d.ts +11 -0
  14. package/dist/types/lib/UniswapV4ContractAddresses.d.ts.map +1 -0
  15. package/dist/types/lib/UniswapV4DefaultPools.d.ts +4 -0
  16. package/dist/types/lib/UniswapV4DefaultPools.d.ts.map +1 -0
  17. package/dist/types/lib/UniswapV4TokenIdentifier.d.ts +8 -0
  18. package/dist/types/lib/UniswapV4TokenIdentifier.d.ts.map +1 -0
  19. package/dist/types/lib/getExchangeRate.d.ts +13 -0
  20. package/dist/types/lib/getExchangeRate.d.ts.map +1 -0
  21. package/dist/types/lib/getPoolId.d.ts +13 -0
  22. package/dist/types/lib/getPoolId.d.ts.map +1 -0
  23. package/dist/types/lib/getPriceFromSqrtX96.d.ts +9 -0
  24. package/dist/types/lib/getPriceFromSqrtX96.d.ts.map +1 -0
  25. package/dist/types/lib/index.d.ts +5 -0
  26. package/dist/types/lib/index.d.ts.map +1 -0
  27. package/dist/types/lib/priceFromUniswapV4.d.ts +5 -0
  28. package/dist/types/lib/priceFromUniswapV4.d.ts.map +1 -0
  29. package/dist/types/lib/pricesFromUniswapV4.d.ts +5 -0
  30. package/dist/types/lib/pricesFromUniswapV4.d.ts.map +1 -0
  31. package/dist/types/lib/sortTokens.d.ts +23 -0
  32. package/dist/types/lib/sortTokens.d.ts.map +1 -0
  33. package/dist/types/lib/tokenRegistryValueToToken.d.ts +4 -0
  34. package/dist/types/lib/tokenRegistryValueToToken.d.ts.map +1 -0
  35. package/dist/types/types/TokenPairPoolKey.d.ts +8 -0
  36. package/dist/types/types/TokenPairPoolKey.d.ts.map +1 -0
  37. package/dist/types/types/TokenParameters.d.ts +36 -0
  38. package/dist/types/types/TokenParameters.d.ts.map +1 -0
  39. package/dist/types/types/index.d.ts +3 -0
  40. package/dist/types/types/index.d.ts.map +1 -0
  41. package/package.json +60 -0
  42. package/src/Config.ts +9 -0
  43. package/src/Plugin.ts +16 -0
  44. package/src/Witness.ts +49 -0
  45. package/src/index.ts +4 -0
  46. package/src/lib/UniswapV4ContractAddresses.ts +11 -0
  47. package/src/lib/UniswapV4DefaultPools.ts +27 -0
  48. package/src/lib/UniswapV4TokenIdentifier.ts +7 -0
  49. package/src/lib/getExchangeRate.ts +35 -0
  50. package/src/lib/getPoolId.ts +28 -0
  51. package/src/lib/getPriceFromSqrtX96.ts +26 -0
  52. package/src/lib/index.ts +4 -0
  53. package/src/lib/priceFromUniswapV4.ts +28 -0
  54. package/src/lib/pricesFromUniswapV4.ts +9 -0
  55. package/src/lib/sortTokens.ts +25 -0
  56. package/src/lib/tokenRegistryValueToToken.ts +12 -0
  57. package/src/types/TokenPairPoolKey.ts +21 -0
  58. package/src/types/TokenParameters.ts +39 -0
  59. package/src/types/index.ts +2 -0
  60. package/typedoc.json +5 -0
  61. package/xy.config.ts +10 -0
package/LICENSE ADDED
@@ -0,0 +1,165 @@
1
+ GNU LESSER GENERAL PUBLIC LICENSE
2
+ Version 3, 29 June 2007
3
+
4
+ Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
5
+ Everyone is permitted to copy and distribute verbatim copies
6
+ of this license document, but changing it is not allowed.
7
+
8
+
9
+ This version of the GNU Lesser General Public License incorporates
10
+ the terms and conditions of version 3 of the GNU General Public
11
+ License, supplemented by the additional permissions listed below.
12
+
13
+ 0. Additional Definitions.
14
+
15
+ As used herein, "this License" refers to version 3 of the GNU Lesser
16
+ General Public License, and the "GNU GPL" refers to version 3 of the GNU
17
+ General Public License.
18
+
19
+ "The Library" refers to a covered work governed by this License,
20
+ other than an Application or a Combined Work as defined below.
21
+
22
+ An "Application" is any work that makes use of an interface provided
23
+ by the Library, but which is not otherwise based on the Library.
24
+ Defining a subclass of a class defined by the Library is deemed a mode
25
+ of using an interface provided by the Library.
26
+
27
+ A "Combined Work" is a work produced by combining or linking an
28
+ Application with the Library. The particular version of the Library
29
+ with which the Combined Work was made is also called the "Linked
30
+ Version".
31
+
32
+ The "Minimal Corresponding Source" for a Combined Work means the
33
+ Corresponding Source for the Combined Work, excluding any source code
34
+ for portions of the Combined Work that, considered in isolation, are
35
+ based on the Application, and not on the Linked Version.
36
+
37
+ The "Corresponding Application Code" for a Combined Work means the
38
+ object code and/or source code for the Application, including any data
39
+ and utility programs needed for reproducing the Combined Work from the
40
+ Application, but excluding the System Libraries of the Combined Work.
41
+
42
+ 1. Exception to Section 3 of the GNU GPL.
43
+
44
+ You may convey a covered work under sections 3 and 4 of this License
45
+ without being bound by section 3 of the GNU GPL.
46
+
47
+ 2. Conveying Modified Versions.
48
+
49
+ If you modify a copy of the Library, and, in your modifications, a
50
+ facility refers to a function or data to be supplied by an Application
51
+ that uses the facility (other than as an argument passed when the
52
+ facility is invoked), then you may convey a copy of the modified
53
+ version:
54
+
55
+ a) under this License, provided that you make a good faith effort to
56
+ ensure that, in the event an Application does not supply the
57
+ function or data, the facility still operates, and performs
58
+ whatever part of its purpose remains meaningful, or
59
+
60
+ b) under the GNU GPL, with none of the additional permissions of
61
+ this License applicable to that copy.
62
+
63
+ 3. Object Code Incorporating Material from Library Header Files.
64
+
65
+ The object code form of an Application may incorporate material from
66
+ a header file that is part of the Library. You may convey such object
67
+ code under terms of your choice, provided that, if the incorporated
68
+ material is not limited to numerical parameters, data structure
69
+ layouts and accessors, or small macros, inline functions and templates
70
+ (ten or fewer lines in length), you do both of the following:
71
+
72
+ a) Give prominent notice with each copy of the object code that the
73
+ Library is used in it and that the Library and its use are
74
+ covered by this License.
75
+
76
+ b) Accompany the object code with a copy of the GNU GPL and this license
77
+ document.
78
+
79
+ 4. Combined Works.
80
+
81
+ You may convey a Combined Work under terms of your choice that,
82
+ taken together, effectively do not restrict modification of the
83
+ portions of the Library contained in the Combined Work and reverse
84
+ engineering for debugging such modifications, if you also do each of
85
+ the following:
86
+
87
+ a) Give prominent notice with each copy of the Combined Work that
88
+ the Library is used in it and that the Library and its use are
89
+ covered by this License.
90
+
91
+ b) Accompany the Combined Work with a copy of the GNU GPL and this license
92
+ document.
93
+
94
+ c) For a Combined Work that displays copyright notices during
95
+ execution, include the copyright notice for the Library among
96
+ these notices, as well as a reference directing the user to the
97
+ copies of the GNU GPL and this license document.
98
+
99
+ d) Do one of the following:
100
+
101
+ 0) Convey the Minimal Corresponding Source under the terms of this
102
+ License, and the Corresponding Application Code in a form
103
+ suitable for, and under terms that permit, the user to
104
+ recombine or relink the Application with a modified version of
105
+ the Linked Version to produce a modified Combined Work, in the
106
+ manner specified by section 6 of the GNU GPL for conveying
107
+ Corresponding Source.
108
+
109
+ 1) Use a suitable shared library mechanism for linking with the
110
+ Library. A suitable mechanism is one that (a) uses at run time
111
+ a copy of the Library already present on the user's computer
112
+ system, and (b) will operate properly with a modified version
113
+ of the Library that is interface-compatible with the Linked
114
+ Version.
115
+
116
+ e) Provide Installation Information, but only if you would otherwise
117
+ be required to provide such information under section 6 of the
118
+ GNU GPL, and only to the extent that such information is
119
+ necessary to install and execute a modified version of the
120
+ Combined Work produced by recombining or relinking the
121
+ Application with a modified version of the Linked Version. (If
122
+ you use option 4d0, the Installation Information must accompany
123
+ the Minimal Corresponding Source and Corresponding Application
124
+ Code. If you use option 4d1, you must provide the Installation
125
+ Information in the manner specified by section 6 of the GNU GPL
126
+ for conveying Corresponding Source.)
127
+
128
+ 5. Combined Libraries.
129
+
130
+ You may place library facilities that are a work based on the
131
+ Library side by side in a single library together with other library
132
+ facilities that are not Applications and are not covered by this
133
+ License, and convey such a combined library under terms of your
134
+ choice, if you do both of the following:
135
+
136
+ a) Accompany the combined library with a copy of the same work based
137
+ on the Library, uncombined with any other library facilities,
138
+ conveyed under the terms of this License.
139
+
140
+ b) Give prominent notice with the combined library that part of it
141
+ is a work based on the Library, and explaining where to find the
142
+ accompanying uncombined form of the same work.
143
+
144
+ 6. Revised Versions of the GNU Lesser General Public License.
145
+
146
+ The Free Software Foundation may publish revised and/or new versions
147
+ of the GNU Lesser General Public License from time to time. Such new
148
+ versions will be similar in spirit to the present version, but may
149
+ differ in detail to address new problems or concerns.
150
+
151
+ Each version is given a distinguishing version number. If the
152
+ Library as you received it specifies that a certain numbered version
153
+ of the GNU Lesser General Public License "or any later version"
154
+ applies to it, you have the option of following the terms and
155
+ conditions either of that published version or of any later version
156
+ published by the Free Software Foundation. If the Library as you
157
+ received it does not specify a version number of the GNU Lesser
158
+ General Public License, you may choose any version of the GNU Lesser
159
+ General Public License ever published by the Free Software Foundation.
160
+
161
+ If the Library as you received it specifies that a proxy can decide
162
+ whether future versions of the GNU Lesser General Public License shall
163
+ apply, that proxy's public statement of acceptance of any version is
164
+ permanent authorization for you to choose that version for the
165
+ Library.
package/README.md ADDED
@@ -0,0 +1,13 @@
1
+ [![logo][]](https://xyo.network)
2
+
3
+ Part of [sdk-xyo-client-js](https://www.npmjs.com/package/@xyo-network/sdk-xyo-client-js)
4
+
5
+ ## License
6
+
7
+ > See the [LICENSE](LICENSE) file for license details
8
+
9
+ ## Credits
10
+
11
+ [Made with 🔥 and ❄️ by XYO](https://xyo.network)
12
+
13
+ [logo]: https://cdn.xy.company/img/brand/XYO_full_colored.png
@@ -0,0 +1,194 @@
1
+ // src/lib/priceFromUniswapV4.ts
2
+ import { ZeroAddress as ZeroAddress3 } from "ethers";
3
+
4
+ // src/lib/getExchangeRate.ts
5
+ import { IStateView__factory } from "@xyo-network/uniswap-typechain/v4-periphery";
6
+ import { ZeroAddress as ZeroAddress2 } from "ethers/constants";
7
+
8
+ // src/lib/getPoolId.ts
9
+ import { AbiCoder } from "ethers/abi";
10
+ import { ZeroAddress } from "ethers/constants";
11
+ import { keccak256 } from "ethers/crypto";
12
+
13
+ // src/lib/sortTokens.ts
14
+ var sortTokens = (tokenA, tokenB) => {
15
+ return tokenA.sortsBefore(tokenB) ? [tokenA, tokenB] : [tokenB, tokenA];
16
+ };
17
+
18
+ // src/lib/getPoolId.ts
19
+ var getPoolId = (tokenA, tokenB, fee, tickSpacing, hooks) => {
20
+ const [currency0, currency1] = sortTokens(tokenA, tokenB);
21
+ const currency0Addr = currency0.isNative ? ZeroAddress : currency0.wrapped.address;
22
+ const currency1Addr = currency1.isNative ? ZeroAddress : currency1.wrapped.address;
23
+ return keccak256(
24
+ AbiCoder.defaultAbiCoder().encode(
25
+ ["address", "address", "uint24", "int24", "address"],
26
+ [currency0Addr, currency1Addr, fee, tickSpacing, hooks]
27
+ )
28
+ );
29
+ };
30
+
31
+ // src/lib/getPriceFromSqrtX96.ts
32
+ var getPriceFromSqrtX96 = (sqrtPriceX96, decimalsA, decimalsB) => {
33
+ const Q96 = 2n ** 96n;
34
+ const numerator = sqrtPriceX96 * sqrtPriceX96 * 10n ** 18n;
35
+ const denominator = Q96 * Q96;
36
+ let price = numerator / denominator;
37
+ const decimalAdjustment = decimalsB - decimalsA;
38
+ if (decimalAdjustment > 0) {
39
+ price *= 10n ** BigInt(decimalAdjustment);
40
+ } else if (decimalAdjustment < 0) {
41
+ price /= 10n ** BigInt(-decimalAdjustment);
42
+ }
43
+ return Number(price) / 1e18;
44
+ };
45
+
46
+ // src/lib/UniswapV4ContractAddresses.ts
47
+ var UniswapV4ContractAddresses = {
48
+ Ethereum: {
49
+ PoolManager: "0x000000000004444c5dc75cB358380D2e3dE08A90",
50
+ PositionDescriptor: "0xd1428ba554f4c8450b763a0b2040a4935c63f06c",
51
+ PositionManager: "0xbd216513d74c8cf14cf4747e6aaa6420ff64ee9e",
52
+ Quoter: "0x52f0e24d1c21c8a0cb1e5a5dd6198556bd9e1203",
53
+ StateView: "0x7ffe42c4a5deea5b0fec41c94c136cf115597227",
54
+ UniversalRouter: "0x66a9893cc07d91d95644aedd05d03f95e1dba8af"
55
+ }
56
+ };
57
+
58
+ // src/lib/getExchangeRate.ts
59
+ var getExchangeRate = async (tokenA, tokenB, fee, hookAddress, provider) => {
60
+ const hooks = hookAddress || ZeroAddress2;
61
+ const stateView = IStateView__factory.connect(UniswapV4ContractAddresses.Ethereum.StateView, provider);
62
+ const [token0, token1] = sortTokens(tokenA, tokenB);
63
+ const poolId = getPoolId(token0, token1, fee, 60, hooks);
64
+ if (poolId === ZeroAddress2) throw new Error("Invalid poolId");
65
+ const response = await stateView.getSlot0(poolId);
66
+ const price = getPriceFromSqrtX96(response.sqrtPriceX96, token1.decimals, token0.decimals);
67
+ return price;
68
+ };
69
+
70
+ // src/lib/tokenRegistryValueToToken.ts
71
+ import { Token } from "@uniswap/sdk-core";
72
+ import { getAddress } from "ethers/address";
73
+ var tokenRegistryValueToToken = (value) => {
74
+ const {
75
+ address,
76
+ chainId,
77
+ decimals,
78
+ symbol,
79
+ name
80
+ } = value;
81
+ const normalizedAddress = getAddress(address.toLowerCase());
82
+ return new Token(chainId, normalizedAddress, decimals, symbol, name);
83
+ };
84
+
85
+ // src/lib/priceFromUniswapV4.ts
86
+ var priceFromUniswapV4 = async (poolId, provider) => {
87
+ const {
88
+ tokens,
89
+ fee,
90
+ hookAddress = ZeroAddress3
91
+ } = poolId;
92
+ const tokenA = tokenRegistryValueToToken(tokens[0]);
93
+ const tokenB = tokenRegistryValueToToken(tokens[1]);
94
+ const rate = await getExchangeRate(tokenA, tokenB, fee, hookAddress, provider);
95
+ const token0 = {
96
+ address: tokenA.address,
97
+ symbol: tokenA.symbol || "",
98
+ value: Math.max(rate, 0)
99
+ };
100
+ const token1 = {
101
+ address: tokenB.address,
102
+ symbol: tokenB.symbol || "",
103
+ value: rate > 0 ? Number((1 / rate).toPrecision(6)) : 0
104
+ };
105
+ const pair = { tokens: [token0, token1] };
106
+ return pair;
107
+ };
108
+
109
+ // src/lib/pricesFromUniswapV4.ts
110
+ var pricesFromUniswapV4 = async (poolId, provider) => {
111
+ return await Promise.all(poolId.map((pool) => priceFromUniswapV4(pool, provider)));
112
+ };
113
+
114
+ // src/lib/UniswapV4DefaultPools.ts
115
+ import { ZeroAddress as ZeroAddress4 } from "ethers";
116
+ var TokenRegistry = {
117
+ USDT: {
118
+ address: "0xdac17f958d2ee523a2206206994597c13d831ec7",
119
+ chainId: 1,
120
+ decimals: 6,
121
+ symbol: "USDT"
122
+ },
123
+ XYO: {
124
+ address: "0x55296f69f40ea6d20e478533c15a6b08b654e758",
125
+ chainId: 1,
126
+ decimals: 18,
127
+ symbol: "XYO"
128
+ }
129
+ };
130
+ var UniswapV4DefaultPools = {
131
+ "XYO:USDT": {
132
+ fee: 3e3,
133
+ hookAddress: ZeroAddress4,
134
+ tickSpacing: 60,
135
+ tokens: [TokenRegistry.XYO, TokenRegistry.USDT]
136
+ }
137
+ };
138
+
139
+ // src/Plugin.ts
140
+ import { PayloadSetSchema } from "@xyo-network/payload-model";
141
+ import { createPayloadSetWitnessPlugin } from "@xyo-network/payloadset-plugin";
142
+ import { UniswapCryptoMarketSchema as UniswapCryptoMarketSchema2 } from "@xyo-network/uniswap-crypto-market-payload-plugin";
143
+
144
+ // src/Witness.ts
145
+ import { assertEx } from "@xylabs/assert";
146
+ import { AbstractWitness } from "@xyo-network/abstract-witness";
147
+ import { UniswapCryptoMarketSchema, UniswapV4CryptoMarketWitnessConfigSchema } from "@xyo-network/uniswap-crypto-market-payload-plugin";
148
+ var UniswapV4CryptoMarketWitness = class extends AbstractWitness {
149
+ static configSchemas = [...super.configSchemas, UniswapV4CryptoMarketWitnessConfigSchema];
150
+ static defaultConfigSchema = UniswapV4CryptoMarketWitnessConfigSchema;
151
+ get pools() {
152
+ return this.config?.poolKeys ?? Object.values(UniswapV4DefaultPools);
153
+ }
154
+ get provider() {
155
+ return assertEx(this.params.provider, () => "Provider Required");
156
+ }
157
+ async observeHandler() {
158
+ await this.started("throw");
159
+ const pairs = await pricesFromUniswapV4(this.pools, this.provider);
160
+ const timestamp = Date.now();
161
+ const payload = {
162
+ pairs,
163
+ schema: UniswapCryptoMarketSchema,
164
+ timestamp
165
+ };
166
+ return [payload];
167
+ }
168
+ async startHandler() {
169
+ await super.startHandler();
170
+ return true;
171
+ }
172
+ };
173
+
174
+ // src/Plugin.ts
175
+ var UniswapV4CryptoMarketPlugin = () => createPayloadSetWitnessPlugin(
176
+ { required: { [UniswapCryptoMarketSchema2]: 1 }, schema: PayloadSetSchema },
177
+ {
178
+ witness: async (params) => {
179
+ const result = await UniswapV4CryptoMarketWitness.create(params);
180
+ return result;
181
+ }
182
+ }
183
+ );
184
+ export {
185
+ TokenRegistry,
186
+ UniswapV4CryptoMarketPlugin,
187
+ UniswapV4CryptoMarketWitness,
188
+ UniswapV4DefaultPools,
189
+ UniswapV4CryptoMarketPlugin as default,
190
+ priceFromUniswapV4,
191
+ pricesFromUniswapV4,
192
+ tokenRegistryValueToToken
193
+ };
194
+ //# sourceMappingURL=index.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../src/lib/priceFromUniswapV4.ts","../../src/lib/getExchangeRate.ts","../../src/lib/getPoolId.ts","../../src/lib/sortTokens.ts","../../src/lib/getPriceFromSqrtX96.ts","../../src/lib/UniswapV4ContractAddresses.ts","../../src/lib/tokenRegistryValueToToken.ts","../../src/lib/pricesFromUniswapV4.ts","../../src/lib/UniswapV4DefaultPools.ts","../../src/Plugin.ts","../../src/Witness.ts"],"sourcesContent":["import type { UniswapCryptoPair, UniswapCryptoToken } from '@xyo-network/uniswap-crypto-market-payload-plugin'\nimport type { Provider } from 'ethers'\nimport { ZeroAddress } from 'ethers'\n\nimport type { TokenPairPoolKey } from '../types/index.ts'\nimport { getExchangeRate } from './getExchangeRate.ts'\nimport { tokenRegistryValueToToken } from './tokenRegistryValueToToken.ts'\n\nexport const priceFromUniswapV4 = async (poolId: TokenPairPoolKey, provider: Provider): Promise<UniswapCryptoPair> => {\n const {\n tokens, fee, hookAddress = ZeroAddress,\n } = poolId\n const tokenA = tokenRegistryValueToToken(tokens[0])\n const tokenB = tokenRegistryValueToToken(tokens[1])\n const rate = await getExchangeRate(tokenA, tokenB, fee, hookAddress, provider)\n const token0: UniswapCryptoToken = {\n address: tokenA.address,\n symbol: tokenA.symbol || '',\n value: Math.max(rate, 0),\n }\n const token1: UniswapCryptoToken = {\n address: tokenB.address,\n symbol: tokenB.symbol || '',\n value: rate > 0 ? Number((1 / rate).toPrecision(6)) : 0,\n }\n const pair: UniswapCryptoPair = { tokens: [token0, token1] }\n return pair\n}\n","import type { Token } from '@uniswap/sdk-core'\nimport { IStateView__factory } from '@xyo-network/uniswap-typechain/v4-periphery'\nimport { ZeroAddress } from 'ethers/constants'\nimport type { Provider } from 'ethers/providers'\n\nimport { getPoolId } from './getPoolId.ts'\nimport { getPriceFromSqrtX96 } from './getPriceFromSqrtX96.ts'\nimport { sortTokens } from './sortTokens.ts'\nimport { UniswapV4ContractAddresses } from './UniswapV4ContractAddresses.ts'\n\n/**\n * Returns the price of the token pair in the Uniswap V4 pool.\n * @param tokenA The first token in the pair.\n * @param tokenB The second token in the pair.\n * @param fee The fee tier for the pool.\n * @param hookAddress The address of the hook contract. Default is ZeroAddress.\n * @param provider The EVM provider to use for the transaction.\n * @returns The price of the token pair.\n */\nexport const getExchangeRate = async (\n tokenA: Token,\n tokenB: Token,\n fee: number,\n hookAddress: string | undefined,\n provider: Provider,\n): Promise<number> => {\n const hooks = hookAddress || ZeroAddress\n const stateView = IStateView__factory.connect(UniswapV4ContractAddresses.Ethereum.StateView, provider)\n const [token0, token1] = sortTokens(tokenA, tokenB)\n const poolId: string = getPoolId(token0, token1, fee, 60, hooks)\n if (poolId === ZeroAddress) throw new Error('Invalid poolId')\n const response = await stateView.getSlot0(poolId)\n const price = getPriceFromSqrtX96(response.sqrtPriceX96, token1.decimals, token0.decimals)\n return price\n}\n","import type { Token } from '@uniswap/sdk-core'\nimport { AbiCoder } from 'ethers/abi'\nimport { ZeroAddress } from 'ethers/constants'\nimport { keccak256 } from 'ethers/crypto'\n\nimport { sortTokens } from './sortTokens.ts'\n\n/**\n * Computes the pool address for a given pair of tokens, fee, tick spacing, and hooks which\n * is used to identify the pool on the Uniswap V4 protocol.\n * @param tokenA - The first token in the pair.\n * @param tokenB - The second token in the pair.\n * @param fee - The fee tier for the pool.\n * @param tickSpacing - The tick spacing for the pool.\n * @param hooks - The hooks associated with the pool.\n * @returns The computed pool address as a string.\n */\nexport const getPoolId = (tokenA: Token, tokenB: Token, fee: number, tickSpacing: number, hooks: string): string => {\n const [currency0, currency1] = sortTokens(tokenA, tokenB)\n const currency0Addr = currency0.isNative ? ZeroAddress : currency0.wrapped.address\n const currency1Addr = currency1.isNative ? ZeroAddress : currency1.wrapped.address\n return keccak256(\n AbiCoder.defaultAbiCoder().encode(\n ['address', 'address', 'uint24', 'int24', 'address'],\n [currency0Addr, currency1Addr, fee, tickSpacing, hooks],\n ),\n )\n}\n","import type { Token } from '@uniswap/sdk-core'\n\n/**\n * Sorts two tokens in ascending order by address to ensure consistent ordering.\n *\n * In Uniswap v2, v3, and v4, pool addresses are deterministically derived using\n * `CREATE2` with a hash of the pool's initialization parameters. One critical\n * part of this hash is the `token0` and `token1` addresses. To ensure uniqueness\n * and prevent duplicate pools (e.g., USDC/WETH and WETH/USDC being treated as different),\n * Uniswap requires that token pairs be ordered **lexicographically by address**.\n *\n * This method ensures that tokens are sorted according to that rule.\n *\n * This is required any time you:\n * - Derive a pool address\n * - Generate a pool ID\n * - Call a function that expects a PoolKey or token pair in sorted order\n *\n * @param tokenA - The first token to compare\n * @param tokenB - The second token to compare\n * @returns A tuple `[token0, token1]` sorted by address in ascending order\n */\nexport const sortTokens = (tokenA: Token, tokenB: Token): [Token, Token] => {\n return tokenA.sortsBefore(tokenB) ? [tokenA, tokenB] : [tokenB, tokenA]\n}\n","/**\n * Calculates the price from the square root price in Q96 format.\n * @param sqrtPriceX96 The square root price in Q96 format.\n * @param decimalsA The number of decimals for the first token.\n * @param decimalsB The number of decimals for the second token.\n * @returns The price as a number.\n */\nexport const getPriceFromSqrtX96 = (sqrtPriceX96: bigint, decimalsA: number, decimalsB: number): number => {\n const Q96 = 2n ** 96n\n\n // Scale to avoid floating point math by using a 1e18 factor\n const numerator = sqrtPriceX96 * sqrtPriceX96 * 10n ** 18n\n const denominator = Q96 * Q96\n\n let price = numerator / denominator\n\n // Adjust for decimal differences\n const decimalAdjustment = decimalsB - decimalsA\n if (decimalAdjustment > 0) {\n price *= 10n ** BigInt(decimalAdjustment)\n } else if (decimalAdjustment < 0) {\n price /= 10n ** BigInt(-decimalAdjustment)\n }\n\n return Number(price) / 1e18\n}\n","// https://docs.uniswap.org/contracts/v4/deployments#mainnet-deployments\nexport const UniswapV4ContractAddresses = {\n Ethereum: {\n PoolManager: '0x000000000004444c5dc75cB358380D2e3dE08A90',\n PositionDescriptor: '0xd1428ba554f4c8450b763a0b2040a4935c63f06c',\n PositionManager: '0xbd216513d74c8cf14cf4747e6aaa6420ff64ee9e',\n Quoter: '0x52f0e24d1c21c8a0cb1e5a5dd6198556bd9e1203',\n StateView: '0x7ffe42c4a5deea5b0fec41c94c136cf115597227',\n UniversalRouter: '0x66a9893cc07d91d95644aedd05d03f95e1dba8af',\n },\n}\n","import { Token } from '@uniswap/sdk-core'\nimport { getAddress } from 'ethers/address'\n\nimport type { TokenParameters } from '../types/index.ts'\n\nexport const tokenRegistryValueToToken = (value: TokenParameters): Token => {\n const {\n address, chainId, decimals, symbol, name,\n } = value\n const normalizedAddress = getAddress(address.toLowerCase())\n return new Token(chainId, normalizedAddress, decimals, symbol, name)\n}\n","import type { UniswapCryptoPair } from '@xyo-network/uniswap-crypto-market-payload-plugin'\nimport type { Provider } from 'ethers'\n\nimport type { TokenPairPoolKey } from '../types/index.ts'\nimport { priceFromUniswapV4 } from './priceFromUniswapV4.ts'\n\nexport const pricesFromUniswapV4 = async (poolId: TokenPairPoolKey[], provider: Provider): Promise<UniswapCryptoPair[]> => {\n return await Promise.all(poolId.map(pool => priceFromUniswapV4(pool, provider)))\n}\n","import { ZeroAddress } from 'ethers'\n\nimport type { TokenPairPoolKey, TokenParameters } from '../types/index.ts'\n\nexport const TokenRegistry: Record<string, TokenParameters> = {\n USDT: {\n address: '0xdac17f958d2ee523a2206206994597c13d831ec7',\n chainId: 1,\n decimals: 6,\n symbol: 'USDT',\n },\n XYO: {\n address: '0x55296f69f40ea6d20e478533c15a6b08b654e758',\n chainId: 1,\n decimals: 18,\n symbol: 'XYO',\n },\n} as const\n\nexport const UniswapV4DefaultPools: Record<string, TokenPairPoolKey> = {\n 'XYO:USDT': {\n fee: 3000,\n hookAddress: ZeroAddress,\n tickSpacing: 60,\n tokens: [TokenRegistry.XYO, TokenRegistry.USDT],\n },\n} as const\n","import { PayloadSetSchema } from '@xyo-network/payload-model'\nimport { createPayloadSetWitnessPlugin } from '@xyo-network/payloadset-plugin'\nimport { UniswapCryptoMarketSchema } from '@xyo-network/uniswap-crypto-market-payload-plugin'\n\nimport { UniswapV4CryptoMarketWitness } from './Witness.ts'\n\nexport const UniswapV4CryptoMarketPlugin = () =>\n createPayloadSetWitnessPlugin<UniswapV4CryptoMarketWitness>(\n { required: { [UniswapCryptoMarketSchema]: 1 }, schema: PayloadSetSchema },\n {\n witness: async (params) => {\n const result = await UniswapV4CryptoMarketWitness.create(params)\n return result\n },\n },\n )\n","import { assertEx } from '@xylabs/assert'\nimport { AbstractWitness } from '@xyo-network/abstract-witness'\nimport type { AnyConfigSchema } from '@xyo-network/module-model'\nimport type { Payload, Schema } from '@xyo-network/payload-model'\nimport type { UniswapCryptoMarketPayload } from '@xyo-network/uniswap-crypto-market-payload-plugin'\nimport { UniswapCryptoMarketSchema, UniswapV4CryptoMarketWitnessConfigSchema } from '@xyo-network/uniswap-crypto-market-payload-plugin'\nimport type { WitnessParams } from '@xyo-network/witness-model'\nimport type { Provider } from 'ethers'\n\nimport type { UniswapV4CryptoMarketWitnessConfig } from './Config.ts'\nimport { pricesFromUniswapV4, UniswapV4DefaultPools } from './lib/index.ts'\nimport type { TokenPairPoolKey } from './types/index.ts'\n\nexport type UniswapV4CryptoMarketWitnessParams = WitnessParams<\n AnyConfigSchema<UniswapV4CryptoMarketWitnessConfig>,\n {\n provider?: Provider\n }\n>\n\nexport class UniswapV4CryptoMarketWitness<\n TParams extends UniswapV4CryptoMarketWitnessParams = UniswapV4CryptoMarketWitnessParams,\n> extends AbstractWitness<TParams> {\n static override readonly configSchemas: Schema[] = [...super.configSchemas, UniswapV4CryptoMarketWitnessConfigSchema]\n static override readonly defaultConfigSchema: Schema = UniswapV4CryptoMarketWitnessConfigSchema\n\n protected get pools(): TokenPairPoolKey[] {\n return this.config?.poolKeys ?? Object.values(UniswapV4DefaultPools)\n }\n\n protected get provider() {\n return assertEx(this.params.provider, () => 'Provider Required')\n }\n\n protected override async observeHandler(): Promise<Payload[]> {\n await this.started('throw')\n const pairs = await pricesFromUniswapV4(this.pools, this.provider)\n const timestamp = Date.now()\n const payload: UniswapCryptoMarketPayload = {\n pairs, schema: UniswapCryptoMarketSchema, timestamp,\n }\n return [payload]\n }\n\n protected override async startHandler() {\n await super.startHandler()\n return true\n }\n}\n"],"mappings":"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","names":["ZeroAddress","ZeroAddress","ZeroAddress","ZeroAddress","ZeroAddress","UniswapCryptoMarketSchema","UniswapCryptoMarketSchema"]}
@@ -0,0 +1,8 @@
1
+ import type { UniswapV4CryptoMarketWitnessConfigSchema } from '@xyo-network/uniswap-crypto-market-payload-plugin';
2
+ import type { WitnessConfig } from '@xyo-network/witness-model';
3
+ import type { TokenPairPoolKey } from './types/index.ts';
4
+ export type UniswapV4CryptoMarketWitnessConfig = WitnessConfig<{
5
+ poolKeys?: TokenPairPoolKey[];
6
+ schema: UniswapV4CryptoMarketWitnessConfigSchema;
7
+ }>;
8
+ //# sourceMappingURL=Config.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"Config.d.ts","sourceRoot":"","sources":["../../src/Config.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,wCAAwC,EAAE,MAAM,mDAAmD,CAAA;AACjH,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,4BAA4B,CAAA;AAE/D,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,kBAAkB,CAAA;AAExD,MAAM,MAAM,kCAAkC,GAAG,aAAa,CAAC;IAC7D,QAAQ,CAAC,EAAE,gBAAgB,EAAE,CAAA;IAC7B,MAAM,EAAE,wCAAwC,CAAA;CACjD,CAAC,CAAA"}
@@ -0,0 +1,15 @@
1
+ import { UniswapV4CryptoMarketWitness } from './Witness.ts';
2
+ export declare const UniswapV4CryptoMarketPlugin: () => import("@xyo-network/payloadset-plugin").PayloadSetWitnessPlugin<UniswapV4CryptoMarketWitness<import(".store/@xylabs-base-npm-4.8.7-ae479fd9f4/package").BaseParamsFields & {
3
+ account?: import(".store/@xyo-network-account-model-npm-3.13.0-942698b671/package").AccountInstance | "random";
4
+ addToResolvers?: boolean;
5
+ additionalSigners?: import(".store/@xyo-network-account-model-npm-3.13.0-942698b671/package").AccountInstance[];
6
+ allowNameResolution?: boolean;
7
+ config: import("@xyo-network/module-model").AnyConfigSchema<import("./Config.ts").UniswapV4CryptoMarketWitnessConfig>;
8
+ ephemeralQueryAccountEnabled?: boolean;
9
+ moduleIdentifierTransformers?: import("@xyo-network/module-model").ModuleIdentifierTransformer[];
10
+ privateChildren?: import("@xyo-network/module-model").ModuleInstance[];
11
+ publicChildren?: import("@xyo-network/module-model").ModuleInstance[];
12
+ } & {
13
+ provider?: import("ethers").Provider;
14
+ }>>;
15
+ //# sourceMappingURL=Plugin.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"Plugin.d.ts","sourceRoot":"","sources":["../../src/Plugin.ts"],"names":[],"mappings":"AAIA,OAAO,EAAE,4BAA4B,EAAE,MAAM,cAAc,CAAA;AAE3D,eAAO,MAAM,2BAA2B;;;;;;;;;;;;GASrC,CAAA"}
@@ -0,0 +1,19 @@
1
+ import { AbstractWitness } from '@xyo-network/abstract-witness';
2
+ import type { AnyConfigSchema } from '@xyo-network/module-model';
3
+ import type { Payload, Schema } from '@xyo-network/payload-model';
4
+ import type { WitnessParams } from '@xyo-network/witness-model';
5
+ import type { Provider } from 'ethers';
6
+ import type { UniswapV4CryptoMarketWitnessConfig } from './Config.ts';
7
+ import type { TokenPairPoolKey } from './types/index.ts';
8
+ export type UniswapV4CryptoMarketWitnessParams = WitnessParams<AnyConfigSchema<UniswapV4CryptoMarketWitnessConfig>, {
9
+ provider?: Provider;
10
+ }>;
11
+ export declare class UniswapV4CryptoMarketWitness<TParams extends UniswapV4CryptoMarketWitnessParams = UniswapV4CryptoMarketWitnessParams> extends AbstractWitness<TParams> {
12
+ static readonly configSchemas: Schema[];
13
+ static readonly defaultConfigSchema: Schema;
14
+ protected get pools(): TokenPairPoolKey[];
15
+ protected get provider(): Provider;
16
+ protected observeHandler(): Promise<Payload[]>;
17
+ protected startHandler(): Promise<boolean>;
18
+ }
19
+ //# sourceMappingURL=Witness.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"Witness.d.ts","sourceRoot":"","sources":["../../src/Witness.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,eAAe,EAAE,MAAM,+BAA+B,CAAA;AAC/D,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,2BAA2B,CAAA;AAChE,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,EAAE,MAAM,4BAA4B,CAAA;AAGjE,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,4BAA4B,CAAA;AAC/D,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,QAAQ,CAAA;AAEtC,OAAO,KAAK,EAAE,kCAAkC,EAAE,MAAM,aAAa,CAAA;AAErE,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,kBAAkB,CAAA;AAExD,MAAM,MAAM,kCAAkC,GAAG,aAAa,CAC5D,eAAe,CAAC,kCAAkC,CAAC,EACnD;IACE,QAAQ,CAAC,EAAE,QAAQ,CAAA;CACpB,CACF,CAAA;AAED,qBAAa,4BAA4B,CACvC,OAAO,SAAS,kCAAkC,GAAG,kCAAkC,CACvF,SAAQ,eAAe,CAAC,OAAO,CAAC;IAChC,gBAAyB,aAAa,EAAE,MAAM,EAAE,CAAqE;IACrH,gBAAyB,mBAAmB,EAAE,MAAM,CAA2C;IAE/F,SAAS,KAAK,KAAK,IAAI,gBAAgB,EAAE,CAExC;IAED,SAAS,KAAK,QAAQ,aAErB;cAEwB,cAAc,IAAI,OAAO,CAAC,OAAO,EAAE,CAAC;cAUpC,YAAY;CAItC"}
@@ -0,0 +1,5 @@
1
+ export * from './Config.ts';
2
+ export * from './lib/index.ts';
3
+ export { UniswapV4CryptoMarketPlugin as default, UniswapV4CryptoMarketPlugin } from './Plugin.ts';
4
+ export * from './Witness.ts';
5
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":"AAAA,cAAc,aAAa,CAAA;AAC3B,cAAc,gBAAgB,CAAA;AAC9B,OAAO,EAAE,2BAA2B,IAAI,OAAO,EAAE,2BAA2B,EAAE,MAAM,aAAa,CAAA;AACjG,cAAc,cAAc,CAAA"}
@@ -0,0 +1,11 @@
1
+ export declare const UniswapV4ContractAddresses: {
2
+ Ethereum: {
3
+ PoolManager: string;
4
+ PositionDescriptor: string;
5
+ PositionManager: string;
6
+ Quoter: string;
7
+ StateView: string;
8
+ UniversalRouter: string;
9
+ };
10
+ };
11
+ //# sourceMappingURL=UniswapV4ContractAddresses.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"UniswapV4ContractAddresses.d.ts","sourceRoot":"","sources":["../../../src/lib/UniswapV4ContractAddresses.ts"],"names":[],"mappings":"AACA,eAAO,MAAM,0BAA0B;;;;;;;;;CAStC,CAAA"}
@@ -0,0 +1,4 @@
1
+ import type { TokenPairPoolKey, TokenParameters } from '../types/index.ts';
2
+ export declare const TokenRegistry: Record<string, TokenParameters>;
3
+ export declare const UniswapV4DefaultPools: Record<string, TokenPairPoolKey>;
4
+ //# sourceMappingURL=UniswapV4DefaultPools.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"UniswapV4DefaultPools.d.ts","sourceRoot":"","sources":["../../../src/lib/UniswapV4DefaultPools.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAAE,gBAAgB,EAAE,eAAe,EAAE,MAAM,mBAAmB,CAAA;AAE1E,eAAO,MAAM,aAAa,EAAE,MAAM,CAAC,MAAM,EAAE,eAAe,CAahD,CAAA;AAEV,eAAO,MAAM,qBAAqB,EAAE,MAAM,CAAC,MAAM,EAAE,gBAAgB,CAOzD,CAAA"}
@@ -0,0 +1,8 @@
1
+ export interface UniswapV4TokenIdentifier {
2
+ chainId: number;
3
+ address: string;
4
+ decimals: number;
5
+ symbol?: string;
6
+ name?: string;
7
+ }
8
+ //# sourceMappingURL=UniswapV4TokenIdentifier.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"UniswapV4TokenIdentifier.d.ts","sourceRoot":"","sources":["../../../src/lib/UniswapV4TokenIdentifier.ts"],"names":[],"mappings":"AAAA,MAAM,WAAW,wBAAwB;IACvC,OAAO,EAAE,MAAM,CAAA;IACf,OAAO,EAAE,MAAM,CAAA;IACf,QAAQ,EAAE,MAAM,CAAA;IAChB,MAAM,CAAC,EAAE,MAAM,CAAA;IACf,IAAI,CAAC,EAAE,MAAM,CAAA;CACd"}
@@ -0,0 +1,13 @@
1
+ import type { Token } from '@uniswap/sdk-core';
2
+ import type { Provider } from 'ethers/providers';
3
+ /**
4
+ * Returns the price of the token pair in the Uniswap V4 pool.
5
+ * @param tokenA The first token in the pair.
6
+ * @param tokenB The second token in the pair.
7
+ * @param fee The fee tier for the pool.
8
+ * @param hookAddress The address of the hook contract. Default is ZeroAddress.
9
+ * @param provider The EVM provider to use for the transaction.
10
+ * @returns The price of the token pair.
11
+ */
12
+ export declare const getExchangeRate: (tokenA: Token, tokenB: Token, fee: number, hookAddress: string | undefined, provider: Provider) => Promise<number>;
13
+ //# sourceMappingURL=getExchangeRate.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"getExchangeRate.d.ts","sourceRoot":"","sources":["../../../src/lib/getExchangeRate.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,KAAK,EAAE,MAAM,mBAAmB,CAAA;AAG9C,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,kBAAkB,CAAA;AAOhD;;;;;;;;GAQG;AACH,eAAO,MAAM,eAAe,GAC1B,QAAQ,KAAK,EACb,QAAQ,KAAK,EACb,KAAK,MAAM,EACX,aAAa,MAAM,GAAG,SAAS,EAC/B,UAAU,QAAQ,KACjB,OAAO,CAAC,MAAM,CAShB,CAAA"}
@@ -0,0 +1,13 @@
1
+ import type { Token } from '@uniswap/sdk-core';
2
+ /**
3
+ * Computes the pool address for a given pair of tokens, fee, tick spacing, and hooks which
4
+ * is used to identify the pool on the Uniswap V4 protocol.
5
+ * @param tokenA - The first token in the pair.
6
+ * @param tokenB - The second token in the pair.
7
+ * @param fee - The fee tier for the pool.
8
+ * @param tickSpacing - The tick spacing for the pool.
9
+ * @param hooks - The hooks associated with the pool.
10
+ * @returns The computed pool address as a string.
11
+ */
12
+ export declare const getPoolId: (tokenA: Token, tokenB: Token, fee: number, tickSpacing: number, hooks: string) => string;
13
+ //# sourceMappingURL=getPoolId.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"getPoolId.d.ts","sourceRoot":"","sources":["../../../src/lib/getPoolId.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,KAAK,EAAE,MAAM,mBAAmB,CAAA;AAO9C;;;;;;;;;GASG;AACH,eAAO,MAAM,SAAS,GAAI,QAAQ,KAAK,EAAE,QAAQ,KAAK,EAAE,KAAK,MAAM,EAAE,aAAa,MAAM,EAAE,OAAO,MAAM,KAAG,MAUzG,CAAA"}
@@ -0,0 +1,9 @@
1
+ /**
2
+ * Calculates the price from the square root price in Q96 format.
3
+ * @param sqrtPriceX96 The square root price in Q96 format.
4
+ * @param decimalsA The number of decimals for the first token.
5
+ * @param decimalsB The number of decimals for the second token.
6
+ * @returns The price as a number.
7
+ */
8
+ export declare const getPriceFromSqrtX96: (sqrtPriceX96: bigint, decimalsA: number, decimalsB: number) => number;
9
+ //# sourceMappingURL=getPriceFromSqrtX96.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"getPriceFromSqrtX96.d.ts","sourceRoot":"","sources":["../../../src/lib/getPriceFromSqrtX96.ts"],"names":[],"mappings":"AAAA;;;;;;GAMG;AACH,eAAO,MAAM,mBAAmB,GAAI,cAAc,MAAM,EAAE,WAAW,MAAM,EAAE,WAAW,MAAM,KAAG,MAkBhG,CAAA"}
@@ -0,0 +1,5 @@
1
+ export * from './priceFromUniswapV4.ts';
2
+ export * from './pricesFromUniswapV4.ts';
3
+ export * from './tokenRegistryValueToToken.ts';
4
+ export * from './UniswapV4DefaultPools.ts';
5
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../src/lib/index.ts"],"names":[],"mappings":"AAAA,cAAc,yBAAyB,CAAA;AACvC,cAAc,0BAA0B,CAAA;AACxC,cAAc,gCAAgC,CAAA;AAC9C,cAAc,4BAA4B,CAAA"}
@@ -0,0 +1,5 @@
1
+ import type { UniswapCryptoPair } from '@xyo-network/uniswap-crypto-market-payload-plugin';
2
+ import type { Provider } from 'ethers';
3
+ import type { TokenPairPoolKey } from '../types/index.ts';
4
+ export declare const priceFromUniswapV4: (poolId: TokenPairPoolKey, provider: Provider) => Promise<UniswapCryptoPair>;
5
+ //# sourceMappingURL=priceFromUniswapV4.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"priceFromUniswapV4.d.ts","sourceRoot":"","sources":["../../../src/lib/priceFromUniswapV4.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,iBAAiB,EAAsB,MAAM,mDAAmD,CAAA;AAC9G,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,QAAQ,CAAA;AAGtC,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,mBAAmB,CAAA;AAIzD,eAAO,MAAM,kBAAkB,GAAU,QAAQ,gBAAgB,EAAE,UAAU,QAAQ,KAAG,OAAO,CAAC,iBAAiB,CAmBhH,CAAA"}
@@ -0,0 +1,5 @@
1
+ import type { UniswapCryptoPair } from '@xyo-network/uniswap-crypto-market-payload-plugin';
2
+ import type { Provider } from 'ethers';
3
+ import type { TokenPairPoolKey } from '../types/index.ts';
4
+ export declare const pricesFromUniswapV4: (poolId: TokenPairPoolKey[], provider: Provider) => Promise<UniswapCryptoPair[]>;
5
+ //# sourceMappingURL=pricesFromUniswapV4.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"pricesFromUniswapV4.d.ts","sourceRoot":"","sources":["../../../src/lib/pricesFromUniswapV4.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,iBAAiB,EAAE,MAAM,mDAAmD,CAAA;AAC1F,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,QAAQ,CAAA;AAEtC,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,mBAAmB,CAAA;AAGzD,eAAO,MAAM,mBAAmB,GAAU,QAAQ,gBAAgB,EAAE,EAAE,UAAU,QAAQ,KAAG,OAAO,CAAC,iBAAiB,EAAE,CAErH,CAAA"}
@@ -0,0 +1,23 @@
1
+ import type { Token } from '@uniswap/sdk-core';
2
+ /**
3
+ * Sorts two tokens in ascending order by address to ensure consistent ordering.
4
+ *
5
+ * In Uniswap v2, v3, and v4, pool addresses are deterministically derived using
6
+ * `CREATE2` with a hash of the pool's initialization parameters. One critical
7
+ * part of this hash is the `token0` and `token1` addresses. To ensure uniqueness
8
+ * and prevent duplicate pools (e.g., USDC/WETH and WETH/USDC being treated as different),
9
+ * Uniswap requires that token pairs be ordered **lexicographically by address**.
10
+ *
11
+ * This method ensures that tokens are sorted according to that rule.
12
+ *
13
+ * This is required any time you:
14
+ * - Derive a pool address
15
+ * - Generate a pool ID
16
+ * - Call a function that expects a PoolKey or token pair in sorted order
17
+ *
18
+ * @param tokenA - The first token to compare
19
+ * @param tokenB - The second token to compare
20
+ * @returns A tuple `[token0, token1]` sorted by address in ascending order
21
+ */
22
+ export declare const sortTokens: (tokenA: Token, tokenB: Token) => [Token, Token];
23
+ //# sourceMappingURL=sortTokens.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"sortTokens.d.ts","sourceRoot":"","sources":["../../../src/lib/sortTokens.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,KAAK,EAAE,MAAM,mBAAmB,CAAA;AAE9C;;;;;;;;;;;;;;;;;;;GAmBG;AACH,eAAO,MAAM,UAAU,GAAI,QAAQ,KAAK,EAAE,QAAQ,KAAK,KAAG,CAAC,KAAK,EAAE,KAAK,CAEtE,CAAA"}
@@ -0,0 +1,4 @@
1
+ import { Token } from '@uniswap/sdk-core';
2
+ import type { TokenParameters } from '../types/index.ts';
3
+ export declare const tokenRegistryValueToToken: (value: TokenParameters) => Token;
4
+ //# sourceMappingURL=tokenRegistryValueToToken.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"tokenRegistryValueToToken.d.ts","sourceRoot":"","sources":["../../../src/lib/tokenRegistryValueToToken.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,KAAK,EAAE,MAAM,mBAAmB,CAAA;AAGzC,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,mBAAmB,CAAA;AAExD,eAAO,MAAM,yBAAyB,GAAI,OAAO,eAAe,KAAG,KAMlE,CAAA"}
@@ -0,0 +1,8 @@
1
+ import type { TokenParameters } from './TokenParameters.ts';
2
+ export type TokenPairPoolKey = {
3
+ fee: number;
4
+ hookAddress: string;
5
+ tickSpacing: number;
6
+ tokens: [TokenParameters, TokenParameters];
7
+ };
8
+ //# sourceMappingURL=TokenPairPoolKey.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"TokenPairPoolKey.d.ts","sourceRoot":"","sources":["../../../src/types/TokenPairPoolKey.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,sBAAsB,CAAA;AAe3D,MAAM,MAAM,gBAAgB,GAAG;IAC7B,GAAG,EAAE,MAAM,CAAA;IACX,WAAW,EAAE,MAAM,CAAA;IACnB,WAAW,EAAE,MAAM,CAAA;IACnB,MAAM,EAAE,CAAC,eAAe,EAAE,eAAe,CAAC,CAAA;CAC3C,CAAA"}
@@ -0,0 +1,36 @@
1
+ /**
2
+ * Represents the minimal metadata required to define an ERC-20 token
3
+ * in the context of Uniswap pool interactions, token registries, or
4
+ * off-chain utilities.
5
+ *
6
+ * This structure is designed to be lightweight but expressive enough
7
+ * to support pool ID generation, token sorting, and on-chain lookups.
8
+ */
9
+ export type TokenParameters = {
10
+ /**
11
+ * The Ethereum address of the token contract.
12
+ */
13
+ address: string;
14
+ /**
15
+ * The chain ID where this token is deployed.
16
+ * This enables multi-chain compatibility and avoids collisions between
17
+ * tokens with the same address on different networks (e.g. mainnet vs testnet).
18
+ */
19
+ chainId: number;
20
+ /**
21
+ * The number of decimals used by the token.
22
+ * This is required for correct price calculations and amount formatting.
23
+ */
24
+ decimals: number;
25
+ /**
26
+ * A short uppercase identifier for the token (e.g. 'USDT', 'WETH').
27
+ * Used for display, logging, and lookup convenience.
28
+ */
29
+ symbol: string;
30
+ /**
31
+ * (Optional) The full human-readable name of the token (e.g. 'Tether USD').
32
+ * Useful for UIs or token metadata enrichment.
33
+ */
34
+ name?: string;
35
+ };
36
+ //# sourceMappingURL=TokenParameters.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"TokenParameters.d.ts","sourceRoot":"","sources":["../../../src/types/TokenParameters.ts"],"names":[],"mappings":"AAAA;;;;;;;GAOG;AACH,MAAM,MAAM,eAAe,GAAG;IAC5B;;OAEG;IACH,OAAO,EAAE,MAAM,CAAA;IAEf;;;;OAIG;IACH,OAAO,EAAE,MAAM,CAAA;IAEf;;;OAGG;IACH,QAAQ,EAAE,MAAM,CAAA;IAEhB;;;OAGG;IACH,MAAM,EAAE,MAAM,CAAA;IAEd;;;OAGG;IACH,IAAI,CAAC,EAAE,MAAM,CAAA;CACd,CAAA"}
@@ -0,0 +1,3 @@
1
+ export * from './TokenPairPoolKey.ts';
2
+ export * from './TokenParameters.ts';
3
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../src/types/index.ts"],"names":[],"mappings":"AAAA,cAAc,uBAAuB,CAAA;AACrC,cAAc,sBAAsB,CAAA"}
package/package.json ADDED
@@ -0,0 +1,60 @@
1
+ {
2
+ "name": "@xyo-network/uniswap-v4-crypto-market-plugin",
3
+ "version": "3.5.2",
4
+ "description": "Typescript/Javascript Plugins for XYO Platform",
5
+ "homepage": "https://xyo.network",
6
+ "bugs": {
7
+ "url": "git+https://github.com/XYOracleNetwork/plugins/issues",
8
+ "email": "support@xyo.network"
9
+ },
10
+ "repository": {
11
+ "type": "git",
12
+ "url": "git+https://github.com/XYOracleNetwork/plugins.git"
13
+ },
14
+ "license": "LGPL-3.0-only",
15
+ "author": {
16
+ "name": "XYO Development Team",
17
+ "email": "support@xyo.network",
18
+ "url": "https://xyo.network"
19
+ },
20
+ "sideEffects": false,
21
+ "type": "module",
22
+ "exports": {
23
+ ".": {
24
+ "types": "./dist/types/index.d.ts",
25
+ "default": "./dist/neutral/index.mjs"
26
+ },
27
+ "./package.json": "./package.json"
28
+ },
29
+ "module": "dist/neutral/index.mjs",
30
+ "types": "dist/types/index.d.ts",
31
+ "dependencies": {
32
+ "@uniswap/sdk-core": "^7.7.2",
33
+ "@uniswap/v3-sdk": "^3.25.2",
34
+ "@xylabs/assert": "^4.8.7",
35
+ "@xylabs/delay": "^4.8.7",
36
+ "@xylabs/enum": "^4.8.7",
37
+ "@xylabs/promise": "^4.8.7",
38
+ "@xyo-network/abstract-witness": "^3.13.0",
39
+ "@xyo-network/module-model": "^3.13.0",
40
+ "@xyo-network/open-zeppelin-typechain": "^3.5.2",
41
+ "@xyo-network/payload-model": "^3.13.0",
42
+ "@xyo-network/payloadset-plugin": "^3.13.0",
43
+ "@xyo-network/uniswap-crypto-market-payload-plugin": "^3.5.2",
44
+ "@xyo-network/uniswap-typechain": "^3.5.2",
45
+ "@xyo-network/witness-model": "^3.13.0",
46
+ "ethers": "^6.13.6"
47
+ },
48
+ "devDependencies": {
49
+ "@xylabs/ts-scripts-yarn3": "^6.3.1",
50
+ "@xylabs/tsconfig": "^6.3.1",
51
+ "@xylabs/vitest-extended": "^4.8.7",
52
+ "@xyo-network/payload-wrapper": "^3.13.0",
53
+ "@xyo-network/witness-blockchain-abstract": "^3.13.0",
54
+ "typescript": "^5.8.3",
55
+ "vitest": "^3.1.1"
56
+ },
57
+ "publishConfig": {
58
+ "access": "public"
59
+ }
60
+ }
package/src/Config.ts ADDED
@@ -0,0 +1,9 @@
1
+ import type { UniswapV4CryptoMarketWitnessConfigSchema } from '@xyo-network/uniswap-crypto-market-payload-plugin'
2
+ import type { WitnessConfig } from '@xyo-network/witness-model'
3
+
4
+ import type { TokenPairPoolKey } from './types/index.ts'
5
+
6
+ export type UniswapV4CryptoMarketWitnessConfig = WitnessConfig<{
7
+ poolKeys?: TokenPairPoolKey[]
8
+ schema: UniswapV4CryptoMarketWitnessConfigSchema
9
+ }>
package/src/Plugin.ts ADDED
@@ -0,0 +1,16 @@
1
+ import { PayloadSetSchema } from '@xyo-network/payload-model'
2
+ import { createPayloadSetWitnessPlugin } from '@xyo-network/payloadset-plugin'
3
+ import { UniswapCryptoMarketSchema } from '@xyo-network/uniswap-crypto-market-payload-plugin'
4
+
5
+ import { UniswapV4CryptoMarketWitness } from './Witness.ts'
6
+
7
+ export const UniswapV4CryptoMarketPlugin = () =>
8
+ createPayloadSetWitnessPlugin<UniswapV4CryptoMarketWitness>(
9
+ { required: { [UniswapCryptoMarketSchema]: 1 }, schema: PayloadSetSchema },
10
+ {
11
+ witness: async (params) => {
12
+ const result = await UniswapV4CryptoMarketWitness.create(params)
13
+ return result
14
+ },
15
+ },
16
+ )
package/src/Witness.ts ADDED
@@ -0,0 +1,49 @@
1
+ import { assertEx } from '@xylabs/assert'
2
+ import { AbstractWitness } from '@xyo-network/abstract-witness'
3
+ import type { AnyConfigSchema } from '@xyo-network/module-model'
4
+ import type { Payload, Schema } from '@xyo-network/payload-model'
5
+ import type { UniswapCryptoMarketPayload } from '@xyo-network/uniswap-crypto-market-payload-plugin'
6
+ import { UniswapCryptoMarketSchema, UniswapV4CryptoMarketWitnessConfigSchema } from '@xyo-network/uniswap-crypto-market-payload-plugin'
7
+ import type { WitnessParams } from '@xyo-network/witness-model'
8
+ import type { Provider } from 'ethers'
9
+
10
+ import type { UniswapV4CryptoMarketWitnessConfig } from './Config.ts'
11
+ import { pricesFromUniswapV4, UniswapV4DefaultPools } from './lib/index.ts'
12
+ import type { TokenPairPoolKey } from './types/index.ts'
13
+
14
+ export type UniswapV4CryptoMarketWitnessParams = WitnessParams<
15
+ AnyConfigSchema<UniswapV4CryptoMarketWitnessConfig>,
16
+ {
17
+ provider?: Provider
18
+ }
19
+ >
20
+
21
+ export class UniswapV4CryptoMarketWitness<
22
+ TParams extends UniswapV4CryptoMarketWitnessParams = UniswapV4CryptoMarketWitnessParams,
23
+ > extends AbstractWitness<TParams> {
24
+ static override readonly configSchemas: Schema[] = [...super.configSchemas, UniswapV4CryptoMarketWitnessConfigSchema]
25
+ static override readonly defaultConfigSchema: Schema = UniswapV4CryptoMarketWitnessConfigSchema
26
+
27
+ protected get pools(): TokenPairPoolKey[] {
28
+ return this.config?.poolKeys ?? Object.values(UniswapV4DefaultPools)
29
+ }
30
+
31
+ protected get provider() {
32
+ return assertEx(this.params.provider, () => 'Provider Required')
33
+ }
34
+
35
+ protected override async observeHandler(): Promise<Payload[]> {
36
+ await this.started('throw')
37
+ const pairs = await pricesFromUniswapV4(this.pools, this.provider)
38
+ const timestamp = Date.now()
39
+ const payload: UniswapCryptoMarketPayload = {
40
+ pairs, schema: UniswapCryptoMarketSchema, timestamp,
41
+ }
42
+ return [payload]
43
+ }
44
+
45
+ protected override async startHandler() {
46
+ await super.startHandler()
47
+ return true
48
+ }
49
+ }
package/src/index.ts ADDED
@@ -0,0 +1,4 @@
1
+ export * from './Config.ts'
2
+ export * from './lib/index.ts'
3
+ export { UniswapV4CryptoMarketPlugin as default, UniswapV4CryptoMarketPlugin } from './Plugin.ts'
4
+ export * from './Witness.ts'
@@ -0,0 +1,11 @@
1
+ // https://docs.uniswap.org/contracts/v4/deployments#mainnet-deployments
2
+ export const UniswapV4ContractAddresses = {
3
+ Ethereum: {
4
+ PoolManager: '0x000000000004444c5dc75cB358380D2e3dE08A90',
5
+ PositionDescriptor: '0xd1428ba554f4c8450b763a0b2040a4935c63f06c',
6
+ PositionManager: '0xbd216513d74c8cf14cf4747e6aaa6420ff64ee9e',
7
+ Quoter: '0x52f0e24d1c21c8a0cb1e5a5dd6198556bd9e1203',
8
+ StateView: '0x7ffe42c4a5deea5b0fec41c94c136cf115597227',
9
+ UniversalRouter: '0x66a9893cc07d91d95644aedd05d03f95e1dba8af',
10
+ },
11
+ }
@@ -0,0 +1,27 @@
1
+ import { ZeroAddress } from 'ethers'
2
+
3
+ import type { TokenPairPoolKey, TokenParameters } from '../types/index.ts'
4
+
5
+ export const TokenRegistry: Record<string, TokenParameters> = {
6
+ USDT: {
7
+ address: '0xdac17f958d2ee523a2206206994597c13d831ec7',
8
+ chainId: 1,
9
+ decimals: 6,
10
+ symbol: 'USDT',
11
+ },
12
+ XYO: {
13
+ address: '0x55296f69f40ea6d20e478533c15a6b08b654e758',
14
+ chainId: 1,
15
+ decimals: 18,
16
+ symbol: 'XYO',
17
+ },
18
+ } as const
19
+
20
+ export const UniswapV4DefaultPools: Record<string, TokenPairPoolKey> = {
21
+ 'XYO:USDT': {
22
+ fee: 3000,
23
+ hookAddress: ZeroAddress,
24
+ tickSpacing: 60,
25
+ tokens: [TokenRegistry.XYO, TokenRegistry.USDT],
26
+ },
27
+ } as const
@@ -0,0 +1,7 @@
1
+ export interface UniswapV4TokenIdentifier {
2
+ chainId: number
3
+ address: string
4
+ decimals: number
5
+ symbol?: string
6
+ name?: string
7
+ }
@@ -0,0 +1,35 @@
1
+ import type { Token } from '@uniswap/sdk-core'
2
+ import { IStateView__factory } from '@xyo-network/uniswap-typechain/v4-periphery'
3
+ import { ZeroAddress } from 'ethers/constants'
4
+ import type { Provider } from 'ethers/providers'
5
+
6
+ import { getPoolId } from './getPoolId.ts'
7
+ import { getPriceFromSqrtX96 } from './getPriceFromSqrtX96.ts'
8
+ import { sortTokens } from './sortTokens.ts'
9
+ import { UniswapV4ContractAddresses } from './UniswapV4ContractAddresses.ts'
10
+
11
+ /**
12
+ * Returns the price of the token pair in the Uniswap V4 pool.
13
+ * @param tokenA The first token in the pair.
14
+ * @param tokenB The second token in the pair.
15
+ * @param fee The fee tier for the pool.
16
+ * @param hookAddress The address of the hook contract. Default is ZeroAddress.
17
+ * @param provider The EVM provider to use for the transaction.
18
+ * @returns The price of the token pair.
19
+ */
20
+ export const getExchangeRate = async (
21
+ tokenA: Token,
22
+ tokenB: Token,
23
+ fee: number,
24
+ hookAddress: string | undefined,
25
+ provider: Provider,
26
+ ): Promise<number> => {
27
+ const hooks = hookAddress || ZeroAddress
28
+ const stateView = IStateView__factory.connect(UniswapV4ContractAddresses.Ethereum.StateView, provider)
29
+ const [token0, token1] = sortTokens(tokenA, tokenB)
30
+ const poolId: string = getPoolId(token0, token1, fee, 60, hooks)
31
+ if (poolId === ZeroAddress) throw new Error('Invalid poolId')
32
+ const response = await stateView.getSlot0(poolId)
33
+ const price = getPriceFromSqrtX96(response.sqrtPriceX96, token1.decimals, token0.decimals)
34
+ return price
35
+ }
@@ -0,0 +1,28 @@
1
+ import type { Token } from '@uniswap/sdk-core'
2
+ import { AbiCoder } from 'ethers/abi'
3
+ import { ZeroAddress } from 'ethers/constants'
4
+ import { keccak256 } from 'ethers/crypto'
5
+
6
+ import { sortTokens } from './sortTokens.ts'
7
+
8
+ /**
9
+ * Computes the pool address for a given pair of tokens, fee, tick spacing, and hooks which
10
+ * is used to identify the pool on the Uniswap V4 protocol.
11
+ * @param tokenA - The first token in the pair.
12
+ * @param tokenB - The second token in the pair.
13
+ * @param fee - The fee tier for the pool.
14
+ * @param tickSpacing - The tick spacing for the pool.
15
+ * @param hooks - The hooks associated with the pool.
16
+ * @returns The computed pool address as a string.
17
+ */
18
+ export const getPoolId = (tokenA: Token, tokenB: Token, fee: number, tickSpacing: number, hooks: string): string => {
19
+ const [currency0, currency1] = sortTokens(tokenA, tokenB)
20
+ const currency0Addr = currency0.isNative ? ZeroAddress : currency0.wrapped.address
21
+ const currency1Addr = currency1.isNative ? ZeroAddress : currency1.wrapped.address
22
+ return keccak256(
23
+ AbiCoder.defaultAbiCoder().encode(
24
+ ['address', 'address', 'uint24', 'int24', 'address'],
25
+ [currency0Addr, currency1Addr, fee, tickSpacing, hooks],
26
+ ),
27
+ )
28
+ }
@@ -0,0 +1,26 @@
1
+ /**
2
+ * Calculates the price from the square root price in Q96 format.
3
+ * @param sqrtPriceX96 The square root price in Q96 format.
4
+ * @param decimalsA The number of decimals for the first token.
5
+ * @param decimalsB The number of decimals for the second token.
6
+ * @returns The price as a number.
7
+ */
8
+ export const getPriceFromSqrtX96 = (sqrtPriceX96: bigint, decimalsA: number, decimalsB: number): number => {
9
+ const Q96 = 2n ** 96n
10
+
11
+ // Scale to avoid floating point math by using a 1e18 factor
12
+ const numerator = sqrtPriceX96 * sqrtPriceX96 * 10n ** 18n
13
+ const denominator = Q96 * Q96
14
+
15
+ let price = numerator / denominator
16
+
17
+ // Adjust for decimal differences
18
+ const decimalAdjustment = decimalsB - decimalsA
19
+ if (decimalAdjustment > 0) {
20
+ price *= 10n ** BigInt(decimalAdjustment)
21
+ } else if (decimalAdjustment < 0) {
22
+ price /= 10n ** BigInt(-decimalAdjustment)
23
+ }
24
+
25
+ return Number(price) / 1e18
26
+ }
@@ -0,0 +1,4 @@
1
+ export * from './priceFromUniswapV4.ts'
2
+ export * from './pricesFromUniswapV4.ts'
3
+ export * from './tokenRegistryValueToToken.ts'
4
+ export * from './UniswapV4DefaultPools.ts'
@@ -0,0 +1,28 @@
1
+ import type { UniswapCryptoPair, UniswapCryptoToken } from '@xyo-network/uniswap-crypto-market-payload-plugin'
2
+ import type { Provider } from 'ethers'
3
+ import { ZeroAddress } from 'ethers'
4
+
5
+ import type { TokenPairPoolKey } from '../types/index.ts'
6
+ import { getExchangeRate } from './getExchangeRate.ts'
7
+ import { tokenRegistryValueToToken } from './tokenRegistryValueToToken.ts'
8
+
9
+ export const priceFromUniswapV4 = async (poolId: TokenPairPoolKey, provider: Provider): Promise<UniswapCryptoPair> => {
10
+ const {
11
+ tokens, fee, hookAddress = ZeroAddress,
12
+ } = poolId
13
+ const tokenA = tokenRegistryValueToToken(tokens[0])
14
+ const tokenB = tokenRegistryValueToToken(tokens[1])
15
+ const rate = await getExchangeRate(tokenA, tokenB, fee, hookAddress, provider)
16
+ const token0: UniswapCryptoToken = {
17
+ address: tokenA.address,
18
+ symbol: tokenA.symbol || '',
19
+ value: Math.max(rate, 0),
20
+ }
21
+ const token1: UniswapCryptoToken = {
22
+ address: tokenB.address,
23
+ symbol: tokenB.symbol || '',
24
+ value: rate > 0 ? Number((1 / rate).toPrecision(6)) : 0,
25
+ }
26
+ const pair: UniswapCryptoPair = { tokens: [token0, token1] }
27
+ return pair
28
+ }
@@ -0,0 +1,9 @@
1
+ import type { UniswapCryptoPair } from '@xyo-network/uniswap-crypto-market-payload-plugin'
2
+ import type { Provider } from 'ethers'
3
+
4
+ import type { TokenPairPoolKey } from '../types/index.ts'
5
+ import { priceFromUniswapV4 } from './priceFromUniswapV4.ts'
6
+
7
+ export const pricesFromUniswapV4 = async (poolId: TokenPairPoolKey[], provider: Provider): Promise<UniswapCryptoPair[]> => {
8
+ return await Promise.all(poolId.map(pool => priceFromUniswapV4(pool, provider)))
9
+ }
@@ -0,0 +1,25 @@
1
+ import type { Token } from '@uniswap/sdk-core'
2
+
3
+ /**
4
+ * Sorts two tokens in ascending order by address to ensure consistent ordering.
5
+ *
6
+ * In Uniswap v2, v3, and v4, pool addresses are deterministically derived using
7
+ * `CREATE2` with a hash of the pool's initialization parameters. One critical
8
+ * part of this hash is the `token0` and `token1` addresses. To ensure uniqueness
9
+ * and prevent duplicate pools (e.g., USDC/WETH and WETH/USDC being treated as different),
10
+ * Uniswap requires that token pairs be ordered **lexicographically by address**.
11
+ *
12
+ * This method ensures that tokens are sorted according to that rule.
13
+ *
14
+ * This is required any time you:
15
+ * - Derive a pool address
16
+ * - Generate a pool ID
17
+ * - Call a function that expects a PoolKey or token pair in sorted order
18
+ *
19
+ * @param tokenA - The first token to compare
20
+ * @param tokenB - The second token to compare
21
+ * @returns A tuple `[token0, token1]` sorted by address in ascending order
22
+ */
23
+ export const sortTokens = (tokenA: Token, tokenB: Token): [Token, Token] => {
24
+ return tokenA.sortsBefore(tokenB) ? [tokenA, tokenB] : [tokenB, tokenA]
25
+ }
@@ -0,0 +1,12 @@
1
+ import { Token } from '@uniswap/sdk-core'
2
+ import { getAddress } from 'ethers/address'
3
+
4
+ import type { TokenParameters } from '../types/index.ts'
5
+
6
+ export const tokenRegistryValueToToken = (value: TokenParameters): Token => {
7
+ const {
8
+ address, chainId, decimals, symbol, name,
9
+ } = value
10
+ const normalizedAddress = getAddress(address.toLowerCase())
11
+ return new Token(chainId, normalizedAddress, decimals, symbol, name)
12
+ }
@@ -0,0 +1,21 @@
1
+ import type { TokenParameters } from './TokenParameters.ts'
2
+
3
+ // NOTE: We could import this type from @uniswap/v4-core, but
4
+ // they are currently hardcoded the ethers v5 which
5
+ // causes many issues since we are using ethers v6. Moreover,
6
+ // we would have to hit the ERC20 contract to get the decimals
7
+ // and name of the token, which is not ideal as it never changes.
8
+ // export type PoolKey = {
9
+ // currency0: string
10
+ // currency1: string
11
+ // fee: number
12
+ // tickSpacing: number
13
+ // hooks: string
14
+ // }
15
+
16
+ export type TokenPairPoolKey = {
17
+ fee: number
18
+ hookAddress: string
19
+ tickSpacing: number
20
+ tokens: [TokenParameters, TokenParameters]
21
+ }
@@ -0,0 +1,39 @@
1
+ /**
2
+ * Represents the minimal metadata required to define an ERC-20 token
3
+ * in the context of Uniswap pool interactions, token registries, or
4
+ * off-chain utilities.
5
+ *
6
+ * This structure is designed to be lightweight but expressive enough
7
+ * to support pool ID generation, token sorting, and on-chain lookups.
8
+ */
9
+ export type TokenParameters = {
10
+ /**
11
+ * The Ethereum address of the token contract.
12
+ */
13
+ address: string
14
+
15
+ /**
16
+ * The chain ID where this token is deployed.
17
+ * This enables multi-chain compatibility and avoids collisions between
18
+ * tokens with the same address on different networks (e.g. mainnet vs testnet).
19
+ */
20
+ chainId: number
21
+
22
+ /**
23
+ * The number of decimals used by the token.
24
+ * This is required for correct price calculations and amount formatting.
25
+ */
26
+ decimals: number
27
+
28
+ /**
29
+ * A short uppercase identifier for the token (e.g. 'USDT', 'WETH').
30
+ * Used for display, logging, and lookup convenience.
31
+ */
32
+ symbol: string
33
+
34
+ /**
35
+ * (Optional) The full human-readable name of the token (e.g. 'Tether USD').
36
+ * Useful for UIs or token metadata enrichment.
37
+ */
38
+ name?: string
39
+ }
@@ -0,0 +1,2 @@
1
+ export * from './TokenPairPoolKey.ts'
2
+ export * from './TokenParameters.ts'
package/typedoc.json ADDED
@@ -0,0 +1,5 @@
1
+ {
2
+ "$schema": "https://typedoc.org/schema.json",
3
+ "entryPoints": ["./src/index.ts"],
4
+ "tsconfig": "./tsconfig.typedoc.json"
5
+ }
package/xy.config.ts ADDED
@@ -0,0 +1,10 @@
1
+ import type { XyTsupConfig } from '@xylabs/ts-scripts-yarn3'
2
+ const config: XyTsupConfig = {
3
+ compile: {
4
+ browser: {},
5
+ node: {},
6
+ neutral: { src: true },
7
+ },
8
+ }
9
+
10
+ export default config