Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Apply code standards to all snippets #771

Merged
merged 5 commits into from
Oct 17, 2023
Merged
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
10 changes: 8 additions & 2 deletions .editorconfig
Original file line number Diff line number Diff line change
Expand Up @@ -2,10 +2,16 @@
indent_style=space
indent_size=2
max_line_length=80
quote_type = single
quote_type=single

[*.js]
indent_style=space
indent_size=2
max_line_length=80
quote_type = single
quote_type=single

[*.json]
indent_style=space
indent_size=4
max_line_length=80
quote_type=single
Original file line number Diff line number Diff line change
Expand Up @@ -8,9 +8,9 @@ type Client = SignerMiddleware<Provider<Http>, Wallet<k256::ecdsa::SigningKey>>;
#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
let provider: Provider<Http> = Provider::<Http>::try_from("https://rpc.api.moonbase.moonbeam.network")?; // Change to correct network
// Do not include the private key in plain text in any produciton code. This is just for demonstration purposes
// Do not include the private key in plain text in any production code. This is just for demonstration purposes
// Do not include '0x' at the start of the private key
let wallet: LocalWallet = "PRIVATE KEY OF YOUR FROM ADDRESS"
let wallet: LocalWallet = "INSERT_PRIVATE_KEY"
.parse::<LocalWallet>()?
.with_chain_id(Chain::Moonbase);
let client = SignerMiddleware::new(provider.clone(), wallet.clone());
Expand All @@ -33,7 +33,7 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
// Need to install solc for this tutorial: https://github.com/crytic/solc-select
async fn compile_deploy_contract(client: &Client) -> Result<H160, Box<dyn std::error::Error>> {
// Incrementer.sol is located in the root directory
let source = Path::new(&env!("CARGO_MANIFEST_DIR"));
let source = Path::new(&env!("INSERT_CARGO_MANIFEST_DIR"));

// Compile it
let compiled = Solc::default()
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,14 +6,14 @@ type Client = SignerMiddleware<Provider<Http>, Wallet<k256::ecdsa::SigningKey>>;
#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
let provider: Provider<Http> = Provider::<Http>::try_from("https://rpc.api.moonbase.moonbeam.network")?; // Change to correct network
// Do not include the private key in plain text in any produciton code. This is just for demonstration purposes
let wallet: LocalWallet = "PRIVATE KEY OF YOUR FROM ADDRESS"
// Do not include the private key in plain text in any production code. This is just for demonstration purposes
let wallet: LocalWallet = "INSERT_PRIVATE_KEY"
.parse::<LocalWallet>()?
.with_chain_id(Chain::Moonbase); // Change to correct network
let client = SignerMiddleware::new(provider.clone(), wallet.clone());

let address_from = "YOUR FROM ADDRESS".parse::<Address>()?;
let address_to = "YOUR TO ADDRESS".parse::<Address>()?;
let address_from = "INSERT_FROM_ADDRESS".parse::<Address>()?;
let address_to = "INSERT_TO_ADDRESS".parse::<Address>()?;

send_transaction(&client, &address_from, &address_to).await?;
print_balances(&provider, &address_from, &address_to).await?;
Expand Down
Original file line number Diff line number Diff line change
@@ -1,39 +1,40 @@
from substrateinterface import SubstrateInterface

# Define the Ethereum transaction hash to check finality
tx_hash = 'INSERT_TX_HASH'
tx_hash = "INSERT_TX_HASH"

# Point API provider to Moonbeam
# This can be adapted for Moonriver or Moonbase Alpha
moonbeam_API_provider = SubstrateInterface(
url='INSERT_WSS_API_ENDPOINT',
url="INSERT_WSS_API_ENDPOINT",
)

if __name__ == '__main__':

if __name__ == "__main__":
# Get the latest finalized block header of the chain
finalized_block_header = moonbeam_API_provider.get_block_header(
finalized_only=True)
finalized_block_header = moonbeam_API_provider.get_block_header(finalized_only=True)
# Get the finalized block number from the block header
finalized_block_number = finalized_block_header['header']['number']
finalized_block_number = finalized_block_header["header"]["number"]
# Get the transaction receipt of the given transaction hash through a
# custom RPC request
tx_receipt = moonbeam_API_provider.rpc_request(
'eth_getTransactionReceipt', [tx_hash])
"eth_getTransactionReceipt", [tx_hash]
)

# Check if tx_receipt is null
if tx_receipt is None:
print('The transaction hash cannot be found in the canonical chain.')
print("The transaction hash cannot be found in the canonical chain.")
else:
# Get the block number of the transaction
tx_block_number = int(tx_receipt['result']['blockNumber'], 16)
tx_block_number = int(tx_receipt["result"]["blockNumber"], 16)
# Get the transaction block through a custom RPC request
tx_block = moonbeam_API_provider.rpc_request(
'eth_getBlockByNumber', [tx_block_number, False])
"eth_getBlockByNumber", [tx_block_number, False]
)

print(f"Current finalized block number is { str(finalized_block_number) }")
print(
f'Current finalized block number is { str(finalized_block_number) }')
print(
f'Your transaction in block { str(tx_block_number) } is finalized? { str(finalized_block_number >= tx_block_number) }')
f"Your transaction in block { str(tx_block_number) } is finalized? { str(finalized_block_number >= tx_block_number) }"
)
print(
f'Your transaction is indeed in block { str(tx_block_number) }? { str(tx_hash in tx_block["result"]["transactions"]) }')
f'Your transaction is indeed in block { str(tx_block_number) }? { str(tx_hash in tx_block["result"]["transactions"]) }'
)
Original file line number Diff line number Diff line change
@@ -1,15 +1,15 @@
from web3 import Web3

# Define the transaction hash to check finality
tx_hash = 'INSERT_TX_HASH'
tx_hash = "INSERT_TX_HASH"

# Define the Web3 provider for Moonbeam
# This can be adapted for Moonriver or Moonbase Alpha
web3_provider = Web3(Web3.HTTPProvider('INSERT_RPC_API_ENDPOINT'))
web3_provider = Web3(Web3.HTTPProvider("INSERT_RPC_API_ENDPOINT"))

if __name__ == "__main__":
# Get the latest finalized block
finalized_block_header = web3_provider.eth.get_block('finalized')
finalized_block_header = web3_provider.eth.get_block("finalized")
finalized_block_number = finalized_block_header.number

# Get the transaction receipt of the given transaction hash
Expand All @@ -23,14 +23,15 @@
tx_block = web3_provider.eth.get_block(tx_block_number)
is_in_block = False
for tx in tx_block.transactions:
if (tx_hash == web3_provider.to_hex(tx)):
if tx_hash == web3_provider.to_hex(tx):
is_in_block = True

print(f"Current finalized block number is { str(finalized_block_number) }")
print(
f'Current finalized block number is { str(finalized_block_number) }')
f"Your transaction in block { str(tx_block_number) } is finalized? { str(finalized_block_number >= tx_block_number) }"
)
print(
f'Your transaction in block { str(tx_block_number) } is finalized? { str(finalized_block_number >= tx_block_number) }')
print(
f'Your transaction is indeed in block { str(tx_block_number) }? { is_in_block }')
f"Your transaction is indeed in block { str(tx_block_number) }? { is_in_block }"
)
else:
print("Your transaction has not been included in the canonical chain")

This file was deleted.

Original file line number Diff line number Diff line change
@@ -0,0 +1,90 @@
import { typesBundlePre900 } from 'moonbeam-types-bundle';
import { ApiPromise, WsProvider } from '@polkadot/api';

// This script will listen to all GLMR transfers (Substrate & Ethereum) and extract the tx hash
// It can be adapted for Moonriver or Moonbase Alpha

const main = async () => {
// Define the provider for Moonbeam
const wsProvider = new WsProvider('wss://wss.api.moonbeam.network');
// Create the provider using Moonbeam types
const polkadotApi = await ApiPromise.create({
provider: wsProvider,
typesBundle: typesBundlePre900 as any,
});

// Subscribe to finalized blocks
await polkadotApi.rpc.chain.subscribeFinalizedHeads(
async (lastFinalizedHeader) => {
const [{ block }, records] = await Promise.all([
polkadotApi.rpc.chain.getBlock(lastFinalizedHeader.hash),
polkadotApi.query.system.events.at(lastFinalizedHeader.hash),
]);

block.extrinsics.forEach((extrinsic, index) => {
const {
method: { args, method, section },
} = extrinsic;

const isEthereum = section == 'ethereum' && method == 'transact';

// Gets the transaction object
const tx = args[0] as any;

// Convert to the correct Ethereum Transaction format
const ethereumTx =
isEthereum &&
((tx.isLegacy && tx.asLegacy) ||
(tx.isEip1559 && tx.asEip1559) ||
(tx.isEip2930 && tx.asEip2930));

// Check if the transaction is a transfer
const isEthereumTransfer =
ethereumTx &&
ethereumTx.input.length === 0 &&
ethereumTx.action.isCall;

// Retrieve all events for this extrinsic
const events = records.filter(
({ phase }) =>
phase.isApplyExtrinsic && phase.asApplyExtrinsic.eq(index)
);

// This hash will only exist if the transaction was executed through Ethereum.
let ethereumHash = '';

if (isEthereum) {
// Search for Ethereum execution
events.forEach(({ event }) => {
if (event.section == 'ethereum' && event.method == 'Executed') {
ethereumHash = event.data[2].toString();
}
});
}

// Search if it is a transfer
events.forEach(({ event }) => {
if (event.section == 'balances' && event.method == 'Transfer') {
const from = event.data[0].toString();
const to = event.data[1].toString();
const balance = (event.data[2] as any).toBigInt();

const substrateHash = extrinsic.hash.toString();

console.log(
`Transfer from ${from} to ${to} of ${balance} (block #${lastFinalizedHeader.number})`
);
console.log(` - Triggered by extrinsic: ${substrateHash}`);
if (isEthereum) {
console.log(
` - Ethereum (isTransfer: ${isEthereumTransfer}) hash: ${ethereumHash}`
);
}
}
});
});
}
);
};

main();
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
```ts
import axios from 'axios';

// This script will decode all native token transfers (Substrate & Ethereum) in a given Sidecar block, and extract the tx hash. It can be adapted for any Moonbeam network.
Expand Down Expand Up @@ -81,4 +80,3 @@ async function main() {
}

main();
```
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
```ts
import axios from 'axios';

// This script calculates the transaction fees of all transactions in a block
Expand Down Expand Up @@ -149,4 +148,3 @@ async function main() {
}

main();
```
Original file line number Diff line number Diff line change
Expand Up @@ -26,4 +26,4 @@ const getEncodedCallData = async () => {
api.disconnect();
};

getEncodedCallData();
getEncodedCallData();
Original file line number Diff line number Diff line change
Expand Up @@ -55,4 +55,4 @@ const sendXcmMessage = async () => {
api.disconnect();
};

sendXcmMessage();
sendXcmMessage();
Original file line number Diff line number Diff line change
@@ -1,14 +1,14 @@
import ABI from './xcmUtilsABI.js'; // Import the XCM Utilities Precompile ABI
import { ethers } from 'ethers'; // Import Ethers library

const PRIVATE_KEY = 'INSERT_YOUR_PRIVATE_KEY';
const privateKey = 'INSERT_YOUR_PRIVATE_KEY';
const xcmUtilsAddress = '0x000000000000000000000000000000000000080C';

/* Create Ethers provider and signer */
const provider = new ethers.JsonRpcProvider(
'https://rpc.api.moonbase.moonbeam.network'
);
const signer = new ethers.Wallet(PRIVATE_KEY, provider);
const signer = new ethers.Wallet(privateKey, provider);

/* Create contract instance of the XCM Utilities Precompile */
const xcmUtils = new ethers.Contract(
Expand Down
Loading
Loading