(function(u,n){typeof exports=="object"&&typeof module<"u"?n(exports,require("starknet")):typeof define=="function"&&define.amd?define(["exports","starknet"],n):(u=typeof globalThis<"u"?globalThis:u||self,n(u.sessions={},u.starknet))})(this,function(u,n){"use strict";const I="https://cloud.argent-api.com/v1";class E extends Error{constructor(t,e){super(t),this.cause=e,Error.captureStackTrace(this,this.constructor)}}class w{constructor(t,e,o=I){this.pubkey=t,this.accountSessionSignature=e,this.argentSessionServiceBaseUrl=o}async signTxAndSession(t,e,o,i,r){const a=n.transaction.getExecuteCalldata(t,e.cairoVersion),c=n.typedData.getMessageHash(o,e.walletAddress),d=n.stark.formatSignature(this.accountSessionSignature),g={session:{sessionHash:c,sessionAuthorisation:d,cacheAuthorisation:r,sessionSignature:{type:"StarknetKey",signer:{publicKey:this.pubkey,r:i[0].toString(),s:i[1].toString()}}}};if(Object.values(n.RPC.ETransactionVersion2).includes(e.version)){const l=e;g.transaction={contractAddress:l.walletAddress,calldata:a,maxFee:l.maxFee.toString(),nonce:l.nonce.toString(),version:n.num.toBigInt(l.version).toString(10),chainId:n.num.toBigInt(l.chainId).toString(10)}}else if(Object.values(n.RPC.ETransactionVersion3).includes(e.version)){const l=e;g.transaction={sender_address:l.walletAddress,calldata:a,nonce:l.nonce.toString(),version:n.num.toBigInt(l.version).toString(10),chain_id:n.num.toBigInt(l.chainId).toString(10),resource_bounds:{l1_gas:{max_amount:l.resourceBounds.l1_gas.max_amount.toString(),max_price_per_unit:l.resourceBounds.l1_gas.max_price_per_unit.toString()},l2_gas:{max_amount:l.resourceBounds.l1_gas.max_amount.toString(),max_price_per_unit:l.resourceBounds.l1_gas.max_price_per_unit.toString()}},tip:l.tip.toString(),paymaster_data:l.paymasterData.map(H=>H.toString()),account_deployment_data:l.accountDeploymentData,nonce_data_availability_mode:l.nonceDataAvailabilityMode,fee_data_availability_mode:l.feeDataAvailabilityMode}}else throw Error("unsupported signTransaction version");const p=await fetch(`${this.argentSessionServiceBaseUrl}/cosigner/signSession`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(g)});if(!p.ok){const l=await p.json();throw new E("Sign session error",l.status)}return(await p.json()).signature}async signSessionEFO(t,e,o,i,r,a){const c=n.typedData.getMessageHash(_(t,a),e),d=n.stark.formatSignature(this.accountSessionSignature),p={session:{sessionHash:c,sessionAuthorisation:d,cacheAuthorisation:r,sessionSignature:{type:"StarknetKey",signer:{publicKey:this.pubkey,r:i[0].toString(),s:i[1].toString()}}},message:{type:"eip712",accountAddress:e,chain:"starknet",message:o}},h=JSON.stringify(p,(M,T)=>typeof T=="bigint"?T.toString():T),l=await fetch(`${this.argentSessionServiceBaseUrl}/cosigner/signSessionEFO`,{method:"POST",headers:{"Content-Type":"application/json"},body:h});if(!l.ok){const M=await l.json();throw new E("Sign session error",M.status)}return(await l.json()).signature}}/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */function B(s){return s instanceof Uint8Array||s!=null&&typeof s=="object"&&s.constructor.name==="Uint8Array"}function j(s){if(!B(s))throw new Error("Uint8Array expected")}const P=Array.from({length:256},(s,t)=>t.toString(16).padStart(2,"0"));function K(s){j(s);let t="";for(let e=0;e({To:o.to,Selector:o.selector,Calldata:o.calldata}))}}}async function V(s,t,e,o,i,r="1"){i=i??await o.getChainId();const a=y(s,i,r),c=await e.signMessage(a,t);return{contractAddress:t,entrypoint:"execute_from_outside_v2",calldata:n.CallData.compile({...s,signature:c})}}var m=(s=>(s[s.Starknet=0]="Starknet",s[s.Secp256k1=1]="Secp256k1",s[s.Secp256r1=2]="Secp256r1",s[s.Eip191=3]="Eip191",s[s.Webauthn=4]="Webauthn",s))(m||{});const W=(s,t)=>{const e={Starknet:void 0,Secp256k1:void 0,Secp256r1:void 0,Eip191:void 0,Webauthn:void 0};if(s===m.Starknet)e.Starknet=t;else if(s===m.Secp256k1)e.Secp256k1=t;else if(s===m.Secp256r1)e.Secp256r1=t;else if(s===m.Eip191)e.Eip191=t;else if(s===m.Webauthn)e.Webauthn=t;else throw new Error("Unknown SignerType");return new n.CairoCustomEnum(e)},x=n.shortString.encodeShortString("session-token");class k extends n.Signer{constructor(t){super(),this.signTransactionCallback=t}async signRaw(t){throw new Error("Method not implemented.")}async signTransaction(t,e){return this.signTransactionCallback(t,e)}}class b{constructor(t,e,o){this.argentSessionService=t,this.chainId=e,this.dappKey=o}getAccountWithSessionSigner(t,e,o,i,r=!1){const a=new k((c,d)=>this.signTransaction(i,o,c,d,r));return new n.Account(t,e,a)}async signTransaction(t,e,o,i,r){const a=n.transaction.getExecuteCalldata(o,i.cairoVersion);let c;if(Object.values(n.RPC.ETransactionVersion2).includes(i.version)){const d=i;c=n.hash.calculateInvokeTransactionHash({...d,senderAddress:d.walletAddress,compiledCalldata:a,version:d.version})}else if(Object.values(n.RPC.ETransactionVersion3).includes(i.version)){const d=i;c=n.hash.calculateInvokeTransactionHash({...d,senderAddress:d.walletAddress,compiledCalldata:a,version:d.version,nonceDataAvailabilityMode:n.stark.intDAM(d.nonceDataAvailabilityMode),feeDataAvailabilityMode:n.stark.intDAM(d.feeDataAvailabilityMode)})}else throw Error("unsupported signTransaction version");return this.getSessionSignatureForTransaction(t,e,c,o,i.walletAddress,i,r)}async getSessionSignatureForTransaction(t,e,o,i,r,a,c){const d=this.compileSessionHelper(e),S=_(e,this.chainId),g=await this.signTxAndSession(o,r,S,c),p=await this.argentSessionService.signTxAndSession(i,a,S,g,c),h=await this.compileSessionTokenHelper(d,e,i,g,t,p,c);return[x,...n.CallData.compile(h)]}async signTxAndSession(t,e,o,i){const r=n.typedData.getMessageHash(o,e),a=n.hash.computePoseidonHashOnElements([t,r,+i]),c=n.ec.starkCurve.sign(a,this.dappKey.privateKey);return[c.r,c.s]}buildMerkleTree(t){const e=t.allowed_methods.map(o=>n.hash.computePoseidonHashOnElements([D,o["Contract Address"],n.selector.getSelectorFromName(o.selector)]));return new n.merkle.MerkleTree(e,n.hash.computePoseidonHash)}getSessionProofs(t,e){const o=this.buildMerkleTree(t);return e.map(i=>{const r=t.allowed_methods.findIndex(a=>n.num.hexToDecimalString(a["Contract Address"])===n.num.hexToDecimalString(i.contractAddress)&&a.selector==i.entrypoint);return o.getProof(o.leaves[r],o.leaves)})}compileSessionHelper(t){const e=n.byteArray.byteArrayFromString(t.metadata),o=[e.data.length,...e.data,e.pending_word,e.pending_word_len],i=n.hash.computePoseidonHashOnElements(o);return{expires_at:t.expires_at,allowed_methods_root:this.buildMerkleTree(t).root.toString(),metadata_hash:i,session_key_guid:t.session_key_guid}}async compileSessionTokenHelper(t,e,o,i,r,a,c){return{session:t,cache_authorization:c,session_authorization:r,sessionSignature:this.getStarknetSignatureType(this.dappKey.publicKey,i),guardianSignature:this.getStarknetSignatureType(a.publicKey,[a.r,a.s]),proofs:this.getSessionProofs(e,o)}}getStarknetSignatureType(t,e){return W(m.Starknet,{pubkey:t,r:e[0],s:e[1]})}buildOutsideExecution(t,e,o,i,r){const a=n.shortString.encodeShortString("ANY_CALLER"),c=n.encode.addHexPrefix(K(n.ec.starkCurve.utils.randomPrivateKey())),d=Date.now(),S=Math.floor((d+6e4*20)/1e3),g=Math.floor((d-6e4*10)/1e3);return{caller:e||a,nonce:r||c,execute_after:o||g,execute_before:i||S,calls:t.map(p=>v(p))}}buildOutsideExecutionTypedData(t,e,o,i,r,a,c="1"){const d=this.buildOutsideExecution(e,o,i,r,a);return y(d,t,c)}async getOutsideExecutionCall(t,e,o,i,r,a,c,d,S,g="1"){const p=this.buildOutsideExecution(i,a,c,d,S),h=y(p,this.chainId,g),l=await this.getSessionSignatureForOutsideExecutionTypedData(e,t,i,r,h,o);return{contractAddress:r,entrypoint:"execute_from_outside_v2",calldata:n.CallData.compile({...p,signature:l})}}async getSessionSignatureForOutsideExecutionTypedData(t,e,o,i,r,a){const c=this.compileSessionHelper(e),d=_(e,this.chainId),S=n.typedData.getMessageHash(r,i),g=await this.signTxAndSession(S,i,d,a),p=await this.argentSessionService.signSessionEFO(e,i,r,g,a,this.chainId),h=await this.compileSessionTokenHelper(c,e,o,g,t,p,a);return[x,...n.CallData.compile(h)]}async getOutsideExecutionTypedData(t,e,o,i,r,a,c,d,S,g="1"){const p=this.buildOutsideExecutionTypedData(this.chainId,i,a,c,d,S,g),h=await this.getSessionSignatureForOutsideExecutionTypedData(e,t,i,r,p,o);return{outsideExecutionTypedData:p,signature:h}}}const f={StarknetDomain:[{name:"name",type:"shortstring"},{name:"version",type:"shortstring"},{name:"chainId",type:"shortstring"},{name:"revision",type:"shortstring"}],"Allowed Method":[{name:"Contract Address",type:"ContractAddress"},{name:"selector",type:"selector"}],Session:[{name:"Expires At",type:"timestamp"},{name:"Allowed Methods",type:"merkletree",contains:"Allowed Method"},{name:"Metadata",type:"string"},{name:"Session Key",type:"felt"}]},D=n.typedData.getTypeHash(f,"Allowed Method",n.typedData.TypedDataRevision.ACTIVE),C=s=>({name:"SessionAccount.session",version:n.shortString.encodeShortString("1"),chainId:s,revision:"1"}),_=(s,t)=>({types:f,primaryType:"Session",domain:C(t),message:{"Expires At":s.expires_at,"Allowed Methods":s.allowed_methods,Metadata:s.metadata,"Session Key":s.session_key_guid}}),O=(s,t,e,o)=>({expires_at:Number(t),allowed_methods:s,metadata:JSON.stringify(e),session_key_guid:n.hash.computePoseidonHash(n.shortString.encodeShortString("Starknet Signer"),o)}),U=async({useCacheAuthorisation:s,accountSessionSignature:t,sessionRequest:e,provider:o,chainId:i,address:r,dappKey:a,argentSessionServiceBaseUrl:c})=>{const d=new w(a.publicKey,t,c);return new b(d,i,a).getAccountWithSessionSigner(o,r,e,t,s)},L=async({wallet:s,sessionParams:t,chainId:e})=>{const{allowedMethods:o,expiry:i=BigInt(Date.now())+10000n,publicDappKey:r,metaData:a}=t;if(!r)throw new Error("publicDappKey is required");const c=O(o,i,a,r),d=_(c,e);return await s.request({type:"wallet_signTypedData",params:d})};u.ALLOWED_METHOD_HASH=D,u.ArgentSessionService=w,u.SessionDappService=b,u.buildSessionAccount=U,u.createSessionRequest=O,u.getOutsideCall=v,u.getOutsideExecutionCall=V,u.getOutsideExecutionTypedData=y,u.getSessionDomain=C,u.getSessionTypedData=_,u.getTypedDataHash=N,u.openSession=L,u.sessionTypes=f,u.typesRev1=A,Object.defineProperty(u,Symbol.toStringTag,{value:"Module"})});