@aztec/wallet-sdk 0.0.1-commit.0208eb9
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/README.md +321 -0
- package/dest/base-wallet/base_wallet.d.ts +117 -0
- package/dest/base-wallet/base_wallet.d.ts.map +1 -0
- package/dest/base-wallet/base_wallet.js +271 -0
- package/dest/base-wallet/index.d.ts +2 -0
- package/dest/base-wallet/index.d.ts.map +1 -0
- package/dest/base-wallet/index.js +1 -0
- package/dest/crypto.d.ts +192 -0
- package/dest/crypto.d.ts.map +1 -0
- package/dest/crypto.js +394 -0
- package/dest/emoji_alphabet.d.ts +35 -0
- package/dest/emoji_alphabet.d.ts.map +1 -0
- package/dest/emoji_alphabet.js +299 -0
- package/dest/extension/handlers/background_connection_handler.d.ts +158 -0
- package/dest/extension/handlers/background_connection_handler.d.ts.map +1 -0
- package/dest/extension/handlers/background_connection_handler.js +258 -0
- package/dest/extension/handlers/content_script_connection_handler.d.ts +56 -0
- package/dest/extension/handlers/content_script_connection_handler.d.ts.map +1 -0
- package/dest/extension/handlers/content_script_connection_handler.js +174 -0
- package/dest/extension/handlers/index.d.ts +12 -0
- package/dest/extension/handlers/index.d.ts.map +1 -0
- package/dest/extension/handlers/index.js +10 -0
- package/dest/extension/handlers/internal_message_types.d.ts +63 -0
- package/dest/extension/handlers/internal_message_types.d.ts.map +1 -0
- package/dest/extension/handlers/internal_message_types.js +22 -0
- package/dest/extension/provider/extension_provider.d.ts +107 -0
- package/dest/extension/provider/extension_provider.d.ts.map +1 -0
- package/dest/extension/provider/extension_provider.js +160 -0
- package/dest/extension/provider/extension_wallet.d.ts +131 -0
- package/dest/extension/provider/extension_wallet.d.ts.map +1 -0
- package/dest/extension/provider/extension_wallet.js +271 -0
- package/dest/extension/provider/index.d.ts +3 -0
- package/dest/extension/provider/index.d.ts.map +1 -0
- package/dest/extension/provider/index.js +2 -0
- package/dest/manager/index.d.ts +3 -0
- package/dest/manager/index.d.ts.map +1 -0
- package/dest/manager/index.js +1 -0
- package/dest/manager/types.d.ts +167 -0
- package/dest/manager/types.d.ts.map +1 -0
- package/dest/manager/types.js +19 -0
- package/dest/manager/wallet_manager.d.ts +70 -0
- package/dest/manager/wallet_manager.d.ts.map +1 -0
- package/dest/manager/wallet_manager.js +226 -0
- package/dest/types.d.ts +123 -0
- package/dest/types.d.ts.map +1 -0
- package/dest/types.js +11 -0
- package/package.json +99 -0
- package/src/base-wallet/base_wallet.ts +394 -0
- package/src/base-wallet/index.ts +1 -0
- package/src/crypto.ts +499 -0
- package/src/emoji_alphabet.ts +317 -0
- package/src/extension/handlers/background_connection_handler.ts +423 -0
- package/src/extension/handlers/content_script_connection_handler.ts +246 -0
- package/src/extension/handlers/index.ts +25 -0
- package/src/extension/handlers/internal_message_types.ts +69 -0
- package/src/extension/provider/extension_provider.ts +233 -0
- package/src/extension/provider/extension_wallet.ts +321 -0
- package/src/extension/provider/index.ts +7 -0
- package/src/manager/index.ts +12 -0
- package/src/manager/types.ts +177 -0
- package/src/manager/wallet_manager.ts +259 -0
- package/src/types.ts +132 -0
|
@@ -0,0 +1,271 @@
|
|
|
1
|
+
import { NO_WAIT } from '@aztec/aztec.js/contracts';
|
|
2
|
+
import { waitForTx } from '@aztec/aztec.js/node';
|
|
3
|
+
import { GAS_ESTIMATION_DA_GAS_LIMIT, GAS_ESTIMATION_L2_GAS_LIMIT, GAS_ESTIMATION_TEARDOWN_DA_GAS_LIMIT, GAS_ESTIMATION_TEARDOWN_L2_GAS_LIMIT } from '@aztec/constants';
|
|
4
|
+
import { AccountFeePaymentMethodOptions } from '@aztec/entrypoints/account';
|
|
5
|
+
import { Fr } from '@aztec/foundation/curves/bn254';
|
|
6
|
+
import { createLogger } from '@aztec/foundation/log';
|
|
7
|
+
import { decodeFromAbi } from '@aztec/stdlib/abi';
|
|
8
|
+
import { computePartialAddress, getContractClassFromArtifact } from '@aztec/stdlib/contract';
|
|
9
|
+
import { SimulationError } from '@aztec/stdlib/errors';
|
|
10
|
+
import { Gas, GasSettings } from '@aztec/stdlib/gas';
|
|
11
|
+
import { siloNullifier } from '@aztec/stdlib/hash';
|
|
12
|
+
import { mergeExecutionPayloads } from '@aztec/stdlib/tx';
|
|
13
|
+
import { inspect } from 'util';
|
|
14
|
+
/**
|
|
15
|
+
* A base class for Wallet implementations
|
|
16
|
+
*/ export class BaseWallet {
|
|
17
|
+
pxe;
|
|
18
|
+
aztecNode;
|
|
19
|
+
log;
|
|
20
|
+
minFeePadding;
|
|
21
|
+
cancellableTransactions;
|
|
22
|
+
// Protected because we want to force wallets to instantiate their own PXE.
|
|
23
|
+
constructor(pxe, aztecNode){
|
|
24
|
+
this.pxe = pxe;
|
|
25
|
+
this.aztecNode = aztecNode;
|
|
26
|
+
this.log = createLogger('wallet-sdk:base_wallet');
|
|
27
|
+
this.minFeePadding = 0.5;
|
|
28
|
+
this.cancellableTransactions = false;
|
|
29
|
+
}
|
|
30
|
+
/**
|
|
31
|
+
* Returns the list of aliased contacts associated with the wallet.
|
|
32
|
+
* This base implementation directly returns PXE's senders, but note that in general contacts are a superset of senders.
|
|
33
|
+
* - Senders: Addresses we check during synching in case they sent us notes,
|
|
34
|
+
* - Contacts: more general concept akin to a phone's contact list.
|
|
35
|
+
* @returns The aliased collection of AztecAddresses that form this wallet's address book
|
|
36
|
+
*/ async getAddressBook() {
|
|
37
|
+
const senders = await this.pxe.getSenders();
|
|
38
|
+
return senders.map((sender)=>({
|
|
39
|
+
item: sender,
|
|
40
|
+
alias: ''
|
|
41
|
+
}));
|
|
42
|
+
}
|
|
43
|
+
async getChainInfo() {
|
|
44
|
+
const { l1ChainId, rollupVersion } = await this.aztecNode.getNodeInfo();
|
|
45
|
+
return {
|
|
46
|
+
chainId: new Fr(l1ChainId),
|
|
47
|
+
version: new Fr(rollupVersion)
|
|
48
|
+
};
|
|
49
|
+
}
|
|
50
|
+
async createTxExecutionRequestFromPayloadAndFee(executionPayload, from, feeOptions) {
|
|
51
|
+
const feeExecutionPayload = await feeOptions.walletFeePaymentMethod?.getExecutionPayload();
|
|
52
|
+
const executionOptions = {
|
|
53
|
+
txNonce: Fr.random(),
|
|
54
|
+
cancellable: this.cancellableTransactions,
|
|
55
|
+
feePaymentMethodOptions: feeOptions.accountFeePaymentMethodOptions
|
|
56
|
+
};
|
|
57
|
+
const finalExecutionPayload = feeExecutionPayload ? mergeExecutionPayloads([
|
|
58
|
+
feeExecutionPayload,
|
|
59
|
+
executionPayload
|
|
60
|
+
]) : executionPayload;
|
|
61
|
+
const fromAccount = await this.getAccountFromAddress(from);
|
|
62
|
+
const chainInfo = await this.getChainInfo();
|
|
63
|
+
return fromAccount.createTxExecutionRequest(finalExecutionPayload, feeOptions.gasSettings, chainInfo, executionOptions);
|
|
64
|
+
}
|
|
65
|
+
async createAuthWit(from, messageHashOrIntent) {
|
|
66
|
+
const account = await this.getAccountFromAddress(from);
|
|
67
|
+
const chainInfo = await this.getChainInfo();
|
|
68
|
+
return account.createAuthWit(messageHashOrIntent, chainInfo);
|
|
69
|
+
}
|
|
70
|
+
/**
|
|
71
|
+
* Request capabilities from the wallet.
|
|
72
|
+
*
|
|
73
|
+
* This method is wallet-implementation-dependent and must be provided by classes extending BaseWallet.
|
|
74
|
+
* Embedded wallets typically don't support capability-based authorization (no user authorization flow),
|
|
75
|
+
* while external wallets (browser extensions, hardware wallets) implement this to reduce authorization
|
|
76
|
+
* friction by allowing apps to request permissions upfront.
|
|
77
|
+
*
|
|
78
|
+
* TODO: Consider making it abstract so implementing it is a conscious decision. Leaving it as-is
|
|
79
|
+
* while the feature stabilizes.
|
|
80
|
+
*
|
|
81
|
+
* @param _manifest - Application capability manifest declaring what operations the app needs
|
|
82
|
+
*/ requestCapabilities(_manifest) {
|
|
83
|
+
throw new Error('Not implemented');
|
|
84
|
+
}
|
|
85
|
+
async batch(methods) {
|
|
86
|
+
const results = [];
|
|
87
|
+
for (const method of methods){
|
|
88
|
+
const { name, args } = method;
|
|
89
|
+
// Type safety is guaranteed by the BatchedMethod type, which ensures that:
|
|
90
|
+
// 1. `name` is a valid batchable method name
|
|
91
|
+
// 2. `args` matches the parameter types of that specific method
|
|
92
|
+
// 3. The return type is correctly mapped in BatchResults<T>
|
|
93
|
+
// We use dynamic dispatch here for simplicity, but the types are enforced at the call site.
|
|
94
|
+
const fn = this[name];
|
|
95
|
+
const result = await fn.apply(this, args);
|
|
96
|
+
// Wrap result with method name for discriminated union deserialization
|
|
97
|
+
results.push({
|
|
98
|
+
name,
|
|
99
|
+
result
|
|
100
|
+
});
|
|
101
|
+
}
|
|
102
|
+
return results;
|
|
103
|
+
}
|
|
104
|
+
/**
|
|
105
|
+
* Completes partial user-provided fee options with wallet defaults.
|
|
106
|
+
* @param from - The address where the transaction is being sent from
|
|
107
|
+
* @param feePayer - The address paying for fees (if any fee payment method is embedded in the execution payload)
|
|
108
|
+
* @param gasSettings - User-provided partial gas settings
|
|
109
|
+
* @returns - Complete fee options that can be used to create a transaction execution request
|
|
110
|
+
*/ async completeFeeOptions(from, feePayer, gasSettings) {
|
|
111
|
+
const maxFeesPerGas = gasSettings?.maxFeesPerGas ?? (await this.aztecNode.getCurrentMinFees()).mul(1 + this.minFeePadding);
|
|
112
|
+
let accountFeePaymentMethodOptions;
|
|
113
|
+
// The transaction does not include a fee payment method, so we set the flag
|
|
114
|
+
// for the account to use its fee juice balance
|
|
115
|
+
if (!feePayer) {
|
|
116
|
+
accountFeePaymentMethodOptions = AccountFeePaymentMethodOptions.PREEXISTING_FEE_JUICE;
|
|
117
|
+
} else {
|
|
118
|
+
// The transaction includes fee payment method, so we check if we are the fee payer for it
|
|
119
|
+
// (this can only happen if the embedded payment method is FeeJuiceWithClaim)
|
|
120
|
+
accountFeePaymentMethodOptions = from.equals(feePayer) ? AccountFeePaymentMethodOptions.FEE_JUICE_WITH_CLAIM : AccountFeePaymentMethodOptions.EXTERNAL;
|
|
121
|
+
}
|
|
122
|
+
const fullGasSettings = GasSettings.default({
|
|
123
|
+
...gasSettings,
|
|
124
|
+
maxFeesPerGas
|
|
125
|
+
});
|
|
126
|
+
this.log.debug(`Using L2 gas settings`, fullGasSettings);
|
|
127
|
+
return {
|
|
128
|
+
gasSettings: fullGasSettings,
|
|
129
|
+
walletFeePaymentMethod: undefined,
|
|
130
|
+
accountFeePaymentMethodOptions
|
|
131
|
+
};
|
|
132
|
+
}
|
|
133
|
+
/**
|
|
134
|
+
* Completes partial user-provided fee options with unreasonably high gas limits
|
|
135
|
+
* for gas estimation. Uses the same logic as completeFeeOptions but sets high limits
|
|
136
|
+
* to avoid running out of gas during estimation.
|
|
137
|
+
* @param from - The address where the transaction is being sent from
|
|
138
|
+
* @param feePayer - The address paying for fees (if any fee payment method is embedded in the execution payload)
|
|
139
|
+
* @param gasSettings - User-provided partial gas settings
|
|
140
|
+
*/ async completeFeeOptionsForEstimation(from, feePayer, gasSettings) {
|
|
141
|
+
const defaultFeeOptions = await this.completeFeeOptions(from, feePayer, gasSettings);
|
|
142
|
+
const { gasSettings: { maxFeesPerGas, maxPriorityFeesPerGas } } = defaultFeeOptions;
|
|
143
|
+
// Use unrealistically high gas limits for estimation to avoid running out of gas.
|
|
144
|
+
// They will be tuned down after the simulation.
|
|
145
|
+
const gasSettingsForEstimation = new GasSettings(new Gas(GAS_ESTIMATION_DA_GAS_LIMIT, GAS_ESTIMATION_L2_GAS_LIMIT), new Gas(GAS_ESTIMATION_TEARDOWN_DA_GAS_LIMIT, GAS_ESTIMATION_TEARDOWN_L2_GAS_LIMIT), maxFeesPerGas, maxPriorityFeesPerGas);
|
|
146
|
+
return {
|
|
147
|
+
...defaultFeeOptions,
|
|
148
|
+
gasSettings: gasSettingsForEstimation
|
|
149
|
+
};
|
|
150
|
+
}
|
|
151
|
+
registerSender(address, _alias = '') {
|
|
152
|
+
return this.pxe.registerSender(address);
|
|
153
|
+
}
|
|
154
|
+
async registerContract(instance, artifact, secretKey) {
|
|
155
|
+
const existingInstance = await this.pxe.getContractInstance(instance.address);
|
|
156
|
+
if (existingInstance) {
|
|
157
|
+
// Instance already registered in the wallet
|
|
158
|
+
if (artifact) {
|
|
159
|
+
const thisContractClass = await getContractClassFromArtifact(artifact);
|
|
160
|
+
if (!thisContractClass.id.equals(existingInstance.currentContractClassId)) {
|
|
161
|
+
// wallet holds an outdated version of this contract
|
|
162
|
+
await this.pxe.updateContract(instance.address, artifact);
|
|
163
|
+
instance.currentContractClassId = thisContractClass.id;
|
|
164
|
+
}
|
|
165
|
+
}
|
|
166
|
+
// If no artifact provided, we just use the existing registration
|
|
167
|
+
} else {
|
|
168
|
+
// Instance not registered yet
|
|
169
|
+
if (!artifact) {
|
|
170
|
+
// Try to get the artifact from the wallet's contract class storage
|
|
171
|
+
artifact = await this.pxe.getContractArtifact(instance.currentContractClassId);
|
|
172
|
+
if (!artifact) {
|
|
173
|
+
throw new Error(`Cannot register contract at ${instance.address.toString()}: artifact is required but not provided, and wallet does not have the artifact for contract class ${instance.currentContractClassId.toString()}`);
|
|
174
|
+
}
|
|
175
|
+
}
|
|
176
|
+
await this.pxe.registerContract({
|
|
177
|
+
artifact,
|
|
178
|
+
instance
|
|
179
|
+
});
|
|
180
|
+
}
|
|
181
|
+
if (secretKey) {
|
|
182
|
+
await this.pxe.registerAccount(secretKey, await computePartialAddress(instance));
|
|
183
|
+
}
|
|
184
|
+
return instance;
|
|
185
|
+
}
|
|
186
|
+
async simulateTx(executionPayload, opts) {
|
|
187
|
+
const feeOptions = opts.fee?.estimateGas ? await this.completeFeeOptionsForEstimation(opts.from, executionPayload.feePayer, opts.fee?.gasSettings) : await this.completeFeeOptions(opts.from, executionPayload.feePayer, opts.fee?.gasSettings);
|
|
188
|
+
const txRequest = await this.createTxExecutionRequestFromPayloadAndFee(executionPayload, opts.from, feeOptions);
|
|
189
|
+
return this.pxe.simulateTx(txRequest, true, opts?.skipTxValidation, opts?.skipFeeEnforcement ?? true);
|
|
190
|
+
}
|
|
191
|
+
async profileTx(executionPayload, opts) {
|
|
192
|
+
const feeOptions = await this.completeFeeOptions(opts.from, executionPayload.feePayer, opts.fee?.gasSettings);
|
|
193
|
+
const txRequest = await this.createTxExecutionRequestFromPayloadAndFee(executionPayload, opts.from, feeOptions);
|
|
194
|
+
return this.pxe.profileTx(txRequest, opts.profileMode, opts.skipProofGeneration ?? true);
|
|
195
|
+
}
|
|
196
|
+
async sendTx(executionPayload, opts) {
|
|
197
|
+
const feeOptions = await this.completeFeeOptions(opts.from, executionPayload.feePayer, opts.fee?.gasSettings);
|
|
198
|
+
const txRequest = await this.createTxExecutionRequestFromPayloadAndFee(executionPayload, opts.from, feeOptions);
|
|
199
|
+
const provenTx = await this.pxe.proveTx(txRequest);
|
|
200
|
+
const tx = await provenTx.toTx();
|
|
201
|
+
const txHash = tx.getTxHash();
|
|
202
|
+
if (await this.aztecNode.getTxEffect(txHash)) {
|
|
203
|
+
throw new Error(`A settled tx with equal hash ${txHash.toString()} exists.`);
|
|
204
|
+
}
|
|
205
|
+
this.log.debug(`Sending transaction ${txHash}`);
|
|
206
|
+
await this.aztecNode.sendTx(tx).catch((err)=>{
|
|
207
|
+
throw this.contextualizeError(err, inspect(tx));
|
|
208
|
+
});
|
|
209
|
+
this.log.info(`Sent transaction ${txHash}`);
|
|
210
|
+
// If wait is NO_WAIT, return txHash immediately
|
|
211
|
+
if (opts.wait === NO_WAIT) {
|
|
212
|
+
return txHash;
|
|
213
|
+
}
|
|
214
|
+
// Otherwise, wait for the full receipt (default behavior on wait: undefined)
|
|
215
|
+
const waitOpts = typeof opts.wait === 'object' ? opts.wait : undefined;
|
|
216
|
+
return await waitForTx(this.aztecNode, txHash, waitOpts);
|
|
217
|
+
}
|
|
218
|
+
contextualizeError(err, ...context) {
|
|
219
|
+
let contextStr = '';
|
|
220
|
+
if (context.length > 0) {
|
|
221
|
+
contextStr = `\nContext:\n${context.join('\n')}`;
|
|
222
|
+
}
|
|
223
|
+
if (err instanceof SimulationError) {
|
|
224
|
+
err.setAztecContext(contextStr);
|
|
225
|
+
} else {
|
|
226
|
+
this.log.error(err.name, err);
|
|
227
|
+
this.log.debug(contextStr);
|
|
228
|
+
}
|
|
229
|
+
return err;
|
|
230
|
+
}
|
|
231
|
+
simulateUtility(call, authwits) {
|
|
232
|
+
return this.pxe.simulateUtility(call, authwits);
|
|
233
|
+
}
|
|
234
|
+
async getPrivateEvents(eventDef, eventFilter) {
|
|
235
|
+
const pxeEvents = await this.pxe.getPrivateEvents(eventDef.eventSelector, eventFilter);
|
|
236
|
+
const decodedEvents = pxeEvents.map((pxeEvent)=>{
|
|
237
|
+
return {
|
|
238
|
+
event: decodeFromAbi([
|
|
239
|
+
eventDef.abiType
|
|
240
|
+
], pxeEvent.packedEvent),
|
|
241
|
+
metadata: {
|
|
242
|
+
l2BlockNumber: pxeEvent.l2BlockNumber,
|
|
243
|
+
l2BlockHash: pxeEvent.l2BlockHash,
|
|
244
|
+
txHash: pxeEvent.txHash
|
|
245
|
+
}
|
|
246
|
+
};
|
|
247
|
+
});
|
|
248
|
+
return decodedEvents;
|
|
249
|
+
}
|
|
250
|
+
async getContractMetadata(address) {
|
|
251
|
+
const instance = await this.pxe.getContractInstance(address);
|
|
252
|
+
const initNullifier = await siloNullifier(address, address.toField());
|
|
253
|
+
const publiclyRegisteredContract = await this.aztecNode.getContract(address);
|
|
254
|
+
const initNullifierMembershipWitness = await this.aztecNode.getNullifierMembershipWitness('latest', initNullifier);
|
|
255
|
+
const isContractUpdated = publiclyRegisteredContract && !publiclyRegisteredContract.currentContractClassId.equals(publiclyRegisteredContract.originalContractClassId);
|
|
256
|
+
return {
|
|
257
|
+
instance: instance ?? undefined,
|
|
258
|
+
isContractInitialized: !!initNullifierMembershipWitness,
|
|
259
|
+
isContractPublished: !!publiclyRegisteredContract,
|
|
260
|
+
isContractUpdated: !!isContractUpdated,
|
|
261
|
+
updatedContractClassId: isContractUpdated ? publiclyRegisteredContract.currentContractClassId : undefined
|
|
262
|
+
};
|
|
263
|
+
}
|
|
264
|
+
async getContractClassMetadata(id) {
|
|
265
|
+
const publiclyRegisteredContractClass = await this.aztecNode.getContractClass(id);
|
|
266
|
+
return {
|
|
267
|
+
isArtifactRegistered: !!await this.pxe.getContractArtifact(id),
|
|
268
|
+
isContractClassPubliclyRegistered: !!publiclyRegisteredContractClass
|
|
269
|
+
};
|
|
270
|
+
}
|
|
271
|
+
}
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
export { BaseWallet, type FeeOptions } from './base_wallet.js';
|
|
2
|
+
//# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiaW5kZXguZC50cyIsInNvdXJjZVJvb3QiOiIiLCJzb3VyY2VzIjpbIi4uLy4uL3NyYy9iYXNlLXdhbGxldC9pbmRleC50cyJdLCJuYW1lcyI6W10sIm1hcHBpbmdzIjoiQUFBQSxPQUFPLEVBQUUsVUFBVSxFQUFFLEtBQUssVUFBVSxFQUFFLE1BQU0sa0JBQWtCLENBQUMifQ==
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/base-wallet/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAE,KAAK,UAAU,EAAE,MAAM,kBAAkB,CAAC"}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export { BaseWallet } from './base_wallet.js';
|
package/dest/crypto.d.ts
ADDED
|
@@ -0,0 +1,192 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Exported public key in JWK format for transmission over untrusted channels.
|
|
3
|
+
*
|
|
4
|
+
* Contains only the public components of an ECDH P-256 key, safe to share.
|
|
5
|
+
*/
|
|
6
|
+
export interface ExportedPublicKey {
|
|
7
|
+
/** Key type - always "EC" for elliptic curve */
|
|
8
|
+
kty: string;
|
|
9
|
+
/** Curve name - always "P-256" */
|
|
10
|
+
crv: string;
|
|
11
|
+
/** X coordinate (base64url encoded) */
|
|
12
|
+
x: string;
|
|
13
|
+
/** Y coordinate (base64url encoded) */
|
|
14
|
+
y: string;
|
|
15
|
+
}
|
|
16
|
+
/**
|
|
17
|
+
* Encrypted message payload containing ciphertext and initialization vector.
|
|
18
|
+
*
|
|
19
|
+
* Both fields are base64-encoded for safe transmission as JSON.
|
|
20
|
+
*/
|
|
21
|
+
export interface EncryptedPayload {
|
|
22
|
+
/** Initialization vector (base64 encoded, 12 bytes) */
|
|
23
|
+
iv: string;
|
|
24
|
+
/** Ciphertext (base64 encoded) */
|
|
25
|
+
ciphertext: string;
|
|
26
|
+
}
|
|
27
|
+
/**
|
|
28
|
+
* ECDH key pair for secure communication.
|
|
29
|
+
*
|
|
30
|
+
* The private key should never be exported or transmitted.
|
|
31
|
+
* The public key can be exported via {@link exportPublicKey} for exchange.
|
|
32
|
+
*/
|
|
33
|
+
export interface SecureKeyPair {
|
|
34
|
+
/** Public key - safe to share */
|
|
35
|
+
publicKey: CryptoKey;
|
|
36
|
+
/** Private key - keep secret, used for key derivation */
|
|
37
|
+
privateKey: CryptoKey;
|
|
38
|
+
}
|
|
39
|
+
/**
|
|
40
|
+
* Session keys derived from ECDH key exchange.
|
|
41
|
+
*
|
|
42
|
+
* Contains both the encryption key and the verification hash (verificationHash)
|
|
43
|
+
* computed from a separate HMAC key.
|
|
44
|
+
*/
|
|
45
|
+
export interface SessionKeys {
|
|
46
|
+
/** AES-256-GCM key for message encryption/decryption */
|
|
47
|
+
encryptionKey: CryptoKey;
|
|
48
|
+
/** Hex-encoded verificationHash for verification */
|
|
49
|
+
verificationHash: string;
|
|
50
|
+
}
|
|
51
|
+
/**
|
|
52
|
+
* Generates an ECDH P-256 key pair for key exchange.
|
|
53
|
+
*
|
|
54
|
+
* The generated key pair can be used to derive session keys with another
|
|
55
|
+
* party's public key using {@link deriveSessionKeys}.
|
|
56
|
+
*
|
|
57
|
+
* @returns A new ECDH key pair
|
|
58
|
+
*
|
|
59
|
+
* @example
|
|
60
|
+
* ```typescript
|
|
61
|
+
* const keyPair = await generateKeyPair();
|
|
62
|
+
* const publicKey = await exportPublicKey(keyPair.publicKey);
|
|
63
|
+
* // Send publicKey to the other party
|
|
64
|
+
* ```
|
|
65
|
+
*/
|
|
66
|
+
export declare function generateKeyPair(): Promise<SecureKeyPair>;
|
|
67
|
+
/**
|
|
68
|
+
* Exports a public key to JWK format for transmission.
|
|
69
|
+
*
|
|
70
|
+
* The exported key contains only public components and is safe to transmit
|
|
71
|
+
* over untrusted channels.
|
|
72
|
+
*
|
|
73
|
+
* @param publicKey - The CryptoKey public key to export
|
|
74
|
+
* @returns The public key in JWK format
|
|
75
|
+
*
|
|
76
|
+
* @example
|
|
77
|
+
* ```typescript
|
|
78
|
+
* const keyPair = await generateKeyPair();
|
|
79
|
+
* const exported = await exportPublicKey(keyPair.publicKey);
|
|
80
|
+
* // exported can be JSON serialized and sent to another party
|
|
81
|
+
* ```
|
|
82
|
+
*/
|
|
83
|
+
export declare function exportPublicKey(publicKey: CryptoKey): Promise<ExportedPublicKey>;
|
|
84
|
+
/**
|
|
85
|
+
* Imports a public key from JWK format.
|
|
86
|
+
*
|
|
87
|
+
* Used to import the other party's public key for deriving session keys.
|
|
88
|
+
*
|
|
89
|
+
* @param exported - The public key in JWK format
|
|
90
|
+
* @returns A CryptoKey that can be used with {@link deriveSessionKeys}
|
|
91
|
+
*
|
|
92
|
+
* @example
|
|
93
|
+
* ```typescript
|
|
94
|
+
* // App side: receive wallet's public key and derive session
|
|
95
|
+
* const walletPublicKey = await importPublicKey(receivedWalletKey);
|
|
96
|
+
* const session = await deriveSessionKeys(appKeyPair, walletPublicKey, true);
|
|
97
|
+
* ```
|
|
98
|
+
*/
|
|
99
|
+
export declare function importPublicKey(exported: ExportedPublicKey): Promise<CryptoKey>;
|
|
100
|
+
/**
|
|
101
|
+
* Derives session keys from ECDH key exchange using HKDF.
|
|
102
|
+
*
|
|
103
|
+
* This is the main key derivation function that produces:
|
|
104
|
+
* 1. An AES-256-GCM encryption key (first 256 bits)
|
|
105
|
+
* 2. An HMAC key for verificationHash computation (second 256 bits)
|
|
106
|
+
* 3. A verificationHash computed as HMAC(hmacKey, "aztec-wallet-verification-verificationHash")
|
|
107
|
+
*
|
|
108
|
+
* The keys are derived using a single HKDF call that produces 512 bits,
|
|
109
|
+
* then split into the two keys.
|
|
110
|
+
*
|
|
111
|
+
* @param ownKeyPair - The caller's ECDH key pair (private for ECDH, public for salt)
|
|
112
|
+
* @param peerPublicKey - The peer's ECDH public key (for ECDH and salt)
|
|
113
|
+
* @param isApp - true if caller is the app, false if caller is the wallet
|
|
114
|
+
* @returns Session keys containing encryption key and verificationHash
|
|
115
|
+
*
|
|
116
|
+
* @example
|
|
117
|
+
* ```typescript
|
|
118
|
+
* // App side
|
|
119
|
+
* const sessionA = await deriveSessionKeys(appKeyPair, walletPublicKey, true);
|
|
120
|
+
* // Wallet side
|
|
121
|
+
* const sessionB = await deriveSessionKeys(walletKeyPair, appPublicKey, false);
|
|
122
|
+
* // sessionA.verificationHash === sessionB.verificationHash
|
|
123
|
+
* ```
|
|
124
|
+
*/
|
|
125
|
+
export declare function deriveSessionKeys(ownKeyPair: SecureKeyPair, peerPublicKey: CryptoKey, isApp: boolean): Promise<SessionKeys>;
|
|
126
|
+
/**
|
|
127
|
+
* Encrypts data using AES-256-GCM.
|
|
128
|
+
*
|
|
129
|
+
* A random 12-byte IV is generated for each encryption operation.
|
|
130
|
+
*
|
|
131
|
+
* AES-GCM provides both confidentiality and authenticity - any tampering
|
|
132
|
+
* with the ciphertext will cause decryption to fail.
|
|
133
|
+
*
|
|
134
|
+
* @param key - The AES-GCM key (from {@link deriveSessionKeys})
|
|
135
|
+
* @param data - The string data to encrypt (caller is responsible for serialization)
|
|
136
|
+
* @returns The encrypted payload with IV and ciphertext
|
|
137
|
+
*
|
|
138
|
+
* @example
|
|
139
|
+
* ```typescript
|
|
140
|
+
* const encrypted = await encrypt(session.encryptionKey, JSON.stringify({ action: 'transfer', amount: 100 }));
|
|
141
|
+
* // encrypted.iv and encrypted.ciphertext are base64 strings
|
|
142
|
+
* ```
|
|
143
|
+
*/
|
|
144
|
+
export declare function encrypt(key: CryptoKey, data: string): Promise<EncryptedPayload>;
|
|
145
|
+
/**
|
|
146
|
+
* Decrypts data using AES-256-GCM.
|
|
147
|
+
*
|
|
148
|
+
* The decrypted data is JSON parsed before returning.
|
|
149
|
+
*
|
|
150
|
+
* @typeParam T - The expected type of the decrypted data
|
|
151
|
+
* @param key - The AES-GCM key (from {@link deriveSessionKeys})
|
|
152
|
+
* @param payload - The encrypted payload from {@link encrypt}
|
|
153
|
+
* @returns The decrypted and parsed data
|
|
154
|
+
*
|
|
155
|
+
* @throws Error if decryption fails (wrong key or tampered ciphertext)
|
|
156
|
+
*
|
|
157
|
+
* @example
|
|
158
|
+
* ```typescript
|
|
159
|
+
* const decrypted = await decrypt<{ action: string; amount: number }>(session.encryptionKey, encrypted);
|
|
160
|
+
* console.log(decrypted.action); // 'transfer'
|
|
161
|
+
* ```
|
|
162
|
+
*/
|
|
163
|
+
export declare function decrypt<T = unknown>(key: CryptoKey, payload: EncryptedPayload): Promise<T>;
|
|
164
|
+
/**
|
|
165
|
+
* Default grid size for emoji verification display.
|
|
166
|
+
* 3x3 grid = 9 emojis = 72 bits of security.
|
|
167
|
+
*/
|
|
168
|
+
export declare const DEFAULT_EMOJI_GRID_SIZE = 9;
|
|
169
|
+
/**
|
|
170
|
+
* Converts a hex hash to an emoji sequence for visual verification.
|
|
171
|
+
*
|
|
172
|
+
* This is used for verification - both the dApp and wallet
|
|
173
|
+
* independently compute the same emoji sequence from the derived keys.
|
|
174
|
+
* Users can visually compare the sequences to detect interception.
|
|
175
|
+
*
|
|
176
|
+
* With a 256-emoji alphabet and 9 emojis (3x3 grid), this provides
|
|
177
|
+
* 72 bits of security (9 * 8 = 72 bits), making brute-force attacks
|
|
178
|
+
* computationally infeasible.
|
|
179
|
+
*
|
|
180
|
+
* @param hash - Hex string from verification hash (64 chars = 32 bytes)
|
|
181
|
+
* @param count - Number of emojis to generate (default: 9 for 3x3 grid)
|
|
182
|
+
* @returns A string of emojis representing the hash
|
|
183
|
+
*
|
|
184
|
+
* @example
|
|
185
|
+
* ```typescript
|
|
186
|
+
* const session = await deriveSessionKeys(...);
|
|
187
|
+
* const emoji = hashToEmoji(session.verificationHash); // e.g., "π΅π¦π―πΌππ²π¦πΈπ"
|
|
188
|
+
* // Display as 3x3 grid to user for verification
|
|
189
|
+
* ```
|
|
190
|
+
*/
|
|
191
|
+
export declare function hashToEmoji(hash: string, count?: number): string;
|
|
192
|
+
//# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiY3J5cHRvLmQudHMiLCJzb3VyY2VSb290IjoiIiwic291cmNlcyI6WyIuLi9zcmMvY3J5cHRvLnRzIl0sIm5hbWVzIjpbXSwibWFwcGluZ3MiOiJBQThEQTs7OztHQUlHO0FBQ0gsTUFBTSxXQUFXLGlCQUFpQjtJQUNoQyxnREFBZ0Q7SUFDaEQsR0FBRyxFQUFFLE1BQU0sQ0FBQztJQUNaLGtDQUFrQztJQUNsQyxHQUFHLEVBQUUsTUFBTSxDQUFDO0lBQ1osdUNBQXVDO0lBQ3ZDLENBQUMsRUFBRSxNQUFNLENBQUM7SUFDVix1Q0FBdUM7SUFDdkMsQ0FBQyxFQUFFLE1BQU0sQ0FBQztDQUNYO0FBRUQ7Ozs7R0FJRztBQUNILE1BQU0sV0FBVyxnQkFBZ0I7SUFDL0IsdURBQXVEO0lBQ3ZELEVBQUUsRUFBRSxNQUFNLENBQUM7SUFDWCxrQ0FBa0M7SUFDbEMsVUFBVSxFQUFFLE1BQU0sQ0FBQztDQUNwQjtBQUVEOzs7OztHQUtHO0FBQ0gsTUFBTSxXQUFXLGFBQWE7SUFDNUIsaUNBQWlDO0lBQ2pDLFNBQVMsRUFBRSxTQUFTLENBQUM7SUFDckIseURBQXlEO0lBQ3pELFVBQVUsRUFBRSxTQUFTLENBQUM7Q0FDdkI7QUFFRDs7Ozs7R0FLRztBQUNILE1BQU0sV0FBVyxXQUFXO0lBQzFCLHdEQUF3RDtJQUN4RCxhQUFh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