@oceanprotocol/lib 5.0.5 → 5.1.0
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/CHANGELOG.md +44 -9
- package/CodeExamples.md +8 -4
- package/ComputeExamples.md +4 -2
- package/dist/lib.cjs +1 -1
- package/dist/lib.cjs.map +1 -1
- package/dist/lib.modern.js +1 -1
- package/dist/lib.modern.js.map +1 -1
- package/dist/lib.module.mjs +1 -1
- package/dist/lib.module.mjs.map +1 -1
- package/dist/lib.umd.js +1 -1
- package/dist/lib.umd.js.map +1 -1
- package/dist/types/config/Config.d.ts +0 -8
- package/dist/types/contracts/Dispenser.d.ts +1 -1
- package/dist/types/contracts/EnterpriseFeeCollector.d.ts +2 -1
- package/dist/types/contracts/Escrow.d.ts +12 -9
- package/dist/types/contracts/FixedRateExchange.d.ts +0 -1
- package/dist/types/contracts/NFT.d.ts +1 -1
- package/dist/types/contracts/index.d.ts +0 -6
- package/dist/types/services/Aquarius.d.ts +3 -2
- package/dist/types/services/Provider.d.ts +5 -3
- package/dist/types/utils/Assets.d.ts +2 -1
- package/dist/types/utils/TokenUtils.d.ts +2 -1
- package/docs/modules.md +0 -6
- package/package.json +5 -5
- package/dist/types/contracts/df/DfRewards.d.ts +0 -31
- package/dist/types/contracts/df/DfStrategyV1.d.ts +0 -21
- package/dist/types/contracts/ve/VeAllocate.d.ts +0 -38
- package/dist/types/contracts/ve/VeFeeDistributor.d.ts +0 -29
- package/dist/types/contracts/ve/VeFeeEstimate.d.ts +0 -14
- package/dist/types/contracts/ve/VeOcean.d.ts +0 -68
- package/docs/classes/DfRewards.md +0 -345
- package/docs/classes/DfStrategyV1.md +0 -313
- package/docs/classes/VeAllocate.md +0 -372
- package/docs/classes/VeFeeDistributor.md +0 -325
- package/docs/classes/VeFeeEstimate.md +0 -281
- package/docs/classes/VeOcean.md +0 -513
package/dist/lib.modern.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import t from"@oceanprotocol/contracts/addresses/address.json";import e from"fs";import{ethers as a,formatUnits as i,parseUnits as n,EventLog as r,toUtf8Bytes as s,keccak256 as o,hexlify as c,toUtf8String as l,getAddress as d,parseEther as u,getBytes as h,toBeHex as g}from"ethers";import*as w from"@oasisprotocol/sapphire-paratime";import p from"bignumber.js";import m from"decimal.js";import f from"@oceanprotocol/contracts/artifacts/contracts/pools/dispenser/Dispenser.sol/Dispenser.json";import y from"@oceanprotocol/contracts/artifacts/contracts/pools/fixedRate/FixedRateExchange.sol/FixedRateExchange.json";import v from"@oceanprotocol/contracts/artifacts/contracts/pools/FactoryRouter.sol/FactoryRouter.json";import k from"@oceanprotocol/contracts/artifacts/contracts/templates/ERC20Template.sol/ERC20Template.json";import b from"@oceanprotocol/contracts/artifacts/contracts/templates/ERC20TemplateEnterprise.sol/ERC20TemplateEnterprise.json";import T from"@oceanprotocol/contracts/artifacts/contracts/templates/ERC721Template.sol/ERC721Template.json";import S from"@oceanprotocol/contracts/artifacts/contracts/ERC721Factory.sol/ERC721Factory.json";import A from"@oceanprotocol/contracts/artifacts/contracts/interfaces/IERC20Template.sol/IERC20Template.json";import F from"@oceanprotocol/contracts/artifacts/contracts/templates/ERC20Template4.sol/ERC20Template4.json";import E from"@oceanprotocol/contracts/artifacts/contracts/accesslists/AccessList.sol/AccessList.json";import C from"@oceanprotocol/contracts/artifacts/contracts/accesslists/AccessListFactory.sol/AccessListFactory.json";import D from"@oceanprotocol/contracts/artifacts/contracts/ve/veOCEAN.vy/veOCEAN.json";import x from"@oceanprotocol/contracts/artifacts/contracts/ve/veFeeDistributor.vy/veFeeDistributor.json";import M from"@oceanprotocol/contracts/artifacts/contracts/ve/veFeeEstimate.vy/veFeeEstimate.json";import O from"@oceanprotocol/contracts/artifacts/contracts/ve/veAllocate.sol/veAllocate.json";import N from"@oceanprotocol/contracts/artifacts/contracts/df/DFRewards.sol/DFRewards.json";import P from"@oceanprotocol/contracts/artifacts/contracts/df/DFStrategyV1.sol/DFStrategyV1.json";import R from"@oceanprotocol/contracts/artifacts/contracts/escrow/Escrow.sol/Escrow.json";import U from"@oceanprotocol/contracts/artifacts/contracts/communityFee/EnterpriseFeeCollector.sol/EnterpriseFeeCollector.json";import I from"cross-fetch";import{DDOManager as L}from"@oceanprotocol/ddo-js";import j from"jsonwebtoken";import G from"crypto-js/sha256.js";import{createHash as _}from"crypto";var $,B,z;!function(t){t.URL="url",t.IPFS="ipfs",t.ARWEAVE="arweave"}($||($={})),function(t){t.AES="AES",t.ECIES="ECIES"}(B||(B={}));class q{constructor(){this.nodeUri=void 0,this.providerAddress=void 0,this.oceanNodeUri=void 0,this.web3Provider=void 0,this.oceanTokenAddress=void 0,this.nftFactoryAddress=void 0,this.routerFactoryAddress=void 0,this.datatokensABI=void 0,this.fixedRateExchangeAddress=void 0,this.fixedRateExchangeAddressABI=void 0,this.dispenserAddress=void 0,this.dispenserABI=void 0,this.opfCommunityFeeCollector=void 0,this.EnterpriseFeeCollector=void 0,this.sideStakingAddress=void 0,this.startBlock=void 0,this.verbose=void 0,this.authMessage=void 0,this.authTokenExpiration=void 0,this.parityUri=void 0,this.threshold=void 0,this.chainId=void 0,this.network=void 0,this.explorerUri=void 0,this.oceanTokenSymbol=void 0,this.transactionBlockTimeout=void 0,this.transactionConfirmationBlocks=void 0,this.transactionPollingTimeout=void 0,this.gasFeeMultiplier=void 0,this.veAllocate=void 0,this.veOCEAN=void 0,this.veDelegation=void 0,this.veFeeDistributor=void 0,this.veDelegationProxy=void 0,this.DFRewards=void 0,this.DFStrategyV1=void 0,this.veFeeEstimate=void 0,this.sdk=void 0,this.accessListFactory=void 0,this.escrow=void 0}}function J(){return J=Object.assign?Object.assign.bind():function(t){for(var e=1;e<arguments.length;e++){var a=arguments[e];for(var i in a)({}).hasOwnProperty.call(a,i)&&(t[i]=a[i])}return t},J.apply(null,arguments)}!function(t){t[t.None=-1]="None",t[t.Error=0]="Error",t[t.Warn=1]="Warn",t[t.Log=2]="Log",t[t.Verbose=3]="Verbose"}(z||(z={}));class W{constructor(t){this.logLevel=void 0,this.logLevel=t,this.logLevel=t||z.Error}setLevel(t){this.logLevel=t}bypass(...t){this.dispatch("log",-Infinity,...t)}debug(...t){this.dispatch("debug",z.Verbose,...t)}log(...t){this.dispatch("log",z.Log,...t)}warn(...t){this.dispatch("warn",z.Warn,...t)}error(...t){this.dispatch("error",z.Error,...t)}dispatch(t,e,...a){this.logLevel>=e&&console[t](...a)}}const V=new W,H={chainId:null,network:"unknown",nodeUri:"http://127.0.0.1:8545",oceanNodeUri:"http://127.0.0.1:8001",explorerUri:null,oceanTokenAddress:null,oceanTokenSymbol:"OCEAN",fixedRateExchangeAddress:null,dispenserAddress:null,startBlock:0,transactionBlockTimeout:50,transactionConfirmationBlocks:1,transactionPollingTimeout:750,gasFeeMultiplier:1},Z=[J({},H),J({},H,{chainId:8996,network:"development",oceanNodeUri:"http://127.0.0.1:8001",sdk:"evm"}),J({},H,{chainId:11155111,network:"sepolia",nodeUri:"https://sepolia.infura.io/v3",explorerUri:"https://sepolia.etherscan.io",gasFeeMultiplier:1.1,sdk:"evm"}),J({},H,{chainId:1,network:"mainnet",nodeUri:"https://mainnet.infura.io/v3",explorerUri:"https://etherscan.io",startBlock:11105459,transactionBlockTimeout:150,transactionConfirmationBlocks:5,transactionPollingTimeout:1750,gasFeeMultiplier:1.05,sdk:"evm"}),J({},H,{chainId:8453,network:"base",nodeUri:"https://mainnet.base.org",explorerUri:"https://etherscan.io",startBlock:30562198,transactionBlockTimeout:150,transactionConfirmationBlocks:5,transactionPollingTimeout:1750,gasFeeMultiplier:1.05,sdk:"evm"}),J({},H,{chainId:137,network:"polygon",nodeUri:"https://polygon-mainnet.infura.io/v3",explorerUri:"https://polygonscan.com",oceanTokenSymbol:"mOCEAN",gasFeeMultiplier:1.6,sdk:"evm"}),J({},H,{chainId:2021e3,network:"gaiaxtestnet",nodeUri:"https://rpc.gaiaxtestnet.oceanprotocol.com",explorerUri:"https://blockscout.gaiaxtestnet.oceanprotocol.com",sdk:"evm"}),J({},H,{chainId:80001,network:"mumbai",nodeUri:"https://polygon-mumbai.infura.io/v3",explorerUri:"https://mumbai.polygonscan.com",gasFeeMultiplier:1.1,sdk:"evm"}),J({},H,{chainId:56,network:"bsc",nodeUri:"https://bsc-dataseed.binance.org",explorerUri:"https://bscscan.com/",gasFeeMultiplier:1.05,sdk:"evm"}),J({},H,{chainId:246,network:"energyweb",nodeUri:"https://rpc.energyweb.org",explorerUri:"https://explorer.energyweb.org",gasFeeMultiplier:1.05,sdk:"evm"}),J({},H,{chainId:1285,network:"moonriver",nodeUri:"https://moonriver.api.onfinality.io/public",explorerUri:"https://moonriver.moonscan.io/",gasFeeMultiplier:1.05,sdk:"evm"}),J({},H,{chainId:100,network:"gen-x-testnet",nodeUri:"https://rpc.genx.minimal-gaia-x.eu",explorerUri:"https://explorer.genx.minimal-gaia-x.eu/",gasFeeMultiplier:1,sdk:"evm"}),J({},H,{chainId:10,network:"optimism",nodeUri:"https://mainnet.optimism.io",explorerUri:"https://optimistic.etherscan.io/",gasFeeMultiplier:1.1,sdk:"evm"}),J({},H,{chainId:11155420,network:"optimism_sepolia",nodeUri:"https://sepolia.optimism.io",explorerUri:"https://sepolia-optimism.etherscan.io/",gasFeeMultiplier:1.1,sdk:"evm"}),J({},H,{chainId:23294,network:"oasis_sapphire",nodeUri:"https://sapphire.oasis.io",explorerUri:"https://explorer.oasis.io/mainnet/sapphire/",gasFeeMultiplier:1,sdk:"oasis"}),J({},H,{chainId:23295,network:"oasis_sapphire_testnet",nodeUri:"https://testnet.sapphire.oasis.dev",explorerUri:"https://explorer.oasis.io/testnet/sapphire/",gasFeeMultiplier:1,sdk:"oasis"}),J({},H,{chainId:32456,network:"pontus-x-devnet",nodeUri:"https://rpc.dev.pontus-x.eu",explorerUri:"https://explorer.dev.pontus-x.eu/testnet/pontusx",sdk:"evm"})],X=[23294,23295];class K{getAddressesFromEnv(e,a){let i;const n=()=>process.env.NODE_URL?{oceanNodeUri:process.env.NODE_URL}:{};if(a&&a[e]){const{FixedPrice:t,Dispenser:r,ERC721Factory:s,OPFCommunityFeeCollector:o,Ocean:c,chainId:l,startBlock:d,veAllocate:u,veOCEAN:h,veDelegation:g,veFeeDistributor:w,veDelegationProxy:p,DFRewards:m,DFStrategyV1:f,veFeeEstimate:y,Router:v,AccessListFactory:k,Escrow:b,EnterpriseFeeCollector:T}=a[e];i=J({nftFactoryAddress:s,opfCommunityFeeCollector:o,fixedRateExchangeAddress:t,dispenserAddress:r,oceanTokenAddress:c,routerFactoryAddress:v,chainId:l,startBlock:d,veAllocate:u,veOCEAN:h,veDelegation:g,veFeeDistributor:w,veDelegationProxy:p,DFRewards:m,DFStrategyV1:f,veFeeEstimate:y,accessListFactory:k,escrow:b,EnterpriseFeeCollector:T},n())}else if(t[e]){const{FixedPrice:a,Dispenser:r,OPFCommunityFeeCollector:s,ERC721Factory:o,Ocean:c,chainId:l,startBlock:d,veAllocate:u,veOCEAN:h,veDelegation:g,veFeeDistributor:w,veDelegationProxy:p,DFRewards:m,DFStrategyV1:f,veFeeEstimate:y,Router:v,AccessListFactory:k,Escrow:b,EnterpriseFeeCollector:T}=t[e];i=J({nftFactoryAddress:o,opfCommunityFeeCollector:s,fixedRateExchangeAddress:a,dispenserAddress:r,oceanTokenAddress:c,routerFactoryAddress:v,chainId:l,startBlock:d,veAllocate:u,veOCEAN:h,veDelegation:g,veFeeDistributor:w,veDelegationProxy:p,DFRewards:m,DFStrategyV1:f,veFeeEstimate:y,accessListFactory:k,escrow:b,EnterpriseFeeCollector:T},n())}return i}getConfig(t,a){const i="string"==typeof t?"network":"chainId";let n,r=Z.find(e=>e[i]===t);if(!r)return V.error(`No config found for given network '${t}'`),null;try{n=process.env.ADDRESS_FILE?JSON.parse(e.readFileSync(process.env.ADDRESS_FILE,"utf8")):null}catch(t){console.log(t),n=null}let s=this.getAddressesFromEnv(r.network,n);return!s&&X.includes(r.chainId)&&(s=this.getAddressesFromEnv(r.network.replace("sapph","saph"),n)),"sdk"in r&&null!==r.sdk||(r.sdk=X.includes(r.chainId)?"oasis":"evm"),s&&"accessListFactory"in s&&(r.accessListFactory=s.accessListFactory),r=J({},r,s),J({},r,{nodeUri:a?`${r.nodeUri}/${a}`:r.nodeUri})}}const Q=[{constant:!0,inputs:[],name:"name",outputs:[{name:"",type:"string"}],payable:!1,stateMutability:"view",type:"function"},{constant:!1,inputs:[{name:"_spender",type:"address"},{name:"_value",type:"uint256"}],name:"approve",outputs:[{name:"",type:"bool"}],payable:!1,stateMutability:"nonpayable",type:"function"},{constant:!0,inputs:[],name:"totalSupply",outputs:[{name:"",type:"uint256"}],payable:!1,stateMutability:"view",type:"function"},{constant:!1,inputs:[{name:"_from",type:"address"},{name:"_to",type:"address"},{name:"_value",type:"uint256"}],name:"transferFrom",outputs:[{name:"",type:"bool"}],payable:!1,stateMutability:"nonpayable",type:"function"},{constant:!0,inputs:[],name:"decimals",outputs:[{name:"",type:"uint8"}],payable:!1,stateMutability:"view",type:"function"},{constant:!0,inputs:[{name:"_owner",type:"address"}],name:"balanceOf",outputs:[{name:"balance",type:"uint256"}],payable:!1,stateMutability:"view",type:"function"},{constant:!0,inputs:[],name:"symbol",outputs:[{name:"",type:"string"}],payable:!1,stateMutability:"view",type:"function"},{constant:!1,inputs:[{name:"_to",type:"address"},{name:"_value",type:"uint256"}],name:"transfer",outputs:[{name:"",type:"bool"}],payable:!1,stateMutability:"nonpayable",type:"function"},{constant:!0,inputs:[{name:"_owner",type:"address"},{name:"_spender",type:"address"}],name:"allowance",outputs:[{name:"",type:"uint256"}],payable:!1,stateMutability:"view",type:"function"},{payable:!0,stateMutability:"payable",type:"fallback"},{anonymous:!1,inputs:[{indexed:!0,name:"owner",type:"address"},{indexed:!0,name:"spender",type:"address"},{indexed:!1,name:"value",type:"uint256"}],name:"Approval",type:"event"},{anonymous:!1,inputs:[{indexed:!0,name:"from",type:"address"},{indexed:!0,name:"to",type:"address"},{indexed:!1,name:"value",type:"uint256"}],name:"Transfer",type:"event"}],Y=3e10,tt=4e9,et=1e10,at=11155111;function it(t,e){return t}async function nt(t,e){const a=await(await t.provider.getFeeData()).gasPrice,i=BigInt(a.toString());return e?(i*BigInt(e)).toString(10):i.toString()}async function rt(t,e){return new a.Contract(e,Q,t).decimals()}async function st(t,e,a,n){let r=n||await rt(t,e);return"0"===r&&(r=18),i(a,r).toString()}async function ot(t,e,a,i){let r=i||await rt(t,e);return"0"===r&&(r=18),n(a,r).toString()}function ct(t,e){if(t&&t.logs)return t.logs.filter(t=>t instanceof r&&t.eventName===e)[0]}async function lt(t,e,a,i,...n){const{chainId:r}=await e.provider.getNetwork(),s=await e.provider.getFeeData();let o={};if(s.maxPriorityFeePerGas){let t=s.maxPriorityFeePerGas.toString(),e=s.maxFeePerGas.toString();a>1&&(t=Math.round(Number(s.maxPriorityFeePerGas)*a).toString(),e=Math.round(Number(s.maxFeePerGas)*a).toString()),o={maxPriorityFeePerGas:(80001===Number(r)||137===Number(r))&&Number(t)<Y?Y:Number(r)===at&&Number(t)<tt?tt:X.includes(Number(r))&&Number(t)<et?et:Number(t),maxFeePerGas:(80001===Number(r)||137===Number(r))&&Number(e)<Y?Y:Number(r)===at&&Number(e)<tt?tt:X.includes(Number(r))&&Number(e)<et?et:Number(e)}}else o={gasPrice:s.gasPrice};o.gasLimit=BigInt(new p(t).plus(20000n).toString());try{const t=await i(...n,o);return await t.wait(),t}catch(t){return V.error("Send tx error: ",t),null}}class dt{constructor(t,e,a,i){this.signer=void 0,this.config=void 0,this.abi=void 0,this.signer=t,this.config=a||(new K).getConfig(e),this.abi=i||this.getDefaultAbi()}getSignerAccordingSdk(){return this.config&&"sdk"in this.config&&"oasis"===this.config.sdk?w.wrap(this.signer):this.signer}async amountToUnits(t,e,a){return ot(this.signer,t,e,a)}async unitsToAmount(t,e,a){return st(this.signer,t,e,a)}async getFairGasPrice(){var t;return nt(this.signer,null==(t=this.config)?void 0:t.gasFeeMultiplier)}getContract(t,e){if(!t)throw new Error("Contract address is required but not provided");return it(new a.Contract(t,new a.Interface(JSON.stringify(e||this.abi)),this.signer))}}class ut extends dt{constructor(t,e,a,i,n){super(e,a,i,n),this.address=void 0,this.contract=void 0,this.address=t,this.contract=this.getContract(this.address)}}class ht extends ut{getDefaultAbi(){return f.abi}async status(t){const e=await this.contract.status(t);if(!e)throw new Error("Np dispenser found for the given datatoken address");return{active:e.active,owner:e.owner,isMinter:e.isMinter,maxTokens:await this.unitsToAmount(null,e.maxTokens,18),maxBalance:await this.unitsToAmount(null,e.maxBalance,18),balance:await this.unitsToAmount(null,e.balance,18),allowedSwapper:e.allowedSwapper}}async create(t,e,a,i,n,r){var s;const o=await this.contract.create.estimateGas(t,this.amountToUnits(null,a,18),this.amountToUnits(null,i,18),e,n);return r?o:await lt(o,this.getSignerAccordingSdk(),null==(s=this.config)?void 0:s.gasFeeMultiplier,this.contract.create,t,this.amountToUnits(null,a,18),this.amountToUnits(null,i,18),e,n)}async activate(t,e,a,i){var n;const r=await this.contract.activate.estimateGas(t,this.amountToUnits(null,e,18),this.amountToUnits(null,a,18));return i?r:await lt(r,this.getSignerAccordingSdk(),null==(n=this.config)?void 0:n.gasFeeMultiplier,this.contract.activate,t,this.amountToUnits(null,e,18),this.amountToUnits(null,a,18))}async deactivate(t,e){var a;const i=await this.contract.deactivate.estimateGas(t);return e?i:await lt(i,this.getSignerAccordingSdk(),null==(a=this.config)?void 0:a.gasFeeMultiplier,this.contract.deactivate,t)}async setAllowedSwapper(t,e,a){var i;const n=await this.contract.setAllowedSwapper.estimateGas(t,e);return a?n:await lt(n,this.getSignerAccordingSdk(),null==(i=this.config)?void 0:i.gasFeeMultiplier,this.contract.setAllowedSwapper,t,e)}async dispense(t,e="1",a,i){var n;const r=await this.contract.dispense.estimateGas(t,this.amountToUnits(null,e,18),a);return i?r:await lt(r,this.getSignerAccordingSdk(),null==(n=this.config)?void 0:n.gasFeeMultiplier,this.contract.dispense,t,this.amountToUnits(null,e,18),a)}async ownerWithdraw(t,e){var a;const i=await this.contract.ownerWithdraw.estimateGas(t);return e?i:await lt(i,this.getSignerAccordingSdk(),null==(a=this.config)?void 0:a.gasFeeMultiplier,this.contract.ownerWithdraw,t)}async isDispensable(t,e,a,i="1"){const n=await this.status(t);return!(!n||!1===n.active||new m(await e.balance(t,a)).greaterThanOrEqualTo(n.maxBalance)||new m(String(i)).greaterThan(n.maxTokens)||!new m(n.balance).greaterThanOrEqualTo(i)&&!0!==n.isMinter)}}const gt="0x0000000000000000000000000000000000000000",wt=1e6,pt="115792089237316195423570985008687907853269984665640564039457584007913129639934",mt="Returned error: Method eth_feeHistory not supported.";class ft extends ut{getDefaultAbi(){return y.abi}async generateExchangeId(t,e){return await this.contract.generateExchangeId(t,e)}async buyDatatokens(t,e,a,i=gt,n="0",r){var s;const o=await this.getExchange(t),c=await this.amountToUnits(null,n,18),l=await this.amountToUnits(o.datatoken,e,Number(o.dtDecimals)),d=await this.amountToUnits(o.baseToken,a,Number(o.btDecimals)),u=await this.contract.buyDT.estimateGas(t,l,d,i,c);return r?u:await lt(u,this.getSignerAccordingSdk(),null==(s=this.config)?void 0:s.gasFeeMultiplier,this.contract.buyDT,t,l,d,i,c)}async sellDatatokens(t,e,a,i=gt,n="0",r){var s;const o=await this.getExchange(t),c=await this.amountToUnits(null,n,18),l=await this.amountToUnits(o.datatoken,e,Number(o.dtDecimals)),d=await this.amountToUnits(o.baseToken,a,Number(o.btDecimals)),u=await this.contract.sellDT.estimateGas(t,l,d,i,c);return r?u:await lt(u,this.getSignerAccordingSdk(),null==(s=this.config)?void 0:s.gasFeeMultiplier,this.contract.sellDT,t,l,d,i,c)}async getNumberOfExchanges(){const t=await this.contract.getNumberOfExchanges();return Number(t)}async setRate(t,e,a){var i;const n=await this.contract.setRate.estimateGas(t,await this.amountToUnits(null,e,18));return a?n:await lt(n,this.getSignerAccordingSdk(),null==(i=this.config)?void 0:i.gasFeeMultiplier,this.contract.setRate,t,await this.amountToUnits(null,e,18))}async setAllowedSwapper(t,e,a){var i;const n=await this.contract.setAllowedSwapper.estimateGas(t,e);return a?n:await lt(n,this.getSignerAccordingSdk(),null==(i=this.config)?void 0:i.gasFeeMultiplier,this.contract.setAllowedSwapper,t,e)}async activate(t,e){var a;const i=await this.getExchange(t);if(!i)return null;if(!0===i.active)return null;const n=await this.contract.toggleExchangeState.estimateGas(t);return e?n:await lt(n,this.getSignerAccordingSdk(),null==(a=this.config)?void 0:a.gasFeeMultiplier,this.contract.toggleExchangeState,t)}async deactivate(t,e){var a;const i=await this.getExchange(t);if(!i)return null;if(!1===i.active)return null;const n=await this.contract.toggleExchangeState.estimateGas(t);return e?n:await lt(n,this.getSignerAccordingSdk(),null==(a=this.config)?void 0:a.gasFeeMultiplier,this.contract.toggleExchangeState,t)}async getRate(t){const e=await this.contract.getRate(t);return await this.unitsToAmount(null,e,18)}async getDatatokenSupply(t){const e=await this.contract.getDTSupply(t),a=await this.getExchange(t);return await this.unitsToAmount(a.datatoken,e,Number(a.dtDecimals))}async getBasetokenSupply(t){const e=await this.contract.getBTSupply(t),a=await this.getExchange(t);return await this.unitsToAmount(a.baseToken,e,Number(a.btDecimals))}async getAllowedSwapper(t){return await this.contract.getAllowedSwapper(t)}async calcBaseInGivenDatatokensOut(t,e,a="0"){const i=await this.getExchange(t),n=await this.contract.calcBaseInGivenOutDT(t,await this.amountToUnits(i.datatoken,e,Number(i.dtDecimals)),await this.amountToUnits(null,a,18));return{baseTokenAmount:await this.unitsToAmount(i.baseToken,n.baseTokenAmount,Number(i.btDecimals)),marketFeeAmount:await this.unitsToAmount(i.baseToken,n.publishMarketFeeAmount,Number(i.btDecimals)),oceanFeeAmount:await this.unitsToAmount(i.baseToken,n.oceanFeeAmount,Number(i.btDecimals)),consumeMarketFeeAmount:await this.unitsToAmount(i.baseToken,n.consumeMarketFeeAmount,Number(i.btDecimals))}}async getAmountBasetokensOut(t,e,a="0"){const i=await this.getExchange(t),n=await this.contract.calcBaseOutGivenInDT(t,await this.amountToUnits(i.datatoken,e,Number(i.dtDecimals)),await this.amountToUnits(null,a,18));return await this.unitsToAmount(i.baseToken,n[0],Number(i.btDecimals))}async getExchange(t){const e=await this.contract.getExchange(t);return{active:e.active,datatoken:e.datatoken,baseToken:e.baseToken,withMint:e.withMint,exchangeOwner:e.exchangeOwner,allowedSwapper:e.allowedSwapper,dtDecimals:e.dtDecimals.toString(),btDecimals:e.btDecimals.toString(),dtBalance:await this.unitsToAmount(e.datatoken,e.dtBalance,Number(e.dtDecimals)),btBalance:await this.unitsToAmount(e.baseToken,e.btBalance,Number(e.btDecimals)),dtSupply:await this.unitsToAmount(e.datatoken,e.dtSupply,Number(e.dtDecimals)),btSupply:await this.unitsToAmount(e.baseToken,e.btSupply,Number(e.btDecimals)),fixedRate:await this.unitsToAmount(null,e.fixedRate,18),exchangeId:t}}async getFeesInfo(t){const e=await this.contract.getFeesInfo(t),a=await this.getExchange(t);return{opcFee:await this.unitsToAmount(null,e.opcFee.toString(),18),marketFee:await this.unitsToAmount(null,e.marketFee.toString(),18),marketFeeCollector:e.marketFeeCollector,marketFeeAvailable:await this.unitsToAmount(a.baseToken,e.marketFeeAvailable,Number(a.btDecimals)),oceanFeeAvailable:await this.unitsToAmount(a.baseToken,e.oceanFeeAvailable,Number(a.btDecimals)),exchangeId:t}}async getExchanges(){return await this.contract.getExchanges()}async isActive(t){return await this.contract.isActive(t)}async activateMint(t,e){var a;const i=await this.getExchange(t);if(!i)return null;if(!0===i.withMint)return null;const n=await this.contract.toggleMintState.estimateGas(t,!0);return e?n:await lt(n,this.getSignerAccordingSdk(),null==(a=this.config)?void 0:a.gasFeeMultiplier,this.contract.toggleMintState,t,!0)}async deactivateMint(t,e){var a;const i=await this.getExchange(t);if(!i)return null;if(!1===i.withMint)return null;const n=await this.contract.toggleMintState.estimateGas(t,!1);return e?n:await lt(n,this.getSignerAccordingSdk(),null==(a=this.config)?void 0:a.gasFeeMultiplier,this.contract.toggleMintState,t,!1)}async collectBasetokens(t,e,a){var i;if(!await this.getExchange(t))return null;const n=await this.contract.getExchange(t),r=await this.amountToUnits(n.baseToken,e,Number(n.btDecimals)),s=await this.contract.collectBT.estimateGas(t,r);return a?s:await lt(s,this.getSignerAccordingSdk(),null==(i=this.config)?void 0:i.gasFeeMultiplier,this.contract.collectBT,t,r)}async collectDatatokens(t,e,a){var i;if(!await this.getExchange(t))return null;const n=await this.contract.getExchange(t),r=await this.amountToUnits(n.datatoken,e,Number(n.dtDecimals)),s=await this.contract.collectDT.estimateGas(t,r);return a?s:await lt(s,this.getSignerAccordingSdk(),null==(i=this.config)?void 0:i.gasFeeMultiplier,this.contract.collectDT,t,r)}async collectMarketFee(t,e){var a;if(!await this.getExchange(t))return null;const i=await this.contract.collectMarketFee.estimateGas(t);return e?i:await lt(i,this.getSignerAccordingSdk(),null==(a=this.config)?void 0:a.gasFeeMultiplier,this.contract.collectMarketFee,t)}async collectOceanFee(t,e){var a;if(!await this.getExchange(t))return null;const i=await this.contract.collectOceanFee.estimateGas(t);return e?i:await lt(i,this.getSignerAccordingSdk(),null==(a=this.config)?void 0:a.gasFeeMultiplier,this.contract.collectOceanFee,t)}async getOPCCollector(){return await this.contract.opcCollector()}async getRouter(){return await this.contract.router()}async getExchangeOwner(t){return await(await this.getExchange(t)).exchangeOwner}async updateMarketFee(t,e,a){var i;const n=await this.contract.updateMarketFee.estimateGas(t,await this.amountToUnits(null,e,18));return a?n:await lt(n,this.getSignerAccordingSdk(),null==(i=this.config)?void 0:i.gasFeeMultiplier,this.contract.updateMarketFee,t,await this.amountToUnits(null,e,18))}async updateMarketFeeCollector(t,e,a){var i;const n=await this.contract.updateMarketFeeCollector.estimateGas(t,e);return a?n:await lt(n,this.getSignerAccordingSdk(),null==(i=this.config)?void 0:i.gasFeeMultiplier,this.contract.updateMarketFeeCollector,t,e)}}class yt extends ut{getDefaultAbi(){return v.abi}async buyDatatokenBatch(t,e){var a;const i=await this.contract.buyDTBatch.estimateGas(t);return e?i:await lt(i,this.getSignerAccordingSdk(),null==(a=this.config)?void 0:a.gasFeeMultiplier,this.contract.buyDTBatch,t)}async isApprovedToken(t){return await this.contract.isApprovedToken(t)}async isFixedPrice(t){return await this.contract.isFixedRateContract(t)}async getOwner(){return await this.contract.routerOwner()}async getNFTFactory(){return await this.contract.factory()}async addApprovedToken(t,e,a){var i;if(await this.getOwner()!==t)throw new Error("Caller is not Router Owner");const n=await this.contract.addApprovedToken.estimateGas(e);return a?n:await lt(n,this.getSignerAccordingSdk(),null==(i=this.config)?void 0:i.gasFeeMultiplier,this.contract.addApprovedToken,e)}async removeApprovedToken(t,e,a){var i;if(await this.getOwner()!==t)throw new Error("Caller is not Router Owner");const n=await this.contract.removeApprovedToken.estimateGas(e);return a?n:await lt(n,this.getSignerAccordingSdk(),null==(i=this.config)?void 0:i.gasFeeMultiplier,this.contract.removeApprovedToken,e)}async addFixedRateContract(t,e,a){var i;if(await this.getOwner()!==t)throw new Error("Caller is not Router Owner");const n=await this.contract.addFixedRateContract.estimateGas(e);return a?n:await lt(n,this.getSignerAccordingSdk(),null==(i=this.config)?void 0:i.gasFeeMultiplier,this.contract.addFixedRateContract,e)}async removeFixedRateContract(t,e,a){var i;if(await this.getOwner()!==t)throw new Error("Caller is not Router Owner");const n=await this.contract.removeFixedRateContract.estimateGas(e);return a?n:await lt(n,this.getSignerAccordingSdk(),null==(i=this.config)?void 0:i.gasFeeMultiplier,this.contract.removeFixedRateContract,e)}async addDispenserContract(t,e,a){var i;if(await this.getOwner()!==t)throw new Error("Caller is not Router Owner");const n=await this.contract.addDispenserContract.estimateGas(e);return a?n:await lt(n,this.getSignerAccordingSdk(),null==(i=this.config)?void 0:i.gasFeeMultiplier,this.contract.addDispenserContract,e)}async removeDispenserContract(t,e,a){var i;if(await this.getOwner()!==t)throw new Error("Caller is not Router Owner");const n=await this.contract.removeDispenserContract.estimateGas(e);return a?n:await lt(n,this.getSignerAccordingSdk(),null==(i=this.config)?void 0:i.gasFeeMultiplier,this.contract.removeDispenserContract,e)}async getOPCFee(t){const e=await this.contract.getOPCFee(t);return Number(e)}async getCurrentOPCFee(){const t=await this.contract.swapOceanFee();return Number(t)}async updateOPCFee(t,e,a,i,n,r){var s;if(await this.getOwner()!==t)throw new Error("Caller is not Router Owner");const o=await this.contract.updateOPCFee.estimateGas(e,a,i,n);return r?o:await lt(o,this.getSignerAccordingSdk(),null==(s=this.config)?void 0:s.gasFeeMultiplier,this.contract.updateOPCFee,e,a,i,n)}}var vt={nouns:["Crab","Fish","Seal","Octopus","Shark","Seahorse","Walrus","Starfish","Whale","Orca","Penguin","Jellyfish","Squid","Lobster","Pelican","Shrimp","Oyster","Clam","Seagull","Dolphin","Shell","Cormorant","Otter","Anemone","Turtle","Coral","Ray","Barracuda","Krill","Anchovy","Angelfish","Barnacle","Clownfish","Cod","Cuttlefish","Eel","Fugu","Herring","Haddock","Ling","Mackerel","Manatee","Narwhal","Nautilus","Plankton","Porpoise","Prawn","Pufferfish","Swordfish","Tuna"],adjectives:["adamant","adroit","amatory","ambitious","amused","animistic","antic","arcadian","artistic","astonishing","astounding","baleful","bellicose","bilious","blissful","boorish","brave","breathtaking","brilliant","calamitous","caustic","cerulean","clever","charming","comely","competent","concomitant","confident","contumacious","corpulent","crapulous","creative","dazzling","dedicated","defamatory","delighted","delightful","determined","didactic","dilatory","dowdy","efficacious","effulgent","egregious","empowered","endemic","enthusiastic","equanimous","exceptional","execrable","fabulous","fantastic","fastidious","feckless","fecund","friable","fulsome","garrulous","generous","gentle","guileless","gustatory","heuristic","histrionic","hubristic","incendiary","incredible","insidious","insolent","inspired","intransigent","inveterate","invidious","invigorated","irksome","jejune","juicy","jocular","joyful","judicious","kind","lachrymose","limpid","loquacious","lovely","luminous","mannered","marvelous","mendacious","meretricious","minatory","mordant","motivated","munificent","nefarious","noxious","obtuse","optimistic","parsimonious","pendulous","pernicious","pervasive","petulant","passionate","phenomenal","platitudinous","pleasant","powerful","precipitate","propitious","puckish","querulous","quiescent","rebarbative","recalcitant","redolent","rhadamanthine","risible","ruminative","sagacious","salubrious","sartorial","sclerotic","serpentine","smart","spasmodic","strident","stunning","stupendous","taciturn","tactful","tasty","tenacious","tremendous","tremulous","trenchant","turbulent","turgid","ubiquitous","uxorious","verdant","vibrant","voluble","voracious","wheedling","withering","wonderful","zealous"]};function kt(t){const e=t||vt,a=Math.floor(Math.random()*e.adjectives.length),i=Math.floor(Math.random()*e.nouns.length),n=Math.floor(100*Math.random()),r=e.adjectives[a].replace(/^\w/,t=>t.toUpperCase()),s=e.nouns[i].replace(/^\w/,t=>t.toUpperCase());return{name:`${r} ${s} Token`,symbol:`${(r.substring(0,3)+s.substring(0,3)).toUpperCase()}-${n}`}}class bt extends ut{getDefaultAbi(){return S.abi}async createNFT(t,e){if(t.templateIndex||(t.templateIndex=1),!t.name||!t.symbol){const{name:e,symbol:a}=kt();t.name=e,t.symbol=a}if(t.templateIndex>await this.getCurrentNFTTemplateCount())throw new Error("Template index doesnt exist");if(0===t.templateIndex)throw new Error("Template index cannot be ZERO");if(!1===(await this.getNFTTemplate(t.templateIndex)).isActive)throw new Error("Template is not active");const a=await this.contract.deployERC721Contract.estimateGas(t.name,t.symbol,t.templateIndex,gt,gt,t.tokenURI,t.transferable,t.owner);if(e)return a;try{var i;const e=await lt(a,this.getSignerAccordingSdk(),null==(i=this.config)?void 0:i.gasFeeMultiplier,this.contract.deployERC721Contract,t.name,t.symbol,t.templateIndex,gt,gt,t.tokenURI,t.transferable,t.owner);if(!e){const t="Tx for deploying new NFT contract does not exist or status is not successful.";throw console.error(t),t}return ct(await e.wait(),"NFTCreated").args[0]}catch(t){console.error(`Creation of NFT failed: ${t}`)}}async getCurrentNFTCount(){const t=await this.contract.getCurrentNFTCount();return Number(t)}async getCurrentTokenCount(){const t=await this.contract.getCurrentTokenCount();return Number(t)}async getOwner(){return await this.contract.owner()}async getCurrentNFTTemplateCount(){const t=await this.contract.getCurrentNFTTemplateCount();return Number(t)}async getCurrentTokenTemplateCount(){const t=await this.contract.getCurrentTemplateCount();return Number(t)}async getNFTTemplate(t){if(t>await this.getCurrentNFTTemplateCount())throw new Error("Template index doesnt exist");if(0===t)throw new Error("Template index cannot be ZERO");return await this.contract.getNFTTemplate(t)}async getTokenTemplate(t){return await this.contract.getTokenTemplate(t)}async checkDatatoken(t){return await this.contract.erc20List(t)}async checkNFT(t){return await this.contract.erc721List(t)}async addNFTTemplate(t,e,a){var i;if(await this.getOwner()!==t)throw new Error("Caller is not Factory Owner");if(e===gt)throw new Error("Template cannot be ZERO address");const n=await this.contract.add721TokenTemplate.estimateGas(e);return a?n:await lt(n,this.getSignerAccordingSdk(),null==(i=this.config)?void 0:i.gasFeeMultiplier,this.contract.add721TokenTemplate,e)}async disableNFTTemplate(t,e,a){var i;if(await this.getOwner()!==t)throw new Error("Caller is not Factory Owner");if(e>await this.getCurrentNFTTemplateCount())throw new Error("Template index doesnt exist");if(0===e)throw new Error("Template index cannot be ZERO");const n=await this.contract.disable721TokenTemplate.estimateGas(e);return a?n:await lt(n,this.getSignerAccordingSdk(),null==(i=this.config)?void 0:i.gasFeeMultiplier,this.contract.disable721TokenTemplate,e)}async reactivateNFTTemplate(t,e,a){var i;if(await this.getOwner()!==t)throw new Error("Caller is not Factory Owner");if(e>await this.getCurrentNFTTemplateCount())throw new Error("Template index doesnt exist");if(0===e)throw new Error("Template index cannot be ZERO");const n=await this.contract.reactivate721TokenTemplate.estimateGas(e);return a?n:await lt(n,this.getSignerAccordingSdk(),null==(i=this.config)?void 0:i.gasFeeMultiplier,this.contract.reactivate721TokenTemplate,e)}async addTokenTemplate(t,e,a){var i;if(await this.getOwner()!==t)throw new Error("Caller is not Factory Owner");if(e===gt)throw new Error("Template cannot be address ZERO");const n=await this.contract.addTokenTemplate.estimateGas(e);return a?n:await lt(n,this.getSignerAccordingSdk(),null==(i=this.config)?void 0:i.gasFeeMultiplier,this.contract.addTokenTemplate,e)}async disableTokenTemplate(t,e,a){var i;if(await this.getOwner()!==t)throw new Error("Caller is not Factory Owner");if(e>await this.getCurrentTokenTemplateCount())throw new Error("Template index doesnt exist");if(0===e)throw new Error("Template index cannot be ZERO");if(!1===(await this.getTokenTemplate(e)).isActive)throw new Error("Template is already disabled");const n=await this.contract.disableTokenTemplate.estimateGas(e);return a?n:await lt(n,this.getSignerAccordingSdk(),null==(i=this.config)?void 0:i.gasFeeMultiplier,this.contract.disableTokenTemplate,e)}async reactivateTokenTemplate(t,e,a){var i;if(await this.getOwner()!==t)throw new Error("Caller is not Factory Owner");if(e>await this.getCurrentTokenTemplateCount())throw new Error("Template index doesnt exist");if(0===e)throw new Error("Template index cannot be ZERO");if(!0===(await this.getTokenTemplate(e)).isActive)throw new Error("Template is already active");const n=await this.contract.reactivateTokenTemplate.estimateGas(e);return a?n:await lt(n,this.getSignerAccordingSdk(),null==(i=this.config)?void 0:i.gasFeeMultiplier,this.contract.reactivateTokenTemplate,e)}async startMultipleTokenOrder(t,e){var a;if(t.length>50)throw new Error("Too many orders");const i=await this.contract.startMultipleTokenOrder.estimateGas(t);return e?i:await lt(i,this.getSignerAccordingSdk(),null==(a=this.config)?void 0:a.gasFeeMultiplier,this.contract.startMultipleTokenOrder,t)}async createNftWithDatatoken(t,e,a){var i;const n=await this.getErcCreationParams(e),r=await this.contract.createNftWithErc20.estimateGas(t,n);return a?r:await lt(r,this.getSignerAccordingSdk(),null==(i=this.config)?void 0:i.gasFeeMultiplier,this.contract.createNftWithErc20,t,n)}async createNftWithDatatokenWithFixedRate(t,e,a,i){var n;const r=await this.getErcCreationParams(e),s=await this.getFreCreationParams(a),o=await this.contract.createNftWithErc20WithFixedRate.estimateGas(t,r,s);return i?o:await lt(o,this.getSignerAccordingSdk(),null==(n=this.config)?void 0:n.gasFeeMultiplier,this.contract.createNftWithErc20WithFixedRate,t,r,s)}async createNftWithDatatokenWithDispenser(t,e,a,i){var n;const r=await this.getErcCreationParams(e);a.maxBalance=await this.amountToUnits(null,a.maxBalance,18),a.maxTokens=await this.amountToUnits(null,a.maxTokens,18);const s=await this.contract.createNftWithErc20WithDispenser.estimateGas(t,r,a);return i?s:await lt(s,this.getSignerAccordingSdk(),null==(n=this.config)?void 0:n.gasFeeMultiplier,this.contract.createNftWithErc20WithDispenser,t,r,a)}async getErcCreationParams(t){let e,a;t.name&&t.symbol||({name:e,symbol:a}=kt());let i=18;if(t.feeToken!==gt)try{i=await rt(this.signer,t.feeToken)}catch(t){V.error("getTokenDecimals error",t)}const n=[t.minter,t.paymentCollector,t.mpFeeAddress,t.feeToken];return t.filesObject&&(t.accessListFactory&&n.push(t.accessListFactory),t.allowAccessList&&n.push(t.allowAccessList),t.denyAccessList&&n.push(t.denyAccessList)),{templateIndex:t.templateIndex,strings:[t.name||e,t.symbol||a],addresses:n,uints:[await this.amountToUnits(null,t.cap,18),await this.amountToUnits(null,t.feeAmount,i)],bytess:t.filesObject?[s(JSON.stringify(t.filesObject))]:[]}}async getFreCreationParams(t){t.allowedConsumer||(t.allowedConsumer=gt);const e=!1===t.withMint?0:1;return{fixedPriceAddress:t.fixedRateAddress,addresses:[t.baseTokenAddress,t.owner,t.marketFeeCollector,t.allowedConsumer],uints:[t.baseTokenDecimals,t.datatokenDecimals,await this.amountToUnits(null,t.fixedRate,18),await this.amountToUnits(null,t.marketFee,18),e]}}}function Tt(){try{if(process.env.ADDRESS_FILE){const t=e.readFileSync(process.env.ADDRESS_FILE,"utf8");return JSON.parse(t)}return t}catch(e){return t}}function St(t){try{const e=Tt();if(e){const a=Object.keys(e);for(const i of a)if(e[i].chainId===t)return e[i]}}catch(t){console.error(t)}return null}async function At(t,e,i,n){const r="number"==typeof i,s=new bt(e,t,n),o=await s.getCurrentTokenTemplateCount();for(let e=1;e<=o;e++){const n=await s.getTokenTemplate(e),o=new a.Contract(n.templateAddress,A.abi,t);if(r){const t=await o.getId();if(n.isActive&&t.toString()===i.toString())return e}else if(n.isActive&&n.templateAddress===i.toString())return e}return-1}class Ft extends dt{getDefaultAbi(){return T.abi}async createDatatoken(t,e,a,i,n,r,o,c,l,d,u,h,g,w,p,m){var f;if(!0!==(await this.getNftPermissions(t,e)).deployERC20)throw new Error("Caller is not DatatokenDeployer");u||(u=1),l&&d||({name:l,symbol:d}=kt());const y=this.getContract(t);if(!this.signer.provider)throw new Error("Provider is required but not available");const{chainId:v}=await this.signer.provider.getNetwork(),k=St(Number(v));h&&(u=await At(this.signer,k.ERC721Factory,4,Number(v)));const b=await y.createERC20.estimateGas(u,[l,d],[a,i,n,r],[await this.amountToUnits(null,c,18),await this.amountToUnits(null,o,18)],[]);if(m)return b;const T=[a,i,n,r];g&&(T.push(g.toLowerCase()),T.push(w?w.toLowerCase():gt),T.push(p||gt));const S=await lt(b,this.getSignerAccordingSdk(),null==(f=this.config)?void 0:f.gasFeeMultiplier,y.createERC20,u,[l,d],T,[await this.amountToUnits(null,c,18),await this.amountToUnits(null,o,18)],h?[s(h)]:[]),A=ct(await S.wait(),"TokenCreated");return null==A?void 0:A.args[0]}async addManager(t,e,a,i){var n;const r=this.getContract(t);if(await this.getNftOwner(t)!==e)throw new Error("Caller is not NFT Owner");const s=await r.addManager.estimateGas(a);return i?s:await lt(s,this.getSignerAccordingSdk(),null==(n=this.config)?void 0:n.gasFeeMultiplier,r.addManager,a)}async removeManager(t,e,a,i){var n;const r=this.getContract(t);if(await this.getNftOwner(t)!==e)throw new Error("Caller is not NFT Owner");const s=await r.removeManager.estimateGas(a);return i?s:await lt(s,this.getSignerAccordingSdk(),null==(n=this.config)?void 0:n.gasFeeMultiplier,r.removeManager,a)}async addDatatokenDeployer(t,e,a,i){var n;const r=this.getContract(t);if(!0!==(await this.getNftPermissions(t,e)).manager)throw new Error("Caller is not Manager");const s=await r.addToCreateERC20List.estimateGas(a);return i?s:await lt(s,this.getSignerAccordingSdk(),null==(n=this.config)?void 0:n.gasFeeMultiplier,r.addToCreateERC20List,a)}async removeDatatokenDeployer(t,e,a,i){var n;const r=this.getContract(t);if(!0!==(await this.getNftPermissions(t,e)).manager||e===a&&!0!==(await this.getNftPermissions(t,e)).deployERC20)throw new Error("Caller is not Manager nor DatatokenDeployer");const s=await r.removeFromCreateERC20List.estimateGas(a);return i?s:await lt(s,this.getSignerAccordingSdk(),null==(n=this.config)?void 0:n.gasFeeMultiplier,r.removeFromCreateERC20List,a)}async addMetadataUpdater(t,e,a,i){var n;const r=this.getContract(t);if(!0!==(await this.getNftPermissions(t,e)).manager)throw new Error("Caller is not Manager");const s=await r.addToMetadataList.estimateGas(a);return i?s:await lt(s,this.getSignerAccordingSdk(),null==(n=this.config)?void 0:n.gasFeeMultiplier,r.addToMetadataList,a)}async removeMetadataUpdater(t,e,a,i){var n;const r=this.getContract(t);if(!0!==(await this.getNftPermissions(t,e)).manager||e!==a&&!0!==(await this.getNftPermissions(t,e)).updateMetadata)throw new Error("Caller is not Manager nor Metadata Updater");const s=await r.removeFromMetadataList.estimateGas(a);return i?s:await lt(s,this.getSignerAccordingSdk(),null==(n=this.config)?void 0:n.gasFeeMultiplier,r.removeFromMetadataList,a)}async addStoreUpdater(t,e,a,i){var n;const r=this.getContract(t);if(!0!==(await this.getNftPermissions(t,e)).manager)throw new Error("Caller is not Manager");const s=await r.addTo725StoreList.estimateGas(a);return i?s:await lt(s,this.getSignerAccordingSdk(),null==(n=this.config)?void 0:n.gasFeeMultiplier,r.addTo725StoreList,a)}async removeStoreUpdater(t,e,a,i){var n;const r=this.getContract(t);if(!0!==(await this.getNftPermissions(t,e)).manager||e!==a&&!0!==(await this.getNftPermissions(t,e)).store)throw new Error("Caller is not Manager nor storeUpdater");const s=await r.removeFrom725StoreList.estimateGas(a);return i?s:await lt(s,this.getSignerAccordingSdk(),null==(n=this.config)?void 0:n.gasFeeMultiplier,r.removeFrom725StoreList,a)}async cleanPermissions(t,e,a){var i;const n=this.getContract(t);if(await this.getNftOwner(t)!==e)throw new Error("Caller is not NFT Owner");const r=await n.cleanPermissions.estimateGas();return a?r:await lt(r,this.getSignerAccordingSdk(),null==(i=this.config)?void 0:i.gasFeeMultiplier,n.cleanPermissions)}async transferNft(t,e,a,i,n){var r;const s=this.getContract(t);if(await this.getNftOwner(t)!==e)throw new Error("Caller is not NFT Owner");const o=i||1,c=await s.transferFrom.estimateGas(e,a,o);return n?c:await lt(c,this.getSignerAccordingSdk(),null==(r=this.config)?void 0:r.gasFeeMultiplier,s.transferFrom,e,a,o)}async safeTransferNft(t,e,a,i,n){var r;const s=this.getContract(t);if(await this.getNftOwner(t)!==e)throw new Error("Caller is not NFT Owner");const o=i||1,c=await s.safeTransferFrom.estimateGas(e,a,o);return n?c:await lt(c,this.getSignerAccordingSdk(),null==(r=this.config)?void 0:r.gasFeeMultiplier,s.safeTransferFrom,e,a,o)}async setMetadata(t,e,a,i,n,r,s,o,c,l){var d;const u=this.getContract(t);if(c||(c=[]),!(await this.getNftPermissions(t,e)).updateMetadata)throw new Error("Caller is not Metadata updater");const h=await u.setMetaData.estimateGas(a,i,n,r,s,o,c);return l?h:await lt(h,this.signer,null==(d=this.config)?void 0:d.gasFeeMultiplier,u.setMetaData,a,i,n,r,s,o,c)}async setMetadataAndTokenURI(t,e,a,i){var n;const r=this.getContract(t);if(!(await this.getNftPermissions(t,e)).updateMetadata)throw new Error("Caller is not Metadata updater");const s=J({},a,{metadataProofs:a.metadataProofs||[]}),o=await r.setMetaDataAndTokenURI.estimateGas(s);return i?o:await lt(o,this.signer,null==(n=this.config)?void 0:n.gasFeeMultiplier,r.setMetaDataAndTokenURI,s)}async setMetadataState(t,e,a,i){var n;const r=this.getContract(t);if(!(await this.getNftPermissions(t,e)).updateMetadata)throw new Error("Caller is not Metadata updater");const s=await r.setMetaDataState.estimateGas(a);return i?s:await lt(s,this.getSignerAccordingSdk(),null==(n=this.config)?void 0:n.gasFeeMultiplier,r.setMetaDataState,a)}async setTokenURI(t,e,a){var i;const n=this.getContract(t),r=await n.setTokenURI.estimateGas("1",e);return a?r:await lt(r,this.getSignerAccordingSdk(),null==(i=this.config)?void 0:i.gasFeeMultiplier,n.setTokenURI,"1",e)}async getNftOwner(t){const e=this.getContract(t);return await e.ownerOf(1)}async getNftPermissions(t,e){const a=this.getContract(t);return await a.getPermissions(e)}async getMetadata(t){const e=this.getContract(t);return await e.getMetaData()}async isDatatokenDeployer(t,e){const a=this.getContract(t);return await a.isERC20Deployer(e)}async setData(t,e,a,i,n){var r;if(!0!==(await this.getNftPermissions(t,e)).store)throw new Error("User is not ERC20 store updater");const l=this.getContract(t),d=o(a),u=c(s(i)),h=await l.setNewData.estimateGas(d,u);return n?h:await lt(h,this.getSignerAccordingSdk(),null==(r=this.config)?void 0:r.gasFeeMultiplier,l.setNewData,d,u)}async getData(t,e){const a=this.getContract(t),i=o(e),n=await a.getData(i);return n?l(n):null}async getTokenURI(t,e){const a=this.getContract(t);return await a.tokenURI(e)}async isDatatokenDeployed(t,e){const a=this.getContract(t);return await a.isDeployed(e)}}class Et extends dt{getDefaultAbi(){return k.abi}constructor(t,e,a,i,n){super(t,e,a,i),this.abiEnterprise=void 0,this.nft=void 0,this.abiEnterprise=n||b.abi,this.nft=new Ft(this.signer,e)}async approve(t,e,a,i){var n;const r=this.getContract(t),s=await r.approve.estimateGas(e,ot(null,null,a,18));return i?s:await lt(s,this.getSignerAccordingSdk(),null==(n=this.config)?void 0:n.gasFeeMultiplier,r.approve,e,ot(null,null,a,18))}async createFixedRate(t,e,a,i){var n;const r=this.getContract(t);if(!await this.isDatatokenDeployer(t,e))throw new Error("User is not Datatoken Deployer");a.allowedConsumer||(a.allowedConsumer=gt);const s=!1===a.withMint?0:1,o=await r.createFixedRate.estimateGas(a.fixedRateAddress,[a.baseTokenAddress,a.owner,a.marketFeeCollector,a.allowedConsumer],[a.baseTokenDecimals,a.datatokenDecimals,a.fixedRate,a.marketFee,s]);return i?o:await lt(o,this.getSignerAccordingSdk(),null==(n=this.config)?void 0:n.gasFeeMultiplier,r.createFixedRate,a.fixedRateAddress,[a.baseTokenAddress,a.owner,a.marketFeeCollector,a.allowedConsumer],[a.baseTokenDecimals,a.datatokenDecimals,a.fixedRate,a.marketFee,s])}async createDispenser(t,e,a,i,n){var r;if(!await this.isDatatokenDeployer(t,e))throw new Error("User is not Datatoken Deployer");const s=this.getContract(t);i.allowedSwapper||(i.allowedSwapper=gt),i.withMint=!1!==i.withMint;const o=await s.createDispenser.estimateGas(a,i.maxTokens,i.maxBalance,i.withMint,i.allowedSwapper);return n?o:await lt(o,this.getSignerAccordingSdk(),null==(r=this.config)?void 0:r.gasFeeMultiplier,s.createDispenser,a,i.maxTokens,i.maxBalance,i.withMint,i.allowedSwapper)}async mint(t,e,a,i,n){const r=this.getContract(t);if(!0!==(await this.getPermissions(t,e)).minter)throw new Error("Caller is not Minter");const s=await this.getCap(t);if(new m(s).gte(a)){var o;const t=await r.mint.estimateGas(i||e,ot(null,null,a,18));return n?t:await lt(t,this.getSignerAccordingSdk(),null==(o=this.config)?void 0:o.gasFeeMultiplier,r.mint,i||e,ot(null,null,a,18))}throw new Error("Mint amount exceeds cap available")}async addMinter(t,e,a,i){var n;const r=this.getContract(t);if(!0!==await this.isDatatokenDeployer(t,e))throw new Error("Caller is not DatatokenDeployer");const s=await r.addMinter.estimateGas(a);return i?s:await lt(s,this.getSignerAccordingSdk(),null==(n=this.config)?void 0:n.gasFeeMultiplier,r.addMinter,a)}async removeMinter(t,e,a,i){var n;const r=this.getContract(t);if(!0!==await this.isDatatokenDeployer(t,e))throw new Error("Caller is not DatatokenDeployer");const s=await r.removeMinter.estimateGas(a);return i?s:await lt(s,this.getSignerAccordingSdk(),null==(n=this.config)?void 0:n.gasFeeMultiplier,r.removeMinter,a)}async addPaymentManager(t,e,a,i){var n;const r=this.getContract(t);if(!0!==await this.isDatatokenDeployer(t,e))throw new Error("Caller is not DatatokenDeployer");const s=await r.addPaymentManager.estimateGas(a);return i?s:await lt(s,this.getSignerAccordingSdk(),null==(n=this.config)?void 0:n.gasFeeMultiplier,r.addPaymentManager,a)}async removePaymentManager(t,e,a,i){var n;const r=this.getContract(t);if(!0!==await this.isDatatokenDeployer(t,e))throw new Error("Caller is not DatatokenDeployer");const s=await r.removePaymentManager.estimateGas(a);return i?s:await lt(s,this.getSignerAccordingSdk(),null==(n=this.config)?void 0:n.gasFeeMultiplier,r.removePaymentManager,a)}async setPaymentCollector(t,e,a,i){var n;const r=this.getContract(t),s=(await this.getPermissions(t,e)).paymentManager,o=!s&&await this.getNFTAddress(t),c=o&&await this.nft.getNftOwner(o)===e,l=o&&!c&&await this.nft.getNftPermissions(o,e);if(!s&&!c&&!(null==l?void 0:l.deployERC20))throw new Error("Caller is not Fee Manager, owner or Datatoken Deployer");const d=await r.setPaymentCollector.estimateGas(a);return i?d:await lt(d,this.getSignerAccordingSdk(),null==(n=this.config)?void 0:n.gasFeeMultiplier,r.setPaymentCollector,a)}async getPaymentCollector(t){const e=this.getContract(t);return await e.getPaymentCollector()}async transfer(t,e,a,i){return this.transferWei(t,e,await ot(null,null,a,18),i)}async transferWei(t,e,a,i){var n;const r=this.getContract(t),s=await r.transfer.estimateGas(e,a);return i?s:await lt(s,this.getSignerAccordingSdk(),null==(n=this.config)?void 0:n.gasFeeMultiplier,r.transfer,e,a)}async startOrder(t,e,a,i,n,r){var s;const o=this.getContract(t,this.abi);n||(n={consumeMarketFeeAddress:gt,consumeMarketFeeToken:gt,consumeMarketFeeAmount:"0"});const c=await o.startOrder.estimateGas(e,a,i,n);return r?c:await lt(c,this.getSignerAccordingSdk(),null==(s=this.config)?void 0:s.gasFeeMultiplier,o.startOrder,e,a,i,n)}async reuseOrder(t,e,a,i){var n;const r=this.getContract(t),s=await r.reuseOrder.estimateGas(e,a);return i?s:await lt(s,this.getSignerAccordingSdk(),null==(n=this.config)?void 0:n.gasFeeMultiplier,r.reuseOrder,e,a)}async buyFromFreAndOrder(t,e,a,i){var n;const r=this.getContract(t,this.abiEnterprise),s=await this.getFreOrderParams(a),o=await r.buyFromFreAndOrder.estimateGas(e,s);return i?o:await lt(o,this.getSignerAccordingSdk(),null==(n=this.config)?void 0:n.gasFeeMultiplier,r.buyFromFreAndOrder,e,s)}async buyFromDispenserAndOrder(t,e,a,i){var n;const r=this.getContract(t,this.abiEnterprise),s=await r.buyFromDispenserAndOrder.estimateGas(e,a);return i?s:await lt(s,this.getSignerAccordingSdk(),null==(n=this.config)?void 0:n.gasFeeMultiplier,r.buyFromDispenserAndOrder,e,a)}async setData(t,e,a,i){var n;if(!await this.isDatatokenDeployer(t,e))throw new Error("User is not Datatoken Deployer");const r=this.getContract(t),o=c(s(a)),l=await r.setData.estimateGas(o);return i?l:await lt(l,this.getSignerAccordingSdk(),null==(n=this.config)?void 0:n.gasFeeMultiplier,r.setData,o)}async cleanPermissions(t,e,a){var i;if(await this.nft.getNftOwner(await this.getNFTAddress(t))!==e)throw new Error("Caller is NOT Nft Owner");const n=this.getContract(t),r=await n.cleanPermissions.estimateGas();return a?r:await lt(r,this.getSignerAccordingSdk(),null==(i=this.config)?void 0:i.gasFeeMultiplier,n.cleanPermissions)}async getPermissions(t,e){const a=this.getContract(t);return await a.permissions(e)}async getCap(t){const e=this.getContract(t),a=await e.cap();return await this.unitsToAmount(null,a,18)}async getDecimals(t){const e=this.getContract(t),a=await e.decimals();return Number(a)}async getId(t){const e=this.getContract(t),a=await e.getId();return Number(a)}async getSymbol(t){const e=this.getContract(t);return await e.symbol()}async getName(t){const e=this.getContract(t);return await e.name()}async getNFTAddress(t){const e=this.getContract(t);return await e.getERC721Address()}async getFixedRates(t){const e=this.getContract(t);return await e.getFixedRates()}async getDispensers(t){const e=this.getContract(t);return await e.getDispensers()}async isDatatokenDeployer(t,e){const a=this.getContract(t);return await a.isERC20Deployer(e)}async balance(t,e){const a=this.getContract(t),i=await a.balanceOf(e);return await this.unitsToAmount(null,i,18)}async allowance(t,e,a,i=18){const n=this.getContract(t),r=await n.allowance(e,a);return await this.unitsToAmount(null,r,i)}async setPublishingMarketFee(t,e,a,i,n,r){var s;const o=this.getContract(t);if((await o.getPublishingMarketFee())[0]!==n)throw new Error("Caller is not the Publishing Market Fee Address");const c=await o.setPublishingMarketFee.estimateGas(e,a,i);return r?c:await lt(c,this.getSignerAccordingSdk(),null==(s=this.config)?void 0:s.gasFeeMultiplier,o.setPublishingMarketFee,e,a,i)}async getPublishingMarketFee(t){const e=this.getContract(t),a=await e.getPublishingMarketFee();return{publishMarketFeeAddress:a[0],publishMarketFeeToken:a[1],publishMarketFeeAmount:a[2].toString()}}async getFreOrderParams(t){return{exchangeContract:t.exchangeContract,exchangeId:t.exchangeId,maxBaseTokenAmount:await ot(this.signer,t.baseTokenAddress,t.maxBaseTokenAmount,t.baseTokenDecimals),swapMarketFee:await ot(this.signer,t.baseTokenAddress,t.swapMarketFee,t.baseTokenDecimals),marketFeeAddress:t.marketFeeAddress}}}class Ct extends Et{getDefaultAbi(){return F.abi}constructor(t,e,a,i,n){super(t,a,i,n),this.accessList=void 0,this.fileObject=void 0,this.abi=this.getDefaultAbi(),this.fileObject=e}setFileObj(t){this.fileObject=t}async getAllowlistContract(t){const e=this.getContract(t,this.getDefaultAbi());return await e.getAllowListContract()}async getDenylistContract(t){const e=this.getContract(t,this.getDefaultAbi());return await e.getDenyListContract()}async setAllowListContract(t,e,a,i){var n;if(!await this.isDatatokenDeployer(t,a))throw new Error("User is not Datatoken Deployer");const r=this.getContract(t),s=await r.setAllowListContract.estimateGas(e);return i?s:await lt(s,this.getSignerAccordingSdk(),null==(n=this.config)?void 0:n.gasFeeMultiplier,r.setAllowListContract,e)}async setDenyListContract(t,e,a,i){var n;if(!await this.isDatatokenDeployer(t,a))throw new Error("User is not Datatoken Deployer");const r=this.getContract(t),s=await r.setDenyListContract.estimateGas(e);return i?s:await lt(s,this.getSignerAccordingSdk(),null==(n=this.config)?void 0:n.gasFeeMultiplier,r.setDenyListContract,e)}async setFileObject(t,e,a){var i;if(!await this.isDatatokenDeployer(t,e))throw new Error("User is not Datatoken Deployer");const n=this.getContract(t),r=await n.setFilesObject.estimateGas(this.fileObject);return a?r:await lt(r,this.getSignerAccordingSdk(),null==(i=this.config)?void 0:i.gasFeeMultiplier,n.setFilesObject,this.fileObject)}async getFileObject(t,e,a,i,n,r,s){const o=this.getContract(t,this.getDefaultAbi());return await o.getFileObject(e,a,i,n,r,s)}}class Dt extends ut{getDefaultAbi(){return E.abi}constructor(t,e,a,i,n){super(t,e,a,i,n),this.abiEnterprise=void 0,this.abi=n||this.getDefaultAbi()}async getTokenUri(t){return await this.contract.tokenURI(t)}async getOwner(){return await this.contract.owner()}async getId(){const t=await this.contract.getId();return Number(t)}async getName(){return await this.contract.name()}async getSymbol(){return await this.contract.symbol()}async balance(t){const e=await this.contract.balanceOf(t);return await this.unitsToAmount(null,e,18)}async mint(t,e,a){var i;const n=await this.contract.mint.estimateGas(t,e);return a?n:await lt(n,this.getSignerAccordingSdk(),null==(i=this.config)?void 0:i.gasFeeMultiplier,this.contract.mint,t,e)}async batchMint(t,e,a){var i;const n=await this.contract.batchMint.estimateGas(t,e);return a?n:await lt(n,this.getSignerAccordingSdk(),null==(i=this.config)?void 0:i.gasFeeMultiplier,this.contract.batchMint,t,e)}async burn(t,e){var a;const i=await this.contract.burn.estimateGas(t);return e?i:await lt(i,this.getSignerAccordingSdk(),null==(a=this.config)?void 0:a.gasFeeMultiplier,this.contract.burn,t)}async transferOwnership(t,e){var a;const i=await this.contract.transferOwnership.estimateGas(t);return e?i:await lt(i,this.getSignerAccordingSdk(),null==(a=this.config)?void 0:a.gasFeeMultiplier,this.contract.transferOwnership,t)}async renounceOwnership(t){var e;const a=await this.contract.renounceOwnership.estimateGas();return t?a:await lt(a,this.getSignerAccordingSdk(),null==(e=this.config)?void 0:e.gasFeeMultiplier,this.contract.renounceOwnership)}}class xt extends ut{getDefaultAbi(){return C.abi}constructor(t,e,a,i,n){super(t,e,a,i,n),this.abi=n||this.getDefaultAbi()}async deployAccessListContract(t,e,a,i=!1,n,r,s){if(!t||!e){const{name:a,symbol:i}=kt();t=a,e=i}const o=await this.contract.deployAccessListContract.estimateGas(t,e,i,n,r,a);if(s)return o;try{var c;const s=await lt(o,this.getSignerAccordingSdk(),null==(c=this.config)?void 0:c.gasFeeMultiplier,this.contract.deployAccessListContract,t,e,i,n,r,a);if(!s){const t="Tx for deploying new access list was not processed on chain.";throw console.error(t),t}return ct(await s.wait(),"NewAccessList").args[0]}catch(t){console.error(`Creation of AccessList failed: ${t}`)}}async getOwner(){return await this.contract.owner()}async isSoulbound(t){return await this.contract.isSoulBound(t)}async isDeployed(t){return await this.contract.isDeployed(t)}async changeTemplateAddress(t,e,a){var i;if(await this.getOwner()!==t)throw new Error("Caller is not Factory Owner");if(e===gt)throw new Error("Template address cannot be ZERO address");const n=await this.contract.changeTemplateAddress.estimateGas(e);return a?n:await lt(n,this.getSignerAccordingSdk(),null==(i=this.config)?void 0:i.gasFeeMultiplier,this.contract.changeTemplateAddress,e)}}class Mt extends ut{getDefaultAbi(){return D.abi}async lockTokens(t,e,a){var i;const n=await this.amountToUnits(await this.getToken(),t),r=await this.contract.create_lock.estimateGas(n,e);return a?r:await lt(BigInt(new p(r).plus(20000n).toString()),this.getSignerAccordingSdk(),null==(i=this.config)?void 0:i.gasFeeMultiplier,this.contract.create_lock,n,e)}async depositFor(t,e,a){var i;const n=await this.amountToUnits(await this.getToken(),e),r=await this.contract.deposit_for.estimateGas(t,n);return a?r:await lt(BigInt(new p(r).plus(20000n).toString()),this.getSignerAccordingSdk(),null==(i=this.config)?void 0:i.gasFeeMultiplier,this.contract.deposit_for,t,n)}async increaseAmount(t,e){var a;const i=await this.amountToUnits(await this.getToken(),t),n=await this.contract.increase_amount.estimateGas(i);return e?n:await lt(BigInt(new p(n).plus(20000n).toString()),this.getSignerAccordingSdk(),null==(a=this.config)?void 0:a.gasFeeMultiplier,this.contract.increase_amount,i)}async increaseUnlockTime(t,e){var a;const i=await this.contract.increase_unlock_time.estimateGas(t);return e?i:await lt(BigInt(new p(i).plus(20000n).toString()),this.getSignerAccordingSdk(),null==(a=this.config)?void 0:a.gasFeeMultiplier,this.contract.increase_unlock_time,t)}async withdraw(t){var e;const a=await this.contract.withdraw.estimateGas();return t?a:await lt(BigInt(new p(a).plus(20000n).toString()),this.getSignerAccordingSdk(),null==(e=this.config)?void 0:e.gasFeeMultiplier,this.contract.withdraw)}async getVotingPower(t){const e=await this.contract.balanceOf(t);return Number(e)}async getLockedAmount(t){const e=await this.contract.locked(t);return await this.unitsToAmount(await this.getToken(),e.amount.toString())}async lockEnd(t){const e=await this.contract.locked__end(t);return parseInt(e.toString())}async totalSupply(){return await this.unitsToAmount(await this.getToken(),await this.contract.totalSupply())}async getToken(){return await this.contract.token()}}class Ot extends ut{getDefaultAbi(){return x.abi}async claim(t){var e;const a=await this.contract.claim.estimateGas();return t?a:await lt(BigInt(new p(a).plus(20000n).toString()),this.getSignerAccordingSdk(),null==(e=this.config)?void 0:e.gasFeeMultiplier,this.contract.claim)}async claimMany(t,e){var a;const i=await this.contract.claim_many.estimateGas(t);return e?i:await lt(BigInt(new p(i).plus(20000n).toString()),this.getSignerAccordingSdk(),null==(a=this.config)?void 0:a.gasFeeMultiplier,this.contract.claim_many,t)}}class Nt extends ut{getDefaultAbi(){return M.abi}async estimateClaim(t){const e=await this.contract.estimateClaim(t),a=new Mt(await this.contract.voting_escrow(),this.signer);return await this.unitsToAmount(await a.getToken(),e)}}class Pt extends ut{getDefaultAbi(){return O.abi}async setAllocation(t,e,a,i){var n;const r=await this.contract.setAllocation.estimateGas(t,e,a);return i?r:await lt(BigInt(new p(r).plus(20000n).toString()),this.getSignerAccordingSdk(),null==(n=this.config)?void 0:n.gasFeeMultiplier,this.contract.setAllocation,t,e,a)}async setBatchAllocation(t,e,a,i){var n;const r=await this.contract.setBatchAllocation.estimateGas(t,e,a);return i?r:await lt(BigInt(new p(r).plus(20000n).toString()),this.getSignerAccordingSdk(),null==(n=this.config)?void 0:n.gasFeeMultiplier,this.contract.setBatchAllocation,t,e,a)}async getTotalAllocation(t){const e=await this.contract.getTotalAllocation(t);return Number(e)}async getVeAllocation(t,e,a){const i=await this.contract.getveAllocation(t,e,a);return Number(i)}}class Rt extends ut{getDefaultAbi(){return N.abi}async getAvailableRewards(t,e){const a=await this.contract.claimable(t,e);return await this.unitsToAmount(e,a)}async claimRewards(t,e,a){var i;const n=await this.contract.claimFor.estimateGas(t,e);return a?n:await lt(n,this.getSignerAccordingSdk(),null==(i=this.config)?void 0:i.gasFeeMultiplier,this.contract.claimFor,t,e)}async allocateRewards(t,e,a,i){var n;for(let t=0;t<e.length;t++)e[t]=await this.amountToUnits(a,e[t]);const r=await this.contract.allocate.estimateGas(t,e,a);return i?r:await lt(r,this.getSignerAccordingSdk(),null==(n=this.config)?void 0:n.gasFeeMultiplier,this.contract.allocate,t,e,a)}}class Ut extends ut{getDefaultAbi(){return P.abi}async getMultipleAvailableRewards(t,e){const a=await this.contract.claimables(t,e),i=[];for(let t=0;t<a.length;t++)i.push(await this.unitsToAmount(e[t],a[t]));return i}async claimMultipleRewards(t,e,a){var i;const n=await this.contract.claimMultiple.estimateGas(t,e);return a?n:await lt(n,this.getSignerAccordingSdk(),null==(i=this.config)?void 0:i.gasFeeMultiplier,this.contract.claimMultiple,t,e)}}class It extends ut{getDefaultAbi(){return R.abi}constructor(t,e,a,i,n){super(t,e,a,i,n),this.abiEnterprise=void 0,this.abi=n||this.getDefaultAbi()}async getFunds(t){return await this.contract.getFunds(t)}async getUserFunds(t,e){return await this.contract.getUserFunds(t,e)}async getUserTokens(t){return await this.contract.getUserTokens(t)}async getLocks(t,e,a){return await this.contract.getLocks(t,e,a)}async getAuthorizations(t,e,a){return await this.contract.getAuthorizations(t,e,a)}async verifyFundsForEscrowPayment(t,e,a,i,n,r){var s;const o=await(null==(s=this.signer.provider)?void 0:s.getBalance(d(e)));if(new p(o).isZero())return{isValid:!1,message:"Native token balance is 0. Please add funds"};const c=new Et(this.signer),l=await c.allowance(t,await this.signer.getAddress(),this.contract.target.toString());new p(await this.amountToUnits(t,l,18)).isLessThan(new p(i))&&await c.approve(d(t),d(this.contract.target.toString()),i);const h=await c.balance(t,await this.signer.getAddress());if(new p(h).isZero())return{isValid:!1,message:"Payment token balance is 0. Please add funds"};const g=await this.getAuthorizations(t,await this.signer.getAddress(),e),w=await this.getUserFunds(await this.signer.getAddress(),t);return new p(w[0]).isZero()&&(a&&new p(u(h)).isLessThanOrEqualTo(new p(u(a)))&&new p(u(a)).isGreaterThan(new p(i))?await this.deposit(t,a):new p(u(h)).isLessThanOrEqualTo(new p(u(i)))?await this.deposit(t,await this.unitsToAmount(t,i)):await this.deposit(t,h)),0===g.length&&await this.authorize(d(t),d(e),(Number(i)/2).toString(),n,r),{isValid:!0,message:""}}async deposit(t,e,a){var i;const n=ot(null,null,e,18),r=await this.contract.deposit.estimateGas(t,n);return a?r:await lt(r,this.getSignerAccordingSdk(),null==(i=this.config)?void 0:i.gasFeeMultiplier,this.contract.deposit,t,n)}async withdraw(t,e,a){var i;const n=[],r=[];if(t.length!==e.length)throw new Error("Tokens and amounts arrays must have the same length");const s=await this.signer.getAddress();for(let a=0;a<t.length;a++){const i=t[a],o=new p(e[a]),c=await this.getUserFunds(s,i),l=new p(c[0]);o.isGreaterThan(0)&&o.isLessThanOrEqualTo(l)?(n.push(i),r.push(e[a])):console.log(`Insufficient funds for token ${i}`)}const o=r.map(t=>ot(null,null,t,18)),c=await this.contract.withdraw.estimateGas(t,o);return a?c:await lt(c,this.getSignerAccordingSdk(),null==(i=this.config)?void 0:i.gasFeeMultiplier,this.contract.withdraw,n,o)}async authorize(t,e,a,i,n,r){var s;if(0!==(await this.getAuthorizations(t,await this.signer.getAddress(),e)).length)return console.log(`Payee ${e} already authorized`),null;const o=ot(null,null,a,18),c=ot(null,null,i,18),l=ot(null,null,n,18),d=await this.contract.authorize.estimateGas(t,e,o,c,l);return r?d:await lt(d,this.getSignerAccordingSdk(),null==(s=this.config)?void 0:s.gasFeeMultiplier,this.contract.authorize,t,e,o,c,l)}async cancelExpiredLocks(t,e,a,i,n){var r;const s=await this.contract.cancelExpiredLocks.estimateGas(t,e,a,i);return n?s:await lt(s,this.getSignerAccordingSdk(),null==(r=this.config)?void 0:r.gasFeeMultiplier,this.contract.cancelExpiredLocks,t,e,a,i)}}class Lt extends ut{getDefaultAbi(){return U.abi}constructor(t,e,a,i,n){super(t,e,a,i,n),this.abi=n||this.getDefaultAbi()}async isTokenAllowed(t){return await this.contract.isTokenAllowed(t)}async getToken(t){return await this.contract.getToken(t)}async calculateFee(t,e){const a=this.amountToUnits(t,e.toString()),i=await this.contract.calculateFee(t,a);return this.unitsToAmount(t,i)}}async function jt(t){return new Promise(e=>{setTimeout(e,t)})}function Gt(t){return null!=t}async function _t(t,e){const a=h(e);let i=await t._legacySignMessage(a);i=i.substr(2);const n="0x"+i.slice(0,64),r="0x"+i.slice(64,128);let s="0x"+i.slice(128,130);return"0x00"===s&&(s="0x1b"),"0x01"===s&&(s="0x1c"),{v:s,r:n,s:r}}async function $t(t,e){const a=o(s(e)),i=h(a);if(!t.provider)throw new Error("Provider is required but not available");const{chainId:n}=await t.provider.getNetwork();try{return await t.signMessage(i)}catch(e){if(V.error("Sign message error: ",e),8996===Number(n))return console.log("Signing message with _legacySignMessage"),await t._legacySignMessage(i)}}class Bt{constructor(t){this.aquariusURL=void 0,this.aquariusURL=t}async resolve(t,e,a){const i=this.aquariusURL+"/api/aquarius/assets/ddo/"+t;try{const t=await I(i,{method:"GET",headers:{"Content-Type":"application/json",Authorization:a},signal:e});if(t.ok)return await t.json();throw new Error("HTTP request failed with status "+t.status)}catch(t){throw V.error(t),new Error("HTTP request failed")}}async waitForIndexer(t,e,a,i=3e4,n=100,r){let s=0;n>500&&(V.warn("Max Limit exceeded, defaulting to 500 retries."),n=500);do{try{const i=this.aquariusURL+"/api/aquarius/assets/ddo/"+t,n=await I(i,{method:"GET",headers:{"Content-Type":"application/json",Authorization:r},signal:a});if(n.ok){const t=await n.json(),a=L.getDDOClass(t),{indexedMetadata:i}=a.getAssetFields();if(!e)return t;if(i.event&&i.event.txid===e)return t}}catch(t){}await jt(i),s++}while(s<n);return null}async validate(t,e,a,i,n){const r=a+"/api/aquarius/assets/ddo/validate",s=a+"/api/services/nonce";try{const a=await e.getAddress(),o=await I(s+`?userAddress=${a}`,{method:"GET",headers:{"Content-Type":"application/json",Authorization:n},signal:i});let{nonce:c}=await o.json();console.log(`[getNonce] Consumer: ${a} nonce: ${c}`),c&&null!==c||(c="0");const l=(Number(c)+1).toString(),d=a+l,u={ddo:t,publisherAddress:a,nonce:l,signature:await $t(e,d)},h=await I(r,{method:"POST",body:JSON.stringify(u),headers:{"Content-Type":"application/octet-stream",Authorization:n},signal:i}),g=await h.json();if(200!==h.status)throw new Error("Metadata validation failed");return console.log("Ddo successfully validated"),{valid:!0,hash:g.hash,proof:{validatorAddress:g.publicKey,r:g.r[0],s:g.s[0],v:g.v}}}catch(t){V.error("Metadata validation failed",t.message)}}async getAssetMetadata(t,e,a){const i=this.aquariusURL+"/api/aquarius/assets/metadata/"+t;try{const t=await I(i,{method:"GET",headers:{"Content-Type":"application/json",Authorization:a},signal:e});if(t.ok)return t.json();throw new Error("getAssetMetadata failed: "+t.status+t.statusText)}catch(t){throw V.error("Error getting metadata: ",t),new Error("Error getting metadata: "+t)}}async querySearch(t,e,a){const i=this.aquariusURL+"/api/aquarius/assets/query";try{const n=await I(i,{method:"POST",body:JSON.stringify(t),headers:{"Content-Type":"application/json",Authorization:a},signal:e});if(n.ok)return n.json();throw new Error("querySearch failed: "+n.status+n.statusText)}catch(t){throw V.error("Error querying metadata: ",t),new Error("Error querying metadata: "+t)}}}class zt{async getConsumerAddress(t){return"string"==typeof t?function(t){try{return j.decode(t,{json:!0})}catch(t){throw new Error("Error decoding JWT")}}(t).address:await t.getAddress()}async getSignature(t,e){return"string"==typeof t?null:await this.signProviderRequest(t,e)}getAuthorization(t){return"string"==typeof t?t:void 0}async getEndpoints(t,e){try{const a=await this.getData(t,e);return await a.json()}catch(t){throw V.error("Finding the service endpoints failed:",t),new Error("HTTP request failed calling Provider")}}getEndpointURL(t,e){return t?t.find(t=>t.serviceName.toLowerCase()===e.toLowerCase()):null}async getServiceEndpoints(t,e){const a=[];for(const i in e.serviceEndpoints){const n={serviceName:i,method:e.serviceEndpoints[i][0],urlPath:t.replace(/\/+$/,"")+"/"+e.serviceEndpoints[i][1].replace(/^\/+/,"")};a.push(n)}return a}async getNonce(t,e,a,i,n){i||(i=await this.getEndpoints(t)),n||(n=await this.getServiceEndpoints(t,i));const r=this.getEndpointURL(n,"nonce")?this.getEndpointURL(n,"nonce").urlPath:null;if(!r)return null;try{const t=await I(r+`?userAddress=${e}`,{method:"GET",headers:{"Content-Type":"application/json"},signal:a}),{nonce:i}=await t.json();return console.log(`[getNonce] Consumer: ${e} nonce: ${i}`),i&&null!==i?Number(i):0}catch(t){throw V.error(t),new Error(t.message)}}async signProviderRequest(t,e){const i=a.solidityPackedKeccak256(["bytes"],[a.hexlify(a.toUtf8Bytes(e))]),n=a.toBeArray(i);try{return await t.signMessage(n)}catch(e){const a=await t.provider.getNetwork();if(8996===Number(a.chainId))return await t._legacySignMessage(n)}}async encrypt(t,e,a,i){const n=await this.getEndpoints(a),r=await this.getServiceEndpoints(a,n),s=(this.getEndpointURL(r,"encrypt")?this.getEndpointURL(r,"encrypt").urlPath:null)+`?chainId=${e}`;if(!s)return null;try{const e=await I(s,{method:"POST",body:JSON.stringify(t),headers:{"Content-Type":"application/octet-stream"},signal:i});return await e.text()}catch(t){throw V.error(t),new Error("HTTP request failed calling Provider")}}async checkDidFiles(t,e,a,i=!1,n){var r;const s=await this.getEndpoints(a),o=await this.getServiceEndpoints(a,s),c={did:t,serviceId:e,checksum:i},l=[],d=this.getEndpointURL(o,"fileinfo")?this.getEndpointURL(o,"fileinfo").urlPath:null;if(!d)return null;let u;try{u=await I(d,{method:"POST",body:JSON.stringify(c),headers:{"Content-Type":"application/json"},signal:n})}catch(t){throw V.error("File info call failed: "),V.error(t),new Error(t)}if(null!=(r=u)&&r.ok){const t=await u.json();for(const e of t)l.push(e);return l}const h=await u.json();throw V.error("File info call failed: ",u.status,u.statusText,h),new Error(JSON.stringify(h))}async getFileInfo(t,e,a=!1,i){var n;const r=await this.getEndpoints(e),s=await this.getServiceEndpoints(e,r),o=J({},t,{checksum:a}),c=[],l=this.getEndpointURL(s,"fileinfo")?this.getEndpointURL(s,"fileinfo").urlPath:null;if(!l)return null;let d;try{d=await I(l,{method:"POST",body:JSON.stringify(o),headers:{"Content-Type":"application/json"},signal:i})}catch(t){throw V.error("File info call failed: "),V.error(t),new Error(t)}if(null!=(n=d)&&n.ok){const t=await d.json();for(const e of t)c.push(e);return c}const u=await d.json();throw V.error("File info call failed: ",d.status,d.statusText,u),new Error(JSON.stringify(u))}async getComputeEnvironments(t,e){var a,i;const n=await this.getEndpoints(t),r=await this.getServiceEndpoints(t,n),s=null==(a=this.getEndpointURL(r,"computeEnvironments"))?void 0:a.urlPath;if(!s)return null;let o;try{o=await I(s,{method:"GET",headers:{"Content-Type":"application/json"},signal:e})}catch(t){throw V.error("Fetch compute env failed: "),V.error(t),new Error(t)}if(null!=(i=o)&&i.ok)return o.json();const c=await o.json();throw V.error("Fetch compute env failed: ",o.status,o.statusText,c),new Error(JSON.stringify(c))}async initialize(t,e,a,i,n,r,s,o,c){var l;const d=await this.getEndpoints(n),u=await this.getServiceEndpoints(n,d);let h,g=this.getEndpointURL(u,"initialize")?this.getEndpointURL(u,"initialize").urlPath:null;if(!g)return null;g+=`?documentId=${t}`,g+=`&serviceId=${e}`,g+=`&fileIndex=${a}`,g+=`&consumerAddress=${i}`,s&&(g+="&userdata="+encodeURI(JSON.stringify(s))),o&&(g+="&environment="+encodeURI(o)),c&&(g+="&validUntil="+c);try{h=await I(g,{method:"GET",headers:{"Content-Type":"application/json"},signal:r})}catch(t){throw V.error("Provider initialized failed: "),V.error(t),new Error(`Provider initialize failed url: ${g} `)}if(200===(null==(l=h)?void 0:l.status))return await h.json();const w=await h.json();throw V.error("Provider initialized failed: ",h.status,h.statusText,w),new Error(JSON.stringify(w))}async initializeComputeV1(t,e,a,i,n,r,s,o,c){var l;const d=await this.getEndpoints(i),u=await this.getServiceEndpoints(i,d),h={datasets:t,algorithm:e,payment:{chainId:r,token:s,maxJobDuration:o},consumerAddress:n,environment:a},g=this.getEndpointURL(u,"initializeCompute")?this.getEndpointURL(u,"initializeCompute").urlPath:null;if(!g)return null;let w;try{w=await I(g,{method:"POST",body:JSON.stringify(h),headers:{"Content-Type":"application/json"},signal:c})}catch(t){throw V.error("Initialize compute failed: "),V.error(t),new Error("ComputeJob cannot be initialized")}if(null!=(l=w)&&l.ok)return await w.json();const p=await w.json();throw V.error("Initialize compute failed: ",w.status,w.statusText,p),V.error("Payload was:",JSON.stringify(h)),new Error(JSON.stringify(p))}async initializeCompute(t,e,a,i,n,r,s,o,c,l,d){var u,h;const g=await this.getEndpoints(r),w=await this.getServiceEndpoints(r,g),p=this.getEndpointURL(w,"initializeCompute")?this.getEndpointURL(w,"initializeCompute").urlPath:null;if(!p)return null;const m=await this.getConsumerAddress(s),f=(await this.getNonce(r,m,d,g,w)+1).toString();let y=m;y+=null==(u=t[0])?void 0:u.documentId,y+=f;const v={datasets:t,algorithm:e,environment:a,payment:{chainId:c,token:i,resources:o},maxJobDuration:n,consumerAddress:m,signature:await this.getSignature(s,y)};let k;l&&(v.policyServer=l);try{if(console.log("Initialize compute url:",p),k=await I(p,{method:"POST",body:JSON.stringify(v),headers:{"Content-Type":"application/json",Authorization:this.getAuthorization(s)},signal:d}),console.log("Raw response:",k),!k.ok){const t=await k.text();throw new Error(`${t}`)}}catch(t){throw V.error("Initialize compute failed: "),V.error(t),new Error(`ComputeJob cannot be initialized: ${t.message}.`)}if(null!=(h=k)&&h.ok)return await k.json();const b=await k.json();throw V.error("Initialize compute failed: ",k.status,k.statusText,b),V.error("Payload was:",JSON.stringify(v)),new Error(JSON.stringify(b))}async getDownloadUrl(t,e,a,i,n,r,s,o){const c=await this.getEndpoints(n),l=await this.getServiceEndpoints(n,c),d=this.getEndpointURL(l,"download")?this.getEndpointURL(l,"download").urlPath:null;if(!d)return null;const u=await this.getConsumerAddress(r),h=(await this.getNonce(n,u,null,c,l)+1).toString(),g=await this.getSignature(r,t+h);let w=d;return w+=`?fileIndex=${a}`,w+=`&documentId=${t}`,w+=`&transferTxId=${i}`,w+=`&serviceId=${e}`,w+=`&consumerAddress=${u}`,w+=`&nonce=${h}`,s&&(w+="&policyServer="+encodeURI(JSON.stringify(s))),w+=`&signature=${g}`,o&&(w+="&userdata="+encodeURI(JSON.stringify(o))),w}async computeStartV1(t,e,a,i,n,r,s,o){var c;const l=await this.getEndpoints(t),d=await this.getServiceEndpoints(t,l),u=this.getEndpointURL(d,"computeStart")?this.getEndpointURL(d,"computeStart").urlPath:null,h=await e.getAddress(),g=(await this.getNonce(t,h,r,l,d)+1).toString();let w=h;w+=i.documentId,w+=g;const p=await this.signProviderRequest(e,w),m=Object();if(m.consumerAddress=h,m.signature=p,m.nonce=g,m.environment=a,m.dataset=i,m.algorithm=n,s&&(m.additionalDatasets=s),o&&(m.output=o),!u)return null;let f;try{f=await I(u,{method:"POST",body:JSON.stringify(m),headers:{"Content-Type":"application/json"},signal:r})}catch(t){throw V.error("Compute start failed:"),V.error(t),V.error("Payload was:",m),new Error("HTTP request failed calling Provider")}return null!=(c=f)&&c.ok?await f.json():(V.error("Compute start failed: ",f.status,f.statusText,await f.json()),V.error("Payload was:",m),null)}async computeStart(t,e,a,i,n,r,s,o,c,l,d,u,h,g,w){var p,m;console.log("called new compute start method..."),console.log("datasets: ",i),console.log("algorithm: ",n);const f=await this.getEndpoints(t),y=await this.getServiceEndpoints(t,f),v=this.getEndpointURL(y,"computeStart")?this.getEndpointURL(y,"computeStart").urlPath:null;if(!v)return V.error("Compute start failed: Cannot get proper computeStart route (perhaps not implemented on provider?)"),null;const k=await this.getConsumerAddress(e),b=(await this.getNonce(t,k,g,f,y)+1).toString(),T=String(k+(null==(p=i[0])?void 0:p.documentId)+b),S=await this.getSignature(e,T),A=Object();let F;A.consumerAddress=k,A.signature=S,A.nonce=b,A.environment=a,A.maxJobDuration=r,A.resources=o,A.dataset=i[0],A.datasets=i,A.algorithm=n,A.chainId=c,A.payment={chainId:c,token:s,maxJobDuration:r},o&&(A.resources=o),l&&(A.metadata=l),d&&(A.additionalViewers=d),u&&(A.output=u),h&&(A.policyServer=h),w&&(A.queueMaxWaitTime=w);try{F=await I(v,{method:"POST",body:JSON.stringify(A),headers:{"Content-Type":"application/json",Authorization:this.getAuthorization(e)},signal:g})}catch(t){throw V.error("Compute start failed:"),V.error(t),V.error("Payload was:",A),new Error("HTTP request failed calling Provider")}if(null!=(m=F)&&m.ok)return await F.json();const E=await F.json();throw V.error("Compute start failed: ",F.status,F.statusText,E),V.error("Payload was:",A),new Error(JSON.stringify(E))}async freeComputeStart(t,e,a,i,n,r,s,o,c,l,d,u){var h;console.log("called new free compute start method..."),console.log("datasets: ",i),console.log("algorithm: ",n);const g=await this.getEndpoints(t),w=await this.getServiceEndpoints(t,g),p=this.getEndpointURL(w,"freeCompute")?this.getEndpointURL(w,"freeCompute").urlPath:null;if(!p)return V.error("Compute start failed: Cannot get proper computeStart route (perhaps not implemented on provider?)"),null;const m=await this.getConsumerAddress(e),f=(await this.getNonce(t,m,d,g,w)+1).toString(),y=f;console.log("signatureMessage: ",y);const v=await this.getSignature(e,y),k=Object();let b;k.consumerAddress=m,k.signature=v,k.nonce=f,k.environment=a,k.resources=r,k.dataset=i[0],k.datasets=i,k.algorithm=n,s&&(k.metadata=s),o&&(k.additionalViewers=o),k.output=c,l&&(k.policyServer=l),u&&(k.queueMaxWaitTime=u);try{b=await I(p,{method:"POST",body:JSON.stringify(k),headers:{"Content-Type":"application/json",Authorization:this.getAuthorization(e)},signal:d})}catch(t){throw V.error("Compute start failed:"),V.error(t),V.error("Payload was:",k),new Error("HTTP request failed calling Provider")}if(null!=(h=b)&&h.ok)return await b.json();const T=await b.json();throw V.error("Compute start failed: ",b.status,b.statusText,T),V.error("Payload was:",k),new Error(JSON.stringify(T))}async computeStreamableLogs(t,e,a,i){var n,r;const s="string"==typeof e,o=await this.getEndpoints(t),c=await this.getServiceEndpoints(t,o),l=this.getEndpointURL(c,"computeStreamableLogs")?this.getEndpointURL(c,"computeStreamableLogs").urlPath:null;if(!l)return V.error("Compute start failed: Cannot get proper computeStreamableLogs route (perhaps not implemented on provider?)"),null;const d=await this.getConsumerAddress(e),u=(await this.getNonce(t,d,i,o,c)+1).toString();let h,g=`?consumerAddress=${d}&jobId=${a}`;if(!s){const t=`${d}${a}${u}`;g+=`&signature=${await this.getSignature(e,t)}`,g+=`&nonce=${u}`}try{h=await I(l+g,{method:"GET",headers:{"Content-Type":"application/json",Authorization:this.getAuthorization(e)},signal:i}),console.log("Raw response:",h)}catch(t){throw V.error("computeStreamableLogs failed:"),V.error(t),new Error("HTTP request failed calling Provider")}return null!=(n=h)&&n.ok||200===(null==(r=h)?void 0:r.status)?(console.log("Response body:",h.body),h.body):(V.error("computeStreamableLogs failed: ",h.status,h.statusText,await h.json()),null)}async getComputeStartRoutes(t,e=!1){const a=await this.getEndpoints(t),i=await this.getServiceEndpoints(t,a);let n=null;return n=e?this.getEndpointURL(i,"freeCompute")?this.getEndpointURL(i,"freeCompute").urlPath:null:this.getEndpointURL(i,"computeStart")?this.getEndpointURL(i,"computeStart").urlPath:null,n}async computeStop(t,e,a,i,n){var r;const s="string"==typeof a,o=await this.getEndpoints(e),c=await this.getServiceEndpoints(e,o),l=this.getEndpointURL(c,"computeStop")?this.getEndpointURL(c,"computeStop").urlPath:null,d=await this.getConsumerAddress(a),u=(await this.getNonce(e,d,n,o,c)+1).toString(),h=d+(t||""),g=await this.getSignature(a,h),w=new URLSearchParams;w.set("consumerAddress",d),w.set("nonce",u),w.set("jobId",t),s||w.set("signature",g),i&&w.set("agreementId",i);const p=w.toString();if(!p)return null;let m;try{m=await I(l+"?"+p,{method:"PUT",headers:{"Content-Type":"application/json",Authorization:this.getAuthorization(a)},signal:n})}catch(t){throw V.error("Compute stop failed:"),V.error(t),new Error("HTTP request failed calling Provider")}if(null!=(r=m)&&r.ok)return await m.json();const f=await m.json();throw V.error("Compute stop failed: ",m.status,m.statusText,f),new Error(JSON.stringify(f))}async computeStatus(t,e,a,i,n,r){var s,o;const c=await this.getEndpoints(t),l=await this.getServiceEndpoints(t,c),d=this.getEndpointURL(l,"computeStatus")?this.getEndpointURL(l,"computeStatus").urlPath:null;let u,h=`?consumerAddress=${e}`;if(h+=i&&`&agreementId=${i}`||"",h+=a&&`&jobId=${a}`||"",!d)return null;try{console.log("computeStatusUrl: ",d+h),u=await I(d+h,{method:"GET",headers:{"Content-Type":"application/json",Authorization:r},signal:n})}catch(t){throw V.error("Get compute status failed"),V.error(t),new Error(t)}if(null!=(s=u)&&s.ok)return await u.json();if(V.error("Get compute status failed:",u.status,u.statusText),null!=(o=u)&&o.ok)return await u.json();const g=await u.json();throw V.error("Get compute status failed:",u.status,u.statusText,g),new Error(JSON.stringify(g))}async getComputeResultUrl(t,e,a,i){const n="string"==typeof e,r=await this.getEndpoints(t),s=await this.getServiceEndpoints(t,r),o=this.getEndpointURL(s,"computeResult")?this.getEndpointURL(s,"computeResult").urlPath:null,c=await this.getConsumerAddress(e),l=(await this.getNonce(t,c,null,r,s)+1).toString();let d=c;d+=a,d+=i.toString(),d+=l;const u=await this.getSignature(e,d);if(!o)return null;let h=o;return h+=`?consumerAddress=${c}`,h+=`&jobId=${a}`,h+=`&index=${i.toString()}`,n||(h+=`&nonce=${l}`,h+=`&signature=${u}`),h}async computeDelete(t,e,a,i,n){var r;const s=await this.getEndpoints(i),o=await this.getServiceEndpoints(i,s),c=this.getEndpointURL(o,"computeDelete")?this.getEndpointURL(o,"computeDelete").urlPath:null,l=await this.getConsumerAddress(e),d=(await this.getNonce(i,l,n,s,o)+1).toString();let u=l;u+=a||"",u+=t&&`${this.noZeroX(t)}`||"",u+=d;const h=await this.getSignature(e,u),g=Object();if(g.documentId=t,g.consumerAddress=l,g.jobId=a,h&&(g.signature=h),!c)return null;let w;try{w=await I(c,{method:"DELETE",body:JSON.stringify(g),headers:{"Content-Type":"application/json",Authorization:this.getAuthorization(e)},signal:n})}catch(t){throw V.error("Delete compute job failed:"),V.error(t),V.error("Payload was:",g),new Error("HTTP request failed calling Provider")}if(null!=(r=w)&&r.ok)return await w.json();const p=await w.json();throw V.error("Delete compute job failed:",w.status,w.statusText,p),V.error("Payload was:",g),new Error(JSON.stringify(p))}async generateAuthToken(t,e,a){const i=await t.getAddress(),n=await this.getEndpoints(e),r=await this.getServiceEndpoints(e,n),s=this.getEndpointURL(r,"generateAuthToken").urlPath||null,o=(await this.getNonce(e,i,a,n,r)+1).toString(),c=i+o,l=await this.signProviderRequest(t,c);try{const t=await I(s,{method:"POST",body:JSON.stringify({address:i,signature:l,nonce:o}),headers:{"Content-Type":"application/json"},signal:a});if(null==t||!t.ok)throw new Error(`Failed to generate auth token: ${t.status} ${t.statusText}`);const e=await t.json();return null==e?void 0:e.token}catch(t){throw V.error("Generate auth token failed:"),V.error(t),new Error("HTTP request failed calling Provider")}}async invalidateAuthToken(t,e,a,i){const n=await t.getAddress(),r=await this.getEndpoints(a),s=await this.getServiceEndpoints(a,r),o=this.getEndpointURL(s,"invalidateAuthToken").urlPath||null,c=(await this.getNonce(a,n,i,r,s)+1).toString(),l=n+c,d=await this.signProviderRequest(t,l);try{const t=await I(o,{method:"POST",body:JSON.stringify({address:n,signature:d,token:e,nonce:c}),headers:{"Content-Type":"application/json"},signal:i});if(null==t||!t.ok)throw new Error(`Failed to invalidate auth token: ${t.status} ${t.statusText}`);return await t.json()}catch(t){throw V.error("Generate auth token failed:"),V.error(t),new Error("HTTP request failed calling Provider")}}async isValidProvider(t,e){try{const a=await I(t,{method:"GET",headers:{"Content-Type":"application/json"},signal:e});if(null!=a&&a.ok){const t=await a.json();if(t&&(t.providerAddress||t.providerAddresses))return!0}return!1}catch(t){return V.error(`Error validating provider: ${t.message}`),!1}}async PolicyServerPassthrough(t,e,a){var i;const n=await this.getEndpoints(t),r=await this.getServiceEndpoints(t,n),s=this.getEndpointURL(r,"PolicyServerPassthrough")?this.getEndpointURL(r,"PolicyServerPassthrough").urlPath:null;if(!s)return null;let o;try{if(o=await I(s,{method:"POST",body:JSON.stringify(e),headers:{"Content-Type":"application/json"},signal:a}),!o.ok){const t=await o.text();throw new Error(`${t}`)}}catch(t){throw V.error("PolicyServerPassthrough failed: "),V.error(t),new Error(`PolicyServerPassthrough failed: ${t.message}.`)}if(null!=(i=o)&&i.ok)return await o.json();const c=await o.json();throw V.error("PolicyServerPassthrough failed: ",o.status,o.statusText,c),V.error("Payload was:",JSON.stringify(e)),new Error(JSON.stringify(c))}async initializePSVerification(t,e,a){var i;const n=await this.getEndpoints(t),r=await this.getServiceEndpoints(t,n),s=this.getEndpointURL(r,"initializePSVerification")?this.getEndpointURL(r,"initializePSVerification").urlPath:null;if(!s)return null;let o;try{if(o=await I(s,{method:"POST",body:JSON.stringify(e),headers:{"Content-Type":"application/json"},signal:a}),!o.ok){const t=await o.text();throw new Error(`${t}`)}}catch(t){throw V.error("initializePSVerification failed: "),V.error(t),new Error(`initializePSVerification failed: ${t.message}.`)}if(null!=(i=o)&&i.ok)return await o.json();const c=await o.json();throw V.error("initializePSVerification failed: ",o.status,o.statusText,c),V.error("Payload was:",JSON.stringify(e)),new Error(JSON.stringify(c))}noZeroX(t){return this.zeroXTransformer(t,!1)}zeroXTransformer(t="",e){const{valid:a,output:i}=this.inputMatch(t,/^(?:0x)*([a-f0-9]+)$/i,"zeroXTransformer");return(e&&a?"0x":"")+i}inputMatch(t,e,a){if("string"!=typeof t)throw V.debug("Not input string:"),V.debug(t),new Error(`[${a}] Expected string, input type: ${typeof t}`);const i=t.match(e);return i?{valid:!0,output:i[1]}:(V.warn(`[${a}] Input transformation failed.`),{valid:!1,output:t})}async getData(t,e){return I(t,{method:"GET",headers:{"Content-type":"application/json",Authorization:e}})}}const qt=new zt;function Jt(t,e){return t=d(t),`did:op:${G(t+e.toString(10)).toString()}`}function Wt(t){return G(t).toString()}function Vt(t){const e=new XMLHttpRequest;e.responseType="blob",e.open("GET",t),e.onload=()=>{const t=e.getResponseHeader("content-disposition"),a=null==t?void 0:t.match(/filename[^;=\n]*=((['"]).*?\2|[^;\n]*)/),i=a&&a[1]?a[1]:"file",n=window.URL.createObjectURL(e.response),r=document.createElement("a");r.href=n,r.setAttribute("download",i),document.body.appendChild(r),r.click(),r.remove(),window.URL.revokeObjectURL(n)},e.send()}async function Ht(t,e){const a=await fetch(t);if(!a.ok)throw new Error("Response error.");let i;try{i=a.headers.get("content-disposition").match(/attachment;filename=(.+)/)[1]}catch(a){try{i=t.split("/").pop()}catch(t){i=`file${e}`}}return{data:await a.arrayBuffer(),filename:i}}async function Zt(t,e,i,n,r,s,o=!1,c,l){const d=new a.Contract(n,Q,t);if(!o){const e=await Qt(t,n,i,r);if(new m(e).greaterThanOrEqualTo(new m(s)))return new m(e).toNumber()}const u=await ot(t,n,s,c),h=await d.approve.estimateGas(r,u);return l?new m(h.toString()):await lt(h,t,null==e?void 0:e.gasFeeMultiplier,d.approve,r,u)}async function Xt(t,e,i,n,r,s,o=!1,c){const l=new a.Contract(n,Q,t);if(!o){const e=await te(t,n,i,r);if(new p(e).isGreaterThan(new p(s)))return BigInt(e)}let d=null;const u=await l.approve.estimateGas(r,s);if(c)return u;try{d=await lt(u,t,null==e?void 0:e.gasFeeMultiplier,l.approve,r,s)}catch(t){V.error(`ERROR: Failed to approve spender to spend tokens : ${t.message}`)}return d}async function Kt(t,e,i,n,r,s){const o=new a.Contract(i,Q,t),c=await ot(t,i,r),l=await o.transfer.estimateGas(n,c);return s?l:await lt(l,t,null==e?void 0:e.gasFeeMultiplier,o.transfer,n,c)}async function Qt(t,e,i,n,r){const s=new a.Contract(e,Q,t),o=await s.allowance(i,n);return await st(t,e,o,r)}async function Yt(t,e,i,n){const r=new a.Contract(e,Q,t),s=await r.balanceOf(i);return await st(t,e,s,n)}async function te(t,e,i,n){const r=new a.Contract(e,Q,t);return await r.allowance(i,n)}async function ee(t,e){const i=new a.Contract(e,Q,t),n=await i.decimals();return Number(n)}const ae={datasets:{invalid:"Datasets is not a list, as expected"},algorithm:{serviceId:{missing:"The serviceId key is missing from the algorithm s DDO.",not_found:"The provided serviceId does not exist.",service_not_access_compute:"Service type is neither access, nor compute.",main_service_compute:"If the main service is not compute for this asset when calling initialize endpoint.",compute_services_not_in_same_provider:"Files attached to the compute service are not decrypted by the correct provider. This occurs when both asset and algorithm are requested by their compute service which cannot be decrypted by a single provider as how it is supposed to be."},container:{checksum_prefix:"Container checksum does not start with the prefix sha256:.",mising_entrypoint_image_checksum:"Either entrypoint, either image, or either checksum are missing from the container dictionary from the algorithm s DDO."},documentId:{did_not_found:"The algorithm s DID could not be retrieved from the metadata store, because the algorithm asset does not exist.",missing:"The documentId key is missing from the algorithm s DDO."},transferTxId:{missing:"The transferTxId key is missing from the algorithm s DDO."},missing_meta_documentId:"Either algorithm metadata, or algorithm DID are missing.",did_not_found:"Either algorithm metadata, or algorithm DID are missing.",not_algo:"Either algorithm metadata, or algorithm DID are missing.",in_use_or_not_on_chain:"Either algorithm metadata, or algorithm DID are missing.",meta_oneof_url_rawcode_remote:"Either algorithm metadata, or algorithm DID are missing.",file_unavailable:"One possibility is that the asset could not be retrieved from Aquariuss database. Otherwise, there are issues related to services"},error:{not_trusted_algo_publisher:"The owner of the algorithm's DDO is not a trusted algorithms publishers list.",not_trusted_algo:"The algorithm's DID is not in the asset's trusted algorithms dictionary. ",no_publisherTrustedAlgorithms:"The algorithm's key publisherTrustedAlgorithms does not exist in the algorithm's DDO.",algorithm_file_checksum_mismatch:"filesChecksum from the algorithm's DDO is invalid.",algorithm_container_checksum_mismatch:"The containerChecksum from the algorithm's DDO is invalid.",no_raw_algo_allowed:"The asset does not allow raw algorithms to be run on it.","Asset malformed":"The asset published on chain is malformed, missing some required keys or not compliant with our schemas.","Asset is not consumable.":"Assets metadata status is not in the range of valid status codes for assets. The recognized states for the metadata are defined on our docs.","DID is not a valid algorithm.":"Either the algorithm assets DID is incorrectly typed, either the algorithm timeout expired.","Compute environment does not exist.":"The compute environment provided by the user does not exist, it is not served by our compute-to-data feature. The user can use get_c2d_environments to check the list of available compute environments.","The validUntil value is not correct.":"validUntil value is most probably expired.","Cannot resolve DID":"The dataset DID does not exist in the Metadata store.","Invalid serviceId":"The serviceId of that dataset is not correct.","Unable to get dataset files":"The files of that dataset could not be decrypted or retrieved","cannot decrypt files for this service.":"The files of that dataset could not be decrypted due to the fact that file object, which contains the structure and the type of specific file, is missing from the validation part.","Unsupported type ":"The file object type is not supported by Provider.","malformed file object":"The file object structure is invalid and does not contain the wanted information for the specific file."},order:{fees_not_paid:" Provider fees are not paid."},output:{invalid:"The algorithms validation after the build stage has not been decoded properly as a dictionary."}};function ie(t){try{const a=JSON.parse(t),i=Object.keys(a)[0];if("error"===i){var e;const t=a[i];return(null==(e=ae[i])?void 0:e[t])||`Provider request failed: ${t}`}{const t=a[i];return`${a[Object.keys(a)[1]]} : ${t}`}}catch(e){return V.error("[getErrorMessage] error: ",e),t}}async function ne(t,e,a,i,n,r,s,o,c="0",l=0,d=0,u=0){const h=L.getDDOClass(t),{datatokens:g}=h.getAssetFields(),{chainId:w,services:p}=h.getDDOFields();s||(s={consumeMarketFeeAddress:"0x0000000000000000000000000000000000000000",consumeMarketFeeAmount:"0",consumeMarketFeeToken:"0x0000000000000000000000000000000000000000"});const f=(await e.provider.getNetwork()).chainId;if(w!==Number(f))throw new Error("Chain ID from DDO is different than the configured network.");if(!g[l].address)throw new Error(`The datatoken with index: ${l} does not exist for the asset with did: ${t.id}`);if(!p[d].id)throw new Error(`There is no service with index: ${d} defined for the asset with did: ${t.id}`);const y=await i.getId(g[l].address),v=await i.getFixedRates(g[l].address),k=await i.getDispensers(g[l].address),b=await i.getPublishingMarketFee(g[l].address),T=v.length>0?"fixed":k.length>0?"free":"NOT_ALLOWED",S=o||(await qt.initialize(t.id,p[d].id,0,await e.getAddress(),n||a.oceanNodeUri)).providerFee;if(S&&S.providerFeeAddress!==gt&&S.providerFeeAmount&&parseInt(S.providerFeeAmount)>0)try{await Xt(e,a,await e.getAddress(),S.providerFeeToken,p[0].datatokenAddress,S.providerFeeAmount)}catch(t){throw new Error(`Failed to approve provider fee token ${S.providerFeeToken}`)}const A={consumer:r||await e.getAddress(),serviceIndex:d,_providerFee:S,_consumeMarketFee:s};switch(T){case"free":if(1===y){const t=new ht(a.dispenserAddress,e),n=await t.dispense(g[l].address,"1",await e.getAddress());if(!n)throw new Error("Failed to dispense !");return await n.wait(),await i.startOrder(g[l].address,A.consumer,A.serviceIndex,A._providerFee,A._consumeMarketFee)}if(2===y||4===y)return await i.buyFromDispenserAndOrder(p[d].datatokenAddress,A,a.dispenserAddress);break;case"fixed":{const n=new ft(a.fixedRateExchangeAddress,e);if(!v[u].id)throw new Error(`There is no fixed rate exchange with index: ${d} for the asset with did: ${t.id}`);const r=await n.getFeesInfo(v[u].id),o=await n.getExchange(v[u].id),{baseTokenAmount:h}=await n.calcBaseInGivenDatatokensOut(r.exchangeId,"1",s.consumeMarketFeeAmount),w=new m(+h||0).add(new m(s.consumeMarketFeeAmount||0)).add(new m(+b.publishMarketFeeAmount||0)).toString(),p={exchangeContract:a.fixedRateExchangeAddress,exchangeId:r.exchangeId,maxBaseTokenAmount:w,baseTokenAddress:o.baseToken,baseTokenDecimals:parseInt(o.btDecimals)||18,swapMarketFee:c,marketFeeAddress:b.publishMarketFeeAddress};if(1===y){const t=await Zt(e,a,await e.getAddress(),o.baseToken,a.fixedRateExchangeAddress,w,!1);if(!("number"!=typeof t?await t.wait():t))throw new Error(`Failed to approve ${o.baseToken} !`);const r=await n.buyDatatokens(o.exchangeId,"1",w,b.publishMarketFeeAddress,c);if(!await r.wait())throw new Error("Failed to buy datatoken from fixed rate!");return await i.startOrder(g[l].address,A.consumer,A.serviceIndex,A._providerFee,A._consumeMarketFee)}if(2===y||4===y){const t=await Zt(e,a,await e.getAddress(),o.baseToken,g[l].address,w,!1);if(!t)throw new Error(`Failed to approve ${o.baseToken} !`);if(!("number"!=typeof t?await t.wait():t))throw new Error("Failed to confirm/mine approval transaction!");return await i.buyFromFreAndOrder(g[l].address,A,p)}break}default:throw new Error("Pricing schema not supported !")}}const re=8996;function se(t){const e=(new K).getConfig(t);return e&&"oasis"===e.sdk}async function oe(t,e,i,n,r,o,l=!0,d,u,h,w,p,m){var f,y,v;const k=L.getDDOClass(o),{indexedMetadata:b}=k.getAssetFields(),T=(null==(f=k.getDDOData())||null==(f=f.stats)||null==(f=f.price)?void 0:f.value)||(null==b||null==(y=b.stats[0])||null==(y=y.prices[0])?void 0:y.price);let{chainId:S,nftAddress:A}=k.getDDOFields();const{services:E}=k.getDDOFields();if("string"!=typeof r&&"number"!=typeof r)throw new Error('Invalid template! Must be a "number" or a "string"');const C=(await i.provider.getNetwork()).chainId;if(S&&S!==Number(C))throw new Error("Chain ID from DDO is different than the configured network.");const D=(new K).getConfig(parseInt(String(C)));let x=await At(i,D.nftFactoryAddress,r,Number(C));if(x<1){if(8996!==Number(C))throw new Error(`Invalid template index: ${x}`);x=1}const M=new Ft(i,Number(C)),O=new bt(D.nftFactoryAddress,i,Number(C)),N=await i.getAddress(),P={name:t,symbol:e,templateIndex:1,tokenURI:"aaa",transferable:!0,owner:N},R={templateIndex:x,cap:"100000",feeAmount:"0",paymentCollector:N,feeToken:u||D.oceanTokenAddress,minter:N,mpFeeAddress:gt};let U;null!=n&&n.files[0].type&&[$.ARWEAVE,$.IPFS,$.URL].includes(null==n||null==(v=n.files[0])||null==(v=v.type)?void 0:v.toLowerCase())||(console.log('Missing or invalid files object type, defaulting to "url"'),n.type=$.URL),"oasis"===D.sdk&&(R.filesObject=n,R.accessListFactory=w||D.accessListFactory,R.allowAccessList=p,R.denyAccessList=m);try{if(T)if("0"===T.toString()){const t={dispenserAddress:D.dispenserAddress,maxTokens:"1",maxBalance:"100000000",withMint:!0,allowedSwapper:gt};U=await O.createNftWithDatatokenWithDispenser(P,R,t)}else{const t={fixedRateAddress:D.fixedRateExchangeAddress,baseTokenAddress:D.oceanTokenAddress,owner:N,marketFeeCollector:N,baseTokenDecimals:18,datatokenDecimals:18,fixedRate:T.toString(),marketFee:"0",allowedConsumer:N,withMint:!0};U=await O.createNftWithDatatokenWithFixedRate(P,R,t)}else U=await O.createNftWithDatatoken(P,R)}catch(t){return console.log("ERROR creating NFT bundle",t),null}const I=await U.wait(),j=ct(I,"NFTCreated"),G=ct(I,"TokenCreated"),B=j.args.newTokenAddress,z=G.args.newTokenAddress;if(n.datatokenAddress=z,n.nftAddress=B,"oasis"===D.sdk){const t=new a.Contract(z,F.abi,i);try{const e=await t.setFilesObject(s(JSON.stringify(n)));e.wait&&await e.wait()}catch(t){return console.log("Error updating files object with data token and nft addresses: ",t),null}}E[0].files="oasis"===D.sdk?"":await qt.encrypt(n,Number(C),d),E[0].datatokenAddress=z,E[0].serviceEndpoint=d,A=B;const q=k.makeDid(A,S.toString());let J,W,V;if(o=k.updateFields({id:q,nftAddress:A}),l)J=await qt.encrypt(o,Number(C),d),W=(await h.validate(o,i,d)).hash,V=2;else{const t=JSON.stringify(o),e=Buffer.from(t);J=c(e),W="0x"+_("sha256").update(J).digest("hex"),V=0}return await M.setMetadata(A,await i.getAddress(),0,d,"",g(V),J,W),o.id}async function ce(t,e,i){const n=new a.Contract(t,C.abi,e),r=await e.getAddress();try{const t=await n.deployAccessListContract("AllowList","ALLOW",!0,r,i||[r],["https://oceanprotocol.com/nft/"]);if(t&&t.wait)return ct(await t.wait(),"NewAccessList").args[0]}catch(t){console.log("ERROR createAccessListFactory(): ",t)}return null}export{Dt as AccessListContract,xt as AccesslistFactory,Bt as Aquarius,q as Config,K as ConfigHelper,re as DEVELOPMENT_CHAIN_ID,Et as Datatoken,Ct as Datatoken4,Rt as DfRewards,Ut as DfStrategyV1,ht as Dispenser,B as EncryptMethod,Lt as EnterpriseFeeCollectorContract,It as EscrowContract,mt as FEE_HISTORY_NOT_SUPPORTED,$ as FileObjectType,ft as FixedRateExchange,wt as GASLIMIT_DEFAULT,X as KNOWN_CONFIDENTIAL_EVMS,z as LogLevel,W as Logger,V as LoggerInstance,pt as MAX_UINT_256,Ft as Nft,bt as NftFactory,zt as Provider,qt as ProviderInstance,yt as Router,dt as SmartContract,ut as SmartContractWithAddress,Pt as VeAllocate,Ot as VeFeeDistributor,Nt as VeFeeEstimate,Mt as VeOcean,gt as ZERO_ADDRESS,Qt as allowance,te as allowanceWei,ot as amountToUnits,Zt as approve,Xt as approveWei,Yt as balance,At as calculateActiveTemplateIndex,Z as configHelperNetworks,ce as createAccessListFactory,oe as createAsset,ee as decimals,Ht as downloadFile,Vt as downloadFileBrowser,Jt as generateDid,kt as generateDtName,ie as getErrorMessage,ct as getEventFromTx,nt as getFairGasPrice,Wt as getHash,Tt as getOceanArtifactsAddresses,St as getOceanArtifactsAddressesByChainId,rt as getTokenDecimals,Gt as isDefined,Q as minAbi,ne as orderAsset,lt as sendTx,it as setContractDefaults,_t as signHash,$t as signRequest,jt as sleep,Kt as transfer,st as unitsToAmount,se as useOasisSDK};
|
|
1
|
+
import t from"@oceanprotocol/contracts/addresses/address.json";import e from"fs";import{ethers as a,formatUnits as i,parseUnits as r,EventLog as n,toUtf8Bytes as s,keccak256 as o,hexlify as c,toUtf8String as l,getAddress as d,parseEther as u,getBytes as h,toBeHex as g}from"ethers";import*as w from"@oasisprotocol/sapphire-paratime";import p from"bignumber.js";import m from"decimal.js";import f from"@oceanprotocol/contracts/artifacts/contracts/pools/dispenser/Dispenser.sol/Dispenser.json";import y from"@oceanprotocol/contracts/artifacts/contracts/pools/fixedRate/FixedRateExchange.sol/FixedRateExchange.json";import v from"@oceanprotocol/contracts/artifacts/contracts/pools/FactoryRouter.sol/FactoryRouter.json";import k from"@oceanprotocol/contracts/artifacts/contracts/templates/ERC20Template.sol/ERC20Template.json";import T from"@oceanprotocol/contracts/artifacts/contracts/templates/ERC20TemplateEnterprise.sol/ERC20TemplateEnterprise.json";import b from"@oceanprotocol/contracts/artifacts/contracts/templates/ERC721Template.sol/ERC721Template.json";import S from"@oceanprotocol/contracts/artifacts/contracts/ERC721Factory.sol/ERC721Factory.json";import E from"@oceanprotocol/contracts/artifacts/contracts/interfaces/IERC20Template.sol/IERC20Template.json";import A from"@oceanprotocol/contracts/artifacts/contracts/templates/ERC20Template4.sol/ERC20Template4.json";import F from"@oceanprotocol/contracts/artifacts/contracts/accesslists/AccessList.sol/AccessList.json";import C from"@oceanprotocol/contracts/artifacts/contracts/accesslists/AccessListFactory.sol/AccessListFactory.json";import x from"@oceanprotocol/contracts/artifacts/contracts/escrow/Escrow.sol/Escrow.json";import D from"@oceanprotocol/contracts/artifacts/contracts/communityFee/EnterpriseFeeCollector.sol/EnterpriseFeeCollector.json";import M from"cross-fetch";import{DDOManager as O}from"@oceanprotocol/ddo-js";import N from"jsonwebtoken";import P from"crypto-js/sha256.js";import{createHash as R}from"crypto";var U,I,L;!function(t){t.URL="url",t.IPFS="ipfs",t.ARWEAVE="arweave"}(U||(U={})),function(t){t.AES="AES",t.ECIES="ECIES"}(I||(I={}));class j{constructor(){this.nodeUri=void 0,this.providerAddress=void 0,this.oceanNodeUri=void 0,this.web3Provider=void 0,this.oceanTokenAddress=void 0,this.nftFactoryAddress=void 0,this.routerFactoryAddress=void 0,this.datatokensABI=void 0,this.fixedRateExchangeAddress=void 0,this.fixedRateExchangeAddressABI=void 0,this.dispenserAddress=void 0,this.dispenserABI=void 0,this.opfCommunityFeeCollector=void 0,this.EnterpriseFeeCollector=void 0,this.sideStakingAddress=void 0,this.startBlock=void 0,this.verbose=void 0,this.authMessage=void 0,this.authTokenExpiration=void 0,this.parityUri=void 0,this.threshold=void 0,this.chainId=void 0,this.network=void 0,this.explorerUri=void 0,this.oceanTokenSymbol=void 0,this.transactionBlockTimeout=void 0,this.transactionConfirmationBlocks=void 0,this.transactionPollingTimeout=void 0,this.gasFeeMultiplier=void 0,this.sdk=void 0,this.accessListFactory=void 0,this.escrow=void 0}}function G(){return G=Object.assign?Object.assign.bind():function(t){for(var e=1;e<arguments.length;e++){var a=arguments[e];for(var i in a)({}).hasOwnProperty.call(a,i)&&(t[i]=a[i])}return t},G.apply(null,arguments)}!function(t){t[t.None=-1]="None",t[t.Error=0]="Error",t[t.Warn=1]="Warn",t[t.Log=2]="Log",t[t.Verbose=3]="Verbose"}(L||(L={}));class _{constructor(t){this.logLevel=void 0,this.logLevel=t,this.logLevel=t||L.Error}setLevel(t){this.logLevel=t}bypass(...t){this.dispatch("log",-Infinity,...t)}debug(...t){this.dispatch("debug",L.Verbose,...t)}log(...t){this.dispatch("log",L.Log,...t)}warn(...t){this.dispatch("warn",L.Warn,...t)}error(...t){this.dispatch("error",L.Error,...t)}dispatch(t,e,...a){this.logLevel>=e&&console[t](...a)}}const $=new _,z={chainId:null,network:"unknown",nodeUri:"http://127.0.0.1:8545",oceanNodeUri:"http://127.0.0.1:8001",explorerUri:null,oceanTokenAddress:null,oceanTokenSymbol:"OCEAN",fixedRateExchangeAddress:null,dispenserAddress:null,startBlock:0,transactionBlockTimeout:50,transactionConfirmationBlocks:1,transactionPollingTimeout:750,gasFeeMultiplier:1},B=[G({},z),G({},z,{chainId:8996,network:"development",oceanNodeUri:"http://127.0.0.1:8001",sdk:"evm"}),G({},z,{chainId:11155111,network:"sepolia",nodeUri:"https://sepolia.infura.io/v3",explorerUri:"https://sepolia.etherscan.io",gasFeeMultiplier:1.1,sdk:"evm"}),G({},z,{chainId:1,network:"mainnet",nodeUri:"https://mainnet.infura.io/v3",explorerUri:"https://etherscan.io",startBlock:11105459,transactionBlockTimeout:150,transactionConfirmationBlocks:5,transactionPollingTimeout:1750,gasFeeMultiplier:1.05,sdk:"evm"}),G({},z,{chainId:8453,network:"base",nodeUri:"https://mainnet.base.org",explorerUri:"https://etherscan.io",startBlock:30562198,transactionBlockTimeout:150,transactionConfirmationBlocks:5,transactionPollingTimeout:1750,gasFeeMultiplier:1.05,sdk:"evm"}),G({},z,{chainId:137,network:"polygon",nodeUri:"https://polygon-mainnet.infura.io/v3",explorerUri:"https://polygonscan.com",oceanTokenSymbol:"mOCEAN",gasFeeMultiplier:1.6,sdk:"evm"}),G({},z,{chainId:2021e3,network:"gaiaxtestnet",nodeUri:"https://rpc.gaiaxtestnet.oceanprotocol.com",explorerUri:"https://blockscout.gaiaxtestnet.oceanprotocol.com",sdk:"evm"}),G({},z,{chainId:80001,network:"mumbai",nodeUri:"https://polygon-mumbai.infura.io/v3",explorerUri:"https://mumbai.polygonscan.com",gasFeeMultiplier:1.1,sdk:"evm"}),G({},z,{chainId:56,network:"bsc",nodeUri:"https://bsc-dataseed.binance.org",explorerUri:"https://bscscan.com/",gasFeeMultiplier:1.05,sdk:"evm"}),G({},z,{chainId:246,network:"energyweb",nodeUri:"https://rpc.energyweb.org",explorerUri:"https://explorer.energyweb.org",gasFeeMultiplier:1.05,sdk:"evm"}),G({},z,{chainId:1285,network:"moonriver",nodeUri:"https://moonriver.api.onfinality.io/public",explorerUri:"https://moonriver.moonscan.io/",gasFeeMultiplier:1.05,sdk:"evm"}),G({},z,{chainId:100,network:"gen-x-testnet",nodeUri:"https://rpc.genx.minimal-gaia-x.eu",explorerUri:"https://explorer.genx.minimal-gaia-x.eu/",gasFeeMultiplier:1,sdk:"evm"}),G({},z,{chainId:10,network:"optimism",nodeUri:"https://mainnet.optimism.io",explorerUri:"https://optimistic.etherscan.io/",gasFeeMultiplier:1.1,sdk:"evm"}),G({},z,{chainId:11155420,network:"optimism_sepolia",nodeUri:"https://sepolia.optimism.io",explorerUri:"https://sepolia-optimism.etherscan.io/",gasFeeMultiplier:1.1,sdk:"evm"}),G({},z,{chainId:23294,network:"oasis_sapphire",nodeUri:"https://sapphire.oasis.io",explorerUri:"https://explorer.oasis.io/mainnet/sapphire/",gasFeeMultiplier:1,sdk:"oasis"}),G({},z,{chainId:23295,network:"oasis_sapphire_testnet",nodeUri:"https://testnet.sapphire.oasis.dev",explorerUri:"https://explorer.oasis.io/testnet/sapphire/",gasFeeMultiplier:1,sdk:"oasis"}),G({},z,{chainId:32456,network:"pontus-x-devnet",nodeUri:"https://rpc.dev.pontus-x.eu",explorerUri:"https://explorer.dev.pontus-x.eu/testnet/pontusx",sdk:"evm"})],q=[23294,23295];class J{getAddressesFromEnv(e,a){let i;const r=()=>process.env.NODE_URL?{oceanNodeUri:process.env.NODE_URL}:{};if(a&&a[e]){const{FixedPrice:t,Dispenser:n,ERC721Factory:s,OPFCommunityFeeCollector:o,Ocean:c,chainId:l,startBlock:d,Router:u,AccessListFactory:h,Escrow:g,EnterpriseFeeCollector:w}=a[e];i=G({nftFactoryAddress:s,opfCommunityFeeCollector:o,fixedRateExchangeAddress:t,dispenserAddress:n,oceanTokenAddress:c,routerFactoryAddress:u,chainId:l,startBlock:d,accessListFactory:h,escrow:g,EnterpriseFeeCollector:w},r())}else if(t[e]){const{FixedPrice:a,Dispenser:n,OPFCommunityFeeCollector:s,ERC721Factory:o,Ocean:c,chainId:l,startBlock:d,Router:u,AccessListFactory:h,Escrow:g,EnterpriseFeeCollector:w}=t[e];i=G({nftFactoryAddress:o,opfCommunityFeeCollector:s,fixedRateExchangeAddress:a,dispenserAddress:n,oceanTokenAddress:c,routerFactoryAddress:u,chainId:l,startBlock:d,accessListFactory:h,escrow:g,EnterpriseFeeCollector:w},r())}return i}getConfig(t,a){const i="string"==typeof t?"network":"chainId";let r,n=B.find(e=>e[i]===t);if(!n)return $.error(`No config found for given network '${t}'`),null;try{r=process.env.ADDRESS_FILE?JSON.parse(e.readFileSync(process.env.ADDRESS_FILE,"utf8")):null}catch(t){console.log(t),r=null}let s=this.getAddressesFromEnv(n.network,r);return!s&&q.includes(n.chainId)&&(s=this.getAddressesFromEnv(n.network.replace("sapph","saph"),r)),"sdk"in n&&null!==n.sdk||(n.sdk=q.includes(n.chainId)?"oasis":"evm"),s&&"accessListFactory"in s&&(n.accessListFactory=s.accessListFactory),n=G({},n,s),G({},n,{nodeUri:a?`${n.nodeUri}/${a}`:n.nodeUri})}}const W=[{constant:!0,inputs:[],name:"name",outputs:[{name:"",type:"string"}],payable:!1,stateMutability:"view",type:"function"},{constant:!1,inputs:[{name:"_spender",type:"address"},{name:"_value",type:"uint256"}],name:"approve",outputs:[{name:"",type:"bool"}],payable:!1,stateMutability:"nonpayable",type:"function"},{constant:!0,inputs:[],name:"totalSupply",outputs:[{name:"",type:"uint256"}],payable:!1,stateMutability:"view",type:"function"},{constant:!1,inputs:[{name:"_from",type:"address"},{name:"_to",type:"address"},{name:"_value",type:"uint256"}],name:"transferFrom",outputs:[{name:"",type:"bool"}],payable:!1,stateMutability:"nonpayable",type:"function"},{constant:!0,inputs:[],name:"decimals",outputs:[{name:"",type:"uint8"}],payable:!1,stateMutability:"view",type:"function"},{constant:!0,inputs:[{name:"_owner",type:"address"}],name:"balanceOf",outputs:[{name:"balance",type:"uint256"}],payable:!1,stateMutability:"view",type:"function"},{constant:!0,inputs:[],name:"symbol",outputs:[{name:"",type:"string"}],payable:!1,stateMutability:"view",type:"function"},{constant:!1,inputs:[{name:"_to",type:"address"},{name:"_value",type:"uint256"}],name:"transfer",outputs:[{name:"",type:"bool"}],payable:!1,stateMutability:"nonpayable",type:"function"},{constant:!0,inputs:[{name:"_owner",type:"address"},{name:"_spender",type:"address"}],name:"allowance",outputs:[{name:"",type:"uint256"}],payable:!1,stateMutability:"view",type:"function"},{payable:!0,stateMutability:"payable",type:"fallback"},{anonymous:!1,inputs:[{indexed:!0,name:"owner",type:"address"},{indexed:!0,name:"spender",type:"address"},{indexed:!1,name:"value",type:"uint256"}],name:"Approval",type:"event"},{anonymous:!1,inputs:[{indexed:!0,name:"from",type:"address"},{indexed:!0,name:"to",type:"address"},{indexed:!1,name:"value",type:"uint256"}],name:"Transfer",type:"event"}],V=3e10,H=4e9,Z=1e10,X=11155111;function K(t,e){return t}async function Q(t,e){const a=(await t.provider.getFeeData()).gasPrice,i=BigInt(a.toString());return e?(i*BigInt(e)).toString(10):i.toString()}async function Y(t,e){return new a.Contract(e,W,t).decimals()}async function tt(t,e,a,r){let n=r||await Y(t,e);return"0"===n&&(n=18),i(a,n).toString()}async function et(t,e,a,i){let n=i||await Y(t,e);return"0"===n&&(n=18),r(a,n).toString()}function at(t,e){if(t&&t.logs)return t.logs.filter(t=>t instanceof n&&t.eventName===e)[0]}async function it(t,e,a,i,...r){const{chainId:n}=await e.provider.getNetwork(),s=await e.provider.getFeeData();let o={};if(s.maxPriorityFeePerGas){let t=s.maxPriorityFeePerGas.toString(),e=s.maxFeePerGas.toString();a>1&&(t=Math.round(Number(s.maxPriorityFeePerGas)*a).toString(),e=Math.round(Number(s.maxFeePerGas)*a).toString()),o={maxPriorityFeePerGas:(80001===Number(n)||137===Number(n))&&Number(t)<V?V:Number(n)===X&&Number(t)<H?H:q.includes(Number(n))&&Number(t)<Z?Z:Number(t),maxFeePerGas:(80001===Number(n)||137===Number(n))&&Number(e)<V?V:Number(n)===X&&Number(e)<H?H:q.includes(Number(n))&&Number(e)<Z?Z:Number(e)}}else o={gasPrice:s.gasPrice};o.gasLimit=BigInt(new p(t).plus(20000n).toString());try{const t=await i(...r,o);return await t.wait(),t}catch(t){return $.error("Send tx error: ",t),null}}class rt{constructor(t,e,a,i){this.signer=void 0,this.config=void 0,this.abi=void 0,this.signer=t,this.config=a||(new J).getConfig(e),this.abi=i||this.getDefaultAbi()}getSignerAccordingSdk(){return this.config&&"sdk"in this.config&&"oasis"===this.config.sdk?w.wrap(this.signer):this.signer}async amountToUnits(t,e,a){return et(this.signer,t,e,a)}async unitsToAmount(t,e,a){return tt(this.signer,t,e,a)}async getFairGasPrice(){var t;return Q(this.signer,null==(t=this.config)?void 0:t.gasFeeMultiplier)}getContract(t,e){if(!t)throw new Error("Contract address is required but not provided");return K(new a.Contract(t,new a.Interface(JSON.stringify(e||this.abi)),this.signer))}}class nt extends rt{constructor(t,e,a,i,r){super(e,a,i,r),this.address=void 0,this.contract=void 0,this.address=t,this.contract=this.getContract(this.address)}}class st extends nt{getDefaultAbi(){return f.abi}async status(t){const e=await this.contract.status(t);if(!e)throw new Error("Np dispenser found for the given datatoken address");return{active:e.active,owner:e.owner,isMinter:e.isMinter,maxTokens:await this.unitsToAmount(null,e.maxTokens,18),maxBalance:await this.unitsToAmount(null,e.maxBalance,18),balance:await this.unitsToAmount(null,e.balance,18),allowedSwapper:e.allowedSwapper}}async create(t,e,a,i,r,n){var s;const o=await this.contract.create.estimateGas(t,this.amountToUnits(null,a,18),this.amountToUnits(null,i,18),e,r);return n?o:await it(o,this.getSignerAccordingSdk(),null==(s=this.config)?void 0:s.gasFeeMultiplier,this.contract.create,t,this.amountToUnits(null,a,18),this.amountToUnits(null,i,18),e,r)}async activate(t,e,a,i){var r;const n=await this.contract.activate.estimateGas(t,this.amountToUnits(null,e,18),this.amountToUnits(null,a,18));return i?n:await it(n,this.getSignerAccordingSdk(),null==(r=this.config)?void 0:r.gasFeeMultiplier,this.contract.activate,t,this.amountToUnits(null,e,18),this.amountToUnits(null,a,18))}async deactivate(t,e){var a;const i=await this.contract.deactivate.estimateGas(t);return e?i:await it(i,this.getSignerAccordingSdk(),null==(a=this.config)?void 0:a.gasFeeMultiplier,this.contract.deactivate,t)}async setAllowedSwapper(t,e,a){var i;const r=await this.contract.setAllowedSwapper.estimateGas(t,e);return a?r:await it(r,this.getSignerAccordingSdk(),null==(i=this.config)?void 0:i.gasFeeMultiplier,this.contract.setAllowedSwapper,t,e)}async dispense(t,e="1",a,i){var r;const n=await this.contract.dispense.estimateGas(t,this.amountToUnits(null,e,18),a);return i?n:await it(n,this.getSignerAccordingSdk(),null==(r=this.config)?void 0:r.gasFeeMultiplier,this.contract.dispense,t,this.amountToUnits(null,e,18),a)}async ownerWithdraw(t,e){var a;const i=await this.contract.ownerWithdraw.estimateGas(t);return e?i:await it(i,this.getSignerAccordingSdk(),null==(a=this.config)?void 0:a.gasFeeMultiplier,this.contract.ownerWithdraw,t)}async isDispensable(t,e,a,i="1"){const r=await this.status(t);return!(!r||!1===r.active||new m(await e.balance(t,a)).greaterThanOrEqualTo(r.maxBalance)||new m(String(i)).greaterThan(r.maxTokens)||!new m(r.balance).greaterThanOrEqualTo(i)&&!0!==r.isMinter)}}const ot="0x0000000000000000000000000000000000000000",ct=1e6,lt="115792089237316195423570985008687907853269984665640564039457584007913129639934",dt="Returned error: Method eth_feeHistory not supported.";class ut extends nt{getDefaultAbi(){return y.abi}async generateExchangeId(t,e){return await this.contract.generateExchangeId(t,e)}async buyDatatokens(t,e,a,i=ot,r="0",n){var s;const o=await this.getExchange(t),c=await this.amountToUnits(null,r,18),l=await this.amountToUnits(o.datatoken,e,Number(o.dtDecimals)),d=await this.amountToUnits(o.baseToken,a,Number(o.btDecimals)),u=await this.contract.buyDT.estimateGas(t,l,d,i,c);return n?u:await it(u,this.getSignerAccordingSdk(),null==(s=this.config)?void 0:s.gasFeeMultiplier,this.contract.buyDT,t,l,d,i,c)}async sellDatatokens(t,e,a,i=ot,r="0",n){var s;const o=await this.getExchange(t),c=await this.amountToUnits(null,r,18),l=await this.amountToUnits(o.datatoken,e,Number(o.dtDecimals)),d=await this.amountToUnits(o.baseToken,a,Number(o.btDecimals)),u=await this.contract.sellDT.estimateGas(t,l,d,i,c);return n?u:await it(u,this.getSignerAccordingSdk(),null==(s=this.config)?void 0:s.gasFeeMultiplier,this.contract.sellDT,t,l,d,i,c)}async getNumberOfExchanges(){const t=await this.contract.getNumberOfExchanges();return Number(t)}async setRate(t,e,a){var i;const r=await this.contract.setRate.estimateGas(t,await this.amountToUnits(null,e,18));return a?r:await it(r,this.getSignerAccordingSdk(),null==(i=this.config)?void 0:i.gasFeeMultiplier,this.contract.setRate,t,await this.amountToUnits(null,e,18))}async setAllowedSwapper(t,e,a){var i;const r=await this.contract.setAllowedSwapper.estimateGas(t,e);return a?r:await it(r,this.getSignerAccordingSdk(),null==(i=this.config)?void 0:i.gasFeeMultiplier,this.contract.setAllowedSwapper,t,e)}async activate(t,e){var a;const i=await this.getExchange(t);if(!i)return null;if(!0===i.active)return null;const r=await this.contract.toggleExchangeState.estimateGas(t);return e?r:await it(r,this.getSignerAccordingSdk(),null==(a=this.config)?void 0:a.gasFeeMultiplier,this.contract.toggleExchangeState,t)}async deactivate(t,e){var a;const i=await this.getExchange(t);if(!i)return null;if(!1===i.active)return null;const r=await this.contract.toggleExchangeState.estimateGas(t);return e?r:await it(r,this.getSignerAccordingSdk(),null==(a=this.config)?void 0:a.gasFeeMultiplier,this.contract.toggleExchangeState,t)}async getRate(t){const e=await this.contract.getRate(t);return await this.unitsToAmount(null,e,18)}async getDatatokenSupply(t){const e=await this.contract.getDTSupply(t),a=await this.getExchange(t);return await this.unitsToAmount(a.datatoken,e,Number(a.dtDecimals))}async getBasetokenSupply(t){const e=await this.contract.getBTSupply(t),a=await this.getExchange(t);return await this.unitsToAmount(a.baseToken,e,Number(a.btDecimals))}async getAllowedSwapper(t){return await this.contract.getAllowedSwapper(t)}async calcBaseInGivenDatatokensOut(t,e,a="0"){const i=await this.getExchange(t),r=await this.contract.calcBaseInGivenOutDT(t,await this.amountToUnits(i.datatoken,e,Number(i.dtDecimals)),await this.amountToUnits(null,a,18));return{baseTokenAmount:await this.unitsToAmount(i.baseToken,r.baseTokenAmount,Number(i.btDecimals)),marketFeeAmount:await this.unitsToAmount(i.baseToken,r.publishMarketFeeAmount,Number(i.btDecimals)),oceanFeeAmount:await this.unitsToAmount(i.baseToken,r.oceanFeeAmount,Number(i.btDecimals)),consumeMarketFeeAmount:await this.unitsToAmount(i.baseToken,r.consumeMarketFeeAmount,Number(i.btDecimals))}}async getAmountBasetokensOut(t,e,a="0"){const i=await this.getExchange(t),r=await this.contract.calcBaseOutGivenInDT(t,await this.amountToUnits(i.datatoken,e,Number(i.dtDecimals)),await this.amountToUnits(null,a,18));return await this.unitsToAmount(i.baseToken,r[0],Number(i.btDecimals))}async getExchange(t){const e=await this.contract.getExchange(t);return{active:e.active,datatoken:e.datatoken,baseToken:e.baseToken,withMint:e.withMint,exchangeOwner:e.exchangeOwner,allowedSwapper:e.allowedSwapper,dtDecimals:e.dtDecimals.toString(),btDecimals:e.btDecimals.toString(),dtBalance:await this.unitsToAmount(e.datatoken,e.dtBalance,Number(e.dtDecimals)),btBalance:await this.unitsToAmount(e.baseToken,e.btBalance,Number(e.btDecimals)),dtSupply:await this.unitsToAmount(e.datatoken,e.dtSupply,Number(e.dtDecimals)),btSupply:await this.unitsToAmount(e.baseToken,e.btSupply,Number(e.btDecimals)),fixedRate:await this.unitsToAmount(null,e.fixedRate,18),exchangeId:t}}async getFeesInfo(t){const e=await this.contract.getFeesInfo(t),a=await this.getExchange(t);return{opcFee:await this.unitsToAmount(null,e.opcFee.toString(),18),marketFee:await this.unitsToAmount(null,e.marketFee.toString(),18),marketFeeCollector:e.marketFeeCollector,marketFeeAvailable:await this.unitsToAmount(a.baseToken,e.marketFeeAvailable,Number(a.btDecimals)),oceanFeeAvailable:await this.unitsToAmount(a.baseToken,e.oceanFeeAvailable,Number(a.btDecimals)),exchangeId:t}}async getExchanges(){return await this.contract.getExchanges()}async isActive(t){return await this.contract.isActive(t)}async activateMint(t,e){var a;const i=await this.getExchange(t);if(!i)return null;if(!0===i.withMint)return null;const r=await this.contract.toggleMintState.estimateGas(t,!0);return e?r:await it(r,this.getSignerAccordingSdk(),null==(a=this.config)?void 0:a.gasFeeMultiplier,this.contract.toggleMintState,t,!0)}async deactivateMint(t,e){var a;const i=await this.getExchange(t);if(!i)return null;if(!1===i.withMint)return null;const r=await this.contract.toggleMintState.estimateGas(t,!1);return e?r:await it(r,this.getSignerAccordingSdk(),null==(a=this.config)?void 0:a.gasFeeMultiplier,this.contract.toggleMintState,t,!1)}async collectBasetokens(t,e,a){var i;if(!await this.getExchange(t))return null;const r=await this.contract.getExchange(t),n=await this.amountToUnits(r.baseToken,e,Number(r.btDecimals)),s=await this.contract.collectBT.estimateGas(t,n);return a?s:await it(s,this.getSignerAccordingSdk(),null==(i=this.config)?void 0:i.gasFeeMultiplier,this.contract.collectBT,t,n)}async collectDatatokens(t,e,a){var i;if(!await this.getExchange(t))return null;const r=await this.contract.getExchange(t),n=await this.amountToUnits(r.datatoken,e,Number(r.dtDecimals)),s=await this.contract.collectDT.estimateGas(t,n);return a?s:await it(s,this.getSignerAccordingSdk(),null==(i=this.config)?void 0:i.gasFeeMultiplier,this.contract.collectDT,t,n)}async collectMarketFee(t,e){var a;if(!await this.getExchange(t))return null;const i=await this.contract.collectMarketFee.estimateGas(t);return e?i:await it(i,this.getSignerAccordingSdk(),null==(a=this.config)?void 0:a.gasFeeMultiplier,this.contract.collectMarketFee,t)}async collectOceanFee(t,e){var a;if(!await this.getExchange(t))return null;const i=await this.contract.collectOceanFee.estimateGas(t);return e?i:await it(i,this.getSignerAccordingSdk(),null==(a=this.config)?void 0:a.gasFeeMultiplier,this.contract.collectOceanFee,t)}async getOPCCollector(){return await this.contract.opcCollector()}async getRouter(){return await this.contract.router()}async getExchangeOwner(t){return(await this.getExchange(t)).exchangeOwner}async updateMarketFee(t,e,a){var i;const r=await this.contract.updateMarketFee.estimateGas(t,await this.amountToUnits(null,e,18));return a?r:await it(r,this.getSignerAccordingSdk(),null==(i=this.config)?void 0:i.gasFeeMultiplier,this.contract.updateMarketFee,t,await this.amountToUnits(null,e,18))}async updateMarketFeeCollector(t,e,a){var i;const r=await this.contract.updateMarketFeeCollector.estimateGas(t,e);return a?r:await it(r,this.getSignerAccordingSdk(),null==(i=this.config)?void 0:i.gasFeeMultiplier,this.contract.updateMarketFeeCollector,t,e)}}class ht extends nt{getDefaultAbi(){return v.abi}async buyDatatokenBatch(t,e){var a;const i=await this.contract.buyDTBatch.estimateGas(t);return e?i:await it(i,this.getSignerAccordingSdk(),null==(a=this.config)?void 0:a.gasFeeMultiplier,this.contract.buyDTBatch,t)}async isApprovedToken(t){return await this.contract.isApprovedToken(t)}async isFixedPrice(t){return await this.contract.isFixedRateContract(t)}async getOwner(){return await this.contract.routerOwner()}async getNFTFactory(){return await this.contract.factory()}async addApprovedToken(t,e,a){var i;if(await this.getOwner()!==t)throw new Error("Caller is not Router Owner");const r=await this.contract.addApprovedToken.estimateGas(e);return a?r:await it(r,this.getSignerAccordingSdk(),null==(i=this.config)?void 0:i.gasFeeMultiplier,this.contract.addApprovedToken,e)}async removeApprovedToken(t,e,a){var i;if(await this.getOwner()!==t)throw new Error("Caller is not Router Owner");const r=await this.contract.removeApprovedToken.estimateGas(e);return a?r:await it(r,this.getSignerAccordingSdk(),null==(i=this.config)?void 0:i.gasFeeMultiplier,this.contract.removeApprovedToken,e)}async addFixedRateContract(t,e,a){var i;if(await this.getOwner()!==t)throw new Error("Caller is not Router Owner");const r=await this.contract.addFixedRateContract.estimateGas(e);return a?r:await it(r,this.getSignerAccordingSdk(),null==(i=this.config)?void 0:i.gasFeeMultiplier,this.contract.addFixedRateContract,e)}async removeFixedRateContract(t,e,a){var i;if(await this.getOwner()!==t)throw new Error("Caller is not Router Owner");const r=await this.contract.removeFixedRateContract.estimateGas(e);return a?r:await it(r,this.getSignerAccordingSdk(),null==(i=this.config)?void 0:i.gasFeeMultiplier,this.contract.removeFixedRateContract,e)}async addDispenserContract(t,e,a){var i;if(await this.getOwner()!==t)throw new Error("Caller is not Router Owner");const r=await this.contract.addDispenserContract.estimateGas(e);return a?r:await it(r,this.getSignerAccordingSdk(),null==(i=this.config)?void 0:i.gasFeeMultiplier,this.contract.addDispenserContract,e)}async removeDispenserContract(t,e,a){var i;if(await this.getOwner()!==t)throw new Error("Caller is not Router Owner");const r=await this.contract.removeDispenserContract.estimateGas(e);return a?r:await it(r,this.getSignerAccordingSdk(),null==(i=this.config)?void 0:i.gasFeeMultiplier,this.contract.removeDispenserContract,e)}async getOPCFee(t){const e=await this.contract.getOPCFee(t);return Number(e)}async getCurrentOPCFee(){const t=await this.contract.swapOceanFee();return Number(t)}async updateOPCFee(t,e,a,i,r,n){var s;if(await this.getOwner()!==t)throw new Error("Caller is not Router Owner");const o=await this.contract.updateOPCFee.estimateGas(e,a,i,r);return n?o:await it(o,this.getSignerAccordingSdk(),null==(s=this.config)?void 0:s.gasFeeMultiplier,this.contract.updateOPCFee,e,a,i,r)}}var gt={nouns:["Crab","Fish","Seal","Octopus","Shark","Seahorse","Walrus","Starfish","Whale","Orca","Penguin","Jellyfish","Squid","Lobster","Pelican","Shrimp","Oyster","Clam","Seagull","Dolphin","Shell","Cormorant","Otter","Anemone","Turtle","Coral","Ray","Barracuda","Krill","Anchovy","Angelfish","Barnacle","Clownfish","Cod","Cuttlefish","Eel","Fugu","Herring","Haddock","Ling","Mackerel","Manatee","Narwhal","Nautilus","Plankton","Porpoise","Prawn","Pufferfish","Swordfish","Tuna"],adjectives:["adamant","adroit","amatory","ambitious","amused","animistic","antic","arcadian","artistic","astonishing","astounding","baleful","bellicose","bilious","blissful","boorish","brave","breathtaking","brilliant","calamitous","caustic","cerulean","clever","charming","comely","competent","concomitant","confident","contumacious","corpulent","crapulous","creative","dazzling","dedicated","defamatory","delighted","delightful","determined","didactic","dilatory","dowdy","efficacious","effulgent","egregious","empowered","endemic","enthusiastic","equanimous","exceptional","execrable","fabulous","fantastic","fastidious","feckless","fecund","friable","fulsome","garrulous","generous","gentle","guileless","gustatory","heuristic","histrionic","hubristic","incendiary","incredible","insidious","insolent","inspired","intransigent","inveterate","invidious","invigorated","irksome","jejune","juicy","jocular","joyful","judicious","kind","lachrymose","limpid","loquacious","lovely","luminous","mannered","marvelous","mendacious","meretricious","minatory","mordant","motivated","munificent","nefarious","noxious","obtuse","optimistic","parsimonious","pendulous","pernicious","pervasive","petulant","passionate","phenomenal","platitudinous","pleasant","powerful","precipitate","propitious","puckish","querulous","quiescent","rebarbative","recalcitant","redolent","rhadamanthine","risible","ruminative","sagacious","salubrious","sartorial","sclerotic","serpentine","smart","spasmodic","strident","stunning","stupendous","taciturn","tactful","tasty","tenacious","tremendous","tremulous","trenchant","turbulent","turgid","ubiquitous","uxorious","verdant","vibrant","voluble","voracious","wheedling","withering","wonderful","zealous"]};function wt(t){const e=t||gt,a=Math.floor(Math.random()*e.adjectives.length),i=Math.floor(Math.random()*e.nouns.length),r=Math.floor(100*Math.random()),n=e.adjectives[a].replace(/^\w/,t=>t.toUpperCase()),s=e.nouns[i].replace(/^\w/,t=>t.toUpperCase());return{name:`${n} ${s} Token`,symbol:`${(n.substring(0,3)+s.substring(0,3)).toUpperCase()}-${r}`}}class pt extends nt{getDefaultAbi(){return S.abi}async createNFT(t,e){if(t.templateIndex||(t.templateIndex=1),!t.name||!t.symbol){const{name:e,symbol:a}=wt();t.name=e,t.symbol=a}if(t.templateIndex>await this.getCurrentNFTTemplateCount())throw new Error("Template index doesnt exist");if(0===t.templateIndex)throw new Error("Template index cannot be ZERO");if(!1===(await this.getNFTTemplate(t.templateIndex)).isActive)throw new Error("Template is not active");const a=await this.contract.deployERC721Contract.estimateGas(t.name,t.symbol,t.templateIndex,ot,ot,t.tokenURI,t.transferable,t.owner);if(e)return a;try{var i;const e=await it(a,this.getSignerAccordingSdk(),null==(i=this.config)?void 0:i.gasFeeMultiplier,this.contract.deployERC721Contract,t.name,t.symbol,t.templateIndex,ot,ot,t.tokenURI,t.transferable,t.owner);if(!e){const t="Tx for deploying new NFT contract does not exist or status is not successful.";throw console.error(t),t}return at(await e.wait(),"NFTCreated").args[0]}catch(t){console.error(`Creation of NFT failed: ${t}`)}}async getCurrentNFTCount(){const t=await this.contract.getCurrentNFTCount();return Number(t)}async getCurrentTokenCount(){const t=await this.contract.getCurrentTokenCount();return Number(t)}async getOwner(){return await this.contract.owner()}async getCurrentNFTTemplateCount(){const t=await this.contract.getCurrentNFTTemplateCount();return Number(t)}async getCurrentTokenTemplateCount(){const t=await this.contract.getCurrentTemplateCount();return Number(t)}async getNFTTemplate(t){if(t>await this.getCurrentNFTTemplateCount())throw new Error("Template index doesnt exist");if(0===t)throw new Error("Template index cannot be ZERO");return await this.contract.getNFTTemplate(t)}async getTokenTemplate(t){return await this.contract.getTokenTemplate(t)}async checkDatatoken(t){return await this.contract.erc20List(t)}async checkNFT(t){return await this.contract.erc721List(t)}async addNFTTemplate(t,e,a){var i;if(await this.getOwner()!==t)throw new Error("Caller is not Factory Owner");if(e===ot)throw new Error("Template cannot be ZERO address");const r=await this.contract.add721TokenTemplate.estimateGas(e);return a?r:await it(r,this.getSignerAccordingSdk(),null==(i=this.config)?void 0:i.gasFeeMultiplier,this.contract.add721TokenTemplate,e)}async disableNFTTemplate(t,e,a){var i;if(await this.getOwner()!==t)throw new Error("Caller is not Factory Owner");if(e>await this.getCurrentNFTTemplateCount())throw new Error("Template index doesnt exist");if(0===e)throw new Error("Template index cannot be ZERO");const r=await this.contract.disable721TokenTemplate.estimateGas(e);return a?r:await it(r,this.getSignerAccordingSdk(),null==(i=this.config)?void 0:i.gasFeeMultiplier,this.contract.disable721TokenTemplate,e)}async reactivateNFTTemplate(t,e,a){var i;if(await this.getOwner()!==t)throw new Error("Caller is not Factory Owner");if(e>await this.getCurrentNFTTemplateCount())throw new Error("Template index doesnt exist");if(0===e)throw new Error("Template index cannot be ZERO");const r=await this.contract.reactivate721TokenTemplate.estimateGas(e);return a?r:await it(r,this.getSignerAccordingSdk(),null==(i=this.config)?void 0:i.gasFeeMultiplier,this.contract.reactivate721TokenTemplate,e)}async addTokenTemplate(t,e,a){var i;if(await this.getOwner()!==t)throw new Error("Caller is not Factory Owner");if(e===ot)throw new Error("Template cannot be address ZERO");const r=await this.contract.addTokenTemplate.estimateGas(e);return a?r:await it(r,this.getSignerAccordingSdk(),null==(i=this.config)?void 0:i.gasFeeMultiplier,this.contract.addTokenTemplate,e)}async disableTokenTemplate(t,e,a){var i;if(await this.getOwner()!==t)throw new Error("Caller is not Factory Owner");if(e>await this.getCurrentTokenTemplateCount())throw new Error("Template index doesnt exist");if(0===e)throw new Error("Template index cannot be ZERO");if(!1===(await this.getTokenTemplate(e)).isActive)throw new Error("Template is already disabled");const r=await this.contract.disableTokenTemplate.estimateGas(e);return a?r:await it(r,this.getSignerAccordingSdk(),null==(i=this.config)?void 0:i.gasFeeMultiplier,this.contract.disableTokenTemplate,e)}async reactivateTokenTemplate(t,e,a){var i;if(await this.getOwner()!==t)throw new Error("Caller is not Factory Owner");if(e>await this.getCurrentTokenTemplateCount())throw new Error("Template index doesnt exist");if(0===e)throw new Error("Template index cannot be ZERO");if(!0===(await this.getTokenTemplate(e)).isActive)throw new Error("Template is already active");const r=await this.contract.reactivateTokenTemplate.estimateGas(e);return a?r:await it(r,this.getSignerAccordingSdk(),null==(i=this.config)?void 0:i.gasFeeMultiplier,this.contract.reactivateTokenTemplate,e)}async startMultipleTokenOrder(t,e){var a;if(t.length>50)throw new Error("Too many orders");const i=await this.contract.startMultipleTokenOrder.estimateGas(t);return e?i:await it(i,this.getSignerAccordingSdk(),null==(a=this.config)?void 0:a.gasFeeMultiplier,this.contract.startMultipleTokenOrder,t)}async createNftWithDatatoken(t,e,a){var i;const r=await this.getErcCreationParams(e),n=await this.contract.createNftWithErc20.estimateGas(t,r);return a?n:await it(n,this.getSignerAccordingSdk(),null==(i=this.config)?void 0:i.gasFeeMultiplier,this.contract.createNftWithErc20,t,r)}async createNftWithDatatokenWithFixedRate(t,e,a,i){var r;const n=await this.getErcCreationParams(e),s=await this.getFreCreationParams(a),o=await this.contract.createNftWithErc20WithFixedRate.estimateGas(t,n,s);return i?o:await it(o,this.getSignerAccordingSdk(),null==(r=this.config)?void 0:r.gasFeeMultiplier,this.contract.createNftWithErc20WithFixedRate,t,n,s)}async createNftWithDatatokenWithDispenser(t,e,a,i){var r;const n=await this.getErcCreationParams(e);a.maxBalance=await this.amountToUnits(null,a.maxBalance,18),a.maxTokens=await this.amountToUnits(null,a.maxTokens,18);const s=await this.contract.createNftWithErc20WithDispenser.estimateGas(t,n,a);return i?s:await it(s,this.getSignerAccordingSdk(),null==(r=this.config)?void 0:r.gasFeeMultiplier,this.contract.createNftWithErc20WithDispenser,t,n,a)}async getErcCreationParams(t){let e,a;t.name&&t.symbol||({name:e,symbol:a}=wt());let i=18;if(t.feeToken!==ot)try{i=await Y(this.signer,t.feeToken)}catch(t){$.error("getTokenDecimals error",t)}const r=[t.minter,t.paymentCollector,t.mpFeeAddress,t.feeToken];return t.filesObject&&(t.accessListFactory&&r.push(t.accessListFactory),t.allowAccessList&&r.push(t.allowAccessList),t.denyAccessList&&r.push(t.denyAccessList)),{templateIndex:t.templateIndex,strings:[t.name||e,t.symbol||a],addresses:r,uints:[await this.amountToUnits(null,t.cap,18),await this.amountToUnits(null,t.feeAmount,i)],bytess:t.filesObject?[s(JSON.stringify(t.filesObject))]:[]}}async getFreCreationParams(t){t.allowedConsumer||(t.allowedConsumer=ot);const e=!1===t.withMint?0:1;return{fixedPriceAddress:t.fixedRateAddress,addresses:[t.baseTokenAddress,t.owner,t.marketFeeCollector,t.allowedConsumer],uints:[t.baseTokenDecimals,t.datatokenDecimals,await this.amountToUnits(null,t.fixedRate,t.datatokenDecimals),await this.amountToUnits(null,t.marketFee,t.datatokenDecimals),e]}}}function mt(){try{if(process.env.ADDRESS_FILE){const t=e.readFileSync(process.env.ADDRESS_FILE,"utf8");return JSON.parse(t)}return t}catch(e){return t}}function ft(t){try{const e=mt();if(e){const a=Object.keys(e);for(const i of a)if(e[i].chainId===t)return e[i]}}catch(t){console.error(t)}return null}async function yt(t,e,i,r){const n="number"==typeof i,s=new pt(e,t,r),o=await s.getCurrentTokenTemplateCount();for(let e=1;e<=o;e++){const r=await s.getTokenTemplate(e),o=new a.Contract(r.templateAddress,E.abi,t);if(n){const t=await o.getId();if(r.isActive&&t.toString()===i.toString())return e}else if(r.isActive&&r.templateAddress===i.toString())return e}return-1}class vt extends rt{getDefaultAbi(){return b.abi}async createDatatoken(t,e,a,i,r,n,o,c,l,d,u,h,g,w,p,m){var f;if(!0!==(await this.getNftPermissions(t,e)).deployERC20)throw new Error("Caller is not DatatokenDeployer");u||(u=1),l&&d||({name:l,symbol:d}=wt());const y=this.getContract(t);if(!this.signer.provider)throw new Error("Provider is required but not available");const{chainId:v}=await this.signer.provider.getNetwork(),k=ft(Number(v));h&&(u=await yt(this.signer,k.ERC721Factory,4,Number(v)));const T=await y.createERC20.estimateGas(u,[l,d],[a,i,r,n],[await this.amountToUnits(null,c,18),await this.amountToUnits(null,o,18)],[]);if(m)return T;const b=[a,i,r,n];g&&(b.push(g.toLowerCase()),b.push(w?w.toLowerCase():ot),b.push(p||ot));const S=await it(T,this.getSignerAccordingSdk(),null==(f=this.config)?void 0:f.gasFeeMultiplier,y.createERC20,u,[l,d],b,[await this.amountToUnits(null,c,18),await this.amountToUnits(null,o,18)],h?[s(h)]:[]),E=at(await S.wait(),"TokenCreated");return null==E?void 0:E.args[0]}async addManager(t,e,a,i){var r;const n=this.getContract(t);if(await this.getNftOwner(t)!==e)throw new Error("Caller is not NFT Owner");const s=await n.addManager.estimateGas(a);return i?s:await it(s,this.getSignerAccordingSdk(),null==(r=this.config)?void 0:r.gasFeeMultiplier,n.addManager,a)}async removeManager(t,e,a,i){var r;const n=this.getContract(t);if(await this.getNftOwner(t)!==e)throw new Error("Caller is not NFT Owner");const s=await n.removeManager.estimateGas(a);return i?s:await it(s,this.getSignerAccordingSdk(),null==(r=this.config)?void 0:r.gasFeeMultiplier,n.removeManager,a)}async addDatatokenDeployer(t,e,a,i){var r;const n=this.getContract(t);if(!0!==(await this.getNftPermissions(t,e)).manager)throw new Error("Caller is not Manager");const s=await n.addToCreateERC20List.estimateGas(a);return i?s:await it(s,this.getSignerAccordingSdk(),null==(r=this.config)?void 0:r.gasFeeMultiplier,n.addToCreateERC20List,a)}async removeDatatokenDeployer(t,e,a,i){var r;const n=this.getContract(t);if(!0!==(await this.getNftPermissions(t,e)).manager||e===a&&!0!==(await this.getNftPermissions(t,e)).deployERC20)throw new Error("Caller is not Manager nor DatatokenDeployer");const s=await n.removeFromCreateERC20List.estimateGas(a);return i?s:await it(s,this.getSignerAccordingSdk(),null==(r=this.config)?void 0:r.gasFeeMultiplier,n.removeFromCreateERC20List,a)}async addMetadataUpdater(t,e,a,i){var r;const n=this.getContract(t);if(!0!==(await this.getNftPermissions(t,e)).manager)throw new Error("Caller is not Manager");const s=await n.addToMetadataList.estimateGas(a);return i?s:await it(s,this.getSignerAccordingSdk(),null==(r=this.config)?void 0:r.gasFeeMultiplier,n.addToMetadataList,a)}async removeMetadataUpdater(t,e,a,i){var r;const n=this.getContract(t);if(!0!==(await this.getNftPermissions(t,e)).manager||e!==a&&!0!==(await this.getNftPermissions(t,e)).updateMetadata)throw new Error("Caller is not Manager nor Metadata Updater");const s=await n.removeFromMetadataList.estimateGas(a);return i?s:await it(s,this.getSignerAccordingSdk(),null==(r=this.config)?void 0:r.gasFeeMultiplier,n.removeFromMetadataList,a)}async addStoreUpdater(t,e,a,i){var r;const n=this.getContract(t);if(!0!==(await this.getNftPermissions(t,e)).manager)throw new Error("Caller is not Manager");const s=await n.addTo725StoreList.estimateGas(a);return i?s:await it(s,this.getSignerAccordingSdk(),null==(r=this.config)?void 0:r.gasFeeMultiplier,n.addTo725StoreList,a)}async removeStoreUpdater(t,e,a,i){var r;const n=this.getContract(t);if(!0!==(await this.getNftPermissions(t,e)).manager||e!==a&&!0!==(await this.getNftPermissions(t,e)).store)throw new Error("Caller is not Manager nor storeUpdater");const s=await n.removeFrom725StoreList.estimateGas(a);return i?s:await it(s,this.getSignerAccordingSdk(),null==(r=this.config)?void 0:r.gasFeeMultiplier,n.removeFrom725StoreList,a)}async cleanPermissions(t,e,a){var i;const r=this.getContract(t);if(await this.getNftOwner(t)!==e)throw new Error("Caller is not NFT Owner");const n=await r.cleanPermissions.estimateGas();return a?n:await it(n,this.getSignerAccordingSdk(),null==(i=this.config)?void 0:i.gasFeeMultiplier,r.cleanPermissions)}async transferNft(t,e,a,i,r){var n;const s=this.getContract(t);if(await this.getNftOwner(t)!==e)throw new Error("Caller is not NFT Owner");const o=i||1,c=await s.transferFrom.estimateGas(e,a,o);return r?c:await it(c,this.getSignerAccordingSdk(),null==(n=this.config)?void 0:n.gasFeeMultiplier,s.transferFrom,e,a,o)}async safeTransferNft(t,e,a,i,r){var n;const s=this.getContract(t);if(await this.getNftOwner(t)!==e)throw new Error("Caller is not NFT Owner");const o=i||1,c=await s.safeTransferFrom.estimateGas(e,a,o);return r?c:await it(c,this.getSignerAccordingSdk(),null==(n=this.config)?void 0:n.gasFeeMultiplier,s.safeTransferFrom,e,a,o)}async setMetadata(t,e,a,i,r,n,s,o,c,l){var d;const u=this.getContract(t);if(c||(c=[]),!(await this.getNftPermissions(t,e)).updateMetadata)throw new Error("Caller is not Metadata updater");const h=await u.setMetaData.estimateGas(a,i,r,n,s,o,c);return l?h:await it(h,this.signer,null==(d=this.config)?void 0:d.gasFeeMultiplier,u.setMetaData,a,i,r,n,s,o,c)}async setMetadataAndTokenURI(t,e,a,i){var r;const n=this.getContract(t);if(!(await this.getNftPermissions(t,e)).updateMetadata)throw new Error("Caller is not Metadata updater");const s=G({},a,{metadataProofs:a.metadataProofs||[]}),o=await n.setMetaDataAndTokenURI.estimateGas(s);return i?o:await it(o,this.signer,null==(r=this.config)?void 0:r.gasFeeMultiplier,n.setMetaDataAndTokenURI,s)}async setMetadataState(t,e,a,i){var r;const n=this.getContract(t);if(!(await this.getNftPermissions(t,e)).updateMetadata)throw new Error("Caller is not Metadata updater");const s=await n.setMetaDataState.estimateGas(a);return i?s:await it(s,this.getSignerAccordingSdk(),null==(r=this.config)?void 0:r.gasFeeMultiplier,n.setMetaDataState,a)}async setTokenURI(t,e,a){var i;const r=this.getContract(t),n=await r.setTokenURI.estimateGas("1",e);return a?n:await it(n,this.getSignerAccordingSdk(),null==(i=this.config)?void 0:i.gasFeeMultiplier,r.setTokenURI,"1",e)}async getNftOwner(t){const e=this.getContract(t);return await e.ownerOf(1)}async getNftPermissions(t,e){const a=this.getContract(t);return await a.getPermissions(e)}async getMetadata(t){const e=this.getContract(t);return await e.getMetaData()}async isDatatokenDeployer(t,e){const a=this.getContract(t);return await a.isERC20Deployer(e)}async setData(t,e,a,i,r){var n;if(!0!==(await this.getNftPermissions(t,e)).store)throw new Error("User is not ERC20 store updater");const l=this.getContract(t),d=o(a),u=c(s(i)),h=await l.setNewData.estimateGas(d,u);return r?h:await it(h,this.getSignerAccordingSdk(),null==(n=this.config)?void 0:n.gasFeeMultiplier,l.setNewData,d,u)}async getData(t,e){const a=this.getContract(t),i=o(e),r=await a.getData(i);return r?l(r):null}async getTokenURI(t,e){const a=this.getContract(t);return await a.tokenURI(e)}async isDatatokenDeployed(t,e){const a=this.getContract(t);return await a.isDeployed(e)}}class kt extends rt{getDefaultAbi(){return k.abi}constructor(t,e,a,i,r){super(t,e,a,i),this.abiEnterprise=void 0,this.nft=void 0,this.abiEnterprise=r||T.abi,this.nft=new vt(this.signer,e)}async approve(t,e,a,i){var r;const n=this.getContract(t),s=await n.approve.estimateGas(e,et(null,null,a,18));return i?s:await it(s,this.getSignerAccordingSdk(),null==(r=this.config)?void 0:r.gasFeeMultiplier,n.approve,e,et(null,null,a,18))}async createFixedRate(t,e,a,i){var r;const n=this.getContract(t);if(!await this.isDatatokenDeployer(t,e))throw new Error("User is not Datatoken Deployer");a.allowedConsumer||(a.allowedConsumer=ot);const s=!1===a.withMint?0:1,o=await n.createFixedRate.estimateGas(a.fixedRateAddress,[a.baseTokenAddress,a.owner,a.marketFeeCollector,a.allowedConsumer],[a.baseTokenDecimals,a.datatokenDecimals,a.fixedRate,a.marketFee,s]);return i?o:await it(o,this.getSignerAccordingSdk(),null==(r=this.config)?void 0:r.gasFeeMultiplier,n.createFixedRate,a.fixedRateAddress,[a.baseTokenAddress,a.owner,a.marketFeeCollector,a.allowedConsumer],[a.baseTokenDecimals,a.datatokenDecimals,a.fixedRate,a.marketFee,s])}async createDispenser(t,e,a,i,r){var n;if(!await this.isDatatokenDeployer(t,e))throw new Error("User is not Datatoken Deployer");const s=this.getContract(t);i.allowedSwapper||(i.allowedSwapper=ot),i.withMint=!1!==i.withMint;const o=await s.createDispenser.estimateGas(a,i.maxTokens,i.maxBalance,i.withMint,i.allowedSwapper);return r?o:await it(o,this.getSignerAccordingSdk(),null==(n=this.config)?void 0:n.gasFeeMultiplier,s.createDispenser,a,i.maxTokens,i.maxBalance,i.withMint,i.allowedSwapper)}async mint(t,e,a,i,r){const n=this.getContract(t);if(!0!==(await this.getPermissions(t,e)).minter)throw new Error("Caller is not Minter");const s=await this.getCap(t);if(new m(s).gte(a)){var o;const t=await n.mint.estimateGas(i||e,et(null,null,a,18));return r?t:await it(t,this.getSignerAccordingSdk(),null==(o=this.config)?void 0:o.gasFeeMultiplier,n.mint,i||e,et(null,null,a,18))}throw new Error("Mint amount exceeds cap available")}async addMinter(t,e,a,i){var r;const n=this.getContract(t);if(!0!==await this.isDatatokenDeployer(t,e))throw new Error("Caller is not DatatokenDeployer");const s=await n.addMinter.estimateGas(a);return i?s:await it(s,this.getSignerAccordingSdk(),null==(r=this.config)?void 0:r.gasFeeMultiplier,n.addMinter,a)}async removeMinter(t,e,a,i){var r;const n=this.getContract(t);if(!0!==await this.isDatatokenDeployer(t,e))throw new Error("Caller is not DatatokenDeployer");const s=await n.removeMinter.estimateGas(a);return i?s:await it(s,this.getSignerAccordingSdk(),null==(r=this.config)?void 0:r.gasFeeMultiplier,n.removeMinter,a)}async addPaymentManager(t,e,a,i){var r;const n=this.getContract(t);if(!0!==await this.isDatatokenDeployer(t,e))throw new Error("Caller is not DatatokenDeployer");const s=await n.addPaymentManager.estimateGas(a);return i?s:await it(s,this.getSignerAccordingSdk(),null==(r=this.config)?void 0:r.gasFeeMultiplier,n.addPaymentManager,a)}async removePaymentManager(t,e,a,i){var r;const n=this.getContract(t);if(!0!==await this.isDatatokenDeployer(t,e))throw new Error("Caller is not DatatokenDeployer");const s=await n.removePaymentManager.estimateGas(a);return i?s:await it(s,this.getSignerAccordingSdk(),null==(r=this.config)?void 0:r.gasFeeMultiplier,n.removePaymentManager,a)}async setPaymentCollector(t,e,a,i){var r;const n=this.getContract(t),s=(await this.getPermissions(t,e)).paymentManager,o=!s&&await this.getNFTAddress(t),c=o&&await this.nft.getNftOwner(o)===e,l=o&&!c&&await this.nft.getNftPermissions(o,e);if(!s&&!c&&!(null==l?void 0:l.deployERC20))throw new Error("Caller is not Fee Manager, owner or Datatoken Deployer");const d=await n.setPaymentCollector.estimateGas(a);return i?d:await it(d,this.getSignerAccordingSdk(),null==(r=this.config)?void 0:r.gasFeeMultiplier,n.setPaymentCollector,a)}async getPaymentCollector(t){const e=this.getContract(t);return await e.getPaymentCollector()}async transfer(t,e,a,i){return this.transferWei(t,e,await et(null,null,a,18),i)}async transferWei(t,e,a,i){var r;const n=this.getContract(t),s=await n.transfer.estimateGas(e,a);return i?s:await it(s,this.getSignerAccordingSdk(),null==(r=this.config)?void 0:r.gasFeeMultiplier,n.transfer,e,a)}async startOrder(t,e,a,i,r,n){var s;const o=this.getContract(t,this.abi);r||(r={consumeMarketFeeAddress:ot,consumeMarketFeeToken:ot,consumeMarketFeeAmount:"0"});const c=await o.startOrder.estimateGas(e,a,i,r);return n?c:await it(c,this.getSignerAccordingSdk(),null==(s=this.config)?void 0:s.gasFeeMultiplier,o.startOrder,e,a,i,r)}async reuseOrder(t,e,a,i){var r;const n=this.getContract(t),s=await n.reuseOrder.estimateGas(e,a);return i?s:await it(s,this.getSignerAccordingSdk(),null==(r=this.config)?void 0:r.gasFeeMultiplier,n.reuseOrder,e,a)}async buyFromFreAndOrder(t,e,a,i){var r;const n=this.getContract(t,this.abiEnterprise),s=await this.getFreOrderParams(a),o=await n.buyFromFreAndOrder.estimateGas(e,s);return i?o:await it(o,this.getSignerAccordingSdk(),null==(r=this.config)?void 0:r.gasFeeMultiplier,n.buyFromFreAndOrder,e,s)}async buyFromDispenserAndOrder(t,e,a,i){var r;const n=this.getContract(t,this.abiEnterprise),s=await n.buyFromDispenserAndOrder.estimateGas(e,a);return i?s:await it(s,this.getSignerAccordingSdk(),null==(r=this.config)?void 0:r.gasFeeMultiplier,n.buyFromDispenserAndOrder,e,a)}async setData(t,e,a,i){var r;if(!await this.isDatatokenDeployer(t,e))throw new Error("User is not Datatoken Deployer");const n=this.getContract(t),o=c(s(a)),l=await n.setData.estimateGas(o);return i?l:await it(l,this.getSignerAccordingSdk(),null==(r=this.config)?void 0:r.gasFeeMultiplier,n.setData,o)}async cleanPermissions(t,e,a){var i;if(await this.nft.getNftOwner(await this.getNFTAddress(t))!==e)throw new Error("Caller is NOT Nft Owner");const r=this.getContract(t),n=await r.cleanPermissions.estimateGas();return a?n:await it(n,this.getSignerAccordingSdk(),null==(i=this.config)?void 0:i.gasFeeMultiplier,r.cleanPermissions)}async getPermissions(t,e){const a=this.getContract(t);return await a.permissions(e)}async getCap(t){const e=this.getContract(t),a=await e.cap();return await this.unitsToAmount(null,a,18)}async getDecimals(t){const e=this.getContract(t),a=await e.decimals();return Number(a)}async getId(t){const e=this.getContract(t),a=await e.getId();return Number(a)}async getSymbol(t){const e=this.getContract(t);return await e.symbol()}async getName(t){const e=this.getContract(t);return await e.name()}async getNFTAddress(t){const e=this.getContract(t);return await e.getERC721Address()}async getFixedRates(t){const e=this.getContract(t);return await e.getFixedRates()}async getDispensers(t){const e=this.getContract(t);return await e.getDispensers()}async isDatatokenDeployer(t,e){const a=this.getContract(t);return await a.isERC20Deployer(e)}async balance(t,e){const a=this.getContract(t),i=await a.balanceOf(e);return await this.unitsToAmount(null,i,18)}async allowance(t,e,a,i=18){const r=this.getContract(t),n=await r.allowance(e,a);return await this.unitsToAmount(null,n,i)}async setPublishingMarketFee(t,e,a,i,r,n){var s;const o=this.getContract(t);if((await o.getPublishingMarketFee())[0]!==r)throw new Error("Caller is not the Publishing Market Fee Address");const c=await o.setPublishingMarketFee.estimateGas(e,a,i);return n?c:await it(c,this.getSignerAccordingSdk(),null==(s=this.config)?void 0:s.gasFeeMultiplier,o.setPublishingMarketFee,e,a,i)}async getPublishingMarketFee(t){const e=this.getContract(t),a=await e.getPublishingMarketFee();return{publishMarketFeeAddress:a[0],publishMarketFeeToken:a[1],publishMarketFeeAmount:a[2].toString()}}async getFreOrderParams(t){return{exchangeContract:t.exchangeContract,exchangeId:t.exchangeId,maxBaseTokenAmount:await et(this.signer,t.baseTokenAddress,t.maxBaseTokenAmount,t.baseTokenDecimals),swapMarketFee:await et(this.signer,t.baseTokenAddress,t.swapMarketFee,t.baseTokenDecimals),marketFeeAddress:t.marketFeeAddress}}}class Tt extends kt{getDefaultAbi(){return A.abi}constructor(t,e,a,i,r){super(t,a,i,r),this.accessList=void 0,this.fileObject=void 0,this.abi=this.getDefaultAbi(),this.fileObject=e}setFileObj(t){this.fileObject=t}async getAllowlistContract(t){const e=this.getContract(t,this.getDefaultAbi());return await e.getAllowListContract()}async getDenylistContract(t){const e=this.getContract(t,this.getDefaultAbi());return await e.getDenyListContract()}async setAllowListContract(t,e,a,i){var r;if(!await this.isDatatokenDeployer(t,a))throw new Error("User is not Datatoken Deployer");const n=this.getContract(t),s=await n.setAllowListContract.estimateGas(e);return i?s:await it(s,this.getSignerAccordingSdk(),null==(r=this.config)?void 0:r.gasFeeMultiplier,n.setAllowListContract,e)}async setDenyListContract(t,e,a,i){var r;if(!await this.isDatatokenDeployer(t,a))throw new Error("User is not Datatoken Deployer");const n=this.getContract(t),s=await n.setDenyListContract.estimateGas(e);return i?s:await it(s,this.getSignerAccordingSdk(),null==(r=this.config)?void 0:r.gasFeeMultiplier,n.setDenyListContract,e)}async setFileObject(t,e,a){var i;if(!await this.isDatatokenDeployer(t,e))throw new Error("User is not Datatoken Deployer");const r=this.getContract(t),n=await r.setFilesObject.estimateGas(this.fileObject);return a?n:await it(n,this.getSignerAccordingSdk(),null==(i=this.config)?void 0:i.gasFeeMultiplier,r.setFilesObject,this.fileObject)}async getFileObject(t,e,a,i,r,n,s){const o=this.getContract(t,this.getDefaultAbi());return await o.getFileObject(e,a,i,r,n,s)}}class bt extends nt{getDefaultAbi(){return F.abi}constructor(t,e,a,i,r){super(t,e,a,i,r),this.abiEnterprise=void 0,this.abi=r||this.getDefaultAbi()}async getTokenUri(t){return await this.contract.tokenURI(t)}async getOwner(){return await this.contract.owner()}async getId(){const t=await this.contract.getId();return Number(t)}async getName(){return await this.contract.name()}async getSymbol(){return await this.contract.symbol()}async balance(t){const e=await this.contract.balanceOf(t);return await this.unitsToAmount(null,e,18)}async mint(t,e,a){var i;const r=await this.contract.mint.estimateGas(t,e);return a?r:await it(r,this.getSignerAccordingSdk(),null==(i=this.config)?void 0:i.gasFeeMultiplier,this.contract.mint,t,e)}async batchMint(t,e,a){var i;const r=await this.contract.batchMint.estimateGas(t,e);return a?r:await it(r,this.getSignerAccordingSdk(),null==(i=this.config)?void 0:i.gasFeeMultiplier,this.contract.batchMint,t,e)}async burn(t,e){var a;const i=await this.contract.burn.estimateGas(t);return e?i:await it(i,this.getSignerAccordingSdk(),null==(a=this.config)?void 0:a.gasFeeMultiplier,this.contract.burn,t)}async transferOwnership(t,e){var a;const i=await this.contract.transferOwnership.estimateGas(t);return e?i:await it(i,this.getSignerAccordingSdk(),null==(a=this.config)?void 0:a.gasFeeMultiplier,this.contract.transferOwnership,t)}async renounceOwnership(t){var e;const a=await this.contract.renounceOwnership.estimateGas();return t?a:await it(a,this.getSignerAccordingSdk(),null==(e=this.config)?void 0:e.gasFeeMultiplier,this.contract.renounceOwnership)}}class St extends nt{getDefaultAbi(){return C.abi}constructor(t,e,a,i,r){super(t,e,a,i,r),this.abi=r||this.getDefaultAbi()}async deployAccessListContract(t,e,a,i=!1,r,n,s){if(!t||!e){const{name:a,symbol:i}=wt();t=a,e=i}const o=await this.contract.deployAccessListContract.estimateGas(t,e,i,r,n,a);if(s)return o;try{var c;const s=await it(o,this.getSignerAccordingSdk(),null==(c=this.config)?void 0:c.gasFeeMultiplier,this.contract.deployAccessListContract,t,e,i,r,n,a);if(!s){const t="Tx for deploying new access list was not processed on chain.";throw console.error(t),t}return at(await s.wait(),"NewAccessList").args[0]}catch(t){console.error(`Creation of AccessList failed: ${t}`)}}async getOwner(){return await this.contract.owner()}async isSoulbound(t){return await this.contract.isSoulBound(t)}async isDeployed(t){return await this.contract.isDeployed(t)}async changeTemplateAddress(t,e,a){var i;if(await this.getOwner()!==t)throw new Error("Caller is not Factory Owner");if(e===ot)throw new Error("Template address cannot be ZERO address");const r=await this.contract.changeTemplateAddress.estimateGas(e);return a?r:await it(r,this.getSignerAccordingSdk(),null==(i=this.config)?void 0:i.gasFeeMultiplier,this.contract.changeTemplateAddress,e)}}class Et extends nt{getDefaultAbi(){return x.abi}constructor(t,e,a,i,r){super(t,e,a,i,r),this.abiEnterprise=void 0,this.abi=r||this.getDefaultAbi()}async getFunds(t){return await this.contract.getFunds(t)}async getUserFunds(t,e){return await this.contract.getUserFunds(t,e)}async getUserTokens(t){return await this.contract.getUserTokens(t)}async getLocks(t,e,a){return await this.contract.getLocks(t,e,a)}async getAuthorizations(t,e,a){return await this.contract.getAuthorizations(t,e,a)}async verifyFundsForEscrowPayment(t,e,a,i,r,n,s){var o;const c=await(null==(o=this.signer.provider)?void 0:o.getBalance(d(e)));if(new p(c).isZero())return{isValid:!1,message:"Native token balance is 0. Please add funds"};const l=new kt(this.signer),h=await l.allowance(t,await this.signer.getAddress(),this.contract.target.toString(),s);new p(await this.amountToUnits(t,h,18)).isLessThan(new p(i))&&await l.approve(d(t),d(this.contract.target.toString()),i);const g=await l.balance(t,await this.signer.getAddress());if(new p(g).isZero())return{isValid:!1,message:"Payment token balance is 0. Please add funds"};const w=await this.getAuthorizations(t,await this.signer.getAddress(),e),m=await this.getUserFunds(await this.signer.getAddress(),t);return new p(m[0]).isZero()&&(a&&new p(u(g)).isLessThanOrEqualTo(new p(u(a)))&&new p(u(a)).isGreaterThan(new p(i))?await this.deposit(t,a,s):new p(u(g)).isLessThanOrEqualTo(new p(u(i)))?await this.deposit(t,await this.unitsToAmount(t,i,s),s):await this.deposit(t,g,s)),0===w.length&&await this.authorize(d(t),d(e),(Number(i)/2).toString(),r,n),{isValid:!0,message:""}}async deposit(t,e,a,i){var r;const n=await this.amountToUnits(t,e,a),s=await this.contract.deposit.estimateGas(t,n);return i?s:await it(s,this.getSignerAccordingSdk(),null==(r=this.config)?void 0:r.gasFeeMultiplier,this.contract.deposit,t,n)}async withdraw(t,e,a,i){var r;const n=[],s=[];if(t.length!==e.length)throw new Error("Tokens and amounts arrays must have the same length");const o=await this.signer.getAddress();for(let a=0;a<t.length;a++){const i=t[a],r=new p(e[a]),c=await this.getUserFunds(o,i),l=new p(c[0]);r.isGreaterThan(0)&&r.isLessThanOrEqualTo(l)?(n.push(i),s.push(e[a])):console.log(`Insufficient funds for token ${i}`)}const c=await Promise.all(s.map((t,e)=>this.amountToUnits(n[e],t,a))),l=await this.contract.withdraw.estimateGas(t,c);return i?l:await it(l,this.getSignerAccordingSdk(),null==(r=this.config)?void 0:r.gasFeeMultiplier,this.contract.withdraw,n,c)}async authorize(t,e,a,i,r,n,s){var o;if(0!==(await this.getAuthorizations(t,await this.signer.getAddress(),e)).length)return console.log(`Payee ${e} already authorized`),null;const c=await this.amountToUnits(t,a,n),l=await this.amountToUnits(t,i,n),d=await this.amountToUnits(t,r,n),u=await this.contract.authorize.estimateGas(t,e,c,l,d);return s?u:await it(u,this.getSignerAccordingSdk(),null==(o=this.config)?void 0:o.gasFeeMultiplier,this.contract.authorize,t,e,c,l,d)}async cancelExpiredLocks(t,e,a,i,r){var n;const s=await this.contract.cancelExpiredLocks.estimateGas(t,e,a,i);return r?s:await it(s,this.getSignerAccordingSdk(),null==(n=this.config)?void 0:n.gasFeeMultiplier,this.contract.cancelExpiredLocks,t,e,a,i)}}class At extends nt{getDefaultAbi(){return D.abi}constructor(t,e,a,i,r){super(t,e,a,i,r),this.abi=r||this.getDefaultAbi()}async isTokenAllowed(t){return await this.contract.isTokenAllowed(t)}async getToken(t){return await this.contract.getToken(t)}async calculateFee(t,e,a){const i=this.amountToUnits(t,e.toString(),a),r=await this.contract.calculateFee(t,i);return this.unitsToAmount(t,r,a)}}async function Ft(t){return new Promise(e=>{setTimeout(e,t)})}function Ct(t){return null!=t}async function xt(t,e){const a=h(e);let i=await t._legacySignMessage(a);i=i.substr(2);const r="0x"+i.slice(0,64),n="0x"+i.slice(64,128);let s="0x"+i.slice(128,130);return"0x00"===s&&(s="0x1b"),"0x01"===s&&(s="0x1c"),{v:s,r,s:n}}async function Dt(t,e){const a=o(s(e)),i=h(a);if(!t.provider)throw new Error("Provider is required but not available");const{chainId:r}=await t.provider.getNetwork();try{return await t.signMessage(i)}catch(e){if($.error("Sign message error: ",e),8996===Number(r))return console.log("Signing message with _legacySignMessage"),await t._legacySignMessage(i)}}class Mt{constructor(t){this.aquariusURL=void 0,this.aquariusURL=t}async resolve(t,e,a){const i=this.aquariusURL+"/api/aquarius/assets/ddo/"+t;try{const t=await M(i,{method:"GET",headers:{"Content-Type":"application/json",Authorization:a},signal:e});if(t.ok)return await t.json();throw new Error("HTTP request failed with status "+t.status)}catch(t){throw $.error(t),new Error("HTTP request failed")}}async waitForIndexer(t,e,a,i=3e4,r=100,n){let s=0;r>500&&($.warn("Max Limit exceeded, defaulting to 500 retries."),r=500);do{try{const i=this.aquariusURL+"/api/aquarius/assets/ddo/"+t,r=await M(i,{method:"GET",headers:{"Content-Type":"application/json",Authorization:n},signal:a});if(r.ok){const t=await r.json(),a=O.getDDOClass(t),{indexedMetadata:i}=a.getAssetFields();if(!e)return t;if(i.event&&i.event.txid===e)return t}}catch(t){}await Ft(i),s++}while(s<r);return null}async validate(t,e,a,i,r){const n=a+"/api/aquarius/assets/ddo/validate",s=a+"/api/services/nonce";try{const a=await e.getAddress(),o=await M(s+`?userAddress=${a}`,{method:"GET",headers:{"Content-Type":"application/json",Authorization:r},signal:i});let{nonce:c}=await o.json();console.log(`[getNonce] Consumer: ${a} nonce: ${c}`),c&&null!==c||(c="0");const l=(Number(c)+1).toString(),d=a+l,u={ddo:t,publisherAddress:a,nonce:l,signature:await Dt(e,d)},h=await M(n,{method:"POST",body:JSON.stringify(u),headers:{"Content-Type":"application/octet-stream",Authorization:r},signal:i}),g=await h.json();if(200!==h.status)throw new Error("Metadata validation failed");return console.log("Ddo successfully validated"),{valid:!0,hash:g.hash,proof:{validatorAddress:g.publicKey,r:g.r[0],s:g.s[0],v:g.v}}}catch(t){$.error("Metadata validation failed",t.message)}}async getAssetMetadata(t,e,a){const i=this.aquariusURL+"/api/aquarius/assets/metadata/"+t;try{const t=await M(i,{method:"GET",headers:{"Content-Type":"application/json",Authorization:a},signal:e});if(t.ok)return t.json();throw new Error("getAssetMetadata failed: "+t.status+t.statusText)}catch(t){throw $.error("Error getting metadata: ",t),new Error("Error getting metadata: "+t)}}async querySearch(t,e,a){const i=this.aquariusURL+"/api/aquarius/assets/query";try{const r=await M(i,{method:"POST",body:JSON.stringify(t),headers:{"Content-Type":"application/json",Authorization:a},signal:e});if(r.ok)return r.json();throw new Error("querySearch failed: "+r.status+r.statusText)}catch(t){throw $.error("Error querying metadata: ",t),new Error("Error querying metadata: "+t)}}}class Ot{async getConsumerAddress(t){return"string"==typeof t?function(t){try{return N.decode(t,{json:!0})}catch(t){throw new Error("Error decoding JWT")}}(t).address:await t.getAddress()}async getSignature(t,e){return"string"==typeof t?null:await this.signProviderRequest(t,e)}getAuthorization(t){return"string"==typeof t?t:void 0}async getEndpoints(t,e){try{const a=await this.getData(t,e);return await a.json()}catch(t){throw $.error("Finding the service endpoints failed:",t),new Error("HTTP request failed calling Provider")}}getEndpointURL(t,e){return t?t.find(t=>t.serviceName.toLowerCase()===e.toLowerCase()):null}async getServiceEndpoints(t,e){const a=[];for(const i in e.serviceEndpoints){const r={serviceName:i,method:e.serviceEndpoints[i][0],urlPath:t.replace(/\/+$/,"")+"/"+e.serviceEndpoints[i][1].replace(/^\/+/,"")};a.push(r)}return a}async getNonce(t,e,a,i,r){i||(i=await this.getEndpoints(t)),r||(r=await this.getServiceEndpoints(t,i));const n=this.getEndpointURL(r,"nonce")?this.getEndpointURL(r,"nonce").urlPath:null;if(!n)return null;try{const t=await M(n+`?userAddress=${e}`,{method:"GET",headers:{"Content-Type":"application/json"},signal:a}),{nonce:i}=await t.json();return console.log(`[getNonce] Consumer: ${e} nonce: ${i}`),i&&null!==i?Number(i):0}catch(t){throw $.error(t),new Error(t.message)}}async signProviderRequest(t,e){const i=a.solidityPackedKeccak256(["bytes"],[a.hexlify(a.toUtf8Bytes(e))]),r=a.toBeArray(i);try{return await t.signMessage(r)}catch(e){const a=await t.provider.getNetwork();if(8996===Number(a.chainId))return await t._legacySignMessage(r)}}async encrypt(t,e,a,i,r,n){const s=await this.getEndpoints(a),o=await this.getServiceEndpoints(a,s),c=await this.getConsumerAddress(i),l=(await this.getNonce(a,c,n,s,o)+1).toString(),d=String(l),u=await this.getSignature(i,d);let h=(this.getEndpointURL(o,"encrypt")?this.getEndpointURL(o,"encrypt").urlPath:null)+`?chainId=${e}`;if(!h)return null;h+=`?nonce=${l}`,h+=`&consumerAddress=${c}`,h+=`&signature=${u}`;try{const e=await M(h,{method:"POST",body:JSON.stringify(t),headers:{"Content-Type":"application/octet-stream"},signal:n});return await e.text()}catch(t){throw $.error(t),new Error("HTTP request failed calling Provider")}}async checkDidFiles(t,e,a,i=!1,r){var n;const s=await this.getEndpoints(a),o=await this.getServiceEndpoints(a,s),c={did:t,serviceId:e,checksum:i},l=[],d=this.getEndpointURL(o,"fileinfo")?this.getEndpointURL(o,"fileinfo").urlPath:null;if(!d)return null;let u;try{u=await M(d,{method:"POST",body:JSON.stringify(c),headers:{"Content-Type":"application/json"},signal:r})}catch(t){throw $.error("File info call failed: "),$.error(t),new Error(t)}if(null!=(n=u)&&n.ok){const t=await u.json();for(const e of t)l.push(e);return l}const h=await u.json();throw $.error("File info call failed: ",u.status,u.statusText,h),new Error(JSON.stringify(h))}async getFileInfo(t,e,a=!1,i){var r;const n=await this.getEndpoints(e),s=await this.getServiceEndpoints(e,n),o=G({},t,{checksum:a}),c=[],l=this.getEndpointURL(s,"fileinfo")?this.getEndpointURL(s,"fileinfo").urlPath:null;if(!l)return null;let d;try{d=await M(l,{method:"POST",body:JSON.stringify(o),headers:{"Content-Type":"application/json"},signal:i})}catch(t){throw $.error("File info call failed: "),$.error(t),new Error(t)}if(null!=(r=d)&&r.ok){const t=await d.json();for(const e of t)c.push(e);return c}const u=await d.json();throw $.error("File info call failed: ",d.status,d.statusText,u),new Error(JSON.stringify(u))}async getComputeEnvironments(t,e){var a,i;const r=await this.getEndpoints(t),n=await this.getServiceEndpoints(t,r),s=null==(a=this.getEndpointURL(n,"computeEnvironments"))?void 0:a.urlPath;if(!s)return null;let o;try{o=await M(s,{method:"GET",headers:{"Content-Type":"application/json"},signal:e})}catch(t){throw $.error("Fetch compute env failed: "),$.error(t),new Error(t)}if(null!=(i=o)&&i.ok)return o.json();const c=await o.json();throw $.error("Fetch compute env failed: ",o.status,o.statusText,c),new Error(JSON.stringify(c))}async initialize(t,e,a,i,r,n,s,o,c){var l;const d=await this.getEndpoints(r),u=await this.getServiceEndpoints(r,d);let h,g=this.getEndpointURL(u,"initialize")?this.getEndpointURL(u,"initialize").urlPath:null;if(!g)return null;g+=`?documentId=${t}`,g+=`&serviceId=${e}`,g+=`&fileIndex=${a}`,g+=`&consumerAddress=${i}`,s&&(g+="&userdata="+encodeURI(JSON.stringify(s))),o&&(g+="&environment="+encodeURI(o)),c&&(g+="&validUntil="+c);try{h=await M(g,{method:"GET",headers:{"Content-Type":"application/json"},signal:n})}catch(t){throw $.error("Provider initialized failed: "),$.error(t),new Error(`Provider initialize failed url: ${g} `)}if(200===(null==(l=h)?void 0:l.status))return await h.json();const w=await h.json();throw $.error("Provider initialized failed: ",h.status,h.statusText,w),new Error(JSON.stringify(w))}async initializeComputeV1(t,e,a,i,r,n,s,o,c){var l;const d=await this.getEndpoints(i),u=await this.getServiceEndpoints(i,d),h={datasets:t,algorithm:e,payment:{chainId:n,token:s,maxJobDuration:o},consumerAddress:r,environment:a},g=this.getEndpointURL(u,"initializeCompute")?this.getEndpointURL(u,"initializeCompute").urlPath:null;if(!g)return null;let w;try{w=await M(g,{method:"POST",body:JSON.stringify(h),headers:{"Content-Type":"application/json"},signal:c})}catch(t){throw $.error("Initialize compute failed: "),$.error(t),new Error("ComputeJob cannot be initialized")}if(null!=(l=w)&&l.ok)return await w.json();const p=await w.json();throw $.error("Initialize compute failed: ",w.status,w.statusText,p),$.error("Payload was:",JSON.stringify(h)),new Error(JSON.stringify(p))}async initializeCompute(t,e,a,i,r,n,s,o,c,l,d){var u,h;const g=await this.getEndpoints(n),w=await this.getServiceEndpoints(n,g),p=this.getEndpointURL(w,"initializeCompute")?this.getEndpointURL(w,"initializeCompute").urlPath:null;if(!p)return null;const m=await this.getConsumerAddress(s),f=(await this.getNonce(n,m,d,g,w)+1).toString();let y=m;y+=null==(u=t[0])?void 0:u.documentId,y+=f;const v={datasets:t,algorithm:e,environment:a,payment:{chainId:c,token:i,resources:o},maxJobDuration:r,consumerAddress:m,signature:await this.getSignature(s,y)};let k;l&&(v.policyServer=l);try{if(console.log("Initialize compute url:",p),k=await M(p,{method:"POST",body:JSON.stringify(v),headers:{"Content-Type":"application/json",Authorization:this.getAuthorization(s)},signal:d}),console.log("Raw response:",k),!k.ok){const t=await k.text();throw new Error(`${t}`)}}catch(t){throw $.error("Initialize compute failed: "),$.error(t),new Error(`ComputeJob cannot be initialized: ${t.message}.`)}if(null!=(h=k)&&h.ok)return await k.json();const T=await k.json();throw $.error("Initialize compute failed: ",k.status,k.statusText,T),$.error("Payload was:",JSON.stringify(v)),new Error(JSON.stringify(T))}async getDownloadUrl(t,e,a,i,r,n,s,o){const c=await this.getEndpoints(r),l=await this.getServiceEndpoints(r,c),d=this.getEndpointURL(l,"download")?this.getEndpointURL(l,"download").urlPath:null;if(!d)return null;const u=await this.getConsumerAddress(n),h=(await this.getNonce(r,u,null,c,l)+1).toString(),g=await this.getSignature(n,t+h);let w=d;return w+=`?fileIndex=${a}`,w+=`&documentId=${t}`,w+=`&transferTxId=${i}`,w+=`&serviceId=${e}`,w+=`&consumerAddress=${u}`,w+=`&nonce=${h}`,s&&(w+="&policyServer="+encodeURI(JSON.stringify(s))),w+=`&signature=${g}`,o&&(w+="&userdata="+encodeURI(JSON.stringify(o))),w}async computeStartV1(t,e,a,i,r,n,s,o){var c;const l=await this.getEndpoints(t),d=await this.getServiceEndpoints(t,l),u=this.getEndpointURL(d,"computeStart")?this.getEndpointURL(d,"computeStart").urlPath:null,h=await e.getAddress(),g=(await this.getNonce(t,h,n,l,d)+1).toString();let w=h;w+=i.documentId,w+=g;const p=await this.signProviderRequest(e,w),m=Object();if(m.consumerAddress=h,m.signature=p,m.nonce=g,m.environment=a,m.dataset=i,m.algorithm=r,s&&(m.additionalDatasets=s),o&&(m.output=o),!u)return null;let f;try{f=await M(u,{method:"POST",body:JSON.stringify(m),headers:{"Content-Type":"application/json"},signal:n})}catch(t){throw $.error("Compute start failed:"),$.error(t),$.error("Payload was:",m),new Error("HTTP request failed calling Provider")}return null!=(c=f)&&c.ok?await f.json():($.error("Compute start failed: ",f.status,f.statusText,await f.json()),$.error("Payload was:",m),null)}async computeStart(t,e,a,i,r,n,s,o,c,l,d,u,h,g,w){var p,m;console.log("called new compute start method..."),console.log("datasets: ",i),console.log("algorithm: ",r);const f=await this.getEndpoints(t),y=await this.getServiceEndpoints(t,f),v=this.getEndpointURL(y,"computeStart")?this.getEndpointURL(y,"computeStart").urlPath:null;if(!v)return $.error("Compute start failed: Cannot get proper computeStart route (perhaps not implemented on provider?)"),null;const k=await this.getConsumerAddress(e),T=(await this.getNonce(t,k,g,f,y)+1).toString(),b=String(k+(null==(p=i[0])?void 0:p.documentId)+T),S=await this.getSignature(e,b),E=Object();let A;E.consumerAddress=k,E.signature=S,E.nonce=T,E.environment=a,E.maxJobDuration=n,E.resources=o,E.dataset=i[0],E.datasets=i,E.algorithm=r,E.chainId=c,E.payment={chainId:c,token:s,maxJobDuration:n},o&&(E.resources=o),l&&(E.metadata=l),d&&(E.additionalViewers=d),u&&(E.output=u),h&&(E.policyServer=h),w&&(E.queueMaxWaitTime=w);try{A=await M(v,{method:"POST",body:JSON.stringify(E),headers:{"Content-Type":"application/json",Authorization:this.getAuthorization(e)},signal:g})}catch(t){throw $.error("Compute start failed:"),$.error(t),$.error("Payload was:",E),new Error("HTTP request failed calling Provider")}if(null!=(m=A)&&m.ok)return await A.json();const F=await A.json();throw $.error("Compute start failed: ",A.status,A.statusText,F),$.error("Payload was:",E),new Error(JSON.stringify(F))}async freeComputeStart(t,e,a,i,r,n,s,o,c,l,d,u){var h;console.log("called new free compute start method..."),console.log("datasets: ",i),console.log("algorithm: ",r);const g=await this.getEndpoints(t),w=await this.getServiceEndpoints(t,g),p=this.getEndpointURL(w,"freeCompute")?this.getEndpointURL(w,"freeCompute").urlPath:null;if(!p)return $.error("Compute start failed: Cannot get proper computeStart route (perhaps not implemented on provider?)"),null;const m=await this.getConsumerAddress(e),f=(await this.getNonce(t,m,d,g,w)+1).toString(),y=f;console.log("signatureMessage: ",y);const v=await this.getSignature(e,y),k=Object();let T;k.consumerAddress=m,k.signature=v,k.nonce=f,k.environment=a,k.resources=n,k.dataset=i[0],k.datasets=i,k.algorithm=r,s&&(k.metadata=s),o&&(k.additionalViewers=o),k.output=c,l&&(k.policyServer=l),u&&(k.queueMaxWaitTime=u);try{T=await M(p,{method:"POST",body:JSON.stringify(k),headers:{"Content-Type":"application/json",Authorization:this.getAuthorization(e)},signal:d})}catch(t){throw $.error("Compute start failed:"),$.error(t),$.error("Payload was:",k),new Error("HTTP request failed calling Provider")}if(null!=(h=T)&&h.ok)return await T.json();const b=await T.json();throw $.error("Compute start failed: ",T.status,T.statusText,b),$.error("Payload was:",k),new Error(JSON.stringify(b))}async computeStreamableLogs(t,e,a,i){var r,n;const s="string"==typeof e,o=await this.getEndpoints(t),c=await this.getServiceEndpoints(t,o),l=this.getEndpointURL(c,"computeStreamableLogs")?this.getEndpointURL(c,"computeStreamableLogs").urlPath:null;if(!l)return $.error("Compute start failed: Cannot get proper computeStreamableLogs route (perhaps not implemented on provider?)"),null;const d=await this.getConsumerAddress(e),u=(await this.getNonce(t,d,i,o,c)+1).toString();let h,g=`?consumerAddress=${d}&jobId=${a}`;if(!s){const t=`${d}${a}${u}`;g+=`&signature=${await this.getSignature(e,t)}`,g+=`&nonce=${u}`}try{h=await M(l+g,{method:"GET",headers:{"Content-Type":"application/json",Authorization:this.getAuthorization(e)},signal:i}),console.log("Raw response:",h)}catch(t){throw $.error("computeStreamableLogs failed:"),$.error(t),new Error("HTTP request failed calling Provider")}return null!=(r=h)&&r.ok||200===(null==(n=h)?void 0:n.status)?(console.log("Response body:",h.body),h.body):($.error("computeStreamableLogs failed: ",h.status,h.statusText,await h.json()),null)}async getComputeStartRoutes(t,e=!1){const a=await this.getEndpoints(t),i=await this.getServiceEndpoints(t,a);let r=null;return r=e?this.getEndpointURL(i,"freeCompute")?this.getEndpointURL(i,"freeCompute").urlPath:null:this.getEndpointURL(i,"computeStart")?this.getEndpointURL(i,"computeStart").urlPath:null,r}async computeStop(t,e,a,i,r){var n;const s="string"==typeof a,o=await this.getEndpoints(e),c=await this.getServiceEndpoints(e,o),l=this.getEndpointURL(c,"computeStop")?this.getEndpointURL(c,"computeStop").urlPath:null,d=await this.getConsumerAddress(a),u=(await this.getNonce(e,d,r,o,c)+1).toString(),h=d+(t||""),g=await this.getSignature(a,h),w=new URLSearchParams;w.set("consumerAddress",d),w.set("nonce",u),w.set("jobId",t),s||w.set("signature",g),i&&w.set("agreementId",i);const p=w.toString();if(!p)return null;let m;try{m=await M(l+"?"+p,{method:"PUT",headers:{"Content-Type":"application/json",Authorization:this.getAuthorization(a)},signal:r})}catch(t){throw $.error("Compute stop failed:"),$.error(t),new Error("HTTP request failed calling Provider")}if(null!=(n=m)&&n.ok)return await m.json();const f=await m.json();throw $.error("Compute stop failed: ",m.status,m.statusText,f),new Error(JSON.stringify(f))}async computeStatus(t,e,a,i,r,n){var s,o;const c=await this.getEndpoints(t),l=await this.getServiceEndpoints(t,c),d=this.getEndpointURL(l,"computeStatus")?this.getEndpointURL(l,"computeStatus").urlPath:null;let u,h=`?consumerAddress=${e}`;if(h+=i&&`&agreementId=${i}`||"",h+=a&&`&jobId=${a}`||"",!d)return null;try{console.log("computeStatusUrl: ",d+h),u=await M(d+h,{method:"GET",headers:{"Content-Type":"application/json",Authorization:n},signal:r})}catch(t){throw $.error("Get compute status failed"),$.error(t),new Error(t)}if(null!=(s=u)&&s.ok)return await u.json();if($.error("Get compute status failed:",u.status,u.statusText),null!=(o=u)&&o.ok)return await u.json();const g=await u.json();throw $.error("Get compute status failed:",u.status,u.statusText,g),new Error(JSON.stringify(g))}async getComputeResultUrl(t,e,a,i){const r="string"==typeof e,n=await this.getEndpoints(t),s=await this.getServiceEndpoints(t,n),o=this.getEndpointURL(s,"computeResult")?this.getEndpointURL(s,"computeResult").urlPath:null,c=await this.getConsumerAddress(e),l=(await this.getNonce(t,c,null,n,s)+1).toString();let d=c;d+=a,d+=i.toString(),d+=l;const u=await this.getSignature(e,d);if(!o)return null;let h=o;return h+=`?consumerAddress=${c}`,h+=`&jobId=${a}`,h+=`&index=${i.toString()}`,r||(h+=`&nonce=${l}`,h+=`&signature=${u}`),h}async computeDelete(t,e,a,i,r){var n;const s=await this.getEndpoints(i),o=await this.getServiceEndpoints(i,s),c=this.getEndpointURL(o,"computeDelete")?this.getEndpointURL(o,"computeDelete").urlPath:null,l=await this.getConsumerAddress(e),d=(await this.getNonce(i,l,r,s,o)+1).toString();let u=l;u+=a||"",u+=t&&`${this.noZeroX(t)}`||"",u+=d;const h=await this.getSignature(e,u),g=Object();if(g.documentId=t,g.consumerAddress=l,g.jobId=a,h&&(g.signature=h),!c)return null;let w;try{w=await M(c,{method:"DELETE",body:JSON.stringify(g),headers:{"Content-Type":"application/json",Authorization:this.getAuthorization(e)},signal:r})}catch(t){throw $.error("Delete compute job failed:"),$.error(t),$.error("Payload was:",g),new Error("HTTP request failed calling Provider")}if(null!=(n=w)&&n.ok)return await w.json();const p=await w.json();throw $.error("Delete compute job failed:",w.status,w.statusText,p),$.error("Payload was:",g),new Error(JSON.stringify(p))}async generateAuthToken(t,e,a){const i=await t.getAddress(),r=await this.getEndpoints(e),n=await this.getServiceEndpoints(e,r),s=this.getEndpointURL(n,"generateAuthToken").urlPath||null,o=(await this.getNonce(e,i,a,r,n)+1).toString(),c=i+o,l=await this.signProviderRequest(t,c);try{const t=await M(s,{method:"POST",body:JSON.stringify({address:i,signature:l,nonce:o}),headers:{"Content-Type":"application/json"},signal:a});if(null==t||!t.ok)throw new Error(`Failed to generate auth token: ${t.status} ${t.statusText}`);const e=await t.json();return null==e?void 0:e.token}catch(t){throw $.error("Generate auth token failed:"),$.error(t),new Error("HTTP request failed calling Provider")}}async invalidateAuthToken(t,e,a,i){const r=await t.getAddress(),n=await this.getEndpoints(a),s=await this.getServiceEndpoints(a,n),o=this.getEndpointURL(s,"invalidateAuthToken").urlPath||null,c=(await this.getNonce(a,r,i,n,s)+1).toString(),l=r+c,d=await this.signProviderRequest(t,l);try{const t=await M(o,{method:"POST",body:JSON.stringify({address:r,signature:d,token:e,nonce:c}),headers:{"Content-Type":"application/json"},signal:i});if(null==t||!t.ok)throw new Error(`Failed to invalidate auth token: ${t.status} ${t.statusText}`);return await t.json()}catch(t){throw $.error("Generate auth token failed:"),$.error(t),new Error("HTTP request failed calling Provider")}}async isValidProvider(t,e){try{const a=await M(t,{method:"GET",headers:{"Content-Type":"application/json"},signal:e});if(null!=a&&a.ok){const t=await a.json();if(t&&(t.providerAddress||t.providerAddresses))return!0}return!1}catch(t){return $.error(`Error validating provider: ${t.message}`),!1}}async PolicyServerPassthrough(t,e,a){var i;const r=await this.getEndpoints(t),n=await this.getServiceEndpoints(t,r),s=this.getEndpointURL(n,"PolicyServerPassthrough")?this.getEndpointURL(n,"PolicyServerPassthrough").urlPath:null;if(!s)return null;let o;try{if(o=await M(s,{method:"POST",body:JSON.stringify(e),headers:{"Content-Type":"application/json"},signal:a}),!o.ok){const t=await o.text();throw new Error(`${t}`)}}catch(t){throw $.error("PolicyServerPassthrough failed: "),$.error(t),new Error(`PolicyServerPassthrough failed: ${t.message}.`)}if(null!=(i=o)&&i.ok)return await o.json();const c=await o.json();throw $.error("PolicyServerPassthrough failed: ",o.status,o.statusText,c),$.error("Payload was:",JSON.stringify(e)),new Error(JSON.stringify(c))}async initializePSVerification(t,e,a){var i;const r=await this.getEndpoints(t),n=await this.getServiceEndpoints(t,r),s=this.getEndpointURL(n,"initializePSVerification")?this.getEndpointURL(n,"initializePSVerification").urlPath:null;if(!s)return null;let o;try{if(o=await M(s,{method:"POST",body:JSON.stringify(e),headers:{"Content-Type":"application/json"},signal:a}),!o.ok){const t=await o.text();throw new Error(`${t}`)}}catch(t){throw $.error("initializePSVerification failed: "),$.error(t),new Error(`initializePSVerification failed: ${t.message}.`)}if(null!=(i=o)&&i.ok)return await o.json();const c=await o.json();throw $.error("initializePSVerification failed: ",o.status,o.statusText,c),$.error("Payload was:",JSON.stringify(e)),new Error(JSON.stringify(c))}noZeroX(t){return this.zeroXTransformer(t,!1)}zeroXTransformer(t="",e){const{valid:a,output:i}=this.inputMatch(t,/^(?:0x)*([a-f0-9]+)$/i,"zeroXTransformer");return(e&&a?"0x":"")+i}inputMatch(t,e,a){if("string"!=typeof t)throw $.debug("Not input string:"),$.debug(t),new Error(`[${a}] Expected string, input type: ${typeof t}`);const i=t.match(e);return i?{valid:!0,output:i[1]}:($.warn(`[${a}] Input transformation failed.`),{valid:!1,output:t})}async getData(t,e){return M(t,{method:"GET",headers:{"Content-type":"application/json",Authorization:e}})}}const Nt=new Ot;function Pt(t,e){return t=d(t),`did:op:${P(t+e.toString(10)).toString()}`}function Rt(t){return P(t).toString()}function Ut(t){const e=new XMLHttpRequest;e.responseType="blob",e.open("GET",t),e.onload=()=>{const t=e.getResponseHeader("content-disposition"),a=null==t?void 0:t.match(/filename[^;=\n]*=((['"]).*?\2|[^;\n]*)/),i=a&&a[1]?a[1]:"file",r=window.URL.createObjectURL(e.response),n=document.createElement("a");n.href=r,n.setAttribute("download",i),document.body.appendChild(n),n.click(),n.remove(),window.URL.revokeObjectURL(r)},e.send()}async function It(t,e){const a=await fetch(t);if(!a.ok)throw new Error("Response error.");let i;try{i=a.headers.get("content-disposition").match(/attachment;filename=(.+)/)[1]}catch(a){try{i=t.split("/").pop()}catch(t){i=`file${e}`}}return{data:await a.arrayBuffer(),filename:i}}async function Lt(t,e,i,r,n,s,o=!1,c,l){const d=new a.Contract(r,W,t);if(!o){const e=await _t(t,r,i,n);if(new m(e).greaterThanOrEqualTo(new m(s)))return new m(e).toNumber()}const u=await et(t,r,s,c),h=await d.approve.estimateGas(n,u);return l?new m(h.toString()):await it(h,t,null==e?void 0:e.gasFeeMultiplier,d.approve,n,u)}async function jt(t,e,i,r,n,s,o=!1,c){const l=new a.Contract(r,W,t);if(!o){const e=await zt(t,r,i,n);if(new p(e).isGreaterThan(new p(s)))return BigInt(e)}let d=null;const u=await l.approve.estimateGas(n,s);if(c)return u;try{d=await it(u,t,null==e?void 0:e.gasFeeMultiplier,l.approve,n,s)}catch(t){$.error(`ERROR: Failed to approve spender to spend tokens : ${t.message}`)}return d}async function Gt(t,e,i,r,n,s,o){const c=new a.Contract(i,W,t),l=await et(t,i,n,s),d=await c.transfer.estimateGas(r,l);return o?d:await it(d,t,null==e?void 0:e.gasFeeMultiplier,c.transfer,r,l)}async function _t(t,e,i,r,n){const s=new a.Contract(e,W,t),o=await s.allowance(i,r);return await tt(t,e,o,n)}async function $t(t,e,i,r){const n=new a.Contract(e,W,t),s=await n.balanceOf(i);return await tt(t,e,s,r)}async function zt(t,e,i,r){const n=new a.Contract(e,W,t);return await n.allowance(i,r)}async function Bt(t,e){const i=new a.Contract(e,W,t),r=await i.decimals();return Number(r)}const qt={datasets:{invalid:"Datasets is not a list, as expected"},algorithm:{serviceId:{missing:"The serviceId key is missing from the algorithm s DDO.",not_found:"The provided serviceId does not exist.",service_not_access_compute:"Service type is neither access, nor compute.",main_service_compute:"If the main service is not compute for this asset when calling initialize endpoint.",compute_services_not_in_same_provider:"Files attached to the compute service are not decrypted by the correct provider. This occurs when both asset and algorithm are requested by their compute service which cannot be decrypted by a single provider as how it is supposed to be."},container:{checksum_prefix:"Container checksum does not start with the prefix sha256:.",mising_entrypoint_image_checksum:"Either entrypoint, either image, or either checksum are missing from the container dictionary from the algorithm s DDO."},documentId:{did_not_found:"The algorithm s DID could not be retrieved from the metadata store, because the algorithm asset does not exist.",missing:"The documentId key is missing from the algorithm s DDO."},transferTxId:{missing:"The transferTxId key is missing from the algorithm s DDO."},missing_meta_documentId:"Either algorithm metadata, or algorithm DID are missing.",did_not_found:"Either algorithm metadata, or algorithm DID are missing.",not_algo:"Either algorithm metadata, or algorithm DID are missing.",in_use_or_not_on_chain:"Either algorithm metadata, or algorithm DID are missing.",meta_oneof_url_rawcode_remote:"Either algorithm metadata, or algorithm DID are missing.",file_unavailable:"One possibility is that the asset could not be retrieved from Aquariuss database. Otherwise, there are issues related to services"},error:{not_trusted_algo_publisher:"The owner of the algorithm's DDO is not a trusted algorithms publishers list.",not_trusted_algo:"The algorithm's DID is not in the asset's trusted algorithms dictionary. ",no_publisherTrustedAlgorithms:"The algorithm's key publisherTrustedAlgorithms does not exist in the algorithm's DDO.",algorithm_file_checksum_mismatch:"filesChecksum from the algorithm's DDO is invalid.",algorithm_container_checksum_mismatch:"The containerChecksum from the algorithm's DDO is invalid.",no_raw_algo_allowed:"The asset does not allow raw algorithms to be run on it.","Asset malformed":"The asset published on chain is malformed, missing some required keys or not compliant with our schemas.","Asset is not consumable.":"Assets metadata status is not in the range of valid status codes for assets. The recognized states for the metadata are defined on our docs.","DID is not a valid algorithm.":"Either the algorithm assets DID is incorrectly typed, either the algorithm timeout expired.","Compute environment does not exist.":"The compute environment provided by the user does not exist, it is not served by our compute-to-data feature. The user can use get_c2d_environments to check the list of available compute environments.","The validUntil value is not correct.":"validUntil value is most probably expired.","Cannot resolve DID":"The dataset DID does not exist in the Metadata store.","Invalid serviceId":"The serviceId of that dataset is not correct.","Unable to get dataset files":"The files of that dataset could not be decrypted or retrieved","cannot decrypt files for this service.":"The files of that dataset could not be decrypted due to the fact that file object, which contains the structure and the type of specific file, is missing from the validation part.","Unsupported type ":"The file object type is not supported by Provider.","malformed file object":"The file object structure is invalid and does not contain the wanted information for the specific file."},order:{fees_not_paid:" Provider fees are not paid."},output:{invalid:"The algorithms validation after the build stage has not been decoded properly as a dictionary."}};function Jt(t){try{const a=JSON.parse(t),i=Object.keys(a)[0];if("error"===i){var e;const t=a[i];return(null==(e=qt[i])?void 0:e[t])||`Provider request failed: ${t}`}{const t=a[i];return`${a[Object.keys(a)[1]]} : ${t}`}}catch(e){return $.error("[getErrorMessage] error: ",e),t}}async function Wt(t,e,a,i,r,n,s,o,c="0",l=0,d=0,u=0){const h=O.getDDOClass(t),{datatokens:g}=h.getAssetFields(),{chainId:w,services:p}=h.getDDOFields();s||(s={consumeMarketFeeAddress:"0x0000000000000000000000000000000000000000",consumeMarketFeeAmount:"0",consumeMarketFeeToken:"0x0000000000000000000000000000000000000000"});const f=(await e.provider.getNetwork()).chainId;if(w!==Number(f))throw new Error("Chain ID from DDO is different than the configured network.");if(!g[l].address)throw new Error(`The datatoken with index: ${l} does not exist for the asset with did: ${t.id}`);if(!p[d].id)throw new Error(`There is no service with index: ${d} defined for the asset with did: ${t.id}`);const y=await i.getId(g[l].address),v=await i.getFixedRates(g[l].address),k=await i.getDispensers(g[l].address),T=await i.getPublishingMarketFee(g[l].address),b=v.length>0?"fixed":k.length>0?"free":"NOT_ALLOWED",S=o||(await Nt.initialize(t.id,p[d].id,0,await e.getAddress(),r||a.oceanNodeUri)).providerFee;if(S&&S.providerFeeAddress!==ot&&S.providerFeeAmount&&parseInt(S.providerFeeAmount)>0)try{await jt(e,a,await e.getAddress(),S.providerFeeToken,p[0].datatokenAddress,S.providerFeeAmount)}catch(t){throw new Error(`Failed to approve provider fee token ${S.providerFeeToken}`)}const E={consumer:n||await e.getAddress(),serviceIndex:d,_providerFee:S,_consumeMarketFee:s};switch(b){case"free":if(1===y){const t=new st(a.dispenserAddress,e),r=await t.dispense(g[l].address,"1",await e.getAddress());if(!r)throw new Error("Failed to dispense !");return await r.wait(),await i.startOrder(g[l].address,E.consumer,E.serviceIndex,E._providerFee,E._consumeMarketFee)}if(2===y||4===y)return await i.buyFromDispenserAndOrder(p[d].datatokenAddress,E,a.dispenserAddress);break;case"fixed":{const r=new ut(a.fixedRateExchangeAddress,e);if(!v[u].id)throw new Error(`There is no fixed rate exchange with index: ${d} for the asset with did: ${t.id}`);const n=await r.getFeesInfo(v[u].id),o=await r.getExchange(v[u].id),{baseTokenAmount:h}=await r.calcBaseInGivenDatatokensOut(n.exchangeId,"1",s.consumeMarketFeeAmount),w=new m(+h||0).add(new m(s.consumeMarketFeeAmount||0)).add(new m(+T.publishMarketFeeAmount||0)).toString(),p={exchangeContract:a.fixedRateExchangeAddress,exchangeId:n.exchangeId,maxBaseTokenAmount:w,baseTokenAddress:o.baseToken,baseTokenDecimals:parseInt(o.btDecimals)||18,swapMarketFee:c,marketFeeAddress:T.publishMarketFeeAddress};if(1===y){const t=await Lt(e,a,await e.getAddress(),o.baseToken,a.fixedRateExchangeAddress,w,!1);if(!("number"!=typeof t?await t.wait():t))throw new Error(`Failed to approve ${o.baseToken} !`);const n=await r.buyDatatokens(o.exchangeId,"1",w,T.publishMarketFeeAddress,c);if(!await n.wait())throw new Error("Failed to buy datatoken from fixed rate!");return await i.startOrder(g[l].address,E.consumer,E.serviceIndex,E._providerFee,E._consumeMarketFee)}if(2===y||4===y){const t=await Lt(e,a,await e.getAddress(),o.baseToken,g[l].address,w,!1);if(!t)throw new Error(`Failed to approve ${o.baseToken} !`);if(!("number"!=typeof t?await t.wait():t))throw new Error("Failed to confirm/mine approval transaction!");return await i.buyFromFreAndOrder(g[l].address,E,p)}break}default:throw new Error("Pricing schema not supported !")}}const Vt=8996;function Ht(t){const e=(new J).getConfig(t);return e&&"oasis"===e.sdk}async function Zt(t,e,i,r,n,o,l=!0,d,u,h,w,p,m,f,y){var v,k,T;const b=O.getDDOClass(o),{indexedMetadata:S}=b.getAssetFields(),E=(null==(v=b.getDDOData())||null==(v=v.stats)||null==(v=v.price)?void 0:v.value)||(null==S||null==(k=S.stats[0])||null==(k=k.prices[0])?void 0:k.price);let{chainId:F,nftAddress:C}=b.getDDOFields();const{services:x}=b.getDDOFields();if("string"!=typeof n&&"number"!=typeof n)throw new Error('Invalid template! Must be a "number" or a "string"');const D=(await i.provider.getNetwork()).chainId;if(F&&F!==Number(D))throw new Error("Chain ID from DDO is different than the configured network.");const M=(new J).getConfig(parseInt(String(D)));let N=await yt(i,M.nftFactoryAddress,n,Number(D));if(N<1){if(8996!==Number(D))throw new Error(`Invalid template index: ${N}`);N=1}const P=new vt(i,Number(D)),I=new pt(M.nftFactoryAddress,i,Number(D)),L=await i.getAddress(),j={name:t,symbol:e,templateIndex:1,tokenURI:"aaa",transferable:!0,owner:L},G={templateIndex:N,cap:"100000",feeAmount:"0",paymentCollector:L,feeToken:u||M.oceanTokenAddress,minter:L,mpFeeAddress:ot};let _;null!=r&&r.files[0].type&&[U.ARWEAVE,U.IPFS,U.URL].includes(null==r||null==(T=r.files[0])||null==(T=T.type)?void 0:T.toLowerCase())||(console.log('Missing or invalid files object type, defaulting to "url"'),r.type=U.URL),"oasis"===M.sdk&&(G.filesObject=r,G.accessListFactory=w||M.accessListFactory,G.allowAccessList=p,G.denyAccessList=m);try{if(E)if("0"===E.toString()){const t={dispenserAddress:M.dispenserAddress,maxTokens:"1",maxBalance:"100000000",withMint:!0,allowedSwapper:ot};_=await I.createNftWithDatatokenWithDispenser(j,G,t)}else{const t=f||M.oceanTokenAddress;y||(y=await Y(this.signer,t));const e={fixedRateAddress:M.fixedRateExchangeAddress,baseTokenAddress:t,owner:L,marketFeeCollector:L,baseTokenDecimals:y,datatokenDecimals:18,fixedRate:E.toString(),marketFee:"0",allowedConsumer:L,withMint:!0};_=await I.createNftWithDatatokenWithFixedRate(j,G,e)}else _=await I.createNftWithDatatoken(j,G)}catch(t){return console.log("ERROR creating NFT bundle",t),null}const $=await _.wait(),z=at($,"NFTCreated"),B=at($,"TokenCreated"),q=z.args.newTokenAddress,W=B.args.newTokenAddress;if(r.datatokenAddress=W,r.nftAddress=q,"oasis"===M.sdk){const t=new a.Contract(W,A.abi,i);try{const e=await t.setFilesObject(s(JSON.stringify(r)));e.wait&&await e.wait()}catch(t){return console.log("Error updating files object with data token and nft addresses: ",t),null}}x[0].files="oasis"===M.sdk?"":await Nt.encrypt(r,Number(D),d,i,null),x[0].datatokenAddress=W,x[0].serviceEndpoint=d,C=q;const V=b.makeDid(C,F.toString());let H,Z,X;if(o=b.updateFields({id:V,nftAddress:C}),l)H=await Nt.encrypt(o,Number(D),d,i,null),Z=(await h.validate(o,i,d)).hash,X=2;else{const t=JSON.stringify(o),e=Buffer.from(t);H=c(e),Z="0x"+R("sha256").update(H).digest("hex"),X=0}return await P.setMetadata(C,await i.getAddress(),0,d,"",g(X),H,Z),o.id}async function Xt(t,e,i){const r=new a.Contract(t,C.abi,e),n=await e.getAddress();try{const t=await r.deployAccessListContract("AllowList","ALLOW",!0,n,i||[n],["https://oceanprotocol.com/nft/"]);if(t&&t.wait)return at(await t.wait(),"NewAccessList").args[0]}catch(t){console.log("ERROR createAccessListFactory(): ",t)}return null}export{bt as AccessListContract,St as AccesslistFactory,Mt as Aquarius,j as Config,J as ConfigHelper,Vt as DEVELOPMENT_CHAIN_ID,kt as Datatoken,Tt as Datatoken4,st as Dispenser,I as EncryptMethod,At as EnterpriseFeeCollectorContract,Et as EscrowContract,dt as FEE_HISTORY_NOT_SUPPORTED,U as FileObjectType,ut as FixedRateExchange,ct as GASLIMIT_DEFAULT,q as KNOWN_CONFIDENTIAL_EVMS,L as LogLevel,_ as Logger,$ as LoggerInstance,lt as MAX_UINT_256,vt as Nft,pt as NftFactory,Ot as Provider,Nt as ProviderInstance,ht as Router,rt as SmartContract,nt as SmartContractWithAddress,ot as ZERO_ADDRESS,_t as allowance,zt as allowanceWei,et as amountToUnits,Lt as approve,jt as approveWei,$t as balance,yt as calculateActiveTemplateIndex,B as configHelperNetworks,Xt as createAccessListFactory,Zt as createAsset,Bt as decimals,It as downloadFile,Ut as downloadFileBrowser,Pt as generateDid,wt as generateDtName,Jt as getErrorMessage,at as getEventFromTx,Q as getFairGasPrice,Rt as getHash,mt as getOceanArtifactsAddresses,ft as getOceanArtifactsAddressesByChainId,Y as getTokenDecimals,Ct as isDefined,W as minAbi,Wt as orderAsset,it as sendTx,K as setContractDefaults,xt as signHash,Dt as signRequest,Ft as sleep,Gt as transfer,tt as unitsToAmount,Ht as useOasisSDK};
|
|
2
2
|
//# sourceMappingURL=lib.modern.js.map
|