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
Strategies for Success (Rutgers NJAES)
Top Samsung Phone Update Issues and How to Fix Them-Dr.Fone
Lowe's Garden Fence Roll
Cintas Pay Bill
Lifewitceee
Kansas Craigslist Free Stuff
Mylaheychart Login
Best Transmission Service Margate
Graveguard Set Bloodborne
Jesus Revolution Showtimes Near Chisholm Trail 8
Synq3 Reviews
Winterset Rants And Raves
Babyrainbow Private
Bestellung Ahrefs
Walmart End Table Lamps
No Hard Feelings Showtimes Near Cinemark At Harlingen
Wausau Obits Legacy
Vrachtwagens in Nederland kopen - gebruikt en nieuw - TrucksNL
1989 Chevy Caprice For Sale Craigslist
Teekay Vop
Encyclopaedia Metallum - WikiMili, The Best Wikipedia Reader
Elbert County Swap Shop
Обзор Joxi: Что это такое? Отзывы, аналоги, сайт и инструкции | APS
Accuradio Unblocked
Watertown Ford Quick Lane
Radical Red Ability Pill
The Collective - Upscale Downtown Milwaukee Hair Salon
Mobile crane from the Netherlands, used mobile crane for sale from the Netherlands
Marlene2295
Desales Field Hockey Schedule
DIY Building Plans for a Picnic Table
Transformers Movie Wiki
Leland Nc Craigslist
M3Gan Showtimes Near Cinemark North Hills And Xd
Goodwill Houston Select Stores Photos
Finland’s Satanic Warmaster’s Werwolf Discusses His Projects
Ursula Creed Datasheet
PruittHealth hiring Certified Nursing Assistant - Third Shift in Augusta, GA | LinkedIn
Mytime Maple Grove Hospital
Other Places to Get Your Steps - Walk Cabarrus
Seminary.churchofjesuschrist.org
The best specialist spirits store | Spirituosengalerie Stuttgart
2017 Ford F550 Rear Axle Nut Torque Spec
Joblink Maine
Dragon Ball Super Card Game Announces Next Set: Realm Of The Gods
Vci Classified Paducah
Devotion Showtimes Near Showplace Icon At Valley Fair
Skyward Login Wylie Isd
Tommy Gold Lpsg
Craigslist.raleigh
Craigslist Centre Alabama
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.