@totalis/hip4-client 0.0.0-stage → 0.65.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 (74) hide show
  1. package/CHANGELOG.md +1541 -0
  2. package/LICENSE +202 -0
  3. package/README.md +143 -2
  4. package/dist/api-keys.d.ts +118 -0
  5. package/dist/api-keys.js +104 -0
  6. package/dist/audience-contract.d.ts +52 -0
  7. package/dist/audience-contract.js +1 -0
  8. package/dist/base.d.ts +41 -0
  9. package/dist/base.js +60 -0
  10. package/dist/client.d.ts +16 -0
  11. package/dist/client.js +15 -0
  12. package/dist/controller.d.ts +50 -0
  13. package/dist/controller.js +60 -0
  14. package/dist/errors.d.ts +3 -0
  15. package/dist/errors.js +3 -0
  16. package/dist/flow-errors.d.ts +61 -0
  17. package/dist/flow-errors.js +70 -0
  18. package/dist/generated/account-read.d.ts +2009 -0
  19. package/dist/generated/account-read.js +1 -0
  20. package/dist/generated/api-keys.d.ts +1303 -0
  21. package/dist/generated/api-keys.js +1 -0
  22. package/dist/generated/browse.d.ts +938 -0
  23. package/dist/generated/browse.js +1 -0
  24. package/dist/generated/client.d.ts +73 -0
  25. package/dist/generated/client.js +1 -0
  26. package/dist/generated/errors.d.ts +404 -0
  27. package/dist/generated/errors.js +1342 -0
  28. package/dist/generated/maker.d.ts +47 -0
  29. package/dist/generated/maker.js +1 -0
  30. package/dist/generated/openapi.d.ts +8044 -0
  31. package/dist/generated/openapi.js +1 -0
  32. package/dist/generated/operator.d.ts +7 -0
  33. package/dist/generated/operator.js +1 -0
  34. package/dist/generated/realtime.d.ts +1416 -0
  35. package/dist/generated/realtime.js +1 -0
  36. package/dist/generated/vault-abi.d.ts +39 -0
  37. package/dist/generated/vault-abi.js +56 -0
  38. package/dist/generated/version.d.ts +23 -0
  39. package/dist/generated/version.js +143 -0
  40. package/dist/hypercore.d.ts +111 -0
  41. package/dist/hypercore.js +132 -0
  42. package/dist/maker.d.ts +205 -0
  43. package/dist/maker.js +608 -0
  44. package/dist/money.d.ts +59 -0
  45. package/dist/money.js +66 -0
  46. package/dist/operator.d.ts +4 -0
  47. package/dist/operator.js +4 -0
  48. package/dist/pagination.d.ts +20 -0
  49. package/dist/pagination.js +27 -0
  50. package/dist/partner.d.ts +59 -0
  51. package/dist/partner.js +57 -0
  52. package/dist/realtime.d.ts +19 -0
  53. package/dist/realtime.js +10 -0
  54. package/dist/request.d.ts +112 -0
  55. package/dist/request.js +187 -0
  56. package/dist/signer.d.ts +51 -0
  57. package/dist/signer.js +90 -0
  58. package/dist/stream.d.ts +133 -0
  59. package/dist/stream.js +318 -0
  60. package/dist/totalis.d.ts +656 -0
  61. package/dist/totalis.js +1160 -0
  62. package/dist/typed-data.d.ts +330 -0
  63. package/dist/typed-data.js +340 -0
  64. package/dist/ui.d.ts +54 -0
  65. package/dist/ui.js +77 -0
  66. package/dist/wallet-session.d.ts +45 -0
  67. package/dist/wallet-session.js +61 -0
  68. package/examples/browser-wallet.html +69 -0
  69. package/examples/browser-wallet.mjs +57 -0
  70. package/examples/node-bot.mjs +57 -0
  71. package/examples/onboard.mjs +132 -0
  72. package/examples/partner-frontend.mjs +44 -0
  73. package/examples/partner-server.mjs +22 -0
  74. package/package.json +104 -4
package/LICENSE ADDED
@@ -0,0 +1,202 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright [yyyy] [name of copyright owner]
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
package/README.md CHANGED
@@ -1,3 +1,144 @@
1
- # Temporary Holding Version
1
+ # `@totalis/hip4-client`
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ The official TypeScript SDK for [Totalis](https://totalis.trade) on Hyperliquid (HIP-4).
4
+
5
+ - **Typed clients** for every REST route, generated from the API contract
6
+ - **Taker and maker flows** that run end to end: open a position, cash out, withdraw, quote, answer acceptances
7
+ - **A realtime stream** that resumes from its cursor and reconnects on its own
8
+ - **Builders for every signed message** (EIP-712, USDC authorizations, the Hyperliquid bridge)
9
+ - **Safe retries**: every command keeps one `Idempotency-Key` and is resent byte for byte, so a retry never trades twice
10
+
11
+ It never holds a key. Every signature goes to the signer you pass in: a viem account or wallet client, an
12
+ EIP-1193 provider such as `window.ethereum`, or an ethers signer. It is ESM, runs in browsers and Node 22 or
13
+ later, and has no wallet dependency.
14
+
15
+ **Documentation: [docs.totalis.trade/hyperliquid/sdk](https://docs.totalis.trade/hyperliquid/sdk)**
16
+
17
+ ## Install
18
+
19
+ ```bash
20
+ npm install @totalis/hip4-client viem
21
+ ```
22
+
23
+ `viem` is optional. The examples below use it to turn a private key into a signer.
24
+
25
+ ## Make a first call
26
+
27
+ Create a `ttk_` API key for your account
28
+ ([Authentication](https://docs.totalis.trade/hyperliquid/authentication)), then:
29
+
30
+ ```ts
31
+ import { createClient, unwrap } from "@totalis/hip4-client";
32
+
33
+ const client = createClient("production", { accessToken: process.env.TOTALIS_API_KEY! });
34
+
35
+ const me = unwrap(await client.GET("/v1/me"));
36
+ console.log(me.wallet);
37
+ ```
38
+
39
+ Every route in the [API reference](https://docs.totalis.trade/hyperliquid/api-reference/introduction) is on
40
+ `client`, typed. `unwrap` returns the body or throws an `ApiError`.
41
+
42
+ ## Open and cash out a position
43
+
44
+ ```ts
45
+ import { createTotalis } from "@totalis/hip4-client";
46
+ import { privateKeyToAccount } from "viem/accounts";
47
+
48
+ const totalis = createTotalis({
49
+ environment: "production",
50
+ accessToken: process.env.TOTALIS_API_KEY!,
51
+ signer: privateKeyToAccount(process.env.TOTALIS_WALLET_KEY as `0x${string}`),
52
+ });
53
+
54
+ const opened = await totalis.openPosition({
55
+ legs: [{ outcome_id: "13160", side: "YES" }],
56
+ stake: 5_000_000n, // 5 USDC
57
+ });
58
+
59
+ if (opened.operationId) {
60
+ const { status } = await totalis.waitForOperation(opened.operationId);
61
+ if (status === "COMMITTED") {
62
+ const sale = await totalis.cashOut({ positionId: opened.positionId });
63
+ }
64
+ }
65
+
66
+ totalis.close();
67
+ ```
68
+
69
+ `openPosition` creates the RFQ, takes the best quote, signs the acceptance and funds any shortfall from the
70
+ wallet. Only `COMMITTED` means the trade happened. A decided position settles and pays out on its own.
71
+
72
+ ## Make markets
73
+
74
+ ```ts
75
+ import { createMaker, type MakerAcceptance } from "@totalis/hip4-client/maker";
76
+ import { privateKeyToAccount } from "viem/accounts";
77
+
78
+ const maker = createMaker({
79
+ environment: "production",
80
+ apiKey: process.env.TOTALIS_MAKER_KEY!,
81
+ makerId: process.env.TOTALIS_MAKER_ID!,
82
+ signer: privateKeyToAccount(process.env.TOTALIS_WALLET_KEY as `0x${string}`),
83
+ });
84
+
85
+ maker.onRfq(async (rfq) => {
86
+ if (rfq.kind === "ENTRY") {
87
+ await maker.quote(rfq, { payout: (BigInt(rfq.stake) * 18n) / 10n }); // placeholder price
88
+ }
89
+ });
90
+
91
+ // Re-check your price and capital before you commit. This placeholder only checks the deadline.
92
+ const stillGood = async (acceptance: MakerAcceptance) => Date.parse(acceptance.deadline) > maker.stream.serverNow();
93
+
94
+ maker.onAcceptance(async (acceptance) => ((await stillGood(acceptance)) ? "CONFIRM" : "DECLINE"));
95
+ ```
96
+
97
+ Set up the maker first ([Market making](https://docs.totalis.trade/hyperliquid/guides/market-making)).
98
+ `examples/onboard.mjs` onboards a maker headless, and `examples/node-bot.mjs` is a fuller bot.
99
+
100
+ ## Environments
101
+
102
+ | `environment` | REST | WebSocket |
103
+ | --- | --- | --- |
104
+ | `"production"` | `https://hip4-api.totalis.trade` | `wss://hip4-ws.totalis.trade` |
105
+ | `"staging"` | `https://hip4-api-staging.totalis.trade` | `wss://hip4-ws-staging.totalis.trade` |
106
+
107
+ Staging runs on Hyperliquid testnet ([Staging](https://docs.totalis.trade/hyperliquid/build/staging)). Pass
108
+ `baseUrl` to point at another origin.
109
+
110
+ Money is atomic USDC (6 decimals): `25_000_000n` is 25 USDC.
111
+
112
+ ## Entry points
113
+
114
+ | Import | Holds |
115
+ | --- | --- |
116
+ | `@totalis/hip4-client` | `createClient`, `createTotalis`, errors, pagination, `TotalisStream`, the money and UI helpers |
117
+ | `.../maker` | `createMaker`, `createMakerClient`, maker onboarding |
118
+ | `.../wallet-session` | `signInWithWallet`, `signOutWallet` |
119
+ | `.../partner` | `signAdmissionConsent`, `createPartnerServer` |
120
+ | `.../api-keys` | Issuing, rotating, listing and revoking keys |
121
+ | `.../typed-data` | Builders and hashing for every signed message |
122
+ | `.../signer` | `toTotalisSigner` |
123
+ | `.../realtime` | `TotalisStream` and the frame types |
124
+ | `.../errors` | The error registry, `ApiError`, `NetworkError` |
125
+
126
+ ## Examples
127
+
128
+ The package ships runnable examples in `examples/`:
129
+
130
+ | File | Shows |
131
+ | --- | --- |
132
+ | `onboard.mjs` | Headless maker onboarding: sign in, open and admit the maker, issue its key, deposit, start the bot |
133
+ | `node-bot.mjs` | A maker bot that quotes entries, buys back cash-outs and confirms acceptances |
134
+ | `browser-wallet.html`, `browser-wallet.mjs` | Opening and cashing out from an injected wallet, with no bundler |
135
+ | `partner-frontend.mjs` | A partner page that collects consent, signs a wallet in and trades |
136
+ | `partner-server.mjs` | A partner server that admits a wallet with its `tpk_` key |
137
+
138
+ ## Versioning
139
+
140
+ The SDK follows semver. See [`CHANGELOG.md`](CHANGELOG.md).
141
+
142
+ ## License
143
+
144
+ Apache-2.0
@@ -0,0 +1,118 @@
1
+ import { type ApiClientOptions, type PublicEnvironment } from "./base.js";
2
+ import type { components, paths } from "./generated/api-keys.js";
3
+ import type { TotalisSigner } from "./signer.js";
4
+ export type { components, operations, paths } from "./generated/api-keys.js";
5
+ /**
6
+ * Key lifecycle uses a session: an app session in a browser, or a wallet
7
+ * session (`signInWithWallet`) headless, with its Origin as a header. Secrets
8
+ * are returned once; POST retries cannot recover them.
9
+ */
10
+ export declare function createApiKeyClient(environment: PublicEnvironment, options?: ApiClientOptions): import("openapi-fetch").Client<paths, `${string}/${string}`>;
11
+ export type ApiKeyClient = ReturnType<typeof createApiKeyClient>;
12
+ type Schemas = components["schemas"];
13
+ export type KeyChallenge = Schemas["KeyChallenge"];
14
+ /** Whose key: the session's personal account, or a maker vault (signed by its controller). */
15
+ export type KeyAccount = {
16
+ readonly maker?: string;
17
+ };
18
+ export type KeyScope = Schemas["Scope"];
19
+ export type KeyMetadata = Schemas["KeyMetadata"];
20
+ /**
21
+ * The maker scopes for a quoting bot: it reads RFQs, quotes and confirms, and
22
+ * reads its capital, but none of these move vault money, so a leaked key can
23
+ * quote but never withdraw.
24
+ */
25
+ export declare const QUOTING_BOT_SCOPES: readonly ["rfq:read", "quote:read", "quote:write", "replay:read", "vault:read"];
26
+ /** The maker scopes for lowering collateral (`reduceCollateral`). Keep this key apart from the quoting bot's. */
27
+ export declare const COLLATERAL_SCOPES: readonly ["vault:read", "vault:write", "operations:submit"];
28
+ /**
29
+ * Check a challenge before the owner signs it: the exact issue_key template,
30
+ * signed by the expected owner, for this account and action, granting exactly
31
+ * `scopes` when given, and not expired.
32
+ */
33
+ export declare function checkKeyChallenge(challenge: KeyChallenge, expected: {
34
+ readonly owner: string;
35
+ readonly action: "create" | "rotate";
36
+ readonly maker?: string | undefined;
37
+ readonly keyId?: string | undefined;
38
+ readonly scopes?: readonly string[] | undefined;
39
+ }, now?: number): void;
40
+ /**
41
+ * Issue a scoped `ttk_` key through the owner-signed challenge (TT-1791): ask
42
+ * for a challenge, check it, personal_sign it with the account owner, then
43
+ * create the key. The secret is returned once; a lost response surfaces
44
+ * SECRET_UNAVAILABLE (list, revoke and replace, never retry).
45
+ */
46
+ export declare function issueApiKey(client: ApiKeyClient, owner: TotalisSigner, request: Schemas["UnsignedCreateKeyRequest"] & KeyAccount): Promise<{
47
+ readonly key: {
48
+ readonly id: components["schemas"]["Uuid"];
49
+ readonly account: {
50
+ readonly kind: "PARTICIPANT";
51
+ readonly id: components["schemas"]["Uuid"];
52
+ };
53
+ readonly environment: "development" | "staging" | "production";
54
+ readonly label: components["schemas"]["KeyLabel"];
55
+ readonly scopes: readonly ("identity:read" | "account:read" | "account:stream" | "rfq:read" | "rfq:write" | "quote:write" | "quote:read" | "replay:read" | "vault:read" | "vault:write" | "quote:accept" | "position:cashout" | "funding:deposit" | "funding:withdraw" | "sponsorship:use" | "maker:access:read" | "operations:read" | "operations:submit")[];
56
+ readonly status: "ACTIVE";
57
+ readonly created_at: components["schemas"]["Timestamp"];
58
+ readonly expires_at: components["schemas"]["Timestamp"] | null;
59
+ };
60
+ readonly secret: string;
61
+ } | {
62
+ readonly key: {
63
+ readonly id: components["schemas"]["Uuid"];
64
+ readonly account: {
65
+ readonly kind: "MAKER";
66
+ readonly id: components["schemas"]["NonZeroUInt64String"];
67
+ readonly chain_id: "998" | "999";
68
+ readonly vault_address: components["schemas"]["LowercaseNonZeroAddress"];
69
+ };
70
+ readonly environment: "development" | "staging" | "production";
71
+ readonly label: components["schemas"]["KeyLabel"];
72
+ readonly scopes: readonly ("identity:read" | "account:read" | "account:stream" | "rfq:read" | "rfq:write" | "quote:write" | "quote:read" | "replay:read" | "vault:read" | "vault:write" | "quote:accept" | "position:cashout" | "funding:deposit" | "funding:withdraw" | "sponsorship:use" | "maker:access:read" | "operations:read" | "operations:submit")[];
73
+ readonly status: "ACTIVE";
74
+ readonly created_at: components["schemas"]["Timestamp"];
75
+ readonly expires_at: components["schemas"]["Timestamp"] | null;
76
+ };
77
+ readonly secret: string;
78
+ }>;
79
+ /** Rotate a key the same way: the owner signs a ROTATE challenge for that key. */
80
+ export declare function rotateApiKey(client: ApiKeyClient, owner: TotalisSigner, keyId: string, request?: Schemas["UnsignedRotateKeyRequest"] & KeyAccount): Promise<{
81
+ readonly key: {
82
+ readonly id: components["schemas"]["Uuid"];
83
+ readonly account: {
84
+ readonly kind: "PARTICIPANT";
85
+ readonly id: components["schemas"]["Uuid"];
86
+ };
87
+ readonly environment: "development" | "staging" | "production";
88
+ readonly label: components["schemas"]["KeyLabel"];
89
+ readonly scopes: readonly ("identity:read" | "account:read" | "account:stream" | "rfq:read" | "rfq:write" | "quote:write" | "quote:read" | "replay:read" | "vault:read" | "vault:write" | "quote:accept" | "position:cashout" | "funding:deposit" | "funding:withdraw" | "sponsorship:use" | "maker:access:read" | "operations:read" | "operations:submit")[];
90
+ readonly status: "ACTIVE";
91
+ readonly created_at: components["schemas"]["Timestamp"];
92
+ readonly expires_at: components["schemas"]["Timestamp"] | null;
93
+ readonly rotated_from: string;
94
+ };
95
+ readonly secret: string;
96
+ } | {
97
+ readonly key: {
98
+ readonly id: components["schemas"]["Uuid"];
99
+ readonly account: {
100
+ readonly kind: "MAKER";
101
+ readonly id: components["schemas"]["NonZeroUInt64String"];
102
+ readonly chain_id: "998" | "999";
103
+ readonly vault_address: components["schemas"]["LowercaseNonZeroAddress"];
104
+ };
105
+ readonly environment: "development" | "staging" | "production";
106
+ readonly label: components["schemas"]["KeyLabel"];
107
+ readonly scopes: readonly ("identity:read" | "account:read" | "account:stream" | "rfq:read" | "rfq:write" | "quote:write" | "quote:read" | "replay:read" | "vault:read" | "vault:write" | "quote:accept" | "position:cashout" | "funding:deposit" | "funding:withdraw" | "sponsorship:use" | "maker:access:read" | "operations:read" | "operations:submit")[];
108
+ readonly status: "ACTIVE";
109
+ readonly created_at: components["schemas"]["Timestamp"];
110
+ readonly expires_at: components["schemas"]["Timestamp"] | null;
111
+ readonly rotated_from: string;
112
+ };
113
+ readonly secret: string;
114
+ }>;
115
+ /** Every key of the account, or of `maker`, oldest first, revoked and expired ones included, read page by page. */
116
+ export declare function listApiKeys(client: ApiKeyClient, account?: KeyAccount): Promise<KeyMetadata[]>;
117
+ /** Revoke a key at once, with any key it is rotating to or from. No signature is needed, and revoking a revoked key succeeds again. */
118
+ export declare function revokeApiKey(client: ApiKeyClient, keyId: string, account?: KeyAccount): Promise<void>;
@@ -0,0 +1,104 @@
1
+ import { audienceClient } from "./base.js";
2
+ import { items } from "./pagination.js";
3
+ import { ApiError, unwrap, uuidv7 } from "./request.js";
4
+ import { parseIssueKeyMessage } from "./typed-data.js";
5
+ /**
6
+ * Key lifecycle uses a session: an app session in a browser, or a wallet
7
+ * session (`signInWithWallet`) headless, with its Origin as a header. Secrets
8
+ * are returned once; POST retries cannot recover them.
9
+ */
10
+ export function createApiKeyClient(environment, options) {
11
+ return audienceClient(environment, options);
12
+ }
13
+ /**
14
+ * The maker scopes for a quoting bot: it reads RFQs, quotes and confirms, and
15
+ * reads its capital, but none of these move vault money, so a leaked key can
16
+ * quote but never withdraw.
17
+ */
18
+ export const QUOTING_BOT_SCOPES = ["rfq:read", "quote:read", "quote:write", "replay:read", "vault:read"];
19
+ /** The maker scopes for lowering collateral (`reduceCollateral`). Keep this key apart from the quoting bot's. */
20
+ export const COLLATERAL_SCOPES = ["vault:read", "vault:write", "operations:submit"];
21
+ /**
22
+ * Check a challenge before the owner signs it: the exact issue_key template,
23
+ * signed by the expected owner, for this account and action, granting exactly
24
+ * `scopes` when given, and not expired.
25
+ */
26
+ export function checkKeyChallenge(challenge, expected, now = Date.now()) {
27
+ const message = parseIssueKeyMessage(challenge.message);
28
+ const path = expected.maker === undefined ? "/v1/me/api-keys" : `/v1/makers/${expected.maker}/api-keys`;
29
+ const scopePrefix = "urn:totalis:scope:";
30
+ const granted = message.resources.filter((resource) => resource.startsWith(scopePrefix)).map((resource) => resource.slice(scopePrefix.length)).sort().join(" ");
31
+ const wanted = expected.scopes && [...expected.scopes].sort().join(" ");
32
+ const problems = [
33
+ message.address.toLowerCase() !== challenge.owner && "message address is not the challenge owner",
34
+ challenge.owner !== expected.owner.toLowerCase() && `challenge owner ${challenge.owner} is not the signer ${expected.owner}`,
35
+ !message.uri.endsWith(path) && `message is for ${message.uri}, not ${path}`,
36
+ expected.maker !== undefined && !message.resources.includes(`urn:totalis:account:maker:${expected.maker}`) && "message is for another account",
37
+ !message.resources.includes(`urn:totalis:action:${expected.action}`) && `message is not for ${expected.action}`,
38
+ expected.keyId !== undefined && !message.resources.includes(`urn:totalis:key:${expected.keyId}`) && "message is for another key",
39
+ wanted !== undefined && granted !== wanted && `message grants ${granted || "no scopes"}, not ${wanted}`,
40
+ message.requestId !== challenge.challenge_id && "message is for another challenge",
41
+ Date.parse(message.expirationTime) <= now && "challenge expired",
42
+ ].filter(Boolean);
43
+ if (problems.length > 0)
44
+ throw new Error(`refusing to sign the key challenge: ${problems.join("; ")}`);
45
+ }
46
+ /**
47
+ * Steps 1 and 2 for both create and rotate: ask the account's challenge route,
48
+ * check the challenge, and have the owner personal_sign it.
49
+ */
50
+ async function ownerProof(client, owner, maker, request) {
51
+ const params = { header: { "Idempotency-Key": uuidv7() } };
52
+ const challenge = unwrap(maker === undefined
53
+ ? await client.POST("/v1/me/api-key-challenges", { params, body: request })
54
+ : await client.POST("/v1/makers/{maker_id}/api-key-challenges", { params: { ...params, path: { maker_id: maker } }, body: request }));
55
+ checkKeyChallenge(challenge, {
56
+ owner: await owner.address(), action: request.action === "CREATE" ? "create" : "rotate", maker,
57
+ keyId: request.action === "ROTATE" ? request.key_id : undefined,
58
+ scopes: request.action === "CREATE" ? request.request.scopes : undefined,
59
+ });
60
+ return { challenge_id: challenge.challenge_id, signature: await owner.signMessage(challenge.message) };
61
+ }
62
+ /**
63
+ * Issue a scoped `ttk_` key through the owner-signed challenge (TT-1791): ask
64
+ * for a challenge, check it, personal_sign it with the account owner, then
65
+ * create the key. The secret is returned once; a lost response surfaces
66
+ * SECRET_UNAVAILABLE (list, revoke and replace, never retry).
67
+ */
68
+ export async function issueApiKey(client, owner, request) {
69
+ const { maker, ...body } = request;
70
+ const proof = await ownerProof(client, owner, maker, { action: "CREATE", request: body });
71
+ const params = { header: { "Idempotency-Key": uuidv7() } };
72
+ return maker === undefined
73
+ ? unwrap(await client.POST("/v1/me/api-keys", { params, body: { ...body, proof } }))
74
+ : unwrap(await client.POST("/v1/makers/{maker_id}/api-keys", { params: { ...params, path: { maker_id: maker } }, body: { ...body, proof } }));
75
+ }
76
+ /** Rotate a key the same way: the owner signs a ROTATE challenge for that key. */
77
+ export async function rotateApiKey(client, owner, keyId, request = {}) {
78
+ const { maker, ...body } = request;
79
+ const proof = await ownerProof(client, owner, maker, { action: "ROTATE", key_id: keyId, request: body });
80
+ const params = { header: { "Idempotency-Key": uuidv7() } };
81
+ return maker === undefined
82
+ ? unwrap(await client.POST("/v1/me/api-keys/{key_id}/rotations", { params: { ...params, path: { key_id: keyId } }, body: { ...body, proof } }))
83
+ : unwrap(await client.POST("/v1/makers/{maker_id}/api-keys/{key_id}/rotations", { params: { ...params, path: { maker_id: maker, key_id: keyId } }, body: { ...body, proof } }));
84
+ }
85
+ /** Every key of the account, or of `maker`, oldest first, revoked and expired ones included, read page by page. */
86
+ export async function listApiKeys(client, account = {}) {
87
+ const { maker } = account;
88
+ const keys = [];
89
+ const read = async (query) => unwrap(maker === undefined
90
+ ? await client.GET("/v1/me/api-keys", { params: { query: { ...query, limit: 200 } } })
91
+ : await client.GET("/v1/makers/{maker_id}/api-keys", { params: { path: { maker_id: maker }, query: { ...query, limit: 200 } } }));
92
+ for await (const key of items(read, (page) => page.items))
93
+ keys.push(key);
94
+ return keys;
95
+ }
96
+ /** Revoke a key at once, with any key it is rotating to or from. No signature is needed, and revoking a revoked key succeeds again. */
97
+ export async function revokeApiKey(client, keyId, account = {}) {
98
+ const { maker } = account;
99
+ const { error, response } = maker === undefined
100
+ ? await client.DELETE("/v1/me/api-keys/{key_id}", { params: { path: { key_id: keyId } } })
101
+ : await client.DELETE("/v1/makers/{maker_id}/api-keys/{key_id}", { params: { path: { maker_id: maker, key_id: keyId } } });
102
+ if (error !== undefined || !response.ok)
103
+ throw ApiError.from(response, error);
104
+ }
@@ -0,0 +1,52 @@
1
+ import type { operations as ClientOperations } from "./generated/client.js";
2
+ import type { operations as MakerOperations } from "./generated/maker.js";
3
+ import type { components as OpenApiComponents } from "./generated/openapi.js";
4
+ import type { operations as OperatorOperations } from "./generated/operator.js";
5
+ type Assert<T extends true> = T;
6
+ type Includes<Operations, Name extends string> = Name extends keyof Operations ? true : false;
7
+ type Excludes<Operations, Name extends string> = Name extends keyof Operations ? false : true;
8
+ type RequiredBranch<Branch, Shape> = [Branch] extends [never] ? false : Branch extends Shape ? true : false;
9
+ type ClientContract = [
10
+ Assert<Includes<ClientOperations, "listMarkets">>,
11
+ Assert<Includes<ClientOperations, "createRfq">>,
12
+ Assert<Excludes<ClientOperations, "createQuote">>,
13
+ Assert<Excludes<ClientOperations, "live">>
14
+ ];
15
+ type MakerContract = [
16
+ Assert<Includes<MakerOperations, "listMarkets">>,
17
+ Assert<Includes<MakerOperations, "createQuote">>,
18
+ Assert<Includes<MakerOperations, "confirmQuote">>,
19
+ Assert<Excludes<MakerOperations, "acceptQuote">>,
20
+ Assert<Excludes<MakerOperations, "createRfq">>,
21
+ Assert<Excludes<MakerOperations, "live">>
22
+ ];
23
+ type OperatorContract = [
24
+ Assert<Includes<OperatorOperations, "live">>,
25
+ Assert<Excludes<OperatorOperations, "listMarkets">>
26
+ ];
27
+ type CashoutContract = Assert<OpenApiComponents["schemas"]["CashoutRfq"] extends {
28
+ readonly decision_block: string;
29
+ readonly decision_read_gas: "500000";
30
+ readonly net_stake: string;
31
+ readonly payout: string;
32
+ } ? true : false>;
33
+ type QuoteContract = [
34
+ Assert<RequiredBranch<Extract<OpenApiComponents["schemas"]["Quote"], {
35
+ readonly kind: "ENTRY";
36
+ }>, {
37
+ readonly quote_id: unknown;
38
+ readonly entry?: unknown;
39
+ }>>,
40
+ Assert<OpenApiComponents["schemas"]["QuoteTerms"]["legs"][number] extends {
41
+ readonly outcome_id: string;
42
+ readonly side: "YES" | "NO";
43
+ } ? true : false>,
44
+ Assert<OpenApiComponents["schemas"]["SellBackTerms"] extends {
45
+ readonly position_id: string;
46
+ } ? true : false>,
47
+ Assert<OpenApiComponents["schemas"]["TransferTerms"] extends {
48
+ readonly position_id: string;
49
+ } ? true : false>
50
+ ];
51
+ export type AudienceContract = [ClientContract, MakerContract, OperatorContract, CashoutContract, QuoteContract];
52
+ export {};
@@ -0,0 +1 @@
1
+ export {};