@ab-org/predicate-market-sdk 0.1.1 → 1.0.1

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 (91) hide show
  1. package/dist/index.d.ts +672 -22
  2. package/dist/index.js +4700 -23
  3. package/package.json +6 -5
  4. package/dist/auth/autoReconnect.d.ts +0 -11
  5. package/dist/auth/autoReconnect.js +0 -36
  6. package/dist/auth/bundledConfig.d.ts +0 -2
  7. package/dist/auth/bundledConfig.js +0 -19
  8. package/dist/auth/config.d.ts +0 -29
  9. package/dist/auth/config.js +0 -53
  10. package/dist/auth/google.d.ts +0 -43
  11. package/dist/auth/google.js +0 -147
  12. package/dist/auth/oidcRelay.d.ts +0 -11
  13. package/dist/auth/oidcRelay.js +0 -107
  14. package/dist/auth/twitter.d.ts +0 -7
  15. package/dist/auth/twitter.js +0 -94
  16. package/dist/auth/walletAccount.d.ts +0 -20
  17. package/dist/auth/walletAccount.js +0 -267
  18. package/dist/constants/chains.d.ts +0 -2
  19. package/dist/constants/chains.js +0 -3
  20. package/dist/modules/api.d.ts +0 -149
  21. package/dist/modules/api.js +0 -95
  22. package/dist/modules/balanceQuery.d.ts +0 -27
  23. package/dist/modules/balanceQuery.js +0 -60
  24. package/dist/modules/deposit.d.ts +0 -31
  25. package/dist/modules/deposit.js +0 -58
  26. package/dist/modules/marketData.d.ts +0 -8
  27. package/dist/modules/marketData.js +0 -107
  28. package/dist/modules/withdraw.d.ts +0 -31
  29. package/dist/modules/withdraw.js +0 -61
  30. package/dist/modules/withdrawDirect.d.ts +0 -14
  31. package/dist/modules/withdrawDirect.js +0 -33
  32. package/dist/modules/withdrawExecutor.d.ts +0 -56
  33. package/dist/modules/withdrawExecutor.js +0 -210
  34. package/dist/policyAdapter.d.ts +0 -11
  35. package/dist/policyAdapter.js +0 -38
  36. package/dist/types.d.ts +0 -62
  37. package/dist/types.js +0 -1
  38. package/dist/ui/DepositModal.d.ts +0 -36
  39. package/dist/ui/DepositModal.js +0 -354
  40. package/dist/ui/SignInModal.d.ts +0 -22
  41. package/dist/ui/SignInModal.js +0 -77
  42. package/dist/ui/SignInModal.sections.d.ts +0 -33
  43. package/dist/ui/SignInModal.sections.js +0 -45
  44. package/dist/ui/SignInModal.shared.d.ts +0 -15
  45. package/dist/ui/SignInModal.shared.js +0 -126
  46. package/dist/ui/WalletSelectionModal.d.ts +0 -14
  47. package/dist/ui/WalletSelectionModal.js +0 -54
  48. package/dist/ui/WithdrawModal.d.ts +0 -57
  49. package/dist/ui/WithdrawModal.js +0 -574
  50. package/dist/ui/components/CloseButton.d.ts +0 -4
  51. package/dist/ui/components/CloseButton.js +0 -15
  52. package/dist/ui/components/Countdown.d.ts +0 -16
  53. package/dist/ui/components/Countdown.js +0 -42
  54. package/dist/ui/components/DepositDetailsPanel.d.ts +0 -8
  55. package/dist/ui/components/DepositDetailsPanel.js +0 -143
  56. package/dist/ui/components/DropdownField.d.ts +0 -19
  57. package/dist/ui/components/DropdownField.js +0 -81
  58. package/dist/ui/components/Field.d.ts +0 -10
  59. package/dist/ui/components/Field.js +0 -21
  60. package/dist/ui/components/LoginRequiredOverlay.d.ts +0 -6
  61. package/dist/ui/components/LoginRequiredOverlay.js +0 -31
  62. package/dist/ui/components/ModalCard.d.ts +0 -9
  63. package/dist/ui/components/ModalCard.js +0 -14
  64. package/dist/ui/components/ModalFrame.d.ts +0 -9
  65. package/dist/ui/components/ModalFrame.js +0 -18
  66. package/dist/ui/components/PrimaryButton.d.ts +0 -2
  67. package/dist/ui/components/PrimaryButton.js +0 -14
  68. package/dist/ui/components/QRCodePanel.d.ts +0 -4
  69. package/dist/ui/components/QRCodePanel.js +0 -43
  70. package/dist/ui/components/Select.d.ts +0 -12
  71. package/dist/ui/components/Select.js +0 -29
  72. package/dist/ui/components/StepIndicator.d.ts +0 -7
  73. package/dist/ui/components/StepIndicator.js +0 -35
  74. package/dist/ui/components/Success.d.ts +0 -1
  75. package/dist/ui/components/Success.js +0 -4
  76. package/dist/ui/components/Toast.d.ts +0 -8
  77. package/dist/ui/components/Toast.js +0 -51
  78. package/dist/ui/hooks/useSession.d.ts +0 -2
  79. package/dist/ui/hooks/useSession.js +0 -10
  80. package/dist/ui/signInTypes.d.ts +0 -28
  81. package/dist/ui/signInTypes.js +0 -1
  82. package/dist/ui/theme.d.ts +0 -31
  83. package/dist/ui/theme.js +0 -31
  84. package/dist/ui/useSignInModalController.d.ts +0 -25
  85. package/dist/ui/useSignInModalController.js +0 -119
  86. package/dist/utils/env.d.ts +0 -1
  87. package/dist/utils/env.js +0 -63
  88. package/dist/utils/explorer.d.ts +0 -3
  89. package/dist/utils/explorer.js +0 -47
  90. package/dist/walletUtils.d.ts +0 -3
  91. package/dist/walletUtils.js +0 -3
@@ -1,267 +0,0 @@
1
- import { EvmSigner } from "@cubist-labs/cubesigner-sdk";
2
- import { CubeSignerAuth, createChainContext, createSessionCapabilityPolicy, } from "@ab-org/sdk-core";
3
- const cubistCapabilities = [
4
- "eth_accounts",
5
- "eth_requestAccounts",
6
- "eth_chainId",
7
- "eth_signTransaction",
8
- "personal_sign",
9
- "eth_signTypedData_v4",
10
- "wallet_disconnect",
11
- ];
12
- const evmChainIdMap = {
13
- ETH: 1,
14
- BSC: 56,
15
- };
16
- const isRecord = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
17
- const toBigIntQuantity = (value) => {
18
- if (typeof value === "bigint")
19
- return value;
20
- if (typeof value === "number") {
21
- if (!Number.isInteger(value) || value < 0) {
22
- throw new Error(`Invalid EVM quantity number: ${value}`);
23
- }
24
- return BigInt(value);
25
- }
26
- const trimmed = value.trim();
27
- if (!trimmed) {
28
- throw new Error("EVM quantity cannot be empty");
29
- }
30
- if (/^0x[0-9a-fA-F]+$/.test(trimmed) || /^\d+$/.test(trimmed)) {
31
- return BigInt(trimmed);
32
- }
33
- throw new Error(`Invalid EVM quantity string: ${value}`);
34
- };
35
- const toHexQuantity = (value) => {
36
- if (value === undefined)
37
- return undefined;
38
- return `0x${toBigIntQuantity(value).toString(16)}`;
39
- };
40
- const normalizeAccessList = (accessList) => {
41
- if (!accessList)
42
- return undefined;
43
- return accessList.map((item) => ({
44
- address: item.address,
45
- storageKeys: item.storageKeys,
46
- }));
47
- };
48
- const textEncoder = new TextEncoder();
49
- const resolveTransactionType = (transaction) => {
50
- if (transaction.type !== undefined) {
51
- const normalized = toHexQuantity(transaction.type);
52
- if (normalized === "0x0" || normalized === "0x1" || normalized === "0x2") {
53
- return normalized;
54
- }
55
- throw new Error(`Unsupported EVM transaction type for Cubist: ${normalized}`);
56
- }
57
- if (transaction.maxFeePerGas !== undefined || transaction.maxPriorityFeePerGas !== undefined) {
58
- return "0x2";
59
- }
60
- if (transaction.accessList?.length) {
61
- return "0x1";
62
- }
63
- return "0x0";
64
- };
65
- const toCubistSignRequest = (address, chain, transaction) => {
66
- const resolvedChainId = (transaction.chainId !== undefined ? Number(toBigIntQuantity(transaction.chainId)) : undefined) ??
67
- evmChainIdMap[chain];
68
- if (!resolvedChainId) {
69
- throw new Error("Cubist signing requires an EVM chainId");
70
- }
71
- const type = resolveTransactionType(transaction);
72
- const commonFields = {
73
- from: transaction.from ?? address,
74
- to: transaction.to,
75
- data: transaction.data,
76
- gas: toHexQuantity(transaction.gas),
77
- nonce: toHexQuantity(transaction.nonce),
78
- value: toHexQuantity(transaction.value),
79
- };
80
- const accessList = normalizeAccessList(transaction.accessList);
81
- const tx = type === "0x2"
82
- ? {
83
- ...commonFields,
84
- type,
85
- ...(accessList ? { accessList } : {}),
86
- maxFeePerGas: toHexQuantity(transaction.maxFeePerGas),
87
- maxPriorityFeePerGas: toHexQuantity(transaction.maxPriorityFeePerGas),
88
- }
89
- : type === "0x1"
90
- ? {
91
- ...commonFields,
92
- type,
93
- ...(accessList ? { accessList } : {}),
94
- gasPrice: toHexQuantity(transaction.gasPrice),
95
- }
96
- : {
97
- ...commonFields,
98
- type,
99
- gasPrice: toHexQuantity(transaction.gasPrice),
100
- };
101
- return {
102
- chain_id: resolvedChainId,
103
- tx,
104
- };
105
- };
106
- const getTransactionParam = (params) => {
107
- const candidate = params?.[0];
108
- if (!isRecord(candidate)) {
109
- throw new Error("eth_signTransaction requires a transaction object");
110
- }
111
- return candidate;
112
- };
113
- const toHexBytes = (value) => {
114
- if (/^0x[0-9a-fA-F]*$/.test(value))
115
- return value;
116
- return `0x${Array.from(textEncoder.encode(value))
117
- .map((byte) => byte.toString(16).padStart(2, "0"))
118
- .join("")}`;
119
- };
120
- const getMessageParam = (address, params) => {
121
- const [first, second] = params ?? [];
122
- if (typeof second === "string" && second.toLowerCase() === address.toLowerCase()) {
123
- return String(first ?? "");
124
- }
125
- if (typeof first === "string" && first.toLowerCase() === address.toLowerCase()) {
126
- return String(second ?? "");
127
- }
128
- return String(first ?? "");
129
- };
130
- const getTypedDataParam = (address, params) => {
131
- const [first, second] = params ?? [];
132
- if (typeof first === "string" && first.toLowerCase() === address.toLowerCase()) {
133
- return typeof second === "string"
134
- ? JSON.parse(second)
135
- : (second ?? {});
136
- }
137
- return typeof second === "string"
138
- ? JSON.parse(second)
139
- : (second ?? first ?? {});
140
- };
141
- function createEmbeddedProvider({ session, address, chain, }) {
142
- const signer = new EvmSigner(address, session.client);
143
- return {
144
- async request(payload) {
145
- switch (payload.method) {
146
- case "eth_accounts":
147
- case "eth_requestAccounts":
148
- return [address];
149
- case "eth_chainId": {
150
- const chainId = evmChainIdMap[chain];
151
- if (!chainId) {
152
- throw new Error(`CubistProvider: chain ${chain} does not expose an EVM chainId`);
153
- }
154
- return `0x${chainId.toString(16)}`;
155
- }
156
- case "eth_signTransaction": {
157
- const transaction = getTransactionParam(payload.params);
158
- const signRequest = toCubistSignRequest(address, chain, transaction);
159
- return (await signer.signTransaction(signRequest));
160
- }
161
- case "personal_sign": {
162
- const message = getMessageParam(address, payload.params);
163
- return (await signer.signEip191({ data: toHexBytes(message) }));
164
- }
165
- case "eth_signTypedData_v4": {
166
- const typedData = getTypedDataParam(address, payload.params);
167
- const domain = typedData.domain;
168
- const chainId = domain?.chainId !== undefined
169
- ? Number(toBigIntQuantity(domain.chainId))
170
- : evmChainIdMap[chain];
171
- if (!chainId) {
172
- throw new Error("CubistProvider: typed data signing requires an EVM chainId");
173
- }
174
- return (await signer.signEip712({
175
- chain_id: chainId,
176
- typed_data: typedData,
177
- }));
178
- }
179
- default:
180
- throw new Error(`CubistProvider: unsupported RPC method "${payload.method}"`);
181
- }
182
- },
183
- async disconnect() {
184
- await session.client.revokeSession();
185
- },
186
- };
187
- }
188
- export class EmbeddedWalletAccountProvider {
189
- constructor(provider) {
190
- this.provider = provider;
191
- }
192
- async request(payload) {
193
- return this.provider.request(payload);
194
- }
195
- async disconnect() {
196
- await this.provider.disconnect();
197
- }
198
- async eth_accounts() {
199
- return this.request({ method: "eth_accounts" });
200
- }
201
- async eth_chainId() {
202
- return this.request({ method: "eth_chainId" });
203
- }
204
- }
205
- class WalletAccount {
206
- static clearInstance() {
207
- WalletAccount.instance = null;
208
- WalletAccount.instanceToken = null;
209
- WalletAccount.walletSession = null;
210
- WalletAccount.cubeSignerSession = null;
211
- }
212
- static getWalletSession() {
213
- return WalletAccount.walletSession;
214
- }
215
- static getCubeSignerSession() {
216
- return WalletAccount.cubeSignerSession;
217
- }
218
- static async getInstance(oidcToken, authSource, cubeSignerConfig) {
219
- if (WalletAccount.instance && WalletAccount.instanceToken === oidcToken) {
220
- return WalletAccount.instance;
221
- }
222
- WalletAccount.clearInstance();
223
- const auth = new CubeSignerAuth(cubeSignerConfig);
224
- const cubeSignerSession = await auth.loginWithGoogle(oidcToken);
225
- const keys = await cubeSignerSession.client.sessionKeys();
226
- const evmKey = keys.find((key) => key.cached.key_type === "SecpEthAddr");
227
- if (!evmKey) {
228
- throw new Error("No EVM key found in CubeSigner session");
229
- }
230
- const address = evmKey.materialId;
231
- const chain = "BSC";
232
- const provider = createEmbeddedProvider({
233
- session: cubeSignerSession,
234
- address,
235
- chain,
236
- });
237
- const wrappedProvider = new EmbeddedWalletAccountProvider(provider);
238
- const capabilityPolicy = auth.defaultSessionPolicy
239
- ? createSessionCapabilityPolicy(auth.defaultSessionPolicy)
240
- : undefined;
241
- WalletAccount.instance = wrappedProvider;
242
- WalletAccount.instanceToken = oidcToken;
243
- WalletAccount.cubeSignerSession = cubeSignerSession;
244
- WalletAccount.walletSession = {
245
- address,
246
- chain,
247
- provider: wrappedProvider,
248
- walletType: "social",
249
- authSource,
250
- sessionId: `${authSource}:${address.toLowerCase()}`,
251
- expiresAt: capabilityPolicy?.expiresAt,
252
- capabilities: [...cubistCapabilities],
253
- sessionData: cubeSignerSession.sessionData,
254
- chainContext: createChainContext(chain),
255
- capabilityPolicy,
256
- };
257
- return wrappedProvider;
258
- }
259
- }
260
- WalletAccount.instance = null;
261
- WalletAccount.instanceToken = null;
262
- WalletAccount.walletSession = null;
263
- WalletAccount.cubeSignerSession = null;
264
- export default WalletAccount;
265
- export function clearSocialAccountInstance() {
266
- WalletAccount.clearInstance();
267
- }
@@ -1,2 +0,0 @@
1
- export { ClientIds, DEFAULT_FUNDING_CHAIN_ID, DEFAULT_FUNDING_TOKEN_ADDRESS, getFundingTokenAddress, getChainInfo, type EvmChainInfo, } from "@ab-org/wallet-utils";
2
- /** Demo / docs placeholder platform contract; replace in production. */
@@ -1,3 +0,0 @@
1
- export { ClientIds, DEFAULT_FUNDING_CHAIN_ID, DEFAULT_FUNDING_TOKEN_ADDRESS, getFundingTokenAddress, getChainInfo, } from "@ab-org/wallet-utils";
2
- /** Demo / docs placeholder platform contract; replace in production. */
3
- // export const FUNDING_TOKEN_PLATFORM_CONTRACT_ADDRESS ="0x1234567890123456789012345678901234567890";
@@ -1,149 +0,0 @@
1
- /**
2
- * Merchant API client
3
- * 基于 axios 封装,类型与文档一致。
4
- */
5
- import { type AxiosInstance } from "axios";
6
- /** 通用 API 响应:所有接口统一格式 */
7
- export interface ApiResponse<T> {
8
- data: T | null;
9
- code: number;
10
- msg: string;
11
- timestamp: number;
12
- }
13
- export interface TokenData {
14
- symbol: string;
15
- address: string;
16
- decimals: number;
17
- /** 最小充值量(最小单位字符串,如 `"15000000"`) */
18
- minimum_deposit?: string;
19
- /** 是否为 USD 类稳定币 */
20
- is_usd_stable?: boolean;
21
- }
22
- export interface ChainData {
23
- chain_id: string;
24
- network: string;
25
- tokens: TokenData[];
26
- }
27
- export interface ChainsResponseData {
28
- chains: ChainData[];
29
- is_testnet: boolean;
30
- }
31
- export interface PlatformRegisterRequest {
32
- platform_contract_address: string;
33
- chain_id: string;
34
- }
35
- export interface PlatformRegisterResponseData {
36
- deposit_address: string;
37
- chain_id: string;
38
- }
39
- export type QuoteDirection = "deposit" | "withdraw";
40
- interface QuoteRequest {
41
- direction: QuoteDirection;
42
- chain_id: string;
43
- token_address: string;
44
- token_amount?: string;
45
- dst_token_amount?: string;
46
- }
47
- export interface QuoteResponseData {
48
- token_address: string;
49
- token_symbol: string;
50
- token_decimals: number;
51
- rate: string;
52
- chain_id: number;
53
- deposit_address?: string;
54
- dst_token_amount?: string;
55
- token_amount?: string;
56
- expires_at?: string;
57
- }
58
- export type DepositOrderStatus = "received" | "processing" | "completed" | "failed" | "funded";
59
- export interface DepositOrderResponseData {
60
- order_id: string;
61
- status: DepositOrderStatus;
62
- source_chain_id: string;
63
- token_address: string;
64
- token_amount?: string;
65
- dst_token_amount?: string;
66
- deposit_address?: string;
67
- source_tx_hash?: string;
68
- created_at?: string;
69
- updated_at?: string;
70
- }
71
- export type WithdrawOrderStatus = "pending" | "funded" | "processing" | "completed" | "failed" | "expired";
72
- export interface WithdrawOrderResponseData {
73
- order_id: string;
74
- status: WithdrawOrderStatus;
75
- one_time_address?: string;
76
- chain_id: string;
77
- dst_token_amount: string;
78
- /** Fee (e.g. "0.01 USDT"); only present if backend includes it in GET /api/v1/orders/withdraw/:id. UI falls back to feeDisplay prop or "—". */
79
- fee?: string;
80
- target_chain_id: string;
81
- target_address: string;
82
- funding_tx_hash?: string;
83
- dst_tx_hash?: string;
84
- out_tx_hash?: string;
85
- created_at?: string;
86
- updated_at?: string;
87
- }
88
- export interface NativeSwapPayload {
89
- chain_id: string;
90
- token_address: string;
91
- token_amount: string;
92
- dst_chain_id: string;
93
- dst_token_address: string;
94
- recipient: string;
95
- }
96
- export interface PaymentPairData {
97
- token_symbol: string;
98
- token_amount: string;
99
- token_address: string;
100
- user_address: string;
101
- chain_id: string;
102
- }
103
- export interface CreateOrderRequest {
104
- intent_id: string;
105
- order_type: "NATIVE_SWAP";
106
- order_payload: NativeSwapPayload;
107
- payment_pairs: PaymentPairData[];
108
- }
109
- export type PaymentSessionStatus = "CREATED" | "PENDING" | "FUNDED" | "CANCELED" | "CAPTURING" | "SUCCEED";
110
- export interface PaymentSessionResponseData {
111
- payment_session_id: string;
112
- created_at?: string;
113
- status: PaymentSessionStatus;
114
- one_time_wallet_address: string;
115
- amount: string;
116
- currency: string;
117
- user_address?: string;
118
- network?: string;
119
- token_symbol?: string;
120
- chain_id?: string;
121
- funding_transaction_hash?: string | null;
122
- capturable_amount?: string;
123
- captured_amount?: string;
124
- }
125
- export interface CreateOrderResponseData {
126
- order_id: string;
127
- payment_sessions: PaymentSessionResponseData[];
128
- }
129
- /**
130
- * 配置 Merchant API 的 baseURL
131
- */
132
- export declare function configureMerchantApi(): void;
133
- /**
134
- * 获取当前 axios 实例(用于自定义请求)
135
- */
136
- export declare function getMerchantApiClient(): AxiosInstance;
137
- /** GET /chains - 查询支持的链和代币列表 */
138
- export declare function getChains(): Promise<ChainsResponseData>;
139
- /** POST /api/v1/platform - 注册平台合约并获取充值地址 */
140
- export declare function registerPlatform(body: PlatformRegisterRequest): Promise<PlatformRegisterResponseData>;
141
- /** POST /api/v1/quote - 统一报价(充值/提现) */
142
- export declare function quote(body: QuoteRequest): Promise<QuoteResponseData>;
143
- /** GET /api/v1/orders/deposit/{order_id} - 查询充值订单状态 */
144
- export declare function getDepositOrder(orderId: string): Promise<DepositOrderResponseData>;
145
- /** GET /api/v1/orders/withdraw/{order_id} - 查询提现订单状态 */
146
- export declare function getWithdrawOrder(orderId: string): Promise<WithdrawOrderResponseData>;
147
- /** POST /order - 创建 NATIVE_SWAP 提现订单 */
148
- export declare function createOrder(body: CreateOrderRequest): Promise<CreateOrderResponseData>;
149
- export {};
@@ -1,95 +0,0 @@
1
- /**
2
- * Merchant API client
3
- * 基于 axios 封装,类型与文档一致。
4
- */
5
- import { getEnv } from "../utils/env.js";
6
- import axios from "axios";
7
- // ─── Axios 实例与请求封装 ─────────────────────────────────────────────────────
8
- function createClient() {
9
- const BASE_URL = getEnv("MERCHANT_BASE_URL");
10
- if (!BASE_URL) {
11
- throw new Error('MERCHANT_BASE_URL is not set');
12
- }
13
- return axios.create({
14
- baseURL: BASE_URL,
15
- timeout: 30000,
16
- headers: { "Content-Type": "application/json" },
17
- });
18
- }
19
- /** 解析通用响应并抛出业务错误 */
20
- function unwrap(res) {
21
- if (res.code !== 0 || res.data === null) {
22
- throw new Error(res.msg || "API error");
23
- }
24
- return res.data;
25
- }
26
- // 单例 client,可通过 configureMerchantApi 修改 baseURL
27
- let apiClient = createClient();
28
- /**
29
- * 配置 Merchant API 的 baseURL
30
- */
31
- export function configureMerchantApi() {
32
- apiClient = createClient();
33
- }
34
- /**
35
- * 获取当前 axios 实例(用于自定义请求)
36
- */
37
- export function getMerchantApiClient() {
38
- return apiClient;
39
- }
40
- // ─── 接口方法(均 try-catch,失败时返回 mock)──────────────────────────────────
41
- /** GET /chains - 查询支持的链和代币列表 */
42
- export async function getChains() {
43
- try {
44
- const { data } = await apiClient.get("/chains");
45
- return unwrap(data);
46
- }
47
- catch {
48
- throw new Error('Failed to get chains');
49
- }
50
- }
51
- /** POST /api/v1/platform - 注册平台合约并获取充值地址 */
52
- export async function registerPlatform(body) {
53
- try {
54
- const { data } = await apiClient.post("/api/v1/platform", body);
55
- return unwrap(data);
56
- }
57
- catch {
58
- throw new Error('Failed to register platform');
59
- }
60
- }
61
- /** POST /api/v1/quote - 统一报价(充值/提现) */
62
- export async function quote(body) {
63
- const { data } = await apiClient.post("/api/v1/quote", body);
64
- return unwrap(data);
65
- }
66
- /** GET /api/v1/orders/deposit/{order_id} - 查询充值订单状态 */
67
- export async function getDepositOrder(orderId) {
68
- try {
69
- const { data } = await apiClient.get(`/api/v1/orders/deposit/${encodeURIComponent(orderId)}`);
70
- return unwrap(data);
71
- }
72
- catch {
73
- throw new Error('Failed to get deposit order');
74
- }
75
- }
76
- /** GET /api/v1/orders/withdraw/{order_id} - 查询提现订单状态 */
77
- export async function getWithdrawOrder(orderId) {
78
- try {
79
- const { data } = await apiClient.get(`/api/v1/orders/withdraw/${encodeURIComponent(orderId)}`);
80
- return unwrap(data);
81
- }
82
- catch {
83
- throw new Error('Failed to get withdraw order');
84
- }
85
- }
86
- /** POST /order - 创建 NATIVE_SWAP 提现订单 */
87
- export async function createOrder(body) {
88
- try {
89
- const { data } = await apiClient.post("/order", body);
90
- return unwrap(data);
91
- }
92
- catch {
93
- throw new Error('Failed to create order');
94
- }
95
- }
@@ -1,27 +0,0 @@
1
- export interface Erc20BalanceResult {
2
- raw: bigint;
3
- formatted: string;
4
- symbol: string;
5
- }
6
- /**
7
- * Query any ERC-20 token balance via a raw JSON-RPC `eth_call`.
8
- * No external library dependency – uses the global `fetch`.
9
- */
10
- export declare function fetchErc20Balance(rpcUrl: string, tokenAddress: string, walletAddress: string): Promise<bigint>;
11
- export interface FundingTokenBalanceOptions {
12
- rpcUrl?: string;
13
- tokenAddress?: string;
14
- decimals?: number;
15
- /**
16
- * Funding chain id (e.g. `"3131"` Tenderly BSC, `"56"` mainnet).
17
- * When omitted, defaults to `3131` via {@link getChainInfo}.
18
- */
19
- chainId?: string | number | null;
20
- /** Label for {@link Erc20BalanceResult.symbol} (default `"Funding"`). */
21
- displaySymbol?: string;
22
- }
23
- /**
24
- * Fetches the configured funding ERC-20 balance on the selected funding chain.
25
- * Defaults: chain `3131`, RPC from {@link getChainInfo}, token from {@link getFundingTokenAddress} / env.
26
- */
27
- export declare function fetchFundingTokenBalance(walletAddress: string, options?: FundingTokenBalanceOptions): Promise<Erc20BalanceResult>;
@@ -1,60 +0,0 @@
1
- import { getEnv } from "../utils/env";
2
- import { getFundingTokenAddress, getChainInfo } from "../constants/chains.js";
3
- const ERC20_BALANCE_OF_SELECTOR = "0x70a08231";
4
- function padAddress(address) {
5
- return address.toLowerCase().replace("0x", "").padStart(64, "0");
6
- }
7
- function formatUnits(value, decimals) {
8
- const divisor = 10n ** BigInt(decimals);
9
- const intPart = value / divisor;
10
- const fracPart = value % divisor;
11
- if (fracPart === 0n)
12
- return intPart.toString();
13
- const fracStr = fracPart.toString().padStart(decimals, "0").replace(/0+$/, "");
14
- return `${intPart}.${fracStr}`;
15
- }
16
- /** 格式化为显示用 balance,保留小数点后 2 位 */
17
- function formatBalanceDisplay(value, decimals) {
18
- const full = formatUnits(value, decimals);
19
- const n = Number(full);
20
- return Number.isNaN(n) ? full : n.toFixed(2);
21
- }
22
- /**
23
- * Query any ERC-20 token balance via a raw JSON-RPC `eth_call`.
24
- * No external library dependency – uses the global `fetch`.
25
- */
26
- export async function fetchErc20Balance(rpcUrl, tokenAddress, walletAddress) {
27
- const data = `${ERC20_BALANCE_OF_SELECTOR}${padAddress(walletAddress)}`;
28
- const response = await fetch(rpcUrl, {
29
- method: "POST",
30
- headers: { "Content-Type": "application/json" },
31
- body: JSON.stringify({
32
- jsonrpc: "2.0",
33
- id: 1,
34
- method: "eth_call",
35
- params: [{ to: tokenAddress, data }, "latest"],
36
- }),
37
- });
38
- const json = (await response.json());
39
- if (json.error)
40
- throw new Error(json.error.message ?? "RPC error");
41
- return BigInt(json.result ?? "0x0");
42
- }
43
- /**
44
- * Fetches the configured funding ERC-20 balance on the selected funding chain.
45
- * Defaults: chain `3131`, RPC from {@link getChainInfo}, token from {@link getFundingTokenAddress} / env.
46
- */
47
- export async function fetchFundingTokenBalance(walletAddress, options) {
48
- const chain = getChainInfo(options?.chainId);
49
- const rpcUrl = options?.rpcUrl ?? chain.rpcUrls[0];
50
- const tokenAddress = options?.tokenAddress ?? getFundingTokenAddress(options?.chainId);
51
- const decimals = options?.decimals ?? chain.nativeCurrencyDecimals;
52
- const FUNDING_TOKEN_SYMBOL = getEnv("FUNDING_TOKEN_SYMBOL");
53
- const displaySymbol = options?.displaySymbol ?? (FUNDING_TOKEN_SYMBOL || "Funding");
54
- const raw = await fetchErc20Balance(rpcUrl, tokenAddress, walletAddress);
55
- return {
56
- raw,
57
- formatted: formatBalanceDisplay(raw, decimals),
58
- symbol: displaySymbol,
59
- };
60
- }
@@ -1,31 +0,0 @@
1
- import type { ChainInfo, CustodyAdapter, DepositAddressResult, MarketDataProvider, ModalController, QuoteResult, TokenInfo } from "../types.js";
2
- export interface DepositModalConfig {
3
- preferredToken?: string;
4
- preferredChain?: string;
5
- onStatusChange?: (status: DepositStatus) => void;
6
- }
7
- export type DepositStatus = {
8
- phase: "idle";
9
- } | {
10
- phase: "address-issued";
11
- depositId: string;
12
- address: string;
13
- } | {
14
- phase: "confirming";
15
- depositId: string;
16
- } | {
17
- phase: "settled";
18
- depositId: string;
19
- txHash?: string;
20
- } | {
21
- phase: "failed";
22
- reason: string;
23
- };
24
- export interface DepositController extends ModalController<DepositModalConfig> {
25
- readonly status: DepositStatus;
26
- fetchTokens(): Promise<TokenInfo[]>;
27
- fetchChains(token: string): Promise<ChainInfo[]>;
28
- fetchQuote(token: string, chain: string, amount: string): Promise<QuoteResult>;
29
- fetchDepositAddress(token: string, chain: string): Promise<DepositAddressResult>;
30
- }
31
- export declare const createDepositController: (custody: CustodyAdapter, marketData: MarketDataProvider) => DepositController;