Skip to content

Commit

Permalink
[Chore | Refactor] Create & use withChainApi (#29)
Browse files Browse the repository at this point in the history
* Create `withChainApi` example

* Refactor most examples

* Refactor `ethBridge` examples
  • Loading branch information
aidan-starke authored Jul 25, 2023
1 parent 942b635 commit fff0534
Show file tree
Hide file tree
Showing 34 changed files with 172 additions and 499 deletions.
19 changes: 3 additions & 16 deletions examples/substrate/use-assets/src/transferAsset.ts
Original file line number Diff line number Diff line change
@@ -1,25 +1,16 @@
import { createKeyring } from "@trne/utils/createKeyring";
import { filterExtrinsicEvents } from "@trne/utils/filterExtrinsicEvents";
import { getChainApi } from "@trne/utils/getChainApi";
import { sendExtrinsic } from "@trne/utils/sendExtrinsic";
import { cleanEnv, str } from "envalid";
import { withChainApi } from "@trne/utils/withChainApi";
import { utils as ethers } from "ethers";

const env = cleanEnv(process.env, {
CALLER_PRIVATE_KEY: str(), // private key of extrinsic caller
});

// Find token details at
// https://explorer.rootnet.cloud/tokens
const ASTO = {
id: 17508,
decimals: 18,
};

export async function main() {
const api = await getChainApi("porcini");
const caller = createKeyring(env.CALLER_PRIVATE_KEY);

withChainApi("porcini", async (api, caller) => {
const assetId = ASTO.id;
const target = "0x25451A4de12dcCc2D166922fA938E900fCc4ED24";
const amount = ethers.parseUnits("100", ASTO.decimals).toString();
Expand All @@ -30,8 +21,4 @@ export async function main() {
const [event] = filterExtrinsicEvents(result.events, ["Assets.Transferred"]);

console.log("Extrinsic Result", event.toJSON());

await api.disconnect();
}

main();
});
19 changes: 3 additions & 16 deletions examples/substrate/use-batch/src/batchExtrinsics.ts
Original file line number Diff line number Diff line change
@@ -1,26 +1,13 @@
import { createKeyring } from "@trne/utils/createKeyring";
import { filterExtrinsicEvents } from "@trne/utils/filterExtrinsicEvents";
import { getChainApi } from "@trne/utils/getChainApi";
import { sendExtrinsic } from "@trne/utils/sendExtrinsic";
import { cleanEnv, str } from "envalid";

const env = cleanEnv(process.env, {
CALLER_PRIVATE_KEY: str(), // private key of extrinsic caller
});

export async function main() {
const api = await getChainApi("porcini");
const caller = createKeyring(env.CALLER_PRIVATE_KEY);
import { withChainApi } from "@trne/utils/withChainApi";

withChainApi("porcini", async (api, caller) => {
const calls = new Array(10).fill(1).map((n, i) => api.tx.system.remark(`Call ${n + i}`));
const extrinsic = api.tx.utility.batch(calls);

const { result } = await sendExtrinsic(extrinsic, caller, { log: console });
const [event] = filterExtrinsicEvents(result.events, ["Utility.BatchCompleted"]);

console.log("Extrinsic Result", event.toJSON());

await api.disconnect();
}

main();
});
19 changes: 3 additions & 16 deletions examples/substrate/use-batch/src/decodeBatchError.ts
Original file line number Diff line number Diff line change
@@ -1,18 +1,9 @@
import { BN, hexToU8a } from "@polkadot/util";
import { createKeyring } from "@trne/utils/createKeyring";
import { filterExtrinsicEvents } from "@trne/utils/filterExtrinsicEvents";
import { getChainApi } from "@trne/utils/getChainApi";
import { sendExtrinsic } from "@trne/utils/sendExtrinsic";
import { cleanEnv, str } from "envalid";

const env = cleanEnv(process.env, {
CALLER_PRIVATE_KEY: str(), // private key of extrinsic caller
});

export async function main() {
const api = await getChainApi("porcini");
const caller = createKeyring(env.CALLER_PRIVATE_KEY);
import { withChainApi } from "@trne/utils/withChainApi";

withChainApi("porcini", async (api, caller) => {
const calls = new Array(10).fill(1).map((n, i) => {
// Force error as Asset ID 3 does not exist
if (i === 6) return api.tx.assets.transfer(3, caller.address, 1);
Expand Down Expand Up @@ -46,8 +37,4 @@ export async function main() {
error: hexToU8a(err.module.error),
});
console.log(`Batch interrupted at index ${index}, [${section}.${name}] ${docs}`);

await api.disconnect();
}

main();
});
19 changes: 3 additions & 16 deletions examples/substrate/use-dex/src/addLiquidity.ts
Original file line number Diff line number Diff line change
@@ -1,21 +1,12 @@
/* eslint-disable @typescript-eslint/no-explicit-any */
import { createKeyring } from "@trne/utils/createKeyring";
import { filterExtrinsicEvents } from "@trne/utils/filterExtrinsicEvents";
import { getChainApi } from "@trne/utils/getChainApi";
import { sendExtrinsic } from "@trne/utils/sendExtrinsic";
import { cleanEnv, str } from "envalid";

const env = cleanEnv(process.env, {
CALLER_PRIVATE_KEY: str(), // private key of extrinsic caller
});
import { withChainApi } from "@trne/utils/withChainApi";

const XrpAssetId = 2;
const RootAssetId = 1;

export async function main() {
const api = await getChainApi("porcini");
const caller = createKeyring(env.CALLER_PRIVATE_KEY);

withChainApi("porcini", async (api, caller) => {
const tokenA = RootAssetId;
const tokenB = XrpAssetId;
const amountADesired = 10_000_000;
Expand Down Expand Up @@ -52,8 +43,4 @@ export async function main() {
} = event;
const liquidity = data[5].toString();
console.log("Liquidity", liquidity);

await api.disconnect();
}

main();
});
22 changes: 4 additions & 18 deletions examples/substrate/use-dex/src/removeLiquidity.ts
Original file line number Diff line number Diff line change
@@ -1,27 +1,17 @@
/* eslint-disable @typescript-eslint/no-explicit-any */
import { collectArgs } from "@trne/utils/collectArgs";
import { createKeyring } from "@trne/utils/createKeyring";
import { filterExtrinsicEvents } from "@trne/utils/filterExtrinsicEvents";
import { getChainApi } from "@trne/utils/getChainApi";
import { sendExtrinsic } from "@trne/utils/sendExtrinsic";
import { withChainApi } from "@trne/utils/withChainApi";
import assert from "assert";
import { cleanEnv, str } from "envalid";

const argv = collectArgs();

const env = cleanEnv(process.env, {
CALLER_PRIVATE_KEY: str(), // private key of extrinsic caller
});
assert("liquidity" in argv, "Liquidity is required");

const XrpAssetId = 2;
const RootAssetId = 1;

export async function main() {
assert("liquidity" in argv, "Liquidity is required");

const api = await getChainApi("porcini");
const caller = createKeyring(env.CALLER_PRIVATE_KEY);

withChainApi("porcini", async (api, caller) => {
const tokenA = RootAssetId;
const tokenB = XrpAssetId;
const amountAMin = 0;
Expand All @@ -44,8 +34,4 @@ export async function main() {
const [event] = filterExtrinsicEvents(result.events, ["Dex.RemoveLiquidity"]);

console.log("Extrinsic Result", event.toJSON());

await api.disconnect();
}

main();
});
19 changes: 3 additions & 16 deletions examples/substrate/use-dex/src/swapTokens.ts
Original file line number Diff line number Diff line change
@@ -1,20 +1,11 @@
import { createKeyring } from "@trne/utils/createKeyring";
import { filterExtrinsicEvents } from "@trne/utils/filterExtrinsicEvents";
import { getChainApi } from "@trne/utils/getChainApi";
import { sendExtrinsic } from "@trne/utils/sendExtrinsic";
import { cleanEnv, str } from "envalid";

const env = cleanEnv(process.env, {
CALLER_PRIVATE_KEY: str(), // private key of extrinsic caller
});
import { withChainApi } from "@trne/utils/withChainApi";

const XrpAssetId = 2;
const RootAssetId = 1;

export async function main() {
const api = await getChainApi("porcini");
const caller = createKeyring(env.CALLER_PRIVATE_KEY);

withChainApi("porcini", async (api, caller) => {
const oneXrp = 1_000_000;

// querying the dex for swap price, to determine the `amountOutMin` you are willing to accept
Expand All @@ -38,8 +29,4 @@ export async function main() {
const [event] = filterExtrinsicEvents(result.events, ["Dex.Swap"]);

console.log("Extrinsic Result", event.toJSON());

await api.disconnect();
}

main();
});
46 changes: 20 additions & 26 deletions examples/substrate/use-ethBridge/src/erc20/bridgeETHToTRN.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,8 @@

/* eslint-disable @typescript-eslint/no-non-null-assertion */
import { collectArgs } from "@trne/utils/collectArgs";
import { getChainApi } from "@trne/utils/getChainApi";
import type { ApiPromise } from "@trne/utils/getChainApi";
import { withChainApi } from "@trne/utils/withChainApi";
import { cleanEnv, str } from "envalid";
import { BigNumber, utils as ethers, getDefaultProvider, Wallet } from "ethers";

Expand All @@ -23,11 +24,10 @@ const EthAsset = {
address: "0x0000000000000000000000000000000000000000",
};

async function main() {
async function main(api: ApiPromise) {
const { asset } = argv as unknown as { asset: string };
const isETH = asset === "ETH";

const api = await getChainApi("porcini");
const provider = getDefaultProvider("goerli");
const wallet = new Wallet(env.CALLER_PRIVATE_KEY, provider);
const syloContract = getERC20Contract(SyloAsset.address, wallet);
Expand All @@ -40,7 +40,7 @@ async function main() {
sendMessageFeeBN = await bridgeContract.sendMessageFee();
} catch (error: any) {
// Error code associated with `defaultProvider` failure
if (error?.code === "CALL_EXCEPTION") await main();
if (error?.code === "CALL_EXCEPTION") await main(api);
return;
}
const sendMessageFee = ethers.formatEther(sendMessageFeeBN!);
Expand Down Expand Up @@ -73,29 +73,23 @@ async function main() {
const receipt = await tx.wait();
console.log("deposited", receipt.transactionHash);

await new Promise<void>((resolve) => {
// subscribe to system events via storage
api.query.system.events((events: any[]) => {
console.log(`\nReceived ${events.length} event(s):`);

// loop through the Vec<EventRecord>
events.forEach((record) => {
const { event } = record;
if (event.section === "ethBridge" && event.method === "EventSubmit") {
console.log(`ETH Bridge transaction added successfully, for event id ${event.data[0]}`);
}

if (event.section === "ethBridge" && event.method === "ProcessingOk") {
console.log(
`ETH Bridge transaction executed successfully, for event id ${event.data[0]}`
);
resolve();
}
});
// subscribe to system events via storage
api.query.system.events((events: any[]) => {
console.log(`\nReceived ${events.length} event(s):`);

// loop through the Vec<EventRecord>
events.forEach((record) => {
const { event } = record;
if (event.section === "ethBridge" && event.method === "EventSubmit") {
console.log(`ETH Bridge transaction added successfully, for event id ${event.data[0]}`);
}

if (event.section === "ethBridge" && event.method === "ProcessingOk") {
console.log(`ETH Bridge transaction executed successfully, for event id ${event.data[0]}`);
api.disconnect().then(() => process.exit(0));
}
});
});

await api.disconnect();
}

main().then(() => process.exit(0));
withChainApi("porcini", main);
15 changes: 8 additions & 7 deletions examples/substrate/use-ethBridge/src/erc20/bridgeTRNToETH.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,10 @@
/* eslint-disable @typescript-eslint/no-explicit-any */
import { createKeyring } from "@trne/utils/createKeyring";
import type { Signer } from "@trne/utils/createKeyring";
import { fetchTRNEvent } from "@trne/utils/fetchTRNEvent";
import { filterExtrinsicEvents } from "@trne/utils/filterExtrinsicEvents";
import { getChainApi } from "@trne/utils/getChainApi";
import type { ApiPromise } from "@trne/utils/getChainApi";
import { sendExtrinsic } from "@trne/utils/sendExtrinsic";
import { withChainApi } from "@trne/utils/withChainApi";
import { cleanEnv, str } from "envalid";
import { BigNumber, utils as ethers, getDefaultProvider, Wallet } from "ethers";

Expand All @@ -18,10 +19,8 @@ const EthAsset = {
assetId: 1124,
};

async function main() {
const api = await getChainApi("porcini");
async function main(api: ApiPromise, caller: Signer) {
const provider = getDefaultProvider("goerli");
const caller = createKeyring(env.CALLER_PRIVATE_KEY);
const wallet = new Wallet(env.CALLER_PRIVATE_KEY, provider);
const { bridgeContract } = getBridgeContracts("goerli", wallet);

Expand All @@ -32,7 +31,7 @@ async function main() {
bridgeFee = await bridgeContract.bridgeFee();
} catch (error: any) {
// Error code associated with `defaultProvider` failure
if (error?.code === "CALL_EXCEPTION") await main();
if (error?.code === "CALL_EXCEPTION") await main(api, caller);
return;
}

Expand Down Expand Up @@ -87,6 +86,8 @@ async function main() {

const receipt = await tx.wait();
console.log("Claimed", receipt.transactionHash);

process.exit(0);
}

main().then(() => process.exit(0));
withChainApi("porcini", main);
10 changes: 5 additions & 5 deletions examples/substrate/use-ethBridge/src/erc721/bridgeETHToTRN.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
/* eslint-disable @typescript-eslint/no-explicit-any */
import { collectArgs } from "@trne/utils/collectArgs";
import { getChainApi } from "@trne/utils/getChainApi";
import type { ApiPromise } from "@trne/utils/getChainApi";
import { withChainApi } from "@trne/utils/withChainApi";
import assert from "assert";
import { cleanEnv, str } from "envalid";
import { BigNumber, getDefaultProvider, Wallet } from "ethers";
Expand All @@ -15,11 +16,10 @@ const env = cleanEnv(process.env, {

const TheNextLegends = "0x5085CC0236ae108812571eADF24beeE4fe8E0c50";

async function main() {
async function main(api: ApiPromise) {
assert("tokenId" in argv, "Token ID is required");
const { tokenId } = argv as unknown as { tokenId: number };

const api = await getChainApi("porcini");
const provider = getDefaultProvider("goerli");
const wallet = new Wallet(env.CALLER_PRIVATE_KEY, provider);
const TheNextLegendsContract = getERC721Contract(TheNextLegends, wallet);
Expand All @@ -37,7 +37,7 @@ async function main() {
sendMessageFee = await bridgeContract.sendMessageFee();
} catch (error: any) {
// Error code associated with `defaultProvider` failure
if (error?.code === "CALL_EXCEPTION") await main();
if (error?.code === "CALL_EXCEPTION") await main(api);
return;
}

Expand Down Expand Up @@ -79,4 +79,4 @@ async function main() {
});
}

main();
withChainApi("porcini", main);
Loading

0 comments on commit fff0534

Please sign in to comment.