@latticexyz/entrykit 2.2.12-entrykit-9d16d7a4d5dde17d31463970d3359bc9faa08d70

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 ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2022-present Lattice Labs Ltd.
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,13 @@
1
+ # EntryKit
2
+
3
+ UI kit to streamline signing in to MUD apps.
4
+
5
+ ## Installation
6
+
7
+ ```
8
+ npm install @latticexyz/entrykit
9
+ ```
10
+
11
+ ## Usage
12
+
13
+ TODO
@@ -0,0 +1,2 @@
1
+ import{createClient as we,custom as Ae,getAddress as Ce,numberToHex as L,SwitchChainError as xe}from"viem";import{ChainNotConfiguredError as Pe,createConnector as ve}from"wagmi";import{createStore as G}from"zustand/vanilla";import{persist as U}from"zustand/middleware";var u=G(U(()=>({publicKeys:{},addresses:{},activeCredential:null}),{name:"mud:passkey:cache"}));function F(e){e.key===u.persist.getOptions().name&&u.persist.rehydrate()}window.addEventListener("storage",F);import{createSmartAccountClient as Ie}from"permissionless/clients";import{toWebAuthnAccount as ae}from"viem/account-abstraction";import{BaseError as _}from"abitype";import{pad as z,encodeFunctionData as x,hashMessage as V,hashTypedData as D,encodeAbiParameters as M,stringToHex as q,size as J,encodePacked as $,parseSignature as Y}from"viem";import{entryPoint07Abi as j,entryPoint07Address as Q,getUserOperationHash as X,toSmartAccount as Z}from"viem/account-abstraction";import{readContract as O}from"viem/actions";import{parseSignature as ee}from"webauthn-p256";async function k(e){let{client:n,owners:i,nonce:a=0n}=e,o=e.address,p={abi:j,address:Q,version:"0.7"},c={abi:ne,address:"0x356336adA1619BeC1Ae4E6D94Dd9c0490DA414a8"};if(!i.length)throw new Error("`owners` must have at least one account.");function y(r){return r.type==="webAuthn"?r.publicKey:z(r.address)}let t=e.signer??i[0],s=i.indexOf(t);if(s===-1)throw new Error("`signer` must be one of `owners`.");return Z({client:n,entryPoint:p,extend:{__isCoinbaseSmartAccount:!0,abi:w,factory:c,signer:t},async encodeCalls(r){return r.length===1?x({abi:w,functionName:"execute",args:[r[0].to,r[0].value??0n,r[0].data??"0x"]}):x({abi:w,functionName:"executeBatch",args:[r.map(d=>({data:d.data??"0x",target:d.to,value:d.value??0n}))]})},async getAddress(){return o??=await O(n,{...c,functionName:"getAddress",args:[i.map(y),a]}),o},async getFactoryArgs(){let r=x({abi:c.abi,functionName:"createAccount",args:[i.map(y),a]});return{factory:c.address,factoryData:r}},async getStubSignature(){return t.type==="webAuthn"?"0x0000000000000000000000000000000000000000000000000000000000000020000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000400000000000000000000000000000000000000000000000000000000000000200000000000000000000000000000000000000000000000000000000000000002000000000000000000000000000000000000000000000000000000000000000c0000000000000000000000000000000000000000000000000000000000000012000000000000000000000000000000000000000000000000000000000000000170000000000000000000000000000000000000000000000000000000000000001949fc7c88032b9fcb5f6efc7a7b8c63668eae9871b765e23123bb473ff57aa831a7c0d9276168ebcc29f2875a0239cffdf2a9cd1c2007c5c77c071db9264df1d000000000000000000000000000000000000000000000000000000000000002549960de5880e8c687434170f6476605b8fe4aeb9a28632c7995cf3ba831d97630500000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000008a7b2274797065223a22776562617574686e2e676574222c226368616c6c656e6765223a2273496a396e6164474850596759334b7156384f7a4a666c726275504b474f716d59576f4d57516869467773222c226f726967696e223a2268747470733a2f2f7369676e2e636f696e626173652e636f6d222c2263726f73734f726967696e223a66616c73657d00000000000000000000000000000000000000000000":b({signature:"0xfffffffffffffffffffffffffffffff0000000000000000000000000000000007aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa1c",ownerIndex:s})},async sign(r){let d=await this.getAddress(),m=P({address:d,chainId:n.chain.id,hash:r.hash}),l=await h({hash:m,owner:t});return b({signature:l,ownerIndex:s})},async signMessage(r){let{message:d}=r,m=await this.getAddress(),l=P({address:m,chainId:n.chain.id,hash:V(d)}),f=await h({hash:l,owner:t});return b({signature:f,ownerIndex:s})},async signTypedData(r){let{domain:d,types:m,primaryType:l,message:f}=r,C=await this.getAddress(),R=P({address:C,chainId:n.chain.id,hash:D({domain:d,message:f,primaryType:l,types:m})}),B=await h({hash:R,owner:t});return b({signature:B,ownerIndex:s})},async signUserOperation(r){let{chainId:d=n.chain.id,...m}=r,l=await this.getAddress(),f=X({chainId:d,entryPointAddress:p.address,entryPointVersion:p.version,userOperation:{...m,sender:l}}),C=await h({hash:f,owner:t});return b({signature:C,ownerIndex:s})},userOperation:{async estimateGas(r){if(t.type==="webAuthn")return{verificationGasLimit:BigInt(Math.max(Number(r.verificationGasLimit??0n),8e5))}}},async isOwner(r){return await O(n,{abi:w,address:await this.getAddress(),functionName:"isOwnerBytes",args:[y(r)]})}})}async function h({hash:e,owner:n}){if(n.type==="webAuthn"){let{signature:i,webauthn:a}=await n.sign({hash:e});return te({signature:i,webauthn:a})}if(n.sign)return n.sign({hash:e});throw new _("`owner` does not support raw sign.")}function P({address:e,chainId:n,hash:i}){return D({domain:{chainId:n,name:"Coinbase Smart Wallet",verifyingContract:e,version:"1"},types:{CoinbaseSmartWalletMessage:[{name:"hash",type:"bytes32"}]},primaryType:"CoinbaseSmartWalletMessage",message:{hash:i}})}function te({webauthn:e,signature:n}){let{r:i,s:a}=ee(n);return M([{components:[{name:"authenticatorData",type:"bytes"},{name:"clientDataJSON",type:"bytes"},{name:"challengeIndex",type:"uint256"},{name:"typeIndex",type:"uint256"},{name:"r",type:"uint256"},{name:"s",type:"uint256"}],type:"tuple"}],[{authenticatorData:e.authenticatorData,clientDataJSON:q(e.clientDataJSON),challengeIndex:BigInt(e.challengeIndex),typeIndex:BigInt(e.typeIndex),r:i,s:a}])}function b(e){let{ownerIndex:n}=e,i=(()=>{if(J(e.signature)!==65)return e.signature;let a=Y(e.signature);return $(["bytes32","bytes32","uint8"],[a.r,a.s,a.yParity===0?27:28])})();return M([{components:[{name:"ownerIndex",type:"uint8"},{name:"signatureData",type:"bytes"}],type:"tuple"}],[{ownerIndex:n,signatureData:i}])}var w=[{inputs:[],stateMutability:"nonpayable",type:"constructor"},{inputs:[{name:"owner",type:"bytes"}],name:"AlreadyOwner",type:"error"},{inputs:[],name:"Initialized",type:"error"},{inputs:[{name:"owner",type:"bytes"}],name:"InvalidEthereumAddressOwner",type:"error"},{inputs:[{name:"key",type:"uint256"}],name:"InvalidNonceKey",type:"error"},{inputs:[{name:"owner",type:"bytes"}],name:"InvalidOwnerBytesLength",type:"error"},{inputs:[],name:"LastOwner",type:"error"},{inputs:[{name:"index",type:"uint256"}],name:"NoOwnerAtIndex",type:"error"},{inputs:[{name:"ownersRemaining",type:"uint256"}],name:"NotLastOwner",type:"error"},{inputs:[{name:"selector",type:"bytes4"}],name:"SelectorNotAllowed",type:"error"},{inputs:[],name:"Unauthorized",type:"error"},{inputs:[],name:"UnauthorizedCallContext",type:"error"},{inputs:[],name:"UpgradeFailed",type:"error"},{inputs:[{name:"index",type:"uint256"},{name:"expectedOwner",type:"bytes"},{name:"actualOwner",type:"bytes"}],name:"WrongOwnerAtIndex",type:"error"},{anonymous:!1,inputs:[{indexed:!0,name:"index",type:"uint256"},{indexed:!1,name:"owner",type:"bytes"}],name:"AddOwner",type:"event"},{anonymous:!1,inputs:[{indexed:!0,name:"index",type:"uint256"},{indexed:!1,name:"owner",type:"bytes"}],name:"RemoveOwner",type:"event"},{anonymous:!1,inputs:[{indexed:!0,name:"implementation",type:"address"}],name:"Upgraded",type:"event"},{stateMutability:"payable",type:"fallback"},{inputs:[],name:"REPLAYABLE_NONCE_KEY",outputs:[{name:"",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[{name:"owner",type:"address"}],name:"addOwnerAddress",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{name:"x",type:"bytes32"},{name:"y",type:"bytes32"}],name:"addOwnerPublicKey",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{name:"functionSelector",type:"bytes4"}],name:"canSkipChainIdValidation",outputs:[{name:"",type:"bool"}],stateMutability:"pure",type:"function"},{inputs:[],name:"domainSeparator",outputs:[{name:"",type:"bytes32"}],stateMutability:"view",type:"function"},{inputs:[],name:"eip712Domain",outputs:[{name:"fields",type:"bytes1"},{name:"name",type:"string"},{name:"version",type:"string"},{name:"chainId",type:"uint256"},{name:"verifyingContract",type:"address"},{name:"salt",type:"bytes32"},{name:"extensions",type:"uint256[]"}],stateMutability:"view",type:"function"},{inputs:[],name:"entryPoint",outputs:[{name:"",type:"address"}],stateMutability:"view",type:"function"},{inputs:[{name:"target",type:"address"},{name:"value",type:"uint256"},{name:"data",type:"bytes"}],name:"execute",outputs:[],stateMutability:"payable",type:"function"},{inputs:[{components:[{name:"target",type:"address"},{name:"value",type:"uint256"},{name:"data",type:"bytes"}],name:"calls",type:"tuple[]"}],name:"executeBatch",outputs:[],stateMutability:"payable",type:"function"},{inputs:[{name:"calls",type:"bytes[]"}],name:"executeWithoutChainIdValidation",outputs:[],stateMutability:"payable",type:"function"},{inputs:[{components:[{name:"sender",type:"address"},{name:"nonce",type:"uint256"},{name:"initCode",type:"bytes"},{name:"callData",type:"bytes"},{name:"callGasLimit",type:"uint256"},{name:"verificationGasLimit",type:"uint256"},{name:"preVerificationGas",type:"uint256"},{name:"maxFeePerGas",type:"uint256"},{name:"maxPriorityFeePerGas",type:"uint256"},{name:"paymasterAndData",type:"bytes"},{name:"signature",type:"bytes"}],name:"userOp",type:"tuple"}],name:"getUserOpHashWithoutChainId",outputs:[{name:"",type:"bytes32"}],stateMutability:"view",type:"function"},{inputs:[],name:"implementation",outputs:[{name:"$",type:"address"}],stateMutability:"view",type:"function"},{inputs:[{name:"owners",type:"bytes[]"}],name:"initialize",outputs:[],stateMutability:"payable",type:"function"},{inputs:[{name:"account",type:"address"}],name:"isOwnerAddress",outputs:[{name:"",type:"bool"}],stateMutability:"view",type:"function"},{inputs:[{name:"account",type:"bytes"}],name:"isOwnerBytes",outputs:[{name:"",type:"bool"}],stateMutability:"view",type:"function"},{inputs:[{name:"x",type:"bytes32"},{name:"y",type:"bytes32"}],name:"isOwnerPublicKey",outputs:[{name:"",type:"bool"}],stateMutability:"view",type:"function"},{inputs:[{name:"hash",type:"bytes32"},{name:"signature",type:"bytes"}],name:"isValidSignature",outputs:[{name:"result",type:"bytes4"}],stateMutability:"view",type:"function"},{inputs:[],name:"nextOwnerIndex",outputs:[{name:"",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[{name:"index",type:"uint256"}],name:"ownerAtIndex",outputs:[{name:"",type:"bytes"}],stateMutability:"view",type:"function"},{inputs:[],name:"ownerCount",outputs:[{name:"",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[],name:"proxiableUUID",outputs:[{name:"",type:"bytes32"}],stateMutability:"view",type:"function"},{inputs:[{name:"index",type:"uint256"},{name:"owner",type:"bytes"}],name:"removeLastOwner",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{name:"index",type:"uint256"},{name:"owner",type:"bytes"}],name:"removeOwnerAtIndex",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[],name:"removedOwnersCount",outputs:[{name:"",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[{name:"hash",type:"bytes32"}],name:"replaySafeHash",outputs:[{name:"",type:"bytes32"}],stateMutability:"view",type:"function"},{inputs:[{name:"newImplementation",type:"address"},{name:"data",type:"bytes"}],name:"upgradeToAndCall",outputs:[],stateMutability:"payable",type:"function"},{inputs:[{components:[{name:"sender",type:"address"},{name:"nonce",type:"uint256"},{name:"initCode",type:"bytes"},{name:"callData",type:"bytes"},{name:"callGasLimit",type:"uint256"},{name:"verificationGasLimit",type:"uint256"},{name:"preVerificationGas",type:"uint256"},{name:"maxFeePerGas",type:"uint256"},{name:"maxPriorityFeePerGas",type:"uint256"},{name:"paymasterAndData",type:"bytes"},{name:"signature",type:"bytes"}],name:"userOp",type:"tuple"},{name:"userOpHash",type:"bytes32"},{name:"missingAccountFunds",type:"uint256"}],name:"validateUserOp",outputs:[{name:"validationData",type:"uint256"}],stateMutability:"nonpayable",type:"function"},{stateMutability:"payable",type:"receive"}],ne=[{inputs:[{name:"implementation_",type:"address"}],stateMutability:"payable",type:"constructor"},{inputs:[],name:"OwnerRequired",type:"error"},{inputs:[{name:"owners",type:"bytes[]"},{name:"nonce",type:"uint256"}],name:"createAccount",outputs:[{name:"account",type:"address"}],stateMutability:"payable",type:"function"},{inputs:[{name:"owners",type:"bytes[]"},{name:"nonce",type:"uint256"}],name:"getAddress",outputs:[{name:"",type:"address"}],stateMutability:"view",type:"function"},{inputs:[],name:"implementation",outputs:[{name:"",type:"address"}],stateMutability:"view",type:"function"},{inputs:[],name:"initCodeHash",outputs:[{name:"",type:"bytes32"}],stateMutability:"view",type:"function"}];async function g(e,n){let{publicKeys:i}=u.getState(),a=i[n];if(!a)throw new Error("No public key found for passkey credential.");let p=[ae({credential:{id:n,publicKey:a}})];return await k({client:e,owners:p})}import{bytesToHex as de,hashMessage as me}from"viem";import{sign as le}from"webauthn-p256";import{bytesToHex as se,hexToBytes as H}from"webauthn-p256";import{concatBytes as ie,utf8ToBytes as re}from"@noble/curves/abstract/utils";async function A(e){let{authenticatorData:n,challengeIndex:i,clientDataJSON:a,typeIndex:o,userVerificationRequired:p}=e,c=o||a.indexOf('"type"'),y=i||a.indexOf('"challenge"'),t=H(n);if(t.length<37)throw new Error("Invalid authenticatorData");let s=t[32];if((s&1)!==1)throw new Error("Invalid authenticatorData");if(p&&(s&4)!==4)throw new Error("Invalid authenticatorData");if((s&8)!==8&&(s&16)===16)throw new Error("Invalid authenticatorData");let r='"type":"webauthn.get"';if(r!==a.slice(Number(c),r.length+1))throw new Error("Invalid clientDataJSON");if(!a.slice(Number(y)).match(/^"challenge":"(.*?)"/))throw new Error("Invalid clientDataJSON");let m=new Uint8Array(await crypto.subtle.digest("SHA-256",re(a))),l=new Uint8Array(await crypto.subtle.digest("SHA-256",ie(H(n),m)));return se(l)}import{sign as ce}from"webauthn-p256";import{parseSignature as oe,serializePublicKey as T}from"webauthn-p256";import{secp256r1 as E}from"@noble/curves/p256";function v(e){let{r:n,s:i}=oe(e.signatureHex),a=new E.Signature(n,i).addRecoveryBit(1).recoverPublicKey(e.messageHash.slice(2)),o=new E.Signature(n,i).addRecoveryBit(0).recoverPublicKey(e.messageHash.slice(2));return[T(a),T(o)]}import{hashMessage as ue}from"viem";function pe([e,n]){return ye([...v(e),...v(n)])}async function K(e){let n=ue(e.signatureHex),{signature:i,webauthn:a,raw:o}=await ce({credentialId:e.credentialId,hash:n}),p=await A(a),c=pe([e,{signatureHex:i,messageHash:p}]);if(c)return{publicKey:c,credential:o}}function ye(e){let n=new Set;for(let i of e){if(n.has(i))return i;n.add(i)}}async function I(){let e=de(crypto.getRandomValues(new Uint8Array(256))),n=me(e),{signature:i,webauthn:a,raw:o}=await le({hash:n}),p=await(async()=>{let c=u.getState().publicKeys[o.id];if(c)return c;let y=await A(a),t=await K({credentialId:o.id,messageHash:y,signatureHex:i});if(!t)throw new Error("recovery failed");if(t.credential.id!==o.id)throw new Error("wrong credential");return u.setState(s=>({publicKeys:{...s.publicKeys,[o.id]:t.publicKey}})),t.publicKey})();return console.log("recovered passkey",o.id,p),u.setState(()=>({activeCredential:o.id})),{id:o.id,publicKey:p,raw:o}}import{createCredential as fe}from"webauthn-p256";async function N(){let e=await fe({name:"MUD Account"});return console.log("created passkey",e),u.setState(n=>({activeCredential:e.id,publicKeys:{...n.publicKeys,[e.id]:e.publicKey}})),e}import{resourceToHex as be}from"@latticexyz/common";import{parseAbi as ge}from"viem";import he from"@latticexyz/world/mud.config";var S={pollingInterval:250},Mt=be({type:"system",namespace:"",name:"unlimited"}),kt=he.namespaces.world.tables,Ht=ge(["function registerDelegation(address delegatee, bytes32 delegationControlId, bytes initCallData)"]);W.type="passkey";function W({chainId:e,bundlerTransport:n,paymasterAddress:i}){return ve(a=>{if(!a.transports)throw new Error("Wagmi must be configured with transports to use the passkey connector.");let o=a.chains.find(t=>t.id===e);if(!o)throw new Error(`Could not find configured chain for chain ID ${e}.`);let p=a.transports[o.id];if(!p)throw new Error(`Could not find configured transport for chain ID ${e}.`);let c=we({...S,chain:o,transport:p}),y=u.getState().activeCredential!=null;return{id:"passkey",type:W.type,name:"Passkey",supportsSimulation:!0,async createPasskey(){let{id:t}=await N(),s=await g(c,t);this.onAccountsChanged([s.address]),this.onConnect?.({chainId:L(e)})},async reusePasskey(){let{id:t}=await I(),s=await g(c,t);this.onAccountsChanged([s.address]),this.onConnect?.({chainId:L(e)})},async connect(t){if(console.log("connect"),t?.chainId!=null&&t.chainId!==e)throw new Error(`Can't connect to chain ${t.chainId}. Passkey connector is bound to chain ${e}.`);!u.getState().activeCredential&&!t?.isReconnecting&&await I();let s=await this.getAccounts();return y=s.length>0,{accounts:s,chainId:e}},async disconnect(){console.log("disconnect"),y=!1,u.setState({activeCredential:null})},async getAccounts(){console.log("getAccounts");let t=u.getState().activeCredential;if(!t)return[];try{console.log("getting account for credential",t);let s=await g(c,t);return console.log("got account",s),[s.address]}catch{console.log("could not get address for credential ID",t)}return[]},async getChainId(){return e},async isAuthorized(){return console.log("isAuthorized"),y?(await this.getAccounts()).length>0:!1},async switchChain(t){if(t.chainId!==e)throw new Error(`Can't connect to chain ${t.chainId}. Passkey connector is bound to chain ${e}.`);let s=a.chains.find(r=>r.id===t.chainId);if(!s)throw new xe(new Pe);return s},onAccountsChanged(t){console.log("onAccountsChanged"),t.length>0?a.emitter.emit("change",{accounts:t.map(s=>Ce(s))}):this.onDisconnect()},onChainChanged(t){console.log("onChainChanged"),a.emitter.emit("change",{chainId:Number(t)})},async onConnect(t){console.log("onConnect");let s=await this.getAccounts();a.emitter.emit("connect",{accounts:s,chainId:e})},async onDisconnect(t){console.log("onDisconnect"),a.emitter.emit("disconnect"),y=!1},async getClient(t){console.log("passkeyConnector.getClient",t);let s=u.getState().activeCredential;if(!s)throw new Error("Not connected.");let r=await g(c,s);return Ie({...S,bundlerTransport:n,client:c,account:r,paymaster:{getPaymasterData:async()=>({paymaster:i,paymasterData:"0x"})},userOperation:{estimateFeesPerGas:c.chain.id===31337?async()=>({maxFeePerGas:100000n,maxPriorityFeePerGas:0n}):void 0}})},async getProvider(t){return Ae({request:c.transport.request})({retryCount:0})}}})}export{k as a,S as b,Mt as c,kt as d,Ht as e,W as f};
2
+ //# sourceMappingURL=chunk-A6N5TZRJ.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../src/passkey/passkeyConnector.ts","../../src/passkey/cache.ts","../../src/passkey/getAccount.ts","../../src/smart-account/toCoinbaseSmartAccount.ts","../../src/passkey/reusePasskey.ts","../../src/passkey/getMessageHash.ts","../../src/passkey/recoverPasskeyPublicKey.ts","../../src/passkey/getCandidatePublicKeys.ts","../../src/passkey/createPasskey.ts","../../src/common.ts"],"sourcesContent":["import {\n createClient,\n custom,\n EIP1193RequestFn,\n EIP1474Methods,\n getAddress,\n numberToHex,\n SwitchChainError,\n Client,\n ProviderConnectInfo,\n Transport,\n Address,\n} from \"viem\";\nimport { ChainNotConfiguredError, createConnector, CreateConnectorFn } from \"wagmi\";\nimport { cache } from \"./cache\";\nimport { createSmartAccountClient } from \"permissionless/clients\";\nimport { getAccount } from \"./getAccount\";\nimport { reusePasskey } from \"./reusePasskey\";\nimport { createPasskey } from \"./createPasskey\";\nimport { defaultClientConfig } from \"../common\";\n\nexport type PasskeyConnectorOptions = {\n // TODO: figure out what we wanna do across chains\n chainId: number;\n bundlerTransport: Transport;\n paymasterAddress: Address;\n};\n\nexport type PasskeyProvider = {\n request: EIP1193RequestFn<EIP1474Methods>;\n};\nexport type PasskeyConnectorProperties = {\n createPasskey(): Promise<void>;\n reusePasskey(): Promise<void>;\n getClient(parameters?: { chainId?: number | undefined } | undefined): Promise<Client>;\n onConnect(connectInfo: ProviderConnectInfo): void;\n};\n\nexport type CreatePasskeyConnector = CreateConnectorFn<PasskeyProvider, PasskeyConnectorProperties, {}>;\nexport type PasskeyConnector = ReturnType<CreatePasskeyConnector>;\n\npasskeyConnector.type = \"passkey\" as const;\n\nexport function passkeyConnector({\n chainId,\n bundlerTransport,\n paymasterAddress,\n}: PasskeyConnectorOptions): CreatePasskeyConnector {\n return createConnector((config) => {\n // TODO: figure out how to use with config's `client` option\n if (!config.transports) {\n throw new Error(`Wagmi must be configured with transports to use the passkey connector.`);\n }\n\n const chain = config.chains.find((c) => c.id === chainId);\n if (!chain) throw new Error(`Could not find configured chain for chain ID ${chainId}.`);\n\n const transport = config.transports[chain.id];\n if (!transport) {\n throw new Error(`Could not find configured transport for chain ID ${chainId}.`);\n }\n const client = createClient({ ...defaultClientConfig, chain, transport });\n\n let connected = cache.getState().activeCredential != null;\n\n return {\n id: \"passkey\",\n type: passkeyConnector.type,\n name: \"Passkey\",\n // TODO: check that this works\n supportsSimulation: true,\n\n async createPasskey() {\n const { id } = await createPasskey();\n const account = await getAccount(client, id);\n this.onAccountsChanged([account.address]);\n this.onConnect?.({ chainId: numberToHex(chainId) });\n },\n async reusePasskey() {\n const { id } = await reusePasskey();\n const account = await getAccount(client, id);\n this.onAccountsChanged([account.address]);\n this.onConnect?.({ chainId: numberToHex(chainId) });\n },\n\n async connect(params) {\n console.log(\"connect\");\n // TODO: allow any chain?\n if (params?.chainId != null && params.chainId !== chainId) {\n throw new Error(`Can't connect to chain ${params.chainId}. Passkey connector is bound to chain ${chainId}.`);\n }\n\n // attempt to reuse credential if this is called directly\n // TODO: move this into wallet so it's only triggered via rainbowkit?\n if (!cache.getState().activeCredential && !params?.isReconnecting) {\n await reusePasskey();\n }\n\n const accounts = await this.getAccounts();\n connected = accounts.length > 0;\n\n return { accounts, chainId };\n },\n async disconnect() {\n console.log(\"disconnect\");\n connected = false;\n cache.setState({ activeCredential: null });\n },\n async getAccounts() {\n console.log(\"getAccounts\");\n const id = cache.getState().activeCredential;\n if (!id) return [];\n\n try {\n console.log(\"getting account for credential\", id);\n const account = await getAccount(client, id);\n console.log(\"got account\", account);\n return [account.address];\n } catch (error) {\n console.log(\"could not get address for credential ID\", id);\n }\n\n return [];\n },\n async getChainId() {\n return chainId;\n },\n async isAuthorized() {\n console.log(\"isAuthorized\");\n if (!connected) return false;\n const accounts = await this.getAccounts();\n return accounts.length > 0;\n },\n async switchChain(params) {\n // TODO: allow any chain?\n if (params.chainId !== chainId) {\n throw new Error(`Can't connect to chain ${params.chainId}. Passkey connector is bound to chain ${chainId}.`);\n }\n\n const chain = config.chains.find((c) => c.id === params.chainId);\n if (!chain) throw new SwitchChainError(new ChainNotConfiguredError());\n return chain;\n },\n onAccountsChanged(accounts) {\n console.log(\"onAccountsChanged\");\n if (accounts.length > 0) {\n config.emitter.emit(\"change\", {\n accounts: accounts.map((a) => getAddress(a)),\n });\n } else {\n this.onDisconnect();\n }\n },\n onChainChanged(chainId) {\n console.log(\"onChainChanged\");\n config.emitter.emit(\"change\", { chainId: Number(chainId) });\n },\n async onConnect(_connectInfo) {\n console.log(\"onConnect\");\n const accounts = await this.getAccounts();\n config.emitter.emit(\"connect\", { accounts, chainId });\n },\n async onDisconnect(_error) {\n console.log(\"onDisconnect\");\n config.emitter.emit(\"disconnect\");\n connected = false;\n },\n\n // By default, connector clients are bound to a `json-rpc` account.\n // We provide our own `getClient` method here so that we can return\n // a `smart` account, which is necessary for using with Viem's\n // account abstraction actions (i.e. user ops).\n //\n // Although Wagmi recommends connectors be tree-shakable, we return\n // an extended client here so that this client works with native\n // Wagmi hooks. Otherwise the app needs to build its own client, then\n // wrap each call in its own react-query hooks.\n async getClient(params) {\n console.log(\"passkeyConnector.getClient\", params);\n\n const credentialId = cache.getState().activeCredential;\n if (!credentialId) throw new Error(\"Not connected.\");\n\n const account = await getAccount(client, credentialId);\n\n return createSmartAccountClient({\n ...defaultClientConfig,\n bundlerTransport,\n client,\n account,\n paymaster: {\n getPaymasterData: async () => ({\n paymaster: paymasterAddress,\n paymasterData: \"0x\",\n }),\n },\n userOperation: {\n estimateFeesPerGas:\n // anvil hardcodes fee returned by `eth_maxPriorityFeePerGas`\n // so we have to override it here\n // https://github.com/foundry-rs/foundry/pull/8081#issuecomment-2402002485\n client.chain.id === 31337\n ? async () => ({\n maxFeePerGas: 100_000n,\n maxPriorityFeePerGas: 0n,\n })\n : undefined,\n },\n });\n },\n\n async getProvider(_params) {\n // TODO: chain specific provider?\n // TODO: is turning off retryCount important? is wrapping in this way enough to turn off retries?\n return custom({ request: client.transport.request })({ retryCount: 0 });\n },\n };\n });\n}\n","import { createStore } from \"zustand/vanilla\";\nimport { persist } from \"zustand/middleware\";\nimport { P256Credential } from \"viem/account-abstraction\";\nimport { Address } from \"viem\";\n\n// TODO: move this to wagmi storage?\n// when I tried, it blew up TS complexity and my IDE was impossible to work with\n\nexport type State = {\n readonly publicKeys: {\n readonly [key in P256Credential[\"id\"]]?: P256Credential[\"publicKey\"];\n };\n readonly addresses: {\n readonly [key in P256Credential[\"id\"]]?: Address;\n };\n readonly activeCredential: P256Credential[\"id\"] | null;\n};\n\nexport const cache = createStore(\n persist<State>(\n () => ({\n publicKeys: {},\n addresses: {},\n activeCredential: null,\n }),\n { name: \"mud:passkey:cache\" },\n ),\n);\n\n// keep cache in sync across tabs/windows via storage event\nfunction listener(event: StorageEvent) {\n if (event.key === cache.persist.getOptions().name) {\n cache.persist.rehydrate();\n }\n}\nwindow.addEventListener(\"storage\", listener);\n","import { Client } from \"viem\";\nimport { toWebAuthnAccount } from \"viem/account-abstraction\";\nimport { cache } from \"./cache\";\nimport { P256Credential } from \"webauthn-p256\";\nimport { toCoinbaseSmartAccount, ToCoinbaseSmartAccountReturnType } from \"../smart-account/toCoinbaseSmartAccount\";\n\nexport async function getAccount(client: Client, id: P256Credential[\"id\"]): Promise<ToCoinbaseSmartAccountReturnType> {\n const { publicKeys } = cache.getState();\n\n const publicKey = publicKeys[id];\n // TODO: should we prompt to recover key here?\n if (!publicKey) {\n throw new Error(\"No public key found for passkey credential.\");\n }\n\n const passkey = toWebAuthnAccount({ credential: { id, publicKey } });\n const owners = [passkey];\n\n return await toCoinbaseSmartAccount({ client, owners });\n}\n","// Forked from https://github.com/wevm/viem/blob/main/src/account-abstraction/accounts/implementations/toCoinbaseSmartAccount.ts\n// to match our forked contracts (upgrade to v0.7 entrypoint)\nimport { BaseError, type Address, type TypedData } from \"abitype\";\nimport {\n Client,\n OneOf,\n LocalAccount,\n Prettify,\n Assign,\n pad,\n encodeFunctionData,\n hashMessage,\n TypedDataDefinition,\n hashTypedData,\n Hash,\n encodeAbiParameters,\n stringToHex,\n size,\n encodePacked,\n parseSignature,\n} from \"viem\";\nimport {\n WebAuthnAccount,\n SmartAccount,\n SmartAccountImplementation,\n entryPoint07Abi,\n entryPoint07Address,\n getUserOperationHash,\n UserOperation,\n toSmartAccount,\n} from \"viem/account-abstraction\";\nimport { readContract } from \"viem/actions\";\nimport { type WebAuthnData, parseSignature as parseP256Signature, Hex } from \"webauthn-p256\";\n\nexport type ToCoinbaseSmartAccountParameters = {\n address?: Address | undefined;\n client: Client;\n owners: readonly OneOf<LocalAccount | WebAuthnAccount>[];\n nonce?: bigint | undefined;\n signer?: OneOf<LocalAccount | WebAuthnAccount>;\n};\n\nexport type ToCoinbaseSmartAccountReturnType = Prettify<SmartAccount<CoinbaseSmartAccountImplementation>>;\n\nexport type CoinbaseSmartAccountImplementation = Assign<\n SmartAccountImplementation<\n typeof entryPoint07Abi,\n \"0.7\",\n {\n __isCoinbaseSmartAccount: true;\n abi: typeof abi;\n factory: { abi: typeof factoryAbi; address: Address };\n signer: OneOf<LocalAccount | WebAuthnAccount>;\n }\n >,\n {\n sign: NonNullable<SmartAccountImplementation[\"sign\"]>;\n // TODO: should this be inside `extend` of `SmartAccountImplementation`?\n isOwner: (account: LocalAccount | WebAuthnAccount) => Promise<boolean>;\n }\n>;\n\n/**\n * @description Create a Coinbase Smart Account.\n *\n * @param parameters - {@link ToCoinbaseSmartAccountParameters}\n * @returns Coinbase Smart Account. {@link ToCoinbaseSmartAccountReturnType}\n *\n * @example\n * import { toCoinbaseSmartAccount } from 'viem/account-abstraction'\n * import { privateKeyToAccount } from 'viem/accounts'\n * import { client } from './client.js'\n *\n * const account = toCoinbaseSmartAccount({\n * client,\n * owners: [privateKeyToAccount('0x...')],\n * })\n */\nexport async function toCoinbaseSmartAccount(\n parameters: ToCoinbaseSmartAccountParameters,\n): Promise<ToCoinbaseSmartAccountReturnType> {\n const { client, owners, nonce = 0n } = parameters;\n\n let address = parameters.address;\n\n const entryPoint = {\n abi: entryPoint07Abi,\n address: entryPoint07Address,\n version: \"0.7\",\n } as const;\n const factory = {\n abi: factoryAbi,\n // TODO: make configurable?\n address: \"0x356336adA1619BeC1Ae4E6D94Dd9c0490DA414a8\",\n } as const;\n\n if (!owners.length) {\n throw new Error(\"`owners` must have at least one account.\");\n }\n\n function accountToBytes(account: LocalAccount | WebAuthnAccount) {\n return account.type === \"webAuthn\" ? account.publicKey : pad(account.address);\n }\n\n const owner = parameters.signer ?? owners[0];\n const ownerIndex = owners.indexOf(owner);\n if (ownerIndex === -1) {\n throw new Error(\"`signer` must be one of `owners`.\");\n }\n\n return toSmartAccount({\n client,\n entryPoint,\n\n extend: {\n __isCoinbaseSmartAccount: true as const,\n abi,\n factory,\n signer: owner,\n },\n\n async encodeCalls(calls) {\n if (calls.length === 1)\n return encodeFunctionData({\n abi,\n functionName: \"execute\",\n args: [calls[0].to, calls[0].value ?? 0n, calls[0].data ?? \"0x\"],\n });\n return encodeFunctionData({\n abi,\n functionName: \"executeBatch\",\n args: [\n calls.map((call) => ({\n data: call.data ?? \"0x\",\n target: call.to,\n value: call.value ?? 0n,\n })),\n ],\n });\n },\n\n async getAddress() {\n address ??= await readContract(client, {\n ...factory,\n functionName: \"getAddress\",\n args: [owners.map(accountToBytes), nonce],\n });\n return address;\n },\n\n async getFactoryArgs() {\n const factoryData = encodeFunctionData({\n abi: factory.abi,\n functionName: \"createAccount\",\n args: [owners.map(accountToBytes), nonce],\n });\n return { factory: factory.address, factoryData };\n },\n\n async getStubSignature() {\n if (owner.type === \"webAuthn\")\n // eslint-disable-next-line max-len\n return \"0x0000000000000000000000000000000000000000000000000000000000000020000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000400000000000000000000000000000000000000000000000000000000000000200000000000000000000000000000000000000000000000000000000000000002000000000000000000000000000000000000000000000000000000000000000c0000000000000000000000000000000000000000000000000000000000000012000000000000000000000000000000000000000000000000000000000000000170000000000000000000000000000000000000000000000000000000000000001949fc7c88032b9fcb5f6efc7a7b8c63668eae9871b765e23123bb473ff57aa831a7c0d9276168ebcc29f2875a0239cffdf2a9cd1c2007c5c77c071db9264df1d000000000000000000000000000000000000000000000000000000000000002549960de5880e8c687434170f6476605b8fe4aeb9a28632c7995cf3ba831d97630500000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000008a7b2274797065223a22776562617574686e2e676574222c226368616c6c656e6765223a2273496a396e6164474850596759334b7156384f7a4a666c726275504b474f716d59576f4d57516869467773222c226f726967696e223a2268747470733a2f2f7369676e2e636f696e626173652e636f6d222c2263726f73734f726967696e223a66616c73657d00000000000000000000000000000000000000000000\";\n return wrapSignature({\n signature:\n \"0xfffffffffffffffffffffffffffffff0000000000000000000000000000000007aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa1c\",\n ownerIndex,\n });\n },\n\n async sign(parameters) {\n const address = await this.getAddress();\n\n const hash = toReplaySafeHash({\n address,\n chainId: client.chain!.id,\n hash: parameters.hash,\n });\n\n const signature = await sign({ hash, owner });\n\n return wrapSignature({ signature, ownerIndex });\n },\n\n async signMessage(parameters) {\n const { message } = parameters;\n const address = await this.getAddress();\n\n const hash = toReplaySafeHash({\n address,\n chainId: client.chain!.id,\n hash: hashMessage(message),\n });\n\n const signature = await sign({ hash, owner });\n\n return wrapSignature({ signature, ownerIndex });\n },\n\n async signTypedData(parameters) {\n const { domain, types, primaryType, message } = parameters as TypedDataDefinition<TypedData, string>;\n const address = await this.getAddress();\n\n const hash = toReplaySafeHash({\n address,\n chainId: client.chain!.id,\n hash: hashTypedData({\n domain,\n message,\n primaryType,\n types,\n }),\n });\n\n const signature = await sign({ hash, owner });\n\n return wrapSignature({ signature, ownerIndex });\n },\n\n async signUserOperation(parameters) {\n const { chainId = client.chain!.id, ...userOperation } = parameters;\n\n const address = await this.getAddress();\n const hash = getUserOperationHash({\n chainId,\n entryPointAddress: entryPoint.address,\n entryPointVersion: entryPoint.version,\n userOperation: {\n ...(userOperation as unknown as UserOperation),\n sender: address,\n },\n });\n\n const signature = await sign({ hash, owner });\n\n return wrapSignature({ signature, ownerIndex });\n },\n\n userOperation: {\n async estimateGas(userOperation) {\n if (owner.type !== \"webAuthn\") return;\n\n // Accounts with WebAuthn owner require a minimum verification gas limit of 800,000.\n return {\n verificationGasLimit: BigInt(Math.max(Number(userOperation.verificationGasLimit ?? 0n), 800_000)),\n };\n },\n },\n\n async isOwner(account: LocalAccount | WebAuthnAccount) {\n return await readContract(client, {\n abi,\n address: await this.getAddress(),\n functionName: \"isOwnerBytes\",\n args: [accountToBytes(account)],\n });\n },\n });\n}\n\n/////////////////////////////////////////////////////////////////////////////////////////////\n// Utilities\n/////////////////////////////////////////////////////////////////////////////////////////////\n\n/** @internal */\nexport async function sign({ hash, owner }: { hash: Hash; owner: OneOf<LocalAccount | WebAuthnAccount> }) {\n // WebAuthn Account (Passkey)\n if (owner.type === \"webAuthn\") {\n const { signature, webauthn } = await owner.sign({\n hash,\n });\n return toWebAuthnSignature({ signature, webauthn });\n }\n\n if (owner.sign) return owner.sign({ hash });\n\n throw new BaseError(\"`owner` does not support raw sign.\");\n}\n\n/** @internal */\nexport function toReplaySafeHash({ address, chainId, hash }: { address: Address; chainId: number; hash: Hash }) {\n return hashTypedData({\n domain: {\n chainId,\n name: \"Coinbase Smart Wallet\",\n verifyingContract: address,\n version: \"1\",\n },\n types: {\n CoinbaseSmartWalletMessage: [\n {\n name: \"hash\",\n type: \"bytes32\",\n },\n ],\n },\n primaryType: \"CoinbaseSmartWalletMessage\",\n message: {\n hash,\n },\n });\n}\n\n/** @internal */\nexport function toWebAuthnSignature({ webauthn, signature }: { webauthn: WebAuthnData; signature: Hex }) {\n const { r, s } = parseP256Signature(signature);\n return encodeAbiParameters(\n [\n {\n components: [\n {\n name: \"authenticatorData\",\n type: \"bytes\",\n },\n { name: \"clientDataJSON\", type: \"bytes\" },\n { name: \"challengeIndex\", type: \"uint256\" },\n { name: \"typeIndex\", type: \"uint256\" },\n {\n name: \"r\",\n type: \"uint256\",\n },\n {\n name: \"s\",\n type: \"uint256\",\n },\n ],\n type: \"tuple\",\n },\n ],\n [\n {\n authenticatorData: webauthn.authenticatorData,\n clientDataJSON: stringToHex(webauthn.clientDataJSON),\n challengeIndex: BigInt(webauthn.challengeIndex),\n typeIndex: BigInt(webauthn.typeIndex),\n r,\n s,\n },\n ],\n );\n}\n\n/** @internal */\nexport function wrapSignature(parameters: { ownerIndex: number; signature: Hex }) {\n const { ownerIndex } = parameters;\n const signatureData = (() => {\n if (size(parameters.signature) !== 65) return parameters.signature;\n const signature = parseSignature(parameters.signature);\n return encodePacked([\"bytes32\", \"bytes32\", \"uint8\"], [signature.r, signature.s, signature.yParity === 0 ? 27 : 28]);\n })();\n return encodeAbiParameters(\n [\n {\n components: [\n {\n name: \"ownerIndex\",\n type: \"uint8\",\n },\n {\n name: \"signatureData\",\n type: \"bytes\",\n },\n ],\n type: \"tuple\",\n },\n ],\n [\n {\n ownerIndex,\n signatureData,\n },\n ],\n );\n}\n\n/////////////////////////////////////////////////////////////////////////////////////////////\n// Constants\n/////////////////////////////////////////////////////////////////////////////////////////////\n\nconst abi = [\n { inputs: [], stateMutability: \"nonpayable\", type: \"constructor\" },\n {\n inputs: [{ name: \"owner\", type: \"bytes\" }],\n name: \"AlreadyOwner\",\n type: \"error\",\n },\n { inputs: [], name: \"Initialized\", type: \"error\" },\n {\n inputs: [{ name: \"owner\", type: \"bytes\" }],\n name: \"InvalidEthereumAddressOwner\",\n type: \"error\",\n },\n {\n inputs: [{ name: \"key\", type: \"uint256\" }],\n name: \"InvalidNonceKey\",\n type: \"error\",\n },\n {\n inputs: [{ name: \"owner\", type: \"bytes\" }],\n name: \"InvalidOwnerBytesLength\",\n type: \"error\",\n },\n { inputs: [], name: \"LastOwner\", type: \"error\" },\n {\n inputs: [{ name: \"index\", type: \"uint256\" }],\n name: \"NoOwnerAtIndex\",\n type: \"error\",\n },\n {\n inputs: [{ name: \"ownersRemaining\", type: \"uint256\" }],\n name: \"NotLastOwner\",\n type: \"error\",\n },\n {\n inputs: [{ name: \"selector\", type: \"bytes4\" }],\n name: \"SelectorNotAllowed\",\n type: \"error\",\n },\n { inputs: [], name: \"Unauthorized\", type: \"error\" },\n { inputs: [], name: \"UnauthorizedCallContext\", type: \"error\" },\n { inputs: [], name: \"UpgradeFailed\", type: \"error\" },\n {\n inputs: [\n { name: \"index\", type: \"uint256\" },\n { name: \"expectedOwner\", type: \"bytes\" },\n { name: \"actualOwner\", type: \"bytes\" },\n ],\n name: \"WrongOwnerAtIndex\",\n type: \"error\",\n },\n {\n anonymous: false,\n inputs: [\n {\n indexed: true,\n\n name: \"index\",\n type: \"uint256\",\n },\n { indexed: false, name: \"owner\", type: \"bytes\" },\n ],\n name: \"AddOwner\",\n type: \"event\",\n },\n {\n anonymous: false,\n inputs: [\n {\n indexed: true,\n\n name: \"index\",\n type: \"uint256\",\n },\n { indexed: false, name: \"owner\", type: \"bytes\" },\n ],\n name: \"RemoveOwner\",\n type: \"event\",\n },\n {\n anonymous: false,\n inputs: [\n {\n indexed: true,\n\n name: \"implementation\",\n type: \"address\",\n },\n ],\n name: \"Upgraded\",\n type: \"event\",\n },\n { stateMutability: \"payable\", type: \"fallback\" },\n {\n inputs: [],\n name: \"REPLAYABLE_NONCE_KEY\",\n outputs: [{ name: \"\", type: \"uint256\" }],\n stateMutability: \"view\",\n type: \"function\",\n },\n {\n inputs: [{ name: \"owner\", type: \"address\" }],\n name: \"addOwnerAddress\",\n outputs: [],\n stateMutability: \"nonpayable\",\n type: \"function\",\n },\n {\n inputs: [\n { name: \"x\", type: \"bytes32\" },\n { name: \"y\", type: \"bytes32\" },\n ],\n name: \"addOwnerPublicKey\",\n outputs: [],\n stateMutability: \"nonpayable\",\n type: \"function\",\n },\n {\n inputs: [{ name: \"functionSelector\", type: \"bytes4\" }],\n name: \"canSkipChainIdValidation\",\n outputs: [{ name: \"\", type: \"bool\" }],\n stateMutability: \"pure\",\n type: \"function\",\n },\n {\n inputs: [],\n name: \"domainSeparator\",\n outputs: [{ name: \"\", type: \"bytes32\" }],\n stateMutability: \"view\",\n type: \"function\",\n },\n {\n inputs: [],\n name: \"eip712Domain\",\n outputs: [\n { name: \"fields\", type: \"bytes1\" },\n { name: \"name\", type: \"string\" },\n { name: \"version\", type: \"string\" },\n { name: \"chainId\", type: \"uint256\" },\n { name: \"verifyingContract\", type: \"address\" },\n { name: \"salt\", type: \"bytes32\" },\n { name: \"extensions\", type: \"uint256[]\" },\n ],\n stateMutability: \"view\",\n type: \"function\",\n },\n {\n inputs: [],\n name: \"entryPoint\",\n outputs: [{ name: \"\", type: \"address\" }],\n stateMutability: \"view\",\n type: \"function\",\n },\n {\n inputs: [\n { name: \"target\", type: \"address\" },\n { name: \"value\", type: \"uint256\" },\n { name: \"data\", type: \"bytes\" },\n ],\n name: \"execute\",\n outputs: [],\n stateMutability: \"payable\",\n type: \"function\",\n },\n {\n inputs: [\n {\n components: [\n { name: \"target\", type: \"address\" },\n { name: \"value\", type: \"uint256\" },\n { name: \"data\", type: \"bytes\" },\n ],\n\n name: \"calls\",\n type: \"tuple[]\",\n },\n ],\n name: \"executeBatch\",\n outputs: [],\n stateMutability: \"payable\",\n type: \"function\",\n },\n {\n inputs: [{ name: \"calls\", type: \"bytes[]\" }],\n name: \"executeWithoutChainIdValidation\",\n outputs: [],\n stateMutability: \"payable\",\n type: \"function\",\n },\n {\n inputs: [\n {\n components: [\n { name: \"sender\", type: \"address\" },\n { name: \"nonce\", type: \"uint256\" },\n { name: \"initCode\", type: \"bytes\" },\n { name: \"callData\", type: \"bytes\" },\n { name: \"callGasLimit\", type: \"uint256\" },\n {\n name: \"verificationGasLimit\",\n type: \"uint256\",\n },\n {\n name: \"preVerificationGas\",\n type: \"uint256\",\n },\n { name: \"maxFeePerGas\", type: \"uint256\" },\n {\n name: \"maxPriorityFeePerGas\",\n type: \"uint256\",\n },\n { name: \"paymasterAndData\", type: \"bytes\" },\n { name: \"signature\", type: \"bytes\" },\n ],\n\n name: \"userOp\",\n type: \"tuple\",\n },\n ],\n name: \"getUserOpHashWithoutChainId\",\n outputs: [{ name: \"\", type: \"bytes32\" }],\n stateMutability: \"view\",\n type: \"function\",\n },\n {\n inputs: [],\n name: \"implementation\",\n outputs: [{ name: \"$\", type: \"address\" }],\n stateMutability: \"view\",\n type: \"function\",\n },\n {\n inputs: [{ name: \"owners\", type: \"bytes[]\" }],\n name: \"initialize\",\n outputs: [],\n stateMutability: \"payable\",\n type: \"function\",\n },\n {\n inputs: [{ name: \"account\", type: \"address\" }],\n name: \"isOwnerAddress\",\n outputs: [{ name: \"\", type: \"bool\" }],\n stateMutability: \"view\",\n type: \"function\",\n },\n {\n inputs: [{ name: \"account\", type: \"bytes\" }],\n name: \"isOwnerBytes\",\n outputs: [{ name: \"\", type: \"bool\" }],\n stateMutability: \"view\",\n type: \"function\",\n },\n {\n inputs: [\n { name: \"x\", type: \"bytes32\" },\n { name: \"y\", type: \"bytes32\" },\n ],\n name: \"isOwnerPublicKey\",\n outputs: [{ name: \"\", type: \"bool\" }],\n stateMutability: \"view\",\n type: \"function\",\n },\n {\n inputs: [\n { name: \"hash\", type: \"bytes32\" },\n { name: \"signature\", type: \"bytes\" },\n ],\n name: \"isValidSignature\",\n outputs: [{ name: \"result\", type: \"bytes4\" }],\n stateMutability: \"view\",\n type: \"function\",\n },\n {\n inputs: [],\n name: \"nextOwnerIndex\",\n outputs: [{ name: \"\", type: \"uint256\" }],\n stateMutability: \"view\",\n type: \"function\",\n },\n {\n inputs: [{ name: \"index\", type: \"uint256\" }],\n name: \"ownerAtIndex\",\n outputs: [{ name: \"\", type: \"bytes\" }],\n stateMutability: \"view\",\n type: \"function\",\n },\n {\n inputs: [],\n name: \"ownerCount\",\n outputs: [{ name: \"\", type: \"uint256\" }],\n stateMutability: \"view\",\n type: \"function\",\n },\n {\n inputs: [],\n name: \"proxiableUUID\",\n outputs: [{ name: \"\", type: \"bytes32\" }],\n stateMutability: \"view\",\n type: \"function\",\n },\n {\n inputs: [\n { name: \"index\", type: \"uint256\" },\n { name: \"owner\", type: \"bytes\" },\n ],\n name: \"removeLastOwner\",\n outputs: [],\n stateMutability: \"nonpayable\",\n type: \"function\",\n },\n {\n inputs: [\n { name: \"index\", type: \"uint256\" },\n { name: \"owner\", type: \"bytes\" },\n ],\n name: \"removeOwnerAtIndex\",\n outputs: [],\n stateMutability: \"nonpayable\",\n type: \"function\",\n },\n {\n inputs: [],\n name: \"removedOwnersCount\",\n outputs: [{ name: \"\", type: \"uint256\" }],\n stateMutability: \"view\",\n type: \"function\",\n },\n {\n inputs: [{ name: \"hash\", type: \"bytes32\" }],\n name: \"replaySafeHash\",\n outputs: [{ name: \"\", type: \"bytes32\" }],\n stateMutability: \"view\",\n type: \"function\",\n },\n {\n inputs: [\n { name: \"newImplementation\", type: \"address\" },\n { name: \"data\", type: \"bytes\" },\n ],\n name: \"upgradeToAndCall\",\n outputs: [],\n stateMutability: \"payable\",\n type: \"function\",\n },\n {\n inputs: [\n {\n components: [\n { name: \"sender\", type: \"address\" },\n { name: \"nonce\", type: \"uint256\" },\n { name: \"initCode\", type: \"bytes\" },\n { name: \"callData\", type: \"bytes\" },\n { name: \"callGasLimit\", type: \"uint256\" },\n {\n name: \"verificationGasLimit\",\n type: \"uint256\",\n },\n {\n name: \"preVerificationGas\",\n type: \"uint256\",\n },\n { name: \"maxFeePerGas\", type: \"uint256\" },\n {\n name: \"maxPriorityFeePerGas\",\n type: \"uint256\",\n },\n { name: \"paymasterAndData\", type: \"bytes\" },\n { name: \"signature\", type: \"bytes\" },\n ],\n\n name: \"userOp\",\n type: \"tuple\",\n },\n { name: \"userOpHash\", type: \"bytes32\" },\n { name: \"missingAccountFunds\", type: \"uint256\" },\n ],\n name: \"validateUserOp\",\n outputs: [{ name: \"validationData\", type: \"uint256\" }],\n stateMutability: \"nonpayable\",\n type: \"function\",\n },\n { stateMutability: \"payable\", type: \"receive\" },\n] as const;\n\nconst factoryAbi = [\n {\n inputs: [{ name: \"implementation_\", type: \"address\" }],\n stateMutability: \"payable\",\n type: \"constructor\",\n },\n { inputs: [], name: \"OwnerRequired\", type: \"error\" },\n {\n inputs: [\n { name: \"owners\", type: \"bytes[]\" },\n { name: \"nonce\", type: \"uint256\" },\n ],\n name: \"createAccount\",\n outputs: [\n {\n name: \"account\",\n type: \"address\",\n },\n ],\n stateMutability: \"payable\",\n type: \"function\",\n },\n {\n inputs: [\n { name: \"owners\", type: \"bytes[]\" },\n { name: \"nonce\", type: \"uint256\" },\n ],\n name: \"getAddress\",\n outputs: [{ name: \"\", type: \"address\" }],\n stateMutability: \"view\",\n type: \"function\",\n },\n {\n inputs: [],\n name: \"implementation\",\n outputs: [{ name: \"\", type: \"address\" }],\n stateMutability: \"view\",\n type: \"function\",\n },\n {\n inputs: [],\n name: \"initCodeHash\",\n outputs: [{ name: \"\", type: \"bytes32\" }],\n stateMutability: \"view\",\n type: \"function\",\n },\n] as const;\n","import { bytesToHex, hashMessage } from \"viem\";\nimport { sign } from \"webauthn-p256\";\nimport { cache } from \"./cache\";\nimport { getMessageHash } from \"./getMessageHash\";\nimport { recoverPasskeyPublicKey } from \"./recoverPasskeyPublicKey\";\nimport { P256Credential } from \"viem/account-abstraction\";\n\nexport async function reusePasskey(): Promise<P256Credential> {\n const randomChallenge = bytesToHex(crypto.getRandomValues(new Uint8Array(256)));\n const messageHash = hashMessage(randomChallenge);\n const { signature, webauthn, raw: credential } = await sign({ hash: messageHash });\n\n const publicKey = await (async () => {\n const publicKey = cache.getState().publicKeys[credential.id];\n if (publicKey) return publicKey;\n\n // TODO: look up account/public key by credential ID once we store it onchain\n\n const webauthnHash = await getMessageHash(webauthn);\n const passkey = await recoverPasskeyPublicKey({\n credentialId: credential.id,\n messageHash: webauthnHash,\n signatureHex: signature,\n });\n if (!passkey) {\n throw new Error(\"recovery failed\");\n }\n if (passkey.credential.id !== credential.id) {\n throw new Error(\"wrong credential\");\n }\n\n cache.setState((state) => ({\n publicKeys: {\n ...state.publicKeys,\n [credential.id]: passkey.publicKey,\n },\n }));\n\n return passkey.publicKey;\n })();\n\n console.log(\"recovered passkey\", credential.id, publicKey);\n\n cache.setState(() => ({\n activeCredential: credential.id,\n }));\n\n return { id: credential.id, publicKey, raw: credential };\n}\n","import { bytesToHex, Hex, hexToBytes, WebAuthnData } from \"webauthn-p256\";\nimport { concatBytes, utf8ToBytes } from \"@noble/curves/abstract/utils\";\n\n// lifted out of https://github.com/wevm/webauthn-p256/blob/main/src/verify.ts\n// TODO: submit a PR to lift this out as a function that can be exported\n\nexport async function getMessageHash(\n webauthn: Omit<WebAuthnData, \"typeIndex\" | \"challengeIndex\"> & {\n challengeIndex?: number;\n typeIndex?: number;\n },\n): Promise<Hex | never> {\n const {\n authenticatorData,\n challengeIndex: challengeIndexRaw,\n clientDataJSON,\n typeIndex: typeIndexRaw,\n userVerificationRequired,\n } = webauthn;\n\n const typeIndex = typeIndexRaw || clientDataJSON.indexOf('\"type\"');\n const challengeIndex = challengeIndexRaw || clientDataJSON.indexOf('\"challenge\"');\n\n const authenticatorDataBytes = hexToBytes(authenticatorData);\n\n // Check length of `authenticatorData`.\n if (authenticatorDataBytes.length < 37) throw new Error(\"Invalid authenticatorData\");\n\n const flag = authenticatorDataBytes[32]!;\n\n // Verify that the UP bit of the flags in authData is set.\n if ((flag & 0x01) !== 0x01) throw new Error(\"Invalid authenticatorData\");\n\n // If user verification was determined to be required, verify that\n // the UV bit of the flags in authData is set. Otherwise, ignore the\n // value of the UV flag.\n if (userVerificationRequired && (flag & 0x04) !== 0x04) throw new Error(\"Invalid authenticatorData\");\n\n // If the BE bit of the flags in authData is not set, verify that\n // the BS bit is not set.\n if ((flag & 0x08) !== 0x08 && (flag & 0x10) === 0x10) throw new Error(\"Invalid authenticatorData\");\n\n // Check that response is for an authentication assertion\n const type = '\"type\":\"webauthn.get\"';\n if (type !== clientDataJSON.slice(Number(typeIndex), type.length + 1)) throw new Error(\"Invalid clientDataJSON\");\n\n // Check that hash is in the clientDataJSON.\n const match = clientDataJSON.slice(Number(challengeIndex)).match(/^\"challenge\":\"(.*?)\"/);\n if (!match) throw new Error(\"Invalid clientDataJSON\");\n\n const clientDataJSONHash = new Uint8Array(await crypto.subtle.digest(\"SHA-256\", utf8ToBytes(clientDataJSON)));\n const messageHash = new Uint8Array(\n await crypto.subtle.digest(\"SHA-256\", concatBytes(hexToBytes(authenticatorData), clientDataJSONHash)),\n );\n\n return bytesToHex(messageHash);\n}\n","import { sign } from \"webauthn-p256\";\nimport { getMessageHash } from \"./getMessageHash\";\nimport { getCandidatePublicKeys } from \"./getCandidatePublicKeys\";\nimport { SignatureAndMessage } from \"./common\";\nimport { hashMessage, Hex } from \"viem\";\nimport { P256Credential } from \"viem/account-abstraction\";\n\nexport function findPublicKey([input1, input2]: [SignatureAndMessage, SignatureAndMessage]): Hex | undefined {\n // Return the candidate public key that appears twice\n return firstDuplicate([...getCandidatePublicKeys(input1), ...getCandidatePublicKeys(input2)]);\n}\n\nexport async function recoverPasskeyPublicKey(input: { credentialId: P256Credential[\"id\"] } & SignatureAndMessage) {\n const message2 = hashMessage(input.signatureHex);\n const {\n signature: signature2,\n webauthn: webauthn2,\n raw: credential,\n } = await sign({ credentialId: input.credentialId, hash: message2 });\n const messageHash2 = await getMessageHash(webauthn2);\n\n const publicKey = findPublicKey([input, { signatureHex: signature2, messageHash: messageHash2 }]);\n if (publicKey) {\n return { publicKey, credential };\n }\n}\n\nfunction firstDuplicate<T>(arr: T[]): T | undefined {\n const seen = new Set<T>();\n for (const s of arr) {\n if (seen.has(s)) {\n return s;\n }\n seen.add(s);\n }\n return undefined;\n}\n","import { parseSignature, serializePublicKey } from \"webauthn-p256\";\nimport { SignatureAndMessage } from \"./common\";\nimport { secp256r1 } from \"@noble/curves/p256\";\n\nexport function getCandidatePublicKeys(input: SignatureAndMessage) {\n const { r, s } = parseSignature(input.signatureHex);\n\n const candidate1 = new secp256r1.Signature(r, s).addRecoveryBit(1).recoverPublicKey(input.messageHash.slice(2));\n const candidate2 = new secp256r1.Signature(r, s).addRecoveryBit(0).recoverPublicKey(input.messageHash.slice(2));\n\n return [serializePublicKey(candidate1), serializePublicKey(candidate2)];\n}\n","import { createCredential } from \"webauthn-p256\";\nimport { cache } from \"./cache\";\nimport { P256Credential } from \"viem/account-abstraction\";\n\nexport async function createPasskey(): Promise<P256Credential> {\n const credential = await createCredential({ name: \"MUD Account\" });\n console.log(\"created passkey\", credential);\n\n cache.setState((state) => ({\n activeCredential: credential.id,\n publicKeys: {\n ...state.publicKeys,\n [credential.id]: credential.publicKey,\n },\n }));\n\n return credential;\n}\n","import { resourceToHex } from \"@latticexyz/common\";\nimport { Client, Chain, Transport, Account, parseAbi, ClientConfig } from \"viem\";\nimport worldConfig from \"@latticexyz/world/mud.config\";\n\nexport type ConnectedClient = Client<Transport, Chain, Account>;\n\nexport const defaultClientConfig = {\n pollingInterval: 250,\n} as const satisfies Pick<ClientConfig, \"pollingInterval\">;\n\nexport const unlimitedDelegationControlId = resourceToHex({ type: \"system\", namespace: \"\", name: \"unlimited\" });\n\nexport const worldTables = worldConfig.namespaces.world.tables;\n\nexport const worldAbi = parseAbi([\n \"function registerDelegation(address delegatee, bytes32 delegationControlId, bytes initCallData)\",\n]);\n"],"mappings":"AAAA,OACE,gBAAAA,GACA,UAAAC,GAGA,cAAAC,GACA,eAAAC,EACA,oBAAAC,OAKK,OACP,OAAS,2BAAAC,GAAyB,mBAAAC,OAA0C,QCb5E,OAAS,eAAAC,MAAmB,kBAC5B,OAAS,WAAAC,MAAe,qBAiBjB,IAAMC,EAAQF,EACnBC,EACE,KAAO,CACL,WAAY,CAAC,EACb,UAAW,CAAC,EACZ,iBAAkB,IACpB,GACA,CAAE,KAAM,mBAAoB,CAC9B,CACF,EAGA,SAASE,EAASC,EAAqB,CACjCA,EAAM,MAAQF,EAAM,QAAQ,WAAW,EAAE,MAC3CA,EAAM,QAAQ,UAAU,CAE5B,CACA,OAAO,iBAAiB,UAAWC,CAAQ,EDpB3C,OAAS,4BAAAE,OAAgC,yBEdzC,OAAS,qBAAAC,OAAyB,2BCClC,OAAS,aAAAC,MAA+C,UACxD,OAME,OAAAC,EACA,sBAAAC,EACA,eAAAC,EAEA,iBAAAC,EAEA,uBAAAC,EACA,eAAAC,EACA,QAAAC,EACA,gBAAAC,EACA,kBAAAC,MACK,OACP,OAIE,mBAAAC,EACA,uBAAAC,EACA,wBAAAC,EAEA,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M,gBAAgB,EAEnD,IAAMZ,EAAU,MAAMC,EAAWR,EAAQmB,CAAY,EAErD,OAAOC,GAAyB,CAC9B,GAAGlB,EACH,iBAAAT,EACA,OAAAO,EACA,QAAAO,EACA,UAAW,CACT,iBAAkB,UAAa,CAC7B,UAAWb,EACX,cAAe,IACjB,EACF,EACA,cAAe,CACb,mBAIEM,EAAO,MAAM,KAAO,MAChB,UAAa,CACX,aAAc,QACd,qBAAsB,EACxB,GACA,MACR,CACF,CAAC,CACH,EAEA,MAAM,YAAYqB,EAAS,CAGzB,OAAOC,GAAO,CAAE,QAAStB,EAAO,UAAU,OAAQ,CAAC,EAAE,CAAE,WAAY,CAAE,CAAC,CACxE,CACF,CACF,CAAC,CACH","names":["createClient","custom","getAddress","numberToHex","SwitchChainError","ChainNotConfiguredError","createConnector","createStore","persist","cache","listener","event","createSmartAccountClient","toWebAuthnAccount","BaseError","pad","encodeFunctionData","hashMessage","hashTypedData","encodeAbiParameters","stringToHex","size","encodePacked","parseSignature","entryPoint07Abi","entryPoint07Address","getUserOperationHash","toSmartAccount","readContract","parseP256Signature","toCoinbaseSmartAccount","parameters","client","owners","nonce","address","entryPoint","factory","factoryAbi","accountToBytes","account","owner","ownerIndex","abi","calls","call","factoryData","wrapSignature","hash","toReplaySafeHash","signature","sign","message","domain","types","primaryType","chainId","userOperation","webauthn","toWebAuthnSignature","r","s","signatureData","getAccount","client","id","publicKeys","cache","publicKey","owners","toWebAuthnAccount","toCoinbaseSmartAccount","bytesToHex","hashMessage","sign","bytesToHex","hexToBytes","concatBytes","utf8ToBytes","getMessageHash","webauthn","authenticatorData","challengeIndexRaw","clientDataJSON","typeIndexRaw","userVerificationRequired","typeIndex","challengeIndex","authenticatorDataBytes","flag","type","clientDataJSONHash","messageHash","sign","parseSignature","serializePublicKey","secp256r1","getCandidatePublicKeys","input","r","s","candidate1","candidate2","hashMessage","findPublicKey","input1","input2","firstDuplicate","getCandidatePublicKeys","recoverPasskeyPublicKey","input","message2","signature2","webauthn2","credential","sign","messageHash2","getMessageHash","publicKey","arr","seen","s","reusePasskey","randomChallenge","bytesToHex","messageHash","hashMessage","signature","webauthn","credential","sign","publicKey","cache","webauthnHash","getMessageHash","passkey","recoverPasskeyPublicKey","state","createCredential","createPasskey","credential","createCredential","cache","state","resourceToHex","parseAbi","worldConfig","defaultClientConfig","unlimitedDelegationControlId","worldTables","worldAbi","passkeyConnector","chainId","bundlerTransport","paymasterAddress","createConnector","config","chain","c","transport","client","createClient","defaultClientConfig","connected","cache","id","createPasskey","account","getAccount","numberToHex","reusePasskey","params","accounts","SwitchChainError","ChainNotConfiguredError","a","getAddress","_connectInfo","_error","credentialId","createSmartAccountClient","_params","custom"]}
@@ -0,0 +1,76 @@
1
+ import { Transport, Client, Chain, Account } from 'viem';
2
+ import { Address } from 'viem/accounts';
3
+ import * as react_jsx_runtime from 'react/jsx-runtime';
4
+ import { ReactNode } from 'react';
5
+
6
+ type EntryKitConfig = {
7
+ /**
8
+ * The chain ID where the world is deployed.
9
+ * There must be a matching chain entry in wagmi's configured chains.
10
+ * The app account client returned by EntryKit will be tied to this chain.
11
+ */
12
+ readonly chainId: number;
13
+ /**
14
+ * The world address.
15
+ */
16
+ readonly worldAddress: Address;
17
+ readonly bundlerTransport: Transport;
18
+ readonly paymasterAddress: Address;
19
+ readonly passIssuerTransport: Transport;
20
+ /**
21
+ * EntryKit UI theme.
22
+ *
23
+ * If not set, defaults to OS' light or dark mode.
24
+ */
25
+ theme?: "dark" | "light";
26
+ readonly appInfo?: {
27
+ /**
28
+ * The app name.
29
+ *
30
+ * If not set, defaults to page's `<title>`.
31
+ */
32
+ readonly name?: string;
33
+ /**
34
+ * The URL of the app icon used throughout the onboarding process. It will be used as a fallback if no `image` is provided. Icon should be 1:1 aspect ratio, at least 200x200.
35
+ *
36
+ * If not set, defaults to the page's `<link rel="icon">` or the origin's `/favicon.ico`.
37
+ */
38
+ readonly icon?: string;
39
+ /**
40
+ * The URL of the splash image displayed during the first step of onboarding. Ideally around 600x250.
41
+ *
42
+ * If not set, defaults to displaying the name, icon, and origin.
43
+ */
44
+ readonly image?: string;
45
+ /**
46
+ * Optional URL to your app's Terms of Use. If set, the step before asking users to sign in to your app will link to this page.
47
+ */
48
+ readonly termsOfUse?: string;
49
+ /**
50
+ * Optional URL to your app's Privacy Policy. If set, the step before asking users to sign in to your app will link to this page.
51
+ */
52
+ readonly privacyPolicy?: string;
53
+ };
54
+ };
55
+
56
+ type Props = {
57
+ config: EntryKitConfig;
58
+ children?: ReactNode;
59
+ };
60
+ declare function EntryKitProvider({ config, children }: Props): react_jsx_runtime.JSX.Element;
61
+
62
+ declare function AccountButton(): react_jsx_runtime.JSX.Element;
63
+
64
+ type UseAccountModalResult = {
65
+ readonly accountModalOpen: boolean;
66
+ readonly openAccountModal: () => void;
67
+ readonly closeAccountModal: () => void;
68
+ readonly toggleAccountModal: (open: boolean) => void;
69
+ };
70
+ declare function useAccountModal(): UseAccountModalResult;
71
+
72
+ type ConnectedClient = Client<Transport, Chain, Account>;
73
+
74
+ declare function usePreparedAppAccountClient(): ConnectedClient | undefined;
75
+
76
+ export { AccountButton, EntryKitConfig, EntryKitProvider, useAccountModal, usePreparedAppAccountClient as useAppAccountClient };