0

I have the below test contract. is it possible through the truffle console to call the function "testStruct" that takes as an argument a struct?

contract TestContract{

    struct TestStructArgs { 
        string title;
        string details;
    }
   
    function testStruct(TestStructArgs memory _params) external{      
    
    }
    function testStruct2(string  memory _params) external{      
    
    }
}

Its being defined as

'testStruct((string,string))': [Function: bound _createTxObject]

EDIT:

Im using Visual Studio Code with the "Truffle for VS Code extension" version 2.7.1 Im also using Ganache to deploy the contract into a local blockchain

Commands i execute on the VS console:

    truffle console --network ganache
    migrate --reset
    let contract = TestContract.deployed();
    const object = {title: "Hello", details: "Hey"};
    await contract.testStruct(object);
    

after this i get

    Uncaught TypeError: contract.testStruct is not a function
at evalmachine.<anonymous>:1:26
    

but all is ok if i execute

await contract.testStruct2("test");

1 Answer 1

1

You can pass an object with the same structure as the struct in solidity.

Here,

const object = {title: "Hello", details: "Hey"};
await contract.testStruct(object);

Then in the solidity function, you can have the same parameters as the struct.

mapping(address => TestStructArgs) mapp;
function testStruct(TestStructArgs memory _params) external{
    mapp[msg.sender].title = _params.title;
    mapp[msg.sender].details = _params.details;        
}

It's as simple as that. All this is possible easily since solidity resembles javascript to quite an extent. I hope this answers your query.

5
  • I did try this but i'm getting "instance.testStruct is not a function"
    – iamIcarus
    Commented Jan 23, 2023 at 18:47
  • Please provide more details.
    – vampireAb
    Commented Jan 24, 2023 at 4:55
  • thanks , i just updated my post with more details
    – iamIcarus
    Commented Jan 24, 2023 at 18:01
  • You got to await till the contract gets deployed. let contract = await TestContract.deployed(); This should do it.
    – vampireAb
    Commented Jan 25, 2023 at 4:19
  • thank you , that did it!
    – iamIcarus
    Commented Jan 25, 2023 at 18:31

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.