Skip to content

Commit abc3875

Browse files
nhussein11brunopgalvaoCopilot0xlukemeshaben
authored
Add deploy basic contract (new IA) (#1126)
* Update navigation and documentation for basic contract deployment * fix: llms * Fix navigation entry for deploying a basic contract (PVM) in .nav.yml * Update deployment guides for basic EVM and PVM contracts, specifying exact package versions and enhancing next steps with links to ERC-20 and NFT deployment guides on Polkadot Hub. * Update smart-contracts/cookbook/smart-contracts/deploy-basic-pvm.md Co-authored-by: Bruno Galvao <[email protected]> * Update smart-contracts/cookbook/smart-contracts/deploy-basic-pvm.md Co-authored-by: Copilot <[email protected]> * Fix: adding reference to polkadot hub * fix: llms * fix evm * fix pvm * fix * fresh llms * Update bytecode writing method in EVM deployment guide and remove TODO reference * hiding pvm content * add tabbed content * llms * merge issue * llms * break deploy-basic-evm in small sections * fix naming * feedback * fix * feedback * Apply suggestions from code review Co-authored-by: Erin Shaben <[email protected]> * feedback * Apply suggestions from code review --------- Co-authored-by: Bruno Galvao <[email protected]> Co-authored-by: Copilot <[email protected]> Co-authored-by: 0xlukem <[email protected]> Co-authored-by: Lucas Malizia <[email protected]> Co-authored-by: Erin Shaben <[email protected]>
1 parent c02562b commit abc3875

File tree

33 files changed

+8780
-379
lines changed

33 files changed

+8780
-379
lines changed

.ai/categories/smart-contracts.md

Lines changed: 3516 additions & 376 deletions
Large diffs are not rendered by default.

.ai/pages/smart-contracts-cookbook-smart-contracts-.deploy-basic-pvm.md

Lines changed: 472 additions & 0 deletions
Large diffs are not rendered by default.
Lines changed: 239 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,239 @@
1+
---
2+
title: JavaScript with Ethers.js
3+
description: Learn how to deploy a basic smart contract to Polkadot Hub using Ethers.js, best for lightweight, programmatic deployments and application integration.
4+
categories: Smart Contracts
5+
url: https://docs.polkadot.com/smart-contracts/cookbook/smart-contracts/deploy-basic-contract/deploy-basic-ethers-js/
6+
---
7+
8+
[Ethers.js](https://docs.ethers.org/v6/){target=\_blank} provides a lightweight approach for deploying contracts using pure JavaScript. This method is ideal for developers who want programmatic control over the deployment process or need to integrate contract deployment into existing applications.
9+
10+
**Prerequisites:**
11+
12+
- Basic understanding of Solidity programming.
13+
- [Node.js](https://nodejs.org/en/download){target=\_blank} v22.13.1 or later.
14+
- Test tokens for gas fees (available from the [Polkadot faucet](https://faucet.polkadot.io/){target=\_blank}).
15+
- A wallet with a private key for signing transactions.
16+
17+
### Setup
18+
19+
First, initialize your project and install dependencies:
20+
21+
```bash
22+
mkdir ethers-deployment
23+
cd ethers-deployment
24+
npm init -y
25+
26+
```
27+
28+
### Create and Compile Your Contract
29+
30+
Create a simple storage contract in `contracts/Storage.sol`:
31+
32+
```solidity title="contracts/Storage.sol"
33+
// SPDX-License-Identifier: MIT
34+
pragma solidity ^0.8.9;
35+
36+
contract Storage {
37+
uint256 private storedNumber;
38+
39+
function store(uint256 num) public {
40+
storedNumber = num;
41+
}
42+
43+
function retrieve() public view returns (uint256) {
44+
return storedNumber;
45+
}
46+
}
47+
```
48+
49+
Create a compilation script `compile.js`:
50+
51+
```javascript title="compile.js"
52+
const solc = require('solc');
53+
const { readFileSync, writeFileSync } = require('fs');
54+
const { basename, join } = require('path');
55+
56+
const compileContract = async (solidityFilePath, outputDir) => {
57+
try {
58+
// Read the Solidity file
59+
const source = readFileSync(solidityFilePath, 'utf8');
60+
61+
// Construct the input object for the compiler
62+
const input = {
63+
language: 'Solidity',
64+
sources: {
65+
[basename(solidityFilePath)]: { content: source },
66+
},
67+
settings: {
68+
outputSelection: {
69+
'*': {
70+
'*': ['*'],
71+
},
72+
},
73+
},
74+
};
75+
76+
console.log(`Compiling contract: ${basename(solidityFilePath)}...`);
77+
78+
// Compile the contract
79+
const output = JSON.parse(solc.compile(JSON.stringify(input)));
80+
81+
if (output.errors) {
82+
output.errors.forEach(error => {
83+
console.error('Compilation error:', error.message);
84+
});
85+
return;
86+
}
87+
88+
for (const contracts of Object.values(output.contracts)) {
89+
for (const [name, contract] of Object.entries(contracts)) {
90+
console.log(`Compiled contract: ${name}`);
91+
92+
// Write the ABI
93+
const abiPath = join(outputDir, `${name}.json`);
94+
writeFileSync(abiPath, JSON.stringify(contract.abi, null, 2));
95+
console.log(`ABI saved to ${abiPath}`);
96+
97+
// Write the bytecode
98+
const bytecodePath = join(outputDir, `${name}.bin`);
99+
writeFileSync(bytecodePath,
100+
Buffer.from(
101+
contract.evm.bytecode.object,
102+
'hex'
103+
));
104+
console.log(`Bytecode saved to ${bytecodePath}`);
105+
}
106+
}
107+
} catch (error) {
108+
console.error('Error compiling contracts:', error);
109+
}
110+
};
111+
112+
const solidityFilePath = join(__dirname, 'contracts/Storage.sol');
113+
const outputDir = join(__dirname, 'contracts');
114+
115+
compileContract(solidityFilePath, outputDir);
116+
```
117+
118+
Run the compilation:
119+
120+
```bash
121+
node compile.js
122+
```
123+
124+
### Deploy the Contract
125+
126+
Create a deployment script `deploy.js`:
127+
128+
```javascript title="deploy.js"
129+
const { writeFileSync, existsSync, readFileSync } = require('fs');
130+
const { join } = require('path');
131+
const { ethers, JsonRpcProvider } = require('ethers');
132+
133+
const codegenDir = join(__dirname);
134+
135+
// Creates a provider with specified RPC URL and chain details
136+
const createProvider = (rpcUrl, chainId, chainName) => {
137+
const provider = new JsonRpcProvider(rpcUrl, {
138+
chainId: chainId,
139+
name: chainName,
140+
});
141+
return provider;
142+
};
143+
144+
// Reads and parses the ABI file for a given contract
145+
const getAbi = (contractName) => {
146+
try {
147+
return JSON.parse(
148+
readFileSync(join(codegenDir, 'contracts', `${contractName}.json`), 'utf8'),
149+
);
150+
} catch (error) {
151+
console.error(
152+
`Could not find ABI for contract ${contractName}:`,
153+
error.message,
154+
);
155+
throw error;
156+
}
157+
};
158+
159+
// Reads the compiled bytecode for a given contract
160+
const getByteCode = (contractName) => {
161+
try {
162+
const bytecodePath = join(
163+
codegenDir,
164+
'contracts',
165+
`${contractName}.bin`,
166+
);
167+
return `0x${readFileSync(bytecodePath).toString('hex')}`;
168+
} catch (error) {
169+
console.error(
170+
`Could not find bytecode for contract ${contractName}:`,
171+
error.message,
172+
);
173+
throw error;
174+
}
175+
};
176+
177+
const deployContract = async (contractName, mnemonic, providerConfig) => {
178+
console.log(`Deploying ${contractName}...`);
179+
180+
try {
181+
// Step 1: Set up provider and wallet
182+
const provider = createProvider(
183+
providerConfig.rpc,
184+
providerConfig.chainId,
185+
providerConfig.name,
186+
);
187+
const walletMnemonic = ethers.Wallet.fromPhrase(mnemonic);
188+
const wallet = walletMnemonic.connect(provider);
189+
190+
// Step 2: Create and deploy the contract
191+
const factory = new ethers.ContractFactory(
192+
getAbi(contractName),
193+
getByteCode(contractName),
194+
wallet,
195+
);
196+
const contract = await factory.deploy();
197+
await contract.waitForDeployment();
198+
199+
// Step 3: Save deployment information
200+
const address = await contract.getAddress();
201+
console.log(`Contract ${contractName} deployed at: ${address}`);
202+
203+
const addressesFile = join(codegenDir, 'contract-address.json');
204+
const addresses = existsSync(addressesFile)
205+
? JSON.parse(readFileSync(addressesFile, 'utf8'))
206+
: {};
207+
addresses[contractName] = address;
208+
writeFileSync(addressesFile, JSON.stringify(addresses, null, 2), 'utf8');
209+
} catch (error) {
210+
console.error(`Failed to deploy contract ${contractName}:`, error);
211+
}
212+
};
213+
214+
const providerConfig = {
215+
rpc: 'https://testnet-passet-hub-eth-rpc.polkadot.io',
216+
chainId: 420420422,
217+
name: 'polkadot-hub-testnet',
218+
};
219+
220+
const mnemonic = 'INSERT_MNEMONIC';
221+
222+
deployContract('Storage', mnemonic, providerConfig);
223+
```
224+
225+
Replace the `INSERT_MNEMONIC` placeholder with your actual mnemonic.
226+
227+
Execute the deployment:
228+
229+
```bash
230+
node deploy.js
231+
```
232+
233+
After running this script, your contract will be deployed to Polkadot Hub, and its address will be saved in `contract-address.json` within your project directory. You can use this address for future contract interactions.
234+
235+
### Next Steps
236+
237+
- Deploy an ERC-20 token on Polkadot Hub, either using the [Deploy an ERC-20](/smart-contracts/cookbook/smart-contracts/deploy-erc20) guide or the [Deploy an ERC-20 to Polkadot Hub](/smart-contracts/cookbook/smart-contracts/deploy-erc20) guide.
238+
- Deploy an NFT on Polkadot Hub, either using the [Deploy an NFT](/smart-contracts/cookbook/smart-contracts/deploy-nft) guide or the [Deploy an NFT to Polkadot Hub](/smart-contracts/cookbook/smart-contracts/deploy-nft) guide.
239+
- Check out in details each [development environment](/smart-contracts/dev-environments/).
Lines changed: 94 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,94 @@
1+
---
2+
title: Foundry
3+
description: Learn how to deploy a basic smart contract to Polkadot Hub using Foundry, excellent for developers who prefer fast, command-line driven development.
4+
categories: Smart Contracts
5+
url: https://docs.polkadot.com/smart-contracts/cookbook/smart-contracts/deploy-basic-contract/deploy-basic-foundry/
6+
---
7+
8+
[Foundry](https://getfoundry.sh/){target=\_blank} offers a fast, modular toolkit written in Rust. It's perfect for developers who prefer command-line interfaces and need high-performance compilation and deployment.
9+
10+
**Prerequisites:**
11+
12+
- Basic understanding of Solidity programming.
13+
- Test tokens for gas fees (available from the [Polkadot faucet](https://faucet.polkadot.io/){target=\_blank}).
14+
- A wallet with a private key for signing transactions.
15+
16+
### Setup
17+
18+
Install Foundry:
19+
20+
```bash
21+
curl -L https://foundry.paradigm.xyz | bash
22+
foundryup
23+
```
24+
25+
Initialize your project:
26+
27+
```bash
28+
forge init foundry-deployment
29+
cd foundry-deployment
30+
```
31+
32+
### Configure Foundry
33+
34+
Edit `foundry.toml`:
35+
36+
```toml
37+
[profile.default]
38+
src = "src"
39+
out = "out"
40+
libs = ["lib"]
41+
42+
[rpc_endpoints]
43+
polkadot_hub_testnet = "https://testnet-passet-hub-eth-rpc.polkadot.io"
44+
```
45+
46+
### Create Your Contract
47+
48+
Replace the default contract in `src/Storage.sol`:
49+
50+
```solidity title="src/Storage.sol"
51+
// SPDX-License-Identifier: MIT
52+
pragma solidity ^0.8.9;
53+
54+
contract Storage {
55+
uint256 private storedNumber;
56+
57+
function store(uint256 num) public {
58+
storedNumber = num;
59+
}
60+
61+
function retrieve() public view returns (uint256) {
62+
return storedNumber;
63+
}
64+
}
65+
```
66+
67+
### Compile
68+
69+
```bash
70+
forge build
71+
```
72+
73+
Verify the compilation by inspecting the bytecode:
74+
75+
```bash
76+
forge inspect Storage bytecode
77+
```
78+
79+
### Deploy
80+
81+
Deploy to Polkadot Hub TestNet:
82+
83+
```bash
84+
forge create Storage \
85+
--rpc-url polkadot_hub_testnet \
86+
--private-key YOUR_PRIVATE_KEY \
87+
--broadcast
88+
```
89+
90+
### Next Steps
91+
92+
- Deploy an ERC-20 token on Polkadot Hub, either using the [Deploy an ERC-20](/smart-contracts/cookbook/smart-contracts/deploy-erc20) guide or the [Deploy an ERC-20 to Polkadot Hub](/smart-contracts/cookbook/smart-contracts/deploy-erc20) guide.
93+
- Deploy an NFT on Polkadot Hub, either using the [Deploy an NFT](/smart-contracts/cookbook/smart-contracts/deploy-nft) guide or the [Deploy an NFT to Polkadot Hub](/smart-contracts/cookbook/smart-contracts/deploy-nft) guide.
94+
- Check out in details each [development environment](/smart-contracts/dev-environments/).

0 commit comments

Comments
 (0)