"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const p=require("@dfinity/agent"),i=require("@dfinity/principal"),d=require("node:fs"),y=require("@dfinity/ledger-icrc"),c=require("node:buffer"),g=require("@dfinity/identity"),m=require("@dfinity/identity-secp256k1"),s=require("pem-file");function k(r){const e=Object.create(null,{[Symbol.toStringTag]:{value:"Module"}});if(r){for(const t in r)if(t!=="default"){const n=Object.getOwnPropertyDescriptor(r,t);Object.defineProperty(e,t,n.get?n:{enumerable:!0,get:()=>r[t]})}}return e.default=r,Object.freeze(e)}const b=k(d),u={};function l(r){const e=s.decode(r);if(r.includes("EC PRIVATE KEY")){if(e.length!==118)throw new Error(`Invalid Secp256k1 key format: expecting byte length 118 but got ${e.length}`);return m.Secp256k1KeyIdentity.fromSecretKey(e.subarray(7,39))}if(e.length!==85)throw new Error(`Invalid Ed25519 key format: expecting byte length 85 but got ${e.length}`);const t=e.subarray(16,48);return g.Ed25519KeyIdentity.fromSecretKey(t)}const w="aes-256-ctr";function C(r,e){const t=u.createHash("sha256").update(e).digest("base64").slice(0,32),n=r.subarray(0,16),o=r.subarray(16),a=u.createDecipheriv(w,t,n);return c.Buffer.concat([a.update(o),a.final()])}function P(r,e){const t=c.Buffer.from(r);if(r.includes("ENCRYPTED")){if(!e)throw new Error("PEM file is encrypted, but no password was provided.");const n=C(s.decode(t),e),o=s.encode(n,"PRIVATE KEY");return l(c.Buffer.from(o))}return l(t)}function T(r,e){const t=d.readFileSync(r,"utf-8");return P(t,e)}function I(r){if(r&&typeof r=="object"&&"errorType"in r){const{errorType:e}=r,t=Object.keys(e)[0],n=e[t];switch(t){case"InsufficientAllowance":return`Insufficient allowance: The user has not approved a large enough spending limit for this server. Current allowance: ${Number(n.allowance)/1e8} tokens.`;case"InsufficientFunds":return`Insufficient funds: The user's wallet balance is too low. Current balance: ${Number(n.balance)/1e8} tokens.`;case"BadFee":return`Bad fee: The transaction fee was incorrect. Expected: ${Number(n.expected_fee)/1e8} tokens.`;case"Duplicate":return`Duplicate transaction: This transaction has already been processed. Duplicate of block: ${n.duplicate_of}.`;case"TemporarilyUnavailable":return"The ledger is temporarily unavailable. Please try again later.";case"TooOld":return"The transaction is too old to be processed.";default:return`An unknown ledger error occurred: ${JSON.stringify(e)}`}}return r instanceof Error?r.message:"An unknown error occurred."}class E{agent;payoutPrincipal;tokenConfigPath;tokenInfoCache=null;constructor(e){const t=e.host??"https://icp-api.io",n=e.fetchRootKey??(t.includes("localhost")||t.includes("127.0.0.1"));this.agent=new p.HttpAgent({host:t,identity:e.identity,shouldFetchRootKey:n}),this.payoutPrincipal=e.payoutPrincipal,this.tokenConfigPath=e.tokenConfigPath}async getSupportedTokens(){if(this.tokenInfoCache!==null)return this.tokenInfoCache;try{const e=b.readFileSync(this.tokenConfigPath,"utf-8"),t=JSON.parse(e);if(t.length===0)throw new Error("Token configuration file is empty.");return this.tokenInfoCache=t,this.tokenInfoCache}catch{throw console.error(`Failed to load or parse token metadata from ${this.tokenConfigPath}.`),new Error(`Configuration error: Please ensure '${this.tokenConfigPath}' exists and is valid. Run 'npx prometheus-cli' if needed.`)}}async charge(e){try{const n=(await this.getSupportedTokens())[0],o=y.IcrcLedgerCanister.create({agent:this.agent,canisterId:i.Principal.fromText(n.canister_id)}),a=typeof e.userToCharge=="string"?i.Principal.fromText(e.userToCharge):e.userToCharge,f=BigInt(Math.round(e.amount*10**n.decimals)),h={from:{owner:a,subaccount:[]},to:{owner:this.payoutPrincipal,subaccount:[]},amount:f};return{ok:!0,blockIndex:await o.transferFrom(h)}}catch(t){const n=I(t);return console.error("Charge operation failed:",n),{ok:!1,error:n}}}}exports.PrometheusServerClient=E;exports.identityFromPem=T;
//# sourceMappingURL=server.cjs.map
