@campnetwork/origin 1.3.0-alpha.5 → 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 +82 -66
- package/dist/core.d.ts +26 -0
- package/dist/core.esm.d.ts +26 -0
- package/dist/core.esm.js +72 -56
- package/dist/react/index.esm.d.ts +26 -0
- package/dist/react/index.esm.js +66 -0
- package/package.json +1 -1
package/dist/core.d.ts
CHANGED
|
@@ -680,6 +680,31 @@ interface DisputeProgress {
|
|
|
680
680
|
*/
|
|
681
681
|
declare function getDisputeProgress(this: Origin, disputeId: bigint): Promise<DisputeProgress>;
|
|
682
682
|
|
|
683
|
+
interface DisputeRequirements {
|
|
684
|
+
bondAmount: bigint;
|
|
685
|
+
protocolFee: bigint;
|
|
686
|
+
totalRequired: bigint;
|
|
687
|
+
tokenAddress: Address;
|
|
688
|
+
isNativeToken: boolean;
|
|
689
|
+
userBalance: bigint;
|
|
690
|
+
hasSufficientBalance: boolean;
|
|
691
|
+
}
|
|
692
|
+
/**
|
|
693
|
+
* Gets the requirements for raising a dispute, including balance check.
|
|
694
|
+
*
|
|
695
|
+
* @param userAddress The address to check balance for.
|
|
696
|
+
* @returns A promise that resolves with the dispute requirements.
|
|
697
|
+
*
|
|
698
|
+
* @example
|
|
699
|
+
* ```typescript
|
|
700
|
+
* const requirements = await origin.getDisputeRequirements(walletAddress);
|
|
701
|
+
* if (!requirements.hasSufficientBalance) {
|
|
702
|
+
* console.log(`Need ${requirements.totalRequired} but only have ${requirements.userBalance}`);
|
|
703
|
+
* }
|
|
704
|
+
* ```
|
|
705
|
+
*/
|
|
706
|
+
declare function getDisputeRequirements(this: Origin, userAddress: Address): Promise<DisputeRequirements>;
|
|
707
|
+
|
|
683
708
|
/**
|
|
684
709
|
* Fractionalizes an IP NFT into fungible ERC20 tokens.
|
|
685
710
|
* The NFT is transferred to the fractionalizer contract and a new ERC20 token is created.
|
|
@@ -1058,6 +1083,7 @@ declare class Origin {
|
|
|
1058
1083
|
getDispute: typeof getDispute;
|
|
1059
1084
|
canVoteOnDispute: typeof canVoteOnDispute;
|
|
1060
1085
|
getDisputeProgress: typeof getDisputeProgress;
|
|
1086
|
+
getDisputeRequirements: typeof getDisputeRequirements;
|
|
1061
1087
|
fractionalize: typeof fractionalize;
|
|
1062
1088
|
redeem: typeof redeem;
|
|
1063
1089
|
getTokenForNFT: typeof getTokenForNFT;
|
package/dist/core.esm.d.ts
CHANGED
|
@@ -680,6 +680,31 @@ interface DisputeProgress {
|
|
|
680
680
|
*/
|
|
681
681
|
declare function getDisputeProgress(this: Origin, disputeId: bigint): Promise<DisputeProgress>;
|
|
682
682
|
|
|
683
|
+
interface DisputeRequirements {
|
|
684
|
+
bondAmount: bigint;
|
|
685
|
+
protocolFee: bigint;
|
|
686
|
+
totalRequired: bigint;
|
|
687
|
+
tokenAddress: Address;
|
|
688
|
+
isNativeToken: boolean;
|
|
689
|
+
userBalance: bigint;
|
|
690
|
+
hasSufficientBalance: boolean;
|
|
691
|
+
}
|
|
692
|
+
/**
|
|
693
|
+
* Gets the requirements for raising a dispute, including balance check.
|
|
694
|
+
*
|
|
695
|
+
* @param userAddress The address to check balance for.
|
|
696
|
+
* @returns A promise that resolves with the dispute requirements.
|
|
697
|
+
*
|
|
698
|
+
* @example
|
|
699
|
+
* ```typescript
|
|
700
|
+
* const requirements = await origin.getDisputeRequirements(walletAddress);
|
|
701
|
+
* if (!requirements.hasSufficientBalance) {
|
|
702
|
+
* console.log(`Need ${requirements.totalRequired} but only have ${requirements.userBalance}`);
|
|
703
|
+
* }
|
|
704
|
+
* ```
|
|
705
|
+
*/
|
|
706
|
+
declare function getDisputeRequirements(this: Origin, userAddress: Address): Promise<DisputeRequirements>;
|
|
707
|
+
|
|
683
708
|
/**
|
|
684
709
|
* Fractionalizes an IP NFT into fungible ERC20 tokens.
|
|
685
710
|
* The NFT is transferred to the fractionalizer contract and a new ERC20 token is created.
|
|
@@ -1058,6 +1083,7 @@ declare class Origin {
|
|
|
1058
1083
|
getDispute: typeof getDispute;
|
|
1059
1084
|
canVoteOnDispute: typeof canVoteOnDispute;
|
|
1060
1085
|
getDisputeProgress: typeof getDisputeProgress;
|
|
1086
|
+
getDisputeRequirements: typeof getDisputeRequirements;
|
|
1061
1087
|
fractionalize: typeof fractionalize;
|
|
1062
1088
|
redeem: typeof redeem;
|
|
1063
1089
|
getTokenForNFT: typeof getTokenForNFT;
|
package/dist/core.esm.js
CHANGED
|
@@ -448,6 +448,22 @@ const R=BigInt(Math.floor(Date.now()/1e3)),_=new Date(1e3*Number(v)),D=new Date(
|
|
|
448
448
|
N=new Date(1e3*Number(A+T)),x=A+T):(
|
|
449
449
|
// for raised disputes, voting ends after cooldown + judgement
|
|
450
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}}))}
|
|
451
467
|
/**
|
|
452
468
|
* Fractionalizes an IP NFT into fungible ERC20 tokens.
|
|
453
469
|
* The NFT is transferred to the fractionalizer contract and a new ERC20 token is created.
|
|
@@ -464,7 +480,7 @@ N=new Date(1e3*Number(v+h+T)),x=v+h+T);const k=(f===Pe.Raised||f===Pe.Asserted)&
|
|
|
464
480
|
* // Then fractionalize
|
|
465
481
|
* const result = await origin.fractionalize(1n);
|
|
466
482
|
* ```
|
|
467
|
-
*/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})}))}
|
|
468
484
|
/**
|
|
469
485
|
* Redeems an IP NFT by burning all of its fractional tokens.
|
|
470
486
|
* The caller must hold the entire supply of the NFT's fractional token.
|
|
@@ -478,7 +494,7 @@ N=new Date(1e3*Number(v+h+T)),x=v+h+T);const k=(f===Pe.Raised||f===Pe.Asserted)&
|
|
|
478
494
|
* // Requires holding 100% of the fractional token supply
|
|
479
495
|
* await origin.redeem(1n);
|
|
480
496
|
* ```
|
|
481
|
-
*/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})}))}
|
|
482
498
|
/**
|
|
483
499
|
* Gets the fractional ERC20 token address for a specific IP NFT.
|
|
484
500
|
* Returns zero address if the NFT has not been fractionalized.
|
|
@@ -495,7 +511,7 @@ N=new Date(1e3*Number(v+h+T)),x=v+h+T);const k=(f===Pe.Raised||f===Pe.Asserted)&
|
|
|
495
511
|
* console.log("NFT has not been fractionalized");
|
|
496
512
|
* }
|
|
497
513
|
* ```
|
|
498
|
-
*/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])}))}
|
|
499
515
|
/**
|
|
500
516
|
* Fractionalizes an IP NFT with automatic approval.
|
|
501
517
|
* This method first approves the fractionalizer contract to transfer your NFT,
|
|
@@ -509,7 +525,7 @@ N=new Date(1e3*Number(v+h+T)),x=v+h+T);const k=(f===Pe.Raised||f===Pe.Asserted)&
|
|
|
509
525
|
* // Single call handles approval and fractionalization
|
|
510
526
|
* const result = await origin.fractionalizeWithApproval(1n);
|
|
511
527
|
* ```
|
|
512
|
-
*/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})}))}
|
|
513
529
|
/**
|
|
514
530
|
* Redeems fractional tokens for the underlying NFT, but only if the caller owns 100% of the supply.
|
|
515
531
|
* This method checks the caller's balance before attempting to redeem, providing a clear error
|
|
@@ -528,7 +544,7 @@ N=new Date(1e3*Number(v+h+T)),x=v+h+T);const k=(f===Pe.Raised||f===Pe.Asserted)&
|
|
|
528
544
|
* console.log("You don't own all fractional tokens yet");
|
|
529
545
|
* }
|
|
530
546
|
* ```
|
|
531
|
-
*/function
|
|
547
|
+
*/function Ke(e){return f(this,void 0,void 0,(function*(){
|
|
532
548
|
// get the ERC20 token address for this NFT
|
|
533
549
|
const t=yield this.getTokenForNFT(e);if(!t||"0x0000000000000000000000000000000000000000"===t)throw new Error("This NFT has not been fractionalized");
|
|
534
550
|
// get current wallet address
|
|
@@ -538,7 +554,7 @@ if(s<r){const e=s*BigInt(1e4)/r;throw new Error(`Cannot redeem: you own ${e/BigI
|
|
|
538
554
|
// proceed with redemption
|
|
539
555
|
return this.callContractMethod(this.environment.FRACTIONALIZER_CONTRACT_ADDRESS,this.environment.FRACTIONALIZER_ABI,"redeem",[e],{waitForReceipt:!0})}))}
|
|
540
556
|
// minimal ERC20 ABI
|
|
541
|
-
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"}];
|
|
542
558
|
/**
|
|
543
559
|
* Gets a user's ownership percentage of a fractionalized NFT.
|
|
544
560
|
* Returns detailed information about the user's fractional token holdings.
|
|
@@ -563,10 +579,10 @@ const Ke=[{inputs:[{name:"owner",type:"address"}],name:"balanceOf",outputs:[{nam
|
|
|
563
579
|
* }
|
|
564
580
|
* }
|
|
565
581
|
* ```
|
|
566
|
-
*/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);
|
|
567
583
|
// get the ERC20 token address for this NFT
|
|
568
584
|
// check if fractionalized
|
|
569
|
-
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:[]})]);
|
|
570
586
|
// fetch ERC20 data
|
|
571
587
|
// calculate ownership percentage
|
|
572
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}}))}
|
|
@@ -593,7 +609,7 @@ let u=0;o>BigInt(0)&&(u=Number(s*BigInt(1e4)/o)/100);const p=s>=o&&o>BigInt(0);r
|
|
|
593
609
|
* console.log(`Cannot fractionalize: ${eligibility.reason}`);
|
|
594
610
|
* }
|
|
595
611
|
* ```
|
|
596
|
-
*/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};
|
|
597
613
|
// check requirements
|
|
598
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}`})}))}
|
|
599
615
|
/**
|
|
@@ -609,13 +625,13 @@ return l?y?Object.assign(Object.assign({},m),{reason:`This NFT is already fracti
|
|
|
609
625
|
* console.log(`Revenue Share: ${appInfo.revenueShareBps / 100}%`);
|
|
610
626
|
* console.log(`Active: ${appInfo.isActive}`);
|
|
611
627
|
* ```
|
|
612
|
-
*/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])}))}
|
|
613
629
|
/**
|
|
614
630
|
* Approves a spender to spend a specified amount of tokens on behalf of the owner.
|
|
615
631
|
* If the current allowance is less than the specified amount, it will perform the approval.
|
|
616
632
|
* Waits for the approval transaction to be confirmed before returning.
|
|
617
633
|
* @param {ApproveParams} params - The parameters for the approval.
|
|
618
|
-
*/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});
|
|
619
635
|
// Wait for the approval transaction to be confirmed with extra confirmations
|
|
620
636
|
yield t.waitForTransactionReceipt({hash:o,confirmations:2}),yield new Promise((e=>setTimeout(e,1e3)))}}))}
|
|
621
637
|
/**
|
|
@@ -636,7 +652,7 @@ yield t.waitForTransactionReceipt({hash:o,confirmations:2}),yield new Promise((e
|
|
|
636
652
|
* const totalValue = 3000000000000000n;
|
|
637
653
|
* await origin.bulkBuyAccess(buyerAddress, purchases, totalValue);
|
|
638
654
|
* ```
|
|
639
|
-
*/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})}
|
|
640
656
|
/**
|
|
641
657
|
* Executes a fault-tolerant bulk purchase of multiple IP-NFT licenses.
|
|
642
658
|
* Individual purchases can fail without reverting the entire transaction.
|
|
@@ -653,7 +669,7 @@ yield t.waitForTransactionReceipt({hash:o,confirmations:2}),yield new Promise((e
|
|
|
653
669
|
* console.log(`Purchased ${result.successCount} of ${purchases.length} IPs`);
|
|
654
670
|
* console.log(`Failed tokens: ${result.failedTokenIds}`);
|
|
655
671
|
* ```
|
|
656
|
-
*/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})}
|
|
657
673
|
/**
|
|
658
674
|
* Previews the total cost of purchasing multiple IP-NFT licenses.
|
|
659
675
|
* This is a view function that doesn't require a transaction.
|
|
@@ -667,7 +683,7 @@ yield t.waitForTransactionReceipt({hash:o,confirmations:2}),yield new Promise((e
|
|
|
667
683
|
* console.log(`Total cost: ${preview.totalNativeCost} wei`);
|
|
668
684
|
* console.log(`Valid tokens: ${preview.validCount}`);
|
|
669
685
|
* ```
|
|
670
|
-
*/function
|
|
686
|
+
*/function st(e){return this.callContractMethod(this.environment.BATCH_PURCHASE_CONTRACT_ADDRESS,this.environment.BATCH_PURCHASE_ABI,"previewBulkCost",[e])}
|
|
671
687
|
/**
|
|
672
688
|
* Builds purchase parameters for multiple tokens by fetching their current license terms.
|
|
673
689
|
* This is a view function that doesn't require a transaction.
|
|
@@ -680,7 +696,7 @@ yield t.waitForTransactionReceipt({hash:o,confirmations:2}),yield new Promise((e
|
|
|
680
696
|
* const params = await origin.buildPurchaseParams([1n, 2n, 3n]);
|
|
681
697
|
* await origin.bulkBuyAccess(buyer, params, totalValue);
|
|
682
698
|
* ```
|
|
683
|
-
*/function
|
|
699
|
+
*/function rt(e){return this.callContractMethod(this.environment.BATCH_PURCHASE_CONTRACT_ADDRESS,this.environment.BATCH_PURCHASE_ABI,"buildPurchaseParams",[e])}
|
|
684
700
|
/**
|
|
685
701
|
* Checks the active status of multiple tokens.
|
|
686
702
|
*
|
|
@@ -692,7 +708,7 @@ yield t.waitForTransactionReceipt({hash:o,confirmations:2}),yield new Promise((e
|
|
|
692
708
|
* const activeFlags = await origin.checkActiveStatus([1n, 2n, 3n]);
|
|
693
709
|
* const activeTokens = tokenIds.filter((_, i) => activeFlags[i]);
|
|
694
710
|
* ```
|
|
695
|
-
*/function
|
|
711
|
+
*/function ot(e){return this.callContractMethod(this.environment.BATCH_PURCHASE_CONTRACT_ADDRESS,this.environment.BATCH_PURCHASE_ABI,"checkActiveStatus",[e])}
|
|
696
712
|
/**
|
|
697
713
|
* Smart bulk purchase that automatically fetches terms and handles the entire purchase flow.
|
|
698
714
|
* This is the recommended method for most use cases.
|
|
@@ -709,7 +725,7 @@ yield t.waitForTransactionReceipt({hash:o,confirmations:2}),yield new Promise((e
|
|
|
709
725
|
* // Tolerant purchase - continue even if some fail
|
|
710
726
|
* const result = await origin.bulkBuyAccessSmart([1n, 2n, 3n], { tolerant: true });
|
|
711
727
|
* ```
|
|
712
|
-
*/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.");
|
|
713
729
|
// Get the buyer's wallet address
|
|
714
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]}
|
|
715
731
|
// Build purchase params from on-chain data
|
|
@@ -719,38 +735,38 @@ let s=BigInt(0);const o=[];for(const e of a)if(e.expectedPaymentToken===r)s+=e.e
|
|
|
719
735
|
// Group ERC20 purchases by token
|
|
720
736
|
const t=o.find((t=>t.token===e.expectedPaymentToken));t?t.amount+=e.expectedPrice:o.push({token:e.expectedPaymentToken,amount:e.expectedPrice})}
|
|
721
737
|
// Approve ERC20 tokens if needed
|
|
722
|
-
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});
|
|
723
739
|
// Execute the purchase
|
|
724
|
-
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;
|
|
725
741
|
/**
|
|
726
742
|
* The Origin class
|
|
727
743
|
* Handles interactions with Origin protocol.
|
|
728
|
-
*/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,
|
|
729
745
|
// DataNFT methods
|
|
730
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),
|
|
731
747
|
// Marketplace methods
|
|
732
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),
|
|
733
749
|
// Bulk purchase methods
|
|
734
|
-
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),
|
|
735
751
|
// Dispute module methods
|
|
736
|
-
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),
|
|
737
753
|
// Fractionalizer module methods
|
|
738
|
-
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),
|
|
739
755
|
// AppRegistry module methods
|
|
740
|
-
this.getAppInfo=
|
|
756
|
+
this.getAppInfo=tt.bind(this)}getJwt(){return this.jwt}setViemClient(e){this.viemClient=e}
|
|
741
757
|
/**
|
|
742
758
|
* Approves an ERC20 token for spending by a spender address if the current allowance is insufficient.
|
|
743
759
|
* Waits for the approval transaction to be confirmed before returning.
|
|
744
760
|
* @param tokenAddress The address of the ERC20 token.
|
|
745
761
|
* @param spender The address that will be approved to spend the tokens.
|
|
746
762
|
* @param amount The amount of tokens to approve.
|
|
747
|
-
*/approveERC20IfNeeded(e,t,n){return f(this,void 0,void 0,(function*(){const i=yield v(this,
|
|
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})}))}
|
|
748
764
|
/**
|
|
749
765
|
* Uploads a JSON object to IPFS and returns the resulting CID.
|
|
750
766
|
* @param data The JSON object to upload.
|
|
751
767
|
* @returns The CID of the uploaded JSON.
|
|
752
768
|
* @throws {APIError} If the upload fails.
|
|
753
|
-
*/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}))}
|
|
754
770
|
/**
|
|
755
771
|
* Mints a file-based IpNFT.
|
|
756
772
|
* @param file The file to mint.
|
|
@@ -759,17 +775,17 @@ this.getAppInfo=et.bind(this)}getJwt(){return this.jwt}setViemClient(e){this.vie
|
|
|
759
775
|
* @param parents Optional parent token IDs for lineage tracking.
|
|
760
776
|
* @param options Optional parameters including progress callback, preview image, and use asset as preview flag.
|
|
761
777
|
* @returns The token ID of the minted IpNFT as a string, or null if minting failed.
|
|
762
|
-
*/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
|
|
763
779
|
let u;this.baseParentId&&(i||(i=[]),i.unshift(this.baseParentId));try{u=yield this.registerIpNFT("file",d,n,t,!0,// isIp
|
|
764
780
|
s.key,// fileKey
|
|
765
|
-
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()}))}
|
|
766
782
|
/**
|
|
767
783
|
* Mints a social IpNFT.
|
|
768
784
|
* @param source The social media source (spotify, twitter, tiktok).
|
|
769
785
|
* @param metadata The metadata associated with the social media content.
|
|
770
786
|
* @param license The license terms for the IpNFT.
|
|
771
787
|
* @return The token ID of the minted IpNFT as a string, or null if minting failed.
|
|
772
|
-
*/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
|
|
773
789
|
let s,r=this.baseParentId?[this.baseParentId]:[];try{s=yield this.registerIpNFT(e,a,n,t,!0,// isIp
|
|
774
790
|
void 0,// fileKey
|
|
775
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()}))}
|
|
@@ -782,9 +798,9 @@ r,this.appId)}catch(e){throw new Error(`Failed to register Social IpNFT: ${e ins
|
|
|
782
798
|
* @param {CallOptions} [options] The call options.
|
|
783
799
|
* @returns {Promise<any>} A promise that resolves with the result of the contract call or transaction hash.
|
|
784
800
|
* @throws {Error} - Throws an error if the wallet client is not connected and the method is not a view function.
|
|
785
|
-
*/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});
|
|
786
802
|
// simulate
|
|
787
|
-
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})}}))}
|
|
788
804
|
/**
|
|
789
805
|
* Gets comprehensive token information in a single call.
|
|
790
806
|
* Combines owner, status, terms, URI, and access information.
|
|
@@ -826,13 +842,13 @@ let u=!1,p=null;if("0x0000000000000000000000000000000000000000"!==i)try{[u,p]=yi
|
|
|
826
842
|
* console.log("Access purchased:", result.txHash);
|
|
827
843
|
* }
|
|
828
844
|
* ```
|
|
829
|
-
*/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.`)}
|
|
830
846
|
// Check if user already has access
|
|
831
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`);
|
|
832
848
|
// Fetch protocol fee from marketplace
|
|
833
|
-
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;
|
|
834
850
|
// Fetch app fee from token's appId
|
|
835
|
-
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))}))}
|
|
836
852
|
/**
|
|
837
853
|
* Fetch the underlying data associated with a specific token ID.
|
|
838
854
|
* @param {bigint} tokenId - The token ID to fetch data for.
|
|
@@ -882,7 +898,7 @@ const e=[{inputs:[{name:"owner",type:"address"}],name:"balanceOf",outputs:[{name
|
|
|
882
898
|
* // Claim ERC20 token royalties to a specific address
|
|
883
899
|
* await origin.claimRoyalties(1n, "0xRecipient...", "0xToken...");
|
|
884
900
|
* ```
|
|
885
|
-
*/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;
|
|
886
902
|
// Call execute on the TBA
|
|
887
903
|
return n&&n!==r?(
|
|
888
904
|
// ERC20 token transfer
|
|
@@ -891,16 +907,16 @@ d=n,u=BigInt(0),
|
|
|
891
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]})):(
|
|
892
908
|
// Native token transfer
|
|
893
909
|
d=i,u=o,p="0x"),this.callContractMethod(s,this.environment.TBA_ABI,"execute",[d,u,p,0],// operation: 0 = CALL
|
|
894
|
-
{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){
|
|
895
911
|
// fallback
|
|
896
|
-
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
|
|
897
913
|
(e);try{yield this.viemClient.request({method:"wallet_switchEthereumChain",params:[{chainId:"0x"+BigInt(e.id).toString(16)}]})}catch(t){
|
|
898
914
|
// Unrecognized chain
|
|
899
|
-
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.");
|
|
900
916
|
// If account is already set on the client, return it directly
|
|
901
917
|
if(this.viemClient.account)return this.viemClient.account.address;
|
|
902
918
|
// Otherwise request accounts (browser wallet flow)
|
|
903
|
-
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{
|
|
904
920
|
// First, get the token info to find its appId
|
|
905
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;
|
|
906
922
|
// Check if app registry is configured
|
|
@@ -908,7 +924,7 @@ if(!this.environment.APP_REGISTRY_CONTRACT_ADDRESS||!this.environment.APP_REGIST
|
|
|
908
924
|
// Fetch app info from registry
|
|
909
925
|
const i=yield this.callContractMethod(this.environment.APP_REGISTRY_CONTRACT_ADDRESS,this.environment.APP_REGISTRY_ABI,"getAppInfo",[n]);
|
|
910
926
|
// Only return fee if app is active
|
|
911
|
-
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.");
|
|
912
928
|
// If account is already set on the client, return it directly
|
|
913
929
|
if(this.viemClient.account)return this.viemClient.account.address;
|
|
914
930
|
// Otherwise request accounts (browser wallet flow)
|
|
@@ -918,7 +934,7 @@ const t=yield this.viemClient.request({method:"eth_requestAccounts",params:[]});
|
|
|
918
934
|
* @class
|
|
919
935
|
* @classdesc The Auth class is used to authenticate the user.
|
|
920
936
|
*/
|
|
921
|
-
class
|
|
937
|
+
class xt{
|
|
922
938
|
/**
|
|
923
939
|
* Constructor for the Auth class.
|
|
924
940
|
* @param {object} options The options object.
|
|
@@ -928,9 +944,9 @@ class Nt{
|
|
|
928
944
|
* @param {StorageAdapter} [options.storage] Custom storage adapter. Defaults to localStorage in browser, memory storage in Node.js.
|
|
929
945
|
* @throws {APIError} - Throws an error if the clientId is not provided.
|
|
930
946
|
*/
|
|
931
|
-
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"),
|
|
932
948
|
// only subscribe to providers in browser environment
|
|
933
|
-
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)}
|
|
934
950
|
/**
|
|
935
951
|
* Subscribe to an event. Possible events are "state", "provider", "providers", and "viem".
|
|
936
952
|
* @param {("state"|"provider"|"providers"|"viem")} event The event.
|
|
@@ -940,18 +956,18 @@ v(this,It,"f")||te((e=>{v(this,At,"m",Ct).call(this,"providers",e)})),v(this,At,
|
|
|
940
956
|
* auth.on("state", (state) => {
|
|
941
957
|
* console.log(state);
|
|
942
958
|
* });
|
|
943
|
-
*/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())}
|
|
944
960
|
/**
|
|
945
961
|
* Unsubscribe from an event. Possible events are "state", "provider", "providers", and "viem".
|
|
946
962
|
* @param {("state"|"provider"|"providers"|"viem")} event The event.
|
|
947
963
|
* @param {function} callback The callback function.
|
|
948
964
|
* @returns {void}
|
|
949
|
-
*/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)))}
|
|
950
966
|
/**
|
|
951
967
|
* Set the loading state.
|
|
952
968
|
* @param {boolean} loading The loading state.
|
|
953
969
|
* @returns {void}
|
|
954
|
-
*/setLoading(e){v(this,
|
|
970
|
+
*/setLoading(e){v(this,wt,"m",Et).call(this,"state",e?"loading":this.isAuthenticated?"authenticated":"unauthenticated")}
|
|
955
971
|
/**
|
|
956
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.
|
|
957
973
|
* @param {object} options The options object. Includes the provider and the provider info.
|
|
@@ -959,7 +975,7 @@ v(this,It,"f")||te((e=>{v(this,At,"m",Ct).call(this,"providers",e)})),v(this,At,
|
|
|
959
975
|
* @throws {APIError} - Throws an error if the provider is not provided.
|
|
960
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),
|
|
961
977
|
// TODO: only use one of these
|
|
962
|
-
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))}
|
|
963
979
|
/**
|
|
964
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.
|
|
965
981
|
* @param {string} walletAddress The wallet address.
|
|
@@ -968,7 +984,7 @@ v(this,At,"m",Ct).call(this,"viem",this.viem),v(this,At,"m",Ct).call(this,"provi
|
|
|
968
984
|
/**
|
|
969
985
|
* Recover the provider from local storage.
|
|
970
986
|
* @returns {Promise<void>}
|
|
971
|
-
*/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:[];
|
|
972
988
|
// first pass: try to find provider by UUID/name and check if it has the right address
|
|
973
989
|
// without prompting (using eth_accounts)
|
|
974
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){
|
|
@@ -985,12 +1001,12 @@ if(!h&&(m.uuid||m.name))for(const e of T)try{if(m.uuid&&(null===(u=e.info)||void
|
|
|
985
1001
|
/**
|
|
986
1002
|
* Disconnect the user.
|
|
987
1003
|
* @returns {Promise<void>}
|
|
988
|
-
*/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"))}))}
|
|
989
1005
|
/**
|
|
990
1006
|
* Connect the user's wallet and sign the message.
|
|
991
1007
|
* @returns {Promise<{ success: boolean; message: string; walletAddress: string }>} A promise that resolves with the authentication result.
|
|
992
1008
|
* @throws {APIError} - Throws an error if the user cannot be authenticated.
|
|
993
|
-
*/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)}`)}}))}
|
|
994
1010
|
/**
|
|
995
1011
|
* Connect with a custom signer (for Node.js or custom wallet implementations).
|
|
996
1012
|
* This method bypasses browser wallet interactions and uses the provided signer directly.
|
|
@@ -1009,9 +1025,9 @@ if(!h&&(m.uuid||m.name))for(const e of T)try{if(m.uuid&&(null===(u=e.info)||void
|
|
|
1009
1025
|
* const account = privateKeyToAccount('0x...');
|
|
1010
1026
|
* const client = createWalletClient({ account, chain: mainnet, transport: http() });
|
|
1011
1027
|
* await auth.connectWithSigner(client);
|
|
1012
|
-
*/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()),
|
|
1013
1029
|
// store the signer as viem client if it's a viem client, otherwise keep adapter
|
|
1014
|
-
"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)}`)}}))}
|
|
1015
1031
|
/**
|
|
1016
1032
|
* Get the user's linked social accounts.
|
|
1017
1033
|
* @returns {Promise<Record<string, boolean>>} A promise that resolves with the user's linked social accounts.
|
|
@@ -1025,17 +1041,17 @@ if(!h&&(m.uuid||m.name))for(const e of T)try{if(m.uuid&&(null===(u=e.info)||void
|
|
|
1025
1041
|
* Link the user's Twitter account.
|
|
1026
1042
|
* @returns {Promise<void>}
|
|
1027
1043
|
* @throws {Error} - Throws an error if the user is not authenticated or in Node.js environment.
|
|
1028
|
-
*/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}`}))}
|
|
1029
1045
|
/**
|
|
1030
1046
|
* Link the user's Discord account.
|
|
1031
1047
|
* @returns {Promise<void>}
|
|
1032
1048
|
* @throws {Error} - Throws an error if the user is not authenticated or in Node.js environment.
|
|
1033
|
-
*/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}`}))}
|
|
1034
1050
|
/**
|
|
1035
1051
|
* Link the user's Spotify account.
|
|
1036
1052
|
* @returns {Promise<void>}
|
|
1037
1053
|
* @throws {Error} - Throws an error if the user is not authenticated or in Node.js environment.
|
|
1038
|
-
*/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}`}))}
|
|
1039
1055
|
/**
|
|
1040
1056
|
* Link the user's TikTok account.
|
|
1041
1057
|
* @param {string} handle The user's TikTok handle.
|
|
@@ -1085,4 +1101,4 @@ if(!h&&(m.uuid||m.name))for(const e of T)try{if(m.uuid&&(null===(u=e.info)||void
|
|
|
1085
1101
|
* @returns {Promise<any>} A promise that resolves with the unlink result.
|
|
1086
1102
|
* @throws {Error} - Throws an error if the user is not authenticated.
|
|
1087
1103
|
* @throws {APIError} - Throws an error if the request fails.
|
|
1088
|
-
*/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};
|