NEWTON

NEWTON


Popular tags

    How can I write contract memory with starknetjs?

    Asked

    23 days ago

    8

    views


    0

    How can I write contract memory with starknetjs?

      starknetjscairostarknet

    Newton

    asked

    23 days ago


    1 answers

    0

    Accepted answer

    ✍️ Write contract memory, with invoke :

    To increase the balance, you need in addition a connected and funded Account. You have to use the invoke function: contract.invoke("function_name",[params]) After the invoke function, you have to wait for the incorporation of the modification of Balance in the network, with await provider.waitForTransaction(transaction_hash) Here an example to increase and check the balance :

    //initialize Provider const provider = new Provider({ sequencer: { network: "goerli-alpha" } }); // connect your account. To adapt to your own account : const privateKey0 = process.env.OZ_ACCOUNT_PRIVATE_KEY; const account0Address = "0x123....789"; const starkKeyPair0 = ec.getKeyPair(privateKey0); const account0 = new Account(provider, account0Address, starkKeyPair0); // Connect the deployed Test contract in Tesnet const testAddress = "0x5f7cd1fd465baff2ba9d2d1501ad0a2eb5337d9a885be319366b5205a414fdd"; // read abi of Test contract const { abi: testAbi } = await provider.getClassAt(testAddress); if (testAbi === undefined) { throw new Error("no abi.") }; const myTestContract = new Contract(testAbi, testAddress, provider); // Connect account with the contract myTestContract.connect(account0); // Interactions with the contract with call & invoke const bal1 = await myTestContract.call("get_balance"); console.log("Initial balance =", bal1.res.toString()); const resu = await myTestContract.invoke("increase_balance", [10, 30]); await provider.waitForTransaction(resu.transaction_hash); const bal2 = await myTestContract.call("get_balance"); console.log("Initial balance =", bal2.res.toString());

    Write contract memory, with Account.execute :

    If you have to invoke a function of a contract that need the proof that you have the private key of the account, you have to invoke this function with account.execute.We will see this case more in detail in ERC20 scripts, but in summary, you uses this command with the following parameters :

    • address of the contract to invoke
    • name of the function to invoke
    • and array of parameters for this function
    const executeHash = await account.execute( { contractAddress: myContractAddress, entrypoint: 'transfer', calldata: stark.compileCalldata({ recipient: receiverAddress, amount: ['10'] }) } ); await provider.waitForTransaction(executeHash.transaction_hash);

    Newton

    answered

    23 days ago

    Your answer

    NEWTON

    NEWTON