diff --git a/dist/core.cjs b/dist/core.cjs index ee5f1bb..02226b4 100644 --- a/dist/core.cjs +++ b/dist/core.cjs @@ -14,7 +14,7 @@ OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. ***************************************************************************** */ /* global Reflect, Promise, SuppressedError, Symbol, Iterator */ -function a(e,t,n,i){return new(n||(n=Promise))((function(a,r){function s(e){try{d(i.next(e))}catch(e){r(e)}}function o(e){try{d(i.throw(e))}catch(e){r(e)}}function d(e){var t;e.done?a(e.value):(t=e.value,t instanceof n?t:new n((function(e){e(t)}))).then(s,o)}d((i=i.apply(e,t||[])).next())}))}function r(e,t,n,i){if("a"===n&&!i)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!i:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===n?i:"a"===n?i.call(e):i?i.value:t.get(e)}function s(e,t,n,i,a){if("m"===i)throw new TypeError("Private method is not writable");if("a"===i&&!a)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!a:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===i?a.call(e,n):a?a.value=n:t.set(e,n),n}"function"==typeof SuppressedError&&SuppressedError;class o extends Error{constructor(e,t){super(e),this.name="APIError",this.statusCode=t||500,Error.captureStackTrace(this,this.constructor)}toJSON(){return{error:this.name,message:this.message,statusCode:this.statusCode||500}}} +function r(e,t,n,i){return new(n||(n=Promise))((function(r,a){function s(e){try{d(i.next(e))}catch(e){a(e)}}function o(e){try{d(i.throw(e))}catch(e){a(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n((function(e){e(t)}))).then(s,o)}d((i=i.apply(e,t||[])).next())}))}function a(e,t,n,i){if("a"===n&&!i)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!i:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===n?i:"a"===n?i.call(e):i?i.value:t.get(e)}function s(e,t,n,i,r){if("m"===i)throw new TypeError("Private method is not writable");if("a"===i&&!r)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===i?r.call(e,n):r?r.value=n:t.set(e,n),n}"function"==typeof SuppressedError&&SuppressedError;class o extends Error{constructor(e,t){super(e),this.name="APIError",this.statusCode=t||500,Error.captureStackTrace(this,this.constructor)}toJSON(){return{error:this.name,message:this.message,statusCode:this.statusCode||500}}}class d extends Error{constructor(e){super(e),this.name="ValidationError",Error.captureStackTrace(this,this.constructor)}toJSON(){return{error:this.name,message:this.message,statusCode:400}}} /** * Makes a GET request to the given URL with the provided headers. * @@ -22,7 +22,7 @@ function a(e,t,n,i){return new(n||(n=Promise))((function(a,r){function s(e){try{ * @param {object} headers - The headers to include in the request. * @returns {Promise} - The response data. * @throws {APIError} - Throws an error if the request fails. - */function d(t){return a(this,arguments,void 0,(function*(t,n={}){try{return(yield e.get(t,{headers:n})).data}catch(e){if(e.response)throw new o(e.response.data.message||"API request failed",e.response.status);throw new o("Network error or server is unavailable",500)}}))} + */function u(t){return r(this,arguments,void 0,(function*(t,n={}){try{return(yield e.get(t,{headers:n})).data}catch(e){if(e.response)throw new o(e.response.data.message||"API request failed",e.response.status);throw new o("Network error or server is unavailable",500)}}))} /** * Constructs a query string from an object of query parameters. * @@ -36,9 +36,9 @@ function a(e,t,n,i){return new(n||(n=Promise))((function(a,r){function s(e){try{ * @param {object} params - An object representing query parameters. * @returns {string} - The complete URL with query string. */ -function u(e,t={}){const n=function(e={}){return Object.keys(e).map((t=>`${encodeURIComponent(t)}=${encodeURIComponent(e[t])}`)).join("&")}(t);return n?`${e}?${n}`:e}const l="https://wv2h4to5qa.execute-api.us-east-2.amazonaws.com/dev/twitter",p="https://wv2h4to5qa.execute-api.us-east-2.amazonaws.com/dev/spotify";const c={id:123420001114,name:"Basecamp",nativeCurrency:{decimals:18,name:"Camp",symbol:"CAMP"},rpcUrls:{default:{http:["https://rpc-campnetwork.xyz","https://rpc.basecamp.t.raas.gelato.cloud"]}},blockExplorers:{default:{name:"Explorer",url:"https://basecamp.cloud.blockscout.com/"}}}; +function l(e,t={}){const n=function(e={}){return Object.keys(e).map((t=>`${encodeURIComponent(t)}=${encodeURIComponent(e[t])}`)).join("&")}(t);return n?`${e}?${n}`:e}const p="https://wv2h4to5qa.execute-api.us-east-2.amazonaws.com/dev/twitter",c="https://wv2h4to5qa.execute-api.us-east-2.amazonaws.com/dev/spotify";const y={id:123420001114,name:"Basecamp",nativeCurrency:{decimals:18,name:"Camp",symbol:"CAMP"},rpcUrls:{default:{http:["https://rpc-campnetwork.xyz","https://rpc.basecamp.t.raas.gelato.cloud"]}},blockExplorers:{default:{name:"Explorer",url:"https://basecamp.cloud.blockscout.com/"}}}; // @ts-ignore -let y=null,h=null;const m=()=>(h||(h=t.createPublicClient({chain:c,transport:t.http()})),h);var f="Connect with Camp Network",w="https://wv2h4to5qa.execute-api.us-east-2.amazonaws.com/dev",v={USER_CONNECTED:"ed42542d-b676-4112-b6d9-6db98048b2e0",USER_DISCONNECTED:"20af31ac-e602-442e-9e0e-b589f4dd4016",TWITTER_LINKED:"7fbea086-90ef-4679-ba69-f47f9255b34c",DISCORD_LINKED:"d73f5ae3-a8e8-48f2-8532-85e0c7780d6a",SPOTIFY_LINKED:"fc1788b4-c984-42c8-96f4-c87f6bb0b8f7",TIKTOK_LINKED:"4a2ffdd3-f0e9-4784-8b49-ff76ec1c0a6a",TELEGRAM_LINKED:"9006bc5d-bcc9-4d01-a860-4f1a201e8e47"},T="0xF90733b9eCDa3b49C250B2C3E3E42c96fC93324E",b="0x5c5e6b458b2e3924E7688b8Dee1Bb49088F6Fef5";let g=[];const I=()=>g,A=e=>{function t(t){g.some((e=>e.info.uuid===t.detail.info.uuid))||(g=[...g,t.detail],e(g))}if("undefined"!=typeof window)return window.addEventListener("eip6963:announceProvider",t),window.dispatchEvent(new Event("eip6963:requestProvider")),()=>window.removeEventListener("eip6963:announceProvider",t)};var k=[{inputs:[{internalType:"string",name:"name_",type:"string"},{internalType:"string",name:"symbol_",type:"string"},{internalType:"uint256",name:"maxTermDuration_",type:"uint256"},{internalType:"address",name:"signer_",type:"address"}],stateMutability:"nonpayable",type:"constructor"},{inputs:[],name:"DurationZero",type:"error"},{inputs:[{internalType:"address",name:"sender",type:"address"},{internalType:"uint256",name:"tokenId",type:"uint256"},{internalType:"address",name:"owner",type:"address"}],name:"ERC721IncorrectOwner",type:"error"},{inputs:[{internalType:"address",name:"operator",type:"address"},{internalType:"uint256",name:"tokenId",type:"uint256"}],name:"ERC721InsufficientApproval",type:"error"},{inputs:[{internalType:"address",name:"approver",type:"address"}],name:"ERC721InvalidApprover",type:"error"},{inputs:[{internalType:"address",name:"operator",type:"address"}],name:"ERC721InvalidOperator",type:"error"},{inputs:[{internalType:"address",name:"owner",type:"address"}],name:"ERC721InvalidOwner",type:"error"},{inputs:[{internalType:"address",name:"receiver",type:"address"}],name:"ERC721InvalidReceiver",type:"error"},{inputs:[{internalType:"address",name:"sender",type:"address"}],name:"ERC721InvalidSender",type:"error"},{inputs:[{internalType:"uint256",name:"tokenId",type:"uint256"}],name:"ERC721NonexistentToken",type:"error"},{inputs:[],name:"EnforcedPause",type:"error"},{inputs:[],name:"ExpectedPause",type:"error"},{inputs:[],name:"InvalidDeadline",type:"error"},{inputs:[],name:"InvalidDuration",type:"error"},{inputs:[{internalType:"uint16",name:"royaltyBps",type:"uint16"}],name:"InvalidRoyalty",type:"error"},{inputs:[],name:"InvalidSignature",type:"error"},{inputs:[{internalType:"uint256",name:"tokenId",type:"uint256"},{internalType:"address",name:"caller",type:"address"}],name:"NotTokenOwner",type:"error"},{inputs:[{internalType:"address",name:"owner",type:"address"}],name:"OwnableInvalidOwner",type:"error"},{inputs:[{internalType:"address",name:"account",type:"address"}],name:"OwnableUnauthorizedAccount",type:"error"},{inputs:[],name:"SignatureAlreadyUsed",type:"error"},{inputs:[{internalType:"uint256",name:"tokenId",type:"uint256"}],name:"TokenAlreadyExists",type:"error"},{inputs:[],name:"Unauthorized",type:"error"},{anonymous:!1,inputs:[{indexed:!0,internalType:"uint256",name:"tokenId",type:"uint256"},{indexed:!0,internalType:"address",name:"buyer",type:"address"},{indexed:!1,internalType:"uint32",name:"periods",type:"uint32"},{indexed:!1,internalType:"uint256",name:"newExpiry",type:"uint256"},{indexed:!1,internalType:"uint256",name:"amountPaid",type:"uint256"}],name:"AccessPurchased",type:"event"},{anonymous:!1,inputs:[{indexed:!0,internalType:"address",name:"owner",type:"address"},{indexed:!0,internalType:"address",name:"approved",type:"address"},{indexed:!0,internalType:"uint256",name:"tokenId",type:"uint256"}],name:"Approval",type:"event"},{anonymous:!1,inputs:[{indexed:!0,internalType:"address",name:"owner",type:"address"},{indexed:!0,internalType:"address",name:"operator",type:"address"},{indexed:!1,internalType:"bool",name:"approved",type:"bool"}],name:"ApprovalForAll",type:"event"},{anonymous:!1,inputs:[{indexed:!0,internalType:"uint256",name:"tokenId",type:"uint256"},{indexed:!0,internalType:"address",name:"creator",type:"address"}],name:"DataDeleted",type:"event"},{anonymous:!1,inputs:[{indexed:!0,internalType:"uint256",name:"tokenId",type:"uint256"},{indexed:!0,internalType:"address",name:"creator",type:"address"},{indexed:!1,internalType:"bytes32",name:"contentHash",type:"bytes32"}],name:"DataMinted",type:"event"},{anonymous:!1,inputs:[{indexed:!0,internalType:"address",name:"previousOwner",type:"address"},{indexed:!0,internalType:"address",name:"newOwner",type:"address"}],name:"OwnershipTransferred",type:"event"},{anonymous:!1,inputs:[{indexed:!1,internalType:"address",name:"account",type:"address"}],name:"Paused",type:"event"},{anonymous:!1,inputs:[{indexed:!0,internalType:"uint256",name:"tokenId",type:"uint256"},{indexed:!1,internalType:"uint256",name:"royaltyAmount",type:"uint256"},{indexed:!1,internalType:"address",name:"creator",type:"address"},{indexed:!1,internalType:"uint256",name:"protocolAmount",type:"uint256"}],name:"RoyaltyPaid",type:"event"},{anonymous:!1,inputs:[{indexed:!0,internalType:"uint256",name:"tokenId",type:"uint256"},{indexed:!1,internalType:"uint128",name:"newPrice",type:"uint128"},{indexed:!1,internalType:"uint32",name:"newDuration",type:"uint32"},{indexed:!1,internalType:"uint16",name:"newRoyaltyBps",type:"uint16"},{indexed:!1,internalType:"address",name:"paymentToken",type:"address"}],name:"TermsUpdated",type:"event"},{anonymous:!1,inputs:[{indexed:!0,internalType:"address",name:"from",type:"address"},{indexed:!0,internalType:"address",name:"to",type:"address"},{indexed:!0,internalType:"uint256",name:"tokenId",type:"uint256"}],name:"Transfer",type:"event"},{anonymous:!1,inputs:[{indexed:!1,internalType:"address",name:"account",type:"address"}],name:"Unpaused",type:"event"},{inputs:[{internalType:"address",name:"to",type:"address"},{internalType:"uint256",name:"tokenId",type:"uint256"}],name:"approve",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"address",name:"owner",type:"address"}],name:"balanceOf",outputs:[{internalType:"uint256",name:"",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"uint256",name:"",type:"uint256"}],name:"contentHash",outputs:[{internalType:"bytes32",name:"",type:"bytes32"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"uint256",name:"",type:"uint256"}],name:"dataStatus",outputs:[{internalType:"enum IpNFT.DataStatus",name:"",type:"uint8"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"uint256",name:"tokenId",type:"uint256"}],name:"finalizeDelete",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"uint256",name:"tokenId",type:"uint256"}],name:"getApproved",outputs:[{internalType:"address",name:"",type:"address"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"uint256",name:"tokenId",type:"uint256"}],name:"getTerms",outputs:[{components:[{internalType:"uint128",name:"price",type:"uint128"},{internalType:"uint32",name:"duration",type:"uint32"},{internalType:"uint16",name:"royaltyBps",type:"uint16"},{internalType:"address",name:"paymentToken",type:"address"}],internalType:"struct IpNFT.LicenseTerms",name:"",type:"tuple"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"address",name:"owner",type:"address"},{internalType:"address",name:"operator",type:"address"}],name:"isApprovedForAll",outputs:[{internalType:"bool",name:"",type:"bool"}],stateMutability:"view",type:"function"},{inputs:[],name:"maxTermDuration",outputs:[{internalType:"uint256",name:"",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"address",name:"to",type:"address"},{internalType:"uint256",name:"tokenId",type:"uint256"},{internalType:"uint256",name:"parentId",type:"uint256"},{internalType:"bytes32",name:"creatorContentHash",type:"bytes32"},{internalType:"string",name:"uri",type:"string"},{components:[{internalType:"uint128",name:"price",type:"uint128"},{internalType:"uint32",name:"duration",type:"uint32"},{internalType:"uint16",name:"royaltyBps",type:"uint16"},{internalType:"address",name:"paymentToken",type:"address"}],internalType:"struct IpNFT.LicenseTerms",name:"licenseTerms",type:"tuple"},{internalType:"uint256",name:"deadline",type:"uint256"},{internalType:"bytes",name:"signature",type:"bytes"}],name:"mintWithSignature",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[],name:"name",outputs:[{internalType:"string",name:"",type:"string"}],stateMutability:"view",type:"function"},{inputs:[],name:"owner",outputs:[{internalType:"address",name:"",type:"address"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"uint256",name:"tokenId",type:"uint256"}],name:"ownerOf",outputs:[{internalType:"address",name:"",type:"address"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"uint256",name:"",type:"uint256"}],name:"parentIpOf",outputs:[{internalType:"uint256",name:"",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[],name:"pause",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[],name:"paused",outputs:[{internalType:"bool",name:"",type:"bool"}],stateMutability:"view",type:"function"},{inputs:[],name:"renounceOwnership",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"uint256",name:"tokenId",type:"uint256"},{internalType:"uint256",name:"salePrice",type:"uint256"}],name:"royaltyInfo",outputs:[{internalType:"address",name:"receiver",type:"address"},{internalType:"uint256",name:"royaltyAmount",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"uint256",name:"",type:"uint256"}],name:"royaltyPercentages",outputs:[{internalType:"uint16",name:"",type:"uint16"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"uint256",name:"",type:"uint256"}],name:"royaltyReceivers",outputs:[{internalType:"address",name:"",type:"address"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"address",name:"from",type:"address"},{internalType:"address",name:"to",type:"address"},{internalType:"uint256",name:"tokenId",type:"uint256"}],name:"safeTransferFrom",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"address",name:"from",type:"address"},{internalType:"address",name:"to",type:"address"},{internalType:"uint256",name:"tokenId",type:"uint256"},{internalType:"bytes",name:"data",type:"bytes"}],name:"safeTransferFrom",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"address",name:"operator",type:"address"},{internalType:"bool",name:"approved",type:"bool"}],name:"setApprovalForAll",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"address",name:"_signer",type:"address"}],name:"setSigner",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[],name:"signer",outputs:[{internalType:"address",name:"",type:"address"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"bytes4",name:"interfaceId",type:"bytes4"}],name:"supportsInterface",outputs:[{internalType:"bool",name:"",type:"bool"}],stateMutability:"view",type:"function"},{inputs:[],name:"symbol",outputs:[{internalType:"string",name:"",type:"string"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"uint256",name:"",type:"uint256"}],name:"terms",outputs:[{internalType:"uint128",name:"price",type:"uint128"},{internalType:"uint32",name:"duration",type:"uint32"},{internalType:"uint16",name:"royaltyBps",type:"uint16"},{internalType:"address",name:"paymentToken",type:"address"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"uint256",name:"_tokenId",type:"uint256"}],name:"tokenURI",outputs:[{internalType:"string",name:"",type:"string"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"address",name:"from",type:"address"},{internalType:"address",name:"to",type:"address"},{internalType:"uint256",name:"tokenId",type:"uint256"}],name:"transferFrom",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"address",name:"newOwner",type:"address"}],name:"transferOwnership",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[],name:"unpause",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"uint256",name:"tokenId",type:"uint256"},{internalType:"address",name:"_royaltyReceiver",type:"address"},{components:[{internalType:"uint128",name:"price",type:"uint128"},{internalType:"uint32",name:"duration",type:"uint32"},{internalType:"uint16",name:"royaltyBps",type:"uint16"},{internalType:"address",name:"paymentToken",type:"address"}],internalType:"struct IpNFT.LicenseTerms",name:"newTerms",type:"tuple"}],name:"updateTerms",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"bytes32",name:"",type:"bytes32"}],name:"usedNonces",outputs:[{internalType:"bool",name:"",type:"bool"}],stateMutability:"view",type:"function"}]; +let h=null,m=null;const f=()=>(m||(m=t.createPublicClient({chain:y,transport:t.http()})),m);var w="Connect with Camp Network",v="https://wv2h4to5qa.execute-api.us-east-2.amazonaws.com/dev",T={USER_CONNECTED:"ed42542d-b676-4112-b6d9-6db98048b2e0",USER_DISCONNECTED:"20af31ac-e602-442e-9e0e-b589f4dd4016",TWITTER_LINKED:"7fbea086-90ef-4679-ba69-f47f9255b34c",DISCORD_LINKED:"d73f5ae3-a8e8-48f2-8532-85e0c7780d6a",SPOTIFY_LINKED:"fc1788b4-c984-42c8-96f4-c87f6bb0b8f7",TIKTOK_LINKED:"4a2ffdd3-f0e9-4784-8b49-ff76ec1c0a6a",TELEGRAM_LINKED:"9006bc5d-bcc9-4d01-a860-4f1a201e8e47"},g="0xF90733b9eCDa3b49C250B2C3E3E42c96fC93324E",b="0x5c5e6b458b2e3924E7688b8Dee1Bb49088F6Fef5";let I=[];const A=()=>I,k=e=>{function t(t){I.some((e=>e.info.uuid===t.detail.info.uuid))||(I=[...I,t.detail],e(I))}if("undefined"!=typeof window)return window.addEventListener("eip6963:announceProvider",t),window.dispatchEvent(new Event("eip6963:requestProvider")),()=>window.removeEventListener("eip6963:announceProvider",t)};var C=[{inputs:[{internalType:"string",name:"name_",type:"string"},{internalType:"string",name:"symbol_",type:"string"},{internalType:"uint256",name:"maxTermDuration_",type:"uint256"},{internalType:"address",name:"signer_",type:"address"}],stateMutability:"nonpayable",type:"constructor"},{inputs:[],name:"DurationZero",type:"error"},{inputs:[{internalType:"address",name:"sender",type:"address"},{internalType:"uint256",name:"tokenId",type:"uint256"},{internalType:"address",name:"owner",type:"address"}],name:"ERC721IncorrectOwner",type:"error"},{inputs:[{internalType:"address",name:"operator",type:"address"},{internalType:"uint256",name:"tokenId",type:"uint256"}],name:"ERC721InsufficientApproval",type:"error"},{inputs:[{internalType:"address",name:"approver",type:"address"}],name:"ERC721InvalidApprover",type:"error"},{inputs:[{internalType:"address",name:"operator",type:"address"}],name:"ERC721InvalidOperator",type:"error"},{inputs:[{internalType:"address",name:"owner",type:"address"}],name:"ERC721InvalidOwner",type:"error"},{inputs:[{internalType:"address",name:"receiver",type:"address"}],name:"ERC721InvalidReceiver",type:"error"},{inputs:[{internalType:"address",name:"sender",type:"address"}],name:"ERC721InvalidSender",type:"error"},{inputs:[{internalType:"uint256",name:"tokenId",type:"uint256"}],name:"ERC721NonexistentToken",type:"error"},{inputs:[],name:"EnforcedPause",type:"error"},{inputs:[],name:"ExpectedPause",type:"error"},{inputs:[],name:"InvalidDeadline",type:"error"},{inputs:[],name:"InvalidDuration",type:"error"},{inputs:[{internalType:"uint16",name:"royaltyBps",type:"uint16"}],name:"InvalidRoyalty",type:"error"},{inputs:[],name:"InvalidSignature",type:"error"},{inputs:[{internalType:"uint256",name:"tokenId",type:"uint256"},{internalType:"address",name:"caller",type:"address"}],name:"NotTokenOwner",type:"error"},{inputs:[{internalType:"address",name:"owner",type:"address"}],name:"OwnableInvalidOwner",type:"error"},{inputs:[{internalType:"address",name:"account",type:"address"}],name:"OwnableUnauthorizedAccount",type:"error"},{inputs:[],name:"SignatureAlreadyUsed",type:"error"},{inputs:[{internalType:"uint256",name:"tokenId",type:"uint256"}],name:"TokenAlreadyExists",type:"error"},{inputs:[],name:"Unauthorized",type:"error"},{anonymous:!1,inputs:[{indexed:!0,internalType:"uint256",name:"tokenId",type:"uint256"},{indexed:!0,internalType:"address",name:"buyer",type:"address"},{indexed:!1,internalType:"uint32",name:"periods",type:"uint32"},{indexed:!1,internalType:"uint256",name:"newExpiry",type:"uint256"},{indexed:!1,internalType:"uint256",name:"amountPaid",type:"uint256"}],name:"AccessPurchased",type:"event"},{anonymous:!1,inputs:[{indexed:!0,internalType:"address",name:"owner",type:"address"},{indexed:!0,internalType:"address",name:"approved",type:"address"},{indexed:!0,internalType:"uint256",name:"tokenId",type:"uint256"}],name:"Approval",type:"event"},{anonymous:!1,inputs:[{indexed:!0,internalType:"address",name:"owner",type:"address"},{indexed:!0,internalType:"address",name:"operator",type:"address"},{indexed:!1,internalType:"bool",name:"approved",type:"bool"}],name:"ApprovalForAll",type:"event"},{anonymous:!1,inputs:[{indexed:!0,internalType:"uint256",name:"tokenId",type:"uint256"},{indexed:!0,internalType:"address",name:"creator",type:"address"}],name:"DataDeleted",type:"event"},{anonymous:!1,inputs:[{indexed:!0,internalType:"uint256",name:"tokenId",type:"uint256"},{indexed:!0,internalType:"address",name:"creator",type:"address"},{indexed:!1,internalType:"bytes32",name:"contentHash",type:"bytes32"}],name:"DataMinted",type:"event"},{anonymous:!1,inputs:[{indexed:!0,internalType:"address",name:"previousOwner",type:"address"},{indexed:!0,internalType:"address",name:"newOwner",type:"address"}],name:"OwnershipTransferred",type:"event"},{anonymous:!1,inputs:[{indexed:!1,internalType:"address",name:"account",type:"address"}],name:"Paused",type:"event"},{anonymous:!1,inputs:[{indexed:!0,internalType:"uint256",name:"tokenId",type:"uint256"},{indexed:!1,internalType:"uint256",name:"royaltyAmount",type:"uint256"},{indexed:!1,internalType:"address",name:"creator",type:"address"},{indexed:!1,internalType:"uint256",name:"protocolAmount",type:"uint256"}],name:"RoyaltyPaid",type:"event"},{anonymous:!1,inputs:[{indexed:!0,internalType:"uint256",name:"tokenId",type:"uint256"},{indexed:!1,internalType:"uint128",name:"newPrice",type:"uint128"},{indexed:!1,internalType:"uint32",name:"newDuration",type:"uint32"},{indexed:!1,internalType:"uint16",name:"newRoyaltyBps",type:"uint16"},{indexed:!1,internalType:"address",name:"paymentToken",type:"address"}],name:"TermsUpdated",type:"event"},{anonymous:!1,inputs:[{indexed:!0,internalType:"address",name:"from",type:"address"},{indexed:!0,internalType:"address",name:"to",type:"address"},{indexed:!0,internalType:"uint256",name:"tokenId",type:"uint256"}],name:"Transfer",type:"event"},{anonymous:!1,inputs:[{indexed:!1,internalType:"address",name:"account",type:"address"}],name:"Unpaused",type:"event"},{inputs:[{internalType:"address",name:"to",type:"address"},{internalType:"uint256",name:"tokenId",type:"uint256"}],name:"approve",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"address",name:"owner",type:"address"}],name:"balanceOf",outputs:[{internalType:"uint256",name:"",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"uint256",name:"",type:"uint256"}],name:"contentHash",outputs:[{internalType:"bytes32",name:"",type:"bytes32"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"uint256",name:"",type:"uint256"}],name:"dataStatus",outputs:[{internalType:"enum IpNFT.DataStatus",name:"",type:"uint8"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"uint256",name:"tokenId",type:"uint256"}],name:"finalizeDelete",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"uint256",name:"tokenId",type:"uint256"}],name:"getApproved",outputs:[{internalType:"address",name:"",type:"address"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"uint256",name:"tokenId",type:"uint256"}],name:"getTerms",outputs:[{components:[{internalType:"uint128",name:"price",type:"uint128"},{internalType:"uint32",name:"duration",type:"uint32"},{internalType:"uint16",name:"royaltyBps",type:"uint16"},{internalType:"address",name:"paymentToken",type:"address"}],internalType:"struct IpNFT.LicenseTerms",name:"",type:"tuple"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"address",name:"owner",type:"address"},{internalType:"address",name:"operator",type:"address"}],name:"isApprovedForAll",outputs:[{internalType:"bool",name:"",type:"bool"}],stateMutability:"view",type:"function"},{inputs:[],name:"maxTermDuration",outputs:[{internalType:"uint256",name:"",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"address",name:"to",type:"address"},{internalType:"uint256",name:"tokenId",type:"uint256"},{internalType:"uint256",name:"parentId",type:"uint256"},{internalType:"bytes32",name:"creatorContentHash",type:"bytes32"},{internalType:"string",name:"uri",type:"string"},{components:[{internalType:"uint128",name:"price",type:"uint128"},{internalType:"uint32",name:"duration",type:"uint32"},{internalType:"uint16",name:"royaltyBps",type:"uint16"},{internalType:"address",name:"paymentToken",type:"address"}],internalType:"struct IpNFT.LicenseTerms",name:"licenseTerms",type:"tuple"},{internalType:"uint256",name:"deadline",type:"uint256"},{internalType:"bytes",name:"signature",type:"bytes"}],name:"mintWithSignature",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[],name:"name",outputs:[{internalType:"string",name:"",type:"string"}],stateMutability:"view",type:"function"},{inputs:[],name:"owner",outputs:[{internalType:"address",name:"",type:"address"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"uint256",name:"tokenId",type:"uint256"}],name:"ownerOf",outputs:[{internalType:"address",name:"",type:"address"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"uint256",name:"",type:"uint256"}],name:"parentIpOf",outputs:[{internalType:"uint256",name:"",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[],name:"pause",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[],name:"paused",outputs:[{internalType:"bool",name:"",type:"bool"}],stateMutability:"view",type:"function"},{inputs:[],name:"renounceOwnership",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"uint256",name:"tokenId",type:"uint256"},{internalType:"uint256",name:"salePrice",type:"uint256"}],name:"royaltyInfo",outputs:[{internalType:"address",name:"receiver",type:"address"},{internalType:"uint256",name:"royaltyAmount",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"uint256",name:"",type:"uint256"}],name:"royaltyPercentages",outputs:[{internalType:"uint16",name:"",type:"uint16"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"uint256",name:"",type:"uint256"}],name:"royaltyReceivers",outputs:[{internalType:"address",name:"",type:"address"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"address",name:"from",type:"address"},{internalType:"address",name:"to",type:"address"},{internalType:"uint256",name:"tokenId",type:"uint256"}],name:"safeTransferFrom",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"address",name:"from",type:"address"},{internalType:"address",name:"to",type:"address"},{internalType:"uint256",name:"tokenId",type:"uint256"},{internalType:"bytes",name:"data",type:"bytes"}],name:"safeTransferFrom",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"address",name:"operator",type:"address"},{internalType:"bool",name:"approved",type:"bool"}],name:"setApprovalForAll",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"address",name:"_signer",type:"address"}],name:"setSigner",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[],name:"signer",outputs:[{internalType:"address",name:"",type:"address"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"bytes4",name:"interfaceId",type:"bytes4"}],name:"supportsInterface",outputs:[{internalType:"bool",name:"",type:"bool"}],stateMutability:"view",type:"function"},{inputs:[],name:"symbol",outputs:[{internalType:"string",name:"",type:"string"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"uint256",name:"",type:"uint256"}],name:"terms",outputs:[{internalType:"uint128",name:"price",type:"uint128"},{internalType:"uint32",name:"duration",type:"uint32"},{internalType:"uint16",name:"royaltyBps",type:"uint16"},{internalType:"address",name:"paymentToken",type:"address"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"uint256",name:"_tokenId",type:"uint256"}],name:"tokenURI",outputs:[{internalType:"string",name:"",type:"string"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"address",name:"from",type:"address"},{internalType:"address",name:"to",type:"address"},{internalType:"uint256",name:"tokenId",type:"uint256"}],name:"transferFrom",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"address",name:"newOwner",type:"address"}],name:"transferOwnership",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[],name:"unpause",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"uint256",name:"tokenId",type:"uint256"},{internalType:"address",name:"_royaltyReceiver",type:"address"},{components:[{internalType:"uint128",name:"price",type:"uint128"},{internalType:"uint32",name:"duration",type:"uint32"},{internalType:"uint16",name:"royaltyBps",type:"uint16"},{internalType:"address",name:"paymentToken",type:"address"}],internalType:"struct IpNFT.LicenseTerms",name:"newTerms",type:"tuple"}],name:"updateTerms",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"bytes32",name:"",type:"bytes32"}],name:"usedNonces",outputs:[{internalType:"bool",name:"",type:"bool"}],stateMutability:"view",type:"function"}]; /** * Mints a Data NFT with a signature. * @param to The address to mint the NFT to. @@ -50,14 +50,14 @@ let y=null,h=null;const m=()=>(h||(h=t.createPublicClient({chain:c,transport:t.h * @param deadline The deadline for the minting operation. * @param signature The signature for the minting operation. * @returns A promise that resolves when the minting is complete. - */function C(e,t,n,i,r,s,o,d){return a(this,void 0,void 0,(function*(){return yield this.callContractMethod(T,k,"mintWithSignature",[e,t,n,i,r,s,o,d],{waitForReceipt:!0})}))} + */function E(e,t,n,i,a,s,o,d){return r(this,void 0,void 0,(function*(){return yield this.callContractMethod(g,C,"mintWithSignature",[e,t,n,i,a,s,o,d],{waitForReceipt:!0})}))} /** * Registers a Data NFT with the Origin service in order to obtain a signature for minting. * @param source The source of the Data NFT (e.g., "spotify", "twitter", "tiktok", or "file"). * @param deadline The deadline for the registration operation. * @param fileKey Optional file key for file uploads. * @return A promise that resolves with the registration data. - */function E(e,t,n,i,r,s){return a(this,void 0,void 0,(function*(){const a={source:e,deadline:Number(t),licenseTerms:{price:n.price.toString(),duration:n.duration,royaltyBps:n.royaltyBps,paymentToken:n.paymentToken},metadata:i,parentId:Number(s)||0};void 0!==r&&(a.fileKey=r);const o=yield fetch(`${w}/auth/origin/register`,{method:"POST",headers:{Authorization:`Bearer ${this.getJwt()}`,"Content-Type":"application/json"},body:JSON.stringify(a)});if(!o.ok)throw new Error(`Failed to get signature: ${o.statusText}`);const d=yield o.json();if(d.isError)throw new Error(`Failed to get signature: ${d.message}`);return d.data}))}function x(e,t,n){return this.callContractMethod(T,k,"updateTerms",[e,t,n],{waitForReceipt:!0})}function M(e){return this.callContractMethod(T,k,"finalizeDelete",[e])}function S(e){return this.callContractMethod(T,k,"getTerms",[e])}function $(e){return this.callContractMethod(T,k,"ownerOf",[e])}function F(e){return this.callContractMethod(T,k,"balanceOf",[e])}function O(e){return this.callContractMethod(T,k,"contentHash",[e])}function P(e){return this.callContractMethod(T,k,"tokenURI",[e])}function j(e){return this.callContractMethod(T,k,"dataStatus",[e])}function U(e,t){return a(this,void 0,void 0,(function*(){return this.callContractMethod(T,k,"royaltyInfo",[e,t])}))}function N(e){return this.callContractMethod(T,k,"getApproved",[e])}function D(e,t){return this.callContractMethod(T,k,"isApprovedForAll",[e,t])}function B(e,t,n){return this.callContractMethod(T,k,"transferFrom",[e,t,n])}function _(e,t,n,i){const a=i?[e,t,n,i]:[e,t,n];return this.callContractMethod(T,k,"safeTransferFrom",a)}function R(e,t){return this.callContractMethod(T,k,"approve",[e,t])}function W(e,t){return this.callContractMethod(T,k,"setApprovalForAll",[e,t])}var q,L,z,J,K,H,G,V,Z,Y,Q,X,ee,te,ne,ie=[{inputs:[{internalType:"address",name:"dataNFT_",type:"address"},{internalType:"uint16",name:"protocolFeeBps_",type:"uint16"},{internalType:"address",name:"treasury_",type:"address"}],stateMutability:"nonpayable",type:"constructor"},{inputs:[],name:"EnforcedPause",type:"error"},{inputs:[],name:"ExpectedPause",type:"error"},{inputs:[{internalType:"uint256",name:"expected",type:"uint256"},{internalType:"uint256",name:"actual",type:"uint256"}],name:"InvalidPayment",type:"error"},{inputs:[{internalType:"uint32",name:"periods",type:"uint32"}],name:"InvalidPeriods",type:"error"},{inputs:[{internalType:"uint16",name:"royaltyBps",type:"uint16"}],name:"InvalidRoyalty",type:"error"},{inputs:[{internalType:"address",name:"owner",type:"address"}],name:"OwnableInvalidOwner",type:"error"},{inputs:[{internalType:"address",name:"account",type:"address"}],name:"OwnableUnauthorizedAccount",type:"error"},{inputs:[],name:"TransferFailed",type:"error"},{inputs:[],name:"Unauthorized",type:"error"},{inputs:[],name:"ZeroAddress",type:"error"},{anonymous:!1,inputs:[{indexed:!0,internalType:"uint256",name:"tokenId",type:"uint256"},{indexed:!0,internalType:"address",name:"buyer",type:"address"},{indexed:!1,internalType:"uint32",name:"periods",type:"uint32"},{indexed:!1,internalType:"uint256",name:"newExpiry",type:"uint256"},{indexed:!1,internalType:"uint256",name:"amountPaid",type:"uint256"}],name:"AccessPurchased",type:"event"},{anonymous:!1,inputs:[{indexed:!0,internalType:"uint256",name:"tokenId",type:"uint256"},{indexed:!0,internalType:"address",name:"creator",type:"address"}],name:"DataDeleted",type:"event"},{anonymous:!1,inputs:[{indexed:!0,internalType:"uint256",name:"tokenId",type:"uint256"},{indexed:!0,internalType:"address",name:"creator",type:"address"},{indexed:!1,internalType:"bytes32",name:"contentHash",type:"bytes32"}],name:"DataMinted",type:"event"},{anonymous:!1,inputs:[{indexed:!0,internalType:"address",name:"previousOwner",type:"address"},{indexed:!0,internalType:"address",name:"newOwner",type:"address"}],name:"OwnershipTransferred",type:"event"},{anonymous:!1,inputs:[{indexed:!1,internalType:"address",name:"account",type:"address"}],name:"Paused",type:"event"},{anonymous:!1,inputs:[{indexed:!0,internalType:"uint256",name:"tokenId",type:"uint256"},{indexed:!1,internalType:"uint256",name:"royaltyAmount",type:"uint256"},{indexed:!1,internalType:"address",name:"creator",type:"address"},{indexed:!1,internalType:"uint256",name:"protocolAmount",type:"uint256"}],name:"RoyaltyPaid",type:"event"},{anonymous:!1,inputs:[{indexed:!0,internalType:"uint256",name:"tokenId",type:"uint256"},{indexed:!1,internalType:"uint128",name:"newPrice",type:"uint128"},{indexed:!1,internalType:"uint32",name:"newDuration",type:"uint32"},{indexed:!1,internalType:"uint16",name:"newRoyaltyBps",type:"uint16"},{indexed:!1,internalType:"address",name:"paymentToken",type:"address"}],name:"TermsUpdated",type:"event"},{anonymous:!1,inputs:[{indexed:!1,internalType:"address",name:"account",type:"address"}],name:"Unpaused",type:"event"},{inputs:[{internalType:"address",name:"feeManager",type:"address"}],name:"addFeeManager",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"address",name:"buyer",type:"address"},{internalType:"uint256",name:"tokenId",type:"uint256"},{internalType:"uint32",name:"periods",type:"uint32"}],name:"buyAccess",outputs:[],stateMutability:"payable",type:"function"},{inputs:[],name:"dataNFT",outputs:[{internalType:"contract IpNFT",name:"",type:"address"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"address",name:"",type:"address"}],name:"feeManagers",outputs:[{internalType:"bool",name:"",type:"bool"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"address",name:"user",type:"address"},{internalType:"uint256",name:"tokenId",type:"uint256"}],name:"hasAccess",outputs:[{internalType:"bool",name:"",type:"bool"}],stateMutability:"view",type:"function"},{inputs:[],name:"owner",outputs:[{internalType:"address",name:"",type:"address"}],stateMutability:"view",type:"function"},{inputs:[],name:"pause",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[],name:"paused",outputs:[{internalType:"bool",name:"",type:"bool"}],stateMutability:"view",type:"function"},{inputs:[],name:"protocolFeeBps",outputs:[{internalType:"uint16",name:"",type:"uint16"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"address",name:"feeManager",type:"address"}],name:"removeFeeManager",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[],name:"renounceOwnership",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"uint256",name:"",type:"uint256"},{internalType:"address",name:"",type:"address"}],name:"subscriptionExpiry",outputs:[{internalType:"uint256",name:"",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"address",name:"newOwner",type:"address"}],name:"transferOwnership",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[],name:"treasury",outputs:[{internalType:"address",name:"",type:"address"}],stateMutability:"view",type:"function"},{inputs:[],name:"unpause",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"uint16",name:"newFeeBps",type:"uint16"}],name:"updateProtocolFee",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"address",name:"newTreasury",type:"address"}],name:"updateTreasury",outputs:[],stateMutability:"nonpayable",type:"function"},{stateMutability:"payable",type:"receive"}];function ae(e,t,n,i){return this.callContractMethod(b,ie,"buyAccess",[e,t,n],{waitForReceipt:!0,value:i})}function re(e,t,n,i){return this.callContractMethod(b,ie,"renewAccess",[e,t,n],void 0!==i?{value:i}:void 0)}function se(e,t){return this.callContractMethod(b,ie,"hasAccess",[e,t])}function oe(e,t){return this.callContractMethod(b,ie,"subscriptionExpiry",[e,t])} + */function x(e,t,n,i,a,s){return r(this,void 0,void 0,(function*(){const r={source:e,deadline:Number(t),licenseTerms:{price:n.price.toString(),duration:n.duration,royaltyBps:n.royaltyBps,paymentToken:n.paymentToken},metadata:i,parentId:Number(s)||0};void 0!==a&&(r.fileKey=a);const o=yield fetch(`${v}/auth/origin/register`,{method:"POST",headers:{Authorization:`Bearer ${this.getJwt()}`,"Content-Type":"application/json"},body:JSON.stringify(r)});if(!o.ok)throw new Error(`Failed to get signature: ${o.statusText}`);const d=yield o.json();if(d.isError)throw new Error(`Failed to get signature: ${d.message}`);return d.data}))}function S(e,t,n){return this.callContractMethod(g,C,"updateTerms",[e,t,n],{waitForReceipt:!0})}function M(e){return this.callContractMethod(g,C,"finalizeDelete",[e])}function P(e){return this.callContractMethod(g,C,"getTerms",[e])}function $(e){return this.callContractMethod(g,C,"ownerOf",[e])}function F(e){return this.callContractMethod(g,C,"balanceOf",[e])}function U(e){return this.callContractMethod(g,C,"contentHash",[e])}function O(e){return this.callContractMethod(g,C,"tokenURI",[e])}function N(e){return this.callContractMethod(g,C,"dataStatus",[e])}function j(e,t){return r(this,void 0,void 0,(function*(){return this.callContractMethod(g,C,"royaltyInfo",[e,t])}))}function D(e){return this.callContractMethod(g,C,"getApproved",[e])}function _(e,t){return this.callContractMethod(g,C,"isApprovedForAll",[e,t])}function B(e,t,n){return this.callContractMethod(g,C,"transferFrom",[e,t,n])}function q(e,t,n,i){const r=i?[e,t,n,i]:[e,t,n];return this.callContractMethod(g,C,"safeTransferFrom",r)}function L(e,t){return this.callContractMethod(g,C,"approve",[e,t])}function W(e,t){return this.callContractMethod(g,C,"setApprovalForAll",[e,t])}var R,z,K,J,H,G,Z,V,Y,Q,X,ee,te,ne,ie,re=[{inputs:[{internalType:"address",name:"dataNFT_",type:"address"},{internalType:"uint16",name:"protocolFeeBps_",type:"uint16"},{internalType:"address",name:"treasury_",type:"address"}],stateMutability:"nonpayable",type:"constructor"},{inputs:[],name:"EnforcedPause",type:"error"},{inputs:[],name:"ExpectedPause",type:"error"},{inputs:[{internalType:"uint256",name:"expected",type:"uint256"},{internalType:"uint256",name:"actual",type:"uint256"}],name:"InvalidPayment",type:"error"},{inputs:[{internalType:"uint32",name:"periods",type:"uint32"}],name:"InvalidPeriods",type:"error"},{inputs:[{internalType:"uint16",name:"royaltyBps",type:"uint16"}],name:"InvalidRoyalty",type:"error"},{inputs:[{internalType:"address",name:"owner",type:"address"}],name:"OwnableInvalidOwner",type:"error"},{inputs:[{internalType:"address",name:"account",type:"address"}],name:"OwnableUnauthorizedAccount",type:"error"},{inputs:[],name:"TransferFailed",type:"error"},{inputs:[],name:"Unauthorized",type:"error"},{inputs:[],name:"ZeroAddress",type:"error"},{anonymous:!1,inputs:[{indexed:!0,internalType:"uint256",name:"tokenId",type:"uint256"},{indexed:!0,internalType:"address",name:"buyer",type:"address"},{indexed:!1,internalType:"uint32",name:"periods",type:"uint32"},{indexed:!1,internalType:"uint256",name:"newExpiry",type:"uint256"},{indexed:!1,internalType:"uint256",name:"amountPaid",type:"uint256"}],name:"AccessPurchased",type:"event"},{anonymous:!1,inputs:[{indexed:!0,internalType:"uint256",name:"tokenId",type:"uint256"},{indexed:!0,internalType:"address",name:"creator",type:"address"}],name:"DataDeleted",type:"event"},{anonymous:!1,inputs:[{indexed:!0,internalType:"uint256",name:"tokenId",type:"uint256"},{indexed:!0,internalType:"address",name:"creator",type:"address"},{indexed:!1,internalType:"bytes32",name:"contentHash",type:"bytes32"}],name:"DataMinted",type:"event"},{anonymous:!1,inputs:[{indexed:!0,internalType:"address",name:"previousOwner",type:"address"},{indexed:!0,internalType:"address",name:"newOwner",type:"address"}],name:"OwnershipTransferred",type:"event"},{anonymous:!1,inputs:[{indexed:!1,internalType:"address",name:"account",type:"address"}],name:"Paused",type:"event"},{anonymous:!1,inputs:[{indexed:!0,internalType:"uint256",name:"tokenId",type:"uint256"},{indexed:!1,internalType:"uint256",name:"royaltyAmount",type:"uint256"},{indexed:!1,internalType:"address",name:"creator",type:"address"},{indexed:!1,internalType:"uint256",name:"protocolAmount",type:"uint256"}],name:"RoyaltyPaid",type:"event"},{anonymous:!1,inputs:[{indexed:!0,internalType:"uint256",name:"tokenId",type:"uint256"},{indexed:!1,internalType:"uint128",name:"newPrice",type:"uint128"},{indexed:!1,internalType:"uint32",name:"newDuration",type:"uint32"},{indexed:!1,internalType:"uint16",name:"newRoyaltyBps",type:"uint16"},{indexed:!1,internalType:"address",name:"paymentToken",type:"address"}],name:"TermsUpdated",type:"event"},{anonymous:!1,inputs:[{indexed:!1,internalType:"address",name:"account",type:"address"}],name:"Unpaused",type:"event"},{inputs:[{internalType:"address",name:"feeManager",type:"address"}],name:"addFeeManager",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"address",name:"buyer",type:"address"},{internalType:"uint256",name:"tokenId",type:"uint256"},{internalType:"uint32",name:"periods",type:"uint32"}],name:"buyAccess",outputs:[],stateMutability:"payable",type:"function"},{inputs:[],name:"dataNFT",outputs:[{internalType:"contract IpNFT",name:"",type:"address"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"address",name:"",type:"address"}],name:"feeManagers",outputs:[{internalType:"bool",name:"",type:"bool"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"address",name:"user",type:"address"},{internalType:"uint256",name:"tokenId",type:"uint256"}],name:"hasAccess",outputs:[{internalType:"bool",name:"",type:"bool"}],stateMutability:"view",type:"function"},{inputs:[],name:"owner",outputs:[{internalType:"address",name:"",type:"address"}],stateMutability:"view",type:"function"},{inputs:[],name:"pause",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[],name:"paused",outputs:[{internalType:"bool",name:"",type:"bool"}],stateMutability:"view",type:"function"},{inputs:[],name:"protocolFeeBps",outputs:[{internalType:"uint16",name:"",type:"uint16"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"address",name:"feeManager",type:"address"}],name:"removeFeeManager",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[],name:"renounceOwnership",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"uint256",name:"",type:"uint256"},{internalType:"address",name:"",type:"address"}],name:"subscriptionExpiry",outputs:[{internalType:"uint256",name:"",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"address",name:"newOwner",type:"address"}],name:"transferOwnership",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[],name:"treasury",outputs:[{internalType:"address",name:"",type:"address"}],stateMutability:"view",type:"function"},{inputs:[],name:"unpause",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"uint16",name:"newFeeBps",type:"uint16"}],name:"updateProtocolFee",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"address",name:"newTreasury",type:"address"}],name:"updateTreasury",outputs:[],stateMutability:"nonpayable",type:"function"},{stateMutability:"payable",type:"receive"}];function ae(e,t,n,i){return this.callContractMethod(b,re,"buyAccess",[e,t,n],{waitForReceipt:!0,value:i})}function se(e,t,n,i){return this.callContractMethod(b,re,"renewAccess",[e,t,n],void 0!==i?{value:i}:void 0)}function oe(e,t){return this.callContractMethod(b,re,"hasAccess",[e,t])}function de(e,t){return this.callContractMethod(b,re,"subscriptionExpiry",[e,t])} /** * Approves a spender to spend a specified amount of tokens on behalf of the owner. * If the current allowance is less than the specified amount, it will perform the approval. @@ -67,18 +67,18 @@ let y=null,h=null;const m=()=>(h||(h=t.createPublicClient({chain:c,transport:t.h * The Origin class * Handles the upload of files to Origin, as well as querying the user's stats */ -class de{constructor(t,n){q.add(this),L.set(this,(e=>a(this,void 0,void 0,(function*(){try{const t=yield fetch(`${w}/auth/origin/upload-url`,{method:"POST",body:JSON.stringify({name:e.name,type:e.type}),headers:{Authorization:`Bearer ${this.jwt}`,"Content-Type":"application/json"}});if(!t.ok)throw new Error(`HTTP ${t.status}: ${t.statusText}`);const n=yield t.json();if(n.isError)throw new Error(n.message||"Failed to generate upload URL");return n.data}catch(e){throw console.error("Failed to generate upload URL:",e),e}})))),z.set(this,((e,t)=>a(this,void 0,void 0,(function*(){try{const n=yield fetch(`${w}/auth/origin/update-status`,{method:"PATCH",body:JSON.stringify({status:t,fileKey:e}),headers:{Authorization:`Bearer ${this.jwt}`,"Content-Type":"application/json"}});if(!n.ok){const e=yield n.text().catch((()=>"Unknown error"));throw new Error(`HTTP ${n.status}: ${e}`)}return!0}catch(e){throw console.error("Failed to update origin status:",e),e}})))),this.uploadFile=(t,n)=>a(this,void 0,void 0,(function*(){let i;try{i=yield r(this,L,"f").call(this,t)}catch(e){throw console.error("Failed to generate upload URL:",e),new Error(`Failed to generate upload URL: ${e instanceof Error?e.message:String(e)}`)}if(!i)throw new Error("Failed to generate upload URL: No upload info returned");try{yield((t,n,i)=>new Promise(((a,r)=>{e.put(n,t,Object.assign({headers:{"Content-Type":t.type}},"undefined"!=typeof window&&"function"==typeof i?{onUploadProgress:e=>{if(e.total){const t=e.loaded/e.total*100;i(t)}}}:{})).then((e=>{a(e.data)})).catch((e=>{var t;const n=(null===(t=null==e?void 0:e.response)||void 0===t?void 0:t.data)||(null==e?void 0:e.message)||"Upload failed";r(n)}))})))(t,i.url,(null==n?void 0:n.progressCallback)||(()=>{}))}catch(e){try{yield r(this,z,"f").call(this,i.key,"failed")}catch(e){console.error("Failed to update status to failed:",e)}const t=e instanceof Error?e.message:String(e);throw new Error(`Failed to upload file: ${t}`)}try{yield r(this,z,"f").call(this,i.key,"success")}catch(e){console.error("Failed to update status to success:",e)}return i})),this.mintFile=(e,t,n,i,r)=>a(this,void 0,void 0,(function*(){if(!this.viemClient)throw new Error("WalletClient not connected.");const a=yield this.uploadFile(e,r);if(!a||!a.key)throw new Error("Failed to upload file or get upload info.");const s=BigInt(Math.floor(Date.now()/1e3)+600),o=yield this.registerIpNFT("file",s,n,t,a.key,i),{tokenId:d,signerAddress:u,creatorContentHash:l,signature:p,uri:c}=o;// 10 minutes from now -if(!(d&&u&&l&&void 0!==p&&c))throw new Error("Failed to register IpNFT: Missing required fields in registration response.");const[y]=yield this.viemClient.request({method:"eth_requestAccounts",params:[]}),h=yield this.mintWithSignature(y,d,i||BigInt(0),l,c,n,s,p);if("0x1"!==h.status)throw new Error(`Minting failed with status: ${h.status}`);return d.toString()})),this.mintSocial=(e,t,n)=>a(this,void 0,void 0,(function*(){if(!this.viemClient)throw new Error("WalletClient not connected.");const i=BigInt(Math.floor(Date.now()/1e3)+600),a=yield this.registerIpNFT(e,i,n,t),{tokenId:r,signerAddress:s,creatorContentHash:o,signature:d,uri:u}=a;// 10 minutes from now -if(!(r&&s&&o&&void 0!==d&&u))throw new Error("Failed to register Social IpNFT: Missing required fields in registration response.");const[l]=yield this.viemClient.request({method:"eth_requestAccounts",params:[]}),p=yield this.mintWithSignature(l,r,BigInt(0),// parentId is not applicable for social IpNFTs -o,u,n,i,d);if("0x1"!==p.status)throw new Error(`Minting Social IpNFT failed with status: ${p.status}`);return r.toString()})),this.getOriginUploads=()=>a(this,void 0,void 0,(function*(){const e=yield fetch(`${w}/auth/origin/files`,{method:"GET",headers:{Authorization:`Bearer ${this.jwt}`}});if(!e.ok)return console.error("Failed to get origin uploads"),null;return(yield e.json()).data})),this.jwt=t,this.viemClient=n, +class ue{constructor(t,n){R.add(this),z.set(this,(e=>r(this,void 0,void 0,(function*(){try{const t=yield fetch(`${v}/auth/origin/upload-url`,{method:"POST",body:JSON.stringify({name:e.name,type:e.type}),headers:{Authorization:`Bearer ${this.jwt}`,"Content-Type":"application/json"}});if(!t.ok)throw new Error(`HTTP ${t.status}: ${t.statusText}`);const n=yield t.json();if(n.isError)throw new Error(n.message||"Failed to generate upload URL");return n.data}catch(e){throw console.error("Failed to generate upload URL:",e),e}})))),K.set(this,((e,t)=>r(this,void 0,void 0,(function*(){try{const n=yield fetch(`${v}/auth/origin/update-status`,{method:"PATCH",body:JSON.stringify({status:t,fileKey:e}),headers:{Authorization:`Bearer ${this.jwt}`,"Content-Type":"application/json"}});if(!n.ok){const e=yield n.text().catch((()=>"Unknown error"));throw new Error(`HTTP ${n.status}: ${e}`)}return!0}catch(e){throw console.error("Failed to update origin status:",e),e}})))),this.uploadFile=(t,n)=>r(this,void 0,void 0,(function*(){let i;try{i=yield a(this,z,"f").call(this,t)}catch(e){throw console.error("Failed to generate upload URL:",e),new Error(`Failed to generate upload URL: ${e instanceof Error?e.message:String(e)}`)}if(!i)throw new Error("Failed to generate upload URL: No upload info returned");try{yield((t,n,i)=>new Promise(((r,a)=>{e.put(n,t,Object.assign({headers:{"Content-Type":t.type}},"undefined"!=typeof window&&"function"==typeof i?{onUploadProgress:e=>{if(e.total){const t=e.loaded/e.total*100;i(t)}}}:{})).then((e=>{r(e.data)})).catch((e=>{var t;const n=(null===(t=null==e?void 0:e.response)||void 0===t?void 0:t.data)||(null==e?void 0:e.message)||"Upload failed";a(n)}))})))(t,i.url,(null==n?void 0:n.progressCallback)||(()=>{}))}catch(e){try{yield a(this,K,"f").call(this,i.key,"failed")}catch(e){console.error("Failed to update status to failed:",e)}const t=e instanceof Error?e.message:String(e);throw new Error(`Failed to upload file: ${t}`)}try{yield a(this,K,"f").call(this,i.key,"success")}catch(e){console.error("Failed to update status to success:",e)}return i})),this.mintFile=(e,t,n,i,a)=>r(this,void 0,void 0,(function*(){if(!this.viemClient)throw new Error("WalletClient not connected.");const r=yield this.uploadFile(e,a);if(!r||!r.key)throw new Error("Failed to upload file or get upload info.");const s=BigInt(Math.floor(Date.now()/1e3)+600),o=yield this.registerIpNFT("file",s,n,t,r.key,i),{tokenId:d,signerAddress:u,creatorContentHash:l,signature:p,uri:c}=o;// 10 minutes from now +if(!(d&&u&&l&&void 0!==p&&c))throw new Error("Failed to register IpNFT: Missing required fields in registration response.");const[y]=yield this.viemClient.request({method:"eth_requestAccounts",params:[]}),h=yield this.mintWithSignature(y,d,i||BigInt(0),l,c,n,s,p);if("0x1"!==h.status)throw new Error(`Minting failed with status: ${h.status}`);return d.toString()})),this.mintSocial=(e,t,n)=>r(this,void 0,void 0,(function*(){if(!this.viemClient)throw new Error("WalletClient not connected.");const i=BigInt(Math.floor(Date.now()/1e3)+600),r=yield this.registerIpNFT(e,i,n,t),{tokenId:a,signerAddress:s,creatorContentHash:o,signature:d,uri:u}=r;// 10 minutes from now +if(!(a&&s&&o&&void 0!==d&&u))throw new Error("Failed to register Social IpNFT: Missing required fields in registration response.");const[l]=yield this.viemClient.request({method:"eth_requestAccounts",params:[]}),p=yield this.mintWithSignature(l,a,BigInt(0),// parentId is not applicable for social IpNFTs +o,u,n,i,d);if("0x1"!==p.status)throw new Error(`Minting Social IpNFT failed with status: ${p.status}`);return a.toString()})),this.getOriginUploads=()=>r(this,void 0,void 0,(function*(){const e=yield fetch(`${v}/auth/origin/files`,{method:"GET",headers:{Authorization:`Bearer ${this.jwt}`}});if(!e.ok)return console.error("Failed to get origin uploads"),null;return(yield e.json()).data})),this.jwt=t,this.viemClient=n, // DataNFT methods -this.mintWithSignature=C.bind(this),this.registerIpNFT=E.bind(this),this.updateTerms=x.bind(this),this.requestDelete=M.bind(this),this.getTerms=S.bind(this),this.ownerOf=$.bind(this),this.balanceOf=F.bind(this),this.contentHash=O.bind(this),this.tokenURI=P.bind(this),this.dataStatus=j.bind(this),this.royaltyInfo=U.bind(this),this.getApproved=N.bind(this),this.isApprovedForAll=D.bind(this),this.transferFrom=B.bind(this),this.safeTransferFrom=_.bind(this),this.approve=R.bind(this),this.setApprovalForAll=W.bind(this), +this.mintWithSignature=E.bind(this),this.registerIpNFT=x.bind(this),this.updateTerms=S.bind(this),this.requestDelete=M.bind(this),this.getTerms=P.bind(this),this.ownerOf=$.bind(this),this.balanceOf=F.bind(this),this.contentHash=U.bind(this),this.tokenURI=O.bind(this),this.dataStatus=N.bind(this),this.royaltyInfo=j.bind(this),this.getApproved=D.bind(this),this.isApprovedForAll=_.bind(this),this.transferFrom=B.bind(this),this.safeTransferFrom=q.bind(this),this.approve=L.bind(this),this.setApprovalForAll=W.bind(this), // Marketplace methods -this.buyAccess=ae.bind(this),this.renewAccess=re.bind(this),this.hasAccess=se.bind(this),this.subscriptionExpiry=oe.bind(this)}getJwt(){return this.jwt}setViemClient(e){this.viemClient=e} +this.buyAccess=ae.bind(this),this.renewAccess=se.bind(this),this.hasAccess=oe.bind(this),this.subscriptionExpiry=de.bind(this)}getJwt(){return this.jwt}setViemClient(e){this.viemClient=e} /** * Get the user's Origin stats (multiplier, consent, usage, etc.). * @returns {Promise} A promise that resolves with the user's Origin stats. - */getOriginUsage(){return a(this,void 0,void 0,(function*(){const e=yield fetch(`${w}/auth/origin/usage`,{method:"GET",headers:{Authorization:`Bearer ${this.jwt}`, + */getOriginUsage(){return r(this,void 0,void 0,(function*(){const e=yield fetch(`${v}/auth/origin/usage`,{method:"GET",headers:{Authorization:`Bearer ${this.jwt}`, // "x-client-id": this.clientId, "Content-Type":"application/json"}}).then((e=>e.json()));if(!e.isError&&e.data.user)return e;throw new o(e.message||"Failed to fetch Origin usage")}))} /** @@ -86,7 +86,7 @@ this.buyAccess=ae.bind(this),this.renewAccess=re.bind(this),this.hasAccess=se.bi * @param {boolean} consent The user's consent. * @returns {Promise} * @throws {Error|APIError} - Throws an error if the user is not authenticated. Also throws an error if the consent is not provided. - */setOriginConsent(e){return a(this,void 0,void 0,(function*(){if(void 0===e)throw new o("Consent is required");const t=yield fetch(`${w}/auth/origin/status`,{method:"PATCH",headers:{Authorization:`Bearer ${this.jwt}`, + */setOriginConsent(e){return r(this,void 0,void 0,(function*(){if(void 0===e)throw new o("Consent is required");const t=yield fetch(`${v}/auth/origin/status`,{method:"PATCH",headers:{Authorization:`Bearer ${this.jwt}`, // "x-client-id": this.clientId, "Content-Type":"application/json"},body:JSON.stringify({active:e})}).then((e=>e.json()));if(t.isError)throw new o(t.message||"Failed to set Origin consent")}))} /** @@ -94,7 +94,7 @@ this.buyAccess=ae.bind(this),this.renewAccess=re.bind(this),this.hasAccess=se.bi * @param {number} multiplier The user's Origin multiplier. * @returns {Promise} * @throws {Error|APIError} - Throws an error if the user is not authenticated. Also throws an error if the multiplier is not provided. - */setOriginMultiplier(e){return a(this,void 0,void 0,(function*(){if(void 0===e)throw new o("Multiplier is required");const t=yield fetch(`${w}/auth/origin/multiplier`,{method:"PATCH",headers:{Authorization:`Bearer ${this.jwt}`, + */setOriginMultiplier(e){return r(this,void 0,void 0,(function*(){if(void 0===e)throw new o("Multiplier is required");const t=yield fetch(`${v}/auth/origin/multiplier`,{method:"PATCH",headers:{Authorization:`Bearer ${this.jwt}`, // "x-client-id": this.clientId, "Content-Type":"application/json"},body:JSON.stringify({multiplier:e})}).then((e=>e.json()));if(t.isError)throw new o(t.message||"Failed to set Origin multiplier")}))} /** @@ -106,17 +106,17 @@ this.buyAccess=ae.bind(this),this.renewAccess=re.bind(this),this.hasAccess=se.bi * @param {CallOptions} [options] The call options. * @returns {Promise} A promise that resolves with the result of the contract call or transaction hash. * @throws {Error} - Throws an error if the wallet client is not connected and the method is not a view function. - */callContractMethod(e,n,i,s){return a(this,arguments,void 0,(function*(e,n,i,a,s={}){const o=t.getAbiItem({abi:n,name:i}),d=o&&"stateMutability"in o&&("view"===o.stateMutability||"pure"===o.stateMutability);if(!d&&!this.viemClient)throw new Error("WalletClient not connected.");if(d){const t=m();return(yield t.readContract({address:e,abi:n,functionName:i,args:a}))||null}{const[o]=yield this.viemClient.request({method:"eth_requestAccounts",params:[]}),d=t.encodeFunctionData({abi:n,functionName:i,args:a});yield r(this,q,"m",K).call(this,c);try{const t=yield this.viemClient.sendTransaction({to:e,data:d,account:o,value:s.value,gas:s.gas});if("string"!=typeof t)throw new Error("Transaction failed to send.");if(!s.waitForReceipt)return t;return yield r(this,q,"m",J).call(this,t)}catch(e){throw console.error("Transaction failed:",e),new Error("Transaction failed: "+e)}}}))} + */callContractMethod(e,n,i,s){return r(this,arguments,void 0,(function*(e,n,i,r,s={}){const o=t.getAbiItem({abi:n,name:i}),d=o&&"stateMutability"in o&&("view"===o.stateMutability||"pure"===o.stateMutability);if(!d&&!this.viemClient)throw new Error("WalletClient not connected.");if(d){const t=f();return(yield t.readContract({address:e,abi:n,functionName:i,args:r}))||null}{const[o]=yield this.viemClient.request({method:"eth_requestAccounts",params:[]}),d=t.encodeFunctionData({abi:n,functionName:i,args:r});yield a(this,R,"m",H).call(this,y);try{const t=yield this.viemClient.sendTransaction({to:e,data:d,account:o,value:s.value,gas:s.gas});if("string"!=typeof t)throw new Error("Transaction failed to send.");if(!s.waitForReceipt)return t;return yield a(this,R,"m",J).call(this,t)}catch(e){throw console.error("Transaction failed:",e),new Error("Transaction failed: "+e)}}}))} /** * Buy access to an asset by first checking its price via getTerms, then calling buyAccess. * @param {bigint} tokenId The token ID of the asset. * @param {number} periods The number of periods to buy access for. * @returns {Promise} The result of the buyAccess call. - */buyAccessSmart(e,n){return a(this,void 0,void 0,(function*(){if(!this.viemClient)throw new Error("WalletClient not connected.");const i=yield this.getTerms(e);if(!i)throw new Error("Failed to fetch terms for asset");const{price:r,paymentToken:s}=i;if(void 0===r||void 0===s)throw new Error("Terms missing price or paymentToken");const[o]=yield this.viemClient.request({method:"eth_requestAccounts",params:[]}),d=r*BigInt(n);return s===t.zeroAddress?this.buyAccess(o,e,n,d):(yield function(e){return a(this,arguments,void 0,(function*({walletClient:e,publicClient:n,tokenAddress:i,owner:a,spender:r,amount:s}){(yield n.readContract({address:i,abi:t.erc20Abi,functionName:"allowance",args:[a,r]}))setTimeout(e,1e3)))}}))},K=function(e){return a(this,void 0,void 0,(function*(){ + */buyAccessSmart(e,n){return r(this,void 0,void 0,(function*(){if(!this.viemClient)throw new Error("WalletClient not connected.");const i=yield this.getTerms(e);if(!i)throw new Error("Failed to fetch terms for asset");const{price:a,paymentToken:s}=i;if(void 0===a||void 0===s)throw new Error("Terms missing price or paymentToken");const[o]=yield this.viemClient.request({method:"eth_requestAccounts",params:[]}),d=a*BigInt(n);return s===t.zeroAddress?this.buyAccess(o,e,n,d):(yield function(e){return r(this,arguments,void 0,(function*({walletClient:e,publicClient:n,tokenAddress:i,owner:r,spender:a,amount:s}){(yield n.readContract({address:i,abi:t.erc20Abi,functionName:"allowance",args:[r,a]}))setTimeout(e,1e3)))}}))},H=function(e){return r(this,void 0,void 0,(function*(){ // return; if(!this.viemClient)throw new Error("WalletClient not connected.");let t=yield this.viemClient.request({method:"eth_chainId",params:[]});if("string"==typeof t&&(t=parseInt(t,16)),t!==e.id)try{yield this.viemClient.request({method:"wallet_switchEthereumChain",params:[{chainId:"0x"+BigInt(e.id).toString(16)}]})}catch(t){ // Unrecognized chain -if(4902!==t.code)throw t;yield this.viemClient.request({method:"wallet_addEthereumChain",params:[{chainId:"0x"+BigInt(e.id).toString(16),chainName:e.name,rpcUrls:e.rpcUrls.default.http,nativeCurrency:e.nativeCurrency}]}),yield this.viemClient.request({method:"wallet_switchEthereumChain",params:[{chainId:"0x"+BigInt(e.id).toString(16)}]})}}))};G=new WeakMap,V=new WeakMap,H=new WeakSet,Z=function(e,t){r(this,G,"f")[e]&&r(this,G,"f")[e].forEach((e=>e(t)))},Y=function(e){return a(this,void 0,void 0,(function*(){if("undefined"==typeof localStorage)return;const t=null===localStorage||void 0===localStorage?void 0:localStorage.getItem("camp-sdk:wallet-address"),n=null===localStorage||void 0===localStorage?void 0:localStorage.getItem("camp-sdk:user-id"),i=null===localStorage||void 0===localStorage?void 0:localStorage.getItem("camp-sdk:jwt");t&&n&&i?(this.walletAddress=t,this.userId=n,this.jwt=i,this.origin=new de(this.jwt),this.isAuthenticated=!0,e?this.setProvider({provider:e.provider,info:e.info||{name:"Unknown"},address:t}):(console.warn("No matching provider was given for the stored wallet address. Trying to recover provider."),yield this.recoverProvider())):this.isAuthenticated=!1}))},Q=function(){return a(this,void 0,void 0,(function*(){try{const[e]=yield this.viem.requestAddresses();return this.walletAddress=t.checksumAddress(e),this.walletAddress}catch(e){throw new o(e)}}))},X=function(){return a(this,void 0,void 0,(function*(){try{const e=yield fetch(`${w}/auth/client-user/nonce`,{method:"POST",headers:{"Content-Type":"application/json","x-client-id":this.clientId},body:JSON.stringify({walletAddress:this.walletAddress})}),t=yield e.json();return 200!==e.status?Promise.reject(t.message||"Failed to fetch nonce"):t.data}catch(e){throw new Error(e)}}))},ee=function(e,t){return a(this,void 0,void 0,(function*(){try{const n=yield fetch(`${w}/auth/client-user/verify`,{method:"POST",headers:{"Content-Type":"application/json","x-client-id":this.clientId},body:JSON.stringify({message:e,signature:t,walletAddress:this.walletAddress})}),i=yield n.json(),a=i.data.split(".")[1],r=JSON.parse(atob(a));return{success:!i.isError,userId:r.id,token:i.data}}catch(e){throw new o(e)}}))},te=function(e){return i.createSiweMessage({domain:window.location.host,address:this.walletAddress,statement:f,uri:window.location.origin,version:"1",chainId:this.viem.chain.id,nonce:e})},ne=function(e,t){return a(this,arguments,void 0,(function*(e,t,n=1){ +if(4902!==t.code)throw t;yield this.viemClient.request({method:"wallet_addEthereumChain",params:[{chainId:"0x"+BigInt(e.id).toString(16),chainName:e.name,rpcUrls:e.rpcUrls.default.http,nativeCurrency:e.nativeCurrency}]}),yield this.viemClient.request({method:"wallet_switchEthereumChain",params:[{chainId:"0x"+BigInt(e.id).toString(16)}]})}}))};Z=new WeakMap,V=new WeakMap,G=new WeakSet,Y=function(e,t){a(this,Z,"f")[e]&&a(this,Z,"f")[e].forEach((e=>e(t)))},Q=function(e){return r(this,void 0,void 0,(function*(){if("undefined"==typeof localStorage)return;const t=null===localStorage||void 0===localStorage?void 0:localStorage.getItem("camp-sdk:wallet-address"),n=null===localStorage||void 0===localStorage?void 0:localStorage.getItem("camp-sdk:user-id"),i=null===localStorage||void 0===localStorage?void 0:localStorage.getItem("camp-sdk:jwt");t&&n&&i?(this.walletAddress=t,this.userId=n,this.jwt=i,this.origin=new ue(this.jwt),this.isAuthenticated=!0,e?this.setProvider({provider:e.provider,info:e.info||{name:"Unknown"},address:t}):(console.warn("No matching provider was given for the stored wallet address. Trying to recover provider."),yield this.recoverProvider())):this.isAuthenticated=!1}))},X=function(){return r(this,void 0,void 0,(function*(){try{const[e]=yield this.viem.requestAddresses();return this.walletAddress=t.checksumAddress(e),this.walletAddress}catch(e){throw new o(e)}}))},ee=function(){return r(this,void 0,void 0,(function*(){try{const e=yield fetch(`${v}/auth/client-user/nonce`,{method:"POST",headers:{"Content-Type":"application/json","x-client-id":this.clientId},body:JSON.stringify({walletAddress:this.walletAddress})}),t=yield e.json();return 200!==e.status?Promise.reject(t.message||"Failed to fetch nonce"):t.data}catch(e){throw new Error(e)}}))},te=function(e,t){return r(this,void 0,void 0,(function*(){try{const n=yield fetch(`${v}/auth/client-user/verify`,{method:"POST",headers:{"Content-Type":"application/json","x-client-id":this.clientId},body:JSON.stringify({message:e,signature:t,walletAddress:this.walletAddress})}),i=yield n.json(),r=i.data.split(".")[1],a=JSON.parse(atob(r));return{success:!i.isError,userId:a.id,token:i.data}}catch(e){throw new o(e)}}))},ne=function(e){return i.createSiweMessage({domain:window.location.host,address:this.walletAddress,statement:w,uri:window.location.origin,version:"1",chainId:this.viem.chain.id,nonce:e})},ie=function(e,t){return r(this,arguments,void 0,(function*(e,t,n=1){ // if (this.#ackeeInstance) // await sendAnalyticsEvent(this.#ackeeInstance, event, message, count); // else return; @@ -136,11 +136,11 @@ class{ * @param {object} [options.ackeeInstance] The Ackee instance. * @throws {APIError} - Throws an error if the clientId is not provided. */ -constructor({clientId:e,redirectUri:t,allowAnalytics:n=!0,ackeeInstance:i}){if(H.add(this),G.set(this,void 0),V.set(this,void 0),!e)throw new Error("clientId is required");this.viem=null, +constructor({clientId:e,redirectUri:t,allowAnalytics:n=!0,ackeeInstance:i}){if(G.add(this),Z.set(this,void 0),V.set(this,void 0),!e)throw new Error("clientId is required");this.viem=null, // if (typeof window !== "undefined") { // if (window.ethereum) this.viem = getClient(window.ethereum); // } -this.redirectUri=(e=>{const t=["twitter","discord","spotify"];return"object"==typeof e?t.reduce(((t,n)=>(t[n]=e[n]||("undefined"!=typeof window?window.location.href:""),t)),{}):"string"==typeof e?t.reduce(((t,n)=>(t[n]=e,t)),{}):e?{}:t.reduce(((e,t)=>(e[t]="undefined"!=typeof window?window.location.href:"",e)),{})})(t),i&&s(this,V,i,"f"),n&&r(this,V,"f"),this.clientId=e,this.isAuthenticated=!1,this.jwt=null,this.origin=null,this.walletAddress=null,this.userId=null,s(this,G,{},"f"),A((e=>{r(this,H,"m",Z).call(this,"providers",e)})),r(this,H,"m",Y).call(this)} +this.redirectUri=(e=>{const t=["twitter","discord","spotify"];return"object"==typeof e?t.reduce(((t,n)=>(t[n]=e[n]||("undefined"!=typeof window?window.location.href:""),t)),{}):"string"==typeof e?t.reduce(((t,n)=>(t[n]=e,t)),{}):e?{}:t.reduce(((e,t)=>(e[t]="undefined"!=typeof window?window.location.href:"",e)),{})})(t),i&&s(this,V,i,"f"),n&&a(this,V,"f"),this.clientId=e,this.isAuthenticated=!1,this.jwt=null,this.origin=null,this.walletAddress=null,this.userId=null,s(this,Z,{},"f"),k((e=>{a(this,G,"m",Y).call(this,"providers",e)})),a(this,G,"m",Q).call(this)} /** * Subscribe to an event. Possible events are "state", "provider", "providers", and "viem". * @param {("state"|"provider"|"providers"|"viem")} event The event. @@ -150,47 +150,47 @@ this.redirectUri=(e=>{const t=["twitter","discord","spotify"];return"object"==ty * auth.on("state", (state) => { * console.log(state); * }); - */on(e,t){r(this,G,"f")[e]||(r(this,G,"f")[e]=[]),r(this,G,"f")[e].push(t),"providers"===e&&t(I())} + */on(e,t){a(this,Z,"f")[e]||(a(this,Z,"f")[e]=[]),a(this,Z,"f")[e].push(t),"providers"===e&&t(A())} /** * Set the loading state. * @param {boolean} loading The loading state. * @returns {void} - */setLoading(e){r(this,H,"m",Z).call(this,"state",e?"loading":this.isAuthenticated?"authenticated":"unauthenticated")} + */setLoading(e){a(this,G,"m",Y).call(this,"state",e?"loading":this.isAuthenticated?"authenticated":"unauthenticated")} /** * Set the provider. This is useful for setting the provider when the user selects a provider from the UI or when dApp wishes to use a specific provider. * @param {object} options The options object. Includes the provider and the provider info. * @returns {void} * @throws {APIError} - Throws an error if the provider is not provided. - */setProvider({provider:e,info:i,address:a}){if(!e)throw new o("provider is required");this.viem=((e,i="window.ethereum",a)=>{var r;if(!e&&!y)return console.warn("Provider is required to create a client."),null;if(!y||y.transport.name!==i&&e||a!==(null===(r=y.account)||void 0===r?void 0:r.address)&&e){const r={chain:c,transport:t.custom(e,{name:i})};a&&(r.account=n.toAccount(a)),y=t.createWalletClient(r)}return y})(e,i.name,a),this.origin&&this.origin.setViemClient(this.viem), + */setProvider({provider:e,info:i,address:r}){if(!e)throw new o("provider is required");this.viem=((e,i="window.ethereum",r)=>{var a;if(!e&&!h)return console.warn("Provider is required to create a client."),null;if(!h||h.transport.name!==i&&e||r!==(null===(a=h.account)||void 0===a?void 0:a.address)&&e){const a={chain:y,transport:t.custom(e,{name:i})};r&&(a.account=n.toAccount(r)),h=t.createWalletClient(a)}return h})(e,i.name,r),this.origin&&this.origin.setViemClient(this.viem), // TODO: only use one of these -r(this,H,"m",Z).call(this,"viem",this.viem),r(this,H,"m",Z).call(this,"provider",{provider:e,info:i}),localStorage.setItem("camp-sdk:provider",JSON.stringify(i))} +a(this,G,"m",Y).call(this,"viem",this.viem),a(this,G,"m",Y).call(this,"provider",{provider:e,info:i}),localStorage.setItem("camp-sdk:provider",JSON.stringify(i))} /** * Set the wallet address. This is useful for edge cases where the provider can't return the wallet address. Don't use this unless you know what you're doing. * @param {string} walletAddress The wallet address. * @returns {void} - */setWalletAddress(e){this.walletAddress=e}recoverProvider(){return a(this,void 0,void 0,(function*(){var e,t,n,i,a,r,s,o,d,u,l,p,c,y,h;if(!this.walletAddress)return void console.warn("No wallet address found in local storage. Please connect your wallet again.");const m=JSON.parse(localStorage.getItem("camp-sdk:provider")||"{}");let f;const w=null!==(e=I())&&void 0!==e?e:[]; + */setWalletAddress(e){this.walletAddress=e}recoverProvider(){return r(this,void 0,void 0,(function*(){var e,t,n,i,r,a,s,o,d,u,l,p,c,y,h;if(!this.walletAddress)return void console.warn("No wallet address found in local storage. Please connect your wallet again.");const m=JSON.parse(localStorage.getItem("camp-sdk:provider")||"{}");let f;const w=null!==(e=A())&&void 0!==e?e:[]; // first pass: try to find provider by UUID/name and check if it has the right address // without prompting (using eth_accounts) for(const e of w)try{if(m.uuid&&(null===(t=e.info)||void 0===t?void 0:t.uuid)===m.uuid||m.name&&(null===(n=e.info)||void 0===n?void 0:n.name)===m.name){ // silently check if the wallet address matches first -const t=yield e.provider.request({method:"eth_accounts"});if(t.length>0&&(null===(i=t[0])||void 0===i?void 0:i.toLowerCase())===(null===(a=this.walletAddress)||void 0===a?void 0:a.toLowerCase())){f=e;break}}}catch(e){console.warn("Failed to fetch accounts from provider:",e)} -// second pass: If no provider found by UUID/name match, try to find by address only +const t=yield e.provider.request({method:"eth_accounts"});if(t.length>0&&(null===(i=t[0])||void 0===i?void 0:i.toLowerCase())===(null===(r=this.walletAddress)||void 0===r?void 0:r.toLowerCase())){f=e;break}}}catch(e){console.warn("Failed to fetch accounts from provider:",e)} +// second pass: if no provider found by UUID/name match, try to find by address only // but still avoid prompting if(!f)for(const e of w)try{ // skip providers we already checked in the first pass -if(m.uuid&&(null===(r=e.info)||void 0===r?void 0:r.uuid)===m.uuid||m.name&&(null===(s=e.info)||void 0===s?void 0:s.name)===m.name)continue;const t=yield e.provider.request({method:"eth_accounts"});if(t.length>0&&(null===(o=t[0])||void 0===o?void 0:o.toLowerCase())===(null===(d=this.walletAddress)||void 0===d?void 0:d.toLowerCase())){f=e;break}}catch(e){console.warn("Failed to fetch accounts from provider:",e)} +if(m.uuid&&(null===(a=e.info)||void 0===a?void 0:a.uuid)===m.uuid||m.name&&(null===(s=e.info)||void 0===s?void 0:s.name)===m.name)continue;const t=yield e.provider.request({method:"eth_accounts"});if(t.length>0&&(null===(o=t[0])||void 0===o?void 0:o.toLowerCase())===(null===(d=this.walletAddress)||void 0===d?void 0:d.toLowerCase())){f=e;break}}catch(e){console.warn("Failed to fetch accounts from provider:",e)} // third pass: if still no provider found and we have UUID/name info, // try prompting the user (only for the stored provider) if(!f&&(m.uuid||m.name))for(const e of w)try{if(m.uuid&&(null===(u=e.info)||void 0===u?void 0:u.uuid)===m.uuid||m.name&&(null===(l=e.info)||void 0===l?void 0:l.name)===m.name){console.log("Attempting to reconnect to stored provider:",(null===(p=e.info)||void 0===p?void 0:p.name)||(null===(c=e.info)||void 0===c?void 0:c.uuid));const t=yield e.provider.request({method:"eth_requestAccounts"});if(t.length>0&&(null===(y=t[0])||void 0===y?void 0:y.toLowerCase())===(null===(h=this.walletAddress)||void 0===h?void 0:h.toLowerCase())){f=e;break}}}catch(e){console.warn("Failed to reconnect to stored provider:",e)}f?this.setProvider({provider:f.provider,info:f.info||{name:"Unknown"},address:this.walletAddress}):console.warn("No matching provider found for the stored wallet address. Please connect your wallet again.")}))} /** * Disconnect the user. * @returns {Promise} - */disconnect(){return a(this,void 0,void 0,(function*(){this.isAuthenticated&&(r(this,H,"m",Z).call(this,"state","unauthenticated"),this.isAuthenticated=!1,this.walletAddress=null,this.userId=null,this.jwt=null,this.origin=null,localStorage.removeItem("camp-sdk:wallet-address"),localStorage.removeItem("camp-sdk:user-id"),localStorage.removeItem("camp-sdk:jwt"))}))} + */disconnect(){return r(this,void 0,void 0,(function*(){this.isAuthenticated&&(a(this,G,"m",Y).call(this,"state","unauthenticated"),this.isAuthenticated=!1,this.walletAddress=null,this.userId=null,this.jwt=null,this.origin=null,localStorage.removeItem("camp-sdk:wallet-address"),localStorage.removeItem("camp-sdk:user-id"),localStorage.removeItem("camp-sdk:jwt"))}))} /** * Connect the user's wallet and sign the message. * @returns {Promise<{ success: boolean; message: string; walletAddress: string }>} A promise that resolves with the authentication result. * @throws {APIError} - Throws an error if the user cannot be authenticated. - */connect(){return a(this,void 0,void 0,(function*(){r(this,H,"m",Z).call(this,"state","loading");try{this.walletAddress||(yield r(this,H,"m",Q).call(this)),this.walletAddress=t.checksumAddress(this.walletAddress);const e=yield r(this,H,"m",X).call(this),n=r(this,H,"m",te).call(this,e),i=yield this.viem.signMessage({account:this.walletAddress,message:n}),a=yield r(this,H,"m",ee).call(this,n,i);if(a.success)return this.isAuthenticated=!0,this.userId=a.userId,this.jwt=a.token,this.origin=new de(this.jwt,this.viem),localStorage.setItem("camp-sdk:jwt",this.jwt),localStorage.setItem("camp-sdk:wallet-address",this.walletAddress),localStorage.setItem("camp-sdk:user-id",this.userId),r(this,H,"m",Z).call(this,"state","authenticated"),yield r(this,H,"m",ne).call(this,v.USER_CONNECTED,"User Connected"),{success:!0,message:"Successfully authenticated",walletAddress:this.walletAddress};throw this.isAuthenticated=!1,r(this,H,"m",Z).call(this,"state","unauthenticated"),new o("Failed to authenticate")}catch(e){throw this.isAuthenticated=!1,r(this,H,"m",Z).call(this,"state","unauthenticated"),new o(e)}}))} + */connect(){return r(this,void 0,void 0,(function*(){a(this,G,"m",Y).call(this,"state","loading");try{this.walletAddress||(yield a(this,G,"m",X).call(this)),this.walletAddress=t.checksumAddress(this.walletAddress);const e=yield a(this,G,"m",ee).call(this),n=a(this,G,"m",ne).call(this,e),i=yield this.viem.signMessage({account:this.walletAddress,message:n}),r=yield a(this,G,"m",te).call(this,n,i);if(r.success)return this.isAuthenticated=!0,this.userId=r.userId,this.jwt=r.token,this.origin=new ue(this.jwt,this.viem),localStorage.setItem("camp-sdk:jwt",this.jwt),localStorage.setItem("camp-sdk:wallet-address",this.walletAddress),localStorage.setItem("camp-sdk:user-id",this.userId),a(this,G,"m",Y).call(this,"state","authenticated"),yield a(this,G,"m",ie).call(this,T.USER_CONNECTED,"User Connected"),{success:!0,message:"Successfully authenticated",walletAddress:this.walletAddress};throw this.isAuthenticated=!1,a(this,G,"m",Y).call(this,"state","unauthenticated"),new o("Failed to authenticate")}catch(e){throw this.isAuthenticated=!1,a(this,G,"m",Y).call(this,"state","unauthenticated"),new o(e)}}))} /** * Get the user's linked social accounts. * @returns {Promise>} A promise that resolves with the user's linked social accounts. @@ -199,49 +199,49 @@ if(!f&&(m.uuid||m.name))for(const e of w)try{if(m.uuid&&(null===(u=e.info)||void * const auth = new Auth({ clientId: "your-client-id" }); * const socials = await auth.getLinkedSocials(); * console.log(socials); - */getLinkedSocials(){return a(this,void 0,void 0,(function*(){if(!this.isAuthenticated)throw new Error("User needs to be authenticated");const e=yield fetch(`${w}/auth/client-user/connections-sdk`,{method:"GET",headers:{Authorization:`Bearer ${this.jwt}`,"x-client-id":this.clientId,"Content-Type":"application/json"}}).then((e=>e.json()));if(e.isError)throw new o(e.message||"Failed to fetch connections");{const t={};return Object.keys(e.data.data).forEach((n=>{t[n.split("User")[0]]=e.data.data[n]})),t}}))} + */getLinkedSocials(){return r(this,void 0,void 0,(function*(){if(!this.isAuthenticated)throw new Error("User needs to be authenticated");const e=yield fetch(`${v}/auth/client-user/connections-sdk`,{method:"GET",headers:{Authorization:`Bearer ${this.jwt}`,"x-client-id":this.clientId,"Content-Type":"application/json"}}).then((e=>e.json()));if(e.isError)throw new o(e.message||"Failed to fetch connections");{const t={};return Object.keys(e.data.data).forEach((n=>{t[n.split("User")[0]]=e.data.data[n]})),t}}))} /** * Link the user's Twitter account. * @returns {Promise} * @throws {Error} - Throws an error if the user is not authenticated. - */linkTwitter(){return a(this,void 0,void 0,(function*(){if(!this.isAuthenticated)throw new Error("User needs to be authenticated"); + */linkTwitter(){return r(this,void 0,void 0,(function*(){if(!this.isAuthenticated)throw new Error("User needs to be authenticated"); // await this.#sendAnalyticsEvent( // constants.ACKEE_EVENTS.TWITTER_LINKED, // "Twitter Linked" // ); -window.location.href=`${w}/twitter/connect?clientId=${this.clientId}&userId=${this.userId}&redirect_url=${this.redirectUri.twitter}`}))} +window.location.href=`${v}/twitter/connect?clientId=${this.clientId}&userId=${this.userId}&redirect_url=${this.redirectUri.twitter}`}))} /** * Link the user's Discord account. * @returns {Promise} * @throws {Error} - Throws an error if the user is not authenticated. - */linkDiscord(){return a(this,void 0,void 0,(function*(){if(!this.isAuthenticated)throw new Error("User needs to be authenticated"); + */linkDiscord(){return r(this,void 0,void 0,(function*(){if(!this.isAuthenticated)throw new Error("User needs to be authenticated"); // await this.#sendAnalyticsEvent( // constants.ACKEE_EVENTS.DISCORD_LINKED, // "Discord Linked" // ); -window.location.href=`${w}/discord/connect?clientId=${this.clientId}&userId=${this.userId}&redirect_url=${this.redirectUri.discord}`}))} +window.location.href=`${v}/discord/connect?clientId=${this.clientId}&userId=${this.userId}&redirect_url=${this.redirectUri.discord}`}))} /** * Link the user's Spotify account. * @returns {Promise} * @throws {Error} - Throws an error if the user is not authenticated. - */linkSpotify(){return a(this,void 0,void 0,(function*(){if(!this.isAuthenticated)throw new Error("User needs to be authenticated"); + */linkSpotify(){return r(this,void 0,void 0,(function*(){if(!this.isAuthenticated)throw new Error("User needs to be authenticated"); // await this.#sendAnalyticsEvent( // constants.ACKEE_EVENTS.SPOTIFY_LINKED, // "Spotify Linked" // ); -window.location.href=`${w}/spotify/connect?clientId=${this.clientId}&userId=${this.userId}&redirect_url=${this.redirectUri.spotify}`}))} +window.location.href=`${v}/spotify/connect?clientId=${this.clientId}&userId=${this.userId}&redirect_url=${this.redirectUri.spotify}`}))} /** * Link the user's TikTok account. * @param {string} handle The user's TikTok handle. * @returns {Promise} A promise that resolves with the TikTok account data. * @throws {Error|APIError} - Throws an error if the user is not authenticated. - */linkTikTok(e){return a(this,void 0,void 0,(function*(){if(!this.isAuthenticated)throw new Error("User needs to be authenticated");const t=yield fetch(`${w}/tiktok/connect-sdk`,{method:"POST",redirect:"follow",headers:{Authorization:`Bearer ${this.jwt}`,"x-client-id":this.clientId,"Content-Type":"application/json"},body:JSON.stringify({userHandle:e,clientId:this.clientId,userId:this.userId})}).then((e=>e.json()));if(t.isError)throw"Request failed with status code 502"===t.message?new o("TikTok service is currently unavailable, try again later"):new o(t.message||"Failed to link TikTok account");return r(this,H,"m",ne).call(this,v.TIKTOK_LINKED,"TikTok Linked"),t.data}))} + */linkTikTok(e){return r(this,void 0,void 0,(function*(){if(!this.isAuthenticated)throw new Error("User needs to be authenticated");const t=yield fetch(`${v}/tiktok/connect-sdk`,{method:"POST",redirect:"follow",headers:{Authorization:`Bearer ${this.jwt}`,"x-client-id":this.clientId,"Content-Type":"application/json"},body:JSON.stringify({userHandle:e,clientId:this.clientId,userId:this.userId})}).then((e=>e.json()));if(t.isError)throw"Request failed with status code 502"===t.message?new o("TikTok service is currently unavailable, try again later"):new o(t.message||"Failed to link TikTok account");return a(this,G,"m",ie).call(this,T.TIKTOK_LINKED,"TikTok Linked"),t.data}))} /** * Send an OTP to the user's Telegram account. * @param {string} phoneNumber The user's phone number. * @returns {Promise} A promise that resolves with the OTP data. * @throws {Error|APIError} - Throws an error if the user is not authenticated. - */sendTelegramOTP(e){return a(this,void 0,void 0,(function*(){if(!this.isAuthenticated)throw new Error("User needs to be authenticated");if(!e)throw new o("Phone number is required");yield this.unlinkTelegram();const t=yield fetch(`${w}/telegram/sendOTP-sdk`,{method:"POST",redirect:"follow",headers:{Authorization:`Bearer ${this.jwt}`,"x-client-id":this.clientId,"Content-Type":"application/json"},body:JSON.stringify({phone:e})}).then((e=>e.json()));if(t.isError)throw new o(t.message||"Failed to send Telegram OTP");return t.data}))} + */sendTelegramOTP(e){return r(this,void 0,void 0,(function*(){if(!this.isAuthenticated)throw new Error("User needs to be authenticated");if(!e)throw new o("Phone number is required");yield this.unlinkTelegram();const t=yield fetch(`${v}/telegram/sendOTP-sdk`,{method:"POST",redirect:"follow",headers:{Authorization:`Bearer ${this.jwt}`,"x-client-id":this.clientId,"Content-Type":"application/json"},body:JSON.stringify({phone:e})}).then((e=>e.json()));if(t.isError)throw new o(t.message||"Failed to send Telegram OTP");return t.data}))} /** * Link the user's Telegram account. * @param {string} phoneNumber The user's phone number. @@ -249,37 +249,37 @@ window.location.href=`${w}/spotify/connect?clientId=${this.clientId}&userId=${th * @param {string} phoneCodeHash The phone code hash. * @returns {Promise} A promise that resolves with the Telegram account data. * @throws {APIError|Error} - Throws an error if the user is not authenticated. Also throws an error if the phone number, OTP, and phone code hash are not provided. - */linkTelegram(e,t,n){return a(this,void 0,void 0,(function*(){if(!this.isAuthenticated)throw new Error("User needs to be authenticated");if(!e||!t||!n)throw new o("Phone number, OTP, and phone code hash are required");const i=yield fetch(`${w}/telegram/signIn-sdk`,{method:"POST",redirect:"follow",headers:{Authorization:`Bearer ${this.jwt}`,"x-client-id":this.clientId,"Content-Type":"application/json"},body:JSON.stringify({phone:e,code:t,phone_code_hash:n,userId:this.userId,clientId:this.clientId})}).then((e=>e.json()));if(i.isError)throw new o(i.message||"Failed to link Telegram account");return r(this,H,"m",ne).call(this,v.TELEGRAM_LINKED,"Telegram Linked"),i.data}))} + */linkTelegram(e,t,n){return r(this,void 0,void 0,(function*(){if(!this.isAuthenticated)throw new Error("User needs to be authenticated");if(!e||!t||!n)throw new o("Phone number, OTP, and phone code hash are required");const i=yield fetch(`${v}/telegram/signIn-sdk`,{method:"POST",redirect:"follow",headers:{Authorization:`Bearer ${this.jwt}`,"x-client-id":this.clientId,"Content-Type":"application/json"},body:JSON.stringify({phone:e,code:t,phone_code_hash:n,userId:this.userId,clientId:this.clientId})}).then((e=>e.json()));if(i.isError)throw new o(i.message||"Failed to link Telegram account");return a(this,G,"m",ie).call(this,T.TELEGRAM_LINKED,"Telegram Linked"),i.data}))} /** * Unlink the user's Twitter account. * @returns {Promise} A promise that resolves with the unlink result. * @throws {Error} - Throws an error if the user is not authenticated. * @throws {APIError} - Throws an error if the request fails. - */unlinkTwitter(){return a(this,void 0,void 0,(function*(){if(!this.isAuthenticated)throw new Error("User needs to be authenticated");const e=yield fetch(`${w}/twitter/disconnect-sdk`,{method:"POST",redirect:"follow",headers:{Authorization:`Bearer ${this.jwt}`,"x-client-id":this.clientId,"Content-Type":"application/json"},body:JSON.stringify({id:this.userId})}).then((e=>e.json()));if(e.isError)throw new o(e.message||"Failed to unlink Twitter account");return e.data}))} + */unlinkTwitter(){return r(this,void 0,void 0,(function*(){if(!this.isAuthenticated)throw new Error("User needs to be authenticated");const e=yield fetch(`${v}/twitter/disconnect-sdk`,{method:"POST",redirect:"follow",headers:{Authorization:`Bearer ${this.jwt}`,"x-client-id":this.clientId,"Content-Type":"application/json"},body:JSON.stringify({id:this.userId})}).then((e=>e.json()));if(e.isError)throw new o(e.message||"Failed to unlink Twitter account");return e.data}))} /** * Unlink the user's Discord account. * @returns {Promise} A promise that resolves with the unlink result. * @throws {Error} - Throws an error if the user is not authenticated. * @throws {APIError} - Throws an error if the request fails. - */unlinkDiscord(){return a(this,void 0,void 0,(function*(){if(!this.isAuthenticated)throw new o("User needs to be authenticated");const e=yield fetch(`${w}/discord/disconnect-sdk`,{method:"POST",redirect:"follow",headers:{Authorization:`Bearer ${this.jwt}`,"x-client-id":this.clientId,"Content-Type":"application/json"},body:JSON.stringify({id:this.userId})}).then((e=>e.json()));if(e.isError)throw new o(e.message||"Failed to unlink Discord account");return e.data}))} + */unlinkDiscord(){return r(this,void 0,void 0,(function*(){if(!this.isAuthenticated)throw new o("User needs to be authenticated");const e=yield fetch(`${v}/discord/disconnect-sdk`,{method:"POST",redirect:"follow",headers:{Authorization:`Bearer ${this.jwt}`,"x-client-id":this.clientId,"Content-Type":"application/json"},body:JSON.stringify({id:this.userId})}).then((e=>e.json()));if(e.isError)throw new o(e.message||"Failed to unlink Discord account");return e.data}))} /** * Unlink the user's Spotify account. * @returns {Promise} A promise that resolves with the unlink result. * @throws {Error} - Throws an error if the user is not authenticated. * @throws {APIError} - Throws an error if the request fails. - */unlinkSpotify(){return a(this,void 0,void 0,(function*(){if(!this.isAuthenticated)throw new o("User needs to be authenticated");const e=yield fetch(`${w}/spotify/disconnect-sdk`,{method:"POST",redirect:"follow",headers:{Authorization:`Bearer ${this.jwt}`,"x-client-id":this.clientId,"Content-Type":"application/json"},body:JSON.stringify({id:this.userId})}).then((e=>e.json()));if(e.isError)throw new o(e.message||"Failed to unlink Spotify account");return e.data}))} + */unlinkSpotify(){return r(this,void 0,void 0,(function*(){if(!this.isAuthenticated)throw new o("User needs to be authenticated");const e=yield fetch(`${v}/spotify/disconnect-sdk`,{method:"POST",redirect:"follow",headers:{Authorization:`Bearer ${this.jwt}`,"x-client-id":this.clientId,"Content-Type":"application/json"},body:JSON.stringify({id:this.userId})}).then((e=>e.json()));if(e.isError)throw new o(e.message||"Failed to unlink Spotify account");return e.data}))} /** * Unlink the user's TikTok account. * @returns {Promise} A promise that resolves with the unlink result. * @throws {Error} - Throws an error if the user is not authenticated. * @throws {APIError} - Throws an error if the request fails. - */unlinkTikTok(){return a(this,void 0,void 0,(function*(){if(!this.isAuthenticated)throw new o("User needs to be authenticated");const e=yield fetch(`${w}/tiktok/disconnect-sdk`,{method:"POST",redirect:"follow",headers:{Authorization:`Bearer ${this.jwt}`,"x-client-id":this.clientId,"Content-Type":"application/json"},body:JSON.stringify({userId:this.userId})}).then((e=>e.json()));if(e.isError)throw new o(e.message||"Failed to unlink TikTok account");return e.data}))} + */unlinkTikTok(){return r(this,void 0,void 0,(function*(){if(!this.isAuthenticated)throw new o("User needs to be authenticated");const e=yield fetch(`${v}/tiktok/disconnect-sdk`,{method:"POST",redirect:"follow",headers:{Authorization:`Bearer ${this.jwt}`,"x-client-id":this.clientId,"Content-Type":"application/json"},body:JSON.stringify({userId:this.userId})}).then((e=>e.json()));if(e.isError)throw new o(e.message||"Failed to unlink TikTok account");return e.data}))} /** * Unlink the user's Telegram account. * @returns {Promise} A promise that resolves with the unlink result. * @throws {Error} - Throws an error if the user is not authenticated. * @throws {APIError} - Throws an error if the request fails. - */unlinkTelegram(){return a(this,void 0,void 0,(function*(){if(!this.isAuthenticated)throw new o("User needs to be authenticated");const e=yield fetch(`${w}/telegram/disconnect-sdk`,{method:"POST",redirect:"follow",headers:{Authorization:`Bearer ${this.jwt}`,"x-client-id":this.clientId,"Content-Type":"application/json"},body:JSON.stringify({userId:this.userId})}).then((e=>e.json()));if(e.isError)throw new o(e.message||"Failed to unlink Telegram account");return e.data}))}},exports.SpotifyAPI= + */unlinkTelegram(){return r(this,void 0,void 0,(function*(){if(!this.isAuthenticated)throw new o("User needs to be authenticated");const e=yield fetch(`${v}/telegram/disconnect-sdk`,{method:"POST",redirect:"follow",headers:{Authorization:`Bearer ${this.jwt}`,"x-client-id":this.clientId,"Content-Type":"application/json"},body:JSON.stringify({userId:this.userId})}).then((e=>e.json()));if(e.isError)throw new o(e.message||"Failed to unlink Telegram account");return e.data}))}},exports.SpotifyAPI= /** * The SpotifyAPI class. * @class @@ -292,57 +292,59 @@ class{ * @param {string} options.apiKey - The Spotify API key. * @throws {Error} - Throws an error if the API key is not provided. */ -constructor(e){this.apiKey=e.apiKey} +constructor(e){if(!e||!e.apiKey||"string"!=typeof e.apiKey||""===e.apiKey.trim())throw new d("API key is required and must be a non-empty string");this.apiKey=e.apiKey.trim()} /** * Fetch the user's saved tracks by Spotify user ID. * @param {string} spotifyId - The user's Spotify ID. * @returns {Promise} - The saved tracks. * @throws {APIError} - Throws an error if the request fails. - */fetchSavedTracksById(e){return a(this,void 0,void 0,(function*(){const t=u(`${p}/save-tracks`,{spotifyId:e});return this._fetchDataWithAuth(t)}))} + */fetchSavedTracksById(e){return r(this,void 0,void 0,(function*(){if(!e||"string"!=typeof e||""===e.trim())throw new d("Spotify ID is required and must be a non-empty string");const t=l(`${c}/save-tracks`,{spotifyId:e.trim()});return this._fetchDataWithAuth(t)}))} /** * Fetch the played tracks of a user by Spotify ID. * @param {string} spotifyId - The user's Spotify ID. * @returns {Promise} - The played tracks. * @throws {APIError} - Throws an error if the request fails. - */fetchPlayedTracksById(e){return a(this,void 0,void 0,(function*(){const t=u(`${p}/played-tracks`,{spotifyId:e});return this._fetchDataWithAuth(t)}))} + */fetchPlayedTracksById(e){return r(this,void 0,void 0,(function*(){if(!e||"string"!=typeof e||""===e.trim())throw new d("Spotify ID is required and must be a non-empty string");const t=l(`${c}/played-tracks`,{spotifyId:e.trim()});return this._fetchDataWithAuth(t)}))} /** * Fetch the user's saved albums by Spotify user ID. * @param {string} spotifyId - The user's Spotify ID. * @returns {Promise} - The saved albums. * @throws {APIError} - Throws an error if the request fails. - */fetchSavedAlbumsById(e){return a(this,void 0,void 0,(function*(){const t=u(`${p}/saved-albums`,{spotifyId:e});return this._fetchDataWithAuth(t)}))} + */fetchSavedAlbumsById(e){return r(this,void 0,void 0,(function*(){if(!e||"string"!=typeof e||""===e.trim())throw new d("Spotify ID is required and must be a non-empty string");const t=l(`${c}/saved-albums`,{spotifyId:e.trim()});return this._fetchDataWithAuth(t)}))} /** * Fetch the user's saved playlists by Spotify user ID. * @param {string} spotifyId - The user's Spotify ID. * @returns {Promise} - The saved playlists. * @throws {APIError} - Throws an error if the request fails. - */fetchSavedPlaylistsById(e){return a(this,void 0,void 0,(function*(){const t=u(`${p}/saved-playlists`,{spotifyId:e});return this._fetchDataWithAuth(t)}))} + */fetchSavedPlaylistsById(e){return r(this,void 0,void 0,(function*(){if(!e||"string"!=typeof e||""===e.trim())throw new d("Spotify ID is required and must be a non-empty string");const t=l(`${c}/saved-playlists`,{spotifyId:e.trim()});return this._fetchDataWithAuth(t)}))} /** * Fetch the tracks of an album by album ID. * @param {string} spotifyId - The Spotify ID of the user. * @param {string} albumId - The album ID. * @returns {Promise} - The tracks in the album. * @throws {APIError} - Throws an error if the request fails. - */fetchTracksInAlbum(e,t){return a(this,void 0,void 0,(function*(){const n=u(`${p}/album/tracks`,{spotifyId:e,albumId:t});return this._fetchDataWithAuth(n)}))} + */fetchTracksInAlbum(e,t){return r(this,void 0,void 0,(function*(){if(!e||"string"!=typeof e||""===e.trim())throw new d("Spotify ID is required and must be a non-empty string");if(!t||"string"!=typeof t||""===t.trim())throw new d("Album ID is required and must be a non-empty string");const n=l(`${c}/album/tracks`,{spotifyId:e.trim(),albumId:t.trim()});return this._fetchDataWithAuth(n)}))} /** * Fetch the tracks in a playlist by playlist ID. * @param {string} spotifyId - The Spotify ID of the user. * @param {string} playlistId - The playlist ID. * @returns {Promise} - The tracks in the playlist. * @throws {APIError} - Throws an error if the request fails. - */fetchTracksInPlaylist(e,t){return a(this,void 0,void 0,(function*(){const n=u(`${p}/playlist/tracks`,{spotifyId:e,playlistId:t});return this._fetchDataWithAuth(n)}))} + */fetchTracksInPlaylist(e,t){return r(this,void 0,void 0,(function*(){if(!e||"string"!=typeof e||""===e.trim())throw new d("Spotify ID is required and must be a non-empty string");if(!t||"string"!=typeof t||""===t.trim())throw new d("Playlist ID is required and must be a non-empty string");const n=l(`${c}/playlist/tracks`,{spotifyId:e.trim(),playlistId:t.trim()});return this._fetchDataWithAuth(n)}))} /** * Fetch the user's Spotify data by wallet address. * @param {string} walletAddress - The wallet address. * @returns {Promise} - The user's Spotify data. * @throws {APIError} - Throws an error if the request fails. - */fetchUserByWalletAddress(e){return a(this,void 0,void 0,(function*(){const t=u(`${p}/wallet-spotify-data`,{walletAddress:e});return this._fetchDataWithAuth(t)}))} + */fetchUserByWalletAddress(e){return r(this,void 0,void 0,(function*(){if(!e||"string"!=typeof e||""===e.trim())throw new d("Wallet address is required and must be a non-empty string"); +// Basic Ethereum address format validation +const t=e.trim();if(!/^0x[a-fA-F0-9]{40}$/.test(t))throw new d("Invalid wallet address format");const n=l(`${c}/wallet-spotify-data`,{walletAddress:t});return this._fetchDataWithAuth(n)}))} /** * Private method to fetch data with authorization header. * @param {string} url - The URL to fetch. * @returns {Promise} - The response data. * @throws {APIError} - Throws an error if the request fails. - */_fetchDataWithAuth(e){return a(this,void 0,void 0,(function*(){if(!this.apiKey)throw new o("API key is required for fetching data",401);try{return yield d(e,{"x-api-key":this.apiKey})}catch(e){throw new o(e.message,e.statusCode)}}))}},exports.TwitterAPI= + */_fetchDataWithAuth(e){return r(this,void 0,void 0,(function*(){if(!this.apiKey)throw new o("API key is required for fetching data",401);try{return yield u(e,{"x-api-key":this.apiKey})}catch(e){throw new o(e.message,e.statusCode)}}))}},exports.TwitterAPI= /** * The TwitterAPI class. * @class @@ -354,13 +356,15 @@ class{ * @param {object} options - The options object. * @param {string} options.apiKey - The API key. (Needed for data fetching) */ -constructor({apiKey:e}){this.apiKey=e} +constructor({apiKey:e}){if(!e||"string"!=typeof e||""===e.trim())throw new d("API key is required and must be a non-empty string");this.apiKey=e.trim()} /** * Fetch Twitter user details by username. * @param {string} twitterUserName - The Twitter username. * @returns {Promise} - The user details. * @throws {APIError} - Throws an error if the request fails. - */fetchUserByUsername(e){return a(this,void 0,void 0,(function*(){const t=u(`${l}/user`,{twitterUserName:e});return this._fetchDataWithAuth(t)}))} + */fetchUserByUsername(e){return r(this,void 0,void 0,(function*(){if(!e||"string"!=typeof e||""===e.trim())throw new d("Twitter username is required and must be a non-empty string");const t=e.trim(); +// Basic Twitter username validation (no @ symbol, alphanumeric + underscore) +if(!/^[a-zA-Z0-9_]{1,15}$/.test(t))throw new d("Invalid Twitter username format");const n=l(`${p}/user`,{twitterUserName:t});return this._fetchDataWithAuth(n)}))} /** * Fetch tweets by Twitter username. * @param {string} twitterUserName - The Twitter username. @@ -368,7 +372,7 @@ constructor({apiKey:e}){this.apiKey=e} * @param {number} limit - The number of items per page. * @returns {Promise} - The tweets. * @throws {APIError} - Throws an error if the request fails. - */fetchTweetsByUsername(e){return a(this,arguments,void 0,(function*(e,t=1,n=10){const i=u(`${l}/tweets`,{twitterUserName:e,page:t,limit:n});return this._fetchDataWithAuth(i)}))} + */fetchTweetsByUsername(e){return r(this,arguments,void 0,(function*(e,t=1,n=10){if(!e||"string"!=typeof e||""===e.trim())throw new d("Twitter username is required and must be a non-empty string");const i=e.trim();if(!/^[a-zA-Z0-9_]{1,15}$/.test(i))throw new d("Invalid Twitter username format");if(!Number.isInteger(t)||t<1)throw new d("Page must be a positive integer");if(!Number.isInteger(n)||n<1||n>100)throw new d("Limit must be a positive integer between 1 and 100");const r=l(`${p}/tweets`,{twitterUserName:i,page:t,limit:n});return this._fetchDataWithAuth(r)}))} /** * Fetch followers by Twitter username. * @param {string} twitterUserName - The Twitter username. @@ -376,7 +380,7 @@ constructor({apiKey:e}){this.apiKey=e} * @param {number} limit - The number of items per page. * @returns {Promise} - The followers. * @throws {APIError} - Throws an error if the request fails. - */fetchFollowersByUsername(e){return a(this,arguments,void 0,(function*(e,t=1,n=10){const i=u(`${l}/followers`,{twitterUserName:e,page:t,limit:n});return this._fetchDataWithAuth(i)}))} + */fetchFollowersByUsername(e){return r(this,arguments,void 0,(function*(e,t=1,n=10){const{validatedUsername:i,validatedPage:r,validatedLimit:a}=this._validateUsernamePageLimit(e,t,n),s=l(`${p}/followers`,{twitterUserName:i,page:r,limit:a});return this._fetchDataWithAuth(s)}))} /** * Fetch following by Twitter username. * @param {string} twitterUserName - The Twitter username. @@ -384,13 +388,15 @@ constructor({apiKey:e}){this.apiKey=e} * @param {number} limit - The number of items per page. * @returns {Promise} - The following. * @throws {APIError} - Throws an error if the request fails. - */fetchFollowingByUsername(e){return a(this,arguments,void 0,(function*(e,t=1,n=10){const i=u(`${l}/following`,{twitterUserName:e,page:t,limit:n});return this._fetchDataWithAuth(i)}))} + */fetchFollowingByUsername(e){return r(this,arguments,void 0,(function*(e,t=1,n=10){const{validatedUsername:i,validatedPage:r,validatedLimit:a}=this._validateUsernamePageLimit(e,t,n),s=l(`${p}/following`,{twitterUserName:i,page:r,limit:a});return this._fetchDataWithAuth(s)}))} /** * Fetch tweet by tweet ID. * @param {string} tweetId - The tweet ID. * @returns {Promise} - The tweet. * @throws {APIError} - Throws an error if the request fails. - */fetchTweetById(e){return a(this,void 0,void 0,(function*(){const t=u(`${l}/getTweetById`,{tweetId:e});return this._fetchDataWithAuth(t)}))} + */fetchTweetById(e){return r(this,void 0,void 0,(function*(){if(!e||"string"!=typeof e||""===e.trim())throw new d("Tweet ID is required and must be a non-empty string");const t=e.trim(); +// Basic tweet ID validation (should be numeric) +if(!/^\d+$/.test(t))throw new d("Invalid tweet ID format");const n=l(`${p}/getTweetById`,{tweetId:t});return this._fetchDataWithAuth(n)}))} /** * Fetch user by wallet address. * @param {string} walletAddress - The wallet address. @@ -398,7 +404,7 @@ constructor({apiKey:e}){this.apiKey=e} * @param {number} limit - The number of items per page. * @returns {Promise} - The user data. * @throws {APIError} - Throws an error if the request fails. - */fetchUserByWalletAddress(e){return a(this,arguments,void 0,(function*(e,t=1,n=10){const i=u(`${l}/wallet-twitter-data`,{walletAddress:e,page:t,limit:n});return this._fetchDataWithAuth(i)}))} + */fetchUserByWalletAddress(e){return r(this,arguments,void 0,(function*(e,t=1,n=10){if(!e||"string"!=typeof e||""===e.trim())throw new d("Wallet address is required and must be a non-empty string");const i=e.trim();if(!/^0x[a-fA-F0-9]{40}$/.test(i))throw new d("Invalid wallet address format");if(!Number.isInteger(t)||t<1)throw new d("Page must be a positive integer");if(!Number.isInteger(n)||n<1||n>100)throw new d("Limit must be a positive integer between 1 and 100");const r=l(`${p}/wallet-twitter-data`,{walletAddress:i,page:t,limit:n});return this._fetchDataWithAuth(r)}))} /** * Fetch reposted tweets by Twitter username. * @param {string} twitterUserName - The Twitter username. @@ -406,7 +412,7 @@ constructor({apiKey:e}){this.apiKey=e} * @param {number} limit - The number of items per page. * @returns {Promise} - The reposted tweets. * @throws {APIError} - Throws an error if the request fails. - */fetchRepostedByUsername(e){return a(this,arguments,void 0,(function*(e,t=1,n=10){const i=u(`${l}/reposted`,{twitterUserName:e,page:t,limit:n});return this._fetchDataWithAuth(i)}))} + */fetchRepostedByUsername(e){return r(this,arguments,void 0,(function*(e,t=1,n=10){const{validatedUsername:i,validatedPage:r,validatedLimit:a}=this._validateUsernamePageLimit(e,t,n),s=l(`${p}/reposted`,{twitterUserName:i,page:r,limit:a});return this._fetchDataWithAuth(s)}))} /** * Fetch replies by Twitter username. * @param {string} twitterUserName - The Twitter username. @@ -414,7 +420,7 @@ constructor({apiKey:e}){this.apiKey=e} * @param {number} limit - The number of items per page. * @returns {Promise} - The replies. * @throws {APIError} - Throws an error if the request fails. - */fetchRepliesByUsername(e){return a(this,arguments,void 0,(function*(e,t=1,n=10){const i=u(`${l}/replies`,{twitterUserName:e,page:t,limit:n});return this._fetchDataWithAuth(i)}))} + */fetchRepliesByUsername(e){return r(this,arguments,void 0,(function*(e,t=1,n=10){const{validatedUsername:i,validatedPage:r,validatedLimit:a}=this._validateUsernamePageLimit(e,t,n),s=l(`${p}/replies`,{twitterUserName:i,page:r,limit:a});return this._fetchDataWithAuth(s)}))} /** * Fetch likes by Twitter username. * @param {string} twitterUserName - The Twitter username. @@ -422,7 +428,7 @@ constructor({apiKey:e}){this.apiKey=e} * @param {number} limit - The number of items per page. * @returns {Promise} - The likes. * @throws {APIError} - Throws an error if the request fails. - */fetchLikesByUsername(e){return a(this,arguments,void 0,(function*(e,t=1,n=10){const i=u(`${l}/event/likes/${e}`,{page:t,limit:n});return this._fetchDataWithAuth(i)}))} + */fetchLikesByUsername(e){return r(this,arguments,void 0,(function*(e,t=1,n=10){const{validatedUsername:i,validatedPage:r,validatedLimit:a}=this._validateUsernamePageLimit(e,t,n),s=l(`${p}/event/likes/${i}`,{page:r,limit:a});return this._fetchDataWithAuth(s)}))} /** * Fetch follows by Twitter username. * @param {string} twitterUserName - The Twitter username. @@ -430,7 +436,7 @@ constructor({apiKey:e}){this.apiKey=e} * @param {number} limit - The number of items per page. * @returns {Promise} - The follows. * @throws {APIError} - Throws an error if the request fails. - */fetchFollowsByUsername(e){return a(this,arguments,void 0,(function*(e,t=1,n=10){const i=u(`${l}/event/follows/${e}`,{page:t,limit:n});return this._fetchDataWithAuth(i)}))} + */fetchFollowsByUsername(e){return r(this,arguments,void 0,(function*(e,t=1,n=10){const{validatedUsername:i,validatedPage:r,validatedLimit:a}=this._validateUsernamePageLimit(e,t,n),s=l(`${p}/event/follows/${i}`,{page:r,limit:a});return this._fetchDataWithAuth(s)}))} /** * Fetch viewed tweets by Twitter username. * @param {string} twitterUserName - The Twitter username. @@ -438,10 +444,18 @@ constructor({apiKey:e}){this.apiKey=e} * @param {number} limit - The number of items per page. * @returns {Promise} - The viewed tweets. * @throws {APIError} - Throws an error if the request fails. - */fetchViewedTweetsByUsername(e){return a(this,arguments,void 0,(function*(e,t=1,n=10){const i=u(`${l}/event/viewed-tweets/${e}`,{page:t,limit:n});return this._fetchDataWithAuth(i)}))} + */fetchViewedTweetsByUsername(e){return r(this,arguments,void 0,(function*(e,t=1,n=10){const{validatedUsername:i,validatedPage:r,validatedLimit:a}=this._validateUsernamePageLimit(e,t,n),s=l(`${p}/event/viewed-tweets/${i}`,{page:r,limit:a});return this._fetchDataWithAuth(s)}))} +/** + * Private method to validate username, page, and limit parameters. + * @param {string} twitterUserName - The Twitter username. + * @param {number} page - The page number. + * @param {number} limit - The limit number. + * @returns {object} - Validated parameters. + * @throws {ValidationError} - Throws an error if validation fails. + */_validateUsernamePageLimit(e,t,n){if(!e||"string"!=typeof e||""===e.trim())throw new d("Twitter username is required and must be a non-empty string");const i=e.trim();if(!/^[a-zA-Z0-9_]{1,15}$/.test(i))throw new d("Invalid Twitter username format");if(!Number.isInteger(t)||t<1)throw new d("Page must be a positive integer");if(!Number.isInteger(n)||n<1||n>100)throw new d("Limit must be a positive integer between 1 and 100");return{validatedUsername:i,validatedPage:t,validatedLimit:n}} /** * Private method to fetch data with authorization header. * @param {string} url - The URL to fetch. * @returns {Promise} - The response data. * @throws {APIError} - Throws an error if the request fails. - */_fetchDataWithAuth(e){return a(this,void 0,void 0,(function*(){if(!this.apiKey)throw new o("API key is required for fetching data",401);try{return yield d(e,{"x-api-key":this.apiKey})}catch(e){throw new o(e.message,e.statusCode)}}))}}; + */_fetchDataWithAuth(e){return r(this,void 0,void 0,(function*(){if(!this.apiKey)throw new o("API key is required for fetching data",401);try{return yield u(e,{"x-api-key":this.apiKey})}catch(e){throw new o(e.message,e.statusCode)}}))}}; diff --git a/dist/core.d.ts b/dist/core.d.ts index 32ea8e9..03fdde9 100644 --- a/dist/core.d.ts +++ b/dist/core.d.ts @@ -110,6 +110,15 @@ declare class TwitterAPI { * @throws {APIError} - Throws an error if the request fails. */ fetchViewedTweetsByUsername(twitterUserName: string, page?: number, limit?: number): Promise; + /** + * Private method to validate username, page, and limit parameters. + * @param {string} twitterUserName - The Twitter username. + * @param {number} page - The page number. + * @param {number} limit - The limit number. + * @returns {object} - Validated parameters. + * @throws {ValidationError} - Throws an error if validation fails. + */ + private _validateUsernamePageLimit; /** * Private method to fetch data with authorization header. * @param {string} url - The URL to fetch. diff --git a/dist/core.esm.d.ts b/dist/core.esm.d.ts index 32ea8e9..03fdde9 100644 --- a/dist/core.esm.d.ts +++ b/dist/core.esm.d.ts @@ -110,6 +110,15 @@ declare class TwitterAPI { * @throws {APIError} - Throws an error if the request fails. */ fetchViewedTweetsByUsername(twitterUserName: string, page?: number, limit?: number): Promise; + /** + * Private method to validate username, page, and limit parameters. + * @param {string} twitterUserName - The Twitter username. + * @param {number} page - The page number. + * @param {number} limit - The limit number. + * @returns {object} - Validated parameters. + * @throws {ValidationError} - Throws an error if validation fails. + */ + private _validateUsernamePageLimit; /** * Private method to fetch data with authorization header. * @param {string} url - The URL to fetch. diff --git a/dist/core.esm.js b/dist/core.esm.js index e862213..c363692 100644 --- a/dist/core.esm.js +++ b/dist/core.esm.js @@ -1,4 +1,4 @@ -import e from"axios";import{custom as t,createWalletClient as n,createPublicClient as i,http as a,erc20Abi as r,getAbiItem as s,encodeFunctionData as o,zeroAddress as d,checksumAddress as u}from"viem";import{toAccount as l}from"viem/accounts";import{createSiweMessage as p}from"viem/siwe"; +import e from"axios";import{custom as t,createWalletClient as n,createPublicClient as i,http as r,erc20Abi as a,getAbiItem as s,encodeFunctionData as o,zeroAddress as d,checksumAddress as u}from"viem";import{toAccount as l}from"viem/accounts";import{createSiweMessage as p}from"viem/siwe"; /****************************************************************************** Copyright (c) Microsoft Corporation. @@ -13,7 +13,7 @@ LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. ***************************************************************************** */ -/* global Reflect, Promise, SuppressedError, Symbol, Iterator */function c(e,t,n,i){return new(n||(n=Promise))((function(a,r){function s(e){try{d(i.next(e))}catch(e){r(e)}}function o(e){try{d(i.throw(e))}catch(e){r(e)}}function d(e){var t;e.done?a(e.value):(t=e.value,t instanceof n?t:new n((function(e){e(t)}))).then(s,o)}d((i=i.apply(e,t||[])).next())}))}function y(e,t,n,i){if("a"===n&&!i)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!i:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===n?i:"a"===n?i.call(e):i?i.value:t.get(e)}function h(e,t,n,i,a){if("m"===i)throw new TypeError("Private method is not writable");if("a"===i&&!a)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!a:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===i?a.call(e,n):a?a.value=n:t.set(e,n),n}"function"==typeof SuppressedError&&SuppressedError;class m extends Error{constructor(e,t){super(e),this.name="APIError",this.statusCode=t||500,Error.captureStackTrace(this,this.constructor)}toJSON(){return{error:this.name,message:this.message,statusCode:this.statusCode||500}}} +/* global Reflect, Promise, SuppressedError, Symbol, Iterator */function c(e,t,n,i){return new(n||(n=Promise))((function(r,a){function s(e){try{d(i.next(e))}catch(e){a(e)}}function o(e){try{d(i.throw(e))}catch(e){a(e)}}function d(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n((function(e){e(t)}))).then(s,o)}d((i=i.apply(e,t||[])).next())}))}function y(e,t,n,i){if("a"===n&&!i)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!i:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===n?i:"a"===n?i.call(e):i?i.value:t.get(e)}function h(e,t,n,i,r){if("m"===i)throw new TypeError("Private method is not writable");if("a"===i&&!r)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===i?r.call(e,n):r?r.value=n:t.set(e,n),n}"function"==typeof SuppressedError&&SuppressedError;class m extends Error{constructor(e,t){super(e),this.name="APIError",this.statusCode=t||500,Error.captureStackTrace(this,this.constructor)}toJSON(){return{error:this.name,message:this.message,statusCode:this.statusCode||500}}}class f extends Error{constructor(e){super(e),this.name="ValidationError",Error.captureStackTrace(this,this.constructor)}toJSON(){return{error:this.name,message:this.message,statusCode:400}}} /** * Makes a GET request to the given URL with the provided headers. * @@ -21,7 +21,7 @@ PERFORMANCE OF THIS SOFTWARE. * @param {object} headers - The headers to include in the request. * @returns {Promise} - The response data. * @throws {APIError} - Throws an error if the request fails. - */function f(t){return c(this,arguments,void 0,(function*(t,n={}){try{return(yield e.get(t,{headers:n})).data}catch(e){if(e.response)throw new m(e.response.data.message||"API request failed",e.response.status);throw new m("Network error or server is unavailable",500)}}))} + */function w(t){return c(this,arguments,void 0,(function*(t,n={}){try{return(yield e.get(t,{headers:n})).data}catch(e){if(e.response)throw new m(e.response.data.message||"API request failed",e.response.status);throw new m("Network error or server is unavailable",500)}}))} /** * Constructs a query string from an object of query parameters. * @@ -35,7 +35,7 @@ PERFORMANCE OF THIS SOFTWARE. * @param {object} params - An object representing query parameters. * @returns {string} - The complete URL with query string. */ -function w(e,t={}){const n=function(e={}){return Object.keys(e).map((t=>`${encodeURIComponent(t)}=${encodeURIComponent(e[t])}`)).join("&")}(t);return n?`${e}?${n}`:e}const v="https://wv2h4to5qa.execute-api.us-east-2.amazonaws.com/dev/twitter",T="https://wv2h4to5qa.execute-api.us-east-2.amazonaws.com/dev/spotify"; +function v(e,t={}){const n=function(e={}){return Object.keys(e).map((t=>`${encodeURIComponent(t)}=${encodeURIComponent(e[t])}`)).join("&")}(t);return n?`${e}?${n}`:e}const T="https://wv2h4to5qa.execute-api.us-east-2.amazonaws.com/dev/twitter",g="https://wv2h4to5qa.execute-api.us-east-2.amazonaws.com/dev/spotify"; /** * The TwitterAPI class. * @class @@ -47,13 +47,15 @@ class b{ * @param {object} options - The options object. * @param {string} options.apiKey - The API key. (Needed for data fetching) */ -constructor({apiKey:e}){this.apiKey=e} +constructor({apiKey:e}){if(!e||"string"!=typeof e||""===e.trim())throw new f("API key is required and must be a non-empty string");this.apiKey=e.trim()} /** * Fetch Twitter user details by username. * @param {string} twitterUserName - The Twitter username. * @returns {Promise} - The user details. * @throws {APIError} - Throws an error if the request fails. - */fetchUserByUsername(e){return c(this,void 0,void 0,(function*(){const t=w(`${v}/user`,{twitterUserName:e});return this._fetchDataWithAuth(t)}))} + */fetchUserByUsername(e){return c(this,void 0,void 0,(function*(){if(!e||"string"!=typeof e||""===e.trim())throw new f("Twitter username is required and must be a non-empty string");const t=e.trim(); +// Basic Twitter username validation (no @ symbol, alphanumeric + underscore) +if(!/^[a-zA-Z0-9_]{1,15}$/.test(t))throw new f("Invalid Twitter username format");const n=v(`${T}/user`,{twitterUserName:t});return this._fetchDataWithAuth(n)}))} /** * Fetch tweets by Twitter username. * @param {string} twitterUserName - The Twitter username. @@ -61,7 +63,7 @@ constructor({apiKey:e}){this.apiKey=e} * @param {number} limit - The number of items per page. * @returns {Promise} - The tweets. * @throws {APIError} - Throws an error if the request fails. - */fetchTweetsByUsername(e){return c(this,arguments,void 0,(function*(e,t=1,n=10){const i=w(`${v}/tweets`,{twitterUserName:e,page:t,limit:n});return this._fetchDataWithAuth(i)}))} + */fetchTweetsByUsername(e){return c(this,arguments,void 0,(function*(e,t=1,n=10){if(!e||"string"!=typeof e||""===e.trim())throw new f("Twitter username is required and must be a non-empty string");const i=e.trim();if(!/^[a-zA-Z0-9_]{1,15}$/.test(i))throw new f("Invalid Twitter username format");if(!Number.isInteger(t)||t<1)throw new f("Page must be a positive integer");if(!Number.isInteger(n)||n<1||n>100)throw new f("Limit must be a positive integer between 1 and 100");const r=v(`${T}/tweets`,{twitterUserName:i,page:t,limit:n});return this._fetchDataWithAuth(r)}))} /** * Fetch followers by Twitter username. * @param {string} twitterUserName - The Twitter username. @@ -69,7 +71,7 @@ constructor({apiKey:e}){this.apiKey=e} * @param {number} limit - The number of items per page. * @returns {Promise} - The followers. * @throws {APIError} - Throws an error if the request fails. - */fetchFollowersByUsername(e){return c(this,arguments,void 0,(function*(e,t=1,n=10){const i=w(`${v}/followers`,{twitterUserName:e,page:t,limit:n});return this._fetchDataWithAuth(i)}))} + */fetchFollowersByUsername(e){return c(this,arguments,void 0,(function*(e,t=1,n=10){const{validatedUsername:i,validatedPage:r,validatedLimit:a}=this._validateUsernamePageLimit(e,t,n),s=v(`${T}/followers`,{twitterUserName:i,page:r,limit:a});return this._fetchDataWithAuth(s)}))} /** * Fetch following by Twitter username. * @param {string} twitterUserName - The Twitter username. @@ -77,13 +79,15 @@ constructor({apiKey:e}){this.apiKey=e} * @param {number} limit - The number of items per page. * @returns {Promise} - The following. * @throws {APIError} - Throws an error if the request fails. - */fetchFollowingByUsername(e){return c(this,arguments,void 0,(function*(e,t=1,n=10){const i=w(`${v}/following`,{twitterUserName:e,page:t,limit:n});return this._fetchDataWithAuth(i)}))} + */fetchFollowingByUsername(e){return c(this,arguments,void 0,(function*(e,t=1,n=10){const{validatedUsername:i,validatedPage:r,validatedLimit:a}=this._validateUsernamePageLimit(e,t,n),s=v(`${T}/following`,{twitterUserName:i,page:r,limit:a});return this._fetchDataWithAuth(s)}))} /** * Fetch tweet by tweet ID. * @param {string} tweetId - The tweet ID. * @returns {Promise} - The tweet. * @throws {APIError} - Throws an error if the request fails. - */fetchTweetById(e){return c(this,void 0,void 0,(function*(){const t=w(`${v}/getTweetById`,{tweetId:e});return this._fetchDataWithAuth(t)}))} + */fetchTweetById(e){return c(this,void 0,void 0,(function*(){if(!e||"string"!=typeof e||""===e.trim())throw new f("Tweet ID is required and must be a non-empty string");const t=e.trim(); +// Basic tweet ID validation (should be numeric) +if(!/^\d+$/.test(t))throw new f("Invalid tweet ID format");const n=v(`${T}/getTweetById`,{tweetId:t});return this._fetchDataWithAuth(n)}))} /** * Fetch user by wallet address. * @param {string} walletAddress - The wallet address. @@ -91,7 +95,7 @@ constructor({apiKey:e}){this.apiKey=e} * @param {number} limit - The number of items per page. * @returns {Promise} - The user data. * @throws {APIError} - Throws an error if the request fails. - */fetchUserByWalletAddress(e){return c(this,arguments,void 0,(function*(e,t=1,n=10){const i=w(`${v}/wallet-twitter-data`,{walletAddress:e,page:t,limit:n});return this._fetchDataWithAuth(i)}))} + */fetchUserByWalletAddress(e){return c(this,arguments,void 0,(function*(e,t=1,n=10){if(!e||"string"!=typeof e||""===e.trim())throw new f("Wallet address is required and must be a non-empty string");const i=e.trim();if(!/^0x[a-fA-F0-9]{40}$/.test(i))throw new f("Invalid wallet address format");if(!Number.isInteger(t)||t<1)throw new f("Page must be a positive integer");if(!Number.isInteger(n)||n<1||n>100)throw new f("Limit must be a positive integer between 1 and 100");const r=v(`${T}/wallet-twitter-data`,{walletAddress:i,page:t,limit:n});return this._fetchDataWithAuth(r)}))} /** * Fetch reposted tweets by Twitter username. * @param {string} twitterUserName - The Twitter username. @@ -99,7 +103,7 @@ constructor({apiKey:e}){this.apiKey=e} * @param {number} limit - The number of items per page. * @returns {Promise} - The reposted tweets. * @throws {APIError} - Throws an error if the request fails. - */fetchRepostedByUsername(e){return c(this,arguments,void 0,(function*(e,t=1,n=10){const i=w(`${v}/reposted`,{twitterUserName:e,page:t,limit:n});return this._fetchDataWithAuth(i)}))} + */fetchRepostedByUsername(e){return c(this,arguments,void 0,(function*(e,t=1,n=10){const{validatedUsername:i,validatedPage:r,validatedLimit:a}=this._validateUsernamePageLimit(e,t,n),s=v(`${T}/reposted`,{twitterUserName:i,page:r,limit:a});return this._fetchDataWithAuth(s)}))} /** * Fetch replies by Twitter username. * @param {string} twitterUserName - The Twitter username. @@ -107,7 +111,7 @@ constructor({apiKey:e}){this.apiKey=e} * @param {number} limit - The number of items per page. * @returns {Promise} - The replies. * @throws {APIError} - Throws an error if the request fails. - */fetchRepliesByUsername(e){return c(this,arguments,void 0,(function*(e,t=1,n=10){const i=w(`${v}/replies`,{twitterUserName:e,page:t,limit:n});return this._fetchDataWithAuth(i)}))} + */fetchRepliesByUsername(e){return c(this,arguments,void 0,(function*(e,t=1,n=10){const{validatedUsername:i,validatedPage:r,validatedLimit:a}=this._validateUsernamePageLimit(e,t,n),s=v(`${T}/replies`,{twitterUserName:i,page:r,limit:a});return this._fetchDataWithAuth(s)}))} /** * Fetch likes by Twitter username. * @param {string} twitterUserName - The Twitter username. @@ -115,7 +119,7 @@ constructor({apiKey:e}){this.apiKey=e} * @param {number} limit - The number of items per page. * @returns {Promise} - The likes. * @throws {APIError} - Throws an error if the request fails. - */fetchLikesByUsername(e){return c(this,arguments,void 0,(function*(e,t=1,n=10){const i=w(`${v}/event/likes/${e}`,{page:t,limit:n});return this._fetchDataWithAuth(i)}))} + */fetchLikesByUsername(e){return c(this,arguments,void 0,(function*(e,t=1,n=10){const{validatedUsername:i,validatedPage:r,validatedLimit:a}=this._validateUsernamePageLimit(e,t,n),s=v(`${T}/event/likes/${i}`,{page:r,limit:a});return this._fetchDataWithAuth(s)}))} /** * Fetch follows by Twitter username. * @param {string} twitterUserName - The Twitter username. @@ -123,7 +127,7 @@ constructor({apiKey:e}){this.apiKey=e} * @param {number} limit - The number of items per page. * @returns {Promise} - The follows. * @throws {APIError} - Throws an error if the request fails. - */fetchFollowsByUsername(e){return c(this,arguments,void 0,(function*(e,t=1,n=10){const i=w(`${v}/event/follows/${e}`,{page:t,limit:n});return this._fetchDataWithAuth(i)}))} + */fetchFollowsByUsername(e){return c(this,arguments,void 0,(function*(e,t=1,n=10){const{validatedUsername:i,validatedPage:r,validatedLimit:a}=this._validateUsernamePageLimit(e,t,n),s=v(`${T}/event/follows/${i}`,{page:r,limit:a});return this._fetchDataWithAuth(s)}))} /** * Fetch viewed tweets by Twitter username. * @param {string} twitterUserName - The Twitter username. @@ -131,17 +135,25 @@ constructor({apiKey:e}){this.apiKey=e} * @param {number} limit - The number of items per page. * @returns {Promise} - The viewed tweets. * @throws {APIError} - Throws an error if the request fails. - */fetchViewedTweetsByUsername(e){return c(this,arguments,void 0,(function*(e,t=1,n=10){const i=w(`${v}/event/viewed-tweets/${e}`,{page:t,limit:n});return this._fetchDataWithAuth(i)}))} + */fetchViewedTweetsByUsername(e){return c(this,arguments,void 0,(function*(e,t=1,n=10){const{validatedUsername:i,validatedPage:r,validatedLimit:a}=this._validateUsernamePageLimit(e,t,n),s=v(`${T}/event/viewed-tweets/${i}`,{page:r,limit:a});return this._fetchDataWithAuth(s)}))} +/** + * Private method to validate username, page, and limit parameters. + * @param {string} twitterUserName - The Twitter username. + * @param {number} page - The page number. + * @param {number} limit - The limit number. + * @returns {object} - Validated parameters. + * @throws {ValidationError} - Throws an error if validation fails. + */_validateUsernamePageLimit(e,t,n){if(!e||"string"!=typeof e||""===e.trim())throw new f("Twitter username is required and must be a non-empty string");const i=e.trim();if(!/^[a-zA-Z0-9_]{1,15}$/.test(i))throw new f("Invalid Twitter username format");if(!Number.isInteger(t)||t<1)throw new f("Page must be a positive integer");if(!Number.isInteger(n)||n<1||n>100)throw new f("Limit must be a positive integer between 1 and 100");return{validatedUsername:i,validatedPage:t,validatedLimit:n}} /** * Private method to fetch data with authorization header. * @param {string} url - The URL to fetch. * @returns {Promise} - The response data. * @throws {APIError} - Throws an error if the request fails. - */_fetchDataWithAuth(e){return c(this,void 0,void 0,(function*(){if(!this.apiKey)throw new m("API key is required for fetching data",401);try{return yield f(e,{"x-api-key":this.apiKey})}catch(e){throw new m(e.message,e.statusCode)}}))}} + */_fetchDataWithAuth(e){return c(this,void 0,void 0,(function*(){if(!this.apiKey)throw new m("API key is required for fetching data",401);try{return yield w(e,{"x-api-key":this.apiKey})}catch(e){throw new m(e.message,e.statusCode)}}))}} /** * The SpotifyAPI class. * @class - */class g{ + */class I{ /** * Constructor for the SpotifyAPI class. * @constructor @@ -149,59 +161,61 @@ constructor({apiKey:e}){this.apiKey=e} * @param {string} options.apiKey - The Spotify API key. * @throws {Error} - Throws an error if the API key is not provided. */ -constructor(e){this.apiKey=e.apiKey} +constructor(e){if(!e||!e.apiKey||"string"!=typeof e.apiKey||""===e.apiKey.trim())throw new f("API key is required and must be a non-empty string");this.apiKey=e.apiKey.trim()} /** * Fetch the user's saved tracks by Spotify user ID. * @param {string} spotifyId - The user's Spotify ID. * @returns {Promise} - The saved tracks. * @throws {APIError} - Throws an error if the request fails. - */fetchSavedTracksById(e){return c(this,void 0,void 0,(function*(){const t=w(`${T}/save-tracks`,{spotifyId:e});return this._fetchDataWithAuth(t)}))} + */fetchSavedTracksById(e){return c(this,void 0,void 0,(function*(){if(!e||"string"!=typeof e||""===e.trim())throw new f("Spotify ID is required and must be a non-empty string");const t=v(`${g}/save-tracks`,{spotifyId:e.trim()});return this._fetchDataWithAuth(t)}))} /** * Fetch the played tracks of a user by Spotify ID. * @param {string} spotifyId - The user's Spotify ID. * @returns {Promise} - The played tracks. * @throws {APIError} - Throws an error if the request fails. - */fetchPlayedTracksById(e){return c(this,void 0,void 0,(function*(){const t=w(`${T}/played-tracks`,{spotifyId:e});return this._fetchDataWithAuth(t)}))} + */fetchPlayedTracksById(e){return c(this,void 0,void 0,(function*(){if(!e||"string"!=typeof e||""===e.trim())throw new f("Spotify ID is required and must be a non-empty string");const t=v(`${g}/played-tracks`,{spotifyId:e.trim()});return this._fetchDataWithAuth(t)}))} /** * Fetch the user's saved albums by Spotify user ID. * @param {string} spotifyId - The user's Spotify ID. * @returns {Promise} - The saved albums. * @throws {APIError} - Throws an error if the request fails. - */fetchSavedAlbumsById(e){return c(this,void 0,void 0,(function*(){const t=w(`${T}/saved-albums`,{spotifyId:e});return this._fetchDataWithAuth(t)}))} + */fetchSavedAlbumsById(e){return c(this,void 0,void 0,(function*(){if(!e||"string"!=typeof e||""===e.trim())throw new f("Spotify ID is required and must be a non-empty string");const t=v(`${g}/saved-albums`,{spotifyId:e.trim()});return this._fetchDataWithAuth(t)}))} /** * Fetch the user's saved playlists by Spotify user ID. * @param {string} spotifyId - The user's Spotify ID. * @returns {Promise} - The saved playlists. * @throws {APIError} - Throws an error if the request fails. - */fetchSavedPlaylistsById(e){return c(this,void 0,void 0,(function*(){const t=w(`${T}/saved-playlists`,{spotifyId:e});return this._fetchDataWithAuth(t)}))} + */fetchSavedPlaylistsById(e){return c(this,void 0,void 0,(function*(){if(!e||"string"!=typeof e||""===e.trim())throw new f("Spotify ID is required and must be a non-empty string");const t=v(`${g}/saved-playlists`,{spotifyId:e.trim()});return this._fetchDataWithAuth(t)}))} /** * Fetch the tracks of an album by album ID. * @param {string} spotifyId - The Spotify ID of the user. * @param {string} albumId - The album ID. * @returns {Promise} - The tracks in the album. * @throws {APIError} - Throws an error if the request fails. - */fetchTracksInAlbum(e,t){return c(this,void 0,void 0,(function*(){const n=w(`${T}/album/tracks`,{spotifyId:e,albumId:t});return this._fetchDataWithAuth(n)}))} + */fetchTracksInAlbum(e,t){return c(this,void 0,void 0,(function*(){if(!e||"string"!=typeof e||""===e.trim())throw new f("Spotify ID is required and must be a non-empty string");if(!t||"string"!=typeof t||""===t.trim())throw new f("Album ID is required and must be a non-empty string");const n=v(`${g}/album/tracks`,{spotifyId:e.trim(),albumId:t.trim()});return this._fetchDataWithAuth(n)}))} /** * Fetch the tracks in a playlist by playlist ID. * @param {string} spotifyId - The Spotify ID of the user. * @param {string} playlistId - The playlist ID. * @returns {Promise} - The tracks in the playlist. * @throws {APIError} - Throws an error if the request fails. - */fetchTracksInPlaylist(e,t){return c(this,void 0,void 0,(function*(){const n=w(`${T}/playlist/tracks`,{spotifyId:e,playlistId:t});return this._fetchDataWithAuth(n)}))} + */fetchTracksInPlaylist(e,t){return c(this,void 0,void 0,(function*(){if(!e||"string"!=typeof e||""===e.trim())throw new f("Spotify ID is required and must be a non-empty string");if(!t||"string"!=typeof t||""===t.trim())throw new f("Playlist ID is required and must be a non-empty string");const n=v(`${g}/playlist/tracks`,{spotifyId:e.trim(),playlistId:t.trim()});return this._fetchDataWithAuth(n)}))} /** * Fetch the user's Spotify data by wallet address. * @param {string} walletAddress - The wallet address. * @returns {Promise} - The user's Spotify data. * @throws {APIError} - Throws an error if the request fails. - */fetchUserByWalletAddress(e){return c(this,void 0,void 0,(function*(){const t=w(`${T}/wallet-spotify-data`,{walletAddress:e});return this._fetchDataWithAuth(t)}))} + */fetchUserByWalletAddress(e){return c(this,void 0,void 0,(function*(){if(!e||"string"!=typeof e||""===e.trim())throw new f("Wallet address is required and must be a non-empty string"); +// Basic Ethereum address format validation +const t=e.trim();if(!/^0x[a-fA-F0-9]{40}$/.test(t))throw new f("Invalid wallet address format");const n=v(`${g}/wallet-spotify-data`,{walletAddress:t});return this._fetchDataWithAuth(n)}))} /** * Private method to fetch data with authorization header. * @param {string} url - The URL to fetch. * @returns {Promise} - The response data. * @throws {APIError} - Throws an error if the request fails. - */_fetchDataWithAuth(e){return c(this,void 0,void 0,(function*(){if(!this.apiKey)throw new m("API key is required for fetching data",401);try{return yield f(e,{"x-api-key":this.apiKey})}catch(e){throw new m(e.message,e.statusCode)}}))}}const I={id:123420001114,name:"Basecamp",nativeCurrency:{decimals:18,name:"Camp",symbol:"CAMP"},rpcUrls:{default:{http:["https://rpc-campnetwork.xyz","https://rpc.basecamp.t.raas.gelato.cloud"]}},blockExplorers:{default:{name:"Explorer",url:"https://basecamp.cloud.blockscout.com/"}}}; + */_fetchDataWithAuth(e){return c(this,void 0,void 0,(function*(){if(!this.apiKey)throw new m("API key is required for fetching data",401);try{return yield w(e,{"x-api-key":this.apiKey})}catch(e){throw new m(e.message,e.statusCode)}}))}}const A={id:123420001114,name:"Basecamp",nativeCurrency:{decimals:18,name:"Camp",symbol:"CAMP"},rpcUrls:{default:{http:["https://rpc-campnetwork.xyz","https://rpc.basecamp.t.raas.gelato.cloud"]}},blockExplorers:{default:{name:"Explorer",url:"https://basecamp.cloud.blockscout.com/"}}}; // @ts-ignore -let k=null,A=null;const C=()=>(A||(A=i({chain:I,transport:a()})),A);var E="Connect with Camp Network",x="https://wv2h4to5qa.execute-api.us-east-2.amazonaws.com/dev",M={USER_CONNECTED:"ed42542d-b676-4112-b6d9-6db98048b2e0",USER_DISCONNECTED:"20af31ac-e602-442e-9e0e-b589f4dd4016",TWITTER_LINKED:"7fbea086-90ef-4679-ba69-f47f9255b34c",DISCORD_LINKED:"d73f5ae3-a8e8-48f2-8532-85e0c7780d6a",SPOTIFY_LINKED:"fc1788b4-c984-42c8-96f4-c87f6bb0b8f7",TIKTOK_LINKED:"4a2ffdd3-f0e9-4784-8b49-ff76ec1c0a6a",TELEGRAM_LINKED:"9006bc5d-bcc9-4d01-a860-4f1a201e8e47"},S="0xF90733b9eCDa3b49C250B2C3E3E42c96fC93324E",$="0x5c5e6b458b2e3924E7688b8Dee1Bb49088F6Fef5";let F=[];const O=()=>F,j=e=>{function t(t){F.some((e=>e.info.uuid===t.detail.info.uuid))||(F=[...F,t.detail],e(F))}if("undefined"!=typeof window)return window.addEventListener("eip6963:announceProvider",t),window.dispatchEvent(new Event("eip6963:requestProvider")),()=>window.removeEventListener("eip6963:announceProvider",t)};var P=[{inputs:[{internalType:"string",name:"name_",type:"string"},{internalType:"string",name:"symbol_",type:"string"},{internalType:"uint256",name:"maxTermDuration_",type:"uint256"},{internalType:"address",name:"signer_",type:"address"}],stateMutability:"nonpayable",type:"constructor"},{inputs:[],name:"DurationZero",type:"error"},{inputs:[{internalType:"address",name:"sender",type:"address"},{internalType:"uint256",name:"tokenId",type:"uint256"},{internalType:"address",name:"owner",type:"address"}],name:"ERC721IncorrectOwner",type:"error"},{inputs:[{internalType:"address",name:"operator",type:"address"},{internalType:"uint256",name:"tokenId",type:"uint256"}],name:"ERC721InsufficientApproval",type:"error"},{inputs:[{internalType:"address",name:"approver",type:"address"}],name:"ERC721InvalidApprover",type:"error"},{inputs:[{internalType:"address",name:"operator",type:"address"}],name:"ERC721InvalidOperator",type:"error"},{inputs:[{internalType:"address",name:"owner",type:"address"}],name:"ERC721InvalidOwner",type:"error"},{inputs:[{internalType:"address",name:"receiver",type:"address"}],name:"ERC721InvalidReceiver",type:"error"},{inputs:[{internalType:"address",name:"sender",type:"address"}],name:"ERC721InvalidSender",type:"error"},{inputs:[{internalType:"uint256",name:"tokenId",type:"uint256"}],name:"ERC721NonexistentToken",type:"error"},{inputs:[],name:"EnforcedPause",type:"error"},{inputs:[],name:"ExpectedPause",type:"error"},{inputs:[],name:"InvalidDeadline",type:"error"},{inputs:[],name:"InvalidDuration",type:"error"},{inputs:[{internalType:"uint16",name:"royaltyBps",type:"uint16"}],name:"InvalidRoyalty",type:"error"},{inputs:[],name:"InvalidSignature",type:"error"},{inputs:[{internalType:"uint256",name:"tokenId",type:"uint256"},{internalType:"address",name:"caller",type:"address"}],name:"NotTokenOwner",type:"error"},{inputs:[{internalType:"address",name:"owner",type:"address"}],name:"OwnableInvalidOwner",type:"error"},{inputs:[{internalType:"address",name:"account",type:"address"}],name:"OwnableUnauthorizedAccount",type:"error"},{inputs:[],name:"SignatureAlreadyUsed",type:"error"},{inputs:[{internalType:"uint256",name:"tokenId",type:"uint256"}],name:"TokenAlreadyExists",type:"error"},{inputs:[],name:"Unauthorized",type:"error"},{anonymous:!1,inputs:[{indexed:!0,internalType:"uint256",name:"tokenId",type:"uint256"},{indexed:!0,internalType:"address",name:"buyer",type:"address"},{indexed:!1,internalType:"uint32",name:"periods",type:"uint32"},{indexed:!1,internalType:"uint256",name:"newExpiry",type:"uint256"},{indexed:!1,internalType:"uint256",name:"amountPaid",type:"uint256"}],name:"AccessPurchased",type:"event"},{anonymous:!1,inputs:[{indexed:!0,internalType:"address",name:"owner",type:"address"},{indexed:!0,internalType:"address",name:"approved",type:"address"},{indexed:!0,internalType:"uint256",name:"tokenId",type:"uint256"}],name:"Approval",type:"event"},{anonymous:!1,inputs:[{indexed:!0,internalType:"address",name:"owner",type:"address"},{indexed:!0,internalType:"address",name:"operator",type:"address"},{indexed:!1,internalType:"bool",name:"approved",type:"bool"}],name:"ApprovalForAll",type:"event"},{anonymous:!1,inputs:[{indexed:!0,internalType:"uint256",name:"tokenId",type:"uint256"},{indexed:!0,internalType:"address",name:"creator",type:"address"}],name:"DataDeleted",type:"event"},{anonymous:!1,inputs:[{indexed:!0,internalType:"uint256",name:"tokenId",type:"uint256"},{indexed:!0,internalType:"address",name:"creator",type:"address"},{indexed:!1,internalType:"bytes32",name:"contentHash",type:"bytes32"}],name:"DataMinted",type:"event"},{anonymous:!1,inputs:[{indexed:!0,internalType:"address",name:"previousOwner",type:"address"},{indexed:!0,internalType:"address",name:"newOwner",type:"address"}],name:"OwnershipTransferred",type:"event"},{anonymous:!1,inputs:[{indexed:!1,internalType:"address",name:"account",type:"address"}],name:"Paused",type:"event"},{anonymous:!1,inputs:[{indexed:!0,internalType:"uint256",name:"tokenId",type:"uint256"},{indexed:!1,internalType:"uint256",name:"royaltyAmount",type:"uint256"},{indexed:!1,internalType:"address",name:"creator",type:"address"},{indexed:!1,internalType:"uint256",name:"protocolAmount",type:"uint256"}],name:"RoyaltyPaid",type:"event"},{anonymous:!1,inputs:[{indexed:!0,internalType:"uint256",name:"tokenId",type:"uint256"},{indexed:!1,internalType:"uint128",name:"newPrice",type:"uint128"},{indexed:!1,internalType:"uint32",name:"newDuration",type:"uint32"},{indexed:!1,internalType:"uint16",name:"newRoyaltyBps",type:"uint16"},{indexed:!1,internalType:"address",name:"paymentToken",type:"address"}],name:"TermsUpdated",type:"event"},{anonymous:!1,inputs:[{indexed:!0,internalType:"address",name:"from",type:"address"},{indexed:!0,internalType:"address",name:"to",type:"address"},{indexed:!0,internalType:"uint256",name:"tokenId",type:"uint256"}],name:"Transfer",type:"event"},{anonymous:!1,inputs:[{indexed:!1,internalType:"address",name:"account",type:"address"}],name:"Unpaused",type:"event"},{inputs:[{internalType:"address",name:"to",type:"address"},{internalType:"uint256",name:"tokenId",type:"uint256"}],name:"approve",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"address",name:"owner",type:"address"}],name:"balanceOf",outputs:[{internalType:"uint256",name:"",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"uint256",name:"",type:"uint256"}],name:"contentHash",outputs:[{internalType:"bytes32",name:"",type:"bytes32"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"uint256",name:"",type:"uint256"}],name:"dataStatus",outputs:[{internalType:"enum IpNFT.DataStatus",name:"",type:"uint8"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"uint256",name:"tokenId",type:"uint256"}],name:"finalizeDelete",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"uint256",name:"tokenId",type:"uint256"}],name:"getApproved",outputs:[{internalType:"address",name:"",type:"address"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"uint256",name:"tokenId",type:"uint256"}],name:"getTerms",outputs:[{components:[{internalType:"uint128",name:"price",type:"uint128"},{internalType:"uint32",name:"duration",type:"uint32"},{internalType:"uint16",name:"royaltyBps",type:"uint16"},{internalType:"address",name:"paymentToken",type:"address"}],internalType:"struct IpNFT.LicenseTerms",name:"",type:"tuple"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"address",name:"owner",type:"address"},{internalType:"address",name:"operator",type:"address"}],name:"isApprovedForAll",outputs:[{internalType:"bool",name:"",type:"bool"}],stateMutability:"view",type:"function"},{inputs:[],name:"maxTermDuration",outputs:[{internalType:"uint256",name:"",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"address",name:"to",type:"address"},{internalType:"uint256",name:"tokenId",type:"uint256"},{internalType:"uint256",name:"parentId",type:"uint256"},{internalType:"bytes32",name:"creatorContentHash",type:"bytes32"},{internalType:"string",name:"uri",type:"string"},{components:[{internalType:"uint128",name:"price",type:"uint128"},{internalType:"uint32",name:"duration",type:"uint32"},{internalType:"uint16",name:"royaltyBps",type:"uint16"},{internalType:"address",name:"paymentToken",type:"address"}],internalType:"struct IpNFT.LicenseTerms",name:"licenseTerms",type:"tuple"},{internalType:"uint256",name:"deadline",type:"uint256"},{internalType:"bytes",name:"signature",type:"bytes"}],name:"mintWithSignature",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[],name:"name",outputs:[{internalType:"string",name:"",type:"string"}],stateMutability:"view",type:"function"},{inputs:[],name:"owner",outputs:[{internalType:"address",name:"",type:"address"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"uint256",name:"tokenId",type:"uint256"}],name:"ownerOf",outputs:[{internalType:"address",name:"",type:"address"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"uint256",name:"",type:"uint256"}],name:"parentIpOf",outputs:[{internalType:"uint256",name:"",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[],name:"pause",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[],name:"paused",outputs:[{internalType:"bool",name:"",type:"bool"}],stateMutability:"view",type:"function"},{inputs:[],name:"renounceOwnership",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"uint256",name:"tokenId",type:"uint256"},{internalType:"uint256",name:"salePrice",type:"uint256"}],name:"royaltyInfo",outputs:[{internalType:"address",name:"receiver",type:"address"},{internalType:"uint256",name:"royaltyAmount",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"uint256",name:"",type:"uint256"}],name:"royaltyPercentages",outputs:[{internalType:"uint16",name:"",type:"uint16"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"uint256",name:"",type:"uint256"}],name:"royaltyReceivers",outputs:[{internalType:"address",name:"",type:"address"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"address",name:"from",type:"address"},{internalType:"address",name:"to",type:"address"},{internalType:"uint256",name:"tokenId",type:"uint256"}],name:"safeTransferFrom",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"address",name:"from",type:"address"},{internalType:"address",name:"to",type:"address"},{internalType:"uint256",name:"tokenId",type:"uint256"},{internalType:"bytes",name:"data",type:"bytes"}],name:"safeTransferFrom",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"address",name:"operator",type:"address"},{internalType:"bool",name:"approved",type:"bool"}],name:"setApprovalForAll",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"address",name:"_signer",type:"address"}],name:"setSigner",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[],name:"signer",outputs:[{internalType:"address",name:"",type:"address"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"bytes4",name:"interfaceId",type:"bytes4"}],name:"supportsInterface",outputs:[{internalType:"bool",name:"",type:"bool"}],stateMutability:"view",type:"function"},{inputs:[],name:"symbol",outputs:[{internalType:"string",name:"",type:"string"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"uint256",name:"",type:"uint256"}],name:"terms",outputs:[{internalType:"uint128",name:"price",type:"uint128"},{internalType:"uint32",name:"duration",type:"uint32"},{internalType:"uint16",name:"royaltyBps",type:"uint16"},{internalType:"address",name:"paymentToken",type:"address"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"uint256",name:"_tokenId",type:"uint256"}],name:"tokenURI",outputs:[{internalType:"string",name:"",type:"string"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"address",name:"from",type:"address"},{internalType:"address",name:"to",type:"address"},{internalType:"uint256",name:"tokenId",type:"uint256"}],name:"transferFrom",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"address",name:"newOwner",type:"address"}],name:"transferOwnership",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[],name:"unpause",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"uint256",name:"tokenId",type:"uint256"},{internalType:"address",name:"_royaltyReceiver",type:"address"},{components:[{internalType:"uint128",name:"price",type:"uint128"},{internalType:"uint32",name:"duration",type:"uint32"},{internalType:"uint16",name:"royaltyBps",type:"uint16"},{internalType:"address",name:"paymentToken",type:"address"}],internalType:"struct IpNFT.LicenseTerms",name:"newTerms",type:"tuple"}],name:"updateTerms",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"bytes32",name:"",type:"bytes32"}],name:"usedNonces",outputs:[{internalType:"bool",name:"",type:"bool"}],stateMutability:"view",type:"function"}]; +let k=null,C=null;const E=()=>(C||(C=i({chain:A,transport:r()})),C);var x="Connect with Camp Network",M="https://wv2h4to5qa.execute-api.us-east-2.amazonaws.com/dev",S={USER_CONNECTED:"ed42542d-b676-4112-b6d9-6db98048b2e0",USER_DISCONNECTED:"20af31ac-e602-442e-9e0e-b589f4dd4016",TWITTER_LINKED:"7fbea086-90ef-4679-ba69-f47f9255b34c",DISCORD_LINKED:"d73f5ae3-a8e8-48f2-8532-85e0c7780d6a",SPOTIFY_LINKED:"fc1788b4-c984-42c8-96f4-c87f6bb0b8f7",TIKTOK_LINKED:"4a2ffdd3-f0e9-4784-8b49-ff76ec1c0a6a",TELEGRAM_LINKED:"9006bc5d-bcc9-4d01-a860-4f1a201e8e47"},P="0xF90733b9eCDa3b49C250B2C3E3E42c96fC93324E",$="0x5c5e6b458b2e3924E7688b8Dee1Bb49088F6Fef5";let U=[];const F=()=>U,O=e=>{function t(t){U.some((e=>e.info.uuid===t.detail.info.uuid))||(U=[...U,t.detail],e(U))}if("undefined"!=typeof window)return window.addEventListener("eip6963:announceProvider",t),window.dispatchEvent(new Event("eip6963:requestProvider")),()=>window.removeEventListener("eip6963:announceProvider",t)};var N=[{inputs:[{internalType:"string",name:"name_",type:"string"},{internalType:"string",name:"symbol_",type:"string"},{internalType:"uint256",name:"maxTermDuration_",type:"uint256"},{internalType:"address",name:"signer_",type:"address"}],stateMutability:"nonpayable",type:"constructor"},{inputs:[],name:"DurationZero",type:"error"},{inputs:[{internalType:"address",name:"sender",type:"address"},{internalType:"uint256",name:"tokenId",type:"uint256"},{internalType:"address",name:"owner",type:"address"}],name:"ERC721IncorrectOwner",type:"error"},{inputs:[{internalType:"address",name:"operator",type:"address"},{internalType:"uint256",name:"tokenId",type:"uint256"}],name:"ERC721InsufficientApproval",type:"error"},{inputs:[{internalType:"address",name:"approver",type:"address"}],name:"ERC721InvalidApprover",type:"error"},{inputs:[{internalType:"address",name:"operator",type:"address"}],name:"ERC721InvalidOperator",type:"error"},{inputs:[{internalType:"address",name:"owner",type:"address"}],name:"ERC721InvalidOwner",type:"error"},{inputs:[{internalType:"address",name:"receiver",type:"address"}],name:"ERC721InvalidReceiver",type:"error"},{inputs:[{internalType:"address",name:"sender",type:"address"}],name:"ERC721InvalidSender",type:"error"},{inputs:[{internalType:"uint256",name:"tokenId",type:"uint256"}],name:"ERC721NonexistentToken",type:"error"},{inputs:[],name:"EnforcedPause",type:"error"},{inputs:[],name:"ExpectedPause",type:"error"},{inputs:[],name:"InvalidDeadline",type:"error"},{inputs:[],name:"InvalidDuration",type:"error"},{inputs:[{internalType:"uint16",name:"royaltyBps",type:"uint16"}],name:"InvalidRoyalty",type:"error"},{inputs:[],name:"InvalidSignature",type:"error"},{inputs:[{internalType:"uint256",name:"tokenId",type:"uint256"},{internalType:"address",name:"caller",type:"address"}],name:"NotTokenOwner",type:"error"},{inputs:[{internalType:"address",name:"owner",type:"address"}],name:"OwnableInvalidOwner",type:"error"},{inputs:[{internalType:"address",name:"account",type:"address"}],name:"OwnableUnauthorizedAccount",type:"error"},{inputs:[],name:"SignatureAlreadyUsed",type:"error"},{inputs:[{internalType:"uint256",name:"tokenId",type:"uint256"}],name:"TokenAlreadyExists",type:"error"},{inputs:[],name:"Unauthorized",type:"error"},{anonymous:!1,inputs:[{indexed:!0,internalType:"uint256",name:"tokenId",type:"uint256"},{indexed:!0,internalType:"address",name:"buyer",type:"address"},{indexed:!1,internalType:"uint32",name:"periods",type:"uint32"},{indexed:!1,internalType:"uint256",name:"newExpiry",type:"uint256"},{indexed:!1,internalType:"uint256",name:"amountPaid",type:"uint256"}],name:"AccessPurchased",type:"event"},{anonymous:!1,inputs:[{indexed:!0,internalType:"address",name:"owner",type:"address"},{indexed:!0,internalType:"address",name:"approved",type:"address"},{indexed:!0,internalType:"uint256",name:"tokenId",type:"uint256"}],name:"Approval",type:"event"},{anonymous:!1,inputs:[{indexed:!0,internalType:"address",name:"owner",type:"address"},{indexed:!0,internalType:"address",name:"operator",type:"address"},{indexed:!1,internalType:"bool",name:"approved",type:"bool"}],name:"ApprovalForAll",type:"event"},{anonymous:!1,inputs:[{indexed:!0,internalType:"uint256",name:"tokenId",type:"uint256"},{indexed:!0,internalType:"address",name:"creator",type:"address"}],name:"DataDeleted",type:"event"},{anonymous:!1,inputs:[{indexed:!0,internalType:"uint256",name:"tokenId",type:"uint256"},{indexed:!0,internalType:"address",name:"creator",type:"address"},{indexed:!1,internalType:"bytes32",name:"contentHash",type:"bytes32"}],name:"DataMinted",type:"event"},{anonymous:!1,inputs:[{indexed:!0,internalType:"address",name:"previousOwner",type:"address"},{indexed:!0,internalType:"address",name:"newOwner",type:"address"}],name:"OwnershipTransferred",type:"event"},{anonymous:!1,inputs:[{indexed:!1,internalType:"address",name:"account",type:"address"}],name:"Paused",type:"event"},{anonymous:!1,inputs:[{indexed:!0,internalType:"uint256",name:"tokenId",type:"uint256"},{indexed:!1,internalType:"uint256",name:"royaltyAmount",type:"uint256"},{indexed:!1,internalType:"address",name:"creator",type:"address"},{indexed:!1,internalType:"uint256",name:"protocolAmount",type:"uint256"}],name:"RoyaltyPaid",type:"event"},{anonymous:!1,inputs:[{indexed:!0,internalType:"uint256",name:"tokenId",type:"uint256"},{indexed:!1,internalType:"uint128",name:"newPrice",type:"uint128"},{indexed:!1,internalType:"uint32",name:"newDuration",type:"uint32"},{indexed:!1,internalType:"uint16",name:"newRoyaltyBps",type:"uint16"},{indexed:!1,internalType:"address",name:"paymentToken",type:"address"}],name:"TermsUpdated",type:"event"},{anonymous:!1,inputs:[{indexed:!0,internalType:"address",name:"from",type:"address"},{indexed:!0,internalType:"address",name:"to",type:"address"},{indexed:!0,internalType:"uint256",name:"tokenId",type:"uint256"}],name:"Transfer",type:"event"},{anonymous:!1,inputs:[{indexed:!1,internalType:"address",name:"account",type:"address"}],name:"Unpaused",type:"event"},{inputs:[{internalType:"address",name:"to",type:"address"},{internalType:"uint256",name:"tokenId",type:"uint256"}],name:"approve",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"address",name:"owner",type:"address"}],name:"balanceOf",outputs:[{internalType:"uint256",name:"",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"uint256",name:"",type:"uint256"}],name:"contentHash",outputs:[{internalType:"bytes32",name:"",type:"bytes32"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"uint256",name:"",type:"uint256"}],name:"dataStatus",outputs:[{internalType:"enum IpNFT.DataStatus",name:"",type:"uint8"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"uint256",name:"tokenId",type:"uint256"}],name:"finalizeDelete",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"uint256",name:"tokenId",type:"uint256"}],name:"getApproved",outputs:[{internalType:"address",name:"",type:"address"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"uint256",name:"tokenId",type:"uint256"}],name:"getTerms",outputs:[{components:[{internalType:"uint128",name:"price",type:"uint128"},{internalType:"uint32",name:"duration",type:"uint32"},{internalType:"uint16",name:"royaltyBps",type:"uint16"},{internalType:"address",name:"paymentToken",type:"address"}],internalType:"struct IpNFT.LicenseTerms",name:"",type:"tuple"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"address",name:"owner",type:"address"},{internalType:"address",name:"operator",type:"address"}],name:"isApprovedForAll",outputs:[{internalType:"bool",name:"",type:"bool"}],stateMutability:"view",type:"function"},{inputs:[],name:"maxTermDuration",outputs:[{internalType:"uint256",name:"",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"address",name:"to",type:"address"},{internalType:"uint256",name:"tokenId",type:"uint256"},{internalType:"uint256",name:"parentId",type:"uint256"},{internalType:"bytes32",name:"creatorContentHash",type:"bytes32"},{internalType:"string",name:"uri",type:"string"},{components:[{internalType:"uint128",name:"price",type:"uint128"},{internalType:"uint32",name:"duration",type:"uint32"},{internalType:"uint16",name:"royaltyBps",type:"uint16"},{internalType:"address",name:"paymentToken",type:"address"}],internalType:"struct IpNFT.LicenseTerms",name:"licenseTerms",type:"tuple"},{internalType:"uint256",name:"deadline",type:"uint256"},{internalType:"bytes",name:"signature",type:"bytes"}],name:"mintWithSignature",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[],name:"name",outputs:[{internalType:"string",name:"",type:"string"}],stateMutability:"view",type:"function"},{inputs:[],name:"owner",outputs:[{internalType:"address",name:"",type:"address"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"uint256",name:"tokenId",type:"uint256"}],name:"ownerOf",outputs:[{internalType:"address",name:"",type:"address"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"uint256",name:"",type:"uint256"}],name:"parentIpOf",outputs:[{internalType:"uint256",name:"",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[],name:"pause",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[],name:"paused",outputs:[{internalType:"bool",name:"",type:"bool"}],stateMutability:"view",type:"function"},{inputs:[],name:"renounceOwnership",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"uint256",name:"tokenId",type:"uint256"},{internalType:"uint256",name:"salePrice",type:"uint256"}],name:"royaltyInfo",outputs:[{internalType:"address",name:"receiver",type:"address"},{internalType:"uint256",name:"royaltyAmount",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"uint256",name:"",type:"uint256"}],name:"royaltyPercentages",outputs:[{internalType:"uint16",name:"",type:"uint16"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"uint256",name:"",type:"uint256"}],name:"royaltyReceivers",outputs:[{internalType:"address",name:"",type:"address"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"address",name:"from",type:"address"},{internalType:"address",name:"to",type:"address"},{internalType:"uint256",name:"tokenId",type:"uint256"}],name:"safeTransferFrom",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"address",name:"from",type:"address"},{internalType:"address",name:"to",type:"address"},{internalType:"uint256",name:"tokenId",type:"uint256"},{internalType:"bytes",name:"data",type:"bytes"}],name:"safeTransferFrom",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"address",name:"operator",type:"address"},{internalType:"bool",name:"approved",type:"bool"}],name:"setApprovalForAll",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"address",name:"_signer",type:"address"}],name:"setSigner",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[],name:"signer",outputs:[{internalType:"address",name:"",type:"address"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"bytes4",name:"interfaceId",type:"bytes4"}],name:"supportsInterface",outputs:[{internalType:"bool",name:"",type:"bool"}],stateMutability:"view",type:"function"},{inputs:[],name:"symbol",outputs:[{internalType:"string",name:"",type:"string"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"uint256",name:"",type:"uint256"}],name:"terms",outputs:[{internalType:"uint128",name:"price",type:"uint128"},{internalType:"uint32",name:"duration",type:"uint32"},{internalType:"uint16",name:"royaltyBps",type:"uint16"},{internalType:"address",name:"paymentToken",type:"address"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"uint256",name:"_tokenId",type:"uint256"}],name:"tokenURI",outputs:[{internalType:"string",name:"",type:"string"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"address",name:"from",type:"address"},{internalType:"address",name:"to",type:"address"},{internalType:"uint256",name:"tokenId",type:"uint256"}],name:"transferFrom",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"address",name:"newOwner",type:"address"}],name:"transferOwnership",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[],name:"unpause",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"uint256",name:"tokenId",type:"uint256"},{internalType:"address",name:"_royaltyReceiver",type:"address"},{components:[{internalType:"uint128",name:"price",type:"uint128"},{internalType:"uint32",name:"duration",type:"uint32"},{internalType:"uint16",name:"royaltyBps",type:"uint16"},{internalType:"address",name:"paymentToken",type:"address"}],internalType:"struct IpNFT.LicenseTerms",name:"newTerms",type:"tuple"}],name:"updateTerms",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"bytes32",name:"",type:"bytes32"}],name:"usedNonces",outputs:[{internalType:"bool",name:"",type:"bool"}],stateMutability:"view",type:"function"}]; /** * Mints a Data NFT with a signature. * @param to The address to mint the NFT to. @@ -213,14 +227,14 @@ let k=null,A=null;const C=()=>(A||(A=i({chain:I,transport:a()})),A);var E="Conne * @param deadline The deadline for the minting operation. * @param signature The signature for the minting operation. * @returns A promise that resolves when the minting is complete. - */function U(e,t,n,i,a,r,s,o){return c(this,void 0,void 0,(function*(){return yield this.callContractMethod(S,P,"mintWithSignature",[e,t,n,i,a,r,s,o],{waitForReceipt:!0})}))} + */function j(e,t,n,i,r,a,s,o){return c(this,void 0,void 0,(function*(){return yield this.callContractMethod(P,N,"mintWithSignature",[e,t,n,i,r,a,s,o],{waitForReceipt:!0})}))} /** * Registers a Data NFT with the Origin service in order to obtain a signature for minting. * @param source The source of the Data NFT (e.g., "spotify", "twitter", "tiktok", or "file"). * @param deadline The deadline for the registration operation. * @param fileKey Optional file key for file uploads. * @return A promise that resolves with the registration data. - */function N(e,t,n,i,a,r){return c(this,void 0,void 0,(function*(){const s={source:e,deadline:Number(t),licenseTerms:{price:n.price.toString(),duration:n.duration,royaltyBps:n.royaltyBps,paymentToken:n.paymentToken},metadata:i,parentId:Number(r)||0};void 0!==a&&(s.fileKey=a);const o=yield fetch(`${x}/auth/origin/register`,{method:"POST",headers:{Authorization:`Bearer ${this.getJwt()}`,"Content-Type":"application/json"},body:JSON.stringify(s)});if(!o.ok)throw new Error(`Failed to get signature: ${o.statusText}`);const d=yield o.json();if(d.isError)throw new Error(`Failed to get signature: ${d.message}`);return d.data}))}function B(e,t,n){return this.callContractMethod(S,P,"updateTerms",[e,t,n],{waitForReceipt:!0})}function D(e){return this.callContractMethod(S,P,"finalizeDelete",[e])}function _(e){return this.callContractMethod(S,P,"getTerms",[e])}function R(e){return this.callContractMethod(S,P,"ownerOf",[e])}function W(e){return this.callContractMethod(S,P,"balanceOf",[e])}function q(e){return this.callContractMethod(S,P,"contentHash",[e])}function L(e){return this.callContractMethod(S,P,"tokenURI",[e])}function z(e){return this.callContractMethod(S,P,"dataStatus",[e])}function J(e,t){return c(this,void 0,void 0,(function*(){return this.callContractMethod(S,P,"royaltyInfo",[e,t])}))}function K(e){return this.callContractMethod(S,P,"getApproved",[e])}function H(e,t){return this.callContractMethod(S,P,"isApprovedForAll",[e,t])}function G(e,t,n){return this.callContractMethod(S,P,"transferFrom",[e,t,n])}function V(e,t,n,i){const a=i?[e,t,n,i]:[e,t,n];return this.callContractMethod(S,P,"safeTransferFrom",a)}function Z(e,t){return this.callContractMethod(S,P,"approve",[e,t])}function Y(e,t){return this.callContractMethod(S,P,"setApprovalForAll",[e,t])}var Q,X,ee,te,ne,ie,ae,re,se,oe,de,ue,le,pe,ce,ye=[{inputs:[{internalType:"address",name:"dataNFT_",type:"address"},{internalType:"uint16",name:"protocolFeeBps_",type:"uint16"},{internalType:"address",name:"treasury_",type:"address"}],stateMutability:"nonpayable",type:"constructor"},{inputs:[],name:"EnforcedPause",type:"error"},{inputs:[],name:"ExpectedPause",type:"error"},{inputs:[{internalType:"uint256",name:"expected",type:"uint256"},{internalType:"uint256",name:"actual",type:"uint256"}],name:"InvalidPayment",type:"error"},{inputs:[{internalType:"uint32",name:"periods",type:"uint32"}],name:"InvalidPeriods",type:"error"},{inputs:[{internalType:"uint16",name:"royaltyBps",type:"uint16"}],name:"InvalidRoyalty",type:"error"},{inputs:[{internalType:"address",name:"owner",type:"address"}],name:"OwnableInvalidOwner",type:"error"},{inputs:[{internalType:"address",name:"account",type:"address"}],name:"OwnableUnauthorizedAccount",type:"error"},{inputs:[],name:"TransferFailed",type:"error"},{inputs:[],name:"Unauthorized",type:"error"},{inputs:[],name:"ZeroAddress",type:"error"},{anonymous:!1,inputs:[{indexed:!0,internalType:"uint256",name:"tokenId",type:"uint256"},{indexed:!0,internalType:"address",name:"buyer",type:"address"},{indexed:!1,internalType:"uint32",name:"periods",type:"uint32"},{indexed:!1,internalType:"uint256",name:"newExpiry",type:"uint256"},{indexed:!1,internalType:"uint256",name:"amountPaid",type:"uint256"}],name:"AccessPurchased",type:"event"},{anonymous:!1,inputs:[{indexed:!0,internalType:"uint256",name:"tokenId",type:"uint256"},{indexed:!0,internalType:"address",name:"creator",type:"address"}],name:"DataDeleted",type:"event"},{anonymous:!1,inputs:[{indexed:!0,internalType:"uint256",name:"tokenId",type:"uint256"},{indexed:!0,internalType:"address",name:"creator",type:"address"},{indexed:!1,internalType:"bytes32",name:"contentHash",type:"bytes32"}],name:"DataMinted",type:"event"},{anonymous:!1,inputs:[{indexed:!0,internalType:"address",name:"previousOwner",type:"address"},{indexed:!0,internalType:"address",name:"newOwner",type:"address"}],name:"OwnershipTransferred",type:"event"},{anonymous:!1,inputs:[{indexed:!1,internalType:"address",name:"account",type:"address"}],name:"Paused",type:"event"},{anonymous:!1,inputs:[{indexed:!0,internalType:"uint256",name:"tokenId",type:"uint256"},{indexed:!1,internalType:"uint256",name:"royaltyAmount",type:"uint256"},{indexed:!1,internalType:"address",name:"creator",type:"address"},{indexed:!1,internalType:"uint256",name:"protocolAmount",type:"uint256"}],name:"RoyaltyPaid",type:"event"},{anonymous:!1,inputs:[{indexed:!0,internalType:"uint256",name:"tokenId",type:"uint256"},{indexed:!1,internalType:"uint128",name:"newPrice",type:"uint128"},{indexed:!1,internalType:"uint32",name:"newDuration",type:"uint32"},{indexed:!1,internalType:"uint16",name:"newRoyaltyBps",type:"uint16"},{indexed:!1,internalType:"address",name:"paymentToken",type:"address"}],name:"TermsUpdated",type:"event"},{anonymous:!1,inputs:[{indexed:!1,internalType:"address",name:"account",type:"address"}],name:"Unpaused",type:"event"},{inputs:[{internalType:"address",name:"feeManager",type:"address"}],name:"addFeeManager",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"address",name:"buyer",type:"address"},{internalType:"uint256",name:"tokenId",type:"uint256"},{internalType:"uint32",name:"periods",type:"uint32"}],name:"buyAccess",outputs:[],stateMutability:"payable",type:"function"},{inputs:[],name:"dataNFT",outputs:[{internalType:"contract IpNFT",name:"",type:"address"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"address",name:"",type:"address"}],name:"feeManagers",outputs:[{internalType:"bool",name:"",type:"bool"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"address",name:"user",type:"address"},{internalType:"uint256",name:"tokenId",type:"uint256"}],name:"hasAccess",outputs:[{internalType:"bool",name:"",type:"bool"}],stateMutability:"view",type:"function"},{inputs:[],name:"owner",outputs:[{internalType:"address",name:"",type:"address"}],stateMutability:"view",type:"function"},{inputs:[],name:"pause",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[],name:"paused",outputs:[{internalType:"bool",name:"",type:"bool"}],stateMutability:"view",type:"function"},{inputs:[],name:"protocolFeeBps",outputs:[{internalType:"uint16",name:"",type:"uint16"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"address",name:"feeManager",type:"address"}],name:"removeFeeManager",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[],name:"renounceOwnership",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"uint256",name:"",type:"uint256"},{internalType:"address",name:"",type:"address"}],name:"subscriptionExpiry",outputs:[{internalType:"uint256",name:"",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"address",name:"newOwner",type:"address"}],name:"transferOwnership",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[],name:"treasury",outputs:[{internalType:"address",name:"",type:"address"}],stateMutability:"view",type:"function"},{inputs:[],name:"unpause",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"uint16",name:"newFeeBps",type:"uint16"}],name:"updateProtocolFee",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"address",name:"newTreasury",type:"address"}],name:"updateTreasury",outputs:[],stateMutability:"nonpayable",type:"function"},{stateMutability:"payable",type:"receive"}];function he(e,t,n,i){return this.callContractMethod($,ye,"buyAccess",[e,t,n],{waitForReceipt:!0,value:i})}function me(e,t,n,i){return this.callContractMethod($,ye,"renewAccess",[e,t,n],void 0!==i?{value:i}:void 0)}function fe(e,t){return this.callContractMethod($,ye,"hasAccess",[e,t])}function we(e,t){return this.callContractMethod($,ye,"subscriptionExpiry",[e,t])} + */function D(e,t,n,i,r,a){return c(this,void 0,void 0,(function*(){const s={source:e,deadline:Number(t),licenseTerms:{price:n.price.toString(),duration:n.duration,royaltyBps:n.royaltyBps,paymentToken:n.paymentToken},metadata:i,parentId:Number(a)||0};void 0!==r&&(s.fileKey=r);const o=yield fetch(`${M}/auth/origin/register`,{method:"POST",headers:{Authorization:`Bearer ${this.getJwt()}`,"Content-Type":"application/json"},body:JSON.stringify(s)});if(!o.ok)throw new Error(`Failed to get signature: ${o.statusText}`);const d=yield o.json();if(d.isError)throw new Error(`Failed to get signature: ${d.message}`);return d.data}))}function _(e,t,n){return this.callContractMethod(P,N,"updateTerms",[e,t,n],{waitForReceipt:!0})}function B(e){return this.callContractMethod(P,N,"finalizeDelete",[e])}function q(e){return this.callContractMethod(P,N,"getTerms",[e])}function L(e){return this.callContractMethod(P,N,"ownerOf",[e])}function W(e){return this.callContractMethod(P,N,"balanceOf",[e])}function R(e){return this.callContractMethod(P,N,"contentHash",[e])}function z(e){return this.callContractMethod(P,N,"tokenURI",[e])}function K(e){return this.callContractMethod(P,N,"dataStatus",[e])}function J(e,t){return c(this,void 0,void 0,(function*(){return this.callContractMethod(P,N,"royaltyInfo",[e,t])}))}function H(e){return this.callContractMethod(P,N,"getApproved",[e])}function G(e,t){return this.callContractMethod(P,N,"isApprovedForAll",[e,t])}function Z(e,t,n){return this.callContractMethod(P,N,"transferFrom",[e,t,n])}function V(e,t,n,i){const r=i?[e,t,n,i]:[e,t,n];return this.callContractMethod(P,N,"safeTransferFrom",r)}function Y(e,t){return this.callContractMethod(P,N,"approve",[e,t])}function Q(e,t){return this.callContractMethod(P,N,"setApprovalForAll",[e,t])}var X,ee,te,ne,ie,re,ae,se,oe,de,ue,le,pe,ce,ye,he=[{inputs:[{internalType:"address",name:"dataNFT_",type:"address"},{internalType:"uint16",name:"protocolFeeBps_",type:"uint16"},{internalType:"address",name:"treasury_",type:"address"}],stateMutability:"nonpayable",type:"constructor"},{inputs:[],name:"EnforcedPause",type:"error"},{inputs:[],name:"ExpectedPause",type:"error"},{inputs:[{internalType:"uint256",name:"expected",type:"uint256"},{internalType:"uint256",name:"actual",type:"uint256"}],name:"InvalidPayment",type:"error"},{inputs:[{internalType:"uint32",name:"periods",type:"uint32"}],name:"InvalidPeriods",type:"error"},{inputs:[{internalType:"uint16",name:"royaltyBps",type:"uint16"}],name:"InvalidRoyalty",type:"error"},{inputs:[{internalType:"address",name:"owner",type:"address"}],name:"OwnableInvalidOwner",type:"error"},{inputs:[{internalType:"address",name:"account",type:"address"}],name:"OwnableUnauthorizedAccount",type:"error"},{inputs:[],name:"TransferFailed",type:"error"},{inputs:[],name:"Unauthorized",type:"error"},{inputs:[],name:"ZeroAddress",type:"error"},{anonymous:!1,inputs:[{indexed:!0,internalType:"uint256",name:"tokenId",type:"uint256"},{indexed:!0,internalType:"address",name:"buyer",type:"address"},{indexed:!1,internalType:"uint32",name:"periods",type:"uint32"},{indexed:!1,internalType:"uint256",name:"newExpiry",type:"uint256"},{indexed:!1,internalType:"uint256",name:"amountPaid",type:"uint256"}],name:"AccessPurchased",type:"event"},{anonymous:!1,inputs:[{indexed:!0,internalType:"uint256",name:"tokenId",type:"uint256"},{indexed:!0,internalType:"address",name:"creator",type:"address"}],name:"DataDeleted",type:"event"},{anonymous:!1,inputs:[{indexed:!0,internalType:"uint256",name:"tokenId",type:"uint256"},{indexed:!0,internalType:"address",name:"creator",type:"address"},{indexed:!1,internalType:"bytes32",name:"contentHash",type:"bytes32"}],name:"DataMinted",type:"event"},{anonymous:!1,inputs:[{indexed:!0,internalType:"address",name:"previousOwner",type:"address"},{indexed:!0,internalType:"address",name:"newOwner",type:"address"}],name:"OwnershipTransferred",type:"event"},{anonymous:!1,inputs:[{indexed:!1,internalType:"address",name:"account",type:"address"}],name:"Paused",type:"event"},{anonymous:!1,inputs:[{indexed:!0,internalType:"uint256",name:"tokenId",type:"uint256"},{indexed:!1,internalType:"uint256",name:"royaltyAmount",type:"uint256"},{indexed:!1,internalType:"address",name:"creator",type:"address"},{indexed:!1,internalType:"uint256",name:"protocolAmount",type:"uint256"}],name:"RoyaltyPaid",type:"event"},{anonymous:!1,inputs:[{indexed:!0,internalType:"uint256",name:"tokenId",type:"uint256"},{indexed:!1,internalType:"uint128",name:"newPrice",type:"uint128"},{indexed:!1,internalType:"uint32",name:"newDuration",type:"uint32"},{indexed:!1,internalType:"uint16",name:"newRoyaltyBps",type:"uint16"},{indexed:!1,internalType:"address",name:"paymentToken",type:"address"}],name:"TermsUpdated",type:"event"},{anonymous:!1,inputs:[{indexed:!1,internalType:"address",name:"account",type:"address"}],name:"Unpaused",type:"event"},{inputs:[{internalType:"address",name:"feeManager",type:"address"}],name:"addFeeManager",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"address",name:"buyer",type:"address"},{internalType:"uint256",name:"tokenId",type:"uint256"},{internalType:"uint32",name:"periods",type:"uint32"}],name:"buyAccess",outputs:[],stateMutability:"payable",type:"function"},{inputs:[],name:"dataNFT",outputs:[{internalType:"contract IpNFT",name:"",type:"address"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"address",name:"",type:"address"}],name:"feeManagers",outputs:[{internalType:"bool",name:"",type:"bool"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"address",name:"user",type:"address"},{internalType:"uint256",name:"tokenId",type:"uint256"}],name:"hasAccess",outputs:[{internalType:"bool",name:"",type:"bool"}],stateMutability:"view",type:"function"},{inputs:[],name:"owner",outputs:[{internalType:"address",name:"",type:"address"}],stateMutability:"view",type:"function"},{inputs:[],name:"pause",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[],name:"paused",outputs:[{internalType:"bool",name:"",type:"bool"}],stateMutability:"view",type:"function"},{inputs:[],name:"protocolFeeBps",outputs:[{internalType:"uint16",name:"",type:"uint16"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"address",name:"feeManager",type:"address"}],name:"removeFeeManager",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[],name:"renounceOwnership",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"uint256",name:"",type:"uint256"},{internalType:"address",name:"",type:"address"}],name:"subscriptionExpiry",outputs:[{internalType:"uint256",name:"",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"address",name:"newOwner",type:"address"}],name:"transferOwnership",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[],name:"treasury",outputs:[{internalType:"address",name:"",type:"address"}],stateMutability:"view",type:"function"},{inputs:[],name:"unpause",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"uint16",name:"newFeeBps",type:"uint16"}],name:"updateProtocolFee",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"address",name:"newTreasury",type:"address"}],name:"updateTreasury",outputs:[],stateMutability:"nonpayable",type:"function"},{stateMutability:"payable",type:"receive"}];function me(e,t,n,i){return this.callContractMethod($,he,"buyAccess",[e,t,n],{waitForReceipt:!0,value:i})}function fe(e,t,n,i){return this.callContractMethod($,he,"renewAccess",[e,t,n],void 0!==i?{value:i}:void 0)}function we(e,t){return this.callContractMethod($,he,"hasAccess",[e,t])}function ve(e,t){return this.callContractMethod($,he,"subscriptionExpiry",[e,t])} /** * Approves a spender to spend a specified amount of tokens on behalf of the owner. * If the current allowance is less than the specified amount, it will perform the approval. @@ -230,18 +244,18 @@ let k=null,A=null;const C=()=>(A||(A=i({chain:I,transport:a()})),A);var E="Conne * The Origin class * Handles the upload of files to Origin, as well as querying the user's stats */ -class ve{constructor(t,n){Q.add(this),X.set(this,(e=>c(this,void 0,void 0,(function*(){try{const t=yield fetch(`${x}/auth/origin/upload-url`,{method:"POST",body:JSON.stringify({name:e.name,type:e.type}),headers:{Authorization:`Bearer ${this.jwt}`,"Content-Type":"application/json"}});if(!t.ok)throw new Error(`HTTP ${t.status}: ${t.statusText}`);const n=yield t.json();if(n.isError)throw new Error(n.message||"Failed to generate upload URL");return n.data}catch(e){throw console.error("Failed to generate upload URL:",e),e}})))),ee.set(this,((e,t)=>c(this,void 0,void 0,(function*(){try{const n=yield fetch(`${x}/auth/origin/update-status`,{method:"PATCH",body:JSON.stringify({status:t,fileKey:e}),headers:{Authorization:`Bearer ${this.jwt}`,"Content-Type":"application/json"}});if(!n.ok){const e=yield n.text().catch((()=>"Unknown error"));throw new Error(`HTTP ${n.status}: ${e}`)}return!0}catch(e){throw console.error("Failed to update origin status:",e),e}})))),this.uploadFile=(t,n)=>c(this,void 0,void 0,(function*(){let i;try{i=yield y(this,X,"f").call(this,t)}catch(e){throw console.error("Failed to generate upload URL:",e),new Error(`Failed to generate upload URL: ${e instanceof Error?e.message:String(e)}`)}if(!i)throw new Error("Failed to generate upload URL: No upload info returned");try{yield((t,n,i)=>new Promise(((a,r)=>{e.put(n,t,Object.assign({headers:{"Content-Type":t.type}},"undefined"!=typeof window&&"function"==typeof i?{onUploadProgress:e=>{if(e.total){const t=e.loaded/e.total*100;i(t)}}}:{})).then((e=>{a(e.data)})).catch((e=>{var t;const n=(null===(t=null==e?void 0:e.response)||void 0===t?void 0:t.data)||(null==e?void 0:e.message)||"Upload failed";r(n)}))})))(t,i.url,(null==n?void 0:n.progressCallback)||(()=>{}))}catch(e){try{yield y(this,ee,"f").call(this,i.key,"failed")}catch(e){console.error("Failed to update status to failed:",e)}const t=e instanceof Error?e.message:String(e);throw new Error(`Failed to upload file: ${t}`)}try{yield y(this,ee,"f").call(this,i.key,"success")}catch(e){console.error("Failed to update status to success:",e)}return i})),this.mintFile=(e,t,n,i,a)=>c(this,void 0,void 0,(function*(){if(!this.viemClient)throw new Error("WalletClient not connected.");const r=yield this.uploadFile(e,a);if(!r||!r.key)throw new Error("Failed to upload file or get upload info.");const s=BigInt(Math.floor(Date.now()/1e3)+600),o=yield this.registerIpNFT("file",s,n,t,r.key,i),{tokenId:d,signerAddress:u,creatorContentHash:l,signature:p,uri:c}=o;// 10 minutes from now -if(!(d&&u&&l&&void 0!==p&&c))throw new Error("Failed to register IpNFT: Missing required fields in registration response.");const[y]=yield this.viemClient.request({method:"eth_requestAccounts",params:[]}),h=yield this.mintWithSignature(y,d,i||BigInt(0),l,c,n,s,p);if("0x1"!==h.status)throw new Error(`Minting failed with status: ${h.status}`);return d.toString()})),this.mintSocial=(e,t,n)=>c(this,void 0,void 0,(function*(){if(!this.viemClient)throw new Error("WalletClient not connected.");const i=BigInt(Math.floor(Date.now()/1e3)+600),a=yield this.registerIpNFT(e,i,n,t),{tokenId:r,signerAddress:s,creatorContentHash:o,signature:d,uri:u}=a;// 10 minutes from now -if(!(r&&s&&o&&void 0!==d&&u))throw new Error("Failed to register Social IpNFT: Missing required fields in registration response.");const[l]=yield this.viemClient.request({method:"eth_requestAccounts",params:[]}),p=yield this.mintWithSignature(l,r,BigInt(0),// parentId is not applicable for social IpNFTs -o,u,n,i,d);if("0x1"!==p.status)throw new Error(`Minting Social IpNFT failed with status: ${p.status}`);return r.toString()})),this.getOriginUploads=()=>c(this,void 0,void 0,(function*(){const e=yield fetch(`${x}/auth/origin/files`,{method:"GET",headers:{Authorization:`Bearer ${this.jwt}`}});if(!e.ok)return console.error("Failed to get origin uploads"),null;return(yield e.json()).data})),this.jwt=t,this.viemClient=n, +class Te{constructor(t,n){X.add(this),ee.set(this,(e=>c(this,void 0,void 0,(function*(){try{const t=yield fetch(`${M}/auth/origin/upload-url`,{method:"POST",body:JSON.stringify({name:e.name,type:e.type}),headers:{Authorization:`Bearer ${this.jwt}`,"Content-Type":"application/json"}});if(!t.ok)throw new Error(`HTTP ${t.status}: ${t.statusText}`);const n=yield t.json();if(n.isError)throw new Error(n.message||"Failed to generate upload URL");return n.data}catch(e){throw console.error("Failed to generate upload URL:",e),e}})))),te.set(this,((e,t)=>c(this,void 0,void 0,(function*(){try{const n=yield fetch(`${M}/auth/origin/update-status`,{method:"PATCH",body:JSON.stringify({status:t,fileKey:e}),headers:{Authorization:`Bearer ${this.jwt}`,"Content-Type":"application/json"}});if(!n.ok){const e=yield n.text().catch((()=>"Unknown error"));throw new Error(`HTTP ${n.status}: ${e}`)}return!0}catch(e){throw console.error("Failed to update origin status:",e),e}})))),this.uploadFile=(t,n)=>c(this,void 0,void 0,(function*(){let i;try{i=yield y(this,ee,"f").call(this,t)}catch(e){throw console.error("Failed to generate upload URL:",e),new Error(`Failed to generate upload URL: ${e instanceof Error?e.message:String(e)}`)}if(!i)throw new Error("Failed to generate upload URL: No upload info returned");try{yield((t,n,i)=>new Promise(((r,a)=>{e.put(n,t,Object.assign({headers:{"Content-Type":t.type}},"undefined"!=typeof window&&"function"==typeof i?{onUploadProgress:e=>{if(e.total){const t=e.loaded/e.total*100;i(t)}}}:{})).then((e=>{r(e.data)})).catch((e=>{var t;const n=(null===(t=null==e?void 0:e.response)||void 0===t?void 0:t.data)||(null==e?void 0:e.message)||"Upload failed";a(n)}))})))(t,i.url,(null==n?void 0:n.progressCallback)||(()=>{}))}catch(e){try{yield y(this,te,"f").call(this,i.key,"failed")}catch(e){console.error("Failed to update status to failed:",e)}const t=e instanceof Error?e.message:String(e);throw new Error(`Failed to upload file: ${t}`)}try{yield y(this,te,"f").call(this,i.key,"success")}catch(e){console.error("Failed to update status to success:",e)}return i})),this.mintFile=(e,t,n,i,r)=>c(this,void 0,void 0,(function*(){if(!this.viemClient)throw new Error("WalletClient not connected.");const a=yield this.uploadFile(e,r);if(!a||!a.key)throw new Error("Failed to upload file or get upload info.");const s=BigInt(Math.floor(Date.now()/1e3)+600),o=yield this.registerIpNFT("file",s,n,t,a.key,i),{tokenId:d,signerAddress:u,creatorContentHash:l,signature:p,uri:c}=o;// 10 minutes from now +if(!(d&&u&&l&&void 0!==p&&c))throw new Error("Failed to register IpNFT: Missing required fields in registration response.");const[y]=yield this.viemClient.request({method:"eth_requestAccounts",params:[]}),h=yield this.mintWithSignature(y,d,i||BigInt(0),l,c,n,s,p);if("0x1"!==h.status)throw new Error(`Minting failed with status: ${h.status}`);return d.toString()})),this.mintSocial=(e,t,n)=>c(this,void 0,void 0,(function*(){if(!this.viemClient)throw new Error("WalletClient not connected.");const i=BigInt(Math.floor(Date.now()/1e3)+600),r=yield this.registerIpNFT(e,i,n,t),{tokenId:a,signerAddress:s,creatorContentHash:o,signature:d,uri:u}=r;// 10 minutes from now +if(!(a&&s&&o&&void 0!==d&&u))throw new Error("Failed to register Social IpNFT: Missing required fields in registration response.");const[l]=yield this.viemClient.request({method:"eth_requestAccounts",params:[]}),p=yield this.mintWithSignature(l,a,BigInt(0),// parentId is not applicable for social IpNFTs +o,u,n,i,d);if("0x1"!==p.status)throw new Error(`Minting Social IpNFT failed with status: ${p.status}`);return a.toString()})),this.getOriginUploads=()=>c(this,void 0,void 0,(function*(){const e=yield fetch(`${M}/auth/origin/files`,{method:"GET",headers:{Authorization:`Bearer ${this.jwt}`}});if(!e.ok)return console.error("Failed to get origin uploads"),null;return(yield e.json()).data})),this.jwt=t,this.viemClient=n, // DataNFT methods -this.mintWithSignature=U.bind(this),this.registerIpNFT=N.bind(this),this.updateTerms=B.bind(this),this.requestDelete=D.bind(this),this.getTerms=_.bind(this),this.ownerOf=R.bind(this),this.balanceOf=W.bind(this),this.contentHash=q.bind(this),this.tokenURI=L.bind(this),this.dataStatus=z.bind(this),this.royaltyInfo=J.bind(this),this.getApproved=K.bind(this),this.isApprovedForAll=H.bind(this),this.transferFrom=G.bind(this),this.safeTransferFrom=V.bind(this),this.approve=Z.bind(this),this.setApprovalForAll=Y.bind(this), +this.mintWithSignature=j.bind(this),this.registerIpNFT=D.bind(this),this.updateTerms=_.bind(this),this.requestDelete=B.bind(this),this.getTerms=q.bind(this),this.ownerOf=L.bind(this),this.balanceOf=W.bind(this),this.contentHash=R.bind(this),this.tokenURI=z.bind(this),this.dataStatus=K.bind(this),this.royaltyInfo=J.bind(this),this.getApproved=H.bind(this),this.isApprovedForAll=G.bind(this),this.transferFrom=Z.bind(this),this.safeTransferFrom=V.bind(this),this.approve=Y.bind(this),this.setApprovalForAll=Q.bind(this), // Marketplace methods -this.buyAccess=he.bind(this),this.renewAccess=me.bind(this),this.hasAccess=fe.bind(this),this.subscriptionExpiry=we.bind(this)}getJwt(){return this.jwt}setViemClient(e){this.viemClient=e} +this.buyAccess=me.bind(this),this.renewAccess=fe.bind(this),this.hasAccess=we.bind(this),this.subscriptionExpiry=ve.bind(this)}getJwt(){return this.jwt}setViemClient(e){this.viemClient=e} /** * Get the user's Origin stats (multiplier, consent, usage, etc.). * @returns {Promise} A promise that resolves with the user's Origin stats. - */getOriginUsage(){return c(this,void 0,void 0,(function*(){const e=yield fetch(`${x}/auth/origin/usage`,{method:"GET",headers:{Authorization:`Bearer ${this.jwt}`, + */getOriginUsage(){return c(this,void 0,void 0,(function*(){const e=yield fetch(`${M}/auth/origin/usage`,{method:"GET",headers:{Authorization:`Bearer ${this.jwt}`, // "x-client-id": this.clientId, "Content-Type":"application/json"}}).then((e=>e.json()));if(!e.isError&&e.data.user)return e;throw new m(e.message||"Failed to fetch Origin usage")}))} /** @@ -249,7 +263,7 @@ this.buyAccess=he.bind(this),this.renewAccess=me.bind(this),this.hasAccess=fe.bi * @param {boolean} consent The user's consent. * @returns {Promise} * @throws {Error|APIError} - Throws an error if the user is not authenticated. Also throws an error if the consent is not provided. - */setOriginConsent(e){return c(this,void 0,void 0,(function*(){if(void 0===e)throw new m("Consent is required");const t=yield fetch(`${x}/auth/origin/status`,{method:"PATCH",headers:{Authorization:`Bearer ${this.jwt}`, + */setOriginConsent(e){return c(this,void 0,void 0,(function*(){if(void 0===e)throw new m("Consent is required");const t=yield fetch(`${M}/auth/origin/status`,{method:"PATCH",headers:{Authorization:`Bearer ${this.jwt}`, // "x-client-id": this.clientId, "Content-Type":"application/json"},body:JSON.stringify({active:e})}).then((e=>e.json()));if(t.isError)throw new m(t.message||"Failed to set Origin consent")}))} /** @@ -257,7 +271,7 @@ this.buyAccess=he.bind(this),this.renewAccess=me.bind(this),this.hasAccess=fe.bi * @param {number} multiplier The user's Origin multiplier. * @returns {Promise} * @throws {Error|APIError} - Throws an error if the user is not authenticated. Also throws an error if the multiplier is not provided. - */setOriginMultiplier(e){return c(this,void 0,void 0,(function*(){if(void 0===e)throw new m("Multiplier is required");const t=yield fetch(`${x}/auth/origin/multiplier`,{method:"PATCH",headers:{Authorization:`Bearer ${this.jwt}`, + */setOriginMultiplier(e){return c(this,void 0,void 0,(function*(){if(void 0===e)throw new m("Multiplier is required");const t=yield fetch(`${M}/auth/origin/multiplier`,{method:"PATCH",headers:{Authorization:`Bearer ${this.jwt}`, // "x-client-id": this.clientId, "Content-Type":"application/json"},body:JSON.stringify({multiplier:e})}).then((e=>e.json()));if(t.isError)throw new m(t.message||"Failed to set Origin multiplier")}))} /** @@ -269,13 +283,13 @@ this.buyAccess=he.bind(this),this.renewAccess=me.bind(this),this.hasAccess=fe.bi * @param {CallOptions} [options] The call options. * @returns {Promise} A promise that resolves with the result of the contract call or transaction hash. * @throws {Error} - Throws an error if the wallet client is not connected and the method is not a view function. - */callContractMethod(e,t,n,i){return c(this,arguments,void 0,(function*(e,t,n,i,a={}){const r=s({abi:t,name:n}),d=r&&"stateMutability"in r&&("view"===r.stateMutability||"pure"===r.stateMutability);if(!d&&!this.viemClient)throw new Error("WalletClient not connected.");if(d){const a=C();return(yield a.readContract({address:e,abi:t,functionName:n,args:i}))||null}{const[r]=yield this.viemClient.request({method:"eth_requestAccounts",params:[]}),s=o({abi:t,functionName:n,args:i});yield y(this,Q,"m",ne).call(this,I);try{const t=yield this.viemClient.sendTransaction({to:e,data:s,account:r,value:a.value,gas:a.gas});if("string"!=typeof t)throw new Error("Transaction failed to send.");if(!a.waitForReceipt)return t;return yield y(this,Q,"m",te).call(this,t)}catch(e){throw console.error("Transaction failed:",e),new Error("Transaction failed: "+e)}}}))} + */callContractMethod(e,t,n,i){return c(this,arguments,void 0,(function*(e,t,n,i,r={}){const a=s({abi:t,name:n}),d=a&&"stateMutability"in a&&("view"===a.stateMutability||"pure"===a.stateMutability);if(!d&&!this.viemClient)throw new Error("WalletClient not connected.");if(d){const r=E();return(yield r.readContract({address:e,abi:t,functionName:n,args:i}))||null}{const[a]=yield this.viemClient.request({method:"eth_requestAccounts",params:[]}),s=o({abi:t,functionName:n,args:i});yield y(this,X,"m",ie).call(this,A);try{const t=yield this.viemClient.sendTransaction({to:e,data:s,account:a,value:r.value,gas:r.gas});if("string"!=typeof t)throw new Error("Transaction failed to send.");if(!r.waitForReceipt)return t;return yield y(this,X,"m",ne).call(this,t)}catch(e){throw console.error("Transaction failed:",e),new Error("Transaction failed: "+e)}}}))} /** * Buy access to an asset by first checking its price via getTerms, then calling buyAccess. * @param {bigint} tokenId The token ID of the asset. * @param {number} periods The number of periods to buy access for. * @returns {Promise} The result of the buyAccess call. - */buyAccessSmart(e,t){return c(this,void 0,void 0,(function*(){if(!this.viemClient)throw new Error("WalletClient not connected.");const n=yield this.getTerms(e);if(!n)throw new Error("Failed to fetch terms for asset");const{price:i,paymentToken:a}=n;if(void 0===i||void 0===a)throw new Error("Terms missing price or paymentToken");const[s]=yield this.viemClient.request({method:"eth_requestAccounts",params:[]}),o=i*BigInt(t);return a===d?this.buyAccess(s,e,t,o):(yield function(e){return c(this,arguments,void 0,(function*({walletClient:e,publicClient:t,tokenAddress:n,owner:i,spender:a,amount:s}){(yield t.readContract({address:n,abi:r,functionName:"allowance",args:[i,a]}))setTimeout(e,1e3)))}}))},ne=function(e){return c(this,void 0,void 0,(function*(){ + */buyAccessSmart(e,t){return c(this,void 0,void 0,(function*(){if(!this.viemClient)throw new Error("WalletClient not connected.");const n=yield this.getTerms(e);if(!n)throw new Error("Failed to fetch terms for asset");const{price:i,paymentToken:r}=n;if(void 0===i||void 0===r)throw new Error("Terms missing price or paymentToken");const[s]=yield this.viemClient.request({method:"eth_requestAccounts",params:[]}),o=i*BigInt(t);return r===d?this.buyAccess(s,e,t,o):(yield function(e){return c(this,arguments,void 0,(function*({walletClient:e,publicClient:t,tokenAddress:n,owner:i,spender:r,amount:s}){(yield t.readContract({address:n,abi:a,functionName:"allowance",args:[i,r]}))setTimeout(e,1e3)))}}))},ie=function(e){return c(this,void 0,void 0,(function*(){ // return; if(!this.viemClient)throw new Error("WalletClient not connected.");let t=yield this.viemClient.request({method:"eth_chainId",params:[]});if("string"==typeof t&&(t=parseInt(t,16)),t!==e.id)try{yield this.viemClient.request({method:"wallet_switchEthereumChain",params:[{chainId:"0x"+BigInt(e.id).toString(16)}]})}catch(t){ // Unrecognized chain @@ -285,7 +299,7 @@ if(4902!==t.code)throw t;yield this.viemClient.request({method:"wallet_addEthere * @class * @classdesc The Auth class is used to authenticate the user. */ -class Te{ +class ge{ /** * Constructor for the Auth class. * @param {object} options The options object. @@ -295,11 +309,11 @@ class Te{ * @param {object} [options.ackeeInstance] The Ackee instance. * @throws {APIError} - Throws an error if the clientId is not provided. */ -constructor({clientId:e,redirectUri:t,allowAnalytics:n=!0,ackeeInstance:i}){if(ie.add(this),ae.set(this,void 0),re.set(this,void 0),!e)throw new Error("clientId is required");this.viem=null, +constructor({clientId:e,redirectUri:t,allowAnalytics:n=!0,ackeeInstance:i}){if(re.add(this),ae.set(this,void 0),se.set(this,void 0),!e)throw new Error("clientId is required");this.viem=null, // if (typeof window !== "undefined") { // if (window.ethereum) this.viem = getClient(window.ethereum); // } -this.redirectUri=(e=>{const t=["twitter","discord","spotify"];return"object"==typeof e?t.reduce(((t,n)=>(t[n]=e[n]||("undefined"!=typeof window?window.location.href:""),t)),{}):"string"==typeof e?t.reduce(((t,n)=>(t[n]=e,t)),{}):e?{}:t.reduce(((e,t)=>(e[t]="undefined"!=typeof window?window.location.href:"",e)),{})})(t),i&&h(this,re,i,"f"),n&&y(this,re,"f"),this.clientId=e,this.isAuthenticated=!1,this.jwt=null,this.origin=null,this.walletAddress=null,this.userId=null,h(this,ae,{},"f"),j((e=>{y(this,ie,"m",se).call(this,"providers",e)})),y(this,ie,"m",oe).call(this)} +this.redirectUri=(e=>{const t=["twitter","discord","spotify"];return"object"==typeof e?t.reduce(((t,n)=>(t[n]=e[n]||("undefined"!=typeof window?window.location.href:""),t)),{}):"string"==typeof e?t.reduce(((t,n)=>(t[n]=e,t)),{}):e?{}:t.reduce(((e,t)=>(e[t]="undefined"!=typeof window?window.location.href:"",e)),{})})(t),i&&h(this,se,i,"f"),n&&y(this,se,"f"),this.clientId=e,this.isAuthenticated=!1,this.jwt=null,this.origin=null,this.walletAddress=null,this.userId=null,h(this,ae,{},"f"),O((e=>{y(this,re,"m",oe).call(this,"providers",e)})),y(this,re,"m",de).call(this)} /** * Subscribe to an event. Possible events are "state", "provider", "providers", and "viem". * @param {("state"|"provider"|"providers"|"viem")} event The event. @@ -309,47 +323,47 @@ this.redirectUri=(e=>{const t=["twitter","discord","spotify"];return"object"==ty * auth.on("state", (state) => { * console.log(state); * }); - */on(e,t){y(this,ae,"f")[e]||(y(this,ae,"f")[e]=[]),y(this,ae,"f")[e].push(t),"providers"===e&&t(O())} + */on(e,t){y(this,ae,"f")[e]||(y(this,ae,"f")[e]=[]),y(this,ae,"f")[e].push(t),"providers"===e&&t(F())} /** * Set the loading state. * @param {boolean} loading The loading state. * @returns {void} - */setLoading(e){y(this,ie,"m",se).call(this,"state",e?"loading":this.isAuthenticated?"authenticated":"unauthenticated")} + */setLoading(e){y(this,re,"m",oe).call(this,"state",e?"loading":this.isAuthenticated?"authenticated":"unauthenticated")} /** * Set the provider. This is useful for setting the provider when the user selects a provider from the UI or when dApp wishes to use a specific provider. * @param {object} options The options object. Includes the provider and the provider info. * @returns {void} * @throws {APIError} - Throws an error if the provider is not provided. - */setProvider({provider:e,info:i,address:a}){if(!e)throw new m("provider is required");this.viem=((e,i="window.ethereum",a)=>{var r;if(!e&&!k)return console.warn("Provider is required to create a client."),null;if(!k||k.transport.name!==i&&e||a!==(null===(r=k.account)||void 0===r?void 0:r.address)&&e){const r={chain:I,transport:t(e,{name:i})};a&&(r.account=l(a)),k=n(r)}return k})(e,i.name,a),this.origin&&this.origin.setViemClient(this.viem), + */setProvider({provider:e,info:i,address:r}){if(!e)throw new m("provider is required");this.viem=((e,i="window.ethereum",r)=>{var a;if(!e&&!k)return console.warn("Provider is required to create a client."),null;if(!k||k.transport.name!==i&&e||r!==(null===(a=k.account)||void 0===a?void 0:a.address)&&e){const a={chain:A,transport:t(e,{name:i})};r&&(a.account=l(r)),k=n(a)}return k})(e,i.name,r),this.origin&&this.origin.setViemClient(this.viem), // TODO: only use one of these -y(this,ie,"m",se).call(this,"viem",this.viem),y(this,ie,"m",se).call(this,"provider",{provider:e,info:i}),localStorage.setItem("camp-sdk:provider",JSON.stringify(i))} +y(this,re,"m",oe).call(this,"viem",this.viem),y(this,re,"m",oe).call(this,"provider",{provider:e,info:i}),localStorage.setItem("camp-sdk:provider",JSON.stringify(i))} /** * Set the wallet address. This is useful for edge cases where the provider can't return the wallet address. Don't use this unless you know what you're doing. * @param {string} walletAddress The wallet address. * @returns {void} - */setWalletAddress(e){this.walletAddress=e}recoverProvider(){return c(this,void 0,void 0,(function*(){var e,t,n,i,a,r,s,o,d,u,l,p,c,y,h;if(!this.walletAddress)return void console.warn("No wallet address found in local storage. Please connect your wallet again.");const m=JSON.parse(localStorage.getItem("camp-sdk:provider")||"{}");let f;const w=null!==(e=O())&&void 0!==e?e:[]; + */setWalletAddress(e){this.walletAddress=e}recoverProvider(){return c(this,void 0,void 0,(function*(){var e,t,n,i,r,a,s,o,d,u,l,p,c,y,h;if(!this.walletAddress)return void console.warn("No wallet address found in local storage. Please connect your wallet again.");const m=JSON.parse(localStorage.getItem("camp-sdk:provider")||"{}");let f;const w=null!==(e=F())&&void 0!==e?e:[]; // first pass: try to find provider by UUID/name and check if it has the right address // without prompting (using eth_accounts) for(const e of w)try{if(m.uuid&&(null===(t=e.info)||void 0===t?void 0:t.uuid)===m.uuid||m.name&&(null===(n=e.info)||void 0===n?void 0:n.name)===m.name){ // silently check if the wallet address matches first -const t=yield e.provider.request({method:"eth_accounts"});if(t.length>0&&(null===(i=t[0])||void 0===i?void 0:i.toLowerCase())===(null===(a=this.walletAddress)||void 0===a?void 0:a.toLowerCase())){f=e;break}}}catch(e){console.warn("Failed to fetch accounts from provider:",e)} -// second pass: If no provider found by UUID/name match, try to find by address only +const t=yield e.provider.request({method:"eth_accounts"});if(t.length>0&&(null===(i=t[0])||void 0===i?void 0:i.toLowerCase())===(null===(r=this.walletAddress)||void 0===r?void 0:r.toLowerCase())){f=e;break}}}catch(e){console.warn("Failed to fetch accounts from provider:",e)} +// second pass: if no provider found by UUID/name match, try to find by address only // but still avoid prompting if(!f)for(const e of w)try{ // skip providers we already checked in the first pass -if(m.uuid&&(null===(r=e.info)||void 0===r?void 0:r.uuid)===m.uuid||m.name&&(null===(s=e.info)||void 0===s?void 0:s.name)===m.name)continue;const t=yield e.provider.request({method:"eth_accounts"});if(t.length>0&&(null===(o=t[0])||void 0===o?void 0:o.toLowerCase())===(null===(d=this.walletAddress)||void 0===d?void 0:d.toLowerCase())){f=e;break}}catch(e){console.warn("Failed to fetch accounts from provider:",e)} +if(m.uuid&&(null===(a=e.info)||void 0===a?void 0:a.uuid)===m.uuid||m.name&&(null===(s=e.info)||void 0===s?void 0:s.name)===m.name)continue;const t=yield e.provider.request({method:"eth_accounts"});if(t.length>0&&(null===(o=t[0])||void 0===o?void 0:o.toLowerCase())===(null===(d=this.walletAddress)||void 0===d?void 0:d.toLowerCase())){f=e;break}}catch(e){console.warn("Failed to fetch accounts from provider:",e)} // third pass: if still no provider found and we have UUID/name info, // try prompting the user (only for the stored provider) if(!f&&(m.uuid||m.name))for(const e of w)try{if(m.uuid&&(null===(u=e.info)||void 0===u?void 0:u.uuid)===m.uuid||m.name&&(null===(l=e.info)||void 0===l?void 0:l.name)===m.name){console.log("Attempting to reconnect to stored provider:",(null===(p=e.info)||void 0===p?void 0:p.name)||(null===(c=e.info)||void 0===c?void 0:c.uuid));const t=yield e.provider.request({method:"eth_requestAccounts"});if(t.length>0&&(null===(y=t[0])||void 0===y?void 0:y.toLowerCase())===(null===(h=this.walletAddress)||void 0===h?void 0:h.toLowerCase())){f=e;break}}}catch(e){console.warn("Failed to reconnect to stored provider:",e)}f?this.setProvider({provider:f.provider,info:f.info||{name:"Unknown"},address:this.walletAddress}):console.warn("No matching provider found for the stored wallet address. Please connect your wallet again.")}))} /** * Disconnect the user. * @returns {Promise} - */disconnect(){return c(this,void 0,void 0,(function*(){this.isAuthenticated&&(y(this,ie,"m",se).call(this,"state","unauthenticated"),this.isAuthenticated=!1,this.walletAddress=null,this.userId=null,this.jwt=null,this.origin=null,localStorage.removeItem("camp-sdk:wallet-address"),localStorage.removeItem("camp-sdk:user-id"),localStorage.removeItem("camp-sdk:jwt"))}))} + */disconnect(){return c(this,void 0,void 0,(function*(){this.isAuthenticated&&(y(this,re,"m",oe).call(this,"state","unauthenticated"),this.isAuthenticated=!1,this.walletAddress=null,this.userId=null,this.jwt=null,this.origin=null,localStorage.removeItem("camp-sdk:wallet-address"),localStorage.removeItem("camp-sdk:user-id"),localStorage.removeItem("camp-sdk:jwt"))}))} /** * Connect the user's wallet and sign the message. * @returns {Promise<{ success: boolean; message: string; walletAddress: string }>} A promise that resolves with the authentication result. * @throws {APIError} - Throws an error if the user cannot be authenticated. - */connect(){return c(this,void 0,void 0,(function*(){y(this,ie,"m",se).call(this,"state","loading");try{this.walletAddress||(yield y(this,ie,"m",de).call(this)),this.walletAddress=u(this.walletAddress);const e=yield y(this,ie,"m",ue).call(this),t=y(this,ie,"m",pe).call(this,e),n=yield this.viem.signMessage({account:this.walletAddress,message:t}),i=yield y(this,ie,"m",le).call(this,t,n);if(i.success)return this.isAuthenticated=!0,this.userId=i.userId,this.jwt=i.token,this.origin=new ve(this.jwt,this.viem),localStorage.setItem("camp-sdk:jwt",this.jwt),localStorage.setItem("camp-sdk:wallet-address",this.walletAddress),localStorage.setItem("camp-sdk:user-id",this.userId),y(this,ie,"m",se).call(this,"state","authenticated"),yield y(this,ie,"m",ce).call(this,M.USER_CONNECTED,"User Connected"),{success:!0,message:"Successfully authenticated",walletAddress:this.walletAddress};throw this.isAuthenticated=!1,y(this,ie,"m",se).call(this,"state","unauthenticated"),new m("Failed to authenticate")}catch(e){throw this.isAuthenticated=!1,y(this,ie,"m",se).call(this,"state","unauthenticated"),new m(e)}}))} + */connect(){return c(this,void 0,void 0,(function*(){y(this,re,"m",oe).call(this,"state","loading");try{this.walletAddress||(yield y(this,re,"m",ue).call(this)),this.walletAddress=u(this.walletAddress);const e=yield y(this,re,"m",le).call(this),t=y(this,re,"m",ce).call(this,e),n=yield this.viem.signMessage({account:this.walletAddress,message:t}),i=yield y(this,re,"m",pe).call(this,t,n);if(i.success)return this.isAuthenticated=!0,this.userId=i.userId,this.jwt=i.token,this.origin=new Te(this.jwt,this.viem),localStorage.setItem("camp-sdk:jwt",this.jwt),localStorage.setItem("camp-sdk:wallet-address",this.walletAddress),localStorage.setItem("camp-sdk:user-id",this.userId),y(this,re,"m",oe).call(this,"state","authenticated"),yield y(this,re,"m",ye).call(this,S.USER_CONNECTED,"User Connected"),{success:!0,message:"Successfully authenticated",walletAddress:this.walletAddress};throw this.isAuthenticated=!1,y(this,re,"m",oe).call(this,"state","unauthenticated"),new m("Failed to authenticate")}catch(e){throw this.isAuthenticated=!1,y(this,re,"m",oe).call(this,"state","unauthenticated"),new m(e)}}))} /** * Get the user's linked social accounts. * @returns {Promise>} A promise that resolves with the user's linked social accounts. @@ -358,7 +372,7 @@ if(!f&&(m.uuid||m.name))for(const e of w)try{if(m.uuid&&(null===(u=e.info)||void * const auth = new Auth({ clientId: "your-client-id" }); * const socials = await auth.getLinkedSocials(); * console.log(socials); - */getLinkedSocials(){return c(this,void 0,void 0,(function*(){if(!this.isAuthenticated)throw new Error("User needs to be authenticated");const e=yield fetch(`${x}/auth/client-user/connections-sdk`,{method:"GET",headers:{Authorization:`Bearer ${this.jwt}`,"x-client-id":this.clientId,"Content-Type":"application/json"}}).then((e=>e.json()));if(e.isError)throw new m(e.message||"Failed to fetch connections");{const t={};return Object.keys(e.data.data).forEach((n=>{t[n.split("User")[0]]=e.data.data[n]})),t}}))} + */getLinkedSocials(){return c(this,void 0,void 0,(function*(){if(!this.isAuthenticated)throw new Error("User needs to be authenticated");const e=yield fetch(`${M}/auth/client-user/connections-sdk`,{method:"GET",headers:{Authorization:`Bearer ${this.jwt}`,"x-client-id":this.clientId,"Content-Type":"application/json"}}).then((e=>e.json()));if(e.isError)throw new m(e.message||"Failed to fetch connections");{const t={};return Object.keys(e.data.data).forEach((n=>{t[n.split("User")[0]]=e.data.data[n]})),t}}))} /** * Link the user's Twitter account. * @returns {Promise} @@ -368,7 +382,7 @@ if(!f&&(m.uuid||m.name))for(const e of w)try{if(m.uuid&&(null===(u=e.info)||void // constants.ACKEE_EVENTS.TWITTER_LINKED, // "Twitter Linked" // ); -window.location.href=`${x}/twitter/connect?clientId=${this.clientId}&userId=${this.userId}&redirect_url=${this.redirectUri.twitter}`}))} +window.location.href=`${M}/twitter/connect?clientId=${this.clientId}&userId=${this.userId}&redirect_url=${this.redirectUri.twitter}`}))} /** * Link the user's Discord account. * @returns {Promise} @@ -378,7 +392,7 @@ window.location.href=`${x}/twitter/connect?clientId=${this.clientId}&userId=${th // constants.ACKEE_EVENTS.DISCORD_LINKED, // "Discord Linked" // ); -window.location.href=`${x}/discord/connect?clientId=${this.clientId}&userId=${this.userId}&redirect_url=${this.redirectUri.discord}`}))} +window.location.href=`${M}/discord/connect?clientId=${this.clientId}&userId=${this.userId}&redirect_url=${this.redirectUri.discord}`}))} /** * Link the user's Spotify account. * @returns {Promise} @@ -388,19 +402,19 @@ window.location.href=`${x}/discord/connect?clientId=${this.clientId}&userId=${th // constants.ACKEE_EVENTS.SPOTIFY_LINKED, // "Spotify Linked" // ); -window.location.href=`${x}/spotify/connect?clientId=${this.clientId}&userId=${this.userId}&redirect_url=${this.redirectUri.spotify}`}))} +window.location.href=`${M}/spotify/connect?clientId=${this.clientId}&userId=${this.userId}&redirect_url=${this.redirectUri.spotify}`}))} /** * Link the user's TikTok account. * @param {string} handle The user's TikTok handle. * @returns {Promise} A promise that resolves with the TikTok account data. * @throws {Error|APIError} - Throws an error if the user is not authenticated. - */linkTikTok(e){return c(this,void 0,void 0,(function*(){if(!this.isAuthenticated)throw new Error("User needs to be authenticated");const t=yield fetch(`${x}/tiktok/connect-sdk`,{method:"POST",redirect:"follow",headers:{Authorization:`Bearer ${this.jwt}`,"x-client-id":this.clientId,"Content-Type":"application/json"},body:JSON.stringify({userHandle:e,clientId:this.clientId,userId:this.userId})}).then((e=>e.json()));if(t.isError)throw"Request failed with status code 502"===t.message?new m("TikTok service is currently unavailable, try again later"):new m(t.message||"Failed to link TikTok account");return y(this,ie,"m",ce).call(this,M.TIKTOK_LINKED,"TikTok Linked"),t.data}))} + */linkTikTok(e){return c(this,void 0,void 0,(function*(){if(!this.isAuthenticated)throw new Error("User needs to be authenticated");const t=yield fetch(`${M}/tiktok/connect-sdk`,{method:"POST",redirect:"follow",headers:{Authorization:`Bearer ${this.jwt}`,"x-client-id":this.clientId,"Content-Type":"application/json"},body:JSON.stringify({userHandle:e,clientId:this.clientId,userId:this.userId})}).then((e=>e.json()));if(t.isError)throw"Request failed with status code 502"===t.message?new m("TikTok service is currently unavailable, try again later"):new m(t.message||"Failed to link TikTok account");return y(this,re,"m",ye).call(this,S.TIKTOK_LINKED,"TikTok Linked"),t.data}))} /** * Send an OTP to the user's Telegram account. * @param {string} phoneNumber The user's phone number. * @returns {Promise} A promise that resolves with the OTP data. * @throws {Error|APIError} - Throws an error if the user is not authenticated. - */sendTelegramOTP(e){return c(this,void 0,void 0,(function*(){if(!this.isAuthenticated)throw new Error("User needs to be authenticated");if(!e)throw new m("Phone number is required");yield this.unlinkTelegram();const t=yield fetch(`${x}/telegram/sendOTP-sdk`,{method:"POST",redirect:"follow",headers:{Authorization:`Bearer ${this.jwt}`,"x-client-id":this.clientId,"Content-Type":"application/json"},body:JSON.stringify({phone:e})}).then((e=>e.json()));if(t.isError)throw new m(t.message||"Failed to send Telegram OTP");return t.data}))} + */sendTelegramOTP(e){return c(this,void 0,void 0,(function*(){if(!this.isAuthenticated)throw new Error("User needs to be authenticated");if(!e)throw new m("Phone number is required");yield this.unlinkTelegram();const t=yield fetch(`${M}/telegram/sendOTP-sdk`,{method:"POST",redirect:"follow",headers:{Authorization:`Bearer ${this.jwt}`,"x-client-id":this.clientId,"Content-Type":"application/json"},body:JSON.stringify({phone:e})}).then((e=>e.json()));if(t.isError)throw new m(t.message||"Failed to send Telegram OTP");return t.data}))} /** * Link the user's Telegram account. * @param {string} phoneNumber The user's phone number. @@ -408,38 +422,38 @@ window.location.href=`${x}/spotify/connect?clientId=${this.clientId}&userId=${th * @param {string} phoneCodeHash The phone code hash. * @returns {Promise} A promise that resolves with the Telegram account data. * @throws {APIError|Error} - Throws an error if the user is not authenticated. Also throws an error if the phone number, OTP, and phone code hash are not provided. - */linkTelegram(e,t,n){return c(this,void 0,void 0,(function*(){if(!this.isAuthenticated)throw new Error("User needs to be authenticated");if(!e||!t||!n)throw new m("Phone number, OTP, and phone code hash are required");const i=yield fetch(`${x}/telegram/signIn-sdk`,{method:"POST",redirect:"follow",headers:{Authorization:`Bearer ${this.jwt}`,"x-client-id":this.clientId,"Content-Type":"application/json"},body:JSON.stringify({phone:e,code:t,phone_code_hash:n,userId:this.userId,clientId:this.clientId})}).then((e=>e.json()));if(i.isError)throw new m(i.message||"Failed to link Telegram account");return y(this,ie,"m",ce).call(this,M.TELEGRAM_LINKED,"Telegram Linked"),i.data}))} + */linkTelegram(e,t,n){return c(this,void 0,void 0,(function*(){if(!this.isAuthenticated)throw new Error("User needs to be authenticated");if(!e||!t||!n)throw new m("Phone number, OTP, and phone code hash are required");const i=yield fetch(`${M}/telegram/signIn-sdk`,{method:"POST",redirect:"follow",headers:{Authorization:`Bearer ${this.jwt}`,"x-client-id":this.clientId,"Content-Type":"application/json"},body:JSON.stringify({phone:e,code:t,phone_code_hash:n,userId:this.userId,clientId:this.clientId})}).then((e=>e.json()));if(i.isError)throw new m(i.message||"Failed to link Telegram account");return y(this,re,"m",ye).call(this,S.TELEGRAM_LINKED,"Telegram Linked"),i.data}))} /** * Unlink the user's Twitter account. * @returns {Promise} A promise that resolves with the unlink result. * @throws {Error} - Throws an error if the user is not authenticated. * @throws {APIError} - Throws an error if the request fails. - */unlinkTwitter(){return c(this,void 0,void 0,(function*(){if(!this.isAuthenticated)throw new Error("User needs to be authenticated");const e=yield fetch(`${x}/twitter/disconnect-sdk`,{method:"POST",redirect:"follow",headers:{Authorization:`Bearer ${this.jwt}`,"x-client-id":this.clientId,"Content-Type":"application/json"},body:JSON.stringify({id:this.userId})}).then((e=>e.json()));if(e.isError)throw new m(e.message||"Failed to unlink Twitter account");return e.data}))} + */unlinkTwitter(){return c(this,void 0,void 0,(function*(){if(!this.isAuthenticated)throw new Error("User needs to be authenticated");const e=yield fetch(`${M}/twitter/disconnect-sdk`,{method:"POST",redirect:"follow",headers:{Authorization:`Bearer ${this.jwt}`,"x-client-id":this.clientId,"Content-Type":"application/json"},body:JSON.stringify({id:this.userId})}).then((e=>e.json()));if(e.isError)throw new m(e.message||"Failed to unlink Twitter account");return e.data}))} /** * Unlink the user's Discord account. * @returns {Promise} A promise that resolves with the unlink result. * @throws {Error} - Throws an error if the user is not authenticated. * @throws {APIError} - Throws an error if the request fails. - */unlinkDiscord(){return c(this,void 0,void 0,(function*(){if(!this.isAuthenticated)throw new m("User needs to be authenticated");const e=yield fetch(`${x}/discord/disconnect-sdk`,{method:"POST",redirect:"follow",headers:{Authorization:`Bearer ${this.jwt}`,"x-client-id":this.clientId,"Content-Type":"application/json"},body:JSON.stringify({id:this.userId})}).then((e=>e.json()));if(e.isError)throw new m(e.message||"Failed to unlink Discord account");return e.data}))} + */unlinkDiscord(){return c(this,void 0,void 0,(function*(){if(!this.isAuthenticated)throw new m("User needs to be authenticated");const e=yield fetch(`${M}/discord/disconnect-sdk`,{method:"POST",redirect:"follow",headers:{Authorization:`Bearer ${this.jwt}`,"x-client-id":this.clientId,"Content-Type":"application/json"},body:JSON.stringify({id:this.userId})}).then((e=>e.json()));if(e.isError)throw new m(e.message||"Failed to unlink Discord account");return e.data}))} /** * Unlink the user's Spotify account. * @returns {Promise} A promise that resolves with the unlink result. * @throws {Error} - Throws an error if the user is not authenticated. * @throws {APIError} - Throws an error if the request fails. - */unlinkSpotify(){return c(this,void 0,void 0,(function*(){if(!this.isAuthenticated)throw new m("User needs to be authenticated");const e=yield fetch(`${x}/spotify/disconnect-sdk`,{method:"POST",redirect:"follow",headers:{Authorization:`Bearer ${this.jwt}`,"x-client-id":this.clientId,"Content-Type":"application/json"},body:JSON.stringify({id:this.userId})}).then((e=>e.json()));if(e.isError)throw new m(e.message||"Failed to unlink Spotify account");return e.data}))} + */unlinkSpotify(){return c(this,void 0,void 0,(function*(){if(!this.isAuthenticated)throw new m("User needs to be authenticated");const e=yield fetch(`${M}/spotify/disconnect-sdk`,{method:"POST",redirect:"follow",headers:{Authorization:`Bearer ${this.jwt}`,"x-client-id":this.clientId,"Content-Type":"application/json"},body:JSON.stringify({id:this.userId})}).then((e=>e.json()));if(e.isError)throw new m(e.message||"Failed to unlink Spotify account");return e.data}))} /** * Unlink the user's TikTok account. * @returns {Promise} A promise that resolves with the unlink result. * @throws {Error} - Throws an error if the user is not authenticated. * @throws {APIError} - Throws an error if the request fails. - */unlinkTikTok(){return c(this,void 0,void 0,(function*(){if(!this.isAuthenticated)throw new m("User needs to be authenticated");const e=yield fetch(`${x}/tiktok/disconnect-sdk`,{method:"POST",redirect:"follow",headers:{Authorization:`Bearer ${this.jwt}`,"x-client-id":this.clientId,"Content-Type":"application/json"},body:JSON.stringify({userId:this.userId})}).then((e=>e.json()));if(e.isError)throw new m(e.message||"Failed to unlink TikTok account");return e.data}))} + */unlinkTikTok(){return c(this,void 0,void 0,(function*(){if(!this.isAuthenticated)throw new m("User needs to be authenticated");const e=yield fetch(`${M}/tiktok/disconnect-sdk`,{method:"POST",redirect:"follow",headers:{Authorization:`Bearer ${this.jwt}`,"x-client-id":this.clientId,"Content-Type":"application/json"},body:JSON.stringify({userId:this.userId})}).then((e=>e.json()));if(e.isError)throw new m(e.message||"Failed to unlink TikTok account");return e.data}))} /** * Unlink the user's Telegram account. * @returns {Promise} A promise that resolves with the unlink result. * @throws {Error} - Throws an error if the user is not authenticated. * @throws {APIError} - Throws an error if the request fails. - */unlinkTelegram(){return c(this,void 0,void 0,(function*(){if(!this.isAuthenticated)throw new m("User needs to be authenticated");const e=yield fetch(`${x}/telegram/disconnect-sdk`,{method:"POST",redirect:"follow",headers:{Authorization:`Bearer ${this.jwt}`,"x-client-id":this.clientId,"Content-Type":"application/json"},body:JSON.stringify({userId:this.userId})}).then((e=>e.json()));if(e.isError)throw new m(e.message||"Failed to unlink Telegram account");return e.data}))}}ae=new WeakMap,re=new WeakMap,ie=new WeakSet,se=function(e,t){y(this,ae,"f")[e]&&y(this,ae,"f")[e].forEach((e=>e(t)))},oe=function(e){return c(this,void 0,void 0,(function*(){if("undefined"==typeof localStorage)return;const t=null===localStorage||void 0===localStorage?void 0:localStorage.getItem("camp-sdk:wallet-address"),n=null===localStorage||void 0===localStorage?void 0:localStorage.getItem("camp-sdk:user-id"),i=null===localStorage||void 0===localStorage?void 0:localStorage.getItem("camp-sdk:jwt");t&&n&&i?(this.walletAddress=t,this.userId=n,this.jwt=i,this.origin=new ve(this.jwt),this.isAuthenticated=!0,e?this.setProvider({provider:e.provider,info:e.info||{name:"Unknown"},address:t}):(console.warn("No matching provider was given for the stored wallet address. Trying to recover provider."),yield this.recoverProvider())):this.isAuthenticated=!1}))},de=function(){return c(this,void 0,void 0,(function*(){try{const[e]=yield this.viem.requestAddresses();return this.walletAddress=u(e),this.walletAddress}catch(e){throw new m(e)}}))},ue=function(){return c(this,void 0,void 0,(function*(){try{const e=yield fetch(`${x}/auth/client-user/nonce`,{method:"POST",headers:{"Content-Type":"application/json","x-client-id":this.clientId},body:JSON.stringify({walletAddress:this.walletAddress})}),t=yield e.json();return 200!==e.status?Promise.reject(t.message||"Failed to fetch nonce"):t.data}catch(e){throw new Error(e)}}))},le=function(e,t){return c(this,void 0,void 0,(function*(){try{const n=yield fetch(`${x}/auth/client-user/verify`,{method:"POST",headers:{"Content-Type":"application/json","x-client-id":this.clientId},body:JSON.stringify({message:e,signature:t,walletAddress:this.walletAddress})}),i=yield n.json(),a=i.data.split(".")[1],r=JSON.parse(atob(a));return{success:!i.isError,userId:r.id,token:i.data}}catch(e){throw new m(e)}}))},pe=function(e){return p({domain:window.location.host,address:this.walletAddress,statement:E,uri:window.location.origin,version:"1",chainId:this.viem.chain.id,nonce:e})},ce=function(e,t){return c(this,arguments,void 0,(function*(e,t,n=1){ + */unlinkTelegram(){return c(this,void 0,void 0,(function*(){if(!this.isAuthenticated)throw new m("User needs to be authenticated");const e=yield fetch(`${M}/telegram/disconnect-sdk`,{method:"POST",redirect:"follow",headers:{Authorization:`Bearer ${this.jwt}`,"x-client-id":this.clientId,"Content-Type":"application/json"},body:JSON.stringify({userId:this.userId})}).then((e=>e.json()));if(e.isError)throw new m(e.message||"Failed to unlink Telegram account");return e.data}))}}ae=new WeakMap,se=new WeakMap,re=new WeakSet,oe=function(e,t){y(this,ae,"f")[e]&&y(this,ae,"f")[e].forEach((e=>e(t)))},de=function(e){return c(this,void 0,void 0,(function*(){if("undefined"==typeof localStorage)return;const t=null===localStorage||void 0===localStorage?void 0:localStorage.getItem("camp-sdk:wallet-address"),n=null===localStorage||void 0===localStorage?void 0:localStorage.getItem("camp-sdk:user-id"),i=null===localStorage||void 0===localStorage?void 0:localStorage.getItem("camp-sdk:jwt");t&&n&&i?(this.walletAddress=t,this.userId=n,this.jwt=i,this.origin=new Te(this.jwt),this.isAuthenticated=!0,e?this.setProvider({provider:e.provider,info:e.info||{name:"Unknown"},address:t}):(console.warn("No matching provider was given for the stored wallet address. Trying to recover provider."),yield this.recoverProvider())):this.isAuthenticated=!1}))},ue=function(){return c(this,void 0,void 0,(function*(){try{const[e]=yield this.viem.requestAddresses();return this.walletAddress=u(e),this.walletAddress}catch(e){throw new m(e)}}))},le=function(){return c(this,void 0,void 0,(function*(){try{const e=yield fetch(`${M}/auth/client-user/nonce`,{method:"POST",headers:{"Content-Type":"application/json","x-client-id":this.clientId},body:JSON.stringify({walletAddress:this.walletAddress})}),t=yield e.json();return 200!==e.status?Promise.reject(t.message||"Failed to fetch nonce"):t.data}catch(e){throw new Error(e)}}))},pe=function(e,t){return c(this,void 0,void 0,(function*(){try{const n=yield fetch(`${M}/auth/client-user/verify`,{method:"POST",headers:{"Content-Type":"application/json","x-client-id":this.clientId},body:JSON.stringify({message:e,signature:t,walletAddress:this.walletAddress})}),i=yield n.json(),r=i.data.split(".")[1],a=JSON.parse(atob(r));return{success:!i.isError,userId:a.id,token:i.data}}catch(e){throw new m(e)}}))},ce=function(e){return p({domain:window.location.host,address:this.walletAddress,statement:x,uri:window.location.origin,version:"1",chainId:this.viem.chain.id,nonce:e})},ye=function(e,t){return c(this,arguments,void 0,(function*(e,t,n=1){ // if (this.#ackeeInstance) // await sendAnalyticsEvent(this.#ackeeInstance, event, message, count); // else return; -}))};export{Te as Auth,g as SpotifyAPI,b as TwitterAPI}; +}))};export{ge as Auth,I as SpotifyAPI,b as TwitterAPI}; diff --git a/src/core/spotify.ts b/src/core/spotify.ts index 5108e88..9c52e8f 100644 --- a/src/core/spotify.ts +++ b/src/core/spotify.ts @@ -1,5 +1,5 @@ import { fetchData, buildURL, baseSpotifyURL as baseURL } from "../utils"; -import { APIError } from "../errors"; +import { APIError, ValidationError } from "../errors"; interface SpotifyAPIOptions { apiKey: string; @@ -20,7 +20,10 @@ class SpotifyAPI { * @throws {Error} - Throws an error if the API key is not provided. */ constructor(options: SpotifyAPIOptions) { - this.apiKey = options.apiKey; + if (!options || !options.apiKey || typeof options.apiKey !== 'string' || options.apiKey.trim() === '') { + throw new ValidationError("API key is required and must be a non-empty string"); + } + this.apiKey = options.apiKey.trim(); } /** @@ -30,8 +33,11 @@ class SpotifyAPI { * @throws {APIError} - Throws an error if the request fails. */ async fetchSavedTracksById(spotifyId: string): Promise { + if (!spotifyId || typeof spotifyId !== 'string' || spotifyId.trim() === '') { + throw new ValidationError("Spotify ID is required and must be a non-empty string"); + } const url = buildURL(`${baseURL}/save-tracks`, { - spotifyId, + spotifyId: spotifyId.trim(), }); return this._fetchDataWithAuth(url); } @@ -43,8 +49,11 @@ class SpotifyAPI { * @throws {APIError} - Throws an error if the request fails. */ async fetchPlayedTracksById(spotifyId: string): Promise { + if (!spotifyId || typeof spotifyId !== 'string' || spotifyId.trim() === '') { + throw new ValidationError("Spotify ID is required and must be a non-empty string"); + } const url = buildURL(`${baseURL}/played-tracks`, { - spotifyId, + spotifyId: spotifyId.trim(), }); return this._fetchDataWithAuth(url); } @@ -56,8 +65,11 @@ class SpotifyAPI { * @throws {APIError} - Throws an error if the request fails. */ async fetchSavedAlbumsById(spotifyId: string): Promise { + if (!spotifyId || typeof spotifyId !== 'string' || spotifyId.trim() === '') { + throw new ValidationError("Spotify ID is required and must be a non-empty string"); + } const url = buildURL(`${baseURL}/saved-albums`, { - spotifyId, + spotifyId: spotifyId.trim(), }); return this._fetchDataWithAuth(url); } @@ -69,8 +81,11 @@ class SpotifyAPI { * @throws {APIError} - Throws an error if the request fails. */ async fetchSavedPlaylistsById(spotifyId: string): Promise { + if (!spotifyId || typeof spotifyId !== 'string' || spotifyId.trim() === '') { + throw new ValidationError("Spotify ID is required and must be a non-empty string"); + } const url = buildURL(`${baseURL}/saved-playlists`, { - spotifyId, + spotifyId: spotifyId.trim(), }); return this._fetchDataWithAuth(url); } @@ -86,9 +101,15 @@ class SpotifyAPI { spotifyId: string, albumId: string ): Promise { + if (!spotifyId || typeof spotifyId !== 'string' || spotifyId.trim() === '') { + throw new ValidationError("Spotify ID is required and must be a non-empty string"); + } + if (!albumId || typeof albumId !== 'string' || albumId.trim() === '') { + throw new ValidationError("Album ID is required and must be a non-empty string"); + } const url = buildURL(`${baseURL}/album/tracks`, { - spotifyId, - albumId, + spotifyId: spotifyId.trim(), + albumId: albumId.trim(), }); return this._fetchDataWithAuth(url); } @@ -104,9 +125,15 @@ class SpotifyAPI { spotifyId: string, playlistId: string ): Promise { + if (!spotifyId || typeof spotifyId !== 'string' || spotifyId.trim() === '') { + throw new ValidationError("Spotify ID is required and must be a non-empty string"); + } + if (!playlistId || typeof playlistId !== 'string' || playlistId.trim() === '') { + throw new ValidationError("Playlist ID is required and must be a non-empty string"); + } const url = buildURL(`${baseURL}/playlist/tracks`, { - spotifyId, - playlistId, + spotifyId: spotifyId.trim(), + playlistId: playlistId.trim(), }); return this._fetchDataWithAuth(url); } @@ -118,7 +145,15 @@ class SpotifyAPI { * @throws {APIError} - Throws an error if the request fails. */ async fetchUserByWalletAddress(walletAddress: string): Promise { - const url = buildURL(`${baseURL}/wallet-spotify-data`, { walletAddress }); + if (!walletAddress || typeof walletAddress !== 'string' || walletAddress.trim() === '') { + throw new ValidationError("Wallet address is required and must be a non-empty string"); + } + // Basic evm address format validation + const trimmedAddress = walletAddress.trim(); + if (!/^0x[a-fA-F0-9]{40}$/.test(trimmedAddress)) { + throw new ValidationError("Invalid wallet address format"); + } + const url = buildURL(`${baseURL}/wallet-spotify-data`, { walletAddress: trimmedAddress }); return this._fetchDataWithAuth(url); } diff --git a/src/core/twitter.ts b/src/core/twitter.ts index 3b65d27..24e12d1 100644 --- a/src/core/twitter.ts +++ b/src/core/twitter.ts @@ -1,5 +1,5 @@ import { fetchData, buildURL, baseTwitterURL as baseURL } from "../utils"; -import { APIError } from "../errors"; +import { APIError, ValidationError } from "../errors"; /** * The TwitterAPI class. @@ -14,7 +14,10 @@ class TwitterAPI { * @param {string} options.apiKey - The API key. (Needed for data fetching) */ constructor({ apiKey }: { apiKey: string }) { - this.apiKey = apiKey; + if (!apiKey || typeof apiKey !== 'string' || apiKey.trim() === '') { + throw new ValidationError("API key is required and must be a non-empty string"); + } + this.apiKey = apiKey.trim(); } /** @@ -24,7 +27,15 @@ class TwitterAPI { * @throws {APIError} - Throws an error if the request fails. */ async fetchUserByUsername(twitterUserName: string): Promise { - const url = buildURL(`${baseURL}/user`, { twitterUserName }); + if (!twitterUserName || typeof twitterUserName !== 'string' || twitterUserName.trim() === '') { + throw new ValidationError("Twitter username is required and must be a non-empty string"); + } + const trimmedUsername = twitterUserName.trim(); + // Basic Twitter(X) username validation (no @ symbol, alphanumeric + underscore) + if (!/^[a-zA-Z0-9_]{1,15}$/.test(trimmedUsername)) { + throw new ValidationError("Invalid Twitter username format"); + } + const url = buildURL(`${baseURL}/user`, { twitterUserName: trimmedUsername }); return this._fetchDataWithAuth(url); } @@ -41,8 +52,21 @@ class TwitterAPI { page: number = 1, limit: number = 10 ): Promise { + if (!twitterUserName || typeof twitterUserName !== 'string' || twitterUserName.trim() === '') { + throw new ValidationError("Twitter username is required and must be a non-empty string"); + } + const trimmedUsername = twitterUserName.trim(); + if (!/^[a-zA-Z0-9_]{1,15}$/.test(trimmedUsername)) { + throw new ValidationError("Invalid Twitter username format"); + } + if (!Number.isInteger(page) || page < 1) { + throw new ValidationError("Page must be a positive integer"); + } + if (!Number.isInteger(limit) || limit < 1 || limit > 100) { + throw new ValidationError("Limit must be a positive integer between 1 and 100"); + } const url = buildURL(`${baseURL}/tweets`, { - twitterUserName, + twitterUserName: trimmedUsername, page, limit, }); @@ -62,10 +86,11 @@ class TwitterAPI { page: number = 1, limit: number = 10 ): Promise { + const { validatedUsername, validatedPage, validatedLimit } = this._validateUsernamePageLimit(twitterUserName, page, limit); const url = buildURL(`${baseURL}/followers`, { - twitterUserName, - page, - limit, + twitterUserName: validatedUsername, + page: validatedPage, + limit: validatedLimit, }); return this._fetchDataWithAuth(url); } @@ -83,10 +108,11 @@ class TwitterAPI { page: number = 1, limit: number = 10 ): Promise { + const { validatedUsername, validatedPage, validatedLimit } = this._validateUsernamePageLimit(twitterUserName, page, limit); const url = buildURL(`${baseURL}/following`, { - twitterUserName, - page, - limit, + twitterUserName: validatedUsername, + page: validatedPage, + limit: validatedLimit, }); return this._fetchDataWithAuth(url); } @@ -98,7 +124,15 @@ class TwitterAPI { * @throws {APIError} - Throws an error if the request fails. */ async fetchTweetById(tweetId: string): Promise { - const url = buildURL(`${baseURL}/getTweetById`, { tweetId }); + if (!tweetId || typeof tweetId !== 'string' || tweetId.trim() === '') { + throw new ValidationError("Tweet ID is required and must be a non-empty string"); + } + const trimmedTweetId = tweetId.trim(); + // Basic tweet ID validation (should be numeric) + if (!/^\d+$/.test(trimmedTweetId)) { + throw new ValidationError("Invalid tweet ID format"); + } + const url = buildURL(`${baseURL}/getTweetById`, { tweetId: trimmedTweetId }); return this._fetchDataWithAuth(url); } @@ -115,8 +149,21 @@ class TwitterAPI { page: number = 1, limit: number = 10 ): Promise { + if (!walletAddress || typeof walletAddress !== 'string' || walletAddress.trim() === '') { + throw new ValidationError("Wallet address is required and must be a non-empty string"); + } + const trimmedAddress = walletAddress.trim(); + if (!/^0x[a-fA-F0-9]{40}$/.test(trimmedAddress)) { + throw new ValidationError("Invalid wallet address format"); + } + if (!Number.isInteger(page) || page < 1) { + throw new ValidationError("Page must be a positive integer"); + } + if (!Number.isInteger(limit) || limit < 1 || limit > 100) { + throw new ValidationError("Limit must be a positive integer between 1 and 100"); + } const url = buildURL(`${baseURL}/wallet-twitter-data`, { - walletAddress, + walletAddress: trimmedAddress, page, limit, }); @@ -136,10 +183,11 @@ class TwitterAPI { page: number = 1, limit: number = 10 ): Promise { + const { validatedUsername, validatedPage, validatedLimit } = this._validateUsernamePageLimit(twitterUserName, page, limit); const url = buildURL(`${baseURL}/reposted`, { - twitterUserName, - page, - limit, + twitterUserName: validatedUsername, + page: validatedPage, + limit: validatedLimit, }); return this._fetchDataWithAuth(url); } @@ -157,10 +205,11 @@ class TwitterAPI { page: number = 1, limit: number = 10 ): Promise { + const { validatedUsername, validatedPage, validatedLimit } = this._validateUsernamePageLimit(twitterUserName, page, limit); const url = buildURL(`${baseURL}/replies`, { - twitterUserName, - page, - limit, + twitterUserName: validatedUsername, + page: validatedPage, + limit: validatedLimit, }); return this._fetchDataWithAuth(url); } @@ -178,9 +227,10 @@ class TwitterAPI { page: number = 1, limit: number = 10 ): Promise { - const url = buildURL(`${baseURL}/event/likes/${twitterUserName}`, { - page, - limit, + const { validatedUsername, validatedPage, validatedLimit } = this._validateUsernamePageLimit(twitterUserName, page, limit); + const url = buildURL(`${baseURL}/event/likes/${validatedUsername}`, { + page: validatedPage, + limit: validatedLimit, }); return this._fetchDataWithAuth(url); } @@ -198,9 +248,10 @@ class TwitterAPI { page: number = 1, limit: number = 10 ): Promise { - const url = buildURL(`${baseURL}/event/follows/${twitterUserName}`, { - page, - limit, + const { validatedUsername, validatedPage, validatedLimit } = this._validateUsernamePageLimit(twitterUserName, page, limit); + const url = buildURL(`${baseURL}/event/follows/${validatedUsername}`, { + page: validatedPage, + limit: validatedLimit, }); return this._fetchDataWithAuth(url); } @@ -218,13 +269,43 @@ class TwitterAPI { page: number = 1, limit: number = 10 ): Promise { - const url = buildURL(`${baseURL}/event/viewed-tweets/${twitterUserName}`, { - page, - limit, + const { validatedUsername, validatedPage, validatedLimit } = this._validateUsernamePageLimit(twitterUserName, page, limit); + const url = buildURL(`${baseURL}/event/viewed-tweets/${validatedUsername}`, { + page: validatedPage, + limit: validatedLimit, }); return this._fetchDataWithAuth(url); } + /** + * Private method to validate username, page, and limit parameters. + * @param {string} twitterUserName - The Twitter username. + * @param {number} page - The page number. + * @param {number} limit - The limit number. + * @returns {object} - Validated parameters. + * @throws {ValidationError} - Throws an error if validation fails. + */ + private _validateUsernamePageLimit(twitterUserName: string, page: number, limit: number) { + if (!twitterUserName || typeof twitterUserName !== 'string' || twitterUserName.trim() === '') { + throw new ValidationError("Twitter username is required and must be a non-empty string"); + } + const trimmedUsername = twitterUserName.trim(); + if (!/^[a-zA-Z0-9_]{1,15}$/.test(trimmedUsername)) { + throw new ValidationError("Invalid Twitter username format"); + } + if (!Number.isInteger(page) || page < 1) { + throw new ValidationError("Page must be a positive integer"); + } + if (!Number.isInteger(limit) || limit < 1 || limit > 100) { + throw new ValidationError("Limit must be a positive integer between 1 and 100"); + } + return { + validatedUsername: trimmedUsername, + validatedPage: page, + validatedLimit: limit + }; + } + /** * Private method to fetch data with authorization header. * @param {string} url - The URL to fetch. diff --git a/test/spotify.test.js b/test/spotify.test.js index c9b6013..8424486 100644 --- a/test/spotify.test.js +++ b/test/spotify.test.js @@ -5,7 +5,7 @@ describe('SpotifyAPI', () => { let spotifyAPI; const apiKey = 'test-api-key'; const spotifyId = 'test-spotify-id'; - const walletAddress = 'test-wallet-address'; + const walletAddress = '0x1234567890abcdef1234567890abcdef12345678'; beforeEach(() => { spotifyAPI = new SpotifyAPI({ apiKey }); diff --git a/test/twitter.test.js b/test/twitter.test.js index 2c2f7a7..875c086 100644 --- a/test/twitter.test.js +++ b/test/twitter.test.js @@ -48,22 +48,22 @@ describe("TwitterAPI", () => { }); test("fetchTweetById should fetch a tweet by ID", async () => { - const mockResponse = { id: "tweet123", text: "Hello World" }; + const mockResponse = { id: "1234567890123456789", text: "Hello World" }; jest .spyOn(twitterAPI, "_fetchDataWithAuth") .mockResolvedValue(mockResponse); - const result = await twitterAPI.fetchTweetById("tweet123"); + const result = await twitterAPI.fetchTweetById("1234567890123456789"); expect(result).toEqual(mockResponse); }); test("fetchUserByWalletAddress should fetch user data by wallet address", async () => { - const mockResponse = { id: "user123", walletAddress: "0x123" }; + const mockResponse = { id: "user123", walletAddress: "0x1234567890abcdef1234567890abcdef12345678" }; jest .spyOn(twitterAPI, "_fetchDataWithAuth") .mockResolvedValue(mockResponse); - const result = await twitterAPI.fetchUserByWalletAddress("0x123"); + const result = await twitterAPI.fetchUserByWalletAddress("0x1234567890abcdef1234567890abcdef12345678"); expect(result).toEqual(mockResponse); }); diff --git a/test/validation.test.js b/test/validation.test.js new file mode 100644 index 0000000..1f66111 --- /dev/null +++ b/test/validation.test.js @@ -0,0 +1,62 @@ +const { SpotifyAPI, TwitterAPI } = require('../dist/core.cjs'); +const { ValidationError } = require('../dist/core.cjs'); + +describe('Input Validation', () => { + describe('SpotifyAPI Validation', () => { + test('should throw ValidationError for empty API key', () => { + expect(() => new SpotifyAPI({ apiKey: '' })).toThrow(ValidationError); + expect(() => new SpotifyAPI({ apiKey: ' ' })).toThrow(ValidationError); + }); + + test('should throw ValidationError for missing spotifyId', async () => { + const spotify = new SpotifyAPI({ apiKey: 'test-key' }); + await expect(spotify.fetchSavedTracksById('')).rejects.toThrow(ValidationError); + await expect(spotify.fetchSavedTracksById(' ')).rejects.toThrow(ValidationError); + }); + + test('should throw ValidationError for invalid wallet address', async () => { + const spotify = new SpotifyAPI({ apiKey: 'test-key' }); + await expect(spotify.fetchUserByWalletAddress('invalid-address')).rejects.toThrow(ValidationError); + await expect(spotify.fetchUserByWalletAddress('0x123')).rejects.toThrow(ValidationError); + // Mock API call for valid address + jest.spyOn(spotify, '_fetchDataWithAuth').mockResolvedValue({}); + await expect(spotify.fetchUserByWalletAddress('0x1234567890abcdef1234567890abcdef12345678')).resolves.not.toThrow(); + }); + }); + + describe('TwitterAPI Validation', () => { + test('should throw ValidationError for empty API key', () => { + expect(() => new TwitterAPI({ apiKey: '' })).toThrow(ValidationError); + expect(() => new TwitterAPI({ apiKey: ' ' })).toThrow(ValidationError); + }); + + test('should throw ValidationError for invalid Twitter username', async () => { + const twitter = new TwitterAPI({ apiKey: 'test-key' }); + await expect(twitter.fetchUserByUsername('')).rejects.toThrow(ValidationError); + await expect(twitter.fetchUserByUsername('invalid-username-too-long')).rejects.toThrow(ValidationError); + await expect(twitter.fetchUserByUsername('invalid@username')).rejects.toThrow(ValidationError); + }); + + test('should throw ValidationError for invalid tweet ID', async () => { + const twitter = new TwitterAPI({ apiKey: 'test-key' }); + await expect(twitter.fetchTweetById('')).rejects.toThrow(ValidationError); + await expect(twitter.fetchTweetById('invalid-tweet-id')).rejects.toThrow(ValidationError); + }); + + test('should throw ValidationError for invalid page/limit parameters', async () => { + const twitter = new TwitterAPI({ apiKey: 'test-key' }); + await expect(twitter.fetchTweetsByUsername('valid_user', 0, 10)).rejects.toThrow(ValidationError); + await expect(twitter.fetchTweetsByUsername('valid_user', 1, 0)).rejects.toThrow(ValidationError); + await expect(twitter.fetchTweetsByUsername('valid_user', 1, 101)).rejects.toThrow(ValidationError); + }); + + test('should throw ValidationError for invalid wallet address', async () => { + const twitter = new TwitterAPI({ apiKey: 'test-key' }); + await expect(twitter.fetchUserByWalletAddress('invalid-address')).rejects.toThrow(ValidationError); + await expect(twitter.fetchUserByWalletAddress('0x123')).rejects.toThrow(ValidationError); + // Mock API call for valid address + jest.spyOn(twitter, '_fetchDataWithAuth').mockResolvedValue({}); + await expect(twitter.fetchUserByWalletAddress('0x1234567890abcdef1234567890abcdef12345678')).resolves.not.toThrow(); + }); + }); +});