@crossmint/client-sdk-smart-wallet 0.1.1 → 0.1.2
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 +1 -1
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +17 -2
- package/dist/index.d.ts +17 -2
- package/dist/index.js +1 -1
- package/dist/index.js.map +1 -1
- package/package.json +2 -1
- package/src/blockchain/wallets/passkey.ts +80 -25
- package/src/error/index.ts +42 -0
- package/src/index.ts +4 -2
- package/src/types/Tokens.ts +1 -1
- package/src/types/internal.ts +1 -1
- package/src/utils/blockchain.ts +1 -1
- package/src/utils/signer.ts +1 -1
- package/src/blockchain/token/index.ts +0 -1
package/dist/index.cjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
"use strict";var G=Object.defineProperty,mt=Object.defineProperties,dt=Object.getOwnPropertyDescriptor,ut=Object.getOwnPropertyDescriptors,yt=Object.getOwnPropertyNames,_e=Object.getOwnPropertySymbols;var Oe=Object.prototype.hasOwnProperty,ft=Object.prototype.propertyIsEnumerable;var We=(r,e,t)=>e in r?G(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t,c=(r,e)=>{for(var t in e||(e={}))Oe.call(e,t)&&We(r,t,e[t]);if(_e)for(var t of _e(e))ft.call(e,t)&&We(r,t,e[t]);return r},E=(r,e)=>mt(r,ut(e));var St=(r,e)=>{for(var t in e)G(r,t,{get:e[t],enumerable:!0})},Et=(r,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let a of yt(e))!Oe.call(r,a)&&a!==t&&G(r,a,{get:()=>e[a],enumerable:!(n=dt(e,a))||n.enumerable});return r};var gt=r=>Et(G({},"__esModule",{value:!0}),r);var i=(r,e,t)=>new Promise((n,a)=>{var o=u=>{try{l(t.next(u))}catch(m){a(m)}},s=u=>{try{l(t.throw(u))}catch(m){a(m)}},l=u=>u.done?n(u.value):Promise.resolve(u.value).then(o,s);l((t=t.apply(r,e)).next())});var vt={};St(vt,{AdminAlreadyUsedError:()=>M,AdminMismatchError:()=>h,ConfigError:()=>L,CrossmintServiceError:()=>f,EVMSmartWallet:()=>K,JWTDecryptionError:()=>k,JWTExpiredError:()=>v,JWTIdentifierError:()=>N,JWTInvalidError:()=>x,NonCustodialWalletsNotEnabledError:()=>U,NotAuthorizedError:()=>R,OutOfCreditsError:()=>V,PasskeyMismatchError:()=>b,SmartWalletChain:()=>ge,SmartWalletSDK:()=>ye,SmartWalletSDKError:()=>p,TransferError:()=>D,UserWalletAlreadyCreatedError:()=>A,blockchainToChainId:()=>pt.blockchainToChainId});module.exports=gt(vt);var pt=require("@crossmint/common-sdk-base");function H(){return typeof window!="undefined"}function z(){return process.env.NODE_ENV==="test"?!1:window.location.origin.includes("localhost")}function q(r,e){return(r==null?void 0:r.toLowerCase())===(e==null?void 0:e.toLowerCase())}var fe=!1,X=class{logInfo(e,t){fe&&console.log(e,t)}logError(e,t){fe&&console.error(e,t)}logWarn(e,t){fe&&console.warn(e,t)}};var De="ZeroDev";var be="pub035be8a594b35be1887b6ba76c4029ca",ve="http://localhost:3000/api",xe="https://staging.crossmint.com/api",ke="https://www.crossmint.com/api",P="SCW_SDK",Ne="0.1.0",Se="2024-06-09",Ve="https://rpc.zerodev.app/api/v2/bundler/",Le="https://rpc.zerodev.app/api/v2/paymaster/";var Z=require("@datadog/browser-logs");var O=class{logInfo(e,t){Ee(e,"info",t)}logError(e,t){Ee(e,"error",t)}logWarn(e,t){Ee(e,"warn",t)}};function Ee(r,e,t){let n=t?E(c({},t),{service:P}):{service:P};Pt(),Z.datadogLogs.logger[e](r,n)}function Pt(){Z.datadogLogs.getInternalContext()==null&&Z.datadogLogs.init({clientToken:be,site:"datadoghq.com",forwardErrorsToLogs:!1,sampleRate:100})}function ht(){return H()&&z()?new X:new O}var{logInfo:Q,logWarn:Yt,logError:I}=ht();var J=require("viem");var y={NOT_AUTHORIZED:"smart-wallet:not-authorized",TRANSFER:"smart-wallet:transfer.error",CROSSMINT_SERVICE:"smart-wallet:crossmint-service.error",ERROR_JWT_EXPIRED:"smart-wallet:not-authorized.jwt-expired",ERROR_JWT_INVALID:"smart-wallet:not-authorized.jwt-invalid",ERROR_JWT_DECRYPTION:"smart-wallet:not-authorized.jwt-decryption",ERROR_JWT_IDENTIFIER:"smart-wallet:not-authorized.jwt-identifier",ERROR_USER_WALLET_ALREADY_CREATED:"smart-wallet:user-wallet-already-created.error",ERROR_OUT_OF_CREDITS:"smart-wallet:out-of-credits.error",ERROR_WALLET_CONFIG:"smart-wallet:wallet-config.error",ERROR_ADMIN_MISMATCH:"smart-wallet:wallet-config.admin-mismatch",ERROR_PASSKEY_MISMATCH:"smart-wallet:wallet-config.passkey-mismatch",ERROR_ADMIN_SIGNER_ALREADY_USED:"smart-wallet:wallet-config.admin-signer-already-used",ERROR_PROJECT_NONCUSTODIAL_WALLETS_NOT_ENABLED:"smart-wallet:wallet-config.non-custodial-wallets-not-enabled",UNCATEGORIZED:"smart-wallet:uncategorized"},p=class extends Error{constructor(e,t,n=y.UNCATEGORIZED){super(e),this.details=t,this.code=n}},D=class extends p{constructor(e){super(e,void 0,y.TRANSFER)}},f=class extends p{constructor(e,t){super(e,void 0,y.CROSSMINT_SERVICE),this.status=t}},h=class extends p{constructor(e,t,n){super(e,y.ERROR_ADMIN_MISMATCH),this.required=t,this.used=n}},b=class extends p{constructor(e,t,n){super(e,y.ERROR_PASSKEY_MISMATCH),this.required=t,this.used=n}},R=class extends p{constructor(e){super(e,void 0,y.NOT_AUTHORIZED)}},v=class extends R{constructor(t){super(`JWT provided expired at timestamp ${t}`);this.code=y.ERROR_JWT_EXPIRED;this.expiredAt=t.toISOString()}},x=class extends R{constructor(){super("Invalid JWT provided");this.code=y.ERROR_JWT_INVALID}},k=class extends R{constructor(){super("Error decrypting JWT");this.code=y.ERROR_JWT_DECRYPTION}},N=class extends R{constructor(t){super(`Missing required identifier '${t}' in the JWT`);this.code=y.ERROR_JWT_IDENTIFIER;this.identifierKey=t}},A=class extends p{constructor(t){super(`The user with userId ${t.toString()} already has a wallet created for this project`);this.code=y.ERROR_USER_WALLET_ALREADY_CREATED}},V=class extends p{constructor(e){super("You've run out of Crossmint API credits. Visit https://docs.crossmint.com/docs/errors for more information",void 0,y.ERROR_OUT_OF_CREDITS)}},L=class extends p{constructor(e){super(e,void 0,y.ERROR_WALLET_CONFIG)}},M=class extends L{constructor(){super("This signer was already used to create another wallet. Please use a different signer.");this.code=y.ERROR_ADMIN_SIGNER_ALREADY_USED}},U=class extends L{constructor(){super("Non-custodial wallets are not enabled for this project");this.code=y.ERROR_PROJECT_NONCUSTODIAL_WALLETS_NOT_ENABLED}};var Me=require("uuid");var w=class{constructor(e,t={},n=(0,Me.v4)()){this.extraInfo=t;this.logIdempotencyKey=n;return new Proxy(this,{get:(a,o,s)=>{let l=a[o],u=`[${P} - ${e} - ${String(o)}]`;return typeof l=="function"?(...m)=>{this.logInput(m,u);let d=l.apply(a,m);return d instanceof Promise?d.then(S=>(this.logOutput(S,u),S)).catch(S=>{throw this.logError(S,u),S}):(this.logOutput(d,u),d)}:Reflect.get(a,o,s)}})}logInput(e,t){$(`${t} input - ${g(e)} - extra_info - ${g(this.extraInfo)} - log_idempotency_key - ${this.logIdempotencyKey}`,E(c({args:e},this.extraInfo),{logIdempotencyKey:this.logIdempotencyKey}))}logOutput(e,t){$(`${t} output - ${g(e)} - extra_info - ${g(this.extraInfo)} - log_idempotency_key - ${this.logIdempotencyKey}`,E(c({res:e},this.extraInfo),{logIdempotencyKey:this.logIdempotencyKey}))}logError(e,t){I(`${t} threw_error - ${e} - extra_info - ${g(this.extraInfo)} - log_idempotency_key - ${this.logIdempotencyKey}`,c({err:e},this.extraInfo))}logPerformance(e,t){return _(e,t,this.extraInfo)}};function _(r,e,t){return i(this,null,function*(){let n=new Date().getTime(),a=yield e(),o=new Date().getTime()-n,s=c({durationInMs:o},t);return $(`[${P} - ${r} - TIME] - ${g(s)}`,{args:s}),a})}function Ue(r,e){return function(...t){let n=`[${P} - function: ${e}]`;$(`${n} input: ${g(t)}`,{args:t});try{let a=r.apply(this,t);return a instanceof Promise?a.then(o=>($(`${n} output: ${g(o)}`,{res:o}),o)).catch(o=>{throw I(`${n} threw_error: ${g(o)}`,{err:o}),o}):($(`${n} output: ${g(a)}`,{res:a}),a)}catch(a){throw I(`${n} threw_error: ${g(a)}`,{err:a}),a}}}function g(r){try{return r!=null?JSON.stringify(r,null,2):r}catch(e){return Tt(r)}}function Tt(r){let e={};for(let t in r)Object.prototype.hasOwnProperty.call(r,t)&&typeof r[t]!="object"&&typeof r[t]!="function"&&(e[t]=r[t]);return JSON.stringify(e,null,2)}function $(r,e){if(z()){console.log(r);return}Q(r,e)}function $e(r){var t;let e=r instanceof Error?r:{message:"Unknown error",name:"Unknown error"};if(!(e instanceof Error)&&((t=e.constructor)==null?void 0:t.name)!=="SyntheticBaseEvent")throw I("ERROR_TO_JSON_FAILED",{error:e}),new Error("[errorToJSON] err is not instanceof Error nor SyntheticBaseEvent");return JSON.parse(JSON.stringify(e,Object.getOwnPropertyNames(e)))}var ee=require("viem");var Ke=[{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 Be({contract:r,config:e,from:t,to:n}){switch(e.token.type){case"ft":return{account:t,address:r,abi:ee.erc20Abi,functionName:"transfer",args:[n,e.amount]};case"sft":return{account:t,address:r,abi:Ke,functionName:"safeTransferFrom",args:[t.address,n,e.token.tokenId,e.quantity,"0x00"],tokenId:e.token.tokenId};case"nft":return{account:t,address:r,abi:ee.erc721Abi,functionName:"safeTransferFrom",args:[t.address,n,e.token.tokenId],tokenId:e.token.tokenId}}}var K=class extends w{constructor(t,n,a,o){super("EVMSmartWallet",{chain:o,address:n.account.address});this.crossmintService=t;this.accountClient=n;this.chain=o,this.client={wallet:n,public:a}}get address(){return this.accountClient.account.address}transferToken(t,n){return i(this,null,function*(){return this.logPerformance("TRANSFER",()=>i(this,null,function*(){if(this.chain!==n.token.chain)throw new Error(`Chain mismatch: Expected ${n.token.chain}, but got ${this.chain}. Ensure you are interacting with the correct blockchain.`);if(!(0,J.isAddress)(t))throw new Error(`Invalid recipient address: '${t}' is not a valid EVM address.`);if(!(0,J.isAddress)(n.token.contractAddress))throw new Error(`Invalid contract address: '${n.token.contractAddress}' is not a valid EVM address.`);let a=Be({contract:n.token.contractAddress,to:t,from:this.accountClient.account,config:n});try{let o=this.accountClient.extend(J.publicActions),{request:s}=yield o.simulateContract(a);return yield o.writeContract(s)}catch(o){I("[TRANSFER] - ERROR_TRANSFERRING_TOKEN",{service:P,error:$e(o),tokenId:a.tokenId,contractAddress:n.token.contractAddress,chain:n.token.chain});let s=a.tokenId==null?"":`:${a.tokenId}}`;throw new D(`Error transferring token ${n.token.contractAddress}${s}`)}}))})}nfts(){return i(this,null,function*(){return this.crossmintService.fetchNFTs(this.address,this.chain)})}};var C=require("viem/chains"),T=require("@crossmint/common-sdk-base");var Fe={BASE_SEPOLIA:T.BlockchainIncludingTestnet.BASE_SEPOLIA,POLYGON_AMOY:T.BlockchainIncludingTestnet.POLYGON_AMOY},fr=(0,T.objectValues)(Fe),Je={BASE:T.BlockchainIncludingTestnet.BASE,POLYGON:T.BlockchainIncludingTestnet.POLYGON},Sr=(0,T.objectValues)(Je),ge=c(c({},Fe),Je),Er=(0,T.objectValues)(ge),Pe={polygon:"5c9f4865-ca8e-44bb-9b9e-3810b2b46f9f","polygon-amoy":"3deef404-ca06-4a5d-9a58-907c99e7ef00","base-sepolia":"5a127978-6473-4784-9dfb-f74395b220a6",base:"e8b3020f-4dde-4176-8a7d-be8102527a5c"},te={polygon:C.polygon,"polygon-amoy":C.polygonAmoy,base:C.base,"base-sepolia":C.baseSepolia},he=r=>Ve+Pe[r];var it=require("viem"),lt=require("@crossmint/common-sdk-base");var Ye=require("@crossmint/common-sdk-base");var re=class{constructor(e={ERROR_JWT_INVALID:()=>new x,ERROR_JWT_DECRYPTION:()=>new k,ERROR_JWT_EXPIRED:({expiredAt:t})=>new v(new Date(t)),ERROR_JWT_IDENTIFIER:({identifierKey:t})=>new N(t),ERROR_USER_WALLET_ALREADY_CREATED:({userId:t})=>new A(t),ERROR_ADMIN_SIGNER_ALREADY_USED:()=>new M,ERROR_PROJECT_NONCUSTODIAL_WALLETS_NOT_ENABLED:()=>new U}){this.errors=e}throwErrorFromResponse(n){return i(this,arguments,function*({response:e,onServerErrorMessage:t}){if(!e.ok){if(e.status>=500)throw new f(t,e.status);if(e.status===402)throw new V;try{let a=yield e.json(),o=a.code;if(o!=null&&this.errors[o]!=null)throw this.errors[o](a);if(a.message!=null)throw new f(a.message,e.status)}catch(a){if(a instanceof p)throw a;console.error("Error parsing response",a)}throw new f(yield e.text(),e.status)}})}};var Y=class Y extends w{constructor(e){super("BaseCrossmintService");let t=(0,Ye.validateAPIKey)(e);if(!t.isValid)throw new Error("API key invalid");this.crossmintAPIHeaders={accept:"application/json","content-type":"application/json","x-api-key":e},this.crossmintBaseUrl=this.getUrlFromEnv(t.environment),this.apiErrorService=new re}fetchCrossmintAPI(o){return i(this,arguments,function*(e,t={method:"GET"},n,a){return _("FETCH_CROSSMINT_API",()=>i(this,null,function*(){let s=`${this.crossmintBaseUrl}/${e}`,{body:l,method:u}=t,m;try{m=yield fetch(s,{body:l,method:u,headers:c(c({},this.crossmintAPIHeaders),a!=null&&{Authorization:`Bearer ${a}`})})}catch(d){throw new f(`Error fetching Crossmint API: ${d}`)}return m.ok||(yield this.apiErrorService.throwErrorFromResponse({response:m,onServerErrorMessage:n})),yield m.json()}),{endpoint:e})})}getUrlFromEnv(e){let t=Y.urlMap[e];if(!t)throw console.log(" CrossmintService.urlMap: ",Y.urlMap),new Error(`URL not found for environment: ${e}`);return t}};Y.urlMap={development:ve,staging:xe,production:ke};var ne=Y;var ae=class extends ne{idempotentCreateSmartWallet(e,t){return i(this,null,function*(){return this.fetchCrossmintAPI(`${Se}/sdk/smart-wallet`,{method:"PUT",body:JSON.stringify(t)},"Error creating abstract wallet. Please contact support",e.jwt)})}getSmartWalletConfig(e,t){return i(this,null,function*(){return this.fetchCrossmintAPI(`${Se}/sdk/smart-wallet/config?chain=${t}`,{method:"GET"},"Error getting smart wallet version configuration. Please contact support",e.jwt)})}fetchNFTs(e,t){return i(this,null,function*(){return this.fetchCrossmintAPI(`v1-alpha1/wallets/${t}:${e}/nfts`,{method:"GET"},`Error fetching NFTs for wallet: ${e}`)})}getPasskeyServerUrl(){return this.crossmintBaseUrl+"/internal/passkeys"}};function oe(r){return!1}var Re=require("viem");var At=["sendTransaction","writeContract","sendUserOperation"],wt=["signMessage","signTypedData"];function Te(r){return At.includes(r)}function Ct(r){return wt.includes(r)}var se=class{constructor(e){this.errorProcessor=e}decorate({crossmintChain:e,smartAccountClient:t}){return new Proxy(t,{get:(n,a,o)=>{let s=Reflect.get(n,a,o);return typeof s!="function"||typeof a!="string"||!(Ct(a)||Te(a))?s:(...l)=>_(`CrossmintSmartWallet.${a}`,()=>this.execute(n,a,s,l,e))}})}execute(e,t,n,a,o){return i(this,null,function*(){try{Q(`[CrossmintSmartWallet.${t}] - params: ${(0,Re.stringify)(a)}`);let s=Te(t)?this.processTxnArgs(t,o,a):a;return yield n.call(e,...s)}catch(s){let l=Te(t)?"signing":"sending transaction";throw this.errorProcessor.map(s,new p(`Error ${l}: ${s.message}`,(0,Re.stringify)(s)))}})}processTxnArgs(e,t,n){if(e==="sendUserOperation"){let[{userOperation:o,middleware:s,account:l}]=n;return[{middleware:s,account:l,userOperation:this.addGelatoBundlerProperties(t,o)},...n.slice(1)]}let[a]=n;return[this.addGelatoBundlerProperties(t,a),...n.slice(1)]}addGelatoBundlerProperties(e,t){return oe(e)?E(c({},t),{maxFeePerGas:"0x0",maxPriorityFeePerGas:"0x0"}):t}};function ie(r){return{pubKeyX:r.pubKeyX,pubKeyY:r.pubKeyY,passkeyName:r.passkeyName,type:"passkeys"}}var ot=require("@zerodev/sdk"),me=require("permissionless"),W=require("viem"),st=require("@crossmint/common-sdk-base");var Ae=["0.3.1","0.3.0","0.2.4"];function je(r){return Ae.includes(r)}var we=["v0.6","v0.7"];function Ge(r){return we.includes(r)}var He=require("permissionless");var ze=Ue(e=>i(void 0,[e],function*({walletParams:r}){if(It(r.signer))return yield(0,He.providerToSmartAccountSigner)(r.signer);if(_t(r.signer))return r.signer.account;{let t=r.signer;throw new p(`The signer type ${t.type} is not supported`)}}),"createOwnerSigner");function It(r){return r&&typeof r.request=="function"}function _t(r){return r&&r.type==="VIEM_ACCOUNT"}var qe=require("@zerodev/ecdsa-validator"),Xe=require("@zerodev/sdk");var le=class{get(u,m){return i(this,arguments,function*({chain:e,publicClient:t,entryPoint:n,walletParams:a,kernelVersion:o,user:s},l){let d=yield ze({chain:e,walletParams:a});if(l!=null&&!q(d.address,l.eoaAddress))throw new h(`User '${s.id}' has an existing wallet with an eoa signer '${l.eoaAddress}', this does not match input eoa signer '${d.address}'.`,l,{type:"eoa",eoaAddress:l.eoaAddress});let S=yield(0,qe.signerToEcdsaValidator)(t,{signer:d,entryPoint:n.address,kernelVersion:o});return{account:yield(0,Xe.createKernelAccount)(t,{plugins:{sudo:S},index:BigInt(0),entryPoint:n.address,kernelVersion:o}),signerData:{eoaAddress:d.address,type:"eoa"}}})}};var B=require("@zerodev/passkey-validator"),Ze=require("@zerodev/sdk"),Qe=require("@zerodev/webauthn-key");function et(r){return r.walletParams.signer.type==="PASSKEY"}var pe=class{constructor(e){this.crossmintService=e}get(l,u){return i(this,arguments,function*({user:e,publicClient:t,walletParams:n,entryPoint:a,kernelVersion:o},s){var Ie;let m=(Ie=n.signer.passkeyName)!=null?Ie:e.id;if(s!=null&&s.passkeyName!==m)throw new b(`User '${e.id}' has an existing wallet created with a passkey named '${s.passkeyName}', this does match input passkey name '${m}'.`,ie(s));let d=yield this.getPasskey(e,m,s),S=B.PasskeyValidatorContractVersion.V0_0_2,F=s==null?S:s.validatorContractVersion,j=yield(0,B.toPasskeyValidator)(t,{webAuthnKey:d,entryPoint:a.address,validatorContractVersion:F,kernelVersion:o}),ct=yield(0,Ze.createKernelAccount)(t,{plugins:{sudo:j},entryPoint:a.address,kernelVersion:o});return{signerData:this.getSignerData(j,F,m),account:ct}})}getPasskey(e,t,n){return i(this,null,function*(){return n!=null?{pubX:BigInt(n.pubKeyX),pubY:BigInt(n.pubKeyY),authenticatorId:n.authenticatorId,authenticatorIdHash:n.authenticatorIdHash}:(0,Qe.toWebAuthnKey)({passkeyName:t,passkeyServerUrl:this.crossmintService.getPasskeyServerUrl(),mode:B.WebAuthnMode.Register,passkeyServerHeaders:this.createPasskeysServerHeaders(e)})})}getSignerData(e,t,n){return E(c({},Wt(e.getSerializedData())),{passkeyName:n,validatorContractVersion:t,domain:window.location.hostname,type:"passkeys"})}createPasskeysServerHeaders(e){return{"x-api-key":this.crossmintService.crossmintAPIHeaders["x-api-key"],Authorization:`Bearer ${e.jwt}`}}},Wt=r=>{let e=Ot(r),t=new TextDecoder().decode(e);return JSON.parse(t)};function Ot(r){let e=atob(r);return Uint8Array.from(e,t=>t.codePointAt(0))}var tt=require("@zerodev/sdk"),rt=require("viem");function nt(r){return!oe(r)}var Dt=r=>Le+Pe[r];function at({entryPoint:r,chain:e}){return{middleware:{sponsorUserOperation:n=>i(this,[n],function*({userOperation:t}){return(0,tt.createZeroDevPaymasterClient)({chain:te[e],transport:(0,rt.http)(Dt(e)),entryPoint:r}).sponsorUserOperation({userOperation:t,entryPoint:r})})}}}var ce=class{constructor(e,t,n=new Ce(new le,new pe(e))){this.crossmintWalletService=e;this.clientDecorator=t;this.accountFactory=n}getOrCreate(e,t,n){return i(this,null,function*(){let{entryPoint:a,kernelVersion:o,existingSignerConfig:s,smartContractWalletAddress:l,userId:u}=yield this.fetchConfig(e,t),m=(0,W.createPublicClient)({transport:(0,W.http)(he(t))}),{account:d,signerData:S}=yield this.accountFactory.get({chain:t,walletParams:n,publicClient:m,user:E(c({},e),{id:u}),entryPoint:a,kernelVersion:o},s);if(l!=null&&!q(l,d.address))throw new A(u);s==null&&(yield this.crossmintWalletService.idempotentCreateSmartWallet(e,{type:De,smartContractWalletAddress:d.address,signerData:S,version:0,baseLayer:"evm",chainId:(0,st.blockchainToChainId)(t),entryPointVersion:a.version,kernelVersion:o}));let F=(0,ot.createKernelAccountClient)(c({account:d,chain:te[t],entryPoint:d.entryPoint,bundlerTransport:(0,W.http)(he(t))},nt(t)&&at({entryPoint:d.entryPoint,chain:t}))),j=this.clientDecorator.decorate({crossmintChain:t,smartAccountClient:F});return new K(this.crossmintWalletService,j,m,t)})}fetchConfig(e,t){return i(this,null,function*(){let{entryPointVersion:n,kernelVersion:a,signers:o,smartContractWalletAddress:s,userId:l}=yield this.crossmintWalletService.getSmartWalletConfig(e,t);if(!je(a))throw new p(`Unsupported kernel version. Supported versions: ${Ae.join(", ")}. Version used: ${a}, Please contact support`);if(!Ge(n))throw new p(`Unsupported entry point version. Supported versions: ${we.join(", ")}. Version used: ${n}. Please contact support`);if(n==="v0.7"&&a.startsWith("0.2")||n==="v0.6"&&a.startsWith("0.3"))throw new p(`Unsupported combination: entryPoint ${n} and kernel version ${a}. Please contact support`);return{entryPoint:{version:n,address:n==="v0.6"?me.ENTRYPOINT_ADDRESS_V06:me.ENTRYPOINT_ADDRESS_V07},kernelVersion:a,userId:l,existingSignerConfig:this.getSigner(o),smartContractWalletAddress:s!=null?(0,W.getAddress)(s):void 0}})}getSigner(e){if(e.length!==0){if(e.length>1)throw new f("Invalid wallet signer configuration. Please contact support");return e[0].signerData}}},Ce=class{constructor(e,t){this.eoa=e;this.passkey=t}get(e,t){if(et(e)){if(t!=null&&(t==null?void 0:t.type)!=="passkeys")throw new h(`Cannot create wallet with passkey signer for user '${e.user.id}', they have an existing wallet with eoa signer '${t.eoaAddress}.'`,t);return this.passkey.get(e,t)}if(t!=null&&(t==null?void 0:t.type)!=="eoa")throw new h(`Cannot create wallet with eoa signer for user '${e.user.id}', they already have a wallet with a passkey named '${t.passkeyName}' as it's signer.`,ie(t));return this.eoa.get(e,t)}};var ue=require("viem");var de=class{constructor(e){this.logger=e}map(e,t){return this.record(e),e instanceof p||e instanceof ue.BaseError?e:t}record(e){let t=e instanceof Error?e.message:String(e);this.logger.logError(`Smart Wallet SDK Error: ${t}`,{stack:e instanceof Error?e.stack:void 0,name:e instanceof Error?e.name:"UnknownError",details:(0,ue.stringify)(e),domain:window.location.hostname,sdk_version:Ne})}};var ye=class r extends w{constructor(t,n){super("SmartWalletSDK");this.smartWalletService=t;this.errorProcessor=n}static init({clientApiKey:t}){if(!H())throw new p("Smart Wallet SDK should only be used client side.");if(!(0,lt.validateAPIKey)(t).isValid)throw new Error("API key invalid");let a=new ae(t),o=new de(new O);return new r(new ce(a,new se(o)),o)}getOrCreateWallet(o,s){return i(this,arguments,function*(t,n,a={signer:{type:"PASSKEY"}}){return _("GET_OR_CREATE_WALLET",()=>i(this,null,function*(){try{return yield this.smartWalletService.getOrCreate(t,n,a)}catch(l){throw this.errorProcessor.map(l,new p(`Wallet creation failed: ${l.message}.`,(0,it.stringify)(l)))}}),{user:t,chain:n})})}};0&&(module.exports={AdminAlreadyUsedError,AdminMismatchError,ConfigError,CrossmintServiceError,EVMSmartWallet,JWTDecryptionError,JWTExpiredError,JWTIdentifierError,JWTInvalidError,NonCustodialWalletsNotEnabledError,NotAuthorizedError,OutOfCreditsError,PasskeyMismatchError,SmartWalletChain,SmartWalletSDK,SmartWalletSDKError,TransferError,UserWalletAlreadyCreatedError,blockchainToChainId});
|
|
1
|
+
"use strict";var q=Object.defineProperty,ue=Object.defineProperties,ye=Object.getOwnPropertyDescriptor,fe=Object.getOwnPropertyDescriptors,Ee=Object.getOwnPropertyNames,bt=Object.getOwnPropertySymbols;var vt=Object.prototype.hasOwnProperty,Se=Object.prototype.propertyIsEnumerable;var Dt=(r,t,e)=>t in r?q(r,t,{enumerable:!0,configurable:!0,writable:!0,value:e}):r[t]=e,d=(r,t)=>{for(var e in t||(t={}))vt.call(t,e)&&Dt(r,e,t[e]);if(bt)for(var e of bt(t))Se.call(t,e)&&Dt(r,e,t[e]);return r},S=(r,t)=>ue(r,fe(t));var ge=(r,t)=>{for(var e in t)q(r,e,{get:t[e],enumerable:!0})},Pe=(r,t,e,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let a of Ee(t))!vt.call(r,a)&&a!==e&&q(r,a,{get:()=>t[a],enumerable:!(n=ye(t,a))||n.enumerable});return r};var he=r=>Pe(q({},"__esModule",{value:!0}),r);var i=(r,t,e)=>new Promise((n,a)=>{var o=u=>{try{l(e.next(u))}catch(p){a(p)}},s=u=>{try{l(e.throw(u))}catch(p){a(p)}},l=u=>u.done?n(u.value):Promise.resolve(u.value).then(o,s);l((e=e.apply(r,t)).next())});var Me={};ge(Me,{AdminAlreadyUsedError:()=>$,AdminMismatchError:()=>h,Chain:()=>gt.EVMBlockchainIncludingTestnet,ConfigError:()=>K,CrossmintServiceError:()=>E,EVMSmartWallet:()=>F,JWTDecryptionError:()=>k,JWTExpiredError:()=>v,JWTIdentifierError:()=>N,JWTInvalidError:()=>x,NonCustodialWalletsNotEnabledError:()=>B,NotAuthorizedError:()=>T,OutOfCreditsError:()=>U,PasskeyIncompatibleAuthenticatorError:()=>L,PasskeyMismatchError:()=>D,PasskeyPromptError:()=>V,PasskeyRegistrationError:()=>M,SmartWalletSDK:()=>St,SmartWalletSDKError:()=>c,TransferError:()=>b,UserWalletAlreadyCreatedError:()=>A,blockchainToChainId:()=>gt.blockchainToChainId});module.exports=he(Me);var gt=require("@crossmint/common-sdk-base");function X(){return typeof window!="undefined"}function Z(){return process.env.NODE_ENV==="test"?!1:window.location.origin.includes("localhost")}function Q(r,t){return(r==null?void 0:r.toLowerCase())===(t==null?void 0:t.toLowerCase())}var Pt=!1,tt=class{logInfo(t,e){Pt&&console.log(t,e)}logError(t,e){Pt&&console.error(t,e)}logWarn(t,e){Pt&&console.warn(t,e)}};var xt="ZeroDev";var kt="pub035be8a594b35be1887b6ba76c4029ca",Nt="http://localhost:3000/api",Vt="https://staging.crossmint.com/api",Mt="https://www.crossmint.com/api",P="SCW_SDK",Lt="0.1.0",ht="2024-06-09",Ut="https://rpc.zerodev.app/api/v2/bundler/",Kt="https://rpc.zerodev.app/api/v2/paymaster/";var et=require("@datadog/browser-logs");var W=class{logInfo(t,e){Rt(t,"info",e)}logError(t,e){Rt(t,"error",e)}logWarn(t,e){Rt(t,"warn",e)}};function Rt(r,t,e){let n=e?S(d({},e),{service:P}):{service:P};Re(),et.datadogLogs.logger[t](r,n)}function Re(){et.datadogLogs.getInternalContext()==null&&et.datadogLogs.init({clientToken:kt,site:"datadoghq.com",forwardErrorsToLogs:!1,sampleRate:100})}function Te(){return X()&&Z()?new tt:new W}var{logInfo:rt,logWarn:qe,logError:C}=Te();var G=require("viem");var y={NOT_AUTHORIZED:"smart-wallet:not-authorized",TRANSFER:"smart-wallet:transfer.error",CROSSMINT_SERVICE:"smart-wallet:crossmint-service.error",ERROR_JWT_EXPIRED:"smart-wallet:not-authorized.jwt-expired",ERROR_JWT_INVALID:"smart-wallet:not-authorized.jwt-invalid",ERROR_JWT_DECRYPTION:"smart-wallet:not-authorized.jwt-decryption",ERROR_JWT_IDENTIFIER:"smart-wallet:not-authorized.jwt-identifier",ERROR_USER_WALLET_ALREADY_CREATED:"smart-wallet:user-wallet-already-created.error",ERROR_OUT_OF_CREDITS:"smart-wallet:out-of-credits.error",ERROR_WALLET_CONFIG:"smart-wallet:wallet-config.error",ERROR_ADMIN_MISMATCH:"smart-wallet:wallet-config.admin-mismatch",ERROR_PASSKEY_MISMATCH:"smart-wallet:wallet-config.passkey-mismatch",ERROR_PASSKEY_PROMPT:"smart-wallet:passkey.prompt",ERROR_PASSKEY_INCOMPATIBLE_AUTHENTICATOR:"smart-wallet.passkey.incompatible-authenticator",ERROR_PASSKEY_REGISTRATION:"smart-wallet:passkey.registration",ERROR_ADMIN_SIGNER_ALREADY_USED:"smart-wallet:wallet-config.admin-signer-already-used",ERROR_PROJECT_NONCUSTODIAL_WALLETS_NOT_ENABLED:"smart-wallet:wallet-config.non-custodial-wallets-not-enabled",UNCATEGORIZED:"smart-wallet:uncategorized"},c=class extends Error{constructor(t,e,n=y.UNCATEGORIZED){super(t),this.details=e,this.code=n}},b=class extends c{constructor(t){super(t,void 0,y.TRANSFER)}},E=class extends c{constructor(t,e){super(t,void 0,y.CROSSMINT_SERVICE),this.status=e}},h=class extends c{constructor(t,e,n){super(t,y.ERROR_ADMIN_MISMATCH),this.required=e,this.used=n}},D=class extends c{constructor(t,e,n){super(t,y.ERROR_PASSKEY_MISMATCH),this.required=e,this.used=n}},T=class extends c{constructor(t){super(t,void 0,y.NOT_AUTHORIZED)}},v=class extends T{constructor(e){super(`JWT provided expired at timestamp ${e}`);this.code=y.ERROR_JWT_EXPIRED;this.expiredAt=e.toISOString()}},x=class extends T{constructor(){super("Invalid JWT provided");this.code=y.ERROR_JWT_INVALID}},k=class extends T{constructor(){super("Error decrypting JWT");this.code=y.ERROR_JWT_DECRYPTION}},N=class extends T{constructor(e){super(`Missing required identifier '${e}' in the JWT`);this.code=y.ERROR_JWT_IDENTIFIER;this.identifierKey=e}},A=class extends c{constructor(e){super(`The user with userId ${e.toString()} already has a wallet created for this project`);this.code=y.ERROR_USER_WALLET_ALREADY_CREATED}},V=class extends c{constructor(t){super(`Prompt was either cancelled or timed out for passkey ${t}`,void 0,y.ERROR_PASSKEY_PROMPT),this.passkeyName=t}},M=class extends c{constructor(t){super(`Registration for passkey ${t} failed, either the registration took too long, or passkey signature vaildation failed.`,void 0,y.ERROR_PASSKEY_REGISTRATION),this.passkeyName=t}},L=class extends c{constructor(t){super(`User selected authenticator for passkey ${t} is not compatible with Crossmint's Smart Wallets.`,void 0,y.ERROR_PASSKEY_INCOMPATIBLE_AUTHENTICATOR),this.passkeyName=t}},U=class extends c{constructor(t){super("You've run out of Crossmint API credits. Visit https://docs.crossmint.com/docs/errors for more information",void 0,y.ERROR_OUT_OF_CREDITS)}},K=class extends c{constructor(t){super(t,void 0,y.ERROR_WALLET_CONFIG)}},$=class extends K{constructor(){super("This signer was already used to create another wallet. Please use a different signer.");this.code=y.ERROR_ADMIN_SIGNER_ALREADY_USED}},B=class extends K{constructor(){super("Non-custodial wallets are not enabled for this project");this.code=y.ERROR_PROJECT_NONCUSTODIAL_WALLETS_NOT_ENABLED}};var $t=require("uuid");var w=class{constructor(t,e={},n=(0,$t.v4)()){this.extraInfo=e;this.logIdempotencyKey=n;return new Proxy(this,{get:(a,o,s)=>{let l=a[o],u=`[${P} - ${t} - ${String(o)}]`;return typeof l=="function"?(...p)=>{this.logInput(p,u);let m=l.apply(a,p);return m instanceof Promise?m.then(f=>(this.logOutput(f,u),f)).catch(f=>{throw this.logError(f,u),f}):(this.logOutput(m,u),m)}:Reflect.get(a,o,s)}})}logInput(t,e){Y(`${e} input - ${g(t)} - extra_info - ${g(this.extraInfo)} - log_idempotency_key - ${this.logIdempotencyKey}`,S(d({args:t},this.extraInfo),{logIdempotencyKey:this.logIdempotencyKey}))}logOutput(t,e){Y(`${e} output - ${g(t)} - extra_info - ${g(this.extraInfo)} - log_idempotency_key - ${this.logIdempotencyKey}`,S(d({res:t},this.extraInfo),{logIdempotencyKey:this.logIdempotencyKey}))}logError(t,e){C(`${e} threw_error - ${t} - extra_info - ${g(this.extraInfo)} - log_idempotency_key - ${this.logIdempotencyKey}`,d({err:t},this.extraInfo))}logPerformance(t,e){return _(t,e,this.extraInfo)}};function _(r,t,e){return i(this,null,function*(){let n=new Date().getTime(),a=yield t(),o=new Date().getTime()-n,s=d({durationInMs:o},e);return Y(`[${P} - ${r} - TIME] - ${g(s)}`,{args:s}),a})}function Bt(r,t){return function(...e){let n=`[${P} - function: ${t}]`;Y(`${n} input: ${g(e)}`,{args:e});try{let a=r.apply(this,e);return a instanceof Promise?a.then(o=>(Y(`${n} output: ${g(o)}`,{res:o}),o)).catch(o=>{throw C(`${n} threw_error: ${g(o)}`,{err:o}),o}):(Y(`${n} output: ${g(a)}`,{res:a}),a)}catch(a){throw C(`${n} threw_error: ${g(a)}`,{err:a}),a}}}function g(r){try{return r!=null?JSON.stringify(r,null,2):r}catch(t){return Ae(r)}}function Ae(r){let t={};for(let e in r)Object.prototype.hasOwnProperty.call(r,e)&&typeof r[e]!="object"&&typeof r[e]!="function"&&(t[e]=r[e]);return JSON.stringify(t,null,2)}function Y(r,t){if(Z()){console.log(r);return}rt(r,t)}function Yt(r){var e;let t=r instanceof Error?r:{message:"Unknown error",name:"Unknown error"};if(!(t instanceof Error)&&((e=t.constructor)==null?void 0:e.name)!=="SyntheticBaseEvent")throw C("ERROR_TO_JSON_FAILED",{error:t}),new Error("[errorToJSON] err is not instanceof Error nor SyntheticBaseEvent");return JSON.parse(JSON.stringify(t,Object.getOwnPropertyNames(t)))}var nt=require("viem");var Ft=[{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 Jt({contract:r,config:t,from:e,to:n}){switch(t.token.type){case"ft":return{account:e,address:r,abi:nt.erc20Abi,functionName:"transfer",args:[n,t.amount]};case"sft":return{account:e,address:r,abi:Ft,functionName:"safeTransferFrom",args:[e.address,n,t.token.tokenId,t.quantity,"0x00"],tokenId:t.token.tokenId};case"nft":return{account:e,address:r,abi:nt.erc721Abi,functionName:"safeTransferFrom",args:[e.address,n,t.token.tokenId],tokenId:t.token.tokenId}}}var F=class extends w{constructor(e,n,a,o){super("EVMSmartWallet",{chain:o,address:n.account.address});this.crossmintService=e;this.accountClient=n;this.chain=o,this.client={wallet:n,public:a}}get address(){return this.accountClient.account.address}transferToken(e,n){return i(this,null,function*(){return this.logPerformance("TRANSFER",()=>i(this,null,function*(){if(this.chain!==n.token.chain)throw new Error(`Chain mismatch: Expected ${n.token.chain}, but got ${this.chain}. Ensure you are interacting with the correct blockchain.`);if(!(0,G.isAddress)(e))throw new Error(`Invalid recipient address: '${e}' is not a valid EVM address.`);if(!(0,G.isAddress)(n.token.contractAddress))throw new Error(`Invalid contract address: '${n.token.contractAddress}' is not a valid EVM address.`);let a=Jt({contract:n.token.contractAddress,to:e,from:this.accountClient.account,config:n});try{let o=this.accountClient.extend(G.publicActions),{request:s}=yield o.simulateContract(a);return yield o.writeContract(s)}catch(o){C("[TRANSFER] - ERROR_TRANSFERRING_TOKEN",{service:P,error:Yt(o),tokenId:a.tokenId,contractAddress:n.token.contractAddress,chain:n.token.chain});let s=a.tokenId==null?"":`:${a.tokenId}}`;throw new b(`Error transferring token ${n.token.contractAddress}${s}`)}}))})}nfts(){return i(this,null,function*(){return this.crossmintService.fetchNFTs(this.address,this.chain)})}};var pe=require("viem"),me=require("@crossmint/common-sdk-base");var Gt=require("@crossmint/common-sdk-base");var at=class{constructor(t={ERROR_JWT_INVALID:()=>new x,ERROR_JWT_DECRYPTION:()=>new k,ERROR_JWT_EXPIRED:({expiredAt:e})=>new v(new Date(e)),ERROR_JWT_IDENTIFIER:({identifierKey:e})=>new N(e),ERROR_USER_WALLET_ALREADY_CREATED:({userId:e})=>new A(e),ERROR_ADMIN_SIGNER_ALREADY_USED:()=>new $,ERROR_PROJECT_NONCUSTODIAL_WALLETS_NOT_ENABLED:()=>new B}){this.errors=t}throwErrorFromResponse(n){return i(this,arguments,function*({response:t,onServerErrorMessage:e}){if(!t.ok){if(t.status>=500)throw new E(e,t.status);if(t.status===402)throw new U;try{let a=yield t.json(),o=a.code;if(o!=null&&this.errors[o]!=null)throw this.errors[o](a);if(a.message!=null)throw new E(a.message,t.status)}catch(a){if(a instanceof c)throw a;console.error("Error parsing response",a)}throw new E(yield t.text(),t.status)}})}};var H=class H extends w{constructor(t){super("BaseCrossmintService");let e=(0,Gt.validateAPIKey)(t);if(!e.isValid)throw new Error("API key invalid");this.crossmintAPIHeaders={accept:"application/json","content-type":"application/json","x-api-key":t},this.crossmintBaseUrl=this.getUrlFromEnv(e.environment),this.apiErrorService=new at}fetchCrossmintAPI(o){return i(this,arguments,function*(t,e={method:"GET"},n,a){return _("FETCH_CROSSMINT_API",()=>i(this,null,function*(){let s=`${this.crossmintBaseUrl}/${t}`,{body:l,method:u}=e,p;try{p=yield fetch(s,{body:l,method:u,headers:d(d({},this.crossmintAPIHeaders),a!=null&&{Authorization:`Bearer ${a}`})})}catch(m){throw new E(`Error fetching Crossmint API: ${m}`)}return p.ok||(yield this.apiErrorService.throwErrorFromResponse({response:p,onServerErrorMessage:n})),yield p.json()}),{endpoint:t})})}getUrlFromEnv(t){let e=H.urlMap[t];if(!e)throw console.log(" CrossmintService.urlMap: ",H.urlMap),new Error(`URL not found for environment: ${t}`);return e}};H.urlMap={development:Nt,staging:Vt,production:Mt};var ot=H;var st=class extends ot{idempotentCreateSmartWallet(t,e){return i(this,null,function*(){return this.fetchCrossmintAPI(`${ht}/sdk/smart-wallet`,{method:"PUT",body:JSON.stringify(e)},"Error creating abstract wallet. Please contact support",t.jwt)})}getSmartWalletConfig(t,e){return i(this,null,function*(){return this.fetchCrossmintAPI(`${ht}/sdk/smart-wallet/config?chain=${e}`,{method:"GET"},"Error getting smart wallet version configuration. Please contact support",t.jwt)})}fetchNFTs(t,e){return i(this,null,function*(){return this.fetchCrossmintAPI(`v1-alpha1/wallets/${e}:${t}/nfts`,{method:"GET"},`Error fetching NFTs for wallet: ${t}`)})}getPasskeyServerUrl(){return this.crossmintBaseUrl+"/internal/passkeys"}};function it(r){return!1}var At=require("viem");var Ie=["sendTransaction","writeContract","sendUserOperation"],Ce=["signMessage","signTypedData"];function Tt(r){return Ie.includes(r)}function _e(r){return Ce.includes(r)}var lt=class{constructor(t){this.errorProcessor=t}decorate({crossmintChain:t,smartAccountClient:e}){return new Proxy(e,{get:(n,a,o)=>{let s=Reflect.get(n,a,o);return typeof s!="function"||typeof a!="string"||!(_e(a)||Tt(a))?s:(...l)=>_(`CrossmintSmartWallet.${a}`,()=>this.execute(n,a,s,l,t))}})}execute(t,e,n,a,o){return i(this,null,function*(){try{rt(`[CrossmintSmartWallet.${e}] - params: ${(0,At.stringify)(a)}`);let s=Tt(e)?this.processTxnArgs(e,o,a):a;return yield n.call(t,...s)}catch(s){let l=Tt(e)?"signing":"sending transaction";throw this.errorProcessor.map(s,new c(`Error ${l}: ${s.message}`,(0,At.stringify)(s)))}})}processTxnArgs(t,e,n){if(t==="sendUserOperation"){let[{userOperation:o,middleware:s,account:l}]=n;return[{middleware:s,account:l,userOperation:this.addGelatoBundlerProperties(e,o)},...n.slice(1)]}let[a]=n;return[this.addGelatoBundlerProperties(e,a),...n.slice(1)]}addGelatoBundlerProperties(t,e){return it(t)?S(d({},e),{maxFeePerGas:"0x0",maxPriorityFeePerGas:"0x0"}):e}};function ct(r){return{pubKeyX:r.pubKeyX,pubKeyY:r.pubKeyY,passkeyName:r.passkeyName,type:"passkeys"}}var le=require("@zerodev/sdk"),yt=require("permissionless"),O=require("viem"),ce=require("@crossmint/common-sdk-base");var wt=["0.3.1","0.3.0","0.2.4"];function Ht(r){return wt.includes(r)}var It=["v0.6","v0.7"];function jt(r){return It.includes(r)}var I=require("viem/chains"),R=require("@crossmint/common-sdk-base");var zt={BASE_SEPOLIA:R.BlockchainIncludingTestnet.BASE_SEPOLIA,POLYGON_AMOY:R.BlockchainIncludingTestnet.POLYGON_AMOY},Br=(0,R.objectValues)(zt),qt={BASE:R.BlockchainIncludingTestnet.BASE,POLYGON:R.BlockchainIncludingTestnet.POLYGON},Yr=(0,R.objectValues)(qt),Oe=d(d({},zt),qt),Fr=(0,R.objectValues)(Oe),Ct={polygon:"5c9f4865-ca8e-44bb-9b9e-3810b2b46f9f","polygon-amoy":"3deef404-ca06-4a5d-9a58-907c99e7ef00","base-sepolia":"5a127978-6473-4784-9dfb-f74395b220a6",base:"e8b3020f-4dde-4176-8a7d-be8102527a5c"},pt={polygon:I.polygon,"polygon-amoy":I.polygonAmoy,base:I.base,"base-sepolia":I.baseSepolia},_t=r=>Ut+Ct[r];var Xt=require("permissionless");var Zt=Bt(t=>i(void 0,[t],function*({walletParams:r}){if(We(r.signer))return yield(0,Xt.providerToSmartAccountSigner)(r.signer);if(be(r.signer))return r.signer.account;{let e=r.signer;throw new c(`The signer type ${e.type} is not supported`)}}),"createOwnerSigner");function We(r){return r&&typeof r.request=="function"}function be(r){return r&&r.type==="VIEM_ACCOUNT"}var Qt=require("@zerodev/ecdsa-validator"),te=require("@zerodev/sdk");var mt=class{get(u,p){return i(this,arguments,function*({chain:t,publicClient:e,entryPoint:n,walletParams:a,kernelVersion:o,user:s},l){let m=yield Zt({chain:t,walletParams:a});if(l!=null&&!Q(m.address,l.eoaAddress))throw new h(`User '${s.id}' has an existing wallet with an eoa signer '${l.eoaAddress}', this does not match input eoa signer '${m.address}'.`,l,{type:"eoa",eoaAddress:l.eoaAddress});let f=yield(0,Qt.signerToEcdsaValidator)(e,{signer:m,entryPoint:n.address,kernelVersion:o});return{account:yield(0,te.createKernelAccount)(e,{plugins:{sudo:f},index:BigInt(0),entryPoint:n.address,kernelVersion:o}),signerData:{eoaAddress:m.address,type:"eoa"}}})}};var J=require("@zerodev/passkey-validator"),ee=require("@zerodev/sdk"),re=require("@zerodev/webauthn-key");function ne(r){return r.walletParams.signer.type==="PASSKEY"}var dt=class{constructor(t){this.crossmintService=t}get(l,u){return i(this,arguments,function*({user:t,publicClient:e,walletParams:n,entryPoint:a,kernelVersion:o},s){var m;let p=(m=n.signer.passkeyName)!=null?m:t.id;if(s!=null&&s.passkeyName!==p)throw new D(`User '${t.id}' has an existing wallet created with a passkey named '${s.passkeyName}', this does match input passkey name '${p}'.`,ct(s));try{let f=yield this.getPasskey(t,p,s),j=J.PasskeyValidatorContractVersion.V0_0_2,z=s==null?j:s.validatorContractVersion,Wt=yield(0,J.toPasskeyValidator)(e,{webAuthnKey:f,entryPoint:a.address,validatorContractVersion:z,kernelVersion:o}),de=yield(0,ee.createKernelAccount)(e,{plugins:{sudo:Wt},entryPoint:a.address,kernelVersion:o});return{signerData:this.getSignerData(Wt,z,p),account:this.decorate(de,p)}}catch(f){throw this.mapError(f,p)}})}getPasskey(t,e,n){return i(this,null,function*(){return n!=null?{pubX:BigInt(n.pubKeyX),pubY:BigInt(n.pubKeyY),authenticatorId:n.authenticatorId,authenticatorIdHash:n.authenticatorIdHash}:(0,re.toWebAuthnKey)({passkeyName:e,passkeyServerUrl:this.crossmintService.getPasskeyServerUrl(),mode:J.WebAuthnMode.Register,passkeyServerHeaders:this.createPasskeysServerHeaders(t)})})}getSignerData(t,e,n){return S(d({},xe(t.getSerializedData())),{passkeyName:n,validatorContractVersion:e,domain:window.location.hostname,type:"passkeys"})}createPasskeysServerHeaders(t){return{"x-api-key":this.crossmintService.crossmintAPIHeaders["x-api-key"],Authorization:`Bearer ${t.jwt}`}}mapError(t,e){return t.code===0&&t.name==="DataError"?new L(e):t.message==="Registration not verified"?new M(e):t.code==="ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY"&&t.name==="NotAllowedError"?new V(e):t}decorate(t,e){return new Proxy(t,{get:(n,a,o)=>{let s=Reflect.get(n,a,o);return typeof s!="function"||typeof a!="string"||!ve(a)?s:(...l)=>i(this,null,function*(){try{return yield s.call(n,...l)}catch(u){throw this.mapError(u,e)}})}})}},De=["signMessage","signTypedData","signUserOperation","signTransaction"];function ve(r){return De.includes(r)}var xe=r=>{let t=ke(r),e=new TextDecoder().decode(t);return JSON.parse(e)};function ke(r){let t=atob(r);return Uint8Array.from(t,e=>e.codePointAt(0))}var ae=require("@zerodev/sdk"),oe=require("viem");function se(r){return!it(r)}var Ne=r=>Kt+Ct[r];function ie({entryPoint:r,chain:t}){return{middleware:{sponsorUserOperation:n=>i(this,[n],function*({userOperation:e}){return(0,ae.createZeroDevPaymasterClient)({chain:pt[t],transport:(0,oe.http)(Ne(t)),entryPoint:r}).sponsorUserOperation({userOperation:e,entryPoint:r})})}}}var ut=class{constructor(t,e,n=new Ot(new mt,new dt(t))){this.crossmintWalletService=t;this.clientDecorator=e;this.accountFactory=n}getOrCreate(t,e,n){return i(this,null,function*(){let{entryPoint:a,kernelVersion:o,existingSignerConfig:s,smartContractWalletAddress:l,userId:u}=yield this.fetchConfig(t,e),p=(0,O.createPublicClient)({transport:(0,O.http)(_t(e))}),{account:m,signerData:f}=yield this.accountFactory.get({chain:e,walletParams:n,publicClient:p,user:S(d({},t),{id:u}),entryPoint:a,kernelVersion:o},s);if(l!=null&&!Q(l,m.address))throw new A(u);s==null&&(yield this.crossmintWalletService.idempotentCreateSmartWallet(t,{type:xt,smartContractWalletAddress:m.address,signerData:f,version:0,baseLayer:"evm",chainId:(0,ce.blockchainToChainId)(e),entryPointVersion:a.version,kernelVersion:o}));let j=(0,le.createKernelAccountClient)(d({account:m,chain:pt[e],entryPoint:m.entryPoint,bundlerTransport:(0,O.http)(_t(e))},se(e)&&ie({entryPoint:m.entryPoint,chain:e}))),z=this.clientDecorator.decorate({crossmintChain:e,smartAccountClient:j});return new F(this.crossmintWalletService,z,p,e)})}fetchConfig(t,e){return i(this,null,function*(){let{entryPointVersion:n,kernelVersion:a,signers:o,smartContractWalletAddress:s,userId:l}=yield this.crossmintWalletService.getSmartWalletConfig(t,e);if(!Ht(a))throw new c(`Unsupported kernel version. Supported versions: ${wt.join(", ")}. Version used: ${a}, Please contact support`);if(!jt(n))throw new c(`Unsupported entry point version. Supported versions: ${It.join(", ")}. Version used: ${n}. Please contact support`);if(n==="v0.7"&&a.startsWith("0.2")||n==="v0.6"&&a.startsWith("0.3"))throw new c(`Unsupported combination: entryPoint ${n} and kernel version ${a}. Please contact support`);return{entryPoint:{version:n,address:n==="v0.6"?yt.ENTRYPOINT_ADDRESS_V06:yt.ENTRYPOINT_ADDRESS_V07},kernelVersion:a,userId:l,existingSignerConfig:this.getSigner(o),smartContractWalletAddress:s!=null?(0,O.getAddress)(s):void 0}})}getSigner(t){if(t.length!==0){if(t.length>1)throw new E("Invalid wallet signer configuration. Please contact support");return t[0].signerData}}},Ot=class{constructor(t,e){this.eoa=t;this.passkey=e}get(t,e){if(ne(t)){if(e!=null&&(e==null?void 0:e.type)!=="passkeys")throw new h(`Cannot create wallet with passkey signer for user '${t.user.id}', they have an existing wallet with eoa signer '${e.eoaAddress}.'`,e);return this.passkey.get(t,e)}if(e!=null&&(e==null?void 0:e.type)!=="eoa")throw new h(`Cannot create wallet with eoa signer for user '${t.user.id}', they already have a wallet with a passkey named '${e.passkeyName}' as it's signer.`,ct(e));return this.eoa.get(t,e)}};var Et=require("viem");var ft=class{constructor(t){this.logger=t}map(t,e){return this.record(t),t instanceof c||t instanceof Et.BaseError?t:e}record(t){let e=t instanceof Error?t.message:String(t);this.logger.logError(`Smart Wallet SDK Error: ${e}`,{stack:t instanceof Error?t.stack:void 0,name:t instanceof Error?t.name:"UnknownError",details:(0,Et.stringify)(t),domain:window.location.hostname,sdk_version:Lt})}};var St=class r extends w{constructor(e,n){super("SmartWalletSDK");this.smartWalletService=e;this.errorProcessor=n}static init({clientApiKey:e}){if(!X())throw new c("Smart Wallet SDK should only be used client side.");if(!(0,me.validateAPIKey)(e).isValid)throw new Error("API key invalid");let a=new st(e),o=new ft(new W);return new r(new ut(a,new lt(o)),o)}getOrCreateWallet(o,s){return i(this,arguments,function*(e,n,a={signer:{type:"PASSKEY"}}){return _("GET_OR_CREATE_WALLET",()=>i(this,null,function*(){try{return yield this.smartWalletService.getOrCreate(e,n,a)}catch(l){throw this.errorProcessor.map(l,new c(`Wallet creation failed: ${l.message}.`,(0,pe.stringify)(l)))}}),{user:e,chain:n})})}};0&&(module.exports={AdminAlreadyUsedError,AdminMismatchError,Chain,ConfigError,CrossmintServiceError,EVMSmartWallet,JWTDecryptionError,JWTExpiredError,JWTIdentifierError,JWTInvalidError,NonCustodialWalletsNotEnabledError,NotAuthorizedError,OutOfCreditsError,PasskeyIncompatibleAuthenticatorError,PasskeyMismatchError,PasskeyPromptError,PasskeyRegistrationError,SmartWalletSDK,SmartWalletSDKError,TransferError,UserWalletAlreadyCreatedError,blockchainToChainId});
|
|
2
2
|
//# sourceMappingURL=index.cjs.map
|