@campnetwork/origin 1.2.0 → 1.2.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,6 +1,6 @@
1
1
  'use client';
2
2
  import React, { createContext, useState, useContext, useEffect, useLayoutEffect, useRef, useSyncExternalStore } from 'react';
3
- import { custom, createWalletClient, createPublicClient, http, erc20Abi, getAbiItem, zeroAddress, formatEther, formatUnits, encodeFunctionData, checksumAddress, parseEther } from 'viem';
3
+ import { custom, createWalletClient, createPublicClient, http, erc20Abi, getAbiItem, checksumAddress, zeroAddress, formatEther, formatUnits, encodeFunctionData, keccak256, toBytes, parseEther } from 'viem';
4
4
  import { toAccount } from 'viem/accounts';
5
5
  import { createSiweMessage } from 'viem/siwe';
6
6
  import axios from 'axios';
@@ -3456,32 +3456,6 @@ function subscriptionExpiry(tokenId, user) {
3456
3456
  return this.callContractMethod(this.environment.MARKETPLACE_CONTRACT_ADDRESS, this.environment.MARKETPLACE_ABI, "subscriptionExpiry", [tokenId, user]);
3457
3457
  }
3458
3458
 
3459
- /**
3460
- * Approves a spender to spend a specified amount of tokens on behalf of the owner.
3461
- * If the current allowance is less than the specified amount, it will perform the approval.
3462
- * @param {ApproveParams} params - The parameters for the approval.
3463
- */
3464
- function approveIfNeeded(_a) {
3465
- return __awaiter(this, arguments, void 0, function* ({ walletClient, publicClient, tokenAddress, owner, spender, amount, }) {
3466
- const allowance = yield publicClient.readContract({
3467
- address: tokenAddress,
3468
- abi: erc20Abi,
3469
- functionName: "allowance",
3470
- args: [owner, spender],
3471
- });
3472
- if (allowance < amount) {
3473
- yield walletClient.writeContract({
3474
- address: tokenAddress,
3475
- account: owner,
3476
- abi: erc20Abi,
3477
- functionName: "approve",
3478
- args: [spender, amount],
3479
- chain: testnet,
3480
- });
3481
- }
3482
- });
3483
- }
3484
-
3485
3459
  /**
3486
3460
  * Enum representing the status of data in the system.
3487
3461
  * * - ACTIVE: The data is currently active and available.
@@ -3521,18 +3495,239 @@ const createLicenseTerms = (price, duration, royaltyBps, paymentToken) => {
3521
3495
  paymentToken,
3522
3496
  };
3523
3497
  };
3498
+ /**
3499
+ * Defines the EIP-712 typed data structure for X402 Intent signatures.
3500
+ */
3501
+ const X402_INTENT_TYPES = {
3502
+ X402Intent: [
3503
+ { name: "payer", type: "address" },
3504
+ { name: "asset", type: "address" },
3505
+ { name: "amount", type: "uint256" },
3506
+ { name: "httpMethod", type: "string" },
3507
+ { name: "payTo", type: "address" },
3508
+ { name: "tokenId", type: "uint256" },
3509
+ { name: "duration", type: "uint32" },
3510
+ { name: "expiresAt", type: "uint256" },
3511
+ { name: "nonce", type: "bytes32" },
3512
+ ],
3513
+ };
3514
+
3515
+ /**
3516
+ * Approves a spender to spend a specified amount of tokens on behalf of the owner.
3517
+ * If the current allowance is less than the specified amount, it will perform the approval.
3518
+ * @param {ApproveParams} params - The parameters for the approval.
3519
+ */
3520
+ function approveIfNeeded(_a) {
3521
+ return __awaiter(this, arguments, void 0, function* ({ walletClient, publicClient, tokenAddress, owner, spender, amount, }) {
3522
+ const allowance = yield publicClient.readContract({
3523
+ address: tokenAddress,
3524
+ abi: erc20Abi,
3525
+ functionName: "allowance",
3526
+ args: [owner, spender],
3527
+ });
3528
+ if (allowance < amount) {
3529
+ yield walletClient.writeContract({
3530
+ address: tokenAddress,
3531
+ account: owner,
3532
+ abi: erc20Abi,
3533
+ functionName: "approve",
3534
+ args: [spender, amount],
3535
+ chain: testnet,
3536
+ });
3537
+ }
3538
+ });
3539
+ }
3540
+
3541
+ /**
3542
+ * Adapter for viem WalletClient
3543
+ */
3544
+ class ViemSignerAdapter {
3545
+ constructor(signer) {
3546
+ this.type = "viem";
3547
+ this.signer = signer;
3548
+ }
3549
+ getAddress() {
3550
+ return __awaiter(this, void 0, void 0, function* () {
3551
+ if (this.signer.account) {
3552
+ return this.signer.account.address;
3553
+ }
3554
+ const accounts = yield this.signer.request({
3555
+ method: "eth_requestAccounts",
3556
+ params: [],
3557
+ });
3558
+ if (!accounts || accounts.length === 0) {
3559
+ throw new Error("No accounts found in viem wallet client");
3560
+ }
3561
+ return accounts[0];
3562
+ });
3563
+ }
3564
+ signMessage(message) {
3565
+ return __awaiter(this, void 0, void 0, function* () {
3566
+ const address = yield this.getAddress();
3567
+ return yield this.signer.signMessage({
3568
+ account: address,
3569
+ message,
3570
+ });
3571
+ });
3572
+ }
3573
+ signTypedData(domain, types, value) {
3574
+ return __awaiter(this, void 0, void 0, function* () {
3575
+ throw new Error("Viem WalletClient does not support signTypedData");
3576
+ });
3577
+ }
3578
+ getChainId() {
3579
+ return __awaiter(this, void 0, void 0, function* () {
3580
+ var _a;
3581
+ return ((_a = this.signer.chain) === null || _a === void 0 ? void 0 : _a.id) || 1;
3582
+ });
3583
+ }
3584
+ }
3585
+ /**
3586
+ * Adapter for ethers Signer (v5 and v6)
3587
+ */
3588
+ class EthersSignerAdapter {
3589
+ constructor(signer) {
3590
+ this.type = "ethers";
3591
+ this.signer = signer;
3592
+ }
3593
+ getAddress() {
3594
+ return __awaiter(this, void 0, void 0, function* () {
3595
+ // Works for both ethers v5 and v6
3596
+ if (typeof this.signer.getAddress === "function") {
3597
+ return yield this.signer.getAddress();
3598
+ }
3599
+ if (this.signer.address) {
3600
+ return this.signer.address;
3601
+ }
3602
+ throw new Error("Unable to get address from ethers signer");
3603
+ });
3604
+ }
3605
+ signMessage(message) {
3606
+ return __awaiter(this, void 0, void 0, function* () {
3607
+ if (typeof this.signer.signMessage !== "function") {
3608
+ throw new Error("Signer does not support signMessage");
3609
+ }
3610
+ return yield this.signer.signMessage(message);
3611
+ });
3612
+ }
3613
+ signTypedData(domain, types, value) {
3614
+ return __awaiter(this, void 0, void 0, function* () {
3615
+ if (typeof this.signer._signTypedData === "function") {
3616
+ return yield this.signer._signTypedData(domain, types, value);
3617
+ }
3618
+ if (typeof this.signer.signTypedData !== "function") {
3619
+ throw new Error("Signer does not support signTypedData or _signTypedData");
3620
+ }
3621
+ return yield this.signer.signTypedData(domain, types, value);
3622
+ });
3623
+ }
3624
+ getChainId() {
3625
+ return __awaiter(this, void 0, void 0, function* () {
3626
+ // Try ethers v6 first
3627
+ if (this.signer.provider &&
3628
+ typeof this.signer.provider.getNetwork === "function") {
3629
+ const network = yield this.signer.provider.getNetwork();
3630
+ // ethers v6 returns bigint, v5 returns number
3631
+ return typeof network.chainId === "bigint"
3632
+ ? Number(network.chainId)
3633
+ : network.chainId;
3634
+ }
3635
+ // Fallback for ethers v5
3636
+ if (typeof this.signer.getChainId === "function") {
3637
+ return yield this.signer.getChainId();
3638
+ }
3639
+ // Default to mainnet if we can't determine
3640
+ return 484;
3641
+ });
3642
+ }
3643
+ }
3644
+ /**
3645
+ * Adapter for custom signer implementations
3646
+ */
3647
+ class CustomSignerAdapter {
3648
+ constructor(signer) {
3649
+ this.type = "custom";
3650
+ this.signer = signer;
3651
+ }
3652
+ getAddress() {
3653
+ return __awaiter(this, void 0, void 0, function* () {
3654
+ if (typeof this.signer.getAddress === "function") {
3655
+ return yield this.signer.getAddress();
3656
+ }
3657
+ if (this.signer.address) {
3658
+ return this.signer.address;
3659
+ }
3660
+ throw new Error("Custom signer must implement getAddress() or have address property");
3661
+ });
3662
+ }
3663
+ signMessage(message) {
3664
+ return __awaiter(this, void 0, void 0, function* () {
3665
+ if (typeof this.signer.signMessage !== "function") {
3666
+ throw new Error("Custom signer must implement signMessage()");
3667
+ }
3668
+ return yield this.signer.signMessage(message);
3669
+ });
3670
+ }
3671
+ signTypedData(domain, types, value) {
3672
+ return __awaiter(this, void 0, void 0, function* () {
3673
+ if (typeof this.signer.signTypedData !== "function") {
3674
+ throw new Error("Custom signer must implement signTypedData()");
3675
+ }
3676
+ return yield this.signer.signTypedData(domain, types, value);
3677
+ });
3678
+ }
3679
+ getChainId() {
3680
+ return __awaiter(this, void 0, void 0, function* () {
3681
+ if (typeof this.signer.getChainId === "function") {
3682
+ const chainId = yield this.signer.getChainId();
3683
+ return typeof chainId === "bigint" ? Number(chainId) : chainId;
3684
+ }
3685
+ if (this.signer.chainId !== undefined) {
3686
+ return typeof this.signer.chainId === "bigint"
3687
+ ? Number(this.signer.chainId)
3688
+ : this.signer.chainId;
3689
+ }
3690
+ // Default to mainnet
3691
+ return 484;
3692
+ });
3693
+ }
3694
+ }
3695
+ /**
3696
+ * Factory function to create appropriate adapter based on signer type
3697
+ */
3698
+ function createSignerAdapter(signer) {
3699
+ // Check for viem WalletClient
3700
+ if (signer.transport &&
3701
+ signer.chain &&
3702
+ typeof signer.signMessage === "function") {
3703
+ return new ViemSignerAdapter(signer);
3704
+ }
3705
+ // Check for ethers signer (v5 or v6)
3706
+ if (signer._isSigner ||
3707
+ (signer.provider && typeof signer.signMessage === "function")) {
3708
+ return new EthersSignerAdapter(signer);
3709
+ }
3710
+ // Try custom adapter
3711
+ return new CustomSignerAdapter(signer);
3712
+ }
3524
3713
 
3525
- var _Origin_instances, _Origin_generateURL, _Origin_setOriginStatus, _Origin_waitForTxReceipt, _Origin_ensureChainId, _Origin_getCurrentAccount, _Origin_resolveWalletAddress;
3714
+ var _Origin_instances, _Origin_generateURL, _Origin_setOriginStatus, _Origin_uploadFile, _Origin_waitForTxReceipt, _Origin_ensureChainId, _Origin_getCurrentAccount, _Origin_makeX402IntentDomain, _Origin_buildX402Payload, _Origin_resolveWalletAddress;
3526
3715
  /**
3527
3716
  * The Origin class
3528
3717
  * Handles the upload of files to Origin, as well as querying the user's stats
3529
3718
  */
3530
3719
  class Origin {
3531
- constructor(jwt, environment, viemClient, baseParentId) {
3720
+ constructor(environment, jwt, viemClient, baseParentId) {
3532
3721
  _Origin_instances.add(this);
3533
- this.jwt = jwt;
3722
+ if (jwt) {
3723
+ this.jwt = jwt;
3724
+ }
3725
+ else {
3726
+ console.warn("JWT not provided. Some features may be unavailable.");
3727
+ }
3534
3728
  this.viemClient = viemClient;
3535
- this.environment = environment;
3729
+ this.environment =
3730
+ typeof environment === "string" ? ENVIRONMENTS[environment] : environment;
3536
3731
  this.baseParentId = baseParentId;
3537
3732
  // DataNFT methods
3538
3733
  this.mintWithSignature = mintWithSignature.bind(this);
@@ -3561,41 +3756,6 @@ class Origin {
3561
3756
  setViemClient(client) {
3562
3757
  this.viemClient = client;
3563
3758
  }
3564
- uploadFile(file, options) {
3565
- return __awaiter(this, void 0, void 0, function* () {
3566
- let uploadInfo;
3567
- try {
3568
- uploadInfo = yield __classPrivateFieldGet(this, _Origin_instances, "m", _Origin_generateURL).call(this, file);
3569
- }
3570
- catch (error) {
3571
- console.error("Failed to generate upload URL:", error);
3572
- throw new Error(`Failed to generate upload URL: ${error instanceof Error ? error.message : String(error)}`);
3573
- }
3574
- if (!uploadInfo) {
3575
- throw new Error("Failed to generate upload URL: No upload info returned");
3576
- }
3577
- try {
3578
- yield uploadWithProgress(file, uploadInfo.url, (options === null || options === void 0 ? void 0 : options.progressCallback) || (() => { }));
3579
- }
3580
- catch (error) {
3581
- try {
3582
- yield __classPrivateFieldGet(this, _Origin_instances, "m", _Origin_setOriginStatus).call(this, uploadInfo.key, "failed");
3583
- }
3584
- catch (statusError) {
3585
- console.error("Failed to update status to failed:", statusError);
3586
- }
3587
- const errorMessage = error instanceof Error ? error.message : String(error);
3588
- throw new Error(`Failed to upload file: ${errorMessage}`);
3589
- }
3590
- try {
3591
- yield __classPrivateFieldGet(this, _Origin_instances, "m", _Origin_setOriginStatus).call(this, uploadInfo.key, "success");
3592
- }
3593
- catch (statusError) {
3594
- console.error("Failed to update status to success:", statusError);
3595
- }
3596
- return uploadInfo;
3597
- });
3598
- }
3599
3759
  mintFile(file, metadata, license, parents, options) {
3600
3760
  return __awaiter(this, void 0, void 0, function* () {
3601
3761
  let account = null;
@@ -3607,7 +3767,7 @@ class Origin {
3607
3767
  }
3608
3768
  let info;
3609
3769
  try {
3610
- info = yield this.uploadFile(file, options);
3770
+ info = yield __classPrivateFieldGet(this, _Origin_instances, "m", _Origin_uploadFile).call(this, file, options);
3611
3771
  if (!info || !info.key) {
3612
3772
  throw new Error("Failed to upload file or get upload info.");
3613
3773
  }
@@ -3694,72 +3854,6 @@ class Origin {
3694
3854
  return tokenId.toString();
3695
3855
  });
3696
3856
  }
3697
- getOriginUploads() {
3698
- return __awaiter(this, void 0, void 0, function* () {
3699
- const res = yield fetch(`${this.environment.AUTH_HUB_BASE_API}/${this.environment.AUTH_ENDPOINT}/origin/files`, {
3700
- method: "GET",
3701
- headers: {
3702
- Authorization: `Bearer ${this.jwt}`,
3703
- },
3704
- });
3705
- if (!res.ok) {
3706
- console.error("Failed to get origin uploads");
3707
- return null;
3708
- }
3709
- const data = yield res.json();
3710
- return data.data;
3711
- });
3712
- }
3713
- /**
3714
- * Get the user's Origin stats (multiplier, consent, usage, etc.).
3715
- * @returns {Promise<OriginUsageReturnType>} A promise that resolves with the user's Origin stats.
3716
- */
3717
- getOriginUsage() {
3718
- return __awaiter(this, void 0, void 0, function* () {
3719
- const data = yield fetch(`${this.environment.AUTH_HUB_BASE_API}/${this.environment.AUTH_ENDPOINT}/origin/usage`, {
3720
- method: "GET",
3721
- headers: {
3722
- Authorization: `Bearer ${this.jwt}`,
3723
- "Content-Type": "application/json",
3724
- },
3725
- }).then((res) => res.json());
3726
- if (!data.isError && data.data.user) {
3727
- return data;
3728
- }
3729
- else {
3730
- throw new APIError(data.message || "Failed to fetch Origin usage");
3731
- }
3732
- });
3733
- }
3734
- /**
3735
- * Set the user's consent for Origin usage.
3736
- * @param {boolean} consent The user's consent.
3737
- * @returns {Promise<void>}
3738
- * @throws {Error|APIError} - Throws an error if the user is not authenticated. Also throws an error if the consent is not provided.
3739
- */
3740
- setOriginConsent(consent) {
3741
- return __awaiter(this, void 0, void 0, function* () {
3742
- if (consent === undefined) {
3743
- throw new APIError("Consent is required");
3744
- }
3745
- const data = yield fetch(`${this.environment.AUTH_HUB_BASE_API}/${this.environment.AUTH_ENDPOINT}/origin/status`, {
3746
- method: "PATCH",
3747
- headers: {
3748
- Authorization: `Bearer ${this.jwt}`,
3749
- "Content-Type": "application/json",
3750
- },
3751
- body: JSON.stringify({
3752
- active: consent,
3753
- }),
3754
- }).then((res) => res.json());
3755
- if (!data.isError) {
3756
- return;
3757
- }
3758
- else {
3759
- throw new APIError(data.message || "Failed to set Origin consent");
3760
- }
3761
- });
3762
- }
3763
3857
  /**
3764
3858
  * Call a contract method.
3765
3859
  * @param {string} contractAddress The contract address.
@@ -3865,6 +3959,12 @@ class Origin {
3865
3959
  return this.buyAccess(account, tokenId, totalCost, duration, paymentToken);
3866
3960
  });
3867
3961
  }
3962
+ /**
3963
+ * Fetch the underlying data associated with a specific token ID.
3964
+ * @param {bigint} tokenId - The token ID to fetch data for.
3965
+ * @returns {Promise<any>} A promise that resolves with the fetched data.
3966
+ * @throws {Error} Throws an error if the data cannot be fetched.
3967
+ */
3868
3968
  getData(tokenId) {
3869
3969
  return __awaiter(this, void 0, void 0, function* () {
3870
3970
  const response = yield fetch(`${this.environment.AUTH_HUB_BASE_API}/${this.environment.AUTH_ENDPOINT}/origin/data/${tokenId}`, {
@@ -3880,6 +3980,60 @@ class Origin {
3880
3980
  return response.json();
3881
3981
  });
3882
3982
  }
3983
+ /**
3984
+ * Fetch data with X402 payment handling.
3985
+ * @param {bigint} tokenId The token ID to fetch data for.
3986
+ * @param {any} [signer] Optional signer object for signing the X402 intent.
3987
+ * @returns {Promise<any>} A promise that resolves with the fetched data.
3988
+ * @throws {Error} Throws an error if the data cannot be fetched or if no signer/wallet client is provided.
3989
+ */
3990
+ getDataWithX402(tokenId, signer) {
3991
+ return __awaiter(this, void 0, void 0, function* () {
3992
+ var _a;
3993
+ if (!signer && !this.viemClient) {
3994
+ throw new Error("No signer or wallet client provided for X402 intent.");
3995
+ }
3996
+ const initialResponse = yield fetch(`${this.environment.AUTH_HUB_BASE_API}/${this.environment.AUTH_ENDPOINT}/origin/data/${tokenId}`, {
3997
+ method: "GET",
3998
+ });
3999
+ if (initialResponse.status !== 402) {
4000
+ if (!initialResponse.ok) {
4001
+ throw new Error("Failed to fetch data");
4002
+ }
4003
+ return initialResponse.json();
4004
+ }
4005
+ const sig = this.viemClient || createSignerAdapter(signer);
4006
+ const walletAddress = this.viemClient
4007
+ ? yield __classPrivateFieldGet(this, _Origin_instances, "m", _Origin_getCurrentAccount).call(this)
4008
+ : yield sig.getAddress();
4009
+ const intentData = yield initialResponse.json();
4010
+ if (intentData.error) {
4011
+ throw new Error(intentData.error);
4012
+ }
4013
+ const requirements = intentData.accepts[0];
4014
+ const x402Payload = yield __classPrivateFieldGet(this, _Origin_instances, "m", _Origin_buildX402Payload).call(this, requirements, checksumAddress(walletAddress), sig);
4015
+ const header = btoa(JSON.stringify(x402Payload));
4016
+ const retryResponse = yield fetch(`${this.environment.AUTH_HUB_BASE_API}/${this.environment.AUTH_ENDPOINT}/origin/data/${tokenId}`, {
4017
+ method: "GET",
4018
+ headers: {
4019
+ "Content-Type": "application/json",
4020
+ "X-PAYMENT": header,
4021
+ },
4022
+ });
4023
+ if (retryResponse.status === 402) {
4024
+ // subscription required
4025
+ return retryResponse.json();
4026
+ }
4027
+ if (!retryResponse.ok) {
4028
+ throw new Error("Failed to fetch data after X402 payment");
4029
+ }
4030
+ const res = yield retryResponse.json();
4031
+ return {
4032
+ error: null,
4033
+ data: (_a = res.data) !== null && _a !== void 0 ? _a : res,
4034
+ };
4035
+ });
4036
+ }
3883
4037
  /**
3884
4038
  * Get the Token Bound Account (TBA) address for a specific token ID.
3885
4039
  * @param {bigint} tokenId - The token ID to get the TBA address for.
@@ -4081,6 +4235,40 @@ _Origin_instances = new WeakSet(), _Origin_generateURL = function _Origin_genera
4081
4235
  throw error;
4082
4236
  }
4083
4237
  });
4238
+ }, _Origin_uploadFile = function _Origin_uploadFile(file, options) {
4239
+ return __awaiter(this, void 0, void 0, function* () {
4240
+ let uploadInfo;
4241
+ try {
4242
+ uploadInfo = yield __classPrivateFieldGet(this, _Origin_instances, "m", _Origin_generateURL).call(this, file);
4243
+ }
4244
+ catch (error) {
4245
+ console.error("Failed to generate upload URL:", error);
4246
+ throw new Error(`Failed to generate upload URL: ${error instanceof Error ? error.message : String(error)}`);
4247
+ }
4248
+ if (!uploadInfo) {
4249
+ throw new Error("Failed to generate upload URL: No upload info returned");
4250
+ }
4251
+ try {
4252
+ yield uploadWithProgress(file, uploadInfo.url, (options === null || options === void 0 ? void 0 : options.progressCallback) || (() => { }));
4253
+ }
4254
+ catch (error) {
4255
+ try {
4256
+ yield __classPrivateFieldGet(this, _Origin_instances, "m", _Origin_setOriginStatus).call(this, uploadInfo.key, "failed");
4257
+ }
4258
+ catch (statusError) {
4259
+ console.error("Failed to update status to failed:", statusError);
4260
+ }
4261
+ const errorMessage = error instanceof Error ? error.message : String(error);
4262
+ throw new Error(`Failed to upload file: ${errorMessage}`);
4263
+ }
4264
+ try {
4265
+ yield __classPrivateFieldGet(this, _Origin_instances, "m", _Origin_setOriginStatus).call(this, uploadInfo.key, "success");
4266
+ }
4267
+ catch (statusError) {
4268
+ console.error("Failed to update status to success:", statusError);
4269
+ }
4270
+ return uploadInfo;
4271
+ });
4084
4272
  }, _Origin_waitForTxReceipt = function _Origin_waitForTxReceipt(txHash_1) {
4085
4273
  return __awaiter(this, arguments, void 0, function* (txHash, opts = {}) {
4086
4274
  var _a, _b, _c;
@@ -4181,6 +4369,47 @@ _Origin_instances = new WeakSet(), _Origin_generateURL = function _Origin_genera
4181
4369
  }
4182
4370
  return accounts[0];
4183
4371
  });
4372
+ }, _Origin_makeX402IntentDomain = function _Origin_makeX402IntentDomain() {
4373
+ return {
4374
+ name: "Origin X402 Intent",
4375
+ version: "1",
4376
+ chainId: this.environment.CHAIN.id,
4377
+ verifyingContract: this.environment
4378
+ .MARKETPLACE_CONTRACT_ADDRESS,
4379
+ };
4380
+ }, _Origin_buildX402Payload = function _Origin_buildX402Payload(requirements, payer, signer) {
4381
+ return __awaiter(this, void 0, void 0, function* () {
4382
+ const asset = requirements.asset === "native" ? zeroAddress : requirements.asset;
4383
+ const amount = BigInt(requirements.maxAmountRequired || 0);
4384
+ const duration = requirements.extra.duration;
4385
+ const domain = __classPrivateFieldGet(this, _Origin_instances, "m", _Origin_makeX402IntentDomain).call(this);
4386
+ const types = X402_INTENT_TYPES;
4387
+ const nonce = crypto.randomUUID();
4388
+ const nonceBytes32 = keccak256(toBytes(nonce));
4389
+ const payment = {
4390
+ payer: payer,
4391
+ asset: asset,
4392
+ amount: amount.toString(),
4393
+ httpMethod: "GET",
4394
+ payTo: checksumAddress(this.environment.MARKETPLACE_CONTRACT_ADDRESS),
4395
+ tokenId: requirements.extra.tokenId,
4396
+ duration: duration,
4397
+ expiresAt: Math.floor(Date.now() / 1000) + requirements.maxTimeoutSeconds,
4398
+ nonce: nonceBytes32,
4399
+ };
4400
+ const signerAdapter = createSignerAdapter(signer);
4401
+ const signature = yield signerAdapter.signTypedData(domain, types, payment);
4402
+ const x402Payload = {
4403
+ x402Version: 1,
4404
+ scheme: "exact",
4405
+ network: requirements.network,
4406
+ payload: Object.assign(Object.assign({}, payment), { sigType: "eip712", signature: signature, license: {
4407
+ tokenId: requirements.extra.tokenId,
4408
+ duration: duration,
4409
+ } }),
4410
+ };
4411
+ return x402Payload;
4412
+ });
4184
4413
  }, _Origin_resolveWalletAddress = function _Origin_resolveWalletAddress(owner) {
4185
4414
  return __awaiter(this, void 0, void 0, function* () {
4186
4415
  if (owner) {
@@ -4205,155 +4434,6 @@ _Origin_instances = new WeakSet(), _Origin_generateURL = function _Origin_genera
4205
4434
  });
4206
4435
  };
4207
4436
 
4208
- /**
4209
- * Adapter for viem WalletClient
4210
- */
4211
- class ViemSignerAdapter {
4212
- constructor(signer) {
4213
- this.type = "viem";
4214
- this.signer = signer;
4215
- }
4216
- getAddress() {
4217
- return __awaiter(this, void 0, void 0, function* () {
4218
- if (this.signer.account) {
4219
- return this.signer.account.address;
4220
- }
4221
- const accounts = yield this.signer.request({
4222
- method: "eth_requestAccounts",
4223
- params: [],
4224
- });
4225
- if (!accounts || accounts.length === 0) {
4226
- throw new Error("No accounts found in viem wallet client");
4227
- }
4228
- return accounts[0];
4229
- });
4230
- }
4231
- signMessage(message) {
4232
- return __awaiter(this, void 0, void 0, function* () {
4233
- const address = yield this.getAddress();
4234
- return yield this.signer.signMessage({
4235
- account: address,
4236
- message,
4237
- });
4238
- });
4239
- }
4240
- getChainId() {
4241
- return __awaiter(this, void 0, void 0, function* () {
4242
- var _a;
4243
- return ((_a = this.signer.chain) === null || _a === void 0 ? void 0 : _a.id) || 1;
4244
- });
4245
- }
4246
- }
4247
- /**
4248
- * Adapter for ethers Signer (v5 and v6)
4249
- */
4250
- class EthersSignerAdapter {
4251
- constructor(signer) {
4252
- this.type = "ethers";
4253
- this.signer = signer;
4254
- }
4255
- getAddress() {
4256
- return __awaiter(this, void 0, void 0, function* () {
4257
- // Works for both ethers v5 and v6
4258
- if (typeof this.signer.getAddress === "function") {
4259
- return yield this.signer.getAddress();
4260
- }
4261
- if (this.signer.address) {
4262
- return this.signer.address;
4263
- }
4264
- throw new Error("Unable to get address from ethers signer");
4265
- });
4266
- }
4267
- signMessage(message) {
4268
- return __awaiter(this, void 0, void 0, function* () {
4269
- if (typeof this.signer.signMessage !== "function") {
4270
- throw new Error("Signer does not support signMessage");
4271
- }
4272
- return yield this.signer.signMessage(message);
4273
- });
4274
- }
4275
- getChainId() {
4276
- return __awaiter(this, void 0, void 0, function* () {
4277
- // Try ethers v6 first
4278
- if (this.signer.provider &&
4279
- typeof this.signer.provider.getNetwork === "function") {
4280
- const network = yield this.signer.provider.getNetwork();
4281
- // ethers v6 returns bigint, v5 returns number
4282
- return typeof network.chainId === "bigint"
4283
- ? Number(network.chainId)
4284
- : network.chainId;
4285
- }
4286
- // Fallback for ethers v5
4287
- if (typeof this.signer.getChainId === "function") {
4288
- return yield this.signer.getChainId();
4289
- }
4290
- // Default to mainnet if we can't determine
4291
- return 484;
4292
- });
4293
- }
4294
- }
4295
- /**
4296
- * Adapter for custom signer implementations
4297
- */
4298
- class CustomSignerAdapter {
4299
- constructor(signer) {
4300
- this.type = "custom";
4301
- this.signer = signer;
4302
- }
4303
- getAddress() {
4304
- return __awaiter(this, void 0, void 0, function* () {
4305
- if (typeof this.signer.getAddress === "function") {
4306
- return yield this.signer.getAddress();
4307
- }
4308
- if (this.signer.address) {
4309
- return this.signer.address;
4310
- }
4311
- throw new Error("Custom signer must implement getAddress() or have address property");
4312
- });
4313
- }
4314
- signMessage(message) {
4315
- return __awaiter(this, void 0, void 0, function* () {
4316
- if (typeof this.signer.signMessage !== "function") {
4317
- throw new Error("Custom signer must implement signMessage()");
4318
- }
4319
- return yield this.signer.signMessage(message);
4320
- });
4321
- }
4322
- getChainId() {
4323
- return __awaiter(this, void 0, void 0, function* () {
4324
- if (typeof this.signer.getChainId === "function") {
4325
- const chainId = yield this.signer.getChainId();
4326
- return typeof chainId === "bigint" ? Number(chainId) : chainId;
4327
- }
4328
- if (this.signer.chainId !== undefined) {
4329
- return typeof this.signer.chainId === "bigint"
4330
- ? Number(this.signer.chainId)
4331
- : this.signer.chainId;
4332
- }
4333
- // Default to mainnet
4334
- return 484;
4335
- });
4336
- }
4337
- }
4338
- /**
4339
- * Factory function to create appropriate adapter based on signer type
4340
- */
4341
- function createSignerAdapter(signer) {
4342
- // Check for viem WalletClient
4343
- if (signer.transport &&
4344
- signer.chain &&
4345
- typeof signer.signMessage === "function") {
4346
- return new ViemSignerAdapter(signer);
4347
- }
4348
- // Check for ethers signer (v5 or v6)
4349
- if (signer._isSigner ||
4350
- (signer.provider && typeof signer.signMessage === "function")) {
4351
- return new EthersSignerAdapter(signer);
4352
- }
4353
- // Try custom adapter
4354
- return new CustomSignerAdapter(signer);
4355
- }
4356
-
4357
4437
  /**
4358
4438
  * Browser localStorage adapter
4359
4439
  */
@@ -4696,7 +4776,7 @@ class Auth {
4696
4776
  this.isAuthenticated = true;
4697
4777
  this.userId = res.userId;
4698
4778
  this.jwt = res.token;
4699
- this.origin = new Origin(this.jwt, this.environment, this.viem, this.baseParentId);
4779
+ this.origin = new Origin(this.environment, this.jwt, this.viem, this.baseParentId);
4700
4780
  yield __classPrivateFieldGet(this, _Auth_storage, "f").setItem("camp-sdk:jwt", this.jwt);
4701
4781
  yield __classPrivateFieldGet(this, _Auth_storage, "f").setItem("camp-sdk:wallet-address", this.walletAddress);
4702
4782
  yield __classPrivateFieldGet(this, _Auth_storage, "f").setItem("camp-sdk:user-id", this.userId);
@@ -4758,7 +4838,7 @@ class Auth {
4758
4838
  this.isAuthenticated = true;
4759
4839
  this.userId = res.userId;
4760
4840
  this.jwt = res.token;
4761
- this.origin = new Origin(this.jwt, this.environment, this.viem, this.baseParentId);
4841
+ this.origin = new Origin(this.environment, this.jwt, this.viem, this.baseParentId);
4762
4842
  yield __classPrivateFieldGet(this, _Auth_storage, "f").setItem("camp-sdk:jwt", this.jwt);
4763
4843
  yield __classPrivateFieldGet(this, _Auth_storage, "f").setItem("camp-sdk:wallet-address", this.walletAddress);
4764
4844
  yield __classPrivateFieldGet(this, _Auth_storage, "f").setItem("camp-sdk:user-id", this.userId);
@@ -5147,7 +5227,7 @@ _Auth_triggers = new WeakMap(), _Auth_isNodeEnvironment = new WeakMap(), _Auth_s
5147
5227
  this.walletAddress = walletAddress;
5148
5228
  this.userId = userId;
5149
5229
  this.jwt = jwt;
5150
- this.origin = new Origin(this.jwt, this.environment, this.viem, this.baseParentId);
5230
+ this.origin = new Origin(this.environment, this.jwt, this.viem, this.baseParentId);
5151
5231
  this.isAuthenticated = true;
5152
5232
  if (provider) {
5153
5233
  this.setProvider({
@@ -5632,30 +5712,6 @@ const useToast = () => {
5632
5712
  return context;
5633
5713
  };
5634
5714
 
5635
- const OriginContext = createContext({
5636
- statsQuery: null,
5637
- uploadsQuery: null,
5638
- });
5639
- const OriginProvider = ({ children }) => {
5640
- const { authenticated } = useAuthState();
5641
- const { auth } = useContext(CampContext);
5642
- if (!auth && typeof window !== "undefined") {
5643
- throw new Error("Auth instance is not available");
5644
- }
5645
- const statsQuery = useQuery({
5646
- queryKey: ["origin-stats", authenticated],
5647
- queryFn: () => { var _a, _b; return (_b = (_a = auth === null || auth === void 0 ? void 0 : auth.origin) === null || _a === void 0 ? void 0 : _a.getOriginUsage()) !== null && _b !== void 0 ? _b : Promise.resolve(null); },
5648
- });
5649
- const uploadsQuery = useQuery({
5650
- queryKey: ["origin-uploads", authenticated],
5651
- queryFn: () => { var _a, _b; return (_b = (_a = auth === null || auth === void 0 ? void 0 : auth.origin) === null || _a === void 0 ? void 0 : _a.getOriginUploads()) !== null && _b !== void 0 ? _b : Promise.resolve(null); },
5652
- });
5653
- return (React.createElement(OriginContext.Provider, { value: {
5654
- statsQuery: statsQuery,
5655
- uploadsQuery: uploadsQuery,
5656
- } }, children));
5657
- };
5658
-
5659
5715
  const CampContext = createContext({
5660
5716
  clientId: null,
5661
5717
  auth: null,
@@ -5697,9 +5753,8 @@ const CampProvider = ({ clientId, redirectUri, children, environment = "DEVELOPM
5697
5753
  environment: ENVIRONMENTS[environment],
5698
5754
  } },
5699
5755
  React.createElement(SocialsProvider, null,
5700
- React.createElement(OriginProvider, null,
5701
- React.createElement(ToastProvider, null,
5702
- React.createElement(ModalProvider, null, children))))));
5756
+ React.createElement(ToastProvider, null,
5757
+ React.createElement(ModalProvider, null, children)))));
5703
5758
  };
5704
5759
 
5705
5760
  const getWalletConnectProvider = (projectId, chain) => __awaiter(void 0, void 0, void 0, function* () {
@@ -5909,8 +5964,6 @@ const FancyInput = ({ value, onChange, step, placeholder, type = "text", icon, l
5909
5964
  */
5910
5965
  const FileUpload = ({ onFileUpload, accept, maxFileSize, }) => {
5911
5966
  const auth = useAuth();
5912
- const { uploads } = useOrigin();
5913
- const { refetch } = uploads;
5914
5967
  const [isDragging, setIsDragging] = useState(false);
5915
5968
  const [selectedFile, setSelectedFile] = useState(null);
5916
5969
  const [isUploading, setIsUploading] = useState(false);
@@ -5953,7 +6006,6 @@ const FileUpload = ({ onFileUpload, accept, maxFileSize, }) => {
5953
6006
  onFileUpload([selectedFile]);
5954
6007
  }
5955
6008
  addToast(`File minted successfully. Token ID: ${res}`, "success", 5000);
5956
- refetch();
5957
6009
  }
5958
6010
  catch (error) {
5959
6011
  if (error.toString().includes("User rejected")) {
@@ -6690,61 +6742,7 @@ const LinkingModal = () => {
6690
6742
  * @returns { JSX.Element } The OriginSection component.
6691
6743
  */
6692
6744
  const OriginSection = () => {
6693
- // const { stats, uploads } = useOrigin();
6694
- // const [royaltiesToClaim, setRoyaltiesToClaim] = useState<null | string>(null);
6695
- // const [isClaiming, setIsClaiming] = useState(false);
6696
- const { environment, auth } = useContext(CampContext);
6697
- useToast();
6698
- // const [uploadedImages, setUploadedImages] = useState(0);
6699
- // const [uploadedVideos, setUploadedVideos] = useState(0);
6700
- // const [uploadedAudio, setUploadedAudio] = useState(0);
6701
- // const [uploadedText, setUploadedText] = useState(0);
6702
- // useEffect(() => {
6703
- // const fetchRoyalties = async () => {
6704
- // if (!auth || !auth.origin) return;
6705
- // const royalties = await auth?.origin.getRoyalties();
6706
- // const bal = formatEther(royalties.balance);
6707
- // setRoyaltiesToClaim(bal !== "0" ? formatCampAmount(Number(bal)) : null);
6708
- // };
6709
- // fetchRoyalties();
6710
- // }, [auth]);
6711
- // const handleClaimRoyalties = async () => {
6712
- // if (!auth || !auth.origin || !royaltiesToClaim) return;
6713
- // setIsClaiming(true);
6714
- // try {
6715
- // await auth.origin.claimRoyalties();
6716
- // setRoyaltiesToClaim(null);
6717
- // toast("Royalties claimed successfully!", "success", 5000);
6718
- // } catch (error) {
6719
- // console.error("Error claiming royalties:", error);
6720
- // toast("Error claiming royalties. Please try again.", "error", 5000);
6721
- // } finally {
6722
- // setIsClaiming(false);
6723
- // }
6724
- // };
6725
- // useEffect(() => {
6726
- // if (uploads.data) {
6727
- // let imagesCount = 0;
6728
- // let videosCount = 0;
6729
- // let audioCount = 0;
6730
- // let textCount = 0;
6731
- // uploads.data.forEach((upload) => {
6732
- // if (upload.type.startsWith("image")) {
6733
- // imagesCount++;
6734
- // } else if (upload.type.startsWith("video")) {
6735
- // videosCount++;
6736
- // } else if (upload.type.startsWith("audio")) {
6737
- // audioCount++;
6738
- // } else if (upload.type.startsWith("text")) {
6739
- // textCount++;
6740
- // }
6741
- // });
6742
- // setUploadedImages(imagesCount);
6743
- // setUploadedVideos(videosCount);
6744
- // setUploadedAudio(audioCount);
6745
- // setUploadedText(textCount);
6746
- // }
6747
- // }, [uploads.data]);
6745
+ const { environment } = useContext(CampContext);
6748
6746
  return (React.createElement("div", { className: styles["origin-wrapper"] },
6749
6747
  React.createElement("div", { className: styles["origin-section"] },
6750
6748
  React.createElement(Tooltip, { content: environment.NAME === "PRODUCTION"
@@ -6900,36 +6898,20 @@ const SocialsTab = ({ connectedSocials, notConnectedSocials, refetch, isLoading,
6900
6898
  connectedSocials.length === 0 && (React.createElement("span", { className: styles["no-socials"] }, "You have no socials linked.")))))));
6901
6899
  };
6902
6900
  const ImagesTab = () => {
6903
- const { uploads } = useOrigin();
6904
- const { isLoading } = uploads;
6905
6901
  return (React.createElement(TabContent, { requiresProvider: true, className: styles["ip-tab-container"] },
6906
- React.createElement(FileUpload, { accept: constants.SUPPORTED_IMAGE_FORMATS.join(","), maxFileSize: 1.049e7 }),
6907
- isLoading ? (React.createElement("div", { className: styles["ip-tab-content"] },
6908
- React.createElement("div", { className: styles.spinner, style: { marginRight: "auto" } }))) : null));
6902
+ React.createElement(FileUpload, { accept: constants.SUPPORTED_IMAGE_FORMATS.join(","), maxFileSize: 1.049e7 })));
6909
6903
  };
6910
6904
  const AudioTab = () => {
6911
- const { uploads } = useOrigin();
6912
- const { isLoading } = uploads;
6913
6905
  return (React.createElement(TabContent, { requiresProvider: true, className: styles["ip-tab-container"] },
6914
- React.createElement(FileUpload, { accept: constants.SUPPORTED_AUDIO_FORMATS.join(","), maxFileSize: 1.573e7 }),
6915
- isLoading ? (React.createElement("div", { className: styles["ip-tab-content"] },
6916
- React.createElement("div", { className: styles.spinner, style: { marginRight: "auto" } }))) : null));
6906
+ React.createElement(FileUpload, { accept: constants.SUPPORTED_AUDIO_FORMATS.join(","), maxFileSize: 1.573e7 })));
6917
6907
  };
6918
6908
  const VideosTab = () => {
6919
- const { uploads } = useOrigin();
6920
- const { isLoading } = uploads;
6921
6909
  return (React.createElement(TabContent, { requiresProvider: true, className: styles["ip-tab-container"] },
6922
- React.createElement(FileUpload, { accept: constants.SUPPORTED_VIDEO_FORMATS.join(","), maxFileSize: 2.097e7 }),
6923
- isLoading ? (React.createElement("div", { className: styles["ip-tab-content"] },
6924
- React.createElement("div", { className: styles.spinner, style: { marginRight: "auto" } }))) : null));
6910
+ React.createElement(FileUpload, { accept: constants.SUPPORTED_VIDEO_FORMATS.join(","), maxFileSize: 2.097e7 })));
6925
6911
  };
6926
6912
  const TextTab = () => {
6927
- const { uploads } = useOrigin();
6928
- const { isLoading } = uploads;
6929
6913
  return (React.createElement(TabContent, { requiresProvider: true, className: styles["ip-tab-container"] },
6930
- React.createElement(FileUpload, { accept: constants.SUPPORTED_TEXT_FORMATS.join(","), maxFileSize: 1.049e7 }),
6931
- isLoading ? (React.createElement("div", { className: styles["ip-tab-content"] },
6932
- React.createElement("div", { className: styles.spinner, style: { marginRight: "auto" } }))) : null));
6914
+ React.createElement(FileUpload, { accept: constants.SUPPORTED_TEXT_FORMATS.join(","), maxFileSize: 1.049e7 })));
6933
6915
  };
6934
6916
 
6935
6917
  const isBrowser = typeof window !== "undefined";
@@ -7195,26 +7177,5 @@ const useSocials = () => {
7195
7177
  const socials = (query === null || query === void 0 ? void 0 : query.data) || {};
7196
7178
  return Object.assign(Object.assign({}, query), { socials });
7197
7179
  };
7198
- /**
7199
- * Fetches the Origin usage data and uploads data.
7200
- * @returns { usage: { data: any, isError: boolean, isLoading: boolean, refetch: () => void }, uploads: { data: any, isError: boolean, isLoading: boolean, refetch: () => void } } The Origin usage data and uploads data.
7201
- */
7202
- const useOrigin = () => {
7203
- const { statsQuery, uploadsQuery } = useContext(OriginContext);
7204
- return {
7205
- stats: {
7206
- data: statsQuery === null || statsQuery === void 0 ? void 0 : statsQuery.data,
7207
- isError: statsQuery === null || statsQuery === void 0 ? void 0 : statsQuery.isError,
7208
- isLoading: statsQuery === null || statsQuery === void 0 ? void 0 : statsQuery.isLoading,
7209
- refetch: statsQuery === null || statsQuery === void 0 ? void 0 : statsQuery.refetch,
7210
- },
7211
- uploads: {
7212
- data: (uploadsQuery === null || uploadsQuery === void 0 ? void 0 : uploadsQuery.data) || [],
7213
- isError: uploadsQuery === null || uploadsQuery === void 0 ? void 0 : uploadsQuery.isError,
7214
- isLoading: uploadsQuery === null || uploadsQuery === void 0 ? void 0 : uploadsQuery.isLoading,
7215
- refetch: uploadsQuery === null || uploadsQuery === void 0 ? void 0 : uploadsQuery.refetch,
7216
- },
7217
- };
7218
- };
7219
7180
 
7220
- export { StandaloneCampButton as CampButton, CampContext, CampModal, CampProvider, LinkButton, ModalContext, MyCampModal, useAuth, useAuthState, useConnect, useLinkModal, useLinkSocials, useModal, useOrigin, useProvider, useProviders, useSocials, useViem };
7181
+ export { StandaloneCampButton as CampButton, CampContext, CampModal, CampProvider, LinkButton, ModalContext, MyCampModal, useAuth, useAuthState, useConnect, useLinkModal, useLinkSocials, useModal, useProvider, useProviders, useSocials, useViem };