agent0-sdk 0.2.2__py3-none-any.whl → 0.5__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,227 +0,0 @@
1
- """
2
- Real Test for Agent Registration with IPFS Pin (using Pinata)
3
- Creates an agent, updates it on-chain, deletes it, reloads it, and verifies data integrity.
4
- """
5
-
6
- import logging
7
- import time
8
- import random
9
- import sys
10
-
11
- # Configure logging: root logger at WARNING to suppress noisy dependencies
12
- logging.basicConfig(
13
- level=logging.WARNING,
14
- format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
15
- datefmt='%Y-%m-%d %H:%M:%S',
16
- handlers=[logging.StreamHandler(sys.stdout)]
17
- )
18
-
19
- # Set debug level ONLY for agent0_sdk
20
- logging.getLogger('agent0_sdk').setLevel(logging.DEBUG)
21
- logging.getLogger('agent0_sdk.core').setLevel(logging.DEBUG)
22
-
23
- from agent0_sdk import SDK
24
- from config import CHAIN_ID, RPC_URL, AGENT_PRIVATE_KEY, PINATA_JWT, print_config
25
-
26
-
27
- def generateRandomData():
28
- """Generate random test data for the agent."""
29
- randomSuffix = random.randint(1000, 9999)
30
- timestamp = int(time.time())
31
-
32
- return {
33
- 'name': f"Test Agent {randomSuffix}",
34
- 'description': f"Created at {timestamp}",
35
- 'image': f"https://example.com/image_{randomSuffix}.png",
36
- 'mcpEndpoint': f"https://api.example.com/mcp/{randomSuffix}",
37
- 'mcpVersion': f"2025-06-{random.randint(1, 28)}",
38
- 'a2aEndpoint': f"https://api.example.com/a2a/{randomSuffix}.json",
39
- 'a2aVersion': f"0.{random.randint(30, 35)}",
40
- 'ensName': f"test{randomSuffix}.eth",
41
- 'ensVersion': f"1.{random.randint(0, 9)}",
42
- 'walletAddress': f"0x{'a' * 40}",
43
- 'walletChainId': random.choice([1, 11155111, 8453, 137, 42161]), # Mainnet, Sepolia, Base, Polygon, Arbitrum
44
- 'active': True,
45
- 'x402support': False,
46
- 'reputation': random.choice([True, False]),
47
- 'cryptoEconomic': random.choice([True, False]),
48
- 'teeAttestation': random.choice([True, False])
49
- }
50
-
51
-
52
- def main():
53
- print("🧪 Testing Agent Registration with IPFS Pin")
54
- print_config()
55
-
56
- # SDK Configuration with Pinata IPFS
57
- sdkConfig = {
58
- 'chainId': CHAIN_ID,
59
- 'rpcUrl': RPC_URL,
60
- 'ipfs': 'pinata',
61
- 'pinataJwt': PINATA_JWT
62
- }
63
-
64
- sdk = SDK(signer=AGENT_PRIVATE_KEY, **sdkConfig)
65
- testData = generateRandomData()
66
-
67
- agent = sdk.createAgent(
68
- name=testData['name'],
69
- description=testData['description'],
70
- image=testData['image']
71
- )
72
-
73
- agent.setMCP(testData['mcpEndpoint'], testData['mcpVersion'])
74
- agent.setA2A(testData['a2aEndpoint'], testData['a2aVersion'])
75
- agent.setENS(testData['ensName'], testData['ensVersion'])
76
- agent.setAgentWallet(testData['walletAddress'], testData['walletChainId'])
77
- agent.setActive(testData['active'])
78
- agent.setX402Support(testData['x402support'])
79
- agent.setTrust(
80
- reputation=testData['reputation'],
81
- cryptoEconomic=testData['cryptoEconomic'],
82
- teeAttestation=testData['teeAttestation']
83
- )
84
-
85
- print(f"\n✅ Created: {testData['name']}")
86
-
87
- agent.registerIPFS()
88
- agentId = agent.agentId
89
- print(f"✅ Registered: ID={agentId}")
90
-
91
- capturedState = {
92
- 'agentId': agent.agentId,
93
- 'agentURI': agent.agentURI,
94
- 'name': agent.name,
95
- 'description': agent.description,
96
- 'image': agent.image,
97
- 'walletAddress': agent.walletAddress,
98
- 'walletChainId': agent.walletChainId,
99
- 'active': agent.active,
100
- 'x402support': agent.x402support,
101
- 'mcpEndpoint': agent.mcpEndpoint,
102
- 'a2aEndpoint': agent.a2aEndpoint,
103
- 'ensEndpoint': agent.ensEndpoint,
104
- 'metadata': agent.metadata.copy()
105
- }
106
-
107
- agent.updateInfo(
108
- name=testData['name'] + " UPDATED",
109
- description=testData['description'] + " - UPDATED",
110
- image=f"https://example.com/image_{random.randint(1000, 9999)}_updated.png"
111
- )
112
- agent.setMCP(f"https://api.example.com/mcp/{random.randint(10000, 99999)}", f"2025-06-{random.randint(1, 28)}")
113
- agent.setA2A(f"https://api.example.com/a2a/{random.randint(10000, 99999)}.json", f"0.{random.randint(30, 35)}")
114
- agent.setAgentWallet(f"0x{'b' * 40}", random.choice([1, 11155111, 8453, 137, 42161]))
115
- agent.setENS(f"{testData['ensName']}.updated", f"1.{random.randint(0, 9)}")
116
- agent.setActive(False)
117
- agent.setX402Support(True)
118
- agent.setTrust(
119
- reputation=random.choice([True, False]),
120
- cryptoEconomic=random.choice([True, False]),
121
- teeAttestation=random.choice([True, False])
122
- )
123
- agent.setMetadata({
124
- "testKey": "testValue",
125
- "timestamp": int(time.time()),
126
- "customField": "customValue",
127
- "anotherField": "anotherValue",
128
- "numericField": random.randint(1000, 9999)
129
- })
130
-
131
- agent.registerIPFS()
132
- print(f"✅ Updated & re-registered")
133
-
134
- # Capture updated state before deletion
135
- updatedState = {
136
- 'name': agent.name,
137
- 'description': agent.description,
138
- 'image': agent.image,
139
- 'walletAddress': agent.walletAddress,
140
- 'walletChainId': agent.walletChainId,
141
- 'active': agent.active,
142
- 'x402support': agent.x402support,
143
- 'mcpEndpoint': agent.mcpEndpoint,
144
- 'a2aEndpoint': agent.a2aEndpoint,
145
- 'ensEndpoint': agent.ensEndpoint,
146
- 'metadata': agent.metadata.copy()
147
- }
148
-
149
- reloadedAgentId = agent.agentId
150
- del agent
151
- # Wait for blockchain transaction to be mined (Sepolia takes ~15 seconds)
152
- print("⏳ Waiting for blockchain transaction to be mined (15 seconds)...")
153
- time.sleep(15)
154
- reloadedAgent = sdk.loadAgent(reloadedAgentId)
155
- print(f"✅ Reloaded from blockchain")
156
-
157
- reloadedState = {
158
- 'name': reloadedAgent.name,
159
- 'description': reloadedAgent.description,
160
- 'image': reloadedAgent.image,
161
- 'walletAddress': reloadedAgent.walletAddress,
162
- 'walletChainId': reloadedAgent.walletChainId,
163
- 'active': reloadedAgent.active,
164
- 'x402support': reloadedAgent.x402support,
165
- 'mcpEndpoint': reloadedAgent.mcpEndpoint,
166
- 'a2aEndpoint': reloadedAgent.a2aEndpoint,
167
- 'ensEndpoint': reloadedAgent.ensEndpoint,
168
- 'metadata': reloadedAgent.metadata.copy()
169
- }
170
-
171
- expectedState = updatedState
172
-
173
- # Override expected values for fields that should match the updated state
174
- expectedState['walletAddress'] = f"0x{'b' * 40}"
175
- # When wallet is set on-chain, walletChainId will be the current chain (where the update happened)
176
- # This is different from the original registration file's chain ID
177
- expectedState['walletChainId'] = sdk.chainId # Current chain where wallet was updated
178
-
179
- allMatch = True
180
- for field, expected in expectedState.items():
181
- actual = reloadedState.get(field)
182
-
183
- # Handle type casting for metadata fields (on-chain values are strings)
184
- if field == 'metadata' and isinstance(actual, dict) and isinstance(expected, dict):
185
- # Try to cast string values back to their original types
186
- normalized_actual = {}
187
- for k, v in actual.items():
188
- if k in expected:
189
- expected_val = expected[k]
190
- # If expected is int or float, try to cast
191
- if isinstance(expected_val, int):
192
- try:
193
- normalized_actual[k] = int(v) if isinstance(v, str) else v
194
- except (ValueError, TypeError):
195
- normalized_actual[k] = v
196
- elif isinstance(expected_val, float):
197
- try:
198
- normalized_actual[k] = float(v) if isinstance(v, str) else v
199
- except (ValueError, TypeError):
200
- normalized_actual[k] = v
201
- else:
202
- normalized_actual[k] = v
203
- else:
204
- normalized_actual[k] = v
205
- actual = normalized_actual
206
-
207
- if actual == expected:
208
- print(f"✅ {field}: {actual}")
209
- else:
210
- print(f"❌ {field}: expected={expected}, got={actual}")
211
- allMatch = False
212
-
213
- if allMatch:
214
- print("\n✅ ALL CHECKS PASSED")
215
- else:
216
- print("\n❌ SOME CHECKS FAILED")
217
-
218
-
219
- if __name__ == "__main__":
220
- try:
221
- main()
222
- except Exception as e:
223
- print(f"\n❌ Error: {e}")
224
- import traceback
225
- traceback.print_exc()
226
- exit(1)
227
-
tests/test_sdk.py DELETED
@@ -1,240 +0,0 @@
1
- """
2
- Tests for SDK class.
3
- """
4
-
5
- import pytest
6
- from unittest.mock import Mock, patch
7
-
8
- from agent0_sdk.core.sdk import SDK
9
- from agent0_sdk.core.models import EndpointType, TrustModel
10
-
11
-
12
- class TestSDK:
13
- """Test SDK class."""
14
-
15
- def test_sdk_initialization(self):
16
- """Test SDK initialization."""
17
- with patch('agent0_sdk.core.sdk.Web3Client') as mock_web3:
18
- mock_web3.return_value.chain_id = 11155111
19
-
20
- sdk = SDK(
21
- chainId=11155111,
22
- signer="0x1234567890abcdef",
23
- rpcUrl="https://eth-sepolia.g.alchemy.com/v2/test"
24
- )
25
-
26
- assert sdk.chainId == 11155111
27
- assert sdk.rpcUrl == "https://eth-sepolia.g.alchemy.com/v2/test"
28
- mock_web3.assert_called_once()
29
-
30
- def test_create_agent(self):
31
- """Test agent creation."""
32
- with patch('agent0_sdk.core.sdk.Web3Client') as mock_web3:
33
- mock_web3.return_value.chain_id = 11155111
34
-
35
- sdk = SDK(
36
- chainId=11155111,
37
- signer="0x1234567890abcdef",
38
- rpcUrl="https://eth-sepolia.g.alchemy.com/v2/test"
39
- )
40
-
41
- agent = sdk.createAgent(
42
- name="Test Agent",
43
- description="A test agent",
44
- image="https://example.com/image.png"
45
- )
46
-
47
- assert agent.name == "Test Agent"
48
- assert agent.description == "A test agent"
49
- assert agent.image == "https://example.com/image.png"
50
- assert agent.sdk == sdk
51
-
52
- def test_registries(self):
53
- """Test registry resolution."""
54
- with patch('agent0_sdk.core.sdk.Web3Client') as mock_web3:
55
- mock_web3.return_value.chain_id = 11155111
56
-
57
- sdk = SDK(
58
- chainId=11155111,
59
- signer="0x1234567890abcdef",
60
- rpcUrl="https://eth-sepolia.g.alchemy.com/v2/test"
61
- )
62
-
63
- registries = sdk.registries()
64
- assert "IDENTITY" in registries
65
- assert "REPUTATION" in registries
66
- assert "VALIDATION" in registries
67
-
68
- def test_set_chain(self):
69
- """Test chain switching."""
70
- with patch('agent0_sdk.core.sdk.Web3Client') as mock_web3:
71
- mock_web3.return_value.chain_id = 11155111
72
-
73
- sdk = SDK(
74
- chainId=11155111,
75
- signer="0x1234567890abcdef",
76
- rpcUrl="https://eth-sepolia.g.alchemy.com/v2/test"
77
- )
78
-
79
- sdk.set_chain(84532) # Switch to Base Sepolia
80
- assert sdk.chainId == 84532
81
- assert sdk._registries["IDENTITY"] is not None # Should have Base Sepolia registry
82
-
83
-
84
- class TestAgent:
85
- """Test Agent class."""
86
-
87
- def test_agent_endpoint_management(self):
88
- """Test agent endpoint management."""
89
- with patch('agent0_sdk.core.sdk.Web3Client') as mock_web3:
90
- mock_web3.return_value.chain_id = 11155111
91
-
92
- sdk = SDK(
93
- chainId=11155111,
94
- signer="0x1234567890abcdef",
95
- rpcUrl="https://eth-sepolia.g.alchemy.com/v2/test"
96
- )
97
-
98
- agent = sdk.createAgent("Test Agent", "A test agent")
99
-
100
- # Add MCP endpoint
101
- agent.setMCP("https://mcp.example.com/")
102
- assert len(agent.endpoints) == 1
103
- assert agent.endpoints[0].type == EndpointType.MCP
104
- assert agent.endpoints[0].value == "https://mcp.example.com/"
105
- assert agent.endpoints[0].meta["version"] == "2025-06-18"
106
-
107
- # Add A2A endpoint
108
- agent.setA2A("https://a2a.example.com/", "1.0")
109
- assert len(agent.endpoints) == 2
110
-
111
- # Add ENS endpoint
112
- agent.setENS("test-agent.eth")
113
- assert len(agent.endpoints) == 3
114
- ens_endpoint = next(ep for ep in agent.endpoints if ep.type == EndpointType.ENS)
115
- assert ens_endpoint.value == "test-agent.eth"
116
- assert ens_endpoint.meta["version"] == "1.0"
117
-
118
- # Remove specific endpoint
119
- agent.removeEndpoint(EndpointType.MCP, "https://mcp.example.com/")
120
- assert len(agent.endpoints) == 2
121
- assert agent.endpoints[0].type == EndpointType.A2A
122
-
123
- # Remove all endpoints
124
- agent.removeEndpoints()
125
- assert len(agent.endpoints) == 0
126
-
127
- def test_agent_trust_models(self):
128
- """Test agent trust model management."""
129
- with patch('agent0_sdk.core.sdk.Web3Client') as mock_web3:
130
- mock_web3.return_value.chain_id = 11155111
131
-
132
- sdk = SDK(
133
- chainId=11155111,
134
- signer="0x1234567890abcdef",
135
- rpcUrl="https://eth-sepolia.g.alchemy.com/v2/test"
136
- )
137
-
138
- agent = sdk.createAgent("Test Agent", "A test agent")
139
-
140
- # Set trust models using new method
141
- agent.setTrust(reputation=True, cryptoEconomic=True)
142
- # Access trustModels through registration_file since property is shadowed by method
143
- assert len(agent.registration_file.trustModels) == 2
144
- assert TrustModel.REPUTATION in agent.registration_file.trustModels
145
- assert TrustModel.CRYPTO_ECONOMIC in agent.registration_file.trustModels
146
-
147
- # Set trust models using direct assignment (since trustModels is a property, not callable)
148
- agent.registration_file.trustModels = [TrustModel.REPUTATION, "custom_trust"]
149
- assert len(agent.registration_file.trustModels) == 2
150
- assert TrustModel.REPUTATION in agent.registration_file.trustModels
151
- assert "custom_trust" in agent.registration_file.trustModels
152
-
153
- def test_agent_metadata_management(self):
154
- """Test agent metadata management."""
155
- with patch('agent0_sdk.core.sdk.Web3Client') as mock_web3:
156
- mock_web3.return_value.chain_id = 11155111
157
-
158
- sdk = SDK(
159
- chainId=11155111,
160
- signer="0x1234567890abcdef",
161
- rpcUrl="https://eth-sepolia.g.alchemy.com/v2/test"
162
- )
163
-
164
- agent = sdk.createAgent("Test Agent", "A test agent")
165
-
166
- # Set metadata
167
- agent.setMetadata({"key1": "value1", "key2": "value2"})
168
- assert agent.getMetadata() == {"key1": "value1", "key2": "value2"}
169
-
170
- # Set single key using setMetadata
171
- agent.setMetadata({"key3": "value3"})
172
- assert agent.getMetadata() == {"key1": "value1", "key2": "value2", "key3": "value3"}
173
-
174
- # Delete key
175
- agent.delMetadata("key2")
176
- assert agent.getMetadata() == {"key1": "value1", "key3": "value3"}
177
-
178
- def test_agent_info_update(self):
179
- """Test agent info updates."""
180
- with patch('agent0_sdk.core.sdk.Web3Client') as mock_web3:
181
- mock_web3.return_value.chain_id = 11155111
182
-
183
- sdk = SDK(
184
- chainId=11155111,
185
- signer="0x1234567890abcdef",
186
- rpcUrl="https://eth-sepolia.g.alchemy.com/v2/test"
187
- )
188
-
189
- agent = sdk.createAgent("Test Agent", "A test agent")
190
-
191
- # Update info
192
- agent.updateInfo(
193
- name="Updated Agent",
194
- description="An updated agent",
195
- image="https://example.com/new-image.png"
196
- )
197
-
198
- assert agent.name == "Updated Agent"
199
- assert agent.description == "An updated agent"
200
- assert agent.image == "https://example.com/new-image.png"
201
-
202
- # Set wallet address (must be valid 42-character Ethereum address)
203
- valid_address = "0x1234567890abcdef1234567890abcdef12345678"
204
- agent.setAgentWallet(valid_address)
205
- assert agent.walletAddress == valid_address
206
-
207
- def test_agent_json_serialization(self):
208
- """Test agent JSON serialization."""
209
- with patch('agent0_sdk.core.sdk.Web3Client') as mock_web3:
210
- mock_web3.return_value.chain_id = 11155111
211
-
212
- sdk = SDK(
213
- chainId=11155111,
214
- signer="0x1234567890abcdef",
215
- rpcUrl="https://eth-sepolia.g.alchemy.com/v2/test"
216
- )
217
-
218
- agent = sdk.createAgent("Test Agent", "A test agent")
219
- agent.setMCP("https://mcp.example.com/")
220
- agent.setTrust(reputation=True)
221
-
222
- json_data = agent.toJson()
223
- assert isinstance(json_data, str)
224
- assert "Test Agent" in json_data
225
- assert "MCP" in json_data
226
- assert "reputation" in json_data
227
-
228
- # Test x402 support
229
- agent.setX402Support(True)
230
- assert agent.x402support is True
231
-
232
- json_data_with_x402 = agent.toJson()
233
- assert "x402support" in json_data_with_x402
234
-
235
- # Test active status
236
- agent.setActive(True)
237
- assert agent.active is True
238
-
239
- agent.setActive(False)
240
- assert agent.active is False