fix(contracts/git3.sol): fix the bug of delRef()

main
cyl19970726 2 years ago
parent 34b779ff30
commit 7187b1c036

@ -111,12 +111,10 @@ contract Git3 {
srs = nameToRefInfo[name]; srs = nameToRefInfo[name];
if (srs.hash1 == bytes32(0) && srs.hash2 == bytes8(0)) { if (srs.hash1 == bytes32(0) && srs.hash2 == bytes8(0)) {
// first store refHash // store refHash for the first time
require(refs.length <= uint256(uint192(int192(-1))),"refs exceed valid length"); require(refs.length <= uint256(uint192(int192(-1))),"refs exceed valid length");
_setRefInfo(nameToRefInfo[name],refHash,uint192(refs.length)); _setRefInfo(nameToRefInfo[name],refHash,uint192(refs.length));
console.log("refs_length:",refs.length);
refs.push(name); refs.push(name);
}else{ }else{
// only update refHash // only update refHash
@ -126,14 +124,19 @@ contract Git3 {
// delRef(path: string): Promise<Status> // delRef(path: string): Promise<Status>
function delRef(string memory name) public { function delRef(string memory name) public {
// only execute `sload` once to reduce gas consumption
refInfo memory srs; refInfo memory srs;
srs = nameToRefInfo[name]; srs = nameToRefInfo[name];
uint256 refsLen = refs.length;
require(srs.hash1 != bytes32(0) || srs.hash2 != bytes8(0),"Reference of this name does not exist"); require(srs.hash1 != bytes32(0) || srs.hash2 != bytes8(0),"Reference of this name does not exist");
refs[srs.index] = refs[refs.length - 1]; require(srs.index < refsLen,"System Error: Invalid index");
nameToRefInfo[refs[refs.length - 1]].index = srs.index; if (srs.index < refsLen-1){
delete refs[refs.length - 1]; refs[srs.index] = refs[refsLen - 1];
nameToRefInfo[refs[refsLen - 1]].index = srs.index;
}
refs.pop();
delete nameToRefInfo[name]; delete nameToRefInfo[name];
} }
} }

@ -88,12 +88,19 @@ describe("Git3 Test", function () {
expect(refs[0]).to.eql([data0,key0]); expect(refs[0]).to.eql([data0,key0]);
expect(refs[1]).to.eql([data1,key1]); expect(refs[1]).to.eql([data1,key1]);
expect(refs[2]).to.eql([data2,key2]); expect(refs[2]).to.eql([data2,key2]);
expect(refs.length).to.eql(3);
// check delRef // check delRef
await git3.delRef(key0); await git3.delRef(key0);
refs = await git3.listRefs(); refs = await git3.listRefs();
expect(refs[0]).to.eql([data2,key2]); expect(refs[0]).to.eql([data2,key2]);
expect(refs[1]).to.eql([data1,key1]); expect(refs[1]).to.eql([data1,key1]);
expect(refs.length).to.eql(2);
await git3.delRef(key1);
refs = await git3.listRefs();
expect(refs[0]).to.eql([data2,key2]);
expect(refs.length).to.eql(1);
}) })

Loading…
Cancel
Save