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