@campnetwork/origin 1.3.0-alpha.7 → 1.3.0-alpha.8
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 +6 -2
- package/dist/core.d.ts +11 -1
- package/dist/core.esm.d.ts +11 -1
- package/dist/core.esm.js +71 -68
- package/package.json +1 -1
package/dist/core.cjs
CHANGED
|
@@ -332,6 +332,9 @@ let y=i.repeat(a);for(;l<u;++l)y+=e.charAt(p[l]);return y},decodeUnsafe:r,decode
|
|
|
332
332
|
function ge(e){const t=Ie.decode(e);if(18!==t[0]||32!==t[1]||34!==t.length)throw new Error("Only CIDv0 with SHA-256 is supported");
|
|
333
333
|
// Return only the 32-byte digest (skip 0x1220 prefix)
|
|
334
334
|
return`0x${Buffer.from(t.slice(2)).toString("hex")}`}
|
|
335
|
+
/**
|
|
336
|
+
* Decode bytes32 back to CIDv0 by prepending 0x1220 multihash prefix.
|
|
337
|
+
*/
|
|
335
338
|
/**
|
|
336
339
|
* Raises a dispute with automatic evidence upload to IPFS.
|
|
337
340
|
* Uploads evidence JSON to IPFS, encodes the CID to bytes32 for on-chain storage,
|
|
@@ -360,7 +363,8 @@ return`0x${Buffer.from(t.slice(2)).toString("hex")}`}
|
|
|
360
363
|
* // Fetch evidence via IPFS gateway
|
|
361
364
|
* // https://ipfs.io/ipfs/{result.evidenceCid}
|
|
362
365
|
* ```
|
|
363
|
-
*/
|
|
366
|
+
*/
|
|
367
|
+
function be(e,t,n){return a(this,void 0,void 0,(function*(){const i=yield this.uploadJSONToIPFS(t),a=ge(i);return{transactionResult:yield this.raiseDispute(e,a,n),evidenceCid:i,evidenceHash:a}}))}
|
|
364
368
|
/**
|
|
365
369
|
* Asserts a dispute as the IP owner with counter-evidence.
|
|
366
370
|
* Must be called by the owner of the disputed IP within the cooldown period.
|
|
@@ -1193,4 +1197,4 @@ if(!T&&(h.uuid||h.name))for(const e of f)try{if(h.uuid&&(null===(p=e.info)||void
|
|
|
1193
1197
|
* @returns {Promise<any>} A promise that resolves with the unlink result.
|
|
1194
1198
|
* @throws {Error} - Throws an error if the user is not authenticated.
|
|
1195
1199
|
* @throws {APIError} - Throws an error if the request fails.
|
|
1196
|
-
*/unlinkTelegram(){return a(this,void 0,void 0,(function*(){if(!this.isAuthenticated)throw new f("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 h(e.message||"Failed to unlink Telegram account");return e.data}))}},exports.BrowserStorage=l,exports.CustomSignerAdapter=u,exports.EthersSignerAdapter=d,exports.MemoryStorage=y,exports.Origin=At,exports.ViemSignerAdapter=o,exports.campMainnet=m,exports.campTestnet=c,exports.createLicenseTerms=(e,t,n,i,a=exports.LicenseType.DURATION_BASED)=>{if(n<F||n>O)throw new Error(`Royalty basis points must be between ${F} and ${O}`);if(a===exports.LicenseType.DURATION_BASED){if(t<M||t>k)throw new Error(`Duration must be between ${M} and ${k} seconds for DURATION_BASED licenses`)}else if((a===exports.LicenseType.SINGLE_PAYMENT||a===exports.LicenseType.X402)&&t>0)throw new Error(`Duration must be 0 for ${exports.LicenseType[a]} licenses`);if(e<B)throw new Error(`Price must be at least ${B} wei`);return{price:e,duration:t,royaltyBps:n,paymentToken:i,licenseType:a}},exports.createNodeWalletClient=function(t,n,i){return e.createWalletClient({account:t,chain:n,transport:e.http(i)})},exports.createSignerAdapter=p;
|
|
1200
|
+
*/unlinkTelegram(){return a(this,void 0,void 0,(function*(){if(!this.isAuthenticated)throw new f("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 h(e.message||"Failed to unlink Telegram account");return e.data}))}},exports.BrowserStorage=l,exports.CustomSignerAdapter=u,exports.EthersSignerAdapter=d,exports.MemoryStorage=y,exports.Origin=At,exports.ViemSignerAdapter=o,exports.campMainnet=m,exports.campTestnet=c,exports.createLicenseTerms=(e,t,n,i,a=exports.LicenseType.DURATION_BASED)=>{if(n<F||n>O)throw new Error(`Royalty basis points must be between ${F} and ${O}`);if(a===exports.LicenseType.DURATION_BASED){if(t<M||t>k)throw new Error(`Duration must be between ${M} and ${k} seconds for DURATION_BASED licenses`)}else if((a===exports.LicenseType.SINGLE_PAYMENT||a===exports.LicenseType.X402)&&t>0)throw new Error(`Duration must be 0 for ${exports.LicenseType[a]} licenses`);if(e<B)throw new Error(`Price must be at least ${B} wei`);return{price:e,duration:t,royaltyBps:n,paymentToken:i,licenseType:a}},exports.createNodeWalletClient=function(t,n,i){return e.createWalletClient({account:t,chain:n,transport:e.http(i)})},exports.createSignerAdapter=p,exports.decodeCidFromBytes32=function(e){const t=Buffer.from(e.slice(2),"hex"),n=Buffer.concat([Buffer.from([18,32]),t]);return Ie.encode(n)},exports.encodeCidToBytes32=ge;
|
package/dist/core.d.ts
CHANGED
|
@@ -488,6 +488,16 @@ interface RaiseDisputeSmartResult {
|
|
|
488
488
|
*/
|
|
489
489
|
declare function raiseDisputeSmart(this: Origin, targetIpId: bigint, evidence: Record<string, any>, disputeTag: Hex): Promise<RaiseDisputeSmartResult>;
|
|
490
490
|
|
|
491
|
+
/**
|
|
492
|
+
* Encode CIDv0 to bytes32 by stripping the 0x1220 multihash prefix.
|
|
493
|
+
* Only works with CIDv0 (SHA-256 hash, starts with "Qm").
|
|
494
|
+
*/
|
|
495
|
+
declare function encodeCidToBytes32(cid: string): Hex;
|
|
496
|
+
/**
|
|
497
|
+
* Decode bytes32 back to CIDv0 by prepending 0x1220 multihash prefix.
|
|
498
|
+
*/
|
|
499
|
+
declare function decodeCidFromBytes32(bytes32: Hex): string;
|
|
500
|
+
|
|
491
501
|
/**
|
|
492
502
|
* Asserts a dispute as the IP owner with counter-evidence.
|
|
493
503
|
* Must be called by the owner of the disputed IP within the cooldown period.
|
|
@@ -1493,4 +1503,4 @@ declare class Auth {
|
|
|
1493
1503
|
unlinkTelegram(): Promise<any>;
|
|
1494
1504
|
}
|
|
1495
1505
|
|
|
1496
|
-
export { type AppInfo, Auth, type BaseSigner, BrowserStorage, type BulkCostPreview, type BuyParams, CustomSignerAdapter, DataStatus, type Dispute, type DisputeProgress, DisputeStatus, EthersSignerAdapter, type FractionOwnership, type FractionalizeEligibility, type LicenseTerms, LicenseType, MemoryStorage, Origin, type SignerAdapter, type SignerType, type StorageAdapter, type TokenInfo, type TolerantResult, ViemSignerAdapter, type VoteEligibility, mainnet as campMainnet, testnet as campTestnet, createLicenseTerms, createNodeWalletClient, createSignerAdapter };
|
|
1506
|
+
export { type AppInfo, Auth, type BaseSigner, BrowserStorage, type BulkCostPreview, type BuyParams, CustomSignerAdapter, DataStatus, type Dispute, type DisputeProgress, DisputeStatus, EthersSignerAdapter, type FractionOwnership, type FractionalizeEligibility, type LicenseTerms, LicenseType, MemoryStorage, Origin, type SignerAdapter, type SignerType, type StorageAdapter, type TokenInfo, type TolerantResult, ViemSignerAdapter, type VoteEligibility, mainnet as campMainnet, testnet as campTestnet, createLicenseTerms, createNodeWalletClient, createSignerAdapter, decodeCidFromBytes32, encodeCidToBytes32 };
|
package/dist/core.esm.d.ts
CHANGED
|
@@ -488,6 +488,16 @@ interface RaiseDisputeSmartResult {
|
|
|
488
488
|
*/
|
|
489
489
|
declare function raiseDisputeSmart(this: Origin, targetIpId: bigint, evidence: Record<string, any>, disputeTag: Hex): Promise<RaiseDisputeSmartResult>;
|
|
490
490
|
|
|
491
|
+
/**
|
|
492
|
+
* Encode CIDv0 to bytes32 by stripping the 0x1220 multihash prefix.
|
|
493
|
+
* Only works with CIDv0 (SHA-256 hash, starts with "Qm").
|
|
494
|
+
*/
|
|
495
|
+
declare function encodeCidToBytes32(cid: string): Hex;
|
|
496
|
+
/**
|
|
497
|
+
* Decode bytes32 back to CIDv0 by prepending 0x1220 multihash prefix.
|
|
498
|
+
*/
|
|
499
|
+
declare function decodeCidFromBytes32(bytes32: Hex): string;
|
|
500
|
+
|
|
491
501
|
/**
|
|
492
502
|
* Asserts a dispute as the IP owner with counter-evidence.
|
|
493
503
|
* Must be called by the owner of the disputed IP within the cooldown period.
|
|
@@ -1493,4 +1503,4 @@ declare class Auth {
|
|
|
1493
1503
|
unlinkTelegram(): Promise<any>;
|
|
1494
1504
|
}
|
|
1495
1505
|
|
|
1496
|
-
export { type AppInfo, Auth, type BaseSigner, BrowserStorage, type BulkCostPreview, type BuyParams, CustomSignerAdapter, DataStatus, type Dispute, type DisputeProgress, DisputeStatus, EthersSignerAdapter, type FractionOwnership, type FractionalizeEligibility, type LicenseTerms, LicenseType, MemoryStorage, Origin, type SignerAdapter, type SignerType, type StorageAdapter, type TokenInfo, type TolerantResult, ViemSignerAdapter, type VoteEligibility, mainnet as campMainnet, testnet as campTestnet, createLicenseTerms, createNodeWalletClient, createSignerAdapter };
|
|
1506
|
+
export { type AppInfo, Auth, type BaseSigner, BrowserStorage, type BulkCostPreview, type BuyParams, CustomSignerAdapter, DataStatus, type Dispute, type DisputeProgress, DisputeStatus, EthersSignerAdapter, type FractionOwnership, type FractionalizeEligibility, type LicenseTerms, LicenseType, MemoryStorage, Origin, type SignerAdapter, type SignerType, type StorageAdapter, type TokenInfo, type TolerantResult, ViemSignerAdapter, type VoteEligibility, mainnet as campMainnet, testnet as campTestnet, createLicenseTerms, createNodeWalletClient, createSignerAdapter, decodeCidFromBytes32, encodeCidToBytes32 };
|
package/dist/core.esm.js
CHANGED
|
@@ -315,6 +315,9 @@ let y=i.repeat(a);for(;l<u;++l)y+=e.charAt(p[l]);return y},decodeUnsafe:r,decode
|
|
|
315
315
|
function Fe(e){const t=Be.decode(e);if(18!==t[0]||32!==t[1]||34!==t.length)throw new Error("Only CIDv0 with SHA-256 is supported");
|
|
316
316
|
// Return only the 32-byte digest (skip 0x1220 prefix)
|
|
317
317
|
return`0x${Buffer.from(t.slice(2)).toString("hex")}`}
|
|
318
|
+
/**
|
|
319
|
+
* Decode bytes32 back to CIDv0 by prepending 0x1220 multihash prefix.
|
|
320
|
+
*/function Oe(e){const t=Buffer.from(e.slice(2),"hex"),n=Buffer.concat([Buffer.from([18,32]),t]);return Be.encode(n)}
|
|
318
321
|
/**
|
|
319
322
|
* Raises a dispute with automatic evidence upload to IPFS.
|
|
320
323
|
* Uploads evidence JSON to IPFS, encodes the CID to bytes32 for on-chain storage,
|
|
@@ -343,7 +346,7 @@ return`0x${Buffer.from(t.slice(2)).toString("hex")}`}
|
|
|
343
346
|
* // Fetch evidence via IPFS gateway
|
|
344
347
|
* // https://ipfs.io/ipfs/{result.evidenceCid}
|
|
345
348
|
* ```
|
|
346
|
-
*/function
|
|
349
|
+
*/function Ue(e,t,n){return T(this,void 0,void 0,(function*(){const i=yield this.uploadJSONToIPFS(t),a=Fe(i);return{transactionResult:yield this.raiseDispute(e,a,n),evidenceCid:i,evidenceHash:a}}))}
|
|
347
350
|
/**
|
|
348
351
|
* Asserts a dispute as the IP owner with counter-evidence.
|
|
349
352
|
* Must be called by the owner of the disputed IP within the cooldown period.
|
|
@@ -356,7 +359,7 @@ return`0x${Buffer.from(t.slice(2)).toString("hex")}`}
|
|
|
356
359
|
* ```typescript
|
|
357
360
|
* await origin.disputeAssertion(1n, "0x1234..."); // counter-evidence hash
|
|
358
361
|
* ```
|
|
359
|
-
*/function
|
|
362
|
+
*/function $e(e,t){return T(this,void 0,void 0,(function*(){return this.callContractMethod(this.environment.DISPUTE_CONTRACT_ADDRESS,this.environment.DISPUTE_ABI,"disputeAssertion",[e,t],{waitForReceipt:!0})}))}
|
|
360
363
|
/**
|
|
361
364
|
* Asserts a dispute with automatic counter-evidence upload to IPFS.
|
|
362
365
|
* Uploads counter-evidence JSON to IPFS, encodes the CID to bytes32 for on-chain storage,
|
|
@@ -385,7 +388,7 @@ return`0x${Buffer.from(t.slice(2)).toString("hex")}`}
|
|
|
385
388
|
* // Fetch counter-evidence via IPFS gateway
|
|
386
389
|
* // https://ipfs.io/ipfs/{result.counterEvidenceCid}
|
|
387
390
|
* ```
|
|
388
|
-
*/function
|
|
391
|
+
*/function He(e,t){return T(this,void 0,void 0,(function*(){const n=yield this.uploadJSONToIPFS(t),i=Fe(n);return{transactionResult:yield this.disputeAssertion(e,i),counterEvidenceCid:n,counterEvidenceHash:i}}))}
|
|
389
392
|
/**
|
|
390
393
|
* Votes on a dispute as a CAMP token staker.
|
|
391
394
|
* Only users who staked before the dispute was raised can vote.
|
|
@@ -403,7 +406,7 @@ return`0x${Buffer.from(t.slice(2)).toString("hex")}`}
|
|
|
403
406
|
* // Vote against the dispute
|
|
404
407
|
* await origin.voteOnDispute(1n, false);
|
|
405
408
|
* ```
|
|
406
|
-
*/function
|
|
409
|
+
*/function je(e,t){return T(this,void 0,void 0,(function*(){return this.callContractMethod(this.environment.DISPUTE_CONTRACT_ADDRESS,this.environment.DISPUTE_ABI,"voteOnDispute",[e,t],{waitForReceipt:!0})}))}
|
|
407
410
|
/**
|
|
408
411
|
* Resolves a dispute after the voting period has ended.
|
|
409
412
|
* Can be called by anyone - resolution is deterministic based on votes and quorum.
|
|
@@ -417,7 +420,7 @@ return`0x${Buffer.from(t.slice(2)).toString("hex")}`}
|
|
|
417
420
|
* ```typescript
|
|
418
421
|
* await origin.resolveDispute(1n);
|
|
419
422
|
* ```
|
|
420
|
-
*/function
|
|
423
|
+
*/function Le(e){return T(this,void 0,void 0,(function*(){return this.callContractMethod(this.environment.DISPUTE_CONTRACT_ADDRESS,this.environment.DISPUTE_ABI,"resolveDispute",[e],{waitForReceipt:!0})}))}
|
|
421
424
|
/**
|
|
422
425
|
* Cancels a dispute that is still in the raised state.
|
|
423
426
|
* Can only be called by the dispute initiator during the cooldown period.
|
|
@@ -430,7 +433,7 @@ return`0x${Buffer.from(t.slice(2)).toString("hex")}`}
|
|
|
430
433
|
* ```typescript
|
|
431
434
|
* await origin.cancelDispute(1n);
|
|
432
435
|
* ```
|
|
433
|
-
*/function
|
|
436
|
+
*/function ze(e){return T(this,void 0,void 0,(function*(){return this.callContractMethod(this.environment.DISPUTE_CONTRACT_ADDRESS,this.environment.DISPUTE_ABI,"cancelDispute",[e],{waitForReceipt:!0})}))}
|
|
434
437
|
/**
|
|
435
438
|
* Tags a child IP as disputed if its parent has been successfully disputed.
|
|
436
439
|
* This propagates the dispute status to derivative IPs.
|
|
@@ -444,7 +447,7 @@ return`0x${Buffer.from(t.slice(2)).toString("hex")}`}
|
|
|
444
447
|
* // After parent IP (tokenId 1) has been disputed, tag child IP (tokenId 2)
|
|
445
448
|
* await origin.tagChildIp(2n, 1n); // childIpId, disputeId of parent
|
|
446
449
|
* ```
|
|
447
|
-
*/function
|
|
450
|
+
*/function Ve(e,t){return T(this,void 0,void 0,(function*(){return this.callContractMethod(this.environment.DISPUTE_CONTRACT_ADDRESS,this.environment.DISPUTE_ABI,"tagChildIp",[e,t],{waitForReceipt:!0})}))}
|
|
448
451
|
/**
|
|
449
452
|
* Gets the details of a dispute by its ID.
|
|
450
453
|
*
|
|
@@ -458,11 +461,11 @@ return`0x${Buffer.from(t.slice(2)).toString("hex")}`}
|
|
|
458
461
|
* console.log(`Yes votes: ${dispute.yesVotes}`);
|
|
459
462
|
* console.log(`No votes: ${dispute.noVotes}`);
|
|
460
463
|
* ```
|
|
461
|
-
*/function
|
|
464
|
+
*/function qe(e){return T(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;
|
|
462
465
|
// Contract returns a tuple, map it to the Dispute interface
|
|
463
466
|
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}}))}
|
|
464
467
|
// minimal ABI for staking vault
|
|
465
|
-
const
|
|
468
|
+
const Je=[{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"}];
|
|
466
469
|
/**
|
|
467
470
|
* Checks if a user meets the requirements to vote on a dispute.
|
|
468
471
|
* Returns detailed information about eligibility and reason if ineligible.
|
|
@@ -482,7 +485,7 @@ const qe=[{inputs:[{name:"account",type:"address"}],name:"balanceOf",outputs:[{n
|
|
|
482
485
|
* console.log(`Cannot vote: ${eligibility.reason}`);
|
|
483
486
|
* }
|
|
484
487
|
* ```
|
|
485
|
-
*/function
|
|
488
|
+
*/function Ge(e,t){return T(this,void 0,void 0,(function*(){const n=yield be(this.viemClient,t),i=O(),a=this.environment.DISPUTE_CONTRACT_ADDRESS,s=this.environment.DISPUTE_ABI,[r,o,d,u,p,l]=yield Promise.all([this.getDispute(e),i.readContract({address:a,abi:s,functionName:"stakingVault",args:[]}),i.readContract({address:a,abi:s,functionName:"stakingThreshold",args:[]}),i.readContract({address:a,abi:s,functionName:"disputeCoolDownPeriod",args:[]}),i.readContract({address:a,abi:s,functionName:"disputeJudgementPeriod",args:[]}),i.readContract({address:a,abi:s,functionName:"hasVoted",args:[e,n]})]),y=r.status,c=r.disputeTimestamp,m=r.assertionTimestamp,[h,T]=yield Promise.all([i.readContract({address:o,abi:Je,functionName:"userStakeTimestamp",args:[n]}),i.readContract({address:o,abi:Je,functionName:"balanceOf",args:[n]})]),f=BigInt(Math.floor(Date.now()/1e3));let v,A=!1;y===Se.Asserted?(
|
|
486
489
|
// for asserted disputes, voting period is relative to assertion timestamp
|
|
487
490
|
v=m+p,A=f<=v):y===Se.Raised&&(
|
|
488
491
|
// for raised disputes, voting period extends from cooldown through judgement
|
|
@@ -512,7 +515,7 @@ return y!==Se.Raised&&y!==Se.Asserted?Object.assign(Object.assign({},w),{reason:
|
|
|
512
515
|
* console.log(`Can resolve in ${progress.timeline.timeUntilResolution} seconds`);
|
|
513
516
|
* }
|
|
514
517
|
* ```
|
|
515
|
-
*/function
|
|
518
|
+
*/function Ye(e){return T(this,void 0,void 0,(function*(){var t,n,i,a,s,r,o,d,u;const p=O(),l=this.environment.DISPUTE_CONTRACT_ADDRESS,y=this.environment.DISPUTE_ABI,[c,m,h,T]=yield Promise.all([p.readContract({address:l,abi:y,functionName:"disputes",args:[e]}),p.readContract({address:l,abi:y,functionName:"disputeQuorum",args:[]}),p.readContract({address:l,abi:y,functionName:"disputeCoolDownPeriod",args:[]}),p.readContract({address:l,abi:y,functionName:"disputeJudgementPeriod",args:[]})]),f=Number(null!==(t=c.status)&&void 0!==t?t:c[9]),v=BigInt(null!==(i=null!==(n=c.disputeTimestamp)&&void 0!==n?n:c[5])&&void 0!==i?i:0),A=BigInt(null!==(s=null!==(a=c.assertionTimestamp)&&void 0!==a?a:c[6])&&void 0!==s?s:0),w=BigInt(null!==(o=null!==(r=c.yesVotes)&&void 0!==r?r:c[7])&&void 0!==o?o:0),I=BigInt(null!==(u=null!==(d=c.noVotes)&&void 0!==d?d:c[8])&&void 0!==u?u:0),g=w+I;let b=0,C=0;g>BigInt(0)&&(b=Number(w*BigInt(1e4)/g)/100,C=Number(I*BigInt(1e4)/g)/100);
|
|
516
519
|
// calculate quorum progress
|
|
517
520
|
let E=0;m>BigInt(0)&&(E=Number(g*BigInt(1e4)/m)/100);const S=g>=m;
|
|
518
521
|
// determine projected outcome
|
|
@@ -536,7 +539,7 @@ N=new Date(1e3*Number(v+h+T)),x=v+h+T);const k=(f===Se.Raised||f===Se.Asserted)&
|
|
|
536
539
|
* console.log(`Need ${requirements.totalRequired} but only have ${requirements.userBalance}`);
|
|
537
540
|
* }
|
|
538
541
|
* ```
|
|
539
|
-
*/function
|
|
542
|
+
*/function We(e){return T(this,void 0,void 0,(function*(){const t=O(),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,p=a+s;
|
|
540
543
|
// Get user's balance
|
|
541
544
|
let l;return l=d?yield t.getBalance({address:e}):yield t.readContract({address:o,abi:u,functionName:"balanceOf",args:[e]}),{bondAmount:a,protocolFee:s,totalRequired:p,tokenAddress:o,isNativeToken:d,userBalance:l,hasSufficientBalance:l>=p}}))}
|
|
542
545
|
/**
|
|
@@ -555,7 +558,7 @@ let l;return l=d?yield t.getBalance({address:e}):yield t.readContract({address:o
|
|
|
555
558
|
* // Then fractionalize
|
|
556
559
|
* const result = await origin.fractionalize(1n);
|
|
557
560
|
* ```
|
|
558
|
-
*/function
|
|
561
|
+
*/function Ze(e){return T(this,void 0,void 0,(function*(){return this.callContractMethod(this.environment.FRACTIONALIZER_CONTRACT_ADDRESS,this.environment.FRACTIONALIZER_ABI,"fractionalize",[e],{waitForReceipt:!0})}))}
|
|
559
562
|
/**
|
|
560
563
|
* Redeems an IP NFT by burning all of its fractional tokens.
|
|
561
564
|
* The caller must hold the entire supply of the NFT's fractional token.
|
|
@@ -569,7 +572,7 @@ let l;return l=d?yield t.getBalance({address:e}):yield t.readContract({address:o
|
|
|
569
572
|
* // Requires holding 100% of the fractional token supply
|
|
570
573
|
* await origin.redeem(1n);
|
|
571
574
|
* ```
|
|
572
|
-
*/function
|
|
575
|
+
*/function Ke(e){return T(this,void 0,void 0,(function*(){return this.callContractMethod(this.environment.FRACTIONALIZER_CONTRACT_ADDRESS,this.environment.FRACTIONALIZER_ABI,"redeem",[e],{waitForReceipt:!0})}))}
|
|
573
576
|
/**
|
|
574
577
|
* Gets the fractional ERC20 token address for a specific IP NFT.
|
|
575
578
|
* Returns zero address if the NFT has not been fractionalized.
|
|
@@ -586,7 +589,7 @@ let l;return l=d?yield t.getBalance({address:e}):yield t.readContract({address:o
|
|
|
586
589
|
* console.log("NFT has not been fractionalized");
|
|
587
590
|
* }
|
|
588
591
|
* ```
|
|
589
|
-
*/function
|
|
592
|
+
*/function Xe(e){return T(this,void 0,void 0,(function*(){return this.callContractMethod(this.environment.FRACTIONALIZER_CONTRACT_ADDRESS,this.environment.FRACTIONALIZER_ABI,"getTokenForNFT",[e])}))}
|
|
590
593
|
/**
|
|
591
594
|
* Fractionalizes an IP NFT with automatic approval.
|
|
592
595
|
* This method first approves the fractionalizer contract to transfer your NFT,
|
|
@@ -600,7 +603,7 @@ let l;return l=d?yield t.getBalance({address:e}):yield t.readContract({address:o
|
|
|
600
603
|
* // Single call handles approval and fractionalization
|
|
601
604
|
* const result = await origin.fractionalizeWithApproval(1n);
|
|
602
605
|
* ```
|
|
603
|
-
*/function
|
|
606
|
+
*/function Qe(e){return T(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})}))}
|
|
604
607
|
/**
|
|
605
608
|
* Redeems fractional tokens for the underlying NFT, but only if the caller owns 100% of the supply.
|
|
606
609
|
* This method checks the caller's balance before attempting to redeem, providing a clear error
|
|
@@ -619,7 +622,7 @@ let l;return l=d?yield t.getBalance({address:e}):yield t.readContract({address:o
|
|
|
619
622
|
* console.log("You don't own all fractional tokens yet");
|
|
620
623
|
* }
|
|
621
624
|
* ```
|
|
622
|
-
*/function
|
|
625
|
+
*/function et(e){return T(this,void 0,void 0,(function*(){
|
|
623
626
|
// get the ERC20 token address for this NFT
|
|
624
627
|
const t=yield this.getTokenForNFT(e);if(!t||"0x0000000000000000000000000000000000000000"===t)throw new Error("This NFT has not been fractionalized");
|
|
625
628
|
// get current wallet address
|
|
@@ -629,7 +632,7 @@ if(s<r){const e=s*BigInt(1e4)/r;throw new Error(`Cannot redeem: you own ${e/BigI
|
|
|
629
632
|
// proceed with redemption
|
|
630
633
|
return this.callContractMethod(this.environment.FRACTIONALIZER_CONTRACT_ADDRESS,this.environment.FRACTIONALIZER_ABI,"redeem",[e],{waitForReceipt:!0})}))}
|
|
631
634
|
// minimal ERC20 ABI
|
|
632
|
-
const
|
|
635
|
+
const tt=[{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"}];
|
|
633
636
|
/**
|
|
634
637
|
* Gets a user's ownership percentage of a fractionalized NFT.
|
|
635
638
|
* Returns detailed information about the user's fractional token holdings.
|
|
@@ -654,10 +657,10 @@ const et=[{inputs:[{name:"owner",type:"address"}],name:"balanceOf",outputs:[{nam
|
|
|
654
657
|
* }
|
|
655
658
|
* }
|
|
656
659
|
* ```
|
|
657
|
-
*/function
|
|
660
|
+
*/function nt(e,t){return T(this,void 0,void 0,(function*(){const n=yield be(this.viemClient,t),i=yield this.getTokenForNFT(e);
|
|
658
661
|
// get the ERC20 token address for this NFT
|
|
659
662
|
// check if fractionalized
|
|
660
|
-
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=O(),[s,o,d]=yield Promise.all([a.readContract({address:i,abi:
|
|
663
|
+
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=O(),[s,o,d]=yield Promise.all([a.readContract({address:i,abi:tt,functionName:"balanceOf",args:[n]}),a.readContract({address:i,abi:tt,functionName:"totalSupply",args:[]}),a.readContract({address:i,abi:tt,functionName:"decimals",args:[]})]);
|
|
661
664
|
// fetch ERC20 data
|
|
662
665
|
// calculate ownership percentage
|
|
663
666
|
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}}))}
|
|
@@ -684,7 +687,7 @@ let u=0;o>BigInt(0)&&(u=Number(s*BigInt(1e4)/o)/100);const p=s>=o&&o>BigInt(0);r
|
|
|
684
687
|
* console.log(`Cannot fractionalize: ${eligibility.reason}`);
|
|
685
688
|
* }
|
|
686
689
|
* ```
|
|
687
|
-
*/function
|
|
690
|
+
*/function it(e,t){return T(this,void 0,void 0,(function*(){const n=yield be(this.viemClient,t),i=O(),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};
|
|
688
691
|
// check requirements
|
|
689
692
|
return l?y?Object.assign(Object.assign({},m),{reason:`This NFT is already fractionalized. ERC20: ${d}`}):o===Ee.DELETED?Object.assign(Object.assign({},m),{reason:"This NFT has been deleted and cannot be fractionalized"}):o===Ee.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}`})}))}
|
|
690
693
|
/**
|
|
@@ -700,13 +703,13 @@ return l?y?Object.assign(Object.assign({},m),{reason:`This NFT is already fracti
|
|
|
700
703
|
* console.log(`Revenue Share: ${appInfo.revenueShareBps / 100}%`);
|
|
701
704
|
* console.log(`Active: ${appInfo.isActive}`);
|
|
702
705
|
* ```
|
|
703
|
-
*/function
|
|
706
|
+
*/function at(e){return T(this,void 0,void 0,(function*(){return this.callContractMethod(this.environment.APP_REGISTRY_CONTRACT_ADDRESS,this.environment.APP_REGISTRY_ABI,"getAppInfo",[e])}))}
|
|
704
707
|
/**
|
|
705
708
|
* Approves a spender to spend a specified amount of tokens on behalf of the owner.
|
|
706
709
|
* If the current allowance is less than the specified amount, it will perform the approval.
|
|
707
710
|
* Waits for the approval transaction to be confirmed before returning.
|
|
708
711
|
* @param {ApproveParams} params - The parameters for the approval.
|
|
709
|
-
*/function
|
|
712
|
+
*/function st(e){return T(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:u,functionName:"allowance",args:[i,a]}))<s){const o=yield e.writeContract({address:n,account:i,abi:u,functionName:"approve",args:[a,s],chain:r});
|
|
710
713
|
// Wait for the approval transaction to be confirmed with extra confirmations
|
|
711
714
|
yield t.waitForTransactionReceipt({hash:o,confirmations:2}),yield new Promise((e=>setTimeout(e,1e3)))}}))}
|
|
712
715
|
/**
|
|
@@ -727,7 +730,7 @@ yield t.waitForTransactionReceipt({hash:o,confirmations:2}),yield new Promise((e
|
|
|
727
730
|
* const totalValue = 3000000000000000n;
|
|
728
731
|
* await origin.bulkBuyAccess(buyerAddress, purchases, totalValue);
|
|
729
732
|
* ```
|
|
730
|
-
*/function
|
|
733
|
+
*/function rt(e,t,n){return this.callContractMethod(this.environment.BATCH_PURCHASE_CONTRACT_ADDRESS,this.environment.BATCH_PURCHASE_ABI,"bulkBuyAccess",[e,t],{waitForReceipt:!0,value:n})}
|
|
731
734
|
/**
|
|
732
735
|
* Executes a fault-tolerant bulk purchase of multiple IP-NFT licenses.
|
|
733
736
|
* Individual purchases can fail without reverting the entire transaction.
|
|
@@ -744,7 +747,7 @@ yield t.waitForTransactionReceipt({hash:o,confirmations:2}),yield new Promise((e
|
|
|
744
747
|
* console.log(`Purchased ${result.successCount} of ${purchases.length} IPs`);
|
|
745
748
|
* console.log(`Failed tokens: ${result.failedTokenIds}`);
|
|
746
749
|
* ```
|
|
747
|
-
*/function
|
|
750
|
+
*/function ot(e,t,n){return this.callContractMethod(this.environment.BATCH_PURCHASE_CONTRACT_ADDRESS,this.environment.BATCH_PURCHASE_ABI,"bulkBuyAccessTolerant",[e,t],{waitForReceipt:!0,value:n})}
|
|
748
751
|
/**
|
|
749
752
|
* Previews the total cost of purchasing multiple IP-NFT licenses.
|
|
750
753
|
* This is a view function that doesn't require a transaction.
|
|
@@ -758,7 +761,7 @@ yield t.waitForTransactionReceipt({hash:o,confirmations:2}),yield new Promise((e
|
|
|
758
761
|
* console.log(`Total cost: ${preview.totalNativeCost} wei`);
|
|
759
762
|
* console.log(`Valid tokens: ${preview.validCount}`);
|
|
760
763
|
* ```
|
|
761
|
-
*/function
|
|
764
|
+
*/function dt(e){return this.callContractMethod(this.environment.BATCH_PURCHASE_CONTRACT_ADDRESS,this.environment.BATCH_PURCHASE_ABI,"previewBulkCost",[e])}
|
|
762
765
|
/**
|
|
763
766
|
* Builds purchase parameters for multiple tokens by fetching their current license terms.
|
|
764
767
|
* This is a view function that doesn't require a transaction.
|
|
@@ -771,7 +774,7 @@ yield t.waitForTransactionReceipt({hash:o,confirmations:2}),yield new Promise((e
|
|
|
771
774
|
* const params = await origin.buildPurchaseParams([1n, 2n, 3n]);
|
|
772
775
|
* await origin.bulkBuyAccess(buyer, params, totalValue);
|
|
773
776
|
* ```
|
|
774
|
-
*/function
|
|
777
|
+
*/function ut(e){return this.callContractMethod(this.environment.BATCH_PURCHASE_CONTRACT_ADDRESS,this.environment.BATCH_PURCHASE_ABI,"buildPurchaseParams",[e])}
|
|
775
778
|
/**
|
|
776
779
|
* Checks the active status of multiple tokens.
|
|
777
780
|
*
|
|
@@ -783,7 +786,7 @@ yield t.waitForTransactionReceipt({hash:o,confirmations:2}),yield new Promise((e
|
|
|
783
786
|
* const activeFlags = await origin.checkActiveStatus([1n, 2n, 3n]);
|
|
784
787
|
* const activeTokens = tokenIds.filter((_, i) => activeFlags[i]);
|
|
785
788
|
* ```
|
|
786
|
-
*/function
|
|
789
|
+
*/function pt(e){return this.callContractMethod(this.environment.BATCH_PURCHASE_CONTRACT_ADDRESS,this.environment.BATCH_PURCHASE_ABI,"checkActiveStatus",[e])}
|
|
787
790
|
/**
|
|
788
791
|
* Smart bulk purchase that automatically fetches terms and handles the entire purchase flow.
|
|
789
792
|
* This is the recommended method for most use cases.
|
|
@@ -800,7 +803,7 @@ yield t.waitForTransactionReceipt({hash:o,confirmations:2}),yield new Promise((e
|
|
|
800
803
|
* // Tolerant purchase - continue even if some fail
|
|
801
804
|
* const result = await origin.bulkBuyAccessSmart([1n, 2n, 3n], { tolerant: true });
|
|
802
805
|
* ```
|
|
803
|
-
*/function
|
|
806
|
+
*/function lt(e,t){return T(this,void 0,void 0,(function*(){if(!e||0===e.length)throw new _("No token IDs provided for bulk purchase. Please provide at least one token ID.");
|
|
804
807
|
// Get the buyer's wallet address
|
|
805
808
|
const n=this.viemClient;if(!n)throw new N("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 N("No accounts found in connected wallet. Please unlock your wallet or add an account.");i=e[0]}
|
|
806
809
|
// Build purchase params from on-chain data
|
|
@@ -810,38 +813,38 @@ let s=BigInt(0);const o=[];for(const e of a)if(e.expectedPaymentToken===r)s+=e.e
|
|
|
810
813
|
// Group ERC20 purchases by token
|
|
811
814
|
const t=o.find((t=>t.token===e.expectedPaymentToken));t?t.amount+=e.expectedPrice:o.push({token:e.expectedPaymentToken,amount:e.expectedPrice})}
|
|
812
815
|
// Approve ERC20 tokens if needed
|
|
813
|
-
const d=O();for(const e of o)yield
|
|
816
|
+
const d=O();for(const e of o)yield st({walletClient:n,publicClient:d,tokenAddress:e.token,owner:i,spender:this.environment.BATCH_PURCHASE_CONTRACT_ADDRESS,amount:e.amount,chain:this.environment.CHAIN});
|
|
814
817
|
// Execute the purchase
|
|
815
|
-
return(null==t?void 0:t.tolerant)?this.bulkBuyAccessTolerant(i,a,s):this.bulkBuyAccess(i,a,s)}))}var
|
|
818
|
+
return(null==t?void 0:t.tolerant)?this.bulkBuyAccessTolerant(i,a,s):this.bulkBuyAccess(i,a,s)}))}var yt,ct,mt,ht,Tt,ft,vt,At,wt,It,gt,bt,Ct,Et,St,Pt,Rt,_t,Dt,Nt,xt,kt;
|
|
816
819
|
/**
|
|
817
820
|
* The Origin class
|
|
818
821
|
* Handles interactions with Origin protocol.
|
|
819
|
-
*/class
|
|
822
|
+
*/class Mt{constructor(e,t,n,i,a){yt.add(this),t?this.jwt=t:console.warn("JWT not provided. Some features may be unavailable."),this.viemClient=n,this.environment="string"==typeof e?K[e]:e||K.DEVELOPMENT,this.environment.AUTH_HUB_BASE_API+="PRODUCTION"===e?"/auth-mainnet":"",this.baseParentId=i,this.appId=a,
|
|
820
823
|
// DataNFT methods
|
|
821
824
|
this.mintWithSignature=ne.bind(this),this.registerIpNFT=ie.bind(this),this.updateTerms=ae.bind(this),this.finalizeDelete=se.bind(this),this.getOrCreateRoyaltyVault=re.bind(this),this.getTerms=oe.bind(this),this.ownerOf=de.bind(this),this.balanceOf=ue.bind(this),this.tokenURI=pe.bind(this),this.dataStatus=le.bind(this),this.isApprovedForAll=ye.bind(this),this.transferFrom=ce.bind(this),this.safeTransferFrom=me.bind(this),this.approve=he.bind(this),this.setApprovalForAll=Te.bind(this),
|
|
822
825
|
// Marketplace methods
|
|
823
826
|
this.buyAccess=fe.bind(this),this.hasAccess=ve.bind(this),this.subscriptionExpiry=Ae.bind(this),this.settlePaymentIntent=ge.bind(this),this.getDataWithIntent=De.bind(this),
|
|
824
827
|
// Bulk purchase methods
|
|
825
|
-
this.bulkBuyAccess=
|
|
828
|
+
this.bulkBuyAccess=rt.bind(this),this.bulkBuyAccessTolerant=ot.bind(this),this.bulkBuyAccessSmart=lt.bind(this),this.previewBulkCost=dt.bind(this),this.buildPurchaseParams=ut.bind(this),this.checkActiveStatus=pt.bind(this),
|
|
826
829
|
// Dispute module methods
|
|
827
|
-
this.raiseDispute=Me.bind(this),this.raiseDisputeSmart=
|
|
830
|
+
this.raiseDispute=Me.bind(this),this.raiseDisputeSmart=Ue.bind(this),this.disputeAssertion=$e.bind(this),this.disputeAssertionSmart=He.bind(this),this.voteOnDispute=je.bind(this),this.resolveDispute=Le.bind(this),this.cancelDispute=ze.bind(this),this.tagChildIp=Ve.bind(this),this.getDispute=qe.bind(this),this.canVoteOnDispute=Ge.bind(this),this.getDisputeProgress=Ye.bind(this),this.getDisputeRequirements=We.bind(this),
|
|
828
831
|
// Fractionalizer module methods
|
|
829
|
-
this.fractionalize=
|
|
832
|
+
this.fractionalize=Ze.bind(this),this.redeem=Ke.bind(this),this.getTokenForNFT=Xe.bind(this),this.fractionalizeWithApproval=Qe.bind(this),this.redeemIfComplete=et.bind(this),this.getFractionOwnership=nt.bind(this),this.canFractionalize=it.bind(this),
|
|
830
833
|
// AppRegistry module methods
|
|
831
|
-
this.getAppInfo=
|
|
834
|
+
this.getAppInfo=at.bind(this)}getJwt(){return this.jwt}setViemClient(e){this.viemClient=e}
|
|
832
835
|
/**
|
|
833
836
|
* Approves an ERC20 token for spending by a spender address if the current allowance is insufficient.
|
|
834
837
|
* Waits for the approval transaction to be confirmed before returning.
|
|
835
838
|
* @param tokenAddress The address of the ERC20 token.
|
|
836
839
|
* @param spender The address that will be approved to spend the tokens.
|
|
837
840
|
* @param amount The amount of tokens to approve.
|
|
838
|
-
*/approveERC20IfNeeded(e,t,n){return T(this,void 0,void 0,(function*(){const i=yield f(this,
|
|
841
|
+
*/approveERC20IfNeeded(e,t,n){return T(this,void 0,void 0,(function*(){const i=yield f(this,yt,"m",gt).call(this);yield st({walletClient:this.viemClient,publicClient:O(),tokenAddress:e,owner:i,spender:t,amount:n,chain:this.environment.CHAIN})}))}
|
|
839
842
|
/**
|
|
840
843
|
* Uploads a JSON object to IPFS and returns the resulting CID.
|
|
841
844
|
* @param data The JSON object to upload.
|
|
842
845
|
* @returns The CID of the uploaded JSON.
|
|
843
846
|
* @throws {APIError} If the upload fails.
|
|
844
|
-
*/uploadJSONToIPFS(e){return T(this,void 0,void 0,(function*(){const t=JSON.stringify(e),n=new File([t],"evidence.json",{type:"application/json"}),i=yield f(this,
|
|
847
|
+
*/uploadJSONToIPFS(e){return T(this,void 0,void 0,(function*(){const t=JSON.stringify(e),n=new File([t],"evidence.json",{type:"application/json"}),i=yield f(this,yt,"m",ht).call(this,n);if(!i)throw new R("Failed to upload evidence to IPFS");return i}))}
|
|
845
848
|
/**
|
|
846
849
|
* Mints a file-based IpNFT.
|
|
847
850
|
* @param file The file to mint.
|
|
@@ -850,17 +853,17 @@ this.getAppInfo=it.bind(this)}getJwt(){return this.jwt}setViemClient(e){this.vie
|
|
|
850
853
|
* @param parents Optional parent token IDs for lineage tracking.
|
|
851
854
|
* @param options Optional parameters including progress callback, preview image, and use asset as preview flag.
|
|
852
855
|
* @returns The token ID of the minted IpNFT as a string, or null if minting failed.
|
|
853
|
-
*/mintFile(e,t,n,i,a){return T(this,void 0,void 0,(function*(){let s,r=null;try{r=yield f(this,
|
|
856
|
+
*/mintFile(e,t,n,i,a){return T(this,void 0,void 0,(function*(){let s,r=null;try{r=yield f(this,yt,"m",At).call(this)}catch(t){throw new N(`Cannot mint file "${e.name}": wallet not connected. Please connect a wallet first.`)}try{if(s=yield f(this,yt,"m",Tt).call(this,e,a),!s||!s.key)throw new R(`Failed to upload file "${e.name}": no upload info returned from server`)}catch(t){if(t instanceof R||t instanceof N)throw t;throw new R(`Failed to upload file "${e.name}": ${k(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 f(this,yt,"m",ht).call(this,a.previewImage):(null==a?void 0:a.useAssetAsPreview)&&e.type.startsWith("image/")&&(o=yield f(this,yt,"m",ht).call(this,e)),o&&(t.image=`ipfs://${o}`);const d=BigInt(Date.now()+6e5);// 10 minutes from now
|
|
854
857
|
let u;this.baseParentId&&(i||(i=[]),i.unshift(this.baseParentId));try{u=yield this.registerIpNFT("file",d,n,t,!0,// isIp
|
|
855
858
|
s.key,// fileKey
|
|
856
|
-
i,this.appId)}catch(e){throw yield f(this,
|
|
859
|
+
i,this.appId)}catch(e){throw yield f(this,yt,"m",mt).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 f(this,yt,"m",mt).call(this,s.key,s.uploadId,[]),new Error(`Minting failed with status: ${e.receipt.status}`)}catch(e){throw yield f(this,yt,"m",mt).call(this,s.key,s.uploadId,[]),new Error(`Minting transaction failed: ${e instanceof Error?e.message:String(e)}`)}return p.toString()}))}
|
|
857
860
|
/**
|
|
858
861
|
* Mints a social IpNFT.
|
|
859
862
|
* @param source The social media source (spotify, twitter, tiktok).
|
|
860
863
|
* @param metadata The metadata associated with the social media content.
|
|
861
864
|
* @param license The license terms for the IpNFT.
|
|
862
865
|
* @return The token ID of the minted IpNFT as a string, or null if minting failed.
|
|
863
|
-
*/mintSocial(e,t,n){return T(this,void 0,void 0,(function*(){let i=null;try{i=yield f(this,
|
|
866
|
+
*/mintSocial(e,t,n){return T(this,void 0,void 0,(function*(){let i=null;try{i=yield f(this,yt,"m",At).call(this)}catch(t){throw new N(`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
|
|
864
867
|
let s,r=this.baseParentId?[this.baseParentId]:[];try{s=yield this.registerIpNFT(e,a,n,t,!0,// isIp
|
|
865
868
|
void 0,// fileKey
|
|
866
869
|
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()}))}
|
|
@@ -873,9 +876,9 @@ r,this.appId)}catch(e){throw new Error(`Failed to register Social IpNFT: ${e ins
|
|
|
873
876
|
* @param {CallOptions} [options] The call options.
|
|
874
877
|
* @returns {Promise<any>} A promise that resolves with the result of the contract call or transaction hash.
|
|
875
878
|
* @throws {Error} - Throws an error if the wallet client is not connected and the method is not a view function.
|
|
876
|
-
*/callContractMethod(e,t,n,i){return T(this,arguments,void 0,(function*(e,t,n,i,a={}){var s;let r=null;try{r=yield f(this,
|
|
879
|
+
*/callContractMethod(e,t,n,i){return T(this,arguments,void 0,(function*(e,t,n,i,a={}){var s;let r=null;try{r=yield f(this,yt,"m",At).call(this)}catch(t){throw new N(`Cannot call "${n}" on contract ${e}: wallet not connected`)}const o=p({abi:t,name:n});if(o&&"stateMutability"in o&&("view"===o.stateMutability||"pure"===o.stateMutability)){const a=O();return(yield a.readContract({address:e,abi:t,functionName:n,args:i}))||null}yield f(this,yt,"m",vt).call(this,this.environment.CHAIN);const d=O(),{result:u,request:l}=yield d.simulateContract({account:r,address:e,abi:t,functionName:n,args:i,value:a.value});
|
|
877
880
|
// simulate
|
|
878
|
-
if(a.simulate)return u;try{const t=yield null===(s=this.viemClient)||void 0===s?void 0:s.writeContract(l);if("string"!=typeof t)throw new x(`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 f(this,
|
|
881
|
+
if(a.simulate)return u;try{const t=yield null===(s=this.viemClient)||void 0===s?void 0:s.writeContract(l);if("string"!=typeof t)throw new x(`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 f(this,yt,"m",ft).call(this,t),simulatedResult:u}}catch(t){if(t instanceof x||t instanceof N)throw t;throw new x(`Transaction for "${n}" failed: ${k(t)}`,{contractName:e,methodName:n})}}))}
|
|
879
882
|
/**
|
|
880
883
|
* Gets comprehensive token information in a single call.
|
|
881
884
|
* Combines owner, status, terms, URI, and access information.
|
|
@@ -917,13 +920,13 @@ let u=!1,p=null;if("0x0000000000000000000000000000000000000000"!==i)try{[u,p]=yi
|
|
|
917
920
|
* console.log("Access purchased:", result.txHash);
|
|
918
921
|
* }
|
|
919
922
|
* ```
|
|
920
|
-
*/buyAccessSmart(e){return T(this,void 0,void 0,(function*(){let t=null;try{t=yield f(this,
|
|
923
|
+
*/buyAccessSmart(e){return T(this,void 0,void 0,(function*(){let t=null;try{t=yield f(this,yt,"m",At).call(this)}catch(t){throw new N(`Cannot buy access to token ${e}: wallet not connected. Please connect a wallet first.`)}
|
|
921
924
|
// Check if user already has access
|
|
922
925
|
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 R(`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 R(`Invalid license terms for token ${e}: missing price, paymentToken, or duration`);
|
|
923
926
|
// Fetch protocol fee from marketplace
|
|
924
|
-
const o=yield f(this,
|
|
927
|
+
const o=yield f(this,yt,"m",wt).call(this),d=yield f(this,yt,"m",It).call(this,e),u=i;
|
|
925
928
|
// Fetch app fee from token's appId
|
|
926
|
-
return a===r?this.buyAccess(t,e,u,s,a,o,d,u):(yield
|
|
929
|
+
return a===r?this.buyAccess(t,e,u,s,a,o,d,u):(yield st({walletClient:this.viemClient,publicClient:O(),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))}))}
|
|
927
930
|
/**
|
|
928
931
|
* Fetch the underlying data associated with a specific token ID.
|
|
929
932
|
* @param {bigint} tokenId - The token ID to fetch data for.
|
|
@@ -973,7 +976,7 @@ const e=[{inputs:[{name:"owner",type:"address"}],name:"balanceOf",outputs:[{name
|
|
|
973
976
|
* // Claim ERC20 token royalties to a specific address
|
|
974
977
|
* await origin.claimRoyalties(1n, "0xRecipient...", "0xToken...");
|
|
975
978
|
* ```
|
|
976
|
-
*/claimRoyalties(e,t,n){return T(this,void 0,void 0,(function*(){const i=yield f(this,
|
|
979
|
+
*/claimRoyalties(e,t,n){return T(this,void 0,void 0,(function*(){const i=yield f(this,yt,"m",gt).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;
|
|
977
980
|
// Call execute on the TBA
|
|
978
981
|
return n&&n!==r?(
|
|
979
982
|
// ERC20 token transfer
|
|
@@ -982,16 +985,16 @@ d=n,u=BigInt(0),
|
|
|
982
985
|
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]})):(
|
|
983
986
|
// Native token transfer
|
|
984
987
|
d=i,u=o,p="0x"),this.callContractMethod(s,this.environment.TBA_ABI,"execute",[d,u,p,0],// operation: 0 = CALL
|
|
985
|
-
{waitForReceipt:!0,value:BigInt(0)})}))}}
|
|
988
|
+
{waitForReceipt:!0,value:BigInt(0)})}))}}yt=new WeakSet,ct=function(e,t){return T(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}}))},mt=function(e,t,n){return T(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}}))},ht=function(e){return T(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}`)}}))},Tt=function(e,t){return T(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 f(this,yt,"m",ct).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 te(i,n.urls,(null==t?void 0:t.progressCallback)||(()=>{}))}catch(e){try{yield f(this,yt,"m",mt).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 f(this,yt,"m",mt).call(this,n.key,n.uploadId,a)}catch(e){console.error("Failed to update status to success:",e)}return n}))},ft=function(e){return T(this,arguments,void 0,(function*(e,t={}){var n,i,a;const s=O();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){
|
|
986
989
|
// fallback
|
|
987
|
-
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}}))},
|
|
990
|
+
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}}))},vt=function(e){return T(this,void 0,void 0,(function*(){if(!this.viemClient)throw new N(`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=>{F=e,B=null})// reset public client to be recreated with new chain
|
|
988
991
|
(e);try{yield this.viemClient.request({method:"wallet_switchEthereumChain",params:[{chainId:"0x"+BigInt(e.id).toString(16)}]})}catch(t){
|
|
989
992
|
// Unrecognized chain
|
|
990
|
-
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)}]})}}}))},
|
|
993
|
+
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)}]})}}}))},At=function(){return T(this,void 0,void 0,(function*(){if(!this.viemClient)throw new N("No wallet connected. Please connect a wallet to perform this action.");
|
|
991
994
|
// If account is already set on the client, return it directly
|
|
992
995
|
if(this.viemClient.account)return this.viemClient.account.address;
|
|
993
996
|
// Otherwise request accounts (browser wallet flow)
|
|
994
|
-
const e=yield this.viemClient.request({method:"eth_requestAccounts",params:[]});if(!e||0===e.length)throw new N("No accounts found in connected wallet. Please unlock your wallet or add an account.");return e[0]}))},
|
|
997
|
+
const e=yield this.viemClient.request({method:"eth_requestAccounts",params:[]});if(!e||0===e.length)throw new N("No accounts found in connected wallet. Please unlock your wallet or add an account.");return e[0]}))},wt=function(){return T(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}}))},It=function(e){return T(this,void 0,void 0,(function*(){try{
|
|
995
998
|
// First, get the token info to find its appId
|
|
996
999
|
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;
|
|
997
1000
|
// Check if app registry is configured
|
|
@@ -999,7 +1002,7 @@ if(!this.environment.APP_REGISTRY_CONTRACT_ADDRESS||!this.environment.APP_REGIST
|
|
|
999
1002
|
// Fetch app info from registry
|
|
1000
1003
|
const i=yield this.callContractMethod(this.environment.APP_REGISTRY_CONTRACT_ADDRESS,this.environment.APP_REGISTRY_ABI,"getAppInfo",[n]);
|
|
1001
1004
|
// Only return fee if app is active
|
|
1002
|
-
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}}))},
|
|
1005
|
+
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}}))},gt=function(e){return T(this,void 0,void 0,(function*(){if(e)return e;if(!this.viemClient)throw new N("No wallet address provided and no wallet connected. Please provide an address or connect a wallet.");
|
|
1003
1006
|
// If account is already set on the client, return it directly
|
|
1004
1007
|
if(this.viemClient.account)return this.viemClient.account.address;
|
|
1005
1008
|
// Otherwise request accounts (browser wallet flow)
|
|
@@ -1009,7 +1012,7 @@ const t=yield this.viemClient.request({method:"eth_requestAccounts",params:[]});
|
|
|
1009
1012
|
* @class
|
|
1010
1013
|
* @classdesc The Auth class is used to authenticate the user.
|
|
1011
1014
|
*/
|
|
1012
|
-
class
|
|
1015
|
+
class Bt{
|
|
1013
1016
|
/**
|
|
1014
1017
|
* Constructor for the Auth class.
|
|
1015
1018
|
* @param {object} options The options object.
|
|
@@ -1019,9 +1022,9 @@ class Mt{
|
|
|
1019
1022
|
* @param {StorageAdapter} [options.storage] Custom storage adapter. Defaults to localStorage in browser, memory storage in Node.js.
|
|
1020
1023
|
* @throws {APIError} - Throws an error if the clientId is not provided.
|
|
1021
1024
|
*/
|
|
1022
|
-
constructor({clientId:e,appId:t,redirectUri:n,environment:i="DEVELOPMENT",baseParentId:a,storage:s}){if(
|
|
1025
|
+
constructor({clientId:e,appId:t,redirectUri:n,environment:i="DEVELOPMENT",baseParentId:a,storage:s}){if(bt.add(this),Ct.set(this,void 0),Et.set(this,void 0),St.set(this,void 0),Pt.set(this,void 0),!e)throw new _("clientId is required");if(!t)throw new _("appId is required");if(-1===["PRODUCTION","DEVELOPMENT"].indexOf(i))throw new _(`Invalid environment "${i}". Must be "DEVELOPMENT" or "PRODUCTION"`);v(this,Et,"undefined"==typeof window,"f"),v(this,Pt,s||(f(this,Et,"f")?new C:new b),"f"),this.viem=null,this.environment=K[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,v(this,Ct,{},"f"),
|
|
1023
1026
|
// only subscribe to providers in browser environment
|
|
1024
|
-
f(this,
|
|
1027
|
+
f(this,Et,"f")||ee((e=>{f(this,bt,"m",Rt).call(this,"providers",e)})),f(this,bt,"m",_t).call(this)}
|
|
1025
1028
|
/**
|
|
1026
1029
|
* Subscribe to an event. Possible events are "state", "provider", "providers", and "viem".
|
|
1027
1030
|
* @param {("state"|"provider"|"providers"|"viem")} event The event.
|
|
@@ -1031,18 +1034,18 @@ f(this,Ct,"f")||ee((e=>{f(this,gt,"m",Pt).call(this,"providers",e)})),f(this,gt,
|
|
|
1031
1034
|
* auth.on("state", (state) => {
|
|
1032
1035
|
* console.log(state);
|
|
1033
1036
|
* });
|
|
1034
|
-
*/on(e,t){f(this,
|
|
1037
|
+
*/on(e,t){f(this,Ct,"f")[e]||(f(this,Ct,"f")[e]=[]),f(this,Ct,"f")[e].push(t),"providers"===e&&t(Q())}
|
|
1035
1038
|
/**
|
|
1036
1039
|
* Unsubscribe from an event. Possible events are "state", "provider", "providers", and "viem".
|
|
1037
1040
|
* @param {("state"|"provider"|"providers"|"viem")} event The event.
|
|
1038
1041
|
* @param {function} callback The callback function.
|
|
1039
1042
|
* @returns {void}
|
|
1040
|
-
*/off(e,t){f(this,
|
|
1043
|
+
*/off(e,t){f(this,Ct,"f")[e]&&(f(this,Ct,"f")[e]=f(this,Ct,"f")[e].filter((e=>e!==t)))}
|
|
1041
1044
|
/**
|
|
1042
1045
|
* Set the loading state.
|
|
1043
1046
|
* @param {boolean} loading The loading state.
|
|
1044
1047
|
* @returns {void}
|
|
1045
|
-
*/setLoading(e){f(this,
|
|
1048
|
+
*/setLoading(e){f(this,bt,"m",Rt).call(this,"state",e?"loading":this.isAuthenticated?"authenticated":"unauthenticated")}
|
|
1046
1049
|
/**
|
|
1047
1050
|
* 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.
|
|
1048
1051
|
* @param {object} options The options object. Includes the provider and the provider info.
|
|
@@ -1050,7 +1053,7 @@ f(this,Ct,"f")||ee((e=>{f(this,gt,"m",Pt).call(this,"providers",e)})),f(this,gt,
|
|
|
1050
1053
|
* @throws {APIError} - Throws an error if the provider is not provided.
|
|
1051
1054
|
*/setProvider({provider:t,info:i,address:a}){if(!t)throw new R("provider is required");this.viem=((t,i="window.ethereum",a,s)=>{var r,o;if(!t&&!M)return console.warn("Provider is required to create a client."),null;const d=a||S;if(!M||M.transport.name!==i&&t||s!==(null===(r=M.account)||void 0===r?void 0:r.address)&&t||(null==F?void 0:F.id)!==d.id){const a={chain:d,transport:n(t,{name:i})};s&&(a.account=c(s)),M=e(a),F=d,B&&(null===(o=B.chain)||void 0===o?void 0:o.id)!==d.id&&(B=null)}return M})(t,i.name,this.environment.CHAIN,a),this.origin&&this.origin.setViemClient(this.viem),
|
|
1052
1055
|
// TODO: only use one of these
|
|
1053
|
-
f(this,
|
|
1056
|
+
f(this,bt,"m",Rt).call(this,"viem",this.viem),f(this,bt,"m",Rt).call(this,"provider",{provider:t,info:i}),f(this,Pt,"f").setItem("camp-sdk:provider",JSON.stringify(i))}
|
|
1054
1057
|
/**
|
|
1055
1058
|
* 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.
|
|
1056
1059
|
* @param {string} walletAddress The wallet address.
|
|
@@ -1059,7 +1062,7 @@ f(this,gt,"m",Pt).call(this,"viem",this.viem),f(this,gt,"m",Pt).call(this,"provi
|
|
|
1059
1062
|
/**
|
|
1060
1063
|
* Recover the provider from local storage.
|
|
1061
1064
|
* @returns {Promise<void>}
|
|
1062
|
-
*/recoverProvider(){return T(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 f(this,
|
|
1065
|
+
*/recoverProvider(){return T(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 f(this,Pt,"f").getItem("camp-sdk:provider");if(!c)return;const m=JSON.parse(c);let h;const T=null!==(e=Q())&&void 0!==e?e:[];
|
|
1063
1066
|
// first pass: try to find provider by UUID/name and check if it has the right address
|
|
1064
1067
|
// without prompting (using eth_accounts)
|
|
1065
1068
|
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){
|
|
@@ -1076,12 +1079,12 @@ if(!h&&(m.uuid||m.name))for(const e of T)try{if(m.uuid&&(null===(u=e.info)||void
|
|
|
1076
1079
|
/**
|
|
1077
1080
|
* Disconnect the user.
|
|
1078
1081
|
* @returns {Promise<void>}
|
|
1079
|
-
*/disconnect(){return T(this,void 0,void 0,(function*(){this.isAuthenticated&&(f(this,
|
|
1082
|
+
*/disconnect(){return T(this,void 0,void 0,(function*(){this.isAuthenticated&&(f(this,bt,"m",Rt).call(this,"state","unauthenticated"),this.isAuthenticated=!1,this.walletAddress=null,this.userId=null,this.jwt=null,this.origin=null,v(this,St,void 0,"f"),yield f(this,Pt,"f").removeItem("camp-sdk:wallet-address"),yield f(this,Pt,"f").removeItem("camp-sdk:user-id"),yield f(this,Pt,"f").removeItem("camp-sdk:jwt"),yield f(this,Pt,"f").removeItem("camp-sdk:environment"))}))}
|
|
1080
1083
|
/**
|
|
1081
1084
|
* Connect the user's wallet and sign the message.
|
|
1082
1085
|
* @returns {Promise<{ success: boolean; message: string; walletAddress: string }>} A promise that resolves with the authentication result.
|
|
1083
1086
|
* @throws {APIError} - Throws an error if the user cannot be authenticated.
|
|
1084
|
-
*/connect(){return T(this,void 0,void 0,(function*(){f(this,
|
|
1087
|
+
*/connect(){return T(this,void 0,void 0,(function*(){f(this,bt,"m",Rt).call(this,"state","loading");try{this.walletAddress||(yield f(this,bt,"m",Dt).call(this)),this.walletAddress=s(this.walletAddress);const e=yield f(this,bt,"m",Nt).call(this),t=f(this,bt,"m",kt).call(this,e),n=yield this.viem.signMessage({account:this.walletAddress,message:t}),i=yield f(this,bt,"m",xt).call(this,t,n);if(i.success)return this.isAuthenticated=!0,this.userId=i.userId,this.jwt=i.token,this.origin=new Mt(this.environment,this.jwt,this.viem,this.baseParentId,this.appId),yield f(this,Pt,"f").setItem("camp-sdk:jwt",this.jwt),yield f(this,Pt,"f").setItem("camp-sdk:wallet-address",this.walletAddress),yield f(this,Pt,"f").setItem("camp-sdk:user-id",this.userId),yield f(this,Pt,"f").setItem("camp-sdk:environment",this.environment.NAME),f(this,bt,"m",Rt).call(this,"state","authenticated"),{success:!0,message:"Successfully authenticated",walletAddress:this.walletAddress};throw this.isAuthenticated=!1,f(this,bt,"m",Rt).call(this,"state","unauthenticated"),new R("Failed to authenticate: signature verification failed")}catch(e){if(this.isAuthenticated=!1,f(this,bt,"m",Rt).call(this,"state","unauthenticated"),e instanceof R||e instanceof N)throw e;throw new R(`Failed to authenticate: ${k(e)}`)}}))}
|
|
1085
1088
|
/**
|
|
1086
1089
|
* Connect with a custom signer (for Node.js or custom wallet implementations).
|
|
1087
1090
|
* This method bypasses browser wallet interactions and uses the provided signer directly.
|
|
@@ -1100,9 +1103,9 @@ if(!h&&(m.uuid||m.name))for(const e of T)try{if(m.uuid&&(null===(u=e.info)||void
|
|
|
1100
1103
|
* const account = privateKeyToAccount('0x...');
|
|
1101
1104
|
* const client = createWalletClient({ account, chain: mainnet, transport: http() });
|
|
1102
1105
|
* await auth.connectWithSigner(client);
|
|
1103
|
-
*/connectWithSigner(e,t){return T(this,void 0,void 0,(function*(){f(this,
|
|
1106
|
+
*/connectWithSigner(e,t){return T(this,void 0,void 0,(function*(){f(this,bt,"m",Rt).call(this,"state","loading");try{v(this,St,g(e),"f"),this.walletAddress=s(yield f(this,St,"f").getAddress()),
|
|
1104
1107
|
// store the signer as viem client if it's a viem client, otherwise keep adapter
|
|
1105
|
-
"viem"===f(this,
|
|
1108
|
+
"viem"===f(this,St,"f").type&&(this.viem=e);const n=yield f(this,bt,"m",Nt).call(this),i=f(this,bt,"m",kt).call(this,n,null==t?void 0:t.domain,null==t?void 0:t.uri),a=yield f(this,St,"f").signMessage(i),r=yield f(this,bt,"m",xt).call(this,i,a);if(r.success)return this.isAuthenticated=!0,this.userId=r.userId,this.jwt=r.token,this.origin=new Mt(this.environment,this.jwt,this.viem,this.baseParentId,this.appId),yield f(this,Pt,"f").setItem("camp-sdk:jwt",this.jwt),yield f(this,Pt,"f").setItem("camp-sdk:wallet-address",this.walletAddress),yield f(this,Pt,"f").setItem("camp-sdk:user-id",this.userId),yield f(this,Pt,"f").setItem("camp-sdk:environment",this.environment.NAME),f(this,bt,"m",Rt).call(this,"state","authenticated"),{success:!0,message:"Successfully authenticated",walletAddress:this.walletAddress};throw this.isAuthenticated=!1,f(this,bt,"m",Rt).call(this,"state","unauthenticated"),new R("Failed to authenticate: signature verification failed")}catch(e){if(this.isAuthenticated=!1,v(this,St,void 0,"f"),f(this,bt,"m",Rt).call(this,"state","unauthenticated"),e instanceof R||e instanceof N)throw e;throw new R(`Failed to authenticate: ${k(e)}`)}}))}
|
|
1106
1109
|
/**
|
|
1107
1110
|
* Get the user's linked social accounts.
|
|
1108
1111
|
* @returns {Promise<Record<string, boolean>>} A promise that resolves with the user's linked social accounts.
|
|
@@ -1116,17 +1119,17 @@ if(!h&&(m.uuid||m.name))for(const e of T)try{if(m.uuid&&(null===(u=e.info)||void
|
|
|
1116
1119
|
* Link the user's Twitter account.
|
|
1117
1120
|
* @returns {Promise<void>}
|
|
1118
1121
|
* @throws {Error} - Throws an error if the user is not authenticated or in Node.js environment.
|
|
1119
|
-
*/linkTwitter(){return T(this,void 0,void 0,(function*(){if(!this.isAuthenticated)throw new D("User must be authenticated to link Twitter account");if(f(this,
|
|
1122
|
+
*/linkTwitter(){return T(this,void 0,void 0,(function*(){if(!this.isAuthenticated)throw new D("User must be authenticated to link Twitter account");if(f(this,Et,"f"))throw new R("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}`}))}
|
|
1120
1123
|
/**
|
|
1121
1124
|
* Link the user's Discord account.
|
|
1122
1125
|
* @returns {Promise<void>}
|
|
1123
1126
|
* @throws {Error} - Throws an error if the user is not authenticated or in Node.js environment.
|
|
1124
|
-
*/linkDiscord(){return T(this,void 0,void 0,(function*(){if(!this.isAuthenticated)throw new D("User must be authenticated to link Discord account");if(f(this,
|
|
1127
|
+
*/linkDiscord(){return T(this,void 0,void 0,(function*(){if(!this.isAuthenticated)throw new D("User must be authenticated to link Discord account");if(f(this,Et,"f"))throw new R("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}`}))}
|
|
1125
1128
|
/**
|
|
1126
1129
|
* Link the user's Spotify account.
|
|
1127
1130
|
* @returns {Promise<void>}
|
|
1128
1131
|
* @throws {Error} - Throws an error if the user is not authenticated or in Node.js environment.
|
|
1129
|
-
*/linkSpotify(){return T(this,void 0,void 0,(function*(){if(!this.isAuthenticated)throw new D("User must be authenticated to link Spotify account");if(f(this,
|
|
1132
|
+
*/linkSpotify(){return T(this,void 0,void 0,(function*(){if(!this.isAuthenticated)throw new D("User must be authenticated to link Spotify account");if(f(this,Et,"f"))throw new R("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}`}))}
|
|
1130
1133
|
/**
|
|
1131
1134
|
* Link the user's TikTok account.
|
|
1132
1135
|
* @param {string} handle The user's TikTok handle.
|
|
@@ -1176,4 +1179,4 @@ if(!h&&(m.uuid||m.name))for(const e of T)try{if(m.uuid&&(null===(u=e.info)||void
|
|
|
1176
1179
|
* @returns {Promise<any>} A promise that resolves with the unlink result.
|
|
1177
1180
|
* @throws {Error} - Throws an error if the user is not authenticated.
|
|
1178
1181
|
* @throws {APIError} - Throws an error if the request fails.
|
|
1179
|
-
*/unlinkTelegram(){return T(this,void 0,void 0,(function*(){if(!this.isAuthenticated)throw new D("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 R(e.message||"Failed to unlink Telegram account");return e.data}))}}
|
|
1182
|
+
*/unlinkTelegram(){return T(this,void 0,void 0,(function*(){if(!this.isAuthenticated)throw new D("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 R(e.message||"Failed to unlink Telegram account");return e.data}))}}Ct=new WeakMap,Et=new WeakMap,St=new WeakMap,Pt=new WeakMap,bt=new WeakSet,Rt=function(e,t){f(this,Ct,"f")[e]&&f(this,Ct,"f")[e].forEach((e=>e(t)))},_t=function(e){return T(this,void 0,void 0,(function*(){const t=yield f(this,Pt,"f").getItem("camp-sdk:wallet-address"),n=yield f(this,Pt,"f").getItem("camp-sdk:user-id"),i=yield f(this,Pt,"f").getItem("camp-sdk:jwt"),a=yield f(this,Pt,"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 Mt(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}):f(this,Et,"f")||(console.warn("No matching provider was given for the stored wallet address. Trying to recover provider."),yield this.recoverProvider())):this.isAuthenticated=!1}))},Dt=function(){return T(this,void 0,void 0,(function*(){try{const[e]=yield this.viem.requestAddresses();return this.walletAddress=s(e),this.walletAddress}catch(e){throw new N(`Failed to connect wallet: ${k(e)}`)}}))},Nt=function(){return T(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 R(t.message||`Failed to fetch nonce (HTTP ${e.status})`,e.status);return t.data}catch(e){if(e instanceof R)throw e;throw new R(`Failed to fetch nonce: ${k(e)}`)}}))},xt=function(e,t){return T(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 R(`Failed to verify signature: ${k(e)}`)}}))},kt=function(e,t,n){return m({domain:t||(f(this,Et,"f")?"localhost":window.location.host),address:this.walletAddress,statement:q,uri:n||(f(this,Et,"f")?"http://localhost":window.location.origin),version:"1",chainId:this.environment.CHAIN.id,nonce:e})};export{Bt as Auth,b as BrowserStorage,I as CustomSignerAdapter,Ee as DataStatus,Se as DisputeStatus,w as EthersSignerAdapter,Ce as LicenseType,C as MemoryStorage,Mt as Origin,A as ViemSignerAdapter,P as campMainnet,S as campTestnet,Pe as createLicenseTerms,E as createNodeWalletClient,g as createSignerAdapter,Oe as decodeCidFromBytes32,Fe as encodeCidToBytes32};
|