@campnetwork/origin 1.3.0-alpha.3 → 1.3.0-alpha.6
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.
- package/dist/core.cjs +100 -68
- package/dist/core.d.ts +38 -3
- package/dist/core.esm.d.ts +38 -3
- package/dist/core.esm.js +92 -60
- package/dist/react/index.esm.d.ts +38 -3
- package/dist/react/index.esm.js +155 -8
- package/package.json +1 -1
package/dist/core.esm.js
CHANGED
|
@@ -251,11 +251,12 @@ if(e.account)return e.account.address;
|
|
|
251
251
|
const t=yield e.request({method:"eth_requestAccounts",params:[]});if(!t||0===t.length)throw new x("No accounts found in connected wallet. Please unlock your wallet or add an account.");return t[0]}))}
|
|
252
252
|
/**
|
|
253
253
|
* Raises a dispute against an IP NFT.
|
|
254
|
-
*
|
|
254
|
+
* Automatically handles token approval for ERC20 bonds or native token value.
|
|
255
|
+
* Includes the protocol dispute fee in the transaction.
|
|
255
256
|
*
|
|
256
257
|
* @param targetIpId The token ID of the IP NFT to dispute.
|
|
257
258
|
* @param evidenceHash The hash of evidence supporting the dispute.
|
|
258
|
-
* @param disputeTag A tag identifying the type of dispute.
|
|
259
|
+
* @param disputeTag A tag identifying the type of dispute (bytes32).
|
|
259
260
|
* @returns A promise that resolves with the transaction result including the dispute ID.
|
|
260
261
|
*
|
|
261
262
|
* @example
|
|
@@ -263,10 +264,13 @@ const t=yield e.request({method:"eth_requestAccounts",params:[]});if(!t||0===t.l
|
|
|
263
264
|
* const result = await origin.raiseDispute(
|
|
264
265
|
* 1n,
|
|
265
266
|
* "0x1234...", // evidence hash
|
|
266
|
-
* "
|
|
267
|
+
* "0x0100000000000000000000000000000000000000000000000000000000000000" // dispute tag (bytes32)
|
|
267
268
|
* );
|
|
268
269
|
* ```
|
|
269
|
-
*/function Fe(e,t,n){return f(this,void 0,void 0,(function*(){
|
|
270
|
+
*/function Fe(e,t,n){return f(this,void 0,void 0,(function*(){const i=U(),a=this.environment.DISPUTE_CONTRACT_ADDRESS,s=this.environment.DISPUTE_ABI,[o,d,u]=yield Promise.all([i.readContract({address:a,abi:s,functionName:"disputeBond"}),i.readContract({address:a,abi:s,functionName:"protocolDisputeFee"}),i.readContract({address:a,abi:s,functionName:"disputeToken"})]),p=u===r,l=o+d;
|
|
271
|
+
// Call the raiseDispute contract method
|
|
272
|
+
// Pass the total (bond + protocol fee) as msg.value if using native token
|
|
273
|
+
return p||(yield this.approveERC20IfNeeded(u,a,l)),this.callContractMethod(a,s,"raiseDispute",[e,t,n],{waitForReceipt:!0,value:p?l:void 0})}))}
|
|
270
274
|
/**
|
|
271
275
|
* Raises a dispute with automatic evidence upload to IPFS.
|
|
272
276
|
* Uploads evidence JSON to IPFS, hashes the CID to bytes32 for on-chain storage,
|
|
@@ -379,7 +383,9 @@ const t=yield e.request({method:"eth_requestAccounts",params:[]});if(!t||0===t.l
|
|
|
379
383
|
* console.log(`Yes votes: ${dispute.yesVotes}`);
|
|
380
384
|
* console.log(`No votes: ${dispute.noVotes}`);
|
|
381
385
|
* ```
|
|
382
|
-
*/function Le(e){return f(this,void 0,void 0,(function*(){
|
|
386
|
+
*/function Le(e){return f(this,void 0,void 0,(function*(){const t=yield this.callContractMethod(this.environment.DISPUTE_CONTRACT_ADDRESS,this.environment.DISPUTE_ABI,"disputes",[e]),[n,i,a,s,r,o,d,u,p,l,y,c]=t;
|
|
387
|
+
// Contract returns a tuple, map it to the Dispute interface
|
|
388
|
+
return{initiator:n,targetId:i,disputeTag:a,disputeEvidenceHash:s,counterEvidenceHash:r,disputeTimestamp:o,assertionTimestamp:d,yesVotes:u,noVotes:p,status:l,bondAmount:y,protocolFeeAmount:c}}))}
|
|
383
389
|
// minimal ABI for staking vault
|
|
384
390
|
const ze=[{inputs:[{name:"account",type:"address"}],name:"balanceOf",outputs:[{name:"",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[{name:"account",type:"address"}],name:"userStakeTimestamp",outputs:[{name:"",type:"uint256"}],stateMutability:"view",type:"function"}];
|
|
385
391
|
/**
|
|
@@ -442,6 +448,22 @@ const R=BigInt(Math.floor(Date.now()/1e3)),_=new Date(1e3*Number(v)),D=new Date(
|
|
|
442
448
|
N=new Date(1e3*Number(A+T)),x=A+T):(
|
|
443
449
|
// for raised disputes, voting ends after cooldown + judgement
|
|
444
450
|
N=new Date(1e3*Number(v+h+T)),x=v+h+T);const k=(f===Pe.Raised||f===Pe.Asserted)&&R>x,M=k?0:Number(x-R);return{disputeId:e,status:f,yesVotes:w,noVotes:I,totalVotes:g,yesPercentage:b,noPercentage:C,quorum:m,quorumPercentage:E,quorumMet:S,projectedOutcome:P,timeline:{raisedAt:_,cooldownEndsAt:D,votingEndsAt:N,canResolveNow:k,timeUntilResolution:M}}}))}
|
|
451
|
+
/**
|
|
452
|
+
* Gets the requirements for raising a dispute, including balance check.
|
|
453
|
+
*
|
|
454
|
+
* @param userAddress The address to check balance for.
|
|
455
|
+
* @returns A promise that resolves with the dispute requirements.
|
|
456
|
+
*
|
|
457
|
+
* @example
|
|
458
|
+
* ```typescript
|
|
459
|
+
* const requirements = await origin.getDisputeRequirements(walletAddress);
|
|
460
|
+
* if (!requirements.hasSufficientBalance) {
|
|
461
|
+
* console.log(`Need ${requirements.totalRequired} but only have ${requirements.userBalance}`);
|
|
462
|
+
* }
|
|
463
|
+
* ```
|
|
464
|
+
*/function Je(e){return f(this,void 0,void 0,(function*(){const t=U(),n=this.environment.DISPUTE_CONTRACT_ADDRESS,i=this.environment.DISPUTE_ABI,[a,s,o]=yield Promise.all([t.readContract({address:n,abi:i,functionName:"disputeBond"}),t.readContract({address:n,abi:i,functionName:"protocolDisputeFee"}),t.readContract({address:n,abi:i,functionName:"disputeToken"})]),d=o===r,u=a+s;
|
|
465
|
+
// Get user's balance
|
|
466
|
+
let l;return l=d?yield t.getBalance({address:e}):yield t.readContract({address:o,abi:p,functionName:"balanceOf",args:[e]}),{bondAmount:a,protocolFee:s,totalRequired:u,tokenAddress:o,isNativeToken:d,userBalance:l,hasSufficientBalance:l>=u}}))}
|
|
445
467
|
/**
|
|
446
468
|
* Fractionalizes an IP NFT into fungible ERC20 tokens.
|
|
447
469
|
* The NFT is transferred to the fractionalizer contract and a new ERC20 token is created.
|
|
@@ -458,7 +480,7 @@ N=new Date(1e3*Number(v+h+T)),x=v+h+T);const k=(f===Pe.Raised||f===Pe.Asserted)&
|
|
|
458
480
|
* // Then fractionalize
|
|
459
481
|
* const result = await origin.fractionalize(1n);
|
|
460
482
|
* ```
|
|
461
|
-
*/function
|
|
483
|
+
*/function Ge(e){return f(this,void 0,void 0,(function*(){return this.callContractMethod(this.environment.FRACTIONALIZER_CONTRACT_ADDRESS,this.environment.FRACTIONALIZER_ABI,"fractionalize",[e],{waitForReceipt:!0})}))}
|
|
462
484
|
/**
|
|
463
485
|
* Redeems an IP NFT by burning all of its fractional tokens.
|
|
464
486
|
* The caller must hold the entire supply of the NFT's fractional token.
|
|
@@ -472,7 +494,7 @@ N=new Date(1e3*Number(v+h+T)),x=v+h+T);const k=(f===Pe.Raised||f===Pe.Asserted)&
|
|
|
472
494
|
* // Requires holding 100% of the fractional token supply
|
|
473
495
|
* await origin.redeem(1n);
|
|
474
496
|
* ```
|
|
475
|
-
*/function
|
|
497
|
+
*/function Ye(e){return f(this,void 0,void 0,(function*(){return this.callContractMethod(this.environment.FRACTIONALIZER_CONTRACT_ADDRESS,this.environment.FRACTIONALIZER_ABI,"redeem",[e],{waitForReceipt:!0})}))}
|
|
476
498
|
/**
|
|
477
499
|
* Gets the fractional ERC20 token address for a specific IP NFT.
|
|
478
500
|
* Returns zero address if the NFT has not been fractionalized.
|
|
@@ -489,7 +511,7 @@ N=new Date(1e3*Number(v+h+T)),x=v+h+T);const k=(f===Pe.Raised||f===Pe.Asserted)&
|
|
|
489
511
|
* console.log("NFT has not been fractionalized");
|
|
490
512
|
* }
|
|
491
513
|
* ```
|
|
492
|
-
*/function
|
|
514
|
+
*/function We(e){return f(this,void 0,void 0,(function*(){return this.callContractMethod(this.environment.FRACTIONALIZER_CONTRACT_ADDRESS,this.environment.FRACTIONALIZER_ABI,"getTokenForNFT",[e])}))}
|
|
493
515
|
/**
|
|
494
516
|
* Fractionalizes an IP NFT with automatic approval.
|
|
495
517
|
* This method first approves the fractionalizer contract to transfer your NFT,
|
|
@@ -503,7 +525,7 @@ N=new Date(1e3*Number(v+h+T)),x=v+h+T);const k=(f===Pe.Raised||f===Pe.Asserted)&
|
|
|
503
525
|
* // Single call handles approval and fractionalization
|
|
504
526
|
* const result = await origin.fractionalizeWithApproval(1n);
|
|
505
527
|
* ```
|
|
506
|
-
*/function
|
|
528
|
+
*/function Ze(e){return f(this,void 0,void 0,(function*(){return yield this.approve(this.environment.FRACTIONALIZER_CONTRACT_ADDRESS,e),this.callContractMethod(this.environment.FRACTIONALIZER_CONTRACT_ADDRESS,this.environment.FRACTIONALIZER_ABI,"fractionalize",[e],{waitForReceipt:!0})}))}
|
|
507
529
|
/**
|
|
508
530
|
* Redeems fractional tokens for the underlying NFT, but only if the caller owns 100% of the supply.
|
|
509
531
|
* This method checks the caller's balance before attempting to redeem, providing a clear error
|
|
@@ -522,7 +544,7 @@ N=new Date(1e3*Number(v+h+T)),x=v+h+T);const k=(f===Pe.Raised||f===Pe.Asserted)&
|
|
|
522
544
|
* console.log("You don't own all fractional tokens yet");
|
|
523
545
|
* }
|
|
524
546
|
* ```
|
|
525
|
-
*/function
|
|
547
|
+
*/function Ke(e){return f(this,void 0,void 0,(function*(){
|
|
526
548
|
// get the ERC20 token address for this NFT
|
|
527
549
|
const t=yield this.getTokenForNFT(e);if(!t||"0x0000000000000000000000000000000000000000"===t)throw new Error("This NFT has not been fractionalized");
|
|
528
550
|
// get current wallet address
|
|
@@ -532,7 +554,7 @@ if(s<r){const e=s*BigInt(1e4)/r;throw new Error(`Cannot redeem: you own ${e/BigI
|
|
|
532
554
|
// proceed with redemption
|
|
533
555
|
return this.callContractMethod(this.environment.FRACTIONALIZER_CONTRACT_ADDRESS,this.environment.FRACTIONALIZER_ABI,"redeem",[e],{waitForReceipt:!0})}))}
|
|
534
556
|
// minimal ERC20 ABI
|
|
535
|
-
const
|
|
557
|
+
const Xe=[{inputs:[{name:"owner",type:"address"}],name:"balanceOf",outputs:[{name:"",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[],name:"totalSupply",outputs:[{name:"",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[],name:"decimals",outputs:[{name:"",type:"uint8"}],stateMutability:"view",type:"function"}];
|
|
536
558
|
/**
|
|
537
559
|
* Gets a user's ownership percentage of a fractionalized NFT.
|
|
538
560
|
* Returns detailed information about the user's fractional token holdings.
|
|
@@ -557,10 +579,10 @@ const Ke=[{inputs:[{name:"owner",type:"address"}],name:"balanceOf",outputs:[{nam
|
|
|
557
579
|
* }
|
|
558
580
|
* }
|
|
559
581
|
* ```
|
|
560
|
-
*/function
|
|
582
|
+
*/function Qe(e,t){return f(this,void 0,void 0,(function*(){const n=yield Ce(this.viemClient,t),i=yield this.getTokenForNFT(e);
|
|
561
583
|
// get the ERC20 token address for this NFT
|
|
562
584
|
// check if fractionalized
|
|
563
|
-
if(!i||i===r)return{tokenId:e,erc20Address:r,isFractionalized:!1,balance:BigInt(0),totalSupply:BigInt(0),ownershipPercentage:0,canRedeem:!1,decimals:18};const a=U(),[s,o,d]=yield Promise.all([a.readContract({address:i,abi:
|
|
585
|
+
if(!i||i===r)return{tokenId:e,erc20Address:r,isFractionalized:!1,balance:BigInt(0),totalSupply:BigInt(0),ownershipPercentage:0,canRedeem:!1,decimals:18};const a=U(),[s,o,d]=yield Promise.all([a.readContract({address:i,abi:Xe,functionName:"balanceOf",args:[n]}),a.readContract({address:i,abi:Xe,functionName:"totalSupply",args:[]}),a.readContract({address:i,abi:Xe,functionName:"decimals",args:[]})]);
|
|
564
586
|
// fetch ERC20 data
|
|
565
587
|
// calculate ownership percentage
|
|
566
588
|
let u=0;o>BigInt(0)&&(u=Number(s*BigInt(1e4)/o)/100);const p=s>=o&&o>BigInt(0);return{tokenId:e,erc20Address:i,isFractionalized:!0,balance:s,totalSupply:o,ownershipPercentage:u,canRedeem:p,decimals:d}}))}
|
|
@@ -587,7 +609,7 @@ let u=0;o>BigInt(0)&&(u=Number(s*BigInt(1e4)/o)/100);const p=s>=o&&o>BigInt(0);r
|
|
|
587
609
|
* console.log(`Cannot fractionalize: ${eligibility.reason}`);
|
|
588
610
|
* }
|
|
589
611
|
* ```
|
|
590
|
-
*/function
|
|
612
|
+
*/function et(e,t){return f(this,void 0,void 0,(function*(){const n=yield Ce(this.viemClient,t),i=U(),a=this.environment.FRACTIONALIZER_CONTRACT_ADDRESS,[s,o,d,u,p]=yield Promise.all([this.ownerOf(e),this.dataStatus(e),this.getTokenForNFT(e),i.readContract({address:this.environment.DATANFT_CONTRACT_ADDRESS,abi:this.environment.IPNFT_ABI,functionName:"getApproved",args:[e]}),i.readContract({address:this.environment.DATANFT_CONTRACT_ADDRESS,abi:this.environment.IPNFT_ABI,functionName:"isApprovedForAll",args:[n,a]})]),l=s.toLowerCase()===n.toLowerCase(),y=d&&d!==r,c=p||u.toLowerCase()===a.toLowerCase(),m={canFractionalize:!1,isOwner:l,currentOwner:s,isAlreadyFractionalized:!!y,existingErc20Address:y?d:void 0,dataStatus:o,isApproved:c,needsApproval:!c};
|
|
591
613
|
// check requirements
|
|
592
614
|
return l?y?Object.assign(Object.assign({},m),{reason:`This NFT is already fractionalized. ERC20: ${d}`}):o===Se.DELETED?Object.assign(Object.assign({},m),{reason:"This NFT has been deleted and cannot be fractionalized"}):o===Se.DISPUTED?Object.assign(Object.assign({},m),{reason:"This NFT is disputed and cannot be fractionalized"}):Object.assign(Object.assign({},m),{canFractionalize:!0}):Object.assign(Object.assign({},m),{reason:`You don't own this NFT. Current owner: ${s}`})}))}
|
|
593
615
|
/**
|
|
@@ -603,12 +625,15 @@ return l?y?Object.assign(Object.assign({},m),{reason:`This NFT is already fracti
|
|
|
603
625
|
* console.log(`Revenue Share: ${appInfo.revenueShareBps / 100}%`);
|
|
604
626
|
* console.log(`Active: ${appInfo.isActive}`);
|
|
605
627
|
* ```
|
|
606
|
-
*/function
|
|
628
|
+
*/function tt(e){return f(this,void 0,void 0,(function*(){return this.callContractMethod(this.environment.APP_REGISTRY_CONTRACT_ADDRESS,this.environment.APP_REGISTRY_ABI,"getAppInfo",[e])}))}
|
|
607
629
|
/**
|
|
608
630
|
* Approves a spender to spend a specified amount of tokens on behalf of the owner.
|
|
609
631
|
* If the current allowance is less than the specified amount, it will perform the approval.
|
|
632
|
+
* Waits for the approval transaction to be confirmed before returning.
|
|
610
633
|
* @param {ApproveParams} params - The parameters for the approval.
|
|
611
|
-
*/function
|
|
634
|
+
*/function nt(e){return f(this,arguments,void 0,(function*({walletClient:e,publicClient:t,tokenAddress:n,owner:i,spender:a,amount:s,chain:r}){if((yield t.readContract({address:n,abi:p,functionName:"allowance",args:[i,a]}))<s){const o=yield e.writeContract({address:n,account:i,abi:p,functionName:"approve",args:[a,s],chain:r});
|
|
635
|
+
// Wait for the approval transaction to be confirmed with extra confirmations
|
|
636
|
+
yield t.waitForTransactionReceipt({hash:o,confirmations:2}),yield new Promise((e=>setTimeout(e,1e3)))}}))}
|
|
612
637
|
/**
|
|
613
638
|
* Executes an atomic bulk purchase of multiple IP-NFT licenses.
|
|
614
639
|
* All purchases succeed or all fail together.
|
|
@@ -627,7 +652,7 @@ return l?y?Object.assign(Object.assign({},m),{reason:`This NFT is already fracti
|
|
|
627
652
|
* const totalValue = 3000000000000000n;
|
|
628
653
|
* await origin.bulkBuyAccess(buyerAddress, purchases, totalValue);
|
|
629
654
|
* ```
|
|
630
|
-
*/function
|
|
655
|
+
*/function it(e,t,n){return this.callContractMethod(this.environment.BATCH_PURCHASE_CONTRACT_ADDRESS,this.environment.BATCH_PURCHASE_ABI,"bulkBuyAccess",[e,t],{waitForReceipt:!0,value:n})}
|
|
631
656
|
/**
|
|
632
657
|
* Executes a fault-tolerant bulk purchase of multiple IP-NFT licenses.
|
|
633
658
|
* Individual purchases can fail without reverting the entire transaction.
|
|
@@ -644,7 +669,7 @@ return l?y?Object.assign(Object.assign({},m),{reason:`This NFT is already fracti
|
|
|
644
669
|
* console.log(`Purchased ${result.successCount} of ${purchases.length} IPs`);
|
|
645
670
|
* console.log(`Failed tokens: ${result.failedTokenIds}`);
|
|
646
671
|
* ```
|
|
647
|
-
*/function
|
|
672
|
+
*/function at(e,t,n){return this.callContractMethod(this.environment.BATCH_PURCHASE_CONTRACT_ADDRESS,this.environment.BATCH_PURCHASE_ABI,"bulkBuyAccessTolerant",[e,t],{waitForReceipt:!0,value:n})}
|
|
648
673
|
/**
|
|
649
674
|
* Previews the total cost of purchasing multiple IP-NFT licenses.
|
|
650
675
|
* This is a view function that doesn't require a transaction.
|
|
@@ -658,7 +683,7 @@ return l?y?Object.assign(Object.assign({},m),{reason:`This NFT is already fracti
|
|
|
658
683
|
* console.log(`Total cost: ${preview.totalNativeCost} wei`);
|
|
659
684
|
* console.log(`Valid tokens: ${preview.validCount}`);
|
|
660
685
|
* ```
|
|
661
|
-
*/function
|
|
686
|
+
*/function st(e){return this.callContractMethod(this.environment.BATCH_PURCHASE_CONTRACT_ADDRESS,this.environment.BATCH_PURCHASE_ABI,"previewBulkCost",[e])}
|
|
662
687
|
/**
|
|
663
688
|
* Builds purchase parameters for multiple tokens by fetching their current license terms.
|
|
664
689
|
* This is a view function that doesn't require a transaction.
|
|
@@ -671,7 +696,7 @@ return l?y?Object.assign(Object.assign({},m),{reason:`This NFT is already fracti
|
|
|
671
696
|
* const params = await origin.buildPurchaseParams([1n, 2n, 3n]);
|
|
672
697
|
* await origin.bulkBuyAccess(buyer, params, totalValue);
|
|
673
698
|
* ```
|
|
674
|
-
*/function
|
|
699
|
+
*/function rt(e){return this.callContractMethod(this.environment.BATCH_PURCHASE_CONTRACT_ADDRESS,this.environment.BATCH_PURCHASE_ABI,"buildPurchaseParams",[e])}
|
|
675
700
|
/**
|
|
676
701
|
* Checks the active status of multiple tokens.
|
|
677
702
|
*
|
|
@@ -683,7 +708,7 @@ return l?y?Object.assign(Object.assign({},m),{reason:`This NFT is already fracti
|
|
|
683
708
|
* const activeFlags = await origin.checkActiveStatus([1n, 2n, 3n]);
|
|
684
709
|
* const activeTokens = tokenIds.filter((_, i) => activeFlags[i]);
|
|
685
710
|
* ```
|
|
686
|
-
*/function
|
|
711
|
+
*/function ot(e){return this.callContractMethod(this.environment.BATCH_PURCHASE_CONTRACT_ADDRESS,this.environment.BATCH_PURCHASE_ABI,"checkActiveStatus",[e])}
|
|
687
712
|
/**
|
|
688
713
|
* Smart bulk purchase that automatically fetches terms and handles the entire purchase flow.
|
|
689
714
|
* This is the recommended method for most use cases.
|
|
@@ -700,7 +725,7 @@ return l?y?Object.assign(Object.assign({},m),{reason:`This NFT is already fracti
|
|
|
700
725
|
* // Tolerant purchase - continue even if some fail
|
|
701
726
|
* const result = await origin.bulkBuyAccessSmart([1n, 2n, 3n], { tolerant: true });
|
|
702
727
|
* ```
|
|
703
|
-
*/function
|
|
728
|
+
*/function dt(e,t){return f(this,void 0,void 0,(function*(){if(!e||0===e.length)throw new D("No token IDs provided for bulk purchase. Please provide at least one token ID.");
|
|
704
729
|
// Get the buyer's wallet address
|
|
705
730
|
const n=this.viemClient;if(!n)throw new x("Cannot perform bulk purchase: wallet not connected. Please connect a wallet first.");let i;if(n.account)i=n.account.address;else{const e=yield n.request({method:"eth_requestAccounts",params:[]});if(!e||0===e.length)throw new x("No accounts found in connected wallet. Please unlock your wallet or add an account.");i=e[0]}
|
|
706
731
|
// Build purchase params from on-chain data
|
|
@@ -710,31 +735,38 @@ let s=BigInt(0);const o=[];for(const e of a)if(e.expectedPaymentToken===r)s+=e.e
|
|
|
710
735
|
// Group ERC20 purchases by token
|
|
711
736
|
const t=o.find((t=>t.token===e.expectedPaymentToken));t?t.amount+=e.expectedPrice:o.push({token:e.expectedPaymentToken,amount:e.expectedPrice})}
|
|
712
737
|
// Approve ERC20 tokens if needed
|
|
713
|
-
const d=U();for(const e of o)yield
|
|
738
|
+
const d=U();for(const e of o)yield nt({walletClient:n,publicClient:d,tokenAddress:e.token,owner:i,spender:this.environment.BATCH_PURCHASE_CONTRACT_ADDRESS,amount:e.amount,chain:this.environment.CHAIN});
|
|
714
739
|
// Execute the purchase
|
|
715
|
-
return(null==t?void 0:t.tolerant)?this.bulkBuyAccessTolerant(i,a,s):this.bulkBuyAccess(i,a,s)}))}var
|
|
740
|
+
return(null==t?void 0:t.tolerant)?this.bulkBuyAccessTolerant(i,a,s):this.bulkBuyAccess(i,a,s)}))}var ut,pt,lt,yt,ct,mt,ht,Tt,ft,vt,At,wt,It,gt,bt,Ct,Et,St,Pt,Rt,_t,Dt;
|
|
716
741
|
/**
|
|
717
742
|
* The Origin class
|
|
718
743
|
* Handles interactions with Origin protocol.
|
|
719
|
-
*/class
|
|
744
|
+
*/class Nt{constructor(e,t,n,i,a){ut.add(this),t?this.jwt=t:console.warn("JWT not provided. Some features may be unavailable."),this.viemClient=n,this.environment="string"==typeof e?X[e]:e||X.DEVELOPMENT,this.environment.AUTH_HUB_BASE_API+="PRODUCTION"===e?"/auth-mainnet":"",this.baseParentId=i,this.appId=a,
|
|
720
745
|
// DataNFT methods
|
|
721
746
|
this.mintWithSignature=ie.bind(this),this.registerIpNFT=ae.bind(this),this.updateTerms=se.bind(this),this.finalizeDelete=re.bind(this),this.getOrCreateRoyaltyVault=oe.bind(this),this.getTerms=de.bind(this),this.ownerOf=ue.bind(this),this.balanceOf=pe.bind(this),this.tokenURI=le.bind(this),this.dataStatus=ye.bind(this),this.isApprovedForAll=ce.bind(this),this.transferFrom=me.bind(this),this.safeTransferFrom=he.bind(this),this.approve=Te.bind(this),this.setApprovalForAll=fe.bind(this),
|
|
722
747
|
// Marketplace methods
|
|
723
748
|
this.buyAccess=ve.bind(this),this.hasAccess=Ae.bind(this),this.subscriptionExpiry=we.bind(this),this.settlePaymentIntent=be.bind(this),this.getDataWithIntent=Ne.bind(this),
|
|
724
749
|
// Bulk purchase methods
|
|
725
|
-
this.bulkBuyAccess=
|
|
750
|
+
this.bulkBuyAccess=it.bind(this),this.bulkBuyAccessTolerant=at.bind(this),this.bulkBuyAccessSmart=dt.bind(this),this.previewBulkCost=st.bind(this),this.buildPurchaseParams=rt.bind(this),this.checkActiveStatus=ot.bind(this),
|
|
726
751
|
// Dispute module methods
|
|
727
|
-
this.raiseDispute=Fe.bind(this),this.raiseDisputeSmart=Be.bind(this),this.disputeAssertion=Oe.bind(this),this.voteOnDispute=Ue.bind(this),this.resolveDispute=$e.bind(this),this.cancelDispute=He.bind(this),this.tagChildIp=je.bind(this),this.getDispute=Le.bind(this),this.canVoteOnDispute=Ve.bind(this),this.getDisputeProgress=qe.bind(this),
|
|
752
|
+
this.raiseDispute=Fe.bind(this),this.raiseDisputeSmart=Be.bind(this),this.disputeAssertion=Oe.bind(this),this.voteOnDispute=Ue.bind(this),this.resolveDispute=$e.bind(this),this.cancelDispute=He.bind(this),this.tagChildIp=je.bind(this),this.getDispute=Le.bind(this),this.canVoteOnDispute=Ve.bind(this),this.getDisputeProgress=qe.bind(this),this.getDisputeRequirements=Je.bind(this),
|
|
728
753
|
// Fractionalizer module methods
|
|
729
|
-
this.fractionalize=
|
|
754
|
+
this.fractionalize=Ge.bind(this),this.redeem=Ye.bind(this),this.getTokenForNFT=We.bind(this),this.fractionalizeWithApproval=Ze.bind(this),this.redeemIfComplete=Ke.bind(this),this.getFractionOwnership=Qe.bind(this),this.canFractionalize=et.bind(this),
|
|
730
755
|
// AppRegistry module methods
|
|
731
|
-
this.getAppInfo=
|
|
756
|
+
this.getAppInfo=tt.bind(this)}getJwt(){return this.jwt}setViemClient(e){this.viemClient=e}
|
|
757
|
+
/**
|
|
758
|
+
* Approves an ERC20 token for spending by a spender address if the current allowance is insufficient.
|
|
759
|
+
* Waits for the approval transaction to be confirmed before returning.
|
|
760
|
+
* @param tokenAddress The address of the ERC20 token.
|
|
761
|
+
* @param spender The address that will be approved to spend the tokens.
|
|
762
|
+
* @param amount The amount of tokens to approve.
|
|
763
|
+
*/approveERC20IfNeeded(e,t,n){return f(this,void 0,void 0,(function*(){const i=yield v(this,ut,"m",At).call(this);yield nt({walletClient:this.viemClient,publicClient:U(),tokenAddress:e,owner:i,spender:t,amount:n,chain:this.environment.CHAIN})}))}
|
|
732
764
|
/**
|
|
733
765
|
* Uploads a JSON object to IPFS and returns the resulting CID.
|
|
734
766
|
* @param data The JSON object to upload.
|
|
735
767
|
* @returns The CID of the uploaded JSON.
|
|
736
768
|
* @throws {APIError} If the upload fails.
|
|
737
|
-
*/uploadJSONToIPFS(e){return f(this,void 0,void 0,(function*(){const t=JSON.stringify(e),n=new File([t],"evidence.json",{type:"application/json"}),i=yield v(this,
|
|
769
|
+
*/uploadJSONToIPFS(e){return f(this,void 0,void 0,(function*(){const t=JSON.stringify(e),n=new File([t],"evidence.json",{type:"application/json"}),i=yield v(this,ut,"m",yt).call(this,n);if(!i)throw new _("Failed to upload evidence to IPFS");return i}))}
|
|
738
770
|
/**
|
|
739
771
|
* Mints a file-based IpNFT.
|
|
740
772
|
* @param file The file to mint.
|
|
@@ -743,17 +775,17 @@ this.getAppInfo=et.bind(this)}getJwt(){return this.jwt}setViemClient(e){this.vie
|
|
|
743
775
|
* @param parents Optional parent token IDs for lineage tracking.
|
|
744
776
|
* @param options Optional parameters including progress callback, preview image, and use asset as preview flag.
|
|
745
777
|
* @returns The token ID of the minted IpNFT as a string, or null if minting failed.
|
|
746
|
-
*/mintFile(e,t,n,i,a){return f(this,void 0,void 0,(function*(){let s,r=null;try{r=yield v(this,
|
|
778
|
+
*/mintFile(e,t,n,i,a){return f(this,void 0,void 0,(function*(){let s,r=null;try{r=yield v(this,ut,"m",Tt).call(this)}catch(t){throw new x(`Cannot mint file "${e.name}": wallet not connected. Please connect a wallet first.`)}try{if(s=yield v(this,ut,"m",ct).call(this,e,a),!s||!s.key)throw new _(`Failed to upload file "${e.name}": no upload info returned from server`)}catch(t){if(t instanceof _||t instanceof x)throw t;throw new _(`Failed to upload file "${e.name}": ${M(t)}`)}e.type&&(t.mimetype=e.type);let o=null;(null==a?void 0:a.previewImage)&&(null==a?void 0:a.previewImage.type.startsWith("image/"))?o=yield v(this,ut,"m",yt).call(this,a.previewImage):(null==a?void 0:a.useAssetAsPreview)&&e.type.startsWith("image/")&&(o=yield v(this,ut,"m",yt).call(this,e)),o&&(t.image=`ipfs://${o}`);const d=BigInt(Date.now()+6e5);// 10 minutes from now
|
|
747
779
|
let u;this.baseParentId&&(i||(i=[]),i.unshift(this.baseParentId));try{u=yield this.registerIpNFT("file",d,n,t,!0,// isIp
|
|
748
780
|
s.key,// fileKey
|
|
749
|
-
i,this.appId)}catch(e){throw yield v(this,
|
|
781
|
+
i,this.appId)}catch(e){throw yield v(this,ut,"m",lt).call(this,s.key,s.uploadId,[]),new Error(`Failed to register IpNFT: ${e instanceof Error?e.message:String(e)}`)}const{tokenId:p,signerAddress:l,creatorContentHash:y,signature:c,uri:m}=u;if(!(p&&l&&y&&void 0!==c&&m))throw new Error("Failed to register IpNFT: Missing required fields in registration response.");try{const e=yield this.mintWithSignature(r,p,i||[],!0,y,m,n,d,c,this.appId);if(-1===["0x1","success"].indexOf(e.receipt.status))throw yield v(this,ut,"m",lt).call(this,s.key,s.uploadId,[]),new Error(`Minting failed with status: ${e.receipt.status}`)}catch(e){throw yield v(this,ut,"m",lt).call(this,s.key,s.uploadId,[]),new Error(`Minting transaction failed: ${e instanceof Error?e.message:String(e)}`)}return p.toString()}))}
|
|
750
782
|
/**
|
|
751
783
|
* Mints a social IpNFT.
|
|
752
784
|
* @param source The social media source (spotify, twitter, tiktok).
|
|
753
785
|
* @param metadata The metadata associated with the social media content.
|
|
754
786
|
* @param license The license terms for the IpNFT.
|
|
755
787
|
* @return The token ID of the minted IpNFT as a string, or null if minting failed.
|
|
756
|
-
*/mintSocial(e,t,n){return f(this,void 0,void 0,(function*(){let i=null;try{i=yield v(this,
|
|
788
|
+
*/mintSocial(e,t,n){return f(this,void 0,void 0,(function*(){let i=null;try{i=yield v(this,ut,"m",Tt).call(this)}catch(t){throw new x(`Cannot mint ${e} social IP: wallet not connected. Please connect a wallet first.`)}t.mimetype=`social/${e}`;const a=BigInt(Math.floor(Date.now()/1e3)+600);// 10 minutes from now
|
|
757
789
|
let s,r=this.baseParentId?[this.baseParentId]:[];try{s=yield this.registerIpNFT(e,a,n,t,!0,// isIp
|
|
758
790
|
void 0,// fileKey
|
|
759
791
|
r,this.appId)}catch(e){throw new Error(`Failed to register Social IpNFT: ${e instanceof Error?e.message:String(e)}`)}const{tokenId:o,signerAddress:d,creatorContentHash:u,signature:p,uri:l}=s;if(!(o&&d&&u&&void 0!==p&&l))throw new Error("Failed to register Social IpNFT: Missing required fields in registration response.");try{const e=yield this.mintWithSignature(i,o,r,!0,u,l,n,a,p,this.appId);if(-1===["0x1","success"].indexOf(e.receipt.status))throw new Error(`Minting Social IpNFT failed with status: ${e.receipt.status}`)}catch(e){throw new Error(`Minting transaction failed: ${e instanceof Error?e.message:String(e)}`)}return o.toString()}))}
|
|
@@ -766,9 +798,9 @@ r,this.appId)}catch(e){throw new Error(`Failed to register Social IpNFT: ${e ins
|
|
|
766
798
|
* @param {CallOptions} [options] The call options.
|
|
767
799
|
* @returns {Promise<any>} A promise that resolves with the result of the contract call or transaction hash.
|
|
768
800
|
* @throws {Error} - Throws an error if the wallet client is not connected and the method is not a view function.
|
|
769
|
-
*/callContractMethod(e,t,n,i){return f(this,arguments,void 0,(function*(e,t,n,i,a={}){var s;let r=null;try{r=yield v(this,
|
|
801
|
+
*/callContractMethod(e,t,n,i){return f(this,arguments,void 0,(function*(e,t,n,i,a={}){var s;let r=null;try{r=yield v(this,ut,"m",Tt).call(this)}catch(t){throw new x(`Cannot call "${n}" on contract ${e}: wallet not connected`)}const o=l({abi:t,name:n});if(o&&"stateMutability"in o&&("view"===o.stateMutability||"pure"===o.stateMutability)){const a=U();return(yield a.readContract({address:e,abi:t,functionName:n,args:i}))||null}yield v(this,ut,"m",ht).call(this,this.environment.CHAIN);const d=U(),{result:u,request:p}=yield d.simulateContract({account:r,address:e,abi:t,functionName:n,args:i,value:a.value});
|
|
770
802
|
// simulate
|
|
771
|
-
if(a.simulate)return u;try{const t=yield null===(s=this.viemClient)||void 0===s?void 0:s.writeContract(p);if("string"!=typeof t)throw new k(`Transaction for "${n}" failed to send: no transaction hash returned`,{contractName:e,methodName:n});if(!a.waitForReceipt)return{txHash:t,simulatedResult:u};return{txHash:t,receipt:yield v(this,
|
|
803
|
+
if(a.simulate)return u;try{const t=yield null===(s=this.viemClient)||void 0===s?void 0:s.writeContract(p);if("string"!=typeof t)throw new k(`Transaction for "${n}" failed to send: no transaction hash returned`,{contractName:e,methodName:n});if(!a.waitForReceipt)return{txHash:t,simulatedResult:u};return{txHash:t,receipt:yield v(this,ut,"m",mt).call(this,t),simulatedResult:u}}catch(t){if(t instanceof k||t instanceof x)throw t;throw new k(`Transaction for "${n}" failed: ${M(t)}`,{contractName:e,methodName:n})}}))}
|
|
772
804
|
/**
|
|
773
805
|
* Gets comprehensive token information in a single call.
|
|
774
806
|
* Combines owner, status, terms, URI, and access information.
|
|
@@ -810,13 +842,13 @@ let u=!1,p=null;if("0x0000000000000000000000000000000000000000"!==i)try{[u,p]=yi
|
|
|
810
842
|
* console.log("Access purchased:", result.txHash);
|
|
811
843
|
* }
|
|
812
844
|
* ```
|
|
813
|
-
*/buyAccessSmart(e){return f(this,void 0,void 0,(function*(){let t=null;try{t=yield v(this,
|
|
845
|
+
*/buyAccessSmart(e){return f(this,void 0,void 0,(function*(){let t=null;try{t=yield v(this,ut,"m",Tt).call(this)}catch(t){throw new x(`Cannot buy access to token ${e}: wallet not connected. Please connect a wallet first.`)}
|
|
814
846
|
// Check if user already has access
|
|
815
847
|
if(yield this.hasAccess(t,e))return console.log("User already has access to this asset"),null;const n=yield this.getTerms(e);if(!n)throw new _(`Failed to fetch license terms for token ${e}: no terms returned`);const{price:i,paymentToken:a,duration:s}=n;if(void 0===i||void 0===a||void 0===s)throw new _(`Invalid license terms for token ${e}: missing price, paymentToken, or duration`);
|
|
816
848
|
// Fetch protocol fee from marketplace
|
|
817
|
-
const o=yield v(this,
|
|
849
|
+
const o=yield v(this,ut,"m",ft).call(this),d=yield v(this,ut,"m",vt).call(this,e),u=i;
|
|
818
850
|
// Fetch app fee from token's appId
|
|
819
|
-
return a===r?this.buyAccess(t,e,u,s,a,o,d,u):(yield
|
|
851
|
+
return a===r?this.buyAccess(t,e,u,s,a,o,d,u):(yield nt({walletClient:this.viemClient,publicClient:U(),tokenAddress:a,owner:t,spender:this.environment.MARKETPLACE_CONTRACT_ADDRESS,amount:u,chain:this.environment.CHAIN}),this.buyAccess(t,e,u,s,a,o,d))}))}
|
|
820
852
|
/**
|
|
821
853
|
* Fetch the underlying data associated with a specific token ID.
|
|
822
854
|
* @param {bigint} tokenId - The token ID to fetch data for.
|
|
@@ -866,7 +898,7 @@ const e=[{inputs:[{name:"owner",type:"address"}],name:"balanceOf",outputs:[{name
|
|
|
866
898
|
* // Claim ERC20 token royalties to a specific address
|
|
867
899
|
* await origin.claimRoyalties(1n, "0xRecipient...", "0xToken...");
|
|
868
900
|
* ```
|
|
869
|
-
*/claimRoyalties(e,t,n){return f(this,void 0,void 0,(function*(){const i=yield v(this,
|
|
901
|
+
*/claimRoyalties(e,t,n){return f(this,void 0,void 0,(function*(){const i=yield v(this,ut,"m",At).call(this,t),s=yield this.getTokenBoundAccount(e),o=(yield this.getRoyalties(e,n)).balance;if(o===BigInt(0))throw new Error("No royalties available to claim");let d,u,p;
|
|
870
902
|
// Call execute on the TBA
|
|
871
903
|
return n&&n!==r?(
|
|
872
904
|
// ERC20 token transfer
|
|
@@ -875,16 +907,16 @@ d=n,u=BigInt(0),
|
|
|
875
907
|
p=a({abi:[{inputs:[{name:"to",type:"address"},{name:"amount",type:"uint256"}],name:"transfer",outputs:[{name:"",type:"bool"}],stateMutability:"nonpayable",type:"function"}],functionName:"transfer",args:[i,o]})):(
|
|
876
908
|
// Native token transfer
|
|
877
909
|
d=i,u=o,p="0x"),this.callContractMethod(s,this.environment.TBA_ABI,"execute",[d,u,p,0],// operation: 0 = CALL
|
|
878
|
-
{waitForReceipt:!0,value:BigInt(0)})}))}}
|
|
910
|
+
{waitForReceipt:!0,value:BigInt(0)})}))}}ut=new WeakSet,pt=function(e,t){return f(this,void 0,void 0,(function*(){try{const n=yield fetch(`${this.environment.AUTH_HUB_BASE_API}/origin/upload-url`,{method:"POST",body:JSON.stringify({name:e.name,type:e.type,partCount:t}),headers:{Authorization:`Bearer ${this.jwt}`,"Content-Type":"application/json"}});if(!n.ok)throw new Error(`HTTP ${n.status}: ${n.statusText}`);const i=yield n.json();if(i.isError)throw new Error(i.message||"Failed to generate upload URL");return i.data}catch(e){throw console.error("Failed to generate upload URL:",e),e}}))},lt=function(e,t,n){return f(this,void 0,void 0,(function*(){try{const i=yield fetch(`${this.environment.AUTH_HUB_BASE_API}/origin/update-status`,{method:"PATCH",body:JSON.stringify({fileKey:e,uploadId:t,parts:n}),headers:{Authorization:`Bearer ${this.jwt}`,"Content-Type":"application/json"}});if(!i.ok){const e=yield i.text().catch((()=>"Unknown error"));throw new Error(`HTTP ${i.status}: ${e}`)}return!0}catch(e){throw console.error("Failed to update origin status:",e),e}}))},yt=function(e){return f(this,void 0,void 0,(function*(){var t;if(!e)return null;try{const n=yield fetch(`${this.environment.AUTH_HUB_BASE_API}/origin/upload-url-ipfs`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.jwt}`},body:JSON.stringify({fileName:e.name,fileType:e.type})});if(!n.ok){const e=yield n.text().catch((()=>"Unknown error"));throw new Error(`Failed to get presigned URL (HTTP ${n.status}): ${e}`)}const i=yield n.json(),{isError:a,data:s,message:r}=i;if(a||!s)throw new Error(`Failed to get presigned URL: ${r||"No URL returned from server"}`);const o=new FormData;o.append("file",e);const d=yield fetch(s,{method:"POST",body:o});if(!d.ok){const e=yield d.text().catch((()=>d.statusText));throw new Error(`Failed to upload preview image to IPFS (HTTP ${d.status}): ${e}`)}const u=yield d.json();if(!u||!u.data)throw new Error("Invalid response from IPFS upload: Missing data field");return null===(t=u.data)||void 0===t?void 0:t.cid}catch(e){const t=e instanceof Error?e.message:String(e);throw console.error("Error uploading preview image to IPFS:",t),new Error(`Failed to upload preview image to IPFS: ${t}`)}}))},ct=function(e,t){return f(this,void 0,void 0,(function*(){let n,i;try{i=((e,t)=>{const n=[];let i=0;for(;i<e.size;)n.push(e.slice(i,i+t)),i+=t;return n})(e,10485760),n=yield v(this,ut,"m",pt).call(this,e,i.length)}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(!n)throw new Error("Failed to generate upload URL: No upload info returned");let a;try{a=yield ne(i,n.urls,(null==t?void 0:t.progressCallback)||(()=>{}))}catch(e){try{yield v(this,ut,"m",lt).call(this,n.key,n.uploadId,a||[])}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 v(this,ut,"m",lt).call(this,n.key,n.uploadId,a)}catch(e){console.error("Failed to update status to success:",e)}return n}))},mt=function(e){return f(this,arguments,void 0,(function*(e,t={}){var n,i,a;const s=U();let r=e;const o=null!==(n=t.confirmations)&&void 0!==n?n:1,d=null!==(i=t.timeoutMs)&&void 0!==i?i:18e4,u=null!==(a=t.pollingIntervalMs)&&void 0!==a?a:1500;try{return yield s.waitForTransactionReceipt({hash:r,confirmations:o,timeout:d,pollingInterval:u,onReplaced:e=>{r=e.transaction.hash}})}catch(e){
|
|
879
911
|
// fallback
|
|
880
|
-
const t=Date.now();for(;Date.now()-t<d;){try{const e=yield s.getTransactionReceipt({hash:r});if(e&&e.blockNumber)return e}catch(e){}yield new Promise((e=>setTimeout(e,u)))}throw e}}))},
|
|
912
|
+
const t=Date.now();for(;Date.now()-t<d;){try{const e=yield s.getTransactionReceipt({hash:r});if(e&&e.blockNumber)return e}catch(e){}yield new Promise((e=>setTimeout(e,u)))}throw e}}))},ht=function(e){return f(this,void 0,void 0,(function*(){if(!this.viemClient)throw new x(`Cannot switch to chain "${e.name}": wallet not connected. Please connect a wallet first.`);let t=yield this.viemClient.request({method:"eth_chainId",params:[]});if("string"==typeof t&&(t=parseInt(t,16)),t!==e.id){(e=>{O=e,B=null})// reset public client to be recreated with new chain
|
|
881
913
|
(e);try{yield this.viemClient.request({method:"wallet_switchEthereumChain",params:[{chainId:"0x"+BigInt(e.id).toString(16)}]})}catch(t){
|
|
882
914
|
// Unrecognized chain
|
|
883
|
-
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)}]})}}}))},
|
|
915
|
+
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)}]})}}}))},Tt=function(){return f(this,void 0,void 0,(function*(){if(!this.viemClient)throw new x("No wallet connected. Please connect a wallet to perform this action.");
|
|
884
916
|
// If account is already set on the client, return it directly
|
|
885
917
|
if(this.viemClient.account)return this.viemClient.account.address;
|
|
886
918
|
// Otherwise request accounts (browser wallet flow)
|
|
887
|
-
const e=yield this.viemClient.request({method:"eth_requestAccounts",params:[]});if(!e||0===e.length)throw new x("No accounts found in connected wallet. Please unlock your wallet or add an account.");return e[0]}))},
|
|
919
|
+
const e=yield this.viemClient.request({method:"eth_requestAccounts",params:[]});if(!e||0===e.length)throw new x("No accounts found in connected wallet. Please unlock your wallet or add an account.");return e[0]}))},ft=function(){return f(this,void 0,void 0,(function*(){try{const e=yield this.callContractMethod(this.environment.MARKETPLACE_CONTRACT_ADDRESS,this.environment.MARKETPLACE_ABI,"protocolFeeBps",[]);return Number(e)}catch(e){return console.warn("Failed to fetch protocol fee, defaulting to 0:",e),0}}))},vt=function(e){return f(this,void 0,void 0,(function*(){try{
|
|
888
920
|
// First, get the token info to find its appId
|
|
889
921
|
const t=yield this.callContractMethod(this.environment.DATANFT_CONTRACT_ADDRESS,this.environment.IPNFT_ABI,"tokenInfo",[e]),n=null==t?void 0:t.appId;if(!n||""===n)return 0;
|
|
890
922
|
// Check if app registry is configured
|
|
@@ -892,7 +924,7 @@ if(!this.environment.APP_REGISTRY_CONTRACT_ADDRESS||!this.environment.APP_REGIST
|
|
|
892
924
|
// Fetch app info from registry
|
|
893
925
|
const i=yield this.callContractMethod(this.environment.APP_REGISTRY_CONTRACT_ADDRESS,this.environment.APP_REGISTRY_ABI,"getAppInfo",[n]);
|
|
894
926
|
// Only return fee if app is active
|
|
895
|
-
return(null==i?void 0:i.isActive)?Number(i.revenueShareBps):0}catch(e){return console.warn("Failed to fetch app fee, defaulting to 0:",e),0}}))},
|
|
927
|
+
return(null==i?void 0:i.isActive)?Number(i.revenueShareBps):0}catch(e){return console.warn("Failed to fetch app fee, defaulting to 0:",e),0}}))},At=function(e){return f(this,void 0,void 0,(function*(){if(e)return e;if(!this.viemClient)throw new x("No wallet address provided and no wallet connected. Please provide an address or connect a wallet.");
|
|
896
928
|
// If account is already set on the client, return it directly
|
|
897
929
|
if(this.viemClient.account)return this.viemClient.account.address;
|
|
898
930
|
// Otherwise request accounts (browser wallet flow)
|
|
@@ -902,7 +934,7 @@ const t=yield this.viemClient.request({method:"eth_requestAccounts",params:[]});
|
|
|
902
934
|
* @class
|
|
903
935
|
* @classdesc The Auth class is used to authenticate the user.
|
|
904
936
|
*/
|
|
905
|
-
class
|
|
937
|
+
class xt{
|
|
906
938
|
/**
|
|
907
939
|
* Constructor for the Auth class.
|
|
908
940
|
* @param {object} options The options object.
|
|
@@ -912,9 +944,9 @@ class Nt{
|
|
|
912
944
|
* @param {StorageAdapter} [options.storage] Custom storage adapter. Defaults to localStorage in browser, memory storage in Node.js.
|
|
913
945
|
* @throws {APIError} - Throws an error if the clientId is not provided.
|
|
914
946
|
*/
|
|
915
|
-
constructor({clientId:e,appId:t,redirectUri:n,environment:i="DEVELOPMENT",baseParentId:a,storage:s}){if(
|
|
947
|
+
constructor({clientId:e,appId:t,redirectUri:n,environment:i="DEVELOPMENT",baseParentId:a,storage:s}){if(wt.add(this),It.set(this,void 0),gt.set(this,void 0),bt.set(this,void 0),Ct.set(this,void 0),!e)throw new D("clientId is required");if(!t)throw new D("appId is required");if(-1===["PRODUCTION","DEVELOPMENT"].indexOf(i))throw new D(`Invalid environment "${i}". Must be "DEVELOPMENT" or "PRODUCTION"`);A(this,gt,"undefined"==typeof window,"f"),A(this,Ct,s||(v(this,gt,"f")?new E:new C),"f"),this.viem=null,this.environment=X[i],this.environment.AUTH_HUB_BASE_API+="PRODUCTION"===i?"/auth-mainnet":"",this.baseParentId=a,this.redirectUri=(e=>{const t=["twitter","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)),{})})(n),this.clientId=e,this.appId=t,this.isAuthenticated=!1,this.jwt=null,this.origin=null,this.walletAddress=null,this.userId=null,A(this,It,{},"f"),
|
|
916
948
|
// only subscribe to providers in browser environment
|
|
917
|
-
v(this,
|
|
949
|
+
v(this,gt,"f")||te((e=>{v(this,wt,"m",Et).call(this,"providers",e)})),v(this,wt,"m",St).call(this)}
|
|
918
950
|
/**
|
|
919
951
|
* Subscribe to an event. Possible events are "state", "provider", "providers", and "viem".
|
|
920
952
|
* @param {("state"|"provider"|"providers"|"viem")} event The event.
|
|
@@ -924,18 +956,18 @@ v(this,It,"f")||te((e=>{v(this,At,"m",Ct).call(this,"providers",e)})),v(this,At,
|
|
|
924
956
|
* auth.on("state", (state) => {
|
|
925
957
|
* console.log(state);
|
|
926
958
|
* });
|
|
927
|
-
*/on(e,t){v(this,
|
|
959
|
+
*/on(e,t){v(this,It,"f")[e]||(v(this,It,"f")[e]=[]),v(this,It,"f")[e].push(t),"providers"===e&&t(ee())}
|
|
928
960
|
/**
|
|
929
961
|
* Unsubscribe from an event. Possible events are "state", "provider", "providers", and "viem".
|
|
930
962
|
* @param {("state"|"provider"|"providers"|"viem")} event The event.
|
|
931
963
|
* @param {function} callback The callback function.
|
|
932
964
|
* @returns {void}
|
|
933
|
-
*/off(e,t){v(this,
|
|
965
|
+
*/off(e,t){v(this,It,"f")[e]&&(v(this,It,"f")[e]=v(this,It,"f")[e].filter((e=>e!==t)))}
|
|
934
966
|
/**
|
|
935
967
|
* Set the loading state.
|
|
936
968
|
* @param {boolean} loading The loading state.
|
|
937
969
|
* @returns {void}
|
|
938
|
-
*/setLoading(e){v(this,
|
|
970
|
+
*/setLoading(e){v(this,wt,"m",Et).call(this,"state",e?"loading":this.isAuthenticated?"authenticated":"unauthenticated")}
|
|
939
971
|
/**
|
|
940
972
|
* 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.
|
|
941
973
|
* @param {object} options The options object. Includes the provider and the provider info.
|
|
@@ -943,7 +975,7 @@ v(this,It,"f")||te((e=>{v(this,At,"m",Ct).call(this,"providers",e)})),v(this,At,
|
|
|
943
975
|
* @throws {APIError} - Throws an error if the provider is not provided.
|
|
944
976
|
*/setProvider({provider:t,info:i,address:a}){if(!t)throw new _("provider is required");this.viem=((t,i="window.ethereum",a,s)=>{var r,o;if(!t&&!F)return console.warn("Provider is required to create a client."),null;const d=a||P;if(!F||F.transport.name!==i&&t||s!==(null===(r=F.account)||void 0===r?void 0:r.address)&&t||(null==O?void 0:O.id)!==d.id){const a={chain:d,transport:n(t,{name:i})};s&&(a.account=m(s)),F=e(a),O=d,B&&(null===(o=B.chain)||void 0===o?void 0:o.id)!==d.id&&(B=null)}return F})(t,i.name,this.environment.CHAIN,a),this.origin&&this.origin.setViemClient(this.viem),
|
|
945
977
|
// TODO: only use one of these
|
|
946
|
-
v(this,
|
|
978
|
+
v(this,wt,"m",Et).call(this,"viem",this.viem),v(this,wt,"m",Et).call(this,"provider",{provider:t,info:i}),v(this,Ct,"f").setItem("camp-sdk:provider",JSON.stringify(i))}
|
|
947
979
|
/**
|
|
948
980
|
* 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.
|
|
949
981
|
* @param {string} walletAddress The wallet address.
|
|
@@ -952,7 +984,7 @@ v(this,At,"m",Ct).call(this,"viem",this.viem),v(this,At,"m",Ct).call(this,"provi
|
|
|
952
984
|
/**
|
|
953
985
|
* Recover the provider from local storage.
|
|
954
986
|
* @returns {Promise<void>}
|
|
955
|
-
*/recoverProvider(){return f(this,void 0,void 0,(function*(){var e,t,n,i,a,s,r,o,d,u,p,l,y;if(!this.walletAddress)return void console.warn("No wallet address found in local storage. Please connect your wallet again.");const c=yield v(this,
|
|
987
|
+
*/recoverProvider(){return f(this,void 0,void 0,(function*(){var e,t,n,i,a,s,r,o,d,u,p,l,y;if(!this.walletAddress)return void console.warn("No wallet address found in local storage. Please connect your wallet again.");const c=yield v(this,Ct,"f").getItem("camp-sdk:provider");if(!c)return;const m=JSON.parse(c);let h;const T=null!==(e=ee())&&void 0!==e?e:[];
|
|
956
988
|
// first pass: try to find provider by UUID/name and check if it has the right address
|
|
957
989
|
// without prompting (using eth_accounts)
|
|
958
990
|
for(const e of T)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){
|
|
@@ -969,12 +1001,12 @@ if(!h&&(m.uuid||m.name))for(const e of T)try{if(m.uuid&&(null===(u=e.info)||void
|
|
|
969
1001
|
/**
|
|
970
1002
|
* Disconnect the user.
|
|
971
1003
|
* @returns {Promise<void>}
|
|
972
|
-
*/disconnect(){return f(this,void 0,void 0,(function*(){this.isAuthenticated&&(v(this,
|
|
1004
|
+
*/disconnect(){return f(this,void 0,void 0,(function*(){this.isAuthenticated&&(v(this,wt,"m",Et).call(this,"state","unauthenticated"),this.isAuthenticated=!1,this.walletAddress=null,this.userId=null,this.jwt=null,this.origin=null,A(this,bt,void 0,"f"),yield v(this,Ct,"f").removeItem("camp-sdk:wallet-address"),yield v(this,Ct,"f").removeItem("camp-sdk:user-id"),yield v(this,Ct,"f").removeItem("camp-sdk:jwt"),yield v(this,Ct,"f").removeItem("camp-sdk:environment"))}))}
|
|
973
1005
|
/**
|
|
974
1006
|
* Connect the user's wallet and sign the message.
|
|
975
1007
|
* @returns {Promise<{ success: boolean; message: string; walletAddress: string }>} A promise that resolves with the authentication result.
|
|
976
1008
|
* @throws {APIError} - Throws an error if the user cannot be authenticated.
|
|
977
|
-
*/connect(){return f(this,void 0,void 0,(function*(){v(this,
|
|
1009
|
+
*/connect(){return f(this,void 0,void 0,(function*(){v(this,wt,"m",Et).call(this,"state","loading");try{this.walletAddress||(yield v(this,wt,"m",Pt).call(this)),this.walletAddress=s(this.walletAddress);const e=yield v(this,wt,"m",Rt).call(this),t=v(this,wt,"m",Dt).call(this,e),n=yield this.viem.signMessage({account:this.walletAddress,message:t}),i=yield v(this,wt,"m",_t).call(this,t,n);if(i.success)return this.isAuthenticated=!0,this.userId=i.userId,this.jwt=i.token,this.origin=new Nt(this.environment,this.jwt,this.viem,this.baseParentId,this.appId),yield v(this,Ct,"f").setItem("camp-sdk:jwt",this.jwt),yield v(this,Ct,"f").setItem("camp-sdk:wallet-address",this.walletAddress),yield v(this,Ct,"f").setItem("camp-sdk:user-id",this.userId),yield v(this,Ct,"f").setItem("camp-sdk:environment",this.environment.NAME),v(this,wt,"m",Et).call(this,"state","authenticated"),{success:!0,message:"Successfully authenticated",walletAddress:this.walletAddress};throw this.isAuthenticated=!1,v(this,wt,"m",Et).call(this,"state","unauthenticated"),new _("Failed to authenticate: signature verification failed")}catch(e){if(this.isAuthenticated=!1,v(this,wt,"m",Et).call(this,"state","unauthenticated"),e instanceof _||e instanceof x)throw e;throw new _(`Failed to authenticate: ${M(e)}`)}}))}
|
|
978
1010
|
/**
|
|
979
1011
|
* Connect with a custom signer (for Node.js or custom wallet implementations).
|
|
980
1012
|
* This method bypasses browser wallet interactions and uses the provided signer directly.
|
|
@@ -993,9 +1025,9 @@ if(!h&&(m.uuid||m.name))for(const e of T)try{if(m.uuid&&(null===(u=e.info)||void
|
|
|
993
1025
|
* const account = privateKeyToAccount('0x...');
|
|
994
1026
|
* const client = createWalletClient({ account, chain: mainnet, transport: http() });
|
|
995
1027
|
* await auth.connectWithSigner(client);
|
|
996
|
-
*/connectWithSigner(e,t){return f(this,void 0,void 0,(function*(){v(this,
|
|
1028
|
+
*/connectWithSigner(e,t){return f(this,void 0,void 0,(function*(){v(this,wt,"m",Et).call(this,"state","loading");try{A(this,bt,b(e),"f"),this.walletAddress=s(yield v(this,bt,"f").getAddress()),
|
|
997
1029
|
// store the signer as viem client if it's a viem client, otherwise keep adapter
|
|
998
|
-
"viem"===v(this,
|
|
1030
|
+
"viem"===v(this,bt,"f").type&&(this.viem=e);const n=yield v(this,wt,"m",Rt).call(this),i=v(this,wt,"m",Dt).call(this,n,null==t?void 0:t.domain,null==t?void 0:t.uri),a=yield v(this,bt,"f").signMessage(i),r=yield v(this,wt,"m",_t).call(this,i,a);if(r.success)return this.isAuthenticated=!0,this.userId=r.userId,this.jwt=r.token,this.origin=new Nt(this.environment,this.jwt,this.viem,this.baseParentId,this.appId),yield v(this,Ct,"f").setItem("camp-sdk:jwt",this.jwt),yield v(this,Ct,"f").setItem("camp-sdk:wallet-address",this.walletAddress),yield v(this,Ct,"f").setItem("camp-sdk:user-id",this.userId),yield v(this,Ct,"f").setItem("camp-sdk:environment",this.environment.NAME),v(this,wt,"m",Et).call(this,"state","authenticated"),{success:!0,message:"Successfully authenticated",walletAddress:this.walletAddress};throw this.isAuthenticated=!1,v(this,wt,"m",Et).call(this,"state","unauthenticated"),new _("Failed to authenticate: signature verification failed")}catch(e){if(this.isAuthenticated=!1,A(this,bt,void 0,"f"),v(this,wt,"m",Et).call(this,"state","unauthenticated"),e instanceof _||e instanceof x)throw e;throw new _(`Failed to authenticate: ${M(e)}`)}}))}
|
|
999
1031
|
/**
|
|
1000
1032
|
* Get the user's linked social accounts.
|
|
1001
1033
|
* @returns {Promise<Record<string, boolean>>} A promise that resolves with the user's linked social accounts.
|
|
@@ -1009,17 +1041,17 @@ if(!h&&(m.uuid||m.name))for(const e of T)try{if(m.uuid&&(null===(u=e.info)||void
|
|
|
1009
1041
|
* Link the user's Twitter account.
|
|
1010
1042
|
* @returns {Promise<void>}
|
|
1011
1043
|
* @throws {Error} - Throws an error if the user is not authenticated or in Node.js environment.
|
|
1012
|
-
*/linkTwitter(){return f(this,void 0,void 0,(function*(){if(!this.isAuthenticated)throw new N("User must be authenticated to link Twitter account");if(v(this,
|
|
1044
|
+
*/linkTwitter(){return f(this,void 0,void 0,(function*(){if(!this.isAuthenticated)throw new N("User must be authenticated to link Twitter account");if(v(this,gt,"f"))throw new _("Cannot link Twitter: OAuth flow requires a browser environment");window.location.href=`${this.environment.AUTH_HUB_BASE_API}/twitter/connect?clientId=${this.clientId}&userId=${this.userId}&redirect_url=${this.redirectUri.twitter}`}))}
|
|
1013
1045
|
/**
|
|
1014
1046
|
* Link the user's Discord account.
|
|
1015
1047
|
* @returns {Promise<void>}
|
|
1016
1048
|
* @throws {Error} - Throws an error if the user is not authenticated or in Node.js environment.
|
|
1017
|
-
*/linkDiscord(){return f(this,void 0,void 0,(function*(){if(!this.isAuthenticated)throw new N("User must be authenticated to link Discord account");if(v(this,
|
|
1049
|
+
*/linkDiscord(){return f(this,void 0,void 0,(function*(){if(!this.isAuthenticated)throw new N("User must be authenticated to link Discord account");if(v(this,gt,"f"))throw new _("Cannot link Discord: OAuth flow requires a browser environment");window.location.href=`${this.environment.AUTH_HUB_BASE_API}/discord/connect?clientId=${this.clientId}&userId=${this.userId}&redirect_url=${this.redirectUri.discord}`}))}
|
|
1018
1050
|
/**
|
|
1019
1051
|
* Link the user's Spotify account.
|
|
1020
1052
|
* @returns {Promise<void>}
|
|
1021
1053
|
* @throws {Error} - Throws an error if the user is not authenticated or in Node.js environment.
|
|
1022
|
-
*/linkSpotify(){return f(this,void 0,void 0,(function*(){if(!this.isAuthenticated)throw new N("User must be authenticated to link Spotify account");if(v(this,
|
|
1054
|
+
*/linkSpotify(){return f(this,void 0,void 0,(function*(){if(!this.isAuthenticated)throw new N("User must be authenticated to link Spotify account");if(v(this,gt,"f"))throw new _("Cannot link Spotify: OAuth flow requires a browser environment");window.location.href=`${this.environment.AUTH_HUB_BASE_API}/spotify/connect?clientId=${this.clientId}&userId=${this.userId}&redirect_url=${this.redirectUri.spotify}`}))}
|
|
1023
1055
|
/**
|
|
1024
1056
|
* Link the user's TikTok account.
|
|
1025
1057
|
* @param {string} handle The user's TikTok handle.
|
|
@@ -1069,4 +1101,4 @@ if(!h&&(m.uuid||m.name))for(const e of T)try{if(m.uuid&&(null===(u=e.info)||void
|
|
|
1069
1101
|
* @returns {Promise<any>} A promise that resolves with the unlink result.
|
|
1070
1102
|
* @throws {Error} - Throws an error if the user is not authenticated.
|
|
1071
1103
|
* @throws {APIError} - Throws an error if the request fails.
|
|
1072
|
-
*/unlinkTelegram(){return f(this,void 0,void 0,(function*(){if(!this.isAuthenticated)throw new N("User must be authenticated to unlink Telegram account");const e=yield fetch(`${this.environment.AUTH_HUB_BASE_API}/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 _(e.message||"Failed to unlink Telegram account");return e.data}))}}
|
|
1104
|
+
*/unlinkTelegram(){return f(this,void 0,void 0,(function*(){if(!this.isAuthenticated)throw new N("User must be authenticated to unlink Telegram account");const e=yield fetch(`${this.environment.AUTH_HUB_BASE_API}/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 _(e.message||"Failed to unlink Telegram account");return e.data}))}}It=new WeakMap,gt=new WeakMap,bt=new WeakMap,Ct=new WeakMap,wt=new WeakSet,Et=function(e,t){v(this,It,"f")[e]&&v(this,It,"f")[e].forEach((e=>e(t)))},St=function(e){return f(this,void 0,void 0,(function*(){const t=yield v(this,Ct,"f").getItem("camp-sdk:wallet-address"),n=yield v(this,Ct,"f").getItem("camp-sdk:user-id"),i=yield v(this,Ct,"f").getItem("camp-sdk:jwt"),a=yield v(this,Ct,"f").getItem("camp-sdk:environment");t&&n&&i&&(a===this.environment.NAME||!a)?(this.walletAddress=t,this.userId=n,this.jwt=i,this.origin=new Nt(this.environment,this.jwt,this.viem,this.baseParentId,this.appId),this.isAuthenticated=!0,e?this.setProvider({provider:e.provider,info:e.info||{name:"Unknown"},address:t}):v(this,gt,"f")||(console.warn("No matching provider was given for the stored wallet address. Trying to recover provider."),yield this.recoverProvider())):this.isAuthenticated=!1}))},Pt=function(){return f(this,void 0,void 0,(function*(){try{const[e]=yield this.viem.requestAddresses();return this.walletAddress=s(e),this.walletAddress}catch(e){throw new x(`Failed to connect wallet: ${M(e)}`)}}))},Rt=function(){return f(this,void 0,void 0,(function*(){try{const e=yield fetch(`${this.environment.AUTH_HUB_BASE_API}/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();if(200!==e.status)throw new _(t.message||`Failed to fetch nonce (HTTP ${e.status})`,e.status);return t.data}catch(e){if(e instanceof _)throw e;throw new _(`Failed to fetch nonce: ${M(e)}`)}}))},_t=function(e,t){return f(this,void 0,void 0,(function*(){try{const n=yield fetch(`${this.environment.AUTH_HUB_BASE_API}/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],s=JSON.parse(atob(a));return{success:!i.isError,userId:s.id,token:i.data}}catch(e){throw new _(`Failed to verify signature: ${M(e)}`)}}))},Dt=function(e,t,n){return h({domain:t||(v(this,gt,"f")?"localhost":window.location.host),address:this.walletAddress,statement:J,uri:n||(v(this,gt,"f")?"http://localhost":window.location.origin),version:"1",chainId:this.environment.CHAIN.id,nonce:e})};export{xt as Auth,C as BrowserStorage,g as CustomSignerAdapter,Se as DataStatus,Pe as DisputeStatus,I as EthersSignerAdapter,Ee as LicenseType,E as MemoryStorage,Nt as Origin,w as ViemSignerAdapter,R as campMainnet,P as campTestnet,Re as createLicenseTerms,S as createNodeWalletClient,b as createSignerAdapter};
|