@crossmint/client-sdk-smart-wallet 0.1.14 → 0.1.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/index.cjs +4 -4
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +39 -12
- package/dist/index.d.ts +39 -12
- package/dist/index.js +4 -4
- package/dist/index.js.map +1 -1
- package/package.json +2 -2
- package/src/blockchain/wallets/EVMSmartWallet.ts +31 -67
- package/src/blockchain/wallets/SendTransactionService.test.ts +43 -47
- package/src/blockchain/wallets/SendTransactionService.ts +12 -10
- package/src/blockchain/wallets/service.ts +3 -4
- package/src/index.ts +1 -2
- package/src/types/internal.ts +3 -3
- package/src/types/params.ts +2 -2
- package/src/types/token.ts +3 -1
package/dist/index.d.cts
CHANGED
|
@@ -1,15 +1,16 @@
|
|
|
1
1
|
import { ObjectValues } from '@crossmint/common-sdk-base';
|
|
2
2
|
export { EVMBlockchainIncludingTestnet as Chain, blockchainToChainId } from '@crossmint/common-sdk-base';
|
|
3
|
+
import * as viem from 'viem';
|
|
4
|
+
import { LocalAccount, EIP1193Provider, HttpTransport, Chain, Address, BaseError, ContractFunctionRevertedError, PublicClient, Transport, Hex, Abi, ContractFunctionName, ContractFunctionArgs, WriteContractParameters } from 'viem';
|
|
3
5
|
import * as _crossmint_client_sdk_base from '@crossmint/client-sdk-base';
|
|
4
6
|
import { BaseCrossmintService, APIErrorService, CrossmintSDKError, SmartWalletErrorCode } from '@crossmint/client-sdk-base';
|
|
5
|
-
export { CrossmintSDKError, CrossmintServiceError, JWTDecryptionError, JWTExpiredError, JWTIdentifierError, JWTInvalidError, NotAuthorizedError, SmartWalletErrorCode
|
|
6
|
-
import * as viem from 'viem';
|
|
7
|
-
import { LocalAccount, EIP1193Provider, HttpTransport, Chain, BaseError, ContractFunctionRevertedError, PublicClient, Abi, ContractFunctionName, ContractFunctionArgs, WriteContractParameters, Hex } from 'viem';
|
|
7
|
+
export { CrossmintSDKError, CrossmintServiceError, JWTDecryptionError, JWTExpiredError, JWTIdentifierError, JWTInvalidError, NotAuthorizedError, SmartWalletErrorCode } from '@crossmint/client-sdk-base';
|
|
8
8
|
import { SmartAccountClient, UserOperation } from 'permissionless';
|
|
9
9
|
import { EntryPoint, GetEntryPointVersion } from 'permissionless/types/entrypoint';
|
|
10
10
|
import { z } from 'zod';
|
|
11
11
|
import { SmartAccount } from 'permissionless/accounts';
|
|
12
12
|
import { PasskeyValidatorContractVersion } from '@zerodev/passkey-validator';
|
|
13
|
+
import { EntryPoint as EntryPoint$1 } from 'permissionless/_types/types';
|
|
13
14
|
|
|
14
15
|
declare const SmartWalletChain: {
|
|
15
16
|
readonly BASE: "base";
|
|
@@ -44,9 +45,9 @@ type PasskeySigner = {
|
|
|
44
45
|
*/
|
|
45
46
|
passkeyName?: string;
|
|
46
47
|
};
|
|
47
|
-
type
|
|
48
|
+
type ExternalSigner = EIP1193Provider | ViemAccount;
|
|
48
49
|
interface WalletParams {
|
|
49
|
-
signer:
|
|
50
|
+
signer: ExternalSigner | PasskeySigner;
|
|
50
51
|
}
|
|
51
52
|
|
|
52
53
|
declare const SUPPORTED_KERNEL_VERSIONS: readonly ["0.3.1", "0.3.0", "0.2.4"];
|
|
@@ -304,7 +305,7 @@ declare class CrossmintWalletService extends BaseCrossmintService {
|
|
|
304
305
|
|
|
305
306
|
interface EVMToken {
|
|
306
307
|
chain: SmartWalletChain;
|
|
307
|
-
contractAddress:
|
|
308
|
+
contractAddress: Address;
|
|
308
309
|
}
|
|
309
310
|
interface NFTEVMToken extends EVMToken {
|
|
310
311
|
tokenId: string;
|
|
@@ -330,6 +331,13 @@ type NFTTransferType = {
|
|
|
330
331
|
};
|
|
331
332
|
type TransferType = ERC20TransferType | SFTTransferType | NFTTransferType;
|
|
332
333
|
|
|
334
|
+
type TransactionServiceTransactionRequest = {
|
|
335
|
+
address: Address;
|
|
336
|
+
abi: Abi;
|
|
337
|
+
functionName: string;
|
|
338
|
+
args: any;
|
|
339
|
+
value?: bigint;
|
|
340
|
+
};
|
|
333
341
|
type SendTransactionFailureStage = "simulation" | "send" | "confirmation" | "execution";
|
|
334
342
|
/**
|
|
335
343
|
* Error thrown when a transaction fails to send.
|
|
@@ -386,6 +394,18 @@ interface SendTransactionOptions {
|
|
|
386
394
|
*/
|
|
387
395
|
transactionConfirmationTimeout: number;
|
|
388
396
|
}
|
|
397
|
+
declare class SendTransactionService {
|
|
398
|
+
private readonly client;
|
|
399
|
+
private readonly defaultSendTransactionOptions;
|
|
400
|
+
constructor(client: {
|
|
401
|
+
public: PublicClient;
|
|
402
|
+
wallet: SmartAccountClient<EntryPoint$1, Transport, Chain, SmartAccount<EntryPoint$1>>;
|
|
403
|
+
}, defaultSendTransactionOptions?: SendTransactionOptions);
|
|
404
|
+
sendTransaction(request: TransactionServiceTransactionRequest, config?: Partial<SendTransactionOptions>): Promise<Hex>;
|
|
405
|
+
private getConfig;
|
|
406
|
+
private handleReceipt;
|
|
407
|
+
private simulateCall;
|
|
408
|
+
}
|
|
389
409
|
|
|
390
410
|
/**
|
|
391
411
|
* Smart wallet interface for EVM chains enhanced with Crossmint capabilities.
|
|
@@ -393,8 +413,7 @@ interface SendTransactionOptions {
|
|
|
393
413
|
*/
|
|
394
414
|
declare class EVMSmartWallet {
|
|
395
415
|
private readonly crossmintService;
|
|
396
|
-
private readonly
|
|
397
|
-
protected readonly logger: _crossmint_client_sdk_base.SDKLogger;
|
|
416
|
+
private readonly sendTransactionService;
|
|
398
417
|
readonly chain: SmartWalletChain;
|
|
399
418
|
/**
|
|
400
419
|
* [viem](https://viem.sh/) clients that provide an interface for core wallet functionality.
|
|
@@ -409,16 +428,24 @@ declare class EVMSmartWallet {
|
|
|
409
428
|
*/
|
|
410
429
|
public: PublicClient;
|
|
411
430
|
};
|
|
412
|
-
|
|
413
|
-
|
|
431
|
+
constructor(client: {
|
|
432
|
+
public: PublicClient<HttpTransport>;
|
|
433
|
+
wallet: SmartWalletClient;
|
|
434
|
+
}, chain: SmartWalletChain, crossmintService: CrossmintWalletService, sendTransactionService?: SendTransactionService);
|
|
414
435
|
/**
|
|
415
436
|
* The address of the smart wallet.
|
|
416
437
|
*/
|
|
417
438
|
get address(): `0x${string}`;
|
|
418
439
|
/**
|
|
440
|
+
* Transfers tokens from the smart wallet to a specified address.
|
|
441
|
+
* @param toAddress The recipient's address.
|
|
442
|
+
* @param config The transfer configuration, including token details and amount.
|
|
419
443
|
* @returns The transaction hash.
|
|
444
|
+
* @throws {SmartWalletError} If there's a chain mismatch between this wallet and the input configuration.
|
|
445
|
+
* @throws {SendTransactionError} If the transaction fails to send. Contains the error thrown by the viem client.
|
|
446
|
+
* @throws {SendTransactionExecutionRevertedError} A subclass of SendTransactionError if the transaction fails due to a contract execution error.
|
|
420
447
|
*/
|
|
421
|
-
transferToken(toAddress:
|
|
448
|
+
transferToken(toAddress: Address, config: TransferType): Promise<string>;
|
|
422
449
|
/**
|
|
423
450
|
* @returns A list of NFTs owned by the wallet.
|
|
424
451
|
*/
|
|
@@ -527,4 +554,4 @@ declare class SmartWalletSDK {
|
|
|
527
554
|
private validChain;
|
|
528
555
|
}
|
|
529
556
|
|
|
530
|
-
export { AdminAlreadyUsedError, AdminMismatchError, ConfigError, type
|
|
557
|
+
export { AdminAlreadyUsedError, AdminMismatchError, ConfigError, type ERC20TransferType, EVMSendTransactionError, EVMSendTransactionExecutionRevertedError, EVMSmartWallet, SmartWalletChain as EVMSmartWalletChain, type ExternalSigner, type NFTTransferType, PasskeyIncompatibleAuthenticatorError, PasskeyMismatchError, PasskeyPromptError, PasskeyRegistrationError, type PasskeySigner, type SFTTransferType, SmartWalletError, SmartWalletSDK, type SmartWalletSDKInitParams, SmartWalletsNotEnabledError, type TransferType, type UserParams, UserWalletAlreadyCreatedError, type ViemAccount, type WalletParams };
|
package/dist/index.d.ts
CHANGED
|
@@ -1,15 +1,16 @@
|
|
|
1
1
|
import { ObjectValues } from '@crossmint/common-sdk-base';
|
|
2
2
|
export { EVMBlockchainIncludingTestnet as Chain, blockchainToChainId } from '@crossmint/common-sdk-base';
|
|
3
|
+
import * as viem from 'viem';
|
|
4
|
+
import { LocalAccount, EIP1193Provider, HttpTransport, Chain, Address, BaseError, ContractFunctionRevertedError, PublicClient, Transport, Hex, Abi, ContractFunctionName, ContractFunctionArgs, WriteContractParameters } from 'viem';
|
|
3
5
|
import * as _crossmint_client_sdk_base from '@crossmint/client-sdk-base';
|
|
4
6
|
import { BaseCrossmintService, APIErrorService, CrossmintSDKError, SmartWalletErrorCode } from '@crossmint/client-sdk-base';
|
|
5
|
-
export { CrossmintSDKError, CrossmintServiceError, JWTDecryptionError, JWTExpiredError, JWTIdentifierError, JWTInvalidError, NotAuthorizedError, SmartWalletErrorCode
|
|
6
|
-
import * as viem from 'viem';
|
|
7
|
-
import { LocalAccount, EIP1193Provider, HttpTransport, Chain, BaseError, ContractFunctionRevertedError, PublicClient, Abi, ContractFunctionName, ContractFunctionArgs, WriteContractParameters, Hex } from 'viem';
|
|
7
|
+
export { CrossmintSDKError, CrossmintServiceError, JWTDecryptionError, JWTExpiredError, JWTIdentifierError, JWTInvalidError, NotAuthorizedError, SmartWalletErrorCode } from '@crossmint/client-sdk-base';
|
|
8
8
|
import { SmartAccountClient, UserOperation } from 'permissionless';
|
|
9
9
|
import { EntryPoint, GetEntryPointVersion } from 'permissionless/types/entrypoint';
|
|
10
10
|
import { z } from 'zod';
|
|
11
11
|
import { SmartAccount } from 'permissionless/accounts';
|
|
12
12
|
import { PasskeyValidatorContractVersion } from '@zerodev/passkey-validator';
|
|
13
|
+
import { EntryPoint as EntryPoint$1 } from 'permissionless/_types/types';
|
|
13
14
|
|
|
14
15
|
declare const SmartWalletChain: {
|
|
15
16
|
readonly BASE: "base";
|
|
@@ -44,9 +45,9 @@ type PasskeySigner = {
|
|
|
44
45
|
*/
|
|
45
46
|
passkeyName?: string;
|
|
46
47
|
};
|
|
47
|
-
type
|
|
48
|
+
type ExternalSigner = EIP1193Provider | ViemAccount;
|
|
48
49
|
interface WalletParams {
|
|
49
|
-
signer:
|
|
50
|
+
signer: ExternalSigner | PasskeySigner;
|
|
50
51
|
}
|
|
51
52
|
|
|
52
53
|
declare const SUPPORTED_KERNEL_VERSIONS: readonly ["0.3.1", "0.3.0", "0.2.4"];
|
|
@@ -304,7 +305,7 @@ declare class CrossmintWalletService extends BaseCrossmintService {
|
|
|
304
305
|
|
|
305
306
|
interface EVMToken {
|
|
306
307
|
chain: SmartWalletChain;
|
|
307
|
-
contractAddress:
|
|
308
|
+
contractAddress: Address;
|
|
308
309
|
}
|
|
309
310
|
interface NFTEVMToken extends EVMToken {
|
|
310
311
|
tokenId: string;
|
|
@@ -330,6 +331,13 @@ type NFTTransferType = {
|
|
|
330
331
|
};
|
|
331
332
|
type TransferType = ERC20TransferType | SFTTransferType | NFTTransferType;
|
|
332
333
|
|
|
334
|
+
type TransactionServiceTransactionRequest = {
|
|
335
|
+
address: Address;
|
|
336
|
+
abi: Abi;
|
|
337
|
+
functionName: string;
|
|
338
|
+
args: any;
|
|
339
|
+
value?: bigint;
|
|
340
|
+
};
|
|
333
341
|
type SendTransactionFailureStage = "simulation" | "send" | "confirmation" | "execution";
|
|
334
342
|
/**
|
|
335
343
|
* Error thrown when a transaction fails to send.
|
|
@@ -386,6 +394,18 @@ interface SendTransactionOptions {
|
|
|
386
394
|
*/
|
|
387
395
|
transactionConfirmationTimeout: number;
|
|
388
396
|
}
|
|
397
|
+
declare class SendTransactionService {
|
|
398
|
+
private readonly client;
|
|
399
|
+
private readonly defaultSendTransactionOptions;
|
|
400
|
+
constructor(client: {
|
|
401
|
+
public: PublicClient;
|
|
402
|
+
wallet: SmartAccountClient<EntryPoint$1, Transport, Chain, SmartAccount<EntryPoint$1>>;
|
|
403
|
+
}, defaultSendTransactionOptions?: SendTransactionOptions);
|
|
404
|
+
sendTransaction(request: TransactionServiceTransactionRequest, config?: Partial<SendTransactionOptions>): Promise<Hex>;
|
|
405
|
+
private getConfig;
|
|
406
|
+
private handleReceipt;
|
|
407
|
+
private simulateCall;
|
|
408
|
+
}
|
|
389
409
|
|
|
390
410
|
/**
|
|
391
411
|
* Smart wallet interface for EVM chains enhanced with Crossmint capabilities.
|
|
@@ -393,8 +413,7 @@ interface SendTransactionOptions {
|
|
|
393
413
|
*/
|
|
394
414
|
declare class EVMSmartWallet {
|
|
395
415
|
private readonly crossmintService;
|
|
396
|
-
private readonly
|
|
397
|
-
protected readonly logger: _crossmint_client_sdk_base.SDKLogger;
|
|
416
|
+
private readonly sendTransactionService;
|
|
398
417
|
readonly chain: SmartWalletChain;
|
|
399
418
|
/**
|
|
400
419
|
* [viem](https://viem.sh/) clients that provide an interface for core wallet functionality.
|
|
@@ -409,16 +428,24 @@ declare class EVMSmartWallet {
|
|
|
409
428
|
*/
|
|
410
429
|
public: PublicClient;
|
|
411
430
|
};
|
|
412
|
-
|
|
413
|
-
|
|
431
|
+
constructor(client: {
|
|
432
|
+
public: PublicClient<HttpTransport>;
|
|
433
|
+
wallet: SmartWalletClient;
|
|
434
|
+
}, chain: SmartWalletChain, crossmintService: CrossmintWalletService, sendTransactionService?: SendTransactionService);
|
|
414
435
|
/**
|
|
415
436
|
* The address of the smart wallet.
|
|
416
437
|
*/
|
|
417
438
|
get address(): `0x${string}`;
|
|
418
439
|
/**
|
|
440
|
+
* Transfers tokens from the smart wallet to a specified address.
|
|
441
|
+
* @param toAddress The recipient's address.
|
|
442
|
+
* @param config The transfer configuration, including token details and amount.
|
|
419
443
|
* @returns The transaction hash.
|
|
444
|
+
* @throws {SmartWalletError} If there's a chain mismatch between this wallet and the input configuration.
|
|
445
|
+
* @throws {SendTransactionError} If the transaction fails to send. Contains the error thrown by the viem client.
|
|
446
|
+
* @throws {SendTransactionExecutionRevertedError} A subclass of SendTransactionError if the transaction fails due to a contract execution error.
|
|
420
447
|
*/
|
|
421
|
-
transferToken(toAddress:
|
|
448
|
+
transferToken(toAddress: Address, config: TransferType): Promise<string>;
|
|
422
449
|
/**
|
|
423
450
|
* @returns A list of NFTs owned by the wallet.
|
|
424
451
|
*/
|
|
@@ -527,4 +554,4 @@ declare class SmartWalletSDK {
|
|
|
527
554
|
private validChain;
|
|
528
555
|
}
|
|
529
556
|
|
|
530
|
-
export { AdminAlreadyUsedError, AdminMismatchError, ConfigError, type
|
|
557
|
+
export { AdminAlreadyUsedError, AdminMismatchError, ConfigError, type ERC20TransferType, EVMSendTransactionError, EVMSendTransactionExecutionRevertedError, EVMSmartWallet, SmartWalletChain as EVMSmartWalletChain, type ExternalSigner, type NFTTransferType, PasskeyIncompatibleAuthenticatorError, PasskeyMismatchError, PasskeyPromptError, PasskeyRegistrationError, type PasskeySigner, type SFTTransferType, SmartWalletError, SmartWalletSDK, type SmartWalletSDKInitParams, SmartWalletsNotEnabledError, type TransferType, type UserParams, UserWalletAlreadyCreatedError, type ViemAccount, type WalletParams };
|
package/dist/index.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import{blockchainToChainId as ia,EVMBlockchainIncludingTestnet as oa}from"@crossmint/common-sdk-base";import{isAddress as le,publicActions as _e}from"viem";import{TransferError as Ne}from"@crossmint/client-sdk-base";import{SDKLogger as ne,getBrowserLogger as We}from"@crossmint/client-sdk-base";var re="ZeroDev";var I="SCW_SDK",R="0.1.0",_="2024-06-09",z=["0.3.1","0.3.0","0.2.4"],q=["v0.6","v0.7"];var u=new ne(I),ae=new ne(I,We(I,{onlyDatadog:!0}));import{erc20Abi as Oe,erc721Abi as Ie}from"viem";var ie=[{inputs:[{internalType:"string",name:"uri_",type:"string"}],stateMutability:"nonpayable",type:"constructor"},{anonymous:!1,inputs:[{indexed:!0,internalType:"address",name:"account",type:"address"},{indexed:!0,internalType:"address",name:"operator",type:"address"},{indexed:!1,internalType:"bool",name:"approved",type:"bool"}],name:"ApprovalForAll",type:"event"},{anonymous:!1,inputs:[{indexed:!0,internalType:"address",name:"operator",type:"address"},{indexed:!0,internalType:"address",name:"from",type:"address"},{indexed:!0,internalType:"address",name:"to",type:"address"},{indexed:!1,internalType:"uint256[]",name:"ids",type:"uint256[]"},{indexed:!1,internalType:"uint256[]",name:"values",type:"uint256[]"}],name:"TransferBatch",type:"event"},{anonymous:!1,inputs:[{indexed:!0,internalType:"address",name:"operator",type:"address"},{indexed:!0,internalType:"address",name:"from",type:"address"},{indexed:!0,internalType:"address",name:"to",type:"address"},{indexed:!1,internalType:"uint256",name:"id",type:"uint256"},{indexed:!1,internalType:"uint256",name:"value",type:"uint256"}],name:"TransferSingle",type:"event"},{anonymous:!1,inputs:[{indexed:!1,internalType:"string",name:"value",type:"string"},{indexed:!0,internalType:"uint256",name:"id",type:"uint256"}],name:"URI",type:"event"},{inputs:[{internalType:"address",name:"account",type:"address"},{internalType:"uint256",name:"id",type:"uint256"}],name:"balanceOf",outputs:[{internalType:"uint256",name:"",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"address[]",name:"accounts",type:"address[]"},{internalType:"uint256[]",name:"ids",type:"uint256[]"}],name:"balanceOfBatch",outputs:[{internalType:"uint256[]",name:"",type:"uint256[]"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"address",name:"account",type:"address"},{internalType:"address",name:"operator",type:"address"}],name:"isApprovedForAll",outputs:[{internalType:"bool",name:"",type:"bool"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"address",name:"from",type:"address"},{internalType:"address",name:"to",type:"address"},{internalType:"uint256[]",name:"ids",type:"uint256[]"},{internalType:"uint256[]",name:"amounts",type:"uint256[]"},{internalType:"bytes",name:"data",type:"bytes"}],name:"safeBatchTransferFrom",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"address",name:"from",type:"address"},{internalType:"address",name:"to",type:"address"},{internalType:"uint256",name:"id",type:"uint256"},{internalType:"uint256",name:"amount",type:"uint256"},{internalType:"bytes",name:"data",type:"bytes"}],name:"safeTransferFrom",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"address",name:"operator",type:"address"},{internalType:"bool",name:"approved",type:"bool"}],name:"setApprovalForAll",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"bytes4",name:"interfaceId",type:"bytes4"}],name:"supportsInterface",outputs:[{internalType:"bool",name:"",type:"bool"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"uint256",name:"",type:"uint256"}],name:"uri",outputs:[{internalType:"string",name:"",type:"string"}],stateMutability:"view",type:"function"}];function oe({contract:r,config:e,from:t,to:n}){switch(e.token.type){case"ft":return{account:t,address:r,abi:Oe,functionName:"transfer",args:[n,e.amount]};case"sft":return{account:t,address:r,abi:ie,functionName:"safeTransferFrom",args:[t.address,n,e.token.tokenId,e.quantity,"0x00"],tokenId:e.token.tokenId};case"nft":return{account:t,address:r,abi:Ie,functionName:"safeTransferFrom",args:[t.address,n,e.token.tokenId],tokenId:e.token.tokenId}}}import{BaseError as X,ContractFunctionRevertedError as N}from"viem";import{CrossmintSDKError as Re,WalletErrorCode as se}from"@crossmint/client-sdk-base";var f=class extends Re{constructor(t,n,a,o=se.SEND_TRANSACTION_FAILED){super(t,o);this.viemError=n;this.stage=a}},A=class extends f{constructor(t,n,a,o,i,s=a.data,p=a.reason){super(t,n,i,se.SEND_TRANSACTION_EXECUTION_REVERTED);this.viemError=n;this.txId=o;this.stage=i;this.data=s;this.reason=p}},D=class{constructor(e,t={confirmations:2,transactionConfirmationTimeout:3e4}){this.publicClient=e;this.defaultSendTransactionOptions=t}async sendTransaction(e,t,n={}){let{confirmations:a,transactionConfirmationTimeout:o}=this.getConfig(n);await this.simulateCall(e,void 0,"simulation");let i;try{i=await t.writeContract({...e,account:t.account,chain:t.chain})}catch(s){throw s instanceof X?new f(s.message,s,"send"):s}try{let s=await this.publicClient.waitForTransactionReceipt({hash:i,confirmations:a,timeout:o});return await this.handleReceipt(s,e)}catch(s){throw s instanceof X?new f(s.message,s,"confirmation"):s}}getConfig(e){return{...this.defaultSendTransactionOptions,...e}}async handleReceipt(e,t){if(e.status==="reverted")throw await this.simulateCall(t,e.transactionHash,"execution"),new A("Transaction reverted but unable to detect the reason",new N({abi:t.abi,functionName:t.functionName}),new N({abi:t.abi,functionName:t.functionName}),e.transactionHash,"execution");return e.transactionHash}async simulateCall(e,t,n){try{await this.publicClient.simulateContract({...e,account:e.address,chain:this.publicClient.chain})}catch(a){if(a instanceof X){let o=a.walk(i=>i instanceof N);throw o instanceof N?new A(o.message,a,o,t,n):new f(a.message,a,n)}throw a}}};var T=class{constructor(e,t,n,a,o=u){this.crossmintService=e;this.accountClient=t;this.logger=o;this.chain=a,this.client={wallet:t,public:n},this.sendTransactionService=new D(n)}get address(){return this.accountClient.account.address}async transferToken(e,t){return this.logger.logPerformance("TRANSFER",async()=>{if(this.chain!==t.token.chain)throw new Error(`Chain mismatch: Expected ${t.token.chain}, but got ${this.chain}. Ensure you are interacting with the correct blockchain.`);if(!le(e))throw new Error(`Invalid recipient address: '${e}' is not a valid EVM address.`);if(!le(t.token.contractAddress))throw new Error(`Invalid contract address: '${t.token.contractAddress}' is not a valid EVM address.`);let n=oe({contract:t.token.contractAddress,to:e,from:this.accountClient.account,config:t});try{let a=this.accountClient.extend(_e),{request:o}=await a.simulateContract(n),i=await a.writeContract(o);return this.logger.log(`[TRANSFER] - Transaction hash from transfer: ${i}`),i}catch(a){this.logger.error("[TRANSFER] - ERROR_TRANSFERRING_TOKEN",{error:a instanceof Error?a.message:JSON.stringify(a),tokenId:n.tokenId,contractAddress:t.token.contractAddress,chain:t.token.chain});let o=n.tokenId==null?"":`:${n.tokenId}}`;throw new Ne(`Error transferring token ${t.token.contractAddress}${o}`)}},{toAddress:e,config:t})}async nfts(){return this.crossmintService.fetchNFTs(this.address,this.chain)}async executeContract({address:e,abi:t,functionName:n,args:a,value:o,config:i}){return this.sendTransactionService.sendTransaction({address:e,abi:t,functionName:n,args:a,value:o},this.accountClient,i)}};import{CrossmintSDKError as De,SmartWalletErrorCode as m}from"@crossmint/client-sdk-base";var l=class extends De{constructor(e,t,n=m.UNCATEGORIZED){super(e,n,t)}},S=class extends l{constructor(e,t,n){super(e,m.ADMIN_MISMATCH),this.required=t,this.used=n}},b=class extends l{constructor(e,t,n){super(e,m.PASSKEY_MISMATCH),this.required=t,this.used=n}},x=class extends l{constructor(t){super(`The user with userId ${t.toString()} already has a wallet created for this project`);this.code=m.USER_WALLET_ALREADY_CREATED}},w=class extends l{constructor(e){super(`Prompt was either cancelled or timed out for passkey ${e}`,void 0,m.PASSKEY_PROMPT),this.passkeyName=e}},v=class extends l{constructor(e){super(`Registration for passkey ${e} failed, either the registration took too long, or passkey signature vaildation failed.`,void 0,m.PASSKEY_REGISTRATION),this.passkeyName=e}},W=class extends l{constructor(e){super(`User selected authenticator for passkey ${e} is not compatible with Crossmint's Smart Wallets.`,void 0,m.PASSKEY_INCOMPATIBLE_AUTHENTICATOR),this.passkeyName=e}},h=class extends l{constructor(e){super(e,void 0,m.WALLET_CONFIG)}},k=class extends h{constructor(){super("This signer was already used to create another wallet. Please use a different signer.");this.code=m.ADMIN_SIGNER_ALREADY_USED}},O=class extends h{constructor(){super("Smart wallets are not enabled for this project. They can be enabled on the project settings page in the developer console.");this.code=m.SMART_WALLETS_NOT_ENABLED}};import{SmartWalletErrorCode as ma,CrossmintSDKError as da,CrossmintServiceError as ua,TransferError as ya,JWTDecryptionError as ga,JWTExpiredError as fa,JWTIdentifierError as Sa,JWTInvalidError as ha,NotAuthorizedError as Ca}from"@crossmint/client-sdk-base";import{stringify as Lt}from"viem";import{validateAPIKey as Kt}from"@crossmint/common-sdk-base";import{APIErrorService as He,BaseCrossmintService as Ge,CrossmintServiceError as je}from"@crossmint/client-sdk-base";import{blockchainToChainId as Je}from"@crossmint/common-sdk-base";import{PasskeyValidatorContractVersion as Me}from"@zerodev/passkey-validator";import{isAddress as Ue,isHex as Ve}from"viem";import{z as c}from"zod";var Le=c.custom(r=>Ve(r),{message:"Invalid hex string"}),M=c.custom(r=>Ue(r),{message:"Invalid evm address"}),Ke=c.object({eoaAddress:M,type:c.literal("eoa")}),$e=c.object({entryPoint:M,validatorAddress:M,pubKeyX:c.string(),pubKeyY:c.string(),authenticatorIdHash:Le,authenticatorId:c.string()}),Be=$e.extend({passkeyName:c.string(),validatorContractVersion:c.nativeEnum(Me),domain:c.string(),type:c.literal("passkeys")}),Fe=c.discriminatedUnion("type",[Be,Ke]),U=c.object({kernelVersion:c.enum(z,{errorMap:(r,e)=>({message:`Unsupported kernel version. Supported versions: ${z.join(", ")}. Version used: ${e.data}. Please contact support`})}),entryPointVersion:c.enum(q,{errorMap:(r,e)=>({message:`Unsupported entry point version. Supported versions: ${q.join(", ")}. Version used: ${e.data}. Please contact support`})}),userId:c.string().min(1),signers:c.array(c.object({signerData:Fe})).min(0).max(1,"Invalid wallet signer configuration. Please contact support"),smartContractWalletAddress:M.optional()});import{toHex as Ye}from"viem";function V(r,e){let t=e(r);return t.replace?t.value:Array.isArray(r)?r.map(n=>V(n,e)):r!==null&&typeof r=="object"?Object.fromEntries(Object.entries(r).map(([n,a])=>[n,V(a,e)])):t.value}function ce(r){return V(r,e=>typeof e=="bigint"?{value:Ye(e),replace:!0}:{value:e,replace:!1})}function pe(r){return V(r,e=>e!=null&&typeof e=="object"&&"__xm_serializedType"in e&&"value"in e&&e.__xm_serializedType==="bigint"&&typeof e.value=="string"?{value:BigInt(e.value),replace:!0}:{value:e,replace:!1})}var L=class extends Ge{constructor(){super(...arguments);this.logger=u;this.apiErrorService=new He({ERROR_USER_WALLET_ALREADY_CREATED:({userId:t})=>new x(t),ERROR_ADMIN_SIGNER_ALREADY_USED:()=>new k,ERROR_PROJECT_NONCUSTODIAL_WALLETS_NOT_ENABLED:()=>new O})}async idempotentCreateSmartWallet(t,n){await this.fetchCrossmintAPI(`${_}/sdk/smart-wallet`,{method:"PUT",body:JSON.stringify(n)},"Error creating abstract wallet. Please contact support",t.jwt)}async sponsorUserOperation(t,n,a,o){let i=Je(o),s=await this.fetchCrossmintAPI(`${_}/sdk/paymaster`,{method:"POST",body:JSON.stringify({userOp:ce(n),entryPoint:a,chainId:i})},"Error sponsoring user operation. Please contact support",t.jwt);return pe(s)}async getSmartWalletConfig(t,n){let a=await this.fetchCrossmintAPI(`${_}/sdk/smart-wallet/config?chain=${n}`,{method:"GET"},"Error getting smart wallet version configuration. Please contact support",t.jwt),o=U.safeParse(a);if(!o.success)throw new je(`Invalid smart wallet config, please contact support. Details below:
|
|
2
|
-
${
|
|
3
|
-
${e.walletParams}`);let t=e.existing.signerConfig.display(),n=Q(e.walletParams)?"passkey":"eoa";throw new
|
|
4
|
-
'${JSON.stringify(t,null,2)}'`,t)}};import{signerToEcdsaValidator as
|
|
1
|
+
import{blockchainToChainId as Jn,EVMBlockchainIncludingTestnet as qn}from"@crossmint/common-sdk-base";import{CrossmintSDKError as ve,SmartWalletErrorCode as m}from"@crossmint/client-sdk-base";var l=class extends ve{constructor(e,t,n=m.UNCATEGORIZED){super(e,n,t)}},f=class extends l{constructor(e,t,n){super(e,m.ADMIN_MISMATCH),this.required=t,this.used=n}},A=class extends l{constructor(e,t,n){super(e,m.PASSKEY_MISMATCH),this.required=t,this.used=n}},T=class extends l{constructor(t){super(`The user with userId ${t.toString()} already has a wallet created for this project`);this.code=m.USER_WALLET_ALREADY_CREATED}},b=class extends l{constructor(e){super(`Prompt was either cancelled or timed out for passkey ${e}`,void 0,m.PASSKEY_PROMPT),this.passkeyName=e}},x=class extends l{constructor(e){super(`Registration for passkey ${e} failed, either the registration took too long, or passkey signature vaildation failed.`,void 0,m.PASSKEY_REGISTRATION),this.passkeyName=e}},w=class extends l{constructor(e){super(`User selected authenticator for passkey ${e} is not compatible with Crossmint's Smart Wallets.`,void 0,m.PASSKEY_INCOMPATIBLE_AUTHENTICATOR),this.passkeyName=e}},g=class extends l{constructor(e){super(e,void 0,m.WALLET_CONFIG)}},v=class extends g{constructor(){super("This signer was already used to create another wallet. Please use a different signer.");this.code=m.ADMIN_SIGNER_ALREADY_USED}},W=class extends g{constructor(){super("Smart wallets are not enabled for this project. They can be enabled on the project settings page in the developer console.");this.code=m.SMART_WALLETS_NOT_ENABLED}};import{erc20Abi as ke,erc721Abi as Oe}from"viem";var re=[{inputs:[{internalType:"string",name:"uri_",type:"string"}],stateMutability:"nonpayable",type:"constructor"},{anonymous:!1,inputs:[{indexed:!0,internalType:"address",name:"account",type:"address"},{indexed:!0,internalType:"address",name:"operator",type:"address"},{indexed:!1,internalType:"bool",name:"approved",type:"bool"}],name:"ApprovalForAll",type:"event"},{anonymous:!1,inputs:[{indexed:!0,internalType:"address",name:"operator",type:"address"},{indexed:!0,internalType:"address",name:"from",type:"address"},{indexed:!0,internalType:"address",name:"to",type:"address"},{indexed:!1,internalType:"uint256[]",name:"ids",type:"uint256[]"},{indexed:!1,internalType:"uint256[]",name:"values",type:"uint256[]"}],name:"TransferBatch",type:"event"},{anonymous:!1,inputs:[{indexed:!0,internalType:"address",name:"operator",type:"address"},{indexed:!0,internalType:"address",name:"from",type:"address"},{indexed:!0,internalType:"address",name:"to",type:"address"},{indexed:!1,internalType:"uint256",name:"id",type:"uint256"},{indexed:!1,internalType:"uint256",name:"value",type:"uint256"}],name:"TransferSingle",type:"event"},{anonymous:!1,inputs:[{indexed:!1,internalType:"string",name:"value",type:"string"},{indexed:!0,internalType:"uint256",name:"id",type:"uint256"}],name:"URI",type:"event"},{inputs:[{internalType:"address",name:"account",type:"address"},{internalType:"uint256",name:"id",type:"uint256"}],name:"balanceOf",outputs:[{internalType:"uint256",name:"",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"address[]",name:"accounts",type:"address[]"},{internalType:"uint256[]",name:"ids",type:"uint256[]"}],name:"balanceOfBatch",outputs:[{internalType:"uint256[]",name:"",type:"uint256[]"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"address",name:"account",type:"address"},{internalType:"address",name:"operator",type:"address"}],name:"isApprovedForAll",outputs:[{internalType:"bool",name:"",type:"bool"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"address",name:"from",type:"address"},{internalType:"address",name:"to",type:"address"},{internalType:"uint256[]",name:"ids",type:"uint256[]"},{internalType:"uint256[]",name:"amounts",type:"uint256[]"},{internalType:"bytes",name:"data",type:"bytes"}],name:"safeBatchTransferFrom",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"address",name:"from",type:"address"},{internalType:"address",name:"to",type:"address"},{internalType:"uint256",name:"id",type:"uint256"},{internalType:"uint256",name:"amount",type:"uint256"},{internalType:"bytes",name:"data",type:"bytes"}],name:"safeTransferFrom",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"address",name:"operator",type:"address"},{internalType:"bool",name:"approved",type:"bool"}],name:"setApprovalForAll",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"bytes4",name:"interfaceId",type:"bytes4"}],name:"supportsInterface",outputs:[{internalType:"bool",name:"",type:"bool"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"uint256",name:"",type:"uint256"}],name:"uri",outputs:[{internalType:"string",name:"",type:"string"}],stateMutability:"view",type:"function"}];function ne({contract:r,config:e,from:t,to:n}){switch(e.token.type){case"ft":return{account:t,address:r,abi:ke,functionName:"transfer",args:[n,e.amount]};case"sft":return{account:t,address:r,abi:re,functionName:"safeTransferFrom",args:[t.address,n,e.token.tokenId,e.quantity,"0x00"],tokenId:e.token.tokenId};case"nft":return{account:t,address:r,abi:Oe,functionName:"safeTransferFrom",args:[t.address,n,e.token.tokenId],tokenId:e.token.tokenId}}}import{BaseError as J,ContractFunctionRevertedError as I}from"viem";import{CrossmintSDKError as Ie,WalletErrorCode as ae}from"@crossmint/client-sdk-base";var S=class extends Ie{constructor(t,n,a,s=ae.SEND_TRANSACTION_FAILED){super(t,s);this.viemError=n;this.stage=a}},k=class extends S{constructor(t,n,a,s,i,o=a.data,p=a.reason){super(t,n,i,ae.SEND_TRANSACTION_EXECUTION_REVERTED);this.viemError=n;this.txId=s;this.stage=i;this.data=o;this.reason=p}},R=class{constructor(e,t={confirmations:2,transactionConfirmationTimeout:3e4}){this.client=e;this.defaultSendTransactionOptions=t}async sendTransaction(e,t={}){let{confirmations:n,transactionConfirmationTimeout:a}=this.getConfig(t);await this.simulateCall(e,void 0,"simulation");let s;try{s=await this.client.wallet.writeContract({...e,account:this.client.wallet.account,chain:this.client.wallet.chain})}catch(i){throw i instanceof J?new S(i.message,i,"send"):i}try{let i=await this.client.public.waitForTransactionReceipt({hash:s,confirmations:n,timeout:a});return await this.handleReceipt(i,e)}catch(i){throw i instanceof J?new S(i.message,i,"confirmation"):i}}getConfig(e){return{...this.defaultSendTransactionOptions,...e}}async handleReceipt(e,t){if(e.status==="reverted")throw await this.simulateCall(t,e.transactionHash,"execution"),new k("Transaction reverted but unable to detect the reason",new I({abi:t.abi,functionName:t.functionName}),new I({abi:t.abi,functionName:t.functionName}),e.transactionHash,"execution");return e.transactionHash}async simulateCall(e,t,n){try{await this.client.public.simulateContract({...e,account:this.client.wallet.account.address,chain:this.client.public.chain})}catch(a){if(a instanceof J){let s=a.walk(i=>i instanceof I);throw s instanceof I?new k(s.message,a,s,t,n):new S(a.message,a,n)}throw a}}};var O=class{constructor(e,t,n,a=new R(e)){this.crossmintService=n;this.sendTransactionService=a;this.chain=t,this.client=e}get address(){return this.client.wallet.account.address}async transferToken(e,t){if(this.chain!==t.token.chain)throw new l(`Chain mismatch: Expected ${t.token.chain}, but got ${this.chain}. Ensure you are interacting with the correct blockchain.`);return this.executeContract(ne({contract:t.token.contractAddress,to:e,from:this.client.wallet.account,config:t}))}async nfts(){return this.crossmintService.fetchNFTs(this.address,this.chain)}async executeContract({address:e,abi:t,functionName:n,args:a,value:s,config:i}){return this.sendTransactionService.sendTransaction({address:e,abi:t,functionName:n,args:a,value:s},i)}};import{SmartWalletErrorCode as ta,CrossmintSDKError as ra,CrossmintServiceError as na,JWTDecryptionError as aa,JWTExpiredError as ia,JWTIdentifierError as sa,JWTInvalidError as oa,NotAuthorizedError as la}from"@crossmint/client-sdk-base";import{stringify as Mt}from"viem";import{validateAPIKey as Ut}from"@crossmint/common-sdk-base";import{APIErrorService as Be,BaseCrossmintService as Fe,CrossmintServiceError as Ye}from"@crossmint/client-sdk-base";import{blockchainToChainId as He}from"@crossmint/common-sdk-base";import{SDKLogger as se,getBrowserLogger as Re}from"@crossmint/client-sdk-base";var ie="ZeroDev";var _="SCW_SDK",N="0.1.0",D="2024-06-09",q=["0.3.1","0.3.0","0.2.4"],X=["v0.6","v0.7"];var h=new se(_),oe=new se(_,Re(_,{onlyDatadog:!0}));import{PasskeyValidatorContractVersion as _e}from"@zerodev/passkey-validator";import{isAddress as Ne,isHex as De}from"viem";import{z as c}from"zod";var Me=c.custom(r=>De(r),{message:"Invalid hex string"}),M=c.custom(r=>Ne(r),{message:"Invalid evm address"}),Ue=c.object({eoaAddress:M,type:c.literal("eoa")}),Ve=c.object({entryPoint:M,validatorAddress:M,pubKeyX:c.string(),pubKeyY:c.string(),authenticatorIdHash:Me,authenticatorId:c.string()}),Le=Ve.extend({passkeyName:c.string(),validatorContractVersion:c.nativeEnum(_e),domain:c.string(),type:c.literal("passkeys")}),Ke=c.discriminatedUnion("type",[Le,Ue]),U=c.object({kernelVersion:c.enum(q,{errorMap:(r,e)=>({message:`Unsupported kernel version. Supported versions: ${q.join(", ")}. Version used: ${e.data}. Please contact support`})}),entryPointVersion:c.enum(X,{errorMap:(r,e)=>({message:`Unsupported entry point version. Supported versions: ${X.join(", ")}. Version used: ${e.data}. Please contact support`})}),userId:c.string().min(1),signers:c.array(c.object({signerData:Ke})).min(0).max(1,"Invalid wallet signer configuration. Please contact support"),smartContractWalletAddress:M.optional()});import{toHex as $e}from"viem";function V(r,e){let t=e(r);return t.replace?t.value:Array.isArray(r)?r.map(n=>V(n,e)):r!==null&&typeof r=="object"?Object.fromEntries(Object.entries(r).map(([n,a])=>[n,V(a,e)])):t.value}function le(r){return V(r,e=>typeof e=="bigint"?{value:$e(e),replace:!0}:{value:e,replace:!1})}function ce(r){return V(r,e=>e!=null&&typeof e=="object"&&"__xm_serializedType"in e&&"value"in e&&e.__xm_serializedType==="bigint"&&typeof e.value=="string"?{value:BigInt(e.value),replace:!0}:{value:e,replace:!1})}var L=class extends Fe{constructor(){super(...arguments);this.logger=h;this.apiErrorService=new Be({ERROR_USER_WALLET_ALREADY_CREATED:({userId:t})=>new T(t),ERROR_ADMIN_SIGNER_ALREADY_USED:()=>new v,ERROR_PROJECT_NONCUSTODIAL_WALLETS_NOT_ENABLED:()=>new W})}async idempotentCreateSmartWallet(t,n){await this.fetchCrossmintAPI(`${D}/sdk/smart-wallet`,{method:"PUT",body:JSON.stringify(n)},"Error creating abstract wallet. Please contact support",t.jwt)}async sponsorUserOperation(t,n,a,s){let i=He(s),o=await this.fetchCrossmintAPI(`${D}/sdk/paymaster`,{method:"POST",body:JSON.stringify({userOp:le(n),entryPoint:a,chainId:i})},"Error sponsoring user operation. Please contact support",t.jwt);return ce(o)}async getSmartWalletConfig(t,n){let a=await this.fetchCrossmintAPI(`${D}/sdk/smart-wallet/config?chain=${n}`,{method:"GET"},"Error getting smart wallet version configuration. Please contact support",t.jwt),s=U.safeParse(a);if(!s.success)throw new Ye(`Invalid smart wallet config, please contact support. Details below:
|
|
2
|
+
${s.error.toString()}`);return s.data}async fetchNFTs(t,n){return this.fetchCrossmintAPI(`v1-alpha1/wallets/${n}:${t}/nfts`,{method:"GET"},`Error fetching NFTs for wallet: ${t}`)}getPasskeyServerUrl(){return this.crossmintBaseUrl+"api/internal/passkeys"}};import{arbitrum as Ge,arbitrumSepolia as je,base as ze,baseSepolia as Je,optimism as qe,optimismSepolia as Xe,polygon as Ze,polygonAmoy as Qe}from"viem/chains";import{BlockchainIncludingTestnet as d,objectValues as Z}from"@crossmint/common-sdk-base";var pe={BASE_SEPOLIA:d.BASE_SEPOLIA,POLYGON_AMOY:d.POLYGON_AMOY,OPTIMISM_SEPOLIA:d.OPTIMISM_SEPOLIA,ARBITRUM_SEPOLIA:d.ARBITRUM_SEPOLIA},et=Z(pe),me={BASE:d.BASE,POLYGON:d.POLYGON,OPTIMISM:d.OPTIMISM,ARBITRUM:d.ARBITRUM},tt=Z(me),rt={...pe,...me},br=Z(rt);function ue(r){return et.includes(r)}function de(r){return tt.includes(r)}var ye={polygon:Ze,"polygon-amoy":Qe,base:ze,"base-sepolia":Je,optimism:qe,"optimism-sepolia":Xe,arbitrum:Ge,"arbitrum-sepolia":je};import{keccak256 as nt,toHex as at}from"viem";var K=class{constructor(e){this.keyPrefix=e}set(e,t){localStorage.setItem(this.key(e),JSON.stringify(t))}get(e){let t=this.key(e),n=localStorage.getItem(t);if(n==null)return null;let a=U.safeParse(JSON.parse(n));return a.success?a.data:(localStorage.removeItem(t),null)}clear(){for(let e=0;e<localStorage.length;e++){let t=localStorage.key(e);t&&t.startsWith(this.keyPrefix)&&(localStorage.removeItem(t),e--)}}key(e){return`${this.keyPrefix}-${nt(at(e.jwt))}`}};var C=class{constructor(e){this.type="passkeys";this.data=e}display(){return{pubKeyX:this.data.pubKeyX,pubKeyY:this.data.pubKeyY,passkeyName:this.data.passkeyName,type:this.type}}},P=class{constructor(e){this.type="eoa";this.data=e}display(){return this.data}};var $=class{constructor(e,t){this.crossmintService=e;this.configCache=t}async get(e,t){let n=this.configCache.get(e);if(n!=null)return{config:this.validateAndFormat(e,n),cached:!0};let a=await this.crossmintService.getSmartWalletConfig(e,t);return{config:this.validateAndFormat(e,a),cached:!1}}cache({entryPointVersion:e,kernelVersion:t,user:n,existing:a}){this.configCache.clear(),this.configCache.set(n,{entryPointVersion:e,kernelVersion:t,userId:n.id,signers:[{signerData:a.signerConfig.data}],smartContractWalletAddress:a.address})}validateAndFormat(e,{entryPointVersion:t,kernelVersion:n,signers:a,smartContractWalletAddress:s,userId:i}){if(t==="v0.7"&&n.startsWith("0.2")||t==="v0.6"&&n.startsWith("0.3"))throw new l(`Unsupported combination: entryPoint ${t} and kernel version ${n}. Please contact support`);let o=a.map(u=>u.signerData),p=this.getSigner(o);if(s!=null&&p==null||p!=null&&s==null)throw new l("Either both signer and address must be present, or both must be null");return p==null||s==null?{entryPointVersion:t,kernelVersion:n,userWithId:{...e,id:i}}:{entryPointVersion:t,kernelVersion:n,userWithId:{...e,id:i},existing:{signerConfig:p,address:s}}}getSigner(e){if(e.length===0)return;let t=e[0];if(t.type==="eoa")return new P(t);if(t.type==="passkeys")return new C(t)}};function Q(r){return"signer"in r&&"type"in r.signer&&r.signer.type==="PASSKEY"}function fe(r){let e=r.existing==null||r.existing.signerConfig.type==="passkeys";return Q(r.walletParams)&&e}function it(r){return"signer"in r&&("type"in r.signer&&r.signer.type==="VIEM_ACCOUNT"||"request"in r.signer&&typeof r.signer.request=="function")}function ge(r){let e=r.existing==null||r.existing.signerConfig.type==="eoa";return it(r.walletParams)&&e}var B=class{constructor(e,t){this.eoaStrategy=e;this.passkeyStrategy=t}get(e){if(fe(e))return this.passkeyStrategy.create(e);if(ge(e))return this.eoaStrategy.create(e);if(e.existing==null)throw new g(`Unsupported wallet params:
|
|
3
|
+
${e.walletParams}`);let t=e.existing.signerConfig.display(),n=Q(e.walletParams)?"passkey":"eoa";throw new f(`Cannot create wallet with ${n} signer for user ${e.user.id}', they already have a wallet with signer:
|
|
4
|
+
'${JSON.stringify(t,null,2)}'`,t)}};import{signerToEcdsaValidator as ct}from"@zerodev/ecdsa-validator";import{createKernelAccount as pt}from"@zerodev/sdk";function Se(r,e){return r?.toLowerCase()===e?.toLowerCase()}import{providerToSmartAccountSigner as st}from"permissionless";async function he({walletParams:r}){if(ot(r.signer))return await st(r.signer);if(lt(r.signer))return r.signer.account;{let e=r.signer;throw new l(`The signer type ${e.type} is not supported`)}}function ot(r){return r&&typeof r.request=="function"}function lt(r){return r&&r.type==="VIEM_ACCOUNT"}var F=class{async create({chain:e,publicClient:t,entryPoint:n,walletParams:a,kernelVersion:s,user:i,existing:o}){let p=await he({chain:e,walletParams:a});if(o!=null&&!Se(p.address,o.signerConfig.data.eoaAddress))throw new f(`User '${i.id}' has an existing wallet with an eoa signer '${o.signerConfig.data.eoaAddress}', this does not match input eoa signer '${p.address}'.`,o.signerConfig.display(),{type:"eoa",eoaAddress:o.signerConfig.data.eoaAddress});let u=await ct(t,{signer:p,entryPoint:n,kernelVersion:s});return{account:await pt(t,{plugins:{sudo:u},index:0n,entryPoint:n,kernelVersion:s,deployedAccountAddress:o?.address}),signerConfig:new P({eoaAddress:p.address,type:"eoa"})}}};import{PasskeyValidatorContractVersion as mt,WebAuthnMode as ut,toPasskeyValidator as dt}from"@zerodev/passkey-validator";import{createKernelAccount as yt}from"@zerodev/sdk";import{toWebAuthnKey as ft}from"@zerodev/webauthn-key";var Y=class{constructor(e,t){this.passkeyServerUrl=e;this.apiKey=t}async create({user:e,publicClient:t,walletParams:n,entryPoint:a,kernelVersion:s,existing:i}){let o=n.signer.passkeyName??e.id;if(i!=null&&i.signerConfig.data.passkeyName!==o)throw new A(`User '${e.id}' has an existing wallet created with a passkey named '${i.signerConfig.data.passkeyName}', this does match input passkey name '${o}'.`,i.signerConfig.display());try{let p=await this.getPasskey(e,o,i?.signerConfig.data),u=mt.V0_0_2,y=i==null?u:i.signerConfig.data.validatorContractVersion,E=await dt(t,{webAuthnKey:p,entryPoint:a,validatorContractVersion:y,kernelVersion:s}),we=await yt(t,{plugins:{sudo:E},entryPoint:a,kernelVersion:s,deployedAccountAddress:i?.address});return{signerConfig:this.getSignerConfig(E,y,o),account:this.decorate(we,o)}}catch(p){throw this.mapError(p,o)}}async getPasskey(e,t,n){return n!=null?{pubX:BigInt(n.pubKeyX),pubY:BigInt(n.pubKeyY),authenticatorId:n.authenticatorId,authenticatorIdHash:n.authenticatorIdHash}:ft({passkeyName:t,passkeyServerUrl:this.passkeyServerUrl,mode:ut.Register,passkeyServerHeaders:this.createPasskeysServerHeaders(e)})}getSignerConfig(e,t,n){return new C({...ht(e.getSerializedData()),passkeyName:n,validatorContractVersion:t,domain:window.location.hostname,type:"passkeys"})}createPasskeysServerHeaders(e){return{"x-api-key":this.apiKey,Authorization:`Bearer ${e.jwt}`}}mapError(e,t){return e.code===0&&e.name==="DataError"?new w(t):e.message==="Registration not verified"?new x(t):e.code==="ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY"&&e.name==="NotAllowedError"?new b(t):e}decorate(e,t){return new Proxy(e,{get:(n,a,s)=>{let i=Reflect.get(n,a,s);return typeof i!="function"||typeof a!="string"||!St(a)?i:async(...o)=>{try{return await i.call(n,...o)}catch(p){throw this.mapError(p,t)}}}})}},gt=["signMessage","signTypedData","signUserOperation","signTransaction"];function St(r){return gt.includes(r)}var ht=r=>{let e=Ct(r),t=new TextDecoder().decode(e);return JSON.parse(t)};function Ct(r){let e=atob(r);return Uint8Array.from(e,t=>t.codePointAt(0))}import{stringify as Ce}from"viem";function H(r){return!1}var Pt=["sendTransaction","writeContract","sendUserOperation"],Et=["signMessage","signTypedData"];function ee(r){return Pt.includes(r)}function At(r){return Et.includes(r)}var G=class{constructor(e,t=h){this.errorProcessor=e;this.logger=t}decorate({crossmintChain:e,smartAccountClient:t}){return new Proxy(t,{get:(n,a,s)=>{let i=Reflect.get(n,a,s);return typeof i!="function"||typeof a!="string"||!(At(a)||ee(a))?i:(...o)=>this.logger.logPerformance(`CrossmintSmartWallet.${a}`,()=>this.execute(n,a,i,o,e))}})}async execute(e,t,n,a,s){try{this.logger.log(`[CrossmintSmartWallet.${t}] - params: ${Ce(a)}`);let i=ee(t)?this.processTxnArgs(t,s,a):a;return await n.call(e,...i)}catch(i){let o=ee(t)?"signing":"sending transaction";throw this.errorProcessor.map(i,new l(`Error ${o}: ${i.message}`,Ce(i)))}}processTxnArgs(e,t,n){if(e==="sendUserOperation"){let[{userOperation:s,middleware:i,account:o}]=n;return[{middleware:i,account:o,userOperation:this.addGelatoBundlerProperties(t,s)},...n.slice(1)]}let[a]=n;return[this.addGelatoBundlerProperties(t,a),...n.slice(1)]}addGelatoBundlerProperties(e,t){return H(e)?{...t,maxFeePerGas:"0x0",maxPriorityFeePerGas:"0x0"}:t}};import{ENTRYPOINT_ADDRESS_V06 as Wt,ENTRYPOINT_ADDRESS_V07 as kt,createSmartAccountClient as Ot}from"permissionless";import{createPimlicoBundlerClient as It}from"permissionless/clients/pimlico";import{createPublicClient as Rt,http as be}from"viem";import{blockchainToChainId as _t}from"@crossmint/common-sdk-base";import{blockchainToChainId as Tt}from"@crossmint/common-sdk-base";var bt="-7M6vRDBDknwvMxnqah_jbcieWg0qad9",xt="pim_9dKmQPxiTCvtbUNF7XFBbA",wt={polygon:"polygon-mainnet","polygon-amoy":"polygon-amoy",base:"base-mainnet","base-sepolia":"base-sepolia",optimism:"opt-mainnet","optimism-sepolia":"opt-sepolia",arbitrum:"arb-mainnet","arbitrum-sepolia":"arb-sepolia"};function Pe(r){return`https://${wt[r]}.g.alchemy.com/v2/${bt}`}function Ee(r){return`https://api.pimlico.io/v2/${Tt(r)}/rpc?apikey=${xt}`}function Ae(r){return!H(r)}function Te({bundlerClient:r,entryPoint:e,chain:t,walletService:n,user:a}){return{middleware:{gasPrice:async()=>(await r.getUserOperationGasPrice()).fast,sponsorUserOperation:async({userOperation:s})=>{let{sponsorUserOpParams:i}=await n.sponsorUserOperation(a,s,e,t);return i}}}}var j=class{constructor(e,t,n,a){this.crossmintService=e;this.accountConfigService=t;this.accountCreator=n;this.clientDecorator=a}async getOrCreate(e,t,n){let{config:{entryPointVersion:a,kernelVersion:s,existing:i,userWithId:o},cached:p}=await this.accountConfigService.get(e,t),u=Rt({transport:be(Pe(t))}),{account:y,signerConfig:E}=await this.accountCreator.get({chain:t,walletParams:n,publicClient:u,user:o,entryPoint:a==="v0.6"?Wt:kt,kernelVersion:s,existing:i});return i==null&&await this.crossmintService.idempotentCreateSmartWallet(e,{type:ie,smartContractWalletAddress:y.address,signerData:E.data,version:0,baseLayer:"evm",chainId:_t(t),entryPointVersion:a,kernelVersion:s}),p||this.accountConfigService.cache({entryPointVersion:a,kernelVersion:s,user:o,existing:{address:y.address,signerConfig:E}}),new O({wallet:this.smartAccountClient(t,y,e),public:u},t,this.crossmintService)}smartAccountClient(e,t,n){let a=be(Ee(e)),s={chain:ye[e],entryPoint:t.entryPoint},i=It({...s,transport:a}),o=Ot({account:t,bundlerTransport:a,...s,...Ae(e)&&Te({bundlerClient:i,entryPoint:t.entryPoint,chain:e,walletService:this.crossmintService,user:n})});return this.clientDecorator.decorate({crossmintChain:e,smartAccountClient:o})}};import{BaseError as Nt,stringify as Dt}from"viem";var z=class{constructor(e){this.logger=e}map(e,t){return this.record(e),e instanceof l||e instanceof Nt?e:t}record(e){let t=e instanceof Error?e.message:String(e);this.logger.error(`Smart Wallet SDK Error: ${t}`,{stack:e instanceof Error?e.stack:void 0,name:e instanceof Error?e.name:"UnknownError",details:Dt(e),domain:window.location.hostname,sdk_version:N})}};function xe(){return typeof window<"u"}var te=class r{constructor(e,t,n,a=h){this.crossmintEnv=e;this.smartWalletService=t;this.errorProcessor=n;this.logger=a}static init({clientApiKey:e}){let t=Ut(e);if(!t.isValid)throw new Error("API key invalid");let n=new L(e),a=new z(oe),s=new B(new F,new Y(n.getPasskeyServerUrl(),e)),i=new K(`smart-wallet-${N}`),o=new j(n,new $(n,i),s,new G(a));return new r(t.environment,o,a)}async getOrCreateWallet(e,t,n={signer:{type:"PASSKEY"}}){if(!xe())throw new l("Smart Wallet SDK should only be used client side.");return this.assertValidChain(t),this.logger.logPerformance("GET_OR_CREATE_WALLET",async()=>{try{return await this.smartWalletService.getOrCreate(e,t,n)}catch(a){throw this.errorProcessor.map(a,new l(`Wallet creation failed: ${a.message}.`,Mt(a)))}})}assertValidChain(e){if(!this.validChain(e))throw new l(`The selected chain "${e}" is not available in "${this.crossmintEnv}". Either set a valid chain or check you're using an API key for the environment you're trying to target.`)}validChain(e){return this.crossmintEnv==="development"||this.crossmintEnv==="staging"?ue(e):de(e)}};export{v as AdminAlreadyUsedError,f as AdminMismatchError,qn as Chain,g as ConfigError,ra as CrossmintSDKError,na as CrossmintServiceError,S as EVMSendTransactionError,k as EVMSendTransactionExecutionRevertedError,O as EVMSmartWallet,aa as JWTDecryptionError,ia as JWTExpiredError,sa as JWTIdentifierError,oa as JWTInvalidError,la as NotAuthorizedError,w as PasskeyIncompatibleAuthenticatorError,A as PasskeyMismatchError,b as PasskeyPromptError,x as PasskeyRegistrationError,l as SmartWalletError,ta as SmartWalletErrorCode,te as SmartWalletSDK,W as SmartWalletsNotEnabledError,T as UserWalletAlreadyCreatedError,Jn as blockchainToChainId};
|
|
5
5
|
//# sourceMappingURL=index.js.map
|