본문으로 건너뛰기
이 페이지는 영어로 된 기계 번역을 사용하므로 오류나 불명확한 언어가 포함될 수 있습니다. 가장 정확한 정보는 영어 원문을 참조하시기 바랍니다. 잦은 업데이트로 인해 일부 콘텐츠는 원래 영어로 되어 있을 수 있습니다. Crowdin에서 이 페이지의 번역을 개선하는 데 동참하여 도움을 주세요. (Crowdin translation page, Contributing guide)

Write

You can make a "transaction" interacting with a Smart Contract when you **need to update some state ** in the contract.

Import necessary classes from the Web3j and kaia libraries(web3j-ext).

Connect to the kaia blockchain using Web3j and specify the URL

Create KlayCredentials using the private key

Define smart contract address to interact with

Define gas price and gas limit for contract transactions

Create a gas provider with static gas price and gas limit

Load the contract using contact address, Web3j instance, credentials, and gas provider. You can read and write the contract through this instance

Get the current number stored in the contract before writing

Increment the number stored in the contract by calling counter.increment().send()

Get the updated number stored in the contract after writing

WriteContractExample.java

package org.web3j.example.contracts;
import java.math.BigInteger;
import org.web3j.crypto.KlayCredentials;
import org.web3j.tx.response.PollingTransactionReceiptProcessor;
import org.web3j.tx.response.TransactionReceiptProcessor;
import org.web3j.example.keySample;
import org.web3j.protocol.http.HttpService;
import org.web3j.protocol.kaia.Web3j;
import org.web3j.tx.gas.StaticGasProvider;
public class WriteContractExample {
/**
* @throws Exception
*
*/
public static void run() throws Exception {
Web3j web3j = Web3j.build(new HttpService(keySample.BAOBAB_URL));
KlayCredentials credentials = KlayCredentials.create(keySample.LEGACY_KEY_privkey);
String contractAddr = "0x95Be48607498109030592C08aDC9577c7C2dD505";
BigInteger GAS_PRICE = BigInteger.valueOf(50000000000L);
BigInteger GAS_LIMIT = BigInteger.valueOf(6721950);
StaticGasProvider gasProvider = new StaticGasProvider(GAS_PRICE, GAS_LIMIT);
Counter counter = Counter.load(contractAddr, web3j, credentials.convertToCredentials(), gasProvider);
// Get number before Contract Write
System.out.println("number before : " + counter.number().send());
// Contract Write (increment function)
counter.increment().send();
// Get number after Contract Write
System.out.println("number after : " + counter.number().send());
}
}

output

❯ java WriteContractExample.java
number before : 297
number after : 298

페이지를 개선해 주세요