@bitflowlabs/core-sdk 2.3.0 → 2.3.2-beta.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.
@@ -1,24 +0,0 @@
1
- import { stringifyWithBigInt } from "./callReadOnlyHelper";
2
- import { convertValue } from "./convertValuesHelper";
3
-
4
- export const constructFunctionArgs = (
5
- parameters: any,
6
- functionArgsDefinition: any[]
7
- ) => {
8
- return functionArgsDefinition.map((arg) => {
9
- const value = parameters[arg.name];
10
-
11
- if (value === undefined || value === null) {
12
- console.warn(`Value for ${arg.name} is ${value}`);
13
- }
14
-
15
- try {
16
- const convertedValue = convertValue(value, arg.type);
17
-
18
- return convertedValue;
19
- } catch (error) {
20
- console.error(`Error converting value for ${arg.name}:`, error);
21
- throw error;
22
- }
23
- });
24
- };
@@ -1,220 +0,0 @@
1
- import {
2
- boolCV,
3
- bufferCV,
4
- ClarityValue,
5
- contractPrincipalCV,
6
- intCV,
7
- listCV,
8
- noneCV,
9
- principalCV,
10
- responseErrorCV,
11
- responseOkCV,
12
- someCV,
13
- standardPrincipalCV,
14
- stringAsciiCV,
15
- stringUtf8CV,
16
- tupleCV,
17
- uintCV,
18
- } from "@stacks/transactions";
19
-
20
- export const convertValue = (value: any, type: any): ClarityValue => {
21
- if (value === null || value === undefined) {
22
- console.warn(
23
- `Received null, undefined, or invalid value for type ${JSON.stringify(
24
- type
25
- )}. Using default value.`
26
- );
27
- return getDefaultValue(type);
28
- }
29
-
30
- if (typeof type === "object") {
31
- return handleObjectType(value, type);
32
- }
33
-
34
- switch (type) {
35
- case "uint128":
36
- case "uint":
37
- return handleUintType(value);
38
- case "int128":
39
- case "int":
40
- return handleIntType(value);
41
- case "bool":
42
- return handleBoolType(value);
43
- case "principal":
44
- return handlePrincipalType(value);
45
- case "trait_reference":
46
- return handleTraitReferenceType(value);
47
- case "optional":
48
- return handleOptionalType(value);
49
- case "response":
50
- return handleResponseType(value);
51
- case "string-ascii":
52
- return stringAsciiCV(value);
53
- case "string-utf8":
54
- return stringUtf8CV(value);
55
- case "list":
56
- return handleListType(value);
57
- case "buffer":
58
- return bufferCV(Buffer.from(value));
59
- default:
60
- if (typeof value === "object") {
61
- return handleTupleType(value);
62
- }
63
- throw new Error(`Unsupported argument type: ${type}`);
64
- }
65
- };
66
-
67
- const getDefaultValue = (type: any): ClarityValue => {
68
- if (typeof type === "object") {
69
- if (
70
- type.type === "uint128" ||
71
- (type.optional && type.optional === "uint128") ||
72
- (type.optional && type.optional === "principal")
73
- ) {
74
- return noneCV();
75
- }
76
- if (type.tuple) {
77
- return tupleCV({});
78
- }
79
- if (type.list) {
80
- return listCV([]);
81
- }
82
- }
83
- switch (type) {
84
- case "uint128":
85
- case "uint":
86
- return uintCV(0);
87
- case "int128":
88
- case "int":
89
- return intCV(0);
90
- case "bool":
91
- return boolCV(false);
92
- case "optional":
93
- case "optional(uint128)":
94
- case "optional(principal)":
95
- return noneCV();
96
- case "string-ascii":
97
- case "string-utf8":
98
- return stringAsciiCV("");
99
- case "buffer":
100
- return bufferCV(Buffer.alloc(0));
101
- case "list":
102
- return listCV([]);
103
- default:
104
- throw new Error(
105
- `Cannot provide default value for type: ${JSON.stringify(type)}`
106
- );
107
- }
108
- };
109
-
110
- const handleObjectType = (value: any, type: any): ClarityValue => {
111
- if (type.type === "uint128") {
112
- return uintCV(value);
113
- }
114
- if (type.optional === "uint128") {
115
- return someCV(uintCV(value));
116
- }
117
- if (type.optional === "principal") {
118
- return someCV(principalCV(value));
119
- }
120
- if (type.tuple) {
121
- return handleTupleType(value, type.tuple);
122
- }
123
- if (type.list) {
124
- return handleListType(value, type.list.type);
125
- }
126
- throw new Error(`Unsupported object-based type: ${JSON.stringify(type)}`);
127
- };
128
-
129
- const handleUintType = (value: any): ClarityValue => {
130
- if (typeof value === "number" || typeof value === "bigint") {
131
- return uintCV(value);
132
- } else if (typeof value === "string") {
133
- if (/^\d+$/.test(value)) {
134
- return uintCV(value);
135
- } else if (/^0x[0-9A-Fa-f]+$/.test(value)) {
136
- return uintCV(BigInt(value));
137
- }
138
- } else if (value instanceof Uint8Array) {
139
- return uintCV(value);
140
- }
141
- throw new Error(`Invalid uint128 value: ${value} (type: ${typeof value})`);
142
- };
143
-
144
- const handleIntType = (value: any): ClarityValue => {
145
- if (
146
- typeof value === "number" ||
147
- typeof value === "bigint" ||
148
- (typeof value === "string" && /^-?\d+$/.test(value))
149
- ) {
150
- return intCV(value);
151
- }
152
- throw new Error(`Invalid int128 value: ${value} (type: ${typeof value})`);
153
- };
154
-
155
- const handleBoolType = (value: any): ClarityValue => {
156
- if (typeof value === "boolean") {
157
- return boolCV(value);
158
- }
159
- throw new Error(`Invalid boolean value: ${value} (type: ${typeof value})`);
160
- };
161
-
162
- const handlePrincipalType = (value: string): ClarityValue => {
163
- if (value.includes(".")) {
164
- const [addr, name] = value.split(".");
165
- return contractPrincipalCV(addr, name);
166
- } else {
167
- return standardPrincipalCV(value);
168
- }
169
- };
170
-
171
- const handleTraitReferenceType = (value: string): ClarityValue => {
172
- const [addr, name] = value.split(".");
173
- return contractPrincipalCV(addr, name);
174
- };
175
-
176
- const handleOptionalType = (value: any): ClarityValue => {
177
- return value !== null && value !== undefined
178
- ? someCV(convertValue(value, "uint128"))
179
- : noneCV();
180
- };
181
-
182
- const handleResponseType = (value: any): ClarityValue => {
183
- if (
184
- value &&
185
- typeof value === "object" &&
186
- ("ok" in value || "error" in value)
187
- ) {
188
- return "ok" in value
189
- ? responseOkCV(convertValue(value.ok, typeof value.ok))
190
- : responseErrorCV(convertValue(value.error, typeof value.error));
191
- }
192
- throw new Error(`Invalid response value: ${JSON.stringify(value)}`);
193
- };
194
-
195
- const handleListType = (value: any[], itemType?: any): ClarityValue => {
196
- if (Array.isArray(value)) {
197
- return listCV(
198
- value.map((item) => convertValue(item, itemType || typeof item))
199
- );
200
- }
201
- throw new Error(`Invalid list value: ${JSON.stringify(value)}`);
202
- };
203
-
204
- const handleTupleType = (value: any, tupleTypes?: any[]): ClarityValue => {
205
- const tupleValues: { [key: string]: ClarityValue } = {};
206
- if (tupleTypes) {
207
- tupleTypes.forEach((item: { name: string; type: any }) => {
208
- if (value && value[item.name] !== undefined) {
209
- tupleValues[item.name] = convertValue(value[item.name], item.type);
210
- } else {
211
- tupleValues[item.name] = getDefaultValue(item.type);
212
- }
213
- });
214
- } else {
215
- for (const [key, val] of Object.entries(value)) {
216
- tupleValues[key] = convertValue(val, typeof val);
217
- }
218
- }
219
- return tupleCV(tupleValues);
220
- };
@@ -1,27 +0,0 @@
1
- import { configs } from "../config";
2
-
3
- const getReadonlyHeaders = () => ({
4
- Accept: "application/json",
5
- "Content-Type": "application/json",
6
- ...(configs.READONLY_CALL_API_KEY && { "x-api-key": configs.READONLY_CALL_API_KEY }),
7
- });
8
-
9
- export const fetchContractInterface = async (
10
- contractDeployer: string,
11
- contractName: string
12
- ): Promise<any> => {
13
- const url = `${configs.READONLY_CALL_API_HOST}/v2/contracts/interface/${contractDeployer}/${contractName}`;
14
-
15
- try {
16
- const response = await fetch(url, {
17
- headers: getReadonlyHeaders(),
18
- });
19
- if (!response.ok) {
20
- throw new Error(`HTTP error! status: ${response.status}`);
21
- }
22
- return await response.json();
23
- } catch (error) {
24
- console.error(`Error fetching contract interface from ${url}:`, error);
25
- throw error;
26
- }
27
- };
@@ -1,88 +0,0 @@
1
- import { configs } from "../config";
2
- import { Token, LayerOneAsset, PriceData } from "../types";
3
-
4
- const getBitflowHeaders = () => ({
5
- Accept: "application/json",
6
- "Content-Type": "application/json",
7
- ...(configs.BITFLOW_API_KEY && { "x-api-key": configs.BITFLOW_API_KEY }),
8
- });
9
-
10
- export const fetchAllTokensFromAPI = async (): Promise<Token[]> => {
11
- const url = `${configs.BITFLOW_API_HOST}/getAllTokensAndPools`;
12
- try {
13
- const response = await fetch(url, {
14
- headers: getBitflowHeaders(),
15
- });
16
- if (!response.ok) {
17
- throw new Error(`HTTP error! status: ${response.status}`);
18
- }
19
- const data = await response.json();
20
- if (!data.tokens || !Array.isArray(data.tokens)) {
21
- console.error("Unexpected data structure returned by API:", data);
22
- throw new Error("Unexpected data structure returned by API");
23
- }
24
-
25
- return data.tokens.map((token: any) => {
26
- // Basic token properties
27
- const mappedToken: Token = {
28
- icon: token.icon || "",
29
- name: token.name || "",
30
- status: token.status || "",
31
- symbol: token.symbol || "",
32
- "token-id": token["token-id"] || "",
33
- tokenId: token["token-id"] || "", // Duplicate for compatibility
34
- tokenContract: token.tokenContract || null,
35
- tokenDecimals: token.tokenDecimals || 0,
36
- tokenName: token.tokenName || null,
37
- wrapTokens: null,
38
- base: token.base || "",
39
- type: token.type || "",
40
- isKeeperToken: token.isKeeperToken || false,
41
- bridge: token.bridge || "FALSE",
42
- layerOneAsset: token.layerOneAsset || null,
43
- priceData: token.priceData || {
44
- "1h_change": null,
45
- "1yr_change": null,
46
- "24h_change": null,
47
- "30d_change": null,
48
- "7d_change": null,
49
- last_price: null,
50
- last_updated: null,
51
- },
52
- };
53
-
54
- // Handle wrapTokens if present
55
- if (token.wrapTokens) {
56
- mappedToken.wrapTokens = Object.keys(token.wrapTokens).reduce(
57
- (acc: any, key: string) => {
58
- acc[key] = {
59
- tokenContract: token.wrapTokens[key].tokenContract,
60
- tokenDecimals: token.wrapTokens[key].tokenDecimals,
61
- tokenName: token.wrapTokens[key].tokenName || null,
62
- };
63
- return acc;
64
- },
65
- {}
66
- );
67
- }
68
-
69
- // Handle layerOneAsset if present
70
- if (token.layerOneAsset && Object.keys(token.layerOneAsset).length > 0) {
71
- mappedToken.layerOneAsset = {
72
- address: token.layerOneAsset.address || "",
73
- divisibility: token.layerOneAsset.divisibility || 0,
74
- icon: token.layerOneAsset.icon || "",
75
- isBitcoin: token.layerOneAsset.isBitcoin || false,
76
- runeid: token.layerOneAsset.runeid || "",
77
- spacedRune: token.layerOneAsset.spacedRune || "",
78
- symbol: token.layerOneAsset.symbol || null,
79
- };
80
- }
81
-
82
- return mappedToken;
83
- });
84
- } catch (error) {
85
- console.error(`Error fetching data from ${url}:`, error);
86
- throw error;
87
- }
88
- };
@@ -1,39 +0,0 @@
1
- import { configs } from "../config";
2
- import { SwapOptions } from "../types";
3
-
4
- const getBitflowHeaders = () => ({
5
- Accept: "application/json",
6
- "Content-Type": "application/json",
7
- ...(configs.BITFLOW_API_KEY && { "x-api-key": configs.BITFLOW_API_KEY }),
8
- });
9
-
10
- export const fetchPossibleSwapsFromAPI = async (
11
- tokenX: string,
12
- page?: "KEEPER"
13
- ): Promise<SwapOptions> => {
14
- const queryParams = new URLSearchParams({
15
- tokenX: tokenX,
16
- depth: "4",
17
- });
18
-
19
- if (page) {
20
- queryParams.append("page", page);
21
- }
22
-
23
- const url = `${
24
- configs.BITFLOW_API_HOST
25
- }/getAllRoutes?${queryParams.toString()}`;
26
-
27
- try {
28
- const response = await fetch(url, {
29
- headers: getBitflowHeaders(),
30
- });
31
- if (!response.ok) {
32
- throw new Error(`HTTP error! status: ${response.status}`);
33
- }
34
- return await response.json();
35
- } catch (error) {
36
- console.error(`Error fetching possible swaps from ${url}:`, error);
37
- throw error;
38
- }
39
- };
@@ -1,20 +0,0 @@
1
- import { fetchContractInterface } from "./fetchContractInterfaceHelper";
2
- import { getFunctionArguments } from "./getFunctionArgs";
3
-
4
- export const getContractInterfaceAndFunction = async (
5
- contractDeployer: string,
6
- contractName: string,
7
- functionName: string
8
- ) => {
9
- const contractInterface = await fetchContractInterface(
10
- contractDeployer,
11
- contractName
12
- );
13
-
14
- const functionArgs = getFunctionArguments(contractInterface, functionName);
15
-
16
- return {
17
- contractInterface,
18
- functionArgs,
19
- };
20
- };
@@ -1,12 +0,0 @@
1
- export const getFunctionArguments = (
2
- contractInterface: any,
3
- functionName: string
4
- ) => {
5
- const func = contractInterface.functions.find(
6
- (f: any) => f.name === functionName
7
- );
8
- if (!func) {
9
- throw new Error(`Function ${functionName} not found in contract interface`);
10
- }
11
- return func.args;
12
- };
@@ -1,33 +0,0 @@
1
- import { SwapContext, Token } from "../types";
2
-
3
- export const getTokenDecimals = (
4
- tokenId: string,
5
- context: SwapContext
6
- ): { tokenContract: string; tokenDecimals: number }[] => {
7
- const decimals: { tokenContract: string; tokenDecimals: number }[] = [];
8
-
9
- const token = context.availableTokens.find((t) => t.tokenId === tokenId);
10
-
11
- if (!token) {
12
- throw new Error(`Token with id ${tokenId} not found`);
13
- }
14
-
15
- if (token.tokenContract) {
16
- decimals.push({
17
- tokenContract: token.tokenContract,
18
- tokenDecimals: token.tokenDecimals,
19
- });
20
- }
21
-
22
- if (token.wrapTokens) {
23
- for (const wrapTokenKey in token.wrapTokens) {
24
- const wrapToken = token.wrapTokens[wrapTokenKey];
25
- decimals.push({
26
- tokenContract: wrapToken.tokenContract,
27
- tokenDecimals: wrapToken.tokenDecimals,
28
- });
29
- }
30
- }
31
-
32
- return decimals;
33
- };
@@ -1,26 +0,0 @@
1
- import { SwapContext } from "../types";
2
-
3
- export const getTokenName = (
4
- tokenContract: string,
5
- context: SwapContext
6
- ): string => {
7
- for (const token of context.availableTokens) {
8
- if (
9
- token.tokenContract &&
10
- token.tokenContract.toLowerCase() === tokenContract.toLowerCase()
11
- ) {
12
- return token.tokenName || token.name;
13
- }
14
- if (token.wrapTokens) {
15
- for (const wrapTokenKey in token.wrapTokens) {
16
- const wrapToken = token.wrapTokens[wrapTokenKey];
17
- if (
18
- wrapToken.tokenContract.toLowerCase() === tokenContract.toLowerCase()
19
- ) {
20
- return wrapToken.tokenName || token.name;
21
- }
22
- }
23
- }
24
- }
25
- throw new Error(`Token contract ${tokenContract} not found`);
26
- };
@@ -1,84 +0,0 @@
1
- export const handleResult = (
2
- result: any
3
- ): { rawResult: any; convertedResult: any } => {
4
- if (result === null || result === undefined) {
5
- return { rawResult: null, convertedResult: null };
6
- }
7
-
8
- let rawResult: any;
9
- let convertedResult: any;
10
-
11
- // Check if the result has a 'data' property and use it if present
12
- const value = result.data !== undefined ? result.data : result.value;
13
- switch (result.type) {
14
- case "int":
15
- rawResult = BigInt(result.value);
16
- convertedResult = Number(rawResult);
17
- break;
18
- case "uint":
19
- rawResult = BigInt(result.value);
20
- convertedResult = Number(rawResult);
21
- break;
22
- case "buffer":
23
- rawResult = Buffer.from(result.value);
24
- convertedResult = rawResult.toString("hex");
25
- break;
26
- case "true":
27
- rawResult = true;
28
- convertedResult = true;
29
- break;
30
- case "false":
31
- rawResult = false;
32
- convertedResult = false;
33
- break;
34
- case "address":
35
- rawResult = result.value;
36
- convertedResult = result.value;
37
- break;
38
- case "contract":
39
- rawResult = `${result.value.address}.${result.value.contractName}`;
40
- convertedResult = rawResult;
41
- break;
42
- case "ok":
43
- return handleResult(result.value);
44
- case "err":
45
- return handleResult(result.value);
46
- case "none":
47
- rawResult = null;
48
- convertedResult = null;
49
- break;
50
- case "some":
51
- return handleResult(result.value);
52
- case "list":
53
- rawResult = result.value.map((item: any) => handleResult(item).rawResult);
54
- convertedResult = result.value.map(
55
- (item: any) => handleResult(item).convertedResult
56
- );
57
- break;
58
- case "tuple":
59
- if (typeof value !== "object" || value === null) {
60
- console.error("Tuple value is not an object:", value);
61
- return { rawResult: null, convertedResult: null };
62
- }
63
- const sortedKeys = Object.keys(value).sort((a, b) => b.localeCompare(a));
64
-
65
- if (sortedKeys.length === 0) {
66
- return { rawResult: null, convertedResult: null };
67
- }
68
- const lastKey = sortedKeys[0];
69
-
70
- return handleResult(value[lastKey]);
71
- case "ascii":
72
- rawResult = result.value;
73
- convertedResult = result.value;
74
- break;
75
- case "utf8":
76
- rawResult = result.value;
77
- convertedResult = result.value;
78
- break;
79
- default:
80
- throw new Error(`Unexpected result type: ${result.type}`);
81
- }
82
-
83
- return { rawResult, convertedResult };
84
- };