Skip to content

Commit

Permalink
Merge pull request #4 from golddydev/master
Browse files Browse the repository at this point in the history
Update return type of functions
  • Loading branch information
bigirishlion authored Nov 7, 2024
2 parents a578030 + 510de9d commit 42c190d
Show file tree
Hide file tree
Showing 15 changed files with 200 additions and 118 deletions.
3 changes: 2 additions & 1 deletion .eslintrc.json
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,7 @@
]
}
],
"simple-import-sort/exports": "error"
"simple-import-sort/exports": "error",
"@typescript-eslint/no-explicit-any": "off"
}
}
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "@koralabs/handles-marketplace-contracts",
"version": "0.1.1",
"version": "0.1.2",
"description": "Smart Contract of Ada Handles Marketplace",
"type": "module",
"main": "index.js",
Expand Down
75 changes: 45 additions & 30 deletions src/buy.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import { HANDLE_POLICY_ID, MIN_FEE, MIN_LOVELACE } from "./constants";
import { buildDatumTag, decodeDatum, decodeParametersDatum } from "./datum";
import { deployedScripts } from "./deployed";
import { mayFail, mayFailAsync, mayFailTransaction } from "./helpers";
import { BuildTxError, SuccessResult } from "./types";
import {
bigIntMax,
fetchLatestmarketplaceScriptDetail,
Expand All @@ -12,7 +13,7 @@ import {
import * as helios from "@koralabs/helios";
import { IUTxO, Network } from "@koralabs/kora-labs-common";
import { Buy } from "redeemer";
import { Err, Ok, Result } from "ts-res";
import { Err, Result } from "ts-res";

/**
* Configuration of function to buy handle
Expand Down Expand Up @@ -56,13 +57,13 @@ interface BuyWithAuthConfig {
* Buy Handle on marketplace
* @param {BuyConfig} config
* @param {Network} network
* @returns {Promise<Result<string, string>>}
* @returns {Promise<Result<SuccessResult, Error | BuildTxError>>}
*/

const buy = async (
config: BuyConfig,
network: Network
): Promise<Result<string, string>> => {
): Promise<Result<SuccessResult, Error | BuildTxError>> => {
const { changeBech32Address, cborUtxos, handleHex, listingUtxo } = config;

/// fetch marketplace reference script detail
Expand All @@ -76,9 +77,10 @@ const buy = async (
: Object.values(deployedScripts[network])[0];

const { cbor, datumCbor, refScriptUtxo } = refScriptDetail;
if (!cbor) return Err(`Deploy script cbor is empty`);
if (!datumCbor) return Err(`Deploy script's datum cbor is empty`);
if (!refScriptUtxo) return Err(`Deployed script UTxO is not defined`);
if (!cbor) return Err(new Error("Deploy script cbor is empty"));
if (!datumCbor) return Err(new Error("Deploy script's datum cbor is empty"));
if (!refScriptUtxo)
return Err(new Error("Deployed script UTxO is not defined"));

/// fetch network parameter
const networkParams = fetchNetworkParameters(network);
Expand All @@ -88,20 +90,24 @@ const buy = async (
decodeParametersDatum(datumCbor)
).complete();
if (!parametersResult.ok)
return Err(`Deployed script's datum cbor is invalid`);
return Err(new Error("Deployed script's datum cbor is invalid"));
const parameters = parametersResult.data;

/// get uplc program
const uplcProgramResult = await mayFailAsync(() =>
getUplcProgram(parameters, true)
).complete();
if (!uplcProgramResult.ok)
return Err(`Getting Uplc Program error: ${uplcProgramResult.error}`);
return Err(
new Error("Getting Uplc Program error: ${uplcProgramResult.error}")
);
const uplcProgram = uplcProgramResult.data;

/// check deployed script cbor hex
if (cbor != helios.bytesToHex(uplcProgram.toCbor()))
return Err(`Deployed script's cbor doesn't match with its parameter`);
return Err(
new Error("Deployed script's cbor doesn't match with its parameter")
);

const changeAddress = helios.Address.fromBech32(changeBech32Address);
const utxos = cborUtxos.map((cborUtxo) =>
Expand All @@ -127,12 +133,12 @@ const buy = async (
);

const handleRawDatum = handleUtxo.output.datum;
if (!handleRawDatum) return Err("Handle UTxO datum not found");
if (!handleRawDatum) return Err(new Error("Handle UTxO datum not found"));
const datumResult = await mayFailAsync(() =>
decodeDatum(handleRawDatum)
).complete();
if (!datumResult.ok)
return Err(`Decoding Datum Cbor error: ${datumResult.error}`);
return Err(new Error(`Decoding Datum Cbor error: ${datumResult.error}`));
const datum = datumResult.data;

/// take fund to pay payouts
Expand All @@ -151,11 +157,13 @@ const buy = async (

/// make redeemer
const redeemer = mayFail(() => Buy(0));
if (!redeemer.ok) return Err(`Making Redeemer error: ${redeemer.error}`);
if (!redeemer.ok)
return Err(new Error(`Making Redeemer error: ${redeemer.error}`));

/// build datum tag
const datumTag = mayFail(() => buildDatumTag(handleUtxo.outputId));
if (!datumTag.ok) return Err(`Building Datum Tag error: ${datumTag.error}`);
if (!datumTag.ok)
return Err(new Error(`Building Datum Tag error: ${datumTag.error}`));

/// marketplace fee output
const marketplaceFeeOutput = new helios.TxOutput(
Expand Down Expand Up @@ -217,23 +225,23 @@ const buy = async (

/// finalize tx
const txCompleteResult = await mayFailTransaction(
tx,
() => tx.finalize(networkParams, changeAddress, unSelected),
refScriptDetail.unoptimizedCbor
).complete();
if (!txCompleteResult.ok) return Err(txCompleteResult.error);
return Ok(txCompleteResult.data.toCborHex());
return txCompleteResult;
};

/**
* Buy Handle on marketplace with one of authorizers
* @param {BuyWithAuthConfig} config
* @param {Network} network
* @returns {Promise<Result<string, string>>}
* @returns {Promise<Result<SuccessResult, Error | BuildTxError>>}
*/
const buyWithAuth = async (
config: BuyWithAuthConfig,
network: Network
): Promise<Result<string, string>> => {
): Promise<Result<SuccessResult, Error | BuildTxError>> => {
const {
changeBech32Address,
cborUtxos,
Expand All @@ -253,9 +261,10 @@ const buyWithAuth = async (
: Object.values(deployedScripts[network])[0];

const { cbor, datumCbor, refScriptUtxo } = refScriptDetail;
if (!cbor) return Err(`Deploy script cbor is empty`);
if (!datumCbor) return Err(`Deploy script's datum cbor is empty`);
if (!refScriptUtxo) return Err(`Deployed script UTxO is not defined`);
if (!cbor) return Err(new Error("Deploy script cbor is empty"));
if (!datumCbor) return Err(new Error("Deploy script's datum cbor is empty"));
if (!refScriptUtxo)
return Err(new Error("Deployed script UTxO is not defined"));

/// fetch network parameter
const networkParams = fetchNetworkParameters(network);
Expand All @@ -265,28 +274,32 @@ const buyWithAuth = async (
decodeParametersDatum(datumCbor)
).complete();
if (!parametersResult.ok)
return Err(`Deployed script's datum cbor is invalid`);
return Err(new Error("Deployed script's datum cbor is invalid"));
const parameters = parametersResult.data;

/// get uplc program
const uplcProgramResult = await mayFailAsync(() =>
getUplcProgram(parameters, true)
).complete();
if (!uplcProgramResult.ok)
return Err(`Getting Uplc Program error: ${uplcProgramResult.error}`);
return Err(
new Error(`Getting Uplc Program error: ${uplcProgramResult.error}`)
);
const uplcProgram = uplcProgramResult.data;

/// check deployed script cbor hex
if (cbor != helios.bytesToHex(uplcProgram.toCbor()))
return Err(`Deployed script's cbor doesn't match with its parameter`);
return Err(
new Error("Deployed script's cbor doesn't match with its parameter")
);

/// check authorizer pub key hash
if (
!parameters.authorizers.some(
(authorizer) => authorizer == authorizerPubKeyHash
)
)
return Err(`Authorizer Pub Key Hash is not valid`);
return Err(new Error("Authorizer Pub Key Hash is not valid"));

const changeAddress = helios.Address.fromBech32(changeBech32Address);
const utxos = cborUtxos.map((cborUtxo) =>
Expand All @@ -312,12 +325,12 @@ const buyWithAuth = async (
);

const handleRawDatum = handleUtxo.output.datum;
if (!handleRawDatum) return Err("Handle UTxO datum not found");
if (!handleRawDatum) return Err(new Error("Handle UTxO datum not found"));
const datumResult = await mayFailAsync(() =>
decodeDatum(handleRawDatum)
).complete();
if (!datumResult.ok)
return Err(`Decoding Datum Cbor error: ${datumResult.error}`);
return Err(new Error(`Decoding Datum Cbor error: ${datumResult.error}`));
const datum = datumResult.data;

/// take fund to pay payouts
Expand All @@ -333,11 +346,13 @@ const buyWithAuth = async (

/// make redeemer
const redeemer = mayFail(() => Buy(0));
if (!redeemer.ok) return Err(`Making Redeemer error: ${redeemer.error}`);
if (!redeemer.ok)
return Err(new Error(`Making Redeemer error: ${redeemer.error}`));

/// build datum tag
const datumTag = mayFail(() => buildDatumTag(handleUtxo.outputId));
if (!datumTag.ok) return Err(`Building Datum Tag error: ${datumTag.error}`);
if (!datumTag.ok)
return Err(new Error(`Building Datum Tag error: ${datumTag.error}`));

/// payout outputs
const payoutOutputs = datum.payouts.map(
Expand Down Expand Up @@ -392,11 +407,11 @@ const buyWithAuth = async (

/// finalize tx
const txCompleteResult = await mayFailTransaction(
tx,
() => tx.finalize(networkParams, changeAddress, unSelected),
refScriptDetail.unoptimizedCbor
).complete();
if (!txCompleteResult.ok) return Err(txCompleteResult.error);
return Ok(txCompleteResult.data.toCborHex());
return txCompleteResult;
};

export { buy, buyWithAuth };
Expand Down
7 changes: 3 additions & 4 deletions src/commands/buy.ts
Original file line number Diff line number Diff line change
Expand Up @@ -53,7 +53,7 @@ program
};

const txResult = await buy(buyConfig, config.network);
if (!txResult.ok) return program.error(txResult.error);
if (!txResult.ok) return program.error(txResult.error.message);
console.log("\nTransaction CBOR Hex, copy and paste to wallet\n");
console.log(txResult.data);
}
Expand Down Expand Up @@ -108,8 +108,7 @@ program
};

const txResult = await buyWithAuth(buyWithAuthConfig, config.network);
if (!txResult.ok) return program.error(txResult.error);
console.log("\nTransaction CBOR Hex, copy and paste to wallet\n");
console.log(txResult.data);
if (!txResult.ok) console.log(txResult.error);
else console.log(txResult.data);
}
);
5 changes: 2 additions & 3 deletions src/commands/list.ts
Original file line number Diff line number Diff line change
Expand Up @@ -53,9 +53,8 @@ const buyCommand = program
};

const txResult = await list(listConfig, config.network);
if (!txResult.ok) return program.error(txResult.error);
console.log("\nTransaction CBOR Hex, copy and paste to wallet\n");
console.log(txResult.data);
if (!txResult.ok) console.log(txResult.error);
else console.log(txResult.data);
}
);

Expand Down
5 changes: 2 additions & 3 deletions src/commands/update.ts
Original file line number Diff line number Diff line change
Expand Up @@ -68,9 +68,8 @@ const updateCommand = program
};

const txResult = await update(updateConfig, config.network);
if (!txResult.ok) return program.error(txResult.error);
console.log("\nTransaction CBOR Hex, copy and paste to wallet\n");
console.log(txResult.data);
if (!txResult.ok) console.log(txResult.error);
else console.log(txResult.data);
}
);

Expand Down
5 changes: 2 additions & 3 deletions src/commands/withdraw.ts
Original file line number Diff line number Diff line change
Expand Up @@ -53,9 +53,8 @@ const withdrawCommand = program
};

const txResult = await withdraw(withdrawConfig, config.network);
if (!txResult.ok) return program.error(txResult.error);
console.log("\nTransaction CBOR Hex, copy and paste to wallet\n");
console.log(txResult.data);
if (!txResult.ok) console.log(txResult.error);
else console.log(txResult.data);
}
);

Expand Down
1 change: 0 additions & 1 deletion src/datum.ts
Original file line number Diff line number Diff line change
Expand Up @@ -54,7 +54,6 @@ const decodeDatum = async (datum: helios.Datum): Promise<Datum> => {
});

const owner = helios.PubKeyHash.fromHex(decoded[1].slice(2)).hex;
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const payouts: Payout[] = decoded[0].map((rawPayout: any) => {
const address = helios.Address.fromHex(rawPayout[0].slice(2)).toBech32();
const amountLovelace = BigInt(rawPayout[1]) as bigint;
Expand Down
2 changes: 0 additions & 2 deletions src/helpers/api.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,6 @@ import { fetch } from "cross-fetch";

const fetchApi = async (
endpoint: string,
// eslint-disable-next-line @typescript-eslint/no-explicit-any
params: any = {}
): Promise<Response> => {
const { headers, ...rest } = params;
Expand All @@ -31,7 +30,6 @@ const fetchApi = async (

const fetchApiJson = async <T>(
endpoint: string,
// eslint-disable-next-line @typescript-eslint/no-explicit-any
params: any = {}
): Promise<T> => {
params.headers = {
Expand Down
1 change: 0 additions & 1 deletion src/helpers/common/invariant.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
const prefix: string = "Invariant failed";

const invariant: (
// eslint-disable-next-line @typescript-eslint/no-explicit-any
condition: any,
message?: string | (() => string)
) => asserts condition = (condition, message?: string | (() => string)) => {
Expand Down
Loading

0 comments on commit 42c190d

Please sign in to comment.