Interact with a deployed contract | Besu documentation (2024)

You can get started with the Developer Quickstart to rapidly generate local blockchain networks.

This tutorial shows you how to interact with smart contracts that have been deployed to a network.

Prerequisites

  • A network with a deployed smart contract as in the deploying smart contracts tutorial

Interact with public contracts

This tutorial uses the SimpleStorage.sol contract:

pragma solidity ^0.7.0;

contract SimpleStorage {
uint public storedData;

constructor(uint initVal) public {
storedData = initVal;
}

function set(uint x) public {
storedData = x;
}

function get() view public returns (uint retVal) {
return storedData;
}
}

Once the contract is deployed, you can perform a read operation using the get function call and a write operation using the set function call. This tutorial uses the web3js library to interact with the contract. A full example of these calls can be found in the Developer Quickstart.

1. Perform a read operation

To perform a read operation, you need the address that the contract was deployed to and the contract's ABI. The contract's ABI can be obtained from compiling the contract; see the deploying smart contracts tutorial for an example.

Use the web3.eth.Contract object to create a new instance of the smart contract, then make the get function call from the contract's list of methods, which will return the value stored:

async function getValueAtAddress(
host,
deployedContractAbi,
deployedContractAddress,
) {
const web3 = new Web3(host);
const contractInstance = new web3.eth.Contract(
deployedContractAbi,
deployedContractAddress,
);
const res = await contractInstance.methods.get().call();
console.log("Obtained value at deployed contract is: " + res);
return res;
}

2. Perform a write operation

To perform a write operation, send a transaction to update the stored value. As with the get call, you need to use the address that the contract was deployed to and the contract's ABI. The account address must correspond to an actual account with some ETH in it to perform the transaction. Because Besu doesn't manage accounts, this address is the address you use in Web3Signer (or equivalent) to manage your accounts.

Make the set call passing in your account address, value as the updated value of the contract, and the amount of gas you are willing to spend for the transaction:

// You need to use the accountAddress details provided to Besu to send/interact with contracts
async function setValueAtAddress(
host,
accountAddress,
value,
deployedContractAbi,
deployedContractAddress,
) {
const web3 = new Web3(host);
const contractInstance = new web3.eth.Contract(
deployedContractAbi,
deployedContractAddress,
);
const res = await contractInstance.methods
.set(value)
.send({ from: accountAddress, gasPrice: "0xFF", gasLimit: "0x24A22" });
return res;
}

3. Verify an updated value

To verify that a value has been updated, perform a get call after a set update call.

Interact with private contracts

This private contracts example uses the same SimpleStorage.sol contract as in the public contracts example, but it uses the web3js-quorum library and the generateAndSendRawTransaction method to interact with the contract. Both read and write operations are performed using the generateAndSendRawTransaction API call. A full example can be found in the Developer Quickstart.

1. Perform a read operation

As in the public contracts example, to perform a read operation, you need the address that the contract was deployed to and the contract's ABI. You also need your private and public keys and the recipient's public key.

Use the web3.eth.Contract object to create a new instance of the smart contract, extract the signature of function's ABI for the get method, and then use this value as the data parameter for the generateAndSendRawTransaction transaction.

The keys remain the same for the sender and recipient, and the to field is the contract's address. Once you make the request, you receive a transactionHash, which you can use to get a transactionReceipt containing the value stored:

async function getValueAtAddress(
clientUrl,
address,
contractAbi,
fromPrivateKey,
fromPublicKey,
toPublicKey,
) {
const Web3 = require("web3");
const Web3Quorum = require("web3js-quorum");
const web3 = new Web3Quorum(new Web3("http://localhost:22000"));
// eslint-disable-next-line no-underscore-dangle
const functionAbi = contract._jsonInterface.find((e) => {
return e.name === "get";
});
const functionParams = {
to: address,
data: functionAbi.signature,
privateKey: fromPrivateKey,
privateFrom: fromPublicKey,
privateFor: [toPublicKey],
};
const transactionHash = await web3quorum.priv.generateAndSendRawTransaction(
functionParams,
);
// console.log(`Transaction hash: ${transactionHash}`);
const result = await web3quorum.priv.waitForTransactionReceipt(
transactionHash,
);
console.log(
"" + nodeName + " value from deployed contract is: " + result.output,
);
return result;
}

2. Perform a write operation

Performing a write operation is almost the same process as the read operation, except that you encode the new value to the set function's ABI, and then append these arguments to the set function's ABI and use this as the data field:

async function setValueAtAddress(
clientUrl,
address,
value,
contractAbi,
fromPrivateKey,
fromPublicKey,
toPublicKey,
) {
const Web3 = require("web3");
const Web3Quorum = require("web3js-quorum");
const web3 = new Web3Quorum(new Web3("http://localhost:22000"));
// eslint-disable-next-line no-underscore-dangle
const functionAbi = contract._jsonInterface.find((e) => {
return e.name === "set";
});
const functionArgs = web3quorum.eth.abi
.encodeParameters(functionAbi.inputs, [value])
.slice(2);
const functionParams = {
to: address,
data: functionAbi.signature + functionArgs,
privateKey: fromPrivateKey,
privateFrom: fromPublicKey,
privateFor: [toPublicKey],
};
const transactionHash = await web3quorum.priv.generateAndSendRawTransaction(
functionParams,
);
console.log(`Transaction hash: ${transactionHash}`);
const result = await web3quorum.priv.waitForTransactionReceipt(
transactionHash,
);
return result;
}

3. Verify an updated value

To verify that a value has been updated, perform a get call after a set update call.

Interact with a deployed contract | Besu documentation (2024)

FAQs

How do I find the contract address of a deployed contract? ›

Contracts can deploy other contracts using the SDK deployer() method. The contract address of the deployed contract is deterministic and is derived from the address of the deployer. The deployment also has to be authorized by the deployer.

How to interact directly with a smart contract? ›

Interacting with Smart Contracts using Etherscan​
  1. Step 1: Go to the Etherscan Sepolia Block Explorer.
  2. Step 2: Go to the contract page by searching the contract address. ...
  3. Step 3: On the contract's page, navigate to the Contract tab and click on Read Contract.
Aug 13, 2024

How do you interact with a deployed contract? ›

Interact with deployed smart contracts
  1. Perform a read operation​ To perform a read operation, you need the address that the contract was deployed to and the contract's ABI. ...
  2. Perform a write operation​ ...
  3. Verify an updated value​ ...
  4. Perform a read operation​ ...
  5. Perform a write operation​ ...
  6. Verify an updated value​

What is deployed contract? ›

Deploying a smart contract means sending a transaction with a blank to field. When Ethereum sees a transaction with a blank to field, it will create a new contract. If you send token to someone, "to" field will be the address of the receiver, but for the contract creation transaction to is empty.

How to get the address of a contract? ›

The contract address can be found on the home page of the NFT collection or next to a particular NFTs token ID and other metadata. When buying an NFT, always make sure it features the same contract address as other NFTs in the collection.

Do you need someone's address for a contract? ›

At the very least, there will need to be identifying information about both parties, including the names of the individuals or businesses, as well as their legal mailing addresses. The second-most basic inclusion in a contract will be the specific terms of the agreement between the parties.

What is contract interaction? ›

Contract interactions, in blockchains networks, refers to the process of communicating with deployed smart contracts. This involves querying contract information or executing specific functions defined within the contract. Interactions can include tasks ranging from checking balances to transferring tokens, and so on.

What are the four steps in executing a smart contract? ›

2 concisely depicts the lifecycle of a smart contract in four fundamental steps which are (1) agreement amongst the parties, (2) establishment of smart contract, (3) verification that the criteria are fulfilled and (4) execution of value transfer (e.g. money and energy ...

How to use a smart contract address? ›

Once you have the smart contract address, you can input it into the search bar of the tool to access the smart contract's page. Here, you may find a variety of information such as the creator address, token name, tokens held in the contract, and so on.

Where can I find smart contracts? ›

An individual can see the transaction record for a smart contract that occurred on the blockchain by looking at a block explorer. In the figures below, we discuss the information available for smart contracts on the Ethereum Blockchain as shown on numerous websites such as www.etherscan.io.

What happens if your contract ends while deployed? ›

When you join the military, you typically sign a contract for a fixed period of active duty. Should your end of service date happen to fall during a deployment, you would still be expected to complete the deployment.

How to deploy a smart contract? ›

Deploying smart contracts onchain requires a wallet and ETH. The ETH pays for the work required by the Ethereum network to add the contract to the blockchain and store the variables. The wallet holds the ETH that you need to pay for the transaction.

What are examples of smart contracts? ›

Now you understand how smart contracts work, let's look at some smart contract examples from the real world.
  • Clinical trials. Data sharing between institutions is vital to effective clinical trials. ...
  • Music industry. ...
  • Supply chain management. ...
  • Property ownership. ...
  • Mortgages. ...
  • Retail. ...
  • Digital identity. ...
  • Recording financial data.

How long are deployment contracts? ›

State active duty missions usually run from 15-60 days, while federal deployments are usually a minimum of 12 months.

How do I find government contract information? ›

The FPDS reports transition is complete and the DataBank is the only place to go to create and run contract data reports. If you are searching for contract data (i.e., searching for specific contracts), you must do so at FPDS.gov , which remains the authoritative source for contract data.

How is contract address determined? ›

The contract address is determined by the sender's address and nonce. When a contract is created, its address is computed by taking the Keccak-25 has of RLP-encoded list of the creator's address and his nonce, and then taking the rightmost 20 bytes of this hash.

What is your contract address? ›

A contract address is a unique identifier for a smart contract deployed on a blockchain. Smart contracts are self-executing agreements that follow predefined rules and automatically enforce actions when specific conditions are met.

How do you determine whether an address is a contract address? ›

Three ways to detect if an address is a smart contract
  1. Check if msg. sender == tx. origin. ...
  2. The second (and recommended way) is to measure the bytecode size of the address using code. length. ...
  3. The third is using codehash and is not recommended because it has the same limitations as code. length with additional complexity.
Apr 5, 2024

Top Articles
Excel Forum
Dostosowywanie jasności i temperatury kolorów na iPhonie lub iPadzie - Wsparcie Apple (PL)
Public Opinion Obituaries Chambersburg Pa
417-990-0201
THE 10 BEST Women's Retreats in Germany for September 2024
Find All Subdomains
Fallout 4 Pipboy Upgrades
Pollen Count Los Altos
Olivia Ponton On Pride, Her Collection With AE & Accidentally Coming Out On TikTok
Revitalising marine ecosystems: D-Shape’s innovative 3D-printed reef restoration solution - StartmeupHK
Slope Unblocked Minecraft Game
‘Accused: Guilty Or Innocent?’: A&E Delivering Up-Close Look At Lives Of Those Accused Of Brutal Crimes
Drago Funeral Home & Cremation Services Obituaries
Top tips for getting around Buenos Aires
Craiglist Galveston
Slope Tyrones Unblocked Games
Directions To Advance Auto
Where to Find Scavs in Customs in Escape from Tarkov
Azpeople View Paycheck/W2
Jobs Hiring Near Me Part Time For 15 Year Olds
Crossword Help - Find Missing Letters & Solve Clues
John Deere 44 Snowblower Parts Manual
The Goonies Showtimes Near Marcus Rosemount Cinema
Kristy Ann Spillane
Mawal Gameroom Download
Gus Floribama Shore Drugs
Red Sox Starting Pitcher Tonight
How to Use Craigslist (with Pictures) - wikiHow
Nacogdoches, Texas: Step Back in Time in Texas' Oldest Town
Autopsy, Grave Rating, and Corpse Guide in Graveyard Keeper
Jambus - Definition, Beispiele, Merkmale, Wirkung
Mississippi State baseball vs Virginia score, highlights: Bulldogs crumble in the ninth, season ends in NCAA regional
Jennifer Reimold Ex Husband Scott Porter
Grapes And Hops Festival Jamestown Ny
Cookie Clicker The Advanced Method
Noaa Duluth Mn
Below Five Store Near Me
Kent And Pelczar Obituaries
ESA Science & Technology - The remarkable Red Rectangle: A stairway to heaven? [heic0408]
Windshield Repair & Auto Glass Replacement in Texas| Safelite
VDJdb in 2019: database extension, new analysis infrastructure and a T-cell receptor motif compendium
Doublelist Paducah Ky
RubberDucks Front Office
25 Hotels TRULY CLOSEST to Woollett Aquatics Center, Irvine, CA
Plumfund Reviews
Walmart Front Door Wreaths
De boeken van Val McDermid op volgorde
What Time Do Papa John's Pizza Close
Competitive Comparison
Denys Davydov - Wikitia
Who We Are at Curt Landry Ministries
Latest Posts
Article information

Author: Clemencia Bogisich Ret

Last Updated:

Views: 5990

Rating: 5 / 5 (80 voted)

Reviews: 95% of readers found this page helpful

Author information

Name: Clemencia Bogisich Ret

Birthday: 2001-07-17

Address: Suite 794 53887 Geri Spring, West Cristentown, KY 54855

Phone: +5934435460663

Job: Central Hospitality Director

Hobby: Yoga, Electronics, Rafting, Lockpicking, Inline skating, Puzzles, scrapbook

Introduction: My name is Clemencia Bogisich Ret, I am a super, outstanding, graceful, friendly, vast, comfortable, agreeable person who loves writing and wants to share my knowledge and understanding with you.