@zerodev/sdk 4.0.15 → 4.0.16
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/dist/cjs/kernel-zerodev/owner/passkey/utils.d.ts +1 -2
- package/dist/cjs/kernel-zerodev/owner/passkey/utils.js +16 -16
- package/dist/cjs/kernel-zerodev/owner/passkey/utils.js.map +1 -1
- package/dist/cjs/kernel-zerodev/provider.js +2 -0
- package/dist/cjs/kernel-zerodev/provider.js.map +1 -1
- package/dist/esm/kernel-zerodev/owner/passkey/utils.d.ts +1 -2
- package/dist/esm/kernel-zerodev/owner/passkey/utils.js +15 -15
- package/dist/esm/kernel-zerodev/owner/passkey/utils.js.map +1 -1
- package/dist/esm/kernel-zerodev/provider.js +2 -0
- package/dist/esm/kernel-zerodev/provider.js.map +1 -1
- package/dist/types/kernel-zerodev/owner/passkey/utils.d.ts +1 -2
- package/dist/types/kernel-zerodev/owner/passkey/utils.d.ts.map +1 -1
- package/dist/types/kernel-zerodev/provider.d.ts.map +1 -1
- package/package.json +1 -1
- package/src/kernel-zerodev/owner/passkey/utils.ts +31 -28
- package/src/kernel-zerodev/provider.ts +3 -0
|
@@ -1,10 +1,9 @@
|
|
|
1
|
-
import type { Hex, Signature } from "./types.js";
|
|
2
1
|
import type { SignTypedDataParams } from "@alchemy/aa-core";
|
|
3
2
|
export declare const publicKey = "public-key";
|
|
4
3
|
export declare const es256 = -7;
|
|
5
4
|
export declare const generateRandomBuffer: () => ArrayBuffer;
|
|
6
5
|
export declare const base64UrlEncode: (challenge: ArrayBuffer) => string;
|
|
7
|
-
export declare
|
|
6
|
+
export declare const signMessageImplementation: (msg: string, id: string, walletId: string, projectId: string, credentialId: string, apiUrl?: string) => Promise<`0x${string}`>;
|
|
8
7
|
export declare const signMessage: (msg: string | Uint8Array, id: string, walletId: string, projectId: string, credentialId: string, apiUrl?: string) => Promise<`0x${string}`>;
|
|
9
8
|
export declare const signTypedData: (params: SignTypedDataParams, id: string, walletId: string, projectId: string, credentialId: string, apiUrl?: string) => Promise<`0x${string}`>;
|
|
10
9
|
export declare function base64URLStringToBuffer(base64URLString: string): ArrayBuffer;
|
|
@@ -3,11 +3,10 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
|
|
|
3
3
|
return (mod && mod.__esModule) ? mod : { "default": mod };
|
|
4
4
|
};
|
|
5
5
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
6
|
-
exports.base64URLStringToBuffer = exports.signTypedData = exports.signMessage = exports.
|
|
6
|
+
exports.base64URLStringToBuffer = exports.signTypedData = exports.signMessage = exports.signMessageImplementation = exports.base64UrlEncode = exports.generateRandomBuffer = exports.es256 = exports.publicKey = void 0;
|
|
7
7
|
const http_1 = require("@turnkey/http");
|
|
8
8
|
const axios_1 = __importDefault(require("axios"));
|
|
9
9
|
const constants_js_1 = require("../../constants.js");
|
|
10
|
-
const ethers_1 = require("ethers");
|
|
11
10
|
const viem_1 = require("viem");
|
|
12
11
|
(0, http_1.browserInit)({
|
|
13
12
|
baseUrl: "https://api.turnkey.com",
|
|
@@ -28,22 +27,15 @@ const base64UrlEncode = (challenge) => {
|
|
|
28
27
|
.replace(/=/g, "");
|
|
29
28
|
};
|
|
30
29
|
exports.base64UrlEncode = base64UrlEncode;
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
r: `0x${r}`,
|
|
34
|
-
s: `0x${s}`,
|
|
35
|
-
v: parseInt(v) + 27,
|
|
36
|
-
});
|
|
37
|
-
}
|
|
38
|
-
exports.signatureToHex = signatureToHex;
|
|
39
|
-
const signMessage = async (msg, id, walletId, projectId, credentialId, apiUrl = constants_js_1.API_URL) => {
|
|
30
|
+
const signMessageImplementation = async (msg, id, walletId, projectId, credentialId, apiUrl = constants_js_1.API_URL) => {
|
|
31
|
+
console.log("SIGN MESSAGE IMPLEMENTATION");
|
|
40
32
|
const signedRequest = await http_1.TurnkeyApi.signSignRawPayload({
|
|
41
33
|
body: {
|
|
42
34
|
type: "ACTIVITY_TYPE_SIGN_RAW_PAYLOAD",
|
|
43
35
|
organizationId: id,
|
|
44
36
|
parameters: {
|
|
45
37
|
privateKeyId: walletId,
|
|
46
|
-
payload:
|
|
38
|
+
payload: msg,
|
|
47
39
|
encoding: "PAYLOAD_ENCODING_HEXADECIMAL",
|
|
48
40
|
hashFunction: "HASH_FUNCTION_NO_OP",
|
|
49
41
|
},
|
|
@@ -66,18 +58,26 @@ const signMessage = async (msg, id, walletId, projectId, credentialId, apiUrl =
|
|
|
66
58
|
if (activity.status === "ACTIVITY_STATUS_COMPLETED") {
|
|
67
59
|
let result = activity?.result?.signRawPayloadResult;
|
|
68
60
|
if (result) {
|
|
69
|
-
const
|
|
70
|
-
|
|
71
|
-
|
|
61
|
+
const signatureHex = (0, viem_1.signatureToHex)({
|
|
62
|
+
r: `0x${result.r}`,
|
|
63
|
+
s: `0x${result.s}`,
|
|
64
|
+
v: result.v === "00" ? 27n : 28n,
|
|
65
|
+
});
|
|
66
|
+
if (signatureHex) {
|
|
67
|
+
return signatureHex;
|
|
72
68
|
}
|
|
73
69
|
}
|
|
74
70
|
}
|
|
75
71
|
return "0x";
|
|
76
72
|
};
|
|
73
|
+
exports.signMessageImplementation = signMessageImplementation;
|
|
74
|
+
const signMessage = async (msg, id, walletId, projectId, credentialId, apiUrl = constants_js_1.API_URL) => {
|
|
75
|
+
return await (0, exports.signMessageImplementation)((0, viem_1.hashMessage)(typeof msg === 'string' ? msg : { raw: msg }), id, walletId, projectId, credentialId, apiUrl);
|
|
76
|
+
};
|
|
77
77
|
exports.signMessage = signMessage;
|
|
78
78
|
const signTypedData = async (params, id, walletId, projectId, credentialId, apiUrl = constants_js_1.API_URL) => {
|
|
79
79
|
const hashToSign = (0, viem_1.hashTypedData)(params);
|
|
80
|
-
return await (0, exports.
|
|
80
|
+
return await (0, exports.signMessageImplementation)(hashToSign, id, walletId, projectId, credentialId, apiUrl);
|
|
81
81
|
};
|
|
82
82
|
exports.signTypedData = signTypedData;
|
|
83
83
|
function base64URLStringToBuffer(base64URLString) {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"utils.js","sourceRoot":"","sources":["../../../../../src/kernel-zerodev/owner/passkey/utils.ts"],"names":[],"mappings":";;;;;;AAAA,wCAAwD;AACxD,kDAA0B;AAC1B,qDAA6C;AAE7C
|
|
1
|
+
{"version":3,"file":"utils.js","sourceRoot":"","sources":["../../../../../src/kernel-zerodev/owner/passkey/utils.ts"],"names":[],"mappings":";;;;;;AAAA,wCAAwD;AACxD,kDAA0B;AAC1B,qDAA6C;AAE7C,+BAAkE;AAElE,IAAA,kBAAW,EAAC;IACV,OAAO,EAAE,yBAAyB;CACnC,CAAC,CAAC;AAEU,QAAA,SAAS,GAAG,YAAY,CAAC;AAEzB,QAAA,KAAK,GAAG,CAAC,CAAC,CAAC;AAEjB,MAAM,oBAAoB,GAAG,GAAgB,EAAE;IACpD,MAAM,GAAG,GAAG,IAAI,UAAU,CAAC,EAAE,CAAC,CAAC;IAE/B,MAAM,CAAC,eAAe,CAAC,GAAG,CAAC,CAAC;IAC5B,OAAO,GAAG,CAAC,MAAM,CAAC;AACpB,CAAC,CAAC;AALW,QAAA,oBAAoB,wBAK/B;AAEK,MAAM,eAAe,GAAG,CAAC,SAAsB,EAAU,EAAE;IAChE,OAAO,MAAM,CAAC,IAAI,CAAC,SAAS,CAAC;SAC1B,QAAQ,CAAC,QAAQ,CAAC;SAClB,OAAO,CAAC,KAAK,EAAE,GAAG,CAAC;SACnB,OAAO,CAAC,KAAK,EAAE,GAAG,CAAC;SACnB,OAAO,CAAC,IAAI,EAAE,EAAE,CAAC,CAAC;AACvB,CAAC,CAAC;AANW,QAAA,eAAe,mBAM1B;AAEK,MAAM,yBAAyB,GAAG,KAAK,EAC5C,GAAW,EACX,EAAU,EACV,QAAgB,EAChB,SAAiB,EACjB,YAAoB,EACpB,MAAM,GAAG,sBAAO,EAChB,EAAE;IACF,OAAO,CAAC,GAAG,CAAC,6BAA6B,CAAC,CAAA;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,KAAK,GAAG,IAAI,UAAU,CAAC,MAAM,CAAC,CAAC;IAErC,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,MAAM,CAAC,MAAM,EAAE,CAAC,EAAE,EAAE;QACtC,KAAK,CAAC,CAAC,CAAC,GAAG,MAAM,CAAC,UAAU,CAAC,CAAC,CAAC,CAAC;KACjC;IAED,OAAO,MAAM,CAAC;AAChB,CAAC;AAzBD,0DAyBC","sourcesContent":["import { browserInit, TurnkeyApi } from \"@turnkey/http\";\nimport axios from \"axios\";\nimport { API_URL } from \"../../constants.js\";\nimport type { SignTypedDataParams } from \"@alchemy/aa-core\";\nimport { hashTypedData, signatureToHex, hashMessage } from \"viem\";\n\nbrowserInit({\n baseUrl: \"https://api.turnkey.com\",\n});\n\nexport const publicKey = \"public-key\";\n\nexport const es256 = -7;\n\nexport const generateRandomBuffer = (): ArrayBuffer => {\n const arr = new Uint8Array(32);\n //@ts-expect-error\n crypto.getRandomValues(arr);\n return arr.buffer;\n};\n\nexport const base64UrlEncode = (challenge: ArrayBuffer): string => {\n return Buffer.from(challenge)\n .toString(\"base64\")\n .replace(/\\+/g, \"-\")\n .replace(/\\//g, \"_\")\n .replace(/=/g, \"\");\n};\n\nexport const signMessageImplementation = async (\n msg: string,\n id: string,\n walletId: string,\n projectId: string,\n credentialId: string,\n apiUrl = API_URL\n) => {\n console.log(\"SIGN MESSAGE IMPLEMENTATION\")\n const signedRequest = await TurnkeyApi.signSignRawPayload(\n {\n body: {\n type: \"ACTIVITY_TYPE_SIGN_RAW_PAYLOAD\",\n organizationId: id,\n parameters: {\n privateKeyId: walletId,\n payload: msg,\n encoding: \"PAYLOAD_ENCODING_HEXADECIMAL\",\n hashFunction: \"HASH_FUNCTION_NO_OP\",\n },\n timestampMs: String(Date.now()),\n },\n },\n {\n publicKey: {\n allowCredentials: [\n {\n id: base64URLStringToBuffer(credentialId),\n type: publicKey,\n },\n ],\n },\n }\n );\n const proxyResponse = await axios.post(\n `${apiUrl}/projects/${projectId}/wallets/proxy`,\n {\n signedRequest,\n }\n );\n const { activity } = await proxyResponse.data;\n if (activity.status === \"ACTIVITY_STATUS_COMPLETED\") {\n let result = activity?.result?.signRawPayloadResult;\n\n if (result) {\n const signatureHex = signatureToHex({\n r: `0x${result.r}`,\n s: `0x${result.s}`,\n v: result.v === \"00\" ? 27n : 28n,\n });\n if (signatureHex) {\n return signatureHex;\n }\n }\n }\n return \"0x\";\n};\n\nexport const signMessage = async (\n msg: string | Uint8Array,\n id: string,\n walletId: string,\n projectId: string,\n credentialId: string,\n apiUrl = API_URL\n) => {\n return await signMessageImplementation(\n hashMessage(typeof msg === 'string' ? msg : {raw: msg}),\n id,\n walletId,\n projectId,\n credentialId,\n apiUrl\n );\n};\n\nexport const signTypedData = async (\n params: SignTypedDataParams,\n id: string,\n walletId: string,\n projectId: string,\n credentialId: string,\n apiUrl = API_URL\n) => {\n const hashToSign = hashTypedData(params);\n return await signMessageImplementation(\n hashToSign,\n id,\n walletId,\n projectId,\n credentialId,\n apiUrl\n );\n};\n\n// https://github.com/MasterKale/SimpleWebAuthn/blob/master/packages/browser/src/helpers/base64URLStringToBuffer.ts#L8\nexport function base64URLStringToBuffer(base64URLString: string): ArrayBuffer {\n // Convert from Base64URL to Base64\n const base64 = base64URLString.replace(/-/g, \"+\").replace(/_/g, \"/\");\n /**\n * Pad with '=' until it's a multiple of four\n * (4 - (85 % 4 = 1) = 3) % 4 = 3 padding\n * (4 - (86 % 4 = 2) = 2) % 4 = 2 padding\n * (4 - (87 % 4 = 3) = 1) % 4 = 1 padding\n * (4 - (88 % 4 = 0) = 4) % 4 = 0 padding\n */\n const padLength = (4 - (base64.length % 4)) % 4;\n const padded = base64.padEnd(base64.length + padLength, \"=\");\n\n // Convert to a binary string\n const binary = atob(padded);\n\n // Convert binary string to buffer\n const buffer = new ArrayBuffer(binary.length);\n const bytes = new Uint8Array(buffer);\n\n for (let i = 0; i < binary.length; i++) {\n bytes[i] = binary.charCodeAt(i);\n }\n\n return buffer;\n}\n"]}
|
|
@@ -191,6 +191,8 @@ class ZeroDevProvider extends aa_core_1.SmartAccountProvider {
|
|
|
191
191
|
case "eth_sendTransaction":
|
|
192
192
|
const [tx] = params;
|
|
193
193
|
return this.sendTransaction(tx);
|
|
194
|
+
case "eth_signTypedData_v4":
|
|
195
|
+
return this.signTypedData(JSON.parse(params[1]));
|
|
194
196
|
case "personal_sign":
|
|
195
197
|
if (!this.account) {
|
|
196
198
|
throw new Error("account not connected!");
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"provider.js","sourceRoot":"","sources":["../../../src/kernel-zerodev/provider.ts"],"names":[],"mappings":";;;AAAA,+BAQc;AACd,8CAe0B;AAC1B,iDAMwB;AACxB,6CAA2E;AAC3E,oEAAwE;AACxE,+DAA0D;AAC1D,2CAA+C;AAC/C,4DAAwE;AACxE,gEAA6E;AAoB7E,IAAY,SAGX;AAHD,WAAY,SAAS;IACnB,yCAAQ,CAAA;IACR,yDAAgB,CAAA;AAClB,CAAC,EAHW,SAAS,yBAAT,SAAS,QAGpB;AAQD,MAAa,eAAgB,SAAQ,8BAAmC;IAKtE,YAAY,EACV,SAAS,EACT,KAAK,EACL,iBAAiB,GAAG,iCAAkB,EACtC,MAAM,GAAG,0BAAW,EACpB,OAAO,EACP,eAAe,EACf,IAAI,GACkB;QACtB,MAAM,MAAM,GAAG,OAAO,KAAK,KAAK,QAAQ,CAAC,CAAC,CAAC,IAAA,kBAAQ,EAAC,KAAK,CAAC,CAAC,CAAC,CAAC,KAAK,CAAC;QACnE,MAAM,SAAS,GAAG,IAAA,mDAAgC,EAAC;YACjD,KAAK,EAAE,MAAM;YACb,MAAM;YACN,SAAS;YACT,eAAe;SAChB,CAAC,CAAC;QAEH,KAAK,CAAC,SAAS,EAAE,iBAAiB,EAAE,MAAM,EAAE,OAAO,EAAE;YACnD,GAAG,IAAI;YACP,YAAY,EAAE,IAAI,EAAE,YAAY,IAAI,EAAE;YACtC,iBAAiB,E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I,CAAC;gBAClE,KAAK,CACN,CAAC;SACH;QACD,OAAO,KAAK,CAAC;IACf,CAAC;IAED,WAAW,CAAC,OAAY;QACtB,IAAI,OAAO,EAAE,KAAK,IAAI,IAAI,EAAE;YAC1B,IAAI,aAAa,GAAW,EAAE,CAAC;YAC/B,IAAI,eAAe,GAAuB,OAAO,EAAE,KAAK,EAAE,OAAO,CAAC;YAClE,IAAI,eAAe,EAAE,QAAQ,CAAC,UAAU,CAAC,KAAK,IAAI,EAAE;gBAElD,MAAM,OAAO,GAAG,eAAe,CAAC,KAAK,CAAC,kBAAkB,CAAC,CAAC;gBAC1D,IAAI,OAAO,IAAI,IAAI,EAAE;oBACnB,MAAM,KAAK,GAAG,OAAO,CAAC,CAAC,CAAC,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC;oBACpC,aAAa,GAAG,uBAAuB,KAAK,CAAC,CAAC,CAAC,GAAG,CAAC;oBACnD,eAAe,GAAG,KAAK,CAAC,CAAC,CAAC,CAAC;iBAC5B;aACF;YACD,MAAM,KAAK,GAAG,IAAI,KAAK,CACrB,+DAA+D,eAAe,IAAI,aAAa,EAAE,CAClG,CAAC;YACF,KAAK,CAAC,KAAK,GAAG,OAAO,CAAC,KAAK,CAAC;YAC5B,OAAO,KAAK,CAAC;SACd;QACD,OAAO,OAAO,CAAC;IACjB,CAAC;IAiBD,2BAA2B,CAAC,MAAwC;QAClE,IAAI,CAAC,IAAI,CAAC,WAAW,EAAE,EAAE;YACvB,MAAM,IAAI,KAAK,CACb,oEAAoE,CACrE,CAAC;SACH;QAED,OAAO,IAAA,0CAA2B,EAAC,IAAI,EAAE,MAAM,CAAC,CAAC;IACnD,CAAC;CA6BF;AAlRD,0CAkRC","sourcesContent":["import {\n fromHex,\n type Address,\n type Chain,\n type Hash,\n type Hex,\n type HttpTransport,\n type RpcTransactionRequest,\n} from \"viem\";\nimport {\n deepHexlify,\n resolveProperties,\n type SmartAccountProviderOpts,\n getChain,\n type UserOperationCallData,\n type BatchUserOperationCallData,\n type SendUserOperationResult,\n asyncPipe,\n noOpMiddleware,\n type UserOperationStruct,\n type BytesLike,\n SmartAccountProvider,\n type AccountMiddlewareFn,\n type UserOperationOverrides,\n} from \"@alchemy/aa-core\";\nimport {\n BUNDLER_URL,\n DEFAULT_SEND_TX_MAX_RETRIES,\n DEFAULT_SEND_TX_RETRY_INTERVAL_MS,\n ENTRYPOINT_ADDRESS,\n minPriorityFeePerBidDefaults,\n} from \"./constants.js\";\nimport { KernelSmartContractAccount, isKernelAccount } from \"./account.js\";\nimport { withZeroDevGasEstimator } from \"./middleware/gas-estimator.js\";\nimport { isValidRequest } from \"./utils/ERC4337-utils.js\";\nimport { InvalidOperation } from \"./errors.js\";\nimport { withZeroDevPaymasterAndData } from \"./middleware/paymaster.js\";\nimport { createZeroDevPublicErc4337Client } from \"./client/create-client.js\";\nimport type {\n PaymasterAndBundlerProviders,\n PaymasterConfig,\n PaymasterPolicy,\n} from \"./paymaster/types.js\";\n\nexport type ZeroDevProviderConfig = {\n projectId: string;\n chain: Chain | number;\n entryPointAddress?: Address;\n rpcUrl?: string;\n account?: KernelSmartContractAccount;\n bundlerProvider?: PaymasterAndBundlerProviders;\n opts?: SmartAccountProviderOpts & {\n sendTxMaxRetries?: number;\n sendTxRetryIntervalMs?: number;\n };\n};\n\nexport enum Operation {\n Call = 0,\n DelegateCall = 1,\n}\n\ntype UserOpDataOperationTypes<T> = T extends UserOperationCallData\n ? Operation.Call | Operation.DelegateCall\n : T extends BatchUserOperationCallData\n ? Operation.Call\n : never;\n\nexport class ZeroDevProvider extends SmartAccountProvider<HttpTransport> {\n protected projectId: string;\n protected sendTxMaxRetries: number;\n protected sendTxRetryIntervalMs: number;\n\n constructor({\n projectId,\n chain,\n entryPointAddress = ENTRYPOINT_ADDRESS,\n rpcUrl = BUNDLER_URL,\n account,\n bundlerProvider,\n opts,\n }: ZeroDevProviderConfig) {\n const _chain = typeof chain === \"number\" ? getChain(chain) : chain;\n const rpcClient = createZeroDevPublicErc4337Client({\n chain: _chain,\n rpcUrl,\n projectId,\n bundlerProvider,\n });\n\n super(rpcClient, entryPointAddress, _chain, account, {\n ...opts,\n txMaxRetries: opts?.txMaxRetries ?? 10,\n txRetryIntervalMs: opts?.txRetryIntervalMs ?? 10000,\n minPriorityFeePerBid:\n opts?.minPriorityFeePerBid ??\n minPriorityFeePerBidDefaults.get(_chain.id),\n });\n\n this.projectId = projectId;\n this.sendTxMaxRetries =\n opts?.sendTxMaxRetries ?? DEFAULT_SEND_TX_MAX_RETRIES;\n this.sendTxRetryIntervalMs =\n opts?.sendTxRetryIntervalMs ?? DEFAULT_SEND_TX_RETRY_INTERVAL_MS;\n\n withZeroDevGasEstimator(this);\n }\n\n getProjectId = (): string => this.projectId;\n\n sendTransaction = async (\n request: RpcTransactionRequest,\n operation: UserOpDataOperationTypes<UserOperationCallData> = Operation.Call\n ): Promise<Hash> => {\n if (!request.to) {\n throw new Error(\"transaction is missing to address\");\n }\n\n const overrides: UserOperationOverrides = {};\n if (request.maxFeePerGas) {\n overrides.maxFeePerGas = request.maxFeePerGas;\n }\n if (request.maxPriorityFeePerGas) {\n overrides.maxPriorityFeePerGas = request.maxPriorityFeePerGas;\n }\n\n const { hash } = await this.sendUserOperation(\n {\n target: request.to,\n data: request.data ?? \"0x\",\n value: request.value ? fromHex(request.value, \"bigint\") : 0n,\n },\n overrides,\n operation\n );\n\n return await this.waitForUserOperationTransaction(hash as Hash);\n };\n\n sendUserOperation = async <\n T extends UserOperationCallData | BatchUserOperationCallData\n >(\n data: T,\n overrides?: UserOperationOverrides,\n operation: UserOpDataOperationTypes<T> = Operation.Call as UserOpDataOperationTypes<T>\n ): Promise<SendUserOperationResult> => {\n if (!isKernelAccount(this.account)) {\n throw new Error(\"account not connected!\");\n }\n if (!this.account.validator) {\n throw new Error(\"validator not connected!\");\n }\n\n let callData: BytesLike = \"0x\";\n\n if (Array.isArray(data)) {\n if (operation === Operation.Call) {\n callData = await this.account.encodeBatchExecute(data);\n } else {\n throw InvalidOperation;\n }\n } else if (isKernelAccount(this.account)) {\n if (operation === Operation.DelegateCall) {\n callData = await this.account.encodeExecuteDelegate(\n data.target,\n data.value ?? 0n,\n data.data\n );\n } else if (operation === Operation.Call) {\n callData = await this.account.encodeExecute(\n data.target,\n data.value ?? 0n,\n data.data\n );\n } else {\n throw InvalidOperation;\n }\n } else {\n throw InvalidOperation;\n }\n\n const initCode = await this.account.getInitCode();\n let hash: string = \"\";\n let i = 0;\n const nonce = await this.account.getNonce();\n let uoStruct: UserOperationStruct;\n let request: UserOperationStruct;\n let maxFeePerGas, maxPriorityFeePerGas;\n do {\n uoStruct = await asyncPipe(\n this.dummyPaymasterDataMiddleware,\n this.feeDataGetter,\n this.paymasterDataMiddleware,\n this.gasEstimator,\n this.customMiddleware ?? noOpMiddleware,\n async (struct) => ({ ...struct, ...overrides })\n )({\n initCode,\n sender: this.getAddress(),\n nonce,\n callData,\n signature: await this.account\n .getValidator()\n .getDynamicDummySignature(await this.getAddress(), callData as Hex),\n maxFeePerGas,\n maxPriorityFeePerGas,\n } as UserOperationStruct);\n request = deepHexlify(await resolveProperties(uoStruct));\n\n if (!isValidRequest(request)) {\n // this pretty prints the uo\n throw new Error(\n `Request is missing parameters. All properties on UserOperationStruct must be set. uo: ${JSON.stringify(\n request,\n null,\n 2\n )}`\n );\n }\n\n this.account.approvePlugin();\n\n request.signature = await this.account.validator.getSignature(request);\n try {\n hash = await this.rpcClient.sendUserOperation(\n request,\n this.entryPointAddress\n );\n } catch (error: any) {\n if (this.isReplacementOpError(error) && i++ < this.sendTxMaxRetries) {\n maxFeePerGas = (BigInt(request.maxFeePerGas) * 113n) / 100n;\n maxPriorityFeePerGas =\n (BigInt(request.maxPriorityFeePerGas) * 113n) / 100n;\n\n console.log(\n `After ${\n this.sendTxRetryIntervalMs / 60000\n } minutes, resending tx with Increased Gas fees: maxFeePerGas: ${maxFeePerGas}, maxPriorityFeePerGas: ${maxPriorityFeePerGas}`\n );\n await new Promise((resolve) =>\n setTimeout(resolve, this.sendTxRetryIntervalMs)\n );\n continue;\n }\n throw this.unwrapError(error);\n }\n } while (hash === \"\");\n\n return {\n hash,\n request,\n };\n };\n\n isReplacementOpError(errorIn: any): boolean {\n if (errorIn.cause != null) {\n const failedOpMessage: string | undefined = errorIn?.cause?.message;\n return (\n (failedOpMessage?.includes(\n \"replacement op must increase maxFeePerGas and MaxPriorityFeePerGas\"\n ) ||\n failedOpMessage?.match(/.*replacement.*underpriced.*/) !== null) ??\n false\n );\n }\n return false;\n }\n\n unwrapError(errorIn: any): Error {\n if (errorIn?.cause != null) {\n let paymasterInfo: string = \"\";\n let failedOpMessage: string | undefined = errorIn?.cause?.message;\n if (failedOpMessage?.includes(\"FailedOp\") === true) {\n // TODO: better error extraction methods will be needed\n const matched = failedOpMessage.match(/FailedOp\\((.*)\\)/);\n if (matched != null) {\n const split = matched[1].split(\",\");\n paymasterInfo = `(paymaster address: ${split[1]})`;\n failedOpMessage = split[2];\n }\n }\n const error = new Error(\n `The bundler has failed to include UserOperation in a batch: ${failedOpMessage} ${paymasterInfo}`\n );\n error.stack = errorIn.stack;\n return error;\n }\n return errorIn;\n }\n\n getAccount: () => KernelSmartContractAccount = () => {\n if (!isKernelAccount(this.account)) {\n throw new Error(\"account not connected!\");\n }\n return this.account;\n };\n\n dummyPaymasterDataMiddleware: AccountMiddlewareFn = async (\n struct: UserOperationStruct\n ): Promise<UserOperationStruct> => {\n struct.paymasterAndData =\n \"0xfe7dbcab8aaee4eb67943c1e6be95b1d065985c6000000000000000000000000000000000000000000000000000001869aa31cf400000000000000000000000000000000000000000000000000000000000000007dfe2190f34af27b265bae608717cdc9368b471fc0c097ab7b4088f255b4961e57b039e7e571b15221081c5dce7bcb93459b27a3ab65d2f8a889f4a40b4022801b\";\n return struct;\n };\n\n withZeroDevPaymasterAndData(config: PaymasterConfig<PaymasterPolicy>) {\n if (!this.isConnected()) {\n throw new Error(\n \"ZeroDevProvider: account is not set, did you call `connect` first?\"\n );\n }\n\n return withZeroDevPaymasterAndData(this, config);\n }\n\n request: (args: { method: string; params?: any[] }) => Promise<any> = async (\n args\n ) => {\n const { method, params } = args;\n switch (method) {\n case \"eth_chainId\":\n return this.chain.id;\n case \"eth_sendTransaction\":\n const [tx] = params as [RpcTransactionRequest];\n return this.sendTransaction(tx);\n case \"personal_sign\":\n if (!this.account) {\n throw new Error(\"account not connected!\");\n }\n const [data, address] = params!;\n if (address !== (await this.getAddress())) {\n throw new Error(\n \"cannot sign for address that is not the current account\"\n );\n }\n // @ts-ignore\n return this.account.signWithEip6492(data);\n default:\n // @ts-ignore\n return this.rpcClient.request(args);\n }\n };\n}\n"]}
|
|
1
|
+
{"version":3,"file":"provider.js","sourceRoot":"","sources":["../../../src/kernel-zerodev/provider.ts"],"names":[],"mappings":";;;AAAA,+BAQc;AACd,8CAe0B;AAC1B,iDAMwB;AACxB,6CAA2E;AAC3E,oEAAwE;AACxE,+DAA0D;AAC1D,2CAA+C;AAC/C,4DAAwE;AACxE,gEAA6E;AAoB7E,IAAY,SAGX;AAHD,WAAY,SAAS;IACnB,yCAAQ,CAAA;IACR,yDAAgB,CAAA;AAClB,CAAC,EAHW,SAAS,yBAAT,SAAS,QAGpB;AAQD,MAAa,eAAgB,SAAQ,8BAAmC;IAKtE,YAAY,EACV,SAAS,EACT,KAAK,EACL,iBAAiB,GAAG,iCAAkB,EACtC,MAAM,GAAG,0BAAW,EACpB,OAAO,EACP,eAAe,EACf,IAAI,GACkB;QACtB,MAAM,MAAM,GAAG,OAAO,KAAK,KAAK,QAAQ,CAAC,CAAC,CAAC,IAAA,kBAAQ,EAAC,KAAK,CAAC,CAAC,CAAC,CAAC,KAAK,CAAC;QACnE,MAAM,SAAS,GAAG,IAAA,mDAAgC,EAAC;YACjD,KAAK,EAAE,MAAM;YACb,MAAM;YACN,SAAS;YACT,eAAe;SAChB,CAAC,CAAC;QAEH,KAAK,CAAC,SAAS,EAAE,iBAAiB,EAAE,MAAM,EAAE,OAAO,EAAE;YACnD,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AAC;CAgCF;AArRD,0CAqRC","sourcesContent":["import {\n fromHex,\n type Address,\n type Chain,\n type Hash,\n type Hex,\n type HttpTransport,\n type RpcTransactionRequest,\n} from \"viem\";\nimport {\n deepHexlify,\n resolveProperties,\n type SmartAccountProviderOpts,\n getChain,\n type UserOperationCallData,\n type BatchUserOperationCallData,\n type SendUserOperationResult,\n asyncPipe,\n noOpMiddleware,\n type UserOperationStruct,\n type BytesLike,\n SmartAccountProvider,\n type AccountMiddlewareFn,\n type UserOperationOverrides,\n} from \"@alchemy/aa-core\";\nimport {\n BUNDLER_URL,\n DEFAULT_SEND_TX_MAX_RETRIES,\n DEFAULT_SEND_TX_RETRY_INTERVAL_MS,\n ENTRYPOINT_ADDRESS,\n minPriorityFeePerBidDefaults,\n} from \"./constants.js\";\nimport { KernelSmartContractAccount, isKernelAccount } from \"./account.js\";\nimport { withZeroDevGasEstimator } from \"./middleware/gas-estimator.js\";\nimport { isValidRequest } from \"./utils/ERC4337-utils.js\";\nimport { InvalidOperation } from \"./errors.js\";\nimport { withZeroDevPaymasterAndData } from \"./middleware/paymaster.js\";\nimport { createZeroDevPublicErc4337Client } from \"./client/create-client.js\";\nimport type {\n PaymasterAndBundlerProviders,\n PaymasterConfig,\n PaymasterPolicy,\n} from \"./paymaster/types.js\";\n\nexport type ZeroDevProviderConfig = {\n projectId: string;\n chain: Chain | number;\n entryPointAddress?: Address;\n rpcUrl?: string;\n account?: KernelSmartContractAccount;\n bundlerProvider?: PaymasterAndBundlerProviders;\n opts?: SmartAccountProviderOpts & {\n sendTxMaxRetries?: number;\n sendTxRetryIntervalMs?: number;\n };\n};\n\nexport enum Operation {\n Call = 0,\n DelegateCall = 1,\n}\n\ntype UserOpDataOperationTypes<T> = T extends UserOperationCallData\n ? Operation.Call | Operation.DelegateCall\n : T extends BatchUserOperationCallData\n ? Operation.Call\n : never;\n\nexport class ZeroDevProvider extends SmartAccountProvider<HttpTransport> {\n protected projectId: string;\n protected sendTxMaxRetries: number;\n protected sendTxRetryIntervalMs: number;\n\n constructor({\n projectId,\n chain,\n entryPointAddress = ENTRYPOINT_ADDRESS,\n rpcUrl = BUNDLER_URL,\n account,\n bundlerProvider,\n opts,\n }: ZeroDevProviderConfig) {\n const _chain = typeof chain === \"number\" ? getChain(chain) : chain;\n const rpcClient = createZeroDevPublicErc4337Client({\n chain: _chain,\n rpcUrl,\n projectId,\n bundlerProvider,\n });\n\n super(rpcClient, entryPointAddress, _chain, account, {\n ...opts,\n txMaxRetries: opts?.txMaxRetries ?? 10,\n txRetryIntervalMs: opts?.txRetryIntervalMs ?? 10000,\n minPriorityFeePerBid:\n opts?.minPriorityFeePerBid ??\n minPriorityFeePerBidDefaults.get(_chain.id),\n });\n\n this.projectId = projectId;\n this.sendTxMaxRetries =\n opts?.sendTxMaxRetries ?? DEFAULT_SEND_TX_MAX_RETRIES;\n this.sendTxRetryIntervalMs =\n opts?.sendTxRetryIntervalMs ?? DEFAULT_SEND_TX_RETRY_INTERVAL_MS;\n\n withZeroDevGasEstimator(this);\n }\n\n getProjectId = (): string => this.projectId;\n\n sendTransaction = async (\n request: RpcTransactionRequest,\n operation: UserOpDataOperationTypes<UserOperationCallData> = Operation.Call\n ): Promise<Hash> => {\n if (!request.to) {\n throw new Error(\"transaction is missing to address\");\n }\n\n const overrides: UserOperationOverrides = {};\n if (request.maxFeePerGas) {\n overrides.maxFeePerGas = request.maxFeePerGas;\n }\n if (request.maxPriorityFeePerGas) {\n overrides.maxPriorityFeePerGas = request.maxPriorityFeePerGas;\n }\n\n const { hash } = await this.sendUserOperation(\n {\n target: request.to,\n data: request.data ?? \"0x\",\n value: request.value ? fromHex(request.value, \"bigint\") : 0n,\n },\n overrides,\n operation\n );\n\n return await this.waitForUserOperationTransaction(hash as Hash);\n };\n\n sendUserOperation = async <\n T extends UserOperationCallData | BatchUserOperationCallData\n >(\n data: T,\n overrides?: UserOperationOverrides,\n operation: UserOpDataOperationTypes<T> = Operation.Call as UserOpDataOperationTypes<T>\n ): Promise<SendUserOperationResult> => {\n if (!isKernelAccount(this.account)) {\n throw new Error(\"account not connected!\");\n }\n if (!this.account.validator) {\n throw new Error(\"validator not connected!\");\n }\n\n let callData: BytesLike = \"0x\";\n\n if (Array.isArray(data)) {\n if (operation === Operation.Call) {\n callData = await this.account.encodeBatchExecute(data);\n } else {\n throw InvalidOperation;\n }\n } else if (isKernelAccount(this.account)) {\n if (operation === Operation.DelegateCall) {\n callData = await this.account.encodeExecuteDelegate(\n data.target,\n data.value ?? 0n,\n data.data\n );\n } else if (operation === Operation.Call) {\n callData = await this.account.encodeExecute(\n data.target,\n data.value ?? 0n,\n data.data\n );\n } else {\n throw InvalidOperation;\n }\n } else {\n throw InvalidOperation;\n }\n\n const initCode = await this.account.getInitCode();\n let hash: string = \"\";\n let i = 0;\n const nonce = await this.account.getNonce();\n let uoStruct: UserOperationStruct;\n let request: UserOperationStruct;\n let maxFeePerGas, maxPriorityFeePerGas;\n do {\n uoStruct = await asyncPipe(\n this.dummyPaymasterDataMiddleware,\n this.feeDataGetter,\n this.paymasterDataMiddleware,\n this.gasEstimator,\n this.customMiddleware ?? noOpMiddleware,\n async (struct) => ({ ...struct, ...overrides })\n )({\n initCode,\n sender: this.getAddress(),\n nonce,\n callData,\n signature: await this.account\n .getValidator()\n .getDynamicDummySignature(await this.getAddress(), callData as Hex),\n maxFeePerGas,\n maxPriorityFeePerGas,\n } as UserOperationStruct);\n request = deepHexlify(await resolveProperties(uoStruct));\n\n if (!isValidRequest(request)) {\n // this pretty prints the uo\n throw new Error(\n `Request is missing parameters. All properties on UserOperationStruct must be set. uo: ${JSON.stringify(\n request,\n null,\n 2\n )}`\n );\n }\n\n this.account.approvePlugin();\n\n request.signature = await this.account.validator.getSignature(request);\n try {\n hash = await this.rpcClient.sendUserOperation(\n request,\n this.entryPointAddress\n );\n } catch (error: any) {\n if (this.isReplacementOpError(error) && i++ < this.sendTxMaxRetries) {\n maxFeePerGas = (BigInt(request.maxFeePerGas) * 113n) / 100n;\n maxPriorityFeePerGas =\n (BigInt(request.maxPriorityFeePerGas) * 113n) / 100n;\n\n console.log(\n `After ${\n this.sendTxRetryIntervalMs / 60000\n } minutes, resending tx with Increased Gas fees: maxFeePerGas: ${maxFeePerGas}, maxPriorityFeePerGas: ${maxPriorityFeePerGas}`\n );\n await new Promise((resolve) =>\n setTimeout(resolve, this.sendTxRetryIntervalMs)\n );\n continue;\n }\n throw this.unwrapError(error);\n }\n } while (hash === \"\");\n\n return {\n hash,\n request,\n };\n };\n\n isReplacementOpError(errorIn: any): boolean {\n if (errorIn.cause != null) {\n const failedOpMessage: string | undefined = errorIn?.cause?.message;\n return (\n (failedOpMessage?.includes(\n \"replacement op must increase maxFeePerGas and MaxPriorityFeePerGas\"\n ) ||\n failedOpMessage?.match(/.*replacement.*underpriced.*/) !== null) ??\n false\n );\n }\n return false;\n }\n\n unwrapError(errorIn: any): Error {\n if (errorIn?.cause != null) {\n let paymasterInfo: string = \"\";\n let failedOpMessage: string | undefined = errorIn?.cause?.message;\n if (failedOpMessage?.includes(\"FailedOp\") === true) {\n // TODO: better error extraction methods will be needed\n const matched = failedOpMessage.match(/FailedOp\\((.*)\\)/);\n if (matched != null) {\n const split = matched[1].split(\",\");\n paymasterInfo = `(paymaster address: ${split[1]})`;\n failedOpMessage = split[2];\n }\n }\n const error = new Error(\n `The bundler has failed to include UserOperation in a batch: ${failedOpMessage} ${paymasterInfo}`\n );\n error.stack = errorIn.stack;\n return error;\n }\n return errorIn;\n }\n\n getAccount: () => KernelSmartContractAccount = () => {\n if (!isKernelAccount(this.account)) {\n throw new Error(\"account not connected!\");\n }\n return this.account;\n };\n\n dummyPaymasterDataMiddleware: AccountMiddlewareFn = async (\n struct: UserOperationStruct\n ): Promise<UserOperationStruct> => {\n struct.paymasterAndData =\n \"0xfe7dbcab8aaee4eb67943c1e6be95b1d065985c6000000000000000000000000000000000000000000000000000001869aa31cf400000000000000000000000000000000000000000000000000000000000000007dfe2190f34af27b265bae608717cdc9368b471fc0c097ab7b4088f255b4961e57b039e7e571b15221081c5dce7bcb93459b27a3ab65d2f8a889f4a40b4022801b\";\n return struct;\n };\n\n withZeroDevPaymasterAndData(config: PaymasterConfig<PaymasterPolicy>) {\n if (!this.isConnected()) {\n throw new Error(\n \"ZeroDevProvider: account is not set, did you call `connect` first?\"\n );\n }\n\n return withZeroDevPaymasterAndData(this, config);\n }\n\n request: (args: { method: string; params?: any[] }) => Promise<any> = async (\n args\n ) => {\n const { method, params } = args;\n switch (method) {\n case \"eth_chainId\":\n return this.chain.id;\n case \"eth_sendTransaction\":\n const [tx] = params as [RpcTransactionRequest];\n return this.sendTransaction(tx);\n case \"eth_signTypedData_v4\":\n //@ts-expect-error\n return this.signTypedData(JSON.parse(params[1]))\n case \"personal_sign\":\n if (!this.account) {\n throw new Error(\"account not connected!\");\n }\n const [data, address] = params!;\n if (address !== (await this.getAddress())) {\n throw new Error(\n \"cannot sign for address that is not the current account\"\n );\n }\n // @ts-ignore\n return this.account.signWithEip6492(data);\n default:\n // @ts-ignore\n return this.rpcClient.request(args);\n }\n };\n}\n"]}
|
|
@@ -1,10 +1,9 @@
|
|
|
1
|
-
import type { Hex, Signature } from "./types.js";
|
|
2
1
|
import type { SignTypedDataParams } from "@alchemy/aa-core";
|
|
3
2
|
export declare const publicKey = "public-key";
|
|
4
3
|
export declare const es256 = -7;
|
|
5
4
|
export declare const generateRandomBuffer: () => ArrayBuffer;
|
|
6
5
|
export declare const base64UrlEncode: (challenge: ArrayBuffer) => string;
|
|
7
|
-
export declare
|
|
6
|
+
export declare const signMessageImplementation: (msg: string, id: string, walletId: string, projectId: string, credentialId: string, apiUrl?: string) => Promise<`0x${string}`>;
|
|
8
7
|
export declare const signMessage: (msg: string | Uint8Array, id: string, walletId: string, projectId: string, credentialId: string, apiUrl?: string) => Promise<`0x${string}`>;
|
|
9
8
|
export declare const signTypedData: (params: SignTypedDataParams, id: string, walletId: string, projectId: string, credentialId: string, apiUrl?: string) => Promise<`0x${string}`>;
|
|
10
9
|
export declare function base64URLStringToBuffer(base64URLString: string): ArrayBuffer;
|
|
@@ -1,8 +1,7 @@
|
|
|
1
1
|
import { browserInit, TurnkeyApi } from "@turnkey/http";
|
|
2
2
|
import axios from "axios";
|
|
3
3
|
import { API_URL } from "../../constants.js";
|
|
4
|
-
import {
|
|
5
|
-
import { hashTypedData } from "viem";
|
|
4
|
+
import { hashTypedData, signatureToHex, hashMessage } from "viem";
|
|
6
5
|
browserInit({
|
|
7
6
|
baseUrl: "https://api.turnkey.com",
|
|
8
7
|
});
|
|
@@ -20,21 +19,15 @@ export const base64UrlEncode = (challenge) => {
|
|
|
20
19
|
.replace(/\//g, "_")
|
|
21
20
|
.replace(/=/g, "");
|
|
22
21
|
};
|
|
23
|
-
export
|
|
24
|
-
|
|
25
|
-
r: `0x${r}`,
|
|
26
|
-
s: `0x${s}`,
|
|
27
|
-
v: parseInt(v) + 27,
|
|
28
|
-
});
|
|
29
|
-
}
|
|
30
|
-
export const signMessage = async (msg, id, walletId, projectId, credentialId, apiUrl = API_URL) => {
|
|
22
|
+
export const signMessageImplementation = async (msg, id, walletId, projectId, credentialId, apiUrl = API_URL) => {
|
|
23
|
+
console.log("SIGN MESSAGE IMPLEMENTATION");
|
|
31
24
|
const signedRequest = await TurnkeyApi.signSignRawPayload({
|
|
32
25
|
body: {
|
|
33
26
|
type: "ACTIVITY_TYPE_SIGN_RAW_PAYLOAD",
|
|
34
27
|
organizationId: id,
|
|
35
28
|
parameters: {
|
|
36
29
|
privateKeyId: walletId,
|
|
37
|
-
payload:
|
|
30
|
+
payload: msg,
|
|
38
31
|
encoding: "PAYLOAD_ENCODING_HEXADECIMAL",
|
|
39
32
|
hashFunction: "HASH_FUNCTION_NO_OP",
|
|
40
33
|
},
|
|
@@ -57,17 +50,24 @@ export const signMessage = async (msg, id, walletId, projectId, credentialId, ap
|
|
|
57
50
|
if (activity.status === "ACTIVITY_STATUS_COMPLETED") {
|
|
58
51
|
let result = activity?.result?.signRawPayloadResult;
|
|
59
52
|
if (result) {
|
|
60
|
-
const
|
|
61
|
-
|
|
62
|
-
|
|
53
|
+
const signatureHex = signatureToHex({
|
|
54
|
+
r: `0x${result.r}`,
|
|
55
|
+
s: `0x${result.s}`,
|
|
56
|
+
v: result.v === "00" ? 27n : 28n,
|
|
57
|
+
});
|
|
58
|
+
if (signatureHex) {
|
|
59
|
+
return signatureHex;
|
|
63
60
|
}
|
|
64
61
|
}
|
|
65
62
|
}
|
|
66
63
|
return "0x";
|
|
67
64
|
};
|
|
65
|
+
export const signMessage = async (msg, id, walletId, projectId, credentialId, apiUrl = API_URL) => {
|
|
66
|
+
return await signMessageImplementation(hashMessage(typeof msg === 'string' ? msg : { raw: msg }), id, walletId, projectId, credentialId, apiUrl);
|
|
67
|
+
};
|
|
68
68
|
export const signTypedData = async (params, id, walletId, projectId, credentialId, apiUrl = API_URL) => {
|
|
69
69
|
const hashToSign = hashTypedData(params);
|
|
70
|
-
return await
|
|
70
|
+
return await signMessageImplementation(hashToSign, id, walletId, projectId, credentialId, apiUrl);
|
|
71
71
|
};
|
|
72
72
|
export function base64URLStringToBuffer(base64URLString) {
|
|
73
73
|
const base64 = base64URLString.replace(/-/g, "+").replace(/_/g, "/");
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"utils.js","sourceRoot":"","sources":["../../../../../src/kernel-zerodev/owner/passkey/utils.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,WAAW,EAAE,UAAU,EAAE,MAAM,eAAe,CAAC;AACxD,OAAO,KAAK,MAAM,OAAO,CAAC;AAC1B,OAAO,EAAE,OAAO,EAAE,MAAM,oBAAoB,CAAC;AAE7C,OAAO,EAAE,
|
|
1
|
+
{"version":3,"file":"utils.js","sourceRoot":"","sources":["../../../../../src/kernel-zerodev/owner/passkey/utils.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,WAAW,EAAE,UAAU,EAAE,MAAM,eAAe,CAAC;AACxD,OAAO,KAAK,MAAM,OAAO,CAAC;AAC1B,OAAO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T,YAAY,EACZ,MAAM,CACP,CAAC;AACJ,CAAC,CAAC;AAEF,MAAM,CAAC,MAAM,aAAa,GAAG,KAAK,EAChC,MAA2B,EAC3B,EAAU,EACV,QAAgB,EAChB,SAAiB,EACjB,YAAoB,EACpB,MAAM,GAAG,OAAO,EAChB,EAAE;IACF,MAAM,UAAU,GAAG,aAAa,CAAC,MAAM,CAAC,CAAC;IACzC,OAAO,MAAM,yBAAyB,CACpC,UAAU,EACV,EAAE,EACF,QAAQ,EACR,SAAS,EACT,YAAY,EACZ,MAAM,CACP,CAAC;AACJ,CAAC,CAAC;AAGF,MAAM,UAAU,uBAAuB,CAAC,eAAuB;IAE7D,MAAM,MAAM,GAAG,eAAe,CAAC,OAAO,CAAC,IAAI,EAAE,GAAG,CAAC,CAAC,OAAO,CAAC,IAAI,EAAE,GAAG,CAAC,CAAC;IAQrE,MAAM,SAAS,GAAG,CAAC,CAAC,GAAG,CAAC,MAAM,CAAC,MAAM,GAAG,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC;IAChD,MAAM,MAAM,GAAG,MAAM,CAAC,MAAM,CAAC,MAAM,CAAC,MAAM,GAAG,SAAS,EAAE,GAAG,CAAC,CAAC;IAG7D,MAAM,MAAM,GAAG,IAAI,CAAC,MAAM,CAAC,CAAC;IAG5B,MAAM,MAAM,GAAG,IAAI,WAAW,CAAC,MAAM,CAAC,MAAM,CAAC,CAAC;IAC9C,MAAM,KAAK,GAAG,IAAI,UAAU,CAAC,MAAM,CAAC,CAAC;IAErC,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,MAAM,CAAC,MAAM,EAAE,CAAC,EAAE,EAAE;QACtC,KAAK,CAAC,CAAC,CAAC,GAAG,MAAM,CAAC,UAAU,CAAC,CAAC,CAAC,CAAC;KACjC;IAED,OAAO,MAAM,CAAC;AAChB,CAAC","sourcesContent":["import { browserInit, TurnkeyApi } from \"@turnkey/http\";\nimport axios from \"axios\";\nimport { API_URL } from \"../../constants.js\";\nimport type { SignTypedDataParams } from \"@alchemy/aa-core\";\nimport { hashTypedData, signatureToHex, hashMessage } from \"viem\";\n\nbrowserInit({\n baseUrl: \"https://api.turnkey.com\",\n});\n\nexport const publicKey = \"public-key\";\n\nexport const es256 = -7;\n\nexport const generateRandomBuffer = (): ArrayBuffer => {\n const arr = new Uint8Array(32);\n //@ts-expect-error\n crypto.getRandomValues(arr);\n return arr.buffer;\n};\n\nexport const base64UrlEncode = (challenge: ArrayBuffer): string => {\n return Buffer.from(challenge)\n .toString(\"base64\")\n .replace(/\\+/g, \"-\")\n .replace(/\\//g, \"_\")\n .replace(/=/g, \"\");\n};\n\nexport const signMessageImplementation = async (\n msg: string,\n id: string,\n walletId: string,\n projectId: string,\n credentialId: string,\n apiUrl = API_URL\n) => {\n console.log(\"SIGN MESSAGE IMPLEMENTATION\")\n const signedRequest = await TurnkeyApi.signSignRawPayload(\n {\n body: {\n type: \"ACTIVITY_TYPE_SIGN_RAW_PAYLOAD\",\n organizationId: id,\n parameters: {\n privateKeyId: walletId,\n payload: msg,\n encoding: \"PAYLOAD_ENCODING_HEXADECIMAL\",\n hashFunction: \"HASH_FUNCTION_NO_OP\",\n },\n timestampMs: String(Date.now()),\n },\n },\n {\n publicKey: {\n allowCredentials: [\n {\n id: base64URLStringToBuffer(credentialId),\n type: publicKey,\n },\n ],\n },\n }\n );\n const proxyResponse = await axios.post(\n `${apiUrl}/projects/${projectId}/wallets/proxy`,\n {\n signedRequest,\n }\n );\n const { activity } = await proxyResponse.data;\n if (activity.status === \"ACTIVITY_STATUS_COMPLETED\") {\n let result = activity?.result?.signRawPayloadResult;\n\n if (result) {\n const signatureHex = signatureToHex({\n r: `0x${result.r}`,\n s: `0x${result.s}`,\n v: result.v === \"00\" ? 27n : 28n,\n });\n if (signatureHex) {\n return signatureHex;\n }\n }\n }\n return \"0x\";\n};\n\nexport const signMessage = async (\n msg: string | Uint8Array,\n id: string,\n walletId: string,\n projectId: string,\n credentialId: string,\n apiUrl = API_URL\n) => {\n return await signMessageImplementation(\n hashMessage(typeof msg === 'string' ? msg : {raw: msg}),\n id,\n walletId,\n projectId,\n credentialId,\n apiUrl\n );\n};\n\nexport const signTypedData = async (\n params: SignTypedDataParams,\n id: string,\n walletId: string,\n projectId: string,\n credentialId: string,\n apiUrl = API_URL\n) => {\n const hashToSign = hashTypedData(params);\n return await signMessageImplementation(\n hashToSign,\n id,\n walletId,\n projectId,\n credentialId,\n apiUrl\n );\n};\n\n// https://github.com/MasterKale/SimpleWebAuthn/blob/master/packages/browser/src/helpers/base64URLStringToBuffer.ts#L8\nexport function base64URLStringToBuffer(base64URLString: string): ArrayBuffer {\n // Convert from Base64URL to Base64\n const base64 = base64URLString.replace(/-/g, \"+\").replace(/_/g, \"/\");\n /**\n * Pad with '=' until it's a multiple of four\n * (4 - (85 % 4 = 1) = 3) % 4 = 3 padding\n * (4 - (86 % 4 = 2) = 2) % 4 = 2 padding\n * (4 - (87 % 4 = 3) = 1) % 4 = 1 padding\n * (4 - (88 % 4 = 0) = 4) % 4 = 0 padding\n */\n const padLength = (4 - (base64.length % 4)) % 4;\n const padded = base64.padEnd(base64.length + padLength, \"=\");\n\n // Convert to a binary string\n const binary = atob(padded);\n\n // Convert binary string to buffer\n const buffer = new ArrayBuffer(binary.length);\n const bytes = new Uint8Array(buffer);\n\n for (let i = 0; i < binary.length; i++) {\n bytes[i] = binary.charCodeAt(i);\n }\n\n return buffer;\n}\n"]}
|
|
@@ -188,6 +188,8 @@ export class ZeroDevProvider extends SmartAccountProvider {
|
|
|
188
188
|
case "eth_sendTransaction":
|
|
189
189
|
const [tx] = params;
|
|
190
190
|
return this.sendTransaction(tx);
|
|
191
|
+
case "eth_signTypedData_v4":
|
|
192
|
+
return this.signTypedData(JSON.parse(params[1]));
|
|
191
193
|
case "personal_sign":
|
|
192
194
|
if (!this.account) {
|
|
193
195
|
throw new Error("account not connected!");
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"provider.js","sourceRoot":"","s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CAAC,8BAA8B,CAAC,KAAK,IAAI,CAAC;gBAClE,KAAK,CACN,CAAC;SACH;QACD,OAAO,KAAK,CAAC;IACf,CAAC;IAED,WAAW,CAAC,OAAY;QACtB,IAAI,OAAO,EAAE,KAAK,IAAI,IAAI,EAAE;YAC1B,IAAI,aAAa,GAAW,EAAE,CAAC;YAC/B,IAAI,eAAe,GAAuB,OAAO,EAAE,KAAK,EAAE,OAAO,CAAC;YAClE,IAAI,eAAe,EAAE,QAAQ,CAAC,UAAU,CAAC,KAAK,IAAI,EAAE;gBAElD,MAAM,OAAO,GAAG,eAAe,CAAC,KAAK,CAAC,kBAAkB,CAAC,CAAC;gBAC1D,IAAI,OAAO,IAAI,IAAI,EAAE;oBACnB,MAAM,KAAK,GAAG,OAAO,CAAC,CAAC,CAAC,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC;oBACpC,aAAa,GAAG,uBAAuB,KAAK,CAAC,CAAC,CAAC,GAAG,CAAC;oBACnD,eAAe,GAAG,KAAK,CAAC,CAAC,CAAC,CAAC;iBAC5B;aACF;YACD,MAAM,KAAK,GAAG,IAAI,KAAK,CACrB,+DAA+D,eAAe,IAAI,aAAa,EAAE,CAClG,CAAC;YACF,KAAK,CAAC,KAAK,GAAG,OAAO,CAAC,KAAK,CAAC;YAC5B,OAAO,KAAK,CAAC;SACd;QACD,OAAO,OAAO,CAAC;IACjB,CAAC;IAiBD,2BAA2B,CAAC,MAAwC;QAClE,IAAI,CAAC,IAAI,CAAC,WAAW,EAAE,EAAE;YACvB,MAAM,IAAI,KAAK,CACb,oEAAoE,CACrE,CAAC;SACH;QAED,OAAO,2BAA2B,CAAC,IAAI,EAAE,MAAM,CAAC,CAAC;IACnD,CAAC;CA6BF","sourcesContent":["import {\n fromHex,\n type Address,\n type Chain,\n type Hash,\n type Hex,\n type HttpTransport,\n type RpcTransactionRequest,\n} from \"viem\";\nimport {\n deepHexlify,\n resolveProperties,\n type SmartAccountProviderOpts,\n getChain,\n type UserOperationCallData,\n type BatchUserOperationCallData,\n type SendUserOperationResult,\n asyncPipe,\n noOpMiddleware,\n type UserOperationStruct,\n type BytesLike,\n SmartAccountProvider,\n type AccountMiddlewareFn,\n type UserOperationOverrides,\n} from \"@alchemy/aa-core\";\nimport {\n BUNDLER_URL,\n DEFAULT_SEND_TX_MAX_RETRIES,\n DEFAULT_SEND_TX_RETRY_INTERVAL_MS,\n ENTRYPOINT_ADDRESS,\n minPriorityFeePerBidDefaults,\n} from \"./constants.js\";\nimport { KernelSmartContractAccount, isKernelAccount } from \"./account.js\";\nimport { withZeroDevGasEstimator } from \"./middleware/gas-estimator.js\";\nimport { isValidRequest } from \"./utils/ERC4337-utils.js\";\nimport { InvalidOperation } from \"./errors.js\";\nimport { withZeroDevPaymasterAndData } from \"./middleware/paymaster.js\";\nimport { createZeroDevPublicErc4337Client } from \"./client/create-client.js\";\nimport type {\n PaymasterAndBundlerProviders,\n PaymasterConfig,\n PaymasterPolicy,\n} from \"./paymaster/types.js\";\n\nexport type ZeroDevProviderConfig = {\n projectId: string;\n chain: Chain | number;\n entryPointAddress?: Address;\n rpcUrl?: string;\n account?: KernelSmartContractAccount;\n bundlerProvider?: PaymasterAndBundlerProviders;\n opts?: SmartAccountProviderOpts & {\n sendTxMaxRetries?: number;\n sendTxRetryIntervalMs?: number;\n };\n};\n\nexport enum Operation {\n Call = 0,\n DelegateCall = 1,\n}\n\ntype UserOpDataOperationTypes<T> = T extends UserOperationCallData\n ? Operation.Call | Operation.DelegateCall\n : T extends BatchUserOperationCallData\n ? Operation.Call\n : never;\n\nexport class ZeroDevProvider extends SmartAccountProvider<HttpTransport> {\n protected projectId: string;\n protected sendTxMaxRetries: number;\n protected sendTxRetryIntervalMs: number;\n\n constructor({\n projectId,\n chain,\n entryPointAddress = ENTRYPOINT_ADDRESS,\n rpcUrl = BUNDLER_URL,\n account,\n bundlerProvider,\n opts,\n }: ZeroDevProviderConfig) {\n const _chain = typeof chain === \"number\" ? getChain(chain) : chain;\n const rpcClient = createZeroDevPublicErc4337Client({\n chain: _chain,\n rpcUrl,\n projectId,\n bundlerProvider,\n });\n\n super(rpcClient, entryPointAddress, _chain, account, {\n ...opts,\n txMaxRetries: opts?.txMaxRetries ?? 10,\n txRetryIntervalMs: opts?.txRetryIntervalMs ?? 10000,\n minPriorityFeePerBid:\n opts?.minPriorityFeePerBid ??\n minPriorityFeePerBidDefaults.get(_chain.id),\n });\n\n this.projectId = projectId;\n this.sendTxMaxRetries =\n opts?.sendTxMaxRetries ?? DEFAULT_SEND_TX_MAX_RETRIES;\n this.sendTxRetryIntervalMs =\n opts?.sendTxRetryIntervalMs ?? DEFAULT_SEND_TX_RETRY_INTERVAL_MS;\n\n withZeroDevGasEstimator(this);\n }\n\n getProjectId = (): string => this.projectId;\n\n sendTransaction = async (\n request: RpcTransactionRequest,\n operation: UserOpDataOperationTypes<UserOperationCallData> = Operation.Call\n ): Promise<Hash> => {\n if (!request.to) {\n throw new Error(\"transaction is missing to address\");\n }\n\n const overrides: UserOperationOverrides = {};\n if (request.maxFeePerGas) {\n overrides.maxFeePerGas = request.maxFeePerGas;\n }\n if (request.maxPriorityFeePerGas) {\n overrides.maxPriorityFeePerGas = request.maxPriorityFeePerGas;\n }\n\n const { hash } = await this.sendUserOperation(\n {\n target: request.to,\n data: request.data ?? \"0x\",\n value: request.value ? fromHex(request.value, \"bigint\") : 0n,\n },\n overrides,\n operation\n );\n\n return await this.waitForUserOperationTransaction(hash as Hash);\n };\n\n sendUserOperation = async <\n T extends UserOperationCallData | BatchUserOperationCallData\n >(\n data: T,\n overrides?: UserOperationOverrides,\n operation: UserOpDataOperationTypes<T> = Operation.Call as UserOpDataOperationTypes<T>\n ): Promise<SendUserOperationResult> => {\n if (!isKernelAccount(this.account)) {\n throw new Error(\"account not connected!\");\n }\n if (!this.account.validator) {\n throw new Error(\"validator not connected!\");\n }\n\n let callData: BytesLike = \"0x\";\n\n if (Array.isArray(data)) {\n if (operation === Operation.Call) {\n callData = await this.account.encodeBatchExecute(data);\n } else {\n throw InvalidOperation;\n }\n } else if (isKernelAccount(this.account)) {\n if (operation === Operation.DelegateCall) {\n callData = await this.account.encodeExecuteDelegate(\n data.target,\n data.value ?? 0n,\n data.data\n );\n } else if (operation === Operation.Call) {\n callData = await this.account.encodeExecute(\n data.target,\n data.value ?? 0n,\n data.data\n );\n } else {\n throw InvalidOperation;\n }\n } else {\n throw InvalidOperation;\n }\n\n const initCode = await this.account.getInitCode();\n let hash: string = \"\";\n let i = 0;\n const nonce = await this.account.getNonce();\n let uoStruct: UserOperationStruct;\n let request: UserOperationStruct;\n let maxFeePerGas, maxPriorityFeePerGas;\n do {\n uoStruct = await asyncPipe(\n this.dummyPaymasterDataMiddleware,\n this.feeDataGetter,\n this.paymasterDataMiddleware,\n this.gasEstimator,\n this.customMiddleware ?? noOpMiddleware,\n async (struct) => ({ ...struct, ...overrides })\n )({\n initCode,\n sender: this.getAddress(),\n nonce,\n callData,\n signature: await this.account\n .getValidator()\n .getDynamicDummySignature(await this.getAddress(), callData as Hex),\n maxFeePerGas,\n maxPriorityFeePerGas,\n } as UserOperationStruct);\n request = deepHexlify(await resolveProperties(uoStruct));\n\n if (!isValidRequest(request)) {\n // this pretty prints the uo\n throw new Error(\n `Request is missing parameters. All properties on UserOperationStruct must be set. uo: ${JSON.stringify(\n request,\n null,\n 2\n )}`\n );\n }\n\n this.account.approvePlugin();\n\n request.signature = await this.account.validator.getSignature(request);\n try {\n hash = await this.rpcClient.sendUserOperation(\n request,\n this.entryPointAddress\n );\n } catch (error: any) {\n if (this.isReplacementOpError(error) && i++ < this.sendTxMaxRetries) {\n maxFeePerGas = (BigInt(request.maxFeePerGas) * 113n) / 100n;\n maxPriorityFeePerGas =\n (BigInt(request.maxPriorityFeePerGas) * 113n) / 100n;\n\n console.log(\n `After ${\n this.sendTxRetryIntervalMs / 60000\n } minutes, resending tx with Increased Gas fees: maxFeePerGas: ${maxFeePerGas}, maxPriorityFeePerGas: ${maxPriorityFeePerGas}`\n );\n await new Promise((resolve) =>\n setTimeout(resolve, this.sendTxRetryIntervalMs)\n );\n continue;\n }\n throw this.unwrapError(error);\n }\n } while (hash === \"\");\n\n return {\n hash,\n request,\n };\n };\n\n isReplacementOpError(errorIn: any): boolean {\n if (errorIn.cause != null) {\n const failedOpMessage: string | undefined = errorIn?.cause?.message;\n return (\n (failedOpMessage?.includes(\n \"replacement op must increase maxFeePerGas and MaxPriorityFeePerGas\"\n ) ||\n failedOpMessage?.match(/.*replacement.*underpriced.*/) !== null) ??\n false\n );\n }\n return false;\n }\n\n unwrapError(errorIn: any): Error {\n if (errorIn?.cause != null) {\n let paymasterInfo: string = \"\";\n let failedOpMessage: string | undefined = errorIn?.cause?.message;\n if (failedOpMessage?.includes(\"FailedOp\") === true) {\n // TODO: better error extraction methods will be needed\n const matched = failedOpMessage.match(/FailedOp\\((.*)\\)/);\n if (matched != null) {\n const split = matched[1].split(\",\");\n paymasterInfo = `(paymaster address: ${split[1]})`;\n failedOpMessage = split[2];\n }\n }\n const error = new Error(\n `The bundler has failed to include UserOperation in a batch: ${failedOpMessage} ${paymasterInfo}`\n );\n error.stack = errorIn.stack;\n return error;\n }\n return errorIn;\n }\n\n getAccount: () => KernelSmartContractAccount = () => {\n if (!isKernelAccount(this.account)) {\n throw new Error(\"account not connected!\");\n }\n return this.account;\n };\n\n dummyPaymasterDataMiddleware: AccountMiddlewareFn = async (\n struct: UserOperationStruct\n ): Promise<UserOperationStruct> => {\n struct.paymasterAndData =\n \"0xfe7dbcab8aaee4eb67943c1e6be95b1d065985c6000000000000000000000000000000000000000000000000000001869aa31cf400000000000000000000000000000000000000000000000000000000000000007dfe2190f34af27b265bae608717cdc9368b471fc0c097ab7b4088f255b4961e57b039e7e571b15221081c5dce7bcb93459b27a3ab65d2f8a889f4a40b4022801b\";\n return struct;\n };\n\n withZeroDevPaymasterAndData(config: PaymasterConfig<PaymasterPolicy>) {\n if (!this.isConnected()) {\n throw new Error(\n \"ZeroDevProvider: account is not set, did you call `connect` first?\"\n );\n }\n\n return withZeroDevPaymasterAndData(this, config);\n }\n\n request: (args: { method: string; params?: any[] }) => Promise<any> = async (\n args\n ) => {\n const { method, params } = args;\n switch (method) {\n case \"eth_chainId\":\n return this.chain.id;\n case \"eth_sendTransaction\":\n const [tx] = params as [RpcTransactionRequest];\n return this.sendTransaction(tx);\n case \"personal_sign\":\n if (!this.account) {\n throw new Error(\"account not connected!\");\n }\n const [data, address] = params!;\n if (address !== (await this.getAddress())) {\n throw new Error(\n \"cannot sign for address that is not the current account\"\n );\n }\n // @ts-ignore\n return this.account.signWithEip6492(data);\n default:\n // @ts-ignore\n return this.rpcClient.request(args);\n }\n };\n}\n"]}
|
|
1
|
+
{"version":3,"file":"provider.js","sourceRoot":"","sources":["../../../src/kernel-zerodev/provider.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,OAAO,GAOR,MAAM,MAAM,CAAC;AACd,OAAO,EACL,WAAW,EACX,iBAAiB,EAEjB,QAAQ,EAIR,SAAS,EACT,cAAc,EAGd,oBAAoB,GAGrB,MAAM,kBAAkB,CAAC;AAC1B,OAAO,EACL,WAAW,EACX,2BAA2B,EAC3B,iCAAiC,EACjC,kBAAkB,EAClB,4BAA4B,GAC7B,MAAM,gBAAgB,CAAC;AACxB,OAAO,EAAE,0BAA0B,EAAE,eAAe,EAAE,MAAM,cAAc,CAAC;AAC3E,OAAO,EAAE,uBAAuB,EAAE,MAAM,+BAA+B,CAAC;AACxE,OAAO,EAAE,cAAc,EAAE,MAAM,0BAA0B,CAAC;AAC1D,OAAO,EAAE,gBAAgB,EAAE,MAAM,aAAa,CAAC;AAC/C,OAAO,EAAE,2BAA2B,EAAE,MAAM,2BAA2B,CAAC;AACxE,OAAO,EAAE,gCAAgC,EAAE,MAAM,2BAA2B,CAAC;AAoB7E,MAAM,CAAN,IAAY,SAGX;AAHD,WAAY,SAAS;IACnB,yCAAQ,CAAA;IACR,yDAAgB,CAAA;AAClB,CAAC,EAHW,SAAS,KAAT,SAAS,QAGpB;AAQD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B;aACF;YACD,MAAM,KAAK,GAAG,IAAI,KAAK,CACrB,+DAA+D,eAAe,IAAI,aAAa,EAAE,CAClG,CAAC;YACF,KAAK,CAAC,KAAK,GAAG,OAAO,CAAC,KAAK,CAAC;YAC5B,OAAO,KAAK,CAAC;SACd;QACD,OAAO,OAAO,CAAC;IACjB,CAAC;IAiBD,2BAA2B,CAAC,MAAwC;QAClE,IAAI,CAAC,IAAI,CAAC,WAAW,EAAE,EAAE;YACvB,MAAM,IAAI,KAAK,CACb,oEAAoE,CACrE,CAAC;SACH;QAED,OAAO,2BAA2B,CAAC,IAAI,EAAE,MAAM,CAAC,CAAC;IACnD,CAAC;CAgCF","sourcesContent":["import {\n fromHex,\n type Address,\n type Chain,\n type Hash,\n type Hex,\n type HttpTransport,\n type RpcTransactionRequest,\n} from \"viem\";\nimport {\n deepHexlify,\n resolveProperties,\n type SmartAccountProviderOpts,\n getChain,\n type UserOperationCallData,\n type BatchUserOperationCallData,\n type SendUserOperationResult,\n asyncPipe,\n noOpMiddleware,\n type UserOperationStruct,\n type BytesLike,\n SmartAccountProvider,\n type AccountMiddlewareFn,\n type UserOperationOverrides,\n} from \"@alchemy/aa-core\";\nimport {\n BUNDLER_URL,\n DEFAULT_SEND_TX_MAX_RETRIES,\n DEFAULT_SEND_TX_RETRY_INTERVAL_MS,\n ENTRYPOINT_ADDRESS,\n minPriorityFeePerBidDefaults,\n} from \"./constants.js\";\nimport { KernelSmartContractAccount, isKernelAccount } from \"./account.js\";\nimport { withZeroDevGasEstimator } from \"./middleware/gas-estimator.js\";\nimport { isValidRequest } from \"./utils/ERC4337-utils.js\";\nimport { InvalidOperation } from \"./errors.js\";\nimport { withZeroDevPaymasterAndData } from \"./middleware/paymaster.js\";\nimport { createZeroDevPublicErc4337Client } from \"./client/create-client.js\";\nimport type {\n PaymasterAndBundlerProviders,\n PaymasterConfig,\n PaymasterPolicy,\n} from \"./paymaster/types.js\";\n\nexport type ZeroDevProviderConfig = {\n projectId: string;\n chain: Chain | number;\n entryPointAddress?: Address;\n rpcUrl?: string;\n account?: KernelSmartContractAccount;\n bundlerProvider?: PaymasterAndBundlerProviders;\n opts?: SmartAccountProviderOpts & {\n sendTxMaxRetries?: number;\n sendTxRetryIntervalMs?: number;\n };\n};\n\nexport enum Operation {\n Call = 0,\n DelegateCall = 1,\n}\n\ntype UserOpDataOperationTypes<T> = T extends UserOperationCallData\n ? Operation.Call | Operation.DelegateCall\n : T extends BatchUserOperationCallData\n ? Operation.Call\n : never;\n\nexport class ZeroDevProvider extends SmartAccountProvider<HttpTransport> {\n protected projectId: string;\n protected sendTxMaxRetries: number;\n protected sendTxRetryIntervalMs: number;\n\n constructor({\n projectId,\n chain,\n entryPointAddress = ENTRYPOINT_ADDRESS,\n rpcUrl = BUNDLER_URL,\n account,\n bundlerProvider,\n opts,\n }: ZeroDevProviderConfig) {\n const _chain = typeof chain === \"number\" ? getChain(chain) : chain;\n const rpcClient = createZeroDevPublicErc4337Client({\n chain: _chain,\n rpcUrl,\n projectId,\n bundlerProvider,\n });\n\n super(rpcClient, entryPointAddress, _chain, account, {\n ...opts,\n txMaxRetries: opts?.txMaxRetries ?? 10,\n txRetryIntervalMs: opts?.txRetryIntervalMs ?? 10000,\n minPriorityFeePerBid:\n opts?.minPriorityFeePerBid ??\n minPriorityFeePerBidDefaults.get(_chain.id),\n });\n\n this.projectId = projectId;\n this.sendTxMaxRetries =\n opts?.sendTxMaxRetries ?? DEFAULT_SEND_TX_MAX_RETRIES;\n this.sendTxRetryIntervalMs =\n opts?.sendTxRetryIntervalMs ?? DEFAULT_SEND_TX_RETRY_INTERVAL_MS;\n\n withZeroDevGasEstimator(this);\n }\n\n getProjectId = (): string => this.projectId;\n\n sendTransaction = async (\n request: RpcTransactionRequest,\n operation: UserOpDataOperationTypes<UserOperationCallData> = Operation.Call\n ): Promise<Hash> => {\n if (!request.to) {\n throw new Error(\"transaction is missing to address\");\n }\n\n const overrides: UserOperationOverrides = {};\n if (request.maxFeePerGas) {\n overrides.maxFeePerGas = request.maxFeePerGas;\n }\n if (request.maxPriorityFeePerGas) {\n overrides.maxPriorityFeePerGas = request.maxPriorityFeePerGas;\n }\n\n const { hash } = await this.sendUserOperation(\n {\n target: request.to,\n data: request.data ?? \"0x\",\n value: request.value ? fromHex(request.value, \"bigint\") : 0n,\n },\n overrides,\n operation\n );\n\n return await this.waitForUserOperationTransaction(hash as Hash);\n };\n\n sendUserOperation = async <\n T extends UserOperationCallData | BatchUserOperationCallData\n >(\n data: T,\n overrides?: UserOperationOverrides,\n operation: UserOpDataOperationTypes<T> = Operation.Call as UserOpDataOperationTypes<T>\n ): Promise<SendUserOperationResult> => {\n if (!isKernelAccount(this.account)) {\n throw new Error(\"account not connected!\");\n }\n if (!this.account.validator) {\n throw new Error(\"validator not connected!\");\n }\n\n let callData: BytesLike = \"0x\";\n\n if (Array.isArray(data)) {\n if (operation === Operation.Call) {\n callData = await this.account.encodeBatchExecute(data);\n } else {\n throw InvalidOperation;\n }\n } else if (isKernelAccount(this.account)) {\n if (operation === Operation.DelegateCall) {\n callData = await this.account.encodeExecuteDelegate(\n data.target,\n data.value ?? 0n,\n data.data\n );\n } else if (operation === Operation.Call) {\n callData = await this.account.encodeExecute(\n data.target,\n data.value ?? 0n,\n data.data\n );\n } else {\n throw InvalidOperation;\n }\n } else {\n throw InvalidOperation;\n }\n\n const initCode = await this.account.getInitCode();\n let hash: string = \"\";\n let i = 0;\n const nonce = await this.account.getNonce();\n let uoStruct: UserOperationStruct;\n let request: UserOperationStruct;\n let maxFeePerGas, maxPriorityFeePerGas;\n do {\n uoStruct = await asyncPipe(\n this.dummyPaymasterDataMiddleware,\n this.feeDataGetter,\n this.paymasterDataMiddleware,\n this.gasEstimator,\n this.customMiddleware ?? noOpMiddleware,\n async (struct) => ({ ...struct, ...overrides })\n )({\n initCode,\n sender: this.getAddress(),\n nonce,\n callData,\n signature: await this.account\n .getValidator()\n .getDynamicDummySignature(await this.getAddress(), callData as Hex),\n maxFeePerGas,\n maxPriorityFeePerGas,\n } as UserOperationStruct);\n request = deepHexlify(await resolveProperties(uoStruct));\n\n if (!isValidRequest(request)) {\n // this pretty prints the uo\n throw new Error(\n `Request is missing parameters. All properties on UserOperationStruct must be set. uo: ${JSON.stringify(\n request,\n null,\n 2\n )}`\n );\n }\n\n this.account.approvePlugin();\n\n request.signature = await this.account.validator.getSignature(request);\n try {\n hash = await this.rpcClient.sendUserOperation(\n request,\n this.entryPointAddress\n );\n } catch (error: any) {\n if (this.isReplacementOpError(error) && i++ < this.sendTxMaxRetries) {\n maxFeePerGas = (BigInt(request.maxFeePerGas) * 113n) / 100n;\n maxPriorityFeePerGas =\n (BigInt(request.maxPriorityFeePerGas) * 113n) / 100n;\n\n console.log(\n `After ${\n this.sendTxRetryIntervalMs / 60000\n } minutes, resending tx with Increased Gas fees: maxFeePerGas: ${maxFeePerGas}, maxPriorityFeePerGas: ${maxPriorityFeePerGas}`\n );\n await new Promise((resolve) =>\n setTimeout(resolve, this.sendTxRetryIntervalMs)\n );\n continue;\n }\n throw this.unwrapError(error);\n }\n } while (hash === \"\");\n\n return {\n hash,\n request,\n };\n };\n\n isReplacementOpError(errorIn: any): boolean {\n if (errorIn.cause != null) {\n const failedOpMessage: string | undefined = errorIn?.cause?.message;\n return (\n (failedOpMessage?.includes(\n \"replacement op must increase maxFeePerGas and MaxPriorityFeePerGas\"\n ) ||\n failedOpMessage?.match(/.*replacement.*underpriced.*/) !== null) ??\n false\n );\n }\n return false;\n }\n\n unwrapError(errorIn: any): Error {\n if (errorIn?.cause != null) {\n let paymasterInfo: string = \"\";\n let failedOpMessage: string | undefined = errorIn?.cause?.message;\n if (failedOpMessage?.includes(\"FailedOp\") === true) {\n // TODO: better error extraction methods will be needed\n const matched = failedOpMessage.match(/FailedOp\\((.*)\\)/);\n if (matched != null) {\n const split = matched[1].split(\",\");\n paymasterInfo = `(paymaster address: ${split[1]})`;\n failedOpMessage = split[2];\n }\n }\n const error = new Error(\n `The bundler has failed to include UserOperation in a batch: ${failedOpMessage} ${paymasterInfo}`\n );\n error.stack = errorIn.stack;\n return error;\n }\n return errorIn;\n }\n\n getAccount: () => KernelSmartContractAccount = () => {\n if (!isKernelAccount(this.account)) {\n throw new Error(\"account not connected!\");\n }\n return this.account;\n };\n\n dummyPaymasterDataMiddleware: AccountMiddlewareFn = async (\n struct: UserOperationStruct\n ): Promise<UserOperationStruct> => {\n struct.paymasterAndData =\n \"0xfe7dbcab8aaee4eb67943c1e6be95b1d065985c6000000000000000000000000000000000000000000000000000001869aa31cf400000000000000000000000000000000000000000000000000000000000000007dfe2190f34af27b265bae608717cdc9368b471fc0c097ab7b4088f255b4961e57b039e7e571b15221081c5dce7bcb93459b27a3ab65d2f8a889f4a40b4022801b\";\n return struct;\n };\n\n withZeroDevPaymasterAndData(config: PaymasterConfig<PaymasterPolicy>) {\n if (!this.isConnected()) {\n throw new Error(\n \"ZeroDevProvider: account is not set, did you call `connect` first?\"\n );\n }\n\n return withZeroDevPaymasterAndData(this, config);\n }\n\n request: (args: { method: string; params?: any[] }) => Promise<any> = async (\n args\n ) => {\n const { method, params } = args;\n switch (method) {\n case \"eth_chainId\":\n return this.chain.id;\n case \"eth_sendTransaction\":\n const [tx] = params as [RpcTransactionRequest];\n return this.sendTransaction(tx);\n case \"eth_signTypedData_v4\":\n //@ts-expect-error\n return this.signTypedData(JSON.parse(params[1]))\n case \"personal_sign\":\n if (!this.account) {\n throw new Error(\"account not connected!\");\n }\n const [data, address] = params!;\n if (address !== (await this.getAddress())) {\n throw new Error(\n \"cannot sign for address that is not the current account\"\n );\n }\n // @ts-ignore\n return this.account.signWithEip6492(data);\n default:\n // @ts-ignore\n return this.rpcClient.request(args);\n }\n };\n}\n"]}
|
|
@@ -1,10 +1,9 @@
|
|
|
1
|
-
import type { Hex, Signature } from "./types.js";
|
|
2
1
|
import type { SignTypedDataParams } from "@alchemy/aa-core";
|
|
3
2
|
export declare const publicKey = "public-key";
|
|
4
3
|
export declare const es256 = -7;
|
|
5
4
|
export declare const generateRandomBuffer: () => ArrayBuffer;
|
|
6
5
|
export declare const base64UrlEncode: (challenge: ArrayBuffer) => string;
|
|
7
|
-
export declare
|
|
6
|
+
export declare const signMessageImplementation: (msg: string, id: string, walletId: string, projectId: string, credentialId: string, apiUrl?: string) => Promise<`0x${string}`>;
|
|
8
7
|
export declare const signMessage: (msg: string | Uint8Array, id: string, walletId: string, projectId: string, credentialId: string, apiUrl?: string) => Promise<`0x${string}`>;
|
|
9
8
|
export declare const signTypedData: (params: SignTypedDataParams, id: string, walletId: string, projectId: string, credentialId: string, apiUrl?: string) => Promise<`0x${string}`>;
|
|
10
9
|
export declare function base64URLStringToBuffer(base64URLString: string): ArrayBuffer;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"utils.d.ts","sourceRoot":"","sources":["../../../../../src/kernel-zerodev/owner/passkey/utils.ts"],"names":[],"mappings":"AAGA,OAAO,KAAK,EAAE,
|
|
1
|
+
{"version":3,"file":"utils.d.ts","sourceRoot":"","sources":["../../../../../src/kernel-zerodev/owner/passkey/utils.ts"],"names":[],"mappings":"AAGA,OAAO,KAAK,EAAE,mBAAmB,EAAE,MAAM,kBAAkB,CAAC;AAO5D,eAAO,MAAM,SAAS,eAAe,CAAC;AAEtC,eAAO,MAAM,KAAK,KAAK,CAAC;AAExB,eAAO,MAAM,oBAAoB,QAAO,WAKvC,CAAC;AAEF,eAAO,MAAM,eAAe,cAAe,WAAW,KAAG,MAMxD,CAAC;AAEF,eAAO,MAAM,yBAAyB,QAC/B,MAAM,MACP,MAAM,YACA,MAAM,aACL,MAAM,gBACH,MAAM,4CAmDrB,CAAC;AAEF,eAAO,MAAM,WAAW,QACjB,MAAM,GAAG,UAAU,MACpB,MAAM,YACA,MAAM,aACL,MAAM,gBACH,MAAM,4CAWrB,CAAC;AAEF,eAAO,MAAM,aAAa,WAChB,mBAAmB,MACvB,MAAM,YACA,MAAM,aACL,MAAM,gBACH,MAAM,4CAYrB,CAAC;AAGF,wBAAgB,u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Bd;IAEF,iBAAiB,sFAIH,sBAAsB,8CAEjC,QAAQ,uBAAuB,CAAC,CA2GjC;IAEF,oBAAoB,CAAC,OAAO,EAAE,GAAG,GAAG,OAAO;IAc3C,WAAW,CAAC,OAAO,EAAE,GAAG,GAAG,KAAK;IAsBhC,UAAU,EAAE,MAAM,0BAA0B,CAK1C;IAEF,4BAA4B,EAAE,mBAAmB,CAM/C;IAEF,2BAA2B,CAAC,MAAM,EAAE,eAAe,CAAC,eAAe,CAAC;;;IAUpE,OAAO,EAAE,CAAC,IAAI,EAAE;QAAE,MAAM,EAAE,MAAM,CAAC;QAAC,MAAM,CAAC,EAAE,GAAG,EAAE,CAAA;KAAE,KAAK,OAAO,CAAC,GAAG,CAAC,CA6BjE;CACH"}
|
package/package.json
CHANGED
|
@@ -1,10 +1,8 @@
|
|
|
1
1
|
import { browserInit, TurnkeyApi } from "@turnkey/http";
|
|
2
2
|
import axios from "axios";
|
|
3
3
|
import { API_URL } from "../../constants.js";
|
|
4
|
-
import type { Hex, Signature } from "./types.js";
|
|
5
|
-
import { ethers } from "ethers";
|
|
6
4
|
import type { SignTypedDataParams } from "@alchemy/aa-core";
|
|
7
|
-
import { hashTypedData } from "viem";
|
|
5
|
+
import { hashTypedData, signatureToHex, hashMessage } from "viem";
|
|
8
6
|
|
|
9
7
|
browserInit({
|
|
10
8
|
baseUrl: "https://api.turnkey.com",
|
|
@@ -29,32 +27,15 @@ export const base64UrlEncode = (challenge: ArrayBuffer): string => {
|
|
|
29
27
|
.replace(/=/g, "");
|
|
30
28
|
};
|
|
31
29
|
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
// return `0x${new secp256k1.Signature(
|
|
35
|
-
// hexToBigInt(r),
|
|
36
|
-
// hexToBigInt(s),
|
|
37
|
-
// ).toCompactHex()}${toHex(v).slice(2)}`
|
|
38
|
-
// }
|
|
39
|
-
|
|
40
|
-
//ETHERS
|
|
41
|
-
export function signatureToHex({ r, s, v }: Signature): Hex {
|
|
42
|
-
return ethers.utils.joinSignature({
|
|
43
|
-
r: `0x${r}`,
|
|
44
|
-
s: `0x${s}`,
|
|
45
|
-
//@ts-expect-error
|
|
46
|
-
v: parseInt(v) + 27,
|
|
47
|
-
}) as Hex;
|
|
48
|
-
}
|
|
49
|
-
|
|
50
|
-
export const signMessage = async (
|
|
51
|
-
msg: string | Uint8Array,
|
|
30
|
+
export const signMessageImplementation = async (
|
|
31
|
+
msg: string,
|
|
52
32
|
id: string,
|
|
53
33
|
walletId: string,
|
|
54
34
|
projectId: string,
|
|
55
35
|
credentialId: string,
|
|
56
36
|
apiUrl = API_URL
|
|
57
37
|
) => {
|
|
38
|
+
console.log("SIGN MESSAGE IMPLEMENTATION")
|
|
58
39
|
const signedRequest = await TurnkeyApi.signSignRawPayload(
|
|
59
40
|
{
|
|
60
41
|
body: {
|
|
@@ -62,7 +43,7 @@ export const signMessage = async (
|
|
|
62
43
|
organizationId: id,
|
|
63
44
|
parameters: {
|
|
64
45
|
privateKeyId: walletId,
|
|
65
|
-
payload:
|
|
46
|
+
payload: msg,
|
|
66
47
|
encoding: "PAYLOAD_ENCODING_HEXADECIMAL",
|
|
67
48
|
hashFunction: "HASH_FUNCTION_NO_OP",
|
|
68
49
|
},
|
|
@@ -91,15 +72,37 @@ export const signMessage = async (
|
|
|
91
72
|
let result = activity?.result?.signRawPayloadResult;
|
|
92
73
|
|
|
93
74
|
if (result) {
|
|
94
|
-
const
|
|
95
|
-
|
|
96
|
-
|
|
75
|
+
const signatureHex = signatureToHex({
|
|
76
|
+
r: `0x${result.r}`,
|
|
77
|
+
s: `0x${result.s}`,
|
|
78
|
+
v: result.v === "00" ? 27n : 28n,
|
|
79
|
+
});
|
|
80
|
+
if (signatureHex) {
|
|
81
|
+
return signatureHex;
|
|
97
82
|
}
|
|
98
83
|
}
|
|
99
84
|
}
|
|
100
85
|
return "0x";
|
|
101
86
|
};
|
|
102
87
|
|
|
88
|
+
export const signMessage = async (
|
|
89
|
+
msg: string | Uint8Array,
|
|
90
|
+
id: string,
|
|
91
|
+
walletId: string,
|
|
92
|
+
projectId: string,
|
|
93
|
+
credentialId: string,
|
|
94
|
+
apiUrl = API_URL
|
|
95
|
+
) => {
|
|
96
|
+
return await signMessageImplementation(
|
|
97
|
+
hashMessage(typeof msg === 'string' ? msg : {raw: msg}),
|
|
98
|
+
id,
|
|
99
|
+
walletId,
|
|
100
|
+
projectId,
|
|
101
|
+
credentialId,
|
|
102
|
+
apiUrl
|
|
103
|
+
);
|
|
104
|
+
};
|
|
105
|
+
|
|
103
106
|
export const signTypedData = async (
|
|
104
107
|
params: SignTypedDataParams,
|
|
105
108
|
id: string,
|
|
@@ -109,7 +112,7 @@ export const signTypedData = async (
|
|
|
109
112
|
apiUrl = API_URL
|
|
110
113
|
) => {
|
|
111
114
|
const hashToSign = hashTypedData(params);
|
|
112
|
-
return await
|
|
115
|
+
return await signMessageImplementation(
|
|
113
116
|
hashToSign,
|
|
114
117
|
id,
|
|
115
118
|
walletId,
|
|
@@ -323,6 +323,9 @@ export class ZeroDevProvider extends SmartAccountProvider<HttpTransport> {
|
|
|
323
323
|
case "eth_sendTransaction":
|
|
324
324
|
const [tx] = params as [RpcTransactionRequest];
|
|
325
325
|
return this.sendTransaction(tx);
|
|
326
|
+
case "eth_signTypedData_v4":
|
|
327
|
+
//@ts-expect-error
|
|
328
|
+
return this.signTypedData(JSON.parse(params[1]))
|
|
326
329
|
case "personal_sign":
|
|
327
330
|
if (!this.account) {
|
|
328
331
|
throw new Error("account not connected!");
|