@campnetwork/origin 1.2.2 → 1.2.3

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.
@@ -168,6 +168,52 @@ declare function hasAccess(this: Origin, user: Address, tokenId: bigint): Promis
168
168
 
169
169
  declare function subscriptionExpiry(this: Origin, tokenId: bigint, user: Address): Promise<bigint>;
170
170
 
171
+ /**
172
+ * Response from getDataWithX402 when payment is required
173
+ */
174
+ interface X402Response {
175
+ error: string;
176
+ marketplaceAction?: {
177
+ kind: string;
178
+ contract: Address;
179
+ network: string;
180
+ chainId: number;
181
+ method: string;
182
+ payer: Address;
183
+ payTo: Address;
184
+ tokenId: string;
185
+ duration: number;
186
+ asset: Address;
187
+ amount: string;
188
+ amountFormatted: string;
189
+ };
190
+ }
191
+ interface TransactionResult {
192
+ txHash: string;
193
+ receipt?: any;
194
+ }
195
+ /**
196
+ * Settles an X402 payment response by purchasing access if needed.
197
+ * This method checks if the user already has access to the item, and if not,
198
+ * it calls buyAccess with the parameters from the X402 response.
199
+ * Supports viem WalletClient, ethers Signer, and custom signer implementations.
200
+ *
201
+ * @param x402Response - The response from getDataWithX402 containing payment details.
202
+ * @param signer - Optional signer object used to interact with the blockchain. If not provided, uses the connected wallet client.
203
+ * @returns A promise that resolves with the transaction hash and receipt, or null if access already exists.
204
+ * @throws {Error} If the response doesn't contain marketplace action or if the method is not buyAccess.
205
+ */
206
+ declare function settleX402(this: Origin, x402Response: X402Response, signer?: any): Promise<TransactionResult | null>;
207
+
208
+ /**
209
+ * Fetch data with X402 payment handling.
210
+ * @param {bigint} tokenId The token ID to fetch data for.
211
+ * @param {any} [signer] Optional signer object for signing the X402 intent.
212
+ * @returns {Promise<any>} A promise that resolves with the fetched data.
213
+ * @throws {Error} Throws an error if the data cannot be fetched or if no signer/wallet client is provided.
214
+ */
215
+ declare function getDataWithX402(this: Origin, tokenId: bigint, signer?: any): Promise<any>;
216
+
171
217
  interface RoyaltyInfo {
172
218
  tokenBoundAccount: Address;
173
219
  balance: bigint;
@@ -203,6 +249,8 @@ declare class Origin {
203
249
  buyAccess: typeof buyAccess;
204
250
  hasAccess: typeof hasAccess;
205
251
  subscriptionExpiry: typeof subscriptionExpiry;
252
+ settleX402: typeof settleX402;
253
+ getDataWithX402: typeof getDataWithX402;
206
254
  private jwt?;
207
255
  environment: Environment;
208
256
  private viemClient?;
@@ -238,14 +286,6 @@ declare class Origin {
238
286
  * @throws {Error} Throws an error if the data cannot be fetched.
239
287
  */
240
288
  getData(tokenId: bigint): Promise<any>;
241
- /**
242
- * Fetch data with X402 payment handling.
243
- * @param {bigint} tokenId The token ID to fetch data for.
244
- * @param {any} [signer] Optional signer object for signing the X402 intent.
245
- * @returns {Promise<any>} A promise that resolves with the fetched data.
246
- * @throws {Error} Throws an error if the data cannot be fetched or if no signer/wallet client is provided.
247
- */
248
- getDataWithX402(tokenId: bigint, signer?: any): Promise<any>;
249
289
  /**
250
290
  * Get the Token Bound Account (TBA) address for a specific token ID.
251
291
  * @param {bigint} tokenId - The token ID to get the TBA address for.
@@ -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, checksumAddress, zeroAddress, formatEther, formatUnits, encodeFunctionData, keccak256, toBytes, parseEther } from 'viem';
3
+ import { custom, createWalletClient, createPublicClient, http, encodeFunctionData, checksumAddress, zeroAddress, keccak256, toBytes, erc20Abi, getAbiItem, formatEther, formatUnits, parseEther } from 'viem';
4
4
  import { toAccount } from 'viem/accounts';
5
5
  import { createSiweMessage } from 'viem/siwe';
6
6
  import axios from 'axios';
@@ -3456,88 +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
- * Enum representing the status of data in the system.
3461
- * * - ACTIVE: The data is currently active and available.
3462
- * * - PENDING_DELETE: The data is scheduled for deletion but not yet removed.
3463
- * * - DELETED: The data has been deleted and is no longer available.
3464
- */
3465
- var DataStatus;
3466
- (function (DataStatus) {
3467
- DataStatus[DataStatus["ACTIVE"] = 0] = "ACTIVE";
3468
- DataStatus[DataStatus["PENDING_DELETE"] = 1] = "PENDING_DELETE";
3469
- DataStatus[DataStatus["DELETED"] = 2] = "DELETED";
3470
- })(DataStatus || (DataStatus = {}));
3471
- /**
3472
- * Creates license terms for a digital asset.
3473
- * @param price The price of the asset in wei.
3474
- * @param duration The duration of the license in seconds.
3475
- * @param royaltyBps The royalty percentage in basis points (0-10000).
3476
- * @param paymentToken The address of the payment token (ERC20 / address(0) for native currency).
3477
- * @returns The created license terms.
3478
- */
3479
- const createLicenseTerms = (price, duration, royaltyBps, paymentToken) => {
3480
- if (royaltyBps < constants.MIN_ROYALTY_BPS ||
3481
- royaltyBps > constants.MAX_ROYALTY_BPS) {
3482
- throw new Error(`Royalty basis points must be between ${constants.MIN_ROYALTY_BPS} and ${constants.MAX_ROYALTY_BPS}`);
3483
- }
3484
- if (duration < constants.MIN_LICENSE_DURATION ||
3485
- duration > constants.MAX_LICENSE_DURATION) {
3486
- throw new Error(`Duration must be between ${constants.MIN_LICENSE_DURATION} and ${constants.MAX_LICENSE_DURATION} seconds`);
3487
- }
3488
- if (price < constants.MIN_PRICE) {
3489
- throw new Error(`Price must be at least ${constants.MIN_PRICE} wei`);
3490
- }
3491
- return {
3492
- price,
3493
- duration,
3494
- royaltyBps,
3495
- paymentToken,
3496
- };
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
3459
  /**
3542
3460
  * Adapter for viem WalletClient
3543
3461
  */
@@ -3711,7 +3629,316 @@ function createSignerAdapter(signer) {
3711
3629
  return new CustomSignerAdapter(signer);
3712
3630
  }
3713
3631
 
3714
- var _Origin_instances, _Origin_generateURL, _Origin_setOriginStatus, _Origin_uploadFile, _Origin_waitForTxReceipt, _Origin_ensureChainId, _Origin_getCurrentAccount, _Origin_makeX402IntentDomain, _Origin_buildX402Payload, _Origin_resolveWalletAddress;
3632
+ /**
3633
+ * Settles an X402 payment response by purchasing access if needed.
3634
+ * This method checks if the user already has access to the item, and if not,
3635
+ * it calls buyAccess with the parameters from the X402 response.
3636
+ * Supports viem WalletClient, ethers Signer, and custom signer implementations.
3637
+ *
3638
+ * @param x402Response - The response from getDataWithX402 containing payment details.
3639
+ * @param signer - Optional signer object used to interact with the blockchain. If not provided, uses the connected wallet client.
3640
+ * @returns A promise that resolves with the transaction hash and receipt, or null if access already exists.
3641
+ * @throws {Error} If the response doesn't contain marketplace action or if the method is not buyAccess.
3642
+ */
3643
+ function settleX402(x402Response, signer) {
3644
+ return __awaiter(this, void 0, void 0, function* () {
3645
+ if (!x402Response.marketplaceAction) {
3646
+ throw new Error("No marketplace action found in X402 response");
3647
+ }
3648
+ const { marketplaceAction } = x402Response;
3649
+ if (marketplaceAction.method !== "buyAccess") {
3650
+ throw new Error(`Unsupported marketplace action method: ${marketplaceAction.method}`);
3651
+ }
3652
+ const tokenId = BigInt(marketplaceAction.tokenId);
3653
+ const payerAddress = marketplaceAction.payer;
3654
+ const alreadyHasAccess = yield this.hasAccess(payerAddress, tokenId);
3655
+ if (alreadyHasAccess) {
3656
+ console.log("User already has access to this item");
3657
+ return null;
3658
+ }
3659
+ const expectedPrice = BigInt(marketplaceAction.amount);
3660
+ const expectedDuration = BigInt(marketplaceAction.duration);
3661
+ const expectedPaymentToken = marketplaceAction.asset;
3662
+ const isNativeToken = expectedPaymentToken === "0x0000000000000000000000000000000000000000";
3663
+ const value = isNativeToken ? expectedPrice : BigInt(0);
3664
+ if (signer) {
3665
+ const signerAdapter = createSignerAdapter(signer);
3666
+ const marketplaceAddress = this.environment
3667
+ .MARKETPLACE_CONTRACT_ADDRESS;
3668
+ const abi = this.environment.MARKETPLACE_ABI;
3669
+ const data = encodeFunctionData({
3670
+ abi,
3671
+ functionName: "buyAccess",
3672
+ args: [
3673
+ payerAddress,
3674
+ tokenId,
3675
+ expectedPrice,
3676
+ expectedDuration,
3677
+ expectedPaymentToken,
3678
+ ],
3679
+ });
3680
+ if (signerAdapter.type === "viem") {
3681
+ const viemSigner = signerAdapter.signer;
3682
+ const txHash = yield viemSigner.sendTransaction({
3683
+ to: marketplaceAddress,
3684
+ data,
3685
+ value,
3686
+ account: (yield signerAdapter.getAddress()),
3687
+ });
3688
+ const receipt = yield viemSigner.waitForTransactionReceipt({
3689
+ hash: txHash,
3690
+ });
3691
+ return { txHash, receipt };
3692
+ }
3693
+ else if (signerAdapter.type === "ethers") {
3694
+ const ethersSigner = signerAdapter.signer;
3695
+ const tx = yield ethersSigner.sendTransaction({
3696
+ to: marketplaceAddress,
3697
+ data,
3698
+ value: value.toString(),
3699
+ });
3700
+ const receipt = yield tx.wait();
3701
+ return { txHash: tx.hash, receipt };
3702
+ }
3703
+ else {
3704
+ const customSigner = signerAdapter.signer;
3705
+ if (typeof customSigner.sendTransaction !== "function") {
3706
+ throw new Error("Custom signer must implement sendTransaction() method");
3707
+ }
3708
+ const tx = yield customSigner.sendTransaction({
3709
+ to: marketplaceAddress,
3710
+ data,
3711
+ value: value.toString(),
3712
+ });
3713
+ if (tx.wait && typeof tx.wait === "function") {
3714
+ const receipt = yield tx.wait();
3715
+ return { txHash: tx.hash, receipt };
3716
+ }
3717
+ return { txHash: tx.hash || tx };
3718
+ }
3719
+ }
3720
+ if (!this.viemClient) {
3721
+ throw new Error("No signer or wallet client provided for settleX402");
3722
+ }
3723
+ return yield this.buyAccess(payerAddress, tokenId, expectedPrice, expectedDuration, expectedPaymentToken, isNativeToken ? value : undefined);
3724
+ });
3725
+ }
3726
+
3727
+ /**
3728
+ * Enum representing the status of data in the system.
3729
+ * * - ACTIVE: The data is currently active and available.
3730
+ * * - PENDING_DELETE: The data is scheduled for deletion but not yet removed.
3731
+ * * - DELETED: The data has been deleted and is no longer available.
3732
+ */
3733
+ var DataStatus;
3734
+ (function (DataStatus) {
3735
+ DataStatus[DataStatus["ACTIVE"] = 0] = "ACTIVE";
3736
+ DataStatus[DataStatus["PENDING_DELETE"] = 1] = "PENDING_DELETE";
3737
+ DataStatus[DataStatus["DELETED"] = 2] = "DELETED";
3738
+ })(DataStatus || (DataStatus = {}));
3739
+ /**
3740
+ * Creates license terms for a digital asset.
3741
+ * @param price The price of the asset in wei.
3742
+ * @param duration The duration of the license in seconds.
3743
+ * @param royaltyBps The royalty percentage in basis points (0-10000).
3744
+ * @param paymentToken The address of the payment token (ERC20 / address(0) for native currency).
3745
+ * @returns The created license terms.
3746
+ */
3747
+ const createLicenseTerms = (price, duration, royaltyBps, paymentToken) => {
3748
+ if (royaltyBps < constants.MIN_ROYALTY_BPS ||
3749
+ royaltyBps > constants.MAX_ROYALTY_BPS) {
3750
+ throw new Error(`Royalty basis points must be between ${constants.MIN_ROYALTY_BPS} and ${constants.MAX_ROYALTY_BPS}`);
3751
+ }
3752
+ if (duration < constants.MIN_LICENSE_DURATION ||
3753
+ duration > constants.MAX_LICENSE_DURATION) {
3754
+ throw new Error(`Duration must be between ${constants.MIN_LICENSE_DURATION} and ${constants.MAX_LICENSE_DURATION} seconds`);
3755
+ }
3756
+ if (price < constants.MIN_PRICE) {
3757
+ throw new Error(`Price must be at least ${constants.MIN_PRICE} wei`);
3758
+ }
3759
+ return {
3760
+ price,
3761
+ duration,
3762
+ royaltyBps,
3763
+ paymentToken,
3764
+ };
3765
+ };
3766
+ /**
3767
+ * Defines the EIP-712 typed data structure for X402 Intent signatures.
3768
+ */
3769
+ const X402_INTENT_TYPES = {
3770
+ X402Intent: [
3771
+ { name: "payer", type: "address" },
3772
+ { name: "asset", type: "address" },
3773
+ { name: "amount", type: "uint256" },
3774
+ { name: "httpMethod", type: "string" },
3775
+ { name: "payTo", type: "address" },
3776
+ { name: "tokenId", type: "uint256" },
3777
+ { name: "duration", type: "uint32" },
3778
+ { name: "expiresAt", type: "uint256" },
3779
+ { name: "nonce", type: "bytes32" },
3780
+ ],
3781
+ };
3782
+
3783
+ /**
3784
+ * Fetch data with X402 payment handling.
3785
+ * @param {bigint} tokenId The token ID to fetch data for.
3786
+ * @param {any} [signer] Optional signer object for signing the X402 intent.
3787
+ * @returns {Promise<any>} A promise that resolves with the fetched data.
3788
+ * @throws {Error} Throws an error if the data cannot be fetched or if no signer/wallet client is provided.
3789
+ */
3790
+ function getDataWithX402(tokenId, signer) {
3791
+ return __awaiter(this, void 0, void 0, function* () {
3792
+ var _a;
3793
+ const viemClient = this.viemClient;
3794
+ if (!signer && !viemClient) {
3795
+ throw new Error("No signer or wallet client provided for X402 intent.");
3796
+ }
3797
+ const initialResponse = yield fetch(`${this.environment.AUTH_HUB_BASE_API}/${this.environment.AUTH_ENDPOINT}/origin/data/${tokenId}`, {
3798
+ method: "GET",
3799
+ });
3800
+ if (initialResponse.status !== 402) {
3801
+ if (!initialResponse.ok) {
3802
+ throw new Error("Failed to fetch data");
3803
+ }
3804
+ return initialResponse.json();
3805
+ }
3806
+ const sig = viemClient || createSignerAdapter(signer);
3807
+ const walletAddress = viemClient
3808
+ ? yield getCurrentAccount.call(this)
3809
+ : yield sig.getAddress();
3810
+ const intentData = yield initialResponse.json();
3811
+ if (intentData.error) {
3812
+ throw new Error(intentData.error);
3813
+ }
3814
+ const requirements = intentData.accepts[0];
3815
+ const x402Payload = yield buildX402Payload.call(this, requirements, checksumAddress(walletAddress), sig);
3816
+ const header = btoa(JSON.stringify(x402Payload));
3817
+ const retryResponse = yield fetch(`${this.environment.AUTH_HUB_BASE_API}/${this.environment.AUTH_ENDPOINT}/origin/data/${tokenId}`, {
3818
+ method: "GET",
3819
+ headers: {
3820
+ "Content-Type": "application/json",
3821
+ "X-PAYMENT": header,
3822
+ },
3823
+ });
3824
+ if (retryResponse.status === 402) {
3825
+ // subscription required
3826
+ return retryResponse.json();
3827
+ }
3828
+ if (!retryResponse.ok) {
3829
+ throw new Error("Failed to fetch data after X402 payment");
3830
+ }
3831
+ const res = yield retryResponse.json();
3832
+ return {
3833
+ error: null,
3834
+ data: (_a = res.data) !== null && _a !== void 0 ? _a : res,
3835
+ };
3836
+ });
3837
+ }
3838
+ /**
3839
+ * Build the X402 payment payload.
3840
+ * @private
3841
+ */
3842
+ function buildX402Payload(requirements, payer, signer) {
3843
+ return __awaiter(this, void 0, void 0, function* () {
3844
+ const asset = requirements.asset === "native" ? zeroAddress : requirements.asset;
3845
+ const amount = BigInt(requirements.maxAmountRequired || 0);
3846
+ const duration = requirements.extra.duration;
3847
+ const domain = makeX402IntentDomain.call(this);
3848
+ const types = X402_INTENT_TYPES;
3849
+ const nonce = crypto.randomUUID();
3850
+ const nonceBytes32 = keccak256(toBytes(nonce));
3851
+ const payment = {
3852
+ payer: payer,
3853
+ asset: asset,
3854
+ amount: amount.toString(),
3855
+ httpMethod: "GET",
3856
+ payTo: checksumAddress(this.environment.MARKETPLACE_CONTRACT_ADDRESS),
3857
+ tokenId: requirements.extra.tokenId,
3858
+ duration: duration,
3859
+ expiresAt: Math.floor(Date.now() / 1000) + requirements.maxTimeoutSeconds,
3860
+ nonce: nonceBytes32,
3861
+ };
3862
+ const signerAdapter = createSignerAdapter(signer);
3863
+ const signature = yield signerAdapter.signTypedData(domain, types, payment);
3864
+ const x402Payload = {
3865
+ x402Version: 1,
3866
+ scheme: "exact",
3867
+ network: requirements.network,
3868
+ payload: Object.assign(Object.assign({}, payment), { sigType: "eip712", signature: signature, license: {
3869
+ tokenId: requirements.extra.tokenId,
3870
+ duration: duration,
3871
+ } }),
3872
+ };
3873
+ return x402Payload;
3874
+ });
3875
+ }
3876
+ /**
3877
+ * Create the X402 Intent domain for EIP-712 signing.
3878
+ * @private
3879
+ */
3880
+ function makeX402IntentDomain() {
3881
+ return {
3882
+ name: "Origin X402 Intent",
3883
+ version: "1",
3884
+ chainId: this.environment.CHAIN.id,
3885
+ verifyingContract: this.environment
3886
+ .MARKETPLACE_CONTRACT_ADDRESS,
3887
+ };
3888
+ }
3889
+ /**
3890
+ * Get the current account address.
3891
+ * @private
3892
+ */
3893
+ function getCurrentAccount() {
3894
+ return __awaiter(this, void 0, void 0, function* () {
3895
+ const viemClient = this.viemClient;
3896
+ if (!viemClient) {
3897
+ throw new Error("WalletClient not connected. Please connect a wallet.");
3898
+ }
3899
+ // If account is already set on the client, return it directly
3900
+ if (viemClient.account) {
3901
+ return viemClient.account.address;
3902
+ }
3903
+ // Otherwise request accounts (browser wallet flow)
3904
+ const accounts = yield viemClient.request({
3905
+ method: "eth_requestAccounts",
3906
+ params: [],
3907
+ });
3908
+ if (!accounts || accounts.length === 0) {
3909
+ throw new Error("No accounts found in connected wallet.");
3910
+ }
3911
+ return accounts[0];
3912
+ });
3913
+ }
3914
+
3915
+ /**
3916
+ * Approves a spender to spend a specified amount of tokens on behalf of the owner.
3917
+ * If the current allowance is less than the specified amount, it will perform the approval.
3918
+ * @param {ApproveParams} params - The parameters for the approval.
3919
+ */
3920
+ function approveIfNeeded(_a) {
3921
+ return __awaiter(this, arguments, void 0, function* ({ walletClient, publicClient, tokenAddress, owner, spender, amount, }) {
3922
+ const allowance = yield publicClient.readContract({
3923
+ address: tokenAddress,
3924
+ abi: erc20Abi,
3925
+ functionName: "allowance",
3926
+ args: [owner, spender],
3927
+ });
3928
+ if (allowance < amount) {
3929
+ yield walletClient.writeContract({
3930
+ address: tokenAddress,
3931
+ account: owner,
3932
+ abi: erc20Abi,
3933
+ functionName: "approve",
3934
+ args: [spender, amount],
3935
+ chain: testnet,
3936
+ });
3937
+ }
3938
+ });
3939
+ }
3940
+
3941
+ var _Origin_instances, _Origin_generateURL, _Origin_setOriginStatus, _Origin_uploadFile, _Origin_waitForTxReceipt, _Origin_ensureChainId, _Origin_getCurrentAccount, _Origin_resolveWalletAddress;
3715
3942
  /**
3716
3943
  * The Origin class
3717
3944
  * Handles the upload of files to Origin, as well as querying the user's stats
@@ -3749,6 +3976,8 @@ class Origin {
3749
3976
  this.buyAccess = buyAccess.bind(this);
3750
3977
  this.hasAccess = hasAccess.bind(this);
3751
3978
  this.subscriptionExpiry = subscriptionExpiry.bind(this);
3979
+ this.settleX402 = settleX402.bind(this);
3980
+ this.getDataWithX402 = getDataWithX402.bind(this);
3752
3981
  }
3753
3982
  getJwt() {
3754
3983
  return this.jwt;
@@ -3980,60 +4209,6 @@ class Origin {
3980
4209
  return response.json();
3981
4210
  });
3982
4211
  }
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
- }
4037
4212
  /**
4038
4213
  * Get the Token Bound Account (TBA) address for a specific token ID.
4039
4214
  * @param {bigint} tokenId - The token ID to get the TBA address for.
@@ -4369,47 +4544,6 @@ _Origin_instances = new WeakSet(), _Origin_generateURL = function _Origin_genera
4369
4544
  }
4370
4545
  return accounts[0];
4371
4546
  });
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
- });
4413
4547
  }, _Origin_resolveWalletAddress = function _Origin_resolveWalletAddress(owner) {
4414
4548
  return __awaiter(this, void 0, void 0, function* () {
4415
4549
  if (owner) {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@campnetwork/origin",
3
- "version": "1.2.2",
3
+ "version": "1.2.3",
4
4
  "main": "dist/core.cjs",
5
5
  "exports": {
6
6
  ".": {