Skip to content

Commit

Permalink
fix: snippets
Browse files Browse the repository at this point in the history
  • Loading branch information
nhussein11 committed Jan 6, 2025
1 parent 3eaef94 commit 8b9f51c
Show file tree
Hide file tree
Showing 7 changed files with 299 additions and 265 deletions.
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
//SPDX-License-Identifier: MIT

// Solidity files have to start with this pragma.
// It will be used by the Solidity compiler to validate its version.
pragma solidity ^0.8.9;

contract Storage {
// Public state variable to store a number
uint256 public storedNumber;

/**
* Updates the stored number.
*
* The `public` modifier allows anyone to call this function.
*
* @param _newNumber - The new value to store.
*/
function setNumber(uint256 _newNumber) public {
storedNumber = _newNumber;
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,84 @@
const { ethers } = require('ethers');
const { readFileSync } = require('fs');
const { join } = require('path');

const createProvider = (providerConfig) => {
return new ethers.JsonRpcProvider(providerConfig.rpc, {
chainId: providerConfig.chainId,
name: providerConfig.name,
});
};

const createWallet = (mnemonic, provider) => {
return ethers.Wallet.fromPhrase(mnemonic).connect(provider);
};

const loadContractAbi = (contractName, directory = __dirname) => {
const contractPath = join(directory, `${contractName}.json`);
const contractJson = JSON.parse(readFileSync(contractPath, 'utf8'));
return contractJson.abi || contractJson; // Depending on JSON structure
};

const createContract = (contractAddress, abi, wallet) => {
return new ethers.Contract(contractAddress, abi, wallet);
};

const interactWithStorageContract = async (
contractName,
contractAddress,
mnemonic,
providerConfig,
numberToSet,
) => {
try {
console.log(`Setting new number in Storage contract: ${numberToSet}`);

// Create provider and wallet
const provider = createProvider(providerConfig);
const wallet = createWallet(mnemonic, provider);

// Load the contract ABI and create the contract instance
const abi = loadContractAbi(contractName);
const contract = createContract(contractAddress, abi, wallet);

// Send a transaction to set the stored number
const tx1 = await contract.setNumber(numberToSet);
await tx1.wait(); // Wait for the transaction to be mined
console.log(`Number successfully set to ${numberToSet}`);

// Retrieve the updated number
const storedNumber = await contract.storedNumber();
console.log(`Retrieved stored number:`, storedNumber.toString());

// Send a transaction to set the stored number
const tx2 = await contract.setNumber(numberToSet * 2);
await tx2.wait(); // Wait for the transaction to be mined
console.log(`Number successfully set to ${numberToSet * 2}`);

// Retrieve the updated number
const updatedNumber = await contract.storedNumber();
console.log(`Retrieved stored number:`, updatedNumber.toString());
} catch (error) {
console.error('Error interacting with Storage contract:', error.message);
}
};

const providerConfig = {
name: 'asset-hub-smart-contracts',
rpc: 'https://westend-asset-hub-eth-rpc.polkadot.io',
chainId: 420420421,
};

const mnemonic = 'INSERT_MNEMONIC';
const contractName = 'Storage';
const contractAddress = 'INSERT_CONTRACT_ADDRESS';
const checkAddress = 'INSERT_ADDRESS_TO_CHECK';
const newNumber = 42;

interactWithStorageContract(
contractName,
contractAddress,
mnemonic,
providerConfig,
newNumber,
);
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
const { compile } = require('@parity/revive');
const { readFileSync, writeFileSync } = require('fs');
const { basename, join } = require('path');

const compileContract = async (solidityFilePath, outputDir) => {
try {
// Read the Solidity file
const source = readFileSync(solidityFilePath, 'utf8');

// Construct the input object for the compiler
const input = {
[basename(solidityFilePath)]: { content: source },
};

console.log(`Compiling contract: ${basename(solidityFilePath)}...`);

// Compile the contract
const out = await compile(input);

for (const contracts of Object.values(out.contracts)) {
for (const [name, contract] of Object.entries(contracts)) {
console.log(`Compiled contract: ${name}`);

// Write the ABI
const abiPath = join(outputDir, `${name}.json`);
writeFileSync(abiPath, JSON.stringify(contract.abi, null, 2));
console.log(`ABI saved to ${abiPath}`);

// Write the bytecode
const bytecodePath = join(outputDir, `${name}.polkavm`);
writeFileSync(
bytecodePath,
Buffer.from(contract.evm.bytecode.object, 'hex'),
);
console.log(`Bytecode saved to ${bytecodePath}`);
}
}
} catch (error) {
console.error('Error compiling contracts:', error);
}
};

const solidityFilePath = './Storage.sol';
const outputDir = '.';

compileContract(solidityFilePath, outputDir);
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
const { JsonRpcProvider } = require('ethers');

const createProvider = (rpcUrl, chainId, chainName) => {
const provider = new JsonRpcProvider(rpcUrl, {
chainId: chainId,
name: chainName,
});

return provider;
};

const PROVIDER_RPC = {
rpc: 'INSERT_RPC_URL',
chainId: 'INSERT_CHAIN_ID',
name: 'INSERT_CHAIN_NAME',
};

createProvider(PROVIDER_RPC.rpc, PROVIDER_RPC.chainId, PROVIDER_RPC.name);
Original file line number Diff line number Diff line change
@@ -0,0 +1,92 @@
const { writeFileSync, existsSync, readFileSync } = require('fs');
const { join } = require('path');
const { ethers, JsonRpcProvider } = require('ethers');

const codegenDir = join(__dirname);

const createProvider = (rpcUrl, chainId, chainName) => {
const provider = new JsonRpcProvider(rpcUrl, {
chainId: chainId,
name: chainName,
});

return provider;
};

const getAbi = (contractName) => {
try {
return JSON.parse(
readFileSync(join(codegenDir, `${contractName}.json`), 'utf8'),
);
} catch (error) {
console.error(
`Could not find ABI for contract ${contractName}:`,
error.message,
);
throw error;
}
};

const getByteCode = (contractName) => {
try {
return `0x${readFileSync(join(codegenDir, `${contractName}.polkavm`)).toString('hex')}`;
} catch (error) {
console.error(
`Could not find bytecode for contract ${contractName}:`,
error.message,
);
throw error;
}
};

const deployContract = async (contractName, mnemonic, providerConfig) => {
console.log(`Deploying ${contractName}...`);

try {
// Create a provider
const provider = createProvider(
providerConfig.rpc,
providerConfig.chainId,
providerConfig.name,
);

// Derive the wallet from the mnemonic
const walletMnemonic = ethers.Wallet.fromPhrase(mnemonic);
const wallet = walletMnemonic.connect(provider);

// Create the contract factory
const factory = new ethers.ContractFactory(
getAbi(contractName),
getByteCode(contractName),
wallet,
);

// Deploy the contract
const contract = await factory.deploy();
await contract.waitForDeployment();

const address = await contract.getAddress();
console.log(`Contract ${contractName} deployed at: ${address}`);

// Save the deployed address
const addressesFile = join(codegenDir, 'contract-address.json');
const addresses = existsSync(addressesFile)
? JSON.parse(readFileSync(addressesFile, 'utf8'))
: {};
addresses[contractName] = address;

writeFileSync(addressesFile, JSON.stringify(addresses, null, 2), 'utf8');
} catch (error) {
console.error(`Failed to deploy contract ${contractName}:`, error);
}
};

const providerConfig = {
rpc: 'https://westend-asset-hub-eth-rpc.polkadot.io',
chainId: 420420421,
name: 'westend-asset-hub',
};

const mnemonic = 'INSERT_MNEMONIC';

deployContract('Storage', mnemonic, providerConfig);
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
const { JsonRpcProvider } = require('ethers');

const createProvider = (rpcUrl, chainId, chainName) => {
const provider = new JsonRpcProvider(rpcUrl, {
chainId: chainId,
name: chainName,
});

return provider;
};

const PROVIDER_RPC = {
rpc: 'https://westend-asset-hub-eth-rpc.polkadot.io',
chainId: 420420421,
name: 'westend-asset-hub',
};

const main = async () => {
try {
const provider = createProvider(
PROVIDER_RPC.rpc,
PROVIDER_RPC.chainId,
PROVIDER_RPC.name,
);
const latestBlock = await provider.getBlockNumber();
console.log(`Latest block: ${latestBlock}`);
} catch (error) {
console.error('Error connecting to Asset Hub: ' + error.message);
}
};

main();
Loading

0 comments on commit 8b9f51c

Please sign in to comment.