@dfinity/oisy-wallet-signer
Version:
A library designed to facilitate communication between a dApp and the OISY Wallet on the Internet Computer.
22 lines (20 loc) • 39.2 kB
JavaScript
var Jr=Object.create;var Be=Object.defineProperty;var Qr=Object.getOwnPropertyDescriptor;var Zr=Object.getOwnPropertyNames;var Xr=Object.getPrototypeOf,Dr=Object.prototype.hasOwnProperty;var Lr=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports),ht=(e,t)=>{for(var r in t)Be(e,r,{get:t[r],enumerable:!0})},es=(e,t,r,s)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of Zr(t))!Dr.call(e,o)&&o!==r&&Be(e,o,{get:()=>t[o],enumerable:!(s=Qr(t,o))||s.enumerable});return e};var ts=(e,t,r)=>(r=e!=null?Jr(Xr(e)):{},es(t||!e||!e.__esModule?Be(r,"default",{value:e,enumerable:!0}):r,e));var lr=Lr((gc,ao)=>{ao.exports={core:{amount:"Amount",from:"From",to:"To",fee:"Fee",memo:"Memo"},icrc1_transfer:{title:"Approve the transfer of funds"},icrc2_approve:{title:"Authorize another address to withdraw from your account",address_is_allowed:"The following address is allowed to withdraw from your account",your_account:"Your account",requested_withdrawal_allowance:"Requested withdrawal allowance",withdrawal_allowance:{some:"Current withdrawal allowance",none:"The allowance will be set to {amount} {symbol} independently of any previous allowance. Until this transaction has been executed the spender can still exercise the previous allowance (if any) to it's full amount."},expiration_date:{title:"Expiration date",none:"No expiration."},approval_fee:"Approval fee",approver_account_transaction_fees:"Transaction fees to be paid by"},icrc2_transfer_from:{title:"Transfer from a withdrawal account",withdrawal_account:"Withdrawal account",sending_the_transfer_request:"Account sending the transfer request",amount_to_withdraw:"Amount to withdraw",fee_paid_by_withdrawal_account:"Fee paid by withdrawal account"}}});import{assertNonNullish as dt,isNullish as le,nonNullish as Hr}from"@dfinity/utils";var K="icrc21_call_consent_message",z="icrc25_request_permissions",fe="icrc25_permissions",ye="icrc25_supported_standards",w="icrc27_accounts",he="icrc29_status",T="icrc49_call_canister",Y="granted",V="denied",F="ask_on_use",St="ICRC-21",gt="ICRC-25",Rt="ICRC-27",_t="ICRC-29",Ct="ICRC-49";import*as Se from"zod";var rs=Se.enum([K,z,fe,ye,w,he,T]),U=rs.extract([w,T]),ge=Se.enum([Y,V,F]),oe=Se.enum([St,gt,Rt,_t,Ct]);var xt=Object.values(oe.enum).map(e=>({name:e,url:`https://github.com/dfinity/ICRC/blob/main/ICRCs/${e}/${e}.md`})),Pt=Object.values(U.enum).map(e=>({scope:{method:e},state:F})),At=10080*60*1e3;import*as y from"zod";var v="2.0",ss=y.literal(v),ne=y.union([y.string(),y.number(),y.null()]),Nt=y.object({jsonrpc:ss,id:y.optional(ne)}),j=Nt.extend({id:ne}).merge(y.object({method:y.string(),params:y.optional(y.any())})).strict(),ce=({method:e})=>j.omit({method:!0,params:!0}).strict().extend({id:ne,method:y.literal(e)}),ke=({params:e,method:t})=>j.omit({method:!0}).extend({id:ne,method:y.literal(t)}).merge(y.object({params:e})),en=j.omit({id:!0}).strict(),It=(c=>(c[c.PARSE_ERROR=-32700]="PARSE_ERROR",c[c.INVALID_REQUEST=-32600]="INVALID_REQUEST",c[c.METHOD_NOT_FOUND=-32601]="METHOD_NOT_FOUND",c[c.INVALID_PARAMS=-32602]="INVALID_PARAMS",c[c.INTERNAL_ERROR=-32603]="INTERNAL_ERROR",c[c.SERVER_ERROR=-32e3]="SERVER_ERROR",c))(It||{}),os=y.union([y.number(),y.nativeEnum(It)]),wt=y.object({code:os,message:y.string(),data:y.optional(y.never())}),ns=Nt.extend({id:ne}),cs=ns.extend({error:wt}).strict(),$=e=>cs.omit({error:!0}).merge(y.object({result:e,error:wt}).partial()).strict().refine(({result:t,error:r})=>t!==void 0||r!==void 0,"Either result or error should be provided."),tn=$(y.any());var A=({id:e,error:t,origin:r})=>{G({msg:{jsonrpc:v,id:e,error:t},origin:r})},G=({msg:e,origin:t})=>window.opener.postMessage(e,t);var Re=({message:e,...t})=>{A({...t,error:{code:2e3,message:e??"The request sent by the relying party is not supported by the signer."}})},_e=e=>{A({...e,error:{code:3001,message:"The signer has canceled the action requested by the relying party."}})},Ve=({message:e,...t})=>{A({...t,error:{code:4e3,message:e}})},je=e=>{A({...e,error:{code:3e3,message:"The signer has not granted the necessary permissions to process the request from the relying party."}})},Ce=e=>{A({...e,error:{code:501,message:"The signer has not registered a prompt to respond to permission requests."}})},Tt=e=>{A({...e,error:{code:502,message:"The sender must match the owner of the signer."}})},Et=e=>{A({...e,error:{code:503,message:"The signer is currently processing a request and cannot handle new requests at this time."}})};var Ot=({id:e,origin:t})=>{G({msg:{jsonrpc:v,id:e,result:"ready"},origin:t})},bt=({id:e,origin:t})=>{G({msg:{jsonrpc:v,id:e,result:{supportedStandards:xt}},origin:t})},vt=({id:e,origin:t,scopes:r})=>{G({msg:{jsonrpc:v,id:e,result:{scopes:r}},origin:t})},Mt=({id:e,origin:t,accounts:r})=>{G({msg:{jsonrpc:v,id:e,result:{accounts:r}},origin:t})},qt=({id:e,origin:t,result:r})=>{G({msg:{jsonrpc:v,id:e,result:r},origin:t})};import{base64ToUint8Array as _r,isNullish as at,notEmptyString as Cr}from"@dfinity/utils";import{mapTokenMetadata as uo}from"@icp-sdk/canisters/ledger/icrc";import{uint8ToBuf as mo}from"@icp-sdk/core/agent";import{Principal as lo}from"@icp-sdk/core/principal";var as=55799;var ie=(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))(ie||{}),M=(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))(M||{}),is=23,ps=255,us=65535,ms=4294967295,ds=BigInt("0xffffffffffffffff"),pe=(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))(pe||{}),$e=!1;function ls(e,t){let r=new Uint8Array(t);return r.set(e),r}var dn=new TextDecoder;var ln=new Uint8Array;var ue=class extends Error{constructor(t){super(t),this.name="SerializationError"}},fs=2*1024,zt=100,ys=new TextEncoder;function ae(e){return e<<5}var O=new Uint8Array(fs),E=new DataView(O.buffer),h=0,Ge=[];function Ut(e,t){h=0;let r=t?.(e)??e;return xe(r,t),O.slice(0,h)}function Bt(e,t){h=0;let r=t?.(e)??e;return Ps(as,r,t),O.slice(0,h)}function kt(e){let t=O.length*2;for(;t<e;)t*=2;O=ls(O,t),E=new DataView(O.buffer)}function xe(e,t){if(e===!1||e===!0||e===null||e===void 0){gs(e);return}if(typeof e=="number"||typeof e=="bigint"){xs(e);return}if(typeof e=="string"){$t(e);return}if(e instanceof Uint8Array){Ft(e);return}if(e instanceof ArrayBuffer){Ft(new Uint8Array(e));return}if(Array.isArray(e)){hs(e,t);return}if(typeof e=="object"){Ss(e,t);return}throw new ue(`Unsupported type: ${typeof e}`)}function hs(e,t){J(M.Array,e.length),e.forEach((r,s)=>{xe(t?.(r,s.toString())??r,t)})}function Ss(e,t){Ge=Object.entries(e),J(M.Map,Ge.length),Ge.forEach(([r,s])=>{$t(r),xe(t?.(s,r)??s,t)})}function J(e,t){if(h>O.length-zt&&kt(h+zt),t<=is){E.setUint8(h++,ae(e)|Number(t));return}if(t<=ps){E.setUint8(h++,ae(e)|pe.OneByte),E.setUint8(h,Number(t)),h+=1;return}if(t<=us){E.setUint8(h++,ae(e)|pe.TwoBytes),E.setUint16(h,Number(t),$e),h+=2;return}if(t<=ms){E.setUint8(h++,ae(e)|pe.FourBytes),E.setUint32(h,Number(t),$e),h+=4;return}if(t<=ds){E.setUint8(h++,ae(e)|pe.EightBytes),E.setBigUint64(h,BigInt(t),$e),h+=8;return}throw new ue(`Value too large to encode: ${t}`)}function gs(e){J(M.Simple,Rs(e))}function Rs(e){if(e===!1)return ie.False;if(e===!0)return ie.True;if(e===null)return ie.Null;if(e===void 0)return ie.Undefined;throw new ue(`Unrecognized simple value: ${e.toString()}`)}function Vt(e,t){J(e,t.length),h>O.length-t.length&&kt(h+t.length),O.set(t,h),h+=t.length}function jt(e,t){J(e,t)}function _s(e){jt(M.UnsignedInteger,e)}function Cs(e){jt(M.NegativeInteger,typeof e=="bigint"?-1n-e:-1-e)}function xs(e){e>=0?_s(e):Cs(e)}function $t(e){Vt(M.TextString,ys.encode(e))}function Ft(e){Vt(M.ByteString,e)}function Ps(e,t,r){J(M.Tag,e),xe(t,r)}import{uint8ArrayToBase64 as ur}from"@dfinity/utils";import{IcrcLedgerCanister as ro}from"@icp-sdk/canisters/ledger/icrc";import{Principal as so}from"@icp-sdk/core/principal";import{z as He}from"zod";import{Expiry as As,JSON_KEY_EXPIRY as Ns}from"@icp-sdk/core/agent";var Gt=e=>{let t=JSON.stringify({[Ns]:e.toString()});return As.fromJSON(t)};var Ht=He.strictObject({_isExpiry:He.literal(!0),__expiry__:He.bigint()}).transform(({__expiry__:e})=>Gt(e));import{Principal as Is}from"@icp-sdk/core/principal";import{z as We}from"zod";var Wt=We.strictObject({_isPrincipal:We.literal(!0),_arr:We.instanceof(Uint8Array)}).transform(e=>Is.from(e));var Kt=(e,t)=>{if(t==="ingress_expiry"){let{success:r,data:s}=Ht.safeParse(e);if(r)return s.toBigInt()}if(["sender","canister_id"].includes(t??"")){let{success:r,data:s}=Wt.safeParse(e);if(r)return s.toUint8Array()}return e};import{isNullish as Ls}from"@dfinity/utils";import{Actor as eo}from"@icp-sdk/core/agent";import{Principal as to}from"@icp-sdk/core/principal";var Ae={};ht(Ae,{Account:()=>Pe,Subaccount:()=>Ke,Timestamp:()=>Ye,TransferArgs:()=>Jt,TransferError:()=>Qt,Value:()=>Yt,idlFactory:()=>Es,idlInitArgs:()=>Ts,idlService:()=>ws,init:()=>Os});import{IDL as i}from"@icp-sdk/core/candid";var Ke=i.Vec(i.Nat8),Pe=i.Record({owner:i.Principal,subaccount:i.Opt(Ke)}),Yt=i.Variant({Int:i.Int,Nat:i.Nat,Blob:i.Vec(i.Nat8),Text:i.Text}),Ye=i.Nat64,Jt=i.Record({to:Pe,fee:i.Opt(i.Nat),memo:i.Opt(i.Vec(i.Nat8)),from_subaccount:i.Opt(Ke),created_at_time:i.Opt(Ye),amount:i.Nat}),Qt=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:Ye}),TooOld:i.Null,InsufficientFunds:i.Record({balance:i.Nat})}),ws=i.Service({icrc1_balance_of:i.Func([Pe],[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,Yt))],["query"]),icrc1_minting_account:i.Func([],[i.Opt(Pe)],["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([Jt],[i.Variant({Ok:i.Nat,Err:Qt})],[])}),Ts=[],Es=({IDL:e})=>{let t=e.Vec(e.Nat8),r=e.Record({owner:e.Principal,subaccount:e.Opt(t)}),s=e.Variant({Int:e.Int,Nat:e.Nat,Blob:e.Vec(e.Nat8),Text:e.Text}),o=e.Nat64,a=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(o),amount:e.Nat}),c=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:o}),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,s))],["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([a],[e.Variant({Ok:e.Nat,Err:c})],[])})},Os=({IDL:e})=>[];var me={};ht(me,{Account:()=>Q,AllowanceArgs:()=>Zt,ApproveArgs:()=>Xt,ApproveError:()=>Dt,TransferFromArgs:()=>Lt,TransferFromError:()=>er,idlFactory:()=>Ms,idlInitArgs:()=>vs,idlService:()=>bs,init:()=>qs});import{IDL as n}from"@icp-sdk/core/candid";var Q=n.Record({owner:n.Principal,subaccount:n.Opt(n.Vec(n.Nat8))}),Zt=n.Record({account:Q,spender:Q}),Xt=n.Record({fee:n.Opt(n.Nat),memo:n.Opt(n.Vec(n.Nat8)),from_subaccount:n.Opt(n.Vec(n.Nat8)),created_at_time:n.Opt(n.Nat64),amount:n.Nat,expected_allowance:n.Opt(n.Nat),expires_at:n.Opt(n.Nat64),spender:Q}),Dt=n.Variant({GenericError:n.Record({message:n.Text,error_code:n.Nat}),TemporarilyUnavailable:n.Null,Duplicate:n.Record({duplicate_of:n.Nat}),BadFee:n.Record({expected_fee:n.Nat}),AllowanceChanged:n.Record({current_allowance:n.Nat}),CreatedInFuture:n.Record({ledger_time:n.Nat64}),TooOld:n.Null,Expired:n.Record({ledger_time:n.Nat64}),InsufficientFunds:n.Record({balance:n.Nat})}),Lt=n.Record({to:Q,fee:n.Opt(n.Nat),spender_subaccount:n.Opt(n.Vec(n.Nat8)),from:Q,memo:n.Opt(n.Vec(n.Nat8)),created_at_time:n.Opt(n.Nat64),amount:n.Nat}),er=n.Variant({GenericError:n.Record({message:n.Text,error_code:n.Nat}),TemporarilyUnavailable:n.Null,InsufficientAllowance:n.Record({allowance:n.Nat}),BadBurn:n.Record({min_burn_amount:n.Nat}),Duplicate:n.Record({duplicate_of:n.Nat}),BadFee:n.Record({expected_fee:n.Nat}),CreatedInFuture:n.Record({ledger_time:n.Nat64}),TooOld:n.Null,InsufficientFunds:n.Record({balance:n.Nat})}),bs=n.Service({icrc1_supported_standards:n.Func([],[n.Vec(n.Record({url:n.Text,name:n.Text}))],["query"]),icrc2_allowance:n.Func([Zt],[n.Record({allowance:n.Nat,expires_at:n.Opt(n.Nat64)})],["query"]),icrc2_approve:n.Func([Xt],[n.Variant({Ok:n.Nat,Err:Dt})],[]),icrc2_transfer_from:n.Func([Lt],[n.Variant({Ok:n.Nat,Err:er})],[])}),vs=[],Ms=({IDL:e})=>{let t=e.Record({owner:e.Principal,subaccount:e.Opt(e.Vec(e.Nat8))}),r=e.Record({account:t,spender:t}),s=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}),o=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})}),a=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}),c=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([s],[e.Variant({Ok:e.Nat,Err:o})],[]),icrc2_transfer_from:e.Func([a],[e.Variant({Ok:e.Nat,Err:c})],[])})},qs=({IDL:e})=>[];import{IDL as u}from"@icp-sdk/core/candid";var tr=u.Record({utc_offset_minutes:u.Opt(u.Int16),language:u.Text}),zs=u.Record({metadata:tr,device_spec:u.Opt(u.Variant({GenericDisplay:u.Null,FieldsDisplay:u.Null}))}),Fs=u.Record({arg:u.Vec(u.Nat8),method:u.Text,user_preferences:zs}),Us=u.Record({content:u.Text}),Bs=u.Record({decimals:u.Nat8,amount:u.Nat64,symbol:u.Text}),ks=u.Record({amount:u.Nat64}),Vs=u.Record({amount:u.Nat64}),js=u.Variant({Text:Us,TokenAmount:Bs,TimestampSeconds:ks,DurationSeconds:Vs}),$s=u.Variant({FieldsDisplayMessage:u.Record({fields:u.Vec(u.Tuple(u.Text,js)),intent:u.Text}),GenericDisplayMessage:u.Text}),Gs=u.Record({metadata:tr,consent_message:$s}),Je=u.Record({description:u.Text}),Hs=u.Variant({GenericError:u.Record({description:u.Text,error_code:u.Nat}),InsufficientPayment:Je,UnsupportedCanisterCall:Je,ConsentMessageUnavailable:Je}),Ws=u.Variant({Ok:Gs,Err:Hs}),En=u.Service({icrc10_supported_standards:u.Func([],[u.Vec(u.Record({url:u.Text,name:u.Text}))],["query"]),icrc21_canister_call_consent_message:u.Func([Fs],[Ws],[])});var Qe=({IDL:e})=>{let t=e.Record({utc_offset_minutes:e.Opt(e.Int16),language:e.Text}),r=e.Record({metadata:t,device_spec:e.Opt(e.Variant({GenericDisplay:e.Null,FieldsDisplay:e.Null}))}),s=e.Record({arg:e.Vec(e.Nat8),method:e.Text,user_preferences:r}),o=e.Record({content:e.Text}),a=e.Record({decimals:e.Nat8,amount:e.Nat64,symbol:e.Text}),c=e.Record({amount:e.Nat64}),m=e.Record({amount:e.Nat64}),d=e.Variant({Text:o,TokenAmount:a,TimestampSeconds:c,DurationSeconds:m}),l=e.Variant({FieldsDisplayMessage:e.Record({fields:e.Vec(e.Tuple(e.Text,d)),intent:e.Text}),GenericDisplayMessage:e.Text}),f=e.Record({metadata:t,consent_message:l}),S=e.Record({description:e.Text}),N=e.Variant({GenericError:e.Record({description:e.Text,error_code:e.Nat}),InsufficientPayment:S,UnsupportedCanisterCall:S,ConsentMessageUnavailable:S}),x=e.Variant({Ok:f,Err:N});return e.Service({icrc10_supported_standards:e.Func([],[e.Vec(e.Record({url:e.Text,name:e.Text}))],["query"]),icrc21_canister_call_consent_message:e.Func([s],[x],[])})};import{isNullish as pr}from"@dfinity/utils";import{base64ToUint8Array as nr,isNullish as Ze,nonNullish as Ne}from"@dfinity/utils";import{Certificate as Qs,HttpAgent as Zs,defaultStrategy as Xs,lookupResultToBuffer as cr,pollForResponse as Ds}from"@icp-sdk/core/agent";import{Principal as ar}from"@icp-sdk/core/principal";import{hashObject as Ks,isNullish as rr,nowInBigIntNanoSeconds as Ys,uint8ArrayToBase64 as sr}from"@dfinity/utils";var or=()=>{let e=new Map;return async t=>{let{canister_id:r,sender:s,method_name:o,arg:a,ingress_expiry:c,nonce:m}=t.body;if(rr(m))return t;let d={canisterId:r.toString(),sender:s.toString(),method:o,arg:sr(a),nonce:sr(m)},l=await Ks(d),f=e.get(l);if(rr(f))return e.set(l,c),t;if(f.toBigInt()<=Ys())throw Error("The request has expired and is no longer valid. Please try again with a new request.");return t.body.ingress_expiry=f,t}};import{HttpAgent as Js}from"@icp-sdk/core/agent";var Z=class e{_agent;constructor(t){this._agent=t}static async create(t){let r=await Js.create(t);return new e(r)}get agent(){return this._agent}};var Xe=class extends Error{},De=class extends Error{},Le=class extends Error{},et=class extends Error{},tt=class extends Error{},Ie=class e extends Z{constructor(t){super(t),this._agent.addTransform("update",or())}static async create(t){let r=await Zs.create(t);return new e(r)}request=async({arg:t,canisterId:r,method:s,nonce:o})=>{let{requestDetails:a,...c}=await this._agent.call(r,{methodName:s,arg:nr(t),effectiveCanisterId:r,nonce:Ne(o)?nr(o):void 0});if(this.assertRequestDetails(a),Ze(a))throw new Xe;let m=await this.readResponse({callResponse:{requestDetails:a,...c},canisterId:r});if(Ne(m))return m;let{response:{status:d}}=c;if(d===202)return await this.pollForResponse({callResponse:{requestDetails:a,...c},canisterId:r});throw new De};async readResponse({callResponse:{requestId:t,response:{body:r,status:s},requestDetails:o},canisterId:a}){if(Ze(r)||!("certificate"in r))return;if(s!==200)throw new et;let{certificate:c}=r;if(Ze(this._agent.rootKey))throw new tt;let m=await Qs.create({certificate:c,rootKey:this._agent.rootKey,canisterId:ar.fromText(a)}),{result:d}=this.assertReply({certificate:m,requestId:t});if(d!=="valid")throw new Le;return{certificate:m,requestDetails:o}}assertRequestDetails(t){return Ne(t)}assertReply({certificate:t,requestId:r}){let s=[new TextEncoder().encode("request_status"),r];switch(new TextDecoder().decode(cr(t.lookup_path([...s,"status"])))){case"replied":let a=cr(t.lookup_path([...s,"reply"]));return{result:Ne(a)?"valid":"invalid"};case"rejected":return{result:"rejected"};default:return{result:"empty"}}}async pollForResponse({callResponse:{requestId:t,requestDetails:r},canisterId:s}){let{certificate:o}=await Ds(this._agent,ar.fromText(s),t,{strategy:Xs()});return{certificate:o,requestDetails:r}}};var rt="https://icp-api.io";var ir=({hostname:e})=>({...(["localhost","127.0.0.1"].includes(e)||e.endsWith(".localhost"))&&{shouldFetchRootKey:!0}});var we=class{#e=void 0;async getAgent({options:t,type:r}){let{owner:s}=t,o=`${s.getPrincipal().toText()}_${r}`;if(pr(this.#e)||pr(this.#e[o])){let a=await this.createAgent({options:t,type:r});return this.#e={...this.#e??{},[o]:a},a}return this.#e[o]}async createAgent({options:{owner:t,host:r},type:s}){let{hostname:o}=new URL(r??rt),a={identity:t,host:r??rt,...ir({hostname:o})};return s==="default"?await Z.create(a):await Ie.create(a)}async getDefaultAgent(t){return await this.getAgent({options:t,type:"default"})}async getCustomAgent(t){return await this.getAgent({options:t,type:"custom"})}};var Te=class extends we{#e;async consentMessage({request:t,...r}){let{icrc21_canister_call_consent_message:s}=await this.getIcrc21Actor(r);return await s(t)}async getIcrc21Actor({canisterId:t,...r}){let s=t instanceof to?t.toText():t,{[s]:o}=this.#e??{[s]:void 0};if(Ls(o)){let a=await this.createActor({canisterId:t,idlFactory:Qe,...r});return this.#e={...this.#e??{},[s]:a},a}return o}async createActor({canisterId:t,idlFactory:r,owner:s,host:o}){let{agent:a}=await this.getDefaultAgent({host:o,owner:s});return await eo.createActor(r,{agent:a,canisterId:t})}};var Ee=class extends Te{async call({owner:t,host:r,params:{canisterId:s,method:o,arg:a,nonce:c}}){let d=await(await this.getCustomAgent({host:r,owner:t})).request({canisterId:s,method:o,arg:a,nonce:c});return this.encodeResult(d)}async ledgerMetadata({host:t,owner:r,params:{canisterId:s}}){let{agent:o}=await this.getDefaultAgent({host:t,owner:r}),{metadata:a}=ro.create({agent:o,canisterId:so.fromText(s)});return await a({certified:!0})}encodeResult({requestDetails:t,certificate:r}){let s=ur(Bt(r.cert)),o=ur(Ut(t,Kt));return{certificate:s,contentMap:o}}};import{fromNullable as _,isNullish as io,nonNullish as fr}from"@dfinity/utils";import{encodeIcrcAccount as H}from"@icp-sdk/canisters/ledger/icrc";import{arrayOfNumberToUint8Array as oo,uint8ArrayToHexString as no}from"@dfinity/utils";var mr=e=>{let t=e instanceof Uint8Array?e:oo(e);try{return new TextDecoder("utf-8").decode(t)}catch{return`0x${no(e)}`}};var q=({amount:e,decimals:t})=>{let r=Number(e)/10**t,s=t>=1?1:t;return new Intl.NumberFormat("en-US",{minimumFractionDigits:s,maximumFractionDigits:t}).format(r)},dr=e=>{let t={weekday:"short",month:"short",day:"numeric",year:"numeric",hour:"2-digit",minute:"2-digit",second:"2-digit",hour12:!1,timeZone:"UTC",timeZoneName:"short"};return new Date(Number(e/1000000n)).toLocaleDateString("en",t)};import{uint8ArrayToBase64 as yc}from"@dfinity/utils";import{IDL as co}from"@icp-sdk/core/candid";var Oe=({recordClass:e,bytes:t})=>{let r=co.decode([e],t);if(r.length!==1)throw new Error("More than one object returned. This is unexpected.");let[s]=r;return s};var yr=async({arg:e,owner:t,token:{symbol:r,decimals:s,fee:o}})=>await ct({arg:e,fn:c=>{let{amount:m,from_subaccount:d,to:{owner:l,subaccount:f},fee:S,memo:N}=Oe({recordClass:Ae.TransferArgs,bytes:new Uint8Array(e)}),{core:{amount:x,from:k,to:D,fee:L},icrc1_transfer:{title:ee}}=c,b=[`# ${ee}`];b.push(`${g(x)}
${q({amount:m,decimals:s})} ${r}`);let te=_(d),re=H({owner:t,subaccount:te});b.push(`${g(k)}
${re}`);let I=H({owner:l,subaccount:_(f)});b.push(`${g(D)}
${I}`),b.push(`${g(L)}
${q({amount:_(S)??o,decimals:s})} ${r}`);let se=nt({memo:N,en:c});return{message:[...b,...se]}}}),hr=async({arg:e,owner:t,token:{symbol:r,decimals:s,fee:o}})=>await ct({arg:e,fn:c=>{let{spender:{owner:m,subaccount:d},from_subaccount:l,amount:f,expected_allowance:S,expires_at:N,fee:x,memo:k}=Oe({recordClass:me.ApproveArgs,bytes:new Uint8Array(e)}),{icrc2_approve:{title:D,address_is_allowed:L,your_account:ee,requested_withdrawal_allowance:b,withdrawal_allowance:{none:te,some:re},expiration_date:{title:I,none:se},approval_fee:ze,approver_account_transaction_fees:Fe}}=c,P=[`# ${D}`],Ue=H({owner:m,subaccount:_(d)});P.push(`${g(L)}
${Ue}`);let Kr=_(l),lt=H({owner:t,subaccount:Kr});P.push(`${g(ee)}
${lt}`),P.push(`${g(b)}
${q({amount:f,decimals:s})} ${r}`);let ft=_(S);fr(ft)?P.push(`${g(re)}
${q({amount:ft,decimals:s})} ${r}`):P.push(`\u26A0 ${te.replace("{amount}",q({amount:f,decimals:s})).replace("{symbol}",r)}`);let yt=_(N);P.push(`${g(I)}
${fr(yt)?dr(yt):se}`),P.push(`${g(ze)}
${q({amount:_(x)??o,decimals:s})} ${r}`),P.push(`${g(Fe)}
${lt}`);let Yr=nt({memo:k,en:c});return{message:[...P,...Yr]}}}),Sr=async({arg:e,owner:t,token:{symbol:r,decimals:s,fee:o}})=>await ct({arg:e,fn:c=>{let{from:{owner:m,subaccount:d},to:{owner:l,subaccount:f},spender_subaccount:S,amount:N,fee:x,memo:k}=Oe({recordClass:me.TransferFromArgs,bytes:new Uint8Array(e)}),{core:{to:D},icrc2_transfer_from:{title:L,withdrawal_account:ee,sending_the_transfer_request:b,amount_to_withdraw:te,fee_paid_by_withdrawal_account:re}}=c,I=[`# ${L}`],se=H({owner:m,subaccount:_(d)});I.push(`${g(ee)}
${se}`);let ze=_(S),Fe=H({owner:t,subaccount:ze});I.push(`${g(b)}
${Fe}`),I.push(`${g(te)}
${q({amount:N,decimals:s})} ${r}`);let P=H({owner:l,subaccount:_(f)});I.push(`${g(D)}
${P}`),I.push(`${g(re)}
${q({amount:_(x)??o,decimals:s})} ${r}`);let Ue=nt({memo:k,en:c});return{message:[...I,...Ue]}}}),g=e=>`**${e}:**`,nt=({memo:e,en:t})=>{let r=_(e);if(io(r))return[];let{core:{memo:s}}=t;return[`${g(s)}
${mr(r)}`]},ct=async({fn:e,arg:t})=>{try{po({arg:t});let{default:r}=await Promise.resolve().then(()=>ts(lr(),1)),{message:s}=e(r);return{Ok:{metadata:{language:"en",utc_offset_minutes:[]},consent_message:{GenericDisplayMessage:s.join(`
`)}}}}catch(r){return{Err:r}}},st=class extends Error{},po=({arg:e})=>{if(e.byteLength>ot)throw new st(`The argument size is too large. The maximum allowed size is ${ot} bytes.`)};var ot=500,gr={icrc1_transfer:yr,icrc2_approve:hr,icrc2_transfer_from:Sr};var Rr=e=>"GenericError"in e?`Error: ${e.GenericError.description} (Code: ${e.GenericError.error_code})`:"InsufficientPayment"in e?`Insufficient Payment: ${e.InsufficientPayment.description}`:"UnsupportedCanisterCall"in e?`Unsupported Canister Call: ${e.UnsupportedCanisterCall.description}`:"ConsentMessageUnavailable"in e?`Consent Message Unavailable: ${e.ConsentMessageUnavailable.description}`:"Unknown error";var be=class{#e=new Ee;async assertAndPromptConsentMessage({params:{sender:t,...r},prompt:s,notify:o,options:{owner:a,host:c}}){let{result:m}=this.assertSender({sender:t,owner:a,notify:o});if(m==="invalid")return{result:"error"};if(at(s))return Ce(o),{result:"error"};let{origin:d}=o;s({origin:d,status:"loading"});try{let l=await this.loadConsentMessage({params:r,options:{host:c,owner:a}});if("Err"in l){let{Err:S}=l;return s({origin:d,status:"error",details:S}),Re({...o,message:Rr(S)}),{result:"error"}}let{result:f}=await this.promptConsentMessage({consentInfo:l,prompt:s,origin:d});return f==="rejected"&&_e(o),{result:f}}catch(l){return this.notifyError({err:l,prompt:s,notify:o})}}async callCanister({params:t,prompt:r,notify:s,options:o}){let{origin:a}=s;r?.({origin:a,status:"executing"});try{let c=await this.#e.call({...o,params:t});return qt({...s,result:c}),r?.({origin:a,status:"result",...c}),{result:"success"}}catch(c){return r?.({origin:a,status:"error",details:c}),Ve({...s,message:c instanceof Error&&Cr(c.message)?c.message:"An unknown error occurred"}),{result:"error"}}}assertSender({notify:t,owner:r,sender:s}){return r.getPrincipal().toText()===lo.fromText(s).toText()?{result:"valid"}:(Tt(t),{result:"invalid"})}async callConsentMessage({params:{canisterId:t,method:r,arg:s},options:{owner:o,host:a}}){return await this.#e.consentMessage({owner:o,host:a,canisterId:t,request:{method:r,arg:_r(s),user_preferences:{metadata:{language:"en",utc_offset_minutes:[]},device_spec:[]}}})}notifyError({err:t,notify:r,prompt:s}){let{origin:o}=r;return s({origin:o,status:"error",details:t}),Ve({...r,message:t instanceof Error&&Cr(t.message)?t.message:"An unknown error occurred"}),{result:"error"}}async promptConsentMessage({prompt:t,...r}){return await new Promise(o=>{t({status:"result",approve:()=>{o({result:"approved"})},reject:()=>{o({result:"rejected"})},...r})})}async loadConsentMessage(t){try{return await this.callConsentMessage(t)}catch(r){let s=await this.tryBuildConsentMessageOnError(t);if("Warn"in s)return s;throw r}}async tryBuildConsentMessageOnError({params:{method:t,arg:r,canisterId:s},options:{owner:o,host:a}}){let c=gr[t];if(at(c))return{NoFallback:null};try{let m=await this.#e.ledgerMetadata({params:{canisterId:s},host:a,owner:o}),d=uo(m);if(at(d))return{Err:new Error("Incomplete token metadata.")};let l=await c({arg:mo(_r(r)),token:d,owner:o.getPrincipal()});return"Err"in l?{Err:l.Err}:{Warn:{consentInfo:l.Ok,method:t,arg:r,canisterId:s}}}catch(m){return{Err:m}}}};import{isNullish as yo}from"@dfinity/utils";import{nonNullish as fo}from"@dfinity/utils";var xr=({key:e,value:t})=>{try{localStorage.setItem(e,JSON.stringify(t))}catch(r){console.error(r)}};var it=({key:e})=>{try{let t=localStorage.getItem(e);return fo(t)?JSON.parse(t):void 0}catch(t){console.error(t);return}};var ho="oisy_signer",Pr=({owner:e,origin:t})=>`${ho}_${t}_${e.toText()}`,Ar=({scopes:e,...t})=>{let r=Pr(t),s=it({key:r}),o=(s?.scopes??[]).filter(({scope:{method:d}})=>e.find(({scope:{method:l}})=>d===l)===void 0),a=Date.now(),c=e.reduce((d,{scope:{method:l,...f},...S})=>{let N=(s?.scopes??[]).find(({scope:{method:x}})=>x===l);return[...d,{...S,scope:{...f,method:l},createdAt:N?.createdAt??a,updatedAt:a}]},[]),m={scopes:[...o,...c],createdAt:s?.createdAt??a,updatedAt:a};xr({key:r,value:m})},pt=({sessionOptions:e,...t})=>{let r=it({key:Pr(t)});if(!yo(r))return r.scopes.filter(({updatedAt:s})=>s>=Date.now()-(e?.sessionPermissionExpirationInMilliseconds??At)).map(({updatedAt:s,createdAt:o,...a})=>({...a}))},Nr=({method:e,...t})=>pt(t)?.find(({scope:{method:s}})=>s===e)?.state??F;import{base64ToUint8Array as So,isNullish as go}from"@dfinity/utils";import{PrincipalTextSchema as wr}from"@dfinity/zod-schemas";import*as C from"zod";import*as Ir from"zod";var B=Ir.string().refine(e=>{try{return btoa(atob(e))===e}catch{return!1}},{message:"Invalid base64 string"});var ea=C.object({scopes:C.array(C.object({method:U})).min(1)}),Ro=C.object({scopes:C.array(C.object({method:C.string()})).min(1)}),Tr=ke({method:z,params:Ro}),Er=ce({method:fe}),Or=ce({method:ye}),br=ce({method:he}),vr=ce({method:w}),_o=C.string().trim().min(1),ut=C.object({canisterId:wr,sender:wr,method:_o,arg:B,nonce:B.optional().refine(e=>{try{return go(e)||So(e).length<=32}catch{return!1}},{message:"Nonce must be a Uint8Array with a maximum length of 32 bytes"})}),Mr=ke({method:T,params:ut});var X=class extends Error{};import*as p from"zod";import{base64ToUint8Array as Co}from"@dfinity/utils";import{PrincipalTextSchema as xo}from"@dfinity/zod-schemas";import*as ve from"zod";var Po=B.refine(e=>{try{return Co(e).length===32}catch{return!1}},{message:"Subaccount must be exactly 32 bytes long."}),Ao=ve.object({owner:xo,subaccount:Po.optional()}).strict(),Me=ve.array(Ao).min(1);import{UrlSchema as No}from"@dfinity/zod-schemas";import*as R from"zod";var Io=R.object({method:U}),wo=R.object({scope:Io,state:ge}).strict(),qe=R.array(wo),To=R.object({scopes:qe}).strict(),da=$(To),Eo=/^https:\/\/github\.com\/dfinity\/ICRC\/blob\/main\/ICRCs\/ICRC-\d+\/ICRC-\d+\.md$/,Oo=R.url().regex(Eo).refine(e=>{try{No.parse(e)}catch{return!1}let t=/(ICRC-\d+)\.md/g.exec(e);if(t===null)return!1;let[r,s]=t;return Object.keys(oe.enum).includes(s)},{message:"The URL does not match any of the IcrcStandard values."}),bo=R.array(R.object({name:oe,url:Oo}).strict()).min(1),la=$(R.object({supportedStandards:bo})),fa=$(R.literal("ready")),ya=$(R.object({accounts:Me})),mt=R.object({contentMap:B,certificate:B}).strict(),ha=$(mt.strict());import{UrlSchema as vo}from"@dfinity/zod-schemas";var qr=vo;var Na=p.enum([K,z,w,T]),W=p.object({origin:qr}),zr=p.function({output:p.void()}),de=p.enum(["result","error"]),Fr=W.extend({status:p.literal(de.enum.error),details:p.unknown().optional()}),Mo=p.function({input:p.tuple([qe]),output:p.void()}),qo=W.extend({requestedScopes:qe,confirm:Mo}),Ur=p.function({input:p.tuple([qo]),output:p.void()}),zo=p.function({input:p.tuple([Me]),output:p.void()}),Fo=W.extend({approve:zo,reject:zr}),Br=p.function({input:p.tuple([Fo]),output:p.void()}),Uo=p.function({output:p.void()}),kr=p.enum(["loading"]),Ia=kr.or(de),Bo=W.extend({status:p.literal(kr.enum.loading)}),Vr=p.custom(),ko=p.object({Ok:Vr}),Vo=p.object({Warn:ut.pick({canisterId:!0,method:!0,arg:!0}).extend({consentInfo:Vr})}),jo=p.union([ko,Vo]),$o=W.extend({status:p.literal(de.enum.result),consentInfo:jo,approve:Uo,reject:zr}),Go=p.union([Bo,$o,Fr]),jr=p.function({input:p.tuple([Go]),output:p.void()}),$r=p.enum(["executing"]),wa=$r.or(de),Ho=W.extend({status:p.literal($r.enum.executing)}),Wo=p.intersection(W.extend({status:p.literal(de.enum.result)}),mt),Ko=p.union([Ho,Wo,Fr]),Gr=p.function({input:p.tuple([Ko]),output:p.void()});var Wr=class e{#e;#t;#r;#s;#n;#c;#o=!1;#a=new be;constructor(t){this.#e=t,window.addEventListener("message",this.onMessageListener)}static init(t){return new e(t)}disconnect=()=>{window.removeEventListener("message",this.onMessageListener),this.#t=null};onMessageListener=t=>{this.onMessage(t)};onMessage=async t=>{let{data:r,origin:s}=t,{success:o,data:a}=j.safeParse(r);if(!o)return;let{handled:c}=this.handleReadOnlyMessage(t);if(c)return;let{busy:m}=this.assertNotBusy(t);if(m)return;let{handled:d}=await this.handleMessage(t);d||Re({id:a?.id??null,origin:s})};handleReadOnlyMessage(t){let{handled:r}=this.handleStatusRequest(t);if(r)return{handled:!0};let{handled:s}=this.handleSupportedStandards(t);return s?{handled:!0}:{handled:!1}}async handleMessage(t){let{valid:r}=this.assertNotUndefinedAndSameOrigin(t);if(!r)return{handled:!0};let{handled:s}=this.handlePermissionsRequest(t);if(s)return{handled:!0};let{handled:o}=await this.handleRequestPermissionsRequest(t);if(o)return{handled:!0};let{handled:a}=await this.handleAccounts(t);if(a)return{handled:!0};let{handled:c}=await this.handleCallCanister(t);return c?{handled:!0}:{handled:!1}}setWalletOrigin({origin:t}){Hr(this.#t)||(this.#t=t)}assertUndefinedOrSameOrigin({data:t,origin:r}){if(Hr(this.#t)&&this.#t!==r){let{data:s}=j.safeParse(t);return A({id:s?.id??null,origin:r,error:{code:500,message:"The relying party's origin is not permitted to obtain the status of the signer."}}),{valid:!1}}return{valid:!0}}assertNotBusy({data:t,origin:r}){return this.#o?(Et({id:t?.id??null,origin:r}),{busy:!0}):{busy:!1}}async handleWithBusy(t){this.#o=!0;try{return await t()}finally{this.setIdle()}}setIdle(){this.#o=!1}assertNotUndefinedAndSameOrigin({data:t,origin:r}){if(le(this.#t)||this.#t!==r){let{data:s}=j.safeParse(t);return A({id:s?.id??null,origin:r,error:{code:500,message:le(this.#t)?"The relying party has not established a connection to the signer.":"The relying party's origin is not allowed to interact with the signer."}}),{valid:!1}}return{valid:!0}}register=({method:t,prompt:r})=>{switch(t){case K:{jr.parse(r),this.#n=r;return}case z:{Ur.parse(r),this.#r=r;return}case w:{Br.parse(r),this.#s=r;return}case T:{Gr.parse(r),this.#c=r;return}}throw new Error("The specified method is not supported. Please ensure you are using a supported standard.")};handleStatusRequest({data:t,origin:r,...s}){let{success:o,data:a}=br.safeParse(t);if(o){let{valid:c}=this.assertUndefinedOrSameOrigin({data:t,origin:r,...s});if(!c)return{handled:!0};let{id:m}=a;return Ot({id:m,origin:r}),this.setWalletOrigin({origin:r}),{handled:!0}}return{handled:!1}}handleSupportedStandards({data:t,origin:r}){let{success:s,data:o}=Or.safeParse(t);if(s){let{id:a}=o;return bt({id:a,origin:r}),{handled:!0}}return{handled:!1}}handlePermissionsRequest({data:t}){let{success:r,data:s}=Er.safeParse(t);if(r){let{id:o}=s;return this.emitPermissions({id:o}),{handled:!0}}return{handled:!1}}async handleRequestPermissionsRequest({data:t,origin:r}){let s=async()=>{let{success:o,data:a}=Tr.safeParse(t);if(!o)return{handled:!1};let{id:c,params:{scopes:m}}=a;if(le(this.#r))return this.assertWalletOriginAndNotifyMissingPromptError(c),{handled:!0};let d=m.filter(({method:f})=>U.safeParse(f).success).map(({method:f})=>({scope:{method:f},state:ge.enum.denied})).sort(({scope:{method:f}},{scope:{method:S}})=>f.localeCompare(S)),l=async()=>{let f=await this.promptPermissions({requestedScopes:d,origin:r});this.savePermissions({scopes:f}),this.emitPermissions({id:c})};return await this.prompt({requestId:c,promptFn:l}),{handled:!0}};return await this.handleWithBusy(s)}async promptPermissions(t){return await new Promise((s,o)=>{let a=c=>{s(c)};if(le(this.#r)){o(new X);return}this.#r({...t,confirm:a})})}emitPermissions({id:t}){dt(this.#t,"The relying party's origin is unknown.");let{owner:r,sessionOptions:s}=this.#e,o=pt({owner:r.getPrincipal(),origin:this.#t,sessionOptions:s}),a=[...o??[],...Pt.filter(({scope:{method:c}})=>(o??[]).find(({scope:{method:m}})=>m===c)===void 0)];vt({id:t,origin:this.#t,scopes:a})}assertWalletOriginAndNotifyMissingPromptError(t){dt(this.#t,"The relying party's origin is unknown."),Ce({id:t??null,origin:this.#t})}savePermissions({scopes:t}){dt(this.#t,"The relying party's origin is unknown.");let{owner:r}=this.#e;Ar({owner:r.getPrincipal(),origin:this.#t,scopes:t})}async handleAccounts({data:t,origin:r}){let s=async()=>{let{success:o,data:a}=vr.safeParse(t);if(!o)return{handled:!1};let{id:c}=a,m=async()=>{let l=async()=>{let{result:f,accounts:S}=await this.promptAccounts({origin:r});if(f==="rejected"){_e({id:c,origin:r});return}Mt({accounts:S,id:c,origin:r})};await this.prompt({requestId:c,promptFn:l})};switch(await this.assertAndPromptPermissions({method:w,requestId:c,origin:r})){case V:{je({id:c??null,origin:r});break}case Y:{await m();break}}return{handled:!0}};return await this.handleWithBusy(s)}async prompt({requestId:t,promptFn:r}){try{await r()}catch(s){if(s instanceof X){this.assertWalletOriginAndNotifyMissingPromptError(t);return}throw s}}async promptAccounts(t){return await new Promise((s,o)=>{let a=()=>{s({result:"rejected",accounts:[]})},c=m=>{s({result:"approved",accounts:m})};if(le(this.#s)){o(new X);return}this.#s({approve:c,reject:a,...t})})}async handleCallCanister({data:t,origin:r}){let s=async()=>{let{success:o,data:a}=Mr.safeParse(t);if(!o)return{handled:!1};let{id:c,params:m}=a;if(await this.assertAndPromptPermissions({method:T,requestId:c,origin:r})===V)return je({id:c??null,origin:r}),{handled:!0};let l={id:c,origin:r},{result:f}=await this.#a.assertAndPromptConsentMessage({notify:l,params:m,prompt:this.#n,options:this.#e});return f!=="approved"?{handled:!0}:(await this.#a.callCanister({notify:l,params:m,options:this.#e,prompt:this.#c}),{handled:!0})};return await this.handleWithBusy(s)}async assertAndPromptPermissions({method:t,origin:r,requestId:s}){let{owner:o}=this.#e,a=Nr({owner:o.getPrincipal(),origin:r,method:t});return a===F?await new Promise((m,d)=>{let l=async()=>{let f=[{scope:{method:t},state:V}],S=await this.promptPermissions({requestedScopes:f,origin:r});if(this.savePermissions({scopes:S}),S.find(({scope:{method:x},state:k})=>x===t&&k===Y)!==void 0){m(Y);return}m(V)};this.prompt({requestId:s,promptFn:l}).catch(f=>{d(f)})}):a}};export{Wr as Signer};
//# sourceMappingURL=signer.js.map