@crossmint/client-sdk-smart-wallet 0.1.0
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/LICENSE +201 -0
- package/dist/index.cjs +2 -0
- package/dist/index.cjs.map +1 -0
- package/dist/index.d.cts +289 -0
- package/dist/index.d.ts +289 -0
- package/dist/index.js +2 -0
- package/dist/index.js.map +1 -0
- package/package.json +46 -0
- package/src/ABI/ERC1155.json +325 -0
- package/src/ABI/ERC20.json +222 -0
- package/src/ABI/ERC721.json +320 -0
- package/src/SmartWalletSDK.test.ts +32 -0
- package/src/SmartWalletSDK.ts +75 -0
- package/src/api/APIErrorService.ts +72 -0
- package/src/api/BaseCrossmintService.ts +82 -0
- package/src/api/CrossmintWalletService.test.ts +42 -0
- package/src/api/CrossmintWalletService.ts +50 -0
- package/src/blockchain/BlockchainNetworks.ts +121 -0
- package/src/blockchain/token/index.ts +1 -0
- package/src/blockchain/transfer.ts +54 -0
- package/src/blockchain/wallets/EVMSmartWallet.ts +109 -0
- package/src/blockchain/wallets/clientDecorator.ts +127 -0
- package/src/blockchain/wallets/eoa.ts +49 -0
- package/src/blockchain/wallets/index.ts +1 -0
- package/src/blockchain/wallets/passkey.ts +117 -0
- package/src/blockchain/wallets/paymaster.ts +49 -0
- package/src/blockchain/wallets/service.ts +193 -0
- package/src/error/index.ts +148 -0
- package/src/error/processor.ts +36 -0
- package/src/index.ts +34 -0
- package/src/services/logging/BrowserLoggerInterface.ts +5 -0
- package/src/services/logging/ConsoleProvider.ts +24 -0
- package/src/services/logging/DatadogProvider.ts +39 -0
- package/src/services/logging/index.ts +16 -0
- package/src/types/API.ts +40 -0
- package/src/types/Config.ts +35 -0
- package/src/types/Tokens.ts +27 -0
- package/src/types/internal.ts +50 -0
- package/src/utils/blockchain.ts +15 -0
- package/src/utils/constants.ts +31 -0
- package/src/utils/environment.ts +3 -0
- package/src/utils/helpers.ts +15 -0
- package/src/utils/log.test.ts +76 -0
- package/src/utils/log.ts +157 -0
- package/src/utils/signer.ts +36 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,201 @@
|
|
|
1
|
+
Apache License
|
|
2
|
+
Version 2.0, January 2004
|
|
3
|
+
http://www.apache.org/licenses/
|
|
4
|
+
|
|
5
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
6
|
+
|
|
7
|
+
1. Definitions.
|
|
8
|
+
|
|
9
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
10
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
11
|
+
|
|
12
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
13
|
+
the copyright owner that is granting the License.
|
|
14
|
+
|
|
15
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
16
|
+
other entities that control, are controlled by, or are under common
|
|
17
|
+
control with that entity. For the purposes of this definition,
|
|
18
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
19
|
+
direction or management of such entity, whether by contract or
|
|
20
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
21
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
22
|
+
|
|
23
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
24
|
+
exercising permissions granted by this License.
|
|
25
|
+
|
|
26
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
27
|
+
including but not limited to software source code, documentation
|
|
28
|
+
source, and configuration files.
|
|
29
|
+
|
|
30
|
+
"Object" form shall mean any form resulting from mechanical
|
|
31
|
+
transformation or translation of a Source form, including but
|
|
32
|
+
not limited to compiled object code, generated documentation,
|
|
33
|
+
and conversions to other media types.
|
|
34
|
+
|
|
35
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
36
|
+
Object form, made available under the License, as indicated by a
|
|
37
|
+
copyright notice that is included in or attached to the work
|
|
38
|
+
(an example is provided in the Appendix below).
|
|
39
|
+
|
|
40
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
41
|
+
form, that is based on (or derived from) the Work and for which the
|
|
42
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
43
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
44
|
+
of this License, Derivative Works shall not include works that remain
|
|
45
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
46
|
+
the Work and Derivative Works thereof.
|
|
47
|
+
|
|
48
|
+
"Contribution" shall mean any work of authorship, including
|
|
49
|
+
the original version of the Work and any modifications or additions
|
|
50
|
+
to that Work or Derivative Works thereof, that is intentionally
|
|
51
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
|
52
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
|
53
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
|
54
|
+
means any form of electronic, verbal, or written communication sent
|
|
55
|
+
to the Licensor or its representatives, including but not limited to
|
|
56
|
+
communication on electronic mailing lists, source code control systems,
|
|
57
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
|
58
|
+
Licensor for the purpose of discussing and improving the Work, but
|
|
59
|
+
excluding communication that is conspicuously marked or otherwise
|
|
60
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
|
61
|
+
|
|
62
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
63
|
+
on behalf of whom a Contribution has been received by Licensor and
|
|
64
|
+
subsequently incorporated within the Work.
|
|
65
|
+
|
|
66
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
67
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
68
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
69
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
70
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
71
|
+
Work and such Derivative Works in Source or Object form.
|
|
72
|
+
|
|
73
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
74
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
75
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
76
|
+
(except as stated in this section) patent license to make, have made,
|
|
77
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
78
|
+
where such license applies only to those patent claims licensable
|
|
79
|
+
by such Contributor that are necessarily infringed by their
|
|
80
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
|
81
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
82
|
+
institute patent litigation against any entity (including a
|
|
83
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
84
|
+
or a Contribution incorporated within the Work constitutes direct
|
|
85
|
+
or contributory patent infringement, then any patent licenses
|
|
86
|
+
granted to You under this License for that Work shall terminate
|
|
87
|
+
as of the date such litigation is filed.
|
|
88
|
+
|
|
89
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
90
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
91
|
+
modifications, and in Source or Object form, provided that You
|
|
92
|
+
meet the following conditions:
|
|
93
|
+
|
|
94
|
+
(a) You must give any other recipients of the Work or
|
|
95
|
+
Derivative Works a copy of this License; and
|
|
96
|
+
|
|
97
|
+
(b) You must cause any modified files to carry prominent notices
|
|
98
|
+
stating that You changed the files; and
|
|
99
|
+
|
|
100
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
101
|
+
that You distribute, all copyright, patent, trademark, and
|
|
102
|
+
attribution notices from the Source form of the Work,
|
|
103
|
+
excluding those notices that do not pertain to any part of
|
|
104
|
+
the Derivative Works; and
|
|
105
|
+
|
|
106
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
107
|
+
distribution, then any Derivative Works that You distribute must
|
|
108
|
+
include a readable copy of the attribution notices contained
|
|
109
|
+
within such NOTICE file, excluding those notices that do not
|
|
110
|
+
pertain to any part of the Derivative Works, in at least one
|
|
111
|
+
of the following places: within a NOTICE text file distributed
|
|
112
|
+
as part of the Derivative Works; within the Source form or
|
|
113
|
+
documentation, if provided along with the Derivative Works; or,
|
|
114
|
+
within a display generated by the Derivative Works, if and
|
|
115
|
+
wherever such third-party notices normally appear. The contents
|
|
116
|
+
of the NOTICE file are for informational purposes only and
|
|
117
|
+
do not modify the License. You may add Your own attribution
|
|
118
|
+
notices within Derivative Works that You distribute, alongside
|
|
119
|
+
or as an addendum to the NOTICE text from the Work, provided
|
|
120
|
+
that such additional attribution notices cannot be construed
|
|
121
|
+
as modifying the License.
|
|
122
|
+
|
|
123
|
+
You may add Your own copyright statement to Your modifications and
|
|
124
|
+
may provide additional or different license terms and conditions
|
|
125
|
+
for use, reproduction, or distribution of Your modifications, or
|
|
126
|
+
for any such Derivative Works as a whole, provided Your use,
|
|
127
|
+
reproduction, and distribution of the Work otherwise complies with
|
|
128
|
+
the conditions stated in this License.
|
|
129
|
+
|
|
130
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
131
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
132
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
133
|
+
this License, without any additional terms or conditions.
|
|
134
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
135
|
+
the terms of any separate license agreement you may have executed
|
|
136
|
+
with Licensor regarding such Contributions.
|
|
137
|
+
|
|
138
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
139
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
140
|
+
except as required for reasonable and customary use in describing the
|
|
141
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
|
142
|
+
|
|
143
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
144
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
145
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
146
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
147
|
+
implied, including, without limitation, any warranties or conditions
|
|
148
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
149
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
150
|
+
appropriateness of using or redistributing the Work and assume any
|
|
151
|
+
risks associated with Your exercise of permissions under this License.
|
|
152
|
+
|
|
153
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
154
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
155
|
+
unless required by applicable law (such as deliberate and grossly
|
|
156
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
157
|
+
liable to You for damages, including any direct, indirect, special,
|
|
158
|
+
incidental, or consequential damages of any character arising as a
|
|
159
|
+
result of this License or out of the use or inability to use the
|
|
160
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
161
|
+
work stoppage, computer failure or malfunction, or any and all
|
|
162
|
+
other commercial damages or losses), even if such Contributor
|
|
163
|
+
has been advised of the possibility of such damages.
|
|
164
|
+
|
|
165
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
|
166
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
|
167
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
168
|
+
or other liability obligations and/or rights consistent with this
|
|
169
|
+
License. However, in accepting such obligations, You may act only
|
|
170
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
|
171
|
+
of any other Contributor, and only if You agree to indemnify,
|
|
172
|
+
defend, and hold each Contributor harmless for any liability
|
|
173
|
+
incurred by, or claims asserted against, such Contributor by reason
|
|
174
|
+
of your accepting any such warranty or additional liability.
|
|
175
|
+
|
|
176
|
+
END OF TERMS AND CONDITIONS
|
|
177
|
+
|
|
178
|
+
APPENDIX: How to apply the Apache License to your work.
|
|
179
|
+
|
|
180
|
+
To apply the Apache License to your work, attach the following
|
|
181
|
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
|
182
|
+
replaced with your own identifying information. (Don't include
|
|
183
|
+
the brackets!) The text should be enclosed in the appropriate
|
|
184
|
+
comment syntax for the file format. We also recommend that a
|
|
185
|
+
file or class name and description of purpose be included on the
|
|
186
|
+
same "printed page" as the copyright notice for easier
|
|
187
|
+
identification within third-party archives.
|
|
188
|
+
|
|
189
|
+
Copyright 2022 Paella Labs Inc
|
|
190
|
+
|
|
191
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
192
|
+
you may not use this file except in compliance with the License.
|
|
193
|
+
You may obtain a copy of the License at
|
|
194
|
+
|
|
195
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
196
|
+
|
|
197
|
+
Unless required by applicable law or agreed to in writing, software
|
|
198
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
199
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
200
|
+
See the License for the specific language governing permissions and
|
|
201
|
+
limitations under the License.
|
package/dist/index.cjs
ADDED
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
"use strict";var H=Object.defineProperty,wt=Object.defineProperties,Ct=Object.getOwnPropertyDescriptor,bt=Object.getOwnPropertyDescriptors,kt=Object.getOwnPropertyNames,ke=Object.getOwnPropertySymbols;var xe=Object.prototype.hasOwnProperty,vt=Object.prototype.propertyIsEnumerable;var ve=(r,e,t)=>e in r?H(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t,y=(r,e)=>{for(var t in e||(e={}))xe.call(e,t)&&ve(r,t,e[t]);if(ke)for(var t of ke(e))vt.call(e,t)&&ve(r,t,e[t]);return r},g=(r,e)=>wt(r,bt(e));var xt=(r,e)=>{for(var t in e)H(r,t,{get:e[t],enumerable:!0})},Wt=(r,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of kt(e))!xe.call(r,o)&&o!==t&&H(r,o,{get:()=>e[o],enumerable:!(n=Ct(e,o))||n.enumerable});return r};var Vt=r=>Wt(H({},"__esModule",{value:!0}),r);var i=(r,e,t)=>new Promise((n,o)=>{var a=u=>{try{l(t.next(u))}catch(d){o(d)}},s=u=>{try{l(t.throw(u))}catch(d){o(d)}},l=u=>u.done?n(u.value):Promise.resolve(u.value).then(a,s);l((t=t.apply(r,e)).next())});var qt={};xt(qt,{AdminAlreadyUsedError:()=>N,AdminMismatchError:()=>h,Blockchain:()=>Pe.EVMBlockchainIncludingTestnet,ConfigError:()=>M,CrossmintServiceError:()=>f,EVMSmartWallet:()=>K,JWTDecryptionError:()=>x,JWTExpiredError:()=>k,JWTIdentifierError:()=>W,JWTInvalidError:()=>v,NonCustodialWalletsNotEnabledError:()=>B,NotAuthorizedError:()=>I,OutOfCreditsError:()=>V,PasskeyMismatchError:()=>b,SmartWalletSDK:()=>fe,SmartWalletSDKError:()=>p,TransferError:()=>C,UserWalletAlreadyCreatedError:()=>R,blockchainToChainId:()=>Pe.blockchainToChainId});module.exports=Vt(qt);var Pe=require("@crossmint/common-sdk-base");function G(){return typeof window!="undefined"}function z(){return process.env.NODE_ENV==="test"?!1:window.location.origin.includes("localhost")}function j(r,e){return(r==null?void 0:r.toLowerCase())===(e==null?void 0:e.toLowerCase())}var ge=!1,q=class{logInfo(e,t){ge&&console.log(e,t)}logError(e,t){ge&&console.error(e,t)}logWarn(e,t){ge&&console.warn(e,t)}};var We="ZeroDev";var Ve="pub035be8a594b35be1887b6ba76c4029ca",Me="http://localhost:3000/api",Ne="https://staging.crossmint.com/api",Be="https://www.crossmint.com/api",Ue="9ee29857-8077-404b-9a9a-31eeea996a4a",Ke="023d4a21-d801-4450-b629-24439ab1369d",Le="3d166617-da86-494b-9348-e8a13343bc04",$e="e9314f9e-a13d-414f-b965-c591a0248243",Je="1641cd99-c1ef-404a-9d26-a9dc67b1ba51",Ze="3cfecfb6-9d7d-4ef6-acaa-ac8f79f6cd5a",Ye="7ff22858-06f0-4f3a-8b46-5b41d8c75d0e",Fe="3b24773b-d91e-4c01-8ce5-04807463bbca",He="d54706a0-304b-419e-8a33-03c26ba3f0e9",Ge="ce986d52-4f27-4a2b-b429-eb2322f15f32",ze="6204f336-643f-41af-94e1-f8d146c91675",je="3eb830c5-f91b-48e0-bb7d-dc30103a60b2",qe="6188b92b-993e-4f39-be22-56e4806416a8",Xe="8b8b6d1a-184c-4198-8f29-c07e63aad595",Qe="5535aa3b-4f9c-45af-9c38-0072369564a3",et="b6a6db7c-65de-4f74-9d8f-f70d9c083531";var S="SCW_SDK",tt="0.1.0",Te="2024-06-09",rt="https://rpc.zerodev.app/api/v2/bundler/",nt="https://rpc.zerodev.app/api/v2/paymaster/",X="https://api.developer.coinbase.com/rpc/v1/base-sepolia/6BTAmOQZ0x1YWtI24hIKKqdHWmVP1UXf",Q="https://api.developer.coinbase.com/rpc/v1/base/6BTAmOQZ0x1YWtI24hIKKqdHWmVP1UXf";var ee=require("@datadog/browser-logs");var w=class{logInfo(e,t){Se(e,"info",t)}logError(e,t){Se(e,"error",t)}logWarn(e,t){Se(e,"warn",t)}};function Se(r,e,t){let n=t?g(y({},t),{service:S}):{service:S};Mt(),ee.datadogLogs.logger[e](r,n)}function Mt(){ee.datadogLogs.getInternalContext()==null&&ee.datadogLogs.init({clientToken:Ve,site:"datadoghq.com",forwardErrorsToLogs:!1,sampleRate:100})}function Nt(){return G()&&z()?new q:new w}var{logInfo:te,logWarn:pr,logError:A}=Nt();var J=require("viem");var E={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",UNCATEGORIZED:"smart-wallet:uncategorized"},p=class extends Error{constructor(e,t,n=E.UNCATEGORIZED){super(e),this.details=t,this.code=n}},C=class extends p{constructor(e){super(e,void 0,E.TRANSFER)}},f=class extends p{constructor(e,t){super(e,void 0,E.CROSSMINT_SERVICE),this.status=t}},h=class extends p{constructor(e,t,n){super(e,E.ERROR_ADMIN_MISMATCH),this.required=t,this.used=n}},b=class extends p{constructor(e,t,n){super(e,E.ERROR_PASSKEY_MISMATCH),this.required=t,this.used=n}},I=class extends p{constructor(e){super(e,void 0,E.NOT_AUTHORIZED)}},k=class extends I{constructor(t){super(`JWT provided expired at timestamp ${t}`);this.code=E.ERROR_JWT_EXPIRED;this.expiredAt=t.toISOString()}},v=class extends I{constructor(){super("Invalid JWT provided");this.code=E.ERROR_JWT_INVALID}},x=class extends I{constructor(){super("Error decrypting JWT");this.code=E.ERROR_JWT_DECRYPTION}},W=class extends I{constructor(t){super(`Missing required identifier '${t}' in the JWT`);this.code=E.ERROR_JWT_IDENTIFIER;this.identifierKey=t}},R=class extends p{constructor(t){super(`The user with userId ${t.toString()} already has a wallet created for this project`);this.code=E.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,E.ERROR_OUT_OF_CREDITS)}},M=class extends p{constructor(e){super(e,void 0,E.ERROR_WALLET_CONFIG)}},N=class extends M{constructor(){super("This signer was already used to create another wallet. Please use a different signer.");this.code=E.ERROR_ADMIN_SIGNER_ALREADY_USED}},B=class extends M{constructor(){super("Non-custodial wallets are not enabled for this project")}};var ot=require("uuid");var _=class{constructor(e,t={},n=(0,ot.v4)()){this.extraInfo=t;this.logIdempotencyKey=n;return new Proxy(this,{get:(o,a,s)=>{let l=o[a],u=`[${S} - ${e} - ${String(a)}]`;return typeof l=="function"?(...d)=>{this.logInput(d,u);let m=l.apply(o,d);return m instanceof Promise?m.then(P=>(this.logOutput(P,u),P)).catch(P=>{throw this.logError(P,u),P}):(this.logOutput(m,u),m)}:Reflect.get(o,a,s)}})}logInput(e,t){U(`${t} input - ${T(e)} - extra_info - ${T(this.extraInfo)} - log_idempotency_key - ${this.logIdempotencyKey}`,g(y({args:e},this.extraInfo),{logIdempotencyKey:this.logIdempotencyKey}))}logOutput(e,t){U(`${t} output - ${T(e)} - extra_info - ${T(this.extraInfo)} - log_idempotency_key - ${this.logIdempotencyKey}`,g(y({res:e},this.extraInfo),{logIdempotencyKey:this.logIdempotencyKey}))}logError(e,t){A(`${t} threw_error - ${e} - extra_info - ${T(this.extraInfo)} - log_idempotency_key - ${this.logIdempotencyKey}`,y({err:e},this.extraInfo))}logPerformance(e,t){return D(e,t,this.extraInfo)}};function D(r,e,t){return i(this,null,function*(){let n=new Date().getTime(),o=yield e(),a=new Date().getTime()-n,s=y({durationInMs:a},t);return U(`[${S} - ${r} - TIME] - ${T(s)}`,{args:s}),o})}function at(r,e){return function(...t){let n=`[${S} - function: ${e}]`;U(`${n} input: ${T(t)}`,{args:t});try{let o=r.apply(this,t);return o instanceof Promise?o.then(a=>(U(`${n} output: ${T(a)}`,{res:a}),a)).catch(a=>{throw A(`${n} threw_error: ${T(a)}`,{err:a}),a}):(U(`${n} output: ${T(o)}`,{res:o}),o)}catch(o){throw A(`${n} threw_error: ${T(o)}`,{err:o}),o}}}function T(r){try{return r!=null?JSON.stringify(r,null,2):r}catch(e){return Bt(r)}}function Bt(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 U(r,e){if(z()){console.log(r);return}te(r,e)}function st(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 A("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 re=require("viem");var it=[{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 ct({contract:r,config:e,from:t,to:n}){switch(e.token.type){case"ft":return{account:t,address:r,abi:re.erc20Abi,functionName:"transfer",args:[n,e.amount]};case"sft":return{account:t,address:r,abi:it,functionName:"safeTransferFrom",args:[t.address,n,e.token.tokenId,e.quantity,"0x00"],tokenId:e.token.tokenId};case"nft":return{account:t,address:r,abi:re.erc721Abi,functionName:"safeTransferFrom",args:[t.address,n,e.token.tokenId],tokenId:e.token.tokenId}}}var K=class extends _{constructor(t,n,o,a){super("EVMSmartWallet",{chain:a,address:n.account.address});this.crossmintService=t;this.accountClient=n;this.chain=a,this.client={wallet:n,public:o}}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 o=ct({contract:n.token.contractAddress,to:t,from:this.accountClient.account,config:n});try{let a=this.accountClient.extend(J.publicActions),{request:s}=yield a.simulateContract(o);return yield a.writeContract(s)}catch(a){A("[TRANSFER] - ERROR_TRANSFERRING_TOKEN",{service:S,error:st(a),tokenId:o.tokenId,contractAddress:n.token.contractAddress,chain:n.token.chain});let s=o.tokenId==null?"":`:${o.tokenId}}`;throw new C(`Error transferring token ${n.token.contractAddress}${s}`)}}))})}nfts(){return i(this,null,function*(){return this.crossmintService.fetchNFTs(this.address,this.chain)})}};var At=require("viem"),Dt=require("@crossmint/common-sdk-base");var lt=require("@crossmint/common-sdk-base");var ne=class{constructor(e={ERROR_JWT_INVALID:()=>new v,ERROR_JWT_DECRYPTION:()=>new x,ERROR_JWT_EXPIRED:({expiredAt:t})=>new k(new Date(t)),ERROR_JWT_IDENTIFIER:({identifierKey:t})=>new W(t),ERROR_USER_WALLET_ALREADY_CREATED:({userId:t})=>new R(t),ERROR_ADMIN_SIGNER_ALREADY_USED:()=>new N,ERROR_PROJECT_NONCUSTODIAL_WALLETS_NOT_ENABLED:()=>new B}){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 o=yield e.json(),a=o.code;if(a!=null&&this.errors[a]!=null)throw this.errors[a](o);if(o.message!=null)throw new f(o.message,e.status)}catch(o){console.error("Error parsing response",o)}throw new f(yield e.text(),e.status)}})}};var Z=class Z extends _{constructor(e){super("BaseCrossmintService");let t=(0,lt.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 ne}fetchCrossmintAPI(a){return i(this,arguments,function*(e,t={method:"GET"},n,o){return D("FETCH_CROSSMINT_API",()=>i(this,null,function*(){let s=`${this.crossmintBaseUrl}/${e}`,{body:l,method:u}=t,d;try{d=yield fetch(s,{body:l,method:u,headers:y(y({},this.crossmintAPIHeaders),o!=null&&{Authorization:`Bearer ${o}`})})}catch(m){throw new f(`Error fetching Crossmint API: ${m}`)}return d.ok||(yield this.apiErrorService.throwErrorFromResponse({response:d,onServerErrorMessage:n})),yield d.json()}),{endpoint:e})})}getUrlFromEnv(e){let t=Z.urlMap[e];if(!t)throw console.log(" CrossmintService.urlMap: ",Z.urlMap),new Error(`URL not found for environment: ${e}`);return t}};Z.urlMap={development:Me,staging:Ne,production:Be};var oe=Z;var Kt=require("@crossmint/common-sdk-base");var ae=class extends oe{idempotentCreateSmartWallet(e,t){return i(this,null,function*(){return this.fetchCrossmintAPI(`${Te}/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(`${Te}/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"}};var Y=require("@crossmint/common-sdk-base");function Lt(r){return[Y.EVMBlockchainIncludingTestnet.ZKYOTO,Y.EVMBlockchainIncludingTestnet.ZKATANA,Y.EVMBlockchainIncludingTestnet.ASTAR_ZKEVM,Y.EVMBlockchainIncludingTestnet.HYPERSONIC_TESTNET].includes(r)}function se(r){return Lt(r)}var Ie=require("viem");var $t=["sendTransaction","writeContract","sendUserOperation"],Jt=["signMessage","signTypedData"];function he(r){return $t.includes(r)}function Zt(r){return Jt.includes(r)}var ie=class{constructor(e){this.errorProcessor=e}decorate({crossmintChain:e,smartAccountClient:t}){return new Proxy(t,{get:(n,o,a)=>{let s=Reflect.get(n,o,a);return typeof s!="function"||typeof o!="string"||!(Zt(o)||he(o))?s:(...l)=>D(`CrossmintSmartWallet.${o}`,()=>this.execute(n,o,s,l,e))}})}execute(e,t,n,o,a){return i(this,null,function*(){try{te(`[CrossmintSmartWallet.${t}] - params: ${(0,Ie.stringify)(o)}`);let s=he(t)?this.processTxnArgs(t,a,o):o;return yield n.call(e,...s)}catch(s){let l=he(t)?"signing":"sending transaction";throw this.errorProcessor.map(s,new p(`Error ${l}: ${s.message}`,(0,Ie.stringify)(s)))}})}processTxnArgs(e,t,n){if(e==="sendUserOperation"){let[{userOperation:a,middleware:s,account:l}]=n;return[{middleware:s,account:l,userOperation:this.addGelatoBundlerProperties(t,a)},...n.slice(1)]}let[o]=n;return[this.addGelatoBundlerProperties(t,o),...n.slice(1)]}addGelatoBundlerProperties(e,t){return se(e)?g(y({},t),{maxFeePerGas:"0x0",maxPriorityFeePerGas:"0x0"}):t}};function ce(r){return{pubKeyX:r.pubKeyX,pubKeyY:r.pubKeyY,passkeyName:r.passkeyName,type:"passkeys"}}var Rt=require("@zerodev/sdk"),ue=require("permissionless"),O=require("viem"),_t=require("@crossmint/common-sdk-base");var Re=["0.3.1","0.3.0","0.2.4"];function pt(r){return Re.includes(r)}var _e=["v0.6","v0.7"];function dt(r){return _e.includes(r)}var c=require("viem/chains"),Ae=require("@crossmint/common-sdk-base"),De=r=>{let e=new Map([["ethereum",Ue],["polygon",Ke],["bsc",Le],["optimism",$e],["arbitrum",Je],["ethereum-goerli",Ze],["ethereum-sepolia",Ye],["polygon-amoy",Fe],["zkatana",He],["zkyoto",Ge],["arbitrum-sepolia",Xe],["base-goerli",null],["base-sepolia",je],["bsc-testnet",null],["optimism-goerli",null],["optimism-sepolia",qe],["zora-goerli",null],["zora-sepolia",null],["base",Qe],["zora",null],["arbitrumnova",et],["astar-zkevm",ze],["apex",null]]).get(r);if(e==null)throw new Error(`ZeroDev project id not found for chain ${r}`);return e},le=r=>{switch(r){case"ethereum":return c.mainnet;case"ethereum-goerli":return c.goerli;case"ethereum-sepolia":return c.sepolia;case"polygon":return c.polygon;case"polygon-amoy":return c.polygonAmoy;case"optimism":return c.optimism;case"optimism-sepolia":return c.optimismSepolia;case"arbitrum":return c.arbitrum;case"arbitrumnova":return c.arbitrumNova;case"arbitrum-sepolia":return c.arbitrumSepolia;case"base":return c.base;case"base-sepolia":return c.baseSepolia;case"zkyoto":return c.astarZkyoto;case"astar-zkevm":return c.astarZkEVM;case"bsc":return c.bsc;default:throw new Error(`Unsupported network: ${r}`)}},Oe=r=>{switch(r){case Ae.EVMBlockchainIncludingTestnet.BASE_SEPOLIA:return X;case Ae.EVMBlockchainIncludingTestnet.BASE:return Q;default:return rt+De(r)+"?bundlerProvider=STACKUP"}};var mt=require("permissionless");var ut=at(e=>i(void 0,[e],function*({walletParams:r}){if(Yt(r.signer))return yield(0,mt.providerToSmartAccountSigner)(r.signer);if(Ft(r.signer))return r.signer.account;{let t=r.signer;throw new p(`The signer type ${t.type} is not supported`)}}),"createOwnerSigner");function Yt(r){return r&&typeof r.request=="function"}function Ft(r){return r&&r.type==="VIEM_ACCOUNT"}var yt=require("@zerodev/ecdsa-validator"),Et=require("@zerodev/sdk");var pe=class{get(u,d){return i(this,arguments,function*({chain:e,publicClient:t,entryPoint:n,walletParams:o,kernelVersion:a,user:s},l){let m=yield ut({chain:e,walletParams:o});if(l!=null&&!j(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 P=yield(0,yt.signerToEcdsaValidator)(t,{signer:m,entryPoint:n.address,kernelVersion:a});return{account:yield(0,Et.createKernelAccount)(t,{plugins:{sudo:P},index:BigInt(0),entryPoint:n.address,kernelVersion:a}),signerData:{eoaAddress:m.address,type:"eoa"}}})}};var L=require("@zerodev/passkey-validator"),ft=require("@zerodev/sdk"),Pt=require("@zerodev/webauthn-key");function gt(r){return r.walletParams.signer.type==="PASSKEY"}var de=class{constructor(e){this.crossmintService=e}get(l,u){return i(this,arguments,function*({user:e,publicClient:t,walletParams:n,entryPoint:o,kernelVersion:a},s){var be;let d=(be=n.signer.passkeyName)!=null?be:e.id;if(s!=null&&s.passkeyName!==d)throw new b(`User '${e.id}' has an existing wallet created with a passkey named '${s.passkeyName}', this does match input passkey name '${d}'.`,ce(s));let m=yield this.getPasskey(e,d,s),P=L.PasskeyValidatorContractVersion.V0_0_2,$=s==null?P:s.validatorContractVersion,F=yield(0,L.toPasskeyValidator)(t,{webAuthnKey:m,entryPoint:o.address,validatorContractVersion:$,kernelVersion:a}),Ot=yield(0,ft.createKernelAccount)(t,{plugins:{sudo:F},entryPoint:o.address,kernelVersion:a});return{signerData:this.getSignerData(F,$,d),account:Ot}})}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,Pt.toWebAuthnKey)({passkeyName:t,passkeyServerUrl:this.crossmintService.getPasskeyServerUrl(),mode:L.WebAuthnMode.Register,passkeyServerHeaders:this.createPasskeysServerHeaders(e)})})}getSignerData(e,t,n){return g(y({},Ht(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}`}}},Ht=r=>{let e=Gt(r),t=new TextDecoder().decode(e);return JSON.parse(t)};function Gt(r){let e=atob(r);return Uint8Array.from(e,t=>t.codePointAt(0))}var Tt=require("@zerodev/sdk"),St=require("viem"),we=require("@crossmint/common-sdk-base");function ht(r){return!se(r)}var zt=r=>{switch(r){case we.EVMBlockchainIncludingTestnet.BASE_SEPOLIA:return X;case we.EVMBlockchainIncludingTestnet.BASE:return Q;default:return nt+De(r)+"?paymasterProvider=STACKUP"}};function It({entryPoint:r,chain:e}){return{middleware:{sponsorUserOperation:n=>i(this,[n],function*({userOperation:t}){return(0,Tt.createZeroDevPaymasterClient)({chain:le(e),transport:(0,St.http)(zt(e)),entryPoint:r}).sponsorUserOperation({userOperation:t,entryPoint:r})})}}}var me=class{constructor(e,t,n=new Ce(new pe,new de(e))){this.crossmintWalletService=e;this.clientDecorator=t;this.accountFactory=n}getOrCreate(e,t,n){return i(this,null,function*(){let{entryPoint:o,kernelVersion:a,existingSignerConfig:s,smartContractWalletAddress:l,userId:u}=yield this.fetchConfig(e,t),d=(0,O.createPublicClient)({transport:(0,O.http)(Oe(t))}),{account:m,signerData:P}=yield this.accountFactory.get({chain:t,walletParams:n,publicClient:d,user:g(y({},e),{id:u}),entryPoint:o,kernelVersion:a},s);if(l!=null&&!j(l,m.address))throw new R(u);s==null&&(yield this.crossmintWalletService.idempotentCreateSmartWallet(e,{type:We,smartContractWalletAddress:m.address,signerData:P,version:0,baseLayer:"evm",chainId:(0,_t.blockchainToChainId)(t),entryPointVersion:o.version,kernelVersion:a}));let $=(0,Rt.createKernelAccountClient)(y({account:m,chain:le(t),entryPoint:m.entryPoint,bundlerTransport:(0,O.http)(Oe(t))},ht(t)&&It({entryPoint:m.entryPoint,chain:t}))),F=this.clientDecorator.decorate({crossmintChain:t,smartAccountClient:$});return new K(this.crossmintWalletService,F,d,t)})}fetchConfig(e,t){return i(this,null,function*(){let{entryPointVersion:n,kernelVersion:o,signers:a,smartContractWalletAddress:s,userId:l}=yield this.crossmintWalletService.getSmartWalletConfig(e,t);if(!pt(o))throw new p(`Unsupported kernel version. Supported versions: ${Re.join(", ")}. Version used: ${o}, Please contact support`);if(!dt(n))throw new p(`Unsupported entry point version. Supported versions: ${_e.join(", ")}. Version used: ${n}. Please contact support`);if(n==="v0.7"&&o.startsWith("0.2")||n==="v0.6"&&o.startsWith("0.3"))throw new p(`Unsupported combination: entryPoint ${n} and kernel version ${o}. Please contact support`);return{entryPoint:{version:n,address:n==="v0.6"?ue.ENTRYPOINT_ADDRESS_V06:ue.ENTRYPOINT_ADDRESS_V07},kernelVersion:o,userId:l,existingSignerConfig:this.getSigner(a),smartContractWalletAddress:s!=null?(0,O.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(gt(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.`,ce(t));return this.eoa.get(e,t)}};var Ee=require("viem");var ye=class{constructor(e){this.logger=e}map(e,t){return this.record(e),e instanceof p||e instanceof Ee.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,Ee.stringify)(e),domain:window.location.hostname,sdk_version:tt})}};var fe=class r extends _{constructor(t,n){super("SmartWalletSDK");this.smartWalletService=t;this.errorProcessor=n}static init({clientApiKey:t}){if(!G())throw new p("Smart Wallet SDK should only be used client side.");if(!(0,Dt.validateAPIKey)(t).isValid)throw new Error("API key invalid");let o=new ae(t),a=new ye(new w);return new r(new me(o,new ie(a)),a)}getOrCreateWallet(a,s){return i(this,arguments,function*(t,n,o={signer:{type:"PASSKEY"}}){return D("GET_OR_CREATE_WALLET",()=>i(this,null,function*(){try{return yield this.smartWalletService.getOrCreate(t,n,o)}catch(l){throw this.errorProcessor.map(l,new p(`Wallet creation failed: ${l.message}.`,(0,At.stringify)(l)))}}),{user:t,chain:n})})}};0&&(module.exports={AdminAlreadyUsedError,AdminMismatchError,Blockchain,ConfigError,CrossmintServiceError,EVMSmartWallet,JWTDecryptionError,JWTExpiredError,JWTIdentifierError,JWTInvalidError,NonCustodialWalletsNotEnabledError,NotAuthorizedError,OutOfCreditsError,PasskeyMismatchError,SmartWalletSDK,SmartWalletSDKError,TransferError,UserWalletAlreadyCreatedError,blockchainToChainId});
|
|
2
|
+
//# sourceMappingURL=index.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/index.ts","../src/utils/environment.ts","../src/utils/helpers.ts","../src/services/logging/ConsoleProvider.ts","../src/utils/constants.ts","../src/services/logging/DatadogProvider.ts","../src/services/logging/index.ts","../src/blockchain/wallets/EVMSmartWallet.ts","../src/error/index.ts","../src/utils/log.ts","../src/blockchain/transfer.ts","../src/ABI/ERC1155.json","../src/SmartWalletSDK.ts","../src/api/BaseCrossmintService.ts","../src/api/APIErrorService.ts","../src/api/CrossmintWalletService.ts","../src/utils/blockchain.ts","../src/blockchain/wallets/clientDecorator.ts","../src/types/API.ts","../src/blockchain/wallets/service.ts","../src/types/internal.ts","../src/blockchain/BlockchainNetworks.ts","../src/utils/signer.ts","../src/blockchain/wallets/eoa.ts","../src/blockchain/wallets/passkey.ts","../src/blockchain/wallets/paymaster.ts","../src/error/processor.ts"],"sourcesContent":["export { EVMBlockchainIncludingTestnet as Blockchain, blockchainToChainId } from \"@crossmint/common-sdk-base\";\n\nexport { EVMSmartWallet } from \"./blockchain/wallets/EVMSmartWallet\";\n\nexport type {\n SmartWalletSDKInitParams,\n UserParams,\n ViemAccount,\n PasskeySigner,\n EOASigner,\n WalletParams,\n} from \"./types/Config\";\n\nexport type { TransferType, ERC20TransferType, NFTTransferType, SFTTransferType } from \"./types/Tokens\";\n\nexport {\n TransferError,\n CrossmintServiceError,\n SmartWalletSDKError,\n JWTDecryptionError,\n JWTExpiredError,\n JWTIdentifierError,\n JWTInvalidError,\n NotAuthorizedError,\n UserWalletAlreadyCreatedError,\n OutOfCreditsError,\n AdminAlreadyUsedError,\n AdminMismatchError,\n PasskeyMismatchError,\n ConfigError,\n NonCustodialWalletsNotEnabledError,\n} from \"./error\";\n\nexport { SmartWalletSDK } from \"./SmartWalletSDK\";\n","export function isClient() {\n return typeof window !== \"undefined\";\n}\n","export function isLocalhost() {\n if (process.env.NODE_ENV === \"test\") {\n return false;\n }\n\n return window.location.origin.includes(\"localhost\");\n}\n\nexport function isEmpty(str: string | undefined | null): str is undefined | null {\n return !str || str.length === 0 || str.trim().length === 0;\n}\n\nexport function equalsIgnoreCase(a?: string, b?: string): boolean {\n return a?.toLowerCase() === b?.toLowerCase();\n}\n","import { BrowserLoggerInterface } from \"./BrowserLoggerInterface\";\n\n// Set to true to enable logging on local development\nconst LOG_IN_LOCALHOST = false;\n\nexport class ConsoleProvider implements BrowserLoggerInterface {\n logInfo(message: string, context?: object) {\n if (LOG_IN_LOCALHOST) {\n console.log(message, context);\n }\n }\n\n logError(message: string, context?: object) {\n if (LOG_IN_LOCALHOST) {\n console.error(message, context);\n }\n }\n\n logWarn(message: string, context?: object) {\n if (LOG_IN_LOCALHOST) {\n console.warn(message, context);\n }\n }\n}\n","export const ZERO_DEV_TYPE = \"ZeroDev\";\nexport const CURRENT_VERSION = 0;\nexport const DATADOG_CLIENT_TOKEN = \"pub035be8a594b35be1887b6ba76c4029ca\";\nexport const CROSSMINT_DEV_URL = \"http://localhost:3000/api\";\nexport const CROSSMINT_STG_URL = \"https://staging.crossmint.com/api\";\nexport const CROSSMINT_PROD_URL = \"https://www.crossmint.com/api\";\nexport const ZD_ETHEREUM_PROJECT_ID = \"9ee29857-8077-404b-9a9a-31eeea996a4a\";\nexport const ZD_POLYGON_PROJECT_ID = \"023d4a21-d801-4450-b629-24439ab1369d\";\nexport const ZD_BSC_PROJECT_ID = \"3d166617-da86-494b-9348-e8a13343bc04\";\nexport const ZD_OPTIMISM_PROJECT_ID = \"e9314f9e-a13d-414f-b965-c591a0248243\";\nexport const ZD_ARBITRUM_PROJECT_ID = \"1641cd99-c1ef-404a-9d26-a9dc67b1ba51\";\nexport const ZD_GOERLI_PROJECT_ID = \"3cfecfb6-9d7d-4ef6-acaa-ac8f79f6cd5a\";\nexport const ZD_SEPOLIA_PROJECT_ID = \"7ff22858-06f0-4f3a-8b46-5b41d8c75d0e\";\nexport const ZD_AMOY_PROJECT_ID = \"3b24773b-d91e-4c01-8ce5-04807463bbca\";\nexport const ZD_ZKATANA_PROJECT_ID = \"d54706a0-304b-419e-8a33-03c26ba3f0e9\";\nexport const ZD_ZKYOTO_PROJECT_ID = \"ce986d52-4f27-4a2b-b429-eb2322f15f32\";\nexport const ZD_ASTAR_PROJECT_ID = \"6204f336-643f-41af-94e1-f8d146c91675\";\nexport const ZD_BASE_SEPOLIA_PROJECT_ID = \"3eb830c5-f91b-48e0-bb7d-dc30103a60b2\";\nexport const ZD_OPTIMISM_SEPOLIA_PROJECT_ID = \"6188b92b-993e-4f39-be22-56e4806416a8\";\nexport const ZD_ARBITRUM_SEPOLIA_PROJECT_ID = \"8b8b6d1a-184c-4198-8f29-c07e63aad595\";\nexport const ZD_BASE_PROJECT_ID = \"5535aa3b-4f9c-45af-9c38-0072369564a3\";\nexport const ZD_ARBITRUM_NOVA_PROJECT_ID = \"b6a6db7c-65de-4f74-9d8f-f70d9c083531\";\nexport const RELAY_API_KEY = \"c8999b7e-8bb7-416d-a854-dac8632f9ee6_crossmint\";\nexport const SCW_SERVICE = \"SCW_SDK\";\nexport const SDK_VERSION = \"0.1.0\";\nexport const API_VERSION = \"2024-06-09\";\nexport const BUNDLER_RPC = \"https://rpc.zerodev.app/api/v2/bundler/\";\nexport const PAYMASTER_RPC = \"https://rpc.zerodev.app/api/v2/paymaster/\";\nexport const PM_BASE_SEPOLIA_RPC =\n \"https://api.developer.coinbase.com/rpc/v1/base-sepolia/6BTAmOQZ0x1YWtI24hIKKqdHWmVP1UXf\";\nexport const PM_BASE_RPC = \"https://api.developer.coinbase.com/rpc/v1/base/6BTAmOQZ0x1YWtI24hIKKqdHWmVP1UXf\";\n","import { DATADOG_CLIENT_TOKEN, SCW_SERVICE } from \"@/utils/constants\";\nimport { datadogLogs } from \"@datadog/browser-logs\";\n\nimport { BrowserLoggerInterface } from \"./BrowserLoggerInterface\";\n\nexport class DatadogProvider implements BrowserLoggerInterface {\n logInfo(message: string, context?: object) {\n log(message, \"info\", context);\n }\n\n logError(message: string, context?: object) {\n log(message, \"error\", context);\n }\n\n logWarn(message: string, context?: object) {\n log(message, \"warn\", context);\n }\n}\n\nfunction log(message: string, loggerType: \"info\" | \"error\" | \"warn\", contextParam?: object) {\n const _context = contextParam ? { ...contextParam, service: SCW_SERVICE } : { service: SCW_SERVICE };\n\n init();\n datadogLogs.logger[loggerType](message, _context);\n}\n\nfunction init() {\n const isDatadogInitialized = datadogLogs.getInternalContext() != null;\n if (isDatadogInitialized) {\n return;\n }\n\n datadogLogs.init({\n clientToken: DATADOG_CLIENT_TOKEN,\n site: \"datadoghq.com\",\n forwardErrorsToLogs: false,\n sampleRate: 100,\n });\n}\n","import { isClient } from \"../../utils/environment\";\nimport { isLocalhost } from \"../../utils/helpers\";\nimport { ConsoleProvider } from \"./ConsoleProvider\";\nimport { DatadogProvider } from \"./DatadogProvider\";\n\nfunction getBrowserLogger() {\n if (isClient() && isLocalhost()) {\n return new ConsoleProvider();\n }\n\n return new DatadogProvider();\n}\n\nconst { logInfo, logWarn, logError } = getBrowserLogger();\n\nexport { logInfo, logWarn, logError };\n","import { logError } from \"@/services/logging\";\nimport { type HttpTransport, type PublicClient, isAddress, publicActions } from \"viem\";\n\nimport { EVMBlockchainIncludingTestnet } from \"@crossmint/common-sdk-base\";\n\nimport type { CrossmintWalletService } from \"../../api/CrossmintWalletService\";\nimport { TransferError } from \"../../error\";\nimport type { TransferType } from \"../../types/Tokens\";\nimport { SmartWalletClient } from \"../../types/internal\";\nimport { SCW_SERVICE } from \"../../utils/constants\";\nimport { LoggerWrapper, errorToJSON } from \"../../utils/log\";\nimport { transferParams } from \"../transfer\";\n\n/**\n * Smart wallet interface for EVM chains enhanced with Crossmint capabilities.\n * Core functionality is exposed via [viem](https://viem.sh/) clients within the `client` property of the class.\n */\nexport class EVMSmartWallet extends LoggerWrapper {\n public readonly chain: EVMBlockchainIncludingTestnet;\n\n /**\n * [viem](https://viem.sh/) clients that provide an interface for core wallet functionality.\n */\n public readonly client: {\n /**\n * An interface to interact with the smart wallet, execute transactions, sign messages, etc.\n */\n wallet: SmartWalletClient;\n\n /**\n * An interface to read onchain data, fetch transactions, retrieve account balances, etc. Corresponds to public [JSON-RPC API](https://ethereum.org/en/developers/docs/apis/json-rpc/) methods.\n */\n public: PublicClient;\n };\n\n constructor(\n private readonly crossmintService: CrossmintWalletService,\n private readonly accountClient: SmartWalletClient,\n publicClient: PublicClient<HttpTransport>,\n chain: EVMBlockchainIncludingTestnet\n ) {\n super(\"EVMSmartWallet\", { chain, address: accountClient.account.address });\n this.chain = chain;\n this.client = {\n wallet: accountClient,\n public: publicClient,\n };\n }\n\n /**\n * The address of the smart wallet.\n */\n public get address() {\n return this.accountClient.account.address;\n }\n\n /**\n * @returns The transaction hash.\n */\n public async transferToken(toAddress: string, config: TransferType): Promise<string> {\n return this.logPerformance(\"TRANSFER\", async () => {\n if (this.chain !== config.token.chain) {\n throw new Error(\n `Chain mismatch: Expected ${config.token.chain}, but got ${this.chain}. Ensure you are interacting with the correct blockchain.`\n );\n }\n\n if (!isAddress(toAddress)) {\n throw new Error(`Invalid recipient address: '${toAddress}' is not a valid EVM address.`);\n }\n\n if (!isAddress(config.token.contractAddress)) {\n throw new Error(\n `Invalid contract address: '${config.token.contractAddress}' is not a valid EVM address.`\n );\n }\n\n const tx = transferParams({\n contract: config.token.contractAddress,\n to: toAddress,\n from: this.accountClient.account,\n config,\n });\n\n try {\n const client = this.accountClient.extend(publicActions);\n const { request } = await client.simulateContract(tx);\n return await client.writeContract(request);\n } catch (error) {\n logError(\"[TRANSFER] - ERROR_TRANSFERRING_TOKEN\", {\n service: SCW_SERVICE,\n error: errorToJSON(error),\n tokenId: tx.tokenId,\n contractAddress: config.token.contractAddress,\n chain: config.token.chain,\n });\n const tokenIdString = tx.tokenId == null ? \"\" : `:${tx.tokenId}}`;\n throw new TransferError(`Error transferring token ${config.token.contractAddress}${tokenIdString}`);\n }\n });\n }\n\n /**\n * @returns A list of NFTs owned by the wallet.\n */\n public async nfts() {\n return this.crossmintService.fetchNFTs(this.address, this.chain);\n }\n}\n","import { PasskeyDisplay, SignerDisplay } from \"@/types/API\";\n\nexport const SmartWalletErrors = {\n NOT_AUTHORIZED: \"smart-wallet:not-authorized\",\n TRANSFER: \"smart-wallet:transfer.error\",\n CROSSMINT_SERVICE: \"smart-wallet:crossmint-service.error\",\n ERROR_JWT_EXPIRED: \"smart-wallet:not-authorized.jwt-expired\",\n ERROR_JWT_INVALID: \"smart-wallet:not-authorized.jwt-invalid\",\n ERROR_JWT_DECRYPTION: \"smart-wallet:not-authorized.jwt-decryption\",\n ERROR_JWT_IDENTIFIER: \"smart-wallet:not-authorized.jwt-identifier\",\n ERROR_USER_WALLET_ALREADY_CREATED: \"smart-wallet:user-wallet-already-created.error\",\n ERROR_OUT_OF_CREDITS: \"smart-wallet:out-of-credits.error\",\n ERROR_WALLET_CONFIG: \"smart-wallet:wallet-config.error\",\n ERROR_ADMIN_MISMATCH: \"smart-wallet:wallet-config.admin-mismatch\",\n ERROR_PASSKEY_MISMATCH: \"smart-wallet:wallet-config.passkey-mismatch\",\n ERROR_ADMIN_SIGNER_ALREADY_USED: \"smart-wallet:wallet-config.admin-signer-already-used\",\n UNCATEGORIZED: \"smart-wallet:uncategorized\", // catch-all error code\n} as const;\nexport type SmartWalletErrorCode = (typeof SmartWalletErrors)[keyof typeof SmartWalletErrors];\n\nexport class SmartWalletSDKError extends Error {\n public readonly code: SmartWalletErrorCode;\n public readonly details?: string;\n\n constructor(message: string, details?: string, code: SmartWalletErrorCode = SmartWalletErrors.UNCATEGORIZED) {\n super(message);\n this.details = details;\n this.code = code;\n }\n}\n\nexport class TransferError extends SmartWalletSDKError {\n constructor(message: string) {\n super(message, undefined, SmartWalletErrors.TRANSFER);\n }\n}\n\nexport class CrossmintServiceError extends SmartWalletSDKError {\n public status?: number;\n\n constructor(message: string, status?: number) {\n super(message, undefined, SmartWalletErrors.CROSSMINT_SERVICE);\n this.status = status;\n }\n}\n\nexport class AdminMismatchError extends SmartWalletSDKError {\n public readonly required: SignerDisplay;\n public readonly used?: SignerDisplay;\n\n constructor(message: string, required: SignerDisplay, used?: SignerDisplay) {\n super(message, SmartWalletErrors.ERROR_ADMIN_MISMATCH);\n this.required = required;\n this.used = used;\n }\n}\n\nexport class PasskeyMismatchError extends SmartWalletSDKError {\n public readonly required: PasskeyDisplay;\n public readonly used?: PasskeyDisplay;\n\n constructor(message: string, required: PasskeyDisplay, used?: PasskeyDisplay) {\n super(message, SmartWalletErrors.ERROR_PASSKEY_MISMATCH);\n this.required = required;\n this.used = used;\n }\n}\n\nexport class NotAuthorizedError extends SmartWalletSDKError {\n constructor(message: string) {\n super(message, undefined, SmartWalletErrors.NOT_AUTHORIZED);\n }\n}\n\nexport class JWTExpiredError extends NotAuthorizedError {\n public readonly code = SmartWalletErrors.ERROR_JWT_EXPIRED;\n\n /**\n * The expiry time of the JWT as an ISO 8601 timestamp.\n */\n public readonly expiredAt: string;\n\n constructor(expiredAt: Date) {\n super(`JWT provided expired at timestamp ${expiredAt}`);\n this.expiredAt = expiredAt.toISOString();\n }\n}\n\nexport class JWTInvalidError extends NotAuthorizedError {\n public readonly code = SmartWalletErrors.ERROR_JWT_INVALID;\n constructor() {\n super(\"Invalid JWT provided\");\n }\n}\n\nexport class JWTDecryptionError extends NotAuthorizedError {\n public readonly code = SmartWalletErrors.ERROR_JWT_DECRYPTION;\n constructor() {\n super(\"Error decrypting JWT\");\n }\n}\n\nexport class JWTIdentifierError extends NotAuthorizedError {\n public readonly code = SmartWalletErrors.ERROR_JWT_IDENTIFIER;\n public readonly identifierKey: string;\n\n constructor(identifierKey: string) {\n super(`Missing required identifier '${identifierKey}' in the JWT`);\n this.identifierKey = identifierKey;\n }\n}\n\nexport class UserWalletAlreadyCreatedError extends SmartWalletSDKError {\n public readonly code = SmartWalletErrors.ERROR_USER_WALLET_ALREADY_CREATED;\n\n constructor(userId: string) {\n super(`The user with userId ${userId.toString()} already has a wallet created for this project`);\n }\n}\n\nexport class OutOfCreditsError extends SmartWalletSDKError {\n constructor(message?: string) {\n super(\n \"You've run out of Crossmint API credits. Visit https://docs.crossmint.com/docs/errors for more information\",\n undefined,\n SmartWalletErrors.ERROR_OUT_OF_CREDITS\n );\n }\n}\n\nexport class ConfigError extends SmartWalletSDKError {\n constructor(message: string) {\n super(message, undefined, SmartWalletErrors.ERROR_WALLET_CONFIG);\n }\n}\n\nexport class AdminAlreadyUsedError extends ConfigError {\n public readonly code = SmartWalletErrors.ERROR_ADMIN_SIGNER_ALREADY_USED;\n constructor() {\n super(\"This signer was already used to create another wallet. Please use a different signer.\");\n }\n}\n\nexport class NonCustodialWalletsNotEnabledError extends ConfigError {\n constructor() {\n super(\"Non-custodial wallets are not enabled for this project\");\n }\n}\n","import { v4 as uuidv4 } from \"uuid\";\n\nimport { logError, logInfo } from \"../services/logging\";\nimport { SCW_SERVICE } from \"./constants\";\nimport { isLocalhost } from \"./helpers\";\n\nexport class LoggerWrapper {\n constructor(className: string, private extraInfo = {}, private logIdempotencyKey = uuidv4()) {\n return new Proxy(this, {\n get: (target: any, propKey: PropertyKey, receiver: any) => {\n const origMethod = target[propKey];\n const identifierTag = `[${SCW_SERVICE} - ${className} - ${String(propKey)}]`;\n\n if (typeof origMethod === \"function\") {\n return (...args: any[]) => {\n this.logInput(args, identifierTag);\n\n const result = origMethod.apply(target, args);\n if (result instanceof Promise) {\n return result\n .then((res: any) => {\n this.logOutput(res, identifierTag);\n return res;\n })\n .catch((err: any) => {\n this.logError(err, identifierTag);\n throw err;\n });\n } else {\n this.logOutput(result, identifierTag);\n return result;\n }\n };\n }\n return Reflect.get(target, propKey, receiver);\n },\n });\n }\n\n private logInput(args: object, identifierTag: string) {\n logInfoIfNotInLocalhost(\n `${identifierTag} input - ${beautify(args)} - extra_info - ${beautify(\n this.extraInfo\n )} - log_idempotency_key - ${this.logIdempotencyKey}`,\n { args, ...this.extraInfo, logIdempotencyKey: this.logIdempotencyKey }\n );\n }\n\n private logOutput(res: object, identifierTag: string) {\n logInfoIfNotInLocalhost(\n `${identifierTag} output - ${beautify(res)} - extra_info - ${beautify(\n this.extraInfo\n )} - log_idempotency_key - ${this.logIdempotencyKey}`,\n {\n res,\n ...this.extraInfo,\n logIdempotencyKey: this.logIdempotencyKey,\n }\n );\n }\n\n private logError(err: object, identifierTag: string) {\n logError(\n `${identifierTag} threw_error - ${err} - extra_info - ${beautify(this.extraInfo)} - log_idempotency_key - ${\n this.logIdempotencyKey\n }`,\n { err, ...this.extraInfo }\n );\n }\n\n protected logPerformance<T>(name: string, cb: () => Promise<T>) {\n return logPerformance(name, cb, this.extraInfo);\n }\n}\n\nexport async function logPerformance<T>(name: string, cb: () => Promise<T>, extraInfo?: object) {\n const start = new Date().getTime();\n const result = await cb();\n const durationInMs = new Date().getTime() - start;\n const args = { durationInMs, ...extraInfo };\n logInfoIfNotInLocalhost(`[${SCW_SERVICE} - ${name} - TIME] - ${beautify(args)}`, { args });\n return result;\n}\n\nexport function logInputOutput<T, A extends any[]>(fn: (...args: A) => T, functionName: string): (...args: A) => T {\n return function (this: any, ...args: A): T {\n const identifierTag = `[${SCW_SERVICE} - function: ${functionName}]`;\n logInfoIfNotInLocalhost(`${identifierTag} input: ${beautify(args)}`, { args });\n\n try {\n const result = fn.apply(this, args);\n if (result instanceof Promise) {\n return result\n .then((res) => {\n logInfoIfNotInLocalhost(`${identifierTag} output: ${beautify(res)}`, { res });\n return res;\n })\n .catch((err) => {\n logError(`${identifierTag} threw_error: ${beautify(err)}`, { err });\n throw err;\n }) as T;\n } else {\n logInfoIfNotInLocalhost(`${identifierTag} output: ${beautify(result)}`, { res: result });\n return result;\n }\n } catch (err) {\n logError(`${identifierTag} threw_error: ${beautify(err)}`, { err });\n throw err;\n }\n };\n}\n\nfunction beautify(json: any) {\n try {\n return json != null ? JSON.stringify(json, null, 2) : json;\n } catch (error) {\n return stringifyAvoidingCircular(json);\n }\n}\n\nfunction stringifyAvoidingCircular(json: any) {\n // stringify an object, avoiding circular structures\n // https://stackoverflow.com/a/31557814\n const simpleObject: { [key: string]: any } = {};\n for (const prop in json) {\n if (!Object.prototype.hasOwnProperty.call(json, prop)) {\n continue;\n }\n if (typeof json[prop] == \"object\") {\n continue;\n }\n if (typeof json[prop] == \"function\") {\n continue;\n }\n simpleObject[prop] = json[prop];\n }\n return JSON.stringify(simpleObject, null, 2); // returns cleaned up JSON\n}\n\nfunction logInfoIfNotInLocalhost(message: string, context?: object) {\n if (isLocalhost()) {\n console.log(message);\n return;\n }\n logInfo(message, context);\n}\n\nexport function errorToJSON(error: Error | unknown) {\n const errorToLog = error instanceof Error ? error : { message: \"Unknown error\", name: \"Unknown error\" };\n\n if (!(errorToLog instanceof Error) && (errorToLog as any).constructor?.name !== \"SyntheticBaseEvent\") {\n logError(\"ERROR_TO_JSON_FAILED\", { error: errorToLog });\n throw new Error(\"[errorToJSON] err is not instanceof Error nor SyntheticBaseEvent\");\n }\n\n return JSON.parse(JSON.stringify(errorToLog, Object.getOwnPropertyNames(errorToLog)));\n}\n","import { Abi, Account, Address, erc20Abi, erc721Abi } from \"viem\";\n\nimport erc1155Abi from \"../ABI/ERC1155.json\";\nimport type { ERC20TransferType, SFTTransferType, TransferType } from \"../types/Tokens\";\n\ntype TransferInputParams = {\n from: Account;\n contract: Address;\n to: Address;\n config: TransferType;\n};\n\ntype TransferSimulationParams = {\n account: Account;\n address: Address;\n abi: Abi;\n functionName: string;\n args: any[];\n tokenId?: string;\n};\n\nexport function transferParams({ contract, config, from, to }: TransferInputParams): TransferSimulationParams {\n switch (config.token.type) {\n case \"ft\": {\n return {\n account: from,\n address: contract,\n abi: erc20Abi,\n functionName: \"transfer\",\n args: [to, (config as ERC20TransferType).amount],\n };\n }\n case \"sft\": {\n return {\n account: from,\n address: contract,\n abi: erc1155Abi as Abi,\n functionName: \"safeTransferFrom\",\n args: [from.address, to, config.token.tokenId, (config as SFTTransferType).quantity, \"0x00\"],\n tokenId: config.token.tokenId,\n };\n }\n case \"nft\": {\n return {\n account: from,\n address: contract,\n abi: erc721Abi,\n functionName: \"safeTransferFrom\",\n args: [from.address, to, config.token.tokenId],\n tokenId: config.token.tokenId,\n };\n }\n }\n}\n","[\n {\n \"inputs\": [\n {\n \"internalType\": \"string\",\n \"name\": \"uri_\",\n \"type\": \"string\"\n }\n ],\n \"stateMutability\": \"nonpayable\",\n \"type\": \"constructor\"\n },\n {\n \"anonymous\": false,\n \"inputs\": [\n {\n \"indexed\": true,\n \"internalType\": \"address\",\n \"name\": \"account\",\n \"type\": \"address\"\n },\n {\n \"indexed\": true,\n \"internalType\": \"address\",\n \"name\": \"operator\",\n \"type\": \"address\"\n },\n {\n \"indexed\": false,\n \"internalType\": \"bool\",\n \"name\": \"approved\",\n \"type\": \"bool\"\n }\n ],\n \"name\": \"ApprovalForAll\",\n \"type\": \"event\"\n },\n {\n \"anonymous\": false,\n \"inputs\": [\n {\n \"indexed\": true,\n \"internalType\": \"address\",\n \"name\": \"operator\",\n \"type\": \"address\"\n },\n {\n \"indexed\": true,\n \"internalType\": \"address\",\n \"name\": \"from\",\n \"type\": \"address\"\n },\n {\n \"indexed\": true,\n \"internalType\": \"address\",\n \"name\": \"to\",\n \"type\": \"address\"\n },\n {\n \"indexed\": false,\n \"internalType\": \"uint256[]\",\n \"name\": \"ids\",\n \"type\": \"uint256[]\"\n },\n {\n \"indexed\": false,\n \"internalType\": \"uint256[]\",\n \"name\": \"values\",\n \"type\": \"uint256[]\"\n }\n ],\n \"name\": \"TransferBatch\",\n \"type\": \"event\"\n },\n {\n \"anonymous\": false,\n \"inputs\": [\n {\n \"indexed\": true,\n \"internalType\": \"address\",\n \"name\": \"operator\",\n \"type\": \"address\"\n },\n {\n \"indexed\": true,\n \"internalType\": \"address\",\n \"name\": \"from\",\n \"type\": \"address\"\n },\n {\n \"indexed\": true,\n \"internalType\": \"address\",\n \"name\": \"to\",\n \"type\": \"address\"\n },\n {\n \"indexed\": false,\n \"internalType\": \"uint256\",\n \"name\": \"id\",\n \"type\": \"uint256\"\n },\n {\n \"indexed\": false,\n \"internalType\": \"uint256\",\n \"name\": \"value\",\n \"type\": \"uint256\"\n }\n ],\n \"name\": \"TransferSingle\",\n \"type\": \"event\"\n },\n {\n \"anonymous\": false,\n \"inputs\": [\n {\n \"indexed\": false,\n \"internalType\": \"string\",\n \"name\": \"value\",\n \"type\": \"string\"\n },\n {\n \"indexed\": true,\n \"internalType\": \"uint256\",\n \"name\": \"id\",\n \"type\": \"uint256\"\n }\n ],\n \"name\": \"URI\",\n \"type\": \"event\"\n },\n {\n \"inputs\": [\n {\n \"internalType\": \"address\",\n \"name\": \"account\",\n \"type\": \"address\"\n },\n {\n \"internalType\": \"uint256\",\n \"name\": \"id\",\n \"type\": \"uint256\"\n }\n ],\n \"name\": \"balanceOf\",\n \"outputs\": [\n {\n \"internalType\": \"uint256\",\n \"name\": \"\",\n \"type\": \"uint256\"\n }\n ],\n \"stateMutability\": \"view\",\n \"type\": \"function\"\n },\n {\n \"inputs\": [\n {\n \"internalType\": \"address[]\",\n \"name\": \"accounts\",\n \"type\": \"address[]\"\n },\n {\n \"internalType\": \"uint256[]\",\n \"name\": \"ids\",\n \"type\": \"uint256[]\"\n }\n ],\n \"name\": \"balanceOfBatch\",\n \"outputs\": [\n {\n \"internalType\": \"uint256[]\",\n \"name\": \"\",\n \"type\": \"uint256[]\"\n }\n ],\n \"stateMutability\": \"view\",\n \"type\": \"function\"\n },\n {\n \"inputs\": [\n {\n \"internalType\": \"address\",\n \"name\": \"account\",\n \"type\": \"address\"\n },\n {\n \"internalType\": \"address\",\n \"name\": \"operator\",\n \"type\": \"address\"\n }\n ],\n \"name\": \"isApprovedForAll\",\n \"outputs\": [\n {\n \"internalType\": \"bool\",\n \"name\": \"\",\n \"type\": \"bool\"\n }\n ],\n \"stateMutability\": \"view\",\n \"type\": \"function\"\n },\n {\n \"inputs\": [\n {\n \"internalType\": \"address\",\n \"name\": \"from\",\n \"type\": \"address\"\n },\n {\n \"internalType\": \"address\",\n \"name\": \"to\",\n \"type\": \"address\"\n },\n {\n \"internalType\": \"uint256[]\",\n \"name\": \"ids\",\n \"type\": \"uint256[]\"\n },\n {\n \"internalType\": \"uint256[]\",\n \"name\": \"amounts\",\n \"type\": \"uint256[]\"\n },\n {\n \"internalType\": \"bytes\",\n \"name\": \"data\",\n \"type\": \"bytes\"\n }\n ],\n \"name\": \"safeBatchTransferFrom\",\n \"outputs\": [],\n \"stateMutability\": \"nonpayable\",\n \"type\": \"function\"\n },\n {\n \"inputs\": [\n {\n \"internalType\": \"address\",\n \"name\": \"from\",\n \"type\": \"address\"\n },\n {\n \"internalType\": \"address\",\n \"name\": \"to\",\n \"type\": \"address\"\n },\n {\n \"internalType\": \"uint256\",\n \"name\": \"id\",\n \"type\": \"uint256\"\n },\n {\n \"internalType\": \"uint256\",\n \"name\": \"amount\",\n \"type\": \"uint256\"\n },\n {\n \"internalType\": \"bytes\",\n \"name\": \"data\",\n \"type\": \"bytes\"\n }\n ],\n \"name\": \"safeTransferFrom\",\n \"outputs\": [],\n \"stateMutability\": \"nonpayable\",\n \"type\": \"function\"\n },\n {\n \"inputs\": [\n {\n \"internalType\": \"address\",\n \"name\": \"operator\",\n \"type\": \"address\"\n },\n {\n \"internalType\": \"bool\",\n \"name\": \"approved\",\n \"type\": \"bool\"\n }\n ],\n \"name\": \"setApprovalForAll\",\n \"outputs\": [],\n \"stateMutability\": \"nonpayable\",\n \"type\": \"function\"\n },\n {\n \"inputs\": [\n {\n \"internalType\": \"bytes4\",\n \"name\": \"interfaceId\",\n \"type\": \"bytes4\"\n }\n ],\n \"name\": \"supportsInterface\",\n \"outputs\": [\n {\n \"internalType\": \"bool\",\n \"name\": \"\",\n \"type\": \"bool\"\n }\n ],\n \"stateMutability\": \"view\",\n \"type\": \"function\"\n },\n {\n \"inputs\": [\n {\n \"internalType\": \"uint256\",\n \"name\": \"\",\n \"type\": \"uint256\"\n }\n ],\n \"name\": \"uri\",\n \"outputs\": [\n {\n \"internalType\": \"string\",\n \"name\": \"\",\n \"type\": \"string\"\n }\n ],\n \"stateMutability\": \"view\",\n \"type\": \"function\"\n }\n]\n","import { stringify } from \"viem\";\n\nimport { EVMBlockchainIncludingTestnet, validateAPIKey } from \"@crossmint/common-sdk-base\";\n\nimport { CrossmintWalletService } from \"./api/CrossmintWalletService\";\nimport type { EVMSmartWallet } from \"./blockchain/wallets\";\nimport { ClientDecorator } from \"./blockchain/wallets/clientDecorator\";\nimport { SmartWalletService } from \"./blockchain/wallets/service\";\nimport { SmartWalletSDKError } from \"./error\";\nimport { ErrorProcessor } from \"./error/processor\";\nimport { DatadogProvider } from \"./services/logging/DatadogProvider\";\nimport type { SmartWalletSDKInitParams, UserParams, WalletParams } from \"./types/Config\";\nimport { isClient } from \"./utils/environment\";\nimport { LoggerWrapper, logPerformance } from \"./utils/log\";\n\nexport class SmartWalletSDK extends LoggerWrapper {\n private constructor(\n private readonly smartWalletService: SmartWalletService,\n private readonly errorProcessor: ErrorProcessor\n ) {\n super(\"SmartWalletSDK\");\n }\n\n /**\n * Initializes the SDK with the **client side** API key obtained from the Crossmint console.\n * @throws error if the api key is not formatted correctly.\n */\n static init({ clientApiKey }: SmartWalletSDKInitParams): SmartWalletSDK {\n if (!isClient()) {\n throw new SmartWalletSDKError(\"Smart Wallet SDK should only be used client side.\");\n }\n\n const validationResult = validateAPIKey(clientApiKey);\n if (!validationResult.isValid) {\n throw new Error(\"API key invalid\");\n }\n\n const crossmintService = new CrossmintWalletService(clientApiKey);\n const errorProcessor = new ErrorProcessor(new DatadogProvider());\n return new SmartWalletSDK(\n new SmartWalletService(crossmintService, new ClientDecorator(errorProcessor)),\n errorProcessor\n );\n }\n\n /**\n * Retrieves or creates a wallet for the specified user.\n * The default configuration is a `PasskeySigner` with the name, which is displayed to the user during creation or signing prompts, derived from the provided jwt.\n *\n * Example using the default passkey signer:\n * ```ts\n * const wallet = await smartWalletSDK.getOrCreateWallet({ jwt: \"xxx\" }, \"base\");\n * ```\n */\n async getOrCreateWallet(\n user: UserParams,\n chain: EVMBlockchainIncludingTestnet,\n walletParams: WalletParams = { signer: { type: \"PASSKEY\" } }\n ): Promise<EVMSmartWallet> {\n return logPerformance(\n \"GET_OR_CREATE_WALLET\",\n async () => {\n try {\n return await this.smartWalletService.getOrCreate(user, chain, walletParams);\n } catch (error: any) {\n throw this.errorProcessor.map(\n error,\n new SmartWalletSDKError(`Wallet creation failed: ${error.message}.`, stringify(error))\n );\n }\n },\n { user, chain }\n );\n }\n}\n","import { validateAPIKey } from \"@crossmint/common-sdk-base\";\n\nimport { CrossmintServiceError } from \"../error\";\nimport { CROSSMINT_DEV_URL, CROSSMINT_PROD_URL, CROSSMINT_STG_URL } from \"../utils/constants\";\nimport { LoggerWrapper, logPerformance } from \"../utils/log\";\nimport { APIErrorService } from \"./APIErrorService\";\n\nexport abstract class BaseCrossmintService extends LoggerWrapper {\n public crossmintAPIHeaders: Record<string, string>;\n protected crossmintBaseUrl: string;\n protected apiErrorService: APIErrorService;\n private static urlMap: Record<string, string> = {\n development: CROSSMINT_DEV_URL,\n staging: CROSSMINT_STG_URL,\n production: CROSSMINT_PROD_URL,\n };\n\n constructor(apiKey: string) {\n super(\"BaseCrossmintService\");\n const result = validateAPIKey(apiKey);\n if (!result.isValid) {\n throw new Error(\"API key invalid\");\n }\n this.crossmintAPIHeaders = {\n accept: \"application/json\",\n \"content-type\": \"application/json\",\n \"x-api-key\": apiKey,\n };\n this.crossmintBaseUrl = this.getUrlFromEnv(result.environment);\n this.apiErrorService = new APIErrorService();\n }\n\n protected async fetchCrossmintAPI(\n endpoint: string,\n options: { body?: string; method: string } = { method: \"GET\" },\n onServerErrorMessage: string,\n authToken?: string\n ) {\n return logPerformance(\n \"FETCH_CROSSMINT_API\",\n async () => {\n const url = `${this.crossmintBaseUrl}/${endpoint}`;\n const { body, method } = options;\n\n let response: Response;\n try {\n response = await fetch(url, {\n body,\n method,\n headers: {\n ...this.crossmintAPIHeaders,\n ...(authToken != null && {\n Authorization: `Bearer ${authToken}`,\n }),\n },\n });\n } catch (error) {\n throw new CrossmintServiceError(`Error fetching Crossmint API: ${error}`);\n }\n\n if (!response.ok) {\n await this.apiErrorService.throwErrorFromResponse({\n response,\n onServerErrorMessage,\n });\n }\n\n return await response.json();\n },\n { endpoint }\n );\n }\n\n protected getUrlFromEnv(environment: string) {\n const url = BaseCrossmintService.urlMap[environment];\n if (!url) {\n console.log(\" CrossmintService.urlMap: \", BaseCrossmintService.urlMap);\n throw new Error(`URL not found for environment: ${environment}`);\n }\n return url;\n }\n}\n","import {\n AdminAlreadyUsedError,\n CrossmintServiceError,\n JWTDecryptionError,\n JWTExpiredError,\n JWTIdentifierError,\n JWTInvalidError,\n NonCustodialWalletsNotEnabledError,\n OutOfCreditsError,\n SmartWalletSDKError,\n UserWalletAlreadyCreatedError,\n} from \"@/error\";\n\nexport type CrossmintAPIErrorCodes =\n | \"ERROR_JWT_INVALID\"\n | \"ERROR_JWT_DECRYPTION\"\n | \"ERROR_JWT_IDENTIFIER\"\n | \"ERROR_JWT_EXPIRED\"\n | \"ERROR_USER_WALLET_ALREADY_CREATED\"\n | \"ERROR_ADMIN_SIGNER_ALREADY_USED\"\n | \"ERROR_PROJECT_NONCUSTODIAL_WALLETS_NOT_ENABLED\";\n\nexport class APIErrorService {\n constructor(\n private errors: Partial<Record<CrossmintAPIErrorCodes, (apiResponse: any) => SmartWalletSDKError>> = {\n ERROR_JWT_INVALID: () => new JWTInvalidError(),\n ERROR_JWT_DECRYPTION: () => new JWTDecryptionError(),\n ERROR_JWT_EXPIRED: ({ expiredAt }: { expiredAt: string }) => new JWTExpiredError(new Date(expiredAt)),\n ERROR_JWT_IDENTIFIER: ({ identifierKey }: { identifierKey: string }) =>\n new JWTIdentifierError(identifierKey),\n ERROR_USER_WALLET_ALREADY_CREATED: ({ userId }: { userId: string }) =>\n new UserWalletAlreadyCreatedError(userId),\n ERROR_ADMIN_SIGNER_ALREADY_USED: () => new AdminAlreadyUsedError(),\n ERROR_PROJECT_NONCUSTODIAL_WALLETS_NOT_ENABLED: () => new NonCustodialWalletsNotEnabledError(),\n }\n ) {}\n\n async throwErrorFromResponse({\n response,\n onServerErrorMessage,\n }: {\n response: Response;\n onServerErrorMessage: string;\n }) {\n if (response.ok) {\n return;\n }\n\n if (response.status >= 500) {\n throw new CrossmintServiceError(onServerErrorMessage, response.status);\n }\n\n if (response.status === 402) {\n throw new OutOfCreditsError();\n }\n\n try {\n const body = await response.json();\n const code = body.code as CrossmintAPIErrorCodes | undefined;\n if (code != null && this.errors[code] != null) {\n throw this.errors[code](body);\n }\n if (body.message != null) {\n throw new CrossmintServiceError(body.message, response.status);\n }\n } catch (e) {\n console.error(\"Error parsing response\", e);\n }\n\n throw new CrossmintServiceError(await response.text(), response.status);\n }\n}\n","import { SignerData, StoreSmartWalletParams } from \"@/types/API\";\nimport type { UserParams } from \"@/types/Config\";\nimport { API_VERSION } from \"@/utils/constants\";\n\nimport type { EVMBlockchainIncludingTestnet } from \"@crossmint/common-sdk-base\";\n\nimport { BaseCrossmintService } from \"./BaseCrossmintService\";\n\nexport { EVMBlockchainIncludingTestnet } from \"@crossmint/common-sdk-base\";\n\nexport class CrossmintWalletService extends BaseCrossmintService {\n async idempotentCreateSmartWallet(user: UserParams, input: StoreSmartWalletParams) {\n return this.fetchCrossmintAPI(\n `${API_VERSION}/sdk/smart-wallet`,\n { method: \"PUT\", body: JSON.stringify(input) },\n \"Error creating abstract wallet. Please contact support\",\n user.jwt\n );\n }\n\n async getSmartWalletConfig(\n user: UserParams,\n chain: EVMBlockchainIncludingTestnet\n ): Promise<{\n kernelVersion: string;\n entryPointVersion: string;\n userId: string;\n signers: { signerData: SignerData }[];\n smartContractWalletAddress?: string;\n }> {\n return this.fetchCrossmintAPI(\n `${API_VERSION}/sdk/smart-wallet/config?chain=${chain}`,\n { method: \"GET\" },\n \"Error getting smart wallet version configuration. Please contact support\",\n user.jwt\n );\n }\n\n async fetchNFTs(address: string, chain: EVMBlockchainIncludingTestnet) {\n return this.fetchCrossmintAPI(\n `v1-alpha1/wallets/${chain}:${address}/nfts`,\n { method: \"GET\" },\n `Error fetching NFTs for wallet: ${address}`\n );\n }\n\n public getPasskeyServerUrl(): string {\n return this.crossmintBaseUrl + \"/internal/passkeys\";\n }\n}\n","import { EVMBlockchainIncludingTestnet } from \"@crossmint/common-sdk-base\";\n\nfunction isPolygonCDK(chain: EVMBlockchainIncludingTestnet) {\n const polygonCDKchains: EVMBlockchainIncludingTestnet[] = [\n EVMBlockchainIncludingTestnet.ZKYOTO,\n EVMBlockchainIncludingTestnet.ZKATANA,\n EVMBlockchainIncludingTestnet.ASTAR_ZKEVM,\n EVMBlockchainIncludingTestnet.HYPERSONIC_TESTNET,\n ];\n return polygonCDKchains.includes(chain);\n}\n\nexport function usesGelatoBundler(chain: EVMBlockchainIncludingTestnet) {\n return isPolygonCDK(chain);\n}\n","import { SmartWalletSDKError } from \"@/error\";\nimport { ErrorProcessor } from \"@/error/processor\";\nimport { logInfo } from \"@/services/logging\";\nimport { usesGelatoBundler } from \"@/utils/blockchain\";\nimport { logPerformance } from \"@/utils/log\";\nimport type { SmartAccountClient } from \"permissionless\";\nimport type { EntryPoint } from \"permissionless/types/entrypoint\";\nimport { stringify } from \"viem\";\n\nimport { EVMBlockchainIncludingTestnet } from \"@crossmint/common-sdk-base\";\n\nconst transactionMethods = [\n \"sendTransaction\",\n \"writeContract\",\n \"sendUserOperation\",\n] as const satisfies readonly (keyof SmartAccountClient<EntryPoint>)[];\n\nconst signingMethods = [\n \"signMessage\",\n \"signTypedData\",\n] as const satisfies readonly (keyof SmartAccountClient<EntryPoint>)[];\n\ntype TxnMethod = (typeof transactionMethods)[number];\ntype SignMethod = (typeof signingMethods)[number];\n\nfunction isTxnMethod(method: string): method is TxnMethod {\n return transactionMethods.includes(method as any);\n}\n\nfunction isSignMethod(method: string): method is SignMethod {\n return signingMethods.includes(method as any);\n}\n\n/**\n * A decorator class for SmartAccountClient instances. It enhances the client with:\n * - Error handling & logging.\n * - Performance metrics.\n * - Automatic formatting of transactions for Gelato bundler compatibility.\n * */\nexport class ClientDecorator {\n constructor(private readonly errorProcessor: ErrorProcessor) {}\n\n public decorate<Client extends SmartAccountClient<EntryPoint>>({\n crossmintChain,\n smartAccountClient,\n }: {\n crossmintChain: EVMBlockchainIncludingTestnet;\n smartAccountClient: Client;\n }): Client {\n return new Proxy(smartAccountClient, {\n get: (target, prop, receiver) => {\n const originalMethod = Reflect.get(target, prop, receiver);\n\n if (\n typeof originalMethod !== \"function\" ||\n typeof prop !== \"string\" ||\n !(isSignMethod(prop) || isTxnMethod(prop))\n ) {\n return originalMethod;\n }\n\n return (...args: any[]) =>\n logPerformance(`CrossmintSmartWallet.${prop}`, () =>\n this.execute(target, prop, originalMethod, args, crossmintChain)\n );\n },\n }) as Client;\n }\n\n private async execute<M extends TxnMethod | SignMethod>(\n target: SmartAccountClient<EntryPoint>,\n prop: M,\n // eslint-disable-next-line @typescript-eslint/ban-types\n originalMethod: Function,\n args: any[],\n crossmintChain: EVMBlockchainIncludingTestnet\n ) {\n try {\n logInfo(`[CrossmintSmartWallet.${prop}] - params: ${stringify(args)}`);\n const processed = isTxnMethod(prop) ? this.processTxnArgs(prop, crossmintChain, args) : args;\n return await originalMethod.call(target, ...processed);\n } catch (error: any) {\n const description = isTxnMethod(prop) ? \"signing\" : \"sending transaction\";\n throw this.errorProcessor.map(\n error,\n new SmartWalletSDKError(`Error ${description}: ${error.message}`, stringify(error))\n );\n }\n }\n\n private processTxnArgs(prop: TxnMethod, crossmintChain: EVMBlockchainIncludingTestnet, args: any[]): any[] {\n if (prop === \"sendUserOperation\") {\n const [{ userOperation, middleware, account }] = args as Parameters<\n SmartAccountClient<EntryPoint>[\"sendUserOperation\"]\n >;\n return [\n {\n middleware,\n account,\n userOperation: this.addGelatoBundlerProperties(crossmintChain, userOperation),\n },\n ...args.slice(1),\n ];\n }\n\n const [txn] = args as\n | Parameters<SmartAccountClient<EntryPoint>[\"sendTransaction\"]>\n | Parameters<SmartAccountClient<EntryPoint>[\"writeContract\"]>;\n\n return [this.addGelatoBundlerProperties(crossmintChain, txn), ...args.slice(1)];\n }\n\n /*\n * Chain that ZD uses Gelato as for bundler require special parameters:\n * https://docs.zerodev.app/sdk/faqs/use-with-gelato#transaction-configuration\n */\n private addGelatoBundlerProperties(\n crossmintChain: EVMBlockchainIncludingTestnet,\n txnParams: { maxFeePerGas?: bigint; maxPriorityFeePerGas?: bigint }\n ) {\n if (usesGelatoBundler(crossmintChain)) {\n return { ...txnParams, maxFeePerGas: \"0x0\" as any, maxPriorityFeePerGas: \"0x0\" as any };\n }\n\n return txnParams;\n }\n}\n","import { PasskeyValidatorContractVersion } from \"@zerodev/passkey-validator\";\n\nimport { PasskeyValidatorSerializedData, SupportedEntryPointVersion, SupportedKernelVersion } from \"./internal\";\n\nexport type StoreSmartWalletParams = {\n type: string;\n smartContractWalletAddress: string;\n signerData: SignerData;\n sessionKeySignerAddress?: string;\n version: number;\n baseLayer: string;\n chainId: number;\n entryPointVersion: SupportedEntryPointVersion;\n kernelVersion: SupportedKernelVersion;\n};\n\nexport type SignerData = EOASignerData | PasskeySignerData;\n\nexport interface EOASignerData {\n eoaAddress: string;\n type: \"eoa\";\n}\n\nexport type PasskeySignerData = PasskeyValidatorSerializedData & {\n passkeyName: string;\n validatorContractVersion: PasskeyValidatorContractVersion;\n domain: string;\n type: \"passkeys\";\n};\n\nexport type PasskeyDisplay = Pick<PasskeySignerData, \"type\" | \"passkeyName\" | \"pubKeyX\" | \"pubKeyY\">;\nexport type SignerDisplay = EOASignerData | PasskeyDisplay;\nexport function displayPasskey(data: PasskeySignerData): PasskeyDisplay {\n return {\n pubKeyX: data.pubKeyX,\n pubKeyY: data.pubKeyY,\n passkeyName: data.passkeyName,\n type: \"passkeys\",\n };\n}\n","import { type SignerData, displayPasskey } from \"@/types/API\";\nimport { equalsIgnoreCase } from \"@/utils/helpers\";\nimport { type KernelSmartAccount, createKernelAccountClient } from \"@zerodev/sdk\";\nimport { ENTRYPOINT_ADDRESS_V06, ENTRYPOINT_ADDRESS_V07 } from \"permissionless\";\nimport type { EntryPoint } from \"permissionless/types/entrypoint\";\nimport { Address, type HttpTransport, createPublicClient, getAddress, http } from \"viem\";\n\nimport { blockchainToChainId } from \"@crossmint/common-sdk-base\";\n\nimport type { CrossmintWalletService, EVMBlockchainIncludingTestnet } from \"../../api/CrossmintWalletService\";\nimport {\n AdminMismatchError,\n CrossmintServiceError,\n SmartWalletSDKError,\n UserWalletAlreadyCreatedError,\n} from \"../../error\";\nimport type { EntryPointDetails, UserParams, WalletParams } from \"../../types/Config\";\nimport {\n SUPPORTED_ENTRYPOINT_VERSIONS,\n SUPPORTED_KERNEL_VERSIONS,\n SmartWalletClient,\n type SupportedKernelVersion,\n type WalletCreationParams,\n isSupportedEntryPointVersion,\n isSupportedKernelVersion,\n} from \"../../types/internal\";\nimport { CURRENT_VERSION, ZERO_DEV_TYPE } from \"../../utils/constants\";\nimport { getBundlerRPC, getViemNetwork } from \"../BlockchainNetworks\";\nimport { EVMSmartWallet } from \"./EVMSmartWallet\";\nimport { ClientDecorator } from \"./clientDecorator\";\nimport { EOAAccountService, type EOAWalletParams } from \"./eoa\";\nimport { PasskeyAccountService, isPasskeyParams } from \"./passkey\";\nimport { paymasterMiddleware, usePaymaster } from \"./paymaster\";\n\nexport class SmartWalletService {\n constructor(\n private readonly crossmintWalletService: CrossmintWalletService,\n private readonly clientDecorator: ClientDecorator,\n private readonly accountFactory = new AccountFactory(\n new EOAAccountService(),\n new PasskeyAccountService(crossmintWalletService)\n )\n ) {}\n\n public async getOrCreate(\n user: UserParams,\n chain: EVMBlockchainIncludingTestnet,\n walletParams: WalletParams\n ): Promise<EVMSmartWallet> {\n const { entryPoint, kernelVersion, existingSignerConfig, smartContractWalletAddress, userId } =\n await this.fetchConfig(user, chain);\n const publicClient = createPublicClient({ transport: http(getBundlerRPC(chain)) });\n\n const { account, signerData } = await this.accountFactory.get(\n {\n chain,\n walletParams,\n publicClient,\n user: { ...user, id: userId },\n entryPoint,\n kernelVersion,\n },\n existingSignerConfig\n );\n\n if (smartContractWalletAddress != null && !equalsIgnoreCase(smartContractWalletAddress, account.address)) {\n throw new UserWalletAlreadyCreatedError(userId);\n }\n\n if (existingSignerConfig == null) {\n await this.crossmintWalletService.idempotentCreateSmartWallet(user, {\n type: ZERO_DEV_TYPE,\n smartContractWalletAddress: account.address,\n signerData: signerData,\n version: CURRENT_VERSION,\n baseLayer: \"evm\",\n chainId: blockchainToChainId(chain),\n entryPointVersion: entryPoint.version,\n kernelVersion,\n });\n }\n\n const kernelAccountClient: SmartWalletClient = createKernelAccountClient({\n account,\n chain: getViemNetwork(chain),\n entryPoint: account.entryPoint,\n bundlerTransport: http(getBundlerRPC(chain)),\n ...(usePaymaster(chain) && paymasterMiddleware({ entryPoint: account.entryPoint, chain })),\n });\n\n const smartAccountClient = this.clientDecorator.decorate({\n crossmintChain: chain,\n smartAccountClient: kernelAccountClient,\n });\n\n return new EVMSmartWallet(this.crossmintWalletService, smartAccountClient, publicClient, chain);\n }\n\n private async fetchConfig(\n user: UserParams,\n chain: EVMBlockchainIncludingTestnet\n ): Promise<{\n entryPoint: EntryPointDetails;\n kernelVersion: SupportedKernelVersion;\n userId: string;\n existingSignerConfig?: SignerData;\n smartContractWalletAddress?: Address;\n }> {\n const { entryPointVersion, kernelVersion, signers, smartContractWalletAddress, userId } =\n await this.crossmintWalletService.getSmartWalletConfig(user, chain);\n\n if (!isSupportedKernelVersion(kernelVersion)) {\n throw new SmartWalletSDKError(\n `Unsupported kernel version. Supported versions: ${SUPPORTED_KERNEL_VERSIONS.join(\n \", \"\n )}. Version used: ${kernelVersion}, Please contact support`\n );\n }\n\n if (!isSupportedEntryPointVersion(entryPointVersion)) {\n throw new SmartWalletSDKError(\n `Unsupported entry point version. Supported versions: ${SUPPORTED_ENTRYPOINT_VERSIONS.join(\n \", \"\n )}. Version used: ${entryPointVersion}. Please contact support`\n );\n }\n\n if (\n (entryPointVersion === \"v0.7\" && kernelVersion.startsWith(\"0.2\")) ||\n (entryPointVersion === \"v0.6\" && kernelVersion.startsWith(\"0.3\"))\n ) {\n throw new SmartWalletSDKError(\n `Unsupported combination: entryPoint ${entryPointVersion} and kernel version ${kernelVersion}. Please contact support`\n );\n }\n\n return {\n entryPoint: {\n version: entryPointVersion,\n address: entryPointVersion === \"v0.6\" ? ENTRYPOINT_ADDRESS_V06 : ENTRYPOINT_ADDRESS_V07,\n },\n kernelVersion,\n userId,\n existingSignerConfig: this.getSigner(signers),\n smartContractWalletAddress:\n smartContractWalletAddress != null ? getAddress(smartContractWalletAddress) : undefined,\n };\n }\n\n private getSigner(signers: any[]): SignerData | undefined {\n if (signers.length === 0) {\n return undefined;\n }\n\n if (signers.length > 1) {\n throw new CrossmintServiceError(\"Invalid wallet signer configuration. Please contact support\");\n }\n\n return signers[0].signerData;\n }\n}\n\nclass AccountFactory {\n constructor(private readonly eoa: EOAAccountService, private readonly passkey: PasskeyAccountService) {}\n\n public get(\n params: WalletCreationParams,\n existingSignerConfig?: SignerData\n ): Promise<{\n signerData: SignerData;\n account: KernelSmartAccount<EntryPoint, HttpTransport>;\n }> {\n if (isPasskeyParams(params)) {\n if (existingSignerConfig != null && existingSignerConfig?.type !== \"passkeys\") {\n throw new AdminMismatchError(\n `Cannot create wallet with passkey signer for user '${params.user.id}', they have an existing wallet with eoa signer '${existingSignerConfig.eoaAddress}.'`,\n existingSignerConfig\n );\n }\n\n return this.passkey.get(params, existingSignerConfig);\n }\n\n if (existingSignerConfig != null && existingSignerConfig?.type !== \"eoa\") {\n throw new AdminMismatchError(\n `Cannot create wallet with eoa signer for user '${params.user.id}', they already have a wallet with a passkey named '${existingSignerConfig.passkeyName}' as it's signer.`,\n displayPasskey(existingSignerConfig)\n );\n }\n\n return this.eoa.get(params as EOAWalletParams, existingSignerConfig);\n }\n}\n","import type { KernelSmartAccount } from \"@zerodev/sdk\";\nimport type { SmartAccountClient } from \"permissionless\";\nimport type { SmartAccount } from \"permissionless/accounts\";\nimport type { EntryPoint } from \"permissionless/types/entrypoint\";\nimport type { Chain, Hex, HttpTransport, PublicClient } from \"viem\";\n\nimport type { EVMBlockchainIncludingTestnet } from \"@crossmint/common-sdk-base\";\n\nimport type { SignerData } from \"./API\";\nimport type { EntryPointDetails, UserParams, WalletParams } from \"./Config\";\n\nexport const SUPPORTED_KERNEL_VERSIONS = [\"0.3.1\", \"0.3.0\", \"0.2.4\"] as const;\nexport type SupportedKernelVersion = (typeof SUPPORTED_KERNEL_VERSIONS)[number];\n\nexport function isSupportedKernelVersion(version: string): version is SupportedKernelVersion {\n return SUPPORTED_KERNEL_VERSIONS.includes(version as any);\n}\n\nexport const SUPPORTED_ENTRYPOINT_VERSIONS = [\"v0.6\", \"v0.7\"] as const;\nexport type SupportedEntryPointVersion = (typeof SUPPORTED_ENTRYPOINT_VERSIONS)[number];\n\nexport function isSupportedEntryPointVersion(version: string): version is SupportedEntryPointVersion {\n return SUPPORTED_ENTRYPOINT_VERSIONS.includes(version as any);\n}\n\nexport interface WalletCreationParams {\n user: UserParams & { id: string };\n chain: EVMBlockchainIncludingTestnet;\n publicClient: PublicClient<HttpTransport>;\n walletParams: WalletParams;\n entryPoint: EntryPointDetails;\n kernelVersion: SupportedKernelVersion;\n}\n\nexport interface AccountAndSigner {\n account: KernelSmartAccount<EntryPoint, HttpTransport>;\n signerData: SignerData;\n}\n\nexport type PasskeyValidatorSerializedData = {\n passkeyServerUrl: string;\n entryPoint: Hex;\n validatorAddress: Hex;\n pubKeyX: string;\n pubKeyY: string;\n authenticatorIdHash: Hex;\n authenticatorId: string;\n};\n\nexport type SmartWalletClient = SmartAccountClient<EntryPoint, HttpTransport, Chain, SmartAccount<EntryPoint>>;\n","import {\n BUNDLER_RPC,\n PM_BASE_RPC,\n PM_BASE_SEPOLIA_RPC,\n ZD_AMOY_PROJECT_ID,\n ZD_ARBITRUM_NOVA_PROJECT_ID,\n ZD_ARBITRUM_PROJECT_ID,\n ZD_ARBITRUM_SEPOLIA_PROJECT_ID,\n ZD_ASTAR_PROJECT_ID,\n ZD_BASE_PROJECT_ID,\n ZD_BASE_SEPOLIA_PROJECT_ID,\n ZD_BSC_PROJECT_ID,\n ZD_ETHEREUM_PROJECT_ID,\n ZD_GOERLI_PROJECT_ID,\n ZD_OPTIMISM_PROJECT_ID,\n ZD_OPTIMISM_SEPOLIA_PROJECT_ID,\n ZD_POLYGON_PROJECT_ID,\n ZD_SEPOLIA_PROJECT_ID,\n ZD_ZKATANA_PROJECT_ID,\n ZD_ZKYOTO_PROJECT_ID,\n} from \"@/utils/constants\";\nimport {\n arbitrum,\n arbitrumNova,\n arbitrumSepolia,\n astarZkEVM,\n astarZkyoto,\n base,\n baseSepolia,\n bsc,\n goerli,\n mainnet,\n optimism,\n optimismSepolia,\n polygon,\n polygonAmoy,\n sepolia,\n} from \"viem/chains\";\n\nimport { EVMBlockchainIncludingTestnet } from \"@crossmint/common-sdk-base\";\n\nexport const getZeroDevProjectIdByBlockchain = (chain: EVMBlockchainIncludingTestnet) => {\n const zeroDevProjectId = new Map<EVMBlockchainIncludingTestnet, string | null>([\n [\"ethereum\", ZD_ETHEREUM_PROJECT_ID],\n [\"polygon\", ZD_POLYGON_PROJECT_ID],\n [\"bsc\", ZD_BSC_PROJECT_ID],\n [\"optimism\", ZD_OPTIMISM_PROJECT_ID],\n [\"arbitrum\", ZD_ARBITRUM_PROJECT_ID],\n [\"ethereum-goerli\", ZD_GOERLI_PROJECT_ID],\n [\"ethereum-sepolia\", ZD_SEPOLIA_PROJECT_ID],\n [\"polygon-amoy\", ZD_AMOY_PROJECT_ID],\n [\"zkatana\", ZD_ZKATANA_PROJECT_ID],\n [\"zkyoto\", ZD_ZKYOTO_PROJECT_ID],\n [\"arbitrum-sepolia\", ZD_ARBITRUM_SEPOLIA_PROJECT_ID],\n [\"base-goerli\", null],\n [\"base-sepolia\", ZD_BASE_SEPOLIA_PROJECT_ID],\n [\"bsc-testnet\", null],\n [\"optimism-goerli\", null],\n [\"optimism-sepolia\", ZD_OPTIMISM_SEPOLIA_PROJECT_ID],\n [\"zora-goerli\", null],\n [\"zora-sepolia\", null],\n [\"base\", ZD_BASE_PROJECT_ID],\n [\"zora\", null],\n [\"arbitrumnova\", ZD_ARBITRUM_NOVA_PROJECT_ID],\n [\"astar-zkevm\", ZD_ASTAR_PROJECT_ID],\n [\"apex\", null],\n ]).get(chain)!;\n\n if (zeroDevProjectId == null) {\n throw new Error(`ZeroDev project id not found for chain ${chain}`);\n }\n return zeroDevProjectId;\n};\n\nexport const getViemNetwork = (cmChain: EVMBlockchainIncludingTestnet) => {\n switch (cmChain) {\n case \"ethereum\":\n return mainnet;\n case \"ethereum-goerli\":\n return goerli;\n case \"ethereum-sepolia\":\n return sepolia;\n case \"polygon\":\n return polygon;\n case \"polygon-amoy\":\n return polygonAmoy;\n case \"optimism\":\n return optimism;\n case \"optimism-sepolia\":\n return optimismSepolia;\n case \"arbitrum\":\n return arbitrum;\n case \"arbitrumnova\":\n return arbitrumNova;\n case \"arbitrum-sepolia\":\n return arbitrumSepolia;\n case \"base\":\n return base;\n case \"base-sepolia\":\n return baseSepolia;\n case \"zkyoto\":\n return astarZkyoto;\n case \"astar-zkevm\":\n return astarZkEVM;\n case \"bsc\":\n return bsc;\n default:\n throw new Error(`Unsupported network: ${cmChain}`);\n }\n};\n\nexport const getBundlerRPC = (chain: EVMBlockchainIncludingTestnet) => {\n switch (chain) {\n case EVMBlockchainIncludingTestnet.BASE_SEPOLIA:\n return PM_BASE_SEPOLIA_RPC;\n case EVMBlockchainIncludingTestnet.BASE:\n return PM_BASE_RPC;\n default:\n return BUNDLER_RPC + getZeroDevProjectIdByBlockchain(chain) + \"?bundlerProvider=STACKUP\";\n }\n};\n","import { providerToSmartAccountSigner } from \"permissionless\";\nimport type { SmartAccountSigner } from \"permissionless/accounts\";\nimport { Address, EIP1193Provider } from \"viem\";\n\nimport { EVMBlockchainIncludingTestnet } from \"@crossmint/common-sdk-base\";\n\nimport { SmartWalletSDKError } from \"../error\";\nimport { ViemAccount, WalletParams } from \"../types/Config\";\nimport { logInputOutput } from \"./log\";\n\ntype CreateOwnerSignerInput = {\n chain: EVMBlockchainIncludingTestnet;\n walletParams: WalletParams;\n};\n\nexport const createOwnerSigner = logInputOutput(\n async ({ walletParams }: CreateOwnerSignerInput): Promise<SmartAccountSigner<\"custom\", Address>> => {\n if (isEIP1193Provider(walletParams.signer)) {\n return await providerToSmartAccountSigner(walletParams.signer);\n } else if (isAccount(walletParams.signer)) {\n return walletParams.signer.account;\n } else {\n const signer = walletParams.signer as any;\n throw new SmartWalletSDKError(`The signer type ${signer.type} is not supported`);\n }\n },\n \"createOwnerSigner\"\n);\n\nfunction isEIP1193Provider(signer: any): signer is EIP1193Provider {\n return signer && typeof signer.request === \"function\";\n}\n\nexport function isAccount(signer: any): signer is ViemAccount {\n return signer && signer.type === \"VIEM_ACCOUNT\";\n}\n","import { EOASignerData } from \"@/types/API\";\nimport type { EOASigner, WalletParams } from \"@/types/Config\";\nimport { AccountAndSigner, WalletCreationParams } from \"@/types/internal\";\nimport { equalsIgnoreCase } from \"@/utils/helpers\";\nimport { createOwnerSigner } from \"@/utils/signer\";\nimport { signerToEcdsaValidator } from \"@zerodev/ecdsa-validator\";\nimport { createKernelAccount } from \"@zerodev/sdk\";\n\nimport { AdminMismatchError } from \"../../error\";\n\nexport interface EOAWalletParams extends WalletCreationParams {\n walletParams: WalletParams & { signer: EOASigner };\n}\n\nexport class EOAAccountService {\n public async get(\n { chain, publicClient, entryPoint, walletParams, kernelVersion, user }: EOAWalletParams,\n existingSignerConfig?: EOASignerData\n ): Promise<AccountAndSigner> {\n const eoa = await createOwnerSigner({\n chain,\n walletParams,\n });\n\n if (existingSignerConfig != null && !equalsIgnoreCase(eoa.address, existingSignerConfig.eoaAddress)) {\n throw new AdminMismatchError(\n `User '${user.id}' has an existing wallet with an eoa signer '${existingSignerConfig.eoaAddress}', this does not match input eoa signer '${eoa.address}'.`,\n existingSignerConfig,\n { type: \"eoa\", eoaAddress: existingSignerConfig.eoaAddress }\n );\n }\n\n const ecdsaValidator = await signerToEcdsaValidator(publicClient, {\n signer: eoa,\n entryPoint: entryPoint.address,\n kernelVersion,\n });\n const account = await createKernelAccount(publicClient, {\n plugins: {\n sudo: ecdsaValidator,\n },\n index: BigInt(0),\n entryPoint: entryPoint.address,\n kernelVersion,\n });\n\n return { account, signerData: { eoaAddress: eoa.address, type: \"eoa\" } };\n }\n}\n","import type { CrossmintWalletService } from \"@/api/CrossmintWalletService\";\nimport { type PasskeySignerData, displayPasskey } from \"@/types/API\";\nimport type { PasskeySigner, UserParams, WalletParams } from \"@/types/Config\";\nimport type { AccountAndSigner, PasskeyValidatorSerializedData, WalletCreationParams } from \"@/types/internal\";\nimport { PasskeyValidatorContractVersion, WebAuthnMode, toPasskeyValidator } from \"@zerodev/passkey-validator\";\nimport { type KernelValidator, createKernelAccount } from \"@zerodev/sdk\";\nimport { WebAuthnKey, toWebAuthnKey } from \"@zerodev/webauthn-key\";\nimport type { EntryPoint } from \"permissionless/types/entrypoint\";\n\nimport { PasskeyMismatchError } from \"../../error\";\n\nexport interface PasskeyWalletParams extends WalletCreationParams {\n walletParams: WalletParams & { signer: PasskeySigner };\n}\n\nexport function isPasskeyParams(params: WalletCreationParams): params is PasskeyWalletParams {\n return (params.walletParams.signer as PasskeySigner).type === \"PASSKEY\";\n}\n\ntype PasskeyValidator = KernelValidator<EntryPoint, \"WebAuthnValidator\"> & {\n getSerializedData: () => string;\n};\n\nexport class PasskeyAccountService {\n constructor(private readonly crossmintService: CrossmintWalletService) {}\n\n public async get(\n { user, publicClient, walletParams, entryPoint, kernelVersion }: PasskeyWalletParams,\n existingSignerConfig?: PasskeySignerData\n ): Promise<AccountAndSigner> {\n const inputPasskeyName = walletParams.signer.passkeyName ?? user.id;\n if (existingSignerConfig != null && existingSignerConfig.passkeyName !== inputPasskeyName) {\n throw new PasskeyMismatchError(\n `User '${user.id}' has an existing wallet created with a passkey named '${existingSignerConfig.passkeyName}', this does match input passkey name '${inputPasskeyName}'.`,\n displayPasskey(existingSignerConfig)\n );\n }\n\n const passkey = await this.getPasskey(user, inputPasskeyName, existingSignerConfig);\n\n const latestValidatorVersion = PasskeyValidatorContractVersion.V0_0_2;\n const validatorContractVersion =\n existingSignerConfig == null ? latestValidatorVersion : existingSignerConfig.validatorContractVersion;\n const validator = await toPasskeyValidator(publicClient, {\n webAuthnKey: passkey,\n entryPoint: entryPoint.address,\n validatorContractVersion,\n kernelVersion,\n });\n\n const kernelAccount = await createKernelAccount(publicClient, {\n plugins: { sudo: validator },\n entryPoint: entryPoint.address,\n kernelVersion,\n });\n\n return {\n signerData: this.getSignerData(validator, validatorContractVersion, inputPasskeyName),\n account: kernelAccount,\n };\n }\n\n private async getPasskey(\n user: UserParams,\n passkeyName: string,\n existing?: PasskeySignerData\n ): Promise<WebAuthnKey> {\n if (existing != null) {\n return {\n pubX: BigInt(existing.pubKeyX),\n pubY: BigInt(existing.pubKeyY),\n authenticatorId: existing.authenticatorId,\n authenticatorIdHash: existing.authenticatorIdHash,\n };\n }\n\n return toWebAuthnKey({\n passkeyName,\n passkeyServerUrl: this.crossmintService.getPasskeyServerUrl(),\n mode: WebAuthnMode.Register,\n passkeyServerHeaders: this.createPasskeysServerHeaders(user),\n });\n }\n\n private getSignerData(\n validator: PasskeyValidator,\n validatorContractVersion: PasskeyValidatorContractVersion,\n passkeyName: string\n ): PasskeySignerData {\n return {\n ...deserializePasskeyValidatorData(validator.getSerializedData()),\n passkeyName,\n validatorContractVersion,\n domain: window.location.hostname,\n type: \"passkeys\",\n };\n }\n\n private createPasskeysServerHeaders(user: UserParams) {\n return {\n \"x-api-key\": this.crossmintService.crossmintAPIHeaders[\"x-api-key\"],\n Authorization: `Bearer ${user.jwt}`,\n };\n }\n}\n\nconst deserializePasskeyValidatorData = (params: string) => {\n const uint8Array = base64ToBytes(params);\n const jsonString = new TextDecoder().decode(uint8Array);\n\n return JSON.parse(jsonString) as PasskeyValidatorSerializedData;\n};\n\nfunction base64ToBytes(base64: string) {\n const binString = atob(base64);\n return Uint8Array.from(binString, (m) => m.codePointAt(0) as number);\n}\n","import { PAYMASTER_RPC, PM_BASE_RPC, PM_BASE_SEPOLIA_RPC } from \"@/utils/constants\";\nimport { createZeroDevPaymasterClient } from \"@zerodev/sdk\";\nimport { Middleware } from \"permissionless/actions/smartAccount\";\nimport { EntryPoint } from \"permissionless/types/entrypoint\";\nimport { http } from \"viem\";\n\nimport { EVMBlockchainIncludingTestnet } from \"@crossmint/common-sdk-base\";\n\nimport { usesGelatoBundler } from \"../../utils/blockchain\";\nimport { getViemNetwork, getZeroDevProjectIdByBlockchain } from \"../BlockchainNetworks\";\n\nexport function usePaymaster(chain: EVMBlockchainIncludingTestnet) {\n return !usesGelatoBundler(chain);\n}\n\nconst getPaymasterRPC = (chain: EVMBlockchainIncludingTestnet) => {\n switch (chain) {\n case EVMBlockchainIncludingTestnet.BASE_SEPOLIA:\n return PM_BASE_SEPOLIA_RPC;\n case EVMBlockchainIncludingTestnet.BASE:\n return PM_BASE_RPC;\n default:\n return PAYMASTER_RPC + getZeroDevProjectIdByBlockchain(chain) + \"?paymasterProvider=STACKUP\";\n }\n};\n\nexport function paymasterMiddleware({\n entryPoint,\n chain,\n}: {\n entryPoint: EntryPoint;\n chain: EVMBlockchainIncludingTestnet;\n}): Middleware<EntryPoint> {\n return {\n middleware: {\n sponsorUserOperation: async ({ userOperation }) => {\n const paymasterClient = createZeroDevPaymasterClient({\n chain: getViemNetwork(chain),\n transport: http(getPaymasterRPC(chain)),\n entryPoint,\n });\n return paymasterClient.sponsorUserOperation({\n userOperation,\n entryPoint,\n });\n },\n },\n };\n}\n","import { logError } from \"@/services/logging\";\nimport { DatadogProvider } from \"@/services/logging/DatadogProvider\";\nimport { SDK_VERSION } from \"@/utils/constants\";\nimport { BaseError, stringify } from \"viem\";\n\nimport { SmartWalletSDKError } from \".\";\n\nexport class ErrorProcessor {\n constructor(private readonly logger: DatadogProvider) {}\n\n public map(error: unknown, fallback: SmartWalletSDKError): SmartWalletSDKError | BaseError {\n this.record(error);\n\n if (error instanceof SmartWalletSDKError) {\n return error;\n }\n\n // Allow viem errors, which are generally pretty friendly.\n if (error instanceof BaseError) {\n return error;\n }\n\n return fallback;\n }\n\n private record(error: unknown) {\n const message = error instanceof Error ? error.message : String(error);\n this.logger.logError(`Smart Wallet SDK Error: ${message}`, {\n stack: error instanceof Error ? error.stack : undefined,\n name: error instanceof Error ? error.name : \"UnknownError\",\n details: stringify(error),\n domain: window.location.hostname,\n sdk_version: SDK_VERSION,\n });\n }\n}\n"],"mappings":"w+BAAA,IAAAA,GAAA,GAAAC,GAAAD,GAAA,2BAAAE,EAAA,uBAAAC,EAAA,gEAAAC,EAAA,0BAAAC,EAAA,mBAAAC,EAAA,uBAAAC,EAAA,oBAAAC,EAAA,uBAAAC,EAAA,oBAAAC,EAAA,uCAAAC,EAAA,uBAAAC,EAAA,sBAAAC,EAAA,yBAAAC,EAAA,mBAAAC,GAAA,wBAAAC,EAAA,kBAAAC,EAAA,kCAAAC,EAAA,gEAAAC,GAAAnB,IAAA,IAAAoB,GAAiF,sCCA1E,SAASC,GAAW,CACvB,OAAO,OAAO,QAAW,WAC7B,CCFO,SAASC,GAAc,CAC1B,OAAI,QAAQ,IAAI,WAAa,OAClB,GAGJ,OAAO,SAAS,OAAO,SAAS,WAAW,CACtD,CAMO,SAASC,EAAiBC,EAAYC,EAAqB,CAC9D,OAAOD,GAAA,YAAAA,EAAG,kBAAkBC,GAAA,YAAAA,EAAG,cACnC,CCXA,IAAMC,GAAmB,GAEZC,EAAN,KAAwD,CAC3D,QAAQC,EAAiBC,EAAkB,CACnCH,IACA,QAAQ,IAAIE,EAASC,CAAO,CAEpC,CAEA,SAASD,EAAiBC,EAAkB,CACpCH,IACA,QAAQ,MAAME,EAASC,CAAO,CAEtC,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ACtC,YACaC,EACAC,EACnB,CACE,MAAM,gBAAgB,EAHL,wBAAAD,EACA,oBAAAC,CAGrB,CAMA,OAAO,KAAK,CAAE,aAAAC,CAAa,EAA6C,CACpE,GAAI,CAACC,EAAS,EACV,MAAM,IAAIC,EAAoB,mDAAmD,EAIrF,GAAI,IADqB,mBAAeF,CAAY,EAC9B,QAClB,MAAM,IAAI,MAAM,iBAAiB,EAGrC,IAAMG,EAAmB,IAAIC,GAAuBJ,CAAY,EAC1DD,EAAiB,IAAIM,GAAe,IAAIC,CAAiB,EAC/D,OAAO,IAAIV,EACP,IAAIW,GAAmBJ,EAAkB,IAAIK,GAAgBT,CAAc,CAAC,EAC5EA,CACJ,CACJ,CAWM,kBACFU,EACAC,EAEuB,QAAAC,EAAA,yBAHvBC,EACAC,EACAC,EAA6B,CAAE,OAAQ,CAAE,KAAM,SAAU,CAAE,EACpC,CACvB,OAAOC,EACH,uBACA,IAAYJ,EAAA,sBACR,GAAI,CACA,OAAO,MAAM,KAAK,mBAAmB,YAAYC,EAAMC,EAAOC,CAAY,CAC9E,OAASE,EAAY,CACjB,MAAM,KAAK,eAAe,IACtBA,EACA,IAAId,EAAoB,2BAA2Bc,EAAM,OAAO,OAAK,cAAUA,CAAK,CAAC,CACzF,CACJ,CACJ,GACA,CAAE,KAAAJ,EAAM,MAAAC,CAAM,CAClB,CACJ,GACJ","names":["src_exports","__export","AdminAlreadyUsedError","AdminMismatchError","ConfigError","CrossmintServiceError","EVMSmartWallet","JWTDecryptionError","JWTExpiredError","JWTIdentifierError","JWTInvalidError","NonCustodialWalletsNotEnabledError","NotAuthorizedError","OutOfCreditsError","PasskeyMismatchError","SmartWalletSDK","SmartWalletSDKError","TransferError","UserWalletAlreadyCreatedError","__toCommonJS","import_common_sdk_base","isClient","isLocalhost","equalsIgnoreCase","a","b","LOG_IN_LOCALHOST","ConsoleProvider","message","context","ZERO_DEV_TYPE","DATADOG_CLIENT_TOKEN","CROSSMINT_DEV_URL","CROSSMINT_STG_URL","CROSSMINT_PROD_URL","ZD_ETHEREUM_PROJECT_ID","ZD_POLYGON_PROJECT_ID","ZD_BSC_PROJECT_ID","ZD_OPTIMISM_PROJECT_ID","ZD_ARBITRUM_PROJECT_ID","ZD_GOERLI_PROJECT_ID","ZD_SEPOLIA_PROJECT_ID","ZD_AMOY_PROJECT_ID","ZD_ZKATANA_PROJECT_ID","ZD_ZKYOTO_PROJECT_ID","ZD_ASTAR_PROJECT_ID","ZD_BASE_SEPOLIA_PROJECT_ID","ZD_OPTIMISM_SEPOLIA_PROJECT_ID","ZD_ARBITRUM_SEPOLIA_PROJECT_ID","ZD_BASE_PROJECT_ID","ZD_ARBITRUM_NOVA_PROJECT_ID","SCW_SERVICE","SDK_VERSION","API_VERSION","BUNDLER_RPC","PAYMASTER_RPC","PM_BASE_SEPOLIA_RPC","PM_BASE_RPC","import_browser_logs","DatadogProvider","message","context","log","loggerType","contextParam","_context","__spreadProps","__spreadValues","SCW_SERVICE","init","DATADOG_CLIENT_TOKEN","getBrowserLogger","isClient","isLocalhost","ConsoleProvider","DatadogProvider","logInfo","logWarn","logError","import_viem","SmartWalletErrors","SmartWalletSDKError","message","details","code","TransferError","CrossmintServiceError","status","AdminMismatchError","required","used","PasskeyMismatchError","NotAuthorizedError","JWTExpiredError","expiredAt","JWTInvalidError","JWTDecryptionError","JWTIdentifierError","identifierKey","UserWalletAlreadyCreatedError","userId","OutOfCreditsError","ConfigError","AdminAlreadyUsedError","NonCustodialWalletsNotEnabledError","import_uuid","LoggerWrapper","className","extraInfo","logIdempotencyKey","uuidv4","target","propKey","receiver","origMethod","identifierTag","SCW_SERVICE","args","result","res","err","logInfoIfNotInLocalhost","beautify","__spreadProps","__spreadValues","logError","name","cb","logPerformance","__async","start","durationInMs","logInputOutput","fn","functionName","json","error","stringifyAvoidingCircular","simpleObject","prop","message","context","isLocalhost","logInfo","errorToJSON","_a","errorToLog","import_viem","ERC1155_default","transferParams","contract","config","from","to","ERC1155_default","EVMSmartWallet","LoggerWrapper","crossmintService","accountClient","publicClient","chain","toAddress","config","__async","tx","transferParams","client","request","error","logError","SCW_SERVICE","errorToJSON","tokenIdString","TransferError","import_viem","import_common_sdk_base","import_common_sdk_base","APIErrorService","errors","JWTInvalidError","JWTDecryptionError","expiredAt","JWTExpiredError","identifierKey","JWTIdentifierError","userId","UserWalletAlreadyCreatedError","AdminAlreadyUsedError","NonCustodialWalletsNotEnabledError","_0","__async","response","onServerErrorMessage","CrossmintServiceError","OutOfCreditsError","body","code","e","_BaseCrossmintService","LoggerWrapper","apiKey","result","APIErrorService","_0","__async","endpoint","options","onServerErrorMessage","authToken","logPerformance","url","body","method","response","__spreadValues","error","CrossmintServiceError","environment","CROSSMINT_DEV_URL","CROSSMINT_STG_URL","CROSSMINT_PROD_URL","BaseCrossmintService","import_common_sdk_base","CrossmintWalletService","BaseCrossmintService","user","input","__async","API_VERSION","chain","address","import_common_sdk_base","isPolygonCDK","chain","usesGelatoBundler","import_viem","transactionMethods","signingMethods","isTxnMethod","method","isSignMethod","ClientDecorator","errorProcessor","crossmintChain","smartAccountClient","target","prop","receiver","originalMethod","args","logPerformance","__async","logInfo","processed","error","description","SmartWalletSDKError","userOperation","middleware","account","txn","txnParams","usesGelatoBundler","__spreadProps","__spreadValues","displayPasskey","data","import_sdk","import_permissionless","import_viem","import_common_sdk_base","SUPPORTED_KERNEL_VERSIONS","isSupportedKernelVersion","version","SUPPORTED_ENTRYPOINT_VERSIONS","isSupportedEntryPointVersion","import_chains","import_common_sdk_base","getZeroDevProjectIdByBlockchain","chain","zeroDevProjectId","ZD_ETHEREUM_PROJECT_ID","ZD_POLYGON_PROJECT_ID","ZD_BSC_PROJECT_ID","ZD_OPTIMISM_PROJECT_ID","ZD_ARBITRUM_PROJECT_ID","ZD_GOERLI_PROJECT_ID","ZD_SEPOLIA_PROJECT_ID","ZD_AMOY_PROJECT_ID","ZD_ZKATANA_PROJECT_ID","ZD_ZKYOTO_PROJECT_ID","ZD_ARBITRUM_SEPOLIA_PROJECT_ID","ZD_BASE_SEPOLIA_PROJECT_ID","ZD_OPTIMISM_SEPOLIA_PROJECT_ID","ZD_BASE_PROJECT_ID","ZD_ARBITRUM_NOVA_PROJECT_ID","ZD_ASTAR_PROJECT_ID","getViemNetwork","cmChain","getBundlerRPC","PM_BASE_SEPOLIA_RPC","PM_BASE_RPC","BUNDLER_RPC","import_permissionless","createOwnerSigner","logInputOutput","_0","__async","walletParams","isEIP1193Provider","isAccount","signer","SmartWalletSDKError","import_ecdsa_validator","import_sdk","EOAAccountService","_0","_1","__async","chain","publicClient","entryPoint","walletParams","kernelVersion","user","existingSignerConfig","eoa","createOwnerSigner","equalsIgnoreCase","AdminMismatchError","ecdsaValidator","import_passkey_validator","import_sdk","import_webauthn_key","isPasskeyParams","params","PasskeyAccountService","crossmintService","_0","_1","__async","user","publicClient","walletParams","entryPoint","kernelVersion","existingSignerConfig","_a","inputPasskeyName","PasskeyMismatchError","displayPasskey","passkey","latestValidatorVersion","validatorContractVersion","validator","kernelAccount","passkeyName","existing","__spreadProps","__spreadValues","deserializePasskeyValidatorData","uint8Array","base64ToBytes","jsonString","base64","binString","m","import_sdk","import_viem","import_common_sdk_base","usePaymaster","chain","usesGelatoBundler","getPaymasterRPC","PM_BASE_SEPOLIA_RPC","PM_BASE_RPC","PAYMASTER_RPC","getZeroDevProjectIdByBlockchain","paymasterMiddleware","entryPoint","_0","__async","userOperation","getViemNetwork","SmartWalletService","crossmintWalletService","clientDecorator","accountFactory","AccountFactory","EOAAccountService","PasskeyAccountService","user","chain","walletParams","__async","entryPoint","kernelVersion","existingSignerConfig","smartContractWalletAddress","userId","publicClient","getBundlerRPC","account","signerData","__spreadProps","__spreadValues","equalsIgnoreCase","UserWalletAlreadyCreatedError","ZERO_DEV_TYPE","kernelAccountClient","getViemNetwork","usePaymaster","paymasterMiddleware","smartAccountClient","EVMSmartWallet","entryPointVersion","signers","isSupportedKernelVersion","SmartWalletSDKError","SUPPORTED_KERNEL_VERSIONS","isSupportedEntryPointVersion","SUPPORTED_ENTRYPOINT_VERSIONS","CrossmintServiceError","eoa","passkey","params","isPasskeyParams","AdminMismatchError","displayPasskey","import_viem","ErrorProcessor","logger","error","fallback","SmartWalletSDKError","message","SDK_VERSION","SmartWalletSDK","_SmartWalletSDK","LoggerWrapper","smartWalletService","errorProcessor","clientApiKey","isClient","SmartWalletSDKError","crossmintService","CrossmintWalletService","ErrorProcessor","DatadogProvider","SmartWalletService","ClientDecorator","_0","_1","__async","user","chain","walletParams","logPerformance","error"]}
|