Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
236 changes: 236 additions & 0 deletions examples/ChaincallinkExamples.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,236 @@
using System;
using System.Collections.Generic;
using System.Threading.Tasks;

namespace PiApps.Chainlink.Examples
{
/// <summary>
/// Chainlink Integration Examples for Pi SDK .NET
/// Complete working examples demonstrating all Chainlink features
/// </summary>
public static class ChaincallinkExamples
{
/// <summary>
/// Example 1: Portfolio Price Monitoring
/// Track real-time prices for multiple assets
/// </summary>
public static async Task PortfolioMonitoringAsync()
{
using (var client = ChaincallinkClientFactory.CreateFromEnvironment())
{
var pairs = new List<string> { "PI/USD", "BTC/USD", "ETH/USD", "XLM/USD", "USDC/USD" };
var prices = await client.GetPricesAsync(pairs);

var holdings = new Dictionary<string, decimal>
{
{ "PI", 1000m },
{ "BTC", 0.5m },
{ "ETH", 5m },
{ "XLM", 10000m },
{ "USDC", 50000m }
};

decimal totalValue = 0;

foreach (var (pair, data) in prices)
{
var asset = pair.Split('/')[0];
var amount = holdings.ContainsKey(asset) ? holdings[asset] : 0;
var value = amount * data.Rate;
totalValue += value;

Console.WriteLine($"{pair}: ${data.Rate} (Confidence: {data.Confidence * 100:F2}%)");
}

Console.WriteLine($"Portfolio Total: ${totalValue:F2}");
}
}

/// <summary>
/// Example 2: Automated Trading with VRF
/// Execute trades based on oracle prices with randomized execution
/// </summary>
public static async Task AutomatedTradingWithVRFAsync()
{
using (var client = ChaincallinkClientFactory.CreateFromEnvironment())
{
var btcPrice = await client.GetPriceAsync("BTC/USD");

decimal buyThreshold = 40000m;
decimal sellThreshold = 50000m;

Console.WriteLine($"Current BTC Price: ${btcPrice.Rate}");

if (btcPrice.Rate < buyThreshold)
{
var vrf = await client.RequestVRFAsync("trading-job-1", "btc-buy", (uint)DateTimeOffset.UtcNow.ToUnixTimeSeconds());
var tradeSize = (vrf.Nonce % 5) + 1;
Console.WriteLine($"Buy Signal: {tradeSize} BTC at ${btcPrice.Rate}");
}
else if (btcPrice.Rate > sellThreshold)
{
var vrf = await client.RequestVRFAsync("trading-job-1", "btc-sell", (uint)DateTimeOffset.UtcNow.ToUnixTimeSeconds());
var tradeSize = (vrf.Nonce % 5) + 1;
Console.WriteLine($"Sell Signal: {tradeSize} BTC at ${btcPrice.Rate}");
}
}
}

/// <summary>
/// Example 3: Staking with Keeper Automation
/// Automate staking rewards collection using Keepers
/// </summary>
public static async Task StakingAutomationAsync()
{
using (var client = ChaincallinkClientFactory.CreateFromEnvironment())
{
var jobs = await client.ListKeeperJobsAsync("active");
var stakingJobs = jobs.FindAll(j => j.Name.Contains("staking"));

Console.WriteLine($"Found {stakingJobs.Count} active staking jobs:");

foreach (var job in stakingJobs)
{
Console.WriteLine($"\nJob: {job.Name}");
Console.WriteLine($"Status: {job.Status}");
Console.WriteLine($"Executions: {job.ExecutionCount} ({job.SuccessCount} successful)");
Console.WriteLine($"Success Rate: {job.GetSuccessRate():F2}%");
Console.WriteLine($"Next Execution: {job.NextExecution:O}");

// Execute if due
if (DateTime.UtcNow >= job.NextExecution)
{
var (success, txHash) = await client.ExecuteKeeperJobAsync(job.Id);
if (success)
Console.WriteLine($"✓ Execution Triggered: {txHash}");
}
}
}
}

/// <summary>
/// Example 4: Cross-Chain Payments with CCIP
/// Send stablecoins across blockchains
/// </summary>
public static async Task CrossChainPaymentsAsync()
{
using (var client = ChaincallinkClientFactory.CreateFromEnvironment())
{
var message = new CCIPMessage
{
SourceChain = "ethereum",
DestinationChain = "polygon",
Receiver = "0x1234567890123456789012345678901234567890",
Data = System.Text.Json.JsonSerializer.SerializeToElement(new
{
type = "payment",
amount = 1000,
currency = "USDC",
reference = "PAY-2025-001"
}),
Tokens = new List<TokenTransfer>
{
new TokenTransfer { Token = "USDC", Amount = "1000000000" }
}
};

Console.WriteLine("Initiating cross-chain payment...");
Console.WriteLine($"From: {message.SourceChain} → To: {message.DestinationChain}");
Console.WriteLine($"Receiver: {message.Receiver}");
Console.WriteLine("Amount: 1000 USDC");

var messageId = await client.SendCCIPMessageAsync(message);
Console.WriteLine($"Message ID: {messageId}");

// Poll message status
var status = await client.GetCCIPMessageStatusAsync(messageId);
Console.WriteLine($"Initial Status: {status.Status}");

for (int i = 0; i < 5; i++)
{
await Task.Delay(2000);
status = await client.GetCCIPMessageStatusAsync(messageId);
Console.WriteLine($"Status Update: {status.Status} (Confirmations: {status.Confirmations})");

if (status.Status == MessageState.Executed)
{
Console.WriteLine("✓ Payment delivered!");
break;
}
}
}
}

/// <summary>
/// Example 5: Oracle Health Monitoring
/// Monitor Chainlink network and adjust strategies
/// </summary>
public static async Task HealthMonitoringAsync()
{
using (var client = ChaincallinkClientFactory.CreateFromEnvironment())
{
var health = await client.GetHealthStatusAsync();

Console.WriteLine("Chainlink Network Health:");
Console.WriteLine($"Status: {health.Status}");
Console.WriteLine($"Active Nodes: {health.ActiveNodes}/{health.TotalNodes}");
Console.WriteLine($"Uptime: {health.Uptime * 100:F2}%");
Console.WriteLine($"Price Feeds: {health.FeedsCount}");
Console.WriteLine($"Avg Latency: {health.AverageLatencyMs}ms");

// Implement fallback strategy
if (health.Status == NetworkStatus.Degraded)
{
Console.WriteLine("⚠ Network degraded - increasing cache duration");
client.SetCacheDuration(600);
}
else if (health.Status == NetworkStatus.Offline)
{
Console.WriteLine("✗ Network offline - using fallback data");
}
else
{
Console.WriteLine("✓ Network healthy");
client.SetCacheDuration(300);
}
}
}

/// <summary>
/// Run all examples
/// </summary>
public static async Task RunAllExamplesAsync()
{
Console.WriteLine("=== Chainlink Pi SDK Integration Examples ===\n");

try
{
Console.WriteLine("📊 Example 1: Portfolio Monitoring");
Console.WriteLine("----------------------------------------");
await PortfolioMonitoringAsync();

Console.WriteLine("\n\n📈 Example 2: Automated Trading with VRF");
Console.WriteLine("----------------------------------------");
await AutomatedTradingWithVRFAsync();

Console.WriteLine("\n\n🔄 Example 3: Staking Automation");
Console.WriteLine("----------------------------------------");
await StakingAutomationAsync();

Console.WriteLine("\n\n💳 Example 4: Cross-Chain Payments");
Console.WriteLine("----------------------------------------");
await CrossChainPaymentsAsync();

Console.WriteLine("\n\n⚡ Example 5: Health Monitoring");
Console.WriteLine("----------------------------------------");
await HealthMonitoringAsync();

Console.WriteLine("\n\n✓ All examples completed successfully!");
}
catch (Exception ex)
{
Console.Error.WriteLine($"✗ Error running examples: {ex.Message}");
}
}
}
}
Loading