Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Use createAsset function from SDK. #73

Open
wants to merge 21 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 9 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 7 additions & 8 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,7 @@
},
"dependencies": {
"@oceanprotocol/contracts": "^2.0.4",
"@oceanprotocol/lib": "^3.4.1",
"@oceanprotocol/lib": "^3.4.3",
"cross-fetch": "^3.1.5",
"crypto-js": "^4.1.1",
"decimal.js": "^10.4.1",
Expand Down
14 changes: 5 additions & 9 deletions src/commands.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import fs from "fs";
import os from "os";
import util from "util";
import {
createAsset,
createAssetUtil,
handleComputeOrder,
updateAssetMetadata,
downloadFile,
Expand Down Expand Up @@ -92,17 +92,15 @@ export class Commands {
const encryptDDO = args[2] === "false" ? false : true;
try {
// add some more checks
const urlAssetId = await createAsset(
const urlAssetId = await createAssetUtil(
asset.nft.name,
asset.nft.symbol,
this.signer,
asset.services[0].files,
asset,
this.providerUrl,
this.providerUrl || this.macOsProviderUrl,
this.config,
this.aquarius,
1,
this.macOsProviderUrl,
encryptDDO
);
console.log("Asset published. ID: " + urlAssetId);
Expand All @@ -124,17 +122,15 @@ export class Commands {
}
const encryptDDO = args[2] === "false" ? false : true;
// add some more checks
const algoDid = await createAsset(
const algoDid = await createAssetUtil(
algoAsset.nft.name,
algoAsset.nft.symbol,
this.signer,
algoAsset.services[0].files,
algoAsset,
this.providerUrl,
this.providerUrl || this.macOsProviderUrl,
this.config,
this.aquarius,
1,
this.macOsProviderUrl,
encryptDDO
);
// add some more checks
Expand Down
169 changes: 16 additions & 153 deletions src/helpers.ts
Original file line number Diff line number Diff line change
@@ -1,17 +1,12 @@
import { SHA256 } from "crypto-js";
import { ethers, Signer } from "ethers";
import fetch from "cross-fetch";
import { promises as fs } from "fs";
import { createHash } from "crypto";
import * as path from "path";
import * as sapphire from '@oasisprotocol/sapphire-paratime';
import {
AccesslistFactory,
Aquarius,
DatatokenCreateParams,
Nft,
NftCreateData,
NftFactory,
ProviderInstance,
ZERO_ADDRESS,
approveWei,
Expand All @@ -22,14 +17,12 @@
DDO,
orderAsset,
getEventFromTx,
DispenserCreationParams,
FreCreationParams,
DownloadResponse,
Asset,
ProviderFees,
ComputeAlgorithm,
LoggerInstance,
Datatoken4
createAsset
} from "@oceanprotocol/lib";
import { hexlify } from "ethers/lib/utils";

Expand Down Expand Up @@ -67,176 +60,46 @@
return { data, filename };
}

export async function createAsset(
export async function createAssetUtil(
name: string,
symbol: string,
owner: Signer,
assetUrl: any,

Check warning on line 67 in src/helpers.ts

View workflow job for this annotation

GitHub Actions / lint

Unexpected any. Specify a different type
ddo: any,

Check warning on line 68 in src/helpers.ts

View workflow job for this annotation

GitHub Actions / lint

Unexpected any. Specify a different type
providerUrl: string,
config: Config,
aquariusInstance: Aquarius,
encryptDDO: boolean = true,
templateIndex: number = 1,
providerFeeToken: string = ZERO_ADDRESS,
accessListFactory?: string,
allowAccessList?: string,
denyAccessList?: string,
macOsProviderUrl?: string,
encryptDDO: boolean = true,

) {
const { chainId } = await owner.provider.getNetwork();
const nft = new Nft(owner, chainId);
const nftFactory = new NftFactory(config.nftFactoryAddress, owner);

let wrappedSigner
let allowListAddress
if(templateIndex === 4){
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

this should be the template id or the template address...
template index is something else (and must be calculated on SDK side)
might work, but is not exactly the same

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

the name is misleading, it should be template id, correct, I'll update this.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think this still needs to be updated

// Wrap the signer for Sapphire
wrappedSigner = sapphire.wrap(owner);
const wrappedSigner = sapphire.wrap(owner);

// Create Access List Factory
const accessListFactory = new AccesslistFactory(config.accessListFactory, wrappedSigner, chainId);
const accessListFactoryObj = new AccesslistFactory(config.accessListFactory, wrappedSigner, chainId);

// Create Allow List
allowListAddress = await accessListFactory.deployAccessListContract(
await accessListFactoryObj.deployAccessListContract(
Copy link
Contributor

@paulo-ocean paulo-ocean Nov 19, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

are we sure about these params?
config.accessListFactory
allowAccessList
denyAccessList
if they do not match probably there will be errors at smart contract level (not sure if console.log will help if the issue is on those)
btw, there is a function to deploy the access list on the SDK as well
export async function createAccessListFactory(
we could probably just use that one instead

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

As far as I double-checked, I put them in place to match createAsset from ocean.js

Copy link
Contributor

@paulo-ocean paulo-ocean Nov 25, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

its not about the order of the params:
accessListFactoryObj, allowAccessList and denyAccessList should be contract addresses (strings)

Here, you're creating a new access list factory and a new access list deployed from that factory

// Create Access List Factory
		const accessListFactoryObj = new AccesslistFactory(config.accessListFactory, wrappedSigner, chainId);

		// Create Allow List
		await accessListFactoryObj.deployAccessListContract(
			'AllowList',
			'ALLOW',
			['https://oceanprotocol.com/nft/'],
			false,
			await owner.getAddress(),
			[await owner.getAddress(), ZERO_ADDRESS]
		)
		return await createAsset(name, symbol, wrappedSigner, assetUrl, templateIndex, ddo, encryptDDO, providerUrl || macOsProviderUrl, providerFeeToken, aquariusInstance, accessListFactory, allowAccessList, denyAccessList)

But you're calling the function with other values, the factory addresses and the allow access list addresses do not match (you're creating new ones and passing something else)
In fact this code is not doing anything.. you can probably delete most of it
cause you're passing the values received on the function (which are not defined btw)

'AllowList',
'ALLOW',
['https://oceanprotocol.com/nft/'],
false,
await owner.getAddress(),
[await owner.getAddress(), ZERO_ADDRESS]
);
)
return await createAsset(name, symbol, wrappedSigner, assetUrl, templateIndex, ddo, encryptDDO, providerUrl || macOsProviderUrl, providerFeeToken, aquariusInstance, accessListFactory, allowAccessList, denyAccessList);
}

ddo.chainId = parseInt(chainId.toString(10));
const nftParamsAsset: NftCreateData = {
name,
symbol,
templateIndex,
tokenURI: "aaa",
transferable: true,
owner: await owner.getAddress(),
};
const datatokenParams: DatatokenCreateParams = {
templateIndex,
cap: "100000",
feeAmount: "0",
paymentCollector: await owner.getAddress(),
feeToken: config.oceanTokenAddress,
minter: await owner.getAddress(),
mpFeeAddress: ZERO_ADDRESS,
};

let bundleNFT;
if (!ddo.stats?.price?.value) {
bundleNFT = await nftFactory.createNftWithDatatoken(
nftParamsAsset,
datatokenParams
);
} else if (ddo?.stats?.price?.value === "0") {
const dispenserParams: DispenserCreationParams = {
dispenserAddress: config.dispenserAddress,
maxTokens: "1",
maxBalance: "100000000",
withMint: true,
allowedSwapper: ZERO_ADDRESS,
};

bundleNFT = await nftFactory.createNftWithDatatokenWithDispenser(
nftParamsAsset,
datatokenParams,
dispenserParams
);
} else {
const fixedPriceParams: FreCreationParams = {
fixedRateAddress: config.fixedRateExchangeAddress,
baseTokenAddress: config.oceanTokenAddress,
owner: await owner.getAddress(),
marketFeeCollector: await owner.getAddress(),
baseTokenDecimals: 18,
datatokenDecimals: 18,
fixedRate: ddo.stats.price.value,
marketFee: "0",
allowedConsumer: await owner.getAddress(),
withMint: true,
};

bundleNFT = await nftFactory.createNftWithDatatokenWithFixedRate(
nftParamsAsset,
datatokenParams,
fixedPriceParams
);
}

const trxReceipt = await bundleNFT.wait();
// events have been emitted
const nftCreatedEvent = getEventFromTx(trxReceipt, "NFTCreated");
const tokenCreatedEvent = getEventFromTx(trxReceipt, "TokenCreated");

const nftAddress = nftCreatedEvent.args.newTokenAddress;
const datatokenAddressAsset = tokenCreatedEvent.args.newTokenAddress;
// create the files encrypted string
assetUrl.datatokenAddress = datatokenAddressAsset;
assetUrl.nftAddress = nftAddress;
ddo.services[0].files = templateIndex === 4 ? '' : await ProviderInstance.encrypt(
assetUrl,
chainId,
macOsProviderUrl || providerUrl
);
ddo.services[0].datatokenAddress = datatokenAddressAsset;
ddo.services[0].serviceEndpoint = providerUrl;

ddo.nftAddress = nftAddress;
ddo.id =
"did:op:" +
SHA256(ethers.utils.getAddress(nftAddress) + chainId.toString(10));

let metadata;
let metadataHash;
let flags;
if (encryptDDO) {
metadata = await ProviderInstance.encrypt(
ddo,
chainId,
macOsProviderUrl || providerUrl
);
const validateResult = await aquariusInstance.validate(ddo);
metadataHash = validateResult.hash;
flags = 2
} else {
const stringDDO = JSON.stringify(ddo);
const bytes = Buffer.from(stringDDO);
metadata = hexlify(bytes);
metadataHash = "0x" + createHash("sha256").update(metadata).digest("hex");
flags = 0
}

await nft.setMetadata(
nftAddress,
await owner.getAddress(),
0,
providerUrl,
"",
ethers.utils.hexlify(flags),
metadata,
metadataHash
);

if(templateIndex === 4){ // Use Datatoken4 for file object
const datatoken = new Datatoken4(
wrappedSigner,
ethers.utils.toUtf8Bytes(JSON.stringify(assetUrl.files)),
chainId,
config
);

// Set file object
await datatoken.setFileObject(datatokenAddressAsset, await wrappedSigner.getAddress());

// Set allow list for the datatoken
await datatoken.setAllowListContract(
datatokenAddressAsset,
allowListAddress,
await wrappedSigner.getAddress()
);}

return ddo.id;
const did = await createAsset(name, symbol, owner, assetUrl, templateIndex, ddo, encryptDDO, providerUrl || macOsProviderUrl, providerFeeToken, aquariusInstance);
console.log('did: ', did)
return did
}


Expand Down
42 changes: 13 additions & 29 deletions src/publishAsset.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ import {
Aquarius,
DDO
} from '@oceanprotocol/lib';
import { createAsset, updateAssetMetadata } from './helpers';
import { createAssetUtil, updateAssetMetadata } from './helpers';

export interface PublishAssetParams {
title: string;
Expand Down Expand Up @@ -44,13 +44,7 @@ export async function publishAsset(params: PublishAssetParams, signer: Signer, c
license: 'MIT',
tags: params.tags
},
stats: {
Copy link
Contributor

@paulo-ocean paulo-ocean Dec 19, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

we turned back the Asset into a DDO, removing the stats..
but by removing this lines:

price: {
          value: params.isCharged ? params.price : "0"
        }

we now have a FixedPrice datatoken instead of Dispenser one
We totally changed the behavior of the previous function
Before it was doing:
bundleNFT = await nftFactory.createNftWithDatatokenWithDispenser(
Now it does always
bundleNFT = await nftFactory.createNftWithDatatokenWithFixedRate(

These changes + the default template of 1 ... breaks download of the asset (on SDK OrderUtils) at least for oasis shappire
you can check the previous version of createAsset here:

export async function createAsset(

and then compare with the SDK one:
https://github.com/oceanprotocol/ocean.js/blob/4437713b2243a87ae1a01730196abc27c872ac24/src/utils/Assets.ts#L46
To make sure we're passing all the relevant/needed parameters
specially the templateIDorAddress and the stats fields are very important

allocated: 0,
orders: 0,
price: {
value: params.isCharged ? params.price : "0"
}
},

services: [
{
id: 'access',
Expand All @@ -62,15 +56,6 @@ export async function publishAsset(params: PublishAssetParams, signer: Signer, c
timeout: Number(params.timeout),
},
],
nft: {
address: "",
name: "Ocean Data NFT",
symbol: "OCEAN-NFT",
state: 5,
tokenURI: "",
owner: "",
created: ""
}
};

// Asset URL setup based on storage type
Expand All @@ -80,18 +65,17 @@ export async function publishAsset(params: PublishAssetParams, signer: Signer, c
files: [{ type: params.storageType, url: params.assetLocation, method: 'GET' }],
};

// Other networks
const did = await createAsset(
params.title,
'OCEAN-NFT',
signer,
assetUrl,
metadata,
params.providerUrl,
config,
aquarius,
params.template || 1
);
// Other networks
const did = await createAssetUtil(
params.title,
'OCEAN-NFT',
signer,
assetUrl,
metadata,
params.providerUrl,
config,
aquarius
);


console.log(`Asset successfully published with DID: ${did}`);
Expand Down
Loading
Loading