Skip to content

Commit 814b763

Browse files
Merge pull request #55 from developerfred/improve-error-handling-code-runner
Add OpenGov Operations Example
2 parents 22e862a + ad866c6 commit 814b763

File tree

3 files changed

+357
-0
lines changed

3 files changed

+357
-0
lines changed
Lines changed: 180 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,180 @@
1+
import type { Network } from "../types/network";
2+
import { ExampleFactory } from "./factory";
3+
4+
export class CoretimeExample extends ExampleFactory {
5+
constructor() {
6+
super({
7+
id: "coretime-operations",
8+
name: "Coretime Chain Operations",
9+
description: "Demonstrate Coretime operations: core buying, renewal, and asset management",
10+
level: "advanced",
11+
categories: ["coretime", "parachains", "assets", "agile-coretime"],
12+
});
13+
}
14+
15+
generateCode(network: Network): string {
16+
return `// Coretime Chain Operations Example on ${network.name}
17+
${this.getImports(network, true)}
18+
19+
// Connect to ${network.name} Coretime Chain
20+
const client = createClient(
21+
withPolkadotSdkCompat(
22+
getWsProvider("${network.endpoint}")
23+
)
24+
);
25+
26+
// Get the typed API using the descriptors
27+
const typedApi = client.getTypedApi(${network.descriptorKey});
28+
29+
// Coretime operations demonstration
30+
const demonstrateCoretimeOperations = async () => {
31+
try {
32+
console.log("⏰ Starting Coretime operations demonstration...");
33+
34+
// 1. Query current price and configuration
35+
console.log("\\n💰 Querying Coretime pricing:");
36+
try {
37+
const coretimeConfig = await typedApi.query.Broker.Configuration.getValue();
38+
console.log("Coretime configuration:", coretimeConfig);
39+
} catch (error) {
40+
console.log("Coretime configuration not available");
41+
}
42+
43+
// 2. Query core sales status
44+
console.log("\\n🏷️ Querying core sales status:");
45+
try {
46+
const saleInfo = await typedApi.query.Broker.SaleInfo.getValue();
47+
console.log("Current sale information:", saleInfo);
48+
} catch (error) {
49+
console.log("Sale info not available");
50+
}
51+
52+
// 3. Query available cores
53+
console.log("\\n🔍 Querying available cores:");
54+
try {
55+
const cores = await typedApi.query.Broker.CoreSchedules.getEntries();
56+
console.log("Found", cores.length, "cores with schedules");
57+
58+
if (cores.length > 0) {
59+
const firstCore = cores[0];
60+
console.log("First core schedule:", {
61+
coreId: firstCore.key?.args?.[0]?.toString(),
62+
schedule: firstCore.value
63+
});
64+
}
65+
} catch (error) {
66+
console.log("Core schedules not available");
67+
}
68+
69+
// 4. Demonstrate core purchase
70+
console.log("\\n🛒 Core Purchase Example:");
71+
console.log("This would purchase coretime for a specific period:");
72+
const purchaseTx = typedApi.tx.Broker.purchase({
73+
price_limit: 1000000000000n, // Maximum price willing to pay
74+
});
75+
console.log("Coretime purchase transaction created (not submitted in simulator)");
76+
77+
// 5. Demonstrate core renewal
78+
console.log("\\n🔄 Core Renewal Example:");
79+
console.log("This would renew an existing core:");
80+
const renewTx = typedApi.tx.Broker.renew({
81+
core: 0, // Core ID to renew
82+
price_limit: 500000000000n, // Maximum price for renewal
83+
});
84+
console.log("Core renewal transaction created for core 0 (not submitted in simulator)");
85+
86+
// 6. Query workload information
87+
console.log("\\n📊 Querying workload information:");
88+
try {
89+
const workload = await typedApi.query.Broker.Workload.getEntries();
90+
console.log("Found workload data for", workload.length, "cores");
91+
} catch (error) {
92+
console.log("Workload data not available");
93+
}
94+
95+
// 7. Query reservations
96+
console.log("\\n📅 Querying reservations:");
97+
try {
98+
const reservations = await typedApi.query.Broker.Reservations.getValue();
99+
console.log("Current reservations:", reservations);
100+
} catch (error) {
101+
console.log("Reservations not available");
102+
}
103+
104+
// 8. Demonstrate partition core operation
105+
console.log("\\n✂️ Core Partition Example:");
106+
console.log("This would partition a core into smaller time slices:");
107+
const partitionTx = typedApi.tx.Broker.partition({
108+
core: 0, // Core to partition
109+
price_limit: 200000000000n, // Price limit for partition
110+
});
111+
console.log("Core partition transaction created (not submitted in simulator)");
112+
113+
// 9. Demonstrate core assignment
114+
console.log("\\n🎯 Core Assignment Example:");
115+
console.log("This would assign a core to a parachain:");
116+
const assignTx = typedApi.tx.Broker.assign({
117+
core: 0, // Core to assign
118+
begin: 1000, // Starting block
119+
assignment: [{
120+
task: 2000, // Parachain ID
121+
ratio: [80, 20] // 80% to parachain, 20% to pool
122+
}],
123+
end_hint: null
124+
});
125+
console.log("Core assignment transaction created (not submitted in simulator)");
126+
127+
// 10. Query core status
128+
console.log("\\n📋 Querying core status:");
129+
try {
130+
const status = await typedApi.query.Broker.StatusOf.getValue(0);
131+
console.log("Status of core 0:", status);
132+
} catch (error) {
133+
console.log("Core status not available");
134+
}
135+
136+
// 11. Query allowed renewal records
137+
console.log("\\n🔑 Querying allowed renewal records:");
138+
try {
139+
const aliceAddress = "${this.getTestAccount("alice")}";
140+
const allowedRenewal = await typedApi.query.Broker.AllowedRenewalRecords.getValue(aliceAddress);
141+
console.log("Alice's allowed renewal records:", allowedRenewal);
142+
} catch (error) {
143+
console.log("Allowed renewal records not available");
144+
}
145+
146+
// 12. Demonstrate pool operations
147+
console.log("\\n🏊 Pool Operations Example:");
148+
console.log("This would add coretime to the instant pool:");
149+
const poolTx = typedApi.tx.Broker.pool({
150+
core: 0, // Core to add to pool
151+
price_limit: 100000000000n, // Price limit
152+
});
153+
console.log("Pool transaction created (not submitted in simulator)");
154+
155+
// 13. Query instant pool configuration
156+
console.log("\\n⚡ Querying instant pool:");
157+
try {
158+
const poolInfo = await typedApi.query.Broker.InstantaneousPoolInfo.getValue();
159+
console.log("Instant pool information:", poolInfo);
160+
} catch (error) {
161+
console.log("Instant pool info not available");
162+
}
163+
164+
console.log("\\n✅ Coretime operations demonstration completed!");
165+
console.log("Note: Coretime operations require:");
166+
console.log("- Understanding of core scheduling and availability");
167+
console.log("- Proper price limits for purchases and renewals");
168+
console.log("- Knowledge of parachain assignments and workload distribution");
169+
console.log("- In a real application, you would sign and submit these transactions");
170+
console.log("- Coretime is a complex system - study the documentation thoroughly");
171+
172+
} catch (error) {
173+
console.error("❌ Error in Coretime operations:", error);
174+
}
175+
};
176+
177+
demonstrateCoretimeOperations().catch(console.error);
178+
`;
179+
}
180+
}

src/lib/examples/OpenGovExample.ts

Lines changed: 169 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,169 @@
1+
import type { Network } from "../types/network";
2+
import { ExampleFactory } from "./factory";
3+
4+
export class OpenGovExample extends ExampleFactory {
5+
constructor() {
6+
super({
7+
id: "opengov-operations",
8+
name: "OpenGov Operations",
9+
description: "Demonstrate OpenGov operations: tracks, referenda, voting, and submission deposits",
10+
level: "advanced",
11+
categories: ["governance", "opengov", "voting", "referenda"],
12+
});
13+
}
14+
15+
generateCode(network: Network): string {
16+
return `// OpenGov Operations Example on ${network.name}
17+
${this.getImports(network, true)}
18+
19+
// Connect to ${network.name}
20+
const client = createClient(
21+
withPolkadotSdkCompat(
22+
getWsProvider("${network.endpoint}")
23+
)
24+
);
25+
26+
// Get the typed API using the descriptors
27+
const typedApi = client.getTypedApi(${network.descriptorKey});
28+
29+
// OpenGov operations demonstration
30+
const demonstrateOpenGovOperations = async () => {
31+
try {
32+
console.log("🏛️ Starting OpenGov operations demonstration...");
33+
34+
// 1. Query current referenda
35+
console.log("\\n📋 Querying active referenda:");
36+
const referenda = await typedApi.query.Referenda.ReferendumInfoFor.getEntries();
37+
console.log("Found", referenda.length, "active referenda");
38+
39+
if (referenda.length > 0) {
40+
const firstReferendum = referenda[0];
41+
console.log("First referendum:", {
42+
id: firstReferendum.key?.args?.[0]?.toString(),
43+
info: firstReferendum.value
44+
});
45+
}
46+
47+
// 2. Query referendum tracks
48+
console.log("\\n🎯 Querying referendum tracks:");
49+
try {
50+
const tracks = await typedApi.query.Referenda.Tracks.getValue();
51+
console.log("Available tracks:", tracks?.map(track => ({
52+
id: track?.[0]?.toString(),
53+
info: track?.[1]
54+
})));
55+
} catch (error) {
56+
console.log("Tracks query not available in current version");
57+
}
58+
59+
// 3. Demonstrate referendum submission
60+
console.log("\\n📝 Referendum Submission Example:");
61+
console.log("This would submit a referendum to a specific track:");
62+
const submissionTx = typedApi.tx.Referenda.submit({
63+
proposalOrigin: {
64+
Origins: "GeneralAdmin" // Track name
65+
},
66+
proposal: {
67+
Lookup: {
68+
hash: "0x0000000000000000000000000000000000000000000000000000000000000000", // Example hash
69+
len: 0
70+
}
71+
},
72+
enactmentMoment: {
73+
After: 100 // Blocks after approval
74+
}
75+
});
76+
console.log("Referendum submission transaction created (not submitted in simulator)");
77+
78+
// 4. Demonstrate voting on referendum
79+
console.log("\\n🗳️ Voting on Referendum Example:");
80+
console.log("This would vote on an active referendum:");
81+
const voteTx = typedApi.tx.ConvictionVoting.vote({
82+
poll_index: 0, // Referendum ID
83+
vote: {
84+
Standard: {
85+
vote: {
86+
aye: true,
87+
conviction: "Locked4x" // 4x conviction
88+
},
89+
balance: 1000000000000n // Vote amount
90+
}
91+
}
92+
});
93+
console.log("Vote transaction created for referendum #0 (not submitted in simulator)");
94+
95+
// 5. Query conviction voting state
96+
console.log("\\n📊 Querying conviction voting state:");
97+
const aliceAddress = "${this.getTestAccount("alice")}";
98+
try {
99+
const votingFor = await typedApi.query.ConvictionVoting.VotingFor.getValue(aliceAddress, 0);
100+
console.log("Alice's vote on referendum 0:", votingFor);
101+
} catch (error) {
102+
console.log("Conviction voting query not available");
103+
}
104+
105+
// 6. Demonstrate proposal deposit
106+
console.log("\\n💰 Proposal Deposit Example:");
107+
console.log("This would place a decision deposit on a referendum:");
108+
const depositTx = typedApi.tx.Referenda.placeDecisionDeposit({
109+
index: 0 // Referendum ID
110+
});
111+
console.log("Decision deposit transaction created (not submitted in simulator)");
112+
113+
// 7. Query decision deposits
114+
console.log("\\n🏦 Querying decision deposits:");
115+
try {
116+
const deposits = await typedApi.query.Referenda.DecisionDeposits.getValue(0);
117+
console.log("Decision deposits for referendum 0:", deposits);
118+
} catch (error) {
119+
console.log("Decision deposits query not available");
120+
}
121+
122+
// 8. Demonstrate whitelisted caller operation
123+
console.log("\\n⭐ Whitelisted Caller Example:");
124+
console.log("This would execute a whitelisted operation:");
125+
const whitelistTx = typedApi.tx.WhitelistedCaller.dispatchAs({
126+
asOrigin: {
127+
Origins: "WhitelistedCaller"
128+
},
129+
call: {
130+
system: {
131+
remark: {
132+
remark: "0x48656c6c6f20506f6c6b61646f7421" // "Hello Polkadot!"
133+
}
134+
}
135+
}
136+
});
137+
console.log("Whitelisted caller transaction created (not submitted in simulator)");
138+
139+
// 9. Query fellowship information (if available)
140+
console.log("\\n👥 Fellowship Information:");
141+
try {
142+
const fellowship = await typedApi.query.FellowshipCollective.Members.getValue(aliceAddress);
143+
console.log("Alice's fellowship rank:", fellowship?.toString());
144+
} catch (error) {
145+
console.log("Fellowship queries not available on this network");
146+
}
147+
148+
// 10. Query current block for timing
149+
console.log("\\n⏰ Current Block Information:");
150+
const currentBlock = await typedApi.query.System.Number.getValue();
151+
console.log("Current block:", currentBlock?.toString());
152+
153+
console.log("\\n✅ OpenGov operations demonstration completed!");
154+
console.log("Note: OpenGov operations require:");
155+
console.log("- Understanding of different tracks and their requirements");
156+
console.log("- Proper deposit amounts for proposal submission");
157+
console.log("- Sufficient conviction voting power");
158+
console.log("- In a real application, you would sign and submit these transactions");
159+
console.log("- Consider the lock periods for conviction voting");
160+
161+
} catch (error) {
162+
console.error("❌ Error in OpenGov operations:", error);
163+
}
164+
};
165+
166+
demonstrateOpenGovOperations().catch(console.error);
167+
`;
168+
}
169+
}

src/lib/examples/index.ts

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,10 @@
22
import { exampleRegistry } from "./factory";
33
import { StakingOperationsExample } from "./StakingOperationsExample";
44
import { AssetHubExample } from "./AssetHubExample";
5+
import { OpenGovExample } from "./OpenGovExample";
6+
import { CoretimeExample } from "./CoretimeExample";
7+
8+
59

610

711
import { SimpleTransferExample } from "./SimpleTransferExample";
@@ -10,7 +14,11 @@ import { AccountBalanceCheckerExample } from "./AccountBalanceCheckerExample";
1014
import { WalletTransferExample } from "./WalletTransferExample";
1115
import { AcalaDeFiExample } from "./AcalaDeFiExample";
1216
import type { Example, ExampleLevel } from "../types/example";
17+
new CoretimeExample(),
18+
1319
import { PolkadotGovernanceExample } from "./PolkadotGovernanceExample";
20+
new OpenGovExample(),
21+
1422

1523
new AssetHubExample(),
1624

0 commit comments

Comments
 (0)