diff --git a/test/.prettierignore b/test/.prettierignore
deleted file mode 100644
index 815ef9bb43..0000000000
--- a/test/.prettierignore
+++ /dev/null
@@ -1,2 +0,0 @@
-src/sdk/
-src/stakeholder/
diff --git a/test/src/e2e.dynval/1/doubleVote.test.ts b/test/src/e2e.dynval/1/doubleVote.test.ts
index 7735757223..18a822cd4e 100644
--- a/test/src/e2e.dynval/1/doubleVote.test.ts
+++ b/test/src/e2e.dynval/1/doubleVote.test.ts
@@ -68,7 +68,10 @@ describe("Double vote detection", function() {
target: 2,
termPeriods: 0.5
});
- const banned = await stake.getBanned(aliceNode.testFramework);
+ const banned = await stake.getBanned(
+ aliceNode.rpc,
+ aliceNode.testFramework
+ );
expect(banned.map(b => b.toString())).to.include(
betty.platformAddress.toString()
);
@@ -90,7 +93,10 @@ describe("Double vote detection", function() {
target: 2,
termPeriods: 0.5
});
- const banned = await stake.getBanned(aliceNode.testFramework);
+ const banned = await stake.getBanned(
+ aliceNode.rpc,
+ aliceNode.testFramework
+ );
expect(banned.map(b => b.toString())).to.include(
betty.platformAddress.toString()
);
@@ -112,7 +118,10 @@ describe("Double vote detection", function() {
target: 2,
termPeriods: 0.5
});
- const banned = await stake.getBanned(aliceNode.testFramework);
+ const banned = await stake.getBanned(
+ aliceNode.rpc,
+ aliceNode.testFramework
+ );
expect(banned.map(b => b.toString())).to.include(
betty.platformAddress.toString()
);
diff --git a/test/src/e2e.dynval/1/dv.changeParams.test.ts b/test/src/e2e.dynval/1/dv.changeParams.test.ts
index 2de7ad3d5b..2b28202bc2 100644
--- a/test/src/e2e.dynval/1/dv.changeParams.test.ts
+++ b/test/src/e2e.dynval/1/dv.changeParams.test.ts
@@ -17,14 +17,16 @@
import * as chai from "chai";
import { expect } from "chai";
import * as chaiAsPromised from "chai-as-promised";
+import RPC from "foundry-rpc";
import "mocha";
-import { SDK } from "../../sdk/src";
import * as stake from "../../stakeholder/src";
+import { H256 } from "codechain-primitives/lib";
import { validators } from "../../../tendermint.dynval/constants";
import { faucetAddress, faucetSecret } from "../../helper/constants";
import { PromiseExpect } from "../../helper/promise";
import { changeParams, setTermTestTimeout, withNodes } from "../setup";
+import { ERROR } from "../../helper/error";
chai.use(chaiAsPromised);
@@ -43,13 +45,13 @@ describe("Change commonParams that affects validator set", function() {
}))
});
- async function checkValidators(sdk: SDK, term: number, target: string[]) {
- const blockNumber = await sdk.rpc.chain.getBestBlockNumber();
- const termMetadata = (await stake.getTermMetadata(sdk, blockNumber))!;
+ async function checkValidators(rpc: RPC, term: number, target: string[]) {
+ const blockNumber = await rpc.chain.getBestBlockNumber();
+ const termMetadata = (await stake.getTermMetadata(rpc, blockNumber))!;
const currentTermInitialBlockNumber =
termMetadata.lastTermFinishedBlockNumber + 1;
const validatorsAfter = (await stake.getPossibleAuthors(
- sdk,
+ rpc,
currentTermInitialBlockNumber
))!.map(platformAddr => platformAddr.toString());
@@ -74,9 +76,9 @@ describe("Change commonParams that affects validator set", function() {
await checkingNode.waitForTx(changeTxHash);
- const faucetSeq = await checkingNode.testFramework.rpc.chain.getSeq(
- faucetAddress
- );
+ const faucetSeq = (await checkingNode.rpc.chain.getSeq({
+ address: faucetAddress.toString()
+ }))!;
const revoked = validators.slice(0, 3);
const untouched = validators.slice(3, 5);
@@ -96,12 +98,12 @@ describe("Change commonParams that affects validator set", function() {
const revokeTxHashes = await Promise.all(
revokeTxs.map(tx =>
- checkingNode.testFramework.rpc.chain.sendSignedTransaction(
- tx
- )
+ checkingNode.rpc.mempool.sendSignedTransaction({
+ tx: `${tx.rlpBytes().toString("hex")}`
+ })
)
);
- await checkingNode.waitForTx(revokeTxHashes);
+ await checkingNode.waitForTx(new H256(revokeTxHashes[0]));
await termWaiter.waitNodeUntilTerm(checkingNode, {
target: 2,
termPeriods: 1
@@ -111,11 +113,7 @@ describe("Change commonParams that affects validator set", function() {
...revoked.slice(0, 2),
...untouched
].map(signer => signer.platformAddress.toString());
- await checkValidators(
- checkingNode.testFramework,
- 2,
- expectedValidators
- );
+ await checkValidators(checkingNode.rpc, 2, expectedValidators);
});
});
@@ -128,7 +126,7 @@ describe("Change commonParams that affects validator set", function() {
const checkingNode = nodes[0];
await checkValidators(
- checkingNode.testFramework,
+ checkingNode.rpc,
1,
validators
.slice(0, 5)
@@ -146,7 +144,7 @@ describe("Change commonParams that affects validator set", function() {
termPeriods: 1
});
await checkValidators(
- checkingNode.testFramework,
+ checkingNode.rpc,
2,
validators
.slice(0, 3)
@@ -164,7 +162,7 @@ describe("Change commonParams that affects validator set", function() {
termPeriods: 1
});
await checkValidators(
- checkingNode.testFramework,
+ checkingNode.rpc,
3,
validators
.slice(0, 4)
@@ -203,9 +201,7 @@ describe("Change commonParams that doesn't affects validator set", function() {
this.slow((initialTermSeconds + newTermSeconds) * 1000 * margin);
this.timeout((initialTermSeconds + newTermSeconds) * 1000 * 2);
- const term1Metadata = (await stake.getTermMetadata(
- nodes[0].testFramework
- ))!;
+ const term1Metadata = (await stake.getTermMetadata(nodes[0].rpc))!;
{
expect(term1Metadata.currentTermId).to.be.equal(1);
}
@@ -218,26 +214,24 @@ describe("Change commonParams that doesn't affects validator set", function() {
await nodes[0].waitForTermChange(2, initialTermSeconds * margin);
- const term2Metadata = (await stake.getTermMetadata(
- nodes[0].testFramework
- ))!;
+ const term2Metadata = (await stake.getTermMetadata(nodes[0].rpc))!;
{
expect(term2Metadata.currentTermId).to.be.equal(2);
}
await nodes[0].waitForTermChange(3, newTermSeconds * margin);
- const term3Metadata = (await stake.getTermMetadata(
- nodes[0].testFramework
- ))!;
+ const term3Metadata = (await stake.getTermMetadata(nodes[0].rpc))!;
{
expect(term2Metadata.currentTermId).to.be.equal(2);
}
const [ts1, ts2, ts3] = await Promise.all(
[term1Metadata, term2Metadata, term3Metadata].map(m =>
- nodes[0].testFramework.rpc.chain
- .getBlock(m.lastTermFinishedBlockNumber)
+ nodes[0].rpc.chain
+ .getBlockByNumber({
+ blockNumber: m.lastTermFinishedBlockNumber
+ })
.then(block => block!.timestamp)
)
);
@@ -276,14 +270,19 @@ describe("Change commonParams that doesn't affects validator set", function() {
})
.sign({
secret: faucetSecret,
- seq: await checkingNode.testFramework.rpc.chain.getSeq(
- faucetAddress
- ),
+ seq: (await checkingNode.rpc.chain.getSeq({
+ address: faucetAddress.toString()
+ }))!,
fee: 10
});
- await expect(
- checkingNode.testFramework.rpc.chain.sendSignedTransaction(tx)
- ).rejectedWith(/Too Low Fee/);
+ try {
+ await checkingNode.rpc.mempool.sendSignedTransaction({
+ tx: tx.rlpBytes().toString("hex")
+ });
+ expect.fail();
+ } catch (e) {
+ expect(e.toString()).is.include(ERROR.TOO_LOW_FEE);
+ }
});
});
@@ -308,29 +307,41 @@ describe("Change commonParams that doesn't affects validator set", function() {
});
await checkingNode.waitForTx(changeTxHash);
const normalNomination = nominationWithMetadata(129);
- const seq = await checkingNode.testFramework.rpc.chain.getSeq(
- alice.platformAddress
- );
- const normalHash = await checkingNode.testFramework.rpc.chain.sendSignedTransaction(
- normalNomination.sign({
- secret: alice.privateKey,
- seq,
- fee: 10
- })
+ const seq = (await checkingNode.rpc.chain.getSeq({
+ address: alice.platformAddress.toString()
+ }))!;
+ const normalHash = await checkingNode.rpc.mempool.sendSignedTransaction(
+ {
+ tx: normalNomination
+ .sign({
+ secret: alice.privateKey,
+ seq,
+ fee: 10
+ })
+ .rlpBytes()
+ .toString("hex")
+ }
);
- await checkingNode.waitForTx(normalHash);
+ await checkingNode.waitForTx(new H256(normalHash));
const largeNomination = nominationWithMetadata(257);
-
- await expect(
- checkingNode.testFramework.rpc.chain.sendSignedTransaction(
- largeNomination.sign({
- secret: alice.privateKey,
- seq: seq + 1,
- fee: 10
- })
- )
- ).rejectedWith(/Too long/);
+ try {
+ await checkingNode.rpc.mempool.sendSignedTransaction({
+ tx: largeNomination
+ .sign({
+ secret: alice.privateKey,
+ seq: seq + 1,
+ fee: 10
+ })
+ .rlpBytes()
+ .toString("hex")
+ });
+ expect.fail();
+ } catch (e) {
+ expect(e.toString()).is.include(
+ ERROR.ACTION_DATA_HANDLER_NOT_FOUND
+ );
+ }
});
it("Should apply smaller metadata limit after decrement", async function() {
@@ -345,28 +356,41 @@ describe("Change commonParams that doesn't affects validator set", function() {
});
await checkingNode.waitForTx(changeTxHash);
const normalNomination = nominationWithMetadata(63);
- const seq = await checkingNode.testFramework.rpc.chain.getSeq(
- alice.platformAddress
- );
- const normalHash = await checkingNode.testFramework.rpc.chain.sendSignedTransaction(
- normalNomination.sign({
- secret: alice.privateKey,
- seq,
- fee: 10
- })
+ const seq = (await checkingNode.rpc.chain.getSeq({
+ address: alice.platformAddress.toString()
+ }))!;
+ const normalHash = await checkingNode.rpc.mempool.sendSignedTransaction(
+ {
+ tx: normalNomination
+ .sign({
+ secret: alice.privateKey,
+ seq,
+ fee: 10
+ })
+ .rlpBytes()
+ .toString("hex")
+ }
);
- await checkingNode.waitForTx(normalHash);
+ await checkingNode.waitForTx(new H256(normalHash));
const largeNomination = nominationWithMetadata(127);
- await expect(
- checkingNode.testFramework.rpc.chain.sendSignedTransaction(
- largeNomination.sign({
- secret: alice.privateKey,
- seq: seq + 1,
- fee: 10
- })
- )
- ).rejectedWith(/Too long/);
+ try {
+ await checkingNode.rpc.mempool.sendSignedTransaction({
+ tx: largeNomination
+ .sign({
+ secret: alice.privateKey,
+ seq: seq + 1,
+ fee: 10
+ })
+ .rlpBytes()
+ .toString("hex")
+ });
+ expect.fail();
+ } catch (e) {
+ expect(e.toString()).is.include(
+ ERROR.ACTION_DATA_HANDLER_NOT_FOUND
+ );
+ }
});
});
diff --git a/test/src/e2e.dynval/1/dv.m-m'.test.ts b/test/src/e2e.dynval/1/dv.m-m'.test.ts
index 8d071700cc..ff7903578d 100644
--- a/test/src/e2e.dynval/1/dv.m-m'.test.ts
+++ b/test/src/e2e.dynval/1/dv.m-m'.test.ts
@@ -15,10 +15,14 @@
// along with this program. If not, see .
import { expect } from "chai";
+import * as chai from "chai";
+import * as chaiAsPromised from "chai-as-promised";
+import RPC from "foundry-rpc";
import "mocha";
-import { SDK } from "../../sdk/src";
+chai.use(chaiAsPromised);
import * as stake from "../../stakeholder/src";
+import { H256 } from "codechain-primitives/lib";
import { validators } from "../../../tendermint.dynval/constants";
import { faucetAddress, faucetSecret } from "../../helper/constants";
import { PromiseExpect } from "../../helper/promise";
@@ -61,8 +65,8 @@ describe("Dynamic Validator M -> M' (Changed the subset, M, M’ = maximum numbe
const charlieDelegationToCatchAlice = 4000;
const daveDepositToCatchAlice = 100000;
- async function expectAllValidatorsArePossibleAuthors(sdk: SDK) {
- const possibleAuthors = (await stake.getPossibleAuthors(sdk))!;
+ async function expectAllValidatorsArePossibleAuthors(rpc: RPC) {
+ const possibleAuthors = (await stake.getPossibleAuthors(rpc))!;
expect(possibleAuthors).to.have.lengthOf(maxNumOfValidators);
expect(possibleAuthors.map(x => x.toString())).to.includes.members(
validators
@@ -72,11 +76,11 @@ describe("Dynamic Validator M -> M' (Changed the subset, M, M’ = maximum numbe
}
async function expectAliceIsReplacedBy(
- sdk: SDK,
+ rpc: RPC,
name: string,
index: number
) {
- const possibleAuthors = await stake.getPossibleAuthors(sdk);
+ const possibleAuthors = await stake.getPossibleAuthors(rpc);
expect(possibleAuthors).not.to.be.null;
expect(possibleAuthors!).to.have.lengthOf(maxNumOfValidators);
const authorAddresses = possibleAuthors!.map(x => x.toString());
@@ -103,7 +107,7 @@ describe("Dynamic Validator M -> M' (Changed the subset, M, M’ = maximum numbe
});
beforeEach(async function() {
- await expectAllValidatorsArePossibleAuthors(nodes[0].testFramework);
+ await expectAllValidatorsArePossibleAuthors(nodes[0].rpc);
});
it("Bob should be a validator when doing nothing", async function() {
@@ -118,14 +122,14 @@ describe("Dynamic Validator M -> M' (Changed the subset, M, M’ = maximum numbe
});
expect(
- (await stake.getJailed(nodes[0].testFramework)).map(x =>
- x.address.toString()
- )
+ (
+ await stake.getJailed(nodes[0].rpc, nodes[0].testFramework)
+ ).map(x => x.address.toString())
).contains(
validators[alice].platformAddress.toString(),
"Alice should be jailed for doing nothing"
);
- await expectAliceIsReplacedBy(nodes[0].testFramework, "Bob", bob);
+ await expectAliceIsReplacedBy(nodes[0].rpc, "Bob", bob);
});
it("Charlie should be a validator when gets enough delegation", async function() {
@@ -133,46 +137,44 @@ describe("Dynamic Validator M -> M' (Changed the subset, M, M’ = maximum numbe
terms: 1
});
- const delegateToCharlie = await nodes[0].testFramework.rpc.chain.sendSignedTransaction(
- stake
- .createDelegateCCSTransaction(
- nodes[0].testFramework,
- validators[charlie].platformAddress,
- charlieDelegationToCatchBob
- )
- .sign({
- secret: faucetSecret,
- seq: await nodes[0].testFramework.rpc.chain.getSeq(
- faucetAddress
- ),
- fee: 10
- })
+ const delegateToCharlie = await nodes[0].rpc.mempool.sendSignedTransaction(
+ {
+ tx: stake
+ .createDelegateCCSTransaction(
+ nodes[0].testFramework,
+ validators[charlie].platformAddress,
+ charlieDelegationToCatchBob
+ )
+ .sign({
+ secret: faucetSecret,
+ seq: (await nodes[0].rpc.chain.getSeq({
+ address: faucetAddress.toString()
+ }))!,
+ fee: 10
+ })
+ .rlpBytes()
+ .toString("hex")
+ }
);
- await nodes[0].waitForTx(delegateToCharlie);
+ const delegateToCharlieH256 = new H256(delegateToCharlie);
+ await nodes[0].waitForTx(delegateToCharlieH256);
await expect(
- termThatIncludeTransaction(
- nodes[0].testFramework,
- delegateToCharlie
- )
- ).eventually.equal(1);
+ termThatIncludeTransaction(nodes[0].rpc, delegateToCharlieH256)
+ ).to.eventually.equal(1);
await termWaiter.waitNodeUntilTerm(nodes[0], {
target: 2,
termPeriods: 1
});
expect(
- (await stake.getJailed(nodes[0].testFramework)).map(x =>
- x.address.toString()
- )
+ (
+ await stake.getJailed(nodes[0].rpc, nodes[0].testFramework)
+ ).map(x => x.address.toString())
).contains(
validators[alice].platformAddress.toString(),
"Alice should be jailed for doing nothing"
);
- await expectAliceIsReplacedBy(
- nodes[0].testFramework,
- "Charlie",
- charlie
- );
+ await expectAliceIsReplacedBy(nodes[0].rpc, "Charlie", charlie);
});
it("Dave should be a validator when deposit enough", async function() {
@@ -182,8 +184,8 @@ describe("Dynamic Validator M -> M' (Changed the subset, M, M’ = maximum numbe
const depositDave = await nodes[
dave
- ].testFramework.rpc.chain.sendSignedTransaction(
- stake
+ ].rpc.mempool.sendSignedTransaction({
+ tx: stake
.createSelfNominateTransaction(
nodes[dave].testFramework,
daveDepositToCatchBob,
@@ -191,27 +193,29 @@ describe("Dynamic Validator M -> M' (Changed the subset, M, M’ = maximum numbe
)
.sign({
secret: validators[dave].privateKey,
- seq: await nodes[dave].testFramework.rpc.chain.getSeq(
- validators[dave].platformAddress
- ),
+ seq: (await nodes[dave].rpc.chain.getSeq({
+ address: validators[dave].platformAddress.toString()
+ }))!,
fee: 10
})
- );
- await nodes[0].waitForTx(depositDave);
+ .rlpBytes()
+ .toString("hex")
+ });
+ await nodes[0].waitForTx(new H256(depositDave));
await termWaiter.waitNodeUntilTerm(nodes[0], {
target: 2,
termPeriods: 1
});
expect(
- (await stake.getJailed(nodes[0].testFramework)).map(x =>
- x.address.toString()
- )
+ (
+ await stake.getJailed(nodes[0].rpc, nodes[0].testFramework)
+ ).map(x => x.address.toString())
).contains(
validators[alice].platformAddress.toString(),
"Alice should be jailed for doing nothing"
);
- await expectAliceIsReplacedBy(nodes[0].testFramework, "Dave", dave);
+ await expectAliceIsReplacedBy(nodes[0].rpc, "Dave", dave);
});
});
@@ -221,10 +225,10 @@ describe("Dynamic Validator M -> M' (Changed the subset, M, M’ = maximum numbe
beforeEach(async function() {
this.timeout(5000);
- await expectAllValidatorsArePossibleAuthors(nodes[0].testFramework);
+ await expectAllValidatorsArePossibleAuthors(nodes[0].rpc);
- const revokeTx = await nodes[0].testFramework.rpc.chain.sendSignedTransaction(
- stake
+ const revokeTx = await nodes[0].rpc.mempool.sendSignedTransaction({
+ tx: stake
.createRevokeTransaction(
nodes[0].testFramework,
validators[alice].platformAddress,
@@ -232,13 +236,15 @@ describe("Dynamic Validator M -> M' (Changed the subset, M, M’ = maximum numbe
)
.sign({
secret: faucetSecret,
- seq: await nodes[0].testFramework.rpc.chain.getSeq(
- faucetAddress
- ),
+ seq: (await nodes[0].rpc.chain.getSeq({
+ address: faucetAddress.toString()
+ }))!,
fee: 10
})
- );
- await nodes[0].waitForTx(revokeTx);
+ .rlpBytes()
+ .toString("hex")
+ });
+ await nodes[0].waitForTx(new H256(revokeTx));
});
it("Bob should be a validator when doing nothing", async function() {
@@ -251,7 +257,7 @@ describe("Dynamic Validator M -> M' (Changed the subset, M, M’ = maximum numbe
target: 2,
termPeriods: 1
});
- await expectAliceIsReplacedBy(nodes[0].testFramework, "Bob", bob);
+ await expectAliceIsReplacedBy(nodes[0].rpc, "Bob", bob);
});
it("Charlie should be a validator when gets enough delegation", async function() {
@@ -259,32 +265,32 @@ describe("Dynamic Validator M -> M' (Changed the subset, M, M’ = maximum numbe
terms: 1
});
- const delegateToCharlie = await nodes[0].testFramework.rpc.chain.sendSignedTransaction(
- stake
- .createDelegateCCSTransaction(
- nodes[0].testFramework,
- validators[charlie].platformAddress,
- charlieDelegationToCatchBob
- )
- .sign({
- secret: faucetSecret,
- seq: await nodes[0].testFramework.rpc.chain.getSeq(
- faucetAddress
- ),
- fee: 10
- })
+ const delegateToCharlie = await nodes[0].rpc.mempool.sendSignedTransaction(
+ {
+ tx: stake
+ .createDelegateCCSTransaction(
+ nodes[0].testFramework,
+ validators[charlie].platformAddress,
+ charlieDelegationToCatchBob
+ )
+ .sign({
+ secret: faucetSecret,
+ seq: (await nodes[0].rpc.chain.getSeq({
+ address: faucetAddress.toString()
+ }))!,
+ fee: 10
+ })
+ .rlpBytes()
+ .toString("hex")
+ }
);
- await nodes[0].waitForTx(delegateToCharlie);
+ await nodes[0].waitForTx(new H256(delegateToCharlie));
await termWaiter.waitNodeUntilTerm(nodes[0], {
target: 2,
termPeriods: 1
});
- await expectAliceIsReplacedBy(
- nodes[0].testFramework,
- "Charlie",
- charlie
- );
+ await expectAliceIsReplacedBy(nodes[0].rpc, "Charlie", charlie);
});
it("Dave should be a validator when deposit enough", async function() {
@@ -294,8 +300,8 @@ describe("Dynamic Validator M -> M' (Changed the subset, M, M’ = maximum numbe
const depositDave = await nodes[
dave
- ].testFramework.rpc.chain.sendSignedTransaction(
- stake
+ ].rpc.mempool.sendSignedTransaction({
+ tx: stake
.createSelfNominateTransaction(
nodes[dave].testFramework,
daveDepositToCatchBob,
@@ -303,19 +309,21 @@ describe("Dynamic Validator M -> M' (Changed the subset, M, M’ = maximum numbe
)
.sign({
secret: validators[dave].privateKey,
- seq: await nodes[dave].testFramework.rpc.chain.getSeq(
- validators[dave].platformAddress
- ),
+ seq: (await nodes[dave].rpc.chain.getSeq({
+ address: validators[dave].platformAddress.toString()
+ }))!,
fee: 10
})
- );
- await nodes[0].waitForTx(depositDave);
+ .rlpBytes()
+ .toString("hex")
+ });
+ await nodes[0].waitForTx(new H256(depositDave));
await termWaiter.waitNodeUntilTerm(nodes[0], {
target: 2,
termPeriods: 1
});
- await expectAliceIsReplacedBy(nodes[0].testFramework, "Dave", dave);
+ await expectAliceIsReplacedBy(nodes[0].rpc, "Dave", dave);
});
});
@@ -323,7 +331,7 @@ describe("Dynamic Validator M -> M' (Changed the subset, M, M’ = maximum numbe
const { nodes } = withNodes(this, nodeParams);
beforeEach(async function() {
- await expectAllValidatorsArePossibleAuthors(nodes[0].testFramework);
+ await expectAllValidatorsArePossibleAuthors(nodes[0].rpc);
});
it("Charlie should be a validator when gets enough delegation", async function() {
@@ -331,32 +339,32 @@ describe("Dynamic Validator M -> M' (Changed the subset, M, M’ = maximum numbe
terms: 1
});
- const delegateToCharlie = await nodes[0].testFramework.rpc.chain.sendSignedTransaction(
- stake
- .createDelegateCCSTransaction(
- nodes[0].testFramework,
- validators[charlie].platformAddress,
- charlieDelegationToCatchAlice
- )
- .sign({
- secret: faucetSecret,
- seq: await nodes[0].testFramework.rpc.chain.getSeq(
- faucetAddress
- ),
- fee: 10
- })
+ const delegateToCharlie = await nodes[0].rpc.mempool.sendSignedTransaction(
+ {
+ tx: stake
+ .createDelegateCCSTransaction(
+ nodes[0].testFramework,
+ validators[charlie].platformAddress,
+ charlieDelegationToCatchAlice
+ )
+ .sign({
+ secret: faucetSecret,
+ seq: (await nodes[0].rpc.chain.getSeq({
+ address: faucetAddress.toString()
+ }))!,
+ fee: 10
+ })
+ .rlpBytes()
+ .toString("hex")
+ }
);
- await nodes[0].waitForTx(delegateToCharlie);
+ await nodes[0].waitForTx(new H256(delegateToCharlie));
await termWaiter.waitNodeUntilTerm(nodes[0], {
target: 2,
termPeriods: 1
});
- await expectAliceIsReplacedBy(
- nodes[0].testFramework,
- "Charlie",
- charlie
- );
+ await expectAliceIsReplacedBy(nodes[0].rpc, "Charlie", charlie);
});
it("Dave should be a validator when deposit enough", async function() {
@@ -366,8 +374,8 @@ describe("Dynamic Validator M -> M' (Changed the subset, M, M’ = maximum numbe
const depositDave = await nodes[
dave
- ].testFramework.rpc.chain.sendSignedTransaction(
- stake
+ ].rpc.mempool.sendSignedTransaction({
+ tx: stake
.createSelfNominateTransaction(
nodes[dave].testFramework,
daveDepositToCatchAlice,
@@ -375,19 +383,21 @@ describe("Dynamic Validator M -> M' (Changed the subset, M, M’ = maximum numbe
)
.sign({
secret: validators[dave].privateKey,
- seq: await nodes[dave].testFramework.rpc.chain.getSeq(
- validators[dave].platformAddress
- ),
+ seq: (await nodes[dave].rpc.chain.getSeq({
+ address: validators[dave].platformAddress.toString()
+ }))!,
fee: 10
})
- );
- await nodes[0].waitForTx(depositDave);
+ .rlpBytes()
+ .toString("hex")
+ });
+ await nodes[0].waitForTx(new H256(depositDave));
await termWaiter.waitNodeUntilTerm(nodes[0], {
target: 2,
termPeriods: 1
});
- await expectAliceIsReplacedBy(nodes[0].testFramework, "Dave", dave);
+ await expectAliceIsReplacedBy(nodes[0].rpc, "Dave", dave);
});
});
diff --git a/test/src/e2e.dynval/1/dv.n'.test.ts b/test/src/e2e.dynval/1/dv.n'.test.ts
index 8921795fee..ffb2f9b56c 100644
--- a/test/src/e2e.dynval/1/dv.n'.test.ts
+++ b/test/src/e2e.dynval/1/dv.n'.test.ts
@@ -15,10 +15,11 @@
// along with this program. If not, see .
import { expect } from "chai";
+import RPC from "foundry-rpc";
import "mocha";
-import { SDK } from "../../sdk/src";
import * as stake from "../../stakeholder/src";
+import { H256 } from "codechain-primitives/lib";
import { validators } from "../../../tendermint.dynval/constants";
import { faucetAddress, faucetSecret } from "../../helper/constants";
import { PromiseExpect } from "../../helper/promise";
@@ -28,12 +29,12 @@ describe("Dynamic Validator N -> N'", function() {
const promiseExpect = new PromiseExpect();
async function expectPossibleAuthors(
- sdk: SDK,
+ rpc: RPC,
expected: typeof validators,
blockNumber?: number
) {
const authors = (await stake.getPossibleAuthors(
- sdk,
+ rpc,
blockNumber
))!.map(author => author.toString());
expect(authors)
@@ -71,7 +72,7 @@ describe("Dynamic Validator N -> N'", function() {
});
const rpcNode = nodes[0];
- await expectPossibleAuthors(rpcNode.testFramework, [
+ await expectPossibleAuthors(rpcNode.rpc, [
...validators.slice(0, 3),
alice
]);
@@ -84,13 +85,17 @@ describe("Dynamic Validator N -> N'", function() {
)
.sign({
secret: faucetSecret,
- seq: await rpcNode.testFramework.rpc.chain.getSeq(
- faucetAddress
- ),
+ seq: (await rpcNode.rpc.chain.getSeq({
+ address: faucetAddress.toString()
+ }))!,
fee: 10
});
await rpcNode.waitForTx(
- rpcNode.testFramework.rpc.chain.sendSignedTransaction(tx)
+ new H256(
+ await rpcNode.rpc.mempool.sendSignedTransaction({
+ tx: tx.rlpBytes().toString("hex")
+ })
+ )
);
await termWaiter.waitNodeUntilTerm(rpcNode, {
@@ -98,7 +103,7 @@ describe("Dynamic Validator N -> N'", function() {
termPeriods: 1
});
- await expectPossibleAuthors(rpcNode.testFramework, [
+ await expectPossibleAuthors(rpcNode.rpc, [
...validators.slice(0, 3),
betty
]);
@@ -133,7 +138,7 @@ describe("Dynamic Validator N -> N'", function() {
});
const rpcNode = nodes[0];
- await expectPossibleAuthors(rpcNode.testFramework, [
+ await expectPossibleAuthors(rpcNode.rpc, [
...validators.slice(0, 3),
alice
]);
@@ -147,14 +152,18 @@ describe("Dynamic Validator N -> N'", function() {
)
.sign({
secret: betty.privateKey,
- seq: await bettyNode.testFramework.rpc.chain.getSeq(
- betty.platformAddress
- ),
+ seq: (await bettyNode.rpc.chain.getSeq({
+ address: betty.platformAddress.toString()
+ }))!,
fee: 10
});
bettyNode.waitForTx(
- bettyNode.testFramework.rpc.chain.sendSignedTransaction(tx)
+ new H256(
+ await bettyNode.rpc.mempool.sendSignedTransaction({
+ tx: tx.rlpBytes().toString("hex")
+ })
+ )
);
await termWaiter.waitNodeUntilTerm(rpcNode, {
@@ -162,7 +171,7 @@ describe("Dynamic Validator N -> N'", function() {
termPeriods: 1
});
- await expectPossibleAuthors(rpcNode.testFramework, [
+ await expectPossibleAuthors(rpcNode.rpc, [
...validators.slice(0, 3),
betty
]);
@@ -193,14 +202,14 @@ describe("Dynamic Validator N -> N'", function() {
});
const rpcNode = nodes[0];
- await expectPossibleAuthors(rpcNode.testFramework, [
+ await expectPossibleAuthors(rpcNode.rpc, [
...validators.slice(0, 3),
alice
]);
- const seq = await rpcNode.testFramework.rpc.chain.getSeq(
- faucetAddress
- );
+ const seq = (await rpcNode.rpc.chain.getSeq({
+ address: faucetAddress.toString()
+ }))!;
const tx = stake
.createDelegateCCSTransaction(
rpcNode.testFramework,
@@ -224,8 +233,16 @@ describe("Dynamic Validator N -> N'", function() {
fee: 10
});
await rpcNode.waitForTx([
- rpcNode.testFramework.rpc.chain.sendSignedTransaction(tx),
- rpcNode.testFramework.rpc.chain.sendSignedTransaction(tx2)
+ new H256(
+ await rpcNode.rpc.mempool.sendSignedTransaction({
+ tx: tx.rlpBytes().toString("hex")
+ })
+ ),
+ new H256(
+ await rpcNode.rpc.mempool.sendSignedTransaction({
+ tx: tx2.rlpBytes().toString("hex")
+ })
+ )
]);
await termWaiter.waitNodeUntilTerm(rpcNode, {
@@ -233,7 +250,7 @@ describe("Dynamic Validator N -> N'", function() {
termPeriods: 1
});
- await expectPossibleAuthors(rpcNode.testFramework, [
+ await expectPossibleAuthors(rpcNode.rpc, [
...validators.slice(0, 3),
betty
]);
@@ -264,7 +281,7 @@ describe("Dynamic Validator N -> N'", function() {
});
const rpcNode = nodes[0];
- await expectPossibleAuthors(rpcNode.testFramework, [
+ await expectPossibleAuthors(rpcNode.rpc, [
...validators.slice(0, 3),
alice
]);
@@ -278,9 +295,9 @@ describe("Dynamic Validator N -> N'", function() {
)
.sign({
secret: betty.privateKey,
- seq: await bettyNode.testFramework.rpc.chain.getSeq(
- betty.platformAddress
- ),
+ seq: (await bettyNode.rpc.chain.getSeq({
+ address: betty.platformAddress.toString()
+ }))!,
fee: 10
});
@@ -292,17 +309,25 @@ describe("Dynamic Validator N -> N'", function() {
)
.sign({
secret: faucetSecret,
- seq: await rpcNode.testFramework.rpc.chain.getSeq(
- faucetAddress
- ),
+ seq: (await rpcNode.rpc.chain.getSeq({
+ address: faucetAddress.toString()
+ }))!,
fee: 10
});
await Promise.all([
bettyNode.waitForTx(
- bettyNode.testFramework.rpc.chain.sendSignedTransaction(tx)
+ new H256(
+ await bettyNode.rpc.mempool.sendSignedTransaction({
+ tx: tx.rlpBytes().toString("hex")
+ })
+ )
),
rpcNode.waitForTx(
- rpcNode.testFramework.rpc.chain.sendSignedTransaction(tx2)
+ new H256(
+ await rpcNode.rpc.mempool.sendSignedTransaction({
+ tx: tx2.rlpBytes().toString("hex")
+ })
+ )
)
]);
@@ -311,7 +336,7 @@ describe("Dynamic Validator N -> N'", function() {
termPeriods: 1
});
- await expectPossibleAuthors(rpcNode.testFramework, [
+ await expectPossibleAuthors(rpcNode.rpc, [
...validators.slice(0, 3),
betty
]);
diff --git a/test/src/e2e.dynval/1/dv.n-1.test.ts b/test/src/e2e.dynval/1/dv.n-1.test.ts
index 3c896ad73b..0cab509334 100644
--- a/test/src/e2e.dynval/1/dv.n-1.test.ts
+++ b/test/src/e2e.dynval/1/dv.n-1.test.ts
@@ -15,10 +15,11 @@
// along with this program. If not, see .
import { expect } from "chai";
+import RPC from "foundry-rpc";
import "mocha";
-import { SDK } from "../../sdk/src";
import * as stake from "../../stakeholder/src";
+import { H256 } from "codechain-primitives/lib";
import { validators as originalValidators } from "../../../tendermint.dynval/constants";
import { faucetAddress, faucetSecret } from "../../helper/constants";
import { PromiseExpect } from "../../helper/promise";
@@ -30,13 +31,13 @@ const [alice, ...otherDynValidators] = allDynValidators;
describe("Dynamic Validator N -> N-1", function() {
const promiseExpect = new PromiseExpect();
- async function aliceContainedCheck(sdk: SDK) {
- const blockNumber = await sdk.rpc.chain.getBestBlockNumber();
- const termMedata = await stake.getTermMetadata(sdk, blockNumber);
+ async function aliceContainedCheck(rpc: RPC) {
+ const blockNumber = await rpc.chain.getBestBlockNumber();
+ const termMedata = await stake.getTermMetadata(rpc, blockNumber);
const currentTermInitialBlockNumber =
termMedata!.lastTermFinishedBlockNumber + 1;
const validatorsBefore = (await stake.getPossibleAuthors(
- sdk,
+ rpc,
currentTermInitialBlockNumber
))!.map(platformAddr => platformAddr.toString());
@@ -48,13 +49,13 @@ describe("Dynamic Validator N -> N-1", function() {
);
}
- async function aliceDropOutCheck(sdk: SDK) {
- const blockNumber = await sdk.rpc.chain.getBestBlockNumber();
- const termMedata = await stake.getTermMetadata(sdk, blockNumber);
+ async function aliceDropOutCheck(rpc: RPC) {
+ const blockNumber = await rpc.chain.getBestBlockNumber();
+ const termMedata = await stake.getTermMetadata(rpc, blockNumber);
const currentTermInitialBlockNumber =
termMedata!.lastTermFinishedBlockNumber + 1;
const validatorsAfter = (await stake.getPossibleAuthors(
- sdk,
+ rpc,
currentTermInitialBlockNumber
))!.map(platformAddr => platformAddr.toString());
@@ -89,14 +90,14 @@ describe("Dynamic Validator N -> N-1", function() {
});
const checkingNode = nodes[1];
- await aliceContainedCheck(checkingNode.testFramework);
+ await aliceContainedCheck(checkingNode.rpc);
await termWaiter.waitNodeUntilTerm(checkingNode, {
target: 2,
termPeriods: 1
});
- await aliceDropOutCheck(checkingNode.testFramework);
+ await aliceDropOutCheck(checkingNode.rpc);
});
});
@@ -115,11 +116,11 @@ describe("Dynamic Validator N -> N-1", function() {
terms: 1
});
const checkingNode = nodes[1];
- await aliceContainedCheck(checkingNode.testFramework);
+ await aliceContainedCheck(checkingNode.rpc);
- const faucetSeq = await checkingNode.testFramework.rpc.chain.getSeq(
- faucetAddress
- );
+ const faucetSeq = (await checkingNode.rpc.chain.getSeq({
+ address: faucetAddress.toString()
+ }))!;
// Revoke all the delegation deposits
const tx = stake
.createRevokeTransaction(
@@ -132,16 +133,18 @@ describe("Dynamic Validator N -> N-1", function() {
seq: faucetSeq,
fee: 10
});
- const revokeTx = await checkingNode.testFramework.rpc.chain.sendSignedTransaction(
- tx
+ const revokeTx = await checkingNode.rpc.mempool.sendSignedTransaction(
+ {
+ tx: tx.rlpBytes().toString("hex")
+ }
);
- await checkingNode.waitForTx(revokeTx);
+ await checkingNode.waitForTx(new H256(revokeTx));
await termWaiter.waitNodeUntilTerm(checkingNode, {
target: 2,
termPeriods: 1
});
- await aliceDropOutCheck(checkingNode.testFramework);
+ await aliceDropOutCheck(checkingNode.rpc);
});
it("Revoke delegation deposits to make it be under threshold", async function() {
@@ -149,11 +152,11 @@ describe("Dynamic Validator N -> N-1", function() {
terms: 1
});
const checkingNode = nodes[1];
- await aliceContainedCheck(checkingNode.testFramework);
+ await aliceContainedCheck(checkingNode.rpc);
- const faucetSeq = await checkingNode.testFramework.rpc.chain.getSeq(
- faucetAddress
- );
+ const faucetSeq = (await checkingNode.rpc.chain.getSeq({
+ address: faucetAddress.toString()
+ }))!;
// make remaining deposits under threshold.
const tx = stake
.createRevokeTransaction(
@@ -166,16 +169,18 @@ describe("Dynamic Validator N -> N-1", function() {
seq: faucetSeq,
fee: 10
});
- const revokeTx = await checkingNode.testFramework.rpc.chain.sendSignedTransaction(
- tx
+ const revokeTx = await checkingNode.rpc.mempool.sendSignedTransaction(
+ {
+ tx: tx.rlpBytes().toString("hex")
+ }
);
- await checkingNode.waitForTx(revokeTx);
+ await checkingNode.waitForTx(new H256(revokeTx));
await termWaiter.waitNodeUntilTerm(checkingNode, {
target: 2,
termPeriods: 1
});
- await aliceDropOutCheck(checkingNode.testFramework);
+ await aliceDropOutCheck(checkingNode.rpc);
});
});
diff --git a/test/src/e2e.dynval/1/dv.n.test.ts b/test/src/e2e.dynval/1/dv.n.test.ts
index 34ccbf6a20..ffb667fb32 100644
--- a/test/src/e2e.dynval/1/dv.n.test.ts
+++ b/test/src/e2e.dynval/1/dv.n.test.ts
@@ -15,25 +15,26 @@
// along with this program. If not, see .
import { expect } from "chai";
+import RPC from "foundry-rpc";
import "mocha";
-import { SDK } from "../../sdk/src";
import * as stake from "../../stakeholder/src";
import { validators } from "../../../tendermint.dynval/constants";
import { faucetAddress, faucetSecret } from "../../helper/constants";
import { PromiseExpect } from "../../helper/promise";
import { findNode, setTermTestTimeout, withNodes } from "../setup";
+import { H256 } from "codechain-primitives/lib";
describe("Dynamic Validator N -> N", function() {
const promiseExpect = new PromiseExpect();
async function expectPossibleAuthors(
- sdk: SDK,
+ rpc: RPC,
expectedValidators: typeof validators,
blockNumber?: number
) {
const possibleAuthors = (await stake.getPossibleAuthors(
- sdk,
+ rpc,
blockNumber
))!;
expect(possibleAuthors).to.have.lengthOf(expectedValidators.length);
@@ -57,10 +58,7 @@ describe("Dynamic Validator N -> N", function() {
});
beforeEach(async function() {
- await expectPossibleAuthors(
- nodes[0].testFramework,
- initialValidators
- );
+ await expectPossibleAuthors(nodes[0].rpc, initialValidators);
});
it("should keep possible authors after a term change", async function() {
@@ -72,9 +70,9 @@ describe("Dynamic Validator N -> N", function() {
target: 2,
termPeriods: 1
});
- const blockNumber = await nodes[0].testFramework.rpc.chain.getBestBlockNumber();
+ const blockNumber = await nodes[0].rpc.chain.getBestBlockNumber();
const termMetadata = await stake.getTermMetadata(
- nodes[0].testFramework,
+ nodes[0].rpc,
blockNumber
);
expect(termMetadata).not.to.be.null;
@@ -84,7 +82,7 @@ describe("Dynamic Validator N -> N", function() {
);
await expectPossibleAuthors(
- nodes[0].testFramework,
+ nodes[0].rpc,
initialValidators,
blockNumber
);
@@ -111,10 +109,7 @@ describe("Dynamic Validator N -> N", function() {
const alice = validators[3];
beforeEach(async function() {
- await expectPossibleAuthors(
- nodes[0].testFramework,
- initialValidators
- );
+ await expectPossibleAuthors(nodes[0].rpc, initialValidators);
});
it("should keep possible authors after a term change", async function() {
@@ -122,30 +117,34 @@ describe("Dynamic Validator N -> N", function() {
terms: 1
});
- const insufficientDelegationTx = await nodes[0].testFramework.rpc.chain.sendSignedTransaction(
- stake
- .createDelegateCCSTransaction(
- nodes[0].testFramework,
- alice.platformAddress,
- 50
- )
- .sign({
- secret: faucetSecret,
- seq: await nodes[0].testFramework.rpc.chain.getSeq(
- faucetAddress
- ),
- fee: 10
- })
+ const insufficientDelegationTx = await nodes[0].rpc.mempool.sendSignedTransaction(
+ {
+ tx: stake
+ .createDelegateCCSTransaction(
+ nodes[0].testFramework,
+ alice.platformAddress,
+ 50
+ )
+ .sign({
+ secret: faucetSecret,
+ seq: (await nodes[0].rpc.chain.getSeq({
+ address: faucetAddress.toString()
+ }))!,
+ fee: 10
+ })
+ .rlpBytes()
+ .toString("hex")
+ }
);
- await nodes[0].waitForTx(insufficientDelegationTx);
+ await nodes[0].waitForTx(new H256(insufficientDelegationTx));
await termWaiter.waitNodeUntilTerm(nodes[0], {
target: 2,
termPeriods: 1
});
- const blockNumber = await nodes[0].testFramework.rpc.chain.getBestBlockNumber();
+ const blockNumber = await nodes[0].rpc.chain.getBestBlockNumber();
const termMetadata = await stake.getTermMetadata(
- nodes[0].testFramework,
+ nodes[0].rpc,
blockNumber
);
expect(termMetadata).not.to.be.null;
@@ -154,7 +153,7 @@ describe("Dynamic Validator N -> N", function() {
blockNumber
);
await expectPossibleAuthors(
- nodes[0].testFramework,
+ nodes[0].rpc,
initialValidators,
blockNumber
);
@@ -181,10 +180,7 @@ describe("Dynamic Validator N -> N", function() {
const alice = validators[3];
beforeEach(async function() {
- await expectPossibleAuthors(
- nodes[0].testFramework,
- initialValidators
- );
+ await expectPossibleAuthors(nodes[0].rpc, initialValidators);
});
it("should keep possible authors after a term change", async function() {
@@ -192,30 +188,34 @@ describe("Dynamic Validator N -> N", function() {
terms: 1
});
- const insufficientDelegationTx = await nodes[0].testFramework.rpc.chain.sendSignedTransaction(
- stake
- .createDelegateCCSTransaction(
- nodes[0].testFramework,
- alice.platformAddress,
- 50
- )
- .sign({
- secret: faucetSecret,
- seq: await nodes[0].testFramework.rpc.chain.getSeq(
- faucetAddress
- ),
- fee: 10
- })
+ const insufficientDelegationTx = await nodes[0].rpc.mempool.sendSignedTransaction(
+ {
+ tx: stake
+ .createDelegateCCSTransaction(
+ nodes[0].testFramework,
+ alice.platformAddress,
+ 50
+ )
+ .sign({
+ secret: faucetSecret,
+ seq: (await nodes[0].rpc.chain.getSeq({
+ address: faucetAddress.toString()
+ }))!,
+ fee: 10
+ })
+ .rlpBytes()
+ .toString("hex")
+ }
);
- await nodes[0].waitForTx(insufficientDelegationTx);
+ await nodes[0].waitForTx(new H256(insufficientDelegationTx));
await termWaiter.waitNodeUntilTerm(nodes[0], {
target: 2,
termPeriods: 1
});
- const blockNumber = await nodes[0].testFramework.rpc.chain.getBestBlockNumber();
+ const blockNumber = await nodes[0].rpc.chain.getBestBlockNumber();
const termMetadata = await stake.getTermMetadata(
- nodes[0].testFramework,
+ nodes[0].rpc,
blockNumber
);
expect(termMetadata).not.to.be.null;
@@ -224,7 +224,7 @@ describe("Dynamic Validator N -> N", function() {
blockNumber
);
await expectPossibleAuthors(
- nodes[0].testFramework,
+ nodes[0].rpc,
initialValidators,
blockNumber
);
@@ -251,10 +251,7 @@ describe("Dynamic Validator N -> N", function() {
const alice = validators[2];
beforeEach(async function() {
- await expectPossibleAuthors(
- nodes[0].testFramework,
- initialValidators
- );
+ await expectPossibleAuthors(nodes[0].rpc, initialValidators);
});
it("should keep possible authors after a term change", async function() {
@@ -262,30 +259,34 @@ describe("Dynamic Validator N -> N", function() {
terms: 1
});
- const insufficientDelegationTx = await nodes[0].testFramework.rpc.chain.sendSignedTransaction(
- stake
- .createRevokeTransaction(
- nodes[0].testFramework,
- alice.platformAddress,
- 50
- )
- .sign({
- secret: faucetSecret,
- seq: await nodes[0].testFramework.rpc.chain.getSeq(
- faucetAddress
- ),
- fee: 10
- })
+ const insufficientDelegationTx = await nodes[0].rpc.mempool.sendSignedTransaction(
+ {
+ tx: stake
+ .createRevokeTransaction(
+ nodes[0].testFramework,
+ alice.platformAddress,
+ 50
+ )
+ .sign({
+ secret: faucetSecret,
+ seq: (await nodes[0].rpc.chain.getSeq({
+ address: faucetAddress.toString()
+ }))!,
+ fee: 10
+ })
+ .rlpBytes()
+ .toString("hex")
+ }
);
- await nodes[0].waitForTx(insufficientDelegationTx);
+ await nodes[0].waitForTx(new H256(insufficientDelegationTx));
await termWaiter.waitNodeUntilTerm(nodes[0], {
target: 2,
termPeriods: 1
});
- const blockNumber = await nodes[0].testFramework.rpc.chain.getBestBlockNumber();
+ const blockNumber = await nodes[0].rpc.chain.getBestBlockNumber();
const termMetadata = await stake.getTermMetadata(
- nodes[0].testFramework,
+ nodes[0].rpc,
blockNumber
);
expect(termMetadata).not.to.be.null;
@@ -294,7 +295,7 @@ describe("Dynamic Validator N -> N", function() {
blockNumber
);
await expectPossibleAuthors(
- nodes[0].testFramework,
+ nodes[0].rpc,
initialValidators,
blockNumber
);
@@ -321,10 +322,7 @@ describe("Dynamic Validator N -> N", function() {
const alice = validators[2];
beforeEach(async function() {
- await expectPossibleAuthors(
- nodes[0].testFramework,
- initialValidators
- );
+ await expectPossibleAuthors(nodes[0].rpc, initialValidators);
});
it("should keep possible authors after a term change", async function() {
@@ -332,30 +330,34 @@ describe("Dynamic Validator N -> N", function() {
terms: 1
});
- const insufficientDelegationTx = await nodes[0].testFramework.rpc.chain.sendSignedTransaction(
- stake
- .createRevokeTransaction(
- nodes[0].testFramework,
- alice.platformAddress,
- 50
- )
- .sign({
- secret: faucetSecret,
- seq: await nodes[0].testFramework.rpc.chain.getSeq(
- faucetAddress
- ),
- fee: 10
- })
+ const insufficientDelegationTx = await nodes[0].rpc.mempool.sendSignedTransaction(
+ {
+ tx: stake
+ .createRevokeTransaction(
+ nodes[0].testFramework,
+ alice.platformAddress,
+ 50
+ )
+ .sign({
+ secret: faucetSecret,
+ seq: (await nodes[0].rpc.chain.getSeq({
+ address: faucetAddress.toString()
+ }))!,
+ fee: 10
+ })
+ .rlpBytes()
+ .toString("hex")
+ }
);
- await nodes[0].waitForTx(insufficientDelegationTx);
+ await nodes[0].waitForTx(new H256(insufficientDelegationTx));
await termWaiter.waitNodeUntilTerm(nodes[0], {
target: 2,
termPeriods: 1
});
- const blockNumber = await nodes[0].testFramework.rpc.chain.getBestBlockNumber();
+ const blockNumber = await nodes[0].rpc.chain.getBestBlockNumber();
const termMetadata = await stake.getTermMetadata(
- nodes[0].testFramework,
+ nodes[0].rpc,
blockNumber
);
expect(termMetadata).not.to.be.null;
@@ -364,7 +366,7 @@ describe("Dynamic Validator N -> N", function() {
blockNumber
);
await expectPossibleAuthors(
- nodes[0].testFramework,
+ nodes[0].rpc,
initialValidators,
blockNumber
);
@@ -392,10 +394,7 @@ describe("Dynamic Validator N -> N", function() {
const alice = validators[3];
beforeEach(async function() {
- await expectPossibleAuthors(
- nodes[0].testFramework,
- initialValidators
- );
+ await expectPossibleAuthors(nodes[0].rpc, initialValidators);
});
[
@@ -428,49 +427,57 @@ describe("Dynamic Validator N -> N", function() {
terms: 1
});
const aliceNode = findNode(nodes, alice);
- const nominationTx = await aliceNode.testFramework.rpc.chain.sendSignedTransaction(
- stake
- .createSelfNominateTransaction(
- aliceNode.testFramework,
- deposit,
- ""
- )
- .sign({
- secret: alice.privateKey,
- seq: await aliceNode.testFramework.rpc.chain.getSeq(
- alice.platformAddress
- ),
- fee: 10
- })
- );
- await nodes[0].waitForTx(nominationTx);
-
- if (delegation > 0) {
- const tx = await nodes[0].testFramework.rpc.chain.sendSignedTransaction(
- stake
- .createDelegateCCSTransaction(
- nodes[0].testFramework,
- alice.platformAddress,
- delegation
+ const nominationTx = await aliceNode.rpc.mempool.sendSignedTransaction(
+ {
+ tx: stake
+ .createSelfNominateTransaction(
+ aliceNode.testFramework,
+ deposit,
+ ""
)
.sign({
- secret: faucetSecret,
- seq: await nodes[0].testFramework.rpc.chain.getSeq(
- faucetAddress
- ),
+ secret: alice.privateKey,
+ seq: (await aliceNode.rpc.chain.getSeq({
+ address: alice.platformAddress.toString()
+ }))!,
fee: 10
})
+ .rlpBytes()
+ .toString("hex")
+ }
+ );
+ await nodes[0].waitForTx(new H256(nominationTx));
+
+ if (delegation > 0) {
+ const tx = await nodes[0].rpc.mempool.sendSignedTransaction(
+ {
+ tx: stake
+ .createDelegateCCSTransaction(
+ nodes[0].testFramework,
+ alice.platformAddress,
+ delegation
+ )
+ .sign({
+ secret: faucetSecret,
+ seq: (await nodes[0].rpc.chain.getSeq({
+ address: faucetAddress.toString()
+ }))!,
+ fee: 10
+ })
+ .rlpBytes()
+ .toString("hex")
+ }
);
- await nodes[0].waitForTx(tx);
+ await nodes[0].waitForTx(new H256(tx));
}
await termWaiter.waitNodeUntilTerm(nodes[0], {
target: 2,
termPeriods: 1
});
- const blockNumber = await nodes[0].testFramework.rpc.chain.getBestBlockNumber();
+ const blockNumber = await nodes[0].rpc.chain.getBestBlockNumber();
const termMetadata = await stake.getTermMetadata(
- nodes[0].testFramework,
+ nodes[0].rpc,
blockNumber
);
expect(termMetadata).not.to.be.null;
@@ -479,7 +486,7 @@ describe("Dynamic Validator N -> N", function() {
blockNumber
);
await expectPossibleAuthors(
- nodes[0].testFramework,
+ nodes[0].rpc,
initialValidators,
blockNumber
);
diff --git a/test/src/e2e.dynval/2/autoselfnomination.test.ts b/test/src/e2e.dynval/2/autoselfnomination.test.ts
index 02d94f8289..1bd3c97ccd 100644
--- a/test/src/e2e.dynval/2/autoselfnomination.test.ts
+++ b/test/src/e2e.dynval/2/autoselfnomination.test.ts
@@ -63,15 +63,14 @@ describe("Auto Self Nomination", function() {
const aliceNode = findNode(nodes, alice);
const selfNominationHash = await selfNominate(
+ aliceNode.rpc,
aliceNode.testFramework,
alice,
10
);
await aliceNode.waitForTx(selfNominationHash);
// bob will send self-nomination transaction automatically.
- const beforeCandidates = await stake.getCandidates(
- nodes[0].testFramework
- );
+ const beforeCandidates = await stake.getCandidates(nodes[0].rpc);
expect(
beforeCandidates.map(candidate => candidate.pubkey.toString())
@@ -91,10 +90,10 @@ describe("Auto Self Nomination", function() {
candidates,
jailed
] = await Promise.all([
- stake.getValidators(nodes[0].testFramework),
- stake.getBanned(nodes[0].testFramework),
- stake.getCandidates(nodes[0].testFramework),
- stake.getJailed(nodes[0].testFramework)
+ stake.getValidators(nodes[0].rpc, nodes[0].testFramework),
+ stake.getBanned(nodes[0].rpc, nodes[0].testFramework),
+ stake.getCandidates(nodes[0].rpc),
+ stake.getJailed(nodes[0].rpc, nodes[0].testFramework)
]);
expect(
diff --git a/test/src/e2e.dynval/2/dv.n+1.test.ts b/test/src/e2e.dynval/2/dv.n+1.test.ts
index 23437805df..96d3caa19e 100644
--- a/test/src/e2e.dynval/2/dv.n+1.test.ts
+++ b/test/src/e2e.dynval/2/dv.n+1.test.ts
@@ -15,14 +15,15 @@
// along with this program. If not, see .
import { expect } from "chai";
+import RPC from "foundry-rpc";
import "mocha";
-import { SDK } from "../../sdk/src";
import * as stake from "../../stakeholder/src";
import { validators } from "../../../tendermint.dynval/constants";
import { faucetAddress, faucetSecret } from "../../helper/constants";
import { PromiseExpect } from "../../helper/promise";
import { findNode, setTermTestTimeout, withNodes } from "../setup";
+import { H256 } from "codechain-primitives/lib";
describe("Dynamic Validator N -> N+1", function() {
const promiseExpect = new PromiseExpect();
@@ -30,13 +31,13 @@ describe("Dynamic Validator N -> N+1", function() {
const initialValidators = validators.slice(0, 3);
const betty = validators[3];
- async function beforeInsertionCheck(sdk: SDK) {
- const blockNumber = await sdk.rpc.chain.getBestBlockNumber();
- const termMedata = await stake.getTermMetadata(sdk, blockNumber);
+ async function beforeInsertionCheck(rpc: RPC) {
+ const blockNumber = await rpc.chain.getBestBlockNumber();
+ const termMedata = await stake.getTermMetadata(rpc, blockNumber);
const currentTermInitialBlockNumber =
termMedata!.lastTermFinishedBlockNumber + 1;
const validatorsBefore = (await stake.getPossibleAuthors(
- sdk,
+ rpc,
currentTermInitialBlockNumber
))!.map(platformAddr => platformAddr.toString());
@@ -50,13 +51,13 @@ describe("Dynamic Validator N -> N+1", function() {
);
}
- async function bettyInsertionCheck(sdk: SDK) {
- const blockNumber = await sdk.rpc.chain.getBestBlockNumber();
- const termMedata = await stake.getTermMetadata(sdk, blockNumber);
+ async function bettyInsertionCheck(rpc: RPC) {
+ const blockNumber = await rpc.chain.getBestBlockNumber();
+ const termMedata = await stake.getTermMetadata(rpc, blockNumber);
const currentTermInitialBlockNumber =
termMedata!.lastTermFinishedBlockNumber + 1;
const validatorsAfter = (await stake.getPossibleAuthors(
- sdk,
+ rpc,
currentTermInitialBlockNumber
))!.map(platformAddr => platformAddr.toString());
@@ -89,7 +90,7 @@ describe("Dynamic Validator N -> N+1", function() {
});
const checkingNode = nodes[0];
- await beforeInsertionCheck(checkingNode.testFramework);
+ await beforeInsertionCheck(checkingNode.rpc);
const bettyNode = findNode(nodes, betty);
const nominateTx = stake
.createSelfNominateTransaction(
@@ -99,13 +100,13 @@ describe("Dynamic Validator N -> N+1", function() {
)
.sign({
secret: betty.privateKey,
- seq: await bettyNode.testFramework.rpc.chain.getSeq(
- betty.platformAddress
- ),
+ seq: (await bettyNode.rpc.chain.getSeq({
+ address: betty.platformAddress.toString()
+ }))!,
fee: 10
});
- const nominateTxHash = bettyNode.testFramework.rpc.chain.sendSignedTransaction(
- nominateTx
+ const nominateTxHash = await bettyNode.rpc.mempool.sendSignedTransaction(
+ { tx: nominateTx.rlpBytes().toString("hex") }
);
const delegateTx = stake
.createDelegateCCSTransaction(
@@ -115,21 +116,24 @@ describe("Dynamic Validator N -> N+1", function() {
)
.sign({
secret: faucetSecret,
- seq: await bettyNode.testFramework.rpc.chain.getSeq(
- faucetAddress
- ),
+ seq: (await bettyNode.rpc.chain.getSeq({
+ address: faucetAddress.toString()
+ }))!,
fee: 10
});
- const delegateTxHash = bettyNode.testFramework.rpc.chain.sendSignedTransaction(
- delegateTx
+ const delegateTxHash = await bettyNode.rpc.mempool.sendSignedTransaction(
+ { tx: delegateTx.rlpBytes().toString("hex") }
);
- await checkingNode.waitForTx([nominateTxHash, delegateTxHash]);
+ await checkingNode.waitForTx([
+ new H256(nominateTxHash),
+ new H256(delegateTxHash)
+ ]);
await termWaiter.waitNodeUntilTerm(checkingNode, {
target: 2,
termPeriods: 1
});
- await bettyInsertionCheck(checkingNode.testFramework);
+ await bettyInsertionCheck(checkingNode.rpc);
});
});
@@ -152,7 +156,7 @@ describe("Dynamic Validator N -> N+1", function() {
});
const checkingNode = nodes[0];
- await beforeInsertionCheck(checkingNode.testFramework);
+ await beforeInsertionCheck(checkingNode.rpc);
const nominateTx = stake
.createSelfNominateTransaction(
checkingNode.testFramework,
@@ -161,21 +165,21 @@ describe("Dynamic Validator N -> N+1", function() {
)
.sign({
secret: betty.privateKey,
- seq: await checkingNode.testFramework.rpc.chain.getSeq(
- betty.platformAddress
- ),
+ seq: (await checkingNode.rpc.chain.getSeq({
+ address: betty.platformAddress.toString()
+ }))!,
fee: 10
});
- const nominateTxHash = checkingNode.testFramework.rpc.chain.sendSignedTransaction(
- nominateTx
+ const nominateTxHash = await checkingNode.rpc.mempool.sendSignedTransaction(
+ { tx: nominateTx.rlpBytes().toString("hex") }
);
- await checkingNode.waitForTx(nominateTxHash);
+ await checkingNode.waitForTx(new H256(nominateTxHash));
await termWaiter.waitNodeUntilTerm(checkingNode, {
target: 2,
termPeriods: 1
});
- await bettyInsertionCheck(checkingNode.testFramework);
+ await bettyInsertionCheck(checkingNode.rpc);
});
});
@@ -198,10 +202,10 @@ describe("Dynamic Validator N -> N+1", function() {
});
const checkingNode = nodes[0];
- await beforeInsertionCheck(checkingNode.testFramework);
- const faucetSeq = await checkingNode.testFramework.rpc.chain.getSeq(
- faucetAddress
- );
+ await beforeInsertionCheck(checkingNode.rpc);
+ const faucetSeq = (await checkingNode.rpc.chain.getSeq({
+ address: faucetAddress.toString()
+ }))!;
const delegateTx = stake
.createDelegateCCSTransaction(
checkingNode.testFramework,
@@ -213,16 +217,16 @@ describe("Dynamic Validator N -> N+1", function() {
seq: faucetSeq,
fee: 10
});
- const delegateTxHash = checkingNode.testFramework.rpc.chain.sendSignedTransaction(
- delegateTx
+ const delegateTxHash = await checkingNode.rpc.mempool.sendSignedTransaction(
+ { tx: delegateTx.rlpBytes().toString("hex") }
);
- await checkingNode.waitForTx(delegateTxHash);
+ await checkingNode.waitForTx(new H256(delegateTxHash));
await termWaiter.waitNodeUntilTerm(checkingNode, {
target: 2,
termPeriods: 1
});
- await bettyInsertionCheck(checkingNode.testFramework);
+ await bettyInsertionCheck(checkingNode.rpc);
});
});
diff --git a/test/src/e2e.dynval/2/dv.nomination.test.ts b/test/src/e2e.dynval/2/dv.nomination.test.ts
index b89d7c7610..d9e3379b7e 100644
--- a/test/src/e2e.dynval/2/dv.nomination.test.ts
+++ b/test/src/e2e.dynval/2/dv.nomination.test.ts
@@ -58,15 +58,14 @@ describe("Nomination", function() {
const aliceNode = findNode(nodes, alice);
const selfNominationHash = await selfNominate(
+ aliceNode.rpc,
aliceNode.testFramework,
alice,
10
);
await aliceNode.waitForTx(selfNominationHash);
- const beforeCandidates = await stake.getCandidates(
- nodes[0].testFramework
- );
+ const beforeCandidates = await stake.getCandidates(nodes[0].rpc);
expect(
beforeCandidates.map(candidate => candidate.pubkey.toString())
@@ -83,10 +82,10 @@ describe("Nomination", function() {
candidates,
jailed
] = await Promise.all([
- stake.getValidators(nodes[0].testFramework),
- stake.getBanned(nodes[0].testFramework),
- stake.getCandidates(nodes[0].testFramework),
- stake.getJailed(nodes[0].testFramework)
+ stake.getValidators(nodes[0].rpc, nodes[0].testFramework),
+ stake.getBanned(nodes[0].rpc, nodes[0].testFramework),
+ stake.getCandidates(nodes[0].rpc),
+ stake.getJailed(nodes[0].rpc, nodes[0].testFramework)
]);
expect(
diff --git a/test/src/e2e.dynval/2/dv.shutdown.test.ts b/test/src/e2e.dynval/2/dv.shutdown.test.ts
index 15f4821334..6abac6cae8 100644
--- a/test/src/e2e.dynval/2/dv.shutdown.test.ts
+++ b/test/src/e2e.dynval/2/dv.shutdown.test.ts
@@ -70,7 +70,7 @@ describe("Shutdown test", function() {
beforeEach(async function() {
const possibleAuthors = (await stake.getPossibleAuthors(
- nodes[0].testFramework
+ nodes[0].rpc
))!;
expect(
possibleAuthors.map(x => x.toString()),
@@ -85,14 +85,14 @@ describe("Shutdown test", function() {
termSeconds: number
): Promise {
const node = getObserver().node;
- const sdk = node.testFramework;
+ const rpc = node.rpc;
const lastTermFinishedBlockNumber = (await stake.getTermMetadata(
- sdk
+ rpc
))!.lastTermFinishedBlockNumber;
- const lastTermFinishedTS = (await sdk.rpc.chain.getBlock(
- lastTermFinishedBlockNumber
- ))!.timestamp;
+ const lastTermFinishedTS = (await rpc.chain.getBlockByNumber({
+ blockNumber: lastTermFinishedBlockNumber
+ }))!.timestamp;
const nextTermExpectedTS =
Math.floor(lastTermFinishedTS / termSeconds) * termSeconds +
termSeconds;
@@ -101,9 +101,9 @@ describe("Shutdown test", function() {
let lastBlockNumber: number;
while (true) {
lastBlockNumber = await node.getBestBlockNumber();
- const block = (await node.testFramework.rpc.chain.getBlock(
- lastBlockNumber
- ))!;
+ const block = (await node.rpc.chain.getBlockByNumber({
+ blockNumber: lastBlockNumber
+ }))!;
if (block.timestamp >= targetTS) {
return;
}
@@ -131,7 +131,7 @@ describe("Shutdown test", function() {
"Should have stopped nodes in time, otherwise it is flaky test"
);
const termMetadata = await stake.getTermMetadata(
- getObserver().node.testFramework
+ getObserver().node.rpc
);
expect(termMetadata).is.not.null;
expect(termMetadata!.currentTermId).is.equals(
@@ -139,7 +139,7 @@ describe("Shutdown test", function() {
"Term should haven't be closed yet"
);
const possibleAuthors = (await stake.getPossibleAuthors(
- getObserver().node.testFramework
+ getObserver().node.rpc
))!;
expect(
possibleAuthors.map(x => x.toString()),
@@ -157,13 +157,14 @@ describe("Shutdown test", function() {
// Wait for it should close the term
await getObserver().node.waitBlockNumber(lastBlockNumberOfTerm + 1);
const termMetadata = await stake.getTermMetadata(
- getObserver().node.testFramework,
+ getObserver().node.rpc,
lastBlockNumberOfTerm + 1
);
expect(termMetadata).is.not.null;
expect(termMetadata!.currentTermId).is.equals(2);
{
const jailed = await stake.getJailed(
+ getObserver().node.rpc,
getObserver().node.testFramework
);
expect(
@@ -173,7 +174,7 @@ describe("Shutdown test", function() {
"All Betas should be jailed (might be some alphas)"
);
const possibleAuthors = (await stake.getPossibleAuthors(
- getObserver().node.testFramework
+ getObserver().node.rpc
))!;
expect(getAlphas().addrs).to.include.members(
possibleAuthors.map(x => x.toString()),
@@ -222,7 +223,7 @@ describe("Shutdown test", function() {
const blockNumberAtStop = await getObserver().node.getBestBlockNumber();
{
const termMetadata = await stake.getTermMetadata(
- getObserver().node.testFramework
+ getObserver().node.rpc
);
expect(termMetadata).is.not.null;
expect(termMetadata!.currentTermId).is.equals(1);
@@ -231,7 +232,7 @@ describe("Shutdown test", function() {
"Should have stopped nodes in time, otherwise it is flaky test"
);
const possibleAuthors = (await stake.getPossibleAuthors(
- getObserver().node.testFramework
+ getObserver().node.rpc
))!;
expect(
possibleAuthors.map(x => x.toString()),
@@ -248,7 +249,7 @@ describe("Shutdown test", function() {
await getObserver().node.waitBlockNumber(blockNumberAtStop + 1);
{
const termMetadata = await stake.getTermMetadata(
- getObserver().node.testFramework,
+ getObserver().node.rpc,
blockNumberAtStop + 1
);
expect(termMetadata).is.not.null;
@@ -256,8 +257,8 @@ describe("Shutdown test", function() {
2,
"Term should be changed"
);
- const block = (await getObserver().node.testFramework.rpc.chain.getBlock(
- blockNumberAtStop + 1
+ const block = (await getObserver().node.rpc.chain.getBlockByNumber(
+ { blockNumber: blockNumberAtStop + 1 }
))!;
expect(getValidators().addrs).to.include(
block.author.toString(),
@@ -265,6 +266,7 @@ describe("Shutdown test", function() {
);
const jailed = await stake.getJailed(
+ getObserver().node.rpc,
getObserver().node.testFramework
);
expect(
@@ -278,7 +280,7 @@ describe("Shutdown test", function() {
)
);
const possibleAuthors = (await stake.getPossibleAuthors(
- getObserver().node.testFramework
+ getObserver().node.rpc
))!;
expect(
possibleAuthors.map(x => x.toString())
diff --git a/test/src/e2e.dynval/2/jail.test.ts b/test/src/e2e.dynval/2/jail.test.ts
index 9f3371c220..f66e76e548 100644
--- a/test/src/e2e.dynval/2/jail.test.ts
+++ b/test/src/e2e.dynval/2/jail.test.ts
@@ -23,6 +23,7 @@ import * as stake from "../../stakeholder/src";
import { validators } from "../../../tendermint.dynval/constants";
import { PromiseExpect } from "../../helper/promise";
import { setTermTestTimeout, withNodes } from "../setup";
+import { H256 } from "codechain-primitives/lib";
chai.use(chaiAsPromised);
@@ -49,21 +50,27 @@ describe("Jail state transition test", function() {
async function isValidator(
entity: typeof validators[number]
): Promise {
- const activated = await stake.getValidators(nodes[0].testFramework);
+ const activated = await stake.getValidators(
+ nodes[0].rpc,
+ nodes[0].testFramework
+ );
return activated.some(v => v.pubkey.toString() === entity.publicKey);
}
async function isCandidate(
entity: typeof validators[number]
): Promise {
- const candidates = await stake.getCandidates(nodes[0].testFramework);
+ const candidates = await stake.getCandidates(nodes[0].rpc);
return candidates.some(c => c.pubkey.toString() === entity.publicKey);
}
async function isBanned(
entity: typeof validators[number]
): Promise {
- const banned = await stake.getBanned(nodes[0].testFramework);
+ const banned = await stake.getBanned(
+ nodes[0].rpc,
+ nodes[0].testFramework
+ );
return banned.some(
b => b.getAccountId().toString() === entity.accountId
);
@@ -72,7 +79,10 @@ describe("Jail state transition test", function() {
async function isPrisoner(
entity: typeof validators[number]
): Promise {
- const prisoners = await stake.getJailed(nodes[0].testFramework);
+ const prisoners = await stake.getJailed(
+ nodes[0].rpc,
+ nodes[0].testFramework
+ );
return prisoners.some(
p => p.address.toString() === entity.platformAddress.toString()
);
@@ -126,16 +136,19 @@ describe("Jail state transition test", function() {
10_000_000,
""
);
- const hash = await node.testFramework.rpc.chain.sendSignedTransaction(
- nomination.sign({
- secret: alice.privateKey,
- seq: await node.testFramework.rpc.chain.getSeq(
- alice.platformAddress
- ),
- fee: 10
- })
- );
- await node.waitForTx(hash);
+ const hash = await node.rpc.mempool.sendSignedTransaction({
+ tx: nomination
+ .sign({
+ secret: alice.privateKey,
+ seq: (await node.rpc.chain.getSeq({
+ address: alice.platformAddress.toString()
+ }))!,
+ fee: 10
+ })
+ .rlpBytes()
+ .toString("hex")
+ });
+ await node.waitForTx(new H256(hash));
await termWaiter.waitNodeUntilTerm(node, { target: 5, termPeriods: 1 });
expect(await isCandidate(alice)).to.be.true;
@@ -152,16 +165,19 @@ describe("Jail state transition test", function() {
10_000_000,
""
);
- const hash = await node.testFramework.rpc.chain.sendSignedTransaction(
- nomination.sign({
- secret: alice.privateKey,
- seq: await node.testFramework.rpc.chain.getSeq(
- alice.platformAddress
- ),
- fee: 10
- })
- );
- await expect(node.waitForTx(hash)).rejectedWith(
+ const hash = await node.rpc.mempool.sendSignedTransaction({
+ tx: nomination
+ .sign({
+ secret: alice.privateKey,
+ seq: (await node.rpc.chain.getSeq({
+ address: alice.platformAddress.toString()
+ }))!,
+ fee: 10
+ })
+ .rlpBytes()
+ .toString("hex")
+ });
+ await expect(node.waitForTx(new H256(hash))).rejectedWith(
"Account is still in custody"
);
await termWaiter.waitNodeUntilTerm(node, { target: 3, termPeriods: 1 });
diff --git a/test/src/e2e.dynval/2/snapshot.test.ts b/test/src/e2e.dynval/2/snapshot.test.ts
index 0a5c72b223..61c42bef40 100644
--- a/test/src/e2e.dynval/2/snapshot.test.ts
+++ b/test/src/e2e.dynval/2/snapshot.test.ts
@@ -17,10 +17,10 @@
import * as chai from "chai";
import { expect } from "chai";
import * as chaiAsPromised from "chai-as-promised";
+import RPC from "foundry-rpc";
import * as fs from "fs";
import "mocha";
import * as path from "path";
-import { SDK } from "../../sdk/src";
import * as stake from "../../stakeholder/src";
import mkdirp = require("mkdirp");
@@ -29,6 +29,7 @@ import { faucetAddress, faucetSecret } from "../../helper/constants";
import { PromiseExpect } from "../../helper/promise";
import CodeChain, { Signer } from "../../helper/spawn";
import { setTermTestTimeout, withNodes } from "../setup";
+import { H256 } from "codechain-primitives/lib";
chai.use(chaiAsPromised);
@@ -122,17 +123,17 @@ describe("Snapshot for Tendermint with Dynamic Validator", function() {
termPeriods: 2
});
- await freshValidatorCheck(nodes[0].testFramework);
+ await freshValidatorCheck(nodes[0].rpc);
expect(
- await node.testFramework.rpc.chain.getBlock(
- snapshotBlock.number - 1
- )
+ await node.rpc.chain.getBlockByNumber({
+ blockNumber: snapshotBlock.number - 1
+ })
).to.be.null;
expect(
- await node.testFramework.rpc.chain.getBlock(
- snapshotBlock.number
- )
+ await node.rpc.chain.getBlockByNumber({
+ blockNumber: snapshotBlock.number
+ })
).not.to.be.null;
// Check that the freshNodeValidator is still a validator & make sure it doesn't have a block/header before termMetadata1.
} catch (e) {
@@ -147,13 +148,13 @@ describe("Snapshot for Tendermint with Dynamic Validator", function() {
promiseExpect.checkFulfilled();
});
- async function freshValidatorCheck(sdk: SDK) {
- const blockNumber = await sdk.rpc.chain.getBestBlockNumber();
- const termMedata = await stake.getTermMetadata(sdk, blockNumber);
+ async function freshValidatorCheck(rpc: RPC) {
+ const blockNumber = await rpc.chain.getBestBlockNumber();
+ const termMedata = await stake.getTermMetadata(rpc, blockNumber);
const currentTermInitialBlockNumber =
termMedata!.lastTermFinishedBlockNumber + 1;
const validatorsAfter = (await stake.getPossibleAuthors(
- sdk,
+ rpc,
currentTermInitialBlockNumber
))!.map(platformAddr => platformAddr.toString());
@@ -169,11 +170,13 @@ async function getSnapshotBlock(
) {
const blockNumber = termMetadata.lastTermFinishedBlockNumber + 1;
await node.waitBlockNumber(blockNumber);
- return (await node.testFramework.rpc.chain.getBlock(blockNumber))!;
+ return (await node.rpc.chain.getBlockByNumber({ blockNumber }))!;
}
async function makeItValidator(node: CodeChain, freshNodeValidator: Signer) {
- const faucetSeq = await node.testFramework.rpc.chain.getSeq(faucetAddress);
+ const faucetSeq = (await node.rpc.chain.getSeq({
+ address: faucetAddress.toString()
+ }))!;
const payTx = node.testFramework.core
.createPayTransaction({
recipient: freshNodeValidator.platformAddress,
@@ -185,19 +188,27 @@ async function makeItValidator(node: CodeChain, freshNodeValidator: Signer) {
fee: 10
});
await node.waitForTx(
- await node.testFramework.rpc.chain.sendSignedTransaction(payTx)
+ new H256(
+ await node.rpc.mempool.sendSignedTransaction({
+ tx: payTx.rlpBytes().toString("hex")
+ })
+ )
);
const selfNominateTx = stake
.createSelfNominateTransaction(node.testFramework, 10000000, "")
.sign({
secret: freshNodeValidator.privateKey,
- seq: await node.testFramework.rpc.chain.getSeq(
- freshNodeValidator.platformAddress
- ),
+ seq: (await node.rpc.chain.getSeq({
+ address: freshNodeValidator.platformAddress.toString()
+ }))!,
fee: 10
});
await node.waitForTx(
- await node.testFramework.rpc.chain.sendSignedTransaction(selfNominateTx)
+ new H256(
+ await node.rpc.mempool.sendSignedTransaction({
+ tx: selfNominateTx.rlpBytes().toString("hex")
+ })
+ )
);
const delegateTx = stake
.createDelegateCCSTransaction(
@@ -211,6 +222,10 @@ async function makeItValidator(node: CodeChain, freshNodeValidator: Signer) {
fee: 10
});
await node.waitForTx(
- await node.testFramework.rpc.chain.sendSignedTransaction(delegateTx)
+ new H256(
+ await node.rpc.mempool.sendSignedTransaction({
+ tx: delegateTx.rlpBytes().toString("hex")
+ })
+ )
);
}
diff --git a/test/src/e2e.dynval/dv.double-vote.test.ts b/test/src/e2e.dynval/dv.double-vote.test.ts
index 9bb61016b1..aa0cfea5bc 100644
--- a/test/src/e2e.dynval/dv.double-vote.test.ts
+++ b/test/src/e2e.dynval/dv.double-vote.test.ts
@@ -23,6 +23,7 @@ import {
signSchnorr,
U64
} from "codechain-primitives/lib";
+import RPC from "foundry-rpc";
import "mocha";
import * as RLP from "rlp";
import { SDK } from "../sdk/src";
@@ -113,12 +114,12 @@ const allDynValidators = originalValidators.slice(0, 4);
const [alice, ...otherDynValidators] = allDynValidators;
async function expectPossibleAuthors(
- sdk: SDK,
+ rpc: RPC,
expected: Signer[],
blockNumber?: number
) {
const authors = (await stake.getPossibleAuthors(
- sdk,
+ rpc,
blockNumber
))!.map(author => author.toString());
expect(authors)
@@ -129,13 +130,13 @@ async function expectPossibleAuthors(
}
// FIXME: neeeds to use common refactored function when gets banned state accounts
-async function ensureAliceIsBanned(sdk: SDK, blockNumber: number) {
+async function ensureAliceIsBanned(rpc: RPC, sdk: SDK, blockNumber: number) {
const bannedAfter = (
- await stake.getBanned(sdk, blockNumber)
+ await stake.getBanned(rpc, sdk, blockNumber)
).map(platformAddr => platformAddr.toString());
expect(bannedAfter).to.includes(alice.platformAddress.toString());
const delegteesAfter = (
- await stake.getDelegations(sdk, faucetAddress, blockNumber)
+ await stake.getDelegations(rpc, sdk, faucetAddress, blockNumber)
).map(delegation => delegation.delegatee.toString());
expect(delegteesAfter).not.to.includes(alice.platformAddress.toString());
}
@@ -144,10 +145,10 @@ describe("Report Double Vote", function() {
const promiseExpect = new PromiseExpect();
async function getAliceIndex(
- sdk: SDK,
+ rpc: RPC,
blockNumber: number
): Promise {
- return (await stake.getPossibleAuthors(sdk, blockNumber))!
+ return (await stake.getPossibleAuthors(rpc, blockNumber))!
.map(platfromAddr => platfromAddr.toString())
.indexOf(alice.platformAddress.toString());
}
@@ -158,8 +159,7 @@ describe("Report Double Vote", function() {
): Promise {
await checkingNode.waitForTx(reportTxHash);
const blockNumberAfterReport =
- (await checkingNode.testFramework.rpc.chain.getBestBlockNumber()) +
- 1;
+ (await checkingNode.rpc.chain.getBestBlockNumber()) + 1;
await checkingNode.waitBlockNumber(blockNumberAfterReport);
return blockNumberAfterReport;
}
@@ -180,23 +180,20 @@ describe("Report Double Vote", function() {
this.timeout(secsPerblock * 14 * 1000);
const checkingNode = nodes[1];
- const blockNumber = await checkingNode.testFramework.rpc.chain.getBestBlockNumber();
+ const blockNumber = await checkingNode.rpc.chain.getBestBlockNumber();
const termMetadata = await stake.getTermMetadata(
- checkingNode.testFramework,
+ checkingNode.rpc,
blockNumber
);
const currentTermInitialBlockNumber =
termMetadata!.lastTermFinishedBlockNumber + 1;
expect(termMetadata!.currentTermId).to.be.equals(1);
- await expectPossibleAuthors(
- checkingNode.testFramework,
- allDynValidators
- );
+ await expectPossibleAuthors(checkingNode.rpc, allDynValidators);
await checkingNode.waitBlockNumber(
currentTermInitialBlockNumber + 1
);
const aliceIdx = await getAliceIndex(
- checkingNode.testFramework,
+ checkingNode.rpc,
currentTermInitialBlockNumber
);
@@ -221,20 +218,26 @@ describe("Report Double Vote", function() {
message1,
message2
);
- const reportTxHash = await checkingNode.testFramework.rpc.chain.sendSignedTransaction(
- reportTx.sign({
- secret: faucetSecret,
- seq: await checkingNode.testFramework.rpc.chain.getSeq(
- faucetAddress
- ),
- fee: 10
- })
+ const reportTxHash = await checkingNode.rpc.mempool.sendSignedTransaction(
+ {
+ tx: reportTx
+ .sign({
+ secret: faucetSecret,
+ seq: (await checkingNode.rpc.chain.getSeq({
+ address: faucetAddress.toString()
+ }))!,
+ fee: 10
+ })
+ .rlpBytes()
+ .toString("hex")
+ }
);
const blockNumberAfterReport = await waitUntilAliceGetBanned(
checkingNode,
- reportTxHash
+ new H256(reportTxHash)
);
await ensureAliceIsBanned(
+ checkingNode.rpc,
checkingNode.testFramework,
blockNumberAfterReport
);
@@ -255,19 +258,24 @@ describe("Report Double Vote", function() {
}
});
- async function ensureAliceIsJailed(sdk: SDK, bestBlockNumber: number) {
+ async function ensureAliceIsJailed(
+ rpc: RPC,
+ sdk: SDK,
+ bestBlockNumber: number
+ ) {
const jailedBefore = (
- await stake.getJailed(sdk, bestBlockNumber)
+ await stake.getJailed(rpc, sdk, bestBlockNumber)
).map(prisoner => prisoner.address.toString());
expect(jailedBefore).to.includes(alice.platformAddress.toString());
}
async function ensureAliceIsReleased(
+ rpc: RPC,
sdk: SDK,
bestBlockNumber: number
) {
const jailedAfter = (
- await stake.getJailed(sdk, bestBlockNumber)
+ await stake.getJailed(rpc, sdk, bestBlockNumber)
).map(prisoner => prisoner.address.toString());
expect(jailedAfter).not.to.includes(
alice.platformAddress.toString()
@@ -284,24 +292,22 @@ describe("Report Double Vote", function() {
target: 2,
termPeriods: 1
});
- const blockNumber = await checkingNode.testFramework.rpc.chain.getBestBlockNumber();
+ const blockNumber = await checkingNode.rpc.chain.getBestBlockNumber();
const termMetadata = (await stake.getTermMetadata(
- checkingNode.testFramework,
+ checkingNode.rpc,
blockNumber
))!;
expect(termMetadata!.currentTermId).to.be.equals(2);
- await expectPossibleAuthors(
- checkingNode.testFramework,
- otherDynValidators
- );
+ await expectPossibleAuthors(checkingNode.rpc, otherDynValidators);
await ensureAliceIsJailed(
+ checkingNode.rpc,
checkingNode.testFramework,
termMetadata.lastTermFinishedBlockNumber
);
const aliceIdxInPrevTerm = await getAliceIndex(
- checkingNode.testFramework,
+ checkingNode.rpc,
termMetadata.lastTermFinishedBlockNumber
);
@@ -326,24 +332,31 @@ describe("Report Double Vote", function() {
message1,
message2
);
- const reportTxHash = await checkingNode.testFramework.rpc.chain.sendSignedTransaction(
- reportTx.sign({
- secret: faucetSecret,
- seq: await checkingNode.testFramework.rpc.chain.getSeq(
- faucetAddress
- ),
- fee: 10
- })
+ const reportTxHash = await checkingNode.rpc.mempool.sendSignedTransaction(
+ {
+ tx: reportTx
+ .sign({
+ secret: faucetSecret,
+ seq: (await checkingNode.rpc.chain.getSeq({
+ address: faucetAddress.toString()
+ }))!,
+ fee: 10
+ })
+ .rlpBytes()
+ .toString("hex")
+ }
);
const blockNumberAfterReport = await waitUntilAliceGetBanned(
checkingNode,
- reportTxHash
+ new H256(reportTxHash)
);
await ensureAliceIsBanned(
+ checkingNode.rpc,
checkingNode.testFramework,
blockNumberAfterReport
);
await ensureAliceIsReleased(
+ checkingNode.rpc,
checkingNode.testFramework,
blockNumberAfterReport
);
@@ -363,9 +376,13 @@ describe("Report Double Vote", function() {
}
});
- async function ensureAliceIsACandidate(sdk: SDK, blockNumber?: number) {
+ async function ensureAliceIsACandidate(
+ rpc: RPC,
+ sdk: SDK,
+ blockNumber?: number
+ ) {
const candidatesBefore = (
- await stake.getCandidates(sdk, blockNumber)
+ await stake.getCandidates(rpc, blockNumber)
).map(candidate =>
PlatformAddress.fromPublic(candidate.pubkey, {
networkId: "tc"
@@ -377,11 +394,11 @@ describe("Report Double Vote", function() {
}
async function ensureAliceIsNotACandidate(
- sdk: SDK,
+ rpc: RPC,
blockNumber?: number
) {
const candidatesAfter = (
- await stake.getCandidates(sdk, blockNumber)
+ await stake.getCandidates(rpc, blockNumber)
).map(candidate =>
PlatformAddress.fromPublic(candidate.pubkey, {
networkId: "tc"
@@ -398,9 +415,9 @@ describe("Report Double Vote", function() {
});
const checkingNode = nodes[1];
- const blockNumber = await checkingNode.testFramework.rpc.chain.getBestBlockNumber();
+ const blockNumber = await checkingNode.rpc.chain.getBestBlockNumber();
const termMetadata = await stake.getTermMetadata(
- checkingNode.testFramework,
+ checkingNode.rpc,
blockNumber
);
const currentTermInitialBlockNumber =
@@ -410,7 +427,7 @@ describe("Report Double Vote", function() {
);
const aliceIdx = await getAliceIndex(
- checkingNode.testFramework,
+ checkingNode.rpc,
currentTermInitialBlockNumber
);
@@ -422,24 +439,24 @@ describe("Report Double Vote", function() {
)
.sign({
secret: faucetSecret,
- seq: await checkingNode.testFramework.rpc.chain.getSeq(
- faucetAddress
- ),
+ seq: (await checkingNode.rpc.chain.getSeq({
+ address: faucetAddress.toString()
+ }))!,
fee: 10
});
- const revokeTxHash = await checkingNode.testFramework.rpc.chain.sendSignedTransaction(
- revoketx
+ const revokeTxHash = await checkingNode.rpc.mempool.sendSignedTransaction(
+ { tx: revoketx.rlpBytes().toString("hex") }
);
- await checkingNode.waitForTx(revokeTxHash);
+ await checkingNode.waitForTx(new H256(revokeTxHash));
await termWaiter.waitNodeUntilTerm(checkingNode, {
target: 2,
termPeriods: 1
});
- await expectPossibleAuthors(
- checkingNode.testFramework,
- otherDynValidators
+ await expectPossibleAuthors(checkingNode.rpc, otherDynValidators);
+ await ensureAliceIsACandidate(
+ checkingNode.rpc,
+ checkingNode.testFramework
);
- await ensureAliceIsACandidate(checkingNode.testFramework);
const [message1, message2] = createDoubleVoteMessages(
{
@@ -462,25 +479,31 @@ describe("Report Double Vote", function() {
message1,
message2
);
- const reportTxHash = await checkingNode.testFramework.rpc.chain.sendSignedTransaction(
- reportTx.sign({
- secret: faucetSecret,
- seq: await checkingNode.testFramework.rpc.chain.getSeq(
- faucetAddress
- ),
- fee: 10
- })
+ const reportTxHash = await checkingNode.rpc.mempool.sendSignedTransaction(
+ {
+ tx: reportTx
+ .sign({
+ secret: faucetSecret,
+ seq: (await checkingNode.rpc.chain.getSeq({
+ address: faucetAddress.toString()
+ }))!,
+ fee: 10
+ })
+ .rlpBytes()
+ .toString("hex")
+ }
);
const blockNumberAfterReport = await waitUntilAliceGetBanned(
checkingNode,
- reportTxHash
+ new H256(reportTxHash)
);
await ensureAliceIsBanned(
+ checkingNode.rpc,
checkingNode.testFramework,
blockNumberAfterReport
);
await ensureAliceIsNotACandidate(
- checkingNode.testFramework,
+ checkingNode.rpc,
blockNumberAfterReport
);
});
diff --git a/test/src/e2e.dynval/setup.ts b/test/src/e2e.dynval/setup.ts
index 4bf662bf57..7af4ad75d6 100644
--- a/test/src/e2e.dynval/setup.ts
+++ b/test/src/e2e.dynval/setup.ts
@@ -15,6 +15,7 @@
// along with this program. If not, see .
import { blake256, H256, U64Value } from "codechain-primitives/lib";
+import RPC from "foundry-rpc";
import { Context, Suite } from "mocha";
import {
aliceSecret,
@@ -178,9 +179,9 @@ async function createNodes(options: {
await fullyConnect(initialNodes.concat(nodes), promiseExpect);
// Give CCC to deposit
- const faucetSeq = await initialNodes[0].testFramework.rpc.chain.getSeq(
- faucetAddress
- );
+ const faucetSeq = (await initialNodes[0].rpc.chain.getSeq({
+ address: faucetAddress.toString()
+ }))!;
const payTxs: (H256 | Promise)[] = [];
for (let i = 0; i < validators.length; i++) {
const { signer: validator } = validators[i];
@@ -195,8 +196,10 @@ async function createNodes(options: {
fee: 10
});
payTxs.push(
- await initialNodes[0].testFramework.rpc.chain.sendSignedTransaction(
- tx
+ new H256(
+ await initialNodes[0].rpc.mempool.sendSignedTransaction({
+ tx: tx.rlpBytes().toString("hex")
+ })
)
);
}
@@ -220,20 +223,24 @@ async function createNodes(options: {
)
.sign({
secret: validator.privateKey,
- seq: await nodes[i].testFramework.rpc.chain.getSeq(
- validator.platformAddress
- ),
+ seq: (await nodes[i].rpc.chain.getSeq({
+ address: validator.platformAddress.toString()
+ }))!,
fee: 10
});
stakeTxs.push(
- await nodes[i].testFramework.rpc.chain.sendSignedTransaction(tx)
+ new H256(
+ await nodes[i].rpc.mempool.sendSignedTransaction({
+ tx: tx.rlpBytes().toString("hex")
+ })
+ )
);
}
// Delegate CCS to become validators
- const faucetSeq2 = await initialNodes[0].testFramework.rpc.chain.getSeq(
- faucetAddress
- );
+ const faucetSeq2 = (await initialNodes[0].rpc.chain.getSeq({
+ address: faucetAddress.toString()
+ }))!;
const delegateTxs = [];
for (let i = 0; i < validators.length; i++) {
const { signer: validator, deposit, delegation = 0 } = validators[
@@ -263,8 +270,10 @@ async function createNodes(options: {
fee: 10
});
delegateTxs.push(
- await initialNodes[0].testFramework.rpc.chain.sendSignedTransaction(
- tx
+ new H256(
+ await initialNodes[0].rpc.mempool.sendSignedTransaction({
+ tx: tx.rlpBytes().toString("hex")
+ })
)
);
}
@@ -311,20 +320,28 @@ async function createNodes(options: {
}
export async function selfNominate(
+ rpc: RPC,
sdk: SDK,
validator: ValidatorConfig["signer"],
deposit: number
): Promise {
const tx = stake.createSelfNominateTransaction(sdk, deposit, "").sign({
secret: validator.privateKey,
- seq: await sdk.rpc.chain.getSeq(validator.platformAddress),
+ seq: (await rpc.chain.getSeq({
+ address: validator.platformAddress.toString()
+ }))!,
fee: 10
});
- return await sdk.rpc.chain.sendSignedTransaction(tx);
+ return new H256(
+ await rpc.mempool.sendSignedTransaction({
+ tx: tx.rlpBytes().toString("hex")
+ })
+ );
}
export async function receiveDelegation(
+ rpc: RPC,
sdk: SDK,
validator: ValidatorConfig["signer"],
delegation: number
@@ -337,10 +354,16 @@ export async function receiveDelegation(
)
.sign({
secret: faucetSecret,
- seq: await sdk.rpc.chain.getSeq(faucetAddress),
+ seq: (await rpc.chain.getSeq({
+ address: faucetAddress.toString()
+ }))!,
fee: 10
});
- return await sdk.rpc.chain.sendSignedTransaction(tx);
+ return new H256(
+ await rpc.mempool.sendSignedTransaction({
+ tx: tx.rlpBytes().toString("hex")
+ })
+ );
}
export async function fullyConnect(
@@ -459,17 +482,23 @@ export async function changeParams(
changeParamsActionRlp.push(`0x${SDK.util.signEcdsa(message, aliceSecret)}`);
changeParamsActionRlp.push(`0x${SDK.util.signEcdsa(message, bobSecret)}`);
- return await node.testFramework.rpc.chain.sendSignedTransaction(
- node.testFramework.core
- .createCustomTransaction({
- handlerId: stakeActionHandlerId,
- bytes: RLP.encode(changeParamsActionRlp)
- })
- .sign({
- secret: faucetSecret,
- seq: await node.testFramework.rpc.chain.getSeq(faucetAddress),
- fee: 10
- })
+ return new H256(
+ await node.rpc.mempool.sendSignedTransaction({
+ tx: node.testFramework.core
+ .createCustomTransaction({
+ handlerId: stakeActionHandlerId,
+ bytes: RLP.encode(changeParamsActionRlp)
+ })
+ .sign({
+ secret: faucetSecret,
+ seq: (await node.rpc.chain.getSeq({
+ address: faucetAddress.toString()
+ }))!,
+ fee: 10
+ })
+ .rlpBytes()
+ .toString("hex")
+ })
);
}
@@ -523,12 +552,14 @@ export function setTermTestTimeout(
}
export async function termThatIncludeTransaction(
- sdk: SDK,
+ rpc: RPC,
txHash: H256
): Promise {
- const transaction = await sdk.rpc.chain.getTransaction(txHash);
+ const transaction = await rpc.chain.getTransaction({
+ transactionHash: `0x${txHash.toString()}`
+ });
const minedBlock = transaction!.blockNumber!;
- const termMetadata = await stake.getTermMetadata(sdk, minedBlock);
+ const termMetadata = await stake.getTermMetadata(rpc, minedBlock);
if (minedBlock > termMetadata!.lastTermFinishedBlockNumber) {
return termMetadata!.currentTermId;
diff --git a/test/src/e2e/chain.test.ts b/test/src/e2e/chain.test.ts
index 829ae9ed5c..1876408067 100644
--- a/test/src/e2e/chain.test.ts
+++ b/test/src/e2e/chain.test.ts
@@ -25,7 +25,8 @@ import {
invalidAddress
} from "../helper/constants";
import CodeChain from "../helper/spawn";
-import { H160, H256, U64 } from "../sdk/src/core/classes";
+import { PlatformAddress } from "../sdk/src/core/classes";
+import { H160, H256, H512, U64 } from "../sdk/src/core/classes";
const RLP = require("rlp");
describe("chain", function() {
@@ -80,10 +81,14 @@ describe("chain", function() {
blockNumber: bestBlockNumber
});
expect(
- (await node.testFramework.rpc.chain.getBlock(blockHash!))!.number
+ (await node.rpc.chain.getBlockByHash({ blockHash: blockHash! }))!
+ .number
).to.equal(bestBlockNumber);
- expect(await node.testFramework.rpc.chain.getBlock(invalidH256)).to.be
- .null;
+ expect(
+ await node.rpc.chain.getBlockByHash({
+ blockHash: `0x${invalidH256.toString()}`
+ })
+ ).to.be.null;
});
it("getSeq", async function() {
@@ -97,7 +102,7 @@ describe("chain", function() {
blockNumber: null
})
).to.equal(0);
- const bestBlockNumber = await node.testFramework.rpc.chain.getBestBlockNumber();
+ const bestBlockNumber = await node.rpc.chain.getBestBlockNumber();
await node.rpc.chain.getSeq({
address: faucetAddress.toString(),
blockNumber: 0
@@ -160,16 +165,14 @@ describe("chain", function() {
});
it("getBlockReward", async function() {
- // FIXME: Add an API to SDK
- const reward = await node.testFramework.rpc.sendRpcRequest(
- "engine_getBlockReward",
- [10]
- );
+ const reward = (await node.rpc.engine.getBlockReward({
+ blockNumber: 10
+ }))!;
expect(reward).to.equal(0);
});
it("getPendingTransactions", async function() {
- const pending = await node.testFramework.rpc.chain.getPendingTransactions();
+ const pending = await node.rpc.mempool.getPendingTransactions();
expect(pending.transactions.length).to.equal(0);
});
@@ -182,21 +185,26 @@ describe("chain", function() {
address: faucetAddress.toString(),
blockNumber: null
}))!;
- const hash = await node.testFramework.rpc.chain.sendSignedTransaction(
- tx.sign({
- secret: faucetSecret,
- fee: 10,
- seq
- })
- );
+ const sig = tx.sign({
+ secret: faucetSecret,
+ fee: 10,
+ seq
+ });
+ const bytes = sig.rlpBytes().toString("hex");
+ const hash = await node.rpc.mempool.sendSignedTransaction({
+ tx: `0x${bytes}`
+ });
expect(
await node.rpc.chain.containsTransaction({
- transactionHash: "0x".concat(hash.toString())
+ transactionHash: hash
})
).be.true;
- const signed = await node.testFramework.rpc.chain.getTransaction(hash);
- expect(signed).not.null;
- expect(signed!.unsigned).to.deep.equal(tx);
+ const thetx = (await node.rpc.chain.getTransaction({
+ transactionHash: hash
+ }))!;
+ expect(thetx).not.null;
+ expect(thetx.sig).to.equal(`0x${sig.signature()}`);
+ expect(+thetx.fee).to.equal(Number(tx.fee()!.toString()));
});
it("sendPayTx, getTransactionSigner", async function() {
@@ -208,26 +216,37 @@ describe("chain", function() {
address: faucetAddress.toString(),
blockNumber: null
}))!;
- const hash = await node.testFramework.rpc.chain.sendSignedTransaction(
- tx.sign({
- secret: faucetSecret,
- fee: 10,
- seq
- })
- );
- expect(await node.testFramework.rpc.chain.containsTransaction(hash)).be
- .true;
- const signer = await node.testFramework.rpc.sendRpcRequest(
- "chain_getTransactionSigner",
- [hash]
- );
+ const sig = tx.sign({
+ secret: faucetSecret,
+ fee: 10,
+ seq
+ });
+ const bytes = sig.rlpBytes().toString("hex");
+ const hash = await node.rpc.mempool.sendSignedTransaction({
+ tx: `0x${bytes}`
+ });
+ expect(
+ await node.rpc.chain.containsTransaction({ transactionHash: hash })
+ ).be.true;
+ const signer = await node.rpc.chain.getTransactionSigner({
+ transactionHash: hash
+ });
expect(signer).equal(faucetAddress.toString());
- const signed = await node.testFramework.rpc.chain.getTransaction(hash);
+ const signed = (await node.rpc.chain.getTransaction({
+ transactionHash: hash
+ }))!;
+ const publicKey = new H512(
+ node.testFramework.util.recoverEcdsa(
+ tx.unsignedHash().toString(),
+ signed.sig
+ )
+ );
expect(signed).not.null;
- expect(signed!.unsigned).to.deep.equal(tx);
+ expect(signed.sig).to.equal(`0x${sig.signature()}`);
+ expect(+signed.fee).to.equal(Number(tx.fee()!.toString()));
expect(
node.testFramework.core.classes.PlatformAddress.fromPublic(
- signed!.getSignerPublic(),
+ publicKey,
{ networkId: "tc" }
).toString()
).equal(signer);
diff --git a/test/src/e2e/changeParams.test.ts b/test/src/e2e/changeParams.test.ts
index 8513c17247..f5f1b871b4 100644
--- a/test/src/e2e/changeParams.test.ts
+++ b/test/src/e2e/changeParams.test.ts
@@ -32,6 +32,7 @@ import {
} from "../helper/constants";
import CodeChain from "../helper/spawn";
import { blake256 } from "../sdk/src/utils";
+import { ERROR } from "../helper/error";
const RLP = require("rlp");
@@ -97,34 +98,38 @@ describe("ChangeParams", function() {
);
{
- const hash = await node.testFramework.rpc.chain.sendSignedTransaction(
- node.testFramework.core
- .createCustomTransaction({
- handlerId: stakeActionHandlerId,
- bytes: RLP.encode(changeParams)
- })
- .sign({
- secret: faucetSecret,
- seq: (await node.rpc.chain.getSeq({
- address: faucetAddress.toString(),
- blockNumber: null
- }))!,
- fee: 10
- })
- );
+ const tx = node.testFramework.core
+ .createCustomTransaction({
+ handlerId: stakeActionHandlerId,
+ bytes: RLP.encode(changeParams)
+ })
+ .sign({
+ secret: faucetSecret,
+ seq: (await node.rpc.chain.getSeq({
+ address: faucetAddress.toString(),
+ blockNumber: null
+ }))!,
+ fee: 10
+ });
+ const trans = tx.rlpBytes().toString("hex");
+ const hash = await node.rpc.mempool.sendSignedTransaction({
+ tx: trans
+ });
expect(
await node.rpc.chain.containsTransaction({
- transactionHash: "0x".concat(hash.toString())
+ transactionHash: hash
})
).be.true;
}
-
- await expect(node.sendPayTx({ fee: 10 })).rejectedWith(/Too Low Fee/);
- const params = await node.testFramework.rpc.sendRpcRequest(
- "chain_getCommonParams",
- [null]
- );
- expect(U64.ensure(params.minPayCost)).to.be.deep.equal(new U64(11));
+ try {
+ await expect(node.sendPayTx({ fee: 10 }));
+ } catch (e) {
+ expect(e.toString()).is.include(
+ ERROR.ACTION_DATA_HANDLER_NOT_FOUND
+ );
+ }
+ const params = await node.rpc.chain.getCommonParams({});
+ expect(+params!.minPayCost!).to.be.deep.equal(11);
});
it("cannot change the network id", async function() {
@@ -176,17 +181,22 @@ describe("ChangeParams", function() {
}))!,
fee: 10
});
- await expect(
- node.testFramework.rpc.chain.sendSignedTransaction(tx)
- ).rejectedWith(/network id/);
+ const trans = tx.rlpBytes().toString("hex");
+ try {
+ await node.rpc.mempool.sendSignedTransaction({ tx: `0x${trans}` });
+ expect.fail();
+ } catch (e) {
+ expect(e.toString()).is.include(
+ ERROR.ACTION_DATA_HANDLER_NOT_FOUND
+ );
+ }
});
it("should keep default common params value", async function() {
- const params = await node.testFramework.rpc.sendRpcRequest(
- "chain_getCommonParams",
- [null]
- );
- expect(U64.ensure(params.minPayCost)).to.be.deep.equal(new U64(10));
+ const params = await node.rpc.chain.getCommonParams({
+ blockNumber: null
+ });
+ expect(+params!.minPayCost!).to.be.deep.equal(10);
});
it("the parameter is applied from the next block", async function() {
@@ -235,23 +245,25 @@ describe("ChangeParams", function() {
address: faucetAddress.toString(),
blockNumber: null
}))!;
- const changeHash = await node.testFramework.rpc.chain.sendSignedTransaction(
- node.testFramework.core
- .createCustomTransaction({
- handlerId: stakeActionHandlerId,
- bytes: RLP.encode(changeParams)
- })
- .sign({
- secret: faucetSecret,
- seq,
- fee: 10
- })
- );
+ const tx = node.testFramework.core
+ .createCustomTransaction({
+ handlerId: stakeActionHandlerId,
+ bytes: RLP.encode(changeParams)
+ })
+ .sign({
+ secret: faucetSecret,
+ seq,
+ fee: 10
+ });
+ const trans = tx.rlpBytes().toString("hex");
+ const changeHash = await node.rpc.mempool.sendSignedTransaction({
+ tx: `0x${trans}`
+ });
const pay = await node.sendPayTx({ seq: seq + 1, fee: 10 });
await node.rpc.devel!.startSealing();
expect(
await node.rpc.chain.containsTransaction({
- transactionHash: "0x".concat(changeHash.toString())
+ transactionHash: changeHash
})
).be.true;
expect(
@@ -263,8 +275,12 @@ describe("ChangeParams", function() {
blockNumber + 1
);
}
-
- await expect(node.sendPayTx({ fee: 10 })).rejectedWith(/Too Low Fee/);
+ try {
+ await node.sendPayTx({ fee: 10 });
+ expect.fail();
+ } catch (e) {
+ expect(e.toString()).is.include(ERROR.TOO_LOW_FEE);
+ }
});
it("the parameter changed twice in the same block", async function() {
@@ -350,39 +366,44 @@ describe("ChangeParams", function() {
address: faucetAddress.toString(),
blockNumber: null
}))!;
- const changeHash1 = await node.testFramework.rpc.chain.sendSignedTransaction(
- node.testFramework.core
- .createCustomTransaction({
- handlerId: stakeActionHandlerId,
- bytes: RLP.encode(changeParams1)
- })
- .sign({
- secret: faucetSecret,
- seq,
- fee: 10
- })
- );
- const changeHash2 = await node.testFramework.rpc.chain.sendSignedTransaction(
- node.testFramework.core
- .createCustomTransaction({
- handlerId: stakeActionHandlerId,
- bytes: RLP.encode(changeParams2)
- })
- .sign({
- secret: faucetSecret,
- seq: seq + 1,
- fee: 10
- })
- );
+
+ const tx = node.testFramework.core
+ .createCustomTransaction({
+ handlerId: stakeActionHandlerId,
+ bytes: RLP.encode(changeParams1)
+ })
+ .sign({
+ secret: faucetSecret,
+ seq,
+ fee: 10
+ });
+ const trans = tx.rlpBytes().toString("hex");
+ const changeHash1 = await node.rpc.mempool.sendSignedTransaction({
+ tx: `0x${trans}`
+ });
+ const tx2 = node.testFramework.core
+ .createCustomTransaction({
+ handlerId: stakeActionHandlerId,
+ bytes: RLP.encode(changeParams2)
+ })
+ .sign({
+ secret: faucetSecret,
+ seq: seq + 1,
+ fee: 10
+ });
+ const trans2 = tx2.rlpBytes().toString("hex");
+ const changeHash2 = await node.rpc.mempool.sendSignedTransaction({
+ tx: `0x${trans2}`
+ });
await node.rpc.devel!.startSealing();
expect(
await node.rpc.chain.containsTransaction({
- transactionHash: "0x".concat(changeHash1.toString())
+ transactionHash: changeHash1
})
).be.true;
expect(
await node.rpc.chain.containsTransaction({
- transactionHash: "0x".concat(changeHash2.toString())
+ transactionHash: changeHash2
})
).be.true;
expect(await node.rpc.chain.getBestBlockNumber()).equal(
@@ -393,10 +414,15 @@ describe("ChangeParams", function() {
const pay = await node.sendPayTx({ fee: 5 });
expect(
await node.rpc.chain.containsTransaction({
- transactionHash: "0x".concat(pay.hash().toString())
+ transactionHash: `0x${pay.hash().toString()}`
})
).be.true;
- await expect(node.sendPayTx({ fee: 4 })).rejectedWith(/Too Low Fee/);
+ try {
+ await node.sendPayTx({ fee: 4 });
+ expect.fail();
+ } catch (e) {
+ expect(e.toString()).is.include(ERROR.TOO_LOW_FEE);
+ }
});
it("cannot reuse the same signature", async function() {
@@ -477,44 +503,49 @@ describe("ChangeParams", function() {
{
await node.rpc.devel!.stopSealing();
- const blockNumber = await node.testFramework.rpc.chain.getBestBlockNumber();
+ const blockNumber = await node.rpc.chain.getBestBlockNumber();
const seq = (await node.rpc.chain.getSeq({
address: faucetAddress.toString(),
blockNumber: null
}))!;
- const changeHash1 = await node.testFramework.rpc.chain.sendSignedTransaction(
- node.testFramework.core
- .createCustomTransaction({
- handlerId: stakeActionHandlerId,
- bytes: RLP.encode(changeParams1)
- })
- .sign({
- secret: faucetSecret,
- seq,
- fee: 10
- })
- );
- const changeHash2 = await node.testFramework.rpc.chain.sendSignedTransaction(
- node.testFramework.core
- .createCustomTransaction({
- handlerId: stakeActionHandlerId,
- bytes: RLP.encode(changeParams2)
- })
- .sign({
- secret: faucetSecret,
- seq: seq + 1,
- fee: 10
- })
- );
+ const tx1 = node.testFramework.core
+ .createCustomTransaction({
+ handlerId: stakeActionHandlerId,
+ bytes: RLP.encode(changeParams1)
+ })
+ .sign({
+ secret: faucetSecret,
+ seq,
+ fee: 10
+ });
+
+ const trans1 = tx1.rlpBytes().toString("hex");
+ const changeHash1 = await node.rpc.mempool.sendSignedTransaction({
+ tx: `0x${trans1}`
+ });
+ const tx2 = node.testFramework.core
+ .createCustomTransaction({
+ handlerId: stakeActionHandlerId,
+ bytes: RLP.encode(changeParams2)
+ })
+ .sign({
+ secret: faucetSecret,
+ seq: seq + 1,
+ fee: 10
+ });
+ const trans2 = tx2.rlpBytes().toString("hex");
+ const changeHash2 = await node.rpc.mempool.sendSignedTransaction({
+ tx: `0x${trans2}`
+ });
await node.rpc.devel!.startSealing();
expect(
await node.rpc.chain.containsTransaction({
- transactionHash: "0x".concat(changeHash1.toString())
+ transactionHash: changeHash1
})
).be.true;
expect(
await node.rpc.chain.containsTransaction({
- transactionHash: "0x".concat(changeHash2.toString())
+ transactionHash: changeHash2
})
).be.true;
expect(await node.rpc.chain.getBestBlockNumber()).equal(
@@ -528,7 +559,12 @@ describe("ChangeParams", function() {
transactionHash: "0x".concat(pay.hash().toString())
})
).be.true;
- await expect(node.sendPayTx({ fee: 4 })).rejectedWith(/Too Low Fee/);
+ try {
+ await node.sendPayTx({ fee: 4 });
+ expect.fail();
+ } catch (e) {
+ expect(e.toString()).is.include(ERROR.TOO_LOW_FEE);
+ }
});
it("cannot change params with insufficient stakes", async function() {
@@ -568,46 +604,48 @@ describe("ChangeParams", function() {
);
{
- const hash = await node.testFramework.rpc.chain.sendSignedTransaction(
- node.testFramework.core
- .createCustomTransaction({
- handlerId: stakeActionHandlerId,
- bytes: RLP.encode(changeParams)
- })
- .sign({
- secret: faucetSecret,
- seq: (await node.rpc.chain.getSeq({
- address: faucetAddress.toString(),
- blockNumber: null
- }))!,
- fee: 10
- })
- );
+ const tx = node.testFramework.core
+ .createCustomTransaction({
+ handlerId: stakeActionHandlerId,
+ bytes: RLP.encode(changeParams)
+ })
+ .sign({
+ secret: faucetSecret,
+ seq: (await node.rpc.chain.getSeq({
+ address: faucetAddress.toString(),
+ blockNumber: null
+ }))!,
+ fee: 10
+ });
+ const trans = tx.rlpBytes().toString("hex");
+ const hash = await node.rpc.mempool.sendSignedTransaction({
+ tx: `${trans}`
+ });
expect(
await node.rpc.chain.containsTransaction({
- transactionHash: "0x".concat(hash.toString())
+ transactionHash: hash
})
).be.true;
}
{
- await node.sendSignedTransactionExpectedToFail(
- node.testFramework.core
- .createCustomTransaction({
- handlerId: stakeActionHandlerId,
- bytes: RLP.encode(changeParams)
- })
- .sign({
- secret: faucetSecret,
- seq:
- (await node.rpc.chain.getSeq({
- address: faucetAddress.toString(),
- blockNumber: null
- }))! + 1,
- fee: 10
- }),
- { error: "Invalid transaction seq Expected 1, found 0" }
- );
+ const tx2 = node.testFramework.core
+ .createCustomTransaction({
+ handlerId: stakeActionHandlerId,
+ bytes: RLP.encode(changeParams)
+ })
+ .sign({
+ secret: faucetSecret,
+ seq:
+ (await node.rpc.chain.getSeq({
+ address: faucetAddress.toString(),
+ blockNumber: null
+ }))! + 1,
+ fee: 10
+ });
+ await node.sendSignedTransactionExpectedToFail(tx2, {
+ error: "Invalid transaction seq Expected 1, found 0"
+ });
}
});
@@ -746,19 +784,25 @@ describe("ChangeParams", function() {
}))!,
fee: 10
});
- const hash = await node.testFramework.rpc.chain.sendSignedTransaction(
- tx
- );
+ const trans = tx.rlpBytes().toString("hex");
+ const hash = await node.rpc.mempool.sendSignedTransaction({
+ tx: `0x${trans}`
+ });
expect(
await node.rpc.chain.containsTransaction({
- transactionHash: "0x".concat(hash.toString())
+ transactionHash: hash
})
).be.true;
- expect(await node.testFramework.rpc.chain.getTransaction(hash)).not
- .be.null;
+ expect(
+ await node.rpc.chain.getTransaction({ transactionHash: hash })
+ ).not.be.null;
+ }
+ try {
+ await node.sendPayTx({ fee: 10 });
+ expect.fail();
+ } catch (e) {
+ expect(e.toString()).is.include(ERROR.TOO_LOW_FEE);
}
-
- await expect(node.sendPayTx({ fee: 10 })).rejectedWith(/Too Low Fee/);
});
describe("with stake parameters", async function() {
@@ -799,37 +843,41 @@ describe("ChangeParams", function() {
);
{
- const hash = await node.testFramework.rpc.chain.sendSignedTransaction(
- node.testFramework.core
- .createCustomTransaction({
- handlerId: stakeActionHandlerId,
- bytes: RLP.encode(changeParams)
- })
- .sign({
- secret: faucetSecret,
- seq: (await node.rpc.chain.getSeq({
- address: faucetAddress.toString(),
- blockNumber: null
- }))!,
- fee: 10
- })
- );
+ const tx = node.testFramework.core
+ .createCustomTransaction({
+ handlerId: stakeActionHandlerId,
+ bytes: RLP.encode(changeParams)
+ })
+ .sign({
+ secret: faucetSecret,
+ seq: (await node.rpc.chain.getSeq({
+ address: faucetAddress.toString(),
+ blockNumber: null
+ }))!,
+ fee: 10
+ });
+ const trans = tx.rlpBytes().toString("hex");
+ const hash = await node.rpc.mempool.sendSignedTransaction({
+ tx: `0x${trans}`
+ });
expect(
await node.rpc.chain.containsTransaction({
- transactionHash: "0x".concat(hash.toString())
+ transactionHash: hash
})
).be.true;
}
- await expect(node.sendPayTx({ fee: 10 })).rejectedWith(
- /Too Low Fee/
- );
+ try {
+ await node.sendPayTx({ fee: 10 });
+ expect.fail();
+ } catch (e) {
+ expect(e.toString()).is.include(ERROR.TOO_LOW_FEE);
+ }
- const params = await node.testFramework.rpc.sendRpcRequest(
- "chain_getCommonParams",
- [null]
- );
- expect(U64.ensure(params.minPayCost)).to.be.deep.equal(new U64(11));
+ const params = await node.rpc.chain.getCommonParams({
+ blockNumber: null
+ });
+ expect(+params!.minPayCost!).to.be.deep.equal(11);
});
it("nomination expiration cannot be zero", async function() {
@@ -890,9 +938,17 @@ describe("ChangeParams", function() {
}))!,
fee: 10
});
- await expect(
- node.testFramework.rpc.chain.sendSignedTransaction(tx)
- ).rejectedWith(/nomination expiration/);
+ const trans = tx.rlpBytes().toString("hex");
+ try {
+ await node.rpc.mempool.sendSignedTransaction({
+ tx: `0x${trans}`
+ });
+ expect.fail();
+ } catch (e) {
+ expect(e.toString()).is.include(
+ ERROR.ACTION_DATA_HANDLER_NOT_FOUND
+ );
+ }
});
it("custody period cannot be zero", async function() {
@@ -953,9 +1009,17 @@ describe("ChangeParams", function() {
}))!,
fee: 10
});
- await expect(
- node.testFramework.rpc.chain.sendSignedTransaction(tx)
- ).rejectedWith(/custody period/);
+ const trans = tx.rlpBytes().toString("hex");
+ try {
+ await node.rpc.mempool.sendSignedTransaction({
+ tx: `0x${trans}`
+ });
+ expect.fail();
+ } catch (e) {
+ expect(e.toString()).is.include(
+ ERROR.ACTION_DATA_HANDLER_NOT_FOUND
+ );
+ }
});
it("release period cannot be zero", async function() {
@@ -1016,9 +1080,17 @@ describe("ChangeParams", function() {
}))!,
fee: 10
});
- await expect(
- node.testFramework.rpc.chain.sendSignedTransaction(tx)
- ).rejectedWith(/release period/);
+ const trans = tx.rlpBytes().toString("hex");
+ try {
+ await node.rpc.mempool.sendSignedTransaction({
+ tx: `0x${trans}`
+ });
+ expect.fail();
+ } catch (e) {
+ expect(e.toString()).is.include(
+ ERROR.ACTION_DATA_HANDLER_NOT_FOUND
+ );
+ }
});
it("A release period cannot be equal to a custody period", async function() {
@@ -1079,12 +1151,16 @@ describe("ChangeParams", function() {
}))!,
fee: 10
});
+ const trans = tx.rlpBytes().toString("hex");
try {
- await node.testFramework.rpc.chain.sendSignedTransaction(tx);
- expect.fail("The transaction must fail");
- } catch (err) {
- expect(err.message).contains("release period");
- expect(err.message).contains("custody period");
+ await node.rpc.mempool.sendSignedTransaction({
+ tx: `0x${trans}`
+ });
+ expect.fail();
+ } catch (e) {
+ expect(e.toString()).is.include(
+ ERROR.ACTION_DATA_HANDLER_NOT_FOUND
+ );
}
});
@@ -1146,9 +1222,17 @@ describe("ChangeParams", function() {
}))!,
fee: 10
});
- await expect(
- node.testFramework.rpc.chain.sendSignedTransaction(tx)
- ).rejectedWith(/minimum deposit/);
+ const trans = tx.rlpBytes().toString("hex");
+ try {
+ await node.rpc.mempool.sendSignedTransaction({
+ tx: `0x${trans}`
+ });
+ expect.fail();
+ } catch (e) {
+ expect(e.toString()).is.include(
+ ERROR.ACTION_DATA_HANDLER_NOT_FOUND
+ );
+ }
});
it("delegation threshold cannot be zero", async function() {
@@ -1209,9 +1293,17 @@ describe("ChangeParams", function() {
}))!,
fee: 10
});
- await expect(
- node.testFramework.rpc.chain.sendSignedTransaction(tx)
- ).rejectedWith(/delegation threshold/);
+ const trans = tx.rlpBytes().toString("hex");
+ try {
+ await node.rpc.mempool.sendSignedTransaction({
+ tx: `0x${trans}`
+ });
+ expect.fail();
+ } catch (e) {
+ expect(e.toString()).is.include(
+ ERROR.ACTION_DATA_HANDLER_NOT_FOUND
+ );
+ }
});
it("min number of validators cannot be zero", async function() {
@@ -1272,9 +1364,17 @@ describe("ChangeParams", function() {
}))!,
fee: 10
});
- await expect(
- node.testFramework.rpc.chain.sendSignedTransaction(tx)
- ).rejectedWith(/minimum number of validators/);
+ const trans = tx.rlpBytes().toString("hex");
+ try {
+ await node.rpc.mempool.sendSignedTransaction({
+ tx: `0x${trans}`
+ });
+ expect.fail();
+ } catch (e) {
+ expect(e.toString()).is.include(
+ ERROR.ACTION_DATA_HANDLER_NOT_FOUND
+ );
+ }
});
it("max number of validators cannot be zero", async function() {
@@ -1335,9 +1435,17 @@ describe("ChangeParams", function() {
}))!,
fee: 10
});
- await expect(
- node.testFramework.rpc.chain.sendSignedTransaction(tx)
- ).rejectedWith(/maximum number of validators/);
+ const trans = tx.rlpBytes().toString("hex");
+ try {
+ await node.rpc.mempool.sendSignedTransaction({
+ tx: `0x${trans}`
+ });
+ expect.fail();
+ } catch (e) {
+ expect(e.toString()).is.include(
+ ERROR.ACTION_DATA_HANDLER_NOT_FOUND
+ );
+ }
});
it("The maximum number of candidates cannot be equal to the minimum number of candidates", async function() {
@@ -1398,12 +1506,16 @@ describe("ChangeParams", function() {
}))!,
fee: 10
});
+ const trans = tx.rlpBytes().toString("hex");
try {
- await node.testFramework.rpc.chain.sendSignedTransaction(tx);
- expect.fail("The transaction must fail");
- } catch (err) {
- expect(err.message).contains("maximum number of validators");
- expect(err.message).contains("minimum number of validators");
+ await node.rpc.mempool.sendSignedTransaction({
+ tx: `0x${trans}`
+ });
+ expect.fail();
+ } catch (e) {
+ expect(e.toString()).is.include(
+ ERROR.ACTION_DATA_HANDLER_NOT_FOUND
+ );
}
});
@@ -1465,12 +1577,16 @@ describe("ChangeParams", function() {
}))!,
fee: 10
});
+ const trans = tx.rlpBytes().toString("hex");
try {
- await node.testFramework.rpc.chain.sendSignedTransaction(tx);
- expect.fail("The transaction must fail");
- } catch (err) {
- expect(err.message).contains("candidate metadata size");
- expect(err.message).contains("text limit");
+ await node.rpc.mempool.sendSignedTransaction({
+ tx: `0x${trans}`
+ });
+ expect.fail();
+ } catch (e) {
+ expect(e.toString()).is.include(
+ ERROR.ACTION_DATA_HANDLER_NOT_FOUND
+ );
}
});
});
@@ -1505,23 +1621,24 @@ async function sendStakeToken(params: {
address: senderAddress.toString()
}))!
} = params;
-
- return node.testFramework.rpc.chain.sendSignedTransaction(
- node.testFramework.core
- .createCustomTransaction({
- handlerId: stakeActionHandlerId,
- bytes: Buffer.from(
- RLP.encode([
- 1,
- receiverAddress.accountId.toEncodeObject(),
- quantity
- ])
- )
- })
- .sign({
- secret: senderSecret,
- seq,
- fee
- })
+ const tx = node.testFramework.core
+ .createCustomTransaction({
+ handlerId: stakeActionHandlerId,
+ bytes: Buffer.from(
+ RLP.encode([
+ 1,
+ receiverAddress.accountId.toEncodeObject(),
+ quantity
+ ])
+ )
+ })
+ .sign({
+ secret: senderSecret,
+ seq,
+ fee
+ });
+ const trans = tx.rlpBytes().toString("hex");
+ return new H256(
+ await node.rpc.mempool.sendSignedTransaction({ tx: `0x${trans}` })
);
}
diff --git a/test/src/e2e/customAction.test.ts b/test/src/e2e/customAction.test.ts
index 2f52cd0643..e622412fa4 100644
--- a/test/src/e2e/customAction.test.ts
+++ b/test/src/e2e/customAction.test.ts
@@ -78,29 +78,31 @@ describe("customAction", function() {
).readUInt8(0);
const increment = 11;
- const hash = await node.testFramework.rpc.chain.sendSignedTransaction(
- node.testFramework.core
- .createCustomTransaction({
- handlerId: hitActionHandlerId,
- bytes: RLP.encode([increment])
- })
- .sign({
- secret: faucetSecret,
- seq: (await node.rpc.chain.getSeq({
- address: faucetAddress.toString(),
- blockNumber: null
- }))!,
- fee: 10
- })
- );
-
+ const tx = node.testFramework.core
+ .createCustomTransaction({
+ handlerId: hitActionHandlerId,
+ bytes: RLP.encode([increment])
+ })
+ .sign({
+ secret: faucetSecret,
+ seq: (await node.rpc.chain.getSeq({
+ address: faucetAddress.toString(),
+ blockNumber: null
+ }))!,
+ fee: 10
+ });
+ const trans = tx.rlpBytes().toString("hex");
+ const hash = await node.rpc.mempool.sendSignedTransaction({
+ tx: `0x${trans}`
+ });
expect(
await node.rpc.chain.containsTransaction({
- transactionHash: `0x${hash.toString()}`
+ transactionHash: hash
})
).be.true;
- expect(await node.testFramework.rpc.chain.getTransaction(hash)).not
- .null;
+ expect(
+ await node.rpc.chain.getTransaction({ transactionHash: hash })
+ ).not.null;
const hitData = (await node.rpc.engine.getCustomActionData({
handlerId: hitActionHandlerId,
@@ -161,24 +163,28 @@ describe("customAction", function() {
it("should throw handler not found on sendCustomTransaction", async function() {
try {
- await node.testFramework.rpc.chain.sendSignedTransaction(
- node.testFramework.core
- .createCustomTransaction({
- handlerId: 99999,
- bytes: RLP.encode([11])
- })
- .sign({
- secret: faucetSecret,
- seq: (await node.rpc.chain.getSeq({
- address: faucetAddress.toString(),
- blockNumber: null
- }))!,
- fee: 10
- })
- );
+ const tx = node.testFramework.core
+ .createCustomTransaction({
+ handlerId: 99999,
+ bytes: RLP.encode([11])
+ })
+ .sign({
+ secret: faucetSecret,
+ seq: (await node.rpc.chain.getSeq({
+ address: faucetAddress.toString(),
+ blockNumber: null
+ }))!,
+ fee: 10
+ });
+ const trans = tx.rlpBytes().toString("hex");
+ await node.rpc.mempool.sendSignedTransaction({
+ tx: `0x${trans}`
+ });
fail();
} catch (e) {
- expect(e).similarTo(ERROR.ACTION_DATA_HANDLER_NOT_FOUND);
+ expect(e.toString()).include(
+ ERROR.ACTION_DATA_HANDLER_NOT_FOUND
+ );
}
});
@@ -188,26 +194,19 @@ describe("customAction", function() {
blockNumber: null
}))!;
const blockNumber = await node.rpc.chain.getBestBlockNumber();
-
- expect(
- node.testFramework.rpc.chain.sendSignedTransaction(
- node.testFramework.core
- .createCustomTransaction({
- handlerId: hitActionHandlerId,
- bytes: RLP.encode([
- "wrong",
- "format",
- "of",
- "message"
- ])
- })
- .sign({
- secret: faucetSecret,
- seq: seq + 1,
- fee: 10
- })
- )
- ).be.rejected;
+ const tx = node.testFramework.core
+ .createCustomTransaction({
+ handlerId: hitActionHandlerId,
+ bytes: RLP.encode(["wrong", "format", "of", "message"])
+ })
+ .sign({
+ secret: faucetSecret,
+ seq: seq + 1,
+ fee: 10
+ });
+ const trans = tx.rlpBytes().toString("hex");
+ expect(node.rpc.mempool.sendSignedTransaction({ tx: `0x${trans}` }))
+ .be.rejected;
});
});
diff --git a/test/src/e2e/network1.test.ts b/test/src/e2e/network1.test.ts
index d240a6f231..c497c536db 100644
--- a/test/src/e2e/network1.test.ts
+++ b/test/src/e2e/network1.test.ts
@@ -50,7 +50,7 @@ describe("network1 node test", function() {
"tag string for the target"
]);
- await node.testFramework.rpc.network.removeFromWhitelist(target);
+ await node.rpc.net.removeFromWhitelist({ address: target });
({ list } = await node.rpc.net.getWhitelist());
expect(list).not.to.include(target);
});
diff --git a/test/src/e2e/network2.test.ts b/test/src/e2e/network2.test.ts
index bcd18b412f..cc677f3baf 100644
--- a/test/src/e2e/network2.test.ts
+++ b/test/src/e2e/network2.test.ts
@@ -57,11 +57,11 @@ describe("network2 nodes", function() {
it("connect", async function() {
expect(
- await nodeA.testFramework.rpc.network.connect(
- address,
- nodeB.port
- )
- ).to.be.null;
+ await nodeA.rpc.net.connect({
+ address: address.toString(),
+ port: nodeB.port
+ })
+ ).to.be.undefined;
while (
!(await nodeA.rpc.net.isConnected({
@@ -78,8 +78,7 @@ describe("network2 nodes", function() {
});
it("getPeers", async function() {
- expect(await nodeA.testFramework.rpc.network.getPeers()).to.be
- .empty;
+ expect(await nodeA.rpc.net.getEstablishedPeers()).to.be.empty;
});
});
@@ -142,12 +141,12 @@ describe("network2 nodes", function() {
});
it("getPeers", async function() {
- expect(
- await nodeA.testFramework.rpc.network.getPeers()
- ).to.deep.equal([`${address}:${nodeB.port}`]);
- expect(
- await nodeB.testFramework.rpc.network.getPeers()
- ).to.deep.equal([`${address}:${nodeA.port}`]);
+ expect(await nodeA.rpc.net.getEstablishedPeers()).to.deep.equal([
+ `${address}:${nodeB.port}`
+ ]);
+ expect(await nodeB.rpc.net.getEstablishedPeers()).to.deep.equal([
+ `${address}:${nodeA.port}`
+ ]);
});
});
diff --git a/test/src/e2e/reward.test.ts b/test/src/e2e/reward.test.ts
index a8aa3471d8..2200513de4 100644
--- a/test/src/e2e/reward.test.ts
+++ b/test/src/e2e/reward.test.ts
@@ -162,7 +162,7 @@ describe("Reward = 50, 1 miner", function() {
});
it("Mining a block with a transaction that pays the author", async function() {
- await node.pay(aliceAddress, 100);
+ await node.pay(aliceAddress.toString(), 100);
expect(
+(await node.rpc.chain.getBalance({
address: faucetAddress.toString()
@@ -234,7 +234,8 @@ describe("Reward = 50, 1 miner", function() {
quantity: 20
})
.sign({ secret: aliceSecret, seq: 0, fee: 10 });
- await node.testFramework.rpc.chain.sendSignedTransaction(tx);
+ const trans = tx.rlpBytes().toString("hex");
+ await node.rpc.mempool.sendSignedTransaction({ tx: `0x${trans}` });
expect(
+(await node.rpc.chain.getBalance({
diff --git a/test/src/e2e/reward1.test.ts b/test/src/e2e/reward1.test.ts
index a4b2783c7d..4df7907d4e 100644
--- a/test/src/e2e/reward1.test.ts
+++ b/test/src/e2e/reward1.test.ts
@@ -51,7 +51,6 @@ describe("reward1", function() {
it("mining reward of the empty block is the same with the block reward", async function() {
await node.rpc.devel!.startSealing();
const bestBlockNumber = await node.rpc.chain.getBestBlockNumber();
- // FIXME: Add an API to SDK
const miningReward = await node.rpc.chain.getMiningReward({
blockNumber: bestBlockNumber
});
@@ -84,7 +83,6 @@ describe("reward1", function() {
});
await node.rpc.devel!.startSealing();
const bestBlockNumber = await node.rpc.chain.getBestBlockNumber();
- // FIXME: Add an API to SDK
const miningReward = await node.rpc.chain.getMiningReward({
blockNumber: bestBlockNumber
});
diff --git a/test/src/e2e/shard.test.ts b/test/src/e2e/shard.test.ts
index dcf2223e3e..434e6c53e7 100644
--- a/test/src/e2e/shard.test.ts
+++ b/test/src/e2e/shard.test.ts
@@ -43,11 +43,13 @@ describe.skip("CreateShard", function() {
blockNumber: null
}))!;
- await node.testFramework.rpc.chain.sendSignedTransaction(
- node.testFramework.core
+ await node.rpc.mempool.sendSignedTransaction({
+ tx: node.testFramework.core
.createPayTransaction({ recipient: aliceAddress, quantity: 1 })
.sign({ secret: faucetSecret, seq, fee: 10 })
- );
+ .rlpBytes()
+ .toString("hex")
+ });
const tx = node.testFramework.core
.createCreateShardTransaction({ users: [aliceAddress] })
@@ -59,7 +61,9 @@ describe.skip("CreateShard", function() {
blockNumber: null
})
).to.be.null;
- await node.testFramework.rpc.chain.sendSignedTransaction(tx);
+ await node.rpc.mempool.sendSignedTransaction({
+ tx: tx.rlpBytes().toString("hex")
+ });
expect(
await node.rpc.chain.containsTransaction({
transactionHash: `0x${tx.hash().toString()}`
@@ -106,21 +110,27 @@ describe.skip("CreateShard", function() {
address: faucetAddress.toString(),
blockNumber: null
}))!;
- await node.testFramework.rpc.chain.sendSignedTransaction(
- node.testFramework.core
+ await node.rpc.mempool.sendSignedTransaction({
+ tx: node.testFramework.core
.createPayTransaction({ recipient: aliceAddress, quantity: 1 })
.sign({ secret: faucetSecret, seq, fee: 10 })
- );
- await node.testFramework.rpc.chain.sendSignedTransaction(
- node.testFramework.core
+ .rlpBytes()
+ .toString("hex")
+ });
+ await node.rpc.mempool.sendSignedTransaction({
+ tx: node.testFramework.core
.createPayTransaction({ recipient: bobAddress, quantity: 1 })
.sign({ secret: faucetSecret, seq: seq + 1, fee: 10 })
- );
+ .rlpBytes()
+ .toString("hex")
+ });
const tx = node.testFramework.core
.createCreateShardTransaction({ users: [aliceAddress] })
.sign({ secret: faucetSecret, seq: seq + 2, fee: 10 });
- await node.testFramework.rpc.chain.sendSignedTransaction(tx);
+ await node.rpc.mempool.sendSignedTransaction({
+ tx: tx.rlpBytes().toString("hex")
+ });
const shardId = (await node.rpc.chain.getShardIdByHash({
transactionHash: `0x${tx.hash().toString()}`,
blockNumber: null
@@ -129,7 +139,9 @@ describe.skip("CreateShard", function() {
const setShardUsers = node.testFramework.core
.createSetShardUsersTransaction({ shardId, users })
.sign({ secret: faucetSecret, seq: seq + 3, fee: 10 });
- await node.testFramework.rpc.chain.sendSignedTransaction(setShardUsers);
+ await node.rpc.mempool.sendSignedTransaction({
+ tx: setShardUsers.rlpBytes().toString("hex")
+ });
const shardUsers = (await node.rpc.chain.getShardIdByHash({
transactionHash: `0x${tx.hash().toString()}`,
blockNumber: null
@@ -142,20 +154,26 @@ describe.skip("CreateShard", function() {
address: faucetAddress.toString(),
blockNumber: null
}))!;
- await node.testFramework.rpc.chain.sendSignedTransaction(
- node.testFramework.core
+ await node.rpc.mempool.sendSignedTransaction({
+ tx: node.testFramework.core
.createPayTransaction({ recipient: aliceAddress, quantity: 1 })
.sign({ secret: faucetSecret, seq, fee: 10 })
- );
- await node.testFramework.rpc.chain.sendSignedTransaction(
- node.testFramework.core
+ .rlpBytes()
+ .toString("hex")
+ });
+ await node.rpc.mempool.sendSignedTransaction({
+ tx: node.testFramework.core
.createPayTransaction({ recipient: bobAddress, quantity: 1 })
.sign({ secret: faucetSecret, seq: seq + 1, fee: 10 })
- );
+ .rlpBytes()
+ .toString("hex")
+ });
const tx = node.testFramework.core
.createCreateShardTransaction({ users: [aliceAddress, bobAddress] })
.sign({ secret: faucetSecret, seq: seq + 2, fee: 10 });
- await node.testFramework.rpc.chain.sendSignedTransaction(tx);
+ await node.rpc.mempool.sendSignedTransaction({
+ tx: tx.rlpBytes().toString("hex")
+ });
const shardId = (await node.rpc.chain.getShardIdByHash({
transactionHash: `0x${tx.hash().toString()}`,
@@ -165,9 +183,9 @@ describe.skip("CreateShard", function() {
const setShardOwners = node.testFramework.core
.createSetShardOwnersTransaction({ shardId, owners })
.sign({ secret: faucetSecret, seq: seq + 3, fee: 10 });
- await node.testFramework.rpc.chain.sendSignedTransaction(
- setShardOwners
- );
+ await node.rpc.mempool.sendSignedTransaction({
+ tx: setShardOwners.rlpBytes().toString("hex")
+ });
const shardOwners = await node.rpc.chain.getShardOwners({ shardId })!;
expect(shardOwners).to.deep.equal(owners.map(owner => owner.value));
});
@@ -177,16 +195,20 @@ describe.skip("CreateShard", function() {
address: faucetAddress.toString(),
blockNumber: null
}))!;
- await node.testFramework.rpc.chain.sendSignedTransaction(
- node.testFramework.core
+ await node.rpc.mempool.sendSignedTransaction({
+ tx: node.testFramework.core
.createPayTransaction({ recipient: aliceAddress, quantity: 1 })
.sign({ secret: faucetSecret, seq, fee: 10 })
- );
- await node.testFramework.rpc.chain.sendSignedTransaction(
- node.testFramework.core
+ .rlpBytes()
+ .toString("hex")
+ });
+ await node.rpc.mempool.sendSignedTransaction({
+ tx: node.testFramework.core
.createPayTransaction({ recipient: bobAddress, quantity: 1 })
.sign({ secret: faucetSecret, seq: seq + 1, fee: 10 })
- );
+ .rlpBytes()
+ .toString("hex")
+ });
const tx1 = node.testFramework.core
.createCreateShardTransaction({ users: [aliceAddress, bobAddress] })
.sign({ secret: faucetSecret, seq: seq + 2, fee: 10 });
@@ -196,7 +218,9 @@ describe.skip("CreateShard", function() {
blockNumber: null
})
).to.be.null;
- await node.testFramework.rpc.chain.sendSignedTransaction(tx1);
+ await node.rpc.mempool.sendSignedTransaction({
+ tx: tx1.rlpBytes().toString("hex")
+ });
expect(
await node.rpc.chain.containsTransaction({
transactionHash: `0x${tx1.hash().toString()}`
@@ -223,7 +247,9 @@ describe.skip("CreateShard", function() {
blockNumber: null
})
).to.be.null;
- await node.testFramework.rpc.chain.sendSignedTransaction(tx2);
+ await node.rpc.mempool.sendSignedTransaction({
+ tx: tx2.rlpBytes().toString("hex")
+ });
expect(
await node.rpc.chain.containsTransaction({
transactionHash: `0x${tx2.hash().toString()}`
@@ -247,32 +273,40 @@ describe.skip("CreateShard", function() {
address: faucetAddress.toString(),
blockNumber: null
}))!;
- await node.testFramework.rpc.chain.sendSignedTransaction(
- node.testFramework.core
+ await node.rpc.mempool.sendSignedTransaction({
+ tx: node.testFramework.core
.createPayTransaction({ recipient: aliceAddress, quantity: 1 })
.sign({ secret: faucetSecret, seq: faucetSeq, fee: 10 })
- );
- await node.testFramework.rpc.chain.sendSignedTransaction(
- node.testFramework.core
+ .rlpBytes()
+ .toString("hex")
+ });
+ await node.rpc.mempool.sendSignedTransaction({
+ tx: node.testFramework.core
.createPayTransaction({ recipient: bobAddress, quantity: 1 })
.sign({ secret: faucetSecret, seq: faucetSeq + 1, fee: 10 })
- );
+ .rlpBytes()
+ .toString("hex")
+ });
const createShard = node.testFramework.core
.createCreateShardTransaction({ users: [aliceAddress] })
.sign({ secret: faucetSecret, seq: faucetSeq + 2, fee: 10 });
- await node.testFramework.rpc.chain.sendSignedTransaction(createShard);
+ await node.rpc.mempool.sendSignedTransaction({
+ tx: createShard.rlpBytes().toString("hex")
+ });
const shardId = (await node.rpc.chain.getShardIdByHash({
transactionHash: `0x${createShard.hash().toString()}`,
blockNumber: null
}))!;
- await node.testFramework.rpc.chain.sendSignedTransaction(
- node.testFramework.core
+ await node.rpc.mempool.sendSignedTransaction({
+ tx: node.testFramework.core
.createPayTransaction({
recipient: bobAddress,
quantity: 100
})
.sign({ secret: faucetSecret, seq: faucetSeq + 3, fee: 10 })
- );
+ .rlpBytes()
+ .toString("hex")
+ });
const bobSeq: number = (await node.rpc.chain.getSeq({
address: bobAddress.toString(),
@@ -297,14 +331,18 @@ describe.skip("CreateShard", function() {
await node.rpc.devel!.stopSealing();
const blockNumber = await node.rpc.chain.getBestBlockNumber();
- await node.testFramework.rpc.chain.sendSignedTransaction(pay);
- await node.testFramework.rpc.chain.sendSignedTransaction(mint);
+ await node.rpc.mempool.sendSignedTransaction({
+ tx: pay.rlpBytes().toString("hex")
+ });
+ await node.rpc.mempool.sendSignedTransaction({
+ tx: mint.rlpBytes().toString("hex")
+ });
await node.rpc.devel!.startSealing();
await node.waitBlockNumber(blockNumber + 1);
- const hint = await node.testFramework.rpc.chain.getErrorHint(
- mint.hash()
- );
+ const hint = await node.rpc.mempool.getErrorHint({
+ transactionHash: mint.hash().toString()
+ });
expect(hint).includes("permission");
});
@@ -316,19 +354,23 @@ describe.skip("CreateShard", function() {
const createShard = node.testFramework.core
.createCreateShardTransaction({ users: [aliceAddress] })
.sign({ secret: faucetSecret, seq: faucetSeq, fee: 10 });
- await node.testFramework.rpc.chain.sendSignedTransaction(createShard);
+ await node.rpc.mempool.sendSignedTransaction({
+ tx: createShard.rlpBytes().toString("hex")
+ });
const shardId = (await node.rpc.chain.getShardIdByHash({
transactionHash: `0x${createShard.hash().toString()}`,
blockNumber: null
}))!;
- await node.testFramework.rpc.chain.sendSignedTransaction(
- node.testFramework.core
+ await node.rpc.mempool.sendSignedTransaction({
+ tx: node.testFramework.core
.createPayTransaction({
recipient: aliceAddress,
quantity: 100
})
.sign({ secret: faucetSecret, seq: faucetSeq + 1, fee: 10 })
- );
+ .rlpBytes()
+ .toString("hex")
+ });
const aliceSeq: number = (await node.rpc.chain.getSeq({
address: aliceAddress.toString(),
@@ -344,7 +386,9 @@ describe.skip("CreateShard", function() {
recipient: await node.createP2PKHAddress()
})
.sign({ secret: aliceSecret, seq: aliceSeq, fee: 10 });
- await node.testFramework.rpc.chain.sendSignedTransaction(mint);
+ await node.rpc.mempool.sendSignedTransaction({
+ tx: mint.rlpBytes().toString("hex")
+ });
expect(
await node.rpc.chain.containsTransaction({
@@ -356,9 +400,9 @@ describe.skip("CreateShard", function() {
transactionHash: `0x${mint.hash().toString()}`
})
).not.null;
- const hint = await node.testFramework.rpc.chain.getErrorHint(
- mint.hash()
- );
+ const hint = await node.rpc.mempool.getErrorHint({
+ transactionHash: mint.hash().toString()
+ });
expect(hint).to.be.null;
});
@@ -370,19 +414,23 @@ describe.skip("CreateShard", function() {
const createShard = node.testFramework.core
.createCreateShardTransaction({ users: [aliceAddress] })
.sign({ secret: faucetSecret, seq: faucetSeq, fee: 10 });
- await node.testFramework.rpc.chain.sendSignedTransaction(createShard);
+ await node.rpc.mempool.sendSignedTransaction({
+ tx: createShard.rlpBytes().toString("hex")
+ });
const shardId = (await node.rpc.chain.getShardIdByHash({
transactionHash: `0x${createShard.hash().toString()}`,
blockNumber: null
}))!;
- await node.testFramework.rpc.chain.sendSignedTransaction(
- node.testFramework.core
+ await node.rpc.mempool.sendSignedTransaction({
+ tx: node.testFramework.core
.createPayTransaction({
recipient: bobAddress,
quantity: 100
})
.sign({ secret: faucetSecret, seq: faucetSeq + 1, fee: 10 })
- );
+ .rlpBytes()
+ .toString("hex")
+ });
const bobSeq: number = (await node.rpc.chain.getSeq({
address: bobAddress.toString(),
@@ -405,8 +453,8 @@ describe.skip("CreateShard", function() {
const blockNumber = await node.rpc.chain.getBestBlockNumber();
await node.rpc.devel!.stopSealing();
- await node.testFramework.rpc.chain.sendSignedTransaction(
- node.testFramework.core
+ await node.rpc.mempool.sendSignedTransaction({
+ tx: node.testFramework.core
.createPayTransaction({
recipient: aliceAddress,
quantity: 1
@@ -416,25 +464,31 @@ describe.skip("CreateShard", function() {
seq: bobSeq,
fee: 10
})
- );
- await node.testFramework.rpc.chain.sendSignedTransaction(signedMint1);
+ .rlpBytes()
+ .toString("hex")
+ });
+ await node.rpc.mempool.sendSignedTransaction({
+ tx: signedMint1.rlpBytes().toString("hex")
+ });
await node.rpc.devel!.startSealing();
await node.waitBlockNumber(blockNumber + 1);
expect(
- await node.testFramework.rpc.chain.getTransactionResultsByTracker(
- mint1.tracker()
- )
+ await node.rpc.mempool.getTransactionResultsByTracker({
+ tracker: mint1.tracker().toString()
+ })
).deep.equal([false]);
- const hint = await node.testFramework.rpc.chain.getErrorHint(
- signedMint1.hash()
- );
+ const hint = await node.rpc.mempool.getErrorHint({
+ transactionHash: signedMint1.hash().toString()
+ });
expect(hint).includes("permission");
const newUsers = [aliceAddress, bobAddress];
const setShardUsers = node.testFramework.core
.createSetShardUsersTransaction({ shardId, users: newUsers })
.sign({ secret: faucetSecret, seq: faucetSeq + 2, fee: 10 });
- await node.testFramework.rpc.chain.sendSignedTransaction(setShardUsers);
+ await node.rpc.mempool.sendSignedTransaction({
+ tx: setShardUsers.rlpBytes().toString("hex")
+ });
const shardUsers = (await node.rpc.chain.getShardUsers({ shardId }))!;
expect(shardUsers).to.deep.equal(newUsers.map(user => user.value));
@@ -452,7 +506,9 @@ describe.skip("CreateShard", function() {
seq: bobSeq + 1,
fee: 20
});
- await node.testFramework.rpc.chain.sendSignedTransaction(signedMint2);
+ await node.rpc.mempool.sendSignedTransaction({
+ tx: signedMint2.rlpBytes().toString("hex")
+ });
expect(
await node.rpc.chain.containsTransaction({
@@ -465,12 +521,14 @@ describe.skip("CreateShard", function() {
})
).not.null;
expect(
- await node.testFramework.rpc.chain.getTransactionResultsByTracker(
- mint2.tracker()
- )
+ await node.rpc.mempool.getTransactionResultsByTracker({
+ tracker: mint2.tracker().toString()
+ })
).deep.equal([false, true]);
expect(
- await node.testFramework.rpc.chain.getErrorHint(signedMint2.hash())
+ await node.rpc.mempool.getErrorHint({
+ transactionHash: signedMint2.hash().toString()
+ })
).to.be.null;
});
@@ -492,11 +550,13 @@ describe.skip("Cannot create shard without allow-create-shard flag", function()
blockNumber: null
}))!;
- await node.testFramework.rpc.chain.sendSignedTransaction(
- node.testFramework.core
+ await node.rpc.mempool.sendSignedTransaction({
+ tx: node.testFramework.core
.createPayTransaction({ recipient: aliceAddress, quantity: 1 })
.sign({ secret: faucetSecret, seq, fee: 10 })
- );
+ .rlpBytes()
+ .toString("hex")
+ });
const tx = node.testFramework.core
.createCreateShardTransaction({ users: [aliceAddress] })
@@ -507,13 +567,21 @@ describe.skip("Cannot create shard without allow-create-shard flag", function()
blockNumber: null
})
).be.null;
- expect(node.testFramework.rpc.chain.sendSignedTransaction(tx)).be
- .rejected;
expect(
- await node.testFramework.rpc.chain.containsTransaction(tx.hash())
+ node.rpc.mempool.sendSignedTransaction({
+ tx: tx.rlpBytes().toString("hex")
+ })
+ ).be.rejected;
+ expect(
+ await node.rpc.chain.containsTransaction({
+ transactionHash: `0x${tx.hash().toString()}`
+ })
).be.false;
- expect(await node.testFramework.rpc.chain.getTransaction(tx.hash())).be
- .null;
+ expect(
+ await node.rpc.chain.getTransaction({
+ transactionHash: `0x${tx.hash().toString()}`
+ })
+ ).be.null;
const afterShardId = await node.rpc.chain.getShardIdByHash({
transactionHash: `0x${tx.hash().toString()}`,
blockNumber: null
diff --git a/test/src/e2e/snapshot.test.ts b/test/src/e2e/snapshot.test.ts
index dd75d5f48d..0127529d9d 100644
--- a/test/src/e2e/snapshot.test.ts
+++ b/test/src/e2e/snapshot.test.ts
@@ -39,18 +39,18 @@ describe("Snapshot", async function() {
recipient: aliceAddress
});
- const blockHash = (await node.testFramework.rpc.chain.getTransaction(
- pay.hash()
- ))!.blockHash!;
- await node.rpc.devel!.developSnapshot({ hash: blockHash.toJSON() })!;
+ const blockHash = (await node.rpc.chain.getTransaction({
+ transactionHash: `0x${pay.hash().toString()}`
+ }))!.blockHash!;
+ await node.rpc.devel!.developSnapshot({ hash: blockHash })!;
// Wait for 1 secs
await new Promise(resolve => setTimeout(resolve, 1000));
- const stateRoot = (await node.testFramework.rpc.chain.getBlock(
+ const stateRoot = (await node.rpc.chain.getBlockByHash({
blockHash
- ))!.stateRoot;
+ }))!.stateRoot;
expect(
- path.join(SNAPSHOT_PATH, blockHash.toString(), stateRoot.toString())
+ path.join(SNAPSHOT_PATH, blockHash.substr(2), stateRoot.substr(2))
).to.satisfies(fs.existsSync);
});
diff --git a/test/src/e2e/staking.test.ts b/test/src/e2e/staking.test.ts
index a920b3d028..e920740196 100644
--- a/test/src/e2e/staking.test.ts
+++ b/test/src/e2e/staking.test.ts
@@ -139,10 +139,10 @@ describe("Staking", function() {
}))!
: params.seq;
- return promiseExpect.shouldFulfill(
+ const hashInString = await promiseExpect.shouldFulfill(
"sendSignTransaction",
- node.testFramework.rpc.chain.sendSignedTransaction(
- node.testFramework.core
+ node.rpc.mempool.sendSignedTransaction({
+ tx: node.testFramework.core
.createCustomTransaction({
handlerId: stakeActionHandlerId,
bytes: Buffer.from(
@@ -158,8 +158,11 @@ describe("Staking", function() {
seq,
fee
})
- )
+ .rlpBytes()
+ .toString("hex")
+ })
);
+ return new H256(hashInString);
}
async function delegateToken(params: {
@@ -178,10 +181,10 @@ describe("Staking", function() {
}))!
: params.seq;
- return promiseExpect.shouldFulfill(
+ const hashInString = await promiseExpect.shouldFulfill(
"sendSignTransaction",
- node.testFramework.rpc.chain.sendSignedTransaction(
- node.testFramework.core
+ node.rpc.mempool.sendSignedTransaction({
+ tx: node.testFramework.core
.createCustomTransaction({
handlerId: stakeActionHandlerId,
bytes: Buffer.from(
@@ -197,8 +200,11 @@ describe("Staking", function() {
seq,
fee
})
- )
+ .rlpBytes()
+ .toString("hex")
+ })
);
+ return new H256(hashInString);
}
async function revokeToken(params: {
@@ -217,10 +223,10 @@ describe("Staking", function() {
}))!
: params.seq;
- return promiseExpect.shouldFulfill(
+ const hashInString = await promiseExpect.shouldFulfill(
"sendSignTransaction",
- node.testFramework.rpc.chain.sendSignedTransaction(
- node.testFramework.core
+ node.rpc.mempool.sendSignedTransaction({
+ tx: node.testFramework.core
.createCustomTransaction({
handlerId: stakeActionHandlerId,
bytes: Buffer.from(
@@ -236,8 +242,11 @@ describe("Staking", function() {
seq,
fee
})
- )
+ .rlpBytes()
+ .toString("hex")
+ })
);
+ return new H256(hashInString);
}
async function selfNominate(params: {
@@ -256,10 +265,10 @@ describe("Staking", function() {
}))!
: params.seq;
- return promiseExpect.shouldFulfill(
+ const hashInString = await promiseExpect.shouldFulfill(
"sendSignTransaction",
- node.testFramework.rpc.chain.sendSignedTransaction(
- node.testFramework.core
+ node.rpc.mempool.sendSignedTransaction({
+ tx: node.testFramework.core
.createCustomTransaction({
handlerId: stakeActionHandlerId,
bytes: Buffer.from(RLP.encode([4, deposit, metadata]))
@@ -269,8 +278,11 @@ describe("Staking", function() {
seq,
fee
})
- )
+ .rlpBytes()
+ .toString("hex")
+ })
);
+ return new H256(hashInString);
}
it("should have proper initial stake tokens", async function() {
@@ -524,8 +536,11 @@ describe("Staking", function() {
});
await node.rpc.devel!.startSealing();
- expect(await node.testFramework.rpc.chain.getErrorHint(hash)).not.to.be
- .null;
+ expect(
+ await node.rpc.mempool.getErrorHint({
+ transactionHash: `0x${hash.toString()}`
+ })
+ ).not.to.be.null;
const { amounts } = await getAllStakingInfo();
expect(amounts).to.be.deep.equal([
diff --git a/test/src/e2e/syncEmptyBlock.test.ts b/test/src/e2e/syncEmptyBlock.test.ts
index 216d7dde68..224987bf27 100644
--- a/test/src/e2e/syncEmptyBlock.test.ts
+++ b/test/src/e2e/syncEmptyBlock.test.ts
@@ -34,7 +34,7 @@ describe("syncEmptyBlock", function() {
});
it("nodeA creates an empty block", async function() {
- await nodeA.testFramework.rpc.devel.startSealing();
+ await nodeA.rpc.devel!.startSealing();
expect(await nodeA.getBestBlockNumber()).to.equal(1);
await nodeA.waitBlockNumberSync(nodeB);
expect(await nodeB.getBestBlockNumber()).to.equal(1);
@@ -45,9 +45,9 @@ describe("syncEmptyBlock", function() {
it("nodeA creates 3 empty blocks", async function() {
await Promise.all([
- nodeA.testFramework.rpc.devel.startSealing(),
- nodeA.testFramework.rpc.devel.startSealing(),
- nodeA.testFramework.rpc.devel.startSealing()
+ nodeA.rpc.devel!.startSealing(),
+ nodeA.rpc.devel!.startSealing(),
+ nodeA.rpc.devel!.startSealing()
]);
expect(await nodeA.getBestBlockNumber()).to.equal(3);
diff --git a/test/src/e2e/termChange.test.ts b/test/src/e2e/termChange.test.ts
index dc3e2dc960..74ced83a0c 100644
--- a/test/src/e2e/termChange.test.ts
+++ b/test/src/e2e/termChange.test.ts
@@ -99,8 +99,8 @@ describe("Term change", function() {
);
{
- const hash = await node.testFramework.rpc.chain.sendSignedTransaction(
- node.testFramework.core
+ const hash = await node.rpc.mempool.sendSignedTransaction({
+ tx: node.testFramework.core
.createCustomTransaction({
handlerId: stakeActionHandlerId,
bytes: RLP.encode(changeParams)
@@ -113,10 +113,12 @@ describe("Term change", function() {
}))!,
fee: 10
})
- );
+ .rlpBytes()
+ .toString("hex")
+ });
expect(
await node.rpc.chain.containsTransaction({
- transactionHash: `0x${hash.toString()}`
+ transactionHash: `${hash.toString()}`
})
).be.true;
}
@@ -131,17 +133,17 @@ describe("Term change", function() {
async function waitForTermPeriodChange(termSeconds: number) {
const lastBlockNumber = await node.rpc.chain.getBestBlockNumber();
- const lastBlock = (await node.testFramework.rpc.chain.getBlock(
- lastBlockNumber
- ))!;
+ const lastBlock = (await node.rpc.chain.getBlockByNumber({
+ blockNumber: lastBlockNumber
+ }))!;
let previousTs = lastBlock.timestamp;
for (let count = 0; count < 20; count++) {
await node.rpc.devel!.startSealing();
const blockNumber = await node.rpc.chain.getBestBlockNumber();
- const block = (await node.testFramework.rpc.chain.getBlock(
+ const block = (await node.rpc.chain.getBlockByNumber({
blockNumber
- ))!;
+ }))!;
const currentTs = block.timestamp;
const previousTermPeriod = Math.floor(previousTs / termSeconds);
diff --git a/test/src/e2e/verification.test.ts b/test/src/e2e/verification.test.ts
index a276347a99..b4f7c5f930 100644
--- a/test/src/e2e/verification.test.ts
+++ b/test/src/e2e/verification.test.ts
@@ -67,7 +67,7 @@ describe("solo - 1 node", function() {
);
expect.fail();
} catch (e) {
- expect(e).is.similarTo(ERROR.INVALID_RLP_TOO_BIG);
+ expect(e.toString()).is.include(ERROR.INVALID_RLP_TOO_BIG);
}
});
});
@@ -83,7 +83,7 @@ describe("solo - 1 node", function() {
);
expect.fail();
} catch (e) {
- expect(e).is.similarTo(ERROR.INVALID_RLP_TOO_BIG);
+ expect(e.toString()).is.include(ERROR.INVALID_RLP_TOO_BIG);
}
});
});
@@ -98,10 +98,13 @@ describe("solo - 1 node", function() {
expect.fail();
} catch (e) {
if (networkId.length !== 2)
- expect(e).is.similarTo(
+ expect(e.toString()).is.include(
ERROR.INVALID_RLP_INVALID_LENGTH
);
- else expect(e).is.similarTo(ERROR.INVALID_NETWORK_ID);
+ else
+ expect(e.toString()).is.include(
+ ERROR.INVALID_NETWORK_ID
+ );
}
});
});
@@ -115,7 +118,7 @@ describe("solo - 1 node", function() {
);
expect.fail();
} catch (e) {
- expect(e).is.similarTo(
+ expect(e.toString()).is.include(
ERROR.INVALID_RLP_UNEXPECTED_ACTION_PREFIX
);
}
@@ -146,7 +149,7 @@ describe("solo - 1 node", function() {
);
expect.fail();
} catch (e) {
- expect(e).is.similarTo(
+ expect(e.toString()).is.include(
ERROR.INVALID_RLP_INCORRECT_LIST_LEN
);
}
@@ -168,8 +171,13 @@ describe("solo - 1 node", function() {
expect.fail();
} catch (e) {
if (sig.length < 132)
- expect(e).is.similarTo(ERROR.INVALID_RLP_TOO_SHORT);
- else expect(e).is.similarTo(ERROR.INVALID_RLP_TOO_BIG);
+ expect(e.toString()).is.include(
+ ERROR.INVALID_RLP_TOO_SHORT
+ );
+ else
+ expect(e.toString()).is.include(
+ ERROR.INVALID_RLP_TOO_BIG
+ );
}
});
});
@@ -207,8 +215,13 @@ describe("solo - 1 node", function() {
expect.fail();
} catch (e) {
if (recipient.length < 42)
- expect(e).is.similarTo(ERROR.INVALID_RLP_TOO_SHORT);
- else expect(e).is.similarTo(ERROR.INVALID_RLP_TOO_BIG);
+ expect(e.toString()).is.include(
+ ERROR.INVALID_RLP_TOO_SHORT
+ );
+ else
+ expect(e.toString()).is.include(
+ ERROR.INVALID_RLP_TOO_BIG
+ );
}
});
});
@@ -224,7 +237,7 @@ describe("solo - 1 node", function() {
);
expect.fail();
} catch (e) {
- expect(e).is.similarTo(ERROR.INVALID_RLP_TOO_BIG);
+ expect(e.toString()).is.include(ERROR.INVALID_RLP_TOO_BIG);
}
});
});
@@ -260,7 +273,7 @@ describe("solo - 1 node", function() {
);
expect.fail();
} catch (e) {
- expect(e).is.similarTo(ERROR.INVALID_RLP_TOO_BIG);
+ expect(e.toString()).is.include(ERROR.INVALID_RLP_TOO_BIG);
}
});
});
@@ -298,7 +311,7 @@ describe("solo - 1 node", function() {
);
expect.fail();
} catch (e) {
- expect(e).is.similarTo(ERROR.INVALID_RLP_TOO_BIG);
+ expect(e.toString()).is.include(ERROR.INVALID_RLP_TOO_BIG);
}
});
});
@@ -323,12 +336,12 @@ describe("solo - 1 node", function() {
seq
});
try {
- await node.testFramework.rpc.chain.sendSignedTransaction(
- signed
- );
+ await node.rpc.mempool.sendSignedTransaction({
+ tx: signed.rlpBytes().toString("hex")
+ });
expect.fail();
} catch (e) {
- expect(e).is.similarTo(ERROR.TOO_LOW_FEE);
+ expect(e.toString()).is.include(ERROR.TOO_LOW_FEE);
}
});
});
diff --git a/test/src/helper/spawn.ts b/test/src/helper/spawn.ts
index 16e65f04b7..34f1c56f01 100644
--- a/test/src/helper/spawn.ts
+++ b/test/src/helper/spawn.ts
@@ -199,9 +199,7 @@ export default class CodeChain {
this._rpc = new RPC(`http://localhost:${this.rpcPort}`, {
devel: true
});
- this._testFramework = new SDK({
- server: `http://localhost:${this.rpcPort}`
- });
+ this._testFramework = new SDK({});
this._chain = chain || "solo";
this.argv = argv || [];
this.env = env || {};
@@ -555,7 +553,11 @@ export default class CodeChain {
}))!,
fee: 10
});
- return this.testFramework.rpc.chain.sendSignedTransaction(tx);
+ return new H256(
+ await this.rpc.mempool.sendSignedTransaction({
+ tx: tx.rlpBytes().toString("hex")
+ })
+ );
}
public async sendTransaction(
@@ -582,7 +584,11 @@ export default class CodeChain {
fee,
seq
});
- return this.testFramework.rpc.chain.sendSignedTransaction(signed);
+ return new H256(
+ await this.rpc.mempool.sendSignedTransaction({
+ tx: signed.rlpBytes().toString("hex")
+ })
+ );
}
public async sendAssetTransaction(
@@ -606,7 +612,11 @@ export default class CodeChain {
fee: fee + this.id,
seq
});
- return this.testFramework.rpc.chain.sendSignedTransaction(signed);
+ return new H256(
+ await this.rpc.mempool.sendSignedTransaction({
+ tx: signed.rlpBytes().toString("hex")
+ })
+ );
}
public async mintAsset(params: {
@@ -707,7 +717,9 @@ export default class CodeChain {
seq,
...options
});
- await this.testFramework.rpc.chain.sendSignedTransaction(tx);
+ await this.rpc.mempool.sendSignedTransaction({
+ tx: tx.rlpBytes().toString("hex")
+ });
return tx;
}
@@ -745,8 +757,11 @@ export default class CodeChain {
transactionHash: `0x${targetTxHash.toString()}`
})
).be.false;
- expect(await this.testFramework.rpc.chain.getErrorHint(targetTxHash))
- .not.null;
+ expect(
+ await this.rpc.mempool.getErrorHint({
+ transactionHash: targetTxHash.toString()
+ })
+ ).not.null;
expect(
await this.rpc.chain.getTransaction({
transactionHash: `0x${targetTxHash.toString()}`
@@ -759,7 +774,9 @@ export default class CodeChain {
})
).be.true;
expect(
- await this.testFramework.rpc.chain.getErrorHint(signedDummyTxHash)
+ await this.rpc.mempool.getErrorHint({
+ transactionHash: signedDummyTxHash.toString()
+ })
).null;
expect(
await this.rpc.chain.getTransaction({
@@ -794,8 +811,11 @@ export default class CodeChain {
transactionHash: `0x${targetTxHash.toString()}`
})
).be.false;
- expect(await this.testFramework.rpc.chain.getErrorHint(targetTxHash))
- .not.null;
+ expect(
+ await this.rpc.mempool.getErrorHint({
+ transactionHash: targetTxHash.toString()
+ })
+ ).not.null;
expect(
await this.rpc.chain.getTransaction({
transactionHash: `0x${targetTxHash.toString()}`
@@ -808,7 +828,9 @@ export default class CodeChain {
})
).be.true;
expect(
- await this.testFramework.rpc.chain.getErrorHint(signedDummyTxHash)
+ await this.rpc.mempool.getErrorHint({
+ transactionHash: signedDummyTxHash.toString()
+ })
).null;
expect(
await this.rpc.chain.getTransaction({
@@ -835,7 +857,9 @@ export default class CodeChain {
const targetTxHash =
tx instanceof SignedTransaction
- ? await this.testFramework.rpc.chain.sendSignedTransaction(tx)
+ ? await this.rpc.mempool.sendSignedTransaction({
+ tx: tx.rlpBytes().toString("hex")
+ })
: await tx();
await this.rpc.devel!.startSealing();
@@ -843,19 +867,19 @@ export default class CodeChain {
expect(
await this.rpc.chain.containsTransaction({
- transactionHash: `0x${targetTxHash.toString()}`
+ transactionHash: `${targetTxHash.toString()}`
})
).be.false;
- const hint = await this.testFramework.rpc.chain.getErrorHint(
- targetTxHash
- );
+ const hint = await this.rpc.mempool.getErrorHint({
+ transactionHash: targetTxHash.toString()
+ });
expect(hint).not.null;
if (options.error != null) {
expect(hint).contains(options.error);
}
expect(
await this.rpc.chain.getTransaction({
- transactionHash: `0x${targetTxHash.toString()}`
+ transactionHash: `${targetTxHash.toString()}`
})
).be.null;
@@ -865,7 +889,9 @@ export default class CodeChain {
})
).be.true;
expect(
- await this.testFramework.rpc.chain.getErrorHint(signedDummyTxHash)
+ await this.rpc.mempool.getErrorHint({
+ transactionHash: `0x${signedDummyTxHash.toString()}`
+ })
).null;
expect(
await this.rpc.chain.getTransaction({
@@ -873,31 +899,20 @@ export default class CodeChain {
})
).not.be.null;
- return targetTxHash;
+ return new H256(targetTxHash.toString());
}
- public sendSignedTransactionWithRlpBytes(rlpBytes: Buffer): Promise {
- return new Promise((resolve, reject) => {
- const bytes = Array.from(rlpBytes)
- .map(byte =>
- byte < 0x10 ? `0${byte.toString(16)}` : byte.toString(16)
- )
- .join("");
- this.testFramework.rpc
- .sendRpcRequest("mempool_sendSignedTransaction", [`0x${bytes}`])
- .then(result => {
- try {
- resolve(new H256(result));
- } catch (e) {
- reject(
- Error(
- `Expected sendSignedTransaction() to return a value of H256, but an error occurred: ${e.toString()}`
- )
- );
- }
- })
- .catch(reject);
- });
+ public async sendSignedTransactionWithRlpBytes(
+ rlpBytes: Buffer
+ ): Promise {
+ const bytes = Array.from(rlpBytes)
+ .map(byte =>
+ byte < 0x10 ? `0${byte.toString(16)}` : byte.toString(16)
+ )
+ .join("");
+ return new H256(
+ await this.rpc.mempool.sendSignedTransaction({ tx: `0x${bytes}` })
+ );
}
public async waitForTx(
@@ -923,7 +938,9 @@ export default class CodeChain {
const checkNoError = async () => {
const errorHints = await Promise.all(
hashes.map(hash =>
- this.testFramework.rpc.chain.getErrorHint(hash)
+ this.rpc.mempool.getErrorHint({
+ transactionHash: `0x${hash.toString()}`
+ })
)
);
for (const errorHint of errorHints) {
@@ -948,9 +965,7 @@ export default class CodeChain {
public async waitForTermChange(target: number, timeout?: number) {
const start = Date.now();
while (true) {
- const termMetadata = (await stake.getTermMetadata(
- this.testFramework
- ))!;
+ const termMetadata = (await stake.getTermMetadata(this.rpc))!;
if (termMetadata.currentTermId >= target) {
return termMetadata;
}
diff --git a/test/src/sdk/src/core/index.ts b/test/src/sdk/src/core/index.ts
index 831e70639a..13807446ca 100644
--- a/test/src/sdk/src/core/index.ts
+++ b/test/src/sdk/src/core/index.ts
@@ -419,7 +419,8 @@ export class Core {
}
| {
recipientFrom: AssetAddressValue;
- }) &
+ }
+ ) &
(
| {
lockScriptHashFee: H160Value;
@@ -428,7 +429,8 @@ export class Core {
| {
recipientFee: AssetAddressValue;
}
- | {})
+ | {}
+ )
): Order {
const {
assetTypeFrom,
@@ -886,7 +888,8 @@ export class Core {
| {
lockScriptHash: H256Value;
parameters: Buffer[];
- })
+ }
+ )
): AssetTransferOutput {
const { assetType, shardId } = params;
const quantity = U64.ensure(params.quantity);
diff --git a/test/src/sdk/src/core/transaction/AssetMintOutput.ts b/test/src/sdk/src/core/transaction/AssetMintOutput.ts
index b2a02affc3..e523792d77 100644
--- a/test/src/sdk/src/core/transaction/AssetMintOutput.ts
+++ b/test/src/sdk/src/core/transaction/AssetMintOutput.ts
@@ -67,9 +67,7 @@ export class AssetMintOutput {
break;
default:
throw Error(
- `Unexpected type of AssetAddress: ${type}, ${
- data.recipient
- }`
+ `Unexpected type of AssetAddress: ${type}, ${data.recipient}`
);
}
} else {
diff --git a/test/src/sdk/src/core/transaction/AssetTransferOutput.ts b/test/src/sdk/src/core/transaction/AssetTransferOutput.ts
index 2d5d805169..8a74c5db6d 100644
--- a/test/src/sdk/src/core/transaction/AssetTransferOutput.ts
+++ b/test/src/sdk/src/core/transaction/AssetTransferOutput.ts
@@ -91,9 +91,7 @@ export class AssetTransferOutput {
break;
default:
throw Error(
- `Unexpected type of AssetAddress: ${type}, ${
- data.recipient
- }`
+ `Unexpected type of AssetAddress: ${type}, ${data.recipient}`
);
}
} else {
diff --git a/test/src/sdk/src/core/transaction/ChangeAssetScheme.ts b/test/src/sdk/src/core/transaction/ChangeAssetScheme.ts
index 3c5a2e7e2a..f717b0fc4d 100644
--- a/test/src/sdk/src/core/transaction/ChangeAssetScheme.ts
+++ b/test/src/sdk/src/core/transaction/ChangeAssetScheme.ts
@@ -61,7 +61,7 @@ export class ChangeAssetScheme extends Transaction {
return "changeAssetScheme";
}
- protected actionToEncodeObject(): (any)[] {
+ protected actionToEncodeObject(): any[] {
const encoded = this._transaction.toEncodeObject();
encoded.push(this.approvals);
return encoded;
diff --git a/test/src/sdk/src/core/transaction/Order.ts b/test/src/sdk/src/core/transaction/Order.ts
index 3103606d34..170e68f969 100644
--- a/test/src/sdk/src/core/transaction/Order.ts
+++ b/test/src/sdk/src/core/transaction/Order.ts
@@ -143,7 +143,8 @@ export class Order {
}
| {
recipientFrom: AssetAddress;
- }) &
+ }
+ ) &
(
| {
lockScriptHashFee: H160;
@@ -151,7 +152,8 @@ export class Order {
}
| {
recipientFee: AssetAddress;
- })
+ }
+ )
) {
if ("recipientFrom" in data) {
const { lockScriptHash, parameters } = decomposeRecipient(
diff --git a/test/src/sdk/src/core/transaction/WrapCCC.ts b/test/src/sdk/src/core/transaction/WrapCCC.ts
index 890857bf20..07cf0d5e47 100644
--- a/test/src/sdk/src/core/transaction/WrapCCC.ts
+++ b/test/src/sdk/src/core/transaction/WrapCCC.ts
@@ -62,9 +62,7 @@ export class WrapCCC extends Transaction implements AssetTransaction {
break;
default:
throw Error(
- `Unexpected type of AssetAddress: ${type}, ${
- data.recipient
- }`
+ `Unexpected type of AssetAddress: ${type}, ${data.recipient}`
);
}
} else {
diff --git a/test/src/sdk/src/index.ts b/test/src/sdk/src/index.ts
index 0dcb2f094f..979226de67 100644
--- a/test/src/sdk/src/index.ts
+++ b/test/src/sdk/src/index.ts
@@ -1,7 +1,6 @@
import { Core } from "./core";
import { NetworkId } from "./core/types";
import { Key, KeyStoreType } from "./key";
-import { Rpc } from "./rpc";
import {
blake128,
blake128WithKey,
@@ -19,7 +18,6 @@ import {
} from "./utils";
class SDK {
- public static Rpc = Rpc;
public static Core = Core;
public static Key = Key;
public static util = {
@@ -39,7 +37,6 @@ class SDK {
};
public static SDK = SDK;
- public rpc: Rpc;
public core: Core;
public key: Key;
public util = SDK.util;
@@ -51,25 +48,11 @@ class SDK {
* @param params.networkId The network id of CodeChain. The default value is "tc" (testnet)
*/
constructor(params: {
- server: string;
keyStoreType?: KeyStoreType;
networkId?: NetworkId;
- options?: {
- transactionSigner?: string;
- fallbackServers?: string[];
- };
}) {
- const {
- server,
- keyStoreType = "local",
- networkId = "tc",
- options
- } = params;
+ const { keyStoreType = "local", networkId = "tc" } = params;
- this.rpc = new Rpc({
- server,
- options
- });
this.core = new Core({ networkId });
this.key = new Key({
networkId,
diff --git a/test/src/sdk/src/rpc/__test__/invalid-argument.spec.ts b/test/src/sdk/src/rpc/__test__/invalid-argument.spec.ts
deleted file mode 100644
index eba1e3859c..0000000000
--- a/test/src/sdk/src/rpc/__test__/invalid-argument.spec.ts
+++ /dev/null
@@ -1,24 +0,0 @@
-import { Rpc } from "..";
-
-describe("Invalid function argument", () => {
- const rpc = new Rpc({ server: "" });
-
- describe("getRegularKeyOwner", () => {
- const regularKey =
- "0x00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000";
- const invalidRegularKey = "0x0";
- const invalidBlockNumber: any = null;
-
- test("first argument", () => {
- expect(() => {
- rpc.chain.getRegularKeyOwner(invalidRegularKey);
- }).toThrow(invalidRegularKey);
- });
-
- test("second argument", () => {
- expect(() => {
- rpc.chain.getRegularKeyOwner(regularKey, invalidBlockNumber);
- }).toThrow("null");
- });
- });
-});
diff --git a/test/src/sdk/src/rpc/__test__/invalid-response.spec.ts b/test/src/sdk/src/rpc/__test__/invalid-response.spec.ts
deleted file mode 100644
index de1c8bf2da..0000000000
--- a/test/src/sdk/src/rpc/__test__/invalid-response.spec.ts
+++ /dev/null
@@ -1,544 +0,0 @@
-import { PlatformAddress } from "codechain-primitives";
-
-import { Pay, U64 } from "../../core/classes";
-
-import { AccountRpc } from "../account";
-import { ChainRpc } from "../chain";
-import { Rpc } from "../index";
-import { NetworkRpc } from "../network";
-import { NodeRpc } from "../node";
-
-describe("Invalid response", () => {
- const rpc: Rpc = new Rpc({ server: "" });
-
- describe("NodeRpc", () => {
- const nodeRpc = new NodeRpc(rpc);
- test("ping", done => {
- rpc.sendRpcRequest = jest.fn().mockResolvedValueOnce(undefined);
- nodeRpc
- .ping()
- .then(done.fail)
- .catch(e => {
- expect(e.toString()).toContain("ping");
- expect(e.toString()).toContain("string");
- expect(e.toString()).toContain("undefined");
- done();
- });
- });
-
- test("getNodeVersion", done => {
- rpc.sendRpcRequest = jest.fn().mockResolvedValueOnce(undefined);
- nodeRpc
- .getNodeVersion()
- .then(done.fail)
- .catch(e => {
- expect(e.toString()).toContain("getNodeVersion");
- expect(e.toString()).toContain("string");
- expect(e.toString()).toContain("undefined");
- done();
- });
- });
-
- test("getCommitHash", done => {
- rpc.sendRpcRequest = jest.fn().mockResolvedValueOnce(undefined);
- nodeRpc
- .getCommitHash()
- .then(done.fail)
- .catch(e => {
- expect(e.toString()).toContain("getCommitHash");
- expect(e.toString()).toContain("string");
- expect(e.toString()).toContain("undefined");
- done();
- });
- });
- });
-
- describe("ChainRpc", () => {
- const chainRpc = new ChainRpc(rpc, {});
- const address = PlatformAddress.fromAccountId(
- "0x0000000000000000000000000000000000000000",
- { networkId: "tc" }
- );
- const hashH160 = "0x0000000000000000000000000000000000000000";
- const hashH256 =
- "0x0000000000000000000000000000000000000000000000000000000000000000";
- const regularKey =
- "0x00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000";
-
- describe("sendSignedTransaction", () => {
- const secret =
- "0x0000000000000000000000000000000000000000000000000000000000000001";
- const signedTransaction = new Pay(address, new U64(0), "tc").sign({
- secret,
- fee: 0,
- seq: 0
- });
-
- test("null", done => {
- rpc.sendRpcRequest = jest.fn().mockResolvedValueOnce(null);
- chainRpc
- .sendSignedTransaction(signedTransaction)
- .then(() => done.fail())
- .catch(e => {
- expect(e.toString()).toContain("sendSignedTransaction");
- expect(e.toString()).toContain("H256");
- expect(e.toString()).toContain("null");
- done();
- });
- });
-
- test("empty string", done => {
- rpc.sendRpcRequest = jest.fn().mockResolvedValueOnce("");
- chainRpc
- .sendSignedTransaction(signedTransaction)
- .then(() => done.fail())
- .catch(e => {
- expect(e.toString()).toContain("sendSignedTransaction");
- expect(e.toString()).toContain("H256");
- expect(e.toString()).toContain(`""`);
- done();
- });
- });
- });
-
- describe("getTransactionByTracker", () => {
- test("undefined", done => {
- rpc.sendRpcRequest = jest.fn().mockResolvedValueOnce(undefined);
- chainRpc
- .getTransaction(hashH256)
- .then(() => done.fail())
- .catch(e => {
- expect(e.toString()).toContain("chain_getTransaction");
- expect(e.toString()).toContain("SignedTransaction");
- expect(e.toString()).toContain("undefined");
- done();
- });
- });
-
- test.skip("Invalid signature", done =>
- done.fail("not implemented"));
- test.skip("Invalid seq", done => done.fail("not implemented"));
- test.skip("Invalid fee", done => done.fail("not implemented"));
- test.skip("Invalid networkId", done =>
- done.fail("not implemented"));
- test.skip("Invalid type", done => done.fail("not implemented"));
- });
-
- describe("containsTransaction", () => {
- test("undefined", done => {
- rpc.sendRpcRequest = jest.fn().mockResolvedValueOnce(undefined);
- chainRpc
- .containsTransaction(hashH256)
- .then(() => done.fail())
- .catch(e => {
- expect(e.toString()).toContain(
- "chain_containsTransaction"
- );
- expect(e.toString()).toContain("JSON of boolean");
- done();
- });
- });
-
- test.skip("Invalid transaction result", done =>
- done.fail("not implemented"));
- test.skip("Invalid transaction results", done =>
- done.fail("not implemented"));
- });
-
- test("getRegularKey", done => {
- rpc.sendRpcRequest = jest.fn().mockResolvedValueOnce(undefined);
- chainRpc
- .getRegularKey(address)
- .then(() => done.fail())
- .catch(e => {
- expect(e.toString()).toContain("chain_getRegularKey");
- expect(e.toString()).toContain("H512");
- expect(e.toString()).toContain("undefined");
- done();
- });
- });
-
- test("getRegularKeyOwner", done => {
- rpc.sendRpcRequest = jest.fn().mockResolvedValueOnce(undefined);
- chainRpc
- .getRegularKeyOwner(regularKey)
- .then(() => done.fail())
- .catch(e => {
- expect(e.toString()).toContain("chain_getRegularKeyOwner");
- expect(e.toString()).toContain("PlatformAddress");
- expect(e.toString()).toContain("undefined");
- done();
- });
- });
-
- describe("getTransactionByTracker", () => {
- test("undefined", done => {
- rpc.sendRpcRequest = jest.fn().mockResolvedValueOnce(undefined);
- chainRpc
- .getTransactionByTracker(hashH256)
- .then(() => done.fail())
- .catch(e => {
- expect(e.toString()).toContain("chain_getTransaction");
- expect(e.toString()).toContain("JSON of Transaction");
- expect(e.toString()).toContain("undefined");
- done();
- });
- });
-
- test.skip("Invalid type", done => done.fail("not implemented"));
- describe("Invalid data", () => {
- test.skip("AssetMint", done => done.fail("not implemented"));
- test.skip("AssetTransfer", done =>
- done.fail("not implemented"));
- });
- });
-
- describe("getTransactionResultsByTracker", () => {
- test("undefined", done => {
- rpc.sendRpcRequest = jest.fn().mockResolvedValueOnce([]);
- chainRpc
- .getTransactionResultsByTracker(hashH256)
- .then(results => {
- expect(results).toEqual([]);
- done();
- })
- .catch(e => {
- expect(e.toString()).toContain(
- "mempool_getTransactionResultsByTracker"
- );
- expect(e.toString()).toContain("JSON of boolean");
- expect(e.toString()).toContain("undefined");
- done();
- });
- });
-
- test.skip("Invalid result", done => done.fail("not implemented"));
- });
-
- test("getSeq", done => {
- rpc.sendRpcRequest = jest.fn().mockResolvedValueOnce(undefined);
- chainRpc
- .getSeq(address)
- .then(() => done.fail())
- .catch(e => {
- expect(e.toString()).toContain("chain_getSeq");
- expect(e.toString()).toContain("undefined");
- done();
- });
- });
-
- test("getBalance", done => {
- rpc.sendRpcRequest = jest.fn().mockResolvedValueOnce(undefined);
- chainRpc
- .getBalance(address)
- .then(() => done.fail())
- .catch(e => {
- expect(e.toString()).toContain("chain_getBalance");
- expect(e.toString()).toContain("U64");
- expect(e.toString()).toContain("undefined");
- done();
- });
- });
-
- test("getBestBlockNumber", done => {
- rpc.sendRpcRequest = jest.fn().mockResolvedValueOnce(undefined);
- chainRpc
- .getBestBlockNumber()
- .then(() => done.fail())
- .catch(e => {
- expect(e.toString()).toContain("chain_getBestBlockNumber");
- expect(e.toString()).toContain("number");
- expect(e.toString()).toContain("undefined");
- done();
- });
- });
-
- test("getBlockHash", done => {
- rpc.sendRpcRequest = jest.fn().mockResolvedValueOnce(undefined);
- chainRpc
- .getBlockHash(0)
- .then(() => done.fail())
- .catch(e => {
- expect(e.toString()).toContain("chain_getBlockHash");
- expect(e.toString()).toContain("H256");
- expect(e.toString()).toContain("undefined");
- done();
- });
- });
-
- describe("getBlock", () => {
- test("undefined", done => {
- rpc.sendRpcRequest = jest.fn().mockResolvedValueOnce(undefined);
- chainRpc
- .getBlock(0)
- .then(() => done.fail())
- .catch(e => {
- expect(e.toString()).toContain("chain_getBlock");
- expect(e.toString()).toContain("JSON of Block");
- expect(e.toString()).toContain("undefined");
- done();
- });
- });
-
- test.skip("Invalid timestamp", done =>
- done.fail("not implemented"));
- test.skip("Invalid number", done => done.fail("not implemented"));
- });
-
- describe("getAssetSchemeByTracker", () => {
- test("undefined", done => {
- rpc.sendRpcRequest = jest.fn().mockResolvedValueOnce(undefined);
- chainRpc
- .getAssetSchemeByTracker(hashH256, 0)
- .then(() => done.fail())
- .catch(e => {
- expect(e.toString()).toContain(
- "chain_getAssetSchemeByTracker"
- );
- expect(e.toString()).toContain("JSON of AssetScheme");
- expect(e.toString()).toContain("undefined");
- done();
- });
- });
-
- test.skip("Invalid asset scheme", done =>
- done.fail("not implemented"));
- });
-
- describe("getAssetSchemeByType", () => {
- test("undefined", done => {
- rpc.sendRpcRequest = jest.fn().mockResolvedValueOnce(undefined);
- chainRpc
- .getAssetSchemeByType(hashH160, 0)
- .then(() => done.fail())
- .catch(e => {
- expect(e.toString()).toContain(
- "chain_getAssetSchemeByType"
- );
- expect(e.toString()).toContain("JSON of AssetScheme");
- expect(e.toString()).toContain("undefined");
- done();
- });
- });
-
- test.skip("Invalid asset scheme", done =>
- done.fail("not implemented"));
- });
-
- describe("getAsset", () => {
- test("undefined", done => {
- rpc.sendRpcRequest = jest.fn().mockResolvedValueOnce(undefined);
- chainRpc
- .getAsset(hashH256, 0, 0)
- .then(() => done.fail())
- .catch(e => {
- expect(e.toString()).toContain("chain_getAsset");
- expect(e.toString()).toContain("JSON of Asset");
- expect(e.toString()).toContain("undefined");
- done();
- });
- });
-
- test.skip("Invalid asset", done => done.fail("not implemented"));
- });
-
- test("isAssetSpent", done => {
- rpc.sendRpcRequest = jest.fn().mockResolvedValueOnce(undefined);
- chainRpc
- .isAssetSpent(hashH256, 0, 0)
- .then(() => done.fail())
- .catch(e => {
- expect(e.toString()).toContain("chain_isAssetSpent");
- expect(e.toString()).toContain("boolean");
- expect(e.toString()).toContain("undefined");
- done();
- });
- });
-
- describe("getPendingTransactions", () => {
- test("undefined", done => {
- rpc.sendRpcRequest = jest.fn().mockResolvedValueOnce(undefined);
- chainRpc
- .getPendingTransactions()
- .then(() => done.fail())
- .catch(e => {
- expect(e.toString()).toContain(
- "mempool_getPendingTransactions"
- );
- expect(e.toString()).toContain("transactions");
- expect(e.toString()).toContain("lastTimestamp");
- expect(e.toString()).toContain("undefined");
- done();
- });
- });
-
- test.skip("Invalid transactions", done =>
- done.fail("not implemented"));
- });
-
- test("getNetworkId", done => {
- rpc.sendRpcRequest = jest.fn().mockResolvedValueOnce(undefined);
- chainRpc
- .getNetworkId()
- .then(() => done.fail())
- .catch(e => {
- expect(e.toString()).toContain("chain_getNetworkId");
- expect(e.toString()).toContain("string");
- expect(e.toString()).toContain("undefined");
- done();
- });
- });
- });
-
- describe("AccountRpc", () => {
- const accountRpc = new AccountRpc(rpc);
- const hashH256 =
- "0x0000000000000000000000000000000000000000000000000000000000000000";
- const secret =
- "0x0000000000000000000000000000000000000000000000000000000000000001";
- const address = PlatformAddress.fromAccountId(
- "0x0000000000000000000000000000000000000000",
- { networkId: "tc" }
- );
-
- describe("getList", () => {
- test("undefined", done => {
- rpc.sendRpcRequest = jest.fn().mockResolvedValueOnce(undefined);
- accountRpc
- .getList()
- .then(() => done.fail())
- .catch(e => {
- expect(e.toString()).toContain("account_getList");
- expect(e.toString()).toContain("array");
- expect(e.toString()).toContain("undefined");
- done();
- });
- });
-
- test.skip("invalid address string", done =>
- done.fail("not implemented"));
- });
-
- describe("create", () => {
- test("undefined", done => {
- rpc.sendRpcRequest = jest.fn().mockResolvedValueOnce(undefined);
- accountRpc
- .create()
- .then(() => done.fail())
- .catch(e => {
- expect(e.toString()).toContain("account_create");
- expect(e.toString()).toContain("PlatformAddress");
- expect(e.toString()).toContain("undefined");
- done();
- });
- });
-
- test.skip("invalid address string", done =>
- done.fail("not implemented"));
- });
-
- describe("importRaw", () => {
- test("undefined", done => {
- rpc.sendRpcRequest = jest.fn().mockResolvedValueOnce(undefined);
- accountRpc
- .importRaw(secret)
- .then(() => done.fail())
- .catch(e => {
- expect(e.toString()).toContain("account_importRaw");
- expect(e.toString()).toContain("PlatformAddress");
- expect(e.toString()).toContain("undefined");
- done();
- });
- });
-
- test.skip("invalid address string", done =>
- done.fail("not implemented"));
- });
-
- describe("sign", () => {
- test("undefined", done => {
- rpc.sendRpcRequest = jest.fn().mockResolvedValueOnce(undefined);
- accountRpc
- .sign(hashH256, address)
- .then(() => done.fail())
- .catch(e => {
- expect(e.toString()).toContain("account_sign");
- expect(e.toString()).toContain("string");
- expect(e.toString()).toContain("undefined");
- done();
- });
- });
-
- test.skip("invalid signature string", done =>
- done.fail("not implemented"));
- });
-
- test("unlock", done => {
- rpc.sendRpcRequest = jest.fn().mockResolvedValueOnce(undefined);
- accountRpc
- .unlock(address)
- .then(() => done.fail())
- .catch(e => {
- expect(e.toString()).toContain("account_unlock");
- expect(e.toString()).toContain("null");
- expect(e.toString()).toContain("undefined");
- done();
- });
- });
- });
-
- describe("NetworkRpc", () => {
- const networkRpc = new NetworkRpc(rpc);
-
- test.skip("connect", done => done.fail("not implemented"));
- test.skip("disconnect", done => done.fail("not implemented"));
- test.skip("isConnected", done => done.fail("not implemented"));
- test.skip("getPeerCount", done => done.fail("not implemented"));
- describe("getPeers", () => {
- test("undefined", done => {
- rpc.sendRpcRequest = jest.fn().mockResolvedValueOnce(undefined);
- networkRpc
- .getPeers()
- .then(() => done.fail())
- .catch(e => {
- expect(e.toString()).toContain(
- "net_getEstablishedPeers"
- );
- expect(e.toString()).toContain("array");
- expect(e.toString()).toContain("undefined");
- done();
- });
- });
-
- test("invalid address", done => {
- rpc.sendRpcRequest = jest
- .fn()
- .mockResolvedValueOnce([
- "127.0.0.1:3333",
- "127.0.0.1111:3333"
- ]);
- networkRpc
- .getPeers()
- .then(() => done.fail())
- .catch(e => {
- expect(e.toString()).toContain(
- "net_getEstablishedPeers"
- );
- expect(e.toString()).toContain("IPv4");
- expect(e.toString()).toContain("127.0.0.1111:3333");
- done();
- });
- });
- });
- test.skip("addToWhitelist", done => done.fail("not implemented"));
- test.skip("removeFromWhitelist", done => done.fail("not implemented"));
- test.skip("addToBlocklist", done => done.fail("not implemented"));
- test.skip("removeFromBlockList", done => done.fail("not implemented"));
- test.skip("enableWhitelist", done => done.fail("not implemented"));
- test.skip("disableWhitelist", done => done.fail("not implemented"));
- test.skip("enableBlacklist", done => done.fail("not implemented"));
- test.skip("disableBlacklist", done => done.fail("not implemented"));
- test.skip("getWhitelist", done => done.fail("not implemented"));
- test.skip("getBlacklist", done => done.fail("not implemented"));
- });
-});
diff --git a/test/src/sdk/src/rpc/account.ts b/test/src/sdk/src/rpc/account.ts
deleted file mode 100644
index 417e370fe5..0000000000
--- a/test/src/sdk/src/rpc/account.ts
+++ /dev/null
@@ -1,318 +0,0 @@
-import {
- H256,
- H256Value,
- PlatformAddress,
- PlatformAddressValue,
- U64Value
-} from "codechain-primitives";
-
-import { Transaction } from "../core/Transaction";
-
-import { Rpc } from ".";
-
-export class AccountRpc {
- private rpc: Rpc;
-
- /**
- * @hidden
- */
- constructor(rpc: Rpc) {
- this.rpc = rpc;
- }
-
- /**
- * Gets a list of accounts.
- * @returns A list of accounts
- */
- public getList(): Promise {
- return new Promise((resolve, reject) => {
- this.rpc
- .sendRpcRequest("account_getList", [])
- .then((accounts: string[]) => {
- try {
- if (Array.isArray(accounts)) {
- resolve(
- accounts.map(account =>
- PlatformAddress.ensure(account).toString()
- )
- );
- } else {
- reject(
- Error(
- `Expected account_getList to return an array but it returned ${accounts}`
- )
- );
- }
- } catch (e) {
- reject(
- Error(
- `Expected account_getList to return an array of PlatformAddress string, but an error occurred: ${e.toString()}`
- )
- );
- }
- })
- .catch(reject);
- });
- }
-
- /**
- * Creates a new account.
- * @param passphrase A passphrase to be used by the account owner
- * @returns An account
- */
- public create(passphrase?: string): Promise {
- if (passphrase && typeof passphrase !== "string") {
- throw Error(
- `Expected the first argument to be a string but given ${passphrase}`
- );
- }
- return new Promise((resolve, reject) => {
- this.rpc
- .sendRpcRequest("account_create", [passphrase])
- .then(account => {
- try {
- resolve(PlatformAddress.ensure(account).toString());
- } catch (e) {
- reject(
- Error(
- `Expected account_create to return PlatformAddress string but an error occurred: ${e.toString()}`
- )
- );
- }
- })
- .catch(reject);
- });
- }
-
- /**
- * Imports a secret key and add the corresponding account.
- * @param secret H256 or hexstring for 256-bit private key
- * @param passphrase A passphrase to be used by the account owner
- * @returns The account
- */
- public importRaw(secret: H256Value, passphrase?: string): Promise {
- if (!H256.check(secret)) {
- throw Error(
- `Expected the first argument to be an H256 value but found ${secret}`
- );
- }
- if (passphrase && typeof passphrase !== "string") {
- throw Error(
- `Expected the second argument to be a string but found ${passphrase}`
- );
- }
- return new Promise((resolve, reject) => {
- this.rpc
- .sendRpcRequest("account_importRaw", [
- `0x${H256.ensure(secret).value}`,
- passphrase
- ])
- .then(account => {
- try {
- resolve(PlatformAddress.ensure(account).toString());
- } catch (e) {
- reject(
- Error(
- `Expected account_importRaw to return PlatformAddress string but an error occurred: ${e.toString()}`
- )
- );
- }
- })
- .catch(reject);
- });
- }
-
- /**
- * Calculates the account's signature for a given message.
- * @param messageDigest A message to sign
- * @param address A platform address
- * @param passphrase The account's passphrase
- */
- public sign(
- messageDigest: H256Value,
- address: PlatformAddressValue,
- passphrase?: string
- ): Promise {
- if (!H256.check(messageDigest)) {
- throw Error(
- `Expected the first argument to be an H256 value but found ${messageDigest}`
- );
- }
- if (!PlatformAddress.check(address)) {
- throw Error(
- `Expected the second argument to be a PlatformAddress value but found ${address}`
- );
- }
- if (passphrase && typeof passphrase !== "string") {
- throw Error(
- `Expected the third argument to be a string but found ${passphrase}`
- );
- }
- return new Promise((resolve, reject) => {
- this.rpc
- .sendRpcRequest("account_sign", [
- `0x${H256.ensure(messageDigest).value}`,
- PlatformAddress.ensure(address).toString(),
- passphrase
- ])
- .then(result => {
- if (
- typeof result === "string" &&
- result.match(/0x[0-9a-f]{130}/)
- ) {
- return resolve(result);
- }
- reject(
- Error(
- `Expected account_sign to return a 65 byte hexstring but it returned ${result}`
- )
- );
- })
- .catch(reject);
- });
- }
-
- /**
- * Sends a transaction with the account's signature.
- * @param params.tx A tx to send
- * @param params.account The platform account to sign the tx
- * @param params.passphrase The account's passphrase
- */
- public async sendTransaction(params: {
- tx: Transaction;
- account: PlatformAddressValue;
- fee?: U64Value;
- passphrase?: string;
- blockNumber?: number;
- }): Promise<{ hash: H256; seq: number }> {
- const { tx, fee, account, passphrase, blockNumber } = params;
- if (!PlatformAddress.check(account)) {
- throw Error(
- `Expected the account param to be a PlatformAddress value but found ${account}`
- );
- }
- if (passphrase && typeof passphrase !== "string") {
- throw Error(
- `Expected the passphrase param to be a string but found ${passphrase}`
- );
- }
- if (fee) {
- tx.setFee(fee);
- }
- if (tx.fee() == null) {
- const minFee = await this.rpc.chain.getMinTransactionFee(
- tx.type(),
- blockNumber
- );
- if (minFee === null) {
- throw new Error("The fee of the tx is not specified");
- }
- tx.setFee(minFee);
- }
- const result = await this.rpc.sendRpcRequest(
- "account_sendTransaction",
- [
- tx.toJSON(),
- PlatformAddress.ensure(account).toString(),
- passphrase
- ]
- );
- return {
- hash: H256.ensure(result.hash),
- seq: result.seq
- };
- }
- /**
- * Unlocks the account.
- * @param address A platform address
- * @param passphrase The account's passphrase
- * @param duration Time to keep the account unlocked. The default value is 300(seconds). Passing 0 unlocks the account indefinitely.
- */
- public unlock(
- address: PlatformAddressValue,
- passphrase?: string,
- duration?: number
- ): Promise {
- if (!PlatformAddress.check(address)) {
- throw Error(
- `Expected the first argument to be a PlatformAddress value but found ${address}`
- );
- }
- if (passphrase && typeof passphrase !== "string") {
- throw Error(
- `Expected the second argument to be a string but found ${passphrase}`
- );
- }
- if (
- duration !== undefined &&
- (typeof duration !== "number" ||
- !Number.isInteger(duration) ||
- duration < 0)
- ) {
- throw Error(
- `Expected the third argument to be non-negative integer but found ${duration}`
- );
- }
- return new Promise((resolve, reject) => {
- this.rpc
- .sendRpcRequest("account_unlock", [
- PlatformAddress.ensure(address).toString(),
- passphrase || "",
- duration
- ])
- .then(result => {
- if (result === null) {
- return resolve(null);
- }
- reject(
- Error(
- `Expected account_unlock to return null but it returned ${result}`
- )
- );
- })
- .catch(reject);
- });
- }
-
- /**
- * Changes the passpharse of the account
- * @param address A platform address
- * @param oldPassphrase The account's current passphrase
- * @param newPassphrase The new passphrase for the account
- */
- public changePassword(
- address: PlatformAddressValue,
- oldPassphrase: string,
- newPassphrase: string
- ): Promise {
- if (oldPassphrase && typeof oldPassphrase !== "string") {
- throw Error(
- `Expected the second argument to be a string but given ${oldPassphrase}`
- );
- }
- if (newPassphrase && typeof newPassphrase !== "string") {
- throw Error(
- `Expected the second argument to be a string but given ${newPassphrase}`
- );
- }
- return new Promise((resolve, reject) => {
- this.rpc
- .sendRpcRequest("account_changePassword", [
- address,
- oldPassphrase,
- newPassphrase
- ])
- .then(result => {
- if (result == null) {
- return resolve(null);
- }
- reject(
- Error(
- `Expected account_changePassword to return null but it returned ${result}`
- )
- );
- })
- .catch(reject);
- });
- }
-}
diff --git a/test/src/sdk/src/rpc/chain.ts b/test/src/sdk/src/rpc/chain.ts
deleted file mode 100644
index 1ed711d0ae..0000000000
--- a/test/src/sdk/src/rpc/chain.ts
+++ /dev/null
@@ -1,1682 +0,0 @@
-import {
- H160,
- H160Value,
- H256,
- H256Value,
- H512,
- H512Value,
- PlatformAddress,
- PlatformAddressValue,
- U64,
- U64Value
-} from "codechain-primitives";
-
-import { Rpc } from ".";
-import { Asset } from "../core/Asset";
-import { AssetScheme } from "../core/AssetScheme";
-import { Block } from "../core/Block";
-import { SignedTransaction } from "../core/SignedTransaction";
-import { Text } from "../core/Text";
-import { Transaction } from "../core/Transaction";
-import { fromJSONToSignedTransaction } from "../core/transaction/json";
-import { CommonParams, NetworkId } from "../core/types";
-
-export class ChainRpc {
- private rpc: Rpc;
- private transactionSigner?: string;
- private fallbackServers?: string[];
-
- /**
- * @hidden
- */
- constructor(
- rpc: Rpc,
- options: { transactionSigner?: string; fallbackServers?: string[] }
- ) {
- const { transactionSigner, fallbackServers } = options;
- this.rpc = rpc;
- this.transactionSigner = transactionSigner;
- this.fallbackServers = fallbackServers;
- }
-
- /**
- * Sends SignedTransaction to CodeChain's network.
- * @param tx SignedTransaction
- * @returns SignedTransaction's hash.
- */
- public sendSignedTransaction(tx: SignedTransaction): Promise {
- if (!(tx instanceof SignedTransaction)) {
- throw Error(
- `Expected the first argument of sendSignedTransaction to be SignedTransaction but found ${tx}`
- );
- }
- return new Promise((resolve, reject) => {
- const bytes = tx.rlpBytes().toString("hex");
- const fallbackServers = this.fallbackServers;
- this.rpc
- .sendRpcRequest(
- "mempool_sendSignedTransaction",
- [`0x${bytes}`],
- {
- fallbackServers
- }
- )
- .then(result => {
- try {
- resolve(new H256(result));
- } catch (e) {
- reject(
- Error(
- `Expected sendSignedTransaction() to return a value of H256, but an error occurred: ${e.toString()}`
- )
- );
- }
- })
- .catch(reject);
- });
- }
-
- /**
- * Signs a tx with the given account and sends it to CodeChain's network.
- * @param tx The tx to send
- * @param options.account The account to sign the tx
- * @param options.passphrase The account's passphrase
- * @param options.seq The seq of the tx
- * @param options.fee The fee of the tx
- * @returns SignedTransaction's hash
- * @throws When the given account cannot afford to pay the fee
- * @throws When the given fee is too low
- * @throws When the given seq does not match
- * @throws When the given account is unknown
- * @throws When the given passphrase does not match
- */
- public async sendTransaction(
- tx: Transaction,
- options: {
- account?: PlatformAddressValue;
- passphrase?: string;
- seq?: number | null;
- fee?: U64Value;
- blockNumber?: number;
- } = {}
- ): Promise {
- if (!(tx instanceof Transaction)) {
- throw Error(
- `Expected the first argument of sendTransaction to be a Transaction but found ${tx}`
- );
- }
- const {
- account = this.transactionSigner,
- passphrase,
- blockNumber,
- fee = await this.getMinTransactionFee(tx.type(), blockNumber)
- } = options;
- if (!account) {
- throw Error("The account to sign the tx is not specified");
- } else if (!PlatformAddress.check(account)) {
- throw Error(
- `Expected account param of sendTransaction to be a PlatformAddress value but found ${account}`
- );
- }
- const { seq = await this.getSeq(account) } = options;
- tx.setSeq(seq!);
- if (!fee) {
- throw Error("The fee of the tx is not specified");
- }
- tx.setFee(fee);
- const address = PlatformAddress.ensure(account);
- const sig = await this.rpc.account.sign(
- tx.unsignedHash(),
- address,
- passphrase
- );
- return this.sendSignedTransaction(new SignedTransaction(tx, sig));
- }
-
- /**
- * Gets SignedTransaction of given hash. Else returns null.
- * @param hash SignedTransaction's hash
- * @returns SignedTransaction, or null when SignedTransaction was not found.
- */
- public getTransaction(hash: H256Value): Promise {
- if (!H256.check(hash)) {
- throw Error(
- `Expected the first argument of getTransaction to be an H256 value but found ${hash}`
- );
- }
- return new Promise((resolve, reject) => {
- const fallbackServers = this.fallbackServers;
- this.rpc
- .sendRpcRequest(
- "chain_getTransaction",
- [`0x${H256.ensure(hash).value}`],
- { fallbackServers }
- )
- .then(result => {
- try {
- resolve(
- result === null
- ? null
- : fromJSONToSignedTransaction(result)
- );
- } catch (e) {
- reject(
- Error(
- `Expected chain_getTransaction to return either null or JSON of SignedTransaction, but an error occurred: ${e.toString()}`
- )
- );
- }
- })
- .catch(reject);
- });
- }
-
- /**
- * Queries whether the chain has the transaction of given tx.
- * @param hash The tx hash of which to get the corresponding tx of.
- * @returns boolean when transaction of given hash not exists.
- */
- public async containsTransaction(hash: H256Value): Promise {
- if (!H256.check(hash)) {
- throw Error(
- `Expected the first argument of containsTransaction to be an H256 value but found ${hash}`
- );
- }
- const result = await this.rpc.sendRpcRequest(
- "chain_containsTransaction",
- [`0x${H256.ensure(hash).value}`],
- { fallbackServers: this.fallbackServers }
- );
- try {
- return JSON.parse(result);
- } catch (e) {
- throw Error(
- `Expected chain_containsTransaction to return JSON of boolean, but an error occurred: ${e.toString()}`
- );
- }
- }
-
- /**
- * Gets the regular key of an account of given address, recorded in the block of given blockNumber. If blockNumber is not given, then returns the regular key in the most recent block.
- * @param address An account address
- * @param blockNumber The specific block number to get account's regular key at given address.
- * @returns The regular key of account at specified block.
- */
- public getRegularKey(
- address: PlatformAddressValue,
- blockNumber?: number
- ): Promise {
- const fallbackServers = this.fallbackServers;
- if (!PlatformAddress.check(address)) {
- throw Error(
- `Expected the first argument of getRegularKey to be a PlatformAddress value but found ${address}`
- );
- }
- if (blockNumber !== undefined && !isNonNegativeInterger(blockNumber)) {
- throw Error(
- `Expected the second argument of getRegularKey to be a number but found ${blockNumber}`
- );
- }
- return new Promise((resolve, reject) => {
- this.rpc
- .sendRpcRequest(
- "chain_getRegularKey",
- [`${PlatformAddress.ensure(address).value}`, blockNumber],
- { fallbackServers }
- )
- .then(result => {
- try {
- resolve(result === null ? null : new H512(result));
- } catch (e) {
- reject(
- Error(
- `Expected chain_getRegularKey to return either null or a value of H512, but an error occurred: ${e.toString()}`
- )
- );
- }
- })
- .catch(reject);
- });
- }
-
- /**
- * Gets the owner of a regular key, recorded in the block of given blockNumber.
- * @param regularKey A regular key.
- * @param blockNumber A block number.
- * @return The platform address that can use the regular key at the specified block.
- */
- public getRegularKeyOwner(
- regularKey: H512Value,
- blockNumber?: number
- ): Promise {
- const fallbackServers = this.fallbackServers;
- if (!H512.check(regularKey)) {
- throw Error(
- `Expected the first argument of getRegularKeyOwner to be an H512 value but found ${regularKey}`
- );
- }
- if (blockNumber !== undefined && !isNonNegativeInterger(blockNumber)) {
- throw Error(
- `Expected the second argument of getRegularKeyOwner to be a number but found ${blockNumber}`
- );
- }
- return new Promise((resolve, reject) => {
- this.rpc
- .sendRpcRequest(
- "chain_getRegularKeyOwner",
- [`0x${H512.ensure(regularKey).value}`, blockNumber],
- { fallbackServers }
- )
- .then(result => {
- try {
- resolve(
- result === null
- ? null
- : PlatformAddress.fromString(result)
- );
- } catch (e) {
- reject(
- Error(
- `Expected chain_getRegularKeyOwner to return a PlatformAddress string, but an error occurred: ${e.toString()}`
- )
- );
- }
- })
- .catch(reject);
- });
- }
-
- /**
- * Gets the shard id of the given hash of a CreateShard transaction.
- * @param hash A transaction hash of a CreateShard transaction.
- * @param blockNumber A block number.
- * @returns A shard id.
- */
- public getShardIdByHash(
- hash: H256Value,
- blockNumber?: number
- ): Promise {
- const fallbackServers = this.fallbackServers;
- if (!H256.check(hash)) {
- throw Error(
- `Expected the first argument of getShardIdByHash to be an H256 value but found ${hash}`
- );
- }
- if (blockNumber !== undefined && !isNonNegativeInterger(blockNumber)) {
- throw Error(
- `Expected the second argument of getShardIdByHash to be a number but found ${blockNumber}`
- );
- }
- return new Promise((resolve, reject) => {
- this.rpc
- .sendRpcRequest(
- "chain_getShardIdByHash",
- [H256.ensure(hash).toJSON(), blockNumber],
- { fallbackServers }
- )
- .then(result => {
- if (result === null || typeof result === "number") {
- resolve(result);
- } else {
- reject(
- Error(
- `Expected chain_getShardIdByHash to return either number or null but it returned ${result}`
- )
- );
- }
- })
- .catch(reject);
- });
- }
-
- /**
- * Gets the owners of the shard.
- * @param shardId A shard id.
- * @returns The platform addresses of the owners.
- */
- public getShardOwners(
- shardId: number,
- blockNumber?: number
- ): Promise {
- const fallbackServers = this.fallbackServers;
- return new Promise((resolve, reject) => {
- this.rpc
- .sendRpcRequest(
- "chain_getShardOwners",
- [shardId, blockNumber],
- { fallbackServers }
- )
- .then(result => {
- try {
- resolve(
- result === null
- ? null
- : (result as string[]).map(str =>
- PlatformAddress.ensure(str)
- )
- );
- } catch (e) {
- reject(
- Error(
- `Expected chain_getShardOwners to return either null or an array of PlatformAddress, but an error occurred: ${e.toString()}`
- )
- );
- }
- })
- .catch(reject);
- });
- }
-
- /**
- * Gets the users of the shard.
- * @param shardId A shard id.
- * @returns The platform addresses of the users.
- */
- public getShardUsers(
- shardId: number,
- blockNumber?: number
- ): Promise {
- const fallbackServers = this.fallbackServers;
- return new Promise((resolve, reject) => {
- this.rpc
- .sendRpcRequest("chain_getShardUsers", [shardId, blockNumber], {
- fallbackServers
- })
- .then(result => {
- try {
- resolve(
- result === null
- ? null
- : (result as string[]).map(str =>
- PlatformAddress.ensure(str)
- )
- );
- } catch (e) {
- reject(
- Error(
- `Expected chain_getShardUsers to return either null or an array of PlatformAddress, but an error occurred: ${e.toString()}`
- )
- );
- }
- })
- .catch(reject);
- });
- }
-
- /**
- * Gets a transaction of given hash.
- * @param tracker The tracker of which to get the corresponding transaction of.
- * @returns A transaction, or null when transaction of given hash not exists.
- */
- public getTransactionByTracker(
- tracker: H256Value
- ): Promise {
- const fallbackServers = this.fallbackServers;
- if (!H256.check(tracker)) {
- throw Error(
- `Expected the first argument of getTransactionByTracker to be an H256 value but found ${tracker}`
- );
- }
- return new Promise((resolve, reject) => {
- this.rpc
- .sendRpcRequest(
- "chain_getTransactionByTracker",
- [`0x${H256.ensure(tracker).value}`],
- { fallbackServers }
- )
- .then(result => {
- try {
- resolve(
- result === null
- ? null
- : fromJSONToSignedTransaction(result)
- );
- } catch (e) {
- reject(
- Error(
- `Expected chain_getTransactionByTracker to return either null or JSON of Transaction, but an error occurred: ${e.toString()}`
- )
- );
- }
- })
- .catch(reject);
- });
- }
-
- /**
- * Gets results of a transaction of given tracker.
- * @param tracker The transaction hash of which to get the corresponding transaction of.
- * @param options.timeout Indicating milliseconds to wait the transaction to be confirmed.
- * @returns List of boolean, or null when transaction of given hash not exists.
- */
- public async getTransactionResultsByTracker(
- tracker: H256Value,
- options: { timeout?: number } = {}
- ): Promise {
- const fallbackServers = this.fallbackServers;
- if (!H256.check(tracker)) {
- throw Error(
- `Expected the first argument of getTransactionResultsByTracker to be an H256 value but found ${tracker}`
- );
- }
- const attemptToGet = async () => {
- return this.rpc.sendRpcRequest(
- "mempool_getTransactionResultsByTracker",
- [`0x${H256.ensure(tracker).value}`],
- { fallbackServers }
- );
- };
- const startTime = Date.now();
- const { timeout } = options;
- if (
- timeout !== undefined &&
- (typeof timeout !== "number" || timeout < 0)
- ) {
- throw Error(
- `Expected timeout param of getTransactionResultsByTracker to be non-negative number but found ${timeout}`
- );
- }
- let result = await attemptToGet();
- while (
- result == null &&
- timeout !== undefined &&
- Date.now() - startTime < timeout
- ) {
- await new Promise(resolve => setTimeout(resolve, 1000));
- result = await attemptToGet();
- }
- if (result == null) {
- return [];
- }
- try {
- return result.map(JSON.parse);
- } catch (e) {
- throw Error(
- `Expected mempool_getTransactionResultsByTracker to return JSON of boolean[], but an error occurred: ${e.toString()}. received: ${JSON.stringify(
- result
- )}`
- );
- }
- }
-
- /**
- * Gets balance of an account of given address, recorded in the block of given blockNumber. If blockNumber is not given, then returns balance recorded in the most recent block.
- * @param address An account address
- * @param blockNumber The specific block number to get account's balance at given address.
- * @returns Balance of account at the specified block, or null if no such block exists.
- */
- public getBalance(
- address: PlatformAddressValue,
- blockNumber?: number
- ): Promise {
- const fallbackServers = this.fallbackServers;
- if (!PlatformAddress.check(address)) {
- throw Error(
- `Expected the first argument of getBalance to be a PlatformAddress value but found ${address}`
- );
- }
- if (blockNumber !== undefined && !isNonNegativeInterger(blockNumber)) {
- throw Error(
- `Expected the second argument of getBalance to be a number but found ${blockNumber}`
- );
- }
- return new Promise((resolve, reject) => {
- this.rpc
- .sendRpcRequest(
- "chain_getBalance",
- [`${PlatformAddress.ensure(address).value}`, blockNumber],
- { fallbackServers }
- )
- .then(result => {
- try {
- // FIXME: Need to discuss changing the return type to `U64 | null`. It's a
- // breaking change.
- resolve(
- result === null ? (null as any) : new U64(result)
- );
- } catch (e) {
- reject(
- Error(
- `Expected chain_getBalance to return a value of U64, but an error occurred: ${e.toString()}`
- )
- );
- }
- })
- .catch(reject);
- });
- }
-
- /**
- * Gets a hint to find out why the transaction failed.
- * @param transactionHash A transaction hash from which the error hint would get.
- * @returns Null if the transaction is not involved in the chain or succeeded. If the transaction failed, this should return the reason for the transaction failing.
- */
- public async getErrorHint(
- transactionHash: H256Value
- ): Promise {
- const fallbackServers = this.fallbackServers;
- if (!H256.check(transactionHash)) {
- throw Error(
- `Expected the first argument of getErrorHint to be an H256 value but found ${transactionHash}`
- );
- }
- return new Promise((resolve, reject) => {
- this.rpc
- .sendRpcRequest(
- "mempool_getErrorHint",
- [`0x${H256.ensure(transactionHash).value}`],
- { fallbackServers }
- )
- .then(result => {
- if (typeof result === "string" || result == null) {
- return resolve(result);
- }
- reject(
- Error(
- `Expected mempool_getErrorHint to return either null or value of string, but it returned ${result}`
- )
- );
- })
- .catch(reject);
- });
- }
-
- /**
- * Gets seq of an account of given address, recorded in the block of given blockNumber. If blockNumber is not given, then returns seq recorded in the most recent block.
- * @param address An account address
- * @param blockNumber The specific block number to get account's seq at given address.
- * @returns Seq of account at the specified block, or null if no such block exists.
- */
- public getSeq(
- address: PlatformAddressValue,
- blockNumber?: number
- ): Promise {
- const fallbackServers = this.fallbackServers;
- if (!PlatformAddress.check(address)) {
- throw Error(
- `Expected the first argument of getSeq to be a PlatformAddress value but found ${address}`
- );
- }
- if (blockNumber !== undefined && !isNonNegativeInterger(blockNumber)) {
- throw Error(
- `Expected the second argument of getSeq to be a number but found ${blockNumber}`
- );
- }
- return new Promise((resolve, reject) => {
- this.rpc
- .sendRpcRequest(
- "chain_getSeq",
- [`${PlatformAddress.ensure(address).value}`, blockNumber],
- { fallbackServers }
- )
- .then(async result => {
- if (result == null) {
- throw Error("chain_getSeq returns undefined");
- }
- resolve(result);
- })
- .catch(reject);
- });
- }
-
- /**
- * Gets number of the latest block.
- * @returns Number of the latest block.
- */
- public getBestBlockNumber(): Promise {
- const fallbackServers = this.fallbackServers;
- return new Promise((resolve, reject) => {
- this.rpc
- .sendRpcRequest("chain_getBestBlockNumber", [], {
- fallbackServers
- })
- .then(result => {
- if (typeof result === "number") {
- return resolve(result);
- }
- reject(
- Error(
- `Expected chain_getBestBlockNumber to return a number, but it returned ${result}`
- )
- );
- })
- .catch(reject);
- });
- }
-
- /**
- * Gets block hash of given blockNumber.
- * @param blockNumber The block number of which to get the block hash of.
- * @returns BlockHash, if block exists. Else, returns null.
- */
- public getBlockHash(blockNumber: number): Promise {
- const fallbackServers = this.fallbackServers;
- if (!isNonNegativeInterger(blockNumber)) {
- throw Error(
- `Expected the first argument of getBlockHash to be a non-negative integer but found ${blockNumber}`
- );
- }
- return new Promise((resolve, reject) => {
- this.rpc
- .sendRpcRequest("chain_getBlockHash", [blockNumber], {
- fallbackServers
- })
- .then(result => {
- try {
- resolve(result === null ? null : new H256(result));
- } catch (e) {
- reject(
- Error(
- `Expected chain_getBlockHash to return either null or a value of H256, but an error occurred: ${e.toString()}`
- )
- );
- }
- })
- .catch(reject);
- });
- }
-
- /**
- * Gets block of given block hash.
- * @param hashOrNumber The block hash or number of which to get the block of
- * @returns Block, if block exists. Else, returns null.
- */
- public async getBlock(
- hashOrNumber: H256Value | number
- ): Promise {
- let result;
- const fallbackServers = this.fallbackServers;
- if (hashOrNumber instanceof H256 || typeof hashOrNumber === "string") {
- result = await this.rpc.sendRpcRequest(
- "chain_getBlockByHash",
- [`0x${H256.ensure(hashOrNumber).value}`],
- { fallbackServers }
- );
- } else if (typeof hashOrNumber === "number") {
- result = await this.rpc.sendRpcRequest(
- "chain_getBlockByNumber",
- [hashOrNumber],
- { fallbackServers }
- );
- } else {
- throw Error(
- `Expected the first argument of getBlock to be either a number or an H256 value but found ${hashOrNumber}`
- );
- }
- try {
- return result === null ? null : Block.fromJSON(result);
- } catch (e) {
- throw Error(
- `Expected chain_getBlock to return either null or JSON of Block, but an error occurred: ${e.toString()}`
- );
- }
- }
-
- /**
- * Gets asset scheme of given tracker of the mint transaction.
- * @param tracker The tracker of the mint transaction.
- * @param shardId The shard id of Asset Scheme.
- * @param blockNumber The specific block number to get the asset scheme from
- * @returns AssetScheme, if asset scheme exists. Else, returns null.
- */
- public getAssetSchemeByTracker(
- tracker: H256Value,
- shardId: number,
- blockNumber?: number | null
- ): Promise {
- const fallbackServers = this.fallbackServers;
- if (!H256.check(tracker)) {
- throw Error(
- `Expected the first arugment of getAssetSchemeByTracker to be an H256 value but found ${tracker}`
- );
- }
- if (!isShardIdValue(shardId)) {
- throw Error(
- `Expected the second argument of getAssetSchemeByTracker to be a shard ID value but found ${shardId}`
- );
- }
- if (blockNumber !== undefined && !isNonNegativeInterger(blockNumber)) {
- throw Error(
- `Expected the third argument of getAssetSchemeByTracker to be non-negative integer but found ${blockNumber}`
- );
- }
- return new Promise((resolve, reject) => {
- this.rpc
- .sendRpcRequest(
- "chain_getAssetSchemeByTracker",
- [`0x${H256.ensure(tracker).value}`, shardId, blockNumber],
- { fallbackServers }
- )
- .then(result => {
- try {
- resolve(
- result === null
- ? null
- : AssetScheme.fromJSON(result)
- );
- } catch (e) {
- reject(
- Error(
- `Expected chain_getAssetSchemeByTracker to return either null or JSON of AssetScheme, but an error occurred: ${e.toString()}`
- )
- );
- }
- })
- .catch(reject);
- });
- }
-
- /**
- * Gets asset scheme of asset type
- * @param assetType The type of Asset.
- * @param shardId The shard id of Asset Scheme.
- * @param blockNumber The specific block number to get the asset scheme from
- * @returns AssetScheme, if asset scheme exists. Else, returns null.
- */
- public getAssetSchemeByType(
- assetType: H160Value,
- shardId: number,
- blockNumber?: number | null
- ): Promise {
- const fallbackServers = this.fallbackServers;
- if (!H160.check(assetType)) {
- throw Error(
- `Expected the first arugment of getAssetSchemeByType to be an H160 value but found ${assetType}`
- );
- }
- if (!isShardIdValue(shardId)) {
- throw Error(
- `Expected the second argument of getAssetSchemeByType to be a shard ID value but found ${shardId}`
- );
- }
- if (blockNumber !== undefined && !isNonNegativeInterger(blockNumber)) {
- throw Error(
- `Expected the third argument of getAssetSchemeByType to be non-negative integer but found ${blockNumber}`
- );
- }
- return new Promise((resolve, reject) => {
- this.rpc
- .sendRpcRequest(
- "chain_getAssetSchemeByType",
- [`0x${H160.ensure(assetType).value}`, shardId, blockNumber],
- { fallbackServers }
- )
- .then(result => {
- try {
- resolve(
- result === null
- ? null
- : AssetScheme.fromJSON(result)
- );
- } catch (e) {
- reject(
- Error(
- `Expected chain_getAssetSchemeByType to return either null or JSON of AssetScheme, but an error occurred: ${e.toString()}`
- )
- );
- }
- })
- .catch(reject);
- });
- }
-
- /**
- * Gets asset of given transaction hash and index.
- * @param tracker The tracker of previous input transaction.
- * @param index The index of output in the transaction.
- * @param shardId The shard id of output in the transaction.
- * @param blockNumber The specific block number to get the asset from
- * @returns Asset, if asset exists, Else, returns null.
- */
- public getAsset(
- tracker: H256Value,
- index: number,
- shardId: number,
- blockNumber?: number
- ): Promise {
- const fallbackServers = this.fallbackServers;
- if (!H256.check(tracker)) {
- throw Error(
- `Expected the first argument of getAsset to be an H256 value but found ${tracker}`
- );
- }
- if (!isNonNegativeInterger(index)) {
- throw Error(
- `Expected the second argument of getAsset to be non-negative integer but found ${index}`
- );
- }
- if (!isShardIdValue(shardId)) {
- throw Error(
- `Expected the third argument of getAsset to be a shard ID value but found ${shardId}`
- );
- }
- if (blockNumber !== undefined && !isNonNegativeInterger(blockNumber)) {
- throw Error(
- `Expected the forth argument of getAsset to be non-negative integer but found ${blockNumber}`
- );
- }
- return new Promise((resolve, reject) => {
- this.rpc
- .sendRpcRequest(
- "chain_getAsset",
- [
- `0x${H256.ensure(tracker).value}`,
- index,
- shardId,
- blockNumber
- ],
- { fallbackServers }
- )
- .then(result => {
- if (result === null) {
- return resolve(null);
- }
- try {
- resolve(
- Asset.fromJSON({
- ...result,
- shardId,
- tracker: H256.ensure(tracker).value,
- transactionOutputIndex: index
- })
- );
- } catch (e) {
- reject(
- Error(
- `Expected chain_getAsset to return either null or JSON of Asset, but an error occurred: ${e.toString()}`
- )
- );
- }
- })
- .catch(reject);
- });
- }
-
- /**
- * Gets the text of the given hash of tx with Store type.
- * @param txHash The tx hash of the Store tx.
- * @param blockNumber The specific block number to get the text from
- * @returns Text, if text exists. Else, returns null.
- */
- public getText(
- txHash: H256Value,
- blockNumber?: number | null
- ): Promise {
- const fallbackServers = this.fallbackServers;
- if (!H256.check(txHash)) {
- throw Error(
- `Expected the first arugment of getText to be an H256 value but found ${txHash}`
- );
- }
- if (blockNumber !== undefined && !isNonNegativeInterger(blockNumber)) {
- throw Error(
- `Expected the second argument of getText to be non-negative integer but found ${blockNumber}`
- );
- }
- return new Promise((resolve, reject) => {
- this.rpc
- .sendRpcRequest(
- "chain_getText",
- [`0x${H256.ensure(txHash).value}`, blockNumber],
- { fallbackServers }
- )
- .then(result => {
- try {
- resolve(result == null ? null : Text.fromJSON(result));
- } catch (e) {
- reject(
- Error(
- `Expected chain_getText to return either null or JSON of Text, but an error occurred: ${e.toString()}`
- )
- );
- }
- })
- .catch(reject);
- });
- }
-
- /**
- * Checks whether an asset is spent or not.
- * @param txhash The tx hash of AssetMintTransaction or AssetTransferTransaction.
- * @param index The index of output in the transaction.
- * @param shardId The shard id of an Asset.
- * @param blockNumber The specific block number to get the asset from.
- * @returns True, if the asset is spent. False, if the asset is not spent. Null, if no such asset exists.
- */
- public isAssetSpent(
- txhash: H256Value,
- index: number,
- shardId: number,
- blockNumber?: number
- ): Promise {
- const fallbackServers = this.fallbackServers;
- if (!H256.check(txhash)) {
- throw Error(
- `Expected the first argument of isAssetSpent to be an H256 value but found ${txhash}`
- );
- }
- if (!isNonNegativeInterger(index)) {
- throw Error(
- `Expected the second argument of isAssetSpent to be a non-negative integer but found ${index}`
- );
- }
- if (!isShardIdValue(shardId)) {
- throw Error(
- `Expected the third argument of isAssetSpent to be a shard ID value but found ${shardId}`
- );
- }
-
- return new Promise((resolve, reject) => {
- this.rpc
- .sendRpcRequest(
- "chain_isAssetSpent",
- [
- `0x${H256.ensure(txhash).value}`,
- index,
- shardId,
- blockNumber
- ],
- { fallbackServers }
- )
- .then(result => {
- if (result === null || typeof result === "boolean") {
- resolve(result);
- } else {
- reject(
- Error(
- `Expected chain_isAssetSpent to return either null or a boolean but it returned ${result}`
- )
- );
- }
- })
- .catch(reject);
- });
- }
-
- /**
- * Gets pending transactions that have the insertion timestamp within the given range.
- * @param from The lower bound of the insertion timestamp.
- * @param to The upper bound of the insertion timestamp.
- * @returns List of SignedTransaction, with each tx has null for blockNumber/blockHash/transactionIndex.
- */
- public getPendingTransactions(
- from?: number | null,
- to?: number | null
- ): Promise<{
- transactions: SignedTransaction[];
- lastTimestamp: number | null;
- }> {
- const fallbackServers = this.fallbackServers;
- if (from != null && !isNonNegativeInterger(from)) {
- throw Error(
- `Expected the first argument of getPendingTransactions to be a non-negative integer but found ${from}`
- );
- }
- if (to != null && !isNonNegativeInterger(to)) {
- throw Error(
- `Expected the second argument of getPendingTransactions to be a non-negative integer but found ${to}`
- );
- }
- return new Promise((resolve, reject) => {
- this.rpc
- .sendRpcRequest("mempool_getPendingTransactions", [from, to], {
- fallbackServers
- })
- .then(result => {
- try {
- const resultTransactions = result.transactions;
- const resultLastTimestamp = result.lastTimestamp;
- if (!Array.isArray(resultTransactions)) {
- return reject(
- Error(
- `Expected mempool_getPendingTransactions to return an object whose property "transactions" is of array type but it is ${resultTransactions}`
- )
- );
- }
- if (
- resultLastTimestamp !== null &&
- typeof resultLastTimestamp !== "number"
- ) {
- return reject(
- Error(
- `Expected mempool_getPendingTransactions to return an object containing a number but it returned ${resultLastTimestamp}`
- )
- );
- }
- resolve({
- transactions: resultTransactions.map(
- fromJSONToSignedTransaction
- ),
- lastTimestamp: resultLastTimestamp
- });
- } catch (e) {
- reject(
- Error(
- `Expected mempool_getPendingTransactions to return an object who has transactions and lastTimestamp properties, but an error occurred: ${e.toString()}`
- )
- );
- }
- })
- .catch(reject);
- });
- }
-
- /**
- * Gets the minimum transaction fee of the given transaction type in the given block.
- * @param transactionType
- * @param blockNumber
- * @returns The minimum transaction fee of the corresponding transactionType in the unit of CCC.
- */
- public getMinTransactionFee(
- transactionType: string,
- blockNumber?: number | null
- ): Promise {
- const fallbackServers = this.fallbackServers;
- if (blockNumber !== undefined && !isNonNegativeInterger(blockNumber)) {
- throw Error(
- `Expected the second argument of getMinTransactionFee to be non-negative integer but found ${blockNumber}`
- );
- }
-
- return new Promise((resolve, reject) => {
- this.rpc
- .sendRpcRequest(
- "chain_getMinTransactionFee",
- [transactionType, blockNumber],
- { fallbackServers }
- )
- .then(result => {
- if (result === null || typeof result === "number") {
- resolve(result);
- } else {
- reject(
- Error(
- `Expected chain_getMinTransactionFee to return either null or a number but it returned ${result}`
- )
- );
- }
- })
- .catch(reject);
- });
- }
-
- /**
- * Gets the network ID of the node.
- * @returns A network ID, e.g. "tc".
- */
- public getNetworkId(): Promise {
- const fallbackServers = this.fallbackServers;
- return new Promise((resolve, reject) => {
- this.rpc
- .sendRpcRequest("chain_getNetworkId", [], { fallbackServers })
- .then(result => {
- if (typeof result === "string") {
- resolve(result);
- } else {
- reject(
- Error(
- `Expected chain_getNetworkId to return a string but it returned ${result}`
- )
- );
- }
- })
- .catch(reject);
- });
- }
-
- /**
- * Gets the number of shards, at the state of the given blockNumber
- * @param blockNumber A block number.
- * @returns A number of shards
- */
- public getNumberOfShards(blockNumber?: number): Promise {
- const fallbackServers = this.fallbackServers;
- if (blockNumber !== undefined && !isNonNegativeInterger(blockNumber)) {
- throw Error(
- `Expected the first argument of getNumberOfShards to be a number but found ${blockNumber}`
- );
- }
-
- return new Promise((resolve, reject) => {
- this.rpc
- .sendRpcRequest("chain_getNumberOfShards", [blockNumber], {
- fallbackServers
- })
- .then(result => {
- if (result === null || typeof result === "number") {
- resolve(result);
- } else {
- reject(
- Error(
- `Expected chain_getNumberOfShards to return a number, but it returned ${result}`
- )
- );
- }
- })
- .catch(reject);
- });
- }
-
- /**
- * Gets the platform account in the genesis block
- * @returns The platform addresses in the genesis block.
- */
- public getGenesisAccounts(): Promise {
- const fallbackServers = this.fallbackServers;
- return new Promise((resolve, reject) => {
- this.rpc
- .sendRpcRequest("chain_getGenesisAccounts", [], {
- fallbackServers
- })
- .then(result => {
- try {
- resolve(
- (result as string[]).map(str =>
- PlatformAddress.ensure(str)
- )
- );
- } catch (e) {
- reject(
- Error(
- `Expected chain_getGenesisAccounts to return an array of PlatformAddress, but an error occurred: ${e.toString()}`
- )
- );
- }
- })
- .catch(reject);
- });
- }
-
- /**
- * Gets the root of the shard, at the state of the given blockNumber.
- * @param shardId A shard Id.
- * @param blockNumber A block number.
- * @returns The hash of root of the shard.
- */
- public getShardRoot(
- shardId: number,
- blockNumber?: number
- ): Promise {
- const fallbackServers = this.fallbackServers;
- if (!isShardIdValue(shardId)) {
- throw Error(
- `Expected the first argument of getShardRoot to be a shard ID value but found ${shardId}`
- );
- }
- if (blockNumber !== undefined && !isNonNegativeInterger(blockNumber)) {
- throw Error(
- `Expected the second argument of getShardRoot to be a non-negative integer but found ${blockNumber}`
- );
- }
-
- return new Promise((resolve, reject) => {
- this.rpc
- .sendRpcRequest("chain_getShardRoot", [shardId, blockNumber], {
- fallbackServers
- })
- .then(result => {
- try {
- resolve(result === null ? null : new H256(result));
- } catch (e) {
- reject(
- Error(
- `Expected chain_getShardRoot to return either null or a value of H256, but an error occurred: ${e.toString()}`
- )
- );
- }
- })
- .catch(reject);
- });
- }
-
- /**
- * Gets the mining reward of the given block number.
- * @param blockNumber A block nubmer.
- * @returns The amount of mining reward, or null if the given block number is not mined yet.
- */
- public getMiningReward(blockNumber: number): Promise {
- const fallbackServers = this.fallbackServers;
- if (!isNonNegativeInterger(blockNumber)) {
- throw Error(
- `Expected the argument of getMiningReward to be a non-negative integer but found ${blockNumber}`
- );
- }
-
- return new Promise((resolve, reject) => {
- this.rpc
- .sendRpcRequest("chain_getMiningReward", [blockNumber], {
- fallbackServers
- })
- .then(result => {
- try {
- resolve(result === null ? null : new U64(result));
- } catch (e) {
- reject(
- Error(
- `Expected chain_getMiningReward to return either null or a value of U64, but an error occurred: ${e.toString()}`
- )
- );
- }
- })
- .catch(reject);
- });
- }
-
- /**
- * Executes the transactions.
- * @param tx A transaction to execute.
- * @param sender A platform address of sender.
- * @returns True, if the transaction is executed successfully. False, if the transaction is not executed.
- */
- public executeTransaction(
- tx: Transaction,
- sender: PlatformAddressValue
- ): Promise {
- const fallbackServers = this.fallbackServers;
- if (!(tx instanceof Transaction)) {
- throw Error(
- `Expected the first argument of executeTransaction to be a Transaction but found ${tx}`
- );
- }
- if (!PlatformAddress.check(sender)) {
- throw Error(
- `Expected the second argument of executeTransaction to be a PlatformAddress value but found ${PlatformAddress}`
- );
- }
- return new Promise((resolve, reject) => {
- this.rpc
- .sendRpcRequest(
- "chain_executeTransaction",
- [tx.toJSON(), PlatformAddress.ensure(sender).toString()],
- { fallbackServers }
- )
- .then(resolve)
- .catch(reject);
- });
- }
-
- /**
- * Gets the id of the latest block.
- * @returns A number and the hash of the latest block.
- */
- public getBestBlockId(): Promise<{ hash: H256; number: number }> {
- const fallbackServers = this.fallbackServers;
- return new Promise((resolve, reject) => {
- this.rpc
- .sendRpcRequest("chain_getBestBlockId", [], { fallbackServers })
- .then(result => {
- if (
- result.hasOwnProperty("hash") &&
- result.hasOwnProperty("number")
- ) {
- return resolve(result);
- } else {
- reject(
- Error(
- `Expected chain_getBestBlockId to return a number and an H256 value , but it returned ${result}`
- )
- );
- }
- })
- .catch(reject);
- });
- }
-
- /**
- * Gets the number of transactions within a block that corresponds with the given hash.
- * @param hash The block hash.
- * @returns A number of transactions within a block.
- */
- public getBlockTransactionCountByHash(
- hash: H256Value
- ): Promise {
- const fallbackServers = this.fallbackServers;
- if (!H256.check(hash)) {
- throw Error(
- `Expected the first argument of getBlockTransactionCountByHash to be an H256 value but found ${hash}`
- );
- }
-
- return new Promise((resolve, reject) => {
- this.rpc
- .sendRpcRequest(
- "chain_getBlockTransactionCountByHash",
- [hash],
- { fallbackServers }
- )
- .then(result => {
- if (result == null || typeof result === "number") {
- return resolve(result);
- } else {
- reject(
- Error(
- `Expected chain_getBlockTransactionCountByHash to return either null or a number but it returned ${result}`
- )
- );
- }
- })
- .catch(reject);
- });
- }
-
- /**
- * Gets the count of the pending transactions within the given range from the transaction queues.
- * @param from The lower bound of collected pending transactions. If null, there is no lower bound.
- * @param to The upper bound of collected pending transactions. If null, there is no upper bound.
- * @returns The count of the pending transactions.
- */
- public getPendingTransactionsCount(
- from?: number | null,
- to?: number | null
- ): Promise {
- const fallbackServers = this.fallbackServers;
- if (from != null && !isNonNegativeInterger(from)) {
- throw Error(
- `Expected the first argument of getPendingTransactions to be a non-negative integer but found ${from}`
- );
- }
- if (to != null && !isNonNegativeInterger(to)) {
- throw Error(
- `Expected the second argument of getPendingTransactions to be a non-negative integer but found ${to}`
- );
- }
- return new Promise((resolve, reject) => {
- this.rpc
- .sendRpcRequest(
- "mempool_getPendingTransactionsCount",
- [from, to],
- { fallbackServers }
- )
- .then(result => {
- if (typeof result === "number") {
- resolve(result);
- } else {
- reject(
- Error(
- `Expected mempool_getPendingTransactionsCount to return a number but returned ${result}`
- )
- );
- }
- })
- .catch(reject);
- });
- }
-
- /**
- * Execute the inputs of the AssetTransfer transaction in the CodeChain VM.
- * @param transaction The transaction that its inputs will be executed.
- * @param parameters Parameters of the outputs as an array.
- * @param indices Indices of inputs to run in VM.
- * @returns The results of VM execution.
- */
- public executeVM(
- transaction: SignedTransaction,
- parameters: string[][],
- indices: number[]
- ): Promise {
- const fallbackServers = this.fallbackServers;
- if (!(transaction instanceof SignedTransaction)) {
- throw Error(
- `Expected the first argument of executeVM to be a Transaction but found ${transaction}`
- );
- }
- if (parameters.length !== indices.length) {
- throw Error(`The length of paramters and indices must be equal`);
- }
- const params = parameters.map(parameter =>
- parameter.map(string => {
- if (/^[0-9a-f]+$/g.test(string)) {
- return [...Buffer.from(string, "hex")];
- } else {
- throw Error(
- `Parameters should be array of array of hex string`
- );
- }
- })
- );
- return new Promise((resolve, reject) => {
- this.rpc
- .sendRpcRequest(
- "chain_executeVM",
- [transaction, params, indices],
- { fallbackServers }
- )
- .then(result => {
- if (result.every((str: any) => typeof str === "string")) {
- resolve(result);
- } else {
- throw Error(`Failed to execute VM`);
- }
- })
- .catch(reject);
- });
- }
-
- /**
- * Gets the common parameters.
- * @param blockNumber A block nubmer.
- * @returns The coomon params, or null if the given block number is not mined yet.
- */
- public getCommonParams(blockNumber?: number): Promise {
- const fallbackServers = this.fallbackServers;
- if (blockNumber !== undefined && !isNonNegativeInterger(blockNumber)) {
- throw Error(
- `Expected the argument of getCommonParams to be a non-negative integer but found ${blockNumber}`
- );
- }
-
- return new Promise((resolve, reject) => {
- this.rpc
- .sendRpcRequest("chain_getCommonParams", [blockNumber], {
- fallbackServers
- })
- .then(result => {
- try {
- if (result === null) {
- return resolve(null);
- }
- resolve({
- maxExtraDataSize: new U64(result.maxExtraDataSize),
- maxAssetSchemeMetadataSize: new U64(
- result.maxAssetSchemeMetadataSize
- ),
- maxTransferMetadataSize: new U64(
- result.maxTransferMetadataSize
- ),
- maxTextContentSize: new U64(
- result.maxTextContentSize
- ),
- networkID: result.networkID,
- minPayCost: new U64(result.minPayCost),
- minSetRegularKeyCost: new U64(
- result.minSetRegularKeyCost
- ),
- minCreateShardCost: new U64(
- result.minCreateShardCost
- ),
- minSetShardOwnersCost: new U64(
- result.minSetShardOwnersCost
- ),
- minSetShardUsersCost: new U64(
- result.minSetShardUsersCost
- ),
- minWrapCccCost: new U64(result.minWrapCccCost),
- minCustomCost: new U64(result.minCustomCost),
- minStoreCost: new U64(result.minStoreCost),
- minRemoveCost: new U64(result.minRemoveCost),
- minMintAssetCost: new U64(result.minMintAssetCost),
- minTransferAssetCost: new U64(
- result.minTransferAssetCost
- ),
- minChangeAssetSchemeCost: new U64(
- result.minChangeAssetSchemeCost
- ),
- minIncreaseAssetSupplyCost: new U64(
- result.minIncreaseAssetSupplyCost
- ),
- minComposeAssetCost: new U64(
- result.minComposeAssetCost
- ),
- minDecomposeAssetCost: new U64(
- result.minDecomposeAssetCost
- ),
- minUnwrapCccCost: new U64(result.minUnwrapCccCost),
- maxBodySize: new U64(result.maxBodySize),
- snapshotPeriod: new U64(result.snapshotPeriod),
- termSeconds: new U64(result.termSeconds),
- nominationExpiration: new U64(
- result.nominationExpiration
- ),
- custodyPeriod: new U64(result.custodyPeriod),
- releasePeriod: new U64(result.releasePeriod),
- maxNumOfValidators: new U64(
- result.maxNumOfValidators
- ),
- minNumOfValidators: new U64(
- result.minNumOfValidators
- ),
- delegationThreshold: new U64(
- result.delegationThreshold
- ),
- minDeposit: new U64(result.minDeposit),
- maxCandidateMetadataSize: new U64(
- result.maxCandidateMetadataSize
- )
- });
- } catch (e) {
- reject(
- Error(
- `Expected chain_getCommonParams to return a common params struct, but an error occurred: ${e.toString()}`
- )
- );
- }
- })
- .catch(reject);
- });
- }
-
- /**
- * Get the list of accounts that can generate the blocks at the given block number.
- * @params blockNumber A block number.
- * @returns A list of possible authors, or null if anyone can generate the block
- */
- public getPossibleAuthors(
- blockNumber?: number
- ): Promise {
- const fallbackServers = this.fallbackServers;
- if (blockNumber !== undefined && !isNonNegativeInterger(blockNumber)) {
- throw Error(
- `Expected the argument of getPossibleAuthors to be a non-negative integer but found ${blockNumber}`
- );
- }
- return new Promise((resolve, reject) => {
- this.rpc
- .sendRpcRequest("chain_getPossibleAuthors", [blockNumber], {
- fallbackServers
- })
- .then(result => {
- try {
- if (result === null) {
- return resolve(null);
- }
-
- resolve(
- result.map((address: string) =>
- PlatformAddress.fromString(address)
- )
- );
- } catch (e) {
- reject(
- Error(
- `Expected chain_getPossibleAuthors to return a list of platform addresses, but an error occurred: ${e.toString()}`
- )
- );
- }
- })
- .catch(reject);
- });
- }
-
- /**
- * Get the signer of the given transaction hash.
- * @param hash The tx hash of which to get the signer of the tx.
- * @returns A platform address of the signer, or null if the transaction hash does not exist.
- */
- public getTransactionSigner(
- hash: H256Value
- ): Promise {
- const fallbackServers = this.fallbackServers;
- if (!H256.check(hash)) {
- throw Error(
- `Expected the first argument of getTransactionSigner to be an H256 value but found ${hash}`
- );
- }
- return new Promise((resolve, reject) => {
- this.rpc
- .sendRpcRequest("chain_getTransactionSigner", [hash], {
- fallbackServers
- })
- .then(result => {
- try {
- if (result === null) {
- return resolve(null);
- }
-
- resolve(PlatformAddress.fromString(result));
- } catch (e) {
- reject(
- Error(
- `Expected chain_getTransactionSigner to return a platform addresses, but an error occurred: ${e.toString()}`
- )
- );
- }
- })
- .catch(reject);
- });
- }
-
- /**
- * Gets the sequence of the chain's metadata.
- * @param blockNumber A block number.
- * @returns A sequence number, or null if the given block number is not mined yet.
- */
- public getMetadataSeq(blockNumber?: number): Promise {
- const fallbackServers = this.fallbackServers;
- if (blockNumber !== undefined && !isNonNegativeInterger(blockNumber)) {
- throw Error(
- `Expected the argument of getMetadataSeq to be a non-negative integer but found ${blockNumber}`
- );
- }
- return new Promise((resolve, reject) => {
- this.rpc
- .sendRpcRequest("chain_getMetadataSeq", [blockNumber], {
- fallbackServers
- })
- .then(result => {
- if (result === null || typeof result === "number") {
- return resolve(result);
- } else {
- reject(
- Error(
- `Expected chain_getMetadataSeq to return a sequence number or null, but it returned ${result}`
- )
- );
- }
- })
- .catch(reject);
- });
- }
-}
-
-function isNonNegativeInterger(value: any): boolean {
- return typeof value === "number" && Number.isInteger(value) && value >= 0;
-}
-
-function isShardIdValue(value: any): boolean {
- return (
- typeof value === "number" &&
- Number.isInteger(value) &&
- value >= 0 &&
- value <= 0xffff
- );
-}
diff --git a/test/src/sdk/src/rpc/devel.ts b/test/src/sdk/src/rpc/devel.ts
deleted file mode 100644
index b32bea68e5..0000000000
--- a/test/src/sdk/src/rpc/devel.ts
+++ /dev/null
@@ -1,150 +0,0 @@
-import { H256 } from "codechain-primitives";
-
-import { Rpc } from ".";
-
-export class DevelRpc {
- private rpc: Rpc;
-
- /**
- * @hidden
- */
- constructor(rpc: Rpc) {
- this.rpc = rpc;
- }
-
- /**
- * Gets keys of the state trie with the given offset and limit.
- * @param offset number
- * @param limit number
- * @returns H256[]
- */
- public getStateTrieKeys(offset: number, limit: number): Promise {
- if (
- typeof offset !== "number" ||
- !Number.isInteger(offset) ||
- offset < 0
- ) {
- throw Error(
- `Expected the first argument to be non-negative integer but found ${offset}`
- );
- }
- if (
- typeof limit !== "number" ||
- !Number.isInteger(limit) ||
- limit <= 0
- ) {
- throw Error(
- `Expected the second argument to be posivit integer but found ${limit}`
- );
- }
- return new Promise((resolve, reject) => {
- this.rpc
- .sendRpcRequest("devel_getStateTrieKeys", [offset, limit])
- .then(result => {
- if (!Array.isArray(result)) {
- return reject(
- Error(
- `Expected devel_getStateTrieKeys to return an array but it returned ${result}`
- )
- );
- }
- result.forEach((value, index, arr) => {
- try {
- arr[index] = new H256(value);
- } catch (e) {
- return reject(
- Error(
- `Expected devel_getStateTrieKeys() to return an array of H256, but an error occurred: ${e.toString()}`
- )
- );
- }
- });
- resolve(result);
- })
- .catch(reject);
- });
- }
-
- /**
- * Gets the value of the state trie with the given key.
- * @param key H256
- * @returns string[]
- */
- public getStateTrieValue(key: H256): Promise {
- if (!H256.check(key)) {
- throw Error(
- `Expected the first argument to be an H256 value but found ${key}`
- );
- }
- return new Promise((resolve, reject) => {
- this.rpc
- .sendRpcRequest("devel_getStateTrieValue", [
- `0x${H256.ensure(key).value}`
- ])
- .then(result => {
- if (!Array.isArray(result)) {
- return reject(
- Error(
- `Expected devel_getStateTrieValue to return an array but it returned ${result}`
- )
- );
- }
- result.forEach((value, index) => {
- if (typeof value !== "string") {
- return reject(
- Error(
- `Expected devel_getStateTrieValue to return an array of strings but found ${value} at ${index}`
- )
- );
- }
- });
- resolve(result);
- })
- .catch(reject);
- });
- }
-
- /**
- * Starts and Enable sealing transactions.
- * @returns null
- */
- public startSealing(): Promise {
- return new Promise((resolve, reject) => {
- this.rpc
- .sendRpcRequest("devel_startSealing", [])
- .then(result => {
- if (result === null) {
- return resolve(null);
- }
- reject(
- Error(
- `Expected devel_startSealing to return null but it returned ${result}`
- )
- );
- })
- .catch(reject);
- });
- }
-
- /**
- * Stops and Disable sealing transactions.
- * @returns null
- */
- public stopSealing(): Promise {
- return new Promise((resolve, reject) => {
- this.rpc
- .sendRpcRequest("devel_stopSealing", [])
- .then(result => {
- if (result === null) {
- return resolve(null);
- }
- reject(
- Error(
- `Expected devel_stopSealing to return null but it returned ${result}`
- )
- );
- })
- .catch(reject);
- });
- }
-}
diff --git a/test/src/sdk/src/rpc/engine.ts b/test/src/sdk/src/rpc/engine.ts
deleted file mode 100644
index 72512e9f3a..0000000000
--- a/test/src/sdk/src/rpc/engine.ts
+++ /dev/null
@@ -1,158 +0,0 @@
-import { PlatformAddress, U64 } from "codechain-primitives";
-
-import { Rpc } from ".";
-import { toHex } from "../utils";
-
-const RLP = require("rlp");
-
-export class EngineRpc {
- private rpc: Rpc;
- private fallbackServers?: string[];
- /**
- * @hidden
- */
- constructor(rpc: Rpc, options: { fallbackServers?: string[] }) {
- this.rpc = rpc;
- const { fallbackServers } = options;
- this.fallbackServers = fallbackServers;
- }
-
- /**
- * Gets coinbase's account id.
- * @returns PlatformAddress or null
- */
- public getCoinbase(): Promise {
- const fallbackServers = this.fallbackServers;
- return new Promise((resolve, reject) => {
- this.rpc
- .sendRpcRequest("engine_getCoinbase", [], { fallbackServers })
- .then(result => {
- try {
- resolve(
- result === null
- ? null
- : PlatformAddress.fromString(result)
- );
- } catch (e) {
- reject(
- Error(
- `Expected engine_getCoinbase to return a PlatformAddress string or null, but an error occurred: ${e.toString()}`
- )
- );
- }
- })
- .catch(reject);
- });
- }
-
- /**
- * Gets coinbase's account id.
- * @returns PlatformAddress or null
- */
- public getBlockReward(): Promise {
- const fallbackServers = this.fallbackServers;
- return new Promise((resolve, reject) => {
- this.rpc
- .sendRpcRequest("engine_getBlockReward", [], {
- fallbackServers
- })
- .then(result => {
- try {
- resolve(U64.ensure(result));
- } catch (e) {
- reject(
- Error(
- `Expected engine_getBlockReward to return a U64, but an error occurred: ${e.toString()}`
- )
- );
- }
- })
- .catch(reject);
- });
- }
-
- /**
- * Gets coinbase's account id.
- * @returns PlatformAddress or null
- */
- public getRecommendedConfirmation(): Promise {
- const fallbackServers = this.fallbackServers;
- return new Promise((resolve, reject) => {
- this.rpc
- .sendRpcRequest("engine_getRecommendedConfirmation", [], {
- fallbackServers
- })
- .then(result => {
- if (typeof result === "number") {
- return resolve(result);
- }
- reject(
- Error(
- `Expected engine_getRecommendedConfirmation to return a number but it returned ${result}`
- )
- );
- })
- .catch(reject);
- });
- }
-
- /**
- * Gets custom type's data at blockNumber with keyFragments.
- * @param handlerId number
- * @param keyFragments any[]
- * @param blockNumber? number
- * @returns string or null returns
- */
- public getCustomActionData(
- handlerId: number,
- keyFragments: any[],
- blockNumber?: number
- ): Promise {
- if (
- typeof handlerId !== "number" ||
- !Number.isInteger(handlerId) ||
- handlerId < 0
- ) {
- throw Error(
- `Expected the first argument to be non-negative integer but found ${handlerId}`
- );
- }
- if (
- typeof blockNumber !== "undefined" &&
- (typeof blockNumber !== "number" ||
- !Number.isInteger(blockNumber) ||
- blockNumber < 0)
- ) {
- throw Error(
- `Expected the third argument to be non-negative integer but found ${blockNumber}`
- );
- }
-
- return new Promise((resolve, reject) => {
- const fallbackServers = this.fallbackServers;
- const rlpKeyFragments = toHex(RLP.encode(keyFragments));
- this.rpc
- .sendRpcRequest(
- "engine_getCustomActionData",
- [handlerId, `0x${rlpKeyFragments}`, blockNumber],
- { fallbackServers }
- )
- .then(result => {
- if (result == null) {
- return resolve(null);
- } else if (
- typeof result === "string" &&
- /^([A-Fa-f0-9]|\s)*$/.test(result)
- ) {
- return resolve(result);
- }
- reject(
- Error(
- `Expected engine_getCustomActionData to return a hex string or null but it returned ${result}`
- )
- );
- })
- .catch(reject);
- });
- }
-}
diff --git a/test/src/sdk/src/rpc/index.ts b/test/src/sdk/src/rpc/index.ts
deleted file mode 100644
index 67df370bbc..0000000000
--- a/test/src/sdk/src/rpc/index.ts
+++ /dev/null
@@ -1,123 +0,0 @@
-import fetch from "node-fetch";
-
-import { AccountRpc } from "./account";
-import { ChainRpc } from "./chain";
-import { DevelRpc } from "./devel";
-import { EngineRpc } from "./engine";
-import { NetworkRpc } from "./network";
-import { NodeRpc } from "./node";
-
-/**
- * @hidden
- */
-const jaysonBrowserClient = require("jayson/lib/client/browser");
-
-export class Rpc {
- /**
- * RPC module for retrieving the node info.
- */
- public node: NodeRpc;
- /**
- * RPC module for accessing the blockchain.
- */
- public chain: ChainRpc;
- /**
- * RPC module for configuring P2P networking of the node.
- */
- public network: NetworkRpc;
- /**
- * RPC module for account management and signing
- */
- public account: AccountRpc;
-
- /**
- * RPC module for retrieving the engine info.
- */
- public engine: EngineRpc;
- /**
- * RPC module for developer functions
- */
- public devel: DevelRpc;
- private client: any;
- private server: string;
-
- /**
- * @param params.server HTTP RPC server address.
- * @param params.options.transactionSigner The default account to sign the tx
- */
- constructor(params: {
- server: string;
- options?: {
- transactionSigner?: string;
- fallbackServers?: string[];
- };
- }) {
- const { server, options = {} } = params;
- this.server = server;
- this.client = (rpcServer: string) => {
- return jaysonBrowserClient((request: any, callback: any) => {
- fetch(rpcServer, {
- method: "POST",
- body: request,
- headers: {
- "Content-Type": "application/json"
- }
- })
- .then(res => {
- return res.text();
- })
- .then(text => {
- return callback(null, text);
- })
- .catch(err => {
- return callback(err);
- });
- });
- };
-
- this.node = new NodeRpc(this);
- this.chain = new ChainRpc(this, options);
- this.network = new NetworkRpc(this);
- this.account = new AccountRpc(this);
- this.engine = new EngineRpc(this, options);
- this.devel = new DevelRpc(this);
- }
-
- public sendRpcRequest = async (
- name: string,
- params: any[],
- options?: { id?: string; fallbackServers?: string[] }
- ) => {
- const { fallbackServers } = options || { fallbackServers: [] };
- const allServers: string[] =
- fallbackServers === undefined
- ? [this.server]
- : [this.server, ...fallbackServers];
- const errors: any[] = [];
- for (const server of allServers) {
- const { id } = options || { id: undefined };
- try {
- return new Promise((resolve, reject) => {
- this.client(server).request(
- name,
- params,
- id,
- (err: any, res: any) => {
- if (err || res.error) {
- reject(err || res.error);
- } else {
- resolve(res.result);
- }
- }
- );
- });
- } catch (err) {
- errors.push({ [server]: err });
- }
- }
- if (errors.length === 1) {
- return Promise.reject(errors[0][this.server]);
- }
- return Promise.reject(errors);
- };
-}
diff --git a/test/src/sdk/src/rpc/network.ts b/test/src/sdk/src/rpc/network.ts
deleted file mode 100644
index d67a33b9f2..0000000000
--- a/test/src/sdk/src/rpc/network.ts
+++ /dev/null
@@ -1,473 +0,0 @@
-import { Rpc } from ".";
-
-export class NetworkRpc {
- private rpc: Rpc;
-
- /**
- * @hidden
- */
- constructor(rpc: Rpc) {
- this.rpc = rpc;
- }
-
- /**
- * Connect to node
- * @param address Node address which to connect
- * @param port
- */
- public connect(address: string, port: number): Promise {
- if (!isIpAddressString(address)) {
- throw Error(
- `Expected the first argument of connect to be an IP address string but found ${address}`
- );
- }
- if (!isPortNumber(port)) {
- throw Error(
- `Expected the second argument of connect to be a port number but found ${port}`
- );
- }
- return new Promise((resolve, reject) => {
- this.rpc
- .sendRpcRequest("net_connect", [address, port])
- .then(result => {
- if (result === null) {
- return resolve(null);
- }
- reject(
- Error(
- `Expected net_connect to return null but it returned ${result}`
- )
- );
- })
- .catch(reject);
- });
- }
-
- /**
- * Disconnect from the node
- * @param address Node address which to disconnect
- * @param port
- */
- public disconnect(address: string, port: number): Promise {
- if (!isIpAddressString(address)) {
- throw Error(
- `Expected the first argument of disconnect to be an IP address string but found ${address}`
- );
- }
- if (!isPortNumber(port)) {
- throw Error(
- `Expected the second argument of disconnect to be a port number but found ${port}`
- );
- }
- return new Promise((resolve, reject) => {
- this.rpc
- .sendRpcRequest("net_disconnect", [address, port])
- .then(result => {
- if (result === null) {
- return resolve(null);
- }
- reject(
- Error(
- `Expected net_disconnect to return null but it returned ${result}`
- )
- );
- })
- .catch(reject);
- });
- }
-
- /**
- * Check the node is connected
- * @param address Node address
- * @param port
- */
- public isConnected(address: string, port: number): Promise {
- if (!isIpAddressString(address)) {
- throw Error(
- `Expected the first argument of isConnected to be an IP address string but found ${address}`
- );
- }
- if (!isPortNumber(port)) {
- throw Error(
- `Expected the second argument of isConnected to be a port number but found ${port}`
- );
- }
- return new Promise((resolve, reject) => {
- this.rpc
- .sendRpcRequest("net_isConnected", [address, port])
- .then(result => {
- if (typeof result === "boolean") {
- return resolve(result);
- }
- reject(
- Error(
- `Expected net_isConnected to return a boolean but it returned ${result}`
- )
- );
- })
- .catch(reject);
- });
- }
-
- /**
- * Get the port
- */
- public getPort(): Promise {
- return new Promise((resolve, reject) => {
- this.rpc
- .sendRpcRequest("net_getPort", [])
- .then(result => {
- if (isPortNumber(result)) {
- return resolve(result);
- }
- reject(
- Error(
- `Expected net_getPort to return a port number but it returned ${result}`
- )
- );
- })
- .catch(reject);
- });
- }
-
- /**
- * Get the number of established peers
- */
- public getPeerCount(): Promise {
- return new Promise((resolve, reject) => {
- this.rpc
- .sendRpcRequest("net_getPeerCount", [])
- .then(result => {
- if (typeof result === "number") {
- return resolve(result);
- }
- reject(
- Error(
- `Expected net_getPeerCount to return a number but it returned ${result}`
- )
- );
- })
- .catch(reject);
- });
- }
-
- /**
- * Get the addresses of established peers
- */
- public getPeers(): Promise {
- return new Promise((resolve, reject) => {
- this.rpc
- .sendRpcRequest("net_getEstablishedPeers", [])
- .then(result => {
- if (!Array.isArray(result)) {
- return reject(
- Error(
- `Expected net_getEstablishedPeers to return an array but it returned ${result}`
- )
- );
- }
- result.forEach((address, index) => {
- if (!isSocketAddressString(address)) {
- return reject(
- Error(
- `Expected net_getEstablishedPeers to return an array of IPv4 address but found ${address} at ${index}`
- )
- );
- }
- });
- resolve(result);
- })
- .catch(reject);
- });
- }
-
- /**
- * Add the IP to whitelist
- * @param ip Node IP
- */
- public addToWhitelist(ipCidr: string, tag?: string): Promise {
- if (!isIpCidrAddressString(ipCidr)) {
- throw Error(
- `Expected the first argument of addToWhitelist to be an IP Cidr block address string but found ${ipCidr}`
- );
- }
- if (tag !== undefined && typeof tag !== "string") {
- throw Error(
- `Expected the second arguments of addToWhitelist to be a string but found ${tag}`
- );
- }
- return new Promise((resolve, reject) => {
- this.rpc
- .sendRpcRequest("net_addToWhitelist", [ipCidr, tag || null])
- .then(result => {
- if (result === null) {
- return resolve(null);
- }
- reject(
- Error(
- `Expected net_addToWhitelist to return null but it returned ${result}`
- )
- );
- })
- .catch(reject);
- });
- }
-
- /**
- * Remove the IP from whitelist
- * @param ip Node IP
- */
- public removeFromWhitelist(ipCidr: string): Promise {
- if (!isIpCidrAddressString(ipCidr)) {
- throw Error(
- `Expected the first argument of removeFromWhitelist to be an IP Cidr block address string but found ${ipCidr}`
- );
- }
- return new Promise((resolve, reject) => {
- this.rpc
- .sendRpcRequest("net_removeFromWhitelist", [ipCidr])
- .then(result => {
- if (result === null) {
- return resolve(null);
- }
- reject(
- Error(
- `Expected net_removeFromWhitelist to return null but it returned ${result}`
- )
- );
- })
- .catch(reject);
- });
- }
-
- /**
- * Add the IP to blacklist
- * @param ip Node IP
- */
- public addToBlacklist(ipCidr: string, tag?: string): Promise {
- if (!isIpCidrAddressString(ipCidr)) {
- throw Error(
- `Expected the first argument of addToBlacklist to be an IP Cidr block address string but found ${ipCidr}`
- );
- }
- if (tag !== undefined && typeof tag !== "string") {
- throw Error(
- `Expected the second arguments of addToWhitelist to be a string but found ${tag}`
- );
- }
- return new Promise((resolve, reject) => {
- this.rpc
- .sendRpcRequest("net_addToBlacklist", [ipCidr, tag || null])
- .then(result => {
- if (result === null) {
- return resolve(null);
- }
- reject(
- Error(
- `Expected net_addToBlacklist to return null but it returned ${result}`
- )
- );
- });
- });
- }
-
- /**
- * Remove the IP from blacklist
- * @param ip Node IP
- */
- public removeFromBlacklist(ipCidr: string): Promise {
- if (!isIpCidrAddressString(ipCidr)) {
- throw Error(
- `Expected the first argument of removeFromBlacklist to be an IP Cidr block address string but found ${ipCidr}`
- );
- }
- return new Promise((resolve, reject) => {
- this.rpc
- .sendRpcRequest("net_removeFromBlacklist", [ipCidr])
- .then(result => {
- if (result === null) {
- return resolve(null);
- }
- reject(
- Error(
- `Expected net_removeFromBlacklist to return null but it returned ${result}`
- )
- );
- })
- .catch(reject);
- });
- }
-
- /**
- * Enable whitelist
- */
- public enableWhitelist(): Promise {
- return new Promise((resolve, reject) => {
- this.rpc
- .sendRpcRequest("net_enableWhitelist", [])
- .then(result => {
- if (result === null) {
- return resolve(null);
- }
- reject(
- Error(
- `Expected net_enableWhitelist to return null but it returned ${result}`
- )
- );
- })
- .catch(reject);
- });
- }
-
- /**
- * Disable whitelist
- */
- public disableWhitelist(): Promise {
- return new Promise((resolve, reject) => {
- this.rpc
- .sendRpcRequest("net_disableWhitelist", [])
- .then(result => {
- if (result === null) {
- return resolve(null);
- }
- reject(
- Error(
- `Expected net_disableWhitelist to return null but it returned ${result}`
- )
- );
- })
- .catch(reject);
- });
- }
-
- /**
- * Enable blacklist
- */
- public enableBlacklist(): Promise {
- return new Promise((resolve, reject) => {
- this.rpc
- .sendRpcRequest("net_enableBlacklist", [])
- .then(result => {
- if (result === null) {
- return resolve(null);
- }
- reject(
- Error(
- `Expected net_enableBlacklist to return null but it returned ${result}`
- )
- );
- })
- .catch(reject);
- });
- }
-
- /**
- * Disable blacklist
- */
- public disableBlacklist(): Promise {
- return new Promise((resolve, reject) => {
- this.rpc
- .sendRpcRequest("net_disableBlacklist", [])
- .then(result => {
- if (result === null) {
- return resolve(null);
- }
- reject(
- Error(
- `Expected net_disableBlacklist to return null but it returned ${result}`
- )
- );
- })
- .catch(reject);
- });
- }
-
- /**
- * Get the status of whitelist
- */
- public getWhitelist(): Promise<{ list: string[]; enabled: boolean }> {
- return new Promise((resolve, reject) => {
- this.rpc
- .sendRpcRequest("net_getWhitelist", [])
- .then(result => {
- if (result === null || typeof result !== "object") {
- return reject(
- Error(
- `Expected net_getWhitelist to return an object but it returned ${result}`
- )
- );
- }
- const { list, enabled } = result;
- if (Array.isArray(list) && typeof enabled === "boolean") {
- // FIXME: Check whether the strings in the list are valid.
- return resolve(result);
- }
- reject(
- Error(
- `Expected net_getWhitelist to return { list: string[], enabled: boolean } but it returned ${JSON.stringify(
- result
- )}`
- )
- );
- })
- .catch(reject);
- });
- }
-
- /**
- * Get the status of blacklist
- */
- public getBlacklist(): Promise<{ list: string[]; enabled: boolean }> {
- return new Promise((resolve, reject) => {
- this.rpc
- .sendRpcRequest("net_getBlacklist", [])
- .then(result => {
- if (result === null || typeof result !== "object") {
- return reject(
- Error(
- `Expected net_getBlacklist to return an object but it returned ${result}`
- )
- );
- }
- const { list, enabled } = result;
- if (Array.isArray(list) && typeof enabled === "boolean") {
- // FIXME: Check whether the strings in the list are valid.
- return resolve(result);
- }
- reject(
- Error(
- `Expected net_getBlacklist to return { list: string[], enabled: boolean } but it returned ${JSON.stringify(
- result
- )}`
- )
- );
- })
- .catch(reject);
- });
- }
-}
-
-function isIpAddressString(value: any): boolean {
- return /\b((25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)(\.|$)){4}\b/.test(value);
-}
-
-function isIpCidrAddressString(value: any): boolean {
- return /^((25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)(\/([0-9]|[1-2][0-9]|3[0-2]))?$/.test(
- value
- );
-}
-
-function isSocketAddressString(value: any): boolean {
- return /((25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)(\.|:)){4}([0-9]{1,4}|[1-5][0-9]{4}|6[0-4][0-9]{3}|65[0-4][0-9]{2}|655[0-2][0-9]|6553[0-5])/.test(
- value
- );
-}
-
-function isPortNumber(value: any): boolean {
- return (
- typeof value === "number" &&
- Number.isInteger(value) &&
- 0 <= value &&
- value < 0xffff
- );
-}
diff --git a/test/src/sdk/src/rpc/node.ts b/test/src/sdk/src/rpc/node.ts
deleted file mode 100644
index 840ead4ad0..0000000000
--- a/test/src/sdk/src/rpc/node.ts
+++ /dev/null
@@ -1,78 +0,0 @@
-import { Rpc } from ".";
-
-export class NodeRpc {
- private rpc: Rpc;
-
- /**
- * @hidden
- */
- constructor(rpc: Rpc) {
- this.rpc = rpc;
- }
-
- /**
- * Sends ping to check whether CodeChain's RPC server is responding or not.
- * @returns String "pong"
- */
- public ping(id?: string): Promise {
- return new Promise((resolve, reject) => {
- this.rpc
- .sendRpcRequest("ping", [], { id })
- .then(result => {
- if (typeof result === "string") {
- return resolve(result);
- }
- return reject(
- Error(
- `Expected ping() to return a string but it returned ${result}`
- )
- );
- })
- .catch(reject);
- });
- }
-
- /**
- * Gets the version of CodeChain node.
- * @returns The version of CodeChain node (e.g. 0.1.0)
- */
- public getNodeVersion(): Promise {
- return new Promise((resolve, reject) => {
- this.rpc
- .sendRpcRequest("version", [])
- .then(result => {
- if (typeof result === "string") {
- return resolve(result);
- }
- return reject(
- Error(
- `Expected getNodeVersion() to return a string but it returned ${result}`
- )
- );
- })
- .catch(reject);
- });
- }
-
- /**
- * Gets the commit hash of the repository upon which the CodeChain executable was built.
- * @hidden
- */
- public getCommitHash(): Promise {
- return new Promise((resolve, reject) => {
- this.rpc
- .sendRpcRequest("commitHash", [])
- .then(result => {
- if (typeof result === "string") {
- return resolve(result);
- }
- return reject(
- Error(
- `Expected getCommitHash() to return a string but it returned ${result}`
- )
- );
- })
- .catch(reject);
- });
- }
-}
diff --git a/test/src/stakeholder/src/actionData.ts b/test/src/stakeholder/src/actionData.ts
index 647158e893..bb67064c1f 100644
--- a/test/src/stakeholder/src/actionData.ts
+++ b/test/src/stakeholder/src/actionData.ts
@@ -2,9 +2,11 @@
// In the import statement below uses "codechain-primitives" which is installed by the SDK.
// We should use the SDK's PlatformAddressValue when the SDK is updated.
import { PlatformAddressValue } from "codechain-primitives";
+import RPC from "foundry-rpc";
import { SDK } from "../../sdk/src";
import { H512, PlatformAddress, U64 } from "../../sdk/src/core/classes";
+import { toHex } from "codechain-primitives/lib";
import { HANDLER_ID } from "./index";
import {
decodeH512,
@@ -16,20 +18,22 @@ import {
const RLP = require("rlp");
export async function getUndelegatedCCS(
- sdk: SDK,
+ rpc: RPC,
address: PlatformAddressValue,
blockNumber?: number
): Promise {
- const data = await sdk.rpc.engine.getCustomActionData(
- HANDLER_ID,
- [
- "Account",
- PlatformAddress.ensure(address)
- .getAccountId()
- .toEncodeObject()
- ],
+ const data = await rpc.engine.getCustomActionData({
+ handlerId: HANDLER_ID,
+ bytes: `0x${toHex(
+ RLP.encode([
+ "Account",
+ PlatformAddress.ensure(address)
+ .getAccountId()
+ .toEncodeObject()
+ ])
+ )}`,
blockNumber
- );
+ });
if (data == null) {
return new U64(0);
}
@@ -37,14 +41,15 @@ export async function getUndelegatedCCS(
}
export async function getCCSHolders(
+ rpc: RPC,
sdk: SDK,
blockNumber?: number
): Promise {
- const data = await sdk.rpc.engine.getCustomActionData(
- HANDLER_ID,
- ["StakeholderAddresses"],
+ const data = await rpc.engine.getCustomActionData({
+ handlerId: HANDLER_ID,
+ bytes: `0x${toHex(RLP.encode(["StakeholderAddresses"]))}`,
blockNumber
- );
+ });
if (data == null) {
throw Error("Expected non-null value, but got a null");
}
@@ -62,15 +67,18 @@ export interface Delegation {
quantity: U64;
}
export async function getDelegations(
+ rpc: RPC,
sdk: SDK,
delegator: PlatformAddress,
blockNumber?: number
): Promise {
- const data = await sdk.rpc.engine.getCustomActionData(
- HANDLER_ID,
- ["Delegation", delegator.accountId.toEncodeObject()],
+ const data = await rpc.engine.getCustomActionData({
+ handlerId: HANDLER_ID,
+ bytes: `0x${toHex(
+ RLP.encode(["Delegation", delegator.accountId.toEncodeObject()])
+ )}`,
blockNumber
- );
+ });
if (data == null) {
return [];
}
@@ -99,14 +107,14 @@ export interface Candidate {
}
export async function getCandidates(
- sdk: SDK,
+ rpc: RPC,
blockNumber?: number
): Promise {
- const data = await sdk.rpc.engine.getCustomActionData(
- HANDLER_ID,
- ["Candidates"],
+ const data = await rpc.engine.getCustomActionData({
+ handlerId: HANDLER_ID,
+ bytes: `0x${toHex(RLP.encode(["Candidates"]))}`,
blockNumber
- );
+ });
if (data == null) {
return [];
}
@@ -135,14 +143,15 @@ export interface Prisoner {
}
export async function getJailed(
+ rpc: RPC,
sdk: SDK,
blockNumber?: number
): Promise {
- const data = await sdk.rpc.engine.getCustomActionData(
- HANDLER_ID,
- ["Jail"],
+ const data = await rpc.engine.getCustomActionData({
+ handlerId: HANDLER_ID,
+ bytes: `0x${toHex(RLP.encode(["Jail"]))}`,
blockNumber
- );
+ });
if (data == null) {
return [];
}
@@ -163,14 +172,15 @@ export async function getJailed(
}
export async function getBanned(
+ rpc: RPC,
sdk: SDK,
blockNumber?: number
): Promise {
- const data = await sdk.rpc.engine.getCustomActionData(
- HANDLER_ID,
- ["Banned"],
+ const data = await rpc.engine.getCustomActionData({
+ handlerId: HANDLER_ID,
+ bytes: `0x${toHex(RLP.encode(["Banned"]))}`,
blockNumber
- );
+ });
if (data == null) {
return [];
}
@@ -194,14 +204,15 @@ export interface IntermediateReward {
}
export async function getIntermediateRewards(
+ rpc: RPC,
sdk: SDK,
blockNumber?: number
): Promise {
- const data = await sdk.rpc.engine.getCustomActionData(
- HANDLER_ID,
- ["IntermediateRewards"],
+ const data = await rpc.engine.getCustomActionData({
+ handlerId: HANDLER_ID,
+ bytes: `0x${toHex(RLP.encode(["IntermediateRewards"]))}`,
blockNumber
- );
+ });
if (data == null) {
return {
previous: [],
@@ -243,14 +254,15 @@ export interface Validator {
}
export async function getValidators(
+ rpc: RPC,
sdk: SDK,
blockNumber?: number
): Promise {
- const data = await sdk.rpc.engine.getCustomActionData(
- HANDLER_ID,
- ["Validators"],
+ const data = await rpc.engine.getCustomActionData({
+ handlerId: HANDLER_ID,
+ bytes: `0x${toHex(RLP.encode(["Validators"]))}`,
blockNumber
- );
+ });
if (data == null) {
return [];
}
diff --git a/test/src/stakeholder/src/rpc.ts b/test/src/stakeholder/src/rpc.ts
index 9896526cf3..48ed614e02 100644
--- a/test/src/stakeholder/src/rpc.ts
+++ b/test/src/stakeholder/src/rpc.ts
@@ -1,3 +1,4 @@
+import RPC from "foundry-rpc";
import { SDK } from "../../sdk/src";
import { PlatformAddress } from "../../sdk/src/core/classes";
@@ -7,12 +8,10 @@ export interface TermMetadata {
}
export async function getTermMetadata(
- sdk: SDK,
+ rpc: RPC,
blockNumber?: number
): Promise {
- const result = await sdk.rpc.sendRpcRequest("chain_getTermMetadata", [
- blockNumber
- ]);
+ const result = await rpc.chain.getTermMetadata({ blockNumber });
if (result === null) {
return null;
}
@@ -31,12 +30,10 @@ export async function getTermMetadata(
}
export async function getPossibleAuthors(
- sdk: SDK,
+ rpc: RPC,
blockNumber?: number
): Promise {
- const result = await sdk.rpc.sendRpcRequest("chain_getPossibleAuthors", [
- blockNumber
- ]);
+ const result = await rpc.chain.getPossibleAuthors({ blockNumber });
if (result === null) {
return null;
}
diff --git a/test/src/stakeholder/src/util.ts b/test/src/stakeholder/src/util.ts
index c01a1a0d02..0512b3e12a 100644
--- a/test/src/stakeholder/src/util.ts
+++ b/test/src/stakeholder/src/util.ts
@@ -1,10 +1,5 @@
import { SDK } from "../../sdk/src";
-import {
- H256,
- H512,
- PlatformAddress,
- U64
-} from "../../sdk/src/core/classes";
+import { H256, H512, PlatformAddress, U64 } from "../../sdk/src/core/classes";
export function isArrayOf(
list: any,
diff --git a/test/src/tendermint.test/local.ts b/test/src/tendermint.test/local.ts
index e8bd6e2ed3..0b6ba127b1 100644
--- a/test/src/tendermint.test/local.ts
+++ b/test/src/tendermint.test/local.ts
@@ -69,9 +69,9 @@ import CodeChain from "../helper/spawn";
const transactions = [];
const numTransactions = parseInt(process.env.TEST_NUM_TXS || "10000", 10);
- const baseSeq = await nodes[0].testFramework.rpc.chain.getSeq(
- faucetAddress
- );
+ const baseSeq = (await nodes[0].rpc.chain.getSeq({
+ address: faucetAddress.toString()
+ }))!;
for (let i = 0; i < numTransactions; i++) {
const value = makeRandomH256();
@@ -96,23 +96,23 @@ import CodeChain from "../helper/spawn";
}
for (let i = numTransactions - 1; i > 0; i--) {
- await nodes[0].testFramework.rpc.chain.sendSignedTransaction(
- transactions[i]
- );
+ await nodes[0].rpc.mempool.sendSignedTransaction({
+ tx: transactions[i].rlpBytes().toString("hex")
+ });
}
const startTime = new Date();
console.log(`Start at: ${startTime}`);
- await nodes[0].testFramework.rpc.chain.sendSignedTransaction(
- transactions[0]
- );
+ await nodes[0].rpc.mempool.sendSignedTransaction({
+ tx: transactions[0].rlpBytes().toString("hex")
+ });
while (true) {
let flag = true;
for (let i = 0; i < 4; i++) {
const hash = transactions[numTransactions - 1].hash();
- const result = await nodes[
- i
- ].testFramework.rpc.chain.containsTransaction(hash);
+ const result = await nodes[i].rpc.chain.containsTransaction({
+ transactionHash: `0x${hash.toString()}`
+ });
console.log(`Node ${i} result: ${result}`);
if (!result) {
diff --git a/test/src/tendermint.test/remote.ts b/test/src/tendermint.test/remote.ts
index e2eba13403..7d21b8fa27 100644
--- a/test/src/tendermint.test/remote.ts
+++ b/test/src/tendermint.test/remote.ts
@@ -29,7 +29,9 @@ import CodeChain from "../helper/spawn";
});
const transactions = [];
- const baseSeq = await node.testFramework.rpc.chain.getSeq(faucetAddress);
+ const baseSeq = (await node.rpc.chain.getSeq({
+ address: faucetAddress.toString()
+ }))!;
for (let i = 0; i < numTransactions; i++) {
const value = makeRandomH256();
@@ -54,19 +56,21 @@ import CodeChain from "../helper/spawn";
}
for (let i = numTransactions - 1; i > 0; i--) {
- await node.testFramework.rpc.chain.sendSignedTransaction(
- transactions[i]
- );
+ await node.rpc.mempool.sendSignedTransaction({
+ tx: transactions[i].rlpBytes().toString("hex")
+ });
}
const startTime = new Date();
console.log(`Start at: ${startTime}`);
- await node.testFramework.rpc.chain.sendSignedTransaction(transactions[0]);
+ await node.rpc.mempool.sendSignedTransaction({
+ tx: transactions[0].rlpBytes().toString("hex")
+ });
while (true) {
const hash = transactions[numTransactions - 1].hash();
- const result = await node.testFramework.rpc.chain.containsTransaction(
- hash
- );
+ const result = await node.rpc.chain.containsTransaction({
+ transactionHash: hash.toString()
+ });
console.log(`Node result: ${result}`);
if (result) {
break;
diff --git a/test/tsconfig.json b/test/tsconfig.json
index 3d1e16f6c2..137e1f9612 100644
--- a/test/tsconfig.json
+++ b/test/tsconfig.json
@@ -9,5 +9,5 @@
"strict": true
},
"include": ["./src/**/*"],
- "exclude": ["./src/**/*.test.ts", "./src/sdk/*" , "./src/stakeholder/*"]
+ "exclude": ["./src/**/*.test.ts"]
}