Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: tracking undelivered request Ids #11

Merged
merged 8 commits into from
Oct 24, 2023
Merged
Show file tree
Hide file tree
Changes from 6 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ coverage
coverage.json
typechain
*.DS_Store
.idea

# Hardhat files
artifacts
Expand Down
1 change: 0 additions & 1 deletion .gitmodules
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@

[submodule "lib/mech"]
path = lib/mech
url = https://github.com/gnosis/mech.git
Expand Down
4 changes: 2 additions & 2 deletions abis/0.8.21/AgentFactory.json

Large diffs are not rendered by default.

84 changes: 63 additions & 21 deletions abis/0.8.21/AgentMech.json

Large diffs are not rendered by default.

3 changes: 3 additions & 0 deletions abis/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
# AI registry mech ABIs
0.8.19 ABIs were obtained with 750 optimization passes.
0.8.21 ABIs were obtained with 1000000 optimization passes.
65 changes: 64 additions & 1 deletion contracts/AgentMech.sol
Original file line number Diff line number Diff line change
Expand Up @@ -22,19 +22,26 @@ error AgentNotFound(uint256 agentId);
/// @param expected Expected amount.
error NotEnoughPaid(uint256 provided, uint256 expected);

/// @dev Request Id not found.
/// @param requestId Request Id.
error RequestIdNotFound(uint256 requestId);

/// @title AgentMech - Smart contract for extending ERC721Mech
/// @dev A Mech that is operated by the holder of an ERC721 non-fungible token.
contract AgentMech is ERC721Mech {
event Perform(address indexed sender, bytes32 taskHash);
Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This event is not used.

event Deliver(address indexed sender, uint256 requestId, bytes data);
event Request(address indexed sender, uint256 requestId, bytes data);
event PriceUpdated(uint256 price);

// Minimum required price
uint256 public price;
// Number of undelivered requests
uint256 public numUndeliveredRequests;

// Map of requests counts for corresponding addresses
mapping (address => uint256) public mapRequestsCounts;
// Map of request Ids
mapping (uint256 => uint256[2]) public mapRequestIds;
Comment on lines +48 to +49
Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

A two-way circular map stores all the undelivered requests and correctly removes elements when requests are delivered.


/// @dev AgentMech constructor.
/// @param _token Address of the token contract.
Expand All @@ -52,6 +59,7 @@ contract AgentMech is ERC721Mech {
revert AgentNotFound(_tokenId);
}

// Record the price
price = _price;
}

Expand All @@ -62,15 +70,51 @@ contract AgentMech is ERC721Mech {
revert NotEnoughPaid(msg.value, price);
}

// Get the request Id
requestId = getRequestId(msg.sender, data);
// Increase the requests count supplied by the sender
mapRequestsCounts[msg.sender]++;

// Record the request Id in the map
// Get previous and next request Ids of the first element
uint256[2] storage requestIds = mapRequestIds[0];
// Create the new element
uint256[2] storage newRequestIds = mapRequestIds[requestId];

// Previous element will be zero, next element will be the current next element
uint256 curNextRequestId = requestIds[1];
newRequestIds[1] = curNextRequestId;
// Next element of the zero element will be the newly created element
requestIds[1] = requestId;
// Previous element of the current next element will be the newly created element
mapRequestIds[curNextRequestId][0] = requestId;

// Increase the number of undelivered requests
numUndeliveredRequests++;

emit Request(msg.sender, requestId, data);
}

/// @dev Delivers a request.
/// @param requestId Request id.
/// @param data Self-descriptive opaque data-blob.
function deliver(uint256 requestId, bytes memory data) external onlyOperator {
// Remove delivered request Id from the request Ids map
uint256[2] memory requestIds = mapRequestIds[requestId];
// Check if the request Id is invalid: previous and next request Ids are zero,
// and the zero's element next request Id is not equal to the provided request Id
if (requestIds[0] == 0 && requestIds[1] == 0 && mapRequestIds[0][1] != requestId) {
revert RequestIdNotFound(requestId);
}

// Re-link previous and next elements between themselves
mapRequestIds[requestIds[0]][1] = requestIds[1];
mapRequestIds[requestIds[1]][0] = requestIds[0];
// Delete the delivered element from the map
delete mapRequestIds[requestId];
// Decrease the number of undelivered requests
numUndeliveredRequests--;

emit Deliver(msg.sender, requestId, data);
}

Expand All @@ -95,4 +139,23 @@ contract AgentMech is ERC721Mech {
function getRequestsCount(address account) external view returns (uint256 requestsCount) {
requestsCount = mapRequestsCounts[account];
}

/// @dev Gets the set of undelivered request Ids.
/// @return requestIds Set of undelivered request Ids.
function getUndeliveredRequestIds() external view returns (uint256[] memory requestIds) {
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Do we need to worry about the number of undelivered requests being too large. Although unlikely, I think it may happen. Could that result in a big request to the rpc which would get dropped constantly?
I am thinking maybe it makes sense to either have this method take a maxNumReqs, or have another method that supports that, just to avoid this case.

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Good point. How about we slightly alter the method to allow to (optionally) set a batch size. Then you can get constant sized returns

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@DavidMinarsch that should do

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I've accounted for both size and offset, please take a look.

// Get the number of undelivered requests
uint256 numRequests = numUndeliveredRequests;

if (numRequests > 0) {
requestIds = new uint256[](numRequests);

// The first request Id is the next request Id of the zero element in the request Ids map
uint256 curRequestId = mapRequestIds[0][1];
for (uint256 i = 0; i < numRequests; ++i) {
requestIds[i] = curRequestId;
// Next request Id of the current element based on the current request Id
curRequestId = mapRequestIds[curRequestId][1];
}
}
}
}
16 changes: 1 addition & 15 deletions scripts/deployment/globals_gnosis_chiado.json
Original file line number Diff line number Diff line change
@@ -1,15 +1 @@
{
"contractVerification": true,
"useLedger": false,
"derivationPath": "m/44'/60'/2'/0/0",
"providerName": "chiado",
"gasPriceInGwei": "2",
"baseURI": "https://gateway.autonolas.tech/ipfs/",
"agentRegistryName": "AI Agent Registry",
"agentRegistrySymbol": "AI-AGENT-V1",
"agentRegistryAddress": "0x9dEc6B62c197268242A768dc3b153AE7a2701396",
"agentFactoryAddress": "0x060268D4fE1Eb97843B14dd98cDf9ef7fbb3c720",
"agentMechAddress": "0x0a3cfc6bee9658eda040e6bb366fe963ddce82c9",
"agentId": "1",
"price": "1000000000000000000"
}
{"contractVerification":true,"useLedger":false,"derivationPath":"m/44'/60'/2'/0/0","providerName":"chiado","gasPriceInGwei":"2","baseURI":"https://gateway.autonolas.tech/ipfs/","agentRegistryName":"AI Agent Registry","agentRegistrySymbol":"AI-AGENT-V1","agentRegistryAddress":"0x9dEc6B62c197268242A768dc3b153AE7a2701396","agentFactoryAddress":"0x1d333b46dB6e8FFd271b6C2D2B254868BD9A2dbd","agentMechAddress":"0x0a3cfc6bee9658eda040e6bb366fe963ddce82c9","agentId":"1","price":"1000000000000000000"}
147 changes: 147 additions & 0 deletions test/AgentMech.js
Original file line number Diff line number Diff line change
Expand Up @@ -63,14 +63,161 @@ describe("AgentMech", function () {
it("Delivering a request", async function () {
const account = signers[1];
const agentMech = await AgentMech.deploy(agentRegistry.address, unitId, price);

const requestId = await agentMech.getRequestId(deployer.address, data);

// Try to deliver a non existent request
await expect(
agentMech.deliver(requestId, data)
).to.be.revertedWithCustomError(agentMech, "RequestIdNotFound");

// Create a request
await agentMech.request(data, {value: price});

// Deliver a request
await agentMech.deliver(requestId, data);

// Try to deliver not by the operator (agent owner)
await expect(
agentMech.connect(account).request(data)
).to.be.reverted;
});

it("Getting undelivered requests info", async function () {
const agentMech = await AgentMech.deploy(agentRegistry.address, unitId, price);

const numRequests = 5;
const datas = new Array();
const requestIds = new Array();
for (let i = 0; i < numRequests; i++) {
datas[i] = data + "00".repeat(i);
requestIds[i] = await agentMech.getRequestId(deployer.address, datas[i]);
}

// Check request Ids
let uRequestIds = await agentMech.getUndeliveredRequestIds();
expect(uRequestIds.length).to.equal(0);

// Create a first request
await agentMech.request(datas[0], {value: price});

// Check request Ids
uRequestIds = await agentMech.getUndeliveredRequestIds();
expect(uRequestIds.length).to.equal(1);
expect(uRequestIds[0]).to.equal(requestIds[0]);

// Deliver a request
await agentMech.deliver(requestIds[0], data);

// Check request Ids
uRequestIds = await agentMech.getUndeliveredRequestIds();
expect(uRequestIds.length).to.equal(0);

// Stack all requests
for (let i = 0; i < numRequests; i++) {
await agentMech.request(datas[i], {value: price});
}

// Check request Ids
uRequestIds = await agentMech.getUndeliveredRequestIds();
expect(uRequestIds.length).to.equal(numRequests);
// Requests are added in the reverse order
for (let i = 0; i < numRequests; i++) {
expect(uRequestIds[numRequests - i - 1]).to.eq(requestIds[i]);
}

// Deliver all requests
for (let i = 0; i < numRequests; i++) {
await agentMech.deliver(requestIds[i], datas[i]);
}

// Check request Ids
uRequestIds = await agentMech.getUndeliveredRequestIds();
expect(uRequestIds.length).to.equal(0);

// Add all requests again
for (let i = 0; i < numRequests; i++) {
await agentMech.request(datas[i], {value: price});
}

// Deliver the first request
await agentMech.deliver(requestIds[0], datas[0]);

// Check request Ids
uRequestIds = await agentMech.getUndeliveredRequestIds();
expect(uRequestIds.length).to.equal(numRequests - 1);
// Requests are added in the reverse order
for (let i = 1; i < numRequests; i++) {
expect(uRequestIds[numRequests - i - 1]).to.eq(requestIds[i]);
}

// Deliver the last request
await agentMech.deliver(requestIds[numRequests - 1], datas[numRequests - 1]);

// Check request Ids
uRequestIds = await agentMech.getUndeliveredRequestIds();
expect(uRequestIds.length).to.equal(numRequests - 2);
for (let i = 1; i < numRequests - 1; i++) {
expect(uRequestIds[numRequests - i - 2]).to.eq(requestIds[i]);
}

// Deliver the middle request
const middle = Math.floor(numRequests / 2);
await agentMech.deliver(requestIds[middle], datas[middle]);

// Check request Ids
uRequestIds = await agentMech.getUndeliveredRequestIds();
expect(uRequestIds.length).to.equal(numRequests - 3);
for (let i = 1; i < middle; i++) {
expect(uRequestIds[middle - i]).to.eq(requestIds[i]);
}
for (let i = middle + 1; i < numRequests - 1; i++) {
expect(uRequestIds[numRequests - i - 2]).to.eq(requestIds[i]);
}
});

it("Getting undelivered requests info for even and odd requests", async function () {
const agentMech = await AgentMech.deploy(agentRegistry.address, unitId, price);

const numRequests = 10;
const datas = new Array();
const requestIds = new Array();
for (let i = 0; i < numRequests; i++) {
datas[i] = data + "00".repeat(i);
requestIds[i] = await agentMech.getRequestId(deployer.address, datas[i]);
}

// Stack all requests except for the last one
for (let i = 0; i < numRequests - 1; i++) {
await agentMech.request(datas[i], {value: price});
}

// Deliver even requests
for (let i = 0; i < numRequests - 1; i++) {
if (i % 2 != 0) {
await agentMech.deliver(requestIds[i], datas[i]);
}
}

// Check request Ids
let uRequestIds = await agentMech.getUndeliveredRequestIds();
const half = Math.floor(numRequests / 2);
expect(uRequestIds.length).to.equal(half);
for (let i = 0; i < half; i++) {
expect(uRequestIds[half - i - 1]).to.eq(requestIds[i * 2]);
}

// Deliver the rest of requests
for (let i = 0; i < numRequests - 1; i++) {
if (i % 2 == 0) {
await agentMech.deliver(requestIds[i], datas[i]);
}
}

// Check request Ids
uRequestIds = await agentMech.getUndeliveredRequestIds();
expect(uRequestIds.length).to.equal(0);
});
});

context("Changing parameters", async function () {
Expand Down