首页 > 解决方案 > 与文本存储以太坊的智能合约

问题描述

我正在尝试在以太坊网络智能合约上创建一个简单的“文本编辑器”。我想做一个数据输入函数,它收集字符串中的文本和一个收集文本位置的 BYTES10 变量。您必须整齐地存储文本,以便以后可以访问它。而且您应该能够输入新文本而无需替换旧文本。然后是一个输出函数,它返回文本和坐标,所有这些从合同开始就进入网络。还有一个功能,允许您删除数据,以防输入错误。到目前为止我有这个代码:

    pragma solidity <0.9.0;
    contract texteditor {
        struct book {
            string block;
            bytes10 coordinates;
        }
        book [] public books;
        function save(string calldata _blocks, bytes10   _coordinates) public{
            books.push(book(_blocks, _coordinates));
        }
        function read()view public returns (string){
            return books[_block][_coordinates];
        }
        function remove(string _blocks, bytes10 _coordinates) private {
            delete book[_blocks][_coordinates];
        }}

保存文本的功能我觉得还可以,但是其他两个我在编译时遇到问题,我不知道是因为编译器版本还是因为功能不对。我在博客和有关此主题的其他帮助中找到的信息,显然在编译器版本方面已经过时,并且往往会给我带来问题。我想我必须做一个映射,但我还没有找到方法。我很感激你能给我的任何帮助,让我在这方面前进。非常感谢您的宝贵时间。

标签: functionblockchainethereumsoliditysmartcontracts

解决方案


pragma solidity ^0.8.4;
// SPDX-License-Identifier: MIT

contract texteditor {
     uint256 public id=0;

struct book {
    string block;
    string coordinates;
}

mapping(uint256=>mapping(uint256 => book)) bookStore;
mapping(uint256=>uint256) bookBlockIndex;

function save(uint256 bookId,string calldata _block, string calldata _coordinates) public{
    book memory temp_book =  book(_block,_coordinates);
    bookStore[bookId][bookBlockIndex[bookId]]=temp_book;
    bookBlockIndex[bookId]++;
}

function read_book(uint256 bookid,uint256 bookBlockid)view public returns (string memory,string memory){
    return (bookStore[bookid][bookBlockid].block,bookStore[bookid][bookBlockid].coordinates);
}

function remove_book(uint bookid,uint256 bookBlockid) public {
    delete bookStore[bookid][bookBlockid];
}

}

这可能会有所帮助


推荐阅读