-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathembedded_wallet.ts
More file actions
201 lines (178 loc) · 7.39 KB
/
embedded_wallet.ts
File metadata and controls
201 lines (178 loc) · 7.39 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
import { getStubAccountContractArtifact, createStubAccount } from '@aztec/accounts/stub/lazy';
import { SchnorrAccountContract } from '@aztec/accounts/schnorr/lazy';
import { getPXEConfig, type PXEConfig } from '@aztec/pxe/config';
import { createPXE, PXE } from '@aztec/pxe/client/lazy';
import { AztecAddress } from '@aztec/stdlib/aztec-address';
import { getContractInstanceFromInstantiationParams } from '@aztec/stdlib/contract';
import { BlockHeader, mergeExecutionPayloads, type ExecutionPayload, type TxSimulationResult } from '@aztec/stdlib/tx';
import type { DefaultAccountEntrypointOptions } from '@aztec/entrypoints/account';
import { deriveSigningKey } from '@aztec/stdlib/keys';
import { SignerlessAccount, type Account, type AccountContract } from '@aztec/aztec.js/account';
import { AccountManager, type SimulateOptions } from '@aztec/aztec.js/wallet';
import type { AztecNode } from '@aztec/aztec.js/node';
import type { SimulateInteractionOptions } from '@aztec/aztec.js/contracts';
import { Fr, GrumpkinScalar } from '@aztec/aztec.js/fields';
import {
BaseWallet,
buildMergedSimulationResult,
extractOptimizablePublicStaticCalls,
simulateViaNode,
type FeeOptions,
} from '@aztec/wallet-sdk/base-wallet';
/**
* Data for generating an account.
*/
export interface AccountData {
/**
* Secret to derive the keys for the account.
*/
secret: Fr;
/**
* Contract address salt.
*/
salt: Fr;
/**
* Contract that backs the account.
*/
contract: AccountContract;
}
export class EmbeddedWallet extends BaseWallet {
protected accounts: Map<string, Account> = new Map();
constructor(pxe: PXE, aztecNode: AztecNode) {
super(pxe, aztecNode);
}
static async create(aztecNode: AztecNode) {
const l1Contracts = await aztecNode.getL1ContractAddresses();
const rollupAddress = l1Contracts.rollupAddress;
const config = getPXEConfig();
config.dataDirectory = `pxe-${rollupAddress}`;
config.proverEnabled = true;
const configWithContracts = {
...config,
l1Contracts,
} as PXEConfig;
const pxe = await createPXE(aztecNode, configWithContracts);
return new EmbeddedWallet(pxe, aztecNode);
}
private async createAccount(accountData?: AccountData): Promise<AccountManager> {
// Generate random values if not provided
const secret = accountData?.secret ?? Fr.random();
const salt = accountData?.salt ?? Fr.random();
// Use SchnorrAccountContract if not provided
const contract = accountData?.contract ?? new SchnorrAccountContract(GrumpkinScalar.random());
const accountManager = await AccountManager.create(this, secret, contract, salt);
const instance = accountManager.getInstance();
const artifact = await contract.getContractArtifact();
await this.registerContract(instance, artifact, secret);
this.accounts.set(accountManager.address.toString(), await accountManager.getAccount());
return accountManager;
}
protected async getAccountFromAddress(address: AztecAddress): Promise<Account> {
let account: Account | undefined;
if (address.equals(AztecAddress.ZERO)) {
account = new SignerlessAccount();
} else if (this.accounts.has(address.toString())) {
account = this.accounts.get(address.toString());
} else {
throw new Error(`Account with address ${address.toString()} not found in wallet`);
}
return account;
}
async getAccounts() {
if (this.accounts.size === 0) {
const accountManager = await this.createAccount({
salt: Fr.ZERO,
secret: Fr.ZERO,
contract: new SchnorrAccountContract(deriveSigningKey(Fr.ZERO)),
});
const account = await accountManager.getAccount();
this.accounts.set(accountManager.address.toString(), account);
}
return Array.from(this.accounts.values()).map(acc => ({ item: acc.getAddress(), alias: '' }));
}
private async getFakeAccountDataFor(address: AztecAddress) {
const originalAccount = await this.getAccountFromAddress(address);
const originalAddress = await originalAccount.getCompleteAddress();
const contractInstance = await this.pxe.getContractInstance(originalAddress.address);
if (!contractInstance) {
throw new Error(`No contract instance found for address: ${originalAddress.address}`);
}
const stubAccount = createStubAccount(originalAddress);
const StubAccountContractArtifact = await getStubAccountContractArtifact();
const instance = await getContractInstanceFromInstantiationParams(StubAccountContractArtifact, {
salt: Fr.random(),
});
return {
account: stubAccount,
instance,
artifact: StubAccountContractArtifact,
};
}
override async simulateTx(executionPayload: ExecutionPayload, opts: SimulateOptions): Promise<TxSimulationResult> {
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);
const { optimizableCalls, remainingCalls } = extractOptimizablePublicStaticCalls(executionPayload);
const remainingPayload = { ...executionPayload, calls: remainingCalls };
const chainInfo = await this.getChainInfo();
let blockHeader: BlockHeader;
// PXE might not be synced yet, so we pull the latest header from the node
// To keep things consistent, we'll always try with PXE first
try {
blockHeader = await this.pxe.getSyncedBlockHeader();
} catch {
blockHeader = (await this.aztecNode.getBlockHeader())!;
}
const [optimizedResults, normalResult] = await Promise.all([
optimizableCalls.length > 0
? simulateViaNode(
this.aztecNode,
optimizableCalls,
opts.from,
chainInfo,
feeOptions.gasSettings,
blockHeader,
opts.skipFeeEnforcement ?? true,
)
: Promise.resolve([]),
remainingCalls.length > 0
? this.simulateViaEntrypoint(
remainingPayload,
opts.from,
feeOptions,
opts.skipTxValidation,
opts.skipFeeEnforcement ?? true,
)
: Promise.resolve(null),
]);
return buildMergedSimulationResult(optimizedResults, normalResult);
}
protected override async simulateViaEntrypoint(
executionPayload: ExecutionPayload,
from: AztecAddress,
feeOptions: FeeOptions,
_skipTxValidation?: boolean,
_skipFeeEnforcement?: boolean,
): Promise<TxSimulationResult> {
const { account: fromAccount, instance, artifact } = await this.getFakeAccountDataFor(from);
const feeExecutionPayload = await feeOptions.walletFeePaymentMethod?.getExecutionPayload();
const executionOptions: DefaultAccountEntrypointOptions = {
txNonce: Fr.random(),
cancellable: this.cancellableTransactions,
feePaymentMethodOptions: feeOptions.accountFeePaymentMethodOptions,
};
const finalExecutionPayload = feeExecutionPayload
? mergeExecutionPayloads([feeExecutionPayload, executionPayload])
: executionPayload;
const chainInfo = await this.getChainInfo();
const txRequest = await fromAccount.createTxExecutionRequest(
finalExecutionPayload,
feeOptions.gasSettings,
chainInfo,
executionOptions,
);
return this.pxe.simulateTx(txRequest, true, true, true, {
contracts: { [from.toString()]: { instance, artifact } },
});
}
}