Skip to main content

Overview

Every Media Protocol Smart-Contract has a corresponding model in the SDK used to interact with the contracts in a more user-friendly way. The following section will describe some common methods and properties that almost all models have.

Common Properties

All models have a config property of type [SdkConfig] which is set when the model is instantiated.

Common Methods

Both the view and execute methods require the following parameters:

  • functionName: The name of the contract's function to call.
  • args: An array of arguments to pass to the contract's function. They must be provided in the required order from the contract's function.

Although both functions are marked with a return of Promise<any>, they will return whatever the blockchain function returns. This could be a single value, an array, or an object.

View

The view method is used to fetch the latest data from the blockchain. It is an asynchronous generic method that returns a Promise<any>.

async view(functionName, args): Promise<any> {
try {
return await this.config.publicClient.readContract({
address: ContractAddresses.Resources[this.config.publicClient.chain!.id],
abi: ResourcesABI.abi,
functionName: functionName,
args: args,
})
} catch (error) {
throw error
}
}

Execute

The execute function in used to send a transaction to the blockchain. It is an asynchronous generic method that returns a Promise<any>.

note

It requires that the given sdk to have been initialized either with a wallet client or a privateKey/mnemonic due to the need to sign the transaction.

async execute(functionName, args): Promise<any> {
try {
const { request } = await this.config.publicClient.simulateContract({
address: ContractAddresses.Resources[this.config.publicClient.chain!.id],
abi: ResourcesABI.abi,
functionName: functionName,
args: args,
account: this.config.walletClient.account,
})
return await this.config.walletClient.writeContract(request)
} catch (error) {
throw error
}
}

Examples

The following example will create a deal and then retrieve it from the blockchain using the Marketplace model.


import { Sdk, Marketplace } from 'media-sdk'

const sdk = new Sdk({mnemonic: 'your mnemonic here'})

const marketplace = new Marketplace(sdk)

const marketplaceId = 1
const resourceId = 1
const offerId = 1
const blockedBalance = 100
const sharedKeyCopy = "Sample Shared Key"

// create a deal
await this.execute("createDeal", [
marketplaceId,
resourceId,
offerId,
blockedBalance,
sharedKeyCopy
])

// retrieve the deal
const dealId = 1
let deal = await marketplace.view("getDealById", [marketplaceId, dealId])

Further considerations

Although the SDK models provide a wide range of functionalities, there are some cases that using this functions to read/write directly over the Media Protocol Contracts might be useful. It is highly recommended if you are going to do so, to read and have a strong understanding of the Media Protocol Smart-Contracts.