String – How to Split a String in Solidity

slicestring

I'm using the OpenZeppelin Preset of the 1155 Token Standard. (https://github.com/OpenZeppelin/openzeppelin-contracts/tree/master/contracts/token/ERC1155/presets)
I'm able to mint tokens with that and I'm able to transfer 4 arguments with the transaction:

address (of the receiver)
id (of the Token)
amount (amount of Tokens)
data (additional data in bytes format)

I use the id and data for transmitting data
Now I'm confronted with the issue, that I want to transfer two variables (in string format) in the data field.
First of all I have to convert the field data from bytes into string.
Then I want to split the content of the data field into two variables.
The one variable got 13 characters, the other one 15.
Then I pobably have to assign each split to these two variables.
With emit Event I transfer both variables on the blockchain and can access it in the Logs.

Please pardon, I'm a bloody noob in coding with solidity.
Does someone knows how i can formulate a function that converts bytes to string, split the string into two parts and then assign it to new variables?

Best Answer

If it is yourself who is packing those two strings s1 and s2 into one bytes, then you may:

  1. At the source (in JavaScript):

    const data = abiCoder.encode(["string", "string"], [s1, s2])

  2. Pass data via the contract function

  3. At the receiving end (in Solidity):

    (string memory s1, string memory s2) = abi.decode(data, (string, string))

Doing it this way avoids string operations altogether.

P.S. Keep in mind that data is not intended for consumption by the transfer function itself, but it is intended for consumption by the receipient of the transfer (if that recipient is a compliant ERC1155TokenReceiver contract.)

Related Topic