@ic-pay/icpay-widget 0.1.98 → 0.1.99

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -51,7 +51,7 @@ ${e(i)}
51
51
  Request ID: ${zt(t)}
52
52
  `)}throw new Error("unreachable")}var PA=ye(()=>{"use strict";Dw();q0();bo();MA();MA();MA()});var fk,pk=ye(()=>{"use strict";fk=({IDL:r})=>{let e=r.Variant({mainnet:r.Null,testnet:r.Null}),t=r.Text,n=r.Record({network:e,address:t,min_confirmations:r.Opt(r.Nat32)}),i=r.Nat64,s=i,o=r.Nat32,a=r.Record({start_height:o,end_height:r.Opt(o),network:e}),c=r.Vec(r.Nat8),l=r.Record({tip_height:o,block_headers:r.Vec(c)}),u=r.Record({network:e}),h=r.Nat64,p=r.Vec(h),w=r.Record({network:e,filter:r.Opt(r.Variant({page:r.Vec(r.Nat8),min_confirmations:r.Nat32})),address:t}),y=r.Vec(r.Nat8),v=r.Record({txid:r.Vec(r.Nat8),vout:r.Nat32}),S=r.Record({height:r.Nat32,value:i,outpoint:v}),N=r.Record({next_page:r.Opt(r.Vec(r.Nat8)),tip_height:o,tip_block_hash:y,utxos:r.Vec(S)}),O=r.Record({transaction:r.Vec(r.Nat8),network:e}),L=r.Principal,j=r.Record({canister_id:L,num_requested_changes:r.Opt(r.Nat64)}),q=r.Variant({from_user:r.Record({user_id:r.Principal}),from_canister:r.Record({canister_version:r.Opt(r.Nat64),canister_id:r.Principal})}),D=r.Vec(r.Nat8),F=r.Variant({creation:r.Record({controllers:r.Vec(r.Principal)}),code_deployment:r.Record({mode:r.Variant({reinstall:r.Null,upgrade:r.Null,install:r.Null}),module_hash:r.Vec(r.Nat8)}),load_snapshot:r.Record({canister_version:r.Nat64,taken_at_timestamp:r.Nat64,snapshot_id:D}),controllers_change:r.Record({controllers:r.Vec(r.Principal)}),code_uninstall:r.Null}),k=r.Record({timestamp_nanos:r.Nat64,canister_version:r.Nat64,origin:q,details:F}),C=r.Record({controllers:r.Vec(r.Principal),module_hash:r.Opt(r.Vec(r.Nat8)),recent_changes:r.Vec(k),total_num_changes:r.Nat64}),z=r.Record({canister_id:L}),R=r.Variant({controllers:r.Null,public:r.Null,allowed_viewers:r.Vec(r.Principal)}),g=r.Record({freezing_threshold:r.Nat,controllers:r.Vec(r.Principal),reserved_cycles_limit:r.Nat,log_visibility:R,wasm_memory_limit:r.Nat,memory_allocation:r.Nat,compute_allocation:r.Nat}),m=r.Record({status:r.Variant({stopped:r.Null,stopping:r.Null,running:r.Null}),memory_size:r.Nat,cycles:r.Nat,settings:g,query_stats:r.Record({response_payload_bytes_total:r.Nat,num_instructions_total:r.Nat,num_calls_total:r.Nat,request_payload_bytes_total:r.Nat}),idle_cycles_burned_per_day:r.Nat,module_hash:r.Opt(r.Vec(r.Nat8)),reserved_cycles:r.Nat}),d=r.Record({canister_id:L}),f=r.Record({freezing_threshold:r.Opt(r.Nat),controllers:r.Opt(r.Vec(r.Principal)),reserved_cycles_limit:r.Opt(r.Nat),log_visibility:r.Opt(R),wasm_memory_limit:r.Opt(r.Nat),memory_allocation:r.Opt(r.Nat),compute_allocation:r.Opt(r.Nat)}),b=r.Record({settings:r.Opt(f),sender_canister_version:r.Opt(r.Nat64)}),_=r.Record({canister_id:L}),T=r.Record({canister_id:L}),I=r.Record({canister_id:L,snapshot_id:D}),A=r.Record({canister_id:L}),U=r.Variant({secp256k1:r.Null}),M=r.Record({key_id:r.Record({name:r.Text,curve:U}),canister_id:r.Opt(L),derivation_path:r.Vec(r.Vec(r.Nat8))}),P=r.Record({public_key:r.Vec(r.Nat8),chain_code:r.Vec(r.Nat8)}),H=r.Record({canister_id:L}),V=r.Record({idx:r.Nat64,timestamp_nanos:r.Nat64,content:r.Vec(r.Nat8)}),G=r.Record({canister_log_records:r.Vec(V)}),X=r.Record({value:r.Text,name:r.Text}),se=r.Record({status:r.Nat,body:r.Vec(r.Nat8),headers:r.Vec(X)}),W=r.Record({url:r.Text,method:r.Variant({get:r.Null,head:r.Null,post:r.Null}),max_response_bytes:r.Opt(r.Nat64),body:r.Opt(r.Vec(r.Nat8)),transform:r.Opt(r.Record({function:r.Func([r.Record({context:r.Vec(r.Nat8),response:se})],[se],["query"]),context:r.Vec(r.Nat8)})),headers:r.Vec(X)}),Q=r.Variant({reinstall:r.Null,upgrade:r.Opt(r.Record({wasm_memory_persistence:r.Opt(r.Variant({keep:r.Null,replace:r.Null})),skip_pre_upgrade:r.Opt(r.Bool)})),install:r.Null}),Y=r.Record({hash:r.Vec(r.Nat8)}),ne=r.Record({arg:r.Vec(r.Nat8),wasm_module_hash:r.Vec(r.Nat8),mode:Q,chunk_hashes_list:r.Vec(Y),target_canister:L,store_canister:r.Opt(L),sender_canister_version:r.Opt(r.Nat64)}),J=r.Vec(r.Nat8),re=r.Record({arg:r.Vec(r.Nat8),wasm_module:J,mode:Q,canister_id:L,sender_canister_version:r.Opt(r.Nat64)}),oe=r.Record({canister_id:L}),ie=r.Record({id:D,total_size:r.Nat64,taken_at_timestamp:r.Nat64}),le=r.Vec(ie),de=r.Record({canister_id:L,sender_canister_version:r.Opt(r.Nat64),snapshot_id:D}),fe=r.Record({start_at_timestamp_nanos:r.Nat64,subnet_id:r.Principal}),Ee=r.Record({num_block_failures_total:r.Nat64,node_id:r.Principal,num_blocks_proposed_total:r.Nat64}),xe=r.Vec(r.Record({timestamp_nanos:r.Nat64,node_metrics:r.Vec(Ee)})),_e=r.Record({settings:r.Opt(f),specified_id:r.Opt(L),amount:r.Opt(r.Nat),sender_canister_version:r.Opt(r.Nat64)}),Qe=r.Record({canister_id:L}),De=r.Record({canister_id:L,amount:r.Nat}),Ye=r.Vec(r.Nat8),Ze=r.Variant({ed25519:r.Null,bip340secp256k1:r.Null}),E=r.Record({key_id:r.Record({algorithm:Ze,name:r.Text}),canister_id:r.Opt(L),derivation_path:r.Vec(r.Vec(r.Nat8))}),x=r.Record({public_key:r.Vec(r.Nat8),chain_code:r.Vec(r.Nat8)}),B=r.Record({key_id:r.Record({name:r.Text,curve:U}),derivation_path:r.Vec(r.Vec(r.Nat8)),message_hash:r.Vec(r.Nat8)}),$=r.Record({signature:r.Vec(r.Nat8)}),K=r.Variant({bip341:r.Record({merkle_root_hash:r.Vec(r.Nat8)})}),Z=r.Record({aux:r.Opt(K),key_id:r.Record({algorithm:Ze,name:r.Text}),derivation_path:r.Vec(r.Vec(r.Nat8)),message:r.Vec(r.Nat8)}),ee=r.Record({signature:r.Vec(r.Nat8)}),Ne=r.Record({canister_id:L}),ke=r.Record({canister_id:L}),Ie=r.Record({canister_id:L}),We=r.Vec(Y),Ge=r.Record({subnet_id:r.Principal}),Xe=r.Record({replica_version:r.Text}),pr=r.Record({replace_snapshot:r.Opt(D),canister_id:L}),Er=ie,St=r.Record({canister_id:L,sender_canister_version:r.Opt(r.Nat64)}),fr=r.Record({canister_id:r.Principal,settings:f,sender_canister_version:r.Opt(r.Nat64)}),nr=r.Record({chunk:r.Vec(r.Nat8),canister_id:r.Principal}),wt=Y;return r.Service({bitcoin_get_balance:r.Func([n],[s],[]),bitcoin_get_block_headers:r.Func([a],[l],[]),bitcoin_get_current_fee_percentiles:r.Func([u],[p],[]),bitcoin_get_utxos:r.Func([w],[N],[]),bitcoin_send_transaction:r.Func([O],[],[]),canister_info:r.Func([j],[C],[]),canister_status:r.Func([z],[m],[]),clear_chunk_store:r.Func([d],[],[]),create_canister:r.Func([b],[_],[]),delete_canister:r.Func([T],[],[]),delete_canister_snapshot:r.Func([I],[],[]),deposit_cycles:r.Func([A],[],[]),ecdsa_public_key:r.Func([M],[P],[]),fetch_canister_logs:r.Func([H],[G],["query"]),http_request:r.Func([W],[se],[]),install_chunked_code:r.Func([ne],[],[]),install_code:r.Func([re],[],[]),list_canister_snapshots:r.Func([oe],[le],[]),load_canister_snapshot:r.Func([de],[],[]),node_metrics_history:r.Func([fe],[xe],[]),provisional_create_canister_with_cycles:r.Func([_e],[Qe],[]),provisional_top_up_canister:r.Func([De],[],[]),raw_rand:r.Func([],[Ye],[]),schnorr_public_key:r.Func([E],[x],[]),sign_with_ecdsa:r.Func([B],[$],[]),sign_with_schnorr:r.Func([Z],[ee],[]),start_canister:r.Func([Ne],[],[]),stop_canister:r.Func([ke],[],[]),stored_chunks:r.Func([Ie],[We],[]),subnet_info:r.Func([Ge],[Xe],[]),take_canister_snapshot:r.Func([pr],[Er],[]),uninstall_code:r.Func([St],[],[]),update_settings:r.Func([fr],[],[]),upload_chunk:r.Func([nr],[wt],[])})}});function J0(r,e){let t=Oh.decode(r,gk.Buffer.from(e));switch(t.length){case 0:return;case 1:return t[0];default:return t}}function Lne(r,e,t,n){let i;t.annotations.includes("query")||t.annotations.includes("composite_query")?i=async(o,...a)=>{var c,l;o=Object.assign(Object.assign({},o),(l=(c=r[Ia].config).queryTransform)===null||l===void 0?void 0:l.call(c,e,a,Object.assign(Object.assign({},r[Ia].config),o)));let u=o.agent||r[Ia].config.agent||OA(),h=Ve.from(o.canisterId||r[Ia].config.canisterId),p=Oh.encode(t.argTypes,a),w=await u.query(h,{methodName:e,arg:p,effectiveCanisterId:o.effectiveCanisterId}),y=Object.assign(Object.assign({},w.httpDetails),{requestDetails:w.requestDetails});switch(w.status){case"rejected":throw new BA(h,e,w);case"replied":return t.annotations.includes(RA)?{httpDetails:y,result:J0(t.retTypes,w.reply.arg)}:J0(t.retTypes,w.reply.arg)}}:i=async(o,...a)=>{var c,l;o=Object.assign(Object.assign({},o),(l=(c=r[Ia].config).callTransform)===null||l===void 0?void 0:l.call(c,e,a,Object.assign(Object.assign({},r[Ia].config),o)));let u=o.agent||r[Ia].config.agent||OA(),{canisterId:h,effectiveCanisterId:p,pollingStrategyFactory:w}=Object.assign(Object.assign(Object.assign({},mk),r[Ia].config),o),y=Ve.from(h),v=p!==void 0?Ve.from(p):y,S=Oh.encode(t.argTypes,a),{requestId:N,response:O,requestDetails:L}=await u.call(y,{methodName:e,arg:S,effectiveCanisterId:v}),j,q;if(O.body&&O.body.certificate){if(u.rootKey==null)throw new Error("Agent is missing root key");let C=O.body.certificate;q=await Ca.create({certificate:nl(C),rootKey:u.rootKey,canisterId:Ve.from(h),blsVerify:n});let z=[new TextEncoder().encode("request_status"),N];switch(new TextDecoder().decode(Ni(q.lookup([...z,"status"])))){case"replied":j=Ni(q.lookup([...z,"reply"]));break;case"rejected":{let g=new Uint8Array(Ni(q.lookup([...z,"reject_code"])))[0],m=new TextDecoder().decode(Ni(q.lookup([...z,"reject_message"]))),d=Ni(q.lookup([...z,"error_code"])),f=d?new TextDecoder().decode(d):void 0;throw new Jw(y,e,N,O,g,m,f)}}}else if(O.body&&"reject_message"in O.body){let{reject_code:C,reject_message:z,error_code:R}=O.body;throw new Jw(y,e,N,O,C,z,R)}if(O.status===202){let C=w(),z=await Zw(u,v,N,C,n);q=z.certificate,j=z.reply}let D=t.annotations.includes(RA),F=t.annotations.includes(g9),k=Object.assign(Object.assign({},O),{requestDetails:L});if(j!==void 0)return D&&F?{httpDetails:k,certificate:q,result:J0(t.retTypes,j)}:F?{certificate:q,result:J0(t.retTypes,j)}:D?{httpDetails:k,result:J0(t.retTypes,j)}:J0(t.retTypes,j);if(t.retTypes.length===0)return D?{httpDetails:O,result:void 0}:void 0;throw new Error(`Call was returned undefined, but type [${t.retTypes.join(",")}].`)};let s=(...o)=>i({},...o);return s.withOptions=o=>(...a)=>i(o,...a),s}function f9(r){function e(t,n){if(r.effectiveCanisterId)return{effectiveCanisterId:Ve.from(r.effectiveCanisterId)};let i=n[0],s=Ve.fromHex("");return i&&typeof i=="object"&&i.target_canister&&t==="install_chunked_code"&&(s=Ve.from(i.target_canister)),i&&typeof i=="object"&&i.canister_id&&(s=Ve.from(i.canister_id)),{effectiveCanisterId:s}}return pi.createActor(fk,Object.assign(Object.assign(Object.assign({},r),{canisterId:Ve.fromHex("")}),{callTransform:e,queryTransform:e}))}var gk,Xw,BA,Jw,Ia,pi,mk,RA,g9,p9,kA=ye(()=>{"use strict";gk=lc(hP());Dw();I0();Mh();PA();Zi();bo();q0();pk();Xw=class extends Jr{constructor(e,t,n,i){super(["Call failed:",` Canister: ${e.toText()}`,` Method: ${t} (${n})`,...Object.getOwnPropertyNames(i).map(s=>` "${s}": ${JSON.stringify(i[s])}`)].join(`
53
53
  `)),this.canisterId=e,this.methodName=t,this.type=n,this.props=i}},BA=class extends Xw{constructor(e,t,n){var i;super(e,t,"query",{Status:n.status,Code:(i=A0[n.reject_code])!==null&&i!==void 0?i:`Unknown Code "${n.reject_code}"`,Message:n.reject_message}),this.result=n}},Jw=class extends Xw{constructor(e,t,n,i,s,o,a){super(e,t,"update",Object.assign({"Request ID":zt(n)},i.body?Object.assign(Object.assign({},a?{"Error code":a}:{}),{"Reject code":String(s),"Reject message":o}):{"HTTP status code":i.status.toString(),"HTTP status text":i.statusText})),this.requestId=n,this.response=i,this.reject_code=s,this.reject_message=o,this.error_code=a}},Ia=Symbol.for("ic-agent-metadata"),pi=class r{constructor(e){this[Ia]=Object.freeze(e)}static agentOf(e){return e[Ia].config.agent}static interfaceOf(e){return e[Ia].service}static canisterIdOf(e){return Ve.from(e[Ia].config.canisterId)}static async install(e,t){let n=e.mode===void 0?{install:null}:e.mode,i=e.arg?[...new Uint8Array(e.arg)]:[],s=[...new Uint8Array(e.module)],o=typeof t.canisterId=="string"?Ve.fromText(t.canisterId):t.canisterId;await f9(t).install_code({mode:n,arg:i,wasm_module:s,canister_id:o,sender_canister_version:[]})}static async createCanister(e,t){function n(s){return[{controllers:s.controllers?[s.controllers]:[],compute_allocation:s.compute_allocation?[s.compute_allocation]:[],freezing_threshold:s.freezing_threshold?[s.freezing_threshold]:[],memory_allocation:s.memory_allocation?[s.memory_allocation]:[],reserved_cycles_limit:[],log_visibility:[],wasm_memory_limit:[]}]}let{canister_id:i}=await f9(e||{}).provisional_create_canister_with_cycles({amount:[],settings:n(t||{}),specified_id:[],sender_canister_version:[]});return i}static async createAndInstallCanister(e,t,n){let i=await this.createCanister(n);return await this.install(Object.assign({},t),Object.assign(Object.assign({},n),{canisterId:i})),this.createActor(e,Object.assign(Object.assign({},n),{canisterId:i}))}static createActorClass(e,t){let n=e({IDL:Oh});class i extends r{constructor(o){if(!o.canisterId)throw new Jr(`Canister ID is required, but received ${typeof o.canisterId} instead. If you are using automatically generated declarations, this may be because your application is not setting the canister ID in process.env correctly.`);let a=typeof o.canisterId=="string"?Ve.fromText(o.canisterId):o.canisterId;super({config:Object.assign(Object.assign(Object.assign({},mk),o),{canisterId:a}),service:n});for(let[c,l]of n._fields)t?.httpDetails&&l.annotations.push(RA),t?.certificate&&l.annotations.push(g9),this[c]=Lne(this,c,l,o.blsVerify)}}return i}static createActor(e,t){if(!t.canisterId)throw new Jr(`Canister ID is required, but received ${typeof t.canisterId} instead. If you are using automatically generated declarations, this may be because your application is not setting the canister ID in process.env correctly.`);return new(this.createActorClass(e))(t)}static createActorWithHttpDetails(e,t){return new(this.createActorClass(e,{httpDetails:!0}))(t)}static createActorWithExtendedDetails(e,t,n={httpDetails:!0,certificate:!0}){return new(this.createActorClass(e,n))(t)}};mk={pollingStrategyFactory:X0.defaultStrategy},RA="http-details",g9="certificate";p9=class extends pi{constructor(e){super(e)}}});var wk,yk=ye(()=>{"use strict";wk=({IDL:r})=>r.Service({retrieve:r.Func([r.Text],[r.Vec(r.Nat8)],["query"]),store:r.Func([r.Text,r.Vec(r.Nat8)],[],[])})});function jne(r){return pi.createActor(wk,r)}var bk=ye(()=>{"use strict";kA();yk()});async function zne(r,e){e||(e=await Vn.create());let n=(await qw({agent:e,canisterId:Ve.fromText(r),paths:["candid"]})).get("candid");if(n)return n;let i=({IDL:o})=>o.Service({__get_candid_interface_tmp_hack:o.Func([],[o.Text],["query"])});return await pi.createActor(i,{agent:e,canisterId:r}).__get_candid_interface_tmp_hack()}var vk=ye(()=>{"use strict";Zi();Fw();l9();kA()});var Ak={};Re(Ak,{ACTOR_METHOD_WITH_CERTIFICATE:()=>g9,ACTOR_METHOD_WITH_HTTP_DETAILS:()=>RA,Actor:()=>pi,ActorCallError:()=>Xw,AdvancedActor:()=>p9,AgentCallError:()=>xw,AgentHTTPResponseError:()=>gf,AgentQueryError:()=>Sw,AgentReadStateError:()=>Cw,AnonymousIdentity:()=>Aa,CanisterStatus:()=>Hw,Cbor:()=>Bh,Certificate:()=>Ca,CertificateVerificationError:()=>Eo,DER_COSE_OID:()=>s9,ED25519_OID:()=>Dh,Ed25519PublicKey:()=>$0,Expiry:()=>wc,HttpAgent:()=>Vn,IC_ROOT_KEY:()=>TA,IdentityInvalidError:()=>Nf,LookupStatus:()=>tn,MANAGEMENT_CANISTER_ID:()=>QE,NodeType:()=>fi,Observable:()=>yA,ObservableLog:()=>Vw,ProxyAgent:()=>h9,ProxyMessageKind:()=>gn,ProxyStubAgent:()=>u9,QueryCallRejectedError:()=>BA,ReplicaRejectCode:()=>A0,RequestStatusResponseStatus:()=>Ec,SECP256K1_OID:()=>Cne,SignIdentity:()=>al,SubmitRequestType:()=>df,UpdateCallRejectedError:()=>Jw,blsVerify:()=>WE,bufEquals:()=>rl,bufFromBufLike:()=>ba,check_canister_ranges:()=>dA,compare:()=>C0,concat:()=>Xi,createAssetCanisterActor:()=>jne,createIdentityDescriptor:()=>Vte,decodeLen:()=>rk,decodeLenBytes:()=>gA,defaultStrategy:()=>Z0,encodeLen:()=>i9,encodeLenBytes:()=>n9,fetchCandid:()=>zne,find_label:()=>jw,flatten_forks:()=>zw,fromHex:()=>Es,getDefaultAgent:()=>OA,getManagementCanister:()=>f9,hash:()=>Ko,hashOfMap:()=>P0,hashTreeToString:()=>hA,hashValue:()=>mw,httpHeadersTransform:()=>pf,lookupResultToBuffer:()=>Ni,lookup_path:()=>yu,makeExpiryTransform:()=>hre,makeNonce:()=>ff,makeNonceTransform:()=>Y2,pollForResponse:()=>Zw,polling:()=>d9,randomNumber:()=>B0,reconstruct:()=>Lw,requestIdOf:()=>pc,strategy:()=>X0,toHex:()=>zt,uint8ToBuf:()=>Ih,unwrapDER:()=>F0,verify:()=>Zre,wrapDER:()=>Af});var _a=ye(()=>{"use strict";kA();Dw();Z2();Ew();aE();bk();q0();o9();vk();c9();a9();ww();VE();bo();mE();PA();Fw();Aw();PA()});function Ek(r){return r!==null&&typeof r=="object"}var jA,qh,UA,LA,eg,tg,Tf,Na,xk=ye(()=>{"use strict";_a();_a();r9();jA=function(r,e,t,n,i){if(n==="m")throw new TypeError("Private method is not writable");if(n==="a"&&!i)throw new TypeError("Private accessor was defined without a setter");if(typeof e=="function"?r!==e||!i:!e.has(r))throw new TypeError("Cannot write private member to an object whose class did not declare it");return n==="a"?i.call(r,t):i?i.value=t:e.set(r,t),t},qh=function(r,e,t,n){if(t==="a"&&!n)throw new TypeError("Private accessor was defined without a getter");if(typeof e=="function"?r!==e||!n:!e.has(r))throw new TypeError("Cannot read private member from an object whose class did not declare it");return t==="m"?n:t==="a"?n.call(r):n?n.value:e.get(r)};Tf=class r{constructor(e){if(UA.set(this,void 0),LA.set(this,void 0),e.byteLength!==r.RAW_KEY_LENGTH)throw new Error("An Ed25519 public key must be exactly 32bytes long");jA(this,UA,ba(e),"f"),jA(this,LA,r.derEncode(e),"f")}static from(e){if(typeof e=="string"){let t=Es(e);return this.fromRaw(t)}else if(Ek(e)){let t=e;if(Ek(t)&&Object.hasOwnProperty.call(t,"__derEncodedPublicKey__"))return this.fromDer(t);if(ArrayBuffer.isView(t)){let n=t;return this.fromRaw(ba(n.buffer))}else{if(t instanceof ArrayBuffer)return this.fromRaw(t);if("rawKey"in t)return this.fromRaw(t.rawKey);if("derKey"in t)return this.fromDer(t.derKey);if("toDer"in t)return this.fromDer(t.toDer())}}throw new Error("Cannot construct Ed25519PublicKey from the provided key.")}static fromRaw(e){return new r(e)}static fromDer(e){return new r(this.derDecode(e))}static derEncode(e){let t=Af(e,Dh).buffer;return t.__derEncodedPublicKey__=void 0,t}static derDecode(e){let t=F0(e,Dh);if(t.length!==this.RAW_KEY_LENGTH)throw new Error("An Ed25519 public key must be exactly 32bytes long");return ba(t)}get rawKey(){return qh(this,UA,"f")}get derKey(){return qh(this,LA,"f")}toDer(){return this.derKey}toRaw(){return this.rawKey}};UA=new WeakMap,LA=new WeakMap;Tf.RAW_KEY_LENGTH=32;Na=class r extends al{constructor(e,t){super(),eg.set(this,void 0),tg.set(this,void 0),jA(this,eg,Tf.from(e),"f"),jA(this,tg,new Uint8Array(t),"f")}static generate(e){if(e&&e.length!==32)throw new Error("Ed25519 Seed needs to be 32 bytes long.");e||(e=Xs.utils.randomPrivateKey()),rl(e,new Uint8Array(new Array(32).fill(0)))&&console.warn("Seed is all zeros. This is not a secure seed. Please provide a seed with sufficient entropy if this is a production environment.");let t=new Uint8Array(32);for(let i=0;i<32;i++)t[i]=new Uint8Array(e)[i];let n=Xs.getPublicKey(t);return r.fromKeyPair(n,t)}static fromParsedJson(e){let[t,n]=e;return new r(Tf.fromDer(Es(t)),Es(n))}static fromJSON(e){let t=JSON.parse(e);if(Array.isArray(t)){if(typeof t[0]=="string"&&typeof t[1]=="string")return this.fromParsedJson([t[0],t[1]]);throw new Error("Deserialization error: JSON must have at least 2 items.")}throw new Error(`Deserialization error: Invalid JSON type for string: ${JSON.stringify(e)}`)}static fromKeyPair(e,t){return new r(Tf.fromRaw(e),t)}static fromSecretKey(e){let t=Xs.getPublicKey(new Uint8Array(e));return r.fromKeyPair(t,e)}toJSON(){return[zt(qh(this,eg,"f").toDer()),zt(qh(this,tg,"f"))]}getKeyPair(){return{secretKey:qh(this,tg,"f"),publicKey:qh(this,eg,"f")}}getPublicKey(){return qh(this,eg,"f")}async sign(e){let t=new Uint8Array(e),n=Ih(Xs.sign(t,qh(this,tg,"f").slice(0,32)));return Object.defineProperty(n,"__signature__",{enumerable:!1,value:void 0}),n}static verify(e,t,n){let[i,s,o]=[e,t,n].map(a=>(typeof a=="string"&&(a=Es(a)),a instanceof Uint8Array&&(a=ba(a.buffer)),new Uint8Array(a)));return Xs.verify(i,s,o)}};eg=new WeakMap,tg=new WeakMap});function Sk(r){if(typeof global<"u"&&global.crypto&&global.crypto.subtle)return global.crypto.subtle;if(r)return r;if(typeof crypto<"u"&&crypto.subtle)return crypto.subtle;throw new m9("Global crypto was not available and none was provided. Please inlcude a SubtleCrypto implementation. See https://developer.mozilla.org/en-US/docs/Web/API/SubtleCrypto")}var m9,Of,Ck=ye(()=>{"use strict";_a();m9=class r extends Error{constructor(e){super(e),this.message=e,Object.setPrototypeOf(this,r.prototype)}};Of=class r extends al{constructor(e,t,n){super(),this._keyPair=e,this._derKey=t,this._subtleCrypto=n}static async generate(e){let{extractable:t=!1,keyUsages:n=["sign","verify"],subtleCrypto:i}=e??{},s=Sk(i),o=await s.generateKey({name:"ECDSA",namedCurve:"P-256"},t,n),a=await s.exportKey("spki",o.publicKey);return new this(o,a,s)}static async fromKeyPair(e,t){let n=Sk(t),i=await n.exportKey("spki",e.publicKey);return new r(e,i,n)}getKeyPair(){return this._keyPair}getPublicKey(){let e=this._derKey,t=Object.create(this._keyPair.publicKey);return t.toDer=function(){return e},t}async sign(e){let t={name:"ECDSA",hash:{name:"SHA-256"}};return await this._subtleCrypto.sign(t,this._keyPair.privateKey,e)}}});var Dne,rg,Eu,zA,w9=ye(()=>{"use strict";Zi();Dne=function(r,e,t,n,i){if(n==="m")throw new TypeError("Private method is not writable");if(n==="a"&&!i)throw new TypeError("Private accessor was defined without a setter");if(typeof e=="function"?r!==e||!i:!e.has(r))throw new TypeError("Cannot write private member to an object whose class did not declare it");return n==="a"?i.call(r,t):i?i.value=t:e.set(r,t),t},rg=function(r,e,t,n){if(t==="a"&&!n)throw new TypeError("Private accessor was defined without a getter");if(typeof e=="function"?r!==e||!n:!e.has(r))throw new TypeError("Cannot read private member from an object whose class did not declare it");return t==="m"?n:t==="a"?n.call(r):n?n.value:e.get(r)},zA=class{constructor(e){Eu.set(this,void 0),Dne(this,Eu,e,"f")}get rawKey(){return rg(this,Eu,"f").rawKey}get derKey(){return rg(this,Eu,"f").derKey}toDer(){return rg(this,Eu,"f").toDer()}getPublicKey(){return rg(this,Eu,"f")}getPrincipal(){if(!rg(this,Eu,"f").rawKey)throw new Error("Cannot get principal from a public key without a raw key.");return Ve.fromUint8Array(new Uint8Array(rg(this,Eu,"f").rawKey))}transformRequest(){return Promise.reject("Not implemented. You are attempting to use a partial identity to sign calls, but this identity only has access to the public key.To sign calls, use a DelegationIdentity instead.")}};Eu=new WeakMap});function y9(r){if(typeof r!="string"||r.length<64)throw new Error("Invalid public key.");return Es(r)}async function Vne(r,e,t,n){let i=new xu(e.toDer(),BigInt(+t)*BigInt(1e6),n),s=new Uint8Array([...$ne,...new Uint8Array(pc(Object.assign({},i)))]),o=await r.sign(nl(s));return{delegation:i,signature:o}}function Ik(r,e){for(let{delegation:i}of r.delegations)if(+new Date(Number(i.expiration/BigInt(1e6)))<=+Date.now())return!1;let t=[],n=e?.scope;n&&(Array.isArray(n)?t.push(...n.map(i=>typeof i=="string"?Ve.fromText(i):i)):t.push(typeof n=="string"?Ve.fromText(n):n));for(let i of t){let s=i.toText();for(let{delegation:o}of r.delegations){if(o.targets===void 0)continue;let a=!0;for(let c of o.targets)if(c.toText()===s){a=!1;break}if(a)return!1}}return!0}var ng,qne,Hne,Fne,DA,$ne,Wne,xu,Su,xc,ey,_k=ye(()=>{"use strict";_a();Zi();ng=lc(bw());w9();Mh();qne=function(r,e,t,n,i){if(n==="m")throw new TypeError("Private method is not writable");if(n==="a"&&!i)throw new TypeError("Private accessor was defined without a setter");if(typeof e=="function"?r!==e||!i:!e.has(r))throw new TypeError("Cannot write private member to an object whose class did not declare it");return n==="a"?i.call(r,t):i?i.value=t:e.set(r,t),t},Hne=function(r,e,t,n){if(t==="a"&&!n)throw new TypeError("Private accessor was defined without a getter");if(typeof e=="function"?r!==e||!n:!e.has(r))throw new TypeError("Cannot read private member from an object whose class did not declare it");return t==="m"?n:t==="a"?n.call(r):n?n.value:e.get(r)},Fne=function(r,e){var t={};for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&e.indexOf(n)<0&&(t[n]=r[n]);if(r!=null&&typeof Object.getOwnPropertySymbols=="function")for(var i=0,n=Object.getOwnPropertySymbols(r);i<n.length;i++)e.indexOf(n[i])<0&&Object.prototype.propertyIsEnumerable.call(r,n[i])&&(t[n[i]]=r[n[i]]);return t},$ne=new TextEncoder().encode("ic-request-auth-delegation"),Wne=new TextEncoder().encode(`
54
- ic-request`);xu=class{constructor(e,t,n){this.pubkey=e,this.expiration=t,this.targets=n}toCBOR(){return ng.value.map(Object.assign({pubkey:ng.value.bytes(this.pubkey),expiration:ng.value.u64(this.expiration.toString(16),16)},this.targets&&{targets:ng.value.array(this.targets.map(e=>ng.value.bytes(nl(e.toUint8Array()))))}))}toJSON(){return Object.assign({expiration:this.expiration.toString(16),pubkey:zt(this.pubkey)},this.targets&&{targets:this.targets.map(e=>e.toHex())})}};Su=class r{constructor(e,t){this.delegations=e,this.publicKey=t}static async create(e,t,n=new Date(Date.now()+900*1e3),i={}){var s,o;let a=await Vne(e,t,n,i.targets);return new r([...((s=i.previous)===null||s===void 0?void 0:s.delegations)||[],a],((o=i.previous)===null||o===void 0?void 0:o.publicKey)||e.getPublicKey().toDer())}static fromJSON(e){let{publicKey:t,delegations:n}=typeof e=="string"?JSON.parse(e):e;if(!Array.isArray(n))throw new Error("Invalid delegations.");let i=n.map(s=>{let{delegation:o,signature:a}=s,{pubkey:c,expiration:l,targets:u}=o;if(u!==void 0&&!Array.isArray(u))throw new Error("Invalid targets.");return{delegation:new xu(y9(c),BigInt("0x"+l),u&&u.map(h=>{if(typeof h!="string")throw new Error("Invalid target.");return Ve.fromHex(h)})),signature:y9(a)}});return new this(i,y9(t))}static fromDelegations(e,t){return new this(e,t)}toJSON(){return{delegations:this.delegations.map(e=>{let{delegation:t,signature:n}=e,{targets:i}=t;return{delegation:Object.assign({expiration:t.expiration.toString(16),pubkey:zt(t.pubkey)},i&&{targets:i.map(s=>s.toHex())}),signature:zt(n)}}),publicKey:zt(this.publicKey)}}},xc=class extends al{constructor(e,t){super(),this._inner=e,this._delegation=t}static fromDelegation(e,t){return new this(e,t)}getDelegation(){return this._delegation}getPublicKey(){return{derKey:this._delegation.publicKey,toDer:()=>this._delegation.publicKey}}sign(e){return this._inner.sign(e)}async transformRequest(e){let{body:t}=e,n=Fne(e,["body"]),i=await pc(t);return Object.assign(Object.assign({},n),{body:{content:t,sender_sig:await this.sign(nl(new Uint8Array([...Wne,...new Uint8Array(i)]))),sender_delegation:this._delegation.delegations,sender_pubkey:this._delegation.publicKey}})}},ey=class r extends zA{constructor(e,t){super(e),DA.set(this,void 0),qne(this,DA,t,"f")}get delegation(){return Hne(this,DA,"f")}static fromDelegation(e,t){return new r(e,t)}};DA=new WeakMap});var Kne,Nk,Tk=ye(()=>{"use strict";_a();Kne=lc(F2());Mh();(function(r){r[r.ECDSA_WITH_SHA256=-7]="ECDSA_WITH_SHA256"})(Nk||(Nk={}))});var b9=ye(()=>{"use strict";xk();Ck();_k();w9();Tk();_a()});var Ok,ig,v9=ye(()=>{"use strict";Ok=["mousedown","mousemove","keydown","touchstart","wheel"],ig=class{constructor(e={}){var t;this.callbacks=[],this.idleTimeout=600*1e3,this.timeoutID=void 0;let{onIdle:n,idleTimeout:i=600*1e3}=e||{};this.callbacks=n?[n]:[],this.idleTimeout=i;let s=this._resetTimer.bind(this);window.addEventListener("load",s,!0),Ok.forEach(function(a){document.addEventListener(a,s,!0)});let o=(a,c)=>{let l;return(...u)=>{let h=this,p=function(){l=void 0,a.apply(h,u)};clearTimeout(l),l=window.setTimeout(p,c)}};if(e?.captureScroll){let a=o(s,(t=e?.scrollDebounce)!==null&&t!==void 0?t:100);window.addEventListener("scroll",a,!0)}s()}static create(e={}){return new this(e)}registerCallback(e){this.callbacks.push(e)}exit(){clearTimeout(this.timeoutID),window.removeEventListener("load",this._resetTimer,!0);let e=this._resetTimer.bind(this);Ok.forEach(function(t){document.removeEventListener(t,e,!0)}),this.callbacks.forEach(t=>t())}_resetTimer(){let e=this.exit.bind(this);window.clearTimeout(this.timeoutID),this.timeoutID=window.setTimeout(e,this.idleTimeout)}}});function Gne(){return Mk||(Mk=[IDBDatabase,IDBObjectStore,IDBIndex,IDBCursor,IDBTransaction])}function Yne(){return Pk||(Pk=[IDBCursor.prototype.advance,IDBCursor.prototype.continue,IDBCursor.prototype.continuePrimaryKey])}function Zne(r){let e=new Promise((t,n)=>{let i=()=>{r.removeEventListener("success",s),r.removeEventListener("error",o)},s=()=>{t(dl(r.result)),i()},o=()=>{n(r.error),i()};r.addEventListener("success",s),r.addEventListener("error",o)});return e.then(t=>{t instanceof IDBCursor&&Bk.set(t,r)}).catch(()=>{}),S9.set(e,r),e}function Xne(r){if(E9.has(r))return;let e=new Promise((t,n)=>{let i=()=>{r.removeEventListener("complete",s),r.removeEventListener("error",o),r.removeEventListener("abort",o)},s=()=>{t(),i()},o=()=>{n(r.error||new DOMException("AbortError","AbortError")),i()};r.addEventListener("complete",s),r.addEventListener("error",o),r.addEventListener("abort",o)});E9.set(r,e)}function kk(r){x9=r(x9)}function Jne(r){return r===IDBDatabase.prototype.transaction&&!("objectStoreNames"in IDBTransaction.prototype)?function(e,...t){let n=r.call(qA(this),e,...t);return Rk.set(n,e.sort?e.sort():[e]),dl(n)}:Yne().includes(r)?function(...e){return r.apply(qA(this),e),dl(Bk.get(this))}:function(...e){return dl(r.apply(qA(this),e))}}function eie(r){return typeof r=="function"?Jne(r):(r instanceof IDBTransaction&&Xne(r),Qne(r,Gne())?new Proxy(r,x9):r)}function dl(r){if(r instanceof IDBRequest)return Zne(r);if(A9.has(r))return A9.get(r);let e=eie(r);return e!==r&&(A9.set(r,e),S9.set(e,r)),e}var Qne,Mk,Pk,Bk,E9,Rk,A9,S9,x9,qA,C9=ye(()=>{"use strict";Qne=(r,e)=>e.some(t=>r instanceof t);Bk=new WeakMap,E9=new WeakMap,Rk=new WeakMap,A9=new WeakMap,S9=new WeakMap;x9={get(r,e,t){if(r instanceof IDBTransaction){if(e==="done")return E9.get(r);if(e==="objectStoreNames")return r.objectStoreNames||Rk.get(r);if(e==="store")return t.objectStoreNames[1]?void 0:t.objectStore(t.objectStoreNames[0])}return dl(r[e])},set(r,e,t){return r[e]=t,!0},has(r,e){return r instanceof IDBTransaction&&(e==="done"||e==="store")?!0:e in r}};qA=r=>S9.get(r)});function Lk(r,e,{blocked:t,upgrade:n,blocking:i,terminated:s}={}){let o=indexedDB.open(r,e),a=dl(o);return n&&o.addEventListener("upgradeneeded",c=>{n(dl(o.result),c.oldVersion,c.newVersion,dl(o.transaction),c)}),t&&o.addEventListener("blocked",c=>t(c.oldVersion,c.newVersion,c)),a.then(c=>{s&&c.addEventListener("close",()=>s()),i&&c.addEventListener("versionchange",l=>i(l.oldVersion,l.newVersion,l))}).catch(()=>{}),a}function Uk(r,e){if(!(r instanceof IDBDatabase&&!(e in r)&&typeof e=="string"))return;if(I9.get(e))return I9.get(e);let t=e.replace(/FromIndex$/,""),n=e!==t,i=rie.includes(t);if(!(t in(n?IDBIndex:IDBObjectStore).prototype)||!(i||tie.includes(t)))return;let s=async function(o,...a){let c=this.transaction(o,i?"readwrite":"readonly"),l=c.store;return n&&(l=l.index(a.shift())),(await Promise.all([l[t](...a),i&&c.done]))[0]};return I9.set(e,s),s}var tie,rie,I9,jk=ye(()=>{"use strict";C9();C9();tie=["get","getKey","getAll","getAllKeys","count"],rie=["put","add","delete","clear"],I9=new Map;kk(r=>({...r,get:(e,t,n)=>Uk(e,t)||r.get(e,t,n),has:(e,t)=>!!Uk(e,t)||r.has(e,t)}))});async function iie(r,e,t){return await r.get(e,t)}async function sie(r,e,t,n){return await r.put(e,n,t)}async function oie(r,e,t){return await r.delete(e,t)}var zk,Dk,nie,sg,_9=ye(()=>{"use strict";jk();FA();zk="auth-client-db",Dk="ic-keyval",nie=async(r=zk,e=Dk,t)=>(HA&&(localStorage!=null&&localStorage.getItem(Ta))&&(localStorage.removeItem(Ta),localStorage.removeItem(Oa)),await Lk(r,t,{upgrade:n=>{n.objectStoreNames.contains(e)&&n.clear(e),n.createObjectStore(e)}}));sg=class r{constructor(e,t){this._db=e,this._storeName=t}static async create(e){let{dbName:t=zk,storeName:n=Dk,version:i=qk}=e??{},s=await nie(t,n,i);return new r(s,n)}async set(e,t){return await sie(this._db,this._storeName,e,t)}async get(e){var t;return(t=await iie(this._db,this._storeName,e))!==null&&t!==void 0?t:null}async remove(e){return await oie(this._db,this._storeName,e)}}});var aie,cie,$A,Oa,Ta,Hk,qk,HA,og,ag,FA=ye(()=>{"use strict";_9();aie=function(r,e,t,n,i){if(n==="m")throw new TypeError("Private method is not writable");if(n==="a"&&!i)throw new TypeError("Private accessor was defined without a setter");if(typeof e=="function"?r!==e||!i:!e.has(r))throw new TypeError("Cannot write private member to an object whose class did not declare it");return n==="a"?i.call(r,t):i?i.value=t:e.set(r,t),t},cie=function(r,e,t,n){if(t==="a"&&!n)throw new TypeError("Private accessor was defined without a getter");if(typeof e=="function"?r!==e||!n:!e.has(r))throw new TypeError("Cannot read private member from an object whose class did not declare it");return t==="m"?n:t==="a"?n.call(r):n?n.value:e.get(r)},Oa="identity",Ta="delegation",Hk="iv",qk=1,HA=typeof window<"u",og=class{constructor(e="ic-",t){this.prefix=e,this._localStorage=t}get(e){return Promise.resolve(this._getLocalStorage().getItem(this.prefix+e))}set(e,t){return this._getLocalStorage().setItem(this.prefix+e,t),Promise.resolve()}remove(e){return this._getLocalStorage().removeItem(this.prefix+e),Promise.resolve()}_getLocalStorage(){if(this._localStorage)return this._localStorage;let e=typeof window>"u"?typeof global>"u"?typeof self>"u"?void 0:self.localStorage:global.localStorage:window.localStorage;if(!e)throw new Error("Could not find local storage.");return e}},ag=class{constructor(e){$A.set(this,void 0),aie(this,$A,e??{},"f")}get _db(){return new Promise(e=>{if(this.initializedDb){e(this.initializedDb);return}sg.create(cie(this,$A,"f")).then(t=>{this.initializedDb=t,e(t)})})}async get(e){return await(await this._db).get(e)}async set(e,t){await(await this._db).set(e,t)}async remove(e){await(await this._db).remove(e)}};$A=new WeakMap});var $k={};Re($k,{AuthClient:()=>ty,ERROR_USER_INTERRUPT:()=>Fk,IdbKeyVal:()=>sg,IdbStorage:()=>ag,IdleManager:()=>ig,KEY_STORAGE_DELEGATION:()=>Ta,KEY_STORAGE_KEY:()=>Oa,LocalStorage:()=>og});async function O9(r){await r.remove(Oa),await r.remove(Ta),await r.remove(Hk)}var lie,uie,N9,T9,hie,Fk,ty,M9=ye(()=>{"use strict";_a();b9();v9();FA();FA();_9();v9();lie="https://identity.internetcomputer.org",uie="#authorize",N9="ECDSA",T9="Ed25519",hie=500,Fk="UserInterrupt",ty=class{constructor(e,t,n,i,s,o,a,c){this._identity=e,this._key=t,this._chain=n,this._storage=i,this.idleManager=s,this._createOptions=o,this._idpWindow=a,this._eventHandler=c,this._registerDefaultIdleCallback()}static async create(e={}){var t,n,i;let s=(t=e.storage)!==null&&t!==void 0?t:new ag,o=(n=e.keyType)!==null&&n!==void 0?n:N9,a=null;if(e.identity)a=e.identity;else{let h=await s.get(Oa);if(!h&&HA)try{let p=new og,w=await p.get(Ta),y=await p.get(Oa);w&&y&&o===N9&&(console.log("Discovered an identity stored in localstorage. Migrating to IndexedDB"),await s.set(Ta,w),await s.set(Oa,y),h=w,await p.remove(Ta),await p.remove(Oa))}catch(p){console.error("error while attempting to recover localstorage: "+p)}if(h)try{typeof h=="object"?o===T9&&typeof h=="string"?a=await Na.fromJSON(h):a=await Of.fromKeyPair(h):typeof h=="string"&&(a=Na.fromJSON(h))}catch{}}let c=new Aa,l=null;if(a)try{let h=await s.get(Ta);if(typeof h=="object"&&h!==null)throw new Error("Delegation chain is incorrectly stored. A delegation chain should be stored as a string.");e.identity?c=e.identity:h&&(l=Su.fromJSON(h),Ik(l)?"toDer"in a?c=ey.fromDelegation(a,l):c=xc.fromDelegation(a,l):(await O9(s),a=null))}catch(h){console.error(h),await O9(s),a=null}let u;return!((i=e.idleOptions)===null||i===void 0)&&i.disableIdle?u=void 0:(l||e.identity)&&(u=ig.create(e.idleOptions)),a||(o===T9?(a=await Na.generate(),await s.set(Oa,JSON.stringify(a.toJSON()))):(e.storage&&o===N9&&console.warn(`You are using a custom storage provider that may not support CryptoKey storage. If you are using a custom storage provider that does not support CryptoKey storage, you should use '${T9}' as the key type, as it can serialize to a string`),a=await Of.generate(),await s.set(Oa,a.getKeyPair()))),new this(c,a,l,s,u,e)}_registerDefaultIdleCallback(){var e,t;let n=(e=this._createOptions)===null||e===void 0?void 0:e.idleOptions;!n?.onIdle&&!n?.disableDefaultIdleCallback&&((t=this.idleManager)===null||t===void 0||t.registerCallback(()=>{this.logout(),location.reload()}))}async _handleSuccess(e,t){var n,i;let s=e.delegations.map(l=>({delegation:new xu(l.delegation.pubkey,l.delegation.expiration,l.delegation.targets),signature:l.signature.buffer})),o=Su.fromDelegations(s,e.userPublicKey.buffer),a=this._key;if(!a)return;this._chain=o,"toDer"in a?this._identity=ey.fromDelegation(a,this._chain):this._identity=xc.fromDelegation(a,this._chain),(n=this._idpWindow)===null||n===void 0||n.close();let c=(i=this._createOptions)===null||i===void 0?void 0:i.idleOptions;!this.idleManager&&!c?.disableIdle&&(this.idleManager=ig.create(c),this._registerDefaultIdleCallback()),this._removeEventListener(),delete this._idpWindow,this._chain&&await this._storage.set(Ta,JSON.stringify(this._chain.toJSON())),t?.(e)}getIdentity(){return this._identity}async isAuthenticated(){return!this.getIdentity().getPrincipal().isAnonymous()&&this._chain!==null}async login(e){var t,n,i,s;let o=BigInt(8)*BigInt(36e11),a=new URL(((t=e?.identityProvider)===null||t===void 0?void 0:t.toString())||lie);a.hash=uie,(n=this._idpWindow)===null||n===void 0||n.close(),this._removeEventListener(),this._eventHandler=this._getEventHandler(a,Object.assign({maxTimeToLive:(i=e?.maxTimeToLive)!==null&&i!==void 0?i:o},e)),window.addEventListener("message",this._eventHandler),this._idpWindow=(s=window.open(a.toString(),"idpWindow",e?.windowOpenerFeatures))!==null&&s!==void 0?s:void 0;let c=()=>{this._idpWindow&&(this._idpWindow.closed?this._handleFailure(Fk,e?.onError):setTimeout(c,hie))};c()}_getEventHandler(e,t){return async n=>{var i,s,o;if(n.origin!==e.origin)return;let a=n.data;switch(a.kind){case"authorize-ready":{let c=Object.assign({kind:"authorize-client",sessionPublicKey:new Uint8Array((i=this._key)===null||i===void 0?void 0:i.getPublicKey().toDer()),maxTimeToLive:t?.maxTimeToLive,allowPinAuthentication:t?.allowPinAuthentication,derivationOrigin:(s=t?.derivationOrigin)===null||s===void 0?void 0:s.toString()},t?.customValues);(o=this._idpWindow)===null||o===void 0||o.postMessage(c,e.origin);break}case"authorize-client-success":try{await this._handleSuccess(a,t?.onSuccess)}catch(c){this._handleFailure(c.message,t?.onError)}break;case"authorize-client-failure":this._handleFailure(a.text,t?.onError);break;default:break}}}_handleFailure(e,t){var n;(n=this._idpWindow)===null||n===void 0||n.close(),t?.(e),this._removeEventListener(),delete this._idpWindow}_removeEventListener(){this._eventHandler&&window.removeEventListener("message",this._eventHandler),this._eventHandler=void 0}async logout(e={}){if(await O9(this._storage),this._identity=new Aa,this._chain=null,e.returnTo)try{window.history.pushState({},"",e.returnTo)}catch{window.location.href=e.returnTo}}}});var B9=$r(WA=>{"use strict";Object.defineProperty(WA,"__esModule",{value:!0});WA.IcpayWallet=void 0;var die=(M9(),Yd($k)),Wk=(Zi(),Yd(k8)),Ma=ew(),P9=class{constructor(e){this.authClient=null,this.identity=null,this.principal=null,this.connectedProvider=null,this.connectedWallet=null,this.providers=[{id:"internet-identity",name:"Internet Identity",icon:"\u{1F310}",description:"Official Internet Computer identity provider"},{id:"oisy",name:"OISY",icon:"\u{1F510}",description:"OISY wallet for Internet Computer"},{id:"plug",name:"Plug Wallet",icon:"\u{1F50C}",description:"Plug wallet extension"}],e?.connectedWallet&&(this.connectedWallet=e.connectedWallet)}getProviders(){return this.providers}isProviderAvailable(e){if(typeof window>"u")return!1;switch(e){case"internet-identity":return!0;case"oisy":return"oisy"in window;case"plug":return"ic"in window&&window.ic!==void 0&&"plug"in window.ic;default:return!1}}async connectToProvider(e){try{switch(e){case"internet-identity":return await this.connectInternetIdentity();case"oisy":return await this.connectOisy();case"plug":return await this.connectPlug();default:throw(0,Ma.createWalletError)(Ma.ICPAY_ERROR_CODES.UNSUPPORTED_PROVIDER,`Unsupported wallet provider: ${e}`)}}catch(t){throw t instanceof Error&&(t.message.includes("rejected")||t.message.includes("cancelled"))?(0,Ma.createWalletError)(Ma.ICPAY_ERROR_CODES.WALLET_USER_CANCELLED,`Connection to ${e} was cancelled by user`):(0,Ma.createWalletError)(Ma.ICPAY_ERROR_CODES.WALLET_CONNECTION_FAILED,`Failed to connect to ${e}`,t)}}async connectInternetIdentity(){return this.authClient=await die.AuthClient.create(),await this.authClient.isAuthenticated()?(this.identity=this.authClient.getIdentity(),this.principal=this.identity.getPrincipal(),this.connectedProvider="internet-identity"):await new Promise((e,t)=>{this.authClient.login({identityProvider:"https://identity.ic0.app",onSuccess:()=>{this.identity=this.authClient.getIdentity(),this.principal=this.identity.getPrincipal(),this.connectedProvider="internet-identity",e()},onError:n=>{t(new Error(`Authentication failed: ${n||"Unknown error"}`))}})}),{provider:"internet-identity",principal:this.principal.toText(),accountId:this.principal.toText(),connected:!0}}async connectOisy(){if(typeof window>"u"||!window.oisy)throw(0,Ma.createWalletError)(Ma.ICPAY_ERROR_CODES.WALLET_PROVIDER_NOT_AVAILABLE,"OISY wallet is not available");try{let e=await window.oisy.requestConnect();if(e.connected)return this.principal=Wk.Principal.fromText(e.principal),this.connectedProvider="oisy",{provider:"oisy",principal:e.principal,accountId:e.principal,connected:!0};throw(0,Ma.createWalletError)(Ma.ICPAY_ERROR_CODES.WALLET_USER_CANCELLED,"OISY connection was rejected by user")}catch(e){throw new Error(`OISY connection failed: ${e}`)}}async connectPlug(){if(typeof window>"u"||!window.ic?.plug)throw new Error("Plug wallet is not available");try{if(await window.ic.plug.requestConnect()){let t=await window.ic.plug.getPrincipal();return this.principal=Wk.Principal.fromText(t),this.connectedProvider="plug",{provider:"plug",principal:t,accountId:t,connected:!0}}else throw new Error("Plug connection was rejected")}catch(e){throw new Error(`Plug connection failed: ${e}`)}}async showConnectionModal(){let e=this.providers.filter(t=>this.isProviderAvailable(t.id));if(e.length===0)throw new Ma.IcpayError({code:"NO_PROVIDERS_AVAILABLE",message:"No wallet providers are available"});return await this.connectToProvider(e[0].id)}getAccountAddress(){if(!this.principal)throw new Ma.IcpayError({code:"WALLET_NOT_CONNECTED",message:"Wallet is not connected"});return this.principal.toText()}async disconnect(){this.authClient&&await this.authClient.logout(),this.authClient=null,this.identity=null,this.principal=null,this.connectedProvider=null}isConnected(){return this.connectedWallet?this.connectedWallet.owner||this.connectedWallet.principal||typeof this.connectedWallet.getPrincipal=="function"?!0:"connected"in this.connectedWallet?!!this.connectedWallet.connected:this.connectedWallet!==null&&typeof this.connectedWallet=="object":this.identity!==null&&this.principal!==null}getIdentity(){return this.identity}getPrincipal(){return this.principal}getConnectedProvider(){return this.connectedProvider}};WA.IcpayWallet=P9});var Vk={};Re(Vk,{idlFactory:()=>fie,init:()=>pie});var fie,pie,Kk=ye(()=>{"use strict";fie=({IDL:r})=>{let e=r.Record({account_canister_id:r.Nat64,percentage:r.Nat16}),t=r.Record({account_canister_id:r.Nat64,platform_fee_percentage:r.Nat16,subaccount:r.Opt(r.Vec(r.Nat8)),wallet_address:r.Text,icp_account_identifier:r.Opt(r.Text),platform_fee_fixed:r.Opt(r.Nat),is_active:r.Bool,splits:r.Vec(e)}),n=r.Variant({Ok:r.Null,Err:r.Text}),i=r.Variant({Failed:r.Text,Processed:r.Null,Received:r.Null,Completed:r.Null,Pending:r.Null}),s=r.Record({account_canister_id:r.Nat64,index_block:r.Opt(r.Nat64),timestamp:r.Opt(r.Nat64),account_percentage:r.Nat16,amount:r.Nat}),o=r.Record({id:r.Nat,status:i,account_canister_id:r.Nat64,platform_fee_amount:r.Nat,transfer_fee:r.Nat,memo:r.Opt(r.Vec(r.Nat8)),timestamp_to_account:r.Opt(r.Nat64),notify_processing:r.Bool,source_type:r.Nat8,timestamp:r.Nat64,index_received:r.Opt(r.Nat64),sender_principal_id:r.Text,account_amount:r.Nat,ledger_canister_id:r.Text,splits:r.Vec(s),timestamp_received:r.Opt(r.Nat64),amount:r.Nat}),a=r.Record({transactions:r.Vec(o),total_count:r.Nat32,has_more:r.Bool}),c=r.Record({total_accounts:r.Nat32,cycles_balance:r.Nat64,controllers:r.Vec(r.Principal),is_healthy:r.Bool,last_update_timestamp:r.Nat64,active_accounts:r.Nat32,memory_size_bytes:r.Nat64,total_transactions:r.Nat32,platform_wallet:r.Text}),l=r.Record({id:r.Nat,fee:r.Nat,status:i,account_canister_id:r.Nat64,to_principal:r.Text,to_subaccount:r.Opt(r.Vec(r.Nat8)),from_subaccount:r.Vec(r.Nat8),icp_account_identifier:r.Opt(r.Text),notify_processing:r.Opt(r.Bool),timestamp_created:r.Nat64,index:r.Opt(r.Nat64),ledger_canister_id:r.Text,timestamp_completed:r.Opt(r.Nat64),amount:r.Nat,status_message:r.Opt(r.Text)}),u=r.Record({status:i,timestamp_platform_to_account:r.Opt(r.Nat64),account_canister_id:r.Nat64,original_tx_id:r.Nat,notify_processing:r.Bool,timestamp_created:r.Nat64,timestamp_to_sender:r.Opt(r.Nat64),ledger_canister_id:r.Text,amount:r.Nat,platform_refund_amount:r.Nat,index_to_sender:r.Opt(r.Nat64),index_platform_to_account:r.Opt(r.Nat64)}),h=r.Record({status:i,amount:r.Nat}),p=r.Record({from_timestamp:r.Opt(r.Nat64),status:r.Opt(i),account_canister_id:r.Opt(r.Nat64),from_id:r.Opt(r.Nat),offset:r.Opt(r.Nat32),limit:r.Opt(r.Nat32),to_timestamp:r.Opt(r.Nat64),ledger_canister_id:r.Opt(r.Text)}),w=r.Record({utc_offset_minutes:r.Opt(r.Int16),language:r.Text}),y=r.Variant({GenericDisplay:r.Null,LineDisplay:r.Record({characters_per_line:r.Nat16,lines_per_page:r.Nat16})}),v=r.Record({metadata:w,device_spec:r.Opt(y)}),S=r.Record({arg:r.Vec(r.Nat8),method:r.Text,user_preferences:v}),N=r.Record({lines:r.Vec(r.Text)}),O=r.Variant({LineDisplayMessage:r.Record({pages:r.Vec(N)}),GenericDisplayMessage:r.Text}),L=r.Record({metadata:w,consent_message:O}),j=r.Record({description:r.Text}),q=r.Variant({GenericError:r.Record({description:r.Text,error_code:r.Nat64}),InsufficientPayment:j,UnsupportedCanisterCall:j,ConsentMessageUnavailable:j}),D=r.Variant({Ok:L,Err:q}),F=r.Record({account_canister_id:r.Nat64,account:t}),k=r.Record({block_index:r.Nat64,ledger_canister_id:r.Text}),C=r.Record({id:r.Text,status:i,amount:r.Nat}),z=r.Variant({Ok:C,Err:r.Text}),R=r.Variant({Ok:l,Err:r.Text}),g=r.Variant({Ok:r.Nat,Err:r.Text});return r.Service({add_account:r.Func([r.Nat64,t],[n],[]),get_account:r.Func([r.Nat64],[r.Opt(t)],["query"]),get_account_transactions:r.Func([r.Nat64,r.Opt(r.Nat32),r.Opt(r.Nat32)],[a],["query"]),get_canister_info:r.Func([],[c],["query"]),get_controllers:r.Func([],[r.Vec(r.Principal)],["query"]),get_payout:r.Func([r.Nat],[r.Opt(l)],["query"]),get_refund_by_original_tx_id:r.Func([r.Nat],[r.Opt(u)],["query"]),get_transaction:r.Func([r.Nat],[r.Opt(o)],["query"]),get_transaction_status_public:r.Func([r.Nat64,r.Nat,r.Opt(r.Nat64)],[r.Opt(h)],["query"]),get_transactions:r.Func([p],[a],["query"]),icrc21_canister_call_consent_message:r.Func([S],[D],["query"]),initialize_controllers:r.Func([],[n],[]),list_accounts:r.Func([],[r.Vec(F)],["query"]),notify_ledger_transaction:r.Func([k],[z],[]),notify_onramp_icp:r.Func([r.Vec(r.Nat8),r.Vec(r.Nat8)],[z],[]),remove_account:r.Func([r.Nat64],[n],[]),request_payout:r.Func([r.Nat64,r.Text,r.Nat],[R],[]),request_refund:r.Func([r.Nat],[g],[]),retry_payout:r.Func([r.Nat],[R],[]),set_platform_wallet:r.Func([r.Text],[n],[]),update_account:r.Func([r.Nat64,t],[n],[]),update_controllers:r.Func([],[n],[])})},pie=({IDL:r})=>[]});var Qk={};Re(Qk,{idlFactory:()=>gie,init:()=>mie});var gie,mie,Gk=ye(()=>{"use strict";gie=({IDL:r})=>{let e=r.Rec(),t=r.Rec(),n=r.Rec(),i=r.Record({num_blocks_to_archive:r.Opt(r.Nat64),max_transactions_per_response:r.Opt(r.Nat64),trigger_threshold:r.Opt(r.Nat64),more_controller_ids:r.Opt(r.Vec(r.Principal)),max_message_size_bytes:r.Opt(r.Nat64),cycles_for_archive_creation:r.Opt(r.Nat64),node_max_memory_size_bytes:r.Opt(r.Nat64),controller_id:r.Opt(r.Principal)}),s=r.Variant({Int:r.Int,Nat:r.Nat,Blob:r.Vec(r.Nat8),Text:r.Text}),o=r.Vec(r.Nat8),a=r.Record({owner:r.Principal,subaccount:r.Opt(o)}),c=r.Variant({SetTo:a,Unset:r.Null}),l=r.Record({icrc2:r.Bool}),u=r.Record({change_archive_options:r.Opt(i),token_symbol:r.Opt(r.Text),transfer_fee:r.Opt(r.Nat),metadata:r.Opt(r.Vec(r.Tuple(r.Text,s))),change_fee_collector:r.Opt(c),max_memo_length:r.Opt(r.Nat16),index_principal:r.Opt(r.Principal),token_name:r.Opt(r.Text),feature_flags:r.Opt(l)}),h=r.Record({decimals:r.Opt(r.Nat8),token_symbol:r.Text,transfer_fee:r.Nat,metadata:r.Vec(r.Tuple(r.Text,s)),minting_account:a,initial_balances:r.Vec(r.Tuple(a,r.Nat)),fee_collector_account:r.Opt(a),archive_options:r.Record({num_blocks_to_archive:r.Nat64,max_transactions_per_response:r.Opt(r.Nat64),trigger_threshold:r.Nat64,more_controller_ids:r.Opt(r.Vec(r.Principal)),max_message_size_bytes:r.Opt(r.Nat64),cycles_for_archive_creation:r.Opt(r.Nat64),node_max_memory_size_bytes:r.Opt(r.Nat64),controller_id:r.Principal}),max_memo_length:r.Opt(r.Nat16),index_principal:r.Opt(r.Principal),token_name:r.Text,feature_flags:r.Opt(l)}),p=r.Variant({Upgrade:r.Opt(u),Init:h}),w=r.Nat,y=r.Record({block_range_end:w,canister_id:r.Principal,block_range_start:w}),v=r.Record({start:w,length:r.Nat}),S=r.Vec(r.Tuple(r.Text,n));n.fill(r.Variant({Int:r.Int,Map:S,Nat:r.Nat,Nat64:r.Nat64,Blob:r.Vec(r.Nat8),Text:r.Text,Array:r.Vec(n)}));let N=n,O=r.Record({blocks:r.Vec(N)}),L=r.Func([v],[O],["query"]),j=r.Record({certificate:r.Opt(r.Vec(r.Nat8)),first_index:w,blocks:r.Vec(N),chain_length:r.Nat64,archived_blocks:r.Vec(r.Record({callback:L,start:w,length:r.Nat}))}),q=r.Record({certificate:r.Opt(r.Vec(r.Nat8)),hash_tree:r.Vec(r.Nat8)}),D=r.Nat,F=r.Record({start:D,length:r.Nat}),k=r.Nat64,C=r.Record({from:a,memo:r.Opt(r.Vec(r.Nat8)),created_at_time:r.Opt(k),amount:r.Nat,spender:r.Opt(a)}),z=r.Record({to:a,memo:r.Opt(r.Vec(r.Nat8)),created_at_time:r.Opt(k),amount:r.Nat}),R=r.Record({fee:r.Opt(r.Nat),from:a,memo:r.Opt(r.Vec(r.Nat8)),created_at_time:r.Opt(k),amount:r.Nat,expected_allowance:r.Opt(r.Nat),expires_at:r.Opt(k),spender:a}),g=r.Record({to:a,fee:r.Opt(r.Nat),from:a,memo:r.Opt(r.Vec(r.Nat8)),created_at_time:r.Opt(k),amount:r.Nat,spender:r.Opt(a)}),m=r.Record({burn:r.Opt(C),kind:r.Text,mint:r.Opt(z),approve:r.Opt(R),timestamp:k,transfer:r.Opt(g)}),d=r.Record({transactions:r.Vec(m)}),f=r.Func([F],[d],["query"]),b=r.Record({first_index:D,log_length:r.Nat,transactions:r.Vec(m),archived_transactions:r.Vec(r.Record({callback:f,start:D,length:r.Nat}))}),_=r.Record({take:r.Opt(r.Nat),prev_spender:r.Opt(a),from_account:r.Opt(a)}),T=r.Record({from_account:a,to_spender:a,allowance:r.Nat,expires_at:r.Opt(r.Nat64)}),I=r.Variant({GenericError:r.Record({message:r.Text,error_code:r.Nat}),AccessDenied:r.Record({reason:r.Text})}),A=r.Variant({Ok:r.Vec(T),Err:I}),U=r.Variant({GenericError:r.Record({description:r.Text,error_code:r.Nat}),IndexPrincipalNotSet:r.Null}),M=r.Variant({Ok:r.Principal,Err:U}),P=r.Nat,H=r.Record({url:r.Text,name:r.Text}),V=r.Record({to:a,fee:r.Opt(P),memo:r.Opt(r.Vec(r.Nat8)),from_subaccount:r.Opt(o),created_at_time:r.Opt(k),amount:P}),G=r.Variant({GenericError:r.Record({message:r.Text,error_code:r.Nat}),TemporarilyUnavailable:r.Null,BadBurn:r.Record({min_burn_amount:P}),Duplicate:r.Record({duplicate_of:w}),BadFee:r.Record({expected_fee:P}),CreatedInFuture:r.Record({ledger_time:k}),TooOld:r.Null,InsufficientFunds:r.Record({balance:P})}),X=r.Variant({Ok:w,Err:G}),se=r.Record({utc_offset_minutes:r.Opt(r.Int16),language:r.Text}),W=r.Record({metadata:se,device_spec:r.Opt(r.Variant({GenericDisplay:r.Null,LineDisplay:r.Record({characters_per_line:r.Nat16,lines_per_page:r.Nat16})}))}),Q=r.Record({arg:r.Vec(r.Nat8),method:r.Text,user_preferences:W}),Y=r.Variant({LineDisplayMessage:r.Record({pages:r.Vec(r.Record({lines:r.Vec(r.Text)}))}),GenericDisplayMessage:r.Text}),ne=r.Record({metadata:se,consent_message:Y}),J=r.Record({description:r.Text}),re=r.Variant({GenericError:r.Record({description:r.Text,error_code:r.Nat}),InsufficientPayment:J,UnsupportedCanisterCall:J,ConsentMessageUnavailable:J}),oe=r.Variant({Ok:ne,Err:re}),ie=r.Record({account:a,spender:a}),le=r.Record({allowance:r.Nat,expires_at:r.Opt(k)}),de=r.Record({fee:r.Opt(r.Nat),memo:r.Opt(r.Vec(r.Nat8)),from_subaccount:r.Opt(r.Vec(r.Nat8)),created_at_time:r.Opt(k),amount:r.Nat,expected_allowance:r.Opt(r.Nat),expires_at:r.Opt(k),spender:a}),fe=r.Variant({GenericError:r.Record({message:r.Text,error_code:r.Nat}),TemporarilyUnavailable:r.Null,Duplicate:r.Record({duplicate_of:w}),BadFee:r.Record({expected_fee:r.Nat}),AllowanceChanged:r.Record({current_allowance:r.Nat}),CreatedInFuture:r.Record({ledger_time:k}),TooOld:r.Null,Expired:r.Record({ledger_time:k}),InsufficientFunds:r.Record({balance:r.Nat})}),Ee=r.Variant({Ok:w,Err:fe}),xe=r.Record({to:a,fee:r.Opt(P),spender_subaccount:r.Opt(o),from:a,memo:r.Opt(r.Vec(r.Nat8)),created_at_time:r.Opt(k),amount:P}),_e=r.Variant({GenericError:r.Record({message:r.Text,error_code:r.Nat}),TemporarilyUnavailable:r.Null,InsufficientAllowance:r.Record({allowance:P}),BadBurn:r.Record({min_burn_amount:P}),Duplicate:r.Record({duplicate_of:w}),BadFee:r.Record({expected_fee:P}),CreatedInFuture:r.Record({ledger_time:k}),TooOld:r.Null,InsufficientFunds:r.Record({balance:P})}),Qe=r.Variant({Ok:w,Err:_e}),De=r.Record({from:r.Opt(r.Principal)}),Ye=r.Vec(r.Record({end:r.Nat,canister_id:r.Principal,start:r.Nat}));t.fill(r.Variant({Int:r.Int,Map:r.Vec(r.Tuple(r.Text,t)),Nat:r.Nat,Blob:r.Vec(r.Nat8),Text:r.Text,Array:r.Vec(t)})),e.fill(r.Record({log_length:r.Nat,blocks:r.Vec(r.Record({id:r.Nat,block:t})),archived_blocks:r.Vec(r.Record({args:r.Vec(v),callback:r.Func([r.Vec(v)],[e],["query"])}))}));let Ze=r.Record({certificate:r.Vec(r.Nat8),hash_tree:r.Vec(r.Nat8)});return r.Service({archives:r.Func([],[r.Vec(y)],["query"]),get_blocks:r.Func([v],[j],["query"]),get_data_certificate:r.Func([],[q],["query"]),get_transactions:r.Func([F],[b],["query"]),icrc103_get_allowances:r.Func([_],[A],["query"]),icrc106_get_index_principal:r.Func([],[M],["query"]),icrc10_supported_standards:r.Func([],[r.Vec(r.Record({url:r.Text,name:r.Text}))],["query"]),icrc1_balance_of:r.Func([a],[P],["query"]),icrc1_decimals:r.Func([],[r.Nat8],["query"]),icrc1_fee:r.Func([],[P],["query"]),icrc1_metadata:r.Func([],[r.Vec(r.Tuple(r.Text,s))],["query"]),icrc1_minting_account:r.Func([],[r.Opt(a)],["query"]),icrc1_name:r.Func([],[r.Text],["query"]),icrc1_supported_standards:r.Func([],[r.Vec(H)],["query"]),icrc1_symbol:r.Func([],[r.Text],["query"]),icrc1_total_supply:r.Func([],[P],["query"]),icrc1_transfer:r.Func([V],[X],[]),icrc21_canister_call_consent_message:r.Func([Q],[oe],[]),icrc2_allowance:r.Func([ie],[le],["query"]),icrc2_approve:r.Func([de],[Ee],[]),icrc2_transfer_from:r.Func([xe],[Qe],[]),icrc3_get_archives:r.Func([De],[Ye],["query"]),icrc3_get_blocks:r.Func([r.Vec(v)],[e],["query"]),icrc3_get_tip_certificate:r.Func([],[r.Opt(Ze)],["query"]),icrc3_supported_block_types:r.Func([],[r.Vec(r.Record({url:r.Text,block_type:r.Text}))],["query"]),is_ledger_ready:r.Func([],[r.Bool],["query"])})},mie=({IDL:r})=>{let e=r.Record({num_blocks_to_archive:r.Opt(r.Nat64),max_transactions_per_response:r.Opt(r.Nat64),trigger_threshold:r.Opt(r.Nat64),more_controller_ids:r.Opt(r.Vec(r.Principal)),max_message_size_bytes:r.Opt(r.Nat64),cycles_for_archive_creation:r.Opt(r.Nat64),node_max_memory_size_bytes:r.Opt(r.Nat64),controller_id:r.Opt(r.Principal)}),t=r.Variant({Int:r.Int,Nat:r.Nat,Blob:r.Vec(r.Nat8),Text:r.Text}),n=r.Vec(r.Nat8),i=r.Record({owner:r.Principal,subaccount:r.Opt(n)}),s=r.Variant({SetTo:i,Unset:r.Null}),o=r.Record({icrc2:r.Bool}),a=r.Record({change_archive_options:r.Opt(e),token_symbol:r.Opt(r.Text),transfer_fee:r.Opt(r.Nat),metadata:r.Opt(r.Vec(r.Tuple(r.Text,t))),change_fee_collector:r.Opt(s),max_memo_length:r.Opt(r.Nat16),index_principal:r.Opt(r.Principal),token_name:r.Opt(r.Text),feature_flags:r.Opt(o)}),c=r.Record({decimals:r.Opt(r.Nat8),token_symbol:r.Text,transfer_fee:r.Nat,metadata:r.Vec(r.Tuple(r.Text,t)),minting_account:i,initial_balances:r.Vec(r.Tuple(i,r.Nat)),fee_collector_account:r.Opt(i),archive_options:r.Record({num_blocks_to_archive:r.Nat64,max_transactions_per_response:r.Opt(r.Nat64),trigger_threshold:r.Nat64,more_controller_ids:r.Opt(r.Vec(r.Principal)),max_message_size_bytes:r.Opt(r.Nat64),cycles_for_archive_creation:r.Opt(r.Nat64),node_max_memory_size_bytes:r.Opt(r.Nat64),controller_id:r.Principal}),max_memo_length:r.Opt(r.Nat16),index_principal:r.Opt(r.Principal),token_name:r.Text,feature_flags:r.Opt(o)});return[r.Variant({Upgrade:r.Opt(a),Init:c})]}});var Yk=$r(R9=>{"use strict";Object.defineProperty(R9,"__esModule",{value:!0});R9.debugLog=wie;function wie(r,e,t){r&&(t!==void 0?console.log(`[ICPay SDK] ${e}`,t):console.log(`[ICPay SDK] ${e}`))}});var Zk=$r(k9=>{"use strict";Object.defineProperty(k9,"__esModule",{value:!0});k9.createProtectedApi=yie;var cg=ew();function yie(r){let e=r.privateApiClient,t=r.emitStart,n=r.emitSuccess,i=r.emitError,s=o=>{if(!e)throw new cg.IcpayError({code:"SECRET_KEY_REQUIRED",message:`${o} requires secret key authentication. Please provide secretKey in configuration.`})};return{async getPaymentById(o){s("getPaymentById"),t("getPaymentById",{id:o});try{let a=await e.get(`/sdk/payments/${o}`);return n("getPaymentById",{id:o}),a}catch(a){throw i("getPaymentById",a),a}},async listPayments(){s("listPayments"),t("listPayments");try{let o=await e.get("/sdk/payments");return n("listPayments",{count:Array.isArray(o)?o.length:void 0}),o}catch(o){throw i("listPayments",o),o}},async getPaymentIntentById(o){s("getPaymentIntentById"),t("getPaymentIntentById",{id:o});try{let a=await e.get(`/sdk/payment-intents/${o}`);return n("getPaymentIntentById",{id:o}),a}catch(a){throw i("getPaymentIntentById",a),a}},async getInvoiceById(o){s("getInvoiceById"),t("getInvoiceById",{id:o});try{let a=await e.get(`/sdk/invoices/${o}`);return n("getInvoiceById",{id:o}),a}catch(a){throw i("getInvoiceById",a),a}},async getTransactionById(o){s("getTransactionById"),t("getTransactionById",{id:o});try{let a=await e.get(`/sdk/transactions/${o}`);return n("getTransactionById",{id:o}),a}catch(a){throw i("getTransactionById",a),a}},async getWalletById(o){s("getWalletById"),t("getWalletById",{id:o});try{let a=await e.get(`/sdk/wallets/${o}`);return n("getWalletById",{id:o}),a}catch(a){throw i("getWalletById",a),a}},async getVerifiedLedgersPrivate(){s("getVerifiedLedgersPrivate"),t("getVerifiedLedgersPrivate");try{let o=await e.get("/sdk/ledgers/verified");return n("getVerifiedLedgersPrivate",{count:Array.isArray(o)?o.length:void 0}),o}catch(o){throw i("getVerifiedLedgersPrivate",o),o}},async getAllLedgersWithPricesPrivate(){s("getAllLedgersWithPricesPrivate"),t("getAllLedgersWithPricesPrivate");try{let o=await e.get("/sdk/ledgers/all-with-prices");return n("getAllLedgersWithPricesPrivate",{count:Array.isArray(o)?o.length:void 0}),o}catch(o){throw i("getAllLedgersWithPricesPrivate",o),o}},async getLedgerInfoPrivate(o){s("getLedgerInfoPrivate"),t("getLedgerInfoPrivate",{idOrCanisterId:o});try{let a=await e.get(`/sdk/ledgers/${o}`);return n("getLedgerInfoPrivate",{idOrCanisterId:o}),a}catch(a){throw i("getLedgerInfoPrivate",a),a}},async getWebhookEventById(o){s("getWebhookEventById"),t("getWebhookEventById",{id:o});try{let a=await e.get(`/sdk/webhook-events/${o}`);return n("getWebhookEventById",{id:o}),a.data}catch(a){throw i("getWebhookEventById",a),a}},async getDetailedAccountInfo(){s("getDetailedAccountInfo"),t("getDetailedAccountInfo");try{let o=await e.get("/sdk/account"),a={id:o.id,name:o.name,email:o.email,isActive:o.isActive,isLive:o.isLive,accountCanisterId:o.accountCanisterId,walletAddress:o.walletAddress,createdAt:new Date(o.createdAt),updatedAt:new Date(o.updatedAt)};return n("getDetailedAccountInfo",a),a}catch(o){let a=new cg.IcpayError({code:"ACCOUNT_INFO_FETCH_FAILED",message:"Failed to fetch detailed account information",details:o});throw i("getDetailedAccountInfo",a),a}},async getTransactionStatus(o){s("getTransactionStatus"),t("getTransactionStatus",{canisterTransactionId:o});try{let a=await e.get(`/sdk/transactions/${o}/status`);return n("getTransactionStatus",a),a}catch(a){let c=new cg.IcpayError({code:"TRANSACTION_STATUS_FETCH_FAILED",message:"Failed to fetch transaction status",details:a});throw i("getTransactionStatus",c),c}},async getPaymentHistory(o={}){s("getPaymentHistory"),t("getPaymentHistory",{request:o});try{let a=new URLSearchParams;o.accountId&&a.append("accountId",o.accountId),o.ledgerCanisterId&&a.append("ledgerCanisterId",o.ledgerCanisterId),o.fromTimestamp&&a.append("fromTimestamp",o.fromTimestamp.toISOString()),o.toTimestamp&&a.append("toTimestamp",o.toTimestamp.toISOString()),o.status&&a.append("status",o.status),o.limit&&a.append("limit",o.limit.toString()),o.offset&&a.append("offset",o.offset.toString());let c=await e.get(`/sdk/payments/history?${a.toString()}`),l={payments:c.payments.map(u=>({id:u.id,status:u.status,amount:u.amount,ledgerCanisterId:u.ledgerCanisterId,ledgerSymbol:u.ledgerSymbol,fromAddress:u.fromAddress,toAddress:u.toAddress,fee:u.fee,decimals:u.decimals,tokenPrice:u.tokenPrice,expectedSenderPrincipal:u.expectedSenderPrincipal,metadata:u.metadata,createdAt:new Date(u.createdAt),updatedAt:new Date(u.updatedAt)})),total:c.total,limit:c.limit,offset:c.offset,hasMore:c.hasMore};return n("getPaymentHistory",{total:l.total}),l}catch(a){let c=new cg.IcpayError({code:"PAYMENT_HISTORY_FETCH_FAILED",message:"Failed to fetch payment history",details:a});throw i("getPaymentHistory",c),c}},async getPaymentsByPrincipal(o){s("getPaymentsByPrincipal"),t("getPaymentsByPrincipal",{request:o});try{let a=new URLSearchParams;o.limit&&a.append("limit",o.limit.toString()),o.offset&&a.append("offset",o.offset.toString()),o.status&&a.append("status",o.status);let c=await e.get(`/sdk/payments/by-principal/${o.principalId}?${a.toString()}`),l={payments:c.payments.map(u=>({id:u.id,status:u.status,amount:u.amount,ledgerCanisterId:u.ledgerCanisterId,ledgerSymbol:u.ledgerSymbol,fromAddress:u.fromAddress,toAddress:u.toAddress,fee:u.fee,decimals:u.decimals,tokenPrice:u.tokenPrice,expectedSenderPrincipal:u.expectedSenderPrincipal,metadata:u.metadata,createdAt:new Date(u.createdAt),updatedAt:new Date(u.updatedAt)})),total:c.total,limit:c.limit,offset:c.offset,hasMore:c.hasMore};return n("getPaymentsByPrincipal",{total:l.total}),l}catch(a){let c=new cg.IcpayError({code:"PAYMENTS_BY_PRINCIPAL_FETCH_FAILED",message:"Failed to fetch payments by principal",details:a});throw i("getPaymentsByPrincipal",c),c}},async getAccountWalletBalances(){s("getAccountWalletBalances"),t("getAccountWalletBalances");try{let o=await e.get("/sdk/account/wallet-balances"),a={balances:o.balances.map(c=>({ledgerId:c.ledgerId,ledgerName:c.ledgerName,ledgerSymbol:c.ledgerSymbol,canisterId:c.canisterId,balance:c.balance,formattedBalance:c.formattedBalance,decimals:c.decimals,currentPrice:c.currentPrice,lastPriceUpdate:c.lastPriceUpdate?new Date(c.lastPriceUpdate):void 0,lastUpdated:new Date(c.lastUpdated)})),totalBalancesUSD:o.totalBalancesUSD,lastUpdated:new Date(o.lastUpdated)};return n("getAccountWalletBalances",{count:a.balances.length,totalUSD:a.totalBalancesUSD}),a}catch(o){let a=new cg.IcpayError({code:"ACCOUNT_WALLET_BALANCES_FETCH_FAILED",message:"Failed to fetch account wallet balances",details:o});throw i("getAccountWalletBalances",a),a}}}}});var Xk=$r(VA=>{"use strict";Object.defineProperty(VA,"__esModule",{value:!0});VA.HttpClient=void 0;var U9=class{constructor(e){this.baseURL=e.baseURL.replace(/\/$/,""),this.defaultHeaders={"Content-Type":"application/json",...e.headers||{}}}setHeader(e,t){t===void 0?delete this.defaultHeaders[e]:this.defaultHeaders[e]=t}async get(e,t){let n=this.resolve(e),i=await fetch(n,{method:"GET",headers:{...this.defaultHeaders,...t||{}}});return this.handleResponse(i)}async post(e,t,n){let i=this.resolve(e),s=await fetch(i,{method:"POST",headers:{...this.defaultHeaders,...n||{}},body:t===void 0?void 0:JSON.stringify(t)});return this.handleResponse(s)}resolve(e){return/^https?:\/\//i.test(e)?e:`${this.baseURL}${e.startsWith("/")?"":"/"}${e}`}async handleResponse(e){let t=await e.text(),i=(e.headers.get("content-type")||"").includes("application/json")&&t?JSON.parse(t):t;if(!e.ok){let s=new Error(`HTTP ${e.status}: ${e.statusText}`);throw s.status=e.status,s.data=i,s}return i}};VA.HttpClient=U9});var eU=$r(Jk=>{"use strict";Object.defineProperty(Jk,"__esModule",{value:!0})});var j9=$r(eo=>{"use strict";var bie=eo&&eo.__createBinding||(Object.create?(function(r,e,t,n){n===void 0&&(n=t);var i=Object.getOwnPropertyDescriptor(e,t);(!i||("get"in i?!e.__esModule:i.writable||i.configurable))&&(i={enumerable:!0,get:function(){return e[t]}}),Object.defineProperty(r,n,i)}):(function(r,e,t,n){n===void 0&&(n=t),r[n]=e[t]})),iU=eo&&eo.__exportStar||function(r,e){for(var t in r)t!=="default"&&!Object.prototype.hasOwnProperty.call(e,t)&&bie(e,r,t)};Object.defineProperty(eo,"__esModule",{value:!0});eo.IcpayWallet=eo.IcpayError=eo.Icpay=void 0;var Mt=ew(),vie=g8(),Aie=B9(),Hh=(_a(),Yd(Ak)),L9=(Kk(),Yd(Vk)),tU=(Gk(),Yd(Qk)),rU=(Zi(),Yd(k8)),Wr=Yk(),Eie=Zk(),nU=Xk(),KA=class{constructor(e){if(this.privateApiClient=null,this.connectedWallet=null,this.icpayCanisterId=null,this.accountInfoCache=null,this.verifiedLedgersCache={data:null,timestamp:0},this.icpLedgerCanisterId="ryjl3-tyaaa-aaaaa-aaaba-cai",this.config={environment:"production",apiUrl:"https://api.icpay.org",debug:!1,enableEvents:!1,awaitServerNotification:!0,...e},(0,Wr.debugLog)(this.config.debug||!1,"constructor",{config:this.config}),!this.config.publishableKey&&!this.config.secretKey)throw new Error("Either publishableKey or secretKey must be provided");if(this.icHost=e.icHost||"https://ic0.app",this.connectedWallet=e.connectedWallet||null,this.actorProvider=e.actorProvider,(0,Wr.debugLog)(this.config.debug||!1,"constructor",{connectedWallet:this.connectedWallet,actorProvider:this.actorProvider}),this.wallet=new Aie.IcpayWallet({connectedWallet:this.connectedWallet}),this.events=new vie.IcpayEventCenter,(0,Wr.debugLog)(this.config.debug||!1,"constructor",{connectedWallet:this.connectedWallet}),this.publicApiClient=new nU.HttpClient({baseURL:this.config.apiUrl||"https://api.icpay.org",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.config.publishableKey||this.config.secretKey||""}`}}),(0,Wr.debugLog)(this.config.debug||!1,"publicApiClient created",this.publicApiClient),this.config.secretKey){let t={"Content-Type":"application/json",Authorization:`Bearer ${this.config.secretKey||""}`};this.privateApiClient=new nU.HttpClient({baseURL:this.config.apiUrl||"https://api.icpay.org",headers:t})}(0,Wr.debugLog)(this.config.debug||!1,"privateApiClient created",this.privateApiClient),this.protected=(0,Eie.createProtectedApi)({privateApiClient:this.privateApiClient,emitStart:(t,n)=>this.emitMethodStart(t,n),emitSuccess:(t,n)=>this.emitMethodSuccess(t,n),emitError:(t,n)=>this.emitMethodError(t,n)})}on(e,t){return this.events.on(e,t)}off(e,t){this.events.off(e,t)}emit(e,t){this.config.enableEvents&&this.events.emit(e,t)}addEventListener(e,t){this.events.addEventListener(e,t)}removeEventListener(e,t){this.events.removeEventListener(e,t)}dispatchEvent(e){return this.events.dispatchEvent(e)}emitError(e){let t=e instanceof Mt.IcpayError?e:new Mt.IcpayError({code:Mt.ICPAY_ERROR_CODES.UNKNOWN_ERROR,message:e&&(e.message||e.toString())||"Unknown error",details:e});this.config.enableEvents&&this.events.emit("icpay-sdk-error",t)}emitMethodStart(e,t){this.config.enableEvents&&this.events.emit("icpay-sdk-method-start",{name:e,args:t})}emitMethodSuccess(e,t){this.config.enableEvents&&this.events.emit("icpay-sdk-method-success",{name:e,result:t})}emitMethodError(e,t){this.config.enableEvents&&this.events.emit("icpay-sdk-method-error",{name:e,error:t}),this.emitError(t)}hasSecretKey(){return!!this.config.secretKey&&!!this.privateApiClient}requireSecretKey(e){if(!this.hasSecretKey())throw new Mt.IcpayError({code:"SECRET_KEY_REQUIRED",message:`${e} requires secret key authentication. Please provide secretKey and accountId in configuration.`})}async getAccountInfo(){this.emitMethodStart("getAccountInfo");try{let e=await this.publicApiClient.get("/sdk/public/account"),t={id:e.id,name:e.name,isActive:e.isActive,isLive:e.isLive,accountCanisterId:e.accountCanisterId,icpayCanisterId:e.icpayCanisterId,branding:e.branding||null};return this.emitMethodSuccess("getAccountInfo",t),t}catch(e){let t=new Mt.IcpayError({code:"ACCOUNT_INFO_FETCH_FAILED",message:"Failed to fetch account information",details:e});throw this.emitMethodError("getAccountInfo",t),t}}async getVerifiedLedgers(){this.emitMethodStart("getVerifiedLedgers");let e=Date.now(),t=3600*1e3;if(this.verifiedLedgersCache.data&&e-this.verifiedLedgersCache.timestamp<t)return this.verifiedLedgersCache.data;try{let i=(await this.publicApiClient.get("/sdk/public/ledgers/verified")).map(s=>({id:s.id,name:s.name,symbol:s.symbol,canisterId:s.canisterId,decimals:s.decimals,logoUrl:s.logoUrl,verified:s.verified,fee:s.fee,currentPrice:s.currentPrice??null,lastPriceUpdate:s.lastPriceUpdate??null}));return this.verifiedLedgersCache={data:i,timestamp:e},this.emitMethodSuccess("getVerifiedLedgers",{count:i.length}),i}catch(n){let i=new Mt.IcpayError({code:"VERIFIED_LEDGERS_FETCH_FAILED",message:"Failed to fetch verified ledgers",details:n});throw this.emitMethodError("getVerifiedLedgers",i),i}}async getLedgerCanisterIdBySymbol(e){if(this.emitMethodStart("getLedgerCanisterIdBySymbol",{symbol:e}),!e||typeof e!="string")throw new Mt.IcpayError({code:"INVALID_LEDGER_SYMBOL",message:"Symbol must be a non-empty string"});let n=(await this.getVerifiedLedgers()).find(s=>s.symbol.toLowerCase()===e.toLowerCase());if(!n)throw new Mt.IcpayError({code:"LEDGER_SYMBOL_NOT_FOUND",message:`Verified ledger with symbol ${e} not found`});let i=n.canisterId;return this.emitMethodSuccess("getLedgerCanisterIdBySymbol",{symbol:e,canisterId:i}),i}async triggerTransactionSync(e){this.emitMethodStart("triggerTransactionSync",{canisterTransactionId:e});try{let t=await this.publicApiClient.get(`/sdk/public/transactions/${e}/sync`);return this.emitMethodSuccess("triggerTransactionSync",t),t}catch(t){let n=new Mt.IcpayError({code:"TRANSACTION_SYNC_TRIGGER_FAILED",message:"Failed to trigger transaction sync from canister",details:t});throw this.emitMethodError("triggerTransactionSync",n),n}}async fetchAccountInfo(){if(this.accountInfoCache)return this.icpayCanisterId=this.accountInfoCache.icpayCanisterId.toString(),this.accountInfoCache;try{let e=await this.publicApiClient.get("/sdk/public/account");return this.accountInfoCache=e,e&&e.icpayCanisterId&&(this.icpayCanisterId=e.icpayCanisterId.toString()),this.accountInfoCache}catch(e){throw new Mt.IcpayError({code:"ACCOUNT_INFO_FETCH_FAILED",message:"Failed to fetch account information",details:e})}}async showWalletModal(){this.emitMethodStart("showWalletModal");try{let e=await this.wallet.showConnectionModal();return this.emitMethodSuccess("showWalletModal",e),e}catch(e){throw this.emitMethodError("showWalletModal",e),e}}async connectWallet(e){this.emitMethodStart("connectWallet",{providerId:e});try{let t=await this.wallet.connectToProvider(e);return this.emitMethodSuccess("connectWallet",t),t}catch(t){throw this.emitMethodError("connectWallet",t),t}}getWalletProviders(){this.emitMethodStart("getWalletProviders");let e=this.wallet.getProviders();return this.emitMethodSuccess("getWalletProviders",{count:Array.isArray(e)?e.length:void 0}),e}isWalletProviderAvailable(e){this.emitMethodStart("isWalletProviderAvailable",{providerId:e});let t=this.wallet.isProviderAvailable(e);return this.emitMethodSuccess("isWalletProviderAvailable",{providerId:e,available:t}),t}getAccountAddress(){this.emitMethodStart("getAccountAddress");let e=this.wallet.getAccountAddress();return this.emitMethodSuccess("getAccountAddress",{accountAddress:e}),e}async getLedgerBalance(e){this.emitMethodStart("getLedgerBalance",{ledgerCanisterId:e});try{let t=null;if(this.connectedWallet&&(this.connectedWallet.owner?t=this.connectedWallet.owner:this.connectedWallet.principal&&(t=this.connectedWallet.principal)),!t)throw new Error("No principal available for balance check");let n=rU.Principal.fromText(t),i=new Hh.HttpAgent({host:this.icHost}),o=await Hh.Actor.createActor(tU.idlFactory,{agent:i,canisterId:e}).icrc1_balance_of({owner:n,subaccount:[]}),a=BigInt(o);return this.emitMethodSuccess("getLedgerBalance",{ledgerCanisterId:e,balance:a.toString()}),a}catch(t){throw this.emitMethodError("getLedgerBalance",t),t}}createPackedMemo(e,t){let n=BigInt(e>>>0)<<BigInt(32)|BigInt(t>>>0);if(n===BigInt(0))return new Uint8Array([0]);let i=[];for(;n>BigInt(0);)i.push(Number(n&BigInt(255))),n>>=BigInt(8);return new Uint8Array(i)}async sendFunds(e){this.emitMethodStart("sendFunds",{request:{...e,amount:typeof e.amount=="string"?e.amount:String(e.amount)}});try{(0,Wr.debugLog)(this.config.debug||!1,"sendFunds start",{request:e});let t=e.ledgerCanisterId;if(!t&&e.symbol&&(t=await this.getLedgerCanisterIdBySymbol(e.symbol)),!t){let F=new Mt.IcpayError({code:Mt.ICPAY_ERROR_CODES.INVALID_CONFIG,message:"Either ledgerCanisterId or symbol must be provided",details:{request:e}});throw this.emitMethodError("sendFunds",F),F}let n=e.accountCanisterId;if(n||((0,Wr.debugLog)(this.config.debug||!1,"fetching account info for accountCanisterId"),n=(await this.getAccountInfo()).accountCanisterId.toString(),(0,Wr.debugLog)(this.config.debug||!1,"accountCanisterId resolved",{accountCanisterId:n})),this.icpayCanisterId||await this.fetchAccountInfo(),!this.icpayCanisterId)try{let F=await this.getAccountInfo();F?.icpayCanisterId&&(this.icpayCanisterId=F.icpayCanisterId.toString())}catch{}if(!this.icpayCanisterId||typeof this.icpayCanisterId!="string"){let F=new Mt.IcpayError({code:Mt.ICPAY_ERROR_CODES.INVALID_CONFIG,message:"Could not resolve ICPay canister ID from account info",details:{accountInfoCache:this.accountInfoCache}});throw this.emitMethodError("sendFunds",F),F}let i=this.icpayCanisterId,s=this.icHost,o;if(e.onrampPayment===!0||this.config.onrampPayment===!0){if(t!==this.icpLedgerCanisterId){let z=new Mt.IcpayError({code:Mt.ICPAY_ERROR_CODES.INVALID_CONFIG,message:"Onramp is only supported for ICP ledger",details:{provided:t,expected:this.icpLedgerCanisterId}});throw this.emitError(z),z}let F=e.amountUsd;if(F==null)try{let z=await this.calculateTokenAmountFromUSD({usdAmount:1,ledgerCanisterId:t}),R=z.currentPrice,g=(typeof e.amount=="string",Number(e.amount));F=R*(g/Math.pow(10,z.decimals))}catch{}let k=null,C=null;try{(0,Wr.debugLog)(this.config.debug||!1,"creating onramp payment intent");let z=await this.publicApiClient.post("/sdk/public/payments/intents",{amount:e.amount,symbol:e.symbol,ledgerCanisterId:t,metadata:e.metadata||{},onrampPayment:!0,widgetParams:e.widgetParams||{},amountUsd:typeof F=="string"?F:F?.toFixed(2)});k=z?.paymentIntentId||z?.paymentIntent?.id||null,C=z?.paymentIntentCode??null;let R=z?.onramp||{};return{transactionId:0,status:"pending",amount:e.amount,recipientCanister:this.icpayCanisterId,timestamp:new Date,metadata:{paymentIntentId:k,paymentIntentCode:C,onramp:R}}}catch(z){let R=new Mt.IcpayError({code:Mt.ICPAY_ERROR_CODES.API_ERROR,message:"Failed to create onramp payment intent",details:z,retryable:!0,userAction:"Try again"});throw this.emitError(R),R}}let c=typeof e.amount=="string"?e.amount:e.amount!=null?String(e.amount):void 0;if(!c&&e.amountUsd!=null)try{c=(await this.calculateTokenAmountFromUSD({usdAmount:Number(e.amountUsd),ledgerCanisterId:t})).tokenAmountDecimals}catch{}if(!c){let F=new Mt.IcpayError({code:Mt.ICPAY_ERROR_CODES.API_ERROR,message:"Either amount or amountUsd must be provided"});throw this.emitError(F),F}let l=BigInt(c);(0,Wr.debugLog)(this.config.debug||!1,"checking balance",{ledgerCanisterId:t,requiredAmount:l.toString()});let u=(F,k=8,C="")=>{let z=BigInt(10**k),R=F/z,m=(F%z).toString().padStart(k,"0").replace(/0+$/,"");return`${R}${m?"."+m:""} ${C}`.trim()};try{let F=await this.getLedgerBalance(t);if(F<l){let k=u(l,8,"tokens"),C=u(F,8,"tokens");throw(0,Mt.createBalanceError)(k,C,{required:l,available:F,ledgerCanisterId:t})}(0,Wr.debugLog)(this.config.debug||!1,"balance ok",{actualBalance:F.toString()})}catch{throw new Mt.IcpayError({code:"INSUFFICIENT_BALANCE",message:"Insufficient balance",details:{required:l,available:0}})}let h=null,p=null,w=typeof e.amount=="string"?e.amount:e.amount!=null?String(e.amount):void 0;try{(0,Wr.debugLog)(this.config.debug||!1,"creating payment intent");let F=this.connectedWallet?.owner||this.connectedWallet?.principal?.toString();if(!F)throw new Mt.IcpayError({code:Mt.ICPAY_ERROR_CODES.WALLET_NOT_CONNECTED,message:"Wallet must be connected to create payment intent",details:{connectedWallet:this.connectedWallet},retryable:!1,userAction:"Connect your wallet first"});let k=await this.publicApiClient.post("/sdk/public/payments/intents",{amount:e.amount,symbol:e.symbol,ledgerCanisterId:t,expectedSenderPrincipal:F,metadata:e.metadata||{},amountUsd:e.amountUsd});h=k?.paymentIntent?.id||null,p=k?.paymentIntent?.intentCode??null,w=k?.paymentIntent?.amount||w,(0,Wr.debugLog)(this.config.debug||!1,"payment intent created",{paymentIntentId:h,paymentIntentCode:p,expectedSenderPrincipal:F,resolvedAmountStr:w}),h&&this.emit("icpay-sdk-transaction-created",{paymentIntentId:h,amount:w,ledgerCanisterId:t,expectedSenderPrincipal:F})}catch(F){let k=new Mt.IcpayError({code:Mt.ICPAY_ERROR_CODES.API_ERROR,message:"Failed to create payment intent. Please try again.",details:F,retryable:!0,userAction:"Try again"});throw this.emitError(k),k}if(!w){let F=new Mt.IcpayError({code:Mt.ICPAY_ERROR_CODES.API_ERROR,message:"Payment intent did not return amount"});throw this.emitError(F),F}let y=BigInt(w);try{let F=parseInt(n);!isNaN(F)&&p!=null&&(o=this.createPackedMemo(F,Number(p)),(0,Wr.debugLog)(this.config.debug||!1,"built packed memo",{accountCanisterId:F,paymentIntentCode:p})),(0,Wr.debugLog)(this.config.debug||!1,"memo",{memo:o})}catch{}let v;t===this.icpLedgerCanisterId?((0,Wr.debugLog)(this.config.debug||!1,"sending ICRC-1 transfer (ICP)"),v=await this.sendFundsToLedger(t,i,y,o,s)):((0,Wr.debugLog)(this.config.debug||!1,"sending ICRC-1 transfer"),v=await this.sendFundsToLedger(t,i,y,o,s));let S=v?.Ok?.toString()||v?.blockIndex?.toString()||`temp-${Date.now()}`;(0,Wr.debugLog)(this.config.debug||!1,"transfer result",{blockIndex:S});let N,O=null;try{(0,Wr.debugLog)(this.config.debug||!1,"notifying canister about ledger tx");let F=await this.notifyLedgerTransaction(this.icpayCanisterId,t,BigInt(S));typeof F=="string"?N=parseInt(F,10):(N=parseInt(F.id,10),O=F),(0,Wr.debugLog)(this.config.debug||!1,"canister notified",{canisterTransactionId:N})}catch{N=parseInt(S,10),(0,Wr.debugLog)(this.config.debug||!1,"notify failed, using blockIndex as tx id",{canisterTransactionId:N})}let L=null;if(O&&O.status)L={status:O.status};else try{(0,Wr.debugLog)(this.config.debug||!1,"polling transaction status (public)",{canisterTransactionId:N}),L=await this.pollTransactionStatus(this.icpayCanisterId,N,n,Number(S),2e3,30),(0,Wr.debugLog)(this.config.debug||!1,"poll done",{status:L})}catch{L={status:"pending"},(0,Wr.debugLog)(this.config.debug||!1,"poll failed, falling back to pending")}let j="pending";if(L&&typeof L=="object"&&L.status)if(typeof L.status=="object"){let F=Object.keys(L.status);if(F.length>0){let k=F[0].toLowerCase();(k==="completed"||k==="failed")&&(j=k)}}else{let F=L.status;(F==="completed"||F==="failed")&&(j=F)}let q;if(this.config.awaitServerNotification){q=await this.performNotifyPaymentIntent({paymentIntentId:h,canisterTransactionId:N?.toString(),maxAttempts:99999,delayMs:1e3});let F=q?.payment?.status||q?.status;if(typeof F=="string"){let k=F.toLowerCase();k==="completed"||k==="succeeded"?j="completed":k==="failed"||k==="canceled"||k==="cancelled"?j="failed":j="pending"}}else this.performNotifyPaymentIntent({paymentIntentId:h,canisterTransactionId:N?.toString(),maxAttempts:5,delayMs:1e3}).then(F=>{this.emitMethodSuccess("sendFunds.notifyApi",{paymentIntentId:h,canisterTransactionId:N,data:F})}).catch(F=>{this.emitMethodError("sendFunds.notifyApi",F)});let D={transactionId:N,status:j,amount:y.toString(),recipientCanister:t,timestamp:new Date,description:"Fund transfer",metadata:e.metadata,payment:q};if((0,Wr.debugLog)(this.config.debug||!1,"sendFunds done",D),j==="completed"){let F=q?.payment?.requestedAmount||null,k=q?.payment?.paidAmount||null;q?.payment?.status==="mismatched"?(this.emit("icpay-sdk-transaction-mismatched",{...D,requestedAmount:F,paidAmount:k}),this.emit("icpay-sdk-transaction-failed",{...D,code:"MISMATCHED_AMOUNT",message:"Paid amount differs from requested amount",requestedAmount:F,paidAmount:k})):this.emit("icpay-sdk-transaction-completed",D)}else j==="failed"?this.emit("icpay-sdk-transaction-failed",D):this.emit("icpay-sdk-transaction-updated",D);return this.emitMethodSuccess("sendFunds",D),D}catch(t){if(t instanceof Mt.IcpayError)throw this.emitMethodError("sendFunds",t),t;let n=new Mt.IcpayError({code:"TRANSACTION_FAILED",message:"Failed to send funds",details:t});throw this.emitMethodError("sendFunds",n),n}}async disconnectWallet(){return await this.wallet.disconnect()}isWalletConnected(){return this.wallet.isConnected()}getConnectedWalletProvider(){return this.wallet.getConnectedProvider()}async pollTransactionStatus(e,t,n,i,s=2e3,o=30){this.emitMethodStart("pollTransactionStatus",{canisterId:e,transactionId:t,accountCanisterId:n,indexReceived:i,intervalMs:s,maxAttempts:o});for(let c=0;c<o;c++)try{let l=await this.getTransactionStatusPublic(e,t,i,n);if(Array.isArray(l)&&l.length>0){let u=l[0];if(u&&typeof u=="object"&&u.status){let h=u.status;if(this.isTransactionCompleted(h))return u}}if(l&&l.status&&this.isTransactionCompleted(l.status))return this.emitMethodSuccess("pollTransactionStatus",{attempt:c,status:l}),l;if(l&&typeof l=="object"&&(l.Ok||l.Err))return this.emitMethodSuccess("pollTransactionStatus",{attempt:c,status:l}),l;c<o-1&&await new Promise(u=>setTimeout(u,s))}catch(l){c===o-1&&this.emitMethodError("pollTransactionStatus",l),c<o-1&&await new Promise(u=>setTimeout(u,s))}let a=new Error("Transaction status polling timed out");throw this.emitMethodError("pollTransactionStatus",a),a}isTransactionCompleted(e){if(!e)return!1;if(typeof e=="object"){let t=Object.keys(e);if(t.length>0)return t[0].toLowerCase()==="completed"}return typeof e=="string"?e.toLowerCase()==="completed":!1}async notifyLedgerTransaction(e,t,n){this.emitMethodStart("notifyLedgerTransaction",{canisterId:e,ledgerCanisterId:t,blockIndex:n.toString()});let i=new Hh.HttpAgent({host:this.icHost}),o=await Hh.Actor.createActor(L9.idlFactory,{agent:i,canisterId:e}).notify_ledger_transaction({ledger_canister_id:t,block_index:n});if(o&&o.Ok)return this.emitMethodSuccess("notifyLedgerTransaction",{result:o.Ok}),o.Ok;if(o&&o.Err){let a=new Error(o.Err);throw this.emitMethodError("notifyLedgerTransaction",a),a}else{let a=new Error("Unexpected canister notify result");throw this.emitMethodError("notifyLedgerTransaction",a),a}}async getTransactionStatusPublic(e,t,n,i){this.emitMethodStart("getTransactionStatusPublic",{canisterId:e,canisterTransactionId:t,indexReceived:n,accountCanisterId:i});let s=new Hh.HttpAgent({host:this.icHost}),o=Hh.Actor.createActor(L9.idlFactory,{agent:s,canisterId:e}),a=parseInt(i),l=await o.get_transaction_status_public(a,BigInt(t),[n])||{status:"pending"};return this.emitMethodSuccess("getTransactionStatusPublic",l),l}async sendFundsToLedger(e,t,n,i,s){this.emitMethodStart("sendFundsToLedger",{ledgerCanisterId:e,toPrincipal:t,amount:n.toString(),hasMemo:!!i});let o;if(this.actorProvider)o=this.actorProvider(e,tU.idlFactory);else{let c=new Error("actorProvider is required for sending funds");throw this.emitMethodError("sendFundsToLedger",c),c}let a=await o.icrc1_transfer({to:{owner:rU.Principal.fromText(t),subaccount:[]},amount:n,fee:[],memo:i?[i]:[],from_subaccount:[],created_at_time:[]});return this.emitMethodSuccess("sendFundsToLedger",a),a}async getTransactionByFilter(e){this.emitMethodStart("getTransactionByFilter",{transactionId:e});try{this.icpayCanisterId||await this.fetchAccountInfo();let t=new Hh.HttpAgent({host:this.icHost}),n=Hh.Actor.createActor(L9.idlFactory,{agent:t,canisterId:this.icpayCanisterId}),i=BigInt(e),s=await n.get_transactions({account_canister_id:[],ledger_canister_id:[],from_timestamp:[],to_timestamp:[],from_id:[],status:[],limit:[],offset:[]});if(s&&s.transactions){let o=s.transactions.find(a=>a.id.toString()===e.toString());return this.emitMethodSuccess("getTransactionByFilter",{found:!!o}),o}return this.emitMethodSuccess("getTransactionByFilter",{found:!1}),null}catch(t){throw this.emitMethodError("getTransactionByFilter",t),t}}async getAllLedgerBalances(){this.emitMethodStart("getAllLedgerBalances");try{if(!this.isWalletConnected())throw new Mt.IcpayError({code:"WALLET_NOT_CONNECTED",message:"Wallet must be connected to fetch balances"});let e=await this.getVerifiedLedgers(),t=[],n=0;for(let s of e)try{let o=await this.getLedgerBalance(s.canisterId),a=this.formatBalance(o.toString(),s.decimals),c={ledgerId:s.id,ledgerName:s.name,ledgerSymbol:s.symbol,canisterId:s.canisterId,balance:o.toString(),formattedBalance:a,decimals:s.decimals,currentPrice:s.currentPrice||void 0,lastPriceUpdate:s.lastPriceUpdate?new Date(s.lastPriceUpdate):void 0,lastUpdated:new Date};if(t.push(c),s.currentPrice&&o>0){let l=parseFloat(a);n+=l*s.currentPrice}}catch(o){this.emit("icpay-sdk-method-error",{name:"getAllLedgerBalances.getLedgerBalance",error:o,ledgerSymbol:s.symbol,ledgerCanisterId:s.canisterId})}let i={balances:t,totalBalancesUSD:n>0?n:void 0,lastUpdated:new Date};return this.emitMethodSuccess("getAllLedgerBalances",{count:t.length,totalUSD:i.totalBalancesUSD}),i}catch(e){let t=new Mt.IcpayError({code:"BALANCES_FETCH_FAILED",message:"Failed to fetch all ledger balances",details:e});throw this.emitMethodError("getAllLedgerBalances",t),t}}async getSingleLedgerBalance(e){this.emitMethodStart("getSingleLedgerBalance",{ledgerCanisterId:e});try{if(!this.isWalletConnected())throw new Mt.IcpayError({code:"WALLET_NOT_CONNECTED",message:"Wallet must be connected to fetch balance"});let n=(await this.getVerifiedLedgers()).find(a=>a.canisterId===e);if(!n)throw new Mt.IcpayError({code:"LEDGER_NOT_FOUND",message:`Ledger with canister ID ${e} not found or not verified`});let i=await this.getLedgerBalance(e),s=this.formatBalance(i.toString(),n.decimals),o={ledgerId:n.id,ledgerName:n.name,ledgerSymbol:n.symbol,canisterId:n.canisterId,balance:i.toString(),formattedBalance:s,decimals:n.decimals,currentPrice:n.currentPrice||void 0,lastPriceUpdate:n.lastPriceUpdate?new Date(n.lastPriceUpdate):void 0,lastUpdated:new Date};return this.emitMethodSuccess("getSingleLedgerBalance",{ledgerCanisterId:e,balance:o.balance}),o}catch(t){let n=new Mt.IcpayError({code:"SINGLE_BALANCE_FETCH_FAILED",message:`Failed to fetch balance for ledger ${e}`,details:t});throw this.emitMethodError("getSingleLedgerBalance",n),n}}async calculateTokenAmountFromUSD(e){this.emitMethodStart("calculateTokenAmountFromUSD",{usdAmount:e.usdAmount,ledgerCanisterId:e.ledgerCanisterId,ledgerSymbol:e.ledgerSymbol});try{let{usdAmount:t,ledgerCanisterId:n,ledgerSymbol:i}=e;if(t<=0)throw new Mt.IcpayError({code:"INVALID_USD_AMOUNT",message:"USD amount must be greater than 0"});let o=(await this.getVerifiedLedgers()).find(u=>u.canisterId===n||i&&u.symbol===i);if(!o)throw new Mt.IcpayError({code:"LEDGER_NOT_FOUND",message:`Ledger not found for canister ID ${n} or symbol ${i}`});if(!o.currentPrice||o.currentPrice<=0)throw new Mt.IcpayError({code:"PRICE_NOT_AVAILABLE",message:`Current price not available for ledger ${o.symbol}`});let a=t/o.currentPrice,c=Math.floor(a*Math.pow(10,o.decimals)).toString(),l={usdAmount:t,ledgerCanisterId:o.canisterId,ledgerSymbol:o.symbol,ledgerName:o.name,currentPrice:o.currentPrice,priceTimestamp:o.lastPriceUpdate?new Date(o.lastPriceUpdate):new Date,tokenAmountHuman:a.toFixed(o.decimals),tokenAmountDecimals:c,decimals:o.decimals};return this.emitMethodSuccess("calculateTokenAmountFromUSD",{ledgerCanisterId:l.ledgerCanisterId,tokenAmountDecimals:c}),l}catch(t){let n=new Mt.IcpayError({code:"PRICE_CALCULATION_FAILED",message:"Failed to calculate token amount from USD",details:t});throw this.emitMethodError("calculateTokenAmountFromUSD",n),n}}async getLedgerInfo(e){this.emitMethodStart("getLedgerInfo",{ledgerCanisterId:e});try{let t=await this.publicApiClient.get(`/sdk/public/ledgers/${e}`),n={id:t.id,name:t.name,symbol:t.symbol,canisterId:t.canisterId,standard:t.standard,decimals:t.decimals,logoUrl:t.logoUrl??null,verified:t.verified,fee:t.fee??null,network:t.network,description:t.description??null,lastBlockIndex:t.lastBlockIndex??null,coingeckoId:t.coingeckoId??null,currentPrice:t.currentPrice??null,priceFetchMethod:t.priceFetchMethod??null,lastPriceUpdate:t.lastPriceUpdate??null,createdAt:t.createdAt,updatedAt:t.updatedAt};return this.emitMethodSuccess("getLedgerInfo",{ledgerCanisterId:e}),n}catch(t){let n=new Mt.IcpayError({code:"LEDGER_INFO_FETCH_FAILED",message:`Failed to fetch ledger info for ${e}`,details:t});throw this.emitMethodError("getLedgerInfo",n),n}}async sendFundsUsd(e){this.emitMethodStart("sendFundsUsd",{request:e});try{let t=typeof e.usdAmount=="string"?parseFloat(e.usdAmount):e.usdAmount,n=e.ledgerCanisterId;if(!n&&e.symbol&&(n=await this.getLedgerCanisterIdBySymbol(e.symbol)),!n){let o=new Mt.IcpayError({code:Mt.ICPAY_ERROR_CODES.INVALID_CONFIG,message:"Either ledgerCanisterId or symbol must be provided",details:{request:e}});throw this.emitMethodError("sendFundsUsd",o),o}let i={ledgerCanisterId:n,symbol:e.symbol,amountUsd:t,accountCanisterId:e.accountCanisterId,metadata:e.metadata,onrampPayment:e.onrampPayment,widgetParams:e.widgetParams},s=await this.sendFunds(i);return this.emitMethodSuccess("sendFundsUsd",s),s}catch(t){if(t instanceof Mt.IcpayError)throw this.emitMethodError("sendFundsUsd",t),t;let n=new Mt.IcpayError({code:"SEND_FUNDS_USD_FAILED",message:"Failed to send funds from USD",details:t});throw this.emitMethodError("sendFundsUsd",n),n}}notifyPaymentIntentOnRamp(e){let t=e.paymentIntentId,n=Math.max(1e3,e.intervalMs??5e3),i=e.orderId,s=null,o=null;try{this.emitMethodSuccess("notifyLedgerTransaction",{paymentIntentId:t})}catch{}let a=async()=>{let l=(await this.performNotifyPaymentIntent({paymentIntentId:t,orderId:i}))?.payment?.status||"";l&&l!==o&&(o=l,l==="completed"||l==="succeeded"?this.dispatchEvent(new CustomEvent("icpay-sdk-transaction-completed",{detail:{id:t,status:l}})):this.dispatchEvent(new CustomEvent("icpay-sdk-transaction-updated",{detail:{id:t,status:l}})))};return a().catch(()=>{}),s=setInterval(a,n),{stop:()=>{s&&(clearInterval(s),s=null)}}}async performNotifyPaymentIntent(e){let t=this.publicApiClient,n="/sdk/public/payments/notify",i=e.maxAttempts??1,s=e.delayMs??0;for(let o=1;o<=i;o++)try{(0,Wr.debugLog)(this.config.debug||!1,"notify payment intent",{attempt:o,notifyPath:n,paymentIntentId:e.paymentIntentId,canisterTxId:e.canisterTransactionId});let a={paymentIntentId:e.paymentIntentId};e.canisterTransactionId&&(a.canisterTxId=e.canisterTransactionId),e.orderId&&(a.orderId=e.orderId);let c=await t.post(n,a);if(o===i)return c;let l=c?.payment?.status||c?.status||"";if(typeof l=="string"){let u=l.toLowerCase();if(u==="completed"||u==="succeeded")return c}s>0&&await new Promise(u=>setTimeout(u,s))}catch(a){let c=a?.response?.status,l=a?.response?.data;(0,Wr.debugLog)(this.config.debug||!1,"notify payment intent error",{attempt:o,status:c,data:l}),o<i&&s>0&&await new Promise(u=>setTimeout(u,s))}}async getAllLedgersWithPrices(){this.emitMethodStart("getAllLedgersWithPrices");try{let t=(await this.publicApiClient.get("/sdk/public/ledgers/all-with-prices")).map(n=>({id:n.id,name:n.name,symbol:n.symbol,canisterId:n.canisterId,standard:n.standard,decimals:n.decimals,logoUrl:n.logoUrl??null,verified:n.verified,fee:n.fee??null,network:n.network,description:n.description??null,lastBlockIndex:n.lastBlockIndex??null,coingeckoId:n.coingeckoId??null,currentPrice:n.currentPrice??null,priceFetchMethod:n.priceFetchMethod??null,lastPriceUpdate:n.lastPriceUpdate??null,createdAt:n.createdAt,updatedAt:n.updatedAt}));return this.emitMethodSuccess("getAllLedgersWithPrices",{count:t.length}),t}catch(e){let t=new Mt.IcpayError({code:"LEDGERS_WITH_PRICES_FETCH_FAILED",message:"Failed to fetch ledgers with price information",details:e});throw this.emitMethodError("getAllLedgersWithPrices",t),t}}formatBalance(e,t){let n=parseFloat(e),i=Math.pow(10,t),s=Math.floor(n/i),a=(n%i).toString().padStart(t,"0").replace(/0+$/,"");return`${s}${a?"."+a:""}`}};eo.Icpay=KA;iU(eU(),eo);var xie=ew();Object.defineProperty(eo,"IcpayError",{enumerable:!0,get:function(){return xie.IcpayError}});var Sie=B9();Object.defineProperty(eo,"IcpayWallet",{enumerable:!0,get:function(){return Sie.IcpayWallet}});iU(g8(),eo);eo.default=KA});var Bie,m$e,aU,cU,lU,oU,ry,Rie,kie,uU,hU=ye(()=>{"use strict";_a();_a();Zi();Bie=(r=>(r[r.FractionalMoreThan8Decimals=0]="FractionalMoreThan8Decimals",r[r.InvalidFormat=1]="InvalidFormat",r[r.FractionalTooManyDecimals=2]="FractionalTooManyDecimals",r))(Bie||{}),m$e=BigInt(1e8),aU=r=>new Uint8Array(r),cU=r=>Array.from(r).map(e=>e.charCodeAt(0)),lU=r=>(r instanceof Uint8Array||(r=Uint8Array.from(r)),r.reduce((e,t)=>e+t.toString(16).padStart(2,"0"),"")),oU="abcdefghijklmnopqrstuvwxyz234567",ry=Object.create(null);for(let r=0;r<oU.length;r++)ry[oU[r]]=r;ry[0]=ry.o;ry[1]=ry.i;Rie=new Uint32Array([0,1996959894,3993919788,2567524794,124634137,1886057615,3915621685,2657392035,249268274,2044508324,3772115230,2547177864,162941995,2125561021,3887607047,2428444049,498536548,1789927666,4089016648,2227061214,450548861,1843258603,4107580753,2211677639,325883990,1684777152,4251122042,2321926636,335633487,1661365465,4195302755,2366115317,997073096,1281953886,3579855332,2724688242,1006888145,1258607687,3524101629,2768942443,901097722,1119000684,3686517206,2898065728,853044451,1172266101,3705015759,2882616665,651767980,1373503546,3369554304,3218104598,565507253,1454621731,3485111705,3099436303,671266974,1594198024,3322730930,2970347812,795835527,1483230225,3244367275,3060149565,1994146192,31158534,2563907772,4023717930,1907459465,112637215,2680153253,3904427059,2013776290,251722036,2517215374,3775830040,2137656763,141376813,2439277719,3865271297,1802195444,476864866,2238001368,4066508878,1812370925,453092731,2181625025,4111451223,1706088902,314042704,2344532202,4240017532,1658658271,366619977,2362670323,4224994405,1303535960,984961486,2747007092,3569037538,1256170817,1037604311,2765210733,3554079995,1131014506,879679996,2909243462,3663771856,1141124467,855842277,2852801631,3708648649,1342533948,654459306,3188396048,3373015174,1466479909,544179635,3110523913,3462522015,1591671054,702138776,2966460450,3352799412,1504918807,783551873,3082640443,3233442989,3988292384,2596254646,62317068,1957810842,3939845945,2647816111,81470997,1943803523,3814918930,2489596804,225274430,2053790376,3826175755,2466906013,167816743,2097651377,4027552580,2265490386,503444072,1762050814,4150417245,2154129355,426522225,1852507879,4275313526,2312317920,282753626,1742555852,4189708143,2394877945,397917763,1622183637,3604390888,2714866558,953729732,1340076626,3518719985,2797360999,1068828381,1219638859,3624741850,2936675148,906185462,1090812512,3747672003,2825379669,829329135,1181335161,3412177804,3160834842,628085408,1382605366,3423369109,3138078467,570562233,1426400815,3317316542,2998733608,733239954,1555261956,3268935591,3050360625,752459403,1541320221,2607071920,3965973030,1969922972,40735498,2617837225,3943577151,1913087877,83908371,2512341634,3803740692,2075208622,213261112,2463272603,3855990285,2094854071,198958881,2262029012,4057260610,1759359992,534414190,2176718541,4139329115,1873836001,414664567,2282248934,4279200368,1711684554,285281116,2405801727,4167216745,1634467795,376229701,2685067896,3608007406,1308918612,956543938,2808555105,3495958263,1231636301,1047427035,2932959818,3654703836,1088359270,936918e3,2847714899,3736837829,1202900863,817233897,3183342108,3401237130,1404277552,615818150,3134207493,3453421203,1423857449,601450431,3009837614,3294710456,1567103746,711928724,3020668471,3272380065,1510334235,755167117]),kie=r=>{let e=-1;for(let t=0;t<r.length;t++){let n=(r[t]^e)&255;e=Rie[n]^e>>>8}return(e^-1)>>>0},uU=r=>{let e=new ArrayBuffer(4);return new DataView(e).setUint32(0,kie(r),!1),new Uint8Array(e)}});function Lie(){if(!GA&&(GA=typeof crypto<"u"&&crypto.getRandomValues&&crypto.getRandomValues.bind(crypto),!GA))throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");return GA(Uie)}function jie(r,e=0){return es[r[e+0]]+es[r[e+1]]+es[r[e+2]]+es[r[e+3]]+"-"+es[r[e+4]]+es[r[e+5]]+"-"+es[r[e+6]]+es[r[e+7]]+"-"+es[r[e+8]]+es[r[e+9]]+"-"+es[r[e+10]]+es[r[e+11]]+es[r[e+12]]+es[r[e+13]]+es[r[e+14]]+es[r[e+15]]}function YA(r,e,t){if(dU.randomUUID&&!r)return dU.randomUUID();r=r||{};let n=r.random||(r.rng||Lie)();return n[6]=n[6]&15|64,n[8]=n[8]&63|128,jie(n)}var GA,Uie,es,zie,dU,H9=ye(()=>{"use strict";Uie=new Uint8Array(16);es=[];for(let r=0;r<256;++r)es.push((r+256).toString(16).slice(1));zie=typeof crypto<"u"&&crypto.randomUUID&&crypto.randomUUID.bind(crypto),dU={randomUUID:zie}});var wU={};Re(wU,{StandardSolflareMetaMaskWalletAccount:()=>n4,default:()=>i4});function Die(){if(fU)return F9;fU=1;function r(e){if(e.length>=255)throw new TypeError("Alphabet too long");for(var t=new Uint8Array(256),n=0;n<t.length;n++)t[n]=255;for(var i=0;i<e.length;i++){var s=e.charAt(i),o=s.charCodeAt(0);if(t[o]!==255)throw new TypeError(s+" is ambiguous");t[o]=i}var a=e.length,c=e.charAt(0),l=Math.log(a)/Math.log(256),u=Math.log(256)/Math.log(a);function h(y){if(y instanceof Uint8Array||(ArrayBuffer.isView(y)?y=new Uint8Array(y.buffer,y.byteOffset,y.byteLength):Array.isArray(y)&&(y=Uint8Array.from(y))),!(y instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(y.length===0)return"";for(var v=0,S=0,N=0,O=y.length;N!==O&&y[N]===0;)N++,v++;for(var L=(O-N)*u+1>>>0,j=new Uint8Array(L);N!==O;){for(var q=y[N],D=0,F=L-1;(q!==0||D<S)&&F!==-1;F--,D++)q+=256*j[F]>>>0,j[F]=q%a>>>0,q=q/a>>>0;if(q!==0)throw new Error("Non-zero carry");S=D,N++}for(var k=L-S;k!==L&&j[k]===0;)k++;for(var C=c.repeat(v);k<L;++k)C+=e.charAt(j[k]);return C}function p(y){if(typeof y!="string")throw new TypeError("Expected String");if(y.length===0)return new Uint8Array;for(var v=0,S=0,N=0;y[v]===c;)S++,v++;for(var O=(y.length-v)*l+1>>>0,L=new Uint8Array(O);y[v];){var j=y.charCodeAt(v);if(j>255)return;var q=t[j];if(q===255)return;for(var D=0,F=O-1;(q!==0||D<N)&&F!==-1;F--,D++)q+=a*L[F]>>>0,L[F]=q%256>>>0,q=q/256>>>0;if(q!==0)throw new Error("Non-zero carry");N=D,v++}for(var k=O-N;k!==O&&L[k]===0;)k++;for(var C=new Uint8Array(S+(O-k)),z=S;k!==O;)C[z++]=L[k++];return C}function w(y){var v=p(y);if(v)return v;throw new Error("Non-base"+a+" character")}return{encode:h,decodeUnsafe:p,decode:w}}return F9=r,F9}function qie(){return pU||(pU=1,$9=Die()("123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz")),$9}function Q9(r){return r.version===void 0}function W9(r){return Q9(r)?r.serialize({verifySignatures:!1,requireAllSignatures:!1}):r.serialize()}function V9(r){return gU(this,void 0,void 0,function*(){try{return yield r.request({method:"wallet_getSnaps"}),!0}catch{return!1}})}function Fie(){return gU(this,void 0,void 0,function*(){try{let r=window.ethereum;if(!r)return null;if(r.providers&&Array.isArray(r.providers)){let e=r.providers;for(let t of e)if(yield V9(t))return t}if(r.detected&&Array.isArray(r.detected)){let e=r.detected;for(let t of e)if(yield V9(t))return t}return(yield V9(r))?r:null}catch(r){return console.error(r),null}})}function K9(r){return mU.includes(r)}var F9,fU,$9,pU,Hie,fl,gU,$ie,Wie,Vie,Kie,mU,lg,ug,ZA,XA,JA,e4,t4,r4,Qie,Gie,n4,Sc,i4,yU=ye(()=>{"use strict";hg();H9();Hie=qie(),fl=co(Hie);gU=function(r,e,t,n){function i(s){return s instanceof t?s:new t(function(o){o(s)})}return new(t||(t=Promise))(function(s,o){function a(u){try{l(n.next(u))}catch(h){o(h)}}function c(u){try{l(n.throw(u))}catch(h){o(h)}}function l(u){u.done?s(u.value):i(u.value).then(a,c)}l((n=n.apply(r,e||[])).next())})};$ie="solana:mainnet",Wie="solana:devnet",Vie="solana:testnet",Kie="solana:localnet",mU=[$ie,Wie,Vie,Kie];lg=function(r,e,t,n){if(t==="a"&&!n)throw new TypeError("Private accessor was defined without a getter");if(typeof e=="function"?r!==e||!n:!e.has(r))throw new TypeError("Cannot read private member from an object whose class did not declare it");return t==="m"?n:t==="a"?n.call(r):n?n.value:e.get(r)},ug=function(r,e,t,n,i){if(n==="m")throw new TypeError("Private method is not writable");if(n==="a"&&!i)throw new TypeError("Private accessor was defined without a setter");if(typeof e=="function"?r!==e||!i:!e.has(r))throw new TypeError("Cannot write private member to an object whose class did not declare it");return n==="a"?i.call(r,t):i?i.value=t:e.set(r,t),t},Qie=mU,Gie=[G9,Z9,Y9],n4=class r{get address(){return lg(this,ZA,"f")}get publicKey(){return lg(this,XA,"f").slice()}get chains(){return lg(this,JA,"f").slice()}get features(){return lg(this,e4,"f").slice()}get label(){return lg(this,t4,"f")}get icon(){return lg(this,r4,"f")}constructor({address:e,publicKey:t,label:n,icon:i}){ZA.set(this,void 0),XA.set(this,void 0),JA.set(this,void 0),e4.set(this,void 0),t4.set(this,void 0),r4.set(this,void 0),new.target===r&&Object.freeze(this),ug(this,ZA,e,"f"),ug(this,XA,t,"f"),ug(this,JA,Qie,"f"),ug(this,e4,Gie,"f"),ug(this,t4,n,"f"),ug(this,r4,i,"f")}};ZA=new WeakMap,XA=new WeakMap,JA=new WeakMap,e4=new WeakMap,t4=new WeakMap,r4=new WeakMap;Sc=function(r,e,t,n){function i(s){return s instanceof t?s:new t(function(o){o(s)})}return new(t||(t=Promise))(function(s,o){function a(u){try{l(n.next(u))}catch(h){o(h)}}function c(u){try{l(n.throw(u))}catch(h){o(h)}}function l(u){u.done?s(u.value):i(u.value).then(a,c)}l((n=n.apply(r,e||[])).next())})},i4=class r extends Cu{constructor(e){super(),this._network="mainnet-beta",this._iframeParams={},this._element=null,this._iframe=null,this._publicKey=null,this._account=null,this._isConnected=!1,this._connectHandler=null,this._messageHandlers={},this._handleEvent=t=>{var n,i;switch(t.type){case"connect":{this._collapseIframe(),!((n=t.data)===null||n===void 0)&&n.publicKey?(this._publicKey=t.data.publicKey,this._isConnected=!0,this._connectHandler&&(this._connectHandler.resolve(),this._connectHandler=null),this._connected()):(this._connectHandler&&(this._connectHandler.reject(),this._connectHandler=null),this._disconnected());return}case"disconnect":{this._connectHandler&&(this._connectHandler.reject(),this._connectHandler=null),this._disconnected();return}case"accountChanged":{!((i=t.data)===null||i===void 0)&&i.publicKey?(this._publicKey=t.data.publicKey,this.emit("accountChanged",this.publicKey),this._standardConnected()):(this.emit("accountChanged",void 0),this._standardDisconnected());return}default:return}},this._handleResize=t=>{t.resizeMode==="full"?t.params.mode==="fullscreen"?this._expandIframe():t.params.mode==="hide"&&this._collapseIframe():t.resizeMode==="coordinates"&&this._resizeIframe(t.params)},this._handleMessage=t=>{var n;if(((n=t.data)===null||n===void 0?void 0:n.channel)!=="solflareIframeToWalletAdapter")return;let i=t.data.data||{};if(i.type==="event")this._handleEvent(i.event);else if(i.type==="resize")this._handleResize(i);else if(i.type==="response"&&this._messageHandlers[i.id]){let{resolve:s,reject:o}=this._messageHandlers[i.id];delete this._messageHandlers[i.id],i.error?o(i.error):s(i.result)}},this._removeElement=()=>{this._element&&(this._element.remove(),this._element=null)},this._removeDanglingElements=()=>{let t=document.getElementsByClassName("solflare-metamask-wallet-adapter-iframe");for(let n of t)n.parentElement&&n.remove()},this._injectElement=()=>{this._removeElement(),this._removeDanglingElements();let t=Object.assign(Object.assign({},this._iframeParams),{mm:!0,v:1,cluster:this._network||"mainnet-beta",origin:window.location.origin||"",title:document.title||""}),n=Object.keys(t).map(s=>`${s}=${encodeURIComponent(t[s])}`).join("&"),i=`${r.IFRAME_URL}?${n}`;this._element=document.createElement("div"),this._element.className="solflare-metamask-wallet-adapter-iframe",this._element.innerHTML=`
54
+ ic-request`);xu=class{constructor(e,t,n){this.pubkey=e,this.expiration=t,this.targets=n}toCBOR(){return ng.value.map(Object.assign({pubkey:ng.value.bytes(this.pubkey),expiration:ng.value.u64(this.expiration.toString(16),16)},this.targets&&{targets:ng.value.array(this.targets.map(e=>ng.value.bytes(nl(e.toUint8Array()))))}))}toJSON(){return Object.assign({expiration:this.expiration.toString(16),pubkey:zt(this.pubkey)},this.targets&&{targets:this.targets.map(e=>e.toHex())})}};Su=class r{constructor(e,t){this.delegations=e,this.publicKey=t}static async create(e,t,n=new Date(Date.now()+900*1e3),i={}){var s,o;let a=await Vne(e,t,n,i.targets);return new r([...((s=i.previous)===null||s===void 0?void 0:s.delegations)||[],a],((o=i.previous)===null||o===void 0?void 0:o.publicKey)||e.getPublicKey().toDer())}static fromJSON(e){let{publicKey:t,delegations:n}=typeof e=="string"?JSON.parse(e):e;if(!Array.isArray(n))throw new Error("Invalid delegations.");let i=n.map(s=>{let{delegation:o,signature:a}=s,{pubkey:c,expiration:l,targets:u}=o;if(u!==void 0&&!Array.isArray(u))throw new Error("Invalid targets.");return{delegation:new xu(y9(c),BigInt("0x"+l),u&&u.map(h=>{if(typeof h!="string")throw new Error("Invalid target.");return Ve.fromHex(h)})),signature:y9(a)}});return new this(i,y9(t))}static fromDelegations(e,t){return new this(e,t)}toJSON(){return{delegations:this.delegations.map(e=>{let{delegation:t,signature:n}=e,{targets:i}=t;return{delegation:Object.assign({expiration:t.expiration.toString(16),pubkey:zt(t.pubkey)},i&&{targets:i.map(s=>s.toHex())}),signature:zt(n)}}),publicKey:zt(this.publicKey)}}},xc=class extends al{constructor(e,t){super(),this._inner=e,this._delegation=t}static fromDelegation(e,t){return new this(e,t)}getDelegation(){return this._delegation}getPublicKey(){return{derKey:this._delegation.publicKey,toDer:()=>this._delegation.publicKey}}sign(e){return this._inner.sign(e)}async transformRequest(e){let{body:t}=e,n=Fne(e,["body"]),i=await pc(t);return Object.assign(Object.assign({},n),{body:{content:t,sender_sig:await this.sign(nl(new Uint8Array([...Wne,...new Uint8Array(i)]))),sender_delegation:this._delegation.delegations,sender_pubkey:this._delegation.publicKey}})}},ey=class r extends zA{constructor(e,t){super(e),DA.set(this,void 0),qne(this,DA,t,"f")}get delegation(){return Hne(this,DA,"f")}static fromDelegation(e,t){return new r(e,t)}};DA=new WeakMap});var Kne,Nk,Tk=ye(()=>{"use strict";_a();Kne=lc(F2());Mh();(function(r){r[r.ECDSA_WITH_SHA256=-7]="ECDSA_WITH_SHA256"})(Nk||(Nk={}))});var b9=ye(()=>{"use strict";xk();Ck();_k();w9();Tk();_a()});var Ok,ig,v9=ye(()=>{"use strict";Ok=["mousedown","mousemove","keydown","touchstart","wheel"],ig=class{constructor(e={}){var t;this.callbacks=[],this.idleTimeout=600*1e3,this.timeoutID=void 0;let{onIdle:n,idleTimeout:i=600*1e3}=e||{};this.callbacks=n?[n]:[],this.idleTimeout=i;let s=this._resetTimer.bind(this);window.addEventListener("load",s,!0),Ok.forEach(function(a){document.addEventListener(a,s,!0)});let o=(a,c)=>{let l;return(...u)=>{let h=this,p=function(){l=void 0,a.apply(h,u)};clearTimeout(l),l=window.setTimeout(p,c)}};if(e?.captureScroll){let a=o(s,(t=e?.scrollDebounce)!==null&&t!==void 0?t:100);window.addEventListener("scroll",a,!0)}s()}static create(e={}){return new this(e)}registerCallback(e){this.callbacks.push(e)}exit(){clearTimeout(this.timeoutID),window.removeEventListener("load",this._resetTimer,!0);let e=this._resetTimer.bind(this);Ok.forEach(function(t){document.removeEventListener(t,e,!0)}),this.callbacks.forEach(t=>t())}_resetTimer(){let e=this.exit.bind(this);window.clearTimeout(this.timeoutID),this.timeoutID=window.setTimeout(e,this.idleTimeout)}}});function Gne(){return Mk||(Mk=[IDBDatabase,IDBObjectStore,IDBIndex,IDBCursor,IDBTransaction])}function Yne(){return Pk||(Pk=[IDBCursor.prototype.advance,IDBCursor.prototype.continue,IDBCursor.prototype.continuePrimaryKey])}function Zne(r){let e=new Promise((t,n)=>{let i=()=>{r.removeEventListener("success",s),r.removeEventListener("error",o)},s=()=>{t(dl(r.result)),i()},o=()=>{n(r.error),i()};r.addEventListener("success",s),r.addEventListener("error",o)});return e.then(t=>{t instanceof IDBCursor&&Bk.set(t,r)}).catch(()=>{}),S9.set(e,r),e}function Xne(r){if(E9.has(r))return;let e=new Promise((t,n)=>{let i=()=>{r.removeEventListener("complete",s),r.removeEventListener("error",o),r.removeEventListener("abort",o)},s=()=>{t(),i()},o=()=>{n(r.error||new DOMException("AbortError","AbortError")),i()};r.addEventListener("complete",s),r.addEventListener("error",o),r.addEventListener("abort",o)});E9.set(r,e)}function kk(r){x9=r(x9)}function Jne(r){return r===IDBDatabase.prototype.transaction&&!("objectStoreNames"in IDBTransaction.prototype)?function(e,...t){let n=r.call(qA(this),e,...t);return Rk.set(n,e.sort?e.sort():[e]),dl(n)}:Yne().includes(r)?function(...e){return r.apply(qA(this),e),dl(Bk.get(this))}:function(...e){return dl(r.apply(qA(this),e))}}function eie(r){return typeof r=="function"?Jne(r):(r instanceof IDBTransaction&&Xne(r),Qne(r,Gne())?new Proxy(r,x9):r)}function dl(r){if(r instanceof IDBRequest)return Zne(r);if(A9.has(r))return A9.get(r);let e=eie(r);return e!==r&&(A9.set(r,e),S9.set(e,r)),e}var Qne,Mk,Pk,Bk,E9,Rk,A9,S9,x9,qA,C9=ye(()=>{"use strict";Qne=(r,e)=>e.some(t=>r instanceof t);Bk=new WeakMap,E9=new WeakMap,Rk=new WeakMap,A9=new WeakMap,S9=new WeakMap;x9={get(r,e,t){if(r instanceof IDBTransaction){if(e==="done")return E9.get(r);if(e==="objectStoreNames")return r.objectStoreNames||Rk.get(r);if(e==="store")return t.objectStoreNames[1]?void 0:t.objectStore(t.objectStoreNames[0])}return dl(r[e])},set(r,e,t){return r[e]=t,!0},has(r,e){return r instanceof IDBTransaction&&(e==="done"||e==="store")?!0:e in r}};qA=r=>S9.get(r)});function Lk(r,e,{blocked:t,upgrade:n,blocking:i,terminated:s}={}){let o=indexedDB.open(r,e),a=dl(o);return n&&o.addEventListener("upgradeneeded",c=>{n(dl(o.result),c.oldVersion,c.newVersion,dl(o.transaction),c)}),t&&o.addEventListener("blocked",c=>t(c.oldVersion,c.newVersion,c)),a.then(c=>{s&&c.addEventListener("close",()=>s()),i&&c.addEventListener("versionchange",l=>i(l.oldVersion,l.newVersion,l))}).catch(()=>{}),a}function Uk(r,e){if(!(r instanceof IDBDatabase&&!(e in r)&&typeof e=="string"))return;if(I9.get(e))return I9.get(e);let t=e.replace(/FromIndex$/,""),n=e!==t,i=rie.includes(t);if(!(t in(n?IDBIndex:IDBObjectStore).prototype)||!(i||tie.includes(t)))return;let s=async function(o,...a){let c=this.transaction(o,i?"readwrite":"readonly"),l=c.store;return n&&(l=l.index(a.shift())),(await Promise.all([l[t](...a),i&&c.done]))[0]};return I9.set(e,s),s}var tie,rie,I9,jk=ye(()=>{"use strict";C9();C9();tie=["get","getKey","getAll","getAllKeys","count"],rie=["put","add","delete","clear"],I9=new Map;kk(r=>({...r,get:(e,t,n)=>Uk(e,t)||r.get(e,t,n),has:(e,t)=>!!Uk(e,t)||r.has(e,t)}))});async function iie(r,e,t){return await r.get(e,t)}async function sie(r,e,t,n){return await r.put(e,n,t)}async function oie(r,e,t){return await r.delete(e,t)}var zk,Dk,nie,sg,_9=ye(()=>{"use strict";jk();FA();zk="auth-client-db",Dk="ic-keyval",nie=async(r=zk,e=Dk,t)=>(HA&&(localStorage!=null&&localStorage.getItem(Ta))&&(localStorage.removeItem(Ta),localStorage.removeItem(Oa)),await Lk(r,t,{upgrade:n=>{n.objectStoreNames.contains(e)&&n.clear(e),n.createObjectStore(e)}}));sg=class r{constructor(e,t){this._db=e,this._storeName=t}static async create(e){let{dbName:t=zk,storeName:n=Dk,version:i=qk}=e??{},s=await nie(t,n,i);return new r(s,n)}async set(e,t){return await sie(this._db,this._storeName,e,t)}async get(e){var t;return(t=await iie(this._db,this._storeName,e))!==null&&t!==void 0?t:null}async remove(e){return await oie(this._db,this._storeName,e)}}});var aie,cie,$A,Oa,Ta,Hk,qk,HA,og,ag,FA=ye(()=>{"use strict";_9();aie=function(r,e,t,n,i){if(n==="m")throw new TypeError("Private method is not writable");if(n==="a"&&!i)throw new TypeError("Private accessor was defined without a setter");if(typeof e=="function"?r!==e||!i:!e.has(r))throw new TypeError("Cannot write private member to an object whose class did not declare it");return n==="a"?i.call(r,t):i?i.value=t:e.set(r,t),t},cie=function(r,e,t,n){if(t==="a"&&!n)throw new TypeError("Private accessor was defined without a getter");if(typeof e=="function"?r!==e||!n:!e.has(r))throw new TypeError("Cannot read private member from an object whose class did not declare it");return t==="m"?n:t==="a"?n.call(r):n?n.value:e.get(r)},Oa="identity",Ta="delegation",Hk="iv",qk=1,HA=typeof window<"u",og=class{constructor(e="ic-",t){this.prefix=e,this._localStorage=t}get(e){return Promise.resolve(this._getLocalStorage().getItem(this.prefix+e))}set(e,t){return this._getLocalStorage().setItem(this.prefix+e,t),Promise.resolve()}remove(e){return this._getLocalStorage().removeItem(this.prefix+e),Promise.resolve()}_getLocalStorage(){if(this._localStorage)return this._localStorage;let e=typeof window>"u"?typeof global>"u"?typeof self>"u"?void 0:self.localStorage:global.localStorage:window.localStorage;if(!e)throw new Error("Could not find local storage.");return e}},ag=class{constructor(e){$A.set(this,void 0),aie(this,$A,e??{},"f")}get _db(){return new Promise(e=>{if(this.initializedDb){e(this.initializedDb);return}sg.create(cie(this,$A,"f")).then(t=>{this.initializedDb=t,e(t)})})}async get(e){return await(await this._db).get(e)}async set(e,t){await(await this._db).set(e,t)}async remove(e){await(await this._db).remove(e)}};$A=new WeakMap});var $k={};Re($k,{AuthClient:()=>ty,ERROR_USER_INTERRUPT:()=>Fk,IdbKeyVal:()=>sg,IdbStorage:()=>ag,IdleManager:()=>ig,KEY_STORAGE_DELEGATION:()=>Ta,KEY_STORAGE_KEY:()=>Oa,LocalStorage:()=>og});async function O9(r){await r.remove(Oa),await r.remove(Ta),await r.remove(Hk)}var lie,uie,N9,T9,hie,Fk,ty,M9=ye(()=>{"use strict";_a();b9();v9();FA();FA();_9();v9();lie="https://identity.internetcomputer.org",uie="#authorize",N9="ECDSA",T9="Ed25519",hie=500,Fk="UserInterrupt",ty=class{constructor(e,t,n,i,s,o,a,c){this._identity=e,this._key=t,this._chain=n,this._storage=i,this.idleManager=s,this._createOptions=o,this._idpWindow=a,this._eventHandler=c,this._registerDefaultIdleCallback()}static async create(e={}){var t,n,i;let s=(t=e.storage)!==null&&t!==void 0?t:new ag,o=(n=e.keyType)!==null&&n!==void 0?n:N9,a=null;if(e.identity)a=e.identity;else{let h=await s.get(Oa);if(!h&&HA)try{let p=new og,w=await p.get(Ta),y=await p.get(Oa);w&&y&&o===N9&&(console.log("Discovered an identity stored in localstorage. Migrating to IndexedDB"),await s.set(Ta,w),await s.set(Oa,y),h=w,await p.remove(Ta),await p.remove(Oa))}catch(p){console.error("error while attempting to recover localstorage: "+p)}if(h)try{typeof h=="object"?o===T9&&typeof h=="string"?a=await Na.fromJSON(h):a=await Of.fromKeyPair(h):typeof h=="string"&&(a=Na.fromJSON(h))}catch{}}let c=new Aa,l=null;if(a)try{let h=await s.get(Ta);if(typeof h=="object"&&h!==null)throw new Error("Delegation chain is incorrectly stored. A delegation chain should be stored as a string.");e.identity?c=e.identity:h&&(l=Su.fromJSON(h),Ik(l)?"toDer"in a?c=ey.fromDelegation(a,l):c=xc.fromDelegation(a,l):(await O9(s),a=null))}catch(h){console.error(h),await O9(s),a=null}let u;return!((i=e.idleOptions)===null||i===void 0)&&i.disableIdle?u=void 0:(l||e.identity)&&(u=ig.create(e.idleOptions)),a||(o===T9?(a=await Na.generate(),await s.set(Oa,JSON.stringify(a.toJSON()))):(e.storage&&o===N9&&console.warn(`You are using a custom storage provider that may not support CryptoKey storage. If you are using a custom storage provider that does not support CryptoKey storage, you should use '${T9}' as the key type, as it can serialize to a string`),a=await Of.generate(),await s.set(Oa,a.getKeyPair()))),new this(c,a,l,s,u,e)}_registerDefaultIdleCallback(){var e,t;let n=(e=this._createOptions)===null||e===void 0?void 0:e.idleOptions;!n?.onIdle&&!n?.disableDefaultIdleCallback&&((t=this.idleManager)===null||t===void 0||t.registerCallback(()=>{this.logout(),location.reload()}))}async _handleSuccess(e,t){var n,i;let s=e.delegations.map(l=>({delegation:new xu(l.delegation.pubkey,l.delegation.expiration,l.delegation.targets),signature:l.signature.buffer})),o=Su.fromDelegations(s,e.userPublicKey.buffer),a=this._key;if(!a)return;this._chain=o,"toDer"in a?this._identity=ey.fromDelegation(a,this._chain):this._identity=xc.fromDelegation(a,this._chain),(n=this._idpWindow)===null||n===void 0||n.close();let c=(i=this._createOptions)===null||i===void 0?void 0:i.idleOptions;!this.idleManager&&!c?.disableIdle&&(this.idleManager=ig.create(c),this._registerDefaultIdleCallback()),this._removeEventListener(),delete this._idpWindow,this._chain&&await this._storage.set(Ta,JSON.stringify(this._chain.toJSON())),t?.(e)}getIdentity(){return this._identity}async isAuthenticated(){return!this.getIdentity().getPrincipal().isAnonymous()&&this._chain!==null}async login(e){var t,n,i,s;let o=BigInt(8)*BigInt(36e11),a=new URL(((t=e?.identityProvider)===null||t===void 0?void 0:t.toString())||lie);a.hash=uie,(n=this._idpWindow)===null||n===void 0||n.close(),this._removeEventListener(),this._eventHandler=this._getEventHandler(a,Object.assign({maxTimeToLive:(i=e?.maxTimeToLive)!==null&&i!==void 0?i:o},e)),window.addEventListener("message",this._eventHandler),this._idpWindow=(s=window.open(a.toString(),"idpWindow",e?.windowOpenerFeatures))!==null&&s!==void 0?s:void 0;let c=()=>{this._idpWindow&&(this._idpWindow.closed?this._handleFailure(Fk,e?.onError):setTimeout(c,hie))};c()}_getEventHandler(e,t){return async n=>{var i,s,o;if(n.origin!==e.origin)return;let a=n.data;switch(a.kind){case"authorize-ready":{let c=Object.assign({kind:"authorize-client",sessionPublicKey:new Uint8Array((i=this._key)===null||i===void 0?void 0:i.getPublicKey().toDer()),maxTimeToLive:t?.maxTimeToLive,allowPinAuthentication:t?.allowPinAuthentication,derivationOrigin:(s=t?.derivationOrigin)===null||s===void 0?void 0:s.toString()},t?.customValues);(o=this._idpWindow)===null||o===void 0||o.postMessage(c,e.origin);break}case"authorize-client-success":try{await this._handleSuccess(a,t?.onSuccess)}catch(c){this._handleFailure(c.message,t?.onError)}break;case"authorize-client-failure":this._handleFailure(a.text,t?.onError);break;default:break}}}_handleFailure(e,t){var n;(n=this._idpWindow)===null||n===void 0||n.close(),t?.(e),this._removeEventListener(),delete this._idpWindow}_removeEventListener(){this._eventHandler&&window.removeEventListener("message",this._eventHandler),this._eventHandler=void 0}async logout(e={}){if(await O9(this._storage),this._identity=new Aa,this._chain=null,e.returnTo)try{window.history.pushState({},"",e.returnTo)}catch{window.location.href=e.returnTo}}}});var B9=$r(WA=>{"use strict";Object.defineProperty(WA,"__esModule",{value:!0});WA.IcpayWallet=void 0;var die=(M9(),Yd($k)),Wk=(Zi(),Yd(k8)),Ma=ew(),P9=class{constructor(e){this.authClient=null,this.identity=null,this.principal=null,this.connectedProvider=null,this.connectedWallet=null,this.providers=[{id:"internet-identity",name:"Internet Identity",icon:"\u{1F310}",description:"Official Internet Computer identity provider"},{id:"oisy",name:"OISY",icon:"\u{1F510}",description:"OISY wallet for Internet Computer"},{id:"plug",name:"Plug Wallet",icon:"\u{1F50C}",description:"Plug wallet extension"}],e?.connectedWallet&&(this.connectedWallet=e.connectedWallet)}getProviders(){return this.providers}isProviderAvailable(e){if(typeof window>"u")return!1;switch(e){case"internet-identity":return!0;case"oisy":return"oisy"in window;case"plug":return"ic"in window&&window.ic!==void 0&&"plug"in window.ic;default:return!1}}async connectToProvider(e){try{switch(e){case"internet-identity":return await this.connectInternetIdentity();case"oisy":return await this.connectOisy();case"plug":return await this.connectPlug();default:throw(0,Ma.createWalletError)(Ma.ICPAY_ERROR_CODES.UNSUPPORTED_PROVIDER,`Unsupported wallet provider: ${e}`)}}catch(t){throw t instanceof Error&&(t.message.includes("rejected")||t.message.includes("cancelled"))?(0,Ma.createWalletError)(Ma.ICPAY_ERROR_CODES.WALLET_USER_CANCELLED,`Connection to ${e} was cancelled by user`):(0,Ma.createWalletError)(Ma.ICPAY_ERROR_CODES.WALLET_CONNECTION_FAILED,`Failed to connect to ${e}`,t)}}async connectInternetIdentity(){return this.authClient=await die.AuthClient.create(),await this.authClient.isAuthenticated()?(this.identity=this.authClient.getIdentity(),this.principal=this.identity.getPrincipal(),this.connectedProvider="internet-identity"):await new Promise((e,t)=>{this.authClient.login({identityProvider:"https://identity.ic0.app",onSuccess:()=>{this.identity=this.authClient.getIdentity(),this.principal=this.identity.getPrincipal(),this.connectedProvider="internet-identity",e()},onError:n=>{t(new Error(`Authentication failed: ${n||"Unknown error"}`))}})}),{provider:"internet-identity",principal:this.principal.toText(),accountId:this.principal.toText(),connected:!0}}async connectOisy(){if(typeof window>"u"||!window.oisy)throw(0,Ma.createWalletError)(Ma.ICPAY_ERROR_CODES.WALLET_PROVIDER_NOT_AVAILABLE,"OISY wallet is not available");try{let e=await window.oisy.requestConnect();if(e.connected)return this.principal=Wk.Principal.fromText(e.principal),this.connectedProvider="oisy",{provider:"oisy",principal:e.principal,accountId:e.principal,connected:!0};throw(0,Ma.createWalletError)(Ma.ICPAY_ERROR_CODES.WALLET_USER_CANCELLED,"OISY connection was rejected by user")}catch(e){throw new Error(`OISY connection failed: ${e}`)}}async connectPlug(){if(typeof window>"u"||!window.ic?.plug)throw new Error("Plug wallet is not available");try{if(await window.ic.plug.requestConnect()){let t=await window.ic.plug.getPrincipal();return this.principal=Wk.Principal.fromText(t),this.connectedProvider="plug",{provider:"plug",principal:t,accountId:t,connected:!0}}else throw new Error("Plug connection was rejected")}catch(e){throw new Error(`Plug connection failed: ${e}`)}}async showConnectionModal(){let e=this.providers.filter(t=>this.isProviderAvailable(t.id));if(e.length===0)throw new Ma.IcpayError({code:"NO_PROVIDERS_AVAILABLE",message:"No wallet providers are available"});return await this.connectToProvider(e[0].id)}getAccountAddress(){if(!this.principal)throw new Ma.IcpayError({code:"WALLET_NOT_CONNECTED",message:"Wallet is not connected"});return this.principal.toText()}async disconnect(){this.authClient&&await this.authClient.logout(),this.authClient=null,this.identity=null,this.principal=null,this.connectedProvider=null}isConnected(){return this.connectedWallet?this.connectedWallet.owner||this.connectedWallet.principal||typeof this.connectedWallet.getPrincipal=="function"?!0:"connected"in this.connectedWallet?!!this.connectedWallet.connected:this.connectedWallet!==null&&typeof this.connectedWallet=="object":this.identity!==null&&this.principal!==null}getIdentity(){return this.identity}getPrincipal(){return this.principal}getConnectedProvider(){return this.connectedProvider}};WA.IcpayWallet=P9});var Vk={};Re(Vk,{idlFactory:()=>fie,init:()=>pie});var fie,pie,Kk=ye(()=>{"use strict";fie=({IDL:r})=>{let e=r.Record({account_canister_id:r.Nat64,percentage:r.Nat16}),t=r.Record({account_canister_id:r.Nat64,platform_fee_percentage:r.Nat16,subaccount:r.Opt(r.Vec(r.Nat8)),wallet_address:r.Text,icp_account_identifier:r.Opt(r.Text),platform_fee_fixed:r.Opt(r.Nat),is_active:r.Bool,splits:r.Vec(e)}),n=r.Variant({Ok:r.Null,Err:r.Text}),i=r.Variant({Failed:r.Text,Processed:r.Null,Received:r.Null,Completed:r.Null,Pending:r.Null}),s=r.Record({account_canister_id:r.Nat64,index_block:r.Opt(r.Nat64),timestamp:r.Opt(r.Nat64),account_percentage:r.Nat16,amount:r.Nat}),o=r.Record({id:r.Nat,status:i,account_canister_id:r.Nat64,platform_fee_amount:r.Nat,transfer_fee:r.Nat,memo:r.Opt(r.Vec(r.Nat8)),timestamp_to_account:r.Opt(r.Nat64),notify_processing:r.Bool,source_type:r.Nat8,timestamp:r.Nat64,index_received:r.Opt(r.Nat64),sender_principal_id:r.Text,account_amount:r.Nat,ledger_canister_id:r.Text,splits:r.Vec(s),timestamp_received:r.Opt(r.Nat64),amount:r.Nat}),a=r.Record({transactions:r.Vec(o),total_count:r.Nat32,has_more:r.Bool}),c=r.Record({total_accounts:r.Nat32,cycles_balance:r.Nat64,controllers:r.Vec(r.Principal),is_healthy:r.Bool,last_update_timestamp:r.Nat64,active_accounts:r.Nat32,memory_size_bytes:r.Nat64,total_transactions:r.Nat32,platform_wallet:r.Text}),l=r.Record({id:r.Nat,fee:r.Nat,status:i,account_canister_id:r.Nat64,to_principal:r.Text,to_subaccount:r.Opt(r.Vec(r.Nat8)),from_subaccount:r.Vec(r.Nat8),icp_account_identifier:r.Opt(r.Text),notify_processing:r.Opt(r.Bool),timestamp_created:r.Nat64,index:r.Opt(r.Nat64),ledger_canister_id:r.Text,timestamp_completed:r.Opt(r.Nat64),amount:r.Nat,status_message:r.Opt(r.Text)}),u=r.Record({status:i,timestamp_platform_to_account:r.Opt(r.Nat64),account_canister_id:r.Nat64,original_tx_id:r.Nat,notify_processing:r.Bool,timestamp_created:r.Nat64,timestamp_to_sender:r.Opt(r.Nat64),ledger_canister_id:r.Text,amount:r.Nat,platform_refund_amount:r.Nat,index_to_sender:r.Opt(r.Nat64),index_platform_to_account:r.Opt(r.Nat64)}),h=r.Record({status:i,amount:r.Nat}),p=r.Record({from_timestamp:r.Opt(r.Nat64),status:r.Opt(i),account_canister_id:r.Opt(r.Nat64),from_id:r.Opt(r.Nat),offset:r.Opt(r.Nat32),limit:r.Opt(r.Nat32),to_timestamp:r.Opt(r.Nat64),ledger_canister_id:r.Opt(r.Text)}),w=r.Record({utc_offset_minutes:r.Opt(r.Int16),language:r.Text}),y=r.Variant({GenericDisplay:r.Null,LineDisplay:r.Record({characters_per_line:r.Nat16,lines_per_page:r.Nat16})}),v=r.Record({metadata:w,device_spec:r.Opt(y)}),S=r.Record({arg:r.Vec(r.Nat8),method:r.Text,user_preferences:v}),N=r.Record({lines:r.Vec(r.Text)}),O=r.Variant({LineDisplayMessage:r.Record({pages:r.Vec(N)}),GenericDisplayMessage:r.Text}),L=r.Record({metadata:w,consent_message:O}),j=r.Record({description:r.Text}),q=r.Variant({GenericError:r.Record({description:r.Text,error_code:r.Nat64}),InsufficientPayment:j,UnsupportedCanisterCall:j,ConsentMessageUnavailable:j}),D=r.Variant({Ok:L,Err:q}),F=r.Record({account_canister_id:r.Nat64,account:t}),k=r.Record({block_index:r.Nat64,ledger_canister_id:r.Text}),C=r.Record({id:r.Text,status:i,amount:r.Nat}),z=r.Variant({Ok:C,Err:r.Text}),R=r.Variant({Ok:l,Err:r.Text}),g=r.Variant({Ok:r.Nat,Err:r.Text});return r.Service({add_account:r.Func([r.Nat64,t],[n],[]),get_account:r.Func([r.Nat64],[r.Opt(t)],["query"]),get_account_transactions:r.Func([r.Nat64,r.Opt(r.Nat32),r.Opt(r.Nat32)],[a],["query"]),get_canister_info:r.Func([],[c],["query"]),get_controllers:r.Func([],[r.Vec(r.Principal)],["query"]),get_payout:r.Func([r.Nat],[r.Opt(l)],["query"]),get_refund_by_original_tx_id:r.Func([r.Nat],[r.Opt(u)],["query"]),get_transaction:r.Func([r.Nat],[r.Opt(o)],["query"]),get_transaction_status_public:r.Func([r.Nat64,r.Nat,r.Opt(r.Nat64)],[r.Opt(h)],["query"]),get_transactions:r.Func([p],[a],["query"]),icrc21_canister_call_consent_message:r.Func([S],[D],["query"]),initialize_controllers:r.Func([],[n],[]),list_accounts:r.Func([],[r.Vec(F)],["query"]),notify_ledger_transaction:r.Func([k],[z],[]),notify_onramp_icp:r.Func([r.Vec(r.Nat8),r.Vec(r.Nat8)],[z],[]),remove_account:r.Func([r.Nat64],[n],[]),request_payout:r.Func([r.Nat64,r.Text,r.Nat],[R],[]),request_refund:r.Func([r.Nat],[g],[]),retry_payout:r.Func([r.Nat],[R],[]),set_platform_wallet:r.Func([r.Text],[n],[]),update_account:r.Func([r.Nat64,t],[n],[]),update_controllers:r.Func([],[n],[])})},pie=({IDL:r})=>[]});var Qk={};Re(Qk,{idlFactory:()=>gie,init:()=>mie});var gie,mie,Gk=ye(()=>{"use strict";gie=({IDL:r})=>{let e=r.Rec(),t=r.Rec(),n=r.Rec(),i=r.Record({num_blocks_to_archive:r.Opt(r.Nat64),max_transactions_per_response:r.Opt(r.Nat64),trigger_threshold:r.Opt(r.Nat64),more_controller_ids:r.Opt(r.Vec(r.Principal)),max_message_size_bytes:r.Opt(r.Nat64),cycles_for_archive_creation:r.Opt(r.Nat64),node_max_memory_size_bytes:r.Opt(r.Nat64),controller_id:r.Opt(r.Principal)}),s=r.Variant({Int:r.Int,Nat:r.Nat,Blob:r.Vec(r.Nat8),Text:r.Text}),o=r.Vec(r.Nat8),a=r.Record({owner:r.Principal,subaccount:r.Opt(o)}),c=r.Variant({SetTo:a,Unset:r.Null}),l=r.Record({icrc2:r.Bool}),u=r.Record({change_archive_options:r.Opt(i),token_symbol:r.Opt(r.Text),transfer_fee:r.Opt(r.Nat),metadata:r.Opt(r.Vec(r.Tuple(r.Text,s))),change_fee_collector:r.Opt(c),max_memo_length:r.Opt(r.Nat16),index_principal:r.Opt(r.Principal),token_name:r.Opt(r.Text),feature_flags:r.Opt(l)}),h=r.Record({decimals:r.Opt(r.Nat8),token_symbol:r.Text,transfer_fee:r.Nat,metadata:r.Vec(r.Tuple(r.Text,s)),minting_account:a,initial_balances:r.Vec(r.Tuple(a,r.Nat)),fee_collector_account:r.Opt(a),archive_options:r.Record({num_blocks_to_archive:r.Nat64,max_transactions_per_response:r.Opt(r.Nat64),trigger_threshold:r.Nat64,more_controller_ids:r.Opt(r.Vec(r.Principal)),max_message_size_bytes:r.Opt(r.Nat64),cycles_for_archive_creation:r.Opt(r.Nat64),node_max_memory_size_bytes:r.Opt(r.Nat64),controller_id:r.Principal}),max_memo_length:r.Opt(r.Nat16),index_principal:r.Opt(r.Principal),token_name:r.Text,feature_flags:r.Opt(l)}),p=r.Variant({Upgrade:r.Opt(u),Init:h}),w=r.Nat,y=r.Record({block_range_end:w,canister_id:r.Principal,block_range_start:w}),v=r.Record({start:w,length:r.Nat}),S=r.Vec(r.Tuple(r.Text,n));n.fill(r.Variant({Int:r.Int,Map:S,Nat:r.Nat,Nat64:r.Nat64,Blob:r.Vec(r.Nat8),Text:r.Text,Array:r.Vec(n)}));let N=n,O=r.Record({blocks:r.Vec(N)}),L=r.Func([v],[O],["query"]),j=r.Record({certificate:r.Opt(r.Vec(r.Nat8)),first_index:w,blocks:r.Vec(N),chain_length:r.Nat64,archived_blocks:r.Vec(r.Record({callback:L,start:w,length:r.Nat}))}),q=r.Record({certificate:r.Opt(r.Vec(r.Nat8)),hash_tree:r.Vec(r.Nat8)}),D=r.Nat,F=r.Record({start:D,length:r.Nat}),k=r.Nat64,C=r.Record({from:a,memo:r.Opt(r.Vec(r.Nat8)),created_at_time:r.Opt(k),amount:r.Nat,spender:r.Opt(a)}),z=r.Record({to:a,memo:r.Opt(r.Vec(r.Nat8)),created_at_time:r.Opt(k),amount:r.Nat}),R=r.Record({fee:r.Opt(r.Nat),from:a,memo:r.Opt(r.Vec(r.Nat8)),created_at_time:r.Opt(k),amount:r.Nat,expected_allowance:r.Opt(r.Nat),expires_at:r.Opt(k),spender:a}),g=r.Record({to:a,fee:r.Opt(r.Nat),from:a,memo:r.Opt(r.Vec(r.Nat8)),created_at_time:r.Opt(k),amount:r.Nat,spender:r.Opt(a)}),m=r.Record({burn:r.Opt(C),kind:r.Text,mint:r.Opt(z),approve:r.Opt(R),timestamp:k,transfer:r.Opt(g)}),d=r.Record({transactions:r.Vec(m)}),f=r.Func([F],[d],["query"]),b=r.Record({first_index:D,log_length:r.Nat,transactions:r.Vec(m),archived_transactions:r.Vec(r.Record({callback:f,start:D,length:r.Nat}))}),_=r.Record({take:r.Opt(r.Nat),prev_spender:r.Opt(a),from_account:r.Opt(a)}),T=r.Record({from_account:a,to_spender:a,allowance:r.Nat,expires_at:r.Opt(r.Nat64)}),I=r.Variant({GenericError:r.Record({message:r.Text,error_code:r.Nat}),AccessDenied:r.Record({reason:r.Text})}),A=r.Variant({Ok:r.Vec(T),Err:I}),U=r.Variant({GenericError:r.Record({description:r.Text,error_code:r.Nat}),IndexPrincipalNotSet:r.Null}),M=r.Variant({Ok:r.Principal,Err:U}),P=r.Nat,H=r.Record({url:r.Text,name:r.Text}),V=r.Record({to:a,fee:r.Opt(P),memo:r.Opt(r.Vec(r.Nat8)),from_subaccount:r.Opt(o),created_at_time:r.Opt(k),amount:P}),G=r.Variant({GenericError:r.Record({message:r.Text,error_code:r.Nat}),TemporarilyUnavailable:r.Null,BadBurn:r.Record({min_burn_amount:P}),Duplicate:r.Record({duplicate_of:w}),BadFee:r.Record({expected_fee:P}),CreatedInFuture:r.Record({ledger_time:k}),TooOld:r.Null,InsufficientFunds:r.Record({balance:P})}),X=r.Variant({Ok:w,Err:G}),se=r.Record({utc_offset_minutes:r.Opt(r.Int16),language:r.Text}),W=r.Record({metadata:se,device_spec:r.Opt(r.Variant({GenericDisplay:r.Null,LineDisplay:r.Record({characters_per_line:r.Nat16,lines_per_page:r.Nat16})}))}),Q=r.Record({arg:r.Vec(r.Nat8),method:r.Text,user_preferences:W}),Y=r.Variant({LineDisplayMessage:r.Record({pages:r.Vec(r.Record({lines:r.Vec(r.Text)}))}),GenericDisplayMessage:r.Text}),ne=r.Record({metadata:se,consent_message:Y}),J=r.Record({description:r.Text}),re=r.Variant({GenericError:r.Record({description:r.Text,error_code:r.Nat}),InsufficientPayment:J,UnsupportedCanisterCall:J,ConsentMessageUnavailable:J}),oe=r.Variant({Ok:ne,Err:re}),ie=r.Record({account:a,spender:a}),le=r.Record({allowance:r.Nat,expires_at:r.Opt(k)}),de=r.Record({fee:r.Opt(r.Nat),memo:r.Opt(r.Vec(r.Nat8)),from_subaccount:r.Opt(r.Vec(r.Nat8)),created_at_time:r.Opt(k),amount:r.Nat,expected_allowance:r.Opt(r.Nat),expires_at:r.Opt(k),spender:a}),fe=r.Variant({GenericError:r.Record({message:r.Text,error_code:r.Nat}),TemporarilyUnavailable:r.Null,Duplicate:r.Record({duplicate_of:w}),BadFee:r.Record({expected_fee:r.Nat}),AllowanceChanged:r.Record({current_allowance:r.Nat}),CreatedInFuture:r.Record({ledger_time:k}),TooOld:r.Null,Expired:r.Record({ledger_time:k}),InsufficientFunds:r.Record({balance:r.Nat})}),Ee=r.Variant({Ok:w,Err:fe}),xe=r.Record({to:a,fee:r.Opt(P),spender_subaccount:r.Opt(o),from:a,memo:r.Opt(r.Vec(r.Nat8)),created_at_time:r.Opt(k),amount:P}),_e=r.Variant({GenericError:r.Record({message:r.Text,error_code:r.Nat}),TemporarilyUnavailable:r.Null,InsufficientAllowance:r.Record({allowance:P}),BadBurn:r.Record({min_burn_amount:P}),Duplicate:r.Record({duplicate_of:w}),BadFee:r.Record({expected_fee:P}),CreatedInFuture:r.Record({ledger_time:k}),TooOld:r.Null,InsufficientFunds:r.Record({balance:P})}),Qe=r.Variant({Ok:w,Err:_e}),De=r.Record({from:r.Opt(r.Principal)}),Ye=r.Vec(r.Record({end:r.Nat,canister_id:r.Principal,start:r.Nat}));t.fill(r.Variant({Int:r.Int,Map:r.Vec(r.Tuple(r.Text,t)),Nat:r.Nat,Blob:r.Vec(r.Nat8),Text:r.Text,Array:r.Vec(t)})),e.fill(r.Record({log_length:r.Nat,blocks:r.Vec(r.Record({id:r.Nat,block:t})),archived_blocks:r.Vec(r.Record({args:r.Vec(v),callback:r.Func([r.Vec(v)],[e],["query"])}))}));let Ze=r.Record({certificate:r.Vec(r.Nat8),hash_tree:r.Vec(r.Nat8)});return r.Service({archives:r.Func([],[r.Vec(y)],["query"]),get_blocks:r.Func([v],[j],["query"]),get_data_certificate:r.Func([],[q],["query"]),get_transactions:r.Func([F],[b],["query"]),icrc103_get_allowances:r.Func([_],[A],["query"]),icrc106_get_index_principal:r.Func([],[M],["query"]),icrc10_supported_standards:r.Func([],[r.Vec(r.Record({url:r.Text,name:r.Text}))],["query"]),icrc1_balance_of:r.Func([a],[P],["query"]),icrc1_decimals:r.Func([],[r.Nat8],["query"]),icrc1_fee:r.Func([],[P],["query"]),icrc1_metadata:r.Func([],[r.Vec(r.Tuple(r.Text,s))],["query"]),icrc1_minting_account:r.Func([],[r.Opt(a)],["query"]),icrc1_name:r.Func([],[r.Text],["query"]),icrc1_supported_standards:r.Func([],[r.Vec(H)],["query"]),icrc1_symbol:r.Func([],[r.Text],["query"]),icrc1_total_supply:r.Func([],[P],["query"]),icrc1_transfer:r.Func([V],[X],[]),icrc21_canister_call_consent_message:r.Func([Q],[oe],[]),icrc2_allowance:r.Func([ie],[le],["query"]),icrc2_approve:r.Func([de],[Ee],[]),icrc2_transfer_from:r.Func([xe],[Qe],[]),icrc3_get_archives:r.Func([De],[Ye],["query"]),icrc3_get_blocks:r.Func([r.Vec(v)],[e],["query"]),icrc3_get_tip_certificate:r.Func([],[r.Opt(Ze)],["query"]),icrc3_supported_block_types:r.Func([],[r.Vec(r.Record({url:r.Text,block_type:r.Text}))],["query"]),is_ledger_ready:r.Func([],[r.Bool],["query"])})},mie=({IDL:r})=>{let e=r.Record({num_blocks_to_archive:r.Opt(r.Nat64),max_transactions_per_response:r.Opt(r.Nat64),trigger_threshold:r.Opt(r.Nat64),more_controller_ids:r.Opt(r.Vec(r.Principal)),max_message_size_bytes:r.Opt(r.Nat64),cycles_for_archive_creation:r.Opt(r.Nat64),node_max_memory_size_bytes:r.Opt(r.Nat64),controller_id:r.Opt(r.Principal)}),t=r.Variant({Int:r.Int,Nat:r.Nat,Blob:r.Vec(r.Nat8),Text:r.Text}),n=r.Vec(r.Nat8),i=r.Record({owner:r.Principal,subaccount:r.Opt(n)}),s=r.Variant({SetTo:i,Unset:r.Null}),o=r.Record({icrc2:r.Bool}),a=r.Record({change_archive_options:r.Opt(e),token_symbol:r.Opt(r.Text),transfer_fee:r.Opt(r.Nat),metadata:r.Opt(r.Vec(r.Tuple(r.Text,t))),change_fee_collector:r.Opt(s),max_memo_length:r.Opt(r.Nat16),index_principal:r.Opt(r.Principal),token_name:r.Opt(r.Text),feature_flags:r.Opt(o)}),c=r.Record({decimals:r.Opt(r.Nat8),token_symbol:r.Text,transfer_fee:r.Nat,metadata:r.Vec(r.Tuple(r.Text,t)),minting_account:i,initial_balances:r.Vec(r.Tuple(i,r.Nat)),fee_collector_account:r.Opt(i),archive_options:r.Record({num_blocks_to_archive:r.Nat64,max_transactions_per_response:r.Opt(r.Nat64),trigger_threshold:r.Nat64,more_controller_ids:r.Opt(r.Vec(r.Principal)),max_message_size_bytes:r.Opt(r.Nat64),cycles_for_archive_creation:r.Opt(r.Nat64),node_max_memory_size_bytes:r.Opt(r.Nat64),controller_id:r.Principal}),max_memo_length:r.Opt(r.Nat16),index_principal:r.Opt(r.Principal),token_name:r.Text,feature_flags:r.Opt(o)});return[r.Variant({Upgrade:r.Opt(a),Init:c})]}});var Yk=$r(R9=>{"use strict";Object.defineProperty(R9,"__esModule",{value:!0});R9.debugLog=wie;function wie(r,e,t){r&&(t!==void 0?console.log(`[ICPay SDK] ${e}`,t):console.log(`[ICPay SDK] ${e}`))}});var Zk=$r(k9=>{"use strict";Object.defineProperty(k9,"__esModule",{value:!0});k9.createProtectedApi=yie;var cg=ew();function yie(r){let e=r.privateApiClient,t=r.emitStart,n=r.emitSuccess,i=r.emitError,s=o=>{if(!e)throw new cg.IcpayError({code:"SECRET_KEY_REQUIRED",message:`${o} requires secret key authentication. Please provide secretKey in configuration.`})};return{async getPaymentById(o){s("getPaymentById"),t("getPaymentById",{id:o});try{let a=await e.get(`/sdk/payments/${o}`);return n("getPaymentById",{id:o}),a}catch(a){throw i("getPaymentById",a),a}},async listPayments(){s("listPayments"),t("listPayments");try{let o=await e.get("/sdk/payments");return n("listPayments",{count:Array.isArray(o)?o.length:void 0}),o}catch(o){throw i("listPayments",o),o}},async getPaymentIntentById(o){s("getPaymentIntentById"),t("getPaymentIntentById",{id:o});try{let a=await e.get(`/sdk/payment-intents/${o}`);return n("getPaymentIntentById",{id:o}),a}catch(a){throw i("getPaymentIntentById",a),a}},async getInvoiceById(o){s("getInvoiceById"),t("getInvoiceById",{id:o});try{let a=await e.get(`/sdk/invoices/${o}`);return n("getInvoiceById",{id:o}),a}catch(a){throw i("getInvoiceById",a),a}},async getTransactionById(o){s("getTransactionById"),t("getTransactionById",{id:o});try{let a=await e.get(`/sdk/transactions/${o}`);return n("getTransactionById",{id:o}),a}catch(a){throw i("getTransactionById",a),a}},async getWalletById(o){s("getWalletById"),t("getWalletById",{id:o});try{let a=await e.get(`/sdk/wallets/${o}`);return n("getWalletById",{id:o}),a}catch(a){throw i("getWalletById",a),a}},async getVerifiedLedgersPrivate(){s("getVerifiedLedgersPrivate"),t("getVerifiedLedgersPrivate");try{let o=await e.get("/sdk/ledgers/verified");return n("getVerifiedLedgersPrivate",{count:Array.isArray(o)?o.length:void 0}),o}catch(o){throw i("getVerifiedLedgersPrivate",o),o}},async getAllLedgersWithPricesPrivate(){s("getAllLedgersWithPricesPrivate"),t("getAllLedgersWithPricesPrivate");try{let o=await e.get("/sdk/ledgers/all-with-prices");return n("getAllLedgersWithPricesPrivate",{count:Array.isArray(o)?o.length:void 0}),o}catch(o){throw i("getAllLedgersWithPricesPrivate",o),o}},async getLedgerInfoPrivate(o){s("getLedgerInfoPrivate"),t("getLedgerInfoPrivate",{idOrCanisterId:o});try{let a=await e.get(`/sdk/ledgers/${o}`);return n("getLedgerInfoPrivate",{idOrCanisterId:o}),a}catch(a){throw i("getLedgerInfoPrivate",a),a}},async getWebhookEventById(o){s("getWebhookEventById"),t("getWebhookEventById",{id:o});try{let a=await e.get(`/sdk/webhook-events/${o}`);return n("getWebhookEventById",{id:o}),a.data}catch(a){throw i("getWebhookEventById",a),a}},async getDetailedAccountInfo(){s("getDetailedAccountInfo"),t("getDetailedAccountInfo");try{let o=await e.get("/sdk/account"),a={id:o.id,name:o.name,email:o.email,isActive:o.isActive,isLive:o.isLive,accountCanisterId:o.accountCanisterId,walletAddress:o.walletAddress,createdAt:new Date(o.createdAt),updatedAt:new Date(o.updatedAt)};return n("getDetailedAccountInfo",a),a}catch(o){let a=new cg.IcpayError({code:"ACCOUNT_INFO_FETCH_FAILED",message:"Failed to fetch detailed account information",details:o});throw i("getDetailedAccountInfo",a),a}},async getTransactionStatus(o){s("getTransactionStatus"),t("getTransactionStatus",{canisterTransactionId:o});try{let a=await e.get(`/sdk/transactions/${o}/status`);return n("getTransactionStatus",a),a}catch(a){let c=new cg.IcpayError({code:"TRANSACTION_STATUS_FETCH_FAILED",message:"Failed to fetch transaction status",details:a});throw i("getTransactionStatus",c),c}},async getPaymentHistory(o={}){s("getPaymentHistory"),t("getPaymentHistory",{request:o});try{let a=new URLSearchParams;o.accountId&&a.append("accountId",o.accountId),o.ledgerCanisterId&&a.append("ledgerCanisterId",o.ledgerCanisterId),o.fromTimestamp&&a.append("fromTimestamp",o.fromTimestamp.toISOString()),o.toTimestamp&&a.append("toTimestamp",o.toTimestamp.toISOString()),o.status&&a.append("status",o.status),o.limit&&a.append("limit",o.limit.toString()),o.offset&&a.append("offset",o.offset.toString());let c=await e.get(`/sdk/payments/history?${a.toString()}`),l={payments:c.payments.map(u=>({id:u.id,status:u.status,amount:u.amount,ledgerCanisterId:u.ledgerCanisterId,ledgerSymbol:u.ledgerSymbol,fromAddress:u.fromAddress,toAddress:u.toAddress,fee:u.fee,decimals:u.decimals,tokenPrice:u.tokenPrice,expectedSenderPrincipal:u.expectedSenderPrincipal,metadata:u.metadata,createdAt:new Date(u.createdAt),updatedAt:new Date(u.updatedAt)})),total:c.total,limit:c.limit,offset:c.offset,hasMore:c.hasMore};return n("getPaymentHistory",{total:l.total}),l}catch(a){let c=new cg.IcpayError({code:"PAYMENT_HISTORY_FETCH_FAILED",message:"Failed to fetch payment history",details:a});throw i("getPaymentHistory",c),c}},async getPaymentsByPrincipal(o){s("getPaymentsByPrincipal"),t("getPaymentsByPrincipal",{request:o});try{let a=new URLSearchParams;o.limit&&a.append("limit",o.limit.toString()),o.offset&&a.append("offset",o.offset.toString()),o.status&&a.append("status",o.status);let c=await e.get(`/sdk/payments/by-principal/${o.principalId}?${a.toString()}`),l={payments:c.payments.map(u=>({id:u.id,status:u.status,amount:u.amount,ledgerCanisterId:u.ledgerCanisterId,ledgerSymbol:u.ledgerSymbol,fromAddress:u.fromAddress,toAddress:u.toAddress,fee:u.fee,decimals:u.decimals,tokenPrice:u.tokenPrice,expectedSenderPrincipal:u.expectedSenderPrincipal,metadata:u.metadata,createdAt:new Date(u.createdAt),updatedAt:new Date(u.updatedAt)})),total:c.total,limit:c.limit,offset:c.offset,hasMore:c.hasMore};return n("getPaymentsByPrincipal",{total:l.total}),l}catch(a){let c=new cg.IcpayError({code:"PAYMENTS_BY_PRINCIPAL_FETCH_FAILED",message:"Failed to fetch payments by principal",details:a});throw i("getPaymentsByPrincipal",c),c}},async getAccountWalletBalances(){s("getAccountWalletBalances"),t("getAccountWalletBalances");try{let o=await e.get("/sdk/account/wallet-balances"),a={balances:o.balances.map(c=>({ledgerId:c.ledgerId,ledgerName:c.ledgerName,ledgerSymbol:c.ledgerSymbol,canisterId:c.canisterId,balance:c.balance,formattedBalance:c.formattedBalance,decimals:c.decimals,currentPrice:c.currentPrice,lastPriceUpdate:c.lastPriceUpdate?new Date(c.lastPriceUpdate):void 0,lastUpdated:new Date(c.lastUpdated)})),totalBalancesUSD:o.totalBalancesUSD,lastUpdated:new Date(o.lastUpdated)};return n("getAccountWalletBalances",{count:a.balances.length,totalUSD:a.totalBalancesUSD}),a}catch(o){let a=new cg.IcpayError({code:"ACCOUNT_WALLET_BALANCES_FETCH_FAILED",message:"Failed to fetch account wallet balances",details:o});throw i("getAccountWalletBalances",a),a}}}}});var Xk=$r(VA=>{"use strict";Object.defineProperty(VA,"__esModule",{value:!0});VA.HttpClient=void 0;var U9=class{constructor(e){this.baseURL=e.baseURL.replace(/\/$/,""),this.defaultHeaders={"Content-Type":"application/json",...e.headers||{}}}setHeader(e,t){t===void 0?delete this.defaultHeaders[e]:this.defaultHeaders[e]=t}async get(e,t){let n=this.resolve(e),i=await fetch(n,{method:"GET",headers:{...this.defaultHeaders,...t||{}}});return this.handleResponse(i)}async post(e,t,n){let i=this.resolve(e),s=await fetch(i,{method:"POST",headers:{...this.defaultHeaders,...n||{}},body:t===void 0?void 0:JSON.stringify(t)});return this.handleResponse(s)}resolve(e){return/^https?:\/\//i.test(e)?e:`${this.baseURL}${e.startsWith("/")?"":"/"}${e}`}async handleResponse(e){let t=await e.text(),i=(e.headers.get("content-type")||"").includes("application/json")&&t?JSON.parse(t):t;if(!e.ok){let s=new Error(`HTTP ${e.status}: ${e.statusText}`);throw s.status=e.status,s.data=i,s}return i}};VA.HttpClient=U9});var eU=$r(Jk=>{"use strict";Object.defineProperty(Jk,"__esModule",{value:!0})});var j9=$r(eo=>{"use strict";var bie=eo&&eo.__createBinding||(Object.create?(function(r,e,t,n){n===void 0&&(n=t);var i=Object.getOwnPropertyDescriptor(e,t);(!i||("get"in i?!e.__esModule:i.writable||i.configurable))&&(i={enumerable:!0,get:function(){return e[t]}}),Object.defineProperty(r,n,i)}):(function(r,e,t,n){n===void 0&&(n=t),r[n]=e[t]})),iU=eo&&eo.__exportStar||function(r,e){for(var t in r)t!=="default"&&!Object.prototype.hasOwnProperty.call(e,t)&&bie(e,r,t)};Object.defineProperty(eo,"__esModule",{value:!0});eo.IcpayWallet=eo.IcpayError=eo.Icpay=void 0;var Mt=ew(),vie=g8(),Aie=B9(),Hh=(_a(),Yd(Ak)),L9=(Kk(),Yd(Vk)),tU=(Gk(),Yd(Qk)),rU=(Zi(),Yd(k8)),Wr=Yk(),Eie=Zk(),nU=Xk(),KA=class{constructor(e){if(this.privateApiClient=null,this.connectedWallet=null,this.icpayCanisterId=null,this.accountInfoCache=null,this.verifiedLedgersCache={data:null,timestamp:0},this.icpLedgerCanisterId="ryjl3-tyaaa-aaaaa-aaaba-cai",this.config={environment:"production",apiUrl:"https://api.icpay.org",debug:!1,enableEvents:!1,awaitServerNotification:!0,...e},(0,Wr.debugLog)(this.config.debug||!1,"constructor",{config:this.config}),!this.config.publishableKey&&!this.config.secretKey)throw new Error("Either publishableKey or secretKey must be provided");if(this.icHost=e.icHost||"https://ic0.app",this.connectedWallet=e.connectedWallet||null,this.actorProvider=e.actorProvider,(0,Wr.debugLog)(this.config.debug||!1,"constructor",{connectedWallet:this.connectedWallet,actorProvider:this.actorProvider}),this.wallet=new Aie.IcpayWallet({connectedWallet:this.connectedWallet}),this.events=new vie.IcpayEventCenter,(0,Wr.debugLog)(this.config.debug||!1,"constructor",{connectedWallet:this.connectedWallet}),this.publicApiClient=new nU.HttpClient({baseURL:this.config.apiUrl||"https://api.icpay.org",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.config.publishableKey||this.config.secretKey||""}`}}),(0,Wr.debugLog)(this.config.debug||!1,"publicApiClient created",this.publicApiClient),this.config.secretKey){let t={"Content-Type":"application/json",Authorization:`Bearer ${this.config.secretKey||""}`};this.privateApiClient=new nU.HttpClient({baseURL:this.config.apiUrl||"https://api.icpay.org",headers:t})}(0,Wr.debugLog)(this.config.debug||!1,"privateApiClient created",this.privateApiClient),this.protected=(0,Eie.createProtectedApi)({privateApiClient:this.privateApiClient,emitStart:(t,n)=>this.emitMethodStart(t,n),emitSuccess:(t,n)=>this.emitMethodSuccess(t,n),emitError:(t,n)=>this.emitMethodError(t,n)})}on(e,t){return this.events.on(e,t)}off(e,t){this.events.off(e,t)}emit(e,t){this.config.enableEvents&&this.events.emit(e,t)}addEventListener(e,t){this.events.addEventListener(e,t)}removeEventListener(e,t){this.events.removeEventListener(e,t)}dispatchEvent(e){return this.events.dispatchEvent(e)}emitError(e){let t=e instanceof Mt.IcpayError?e:new Mt.IcpayError({code:Mt.ICPAY_ERROR_CODES.UNKNOWN_ERROR,message:e&&(e.message||e.toString())||"Unknown error",details:e});this.config.enableEvents&&this.events.emit("icpay-sdk-error",t)}emitMethodStart(e,t){this.config.enableEvents&&this.events.emit("icpay-sdk-method-start",{name:e,args:t})}emitMethodSuccess(e,t){this.config.enableEvents&&this.events.emit("icpay-sdk-method-success",{name:e,result:t})}emitMethodError(e,t){this.config.enableEvents&&this.events.emit("icpay-sdk-method-error",{name:e,error:t}),this.emitError(t)}hasSecretKey(){return!!this.config.secretKey&&!!this.privateApiClient}requireSecretKey(e){if(!this.hasSecretKey())throw new Mt.IcpayError({code:"SECRET_KEY_REQUIRED",message:`${e} requires secret key authentication. Please provide secretKey and accountId in configuration.`})}async getAccountInfo(){this.emitMethodStart("getAccountInfo");try{let e=await this.publicApiClient.get("/sdk/public/account"),t={id:e.id,name:e.name,isActive:e.isActive,isLive:e.isLive,accountCanisterId:e.accountCanisterId,icpayCanisterId:e.icpayCanisterId,branding:e.branding||null};return this.emitMethodSuccess("getAccountInfo",t),t}catch(e){let t=new Mt.IcpayError({code:"ACCOUNT_INFO_FETCH_FAILED",message:"Failed to fetch account information",details:e});throw this.emitMethodError("getAccountInfo",t),t}}async getVerifiedLedgers(){this.emitMethodStart("getVerifiedLedgers");let e=Date.now(),t=3600*1e3;if(this.verifiedLedgersCache.data&&e-this.verifiedLedgersCache.timestamp<t)return this.verifiedLedgersCache.data;try{let i=(await this.publicApiClient.get("/sdk/public/ledgers/verified")).map(s=>({id:s.id,name:s.name,symbol:s.symbol,canisterId:s.canisterId,decimals:s.decimals,logoUrl:s.logoUrl,verified:s.verified,fee:s.fee,currentPrice:s.currentPrice??null,lastPriceUpdate:s.lastPriceUpdate??null}));return this.verifiedLedgersCache={data:i,timestamp:e},this.emitMethodSuccess("getVerifiedLedgers",{count:i.length}),i}catch(n){let i=new Mt.IcpayError({code:"VERIFIED_LEDGERS_FETCH_FAILED",message:"Failed to fetch verified ledgers",details:n});throw this.emitMethodError("getVerifiedLedgers",i),i}}async getLedgerCanisterIdBySymbol(e){if(this.emitMethodStart("getLedgerCanisterIdBySymbol",{symbol:e}),!e||typeof e!="string")throw new Mt.IcpayError({code:"INVALID_LEDGER_SYMBOL",message:"Symbol must be a non-empty string"});let n=(await this.getVerifiedLedgers()).find(s=>s.symbol.toLowerCase()===e.toLowerCase());if(!n)throw new Mt.IcpayError({code:"LEDGER_SYMBOL_NOT_FOUND",message:`Verified ledger with symbol ${e} not found`});let i=n.canisterId;return this.emitMethodSuccess("getLedgerCanisterIdBySymbol",{symbol:e,canisterId:i}),i}async triggerTransactionSync(e){this.emitMethodStart("triggerTransactionSync",{canisterTransactionId:e});try{let t=await this.publicApiClient.get(`/sdk/public/transactions/${e}/sync`);return this.emitMethodSuccess("triggerTransactionSync",t),t}catch(t){let n=new Mt.IcpayError({code:"TRANSACTION_SYNC_TRIGGER_FAILED",message:"Failed to trigger transaction sync from canister",details:t});throw this.emitMethodError("triggerTransactionSync",n),n}}async fetchAccountInfo(){if(this.accountInfoCache)return this.icpayCanisterId=this.accountInfoCache.icpayCanisterId.toString(),this.accountInfoCache;try{let e=await this.publicApiClient.get("/sdk/public/account");return this.accountInfoCache=e,e&&e.icpayCanisterId&&(this.icpayCanisterId=e.icpayCanisterId.toString()),this.accountInfoCache}catch(e){throw new Mt.IcpayError({code:"ACCOUNT_INFO_FETCH_FAILED",message:"Failed to fetch account information",details:e})}}async showWalletModal(){this.emitMethodStart("showWalletModal");try{let e=await this.wallet.showConnectionModal();return this.emitMethodSuccess("showWalletModal",e),e}catch(e){throw this.emitMethodError("showWalletModal",e),e}}async connectWallet(e){this.emitMethodStart("connectWallet",{providerId:e});try{let t=await this.wallet.connectToProvider(e);return this.emitMethodSuccess("connectWallet",t),t}catch(t){throw this.emitMethodError("connectWallet",t),t}}getWalletProviders(){this.emitMethodStart("getWalletProviders");let e=this.wallet.getProviders();return this.emitMethodSuccess("getWalletProviders",{count:Array.isArray(e)?e.length:void 0}),e}isWalletProviderAvailable(e){this.emitMethodStart("isWalletProviderAvailable",{providerId:e});let t=this.wallet.isProviderAvailable(e);return this.emitMethodSuccess("isWalletProviderAvailable",{providerId:e,available:t}),t}getAccountAddress(){this.emitMethodStart("getAccountAddress");let e=this.wallet.getAccountAddress();return this.emitMethodSuccess("getAccountAddress",{accountAddress:e}),e}async getLedgerBalance(e){this.emitMethodStart("getLedgerBalance",{ledgerCanisterId:e});try{let t=null;if(this.connectedWallet&&(this.connectedWallet.owner?t=this.connectedWallet.owner:this.connectedWallet.principal&&(t=this.connectedWallet.principal)),!t)throw new Error("No principal available for balance check");let n=rU.Principal.fromText(t),i=new Hh.HttpAgent({host:this.icHost}),o=await Hh.Actor.createActor(tU.idlFactory,{agent:i,canisterId:e}).icrc1_balance_of({owner:n,subaccount:[]}),a=BigInt(o);return this.emitMethodSuccess("getLedgerBalance",{ledgerCanisterId:e,balance:a.toString()}),a}catch(t){throw this.emitMethodError("getLedgerBalance",t),t}}createPackedMemo(e,t){let n=BigInt(e>>>0)<<BigInt(32)|BigInt(t>>>0);if(n===BigInt(0))return new Uint8Array([0]);let i=[];for(;n>BigInt(0);)i.push(Number(n&BigInt(255))),n>>=BigInt(8);return new Uint8Array(i)}async sendFunds(e){this.emitMethodStart("sendFunds",{request:{...e,amount:typeof e.amount=="string"?e.amount:String(e.amount)}});try{(0,Wr.debugLog)(this.config.debug||!1,"sendFunds start",{request:e});let t=e.ledgerCanisterId;if(!t&&e.symbol&&(t=await this.getLedgerCanisterIdBySymbol(e.symbol)),!t){let F=new Mt.IcpayError({code:Mt.ICPAY_ERROR_CODES.INVALID_CONFIG,message:"Either ledgerCanisterId or symbol must be provided",details:{request:e}});throw this.emitMethodError("sendFunds",F),F}let n=e.accountCanisterId;if(n||((0,Wr.debugLog)(this.config.debug||!1,"fetching account info for accountCanisterId"),n=(await this.getAccountInfo()).accountCanisterId.toString(),(0,Wr.debugLog)(this.config.debug||!1,"accountCanisterId resolved",{accountCanisterId:n})),this.icpayCanisterId||await this.fetchAccountInfo(),!this.icpayCanisterId)try{let F=await this.getAccountInfo();F?.icpayCanisterId&&(this.icpayCanisterId=F.icpayCanisterId.toString())}catch{}if(!this.icpayCanisterId||typeof this.icpayCanisterId!="string"){let F=new Mt.IcpayError({code:Mt.ICPAY_ERROR_CODES.INVALID_CONFIG,message:"Could not resolve ICPay canister ID from account info",details:{accountInfoCache:this.accountInfoCache}});throw this.emitMethodError("sendFunds",F),F}let i=this.icpayCanisterId,s=this.icHost,o;if(e.onrampPayment===!0||this.config.onrampPayment===!0){if(t!==this.icpLedgerCanisterId){let z=new Mt.IcpayError({code:Mt.ICPAY_ERROR_CODES.INVALID_CONFIG,message:"Onramp is only supported for ICP ledger",details:{provided:t,expected:this.icpLedgerCanisterId}});throw this.emitError(z),z}let F=e.amountUsd;if(F==null)try{let z=await this.calculateTokenAmountFromUSD({usdAmount:1,ledgerCanisterId:t}),R=z.currentPrice,g=(typeof e.amount=="string",Number(e.amount));F=R*(g/Math.pow(10,z.decimals))}catch{}let k=null,C=null;try{(0,Wr.debugLog)(this.config.debug||!1,"creating onramp payment intent");let z=await this.publicApiClient.post("/sdk/public/payments/intents",{amount:e.amount,symbol:e.symbol,ledgerCanisterId:t,metadata:e.metadata||{},onrampPayment:!0,widgetParams:e.widgetParams||{},amountUsd:typeof F=="string"?F:F?.toFixed(2)});k=z?.paymentIntentId||z?.paymentIntent?.id||null,C=z?.paymentIntentCode??null;let R=z?.onramp||{};return{transactionId:0,status:"pending",amount:e.amount,recipientCanister:this.icpayCanisterId,timestamp:new Date,metadata:{paymentIntentId:k,paymentIntentCode:C,onramp:R}}}catch(z){let R=new Mt.IcpayError({code:Mt.ICPAY_ERROR_CODES.API_ERROR,message:"Failed to create onramp payment intent",details:z,retryable:!0,userAction:"Try again"});throw this.emitError(R),R}}let c=typeof e.amount=="string"?e.amount:e.amount!=null?String(e.amount):void 0;if(!c&&e.amountUsd!=null)try{c=(await this.calculateTokenAmountFromUSD({usdAmount:Number(e.amountUsd),ledgerCanisterId:t})).tokenAmountDecimals}catch{}if(!c){let F=new Mt.IcpayError({code:Mt.ICPAY_ERROR_CODES.API_ERROR,message:"Either amount or amountUsd must be provided"});throw this.emitError(F),F}let l=BigInt(c);(0,Wr.debugLog)(this.config.debug||!1,"checking balance",{ledgerCanisterId:t,requiredAmount:l.toString()});let u=(F,k=8,C="")=>{let z=BigInt(10**k),R=F/z,m=(F%z).toString().padStart(k,"0").replace(/0+$/,"");return`${R}${m?"."+m:""} ${C}`.trim()};try{let F=await this.getLedgerBalance(t);if(F<l){let k=u(l,8,"tokens"),C=u(F,8,"tokens");throw(0,Mt.createBalanceError)(k,C,{required:l,available:F,ledgerCanisterId:t})}(0,Wr.debugLog)(this.config.debug||!1,"balance ok",{actualBalance:F.toString()})}catch{throw new Mt.IcpayError({code:"INSUFFICIENT_BALANCE",message:"Insufficient balance",details:{required:l,available:0}})}let h=null,p=null,w=typeof e.amount=="string"?e.amount:e.amount!=null?String(e.amount):void 0;try{(0,Wr.debugLog)(this.config.debug||!1,"creating payment intent");let F=this.connectedWallet?.owner||this.connectedWallet?.principal?.toString();if(!F)throw new Mt.IcpayError({code:Mt.ICPAY_ERROR_CODES.WALLET_NOT_CONNECTED,message:"Wallet must be connected to create payment intent",details:{connectedWallet:this.connectedWallet},retryable:!1,userAction:"Connect your wallet first"});let k=await this.publicApiClient.post("/sdk/public/payments/intents",{amount:e.amount,symbol:e.symbol,ledgerCanisterId:t,expectedSenderPrincipal:F,metadata:e.metadata||{},amountUsd:e.amountUsd});h=k?.paymentIntent?.id||null,p=k?.paymentIntent?.intentCode??null,w=k?.paymentIntent?.amount||w,(0,Wr.debugLog)(this.config.debug||!1,"payment intent created",{paymentIntentId:h,paymentIntentCode:p,expectedSenderPrincipal:F,resolvedAmountStr:w}),h&&this.emit("icpay-sdk-transaction-created",{paymentIntentId:h,amount:w,ledgerCanisterId:t,expectedSenderPrincipal:F})}catch(F){let k=new Mt.IcpayError({code:Mt.ICPAY_ERROR_CODES.API_ERROR,message:"Failed to create payment intent. Please try again.",details:F,retryable:!0,userAction:"Try again"});throw this.emitError(k),k}if(!w){let F=new Mt.IcpayError({code:Mt.ICPAY_ERROR_CODES.API_ERROR,message:"Payment intent did not return amount"});throw this.emitError(F),F}let y=BigInt(w);try{let F=parseInt(n);!isNaN(F)&&p!=null&&(o=this.createPackedMemo(F,Number(p)),(0,Wr.debugLog)(this.config.debug||!1,"built packed memo",{accountCanisterId:F,paymentIntentCode:p})),(0,Wr.debugLog)(this.config.debug||!1,"memo",{memo:o})}catch{}let v;t===this.icpLedgerCanisterId?((0,Wr.debugLog)(this.config.debug||!1,"sending ICRC-1 transfer (ICP)"),v=await this.sendFundsToLedger(t,i,y,o,s)):((0,Wr.debugLog)(this.config.debug||!1,"sending ICRC-1 transfer"),v=await this.sendFundsToLedger(t,i,y,o,s));let S=v?.Ok?.toString()||v?.blockIndex?.toString()||`temp-${Date.now()}`;(0,Wr.debugLog)(this.config.debug||!1,"transfer result",{blockIndex:S});let N,O=null;try{(0,Wr.debugLog)(this.config.debug||!1,"notifying canister about ledger tx");let F=await this.notifyLedgerTransaction(this.icpayCanisterId,t,BigInt(S));typeof F=="string"?N=parseInt(F,10):(N=parseInt(F.id,10),O=F),(0,Wr.debugLog)(this.config.debug||!1,"canister notified",{canisterTransactionId:N})}catch{N=parseInt(S,10),(0,Wr.debugLog)(this.config.debug||!1,"notify failed, using blockIndex as tx id",{canisterTransactionId:N})}let L=null;if(O&&O.status)L={status:O.status};else try{(0,Wr.debugLog)(this.config.debug||!1,"polling transaction status (public)",{canisterTransactionId:N}),L=await this.pollTransactionStatus(this.icpayCanisterId,N,n,Number(S),2e3,30),(0,Wr.debugLog)(this.config.debug||!1,"poll done",{status:L})}catch{L={status:"pending"},(0,Wr.debugLog)(this.config.debug||!1,"poll failed, falling back to pending")}let j="pending";if(L&&typeof L=="object"&&L.status)if(typeof L.status=="object"){let F=Object.keys(L.status);if(F.length>0){let k=F[0].toLowerCase();(k==="completed"||k==="failed")&&(j=k)}}else{let F=L.status;(F==="completed"||F==="failed")&&(j=F)}let q;if(this.config.awaitServerNotification){q=await this.performNotifyPaymentIntent({paymentIntentId:h,canisterTransactionId:N?.toString(),maxAttempts:99999,delayMs:1e3});let F=q?.payment?.status||q?.status;if(typeof F=="string"){let k=F.toLowerCase();k==="completed"||k==="succeeded"?j="completed":k==="failed"||k==="canceled"||k==="cancelled"?j="failed":j="pending"}}else this.performNotifyPaymentIntent({paymentIntentId:h,canisterTransactionId:N?.toString(),maxAttempts:5,delayMs:1e3}).then(F=>{this.emitMethodSuccess("sendFunds.notifyApi",{paymentIntentId:h,canisterTransactionId:N,data:F})}).catch(F=>{this.emitMethodError("sendFunds.notifyApi",F)});let D={transactionId:N,status:j,amount:y.toString(),recipientCanister:t,timestamp:new Date,description:"Fund transfer",metadata:e.metadata,payment:q};if((0,Wr.debugLog)(this.config.debug||!1,"sendFunds done",D),j==="completed"){let F=q?.payment?.requestedAmount||null,k=q?.payment?.paidAmount||null;q?.payment?.status==="mismatched"?(this.emit("icpay-sdk-transaction-mismatched",{...D,requestedAmount:F,paidAmount:k}),this.emit("icpay-sdk-transaction-updated",{...D,status:"mismatched",requestedAmount:F,paidAmount:k})):this.emit("icpay-sdk-transaction-completed",D)}else j==="failed"?this.emit("icpay-sdk-transaction-failed",D):this.emit("icpay-sdk-transaction-updated",D);return this.emitMethodSuccess("sendFunds",D),D}catch(t){if(t instanceof Mt.IcpayError)throw this.emitMethodError("sendFunds",t),t;let n=new Mt.IcpayError({code:"TRANSACTION_FAILED",message:"Failed to send funds",details:t});throw this.emitMethodError("sendFunds",n),n}}async disconnectWallet(){return await this.wallet.disconnect()}isWalletConnected(){return this.wallet.isConnected()}getConnectedWalletProvider(){return this.wallet.getConnectedProvider()}async pollTransactionStatus(e,t,n,i,s=2e3,o=30){this.emitMethodStart("pollTransactionStatus",{canisterId:e,transactionId:t,accountCanisterId:n,indexReceived:i,intervalMs:s,maxAttempts:o});for(let c=0;c<o;c++)try{let l=await this.getTransactionStatusPublic(e,t,i,n);if(Array.isArray(l)&&l.length>0){let u=l[0];if(u&&typeof u=="object"&&u.status){let h=u.status;if(this.isTransactionCompleted(h))return u}}if(l&&l.status&&this.isTransactionCompleted(l.status))return this.emitMethodSuccess("pollTransactionStatus",{attempt:c,status:l}),l;if(l&&typeof l=="object"&&(l.Ok||l.Err))return this.emitMethodSuccess("pollTransactionStatus",{attempt:c,status:l}),l;c<o-1&&await new Promise(u=>setTimeout(u,s))}catch(l){c===o-1&&this.emitMethodError("pollTransactionStatus",l),c<o-1&&await new Promise(u=>setTimeout(u,s))}let a=new Error("Transaction status polling timed out");throw this.emitMethodError("pollTransactionStatus",a),a}isTransactionCompleted(e){if(!e)return!1;if(typeof e=="object"){let t=Object.keys(e);if(t.length>0)return t[0].toLowerCase()==="completed"}return typeof e=="string"?e.toLowerCase()==="completed":!1}async notifyLedgerTransaction(e,t,n){this.emitMethodStart("notifyLedgerTransaction",{canisterId:e,ledgerCanisterId:t,blockIndex:n.toString()});let i=new Hh.HttpAgent({host:this.icHost}),o=await Hh.Actor.createActor(L9.idlFactory,{agent:i,canisterId:e}).notify_ledger_transaction({ledger_canister_id:t,block_index:n});if(o&&o.Ok)return this.emitMethodSuccess("notifyLedgerTransaction",{result:o.Ok}),o.Ok;if(o&&o.Err){let a=new Error(o.Err);throw this.emitMethodError("notifyLedgerTransaction",a),a}else{let a=new Error("Unexpected canister notify result");throw this.emitMethodError("notifyLedgerTransaction",a),a}}async getTransactionStatusPublic(e,t,n,i){this.emitMethodStart("getTransactionStatusPublic",{canisterId:e,canisterTransactionId:t,indexReceived:n,accountCanisterId:i});let s=new Hh.HttpAgent({host:this.icHost}),o=Hh.Actor.createActor(L9.idlFactory,{agent:s,canisterId:e}),a=parseInt(i),l=await o.get_transaction_status_public(a,BigInt(t),[n])||{status:"pending"};return this.emitMethodSuccess("getTransactionStatusPublic",l),l}async sendFundsToLedger(e,t,n,i,s){this.emitMethodStart("sendFundsToLedger",{ledgerCanisterId:e,toPrincipal:t,amount:n.toString(),hasMemo:!!i});let o;if(this.actorProvider)o=this.actorProvider(e,tU.idlFactory);else{let c=new Error("actorProvider is required for sending funds");throw this.emitMethodError("sendFundsToLedger",c),c}let a=await o.icrc1_transfer({to:{owner:rU.Principal.fromText(t),subaccount:[]},amount:n,fee:[],memo:i?[i]:[],from_subaccount:[],created_at_time:[]});return this.emitMethodSuccess("sendFundsToLedger",a),a}async getTransactionByFilter(e){this.emitMethodStart("getTransactionByFilter",{transactionId:e});try{this.icpayCanisterId||await this.fetchAccountInfo();let t=new Hh.HttpAgent({host:this.icHost}),n=Hh.Actor.createActor(L9.idlFactory,{agent:t,canisterId:this.icpayCanisterId}),i=BigInt(e),s=await n.get_transactions({account_canister_id:[],ledger_canister_id:[],from_timestamp:[],to_timestamp:[],from_id:[],status:[],limit:[],offset:[]});if(s&&s.transactions){let o=s.transactions.find(a=>a.id.toString()===e.toString());return this.emitMethodSuccess("getTransactionByFilter",{found:!!o}),o}return this.emitMethodSuccess("getTransactionByFilter",{found:!1}),null}catch(t){throw this.emitMethodError("getTransactionByFilter",t),t}}async getAllLedgerBalances(){this.emitMethodStart("getAllLedgerBalances");try{if(!this.isWalletConnected())throw new Mt.IcpayError({code:"WALLET_NOT_CONNECTED",message:"Wallet must be connected to fetch balances"});let e=await this.getVerifiedLedgers(),t=[],n=0;for(let s of e)try{let o=await this.getLedgerBalance(s.canisterId),a=this.formatBalance(o.toString(),s.decimals),c={ledgerId:s.id,ledgerName:s.name,ledgerSymbol:s.symbol,canisterId:s.canisterId,balance:o.toString(),formattedBalance:a,decimals:s.decimals,currentPrice:s.currentPrice||void 0,lastPriceUpdate:s.lastPriceUpdate?new Date(s.lastPriceUpdate):void 0,lastUpdated:new Date};if(t.push(c),s.currentPrice&&o>0){let l=parseFloat(a);n+=l*s.currentPrice}}catch(o){this.emit("icpay-sdk-method-error",{name:"getAllLedgerBalances.getLedgerBalance",error:o,ledgerSymbol:s.symbol,ledgerCanisterId:s.canisterId})}let i={balances:t,totalBalancesUSD:n>0?n:void 0,lastUpdated:new Date};return this.emitMethodSuccess("getAllLedgerBalances",{count:t.length,totalUSD:i.totalBalancesUSD}),i}catch(e){let t=new Mt.IcpayError({code:"BALANCES_FETCH_FAILED",message:"Failed to fetch all ledger balances",details:e});throw this.emitMethodError("getAllLedgerBalances",t),t}}async getSingleLedgerBalance(e){this.emitMethodStart("getSingleLedgerBalance",{ledgerCanisterId:e});try{if(!this.isWalletConnected())throw new Mt.IcpayError({code:"WALLET_NOT_CONNECTED",message:"Wallet must be connected to fetch balance"});let n=(await this.getVerifiedLedgers()).find(a=>a.canisterId===e);if(!n)throw new Mt.IcpayError({code:"LEDGER_NOT_FOUND",message:`Ledger with canister ID ${e} not found or not verified`});let i=await this.getLedgerBalance(e),s=this.formatBalance(i.toString(),n.decimals),o={ledgerId:n.id,ledgerName:n.name,ledgerSymbol:n.symbol,canisterId:n.canisterId,balance:i.toString(),formattedBalance:s,decimals:n.decimals,currentPrice:n.currentPrice||void 0,lastPriceUpdate:n.lastPriceUpdate?new Date(n.lastPriceUpdate):void 0,lastUpdated:new Date};return this.emitMethodSuccess("getSingleLedgerBalance",{ledgerCanisterId:e,balance:o.balance}),o}catch(t){let n=new Mt.IcpayError({code:"SINGLE_BALANCE_FETCH_FAILED",message:`Failed to fetch balance for ledger ${e}`,details:t});throw this.emitMethodError("getSingleLedgerBalance",n),n}}async calculateTokenAmountFromUSD(e){this.emitMethodStart("calculateTokenAmountFromUSD",{usdAmount:e.usdAmount,ledgerCanisterId:e.ledgerCanisterId,ledgerSymbol:e.ledgerSymbol});try{let{usdAmount:t,ledgerCanisterId:n,ledgerSymbol:i}=e;if(t<=0)throw new Mt.IcpayError({code:"INVALID_USD_AMOUNT",message:"USD amount must be greater than 0"});let o=(await this.getVerifiedLedgers()).find(u=>u.canisterId===n||i&&u.symbol===i);if(!o)throw new Mt.IcpayError({code:"LEDGER_NOT_FOUND",message:`Ledger not found for canister ID ${n} or symbol ${i}`});if(!o.currentPrice||o.currentPrice<=0)throw new Mt.IcpayError({code:"PRICE_NOT_AVAILABLE",message:`Current price not available for ledger ${o.symbol}`});let a=t/o.currentPrice,c=Math.floor(a*Math.pow(10,o.decimals)).toString(),l={usdAmount:t,ledgerCanisterId:o.canisterId,ledgerSymbol:o.symbol,ledgerName:o.name,currentPrice:o.currentPrice,priceTimestamp:o.lastPriceUpdate?new Date(o.lastPriceUpdate):new Date,tokenAmountHuman:a.toFixed(o.decimals),tokenAmountDecimals:c,decimals:o.decimals};return this.emitMethodSuccess("calculateTokenAmountFromUSD",{ledgerCanisterId:l.ledgerCanisterId,tokenAmountDecimals:c}),l}catch(t){let n=new Mt.IcpayError({code:"PRICE_CALCULATION_FAILED",message:"Failed to calculate token amount from USD",details:t});throw this.emitMethodError("calculateTokenAmountFromUSD",n),n}}async getLedgerInfo(e){this.emitMethodStart("getLedgerInfo",{ledgerCanisterId:e});try{let t=await this.publicApiClient.get(`/sdk/public/ledgers/${e}`),n={id:t.id,name:t.name,symbol:t.symbol,canisterId:t.canisterId,standard:t.standard,decimals:t.decimals,logoUrl:t.logoUrl??null,verified:t.verified,fee:t.fee??null,network:t.network,description:t.description??null,lastBlockIndex:t.lastBlockIndex??null,coingeckoId:t.coingeckoId??null,currentPrice:t.currentPrice??null,priceFetchMethod:t.priceFetchMethod??null,lastPriceUpdate:t.lastPriceUpdate??null,createdAt:t.createdAt,updatedAt:t.updatedAt};return this.emitMethodSuccess("getLedgerInfo",{ledgerCanisterId:e}),n}catch(t){let n=new Mt.IcpayError({code:"LEDGER_INFO_FETCH_FAILED",message:`Failed to fetch ledger info for ${e}`,details:t});throw this.emitMethodError("getLedgerInfo",n),n}}async sendFundsUsd(e){this.emitMethodStart("sendFundsUsd",{request:e});try{let t=typeof e.usdAmount=="string"?parseFloat(e.usdAmount):e.usdAmount,n=e.ledgerCanisterId;if(!n&&e.symbol&&(n=await this.getLedgerCanisterIdBySymbol(e.symbol)),!n){let o=new Mt.IcpayError({code:Mt.ICPAY_ERROR_CODES.INVALID_CONFIG,message:"Either ledgerCanisterId or symbol must be provided",details:{request:e}});throw this.emitMethodError("sendFundsUsd",o),o}let i={ledgerCanisterId:n,symbol:e.symbol,amountUsd:t,accountCanisterId:e.accountCanisterId,metadata:e.metadata,onrampPayment:e.onrampPayment,widgetParams:e.widgetParams},s=await this.sendFunds(i);return this.emitMethodSuccess("sendFundsUsd",s),s}catch(t){if(t instanceof Mt.IcpayError)throw this.emitMethodError("sendFundsUsd",t),t;let n=new Mt.IcpayError({code:"SEND_FUNDS_USD_FAILED",message:"Failed to send funds from USD",details:t});throw this.emitMethodError("sendFundsUsd",n),n}}notifyPaymentIntentOnRamp(e){let t=e.paymentIntentId,n=Math.max(1e3,e.intervalMs??5e3),i=e.orderId,s=null,o=null;try{this.emitMethodSuccess("notifyLedgerTransaction",{paymentIntentId:t})}catch{}let a=async()=>{let c=await this.performNotifyPaymentIntent({paymentIntentId:t,orderId:i}),l=(c?.payment?.status||"").toLowerCase();l&&l!==o&&(o=l,l==="completed"||l==="succeeded"?this.dispatchEvent(new CustomEvent("icpay-sdk-transaction-completed",{detail:{id:t,status:l}})):l==="mismatched"?(this.dispatchEvent(new CustomEvent("icpay-sdk-transaction-mismatched",{detail:{id:t,status:l,payment:c?.payment}})),this.dispatchEvent(new CustomEvent("icpay-sdk-transaction-updated",{detail:{id:t,status:l}}))):this.dispatchEvent(new CustomEvent("icpay-sdk-transaction-updated",{detail:{id:t,status:l}})))};return a().catch(()=>{}),s=setInterval(a,n),{stop:()=>{s&&(clearInterval(s),s=null)}}}async performNotifyPaymentIntent(e){let t=this.publicApiClient,n="/sdk/public/payments/notify",i=e.maxAttempts??1,s=e.delayMs??0;for(let o=1;o<=i;o++)try{(0,Wr.debugLog)(this.config.debug||!1,"notify payment intent",{attempt:o,notifyPath:n,paymentIntentId:e.paymentIntentId,canisterTxId:e.canisterTransactionId});let a={paymentIntentId:e.paymentIntentId};e.canisterTransactionId&&(a.canisterTxId=e.canisterTransactionId),e.orderId&&(a.orderId=e.orderId);let c=await t.post(n,a);if(o===i)return c;let l=c?.payment?.status||c?.status||"";if(typeof l=="string"){let u=l.toLowerCase();if(u==="completed"||u==="succeeded")return c}s>0&&await new Promise(u=>setTimeout(u,s))}catch(a){let c=a?.response?.status,l=a?.response?.data;(0,Wr.debugLog)(this.config.debug||!1,"notify payment intent error",{attempt:o,status:c,data:l}),o<i&&s>0&&await new Promise(u=>setTimeout(u,s))}}async getAllLedgersWithPrices(){this.emitMethodStart("getAllLedgersWithPrices");try{let t=(await this.publicApiClient.get("/sdk/public/ledgers/all-with-prices")).map(n=>({id:n.id,name:n.name,symbol:n.symbol,canisterId:n.canisterId,standard:n.standard,decimals:n.decimals,logoUrl:n.logoUrl??null,verified:n.verified,fee:n.fee??null,network:n.network,description:n.description??null,lastBlockIndex:n.lastBlockIndex??null,coingeckoId:n.coingeckoId??null,currentPrice:n.currentPrice??null,priceFetchMethod:n.priceFetchMethod??null,lastPriceUpdate:n.lastPriceUpdate??null,createdAt:n.createdAt,updatedAt:n.updatedAt}));return this.emitMethodSuccess("getAllLedgersWithPrices",{count:t.length}),t}catch(e){let t=new Mt.IcpayError({code:"LEDGERS_WITH_PRICES_FETCH_FAILED",message:"Failed to fetch ledgers with price information",details:e});throw this.emitMethodError("getAllLedgersWithPrices",t),t}}formatBalance(e,t){let n=parseFloat(e),i=Math.pow(10,t),s=Math.floor(n/i),a=(n%i).toString().padStart(t,"0").replace(/0+$/,"");return`${s}${a?"."+a:""}`}};eo.Icpay=KA;iU(eU(),eo);var xie=ew();Object.defineProperty(eo,"IcpayError",{enumerable:!0,get:function(){return xie.IcpayError}});var Sie=B9();Object.defineProperty(eo,"IcpayWallet",{enumerable:!0,get:function(){return Sie.IcpayWallet}});iU(g8(),eo);eo.default=KA});var Bie,m$e,aU,cU,lU,oU,ry,Rie,kie,uU,hU=ye(()=>{"use strict";_a();_a();Zi();Bie=(r=>(r[r.FractionalMoreThan8Decimals=0]="FractionalMoreThan8Decimals",r[r.InvalidFormat=1]="InvalidFormat",r[r.FractionalTooManyDecimals=2]="FractionalTooManyDecimals",r))(Bie||{}),m$e=BigInt(1e8),aU=r=>new Uint8Array(r),cU=r=>Array.from(r).map(e=>e.charCodeAt(0)),lU=r=>(r instanceof Uint8Array||(r=Uint8Array.from(r)),r.reduce((e,t)=>e+t.toString(16).padStart(2,"0"),"")),oU="abcdefghijklmnopqrstuvwxyz234567",ry=Object.create(null);for(let r=0;r<oU.length;r++)ry[oU[r]]=r;ry[0]=ry.o;ry[1]=ry.i;Rie=new Uint32Array([0,1996959894,3993919788,2567524794,124634137,1886057615,3915621685,2657392035,249268274,2044508324,3772115230,2547177864,162941995,2125561021,3887607047,2428444049,498536548,1789927666,4089016648,2227061214,450548861,1843258603,4107580753,2211677639,325883990,1684777152,4251122042,2321926636,335633487,1661365465,4195302755,2366115317,997073096,1281953886,3579855332,2724688242,1006888145,1258607687,3524101629,2768942443,901097722,1119000684,3686517206,2898065728,853044451,1172266101,3705015759,2882616665,651767980,1373503546,3369554304,3218104598,565507253,1454621731,3485111705,3099436303,671266974,1594198024,3322730930,2970347812,795835527,1483230225,3244367275,3060149565,1994146192,31158534,2563907772,4023717930,1907459465,112637215,2680153253,3904427059,2013776290,251722036,2517215374,3775830040,2137656763,141376813,2439277719,3865271297,1802195444,476864866,2238001368,4066508878,1812370925,453092731,2181625025,4111451223,1706088902,314042704,2344532202,4240017532,1658658271,366619977,2362670323,4224994405,1303535960,984961486,2747007092,3569037538,1256170817,1037604311,2765210733,3554079995,1131014506,879679996,2909243462,3663771856,1141124467,855842277,2852801631,3708648649,1342533948,654459306,3188396048,3373015174,1466479909,544179635,3110523913,3462522015,1591671054,702138776,2966460450,3352799412,1504918807,783551873,3082640443,3233442989,3988292384,2596254646,62317068,1957810842,3939845945,2647816111,81470997,1943803523,3814918930,2489596804,225274430,2053790376,3826175755,2466906013,167816743,2097651377,4027552580,2265490386,503444072,1762050814,4150417245,2154129355,426522225,1852507879,4275313526,2312317920,282753626,1742555852,4189708143,2394877945,397917763,1622183637,3604390888,2714866558,953729732,1340076626,3518719985,2797360999,1068828381,1219638859,3624741850,2936675148,906185462,1090812512,3747672003,2825379669,829329135,1181335161,3412177804,3160834842,628085408,1382605366,3423369109,3138078467,570562233,1426400815,3317316542,2998733608,733239954,1555261956,3268935591,3050360625,752459403,1541320221,2607071920,3965973030,1969922972,40735498,2617837225,3943577151,1913087877,83908371,2512341634,3803740692,2075208622,213261112,2463272603,3855990285,2094854071,198958881,2262029012,4057260610,1759359992,534414190,2176718541,4139329115,1873836001,414664567,2282248934,4279200368,1711684554,285281116,2405801727,4167216745,1634467795,376229701,2685067896,3608007406,1308918612,956543938,2808555105,3495958263,1231636301,1047427035,2932959818,3654703836,1088359270,936918e3,2847714899,3736837829,1202900863,817233897,3183342108,3401237130,1404277552,615818150,3134207493,3453421203,1423857449,601450431,3009837614,3294710456,1567103746,711928724,3020668471,3272380065,1510334235,755167117]),kie=r=>{let e=-1;for(let t=0;t<r.length;t++){let n=(r[t]^e)&255;e=Rie[n]^e>>>8}return(e^-1)>>>0},uU=r=>{let e=new ArrayBuffer(4);return new DataView(e).setUint32(0,kie(r),!1),new Uint8Array(e)}});function Lie(){if(!GA&&(GA=typeof crypto<"u"&&crypto.getRandomValues&&crypto.getRandomValues.bind(crypto),!GA))throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");return GA(Uie)}function jie(r,e=0){return es[r[e+0]]+es[r[e+1]]+es[r[e+2]]+es[r[e+3]]+"-"+es[r[e+4]]+es[r[e+5]]+"-"+es[r[e+6]]+es[r[e+7]]+"-"+es[r[e+8]]+es[r[e+9]]+"-"+es[r[e+10]]+es[r[e+11]]+es[r[e+12]]+es[r[e+13]]+es[r[e+14]]+es[r[e+15]]}function YA(r,e,t){if(dU.randomUUID&&!r)return dU.randomUUID();r=r||{};let n=r.random||(r.rng||Lie)();return n[6]=n[6]&15|64,n[8]=n[8]&63|128,jie(n)}var GA,Uie,es,zie,dU,H9=ye(()=>{"use strict";Uie=new Uint8Array(16);es=[];for(let r=0;r<256;++r)es.push((r+256).toString(16).slice(1));zie=typeof crypto<"u"&&crypto.randomUUID&&crypto.randomUUID.bind(crypto),dU={randomUUID:zie}});var wU={};Re(wU,{StandardSolflareMetaMaskWalletAccount:()=>n4,default:()=>i4});function Die(){if(fU)return F9;fU=1;function r(e){if(e.length>=255)throw new TypeError("Alphabet too long");for(var t=new Uint8Array(256),n=0;n<t.length;n++)t[n]=255;for(var i=0;i<e.length;i++){var s=e.charAt(i),o=s.charCodeAt(0);if(t[o]!==255)throw new TypeError(s+" is ambiguous");t[o]=i}var a=e.length,c=e.charAt(0),l=Math.log(a)/Math.log(256),u=Math.log(256)/Math.log(a);function h(y){if(y instanceof Uint8Array||(ArrayBuffer.isView(y)?y=new Uint8Array(y.buffer,y.byteOffset,y.byteLength):Array.isArray(y)&&(y=Uint8Array.from(y))),!(y instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(y.length===0)return"";for(var v=0,S=0,N=0,O=y.length;N!==O&&y[N]===0;)N++,v++;for(var L=(O-N)*u+1>>>0,j=new Uint8Array(L);N!==O;){for(var q=y[N],D=0,F=L-1;(q!==0||D<S)&&F!==-1;F--,D++)q+=256*j[F]>>>0,j[F]=q%a>>>0,q=q/a>>>0;if(q!==0)throw new Error("Non-zero carry");S=D,N++}for(var k=L-S;k!==L&&j[k]===0;)k++;for(var C=c.repeat(v);k<L;++k)C+=e.charAt(j[k]);return C}function p(y){if(typeof y!="string")throw new TypeError("Expected String");if(y.length===0)return new Uint8Array;for(var v=0,S=0,N=0;y[v]===c;)S++,v++;for(var O=(y.length-v)*l+1>>>0,L=new Uint8Array(O);y[v];){var j=y.charCodeAt(v);if(j>255)return;var q=t[j];if(q===255)return;for(var D=0,F=O-1;(q!==0||D<N)&&F!==-1;F--,D++)q+=a*L[F]>>>0,L[F]=q%256>>>0,q=q/256>>>0;if(q!==0)throw new Error("Non-zero carry");N=D,v++}for(var k=O-N;k!==O&&L[k]===0;)k++;for(var C=new Uint8Array(S+(O-k)),z=S;k!==O;)C[z++]=L[k++];return C}function w(y){var v=p(y);if(v)return v;throw new Error("Non-base"+a+" character")}return{encode:h,decodeUnsafe:p,decode:w}}return F9=r,F9}function qie(){return pU||(pU=1,$9=Die()("123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz")),$9}function Q9(r){return r.version===void 0}function W9(r){return Q9(r)?r.serialize({verifySignatures:!1,requireAllSignatures:!1}):r.serialize()}function V9(r){return gU(this,void 0,void 0,function*(){try{return yield r.request({method:"wallet_getSnaps"}),!0}catch{return!1}})}function Fie(){return gU(this,void 0,void 0,function*(){try{let r=window.ethereum;if(!r)return null;if(r.providers&&Array.isArray(r.providers)){let e=r.providers;for(let t of e)if(yield V9(t))return t}if(r.detected&&Array.isArray(r.detected)){let e=r.detected;for(let t of e)if(yield V9(t))return t}return(yield V9(r))?r:null}catch(r){return console.error(r),null}})}function K9(r){return mU.includes(r)}var F9,fU,$9,pU,Hie,fl,gU,$ie,Wie,Vie,Kie,mU,lg,ug,ZA,XA,JA,e4,t4,r4,Qie,Gie,n4,Sc,i4,yU=ye(()=>{"use strict";hg();H9();Hie=qie(),fl=co(Hie);gU=function(r,e,t,n){function i(s){return s instanceof t?s:new t(function(o){o(s)})}return new(t||(t=Promise))(function(s,o){function a(u){try{l(n.next(u))}catch(h){o(h)}}function c(u){try{l(n.throw(u))}catch(h){o(h)}}function l(u){u.done?s(u.value):i(u.value).then(a,c)}l((n=n.apply(r,e||[])).next())})};$ie="solana:mainnet",Wie="solana:devnet",Vie="solana:testnet",Kie="solana:localnet",mU=[$ie,Wie,Vie,Kie];lg=function(r,e,t,n){if(t==="a"&&!n)throw new TypeError("Private accessor was defined without a getter");if(typeof e=="function"?r!==e||!n:!e.has(r))throw new TypeError("Cannot read private member from an object whose class did not declare it");return t==="m"?n:t==="a"?n.call(r):n?n.value:e.get(r)},ug=function(r,e,t,n,i){if(n==="m")throw new TypeError("Private method is not writable");if(n==="a"&&!i)throw new TypeError("Private accessor was defined without a setter");if(typeof e=="function"?r!==e||!i:!e.has(r))throw new TypeError("Cannot write private member to an object whose class did not declare it");return n==="a"?i.call(r,t):i?i.value=t:e.set(r,t),t},Qie=mU,Gie=[G9,Z9,Y9],n4=class r{get address(){return lg(this,ZA,"f")}get publicKey(){return lg(this,XA,"f").slice()}get chains(){return lg(this,JA,"f").slice()}get features(){return lg(this,e4,"f").slice()}get label(){return lg(this,t4,"f")}get icon(){return lg(this,r4,"f")}constructor({address:e,publicKey:t,label:n,icon:i}){ZA.set(this,void 0),XA.set(this,void 0),JA.set(this,void 0),e4.set(this,void 0),t4.set(this,void 0),r4.set(this,void 0),new.target===r&&Object.freeze(this),ug(this,ZA,e,"f"),ug(this,XA,t,"f"),ug(this,JA,Qie,"f"),ug(this,e4,Gie,"f"),ug(this,t4,n,"f"),ug(this,r4,i,"f")}};ZA=new WeakMap,XA=new WeakMap,JA=new WeakMap,e4=new WeakMap,t4=new WeakMap,r4=new WeakMap;Sc=function(r,e,t,n){function i(s){return s instanceof t?s:new t(function(o){o(s)})}return new(t||(t=Promise))(function(s,o){function a(u){try{l(n.next(u))}catch(h){o(h)}}function c(u){try{l(n.throw(u))}catch(h){o(h)}}function l(u){u.done?s(u.value):i(u.value).then(a,c)}l((n=n.apply(r,e||[])).next())})},i4=class r extends Cu{constructor(e){super(),this._network="mainnet-beta",this._iframeParams={},this._element=null,this._iframe=null,this._publicKey=null,this._account=null,this._isConnected=!1,this._connectHandler=null,this._messageHandlers={},this._handleEvent=t=>{var n,i;switch(t.type){case"connect":{this._collapseIframe(),!((n=t.data)===null||n===void 0)&&n.publicKey?(this._publicKey=t.data.publicKey,this._isConnected=!0,this._connectHandler&&(this._connectHandler.resolve(),this._connectHandler=null),this._connected()):(this._connectHandler&&(this._connectHandler.reject(),this._connectHandler=null),this._disconnected());return}case"disconnect":{this._connectHandler&&(this._connectHandler.reject(),this._connectHandler=null),this._disconnected();return}case"accountChanged":{!((i=t.data)===null||i===void 0)&&i.publicKey?(this._publicKey=t.data.publicKey,this.emit("accountChanged",this.publicKey),this._standardConnected()):(this.emit("accountChanged",void 0),this._standardDisconnected());return}default:return}},this._handleResize=t=>{t.resizeMode==="full"?t.params.mode==="fullscreen"?this._expandIframe():t.params.mode==="hide"&&this._collapseIframe():t.resizeMode==="coordinates"&&this._resizeIframe(t.params)},this._handleMessage=t=>{var n;if(((n=t.data)===null||n===void 0?void 0:n.channel)!=="solflareIframeToWalletAdapter")return;let i=t.data.data||{};if(i.type==="event")this._handleEvent(i.event);else if(i.type==="resize")this._handleResize(i);else if(i.type==="response"&&this._messageHandlers[i.id]){let{resolve:s,reject:o}=this._messageHandlers[i.id];delete this._messageHandlers[i.id],i.error?o(i.error):s(i.result)}},this._removeElement=()=>{this._element&&(this._element.remove(),this._element=null)},this._removeDanglingElements=()=>{let t=document.getElementsByClassName("solflare-metamask-wallet-adapter-iframe");for(let n of t)n.parentElement&&n.remove()},this._injectElement=()=>{this._removeElement(),this._removeDanglingElements();let t=Object.assign(Object.assign({},this._iframeParams),{mm:!0,v:1,cluster:this._network||"mainnet-beta",origin:window.location.origin||"",title:document.title||""}),n=Object.keys(t).map(s=>`${s}=${encodeURIComponent(t[s])}`).join("&"),i=`${r.IFRAME_URL}?${n}`;this._element=document.createElement("div"),this._element.className="solflare-metamask-wallet-adapter-iframe",this._element.innerHTML=`
55
55
  <iframe src='${i}' style='position: fixed; top: 0; bottom: 0; left: 0; right: 0; width: 100%; height: 100%; border: none; border-radius: 0; z-index: 99999; color-scheme: auto;' allowtransparency='true'></iframe>
56
56
  `,document.body.appendChild(this._element),this._iframe=this._element.querySelector("iframe"),window.addEventListener("message",this._handleMessage,!1)},this._collapseIframe=()=>{this._iframe&&(this._iframe.style.top="",this._iframe.style.right="",this._iframe.style.height="2px",this._iframe.style.width="2px")},this._expandIframe=()=>{this._iframe&&(this._iframe.style.top="0px",this._iframe.style.bottom="0px",this._iframe.style.left="0px",this._iframe.style.right="0px",this._iframe.style.width="100%",this._iframe.style.height="100%")},this._resizeIframe=t=>{this._iframe&&(this._iframe.style.top=isFinite(t.top)?`${t.top}px`:"",this._iframe.style.bottom=isFinite(t.bottom)?`${t.bottom}px`:"",this._iframe.style.left=isFinite(t.left)?`${t.left}px`:"",this._iframe.style.right=isFinite(t.right)?`${t.right}px`:"",this._iframe.style.width=isFinite(t.width)?`${t.width}px`:t.width,this._iframe.style.height=isFinite(t.height)?`${t.height}px`:t.height)},this._sendIframeMessage=t=>{if(!this.connected||!this.publicKey)throw new Error("Wallet not connected");return new Promise((n,i)=>{var s,o;let a=YA();this._messageHandlers[a]={resolve:n,reject:i},(o=(s=this._iframe)===null||s===void 0?void 0:s.contentWindow)===null||o===void 0||o.postMessage({channel:"solflareWalletAdapterToIframe",data:Object.assign({id:a},t)},"*")})},this._connected=()=>{this._isConnected=!0,this.emit("connect",this.publicKey),this._standardConnected()},this._disconnected=()=>{this._publicKey=null,this._isConnected=!1,window.removeEventListener("message",this._handleMessage,!1),this._removeElement(),this.emit("disconnect"),this._standardDisconnected()},this._standardConnected=()=>{if(!this.publicKey)return;let t=this.publicKey.toString();(!this._account||this._account.address!==t)&&(this._account=new n4({address:t,publicKey:this.publicKey.toBytes()}),this.emit("standard_change",{accounts:this.standardAccounts}))},this._standardDisconnected=()=>{this._account&&(this._account=null,this.emit("standard_change",{accounts:this.standardAccounts}))},e?.network&&(this._network=e?.network),window.SolflareMetaMaskParams&&(this._iframeParams=Object.assign(Object.assign({},this._iframeParams),window.SolflareMetaMaskParams)),e?.params&&(this._iframeParams=Object.assign(Object.assign({},this._iframeParams),e?.params))}get publicKey(){return this._publicKey?new ht(this._publicKey):null}get standardAccount(){return this._account}get standardAccounts(){return this._account?[this._account]:[]}get isConnected(){return this._isConnected}get connected(){return this.isConnected}get autoApprove(){return!1}connect(){return Sc(this,void 0,void 0,function*(){this.connected||(this._injectElement(),yield new Promise((e,t)=>{this._connectHandler={resolve:e,reject:t}}))})}disconnect(){return Sc(this,void 0,void 0,function*(){yield this._sendIframeMessage({method:"disconnect"}),this._disconnected()})}signTransaction(e){var t;return Sc(this,void 0,void 0,function*(){if(!this.connected||!this.publicKey)throw new Error("Wallet not connected");try{let n=W9(e),i=yield this._sendIframeMessage({method:"signTransactionV2",params:{transaction:fl.encode(n)}}),{transaction:s}=i;return Q9(e)?ao.from(fl.decode(s)):Go.deserialize(fl.decode(s))}catch(n){throw new Error(((t=n?.toString)===null||t===void 0?void 0:t.call(n))||"Failed to sign transaction")}})}signAllTransactions(e){var t;return Sc(this,void 0,void 0,function*(){if(!this.connected||!this.publicKey)throw new Error("Wallet not connected");try{let n=e.map(s=>W9(s)),{transactions:i}=yield this._sendIframeMessage({method:"signAllTransactionsV2",params:{transactions:n.map(s=>fl.encode(s))}});return i.map((s,o)=>Q9(e[o])?ao.from(fl.decode(s)):Go.deserialize(fl.decode(s)))}catch(n){throw new Error(((t=n?.toString)===null||t===void 0?void 0:t.call(n))||"Failed to sign transactions")}})}signAndSendTransaction(e,t){var n;return Sc(this,void 0,void 0,function*(){if(!this.connected||!this.publicKey)throw new Error("Wallet not connected");try{let i=W9(e),{signature:s}=yield this._sendIframeMessage({method:"signAndSendTransaction",params:{transaction:fl.encode(i),options:t}});return s}catch(i){throw new Error(((n=i?.toString)===null||n===void 0?void 0:n.call(i))||"Failed to sign and send transaction")}})}signMessage(e,t="utf8"){var n;return Sc(this,void 0,void 0,function*(){if(!this.connected||!this.publicKey)throw new Error("Wallet not connected");try{let{signature:i}=yield this._sendIframeMessage({method:"signMessage",params:{data:fl.encode(e),display:t}});return Uint8Array.from(fl.decode(i))}catch(i){throw new Error(((n=i?.toString)===null||n===void 0?void 0:n.call(i))||"Failed to sign message")}})}sign(e,t="utf8"){return Sc(this,void 0,void 0,function*(){return yield this.signMessage(e,t)})}static isSupported(){return Sc(this,void 0,void 0,function*(){return!!(yield Fie())})}standardSignAndSendTransaction(...e){return Sc(this,void 0,void 0,function*(){if(!this.connected)throw new Error("not connected");let t=[];if(e.length===1){let{transaction:n,account:i,chain:s,options:o}=e[0],{minContextSlot:a,preflightCommitment:c,skipPreflight:l,maxRetries:u}=o||{};if(i!==this._account)throw new Error("invalid account");if(!K9(s))throw new Error("invalid chain");let h=yield this.signAndSendTransaction(Go.deserialize(n),{preflightCommitment:c,minContextSlot:a,maxRetries:u,skipPreflight:l});t.push({signature:fl.decode(h)})}else if(e.length>1)for(let n of e)t.push(...yield this.standardSignAndSendTransaction(n));return t})}standardSignTransaction(...e){return Sc(this,void 0,void 0,function*(){if(!this.connected)throw new Error("not connected");let t=[];if(e.length===1){let{transaction:n,account:i,chain:s}=e[0];if(i!==this._account)throw new Error("invalid account");if(s&&!K9(s))throw new Error("invalid chain");let o=yield this.signTransaction(Go.deserialize(n));t.push({signedTransaction:o.serialize()})}else if(e.length>1){let n;for(let o of e){if(o.account!==this._account)throw new Error("invalid account");if(o.chain){if(!K9(o.chain))throw new Error("invalid chain");if(n){if(o.chain!==n)throw new Error("conflicting chain")}else n=o.chain}}let i=e.map(({transaction:o})=>Go.deserialize(o)),s=yield this.signAllTransactions(i);t.push(...s.map(o=>({signedTransaction:o.serialize()})))}return t})}standardSignMessage(...e){return Sc(this,void 0,void 0,function*(){if(!this.connected)throw new Error("not connected");let t=[];if(e.length===1){let{message:n,account:i}=e[0];if(i!==this._account)throw new Error("invalid account");let s=yield this.signMessage(n);t.push({signedMessage:n,signature:s})}else if(e.length>1)for(let n of e)t.push(...yield this.standardSignMessage(n));return t})}};i4.IFRAME_URL="https://widget.solflare.com/"});var SU={};Re(SU,{default:()=>dse});function Zie(){if(bU)return X9;bU=1;function r(e){if(e.length>=255)throw new TypeError("Alphabet too long");for(var t=new Uint8Array(256),n=0;n<t.length;n++)t[n]=255;for(var i=0;i<e.length;i++){var s=e.charAt(i),o=s.charCodeAt(0);if(t[o]!==255)throw new TypeError(s+" is ambiguous");t[o]=i}var a=e.length,c=e.charAt(0),l=Math.log(a)/Math.log(256),u=Math.log(256)/Math.log(a);function h(y){if(y instanceof Uint8Array||(ArrayBuffer.isView(y)?y=new Uint8Array(y.buffer,y.byteOffset,y.byteLength):Array.isArray(y)&&(y=Uint8Array.from(y))),!(y instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(y.length===0)return"";for(var v=0,S=0,N=0,O=y.length;N!==O&&y[N]===0;)N++,v++;for(var L=(O-N)*u+1>>>0,j=new Uint8Array(L);N!==O;){for(var q=y[N],D=0,F=L-1;(q!==0||D<S)&&F!==-1;F--,D++)q+=256*j[F]>>>0,j[F]=q%a>>>0,q=q/a>>>0;if(q!==0)throw new Error("Non-zero carry");S=D,N++}for(var k=L-S;k!==L&&j[k]===0;)k++;for(var C=c.repeat(v);k<L;++k)C+=e.charAt(j[k]);return C}function p(y){if(typeof y!="string")throw new TypeError("Expected String");if(y.length===0)return new Uint8Array;for(var v=0,S=0,N=0;y[v]===c;)S++,v++;for(var O=(y.length-v)*l+1>>>0,L=new Uint8Array(O);y[v];){var j=y.charCodeAt(v);if(j>255)return;var q=t[j];if(q===255)return;for(var D=0,F=O-1;(q!==0||D<N)&&F!==-1;F--,D++)q+=a*L[F]>>>0,L[F]=q%256>>>0,q=q/256>>>0;if(q!==0)throw new Error("Non-zero carry");N=D,v++}for(var k=O-N;k!==O&&L[k]===0;)k++;for(var C=new Uint8Array(S+(O-k)),z=S;k!==O;)C[z++]=L[k++];return C}function w(y){var v=p(y);if(v)return v;throw new Error("Non-base"+a+" character")}return{encode:h,decodeUnsafe:p,decode:w}}return X9=r,X9}function Xie(){return vU||(vU=1,J9=Zie()("123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz")),J9}function rse(r){return typeof r=="string"}function nse(r){return ise(r)&&sse(r.postMessage)}function ise(r){return typeof r=="object"&&r!==null}function sse(r){return typeof r=="function"}function ny(r){return r.version===void 0}var Yie,xU,X9,bU,J9,vU,Jie,Pa,ese,r7,e7,t7,AU,tse,ose,Pf,Bf,ase,cse,n7,dg,fg,EU,lse,use,iy,Fh,$h,hse,dse,CU=ye(()=>{"use strict";hg();H9();Yie=(function(){var r=function(e,t){return r=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(n,i){n.__proto__=i}||function(n,i){for(var s in i)Object.prototype.hasOwnProperty.call(i,s)&&(n[s]=i[s])},r(e,t)};return function(e,t){if(typeof t!="function"&&t!==null)throw new TypeError("Class extends value "+String(t)+" is not a constructor or null");r(e,t);function n(){this.constructor=e}e.prototype=t===null?Object.create(t):(n.prototype=t.prototype,new n)}})(),xU=(function(r){Yie(e,r);function e(){return r!==null&&r.apply(this,arguments)||this}return e})(Cu);Jie=Xie(),Pa=co(Jie),ese=(function(){var r=function(e,t){return r=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(n,i){n.__proto__=i}||function(n,i){for(var s in i)Object.prototype.hasOwnProperty.call(i,s)&&(n[s]=i[s])},r(e,t)};return function(e,t){if(typeof t!="function"&&t!==null)throw new TypeError("Class extends value "+String(t)+" is not a constructor or null");r(e,t);function n(){this.constructor=e}e.prototype=t===null?Object.create(t):(n.prototype=t.prototype,new n)}})(),r7=function(){return r7=Object.assign||function(r){for(var e,t=1,n=arguments.length;t<n;t++){e=arguments[t];for(var i in e)Object.prototype.hasOwnProperty.call(e,i)&&(r[i]=e[i])}return r},r7.apply(this,arguments)},e7=function(r,e,t,n){function i(s){return s instanceof t?s:new t(function(o){o(s)})}return new(t||(t=Promise))(function(s,o){function a(u){try{l(n.next(u))}catch(h){o(h)}}function c(u){try{l(n.throw(u))}catch(h){o(h)}}function l(u){u.done?s(u.value):i(u.value).then(a,c)}l((n=n.apply(r,e||[])).next())})},t7=function(r,e){var t={label:0,sent:function(){if(s[0]&1)throw s[1];return s[1]},trys:[],ops:[]},n,i,s,o;return o={next:a(0),throw:a(1),return:a(2)},typeof Symbol=="function"&&(o[Symbol.iterator]=function(){return this}),o;function a(l){return function(u){return c([l,u])}}function c(l){if(n)throw new TypeError("Generator is already executing.");for(;o&&(o=0,l[0]&&(t=0)),t;)try{if(n=1,i&&(s=l[0]&2?i.return:l[0]?i.throw||((s=i.return)&&s.call(i),0):i.next)&&!(s=s.call(i,l[1])).done)return s;switch(i=0,s&&(l=[l[0]&2,s.value]),l[0]){case 0:case 1:s=l;break;case 4:return t.label++,{value:l[1],done:!1};case 5:t.label++,i=l[1],l=[0];continue;case 7:l=t.ops.pop(),t.trys.pop();continue;default:if(s=t.trys,!(s=s.length>0&&s[s.length-1])&&(l[0]===6||l[0]===2)){t=0;continue}if(l[0]===3&&(!s||l[1]>s[0]&&l[1]<s[3])){t.label=l[1];break}if(l[0]===6&&t.label<s[1]){t.label=s[1],s=l;break}if(s&&t.label<s[2]){t.label=s[2],t.ops.push(l);break}s[2]&&t.ops.pop(),t.trys.pop();continue}l=e.call(r,t)}catch(u){l=[6,u],i=0}finally{n=s=0}if(l[0]&5)throw l[1];return{value:l[0]?l[1]:void 0,done:!0}}},AU=function(r,e){var t=typeof Symbol=="function"&&r[Symbol.iterator];if(!t)return r;var n=t.call(r),i,s=[],o;try{for(;(e===void 0||e-- >0)&&!(i=n.next()).done;)s.push(i.value)}catch(a){o={error:a}}finally{try{i&&!i.done&&(t=n.return)&&t.call(n)}finally{if(o)throw o.error}}return s},tse=(function(r){ese(e,r);function e(t,n){var i=r.call(this)||this;if(i._handleMessage=function(s){if(i._injectedProvider&&s.source===window||s.origin===i._providerUrl.origin&&s.source===i._popup){if(s.data.method==="connected"){var o=new ht(s.data.params.publicKey);(!i._publicKey||!i._publicKey.equals(o))&&(i._publicKey&&!i._publicKey.equals(o)&&i._handleDisconnect(),i._publicKey=o,i._autoApprove=!!s.data.params.autoApprove,i.emit("connect",i._publicKey))}else if(s.data.method==="disconnected")i._handleDisconnect();else if((s.data.result||s.data.error)&&i._responsePromises.has(s.data.id)){var a=AU(i._responsePromises.get(s.data.id),2),c=a[0],l=a[1];s.data.result?c(s.data.result):l(new Error(s.data.error))}}},i._handleConnect=function(){return i._handlerAdded||(i._handlerAdded=!0,window.addEventListener("message",i._handleMessage),window.addEventListener("beforeunload",i.disconnect)),i._injectedProvider?new Promise(function(s){i._sendRequest("connect",{}),s()}):(window.name="parent",i._popup=window.open(i._providerUrl.toString(),"_blank","location,resizable,width=460,height=675"),new Promise(function(s){i.once("connect",s)}))},i._handleDisconnect=function(){i._handlerAdded&&(i._handlerAdded=!1,window.removeEventListener("message",i._handleMessage),window.removeEventListener("beforeunload",i.disconnect)),i._publicKey&&(i._publicKey=null,i.emit("disconnect")),i._responsePromises.forEach(function(s,o){var a=AU(s,2);a[0];var c=a[1];i._responsePromises.delete(o),c("Wallet disconnected")})},i._sendRequest=function(s,o){return e7(i,void 0,void 0,function(){var a,c=this;return t7(this,function(l){if(s!=="connect"&&!this.connected)throw new Error("Wallet not connected");return a=this._nextRequestId,++this._nextRequestId,[2,new Promise(function(u,h){c._responsePromises.set(a,[u,h]),c._injectedProvider?c._injectedProvider.postMessage({jsonrpc:"2.0",id:a,method:s,params:r7({network:c._network},o)}):(c._popup.postMessage({jsonrpc:"2.0",id:a,method:s,params:o},c._providerUrl.origin),c.autoApprove||c._popup.focus())})]})})},i.connect=function(){return i._popup&&i._popup.close(),i._handleConnect()},i.disconnect=function(){return e7(i,void 0,void 0,function(){return t7(this,function(s){switch(s.label){case 0:return this._injectedProvider?[4,this._sendRequest("disconnect",{})]:[3,2];case 1:s.sent(),s.label=2;case 2:return this._popup&&this._popup.close(),this._handleDisconnect(),[2]}})})},i.sign=function(s,o){return e7(i,void 0,void 0,function(){var a,c,l;return t7(this,function(u){switch(u.label){case 0:if(!(s instanceof Uint8Array))throw new Error("Data must be an instance of Uint8Array");return[4,this._sendRequest("sign",{data:s,display:o})];case 1:return a=u.sent(),c=Pa.decode(a.signature),l=new ht(a.publicKey),[2,{signature:c,publicKey:l}]}})})},nse(t))i._injectedProvider=t;else if(rse(t))i._providerUrl=new URL(t),i._providerUrl.hash=new URLSearchParams({origin:window.location.origin,network:n}).toString();else throw new Error("provider parameter must be an injected provider or a URL string.");return i._network=n,i._publicKey=null,i._autoApprove=!1,i._popup=null,i._handlerAdded=!1,i._nextRequestId=1,i._responsePromises=new Map,i}return Object.defineProperty(e.prototype,"publicKey",{get:function(){return this._publicKey},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"connected",{get:function(){return this._publicKey!==null},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"autoApprove",{get:function(){return this._autoApprove},enumerable:!1,configurable:!0}),e})(Cu);ose=(function(){var r=function(e,t){return r=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(n,i){n.__proto__=i}||function(n,i){for(var s in i)Object.prototype.hasOwnProperty.call(i,s)&&(n[s]=i[s])},r(e,t)};return function(e,t){if(typeof t!="function"&&t!==null)throw new TypeError("Class extends value "+String(t)+" is not a constructor or null");r(e,t);function n(){this.constructor=e}e.prototype=t===null?Object.create(t):(n.prototype=t.prototype,new n)}})(),Pf=function(r,e,t,n){function i(s){return s instanceof t?s:new t(function(o){o(s)})}return new(t||(t=Promise))(function(s,o){function a(u){try{l(n.next(u))}catch(h){o(h)}}function c(u){try{l(n.throw(u))}catch(h){o(h)}}function l(u){u.done?s(u.value):i(u.value).then(a,c)}l((n=n.apply(r,e||[])).next())})},Bf=function(r,e){var t={label:0,sent:function(){if(s[0]&1)throw s[1];return s[1]},trys:[],ops:[]},n,i,s,o;return o={next:a(0),throw:a(1),return:a(2)},typeof Symbol=="function"&&(o[Symbol.iterator]=function(){return this}),o;function a(l){return function(u){return c([l,u])}}function c(l){if(n)throw new TypeError("Generator is already executing.");for(;o&&(o=0,l[0]&&(t=0)),t;)try{if(n=1,i&&(s=l[0]&2?i.return:l[0]?i.throw||((s=i.return)&&s.call(i),0):i.next)&&!(s=s.call(i,l[1])).done)return s;switch(i=0,s&&(l=[l[0]&2,s.value]),l[0]){case 0:case 1:s=l;break;case 4:return t.label++,{value:l[1],done:!1};case 5:t.label++,i=l[1],l=[0];continue;case 7:l=t.ops.pop(),t.trys.pop();continue;default:if(s=t.trys,!(s=s.length>0&&s[s.length-1])&&(l[0]===6||l[0]===2)){t=0;continue}if(l[0]===3&&(!s||l[1]>s[0]&&l[1]<s[3])){t.label=l[1];break}if(l[0]===6&&t.label<s[1]){t.label=s[1],s=l;break}if(s&&t.label<s[2]){t.label=s[2],t.ops.push(l);break}s[2]&&t.ops.pop(),t.trys.pop();continue}l=e.call(r,t)}catch(u){l=[6,u],i=0}finally{n=s=0}if(l[0]&5)throw l[1];return{value:l[0]?l[1]:void 0,done:!0}}},ase=(function(r){ose(e,r);function e(t,n,i){var s=r.call(this)||this;return s._instance=null,s.handleMessage=function(o){},s._sendRequest=function(o,a){return Pf(s,void 0,void 0,function(){var c,l;return Bf(this,function(u){switch(u.label){case 0:return!((c=this._instance)===null||c===void 0)&&c.sendRequest?[4,this._instance.sendRequest(o,a)]:[3,2];case 1:return[2,u.sent()];case 2:return!((l=this._instance)===null||l===void 0)&&l._sendRequest?[4,this._instance._sendRequest(o,a)]:[3,4];case 3:return[2,u.sent()];case 4:throw new Error("Unsupported version of `@project-serum/sol-wallet-adapter`")}})})},s._handleConnect=function(){s.emit("connect")},s._handleDisconnect=function(){window.clearInterval(s._pollTimer),s.emit("disconnect")},s._network=n,s._provider=i,s}return Object.defineProperty(e.prototype,"publicKey",{get:function(){return this._instance.publicKey||null},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"connected",{get:function(){return this._instance.connected||!1},enumerable:!1,configurable:!0}),e.prototype.connect=function(){return Pf(this,void 0,void 0,function(){var t=this;return Bf(this,function(n){switch(n.label){case 0:return this._instance=new tse(this._provider,this._network),this._instance.on("connect",this._handleConnect),this._instance.on("disconnect",this._handleDisconnect),this._pollTimer=window.setInterval(function(){var i,s;((s=(i=t._instance)===null||i===void 0?void 0:i._popup)===null||s===void 0?void 0:s.closed)!==!1&&t._handleDisconnect()},200),[4,this._instance.connect()];case 1:return n.sent(),[2]}})})},e.prototype.disconnect=function(){return Pf(this,void 0,void 0,function(){return Bf(this,function(t){switch(t.label){case 0:if(!this.connected)throw new Error("Wallet not connected");return this._instance.removeAllListeners("connect"),this._instance.removeAllListeners("disconnect"),[4,this._instance.disconnect()];case 1:return t.sent(),[2]}})})},e.prototype.signTransaction=function(t){return Pf(this,void 0,void 0,function(){var n;return Bf(this,function(i){switch(i.label){case 0:if(!this.connected)throw new Error("Wallet not connected");return[4,this._sendRequest("signTransactionV2",{transaction:Pa.encode(t)})];case 1:return n=i.sent().transaction,[2,Pa.decode(n)]}})})},e.prototype.signAllTransactions=function(t){return Pf(this,void 0,void 0,function(){var n;return Bf(this,function(i){switch(i.label){case 0:if(!this.connected)throw new Error("Wallet not connected");return[4,this._sendRequest("signAllTransactionsV2",{transactions:t.map(function(s){return Pa.encode(s)})})];case 1:return n=i.sent().transactions,[2,n.map(function(s){return Pa.decode(s)})]}})})},e.prototype.signAndSendTransaction=function(t,n){return Pf(this,void 0,void 0,function(){var i;return Bf(this,function(s){switch(s.label){case 0:if(!this.connected)throw new Error("Wallet not connected");return[4,this._sendRequest("signAndSendTransaction",{transaction:Pa.encode(t),options:n})];case 1:return i=s.sent(),[2,i.signature]}})})},e.prototype.signMessage=function(t,n){return n===void 0&&(n="hex"),Pf(this,void 0,void 0,function(){var i;return Bf(this,function(s){switch(s.label){case 0:if(!this.connected)throw new Error("Wallet not connected");return[4,this._instance.sign(t,n)];case 1:return i=s.sent().signature,[2,Uint8Array.from(i)]}})})},e})(xU),cse=(function(){var r=function(e,t){return r=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(n,i){n.__proto__=i}||function(n,i){for(var s in i)Object.prototype.hasOwnProperty.call(i,s)&&(n[s]=i[s])},r(e,t)};return function(e,t){if(typeof t!="function"&&t!==null)throw new TypeError("Class extends value "+String(t)+" is not a constructor or null");r(e,t);function n(){this.constructor=e}e.prototype=t===null?Object.create(t):(n.prototype=t.prototype,new n)}})(),n7=function(){return n7=Object.assign||function(r){for(var e,t=1,n=arguments.length;t<n;t++){e=arguments[t];for(var i in e)Object.prototype.hasOwnProperty.call(e,i)&&(r[i]=e[i])}return r},n7.apply(this,arguments)},dg=function(r,e,t,n){function i(s){return s instanceof t?s:new t(function(o){o(s)})}return new(t||(t=Promise))(function(s,o){function a(u){try{l(n.next(u))}catch(h){o(h)}}function c(u){try{l(n.throw(u))}catch(h){o(h)}}function l(u){u.done?s(u.value):i(u.value).then(a,c)}l((n=n.apply(r,e||[])).next())})},fg=function(r,e){var t={label:0,sent:function(){if(s[0]&1)throw s[1];return s[1]},trys:[],ops:[]},n,i,s,o;return o={next:a(0),throw:a(1),return:a(2)},typeof Symbol=="function"&&(o[Symbol.iterator]=function(){return this}),o;function a(l){return function(u){return c([l,u])}}function c(l){if(n)throw new TypeError("Generator is already executing.");for(;o&&(o=0,l[0]&&(t=0)),t;)try{if(n=1,i&&(s=l[0]&2?i.return:l[0]?i.throw||((s=i.return)&&s.call(i),0):i.next)&&!(s=s.call(i,l[1])).done)return s;switch(i=0,s&&(l=[l[0]&2,s.value]),l[0]){case 0:case 1:s=l;break;case 4:return t.label++,{value:l[1],done:!1};case 5:t.label++,i=l[1],l=[0];continue;case 7:l=t.ops.pop(),t.trys.pop();continue;default:if(s=t.trys,!(s=s.length>0&&s[s.length-1])&&(l[0]===6||l[0]===2)){t=0;continue}if(l[0]===3&&(!s||l[1]>s[0]&&l[1]<s[3])){t.label=l[1];break}if(l[0]===6&&t.label<s[1]){t.label=s[1],s=l;break}if(s&&t.label<s[2]){t.label=s[2],t.ops.push(l);break}s[2]&&t.ops.pop(),t.trys.pop();continue}l=e.call(r,t)}catch(u){l=[6,u],i=0}finally{n=s=0}if(l[0]&5)throw l[1];return{value:l[0]?l[1]:void 0,done:!0}}},EU=(function(r){cse(e,r);function e(t,n){var i=this,s;return i=r.call(this)||this,i._publicKey=null,i._messageHandlers={},i.handleMessage=function(o){if(i._messageHandlers[o.id]){var a=i._messageHandlers[o.id],c=a.resolve,l=a.reject;delete i._messageHandlers[o.id],o.error?l(o.error):c(o.result)}},i._sendMessage=function(o){if(!i.connected)throw new Error("Wallet not connected");return new Promise(function(a,c){var l,u,h=YA();i._messageHandlers[h]={resolve:a,reject:c},(u=(l=i._iframe)===null||l===void 0?void 0:l.contentWindow)===null||u===void 0||u.postMessage({channel:"solflareWalletAdapterToIframe",data:n7({id:h},o)},"*")})},i._iframe=t,i._publicKey=new ht((s=n?.toString)===null||s===void 0?void 0:s.call(n)),i}return Object.defineProperty(e.prototype,"publicKey",{get:function(){return this._publicKey||null},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"connected",{get:function(){return!0},enumerable:!1,configurable:!0}),e.prototype.connect=function(){return dg(this,void 0,void 0,function(){return fg(this,function(t){return[2]})})},e.prototype.disconnect=function(){return dg(this,void 0,void 0,function(){return fg(this,function(t){switch(t.label){case 0:return[4,this._sendMessage({method:"disconnect"})];case 1:return t.sent(),[2]}})})},e.prototype.signTransaction=function(t){var n;return dg(this,void 0,void 0,function(){var i,s;return fg(this,function(o){switch(o.label){case 0:if(!this.connected)throw new Error("Wallet not connected");o.label=1;case 1:return o.trys.push([1,3,,4]),[4,this._sendMessage({method:"signTransaction",params:{transaction:Pa.encode(t)}})];case 2:return i=o.sent(),[2,Pa.decode(i)];case 3:throw s=o.sent(),new Error(((n=s?.toString)===null||n===void 0?void 0:n.call(s))||"Failed to sign transaction");case 4:return[2]}})})},e.prototype.signAllTransactions=function(t){var n;return dg(this,void 0,void 0,function(){var i,s;return fg(this,function(o){switch(o.label){case 0:if(!this.connected)throw new Error("Wallet not connected");o.label=1;case 1:return o.trys.push([1,3,,4]),[4,this._sendMessage({method:"signAllTransactions",params:{transactions:t.map(function(a){return Pa.encode(a)})}})];case 2:return i=o.sent(),[2,i.map(function(a){return Pa.decode(a)})];case 3:throw s=o.sent(),new Error(((n=s?.toString)===null||n===void 0?void 0:n.call(s))||"Failed to sign transactions");case 4:return[2]}})})},e.prototype.signAndSendTransaction=function(t,n){var i;return dg(this,void 0,void 0,function(){var s,o;return fg(this,function(a){switch(a.label){case 0:if(!this.connected)throw new Error("Wallet not connected");a.label=1;case 1:return a.trys.push([1,3,,4]),[4,this._sendMessage({method:"signAndSendTransaction",params:{transaction:Pa.encode(t),options:n}})];case 2:return s=a.sent(),[2,s];case 3:throw o=a.sent(),new Error(((i=o?.toString)===null||i===void 0?void 0:i.call(o))||"Failed to sign and send transaction");case 4:return[2]}})})},e.prototype.signMessage=function(t,n){var i;return n===void 0&&(n="hex"),dg(this,void 0,void 0,function(){var s,o;return fg(this,function(a){switch(a.label){case 0:if(!this.connected)throw new Error("Wallet not connected");a.label=1;case 1:return a.trys.push([1,3,,4]),[4,this._sendMessage({method:"signMessage",params:{data:t,display:n}})];case 2:return s=a.sent(),[2,Uint8Array.from(Pa.decode(s))];case 3:throw o=a.sent(),new Error(((i=o?.toString)===null||i===void 0?void 0:i.call(o))||"Failed to sign message");case 4:return[2]}})})},e})(xU);lse="1.4.2",use=(function(){var r=function(e,t){return r=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(n,i){n.__proto__=i}||function(n,i){for(var s in i)Object.prototype.hasOwnProperty.call(i,s)&&(n[s]=i[s])},r(e,t)};return function(e,t){if(typeof t!="function"&&t!==null)throw new TypeError("Class extends value "+String(t)+" is not a constructor or null");r(e,t);function n(){this.constructor=e}e.prototype=t===null?Object.create(t):(n.prototype=t.prototype,new n)}})(),iy=function(){return iy=Object.assign||function(r){for(var e,t=1,n=arguments.length;t<n;t++){e=arguments[t];for(var i in e)Object.prototype.hasOwnProperty.call(e,i)&&(r[i]=e[i])}return r},iy.apply(this,arguments)},Fh=function(r,e,t,n){function i(s){return s instanceof t?s:new t(function(o){o(s)})}return new(t||(t=Promise))(function(s,o){function a(u){try{l(n.next(u))}catch(h){o(h)}}function c(u){try{l(n.throw(u))}catch(h){o(h)}}function l(u){u.done?s(u.value):i(u.value).then(a,c)}l((n=n.apply(r,e||[])).next())})},$h=function(r,e){var t={label:0,sent:function(){if(s[0]&1)throw s[1];return s[1]},trys:[],ops:[]},n,i,s,o;return o={next:a(0),throw:a(1),return:a(2)},typeof Symbol=="function"&&(o[Symbol.iterator]=function(){return this}),o;function a(l){return function(u){return c([l,u])}}function c(l){if(n)throw new TypeError("Generator is already executing.");for(;o&&(o=0,l[0]&&(t=0)),t;)try{if(n=1,i&&(s=l[0]&2?i.return:l[0]?i.throw||((s=i.return)&&s.call(i),0):i.next)&&!(s=s.call(i,l[1])).done)return s;switch(i=0,s&&(l=[l[0]&2,s.value]),l[0]){case 0:case 1:s=l;break;case 4:return t.label++,{value:l[1],done:!1};case 5:t.label++,i=l[1],l=[0];continue;case 7:l=t.ops.pop(),t.trys.pop();continue;default:if(s=t.trys,!(s=s.length>0&&s[s.length-1])&&(l[0]===6||l[0]===2)){t=0;continue}if(l[0]===3&&(!s||l[1]>s[0]&&l[1]<s[3])){t.label=l[1];break}if(l[0]===6&&t.label<s[1]){t.label=s[1],s=l;break}if(s&&t.label<s[2]){t.label=s[2],t.ops.push(l);break}s[2]&&t.ops.pop(),t.trys.pop();continue}l=e.call(r,t)}catch(u){l=[6,u],i=0}finally{n=s=0}if(l[0]&5)throw l[1];return{value:l[0]?l[1]:void 0,done:!0}}},hse=function(r){var e=typeof Symbol=="function"&&Symbol.iterator,t=e&&r[e],n=0;if(t)return t.call(r);if(r&&typeof r.length=="number")return{next:function(){return r&&n>=r.length&&(r=void 0),{value:r&&r[n++],done:!r}}};throw new TypeError(e?"Object is not iterable.":"Symbol.iterator is not defined.")},dse=(function(r){use(e,r);function e(t){var n=r.call(this)||this;return n._network="mainnet-beta",n._provider=null,n._iframeParams={},n._adapterInstance=null,n._element=null,n._iframe=null,n._connectHandler=null,n._flutterHandlerInterval=null,n._handleEvent=function(i){var s,o,a,c;switch(i.type){case"connect_native_web":{n._collapseIframe(),n._adapterInstance=new ase(n._iframe,n._network,((s=i.data)===null||s===void 0?void 0:s.provider)||n._provider||"https://solflare.com/provider"),n._adapterInstance.on("connect",n._webConnected),n._adapterInstance.on("disconnect",n._webDisconnected),n._adapterInstance.connect(),n._setPreferredAdapter("native_web");return}case"connect":{n._collapseIframe(),n._adapterInstance=new EU(n._iframe,((o=i.data)===null||o===void 0?void 0:o.publicKey)||""),n._adapterInstance.connect(),n._setPreferredAdapter((a=i.data)===null||a===void 0?void 0:a.adapter),n._connectHandler&&(n._connectHandler.resolve(),n._connectHandler=null),n.emit("connect",n.publicKey);return}case"disconnect":{n._connectHandler&&(n._connectHandler.reject(),n._connectHandler=null),n._disconnected(),n.emit("disconnect");return}case"accountChanged":{!((c=i.data)===null||c===void 0)&&c.publicKey?(n._adapterInstance=new EU(n._iframe,i.data.publicKey),n._adapterInstance.connect(),n.emit("accountChanged",n.publicKey)):n.emit("accountChanged",void 0);return}case"collapse":{n._collapseIframe();return}default:return}},n._handleResize=function(i){i.resizeMode==="full"?i.params.mode==="fullscreen"?n._expandIframe():i.params.mode==="hide"&&n._collapseIframe():i.resizeMode==="coordinates"&&n._iframe&&(n._iframe.style.top=isFinite(i.params.top)?"".concat(i.params.top,"px"):"",n._iframe.style.bottom=isFinite(i.params.bottom)?"".concat(i.params.bottom,"px"):"",n._iframe.style.left=isFinite(i.params.left)?"".concat(i.params.left,"px"):"",n._iframe.style.right=isFinite(i.params.right)?"".concat(i.params.right,"px"):"",n._iframe.style.width=isFinite(i.params.width)?"".concat(i.params.width,"px"):i.params.width,n._iframe.style.height=isFinite(i.params.height)?"".concat(i.params.height,"px"):i.params.height)},n._handleMessage=function(i){var s;if(((s=i.data)===null||s===void 0?void 0:s.channel)==="solflareIframeToWalletAdapter"){var o=i.data.data||{};o.type==="event"?n._handleEvent(o.event):o.type==="resize"?n._handleResize(o):o.type==="response"&&n._adapterInstance&&n._adapterInstance.handleMessage(o)}},n._removeElement=function(){n._flutterHandlerInterval!==null&&(clearInterval(n._flutterHandlerInterval),n._flutterHandlerInterval=null),n._element&&(n._element.remove(),n._element=null)},n._removeDanglingElements=function(){var i,s,o=document.getElementsByClassName("solflare-wallet-adapter-iframe");try{for(var a=hse(o),c=a.next();!c.done;c=a.next()){var l=c.value;l.parentElement&&l.remove()}}catch(u){i={error:u}}finally{try{c&&!c.done&&(s=a.return)&&s.call(a)}finally{if(i)throw i.error}}},n._injectElement=function(){n._removeElement(),n._removeDanglingElements();var i=iy(iy({},n._iframeParams),{cluster:n._network||"mainnet-beta",origin:window.location.origin||"",title:document.title||"",version:1,sdkVersion:lse}),s=n._getPreferredAdapter();s&&(i.adapter=s),n._provider&&(i.provider=n._provider);var o=Object.keys(i).map(function(c){return"".concat(c,"=").concat(encodeURIComponent(i[c]))}).join("&"),a="".concat(e.IFRAME_URL,"?").concat(o);n._element=document.createElement("div"),n._element.className="solflare-wallet-adapter-iframe",n._element.innerHTML=`
57
57
  <iframe src='`.concat(a,`' referrerPolicy='strict-origin-when-cross-origin' style='position: fixed; top: 0; bottom: 0; left: 0; right: 0; width: 100%; height: 100%; border: none; border-radius: 0; z-index: 99999; color-scheme: auto;' allowtransparency='true'></iframe>