@wagmipro/sdk 0.0.0-stage → 0.6.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +16 -0
- package/README.md +51 -2
- package/dist/action.d.ts +156 -0
- package/dist/action.js +379 -0
- package/dist/client.d.ts +234 -0
- package/dist/client.js +244 -0
- package/dist/index.d.ts +9 -0
- package/dist/index.js +5 -0
- package/dist/partner.d.ts +342 -0
- package/dist/partner.js +239 -0
- package/dist/sign.d.ts +11 -0
- package/dist/sign.js +62 -0
- package/dist/stream.d.ts +81 -0
- package/dist/stream.js +234 -0
- package/package.json +35 -4
- package/test/vectors.test.mjs +31 -0
- package/testvectors.json +1013 -0
|
@@ -0,0 +1,342 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* THE BUILDER CLIENT (builder codes): your backend's calls with your builder key (fxp_...), the earnings stream, and the
|
|
3
|
+
* in-app setup of each user: you show their wallet the messages we return, exactly as returned, and pass the signatures
|
|
4
|
+
* back. `onboardUser` does the whole setup with a wallet adapter (viem or ethers), so you never build a signature.
|
|
5
|
+
*
|
|
6
|
+
* const partner = new WagmiPartner({ keyId: process.env.FX_BUILDER_KEY, secret: process.env.FX_BUILDER_SECRET })
|
|
7
|
+
* await partner.createUser({ externalRef: 'user-1842', wallet }) // accountIndex optional: none yet is fine
|
|
8
|
+
* await partner.depositAddress('user-1842', { chainId: '42161', token: 'USDC' }) // their first deposit opens the account
|
|
9
|
+
* const requestKey = await newRequestKey() // keep requestKey.signingKey for this user
|
|
10
|
+
* const setup = await partner.onboardUser('user-1842', { requestKey, wallet: viemWallet(walletClient) })
|
|
11
|
+
* const user = await partner.userClient(setup, requestKey) // a WagmiClient trading as this user
|
|
12
|
+
* await user.placeOrder('BTC', { side: 'buy', orderType: 'market', size: '0.001', price: '99000' }, { partner: 'YOURCODE' })
|
|
13
|
+
*
|
|
14
|
+
* A builder key never trades: every order goes with the user's own key, signed with the request key your app holds for
|
|
15
|
+
* them. Nothing here holds or moves anyone's funds; each user's money stays on their own trading account.
|
|
16
|
+
*/
|
|
17
|
+
import { WagmiClient, type ClientOptions } from './client.js';
|
|
18
|
+
import { WagmiStream, type StreamOptions } from './stream.js';
|
|
19
|
+
export interface PartnerOptions {
|
|
20
|
+
/** Your builder key id (fxp_...) and its secret. */
|
|
21
|
+
keyId?: string;
|
|
22
|
+
secret?: string;
|
|
23
|
+
/** The same as keyId and secret (0.4.1): the names WagmiClient takes, accepted here too. */
|
|
24
|
+
apiKey?: string;
|
|
25
|
+
apiSecret?: string;
|
|
26
|
+
baseUrl?: string;
|
|
27
|
+
wsUrl?: string;
|
|
28
|
+
fetch?: typeof fetch;
|
|
29
|
+
now?: () => number;
|
|
30
|
+
}
|
|
31
|
+
/** One side's fee, in millionths (100 is one basis point). */
|
|
32
|
+
export interface SideFee {
|
|
33
|
+
taker: number;
|
|
34
|
+
maker: number;
|
|
35
|
+
}
|
|
36
|
+
export interface PartnerFee {
|
|
37
|
+
perp: SideFee;
|
|
38
|
+
spot: SideFee;
|
|
39
|
+
}
|
|
40
|
+
/** GET /v1/partner/me. feeChangeAllowedAfter: null when setFee would be taken now. */
|
|
41
|
+
export interface PartnerMe {
|
|
42
|
+
code: string;
|
|
43
|
+
name: string;
|
|
44
|
+
status: 'active' | 'paused';
|
|
45
|
+
pausedAt: string | null;
|
|
46
|
+
sandbox: boolean;
|
|
47
|
+
fee: PartnerFee;
|
|
48
|
+
feeChangeAllowedAfter: string | null;
|
|
49
|
+
payout: {
|
|
50
|
+
toAccount: string | null;
|
|
51
|
+
};
|
|
52
|
+
createdAt: string;
|
|
53
|
+
}
|
|
54
|
+
export interface PersonalSignStep {
|
|
55
|
+
type: 'personal_sign';
|
|
56
|
+
message: string;
|
|
57
|
+
}
|
|
58
|
+
export interface TypedDataStep {
|
|
59
|
+
type: 'eip712';
|
|
60
|
+
typedData: {
|
|
61
|
+
domain: Record<string, unknown>;
|
|
62
|
+
types: Record<string, Array<{
|
|
63
|
+
name: string;
|
|
64
|
+
type: string;
|
|
65
|
+
}>>;
|
|
66
|
+
primaryType: string;
|
|
67
|
+
message: Record<string, unknown>;
|
|
68
|
+
};
|
|
69
|
+
}
|
|
70
|
+
export type SetupStep = PersonalSignStep | TypedDataStep;
|
|
71
|
+
/** A setup or re-approval draft: what the user's wallet signs, valid 10 minutes. */
|
|
72
|
+
export interface SetupDraft {
|
|
73
|
+
status: 'needs_signatures' | 'ready' | string;
|
|
74
|
+
steps: Record<string, string>;
|
|
75
|
+
draftId?: string;
|
|
76
|
+
expiresAt?: string;
|
|
77
|
+
authorization?: {
|
|
78
|
+
version: string;
|
|
79
|
+
text: string;
|
|
80
|
+
hash: string;
|
|
81
|
+
};
|
|
82
|
+
toSign?: Record<string, SetupStep>;
|
|
83
|
+
apiKey?: {
|
|
84
|
+
keyId: string;
|
|
85
|
+
secret: string;
|
|
86
|
+
secretShownOnce: boolean;
|
|
87
|
+
};
|
|
88
|
+
}
|
|
89
|
+
/**
|
|
90
|
+
* A wallet that signs the setup: `personal_sign` messages and EIP-712 typed data (`eth_signTypedData_v4`). Use
|
|
91
|
+
* viemWallet or ethersWallet, or give your own two functions (a browser wallet, a server signer).
|
|
92
|
+
*/
|
|
93
|
+
export interface SetupWallet {
|
|
94
|
+
signMessage(message: string): Promise<string>;
|
|
95
|
+
signTypedData(typedData: TypedDataStep['typedData']): Promise<string>;
|
|
96
|
+
/** Sends a transaction from this wallet and answers its hash (only for withdraw: the user's own withdrawal). */
|
|
97
|
+
sendTransaction?(tx: WithdrawalTransaction): Promise<string>;
|
|
98
|
+
}
|
|
99
|
+
/** The Ethereum transaction a user's own wallet sends to withdraw (withdrawalDraft). */
|
|
100
|
+
export interface WithdrawalTransaction {
|
|
101
|
+
chainId: number;
|
|
102
|
+
from: string;
|
|
103
|
+
to: string;
|
|
104
|
+
data: string;
|
|
105
|
+
value: string;
|
|
106
|
+
gas: string;
|
|
107
|
+
}
|
|
108
|
+
/** `account` is the WAGMI.PRO account id (as on /v1/account/*); `accountIndex` the trading account's number on the exchange, as the transaction carries it. */
|
|
109
|
+
export interface WithdrawalDraft {
|
|
110
|
+
asset: 'USDC';
|
|
111
|
+
amount: string;
|
|
112
|
+
wallet: string;
|
|
113
|
+
account: number;
|
|
114
|
+
accountIndex: string;
|
|
115
|
+
paysTo: string;
|
|
116
|
+
transaction: WithdrawalTransaction;
|
|
117
|
+
notes: string[];
|
|
118
|
+
sandbox?: boolean;
|
|
119
|
+
}
|
|
120
|
+
export interface Withdrawal {
|
|
121
|
+
id: string;
|
|
122
|
+
externalRef: string;
|
|
123
|
+
asset: 'USDC';
|
|
124
|
+
amount: string;
|
|
125
|
+
wallet: string;
|
|
126
|
+
chainId: number;
|
|
127
|
+
/** sent: the wallet sent it; mined: on Ethereum, the exchange takes it from the account; arrived: paid to the wallet. */
|
|
128
|
+
status: 'sent' | 'mined' | 'arrived' | 'failed';
|
|
129
|
+
txHash: string;
|
|
130
|
+
arrivalTxHash: string | null;
|
|
131
|
+
failure: string | null;
|
|
132
|
+
sandbox: boolean;
|
|
133
|
+
createdAt: string;
|
|
134
|
+
updatedAt: string;
|
|
135
|
+
}
|
|
136
|
+
/** A viem WalletClient (with its account, or name one) as a SetupWallet. */
|
|
137
|
+
export declare function viemWallet(client: {
|
|
138
|
+
account?: unknown;
|
|
139
|
+
signMessage(a: {
|
|
140
|
+
account?: any;
|
|
141
|
+
message: string;
|
|
142
|
+
}): Promise<string>;
|
|
143
|
+
signTypedData(a: {
|
|
144
|
+
account?: any;
|
|
145
|
+
domain: any;
|
|
146
|
+
types: any;
|
|
147
|
+
primaryType: string;
|
|
148
|
+
message: any;
|
|
149
|
+
}): Promise<string>;
|
|
150
|
+
sendTransaction?(a: {
|
|
151
|
+
account?: any;
|
|
152
|
+
to: string;
|
|
153
|
+
data: string;
|
|
154
|
+
value: bigint;
|
|
155
|
+
gas: bigint;
|
|
156
|
+
chain?: any;
|
|
157
|
+
}): Promise<string>;
|
|
158
|
+
}, account?: unknown): SetupWallet;
|
|
159
|
+
/** An ethers v6 Signer (a Wallet, a BrowserProvider's signer) as a SetupWallet. */
|
|
160
|
+
export declare function ethersWallet(signer: {
|
|
161
|
+
signMessage(message: string): Promise<string>;
|
|
162
|
+
signTypedData(domain: any, types: any, value: any): Promise<string>;
|
|
163
|
+
sendTransaction?(tx: {
|
|
164
|
+
to: string;
|
|
165
|
+
data: string;
|
|
166
|
+
value: bigint;
|
|
167
|
+
gasLimit: bigint;
|
|
168
|
+
chainId: number;
|
|
169
|
+
}): Promise<{
|
|
170
|
+
hash: string;
|
|
171
|
+
}>;
|
|
172
|
+
}): SetupWallet;
|
|
173
|
+
/**
|
|
174
|
+
* A new request key for one user: an Ed25519 key pair your app keeps for them. `publicKey` goes to the setup;
|
|
175
|
+
* `signingKey` (keep it secret, per user) signs each of their orders (WagmiClient's signingKey).
|
|
176
|
+
*/
|
|
177
|
+
export declare function newRequestKey(): Promise<{
|
|
178
|
+
publicKey: string;
|
|
179
|
+
signingKey: string;
|
|
180
|
+
}>;
|
|
181
|
+
/** Every signature a draft asks for, from the wallet, exactly as returned. */
|
|
182
|
+
export declare function signDraft(draft: SetupDraft, wallet: SetupWallet): Promise<Record<string, string>>;
|
|
183
|
+
export declare class WagmiPartner {
|
|
184
|
+
private readonly http;
|
|
185
|
+
private readonly o;
|
|
186
|
+
constructor(options?: PartnerOptions);
|
|
187
|
+
private call;
|
|
188
|
+
private ref;
|
|
189
|
+
/**
|
|
190
|
+
* A new WAGMI.PRO account for one of your users, linked to your builder code (the same values again: the same user).
|
|
191
|
+
* Leave accountIndex out for a user with no trading account yet: `trading` is 'awaiting_deposit' until their first
|
|
192
|
+
* deposit (depositAddress) creates it, owned by their wallet; then 'ready' and the setup can start.
|
|
193
|
+
*/
|
|
194
|
+
createUser(u: {
|
|
195
|
+
externalRef: string;
|
|
196
|
+
wallet: string;
|
|
197
|
+
accountIndex?: string | number;
|
|
198
|
+
}): Promise<any>;
|
|
199
|
+
users(): Promise<any>;
|
|
200
|
+
user(externalRef: string): Promise<any>;
|
|
201
|
+
/** Volume per user and in total: fills, traded volume and your builder fee, in dollars. from included, to not (UTC days, YYYY-MM-DD); default the last 30 days. */
|
|
202
|
+
volumeReport(q?: {
|
|
203
|
+
from?: string;
|
|
204
|
+
to?: string;
|
|
205
|
+
}): Promise<any>;
|
|
206
|
+
/** One row per UTC day (empty days included): fills, volume, your fee, active users, new users. */
|
|
207
|
+
dailyReport(q?: {
|
|
208
|
+
from?: string;
|
|
209
|
+
to?: string;
|
|
210
|
+
}): Promise<any>;
|
|
211
|
+
/** Either report as CSV text (a TOTAL row closes the volume report). */
|
|
212
|
+
reportCsv(kind: 'volume' | 'daily', q?: {
|
|
213
|
+
from?: string;
|
|
214
|
+
to?: string;
|
|
215
|
+
}): Promise<string>;
|
|
216
|
+
/** Your sandbox's code, and whether this key is the sandbox's. */
|
|
217
|
+
sandbox(): Promise<any>;
|
|
218
|
+
/**
|
|
219
|
+
* With your LIVE key: your sandbox (made on the first call) and a new sandbox builder key, its secret in this answer
|
|
220
|
+
* only. Every call with that key answers from the sandbox: setups are checked as live, nothing is signed for the
|
|
221
|
+
* exchange, deposited or paid. `new WagmiPartner({ keyId, secret })` with it, and build as usual.
|
|
222
|
+
*/
|
|
223
|
+
createSandboxKey(): Promise<any>;
|
|
224
|
+
/** Sandbox only: the user's deposit marked as arrived (they get a stand-in trading account, trading 'ready'). */
|
|
225
|
+
sandboxDeposit(externalRef: string): Promise<any>;
|
|
226
|
+
/** Every chain and coin a deposit can be sent from, with each one's minimum. */
|
|
227
|
+
depositOptions(): Promise<any>;
|
|
228
|
+
/** The user's own deposit address for one chain and coin; it arrives on their own trading account as USDC. */
|
|
229
|
+
depositAddress(externalRef: string, q: {
|
|
230
|
+
chainId: string | number;
|
|
231
|
+
token: string;
|
|
232
|
+
}): Promise<any>;
|
|
233
|
+
/** What a deposit of `amount` (in the coin's units) would deliver, what it costs and how long it takes. */
|
|
234
|
+
depositQuote(externalRef: string, q: {
|
|
235
|
+
chainId: string | number;
|
|
236
|
+
token: string;
|
|
237
|
+
amount: string;
|
|
238
|
+
}): Promise<any>;
|
|
239
|
+
/**
|
|
240
|
+
* The Ethereum transaction the user's OWN wallet sends to withdraw `amount` USDC. No key you or we hold is involved:
|
|
241
|
+
* the wallet sends it to the exchange, which pays the account's owner, that same wallet, on Ethereum. The wallet pays
|
|
242
|
+
* the gas in ETH (about 132,000 gas). Checked: the account is the wallet's, at least 1 USDC, at most what is free now.
|
|
243
|
+
*/
|
|
244
|
+
withdrawalDraft(externalRef: string, q: {
|
|
245
|
+
amount: string;
|
|
246
|
+
}): Promise<WithdrawalDraft>;
|
|
247
|
+
/** Hands back the hash the wallet sent: checked on Ethereum, then followed (status on your stream as type 'withdrawal'). */
|
|
248
|
+
recordWithdrawal(externalRef: string, q: {
|
|
249
|
+
txHash: string;
|
|
250
|
+
}): Promise<Withdrawal>;
|
|
251
|
+
/** The user's withdrawals, newest first. */
|
|
252
|
+
withdrawals(externalRef: string): Promise<Withdrawal[]>;
|
|
253
|
+
/**
|
|
254
|
+
* The whole withdrawal: the draft, the user's wallet sends it (wallet.sendTransaction: viemWallet or ethersWallet over
|
|
255
|
+
* the user's own wallet), the hash handed back (again for up to a minute while Ethereum has not shown it yet).
|
|
256
|
+
*/
|
|
257
|
+
withdraw(externalRef: string, o: {
|
|
258
|
+
amount: string;
|
|
259
|
+
wallet: SetupWallet;
|
|
260
|
+
onDraft?: (d: WithdrawalDraft) => void;
|
|
261
|
+
}): Promise<Withdrawal>;
|
|
262
|
+
setupDraft(externalRef: string, q: {
|
|
263
|
+
requestKey: string;
|
|
264
|
+
approvalExpiry?: number;
|
|
265
|
+
ipAllowlist?: string;
|
|
266
|
+
}): Promise<SetupDraft>;
|
|
267
|
+
sendSetup(externalRef: string, draftId: string, signatures: Record<string, string>): Promise<SetupDraft>;
|
|
268
|
+
/** A new API key for a set-up user (the old one stops at once); its secret is in this answer only. */
|
|
269
|
+
newUserKey(externalRef: string): Promise<any>;
|
|
270
|
+
/**
|
|
271
|
+
* The whole setup: the draft, the wallet's signatures, sent back, again for any step still open (a user who stopped
|
|
272
|
+
* half-way picks up where they were). Answers the finished setup, with the user's own API key (its secret once).
|
|
273
|
+
*/
|
|
274
|
+
onboardUser(externalRef: string, o: {
|
|
275
|
+
requestKey: {
|
|
276
|
+
publicKey: string;
|
|
277
|
+
};
|
|
278
|
+
wallet: SetupWallet;
|
|
279
|
+
approvalExpiry?: number;
|
|
280
|
+
ipAllowlist?: string;
|
|
281
|
+
onDraft?: (d: SetupDraft) => void;
|
|
282
|
+
}): Promise<SetupDraft>;
|
|
283
|
+
/** A WagmiClient trading as this user: their API key from the setup and the request key you keep for them. */
|
|
284
|
+
userClient(setup: {
|
|
285
|
+
apiKey?: {
|
|
286
|
+
keyId: string;
|
|
287
|
+
secret: string;
|
|
288
|
+
};
|
|
289
|
+
grantId?: string | null;
|
|
290
|
+
} | {
|
|
291
|
+
keyId: string;
|
|
292
|
+
secret: string;
|
|
293
|
+
grantId?: string | null;
|
|
294
|
+
}, requestKey: {
|
|
295
|
+
signingKey: string;
|
|
296
|
+
}, o?: {
|
|
297
|
+
externalRef?: string;
|
|
298
|
+
} & ClientOptions): Promise<WagmiClient>;
|
|
299
|
+
/** Your builder code itself: code, name, status, whether this key is a sandbox's, your fee, when you may next change it, and the account your earnings are paid to. */
|
|
300
|
+
me(): Promise<PartnerMe>;
|
|
301
|
+
fee(): Promise<any>;
|
|
302
|
+
/** Your fee per kind and side (millionths). A raise needs each user's new approval; a cut applies at once. Once a day. */
|
|
303
|
+
setFee(fee: PartnerFee): Promise<any>;
|
|
304
|
+
approvalDraft(externalRef: string, q?: {
|
|
305
|
+
approvalExpiry?: number;
|
|
306
|
+
}): Promise<SetupDraft>;
|
|
307
|
+
sendApproval(externalRef: string, draftId: string, signatures: Record<string, string>): Promise<any>;
|
|
308
|
+
/** The re-approval in one call: the draft, the wallet's two signatures, sent. */
|
|
309
|
+
reapprove(externalRef: string, o: {
|
|
310
|
+
wallet: SetupWallet;
|
|
311
|
+
approvalExpiry?: number;
|
|
312
|
+
}): Promise<any>;
|
|
313
|
+
/** Revoke the user's approval: answers {revoked: true, approval (the status now, null when none is active), reapprovalNeeded}. */
|
|
314
|
+
revokeApproval(externalRef: string): Promise<{
|
|
315
|
+
revoked: true;
|
|
316
|
+
approval: {
|
|
317
|
+
status: string;
|
|
318
|
+
partnerFee: PartnerFee;
|
|
319
|
+
expiresAt: string;
|
|
320
|
+
createdAt: string;
|
|
321
|
+
} | null;
|
|
322
|
+
reapprovalNeeded: boolean;
|
|
323
|
+
}>;
|
|
324
|
+
earnings(q?: {
|
|
325
|
+
since?: string;
|
|
326
|
+
before?: string;
|
|
327
|
+
limit?: number;
|
|
328
|
+
}): Promise<any>;
|
|
329
|
+
payouts(q?: {
|
|
330
|
+
before?: string;
|
|
331
|
+
limit?: number;
|
|
332
|
+
}): Promise<any>;
|
|
333
|
+
balance(): Promise<any>;
|
|
334
|
+
/** Your live stream (earnings, payouts, approval changes): reconnects by itself; on {"type":"resync"} read earnings(). */
|
|
335
|
+
/**
|
|
336
|
+
* Your ONE live stream: earnings, payouts and approval changes, and every user's account channels
|
|
337
|
+
* ({type: 'account', externalRef, channel: 'orders' | 'fills' | 'positions' | 'account', kind: 'snapshot' | 'update' |
|
|
338
|
+
* 'event', data}); a snapshot of each first, again after every reconnect. It reconnects by itself; on
|
|
339
|
+
* {type: 'resync'}, read earnings() for anything missed.
|
|
340
|
+
*/
|
|
341
|
+
stream(extra?: Omit<StreamOptions, 'apiKey' | 'apiSecret' | 'url'>): WagmiStream;
|
|
342
|
+
}
|
package/dist/partner.js
ADDED
|
@@ -0,0 +1,239 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* THE BUILDER CLIENT (builder codes): your backend's calls with your builder key (fxp_...), the earnings stream, and the
|
|
3
|
+
* in-app setup of each user: you show their wallet the messages we return, exactly as returned, and pass the signatures
|
|
4
|
+
* back. `onboardUser` does the whole setup with a wallet adapter (viem or ethers), so you never build a signature.
|
|
5
|
+
*
|
|
6
|
+
* const partner = new WagmiPartner({ keyId: process.env.FX_BUILDER_KEY, secret: process.env.FX_BUILDER_SECRET })
|
|
7
|
+
* await partner.createUser({ externalRef: 'user-1842', wallet }) // accountIndex optional: none yet is fine
|
|
8
|
+
* await partner.depositAddress('user-1842', { chainId: '42161', token: 'USDC' }) // their first deposit opens the account
|
|
9
|
+
* const requestKey = await newRequestKey() // keep requestKey.signingKey for this user
|
|
10
|
+
* const setup = await partner.onboardUser('user-1842', { requestKey, wallet: viemWallet(walletClient) })
|
|
11
|
+
* const user = await partner.userClient(setup, requestKey) // a WagmiClient trading as this user
|
|
12
|
+
* await user.placeOrder('BTC', { side: 'buy', orderType: 'market', size: '0.001', price: '99000' }, { partner: 'YOURCODE' })
|
|
13
|
+
*
|
|
14
|
+
* A builder key never trades: every order goes with the user's own key, signed with the request key your app holds for
|
|
15
|
+
* them. Nothing here holds or moves anyone's funds; each user's money stays on their own trading account.
|
|
16
|
+
*/
|
|
17
|
+
import { WagmiClient } from './client.js';
|
|
18
|
+
import { WagmiError } from './action.js';
|
|
19
|
+
import { WagmiStream } from './stream.js';
|
|
20
|
+
const withoutDomainType = (types) => {
|
|
21
|
+
const { EIP712Domain: _drop, ...rest } = types;
|
|
22
|
+
return rest;
|
|
23
|
+
};
|
|
24
|
+
/** A viem WalletClient (with its account, or name one) as a SetupWallet. */
|
|
25
|
+
export function viemWallet(client, account) {
|
|
26
|
+
const acct = account ?? client.account;
|
|
27
|
+
return {
|
|
28
|
+
signMessage: (message) => client.signMessage({ account: acct, message }),
|
|
29
|
+
signTypedData: (t) => client.signTypedData({ account: acct, domain: t.domain, types: withoutDomainType(t.types), primaryType: t.primaryType, message: t.message }),
|
|
30
|
+
sendTransaction: client.sendTransaction
|
|
31
|
+
? (tx) => client.sendTransaction({ account: acct, to: tx.to, data: tx.data, value: BigInt(tx.value), gas: BigInt(tx.gas) })
|
|
32
|
+
: undefined,
|
|
33
|
+
};
|
|
34
|
+
}
|
|
35
|
+
/** An ethers v6 Signer (a Wallet, a BrowserProvider's signer) as a SetupWallet. */
|
|
36
|
+
export function ethersWallet(signer) {
|
|
37
|
+
return {
|
|
38
|
+
signMessage: (message) => signer.signMessage(message),
|
|
39
|
+
signTypedData: (t) => signer.signTypedData(t.domain, withoutDomainType(t.types), t.message),
|
|
40
|
+
sendTransaction: signer.sendTransaction
|
|
41
|
+
? async (tx) => (await signer.sendTransaction({ to: tx.to, data: tx.data, value: BigInt(tx.value), gasLimit: BigInt(tx.gas), chainId: tx.chainId })).hash
|
|
42
|
+
: undefined,
|
|
43
|
+
};
|
|
44
|
+
}
|
|
45
|
+
const hex = (b) => Array.from(b, (x) => x.toString(16).padStart(2, '0')).join('');
|
|
46
|
+
/**
|
|
47
|
+
* A new request key for one user: an Ed25519 key pair your app keeps for them. `publicKey` goes to the setup;
|
|
48
|
+
* `signingKey` (keep it secret, per user) signs each of their orders (WagmiClient's signingKey).
|
|
49
|
+
*/
|
|
50
|
+
export async function newRequestKey() {
|
|
51
|
+
const subtle = globalThis.crypto?.subtle;
|
|
52
|
+
if (!subtle)
|
|
53
|
+
throw new Error('no WebCrypto: Node 20 or later, or a current browser');
|
|
54
|
+
const pair = await subtle.generateKey({ name: 'Ed25519' }, true, ['sign', 'verify']);
|
|
55
|
+
const pub = new Uint8Array(await subtle.exportKey('raw', pair.publicKey));
|
|
56
|
+
const pkcs8 = new Uint8Array(await subtle.exportKey('pkcs8', pair.privateKey));
|
|
57
|
+
return { publicKey: `0x${hex(pub)}`, signingKey: `0x${hex(pkcs8.slice(-32))}` };
|
|
58
|
+
}
|
|
59
|
+
/** Every signature a draft asks for, from the wallet, exactly as returned. */
|
|
60
|
+
export async function signDraft(draft, wallet) {
|
|
61
|
+
const out = {};
|
|
62
|
+
for (const [step, s] of Object.entries(draft.toSign ?? {})) {
|
|
63
|
+
out[step] = s.type === 'eip712' ? await wallet.signTypedData(s.typedData) : await wallet.signMessage(s.message);
|
|
64
|
+
}
|
|
65
|
+
return out;
|
|
66
|
+
}
|
|
67
|
+
export class WagmiPartner {
|
|
68
|
+
http;
|
|
69
|
+
o;
|
|
70
|
+
constructor(options = {}) {
|
|
71
|
+
const o = { ...options, keyId: options.keyId ?? options.apiKey, secret: options.secret ?? options.apiSecret };
|
|
72
|
+
this.o = o;
|
|
73
|
+
const c = { apiKey: o.keyId, apiSecret: o.secret, baseUrl: o.baseUrl, fetch: o.fetch, now: o.now };
|
|
74
|
+
this.http = new WagmiClient(c);
|
|
75
|
+
}
|
|
76
|
+
async call(method, path, query, body) {
|
|
77
|
+
if (!this.o.keyId || !this.o.secret)
|
|
78
|
+
throw new WagmiError('missing_auth', 'the builder calls need keyId and secret (your fxp_ key)');
|
|
79
|
+
const r = await this.http.request(method, path, query, body === undefined ? undefined : JSON.stringify(body));
|
|
80
|
+
if (r.status >= 400)
|
|
81
|
+
throw new WagmiError(r.json?.error ?? `http_${r.status}`, r.json?.message ?? `HTTP ${r.status}`, r.status, r.json);
|
|
82
|
+
return r.json;
|
|
83
|
+
}
|
|
84
|
+
ref(externalRef) { return `/v1/partner/users/${encodeURIComponent(externalRef)}`; }
|
|
85
|
+
/* ── users ───────────────────────────────────────────────────────────────────────────────────── */
|
|
86
|
+
/**
|
|
87
|
+
* A new WAGMI.PRO account for one of your users, linked to your builder code (the same values again: the same user).
|
|
88
|
+
* Leave accountIndex out for a user with no trading account yet: `trading` is 'awaiting_deposit' until their first
|
|
89
|
+
* deposit (depositAddress) creates it, owned by their wallet; then 'ready' and the setup can start.
|
|
90
|
+
*/
|
|
91
|
+
createUser(u) {
|
|
92
|
+
const { accountIndex, ...rest } = u;
|
|
93
|
+
return this.call('POST', '/v1/partner/users', undefined, accountIndex === undefined ? rest : { ...rest, accountIndex: String(accountIndex) });
|
|
94
|
+
}
|
|
95
|
+
users() { return this.call('GET', '/v1/partner/users'); }
|
|
96
|
+
user(externalRef) { return this.call('GET', this.ref(externalRef)); }
|
|
97
|
+
/* ── reports ──────────────────────────────────────────────────────────────────────────────────── */
|
|
98
|
+
/** Volume per user and in total: fills, traded volume and your builder fee, in dollars. from included, to not (UTC days, YYYY-MM-DD); default the last 30 days. */
|
|
99
|
+
volumeReport(q = {}) { return this.call('GET', '/v1/partner/reports/volume', q); }
|
|
100
|
+
/** One row per UTC day (empty days included): fills, volume, your fee, active users, new users. */
|
|
101
|
+
dailyReport(q = {}) { return this.call('GET', '/v1/partner/reports/daily', q); }
|
|
102
|
+
/** Either report as CSV text (a TOTAL row closes the volume report). */
|
|
103
|
+
async reportCsv(kind, q = {}) {
|
|
104
|
+
return (await this.call('GET', `/v1/partner/reports/${kind}`, { ...q, format: 'csv' })).csv;
|
|
105
|
+
}
|
|
106
|
+
/* ── your sandbox ─────────────────────────────────────────────────────────────────────────────── */
|
|
107
|
+
/** Your sandbox's code, and whether this key is the sandbox's. */
|
|
108
|
+
sandbox() { return this.call('GET', '/v1/partner/sandbox'); }
|
|
109
|
+
/**
|
|
110
|
+
* With your LIVE key: your sandbox (made on the first call) and a new sandbox builder key, its secret in this answer
|
|
111
|
+
* only. Every call with that key answers from the sandbox: setups are checked as live, nothing is signed for the
|
|
112
|
+
* exchange, deposited or paid. `new WagmiPartner({ keyId, secret })` with it, and build as usual.
|
|
113
|
+
*/
|
|
114
|
+
createSandboxKey() { return this.call('POST', '/v1/partner/sandbox'); }
|
|
115
|
+
/** Sandbox only: the user's deposit marked as arrived (they get a stand-in trading account, trading 'ready'). */
|
|
116
|
+
sandboxDeposit(externalRef) { return this.call('POST', `${this.ref(externalRef)}/sandbox-deposit`, undefined, {}); }
|
|
117
|
+
/* ── deposits, in your app ───────────────────────────────────────────────────────────────────── */
|
|
118
|
+
/** Every chain and coin a deposit can be sent from, with each one's minimum. */
|
|
119
|
+
depositOptions() { return this.call('GET', '/v1/partner/deposit-options'); }
|
|
120
|
+
/** The user's own deposit address for one chain and coin; it arrives on their own trading account as USDC. */
|
|
121
|
+
depositAddress(externalRef, q) {
|
|
122
|
+
return this.call('POST', `${this.ref(externalRef)}/deposit-address`, undefined, { chainId: String(q.chainId), token: q.token });
|
|
123
|
+
}
|
|
124
|
+
/** What a deposit of `amount` (in the coin's units) would deliver, what it costs and how long it takes. */
|
|
125
|
+
depositQuote(externalRef, q) {
|
|
126
|
+
return this.call('POST', `${this.ref(externalRef)}/deposit-quote`, undefined, { chainId: String(q.chainId), token: q.token, amount: q.amount });
|
|
127
|
+
}
|
|
128
|
+
/* ── withdrawals, by the user's own wallet ───────────────────────────────────────────────────── */
|
|
129
|
+
/**
|
|
130
|
+
* The Ethereum transaction the user's OWN wallet sends to withdraw `amount` USDC. No key you or we hold is involved:
|
|
131
|
+
* the wallet sends it to the exchange, which pays the account's owner, that same wallet, on Ethereum. The wallet pays
|
|
132
|
+
* the gas in ETH (about 132,000 gas). Checked: the account is the wallet's, at least 1 USDC, at most what is free now.
|
|
133
|
+
*/
|
|
134
|
+
withdrawalDraft(externalRef, q) {
|
|
135
|
+
return this.call('POST', `${this.ref(externalRef)}/withdrawals/draft`, undefined, { amount: q.amount });
|
|
136
|
+
}
|
|
137
|
+
/** Hands back the hash the wallet sent: checked on Ethereum, then followed (status on your stream as type 'withdrawal'). */
|
|
138
|
+
async recordWithdrawal(externalRef, q) {
|
|
139
|
+
return (await this.call('POST', `${this.ref(externalRef)}/withdrawals`, undefined, { txHash: q.txHash })).withdrawal;
|
|
140
|
+
}
|
|
141
|
+
/** The user's withdrawals, newest first. */
|
|
142
|
+
async withdrawals(externalRef) {
|
|
143
|
+
return (await this.call('GET', `${this.ref(externalRef)}/withdrawals`)).withdrawals;
|
|
144
|
+
}
|
|
145
|
+
/**
|
|
146
|
+
* The whole withdrawal: the draft, the user's wallet sends it (wallet.sendTransaction: viemWallet or ethersWallet over
|
|
147
|
+
* the user's own wallet), the hash handed back (again for up to a minute while Ethereum has not shown it yet).
|
|
148
|
+
*/
|
|
149
|
+
async withdraw(externalRef, o) {
|
|
150
|
+
if (!o.wallet.sendTransaction)
|
|
151
|
+
throw new WagmiError('wallet_cannot_send', 'this wallet adapter cannot send a transaction: give it sendTransaction');
|
|
152
|
+
const d = await this.withdrawalDraft(externalRef, { amount: o.amount });
|
|
153
|
+
o.onDraft?.(d);
|
|
154
|
+
const txHash = await o.wallet.sendTransaction(d.transaction);
|
|
155
|
+
for (let i = 0;; i++) {
|
|
156
|
+
try {
|
|
157
|
+
return await this.recordWithdrawal(externalRef, { txHash });
|
|
158
|
+
}
|
|
159
|
+
catch (e) {
|
|
160
|
+
if (!(e instanceof WagmiError) || e.code !== 'tx_not_seen_yet' || i >= 12)
|
|
161
|
+
throw e;
|
|
162
|
+
await new Promise((r) => setTimeout(r, 5_000));
|
|
163
|
+
}
|
|
164
|
+
}
|
|
165
|
+
}
|
|
166
|
+
/* ── the setup, in your app ──────────────────────────────────────────────────────────────────── */
|
|
167
|
+
setupDraft(externalRef, q) {
|
|
168
|
+
return this.call('GET', `${this.ref(externalRef)}/onboarding`, q);
|
|
169
|
+
}
|
|
170
|
+
sendSetup(externalRef, draftId, signatures) {
|
|
171
|
+
return this.call('POST', `${this.ref(externalRef)}/onboarding`, undefined, { draftId, signatures });
|
|
172
|
+
}
|
|
173
|
+
/** A new API key for a set-up user (the old one stops at once); its secret is in this answer only. */
|
|
174
|
+
newUserKey(externalRef) { return this.call('POST', `${this.ref(externalRef)}/onboarding/key`); }
|
|
175
|
+
/**
|
|
176
|
+
* The whole setup: the draft, the wallet's signatures, sent back, again for any step still open (a user who stopped
|
|
177
|
+
* half-way picks up where they were). Answers the finished setup, with the user's own API key (its secret once).
|
|
178
|
+
*/
|
|
179
|
+
async onboardUser(externalRef, o) {
|
|
180
|
+
for (let round = 0; round < 4; round++) {
|
|
181
|
+
const draft = await this.setupDraft(externalRef, { requestKey: o.requestKey.publicKey, approvalExpiry: o.approvalExpiry, ipAllowlist: o.ipAllowlist });
|
|
182
|
+
if (draft.status === 'ready' || !draft.draftId || !draft.toSign || !Object.keys(draft.toSign).length)
|
|
183
|
+
return draft;
|
|
184
|
+
o.onDraft?.(draft);
|
|
185
|
+
const done = await this.sendSetup(externalRef, draft.draftId, await signDraft(draft, o.wallet));
|
|
186
|
+
if (done.status === 'ready' || done.apiKey)
|
|
187
|
+
return done;
|
|
188
|
+
}
|
|
189
|
+
throw new WagmiError('setup_incomplete', 'the setup did not finish after several rounds; read user() for the step that is open');
|
|
190
|
+
}
|
|
191
|
+
/** A WagmiClient trading as this user: their API key from the setup and the request key you keep for them. */
|
|
192
|
+
async userClient(setup, requestKey, o = {}) {
|
|
193
|
+
const k = 'apiKey' in setup ? setup.apiKey : setup;
|
|
194
|
+
if (!k)
|
|
195
|
+
throw new WagmiError('missing_key', 'no API key in this setup: it is not finished, or its secret was already handed out');
|
|
196
|
+
const { externalRef, ...extra } = o;
|
|
197
|
+
// The grant id: in the finished setup, else your user read (externalRef), else the key's own Agent Key read.
|
|
198
|
+
let grantId = setup.grantId ?? null;
|
|
199
|
+
if (!grantId && externalRef)
|
|
200
|
+
grantId = (await this.user(externalRef))?.grantId ?? null;
|
|
201
|
+
if (!grantId)
|
|
202
|
+
grantId = (await new WagmiClient({ ...extra, baseUrl: this.o.baseUrl, fetch: this.o.fetch, apiKey: k.keyId, apiSecret: k.secret }).agentKey().catch(() => null))?.grantId ?? null;
|
|
203
|
+
if (!grantId)
|
|
204
|
+
throw new WagmiError('no_grant', 'this user has no Agent Key approval yet: finish the setup');
|
|
205
|
+
return new WagmiClient({ ...extra, baseUrl: this.o.baseUrl, fetch: this.o.fetch, apiKey: k.keyId, apiSecret: k.secret, signingKey: requestKey.signingKey, grantId });
|
|
206
|
+
}
|
|
207
|
+
/* ── your fee and its re-approval ────────────────────────────────────────────────────────────── */
|
|
208
|
+
/** Your builder code itself: code, name, status, whether this key is a sandbox's, your fee, when you may next change it, and the account your earnings are paid to. */
|
|
209
|
+
me() { return this.call('GET', '/v1/partner/me'); }
|
|
210
|
+
fee() { return this.call('GET', '/v1/partner/fees'); }
|
|
211
|
+
/** Your fee per kind and side (millionths). A raise needs each user's new approval; a cut applies at once. Once a day. */
|
|
212
|
+
setFee(fee) { return this.call('PUT', '/v1/partner/fees', undefined, fee); }
|
|
213
|
+
approvalDraft(externalRef, q = {}) { return this.call('GET', `${this.ref(externalRef)}/approval/message`, q); }
|
|
214
|
+
sendApproval(externalRef, draftId, signatures) { return this.call('POST', `${this.ref(externalRef)}/approval`, undefined, { draftId, signatures }); }
|
|
215
|
+
/** The re-approval in one call: the draft, the wallet's two signatures, sent. */
|
|
216
|
+
async reapprove(externalRef, o) {
|
|
217
|
+
const d = await this.approvalDraft(externalRef, { approvalExpiry: o.approvalExpiry });
|
|
218
|
+
if (!d.draftId)
|
|
219
|
+
throw new WagmiError('no_draft', 'no re-approval draft was returned');
|
|
220
|
+
return this.sendApproval(externalRef, d.draftId, await signDraft(d, o.wallet));
|
|
221
|
+
}
|
|
222
|
+
/** Revoke the user's approval: answers {revoked: true, approval (the status now, null when none is active), reapprovalNeeded}. */
|
|
223
|
+
revokeApproval(externalRef) { return this.call('DELETE', `${this.ref(externalRef)}/approval`); }
|
|
224
|
+
/* ── what you earn ───────────────────────────────────────────────────────────────────────────── */
|
|
225
|
+
earnings(q = {}) { return this.call('GET', '/v1/partner/earnings', q); }
|
|
226
|
+
payouts(q = {}) { return this.call('GET', '/v1/partner/payouts', q); }
|
|
227
|
+
balance() { return this.call('GET', '/v1/partner/balance'); }
|
|
228
|
+
/** Your live stream (earnings, payouts, approval changes): reconnects by itself; on {"type":"resync"} read earnings(). */
|
|
229
|
+
/**
|
|
230
|
+
* Your ONE live stream: earnings, payouts and approval changes, and every user's account channels
|
|
231
|
+
* ({type: 'account', externalRef, channel: 'orders' | 'fills' | 'positions' | 'account', kind: 'snapshot' | 'update' |
|
|
232
|
+
* 'event', data}); a snapshot of each first, again after every reconnect. It reconnects by itself; on
|
|
233
|
+
* {type: 'resync'}, read earnings() for anything missed.
|
|
234
|
+
*/
|
|
235
|
+
stream(extra = {}) {
|
|
236
|
+
const base = (this.o.wsUrl ?? `${(this.o.baseUrl ?? 'https://api.wagmi.pro').replace(/\/$/, '').replace(/^http/, 'ws')}/v1/ws`);
|
|
237
|
+
return new WagmiStream({ ...extra, url: base, apiKey: this.o.keyId, apiSecret: this.o.secret });
|
|
238
|
+
}
|
|
239
|
+
}
|
package/dist/sign.d.ts
ADDED
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
export declare const REQUEST_PREFIX = "wagmipro-agent-key/request/v1";
|
|
2
|
+
export declare function sha256Hex(text: string): Promise<string>;
|
|
3
|
+
/** The text the signing key signs: five lines joined with "\n", no newline at the end. */
|
|
4
|
+
export declare function requestMessage(grantId: string, ts: number, nonce: string, action: string): Promise<string>;
|
|
5
|
+
/** A random request nonce: 32 lowercase hex characters. */
|
|
6
|
+
export declare function newNonce(): string;
|
|
7
|
+
/** auth.sig: the Ed25519 signature of the request message, 128 lowercase hex characters. */
|
|
8
|
+
export declare function signRequest(signingKey: string, message: string): Promise<string>;
|
|
9
|
+
/** X-FX-SIGNATURE: hex HMAC-SHA256(secret, timestamp + method + pathWithQuery + body). */
|
|
10
|
+
export declare function hmacHex(secret: string, text: string): Promise<string>;
|
|
11
|
+
export declare function keyHeaders(apiKey: string, secret: string, method: string, pathWithQuery: string, body: string, ts: number): Promise<Record<string, string>>;
|
package/dist/sign.js
ADDED
|
@@ -0,0 +1,62 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The two signatures of a WAGMI.PRO API trading request (signing format v1), with WebCrypto only (Node 20+, browsers):
|
|
3
|
+
* the REQUEST signature, with your signing key (Ed25519), over the action: what the Agent Key checks
|
|
4
|
+
* the KEY signature, HMAC-SHA256 with your API secret, over the HTTP request: what the API checks
|
|
5
|
+
*/
|
|
6
|
+
const enc = new TextEncoder();
|
|
7
|
+
const hex = (b) => Array.from(b instanceof Uint8Array ? b : new Uint8Array(b), (x) => x.toString(16).padStart(2, '0')).join('');
|
|
8
|
+
const unhex = (s) => {
|
|
9
|
+
const h = s.startsWith('0x') ? s.slice(2) : s;
|
|
10
|
+
if (!/^([0-9a-fA-F]{2})*$/.test(h))
|
|
11
|
+
throw new Error('not hex');
|
|
12
|
+
return Uint8Array.from(h.match(/../g) ?? [], (x) => parseInt(x, 16));
|
|
13
|
+
};
|
|
14
|
+
const subtle = () => {
|
|
15
|
+
const s = globalThis.crypto?.subtle;
|
|
16
|
+
if (!s)
|
|
17
|
+
throw new Error('WebCrypto is not available: Node 20 or later, or a current browser');
|
|
18
|
+
return s;
|
|
19
|
+
};
|
|
20
|
+
export const REQUEST_PREFIX = 'wagmipro-agent-key/request/v1';
|
|
21
|
+
/** The PKCS #8 prefix of an Ed25519 private key; the 32 byte seed follows it. */
|
|
22
|
+
const PKCS8_ED25519 = unhex('302e020100300506032b657004220420');
|
|
23
|
+
export async function sha256Hex(text) {
|
|
24
|
+
return hex(await subtle().digest('SHA-256', enc.encode(text)));
|
|
25
|
+
}
|
|
26
|
+
/** The text the signing key signs: five lines joined with "\n", no newline at the end. */
|
|
27
|
+
export async function requestMessage(grantId, ts, nonce, action) {
|
|
28
|
+
return [REQUEST_PREFIX, grantId, String(ts), nonce, await sha256Hex(action)].join('\n');
|
|
29
|
+
}
|
|
30
|
+
/** A random request nonce: 32 lowercase hex characters. */
|
|
31
|
+
export function newNonce() {
|
|
32
|
+
const b = new Uint8Array(16);
|
|
33
|
+
globalThis.crypto.getRandomValues(b);
|
|
34
|
+
return hex(b);
|
|
35
|
+
}
|
|
36
|
+
const keyCache = new Map();
|
|
37
|
+
function signingKeyOf(seedHex) {
|
|
38
|
+
let k = keyCache.get(seedHex);
|
|
39
|
+
if (!k) {
|
|
40
|
+
const seed = unhex(seedHex);
|
|
41
|
+
if (seed.length !== 32)
|
|
42
|
+
throw new Error('the signing key is a 32 byte Ed25519 seed in hex (0x and 64 hex characters)');
|
|
43
|
+
const der = new Uint8Array(PKCS8_ED25519.length + 32);
|
|
44
|
+
der.set(PKCS8_ED25519);
|
|
45
|
+
der.set(seed, PKCS8_ED25519.length);
|
|
46
|
+
k = subtle().importKey('pkcs8', der, { name: 'Ed25519' }, false, ['sign']);
|
|
47
|
+
keyCache.set(seedHex, k);
|
|
48
|
+
}
|
|
49
|
+
return k;
|
|
50
|
+
}
|
|
51
|
+
/** auth.sig: the Ed25519 signature of the request message, 128 lowercase hex characters. */
|
|
52
|
+
export async function signRequest(signingKey, message) {
|
|
53
|
+
return hex(await subtle().sign({ name: 'Ed25519' }, await signingKeyOf(signingKey), enc.encode(message)));
|
|
54
|
+
}
|
|
55
|
+
/** X-FX-SIGNATURE: hex HMAC-SHA256(secret, timestamp + method + pathWithQuery + body). */
|
|
56
|
+
export async function hmacHex(secret, text) {
|
|
57
|
+
const k = await subtle().importKey('raw', enc.encode(secret), { name: 'HMAC', hash: 'SHA-256' }, false, ['sign']);
|
|
58
|
+
return hex(await subtle().sign('HMAC', k, enc.encode(text)));
|
|
59
|
+
}
|
|
60
|
+
export async function keyHeaders(apiKey, secret, method, pathWithQuery, body, ts) {
|
|
61
|
+
return { 'X-FX-KEY': apiKey, 'X-FX-TIMESTAMP': String(ts), 'X-FX-SIGNATURE': await hmacHex(secret, `${ts}${method}${pathWithQuery}${body}`) };
|
|
62
|
+
}
|