@dfinity/oisy-wallet-signer
Version:
A library designed to facilitate communication between a dApp and the OISY Wallet on the Internet Computer.
3 lines (2 loc) • 24.8 kB
JavaScript
var Qt=Object.defineProperty;var Ae=(e,t)=>{for(var r in t)Qt(e,r,{get:t[r],enumerable:!0})};import{mapIcrc1TransferError as Lr,mapIcrc2ApproveError as Dr,toIcrc1TransferRawRequest as eo,toIcrc2ApproveRawRequest as to}from"@icp-sdk/canisters/ledger/icp";import{IDL as Fe}from"@icp-sdk/core/candid";var w={};Ae(w,{Account:()=>J,Subaccount:()=>de,Timestamp:()=>le,TransferArgs:()=>we,TransferError:()=>qe,Value:()=>Pe,idlFactory:()=>Zt,idlInitArgs:()=>Xt,idlService:()=>Jt,init:()=>Lt});import{IDL as i}from"@icp-sdk/core/candid";var de=i.Vec(i.Nat8),J=i.Record({owner:i.Principal,subaccount:i.Opt(de)}),Pe=i.Variant({Int:i.Int,Nat:i.Nat,Blob:i.Vec(i.Nat8),Text:i.Text}),le=i.Nat64,we=i.Record({to:J,fee:i.Opt(i.Nat),memo:i.Opt(i.Vec(i.Nat8)),from_subaccount:i.Opt(de),created_at_time:i.Opt(le),amount:i.Nat}),qe=i.Variant({GenericError:i.Record({message:i.Text,error_code:i.Nat}),TemporarilyUnavailable:i.Null,BadBurn:i.Record({min_burn_amount:i.Nat}),Duplicate:i.Record({duplicate_of:i.Nat}),BadFee:i.Record({expected_fee:i.Nat}),CreatedInFuture:i.Record({ledger_time:le}),TooOld:i.Null,InsufficientFunds:i.Record({balance:i.Nat})}),Jt=i.Service({icrc1_balance_of:i.Func([J],[i.Nat],["query"]),icrc1_decimals:i.Func([],[i.Nat8],["query"]),icrc1_fee:i.Func([],[i.Nat],["query"]),icrc1_metadata:i.Func([],[i.Vec(i.Tuple(i.Text,Pe))],["query"]),icrc1_minting_account:i.Func([],[i.Opt(J)],["query"]),icrc1_name:i.Func([],[i.Text],["query"]),icrc1_supported_standards:i.Func([],[i.Vec(i.Record({url:i.Text,name:i.Text}))],["query"]),icrc1_symbol:i.Func([],[i.Text],["query"]),icrc1_total_supply:i.Func([],[i.Nat],["query"]),icrc1_transfer:i.Func([we],[i.Variant({Ok:i.Nat,Err:qe})],[])}),Xt=[],Zt=({IDL:e})=>{let t=e.Vec(e.Nat8),r=e.Record({owner:e.Principal,subaccount:e.Opt(t)}),c=e.Variant({Int:e.Int,Nat:e.Nat,Blob:e.Vec(e.Nat8),Text:e.Text}),n=e.Nat64,s=e.Record({to:r,fee:e.Opt(e.Nat),memo:e.Opt(e.Vec(e.Nat8)),from_subaccount:e.Opt(t),created_at_time:e.Opt(n),amount:e.Nat}),a=e.Variant({GenericError:e.Record({message:e.Text,error_code:e.Nat}),TemporarilyUnavailable:e.Null,BadBurn:e.Record({min_burn_amount:e.Nat}),Duplicate:e.Record({duplicate_of:e.Nat}),BadFee:e.Record({expected_fee:e.Nat}),CreatedInFuture:e.Record({ledger_time:n}),TooOld:e.Null,InsufficientFunds:e.Record({balance:e.Nat})});return e.Service({icrc1_balance_of:e.Func([r],[e.Nat],["query"]),icrc1_decimals:e.Func([],[e.Nat8],["query"]),icrc1_fee:e.Func([],[e.Nat],["query"]),icrc1_metadata:e.Func([],[e.Vec(e.Tuple(e.Text,c))],["query"]),icrc1_minting_account:e.Func([],[e.Opt(r)],["query"]),icrc1_name:e.Func([],[e.Text],["query"]),icrc1_supported_standards:e.Func([],[e.Vec(e.Record({url:e.Text,name:e.Text}))],["query"]),icrc1_symbol:e.Func([],[e.Text],["query"]),icrc1_total_supply:e.Func([],[e.Nat],["query"]),icrc1_transfer:e.Func([s],[e.Variant({Ok:e.Nat,Err:a})],[])})},Lt=({IDL:e})=>[];var N={};Ae(N,{Account:()=>q,AllowanceArgs:()=>be,ApproveArgs:()=>Ue,ApproveError:()=>Me,TransferFromArgs:()=>ve,TransferFromError:()=>ze,idlFactory:()=>tr,idlInitArgs:()=>er,idlService:()=>Dt,init:()=>rr});import{IDL as o}from"@icp-sdk/core/candid";var q=o.Record({owner:o.Principal,subaccount:o.Opt(o.Vec(o.Nat8))}),be=o.Record({account:q,spender:q}),Ue=o.Record({fee:o.Opt(o.Nat),memo:o.Opt(o.Vec(o.Nat8)),from_subaccount:o.Opt(o.Vec(o.Nat8)),created_at_time:o.Opt(o.Nat64),amount:o.Nat,expected_allowance:o.Opt(o.Nat),expires_at:o.Opt(o.Nat64),spender:q}),Me=o.Variant({GenericError:o.Record({message:o.Text,error_code:o.Nat}),TemporarilyUnavailable:o.Null,Duplicate:o.Record({duplicate_of:o.Nat}),BadFee:o.Record({expected_fee:o.Nat}),AllowanceChanged:o.Record({current_allowance:o.Nat}),CreatedInFuture:o.Record({ledger_time:o.Nat64}),TooOld:o.Null,Expired:o.Record({ledger_time:o.Nat64}),InsufficientFunds:o.Record({balance:o.Nat})}),ve=o.Record({to:q,fee:o.Opt(o.Nat),spender_subaccount:o.Opt(o.Vec(o.Nat8)),from:q,memo:o.Opt(o.Vec(o.Nat8)),created_at_time:o.Opt(o.Nat64),amount:o.Nat}),ze=o.Variant({GenericError:o.Record({message:o.Text,error_code:o.Nat}),TemporarilyUnavailable:o.Null,InsufficientAllowance:o.Record({allowance:o.Nat}),BadBurn:o.Record({min_burn_amount:o.Nat}),Duplicate:o.Record({duplicate_of:o.Nat}),BadFee:o.Record({expected_fee:o.Nat}),CreatedInFuture:o.Record({ledger_time:o.Nat64}),TooOld:o.Null,InsufficientFunds:o.Record({balance:o.Nat})}),Dt=o.Service({icrc1_supported_standards:o.Func([],[o.Vec(o.Record({url:o.Text,name:o.Text}))],["query"]),icrc2_allowance:o.Func([be],[o.Record({allowance:o.Nat,expires_at:o.Opt(o.Nat64)})],["query"]),icrc2_approve:o.Func([Ue],[o.Variant({Ok:o.Nat,Err:Me})],[]),icrc2_transfer_from:o.Func([ve],[o.Variant({Ok:o.Nat,Err:ze})],[])}),er=[],tr=({IDL:e})=>{let t=e.Record({owner:e.Principal,subaccount:e.Opt(e.Vec(e.Nat8))}),r=e.Record({account:t,spender:t}),c=e.Record({fee:e.Opt(e.Nat),memo:e.Opt(e.Vec(e.Nat8)),from_subaccount:e.Opt(e.Vec(e.Nat8)),created_at_time:e.Opt(e.Nat64),amount:e.Nat,expected_allowance:e.Opt(e.Nat),expires_at:e.Opt(e.Nat64),spender:t}),n=e.Variant({GenericError:e.Record({message:e.Text,error_code:e.Nat}),TemporarilyUnavailable:e.Null,Duplicate:e.Record({duplicate_of:e.Nat}),BadFee:e.Record({expected_fee:e.Nat}),AllowanceChanged:e.Record({current_allowance:e.Nat}),CreatedInFuture:e.Record({ledger_time:e.Nat64}),TooOld:e.Null,Expired:e.Record({ledger_time:e.Nat64}),InsufficientFunds:e.Record({balance:e.Nat})}),s=e.Record({to:t,fee:e.Opt(e.Nat),spender_subaccount:e.Opt(e.Vec(e.Nat8)),from:t,memo:e.Opt(e.Vec(e.Nat8)),created_at_time:e.Opt(e.Nat64),amount:e.Nat}),a=e.Variant({GenericError:e.Record({message:e.Text,error_code:e.Nat}),TemporarilyUnavailable:e.Null,InsufficientAllowance:e.Record({allowance:e.Nat}),BadBurn:e.Record({min_burn_amount:e.Nat}),Duplicate:e.Record({duplicate_of:e.Nat}),BadFee:e.Record({expected_fee:e.Nat}),CreatedInFuture:e.Record({ledger_time:e.Nat64}),TooOld:e.Null,InsufficientFunds:e.Record({balance:e.Nat})});return e.Service({icrc1_supported_standards:e.Func([],[e.Vec(e.Record({url:e.Text,name:e.Text}))],["query"]),icrc2_allowance:e.Func([r],[e.Record({allowance:e.Nat,expires_at:e.Opt(e.Nat64)})],["query"]),icrc2_approve:e.Func([c],[e.Variant({Ok:e.Nat,Err:n})],[]),icrc2_transfer_from:e.Func([s],[e.Variant({Ok:e.Nat,Err:a})],[])})},rr=({IDL:e})=>[];var We=Fe.Variant({Ok:Fe.Nat,Err:w.TransferError});import{IDL as X}from"@icp-sdk/core/candid";var Be=X.Variant({Ok:X.Nat,Err:N.ApproveError}),lo=X.Variant({Ok:X.Nat,Err:N.TransferFromError});import{assertNonNullish as jt,nonNullish as U,notEmptyString as $t}from"@dfinity/utils";var Ve="icrc21_call_consent_message",Z="icrc25_request_permissions",L="icrc25_permissions",D="icrc25_supported_standards",v="icrc27_accounts",z="icrc29_status",F="icrc49_call_canister",ee="granted",Ge="denied",ke="ask_on_use",Ye="ICRC-21",je="ICRC-25",$e="ICRC-27",He="ICRC-29",Ke="ICRC-49";import*as te from"zod";var or=te.enum([Ve,Z,L,D,v,z,F]),re=or.extract([v,F]),Qe=te.enum([ee,Ge,ke]),me=te.enum([Ye,je,$e,He,Ke]);var Je=5e3,oe=120*1e3,Re=5e3,Xe=oe,Ze=Re,Le=oe,De=Re,et=oe,tt=oe,rt=Re,ot={scopes:Object.values(re.enum).map(e=>({method:e}))};var W="toolbar=no, location=no, directories=no, status=no, menubar=no, scrollbars=yes, resizable=no, copyhistory=no",nt={width:576,height:625},st={...nt,position:"top-right",features:W},go={...nt,position:"center",features:W};var ct="http://localhost:4943",it="https://icp-api.io";import*as u from"zod";var I="2.0",nr=u.literal(I),B=u.union([u.string(),u.number(),u.null()]),at=u.object({jsonrpc:nr,id:u.optional(B)}),sr=at.extend({id:B}).merge(u.object({method:u.string(),params:u.optional(u.any())})).strict();var To=sr.omit({id:!0}).strict(),pt=(a=>(a[a.PARSE_ERROR=-32700]="PARSE_ERROR",a[a.INVALID_REQUEST=-32600]="INVALID_REQUEST",a[a.METHOD_NOT_FOUND=-32601]="METHOD_NOT_FOUND",a[a.INVALID_PARAMS=-32602]="INVALID_PARAMS",a[a.INTERNAL_ERROR=-32603]="INTERNAL_ERROR",a[a.SERVER_ERROR=-32e3]="SERVER_ERROR",a))(pt||{}),cr=u.union([u.number(),u.nativeEnum(pt)]),ut=u.object({code:cr,message:u.string(),data:u.optional(u.never())}),ir=at.extend({id:B}),ye=ir.extend({error:ut}).strict(),C=e=>ye.omit({error:!0}).merge(u.object({result:e,error:ut}).partial()).strict().refine(({result:t,error:r})=>t!==void 0||r!==void 0,"Either result or error should be provided."),fe=C(u.any());var pr=async e=>{await new Promise(t=>{setTimeout(t,e)})},he=async({retries:e,isReady:t,fn:r,intervalInMilliseconds:c=500})=>{let n=t();if(n!=="pending")return n;let s=e-1;return s===0?"timeout":(r(),await pr(c),await he({retries:s,intervalInMilliseconds:c,isReady:t,fn:r}))};var dt=async({popup:e,id:t,isReady:r,timeoutInMilliseconds:c,intervalInMilliseconds:n})=>{let s=()=>{V({popup:e,msg:{jsonrpc:I,id:t,method:z},origin:"*"})};return await he({retries:c/(n??500),intervalInMilliseconds:n,isReady:r,fn:s})},lt=({id:e,...t})=>{V({msg:{jsonrpc:I,id:e,method:z},...t})},mt=({id:e,...t})=>{V({msg:{jsonrpc:I,id:e,method:D},...t})},Rt=({id:e,...t})=>{V({msg:{jsonrpc:I,id:e,method:L},...t})},yt=({id:e,params:t,...r})=>{Se({msg:{jsonrpc:I,id:e,method:Z,params:t},...r})},ft=({id:e,...t})=>{Se({msg:{jsonrpc:I,id:e,method:v},...t})},ht=({id:e,params:t,...r})=>{Se({msg:{jsonrpc:I,id:e,method:F,params:t},...r})},Se=({popup:e,...t})=>{e.focus(),V({popup:e,...t})},V=({popup:e,msg:t,origin:r})=>{e.postMessage(t,r)};import{UrlSchema as Rr}from"@dfinity/zod-schemas";import*as f from"zod";import*as St from"zod";var G=St.string().refine(e=>{try{return btoa(atob(e))===e}catch{return!1}},{message:"Invalid base64 string"});import{base64ToUint8Array as ur}from"@dfinity/utils";import{PrincipalTextSchema as dr}from"@dfinity/zod-schemas";import*as ne from"zod";var lr=G.refine(e=>{try{return ur(e).length===32}catch{return!1}},{message:"Subaccount must be exactly 32 bytes long."}),mr=ne.object({owner:dr,subaccount:lr.optional()}).strict(),gt=ne.array(mr).min(1);var yr=f.object({method:re}),fr=f.object({scope:yr,state:Qe}).strict(),hr=f.array(fr),Sr=f.object({scopes:hr}).strict(),_t=C(Sr),gr=/^https:\/\/github\.com\/dfinity\/ICRC\/blob\/main\/ICRCs\/ICRC-\d+\/ICRC-\d+\.md$/,_r=f.url().regex(gr).refine(e=>{try{Rr.parse(e)}catch{return!1}let t=/(ICRC-\d+)\.md/g.exec(e);if(t===null)return!1;let[r,c]=t;return Object.keys(me.enum).includes(c)},{message:"The URL does not match any of the IcrcStandard values."}),Ir=f.array(f.object({name:me,url:_r}).strict()).min(1),It=C(f.object({supportedStandards:Ir})),ge=C(f.literal("ready")),Tt=C(f.object({accounts:gt})),Tr=f.object({contentMap:G,certificate:G}).strict(),Et=C(Tr.strict());var se=class extends Error{code;constructor({message:t,code:r}){super(t),this.code=r}},k=class extends Error{};import{UrlSchema as Nt}from"@dfinity/zod-schemas";import*as m from"zod";var Er=m.object({pollingIntervalInMilliseconds:m.number().positive().optional(),timeoutInMilliseconds:m.number().positive().optional()}),Nr=m.object({position:m.enum(["top-right","center"]),width:m.number().positive(),height:m.number().positive(),features:m.string().optional()}),Cr=m.function({output:m.void()}).optional(),xr=Nt.optional(),Ct=m.object({url:Nt,windowOptions:m.union([Nr,m.string()]).optional(),connectionOptions:Er.optional(),onDisconnect:Cr,host:xr});import*as Y from"zod";var xt=Y.object({timeoutInMilliseconds:Y.number().positive()}),_e=Y.object({requestId:B.optional()}).merge(xt.partial()),jo=_e.omit({timeoutInMilliseconds:!0}).merge(xt);import{assertNonNullish as Vt,base64ToUint8Array as jr}from"@dfinity/utils";import{AnonymousIdentity as $r,Certificate as Hr,HttpAgent as Kr,lookupResultToBuffer as Qr,requestIdOf as Jr}from"@icp-sdk/core/agent";import{Principal as Gt}from"@icp-sdk/core/principal";var Ot=({hostname:e})=>({...(["localhost","127.0.0.1"].includes(e)||e.endsWith(".localhost"))&&{shouldFetchRootKey:!0}});var T=class extends Error{constructor(t){super(t),this.name="DecodingError"}},Or=55799,At=Symbol("CBOR_STOP_CODE"),O=(e=>(e[e.False=20]="False",e[e.True=21]="True",e[e.Null=22]="Null",e[e.Undefined=23]="Undefined",e[e.Break=31]="Break",e))(O||{}),g=(e=>(e[e.UnsignedInteger=0]="UnsignedInteger",e[e.NegativeInteger=1]="NegativeInteger",e[e.ByteString=2]="ByteString",e[e.TextString=3]="TextString",e[e.Array=4]="Array",e[e.Map=5]="Map",e[e.Tag=6]="Tag",e[e.Simple=7]="Simple",e))(g||{});var Ko=BigInt("0xffffffffffffffff"),x=(e=>(e[e.Value=23]="Value",e[e.OneByte=24]="OneByte",e[e.TwoBytes=25]="TwoBytes",e[e.FourBytes=26]="FourBytes",e[e.EightBytes=27]="EightBytes",e[e.Indefinite=31]="Indefinite",e))(x||{}),Ie=!1;function Ar(e){return e==null}var Pr=new TextDecoder;function wr(e){return(e&224)>>5}function qr(e){return e&31}var $=new Uint8Array,j,_=0;function Pt(e,t){$=e,_=0;let r=A(t);return t?.(r)??r}function A(e){let[t,r]=ce();switch(t){case g.UnsignedInteger:return b(r);case g.NegativeInteger:return vr(r);case g.ByteString:return wt(r);case g.TextString:return Te(r);case g.Array:return br(r,e);case g.Map:return Mr(r,e);case g.Tag:return zr(r,e);case g.Simple:return Ur(r)}throw new T(`Unsupported major type: ${t}`)}function ce(){let e=$.at(_);if(Ar(e))throw new T("Provided CBOR data is empty");let t=wr(e),r=qr(e);return _++,[t,r]}function br(e,t){let r=b(e);if(r===1/0){let n=[],s=A(t);for(;s!==At;)n.push(t?.(s)??s),s=A(t);return n}let c=new Array(r);for(let n=0;n<r;n++){let s=A(t);c[n]=t?.(s)??s}return c}function Ur(e){switch(e){case O.False:return!1;case O.True:return!0;case O.Null:return null;case O.Undefined:return;case O.Break:return At}throw new T(`Unrecognized simple type: ${e.toString(2)}`)}function Mr(e,t){let r=b(e),c={};if(r===1/0){let[n,s]=ce();for(;n!==g.Simple&&s!==O.Break;){let a=Te(s),p=A(t);c[a]=t?.(p,a)??p,[n,s]=ce()}return c}for(let n=0;n<r;n++){let[s,a]=ce();if(s!==g.TextString)throw new T("Map keys must be text strings");let p=Te(a),d=A(t);c[p]=t?.(d,p)??d}return c}function b(e){if(e<=x.Value)return e;switch(j=new DataView($.buffer,$.byteOffset+_),e){case x.OneByte:return _++,j.getUint8(0);case x.TwoBytes:return _+=2,j.getUint16(0,Ie);case x.FourBytes:return _+=4,j.getUint32(0,Ie);case x.EightBytes:return _+=8,j.getBigUint64(0,Ie);case x.Indefinite:return 1/0;default:throw new T(`Unsupported integer info: ${e.toString(2)}`)}}function vr(e){let t=b(e);return typeof t=="number"?-1-t:-1n-t}function wt(e){let t=b(e);if(t>Number.MAX_SAFE_INTEGER)throw new T("Byte length is too large");let r=Number(t);return _+=r,$.slice(_-r,_)}function Te(e){let t=wt(e);return Pr.decode(t)}function zr(e,t){let r=b(e);if(r===Or)return A(t);throw new T(`Unsupported tag: ${r}.`)}var Fr=2*1024;var Qo=new TextEncoder;var Wr=new Uint8Array(Fr),Jo=new DataView(Wr.buffer);import{base64ToUint8Array as Gr}from"@dfinity/utils";import{Principal as bt}from"@icp-sdk/core/principal";import{Expiry as Br,JSON_KEY_EXPIRY as Vr}from"@icp-sdk/core/agent";var qt=e=>{let t=JSON.stringify({[Vr]:e.toString()});return Br.fromJSON(t)};var Ee=e=>{let{ingress_expiry:t,canister_id:r,sender:c,...n}=Pt(Gr(e));return{...n,canister_id:bt.fromUint8Array(r),sender:bt.fromUint8Array(c),ingress_expiry:qt(t)}};import{base64ToUint8Array as kr}from"@dfinity/utils";import{Principal as Ut}from"@icp-sdk/core/principal";var Mt=({requestMethod:e,responseMethod:t})=>{if(t!==e)throw new Error("The response method does not match the request method.")},vt=({responseArg:e,requestArg:t})=>{let r=kr(t);if(!(({first:s,second:a})=>s.length===a.length&&s.every((p,d)=>p===a[d]))({first:r,second:e}))throw new Error("The response does not contain the request arguments.")},zt=({requestCanisterId:e,responseCanisterId:t})=>{if(e.toText()!==t.toText())throw new Error("The response canister ID does not match the requested canister ID.")},Ft=({requestSender:e,responseSender:t})=>{if((t instanceof Uint8Array?Ut.fromUint8Array(t):t).toText()!==Ut.fromText(e).toText())throw new Error("The response sender does not match the request sender.")};import{uint8ArrayToBase64 as Yr}from"@dfinity/utils";import{IDL as Wt}from"@icp-sdk/core/candid";var Ne=({recordClass:e,rawArgs:t})=>Yr(new Uint8Array(Wt.encode([e],[t]))),Bt=({recordClass:e,bytes:t})=>{let r=Wt.decode([e],t);if(r.length!==1)throw new Error("More than one object returned. This is unexpected.");let[c]=r;return c};var kt=({params:{method:e,arg:t,canisterId:r,sender:c},result:{contentMap:n}})=>{let s=Ee(n);zt({requestCanisterId:Gt.fromText(r),responseCanisterId:s.canister_id}),Mt({requestMethod:e,responseMethod:s.method_name}),vt({requestArg:t,responseArg:s.arg}),Ft({requestSender:c,responseSender:s.sender})},Ce=async({params:{canisterId:e},result:{certificate:t,contentMap:r},resultRecordClass:c,host:n})=>{let s=Ee(r),{location:{hostname:a}}=window,p=Ot({hostname:a}),d=await Kr.create({identity:new $r,host:p?.shouldFetchRootKey===!0?n??ct:it,...p});Vt(d.rootKey,"Missing agent root key, which is required to certify the response.");let l=await Hr.create({certificate:jr(t),rootKey:d.rootKey,canisterId:Gt.fromText(e)}),h=Jr(s),R=[new TextEncoder().encode("request_status"),h],y=Qr(l.lookup_path([...R,"reply"]));return Vt(y,"A reply cannot be resolved within the provided certificate. This is unexpected; it should have been known at this point."),Bt({recordClass:c,bytes:y})};import{isNullish as ie}from"@dfinity/utils";var xe=()=>typeof window<"u";var Yt=({position:e,...t})=>(e==="center"?Xr:Zr)(t),Xr=({width:e,height:t,features:r=W})=>{if(!xe()||ie(window)||ie(window.top))return;let{top:{innerWidth:c,innerHeight:n}}=window,s=n/2+screenY-t/2,a=c/2+screenX-e/2;return`${r}, width=${e}, height=${t}, top=${s}, left=${a}`},Zr=({width:e,height:t,features:r=W})=>{if(!xe()||ie(window)||ie(window.top))return;let{top:{innerWidth:c,innerHeight:n}}=window,s=outerHeight-n,a=c-e;return`${r}, width=${e}, height=${t}, top=${s}, left=${a}`};var ae=class e{#t;#e;#o;host;#r="connected";#n;constructor({origin:t,popup:r,onDisconnect:c,host:n}){this.#t=t,this.#e=r,this.#o=c,this.host=n,this.#r="connected",this.#n=setInterval(this.checkWalletStatusCallback,Je)}static async connect({onDisconnect:t,...r}){return await this.connectSigner({options:r,init:c=>new e({...c,onDisconnect:t})})}static async connectSigner({options:t,init:r}){let{success:c,error:n}=Ct.safeParse(t);if(!c)throw new Error(`Options cannot be parsed: ${n?.message??""}`);let{url:s,windowOptions:a,connectionOptions:p}=t,d=typeof a=="string"?a:Yt(a??st),l=window.open(s,"relyingPartyWindow",d);jt(l,"Unable to open the signer window.");let h=()=>{l.close()};class R extends Error{}let y,H=({origin:S,data:P})=>{let{success:pe}=fe.safeParse(P);if(!pe)return;let Q;try{let{origin:M}=new URL(s);Q=M}catch{y=new R(`The origin ${S} of the signer URL ${s} cannot be parsed.`);return}if($t(S)&&S!==Q){y=new R(`The response origin ${S} does not match the requested signer URL ${s}.`);return}let{success:ue}=ge.safeParse(P);ue&&(y=r({origin:S,popup:l}))};window.addEventListener("message",H);let K=()=>{window.removeEventListener("message",H)},E=async()=>{if(await dt({popup:l,isReady:()=>U(y)?y instanceof e?"ready":"error":"pending",id:crypto.randomUUID(),timeoutInMilliseconds:p?.timeoutInMilliseconds??Xe,intervalInMilliseconds:p?.pollingIntervalInMilliseconds})==="timeout")throw new Error("Connection timeout. Unable to connect to the signer.");if(jt(y,"Unexpected error. The request status succeeded, but the signer response is not defined."),y instanceof R)throw y;return y};try{return await E()}catch(S){throw h(),S}finally{K()}}disconnect=async()=>{clearInterval(this.#n),this.#e.close(),this.#o?.()};checkWalletStatusCallback=()=>{this.checkWalletStatus()};async checkWalletStatus(){let t=({data:n,id:s})=>{let{success:a,data:p}=ge.safeParse(n);return a&&s===p?.id?{handled:!0,result:"connected"}:{handled:!0,result:"disconnected"}},r=n=>{lt({popup:this.#e,origin:this.#t,id:n})},c=async()=>{try{return await this.request({options:{timeoutInMilliseconds:rt},postRequest:r,handleMessage:t})}catch{return"disconnected"}};this.#r=await c(),this.#r!=="connected"&&await this.disconnect()}request=async({options:t,postRequest:r,handleMessage:c})=>await new Promise((n,s)=>{let{connected:a,err:p}=this.assertWalletConnected();if(!a){s(p??new Error("Unexpected reason for disconnection."));return}let{success:d,error:l}=_e.safeParse(t);if(!d)throw new Error(`Wallet request options cannot be parsed: ${l?.message??""}`);let{requestId:h,timeoutInMilliseconds:R}=t,y=h??crypto.randomUUID(),H=setTimeout(()=>{s(new Error(`Request to signer timed out after ${R} milliseconds.`)),E()},R),K=({origin:S,data:P,source:pe})=>{let{success:Q}=fe.safeParse(P);if(!Q)return;if(pe!==this.#e){s(new Error("The response is not originating from the window that was opened.")),E();return}if($t(S)&&S!==this.#t){s(new Error(`The response origin ${S} does not match the signer origin ${this.#t}.`)),E();return}let{handled:ue,result:M}=c({data:P,id:y});if(ue&&U(M)){n(M),E();return}let Oe=this.handleErrorMessage({data:P,id:y});Oe.valid||(s(Oe.error),E())};window.addEventListener("message",K);let E=()=>{clearTimeout(H),window.removeEventListener("message",K)};r(y)});assertWalletConnected(){return this.#r==="disconnected"?{connected:!1,err:new k("The signer has been disconnected. Your request cannot be processed.")}:this.#e.closed?{connected:!1,err:new k("The signer has been closed. Your request cannot be processed.")}:{connected:!0}}supportedStandards=async({options:{timeoutInMilliseconds:t,...r}={}}={})=>{let c=({data:s,id:a})=>{let{success:p,data:d}=It.safeParse(s);if(p&&a===d?.id&&U(d?.result)){let{result:{supportedStandards:l}}=d;return{handled:!0,result:l}}return{handled:!1}},n=s=>{mt({popup:this.#e,origin:this.#t,id:s})};return await this.request({options:{timeoutInMilliseconds:t??Ze,...r},postRequest:n,handleMessage:c})};permissions=async({options:{timeoutInMilliseconds:t,...r}={}}={})=>{let c=n=>{Rt({popup:this.#e,origin:this.#t,id:n})};return await this.requestPermissionsScopes({options:{timeoutInMilliseconds:t??De,...r},postRequest:c})};requestPermissions=async({options:{timeoutInMilliseconds:t,...r}={},params:c}={})=>{let n=s=>{yt({popup:this.#e,origin:this.#t,id:s,params:c??ot})};return await this.requestPermissionsScopes({options:{timeoutInMilliseconds:t??Le,...r},postRequest:n})};requestPermissionsScopes=async({options:t,postRequest:r})=>{let c=({data:n,id:s})=>{let{success:a,data:p}=_t.safeParse(n);if(a&&s===p?.id&&U(p?.result)){let{result:{scopes:d}}=p;return{handled:!0,result:d}}return{handled:!1}};return await this.request({options:t,postRequest:r,handleMessage:c})};accounts=async({options:{timeoutInMilliseconds:t,...r}={}}={})=>{let c=({data:s,id:a})=>{let{success:p,data:d}=Tt.safeParse(s);if(p&&a===d?.id&&U(d?.result)){let{result:{accounts:l}}=d;return{handled:!0,result:l}}return{handled:!1}},n=s=>{ft({popup:this.#e,origin:this.#t,id:s})};return await this.request({options:{timeoutInMilliseconds:t??et,...r},postRequest:n,handleMessage:c})};call=async({options:{timeoutInMilliseconds:t,...r}={},params:c})=>{let n=({data:p,id:d})=>{let{success:l,data:h}=Et.safeParse(p);if(l&&d===h?.id&&U(h?.result)){let{result:R}=h;return{handled:!0,result:R}}return{handled:!1}},s=p=>{ht({popup:this.#e,origin:this.#t,id:p,params:c})},a=await this.request({options:{timeoutInMilliseconds:t??tt,...r},postRequest:s,handleMessage:n});return kt({params:c,result:a}),a};handleErrorMessage=({data:t,id:r})=>{let{success:c,data:n}=ye.safeParse(t);return!c||r!==n?.id?{valid:!0}:{valid:!1,error:new se(n.error)}};requestPermissionsNotGranted=async({options:t}={})=>{let r=p=>p.filter(({state:d})=>d!==ee).map(({scope:d})=>d),c=await this.permissions({options:t});if(c.length===0)throw new Error("The signer did not provide any data about the current set of permissions.");let n=r(c);if(n.length===0)return{allPermissionsGranted:!0};let s=await this.requestPermissions({options:t,params:{scopes:n}});if(s.length===0)throw new Error("The signer did not provide any data about the current set of permissions following the request.");return{allPermissionsGranted:r(s).length===0}}};var Ht="ryjl3-tyaaa-aaaaa-aaaba-cai",Kt=class e extends ae{static async connect({onDisconnect:t,host:r,...c}){return await this.connectSigner({options:c,init:n=>new e({...n,onDisconnect:t,host:r})})}icrc1Transfer=async({request:t,owner:r,ledgerCanisterId:c,options:n})=>{let s=eo(t),a=Ne({recordClass:w.TransferArgs,rawArgs:s}),l={sender:r,method:"icrc1_transfer",canisterId:c??Ht,arg:a},h=await this.call({params:l,options:n}),R=await Ce({params:l,result:h,resultRecordClass:We,host:this.host});if("Err"in R)throw Lr(R.Err);return R.Ok};icrc2Approve=async({request:t,owner:r,ledgerCanisterId:c,options:n})=>{let s=to(t),a=Ne({recordClass:N.ApproveArgs,rawArgs:s}),l={sender:r,method:"icrc2_approve",canisterId:c??Ht,arg:a},h=await this.call({params:l,options:n}),R=await Ce({params:l,result:h,resultRecordClass:Be,host:this.host});if("Err"in R)throw Dr(R.Err);return R.Ok}};export{Kt as IcpWallet};
//# sourceMappingURL=icp-wallet.js.map