Skip to content

Commit

Permalink
Remove result parser and smart contract querties
Browse files Browse the repository at this point in the history
  • Loading branch information
danielailie committed Nov 27, 2024
1 parent e948755 commit c8000be
Show file tree
Hide file tree
Showing 27 changed files with 441 additions and 1,249 deletions.
1 change: 0 additions & 1 deletion src/abi/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,6 @@ export * from "./interactionChecker";
export * from "./interface";
export * from "./nativeSerializer";
export * from "./query";
export * from "./resultsParser";
export * from "./returnCode";
export * from "./smartContract";
export * from "./transactionPayloadBuilders";
Expand Down
143 changes: 83 additions & 60 deletions src/abi/interaction.spec.ts
Original file line number Diff line number Diff line change
@@ -1,20 +1,19 @@
import BigNumber from "bignumber.js";
import { assert } from "chai";
import { Address } from "../address";
import { ContractQueryResponse } from "../networkProviders";
import { SmartContractQueryInput, SmartContractQueryResponse } from "../smartContractQuery";
import { SmartContractController } from "../smartContracts";
import {
loadAbiRegistry,
loadTestWallets,
MockNetworkProvider,
setupUnitTestWatcherTimeouts,
TestWallet,
} from "../testutils";
import { ContractController } from "../testutils/contractController";
import { Token, TokenTransfer } from "../tokens";
import { Transaction } from "../transaction";
import { ContractFunction } from "./function";
import { Interaction } from "./interaction";
import { ReturnCode } from "./returnCode";
import { SmartContract } from "./smartContract";
import { BigUIntValue, BytesValue, OptionalValue, OptionValue, TokenIdentifierValue, U32Value } from "./typesystem";

Expand Down Expand Up @@ -173,8 +172,8 @@ describe("test smart contract interactor", function () {
});

it("should create transaction, with ABI, with transfer & execute", async function () {
const abiRegistry = await loadAbiRegistry("src/testdata/answer.abi.json");
const contract = new SmartContract({ address: dummyAddress, abi: abiRegistry });
const abi = await loadAbiRegistry("src/testdata/answer.abi.json");
const contract = new SmartContract({ address: dummyAddress, abi: abi });
const alice = new Address("erd1qyu5wthldzr8wx5c9ucg8kjagg0jfs53s8nr3zpz3hypefsdd8ssycr6th");
const token = new Token({ identifier: "FOO-abcdef", nonce: 0n });

Expand Down Expand Up @@ -207,7 +206,7 @@ describe("test smart contract interactor", function () {

let abiRegistry = await loadAbiRegistry("src/testdata/answer.abi.json");
let contract = new SmartContract({ address: dummyAddress, abi: abiRegistry });
let controller = new ContractController(provider);
let controller = new SmartContractController({ chainID: "D", networkProvider: provider, abi: abiRegistry });

let interaction = <Interaction>contract.methods.getUltimateAnswer().withGasLimit(543210).withChainID("T");

Expand All @@ -218,18 +217,29 @@ describe("test smart contract interactor", function () {

provider.mockQueryContractOnFunction(
"getUltimateAnswer",
new ContractQueryResponse({ returnData: [Buffer.from([42]).toString("base64")], returnCode: "ok" }),
new SmartContractQueryResponse({
returnDataParts: [Buffer.from([42])],
returnCode: "ok",
returnMessage: "msg",
function: "getUltimateAnswer",
}),
);

// Query
let {
values: queryValues,
firstValue: queryAnwser,
returnCode: queryCode,
} = await controller.query(interaction);
assert.lengthOf(queryValues, 1);
assert.deepEqual(queryAnwser!.valueOf(), new BigNumber(42));
assert.isTrue(queryCode.equals(ReturnCode.Ok));
// Query;

const interactionQuery = interaction.buildQuery();
let response = await controller.query(
new SmartContractQueryInput({
contract: interactionQuery.address,
arguments: interactionQuery.getEncodedArguments(),
function: interactionQuery.func.toString(),
caller: interactionQuery.caller,
value: BigInt(interactionQuery.value.toString()),
}),
);
console.log(22222, response);
assert.isTrue(response.length == 1);
assert.deepEqual(response[0], new BigNumber(42));

// Execute, do not wait for execution
let transaction = interaction.withSender(alice.address).withNonce(0).buildTransaction();
Expand Down Expand Up @@ -257,20 +267,22 @@ describe("test smart contract interactor", function () {
transaction = interaction.withNonce(2).buildTransaction();
transaction.setSender(alice.address);
transaction.applySignature(await alice.signer.sign(transaction.serializeForSigning()));
provider.mockGetTransactionWithAnyHashAsNotarizedWithOneResult("@6f6b@2bs");
let { bundle } = await controller.execute(interaction, transaction);

assert.lengthOf(bundle.values, 1);
assert.deepEqual(bundle.firstValue!.valueOf(), new BigNumber(43));
assert.isTrue(bundle.returnCode.equals(ReturnCode.Ok));
provider.mockGetTransactionWithAnyHashAsNotarizedWithOneResult("@6f6b@2bs", "getUltimateAnswer");
let hash = await provider.sendTransaction(transaction);
let responseExecute = await controller.awaitCompletedExecute(hash);

console.log(responseExecute, responseExecute.values[0]!.valueOf());
assert.isTrue(responseExecute.values.length == 1);
assert.deepEqual(responseExecute.values[0], new BigNumber(43));
assert.isTrue(responseExecute.returnCode == "ok");
});

it("should interact with 'counter'", async function () {
setupUnitTestWatcherTimeouts();

let abiRegistry = await loadAbiRegistry("src/testdata/counter.abi.json");
let contract = new SmartContract({ address: dummyAddress, abi: abiRegistry });
let controller = new ContractController(provider);
let abi = await loadAbiRegistry("src/testdata/counter.abi.json");
let contract = new SmartContract({ address: dummyAddress, abi: abi });
let controller = new SmartContractController({ chainID: "D", networkProvider: provider, abi: abi });

let getInteraction = <Interaction>contract.methodsExplicit.get().check();
let incrementInteraction = (<Interaction>contract.methods.increment()).withGasLimit(543210);
Expand All @@ -279,13 +291,26 @@ describe("test smart contract interactor", function () {
// For "get()", return fake 7
provider.mockQueryContractOnFunction(
"get",
new ContractQueryResponse({ returnData: [Buffer.from([7]).toString("base64")], returnCode: "ok" }),
new SmartContractQueryResponse({
returnDataParts: [Buffer.from([7])],
returnCode: "ok",
function: "get",
returnMessage: "",
}),
);

// Query "get()"
let { firstValue: counterValue } = await controller.query(getInteraction);

assert.deepEqual(counterValue!.valueOf(), new BigNumber(7));
const interactionQuery = getInteraction.buildQuery();
let response = await controller.query(
new SmartContractQueryInput({
contract: interactionQuery.address,
arguments: interactionQuery.getEncodedArguments(),
function: interactionQuery.func.toString(),
caller: interactionQuery.caller,
value: BigInt(interactionQuery.value.toString()),
}),
);
assert.deepEqual(response[0], new BigNumber(7));

let incrementTransaction = incrementInteraction
.withSender(alice.address)
Expand All @@ -294,11 +319,10 @@ describe("test smart contract interactor", function () {
.buildTransaction();

incrementTransaction.applySignature(await alice.signer.sign(incrementTransaction.serializeForSigning()));
provider.mockGetTransactionWithAnyHashAsNotarizedWithOneResult("@6f6b@08");
let {
bundle: { firstValue: valueAfterIncrement },
} = await controller.execute(incrementInteraction, incrementTransaction);
assert.deepEqual(valueAfterIncrement!.valueOf(), new BigNumber(8));
provider.mockGetTransactionWithAnyHashAsNotarizedWithOneResult("@6f6b@08", "increment");
let hash = await provider.sendTransaction(incrementTransaction);
let responseExecute = await controller.awaitCompletedExecute(hash);
assert.deepEqual(responseExecute.values[0], new BigNumber(8));

// Decrement three times (simulate three parallel broadcasts). Wait for execution of the latter (third transaction). Return fake "5".
// Decrement #1
Expand All @@ -318,19 +342,18 @@ describe("test smart contract interactor", function () {

decrementTransaction = decrementInteraction.withNonce(17).buildTransaction();
decrementTransaction.applySignature(await alice.signer.sign(decrementTransaction.serializeForSigning()));
provider.mockGetTransactionWithAnyHashAsNotarizedWithOneResult("@6f6b@05");
let {
bundle: { firstValue: valueAfterDecrement },
} = await controller.execute(decrementInteraction, decrementTransaction);
assert.deepEqual(valueAfterDecrement!.valueOf(), new BigNumber(5));
provider.mockGetTransactionWithAnyHashAsNotarizedWithOneResult("@6f6b@05", "decrement");
hash = await provider.sendTransaction(decrementTransaction);
responseExecute = await controller.awaitCompletedExecute(hash);
assert.deepEqual(responseExecute.values[0], new BigNumber(5));
});

it("should interact with 'lottery-esdt'", async function () {
setupUnitTestWatcherTimeouts();

let abiRegistry = await loadAbiRegistry("src/testdata/lottery-esdt.abi.json");
let contract = new SmartContract({ address: dummyAddress, abi: abiRegistry });
let controller = new ContractController(provider);
let controller = new SmartContractController({ chainID: "D", networkProvider: provider, abi: abiRegistry });

let startInteraction = <Interaction>contract.methodsExplicit
.start([
Expand Down Expand Up @@ -359,17 +382,17 @@ describe("test smart contract interactor", function () {
.buildTransaction();

startTransaction.applySignature(await alice.signer.sign(startTransaction.serializeForSigning()));
provider.mockGetTransactionWithAnyHashAsNotarizedWithOneResult("@6f6b");
let {
bundle: { returnCode: startReturnCode, values: startReturnValues },
} = await controller.execute(startInteraction, startTransaction);

provider.mockGetTransactionWithAnyHashAsNotarizedWithOneResult("@6f6b", "start");
let hash = await provider.sendTransaction(startTransaction);
let response = await controller.awaitCompletedExecute(hash);

assert.equal(
startTransaction.getData().toString(),
"start@6c75636b79@6c75636b792d746f6b656e@01@@@0100000001@@",
);
assert.isTrue(startReturnCode.equals(ReturnCode.Ok));
assert.lengthOf(startReturnValues, 0);
assert.isTrue(response.returnCode == "ok");
assert.isTrue(response.values.length == 0);

// status() (this is a view function, but for the sake of the test, we'll execute it)
let statusTransaction = statusInteraction
Expand All @@ -379,15 +402,16 @@ describe("test smart contract interactor", function () {
.buildTransaction();

statusTransaction.applySignature(await alice.signer.sign(statusTransaction.serializeForSigning()));
provider.mockGetTransactionWithAnyHashAsNotarizedWithOneResult("@6f6b@01");
let {
bundle: { returnCode: statusReturnCode, values: statusReturnValues, firstValue: statusFirstValue },
} = await controller.execute(statusInteraction, statusTransaction);
provider.mockGetTransactionWithAnyHashAsNotarizedWithOneResult("@6f6b@01", "status");

hash = await provider.sendTransaction(startTransaction);
response = await controller.awaitCompletedExecute(hash);

console.log({ response });
assert.equal(statusTransaction.getData().toString(), "status@6c75636b79");
assert.isTrue(statusReturnCode.equals(ReturnCode.Ok));
assert.lengthOf(statusReturnValues, 1);
assert.deepEqual(statusFirstValue!.valueOf(), { name: "Running", fields: [] });
assert.isTrue(response.returnCode == "ok");
assert.isTrue(response.values.length == 1);
assert.deepEqual(response.values[0]!.valueOf(), { name: "Running", fields: [] });

// lotteryInfo() (this is a view function, but for the sake of the test, we'll execute it)
let getLotteryInfoTransaction = getLotteryInfoInteraction
Expand All @@ -401,16 +425,15 @@ describe("test smart contract interactor", function () {
);
provider.mockGetTransactionWithAnyHashAsNotarizedWithOneResult(
"@6f6b@0000000b6c75636b792d746f6b656e000000010100000000000000005fc2b9dbffffffff00000001640000000a140ec80fa7ee88000000",
"getLotteryInfo",
);
let {
bundle: { returnCode: infoReturnCode, values: infoReturnValues, firstValue: infoFirstValue },
} = await controller.execute(getLotteryInfoInteraction, getLotteryInfoTransaction);

hash = await provider.sendTransaction(startTransaction);
response = await controller.awaitCompletedExecute(hash);
assert.equal(getLotteryInfoTransaction.getData().toString(), "getLotteryInfo@6c75636b79");
assert.isTrue(infoReturnCode.equals(ReturnCode.Ok));
assert.lengthOf(infoReturnValues, 1);
assert.isTrue(response.returnCode == "ok");
assert.isTrue(response.values.length == 1);

assert.deepEqual(infoFirstValue!.valueOf(), {
assert.deepEqual(response.values[0]!.valueOf(), {
token_identifier: "lucky-token",
ticket_price: new BigNumber("1"),
tickets_left: new BigNumber(0),
Expand Down
4 changes: 2 additions & 2 deletions src/abi/interaction.ts
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,7 @@ export class Interaction {
private gasLimit: IGasLimit = 0;
private gasPrice: IGasPrice | undefined = undefined;
private chainID: IChainID = "";
private querent: IAddress = Address.empty();
private querent: Address = Address.empty();
private explicitReceiver?: IAddress;
private sender: Address = Address.empty();
private version: number = TRANSACTION_VERSION_DEFAULT;
Expand Down Expand Up @@ -186,7 +186,7 @@ export class Interaction {
/**
* Sets the "caller" field on contract queries.
*/
withQuerent(querent: IAddress): Interaction {
withQuerent(querent: Address): Interaction {
this.querent = querent;
return this;
}
Expand Down
12 changes: 6 additions & 6 deletions src/abi/query.ts
Original file line number Diff line number Diff line change
@@ -1,19 +1,19 @@
import { Address } from "../address";
import { TypedValue } from "./typesystem";
import { ITransactionValue } from "../interface";
import { ArgSerializer } from "./argSerializer";
import { IAddress, ITransactionValue } from "../interface";
import { IContractFunction } from "./interface";
import { TypedValue } from "./typesystem";

export class Query {
caller: IAddress;
address: IAddress;
caller: Address;
address: Address;
func: IContractFunction;
args: TypedValue[];
value: ITransactionValue;

constructor(obj: {
caller?: IAddress;
address: IAddress;
caller?: Address;
address: Address;
func: IContractFunction;
args?: TypedValue[];
value?: ITransactionValue;
Expand Down
Loading

0 comments on commit c8000be

Please sign in to comment.