-
Notifications
You must be signed in to change notification settings - Fork 509
/
Copy pathindex.ts
224 lines (212 loc) · 6.7 KB
/
index.ts
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
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
import type { Chain } from "../../chains/types.js";
import type { Hex } from "../../utils/encoding/hex.js";
import { toHex } from "../../utils/encoding/hex.js";
import type { Account, SendTransactionOption } from "../interfaces/wallet.js";
/**
* Options for creating an engine account.
*/
export type EngineAccountOptions = {
/**
* The URL of your engine instance.
*/
engineUrl: string;
/**
* The auth token to use with the engine instance.
*/
authToken: string;
/**
* The backend wallet to use for sending transactions inside engine.
*/
walletAddress: string;
overrides?: {
/**
* The address of the smart account to act on behalf of. Requires your backend wallet to be a valid signer on that smart account.
*/
accountAddress?: string;
/**
* The address of the smart account factory to use for creating smart accounts.
*/
accountFactoryAddress?: string;
/**
* The salt to use for creating the smart account.
*/
accountSalt?: string;
};
/**
* The chain to use for signing messages and typed data (smart backend wallet only).
*/
chain?: Chain;
};
/**
* Creates an account that uses your engine backend wallet for sending transactions and signing messages.
*
* @param options - The options for the engine account.
* @returns An account that uses your engine backend wallet.
*
* @beta
* @wallet
*
* @example
* ```ts
* import { engineAccount } from "thirdweb/wallets/engine";
*
* const engineAcc = engineAccount({
* engineUrl: "https://engine.thirdweb.com",
* authToken: "your-auth-token",
* walletAddress: "0x...",
* });
*
* // then use the account as you would any other account
* const transaction = claimTo({
* contract,
* to: "0x...",
* quantity: 1n,
* });
* const result = await sendTransaction({ transaction, account: engineAcc });
* console.log("Transaction sent:", result.transactionHash);
* ```
*/
export function engineAccount(options: EngineAccountOptions): Account {
const { engineUrl, authToken, walletAddress, chain, overrides } = options;
// these are shared across all methods
const headers: HeadersInit = {
"x-backend-wallet-address": walletAddress,
Authorization: `Bearer ${authToken}`,
"Content-Type": "application/json",
};
if (overrides?.accountAddress) {
headers["x-account-address"] = overrides.accountAddress;
}
if (overrides?.accountFactoryAddress) {
headers["x-account-factory-address"] = overrides.accountFactoryAddress;
}
if (overrides?.accountSalt) {
headers["x-account-salt"] = overrides.accountSalt;
}
return {
address: walletAddress,
sendTransaction: async (transaction: SendTransactionOption) => {
const ENGINE_URL = new URL(engineUrl);
ENGINE_URL.pathname = `/backend-wallet/${transaction.chainId}/send-transaction`;
const engineData: Record<string, string | undefined> = {
// add to address if we have it (is optional to pass to engine)
toAddress: transaction.to || undefined,
// engine wants a hex string here so we serialize it
data: transaction.data || "0x",
// value is always required
value: toHex(transaction.value ?? 0n),
};
// TODO: gas overrides etc?
const engineRes = await fetch(ENGINE_URL, {
method: "POST",
headers,
body: JSON.stringify(engineData),
});
if (!engineRes.ok) {
const body = await engineRes.text();
throw new Error(
`Engine request failed with status ${engineRes.status} - ${body}`,
);
}
const engineJson = (await engineRes.json()) as {
result: {
queueId: string;
};
};
// wait for the queueId to be processed
ENGINE_URL.pathname = `/transaction/status/${engineJson.result.queueId}`;
const startTime = Date.now();
const TIMEOUT_IN_MS = 5 * 60 * 1000; // 5 minutes in milliseconds
while (Date.now() - startTime < TIMEOUT_IN_MS) {
const queueRes = await fetch(ENGINE_URL, {
method: "GET",
headers,
});
if (!queueRes.ok) {
const body = await queueRes.text();
throw new Error(
`Engine request failed with status ${queueRes.status} - ${body}`,
);
}
const queueJSON = (await queueRes.json()) as {
result: {
status: "queued" | "mined" | "cancelled" | "errored";
transactionHash: Hex | null;
userOpHash: Hex | null;
errorMessage: string | null;
};
};
if (
queueJSON.result.status === "errored" &&
queueJSON.result.errorMessage
) {
throw new Error(queueJSON.result.errorMessage);
}
if (queueJSON.result.transactionHash) {
return {
transactionHash: queueJSON.result.transactionHash,
};
}
// wait 1s before checking again
await new Promise((resolve) => setTimeout(resolve, 1000));
}
throw new Error("Transaction timed out after 5 minutes");
},
signMessage: async ({ message }) => {
let engineMessage: string | Hex;
let isBytes = false;
if (typeof message === "string") {
engineMessage = message;
} else {
engineMessage = toHex(message.raw);
isBytes = true;
}
const ENGINE_URL = new URL(engineUrl);
ENGINE_URL.pathname = "/backend-wallet/sign-message";
const engineRes = await fetch(ENGINE_URL, {
method: "POST",
headers,
body: JSON.stringify({
message: engineMessage,
isBytes,
chainId: chain?.id,
}),
});
if (!engineRes.ok) {
const body = await engineRes.text();
throw new Error(
`Engine request failed with status ${engineRes.status} - ${body}`,
);
}
const engineJson = (await engineRes.json()) as {
result: Hex;
};
return engineJson.result;
},
signTypedData: async (_typedData) => {
const ENGINE_URL = new URL(engineUrl);
ENGINE_URL.pathname = "/backend-wallet/sign-typed-data";
const engineRes = await fetch(ENGINE_URL, {
method: "POST",
headers,
body: JSON.stringify({
domain: _typedData.domain,
types: _typedData.types,
value: _typedData.message,
primaryType: _typedData.primaryType,
chainId: chain?.id,
}),
});
if (!engineRes.ok) {
const body = await engineRes.text();
throw new Error(
`Engine request failed with status ${engineRes.status} - ${body}`,
);
}
const engineJson = (await engineRes.json()) as {
result: Hex;
};
return engineJson.result;
},
};
}