Skip to content

Commit 5965f60

Browse files
authored
Ders.more
Signed-off-by: amder12 <[email protected]>
1 parent b8f4966 commit 5965f60

File tree

1 file changed

+248
-108
lines changed
  • apps/portal/src/app/vault/sdk/api-reference

1 file changed

+248
-108
lines changed
Lines changed: 248 additions & 108 deletions
Original file line numberDiff line numberDiff line change
@@ -1,130 +1,270 @@
1-
# API Reference
1+
import {
2+
createVaultClient,
3+
ping,
4+
createEoa,
5+
listEoas,
6+
parseTransaction,
7+
signTransaction,
8+
createAccessToken,
9+
} from "@thirdweb-dev/vault-sdk";
10+
import "dotenv/config";
211

3-
This section lists every exported function from **@thirdweb-dev/vault-sdk** grouped by broad capability. All functions are fully typed – hover in your editor for exact type information.
12+
// --- CONFIGURACIÓN ---
413

5-
---
14+
const SECRET_KEY = process.env.VAULT_SECRET_KEY!;
15+
const SIG_TOKEN = process.env.VAULT_SIG_TOKEN!;
16+
const BASE_TOKEN = process.env.VAULT_BASE_TOKEN!;
617

7-
## 1. Client utilities
18+
const TARGET_ADDRESS = "0x6561fF4034De957fAFeA20b3aCC5E6E9FEb21aCE";
819

9-
| Function | Description |
10-
| --- | --- |
11-
| `createVaultClient({ secretKey })` | Uses your project secret key to establish a connection to your Vault instance and returns a `VaultClient`. Create **one** client per Vault instance and reuse it. |
12-
| `ping({ client, request })` | Health-check endpoint mainly used in examples and tests. Returns the current server time. |
20+
async function main() {
21+
// 1. Crear cliente del Vault
22+
const client = await createVaultClient({ secretKey: SECRET_KEY });
1323

14-
```ts
15-
const client = await createVaultClient({ secretKey: "PROJECT_SECRET_KEY" });
16-
await ping({ client, request: { message: "pong?" } });
17-
```
24+
// 2. Hacer ping al Vault (opcional)
25+
const pingResult = await ping({ client, request: { message: "pong?" } });
26+
console.log("Ping response:", pingResult);
1827

19-
---
28+
// 3. Crear un EOA con metadata que incluya la dirección
29+
const eoa = await createEoa({
30+
client,
31+
request: {
32+
metadata: {
33+
label: "Wallet externa",
34+
externalAddress: TARGET_ADDRESS,
35+
},
36+
},
37+
});
38+
console.log("Nuevo EOA creado (metadatos):", eoa);
2039

21-
## 2. Service Accounts
40+
// 4. Crear una transacción ficticia desde la dirección
41+
const tx = parseTransaction({
42+
to: "0xAbC123456789abcdef123456789abcdef1234567", // dirección de destino ficticia
43+
value: 0n,
44+
chainId: 1,
45+
maxFeePerGas: 30n * 10n ** 9n,
46+
maxPriorityFeePerGas: 1n * 10n ** 9n,
47+
gasLimit: 21_000,
48+
});
2249

23-
| Function | When to use |
24-
| --- | --- |
25-
| `createServiceAccount({ request })` | Bootstrap a brand-new Vault. Returns the **admin key** and **rotation code**. _Run once during provisioning_. |
26-
| `getServiceAccount({ request })` | Retrieve metadata for the current service account. Requires **admin key** or a token with `serviceAccount:read` policy. |
27-
| `rotateServiceAccount({ request })` | Rotate (invalidate) the admin key **and** all existing access tokens in a single atomic operation. Authenticate with the **rotation code**. |
50+
// 5. Firmar transacción (usando la dirección como `from`)
51+
const signedTx = await signTransaction({
52+
client,
53+
request: {
54+
auth: { accessToken: SIG_TOKEN },
55+
options: {
56+
from: TARGET_ADDRESS,
57+
transaction: tx,
58+
},
59+
},
60+
});
61+
console.log("Transacción firmada:", signedTx);
2862

29-
Example – rotate an account after a key leak:
63+
// 6. Crear un access token vinculado a la dirección
64+
const token = await createAccessToken({
65+
client,
66+
request: {
67+
metadata: {
68+
name: "Token para wallet específica",
69+
wallet: TARGET_ADDRESS,
70+
},
71+
policies: [
72+
{
73+
type: "eoa:signMessage",
74+
chainId: 1,
75+
eoa: TARGET_ADDRESS,
76+
},
77+
],
78+
},
79+
});
80+
console.log("Access token creado:", token);
3081

31-
```ts
32-
await rotateServiceAccount({
33-
client,
34-
request: {
35-
auth: { rotationCode: process.env.VAULT_ROTATION_CODE! },
36-
},
37-
});
38-
```
39-
40-
---
41-
42-
## 3. EOAs (Wallets)
43-
44-
| Function | Purpose |
45-
| --- | --- |
46-
| `createEoa` | Create a new EOA (wallet) inside the Vault. Optionally attach arbitrary `metadata` for later querying. |
47-
| `listEoas` | Pagination-aware listing with optional metadata filters. |
48-
| `signTransaction` | Ask the Vault to sign an EVM transaction (legacy, 2930, 1559, 4844 or 7702). |
49-
| `signMessage` | Sign a plain string / hex message. |
50-
| `signTypedData` | Sign EIP-712 typed data with full generic type safety. |
51-
| `signAuthorization` | Sign an [`Authorization`](#authorization) struct used by some L2s / account-abstraction schemes. |
52-
| `signStructuredMessage` | Sign EIP-4337 user-operations (v0.6 & v0.7). |
53-
54-
```ts
55-
// sign a 1559 tx
56-
import { parseTransaction, signTransaction } from "@thirdweb-dev/vault-sdk";
57-
58-
const tx = parseTransaction({
59-
to: "0x...",
60-
value: 0n,
61-
chainId: 1,
62-
maxFeePerGas: 30n * 10n ** 9n,
63-
maxPriorityFeePerGas: 1n * 10n ** 9n,
64-
gasLimit: 21_000,
82+
// 7. Listar EOAs que tengan la dirección como metadato
83+
const matchingEoas = await listEoas({
84+
client,
85+
request: {
86+
metadata: {
87+
externalAddress: TARGET_ADDRESS,
88+
},
89+
},
90+
});
91+
console.log("EOAs encontrados con esa dirección:", matchingEoas);
92+
}
93+
94+
// Ejecutar
95+
main().catch((err) => {
96+
console.error("Error durante la ejecución:", err);
6597
});
98+
✅ Requisitos
99+
Instala las dependencias si aún no las tienes:
100+
npm install @thirdweb-dev/vault-sdk dotenv
101+
Crea un archivo .env en la raíz del proyecto con tus claves:
102+
VAULT_SECRET_KEY=tu_clave_secreta_del_vault
103+
VAULT_SIG_TOKEN=tu_access_token_para_firmar
104+
VAULT_BASE_TOKEN=tu_access_token_base
105+
Ejecuta el script:
106+
ts-node vault-integration.ts
66107

67-
await signTransaction({
68-
client,
69-
request: {
70-
auth: { accessToken: process.env.VAULT_SIG_TOKEN! },
71-
options: { from: "0xEoaAddress", transaction: tx },
108+
Estructura del Proyecto
109+
vault-project/
110+
111+
├── .env.example
112+
├── .gitignore
113+
├── package.json
114+
├── tsconfig.json
115+
├── vault-integration.ts
116+
1. 📦 package.json
117+
{
118+
"name": "vault-project",
119+
"version": "1.0.0",
120+
"type": "module",
121+
"main": "vault-integration.ts",
122+
"scripts": {
123+
"start": "ts-node vault-integration.ts"
72124
},
73-
});
74-
```
75-
76-
> **Note**: `parseTransaction` is a convenience helper that normalises user-supplied objects – you can also build the canonical tx object yourself.
77-
78-
---
79-
80-
## 4. Access Tokens
81-
82-
| Function | Purpose |
83-
| --- | --- |
84-
| `createAccessToken` | Mint a **base token** scoped by policies & metadata. Requires **admin key**. |
85-
| `createSignedAccessToken` | Pure-client helper that turns a *base* token into a short-lived, signed JWT (prefixed with `vt_sat_`). No server round-trip required. |
86-
| `listAccessTokens` | List existing tokens with pagination and optional metadata filters. |
87-
| `revokeAccessToken` | Immediately invalidate a token (or all derived signed tokens) by `id`. |
88-
89-
```ts
90-
// Derive a time-boxed signed token for a serverless function
91-
const sat = await createSignedAccessToken({
92-
vaultClient: client,
93-
baseAccessToken: process.env.VAULT_BASE_TOKEN!,
94-
additionalPolicies: [
95-
{ type: "eoa:signMessage", chainId: 1, messagePattern: "^0x.*" },
96-
],
97-
expiryTimestamp: Math.floor(Date.now() / 1000) + 60 * 5, // 5 min
98-
});
99-
```
125+
"dependencies": {
126+
"@thirdweb-dev/vault-sdk": "^0.9.0",
127+
"dotenv": "^16.3.1"
128+
},
129+
"devDependencies": {
130+
"ts-node": "^10.9.1",
131+
"typescript": "^5.2.2"
132+
}
133+
}
134+
2. ⚙️ tsconfig.json
135+
{
136+
"compilerOptions": {
137+
"target": "ES2020",
138+
"module": "ESNext",
139+
"moduleResolution": "Node",
140+
"esModuleInterop": true,
141+
"skipLibCheck": true,
142+
"forceConsistentCasingInFileNames": true,
143+
"strict": true
144+
},
145+
"include": ["vault-integration.ts"]
146+
}
147+
3. 🗂 .env.example
148+
# Reemplaza estos valores en tu archivo .env
149+
VAULT_SECRET_KEY=tu_clave_secreta_del_vault
150+
VAULT_SIG_TOKEN=tu_access_token_para_firmar
151+
VAULT_BASE_TOKEN=tu_access_token_base
152+
4. 📄 .gitignore
153+
.env
154+
node_modules/
155+
dist/
100156

101-
---
157+
vault-integration.ts
158+
Este es el archivo que ya construimos antes. Puedes copiarlo directamente desde aquí arriba o te lo dejo resumido aquí de nuevo:
159+
<details> <summary>Ver el código</summary>
160+
import {
161+
createVaultClient,
162+
ping,
163+
createEoa,
164+
listEoas,
165+
parseTransaction,
166+
signTransaction,
167+
createAccessToken,
168+
} from "@thirdweb-dev/vault-sdk";
169+
import {
170+
createVaultClient,
171+
ping,
172+
createEoa,
173+
listEoas,
174+
parseTransaction,
175+
signTransaction,
176+
createAccessToken,
177+
} from "@thirdweb-dev/vault-sdk";
178+
import "dotenv/config";
102179

103-
## 5. Utilities
180+
// --- CONFIGURACIÓN ---
181+
const SECRET_KEY = process.env.VAULT_SECRET_KEY!;
182+
const SIG_TOKEN = process.env.VAULT_SIG_TOKEN!;
183+
const BASE_TOKEN = process.env.VAULT_BASE_TOKEN!;
104184

105-
| Function | Notes |
106-
| --- | --- |
107-
| `parseTransaction` | Normalises user input into a canonical `EthereumTypedTransaction` (supports Legacy, 2930, 1559, 4844, 7702). Throws `ParseTransactionError` on invalid input. |
108-
| `ParseTransactionError` | Custom error class thrown by the above helper. |
185+
const TARGET_ADDRESS = "0x6561fF4034De957fAFeA20b3aCC5E6E9FEb21aCE";
109186

110-
```ts
111-
try {
112-
parseTransaction({ gas: 100_000 });
113-
} catch (err) {
114-
if (err instanceof ParseTransactionError) {
115-
console.error(err.message);
116-
}
117-
}
118-
```
187+
async function main() {
188+
const client = await createVaultClient({ secretKey: SECRET_KEY });
189+
190+
const pingResult = await ping({ client, request: { message: "pong?" } });
191+
console.log("Ping response:", pingResult);
119192

120-
---
193+
const eoa = await createEoa({
194+
client,
195+
request: {
196+
metadata: {
197+
label: "Wallet externa",
198+
externalAddress: TARGET_ADDRESS,
199+
},
200+
},
201+
});
202+
console.log("Nuevo EOA creado:", eoa);
121203

122-
### Types
204+
const tx = parseTransaction({
205+
to: "0xAbC123456789abcdef123456789abcdef1234567",
206+
value: 0n,
207+
chainId: 1,
208+
maxFeePerGas: 30n * 10n ** 9n,
209+
maxPriorityFeePerGas: 1n * 10n ** 9n,
210+
gasLimit: 21_000,
211+
});
123212

124-
All request & response shapes are exported as TypeScript types so you can easily model higher-level abstractions:
213+
const signedTx = await signTransaction({
214+
client,
215+
request: {
216+
auth: { accessToken: SIG_TOKEN },
217+
options: {
218+
from: TARGET_ADDRESS,
219+
transaction: tx,
220+
},
221+
},
222+
});
223+
console.log("Transacción firmada:", signedTx);
125224

126-
```ts
127-
import type { CreateEoaPayload, SignMessagePayload, PolicyComponent } from "@thirdweb-dev/vault-sdk";
128-
```
225+
const token = await createAccessToken({
226+
client,
227+
request: {
228+
metadata: {
229+
name: "Token para wallet específica",
230+
wallet: TARGET_ADDRESS,
231+
},
232+
policies: [
233+
{
234+
type: "eoa:signMessage",
235+
chainId: 1,
236+
eoa: TARGET_ADDRESS,
237+
},
238+
],
239+
},
240+
});
241+
console.log("Access token creado:", token);
242+
243+
const matchingEoas = await listEoas({
244+
client,
245+
request: {
246+
metadata: {
247+
externalAddress: TARGET_ADDRESS,
248+
},
249+
},
250+
});
251+
console.log("EOAs encontrados:", matchingEoas);
252+
}
253+
254+
main().catch((err) => {
255+
console.error("Error:", err);
256+
});
257+
</details>
129258

130-
Refer to the generated `.d.ts` files for the complete list.
259+
Instrucciones para Ejecutar
260+
Clona o crea el proyecto:
261+
mkdir vault-project
262+
cd vault-project
263+
Copia los archivos arriba o usa npm init y crea el package.json manualmente.
264+
Instala dependencias:
265+
npm install
266+
Crea tu archivo .env desde el ejemplo:
267+
cp .env.example .env
268+
Edita .env con tus claves reales.
269+
Ejecuta el script:
270+
npm start

0 commit comments

Comments
 (0)