Code Examples
This page provides practical code examples to help you understand how to use various features of the Neo N3 Service Layer. Each example includes explanations and can be used as a starting point for your own applications.
Function Service Examples
Example 1: Token Balance Checker
This function retrieves and returns the NEO and GAS balance for a given address.
1// Token Balance Checker
2// Retrieves NEO and GAS balance for a given address
3
4function main(args) {
5 // Validate input
6 if (!args.address) {
7 return { error: "No address provided" };
8 }
9
10 try {
11 // Get NEO balance
12 const neoBalance = neo.getBalance(args.address, 'NEO');
13
14 // Get GAS balance
15 const gasBalance = neo.getBalance(args.address, 'GAS');
16
17 // Return formatted results
18 return {
19 address: args.address,
20 balances: {
21 neo: neoBalance,
22 gas: gasBalance
23 },
24 timestamp: new Date().toISOString()
25 };
26 } catch (error) {
27 return {
28 error: error.message,
29 address: args.address
30 };
31 }
32}
Usage Example
1// Invoke the function
2const result = await serviceLayer.functions.invoke("tokenBalanceChecker", {
3 address: "NhGomBpYnKXArr55nHRQ5rzy79TwKVXZbr"
4});
5
6console.log(result);
7// Output:
8// {
9// "address": "NhGomBpYnKXArr55nHRQ5rzy79TwKVXZbr",
10// "balances": {
11// "neo": "100.0",
12// "gas": "25.34928451"
13// },
14// "timestamp": "2023-03-22T12:34:56.789Z"
15// }
16
Example 2: Price Alert Function
This function checks if a token's price has moved beyond specified thresholds and sends notifications.
1// Price Alert Function
2// Monitors token prices and sends alerts when thresholds are crossed
3
4async function main(args) {
5 // Input validation
6 if (!args.token || !args.upperThreshold || !args.lowerThreshold) {
7 return { error: "Missing required parameters" };
8 }
9
10 try {
11 // Get current token price using the Price Feed service
12 const tokenPrice = await priceFeed.getPrice(args.token);
13
14 // Get previous price from our last run (stored in a secret)
15 let previousData = {};
16 try {
17 const storedData = await secrets.get('previous_price_data');
18 previousData = JSON.parse(storedData || '{}');
19 } catch (e) {
20 // This might be the first run, so we'll create the data
21 console.log("No previous price data found, creating new entry");
22 }
23
24 const previousPrice = previousData[args.token] || tokenPrice;
25
26 // Check if price crossed any thresholds
27 const crossedUpper = previousPrice < args.upperThreshold && tokenPrice >= args.upperThreshold;
28 const crossedLower = previousPrice > args.lowerThreshold && tokenPrice <= args.lowerThreshold;
29
30 // Store the current price for next run
31 previousData[args.token] = tokenPrice;
32 await secrets.put('previous_price_data', JSON.stringify(previousData));
33
34 // If a threshold was crossed, send notification
35 if (crossedUpper || crossedLower) {
36 const message = crossedUpper
37 ? `${args.token} price crossed above ${args.upperThreshold}! Current price: ${tokenPrice}`
38 : `${args.token} price crossed below ${args.lowerThreshold}! Current price: ${tokenPrice}`;
39
40 // Send notification (assuming we have a webhook URL in secrets)
41 const webhookUrl = await secrets.get('notification_webhook');
42 if (webhookUrl) {
43 await fetch(webhookUrl, {
44 method: 'POST',
45 headers: { 'Content-Type': 'application/json' },
46 body: JSON.stringify({ message })
47 });
48 }
49
50 return {
51 alertTriggered: true,
52 threshold: crossedUpper ? 'upper' : 'lower',
53 token: args.token,
54 price: tokenPrice,
55 message
56 };
57 }
58
59 // No alert triggered
60 return {
61 alertTriggered: false,
62 token: args.token,
63 price: tokenPrice
64 };
65 } catch (error) {
66 return { error: error.message };
67 }
68}
Scheduling the Alert Function
1// Schedule this function to run every hour
2const automation = await serviceLayer.automation.create({
3 name: "Hourly NEO Price Alert",
4 schedule: "0 * * * *", // Cron expression for hourly execution
5 function: "priceAlertFunction",
6 functionArgs: {
7 token: "NEO",
8 upperThreshold: 15.00,
9 lowerThreshold: 10.00
10 }
11});
12
13console.log("Created automation:", automation.id);
Automation Service Examples
Example: Contract Event Listener
This example shows how to set up an automation that triggers when specific events occur in a smart contract.
1// Set up an automation to listen for Transfer events on a NEP-17 token contract
2const automation = await serviceLayer.automation.create({
3 name: "Token Transfer Monitor",
4 trigger: {
5 type: "contract_event",
6 contractHash: "0x7a16a1f5c40e69790333f3bfe7e4325a08cc2f79", // Example NEP-17 token
7 eventName: "Transfer",
8
9 // Optional: filter conditions
10 filter: {
11 // Only trigger for transfers to this address
12 toAddress: "NhGomBpYnKXArr55nHRQ5rzy79TwKVXZbr"
13 }
14 },
15
16 // Function to call when the event occurs
17 function: "processTransfer",
18
19 // Dynamic function arguments that include event data
20 functionArgs: {
21 // Special syntax to pass event data to the function
22 fromAddress: "$event.from",
23 toAddress: "$event.to",
24 amount: "$event.amount",
25 txid: "$event.txid"
26 }
27});
28
29console.log("Created automation:", automation.id);
Gas Bank Service Examples
Example: Sponsored User Transaction
This example demonstrates how to use the Gas Bank to sponsor user transactions, allowing users to interact with smart contracts without needing to own GAS themselves.
1// Function to initiate a user transaction with gas sponsorship
2async function main(args) {
3 // Validate input
4 if (!args.userAddress || !args.amount || !args.tokenAddress) {
5 return { error: "Missing required parameters" };
6 }
7
8 // Our application's address that holds the tokens to transfer
9 const appAddress = "NdUL5oDPD159KeFpD5A9zw5xNF1xLX6nLT";
10
11 try {
12 // Get the current token balance of the app address
13 const tokenBalance = await neo.getTokenBalance(args.tokenAddress, appAddress);
14
15 // Check if the app has enough tokens
16 const amountToSend = parseFloat(args.amount);
17 if (parseFloat(tokenBalance) < amountToSend) {
18 return {
19 success: false,
20 error: "Insufficient token balance in application wallet"
21 };
22 }
23
24 // Execute the token transfer using Gas Bank for gas fees
25 const transferResult = await neo.invokeContract({
26 scriptHash: args.tokenAddress,
27 operation: "transfer",
28 args: [
29 appAddress, // from
30 args.userAddress, // to
31 amountToSend * 100000000 // amount (assuming 8 decimals)
32 ],
33 signers: [
34 {
35 account: appAddress,
36 scopes: "CalledByEntry"
37 }
38 ],
39 useGasBank: true // This flag tells the service to use Gas Bank
40 });
41
42 // Return success response with transaction details
43 return {
44 success: true,
45 txid: transferResult.txid,
46 from: appAddress,
47 to: args.userAddress,
48 amount: args.amount,
49 gasUsed: transferResult.gasConsumed
50 };
51
52 } catch (error) {
53 return {
54 success: false,
55 error: error.message
56 };
57 }
58}
Client Application Example
How a client application might use this function:
1// Client-side code to request a token transfer without the user paying gas
2async function requestTokens() {
3 const userAddress = await getNeoWalletAddress(); // Get user's address
4
5 // Call the Service Layer API
6 const response = await fetch('https://api.yourapplication.com/request-tokens', {
7 method: 'POST',
8 headers: { 'Content-Type': 'application/json' },
9 body: JSON.stringify({
10 userAddress: userAddress,
11 amount: '10.0' // Request 10 tokens
12 })
13 });
14
15 const result = await response.json();
16
17 if (result.success) {
18 console.log(`Transaction successful! TXID: ${result.txid}`);
19 console.log(`Received ${result.amount} tokens`);
20 } else {
21 console.error(`Failed: ${result.error}`);
22 }
23}
Secrets Management Examples
Example: External API Integration
This example shows how to securely store and use API credentials for third-party services.
1// Function that uses a secret to authenticate with an external weather API
2async function main(args) {
3 if (!args.city) {
4 return { error: "City parameter is required" };
5 }
6
7 try {
8 // Retrieve the API key from secure storage
9 const apiKey = await secrets.get('weather_api_key');
10
11 if (!apiKey) {
12 return { error: "Weather API key not configured" };
13 }
14
15 // Make the API call with the secret API key
16 const response = await fetch(
17 `https://api.weatherapi.com/v1/current.json?key=${apiKey}&q=${encodeURIComponent(args.city)}`
18 );
19
20 if (!response.ok) {
21 throw new Error(`Weather API request failed: ${response.status} ${response.statusText}`);
22 }
23
24 const data = await response.json();
25
26 // Transform and return the relevant weather data
27 return {
28 city: data.location.name,
29 country: data.location.country,
30 temperature: {
31 celsius: data.current.temp_c,
32 fahrenheit: data.current.temp_f
33 },
34 condition: data.current.condition.text,
35 humidity: data.current.humidity,
36 updatedAt: data.current.last_updated
37 };
38
39 } catch (error) {
40 return {
41 error: error.message,
42 city: args.city
43 };
44 }
45}
Setting Up Secrets
Before using this function, you would need to store your API key using the Secrets API:
1// Store the API key securely
2await serviceLayer.secrets.put('weather_api_key', 'your-api-key-here');
3
4// The key is now securely stored and can only be accessed by
5// your functions running in the TEE environment
Need More Examples?
These examples demonstrate some common use cases, but there are many more possibilities. If you need examples for specific scenarios, please check ourGitHub repositoryor ask in our Discord community.