@envolvr/sdk 0.1.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 +176 -0
- package/README.md +65 -0
- package/dist/api.d.ts +76 -0
- package/dist/api.js +112 -0
- package/dist/attest.d.ts +58 -0
- package/dist/attest.js +85 -0
- package/dist/cli.d.ts +2 -0
- package/dist/cli.js +171 -0
- package/dist/client.d.ts +84 -0
- package/dist/client.js +156 -0
- package/dist/evm.d.ts +41 -0
- package/dist/evm.js +102 -0
- package/dist/index.d.ts +12 -0
- package/dist/index.js +7 -0
- package/dist/network.d.ts +19 -0
- package/dist/network.js +27 -0
- package/dist/receipts.d.ts +46 -0
- package/dist/receipts.js +100 -0
- package/dist/wallet.d.ts +14 -0
- package/dist/wallet.js +47 -0
- package/package.json +65 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,176 @@
|
|
|
1
|
+
Apache License
|
|
2
|
+
Version 2.0, January 2004
|
|
3
|
+
http://www.apache.org/licenses/
|
|
4
|
+
|
|
5
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
6
|
+
|
|
7
|
+
1. Definitions.
|
|
8
|
+
|
|
9
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
10
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
11
|
+
|
|
12
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
13
|
+
the copyright owner that is granting the License.
|
|
14
|
+
|
|
15
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
16
|
+
other entities that control, are controlled by, or are under common
|
|
17
|
+
control with that entity. For the purposes of this definition,
|
|
18
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
19
|
+
direction or management of such entity, whether by contract or
|
|
20
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
21
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
22
|
+
|
|
23
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
24
|
+
exercising permissions granted by this License.
|
|
25
|
+
|
|
26
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
27
|
+
including but not limited to software source code, documentation
|
|
28
|
+
source, and configuration files.
|
|
29
|
+
|
|
30
|
+
"Object" form shall mean any form resulting from mechanical
|
|
31
|
+
transformation or translation of a Source form, including but
|
|
32
|
+
not limited to compiled object code, generated documentation,
|
|
33
|
+
and conversions to other media types.
|
|
34
|
+
|
|
35
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
36
|
+
Object form, made available under the License, as indicated by a
|
|
37
|
+
copyright notice that is included in or attached to the work
|
|
38
|
+
(an example is provided in the Appendix below).
|
|
39
|
+
|
|
40
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
41
|
+
form, that is based on (or derived from) the Work and for which the
|
|
42
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
43
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
44
|
+
of this License, Derivative Works shall not include works that remain
|
|
45
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
46
|
+
the Work and Derivative Works thereof.
|
|
47
|
+
|
|
48
|
+
"Contribution" shall mean any work of authorship, including
|
|
49
|
+
the original version of the Work and any modifications or additions
|
|
50
|
+
to that Work or Derivative Works thereof, that is intentionally
|
|
51
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
|
52
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
|
53
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
|
54
|
+
means any form of electronic, verbal, or written communication sent
|
|
55
|
+
to the Licensor or its representatives, including but not limited to
|
|
56
|
+
communication on electronic mailing lists, source code control systems,
|
|
57
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
|
58
|
+
Licensor for the purpose of discussing and improving the Work, but
|
|
59
|
+
excluding communication that is conspicuously marked or otherwise
|
|
60
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
|
61
|
+
|
|
62
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
63
|
+
on behalf of whom a Contribution has been received by Licensor and
|
|
64
|
+
subsequently incorporated within the Work.
|
|
65
|
+
|
|
66
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
67
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
68
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
69
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
70
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
71
|
+
Work and such Derivative Works in Source or Object form.
|
|
72
|
+
|
|
73
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
74
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
75
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
76
|
+
(except as stated in this section) patent license to make, have made,
|
|
77
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
78
|
+
where such license applies only to those patent claims licensable
|
|
79
|
+
by such Contributor that are necessarily infringed by their
|
|
80
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
|
81
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
82
|
+
institute patent litigation against any entity (including a
|
|
83
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
84
|
+
or a Contribution incorporated within the Work constitutes direct
|
|
85
|
+
or contributory patent infringement, then any patent licenses
|
|
86
|
+
granted to You under this License for that Work shall terminate
|
|
87
|
+
as of the date such litigation is filed.
|
|
88
|
+
|
|
89
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
90
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
91
|
+
modifications, and in Source or Object form, provided that You
|
|
92
|
+
meet the following conditions:
|
|
93
|
+
|
|
94
|
+
(a) You must give any other recipients of the Work or
|
|
95
|
+
Derivative Works a copy of this License; and
|
|
96
|
+
|
|
97
|
+
(b) You must cause any modified files to carry prominent notices
|
|
98
|
+
stating that You changed the files; and
|
|
99
|
+
|
|
100
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
101
|
+
that You distribute, all copyright, patent, trademark, and
|
|
102
|
+
attribution notices from the Source form of the Work,
|
|
103
|
+
excluding those notices that do not pertain to any part of
|
|
104
|
+
the Derivative Works; and
|
|
105
|
+
|
|
106
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
107
|
+
distribution, then any Derivative Works that You distribute must
|
|
108
|
+
include a readable copy of the attribution notices contained
|
|
109
|
+
within such NOTICE file, excluding those notices that do not
|
|
110
|
+
pertain to any part of the Derivative Works, in at least one
|
|
111
|
+
of the following places: within a NOTICE text file distributed
|
|
112
|
+
as part of the Derivative Works; within the Source form or
|
|
113
|
+
documentation, if provided along with the Derivative Works; or,
|
|
114
|
+
within a display generated by the Derivative Works, if and
|
|
115
|
+
wherever such third-party notices normally appear. The contents
|
|
116
|
+
of the NOTICE file are for informational purposes only and
|
|
117
|
+
do not modify the License. You may add Your own attribution
|
|
118
|
+
notices within Derivative Works that You distribute, alongside
|
|
119
|
+
or as an addendum to the NOTICE text from the Work, provided
|
|
120
|
+
that such additional attribution notices cannot be construed
|
|
121
|
+
as modifying the License.
|
|
122
|
+
|
|
123
|
+
You may add Your own copyright statement to Your modifications and
|
|
124
|
+
may provide additional or different license terms and conditions
|
|
125
|
+
for use, reproduction, or distribution of Your modifications, or
|
|
126
|
+
for any such Derivative Works as a whole, provided Your use,
|
|
127
|
+
reproduction, and distribution of the Work otherwise complies with
|
|
128
|
+
the conditions stated in this License.
|
|
129
|
+
|
|
130
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
131
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
132
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
133
|
+
this License, without any additional terms or conditions.
|
|
134
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
135
|
+
the terms of any separate license agreement you may have executed
|
|
136
|
+
with Licensor regarding such Contributions.
|
|
137
|
+
|
|
138
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
139
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
140
|
+
except as required for reasonable and customary use in describing the
|
|
141
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
|
142
|
+
|
|
143
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
144
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
145
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
146
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
147
|
+
implied, including, without limitation, any warranties or conditions
|
|
148
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
149
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
150
|
+
appropriateness of using or redistributing the Work and assume any
|
|
151
|
+
risks associated with Your exercise of permissions under this License.
|
|
152
|
+
|
|
153
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
154
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
155
|
+
unless required by applicable law (such as deliberate and grossly
|
|
156
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
157
|
+
liable to You for damages, including any direct, indirect, special,
|
|
158
|
+
incidental, or consequential damages of any character arising as a
|
|
159
|
+
result of this License or out of the use or inability to use the
|
|
160
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
161
|
+
work stoppage, computer failure or malfunction, or any and all
|
|
162
|
+
other commercial damages or losses), even if such Contributor
|
|
163
|
+
has been advised of the possibility of such damages.
|
|
164
|
+
|
|
165
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
|
166
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
|
167
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
168
|
+
or other liability obligations and/or rights consistent with this
|
|
169
|
+
License. However, in accepting such obligations, You may act only
|
|
170
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
|
171
|
+
of any other Contributor, and only if You agree to indemnify,
|
|
172
|
+
defend, and hold each Contributor harmless for any liability
|
|
173
|
+
incurred by, or claims asserted against, such Contributor by reason
|
|
174
|
+
of your accepting any such warranty or additional liability.
|
|
175
|
+
|
|
176
|
+
END OF TERMS AND CONDITIONS
|
package/README.md
ADDED
|
@@ -0,0 +1,65 @@
|
|
|
1
|
+
# @envolvr/sdk
|
|
2
|
+
|
|
3
|
+
Private inference your agent can prove. The envolvr gateway runs in an attested
|
|
4
|
+
Intel TDX enclave and speaks the OpenAI API; every response comes with a signed
|
|
5
|
+
receipt that records the model, the attested provider session, commitments to
|
|
6
|
+
the request and response, and what was billed. Receipt hashes are anchored on
|
|
7
|
+
Robinhood Chain every 10 minutes. This package signs in with a wallet, funds
|
|
8
|
+
the account with USDG, runs inference, keeps every receipt, and verifies it.
|
|
9
|
+
|
|
10
|
+
```bash
|
|
11
|
+
npm install @envolvr/sdk # Node 20+
|
|
12
|
+
```
|
|
13
|
+
|
|
14
|
+
## From zero to a verified receipt (testnet)
|
|
15
|
+
|
|
16
|
+
```bash
|
|
17
|
+
export ENVOLVR_PRIVATE_KEY=0x… # a wallet with a little Robinhood testnet ETH for gas
|
|
18
|
+
npx envolvr signin --save # sign a message, get an API key
|
|
19
|
+
npx envolvr testnet-mint 20 # test USDG (testnet only)
|
|
20
|
+
npx envolvr deposit 10 # credited net of the deposit fee, within seconds
|
|
21
|
+
npx envolvr chat "Reply with the single word: sealed"
|
|
22
|
+
npx envolvr verify --last # signature, billing, payer, on-chain anchor
|
|
23
|
+
```
|
|
24
|
+
|
|
25
|
+
`verify` prints what the receipt proves: the gateway's TDX attestation and the
|
|
26
|
+
receipt signature (checked by `private-ai-proxy`), what was billed and that it
|
|
27
|
+
was billed to your key, and the batch and transaction that anchor it. A receipt
|
|
28
|
+
is anchored at the end of its 10-minute slot (UTC).
|
|
29
|
+
|
|
30
|
+
## In code
|
|
31
|
+
|
|
32
|
+
```ts
|
|
33
|
+
import { Envolvr, privateKeySigner, signIn, depositUsdg, TESTNET, toMicros } from '@envolvr/sdk';
|
|
34
|
+
|
|
35
|
+
const wallet = privateKeySigner(process.env.KEY!, { rpcUrl: TESTNET.rpcUrl, chainId: TESTNET.chainId });
|
|
36
|
+
const { apiKey } = await signIn(wallet); // keep it: shown once
|
|
37
|
+
await depositUsdg({ signer: wallet, amountMicros: toMicros('10') });
|
|
38
|
+
|
|
39
|
+
const envolvr = new Envolvr({ apiKey, receiptDir: './receipts' });
|
|
40
|
+
const { response, saved } = await envolvr.chat({
|
|
41
|
+
model: 'z-ai/glm-5.3',
|
|
42
|
+
messages: [{ role: 'user', content: 'hello' }],
|
|
43
|
+
provider: { only: ['redpill'] }, // optional: pin providers
|
|
44
|
+
});
|
|
45
|
+
const proof = await envolvr.verify(saved!.dir!); // after the slot closes
|
|
46
|
+
```
|
|
47
|
+
|
|
48
|
+
Using the OpenAI SDK instead: `new OpenAI(envolvr.openai)`. Then fetch each
|
|
49
|
+
receipt yourself with `envolvr.receipt(id)` within an hour: the gateway keeps
|
|
50
|
+
receipts for an hour. For an OpenAI client that verifies the service before
|
|
51
|
+
sending and checks every receipt, run the local verifying proxy
|
|
52
|
+
`npx private-ai-proxy serve https://api.envolvr.xyz` and point the client at
|
|
53
|
+
`http://127.0.0.1:4180/v1`.
|
|
54
|
+
|
|
55
|
+
Any wallet works for sign-in and deposits: implement `Signer` (`address`,
|
|
56
|
+
`signMessage`, and `sendTransaction` for deposits) around viem, ethers or a
|
|
57
|
+
hardware wallet.
|
|
58
|
+
|
|
59
|
+
## Pricing
|
|
60
|
+
|
|
61
|
+
Per-token prices are the providers' own list prices (`envolvr models`). A fee
|
|
62
|
+
is kept from each USDG deposit (`envolvr pricing`). Every receipt records the
|
|
63
|
+
token counts, the rates and the amount billed, so any charge can be recomputed.
|
|
64
|
+
If a request allows several providers, it is priced at the highest of their
|
|
65
|
+
list prices.
|
package/dist/api.d.ts
ADDED
|
@@ -0,0 +1,76 @@
|
|
|
1
|
+
import { type Network } from './network.ts';
|
|
2
|
+
import type { Signer } from './wallet.ts';
|
|
3
|
+
/** The message the sign-in signs; the SDK signs nothing else. */
|
|
4
|
+
export declare function signInMessage(wallet: string, nonce: string, issuedAt: string): string;
|
|
5
|
+
/**
|
|
6
|
+
* Sign in with a wallet and get an API key. The key is shown once; keep it.
|
|
7
|
+
* Each sign-in issues a new key; earlier keys keep working.
|
|
8
|
+
*/
|
|
9
|
+
export declare function signIn(signer: Signer, network?: Network): Promise<{
|
|
10
|
+
apiKey: string;
|
|
11
|
+
wallet: string;
|
|
12
|
+
}>;
|
|
13
|
+
/** The message that closes an account; the SDK signs nothing else for it. */
|
|
14
|
+
export declare function closeAccountMessage(wallet: string, refundTo: string, nonce: string, issuedAt: string): string;
|
|
15
|
+
/**
|
|
16
|
+
* Close the account of `signer`'s wallet: every API key stops working, and the
|
|
17
|
+
* balance (net of deposit fees; the staking allowance is not money) is refunded
|
|
18
|
+
* to `refundTo`, by default the wallet itself. The refund is paid from the
|
|
19
|
+
* credit vault shortly after.
|
|
20
|
+
*/
|
|
21
|
+
export declare function closeAccount(signer: Signer, opts?: {
|
|
22
|
+
refundTo?: string;
|
|
23
|
+
network?: Network;
|
|
24
|
+
}): Promise<{
|
|
25
|
+
closed: boolean;
|
|
26
|
+
revokedKeys: number;
|
|
27
|
+
refund?: {
|
|
28
|
+
id: number;
|
|
29
|
+
amountMicros: string;
|
|
30
|
+
status: 'pending' | 'held';
|
|
31
|
+
refundTo: string;
|
|
32
|
+
};
|
|
33
|
+
}>;
|
|
34
|
+
export interface Account {
|
|
35
|
+
wallet: string;
|
|
36
|
+
/** USDG balance, micro-USD (6 decimals), as a decimal string. */
|
|
37
|
+
balanceMicros: string;
|
|
38
|
+
/** Today's staking allowance and what is left of it, micro-USD. */
|
|
39
|
+
allowanceTodayMicros: string;
|
|
40
|
+
allowanceLeftMicros: string;
|
|
41
|
+
}
|
|
42
|
+
export declare function getAccount(apiKey: string, network?: Network): Promise<Account>;
|
|
43
|
+
export interface Pricing {
|
|
44
|
+
/** Kept from each USDG deposit, in basis points (500 = 5%). */
|
|
45
|
+
depositFeeBps: number;
|
|
46
|
+
tokenPricing: string;
|
|
47
|
+
}
|
|
48
|
+
export declare function getPricing(network?: Network): Promise<Pricing>;
|
|
49
|
+
/** What a deposit of `amountMicros` credits at `feeBps` (the fee rounds down). */
|
|
50
|
+
export declare function netCredit(amountMicros: bigint, feeBps: number): bigint;
|
|
51
|
+
/**
|
|
52
|
+
* Deposit USDG into the credit vault for `account` (default: the signer's own
|
|
53
|
+
* wallet, the one that signs in). Approves the vault first when needed. The
|
|
54
|
+
* balance is credited, net of the deposit fee, within seconds of the deposit
|
|
55
|
+
* being mined. Deposit from a wallet you control; a plain USDG transfer to the
|
|
56
|
+
* vault is not credited.
|
|
57
|
+
*/
|
|
58
|
+
export declare function depositUsdg(opts: {
|
|
59
|
+
signer: Signer;
|
|
60
|
+
amountMicros: bigint;
|
|
61
|
+
account?: string;
|
|
62
|
+
network?: Network;
|
|
63
|
+
}): Promise<{
|
|
64
|
+
approveTx: string | undefined;
|
|
65
|
+
depositTx: string;
|
|
66
|
+
account: string;
|
|
67
|
+
amountMicros: bigint;
|
|
68
|
+
depositFeeBps: number;
|
|
69
|
+
expectedCreditMicros: bigint;
|
|
70
|
+
}>;
|
|
71
|
+
/** Testnet only: mint test USDG to the signer (the test token has an open mint). */
|
|
72
|
+
export declare function mintTestUsdg(opts: {
|
|
73
|
+
signer: Signer;
|
|
74
|
+
amountMicros: bigint;
|
|
75
|
+
network?: Network;
|
|
76
|
+
}): Promise<string>;
|
package/dist/api.js
ADDED
|
@@ -0,0 +1,112 @@
|
|
|
1
|
+
// envolvr's HTTP surface for an agent: sign in with a wallet, read the account
|
|
2
|
+
// and the pricing, and move USDG into the credit vault.
|
|
3
|
+
import { decodeWords, encodeCall, Rpc } from "./evm.js";
|
|
4
|
+
import { TESTNET } from "./network.js";
|
|
5
|
+
async function json(res) {
|
|
6
|
+
const body = (await res.json().catch(() => ({})));
|
|
7
|
+
if (!res.ok)
|
|
8
|
+
throw new Error(`${new URL(res.url).pathname}: ${res.status} ${body.error ?? ''}`.trim());
|
|
9
|
+
return body;
|
|
10
|
+
}
|
|
11
|
+
/** The message the sign-in signs; the SDK signs nothing else. */
|
|
12
|
+
export function signInMessage(wallet, nonce, issuedAt) {
|
|
13
|
+
return ['envolvr: sign in to get an API key.', '', `Wallet: ${wallet.toLowerCase()}`, `Nonce: ${nonce}`, `Issued At: ${issuedAt}`]
|
|
14
|
+
.join('\n');
|
|
15
|
+
}
|
|
16
|
+
/**
|
|
17
|
+
* Sign in with a wallet and get an API key. The key is shown once; keep it.
|
|
18
|
+
* Each sign-in issues a new key; earlier keys keep working.
|
|
19
|
+
*/
|
|
20
|
+
export async function signIn(signer, network = TESTNET) {
|
|
21
|
+
const n = await json(await fetch(`${network.control}/auth/nonce?wallet=${signer.address}`));
|
|
22
|
+
const expected = signInMessage(signer.address, n.nonce, n.issuedAt);
|
|
23
|
+
if (n.message !== expected)
|
|
24
|
+
throw new Error('the sign-in message is not the one envolvr defines; refusing to sign it');
|
|
25
|
+
const signature = await signer.signMessage(expected);
|
|
26
|
+
return json(await fetch(`${network.control}/auth/key`, {
|
|
27
|
+
method: 'POST',
|
|
28
|
+
headers: { 'content-type': 'application/json' },
|
|
29
|
+
body: JSON.stringify({ wallet: signer.address, nonce: n.nonce, issuedAt: n.issuedAt, signature }),
|
|
30
|
+
}));
|
|
31
|
+
}
|
|
32
|
+
/** The message that closes an account; the SDK signs nothing else for it. */
|
|
33
|
+
export function closeAccountMessage(wallet, refundTo, nonce, issuedAt) {
|
|
34
|
+
return ['envolvr: close this account and refund its balance.', '', `Wallet: ${wallet.toLowerCase()}`,
|
|
35
|
+
`Refund to: ${refundTo.toLowerCase()}`, `Nonce: ${nonce}`, `Issued At: ${issuedAt}`].join('\n');
|
|
36
|
+
}
|
|
37
|
+
/**
|
|
38
|
+
* Close the account of `signer`'s wallet: every API key stops working, and the
|
|
39
|
+
* balance (net of deposit fees; the staking allowance is not money) is refunded
|
|
40
|
+
* to `refundTo`, by default the wallet itself. The refund is paid from the
|
|
41
|
+
* credit vault shortly after.
|
|
42
|
+
*/
|
|
43
|
+
export async function closeAccount(signer, opts = {}) {
|
|
44
|
+
const network = opts.network ?? TESTNET;
|
|
45
|
+
const refundTo = opts.refundTo ?? signer.address;
|
|
46
|
+
const n = await json(await fetch(`${network.control}/account/close/nonce?wallet=${signer.address}&refundTo=${refundTo}`));
|
|
47
|
+
const expected = closeAccountMessage(signer.address, refundTo, n.nonce, n.issuedAt);
|
|
48
|
+
if (n.message !== expected)
|
|
49
|
+
throw new Error('the close message is not the one envolvr defines; refusing to sign it');
|
|
50
|
+
const signature = await signer.signMessage(expected);
|
|
51
|
+
return json(await fetch(`${network.control}/account/close`, {
|
|
52
|
+
method: 'POST',
|
|
53
|
+
headers: { 'content-type': 'application/json' },
|
|
54
|
+
body: JSON.stringify({ wallet: signer.address, refundTo, nonce: n.nonce, issuedAt: n.issuedAt, signature }),
|
|
55
|
+
}));
|
|
56
|
+
}
|
|
57
|
+
export async function getAccount(apiKey, network = TESTNET) {
|
|
58
|
+
return json(await fetch(`${network.control}/account`, { headers: { authorization: `Bearer ${apiKey}` } }));
|
|
59
|
+
}
|
|
60
|
+
export async function getPricing(network = TESTNET) {
|
|
61
|
+
return json(await fetch(`${network.control}/pricing`));
|
|
62
|
+
}
|
|
63
|
+
/** What a deposit of `amountMicros` credits at `feeBps` (the fee rounds down). */
|
|
64
|
+
export function netCredit(amountMicros, feeBps) {
|
|
65
|
+
return amountMicros - (amountMicros * BigInt(feeBps)) / 10000n;
|
|
66
|
+
}
|
|
67
|
+
/**
|
|
68
|
+
* Deposit USDG into the credit vault for `account` (default: the signer's own
|
|
69
|
+
* wallet, the one that signs in). Approves the vault first when needed. The
|
|
70
|
+
* balance is credited, net of the deposit fee, within seconds of the deposit
|
|
71
|
+
* being mined. Deposit from a wallet you control; a plain USDG transfer to the
|
|
72
|
+
* vault is not credited.
|
|
73
|
+
*/
|
|
74
|
+
export async function depositUsdg(opts) {
|
|
75
|
+
const network = opts.network ?? TESTNET;
|
|
76
|
+
const { signer, amountMicros } = opts;
|
|
77
|
+
if (!signer.sendTransaction)
|
|
78
|
+
throw new Error('this signer cannot send transactions');
|
|
79
|
+
if (amountMicros <= 0n)
|
|
80
|
+
throw new Error('the amount must be positive');
|
|
81
|
+
const rpc = new Rpc(network.rpcUrl);
|
|
82
|
+
const view = async (to, sig, args) => BigInt(decodeWords(await rpc.call('eth_call', [{ to, data: encodeCall(sig, args) }, 'latest']))[0]);
|
|
83
|
+
const balance = await view(network.usdg, 'balanceOf(address)', [signer.address]);
|
|
84
|
+
if (balance < amountMicros)
|
|
85
|
+
throw new Error(`the wallet holds ${balance} micro-USDG, less than ${amountMicros}`);
|
|
86
|
+
const { depositFeeBps } = await getPricing(network);
|
|
87
|
+
let approveTx;
|
|
88
|
+
if ((await view(network.usdg, 'allowance(address,address)', [signer.address, network.creditVault])) < amountMicros) {
|
|
89
|
+
approveTx = await signer.sendTransaction({
|
|
90
|
+
to: network.usdg, data: encodeCall('approve(address,uint256)', [network.creditVault, amountMicros]),
|
|
91
|
+
});
|
|
92
|
+
}
|
|
93
|
+
const account = opts.account ?? signer.address;
|
|
94
|
+
const depositTx = await signer.sendTransaction({
|
|
95
|
+
to: network.creditVault,
|
|
96
|
+
data: account.toLowerCase() === signer.address.toLowerCase()
|
|
97
|
+
? encodeCall('deposit(uint256)', [amountMicros])
|
|
98
|
+
: encodeCall('depositFor(address,uint256)', [account, amountMicros]),
|
|
99
|
+
});
|
|
100
|
+
return { approveTx, depositTx, account, amountMicros, depositFeeBps, expectedCreditMicros: netCredit(amountMicros, depositFeeBps) };
|
|
101
|
+
}
|
|
102
|
+
/** Testnet only: mint test USDG to the signer (the test token has an open mint). */
|
|
103
|
+
export async function mintTestUsdg(opts) {
|
|
104
|
+
const network = opts.network ?? TESTNET;
|
|
105
|
+
if (network.chainId !== TESTNET.chainId)
|
|
106
|
+
throw new Error('mintTestUsdg is for the testnet only');
|
|
107
|
+
if (!opts.signer.sendTransaction)
|
|
108
|
+
throw new Error('this signer cannot send transactions');
|
|
109
|
+
return opts.signer.sendTransaction({
|
|
110
|
+
to: network.usdg, data: encodeCall('mint(address,uint256)', [opts.signer.address, opts.amountMicros]),
|
|
111
|
+
});
|
|
112
|
+
}
|
package/dist/attest.d.ts
ADDED
|
@@ -0,0 +1,58 @@
|
|
|
1
|
+
import type { Network } from './network.ts';
|
|
2
|
+
export declare const PAP_PACKAGE = "private-ai-proxy@0.1.6";
|
|
3
|
+
export interface PapResult {
|
|
4
|
+
/** True only when pap's verdict is VERIFIED (exit 0). */
|
|
5
|
+
verified: boolean;
|
|
6
|
+
/** pap's --json transcript, or its text output when that is not JSON. */
|
|
7
|
+
transcript: unknown;
|
|
8
|
+
stderr: string;
|
|
9
|
+
}
|
|
10
|
+
export declare function runPap(args: string[], opts?: {
|
|
11
|
+
timeoutMs?: number;
|
|
12
|
+
}): Promise<PapResult>;
|
|
13
|
+
/**
|
|
14
|
+
* Verify the live gateway: a fresh nonce, the TDX quote, the measured compose
|
|
15
|
+
* and source, and the TLS key being served. `acceptCompose` pins the compose
|
|
16
|
+
* hashes you accept; without it pap verifies and reports the measurement and
|
|
17
|
+
* you appraise it yourself.
|
|
18
|
+
*/
|
|
19
|
+
export declare function verifyGateway(network: Network, opts?: {
|
|
20
|
+
acceptCompose?: string[];
|
|
21
|
+
}): Promise<PapResult>;
|
|
22
|
+
/** A fresh 32-byte attestation nonce (64 lowercase hex). */
|
|
23
|
+
export declare const newNonce: () => string;
|
|
24
|
+
/** Fetch the gateway's attestation report for a nonce (to keep beside receipts). */
|
|
25
|
+
export declare function fetchAttestationReport(network: Network, nonce?: string): Promise<{
|
|
26
|
+
nonce: string;
|
|
27
|
+
report: Record<string, unknown>;
|
|
28
|
+
}>;
|
|
29
|
+
/**
|
|
30
|
+
* Check a saved receipt offline against the attestation report of the keyset
|
|
31
|
+
* that signed it: the report itself (quote, binding, provenance), the receipt
|
|
32
|
+
* signature, and, when given, the exact request and response bytes against the
|
|
33
|
+
* receipt's commitments.
|
|
34
|
+
*/
|
|
35
|
+
export declare function auditReceipt(opts: {
|
|
36
|
+
reportPath: string;
|
|
37
|
+
nonce?: string;
|
|
38
|
+
receiptPath: string;
|
|
39
|
+
requestBodyPath?: string;
|
|
40
|
+
responseBodyPath?: string;
|
|
41
|
+
sessionPath?: string;
|
|
42
|
+
acceptCompose?: string[];
|
|
43
|
+
}): Promise<PapResult>;
|
|
44
|
+
export interface AuditCheck {
|
|
45
|
+
id: string;
|
|
46
|
+
title: string;
|
|
47
|
+
status: 'pass' | 'fail' | 'skip';
|
|
48
|
+
detail: string;
|
|
49
|
+
}
|
|
50
|
+
/** What an offline audit establishes, by name. */
|
|
51
|
+
export interface AuditSummary {
|
|
52
|
+
/** The receipt's signature, keyset, commitments and cited session all check out, and nothing failed. */
|
|
53
|
+
signed: boolean;
|
|
54
|
+
checks: Record<string, AuditCheck | undefined>;
|
|
55
|
+
failed: AuditCheck[];
|
|
56
|
+
}
|
|
57
|
+
export declare const AUDIT_CHECKS: Record<string, string>;
|
|
58
|
+
export declare function summarizeAudit(result: PapResult): AuditSummary;
|
package/dist/attest.js
ADDED
|
@@ -0,0 +1,85 @@
|
|
|
1
|
+
// Attestation: is this really envolvr's measured gateway, and did it sign this
|
|
2
|
+
// receipt? The checks are done by private-ai-proxy (pap), the open verifier for
|
|
3
|
+
// the ACI protocol the gateway speaks (TDX quote to Intel's root, keyset and
|
|
4
|
+
// nonce binding, source provenance, TLS channel binding, receipt signature,
|
|
5
|
+
// request and response commitments). This module runs it and reads its verdict.
|
|
6
|
+
import { spawn } from 'node:child_process';
|
|
7
|
+
import { randomBytes } from 'node:crypto';
|
|
8
|
+
export const PAP_PACKAGE = 'private-ai-proxy@0.1.6';
|
|
9
|
+
export function runPap(args, opts = {}) {
|
|
10
|
+
return new Promise((resolve, reject) => {
|
|
11
|
+
const child = spawn('npx', ['-y', PAP_PACKAGE, ...args, '--json', '--non-interactive'], { stdio: ['ignore', 'pipe', 'pipe'] });
|
|
12
|
+
let stdout = '';
|
|
13
|
+
let stderr = '';
|
|
14
|
+
const timer = setTimeout(() => child.kill('SIGTERM'), opts.timeoutMs ?? 300_000);
|
|
15
|
+
child.stdout.on('data', (d) => { stdout += d; });
|
|
16
|
+
child.stderr.on('data', (d) => { stderr += d; });
|
|
17
|
+
child.on('error', (err) => { clearTimeout(timer); reject(new Error(`could not run ${PAP_PACKAGE} (needs npx): ${err.message}`)); });
|
|
18
|
+
child.on('close', (code) => {
|
|
19
|
+
clearTimeout(timer);
|
|
20
|
+
let transcript = stdout.trim();
|
|
21
|
+
try {
|
|
22
|
+
transcript = JSON.parse(stdout);
|
|
23
|
+
}
|
|
24
|
+
catch { /* keep the text */ }
|
|
25
|
+
resolve({ verified: code === 0, transcript, stderr: stderr.trim() });
|
|
26
|
+
});
|
|
27
|
+
});
|
|
28
|
+
}
|
|
29
|
+
/**
|
|
30
|
+
* Verify the live gateway: a fresh nonce, the TDX quote, the measured compose
|
|
31
|
+
* and source, and the TLS key being served. `acceptCompose` pins the compose
|
|
32
|
+
* hashes you accept; without it pap verifies and reports the measurement and
|
|
33
|
+
* you appraise it yourself.
|
|
34
|
+
*/
|
|
35
|
+
export function verifyGateway(network, opts = {}) {
|
|
36
|
+
return runPap(['verify', '--require-production-os',
|
|
37
|
+
...(opts.acceptCompose ?? []).flatMap((h) => ['--accept-compose', h]), network.gateway]);
|
|
38
|
+
}
|
|
39
|
+
/** A fresh 32-byte attestation nonce (64 lowercase hex). */
|
|
40
|
+
export const newNonce = () => randomBytes(32).toString('hex');
|
|
41
|
+
/** Fetch the gateway's attestation report for a nonce (to keep beside receipts). */
|
|
42
|
+
export async function fetchAttestationReport(network, nonce = newNonce()) {
|
|
43
|
+
const res = await fetch(`${network.gateway}/v1/aci/attestation?nonce=${nonce}`);
|
|
44
|
+
if (!res.ok)
|
|
45
|
+
throw new Error(`attestation report: HTTP ${res.status}`);
|
|
46
|
+
return { nonce, report: await res.json() };
|
|
47
|
+
}
|
|
48
|
+
/**
|
|
49
|
+
* Check a saved receipt offline against the attestation report of the keyset
|
|
50
|
+
* that signed it: the report itself (quote, binding, provenance), the receipt
|
|
51
|
+
* signature, and, when given, the exact request and response bytes against the
|
|
52
|
+
* receipt's commitments.
|
|
53
|
+
*/
|
|
54
|
+
export function auditReceipt(opts) {
|
|
55
|
+
return runPap([
|
|
56
|
+
'audit', '--report', opts.reportPath, '--receipt', opts.receiptPath, '--require-production-os', '--skip-expiry',
|
|
57
|
+
...(opts.nonce ? ['--nonce', opts.nonce] : []),
|
|
58
|
+
...(opts.requestBodyPath ? ['--request-body', opts.requestBodyPath] : []),
|
|
59
|
+
...(opts.responseBodyPath ? ['--response-body', opts.responseBodyPath] : []),
|
|
60
|
+
...(opts.sessionPath ? ['--session', opts.sessionPath] : []),
|
|
61
|
+
...(opts.acceptCompose ?? []).flatMap((h) => ['--accept-compose', h]),
|
|
62
|
+
]);
|
|
63
|
+
}
|
|
64
|
+
// pap's check ids (ACI spec sections): what each one tells an agent.
|
|
65
|
+
export const AUDIT_CHECKS = {
|
|
66
|
+
'receipt-1': 'receipt signature by the attested key',
|
|
67
|
+
'receipt-2': 'receipt names the attested keyset',
|
|
68
|
+
'receipt-3': 'request commitment matches the bytes sent',
|
|
69
|
+
'receipt-4': 'response commitment matches the bytes received',
|
|
70
|
+
'upstream-1': 'provider enclave verified before forwarding',
|
|
71
|
+
'upstream-2': 'cited provider session checks out',
|
|
72
|
+
'id-2': 'keyset bound into the TDX quote',
|
|
73
|
+
'id-4': 'workload measured and linked to public source',
|
|
74
|
+
'policy-os': 'production dstack OS image',
|
|
75
|
+
'id-1': 'TDX quote chains to Intel (checked live by verify-gateway)',
|
|
76
|
+
};
|
|
77
|
+
export function summarizeAudit(result) {
|
|
78
|
+
const transcript = result.transcript;
|
|
79
|
+
const all = typeof transcript === 'object' && Array.isArray(transcript.checks) ? transcript.checks : [];
|
|
80
|
+
const checks = Object.fromEntries(Object.keys(AUDIT_CHECKS).map((id) => [id, all.find((c) => c.id === id)]));
|
|
81
|
+
const failed = all.filter((c) => c.status === 'fail');
|
|
82
|
+
const required = ['receipt-1', 'receipt-2', 'id-2', 'id-4', 'policy-os', 'upstream-1'];
|
|
83
|
+
const signed = failed.length === 0 && required.every((id) => checks[id]?.status === 'pass');
|
|
84
|
+
return { signed, checks, failed };
|
|
85
|
+
}
|
package/dist/cli.d.ts
ADDED