Skip to content
Merged
Show file tree
Hide file tree
Changes from all 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 .claude/CLAUDE.md
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ TypeScript client for the AgentScore trust and reputation API.
- `createCredential(options?)` — create operator credential (24h TTL default)
- `listCredentials()` — list active credentials
- `revokeCredential(id)` — revoke a credential
- `associateWallet({ operatorToken, walletAddress, network, idempotencyKey? })` — report a signer wallet seen paying under a credential (TEC-189). Fire-and-forget; use the payment intent id / tx hash as `idempotencyKey` so retries don't inflate transaction_count.

## Architecture

Expand Down
12 changes: 11 additions & 1 deletion .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -9,12 +9,22 @@ on:
permissions:
contents: read

concurrency:
group: ${{ github.workflow }}-${{ github.ref }}
cancel-in-progress: true

jobs:
ci:
runs-on: blacksmith-2vcpu-ubuntu-2404
runs-on: blacksmith-2vcpu-ubuntu-2404-arm
timeout-minutes: 10
steps:
- uses: useblacksmith/checkout@v1
- uses: oven-sh/setup-bun@v2
- uses: actions/cache@v4
with:
path: ~/.bun/install/cache
key: ${{ runner.os }}-bun-${{ hashFiles('bun.lock') }}
restore-keys: ${{ runner.os }}-bun-
- run: bun install --frozen-lockfile
- run: bun run lint
- run: bunx tsc --noEmit
Expand Down
5 changes: 5 additions & 0 deletions .github/workflows/publish.yml
Original file line number Diff line number Diff line change
Expand Up @@ -8,9 +8,14 @@ permissions:
contents: write
id-token: write

concurrency:
group: publish
cancel-in-progress: false

jobs:
publish:
runs-on: ubuntu-latest
timeout-minutes: 15
steps:
- uses: actions/checkout@v6

Expand Down
2 changes: 1 addition & 1 deletion .github/workflows/security.yml
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ permissions:
jobs:
osv-scan:
name: Dependency Scan
runs-on: blacksmith-2vcpu-ubuntu-2404
runs-on: blacksmith-2vcpu-ubuntu-2404-arm
timeout-minutes: 5
steps:
- uses: useblacksmith/checkout@v1
Expand Down
13 changes: 13 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -85,6 +85,19 @@ console.log(list); // active, non-expired credentials
await client.revokeCredential(cred.id);
```

### Report an Agent's Wallet (Cross-Merchant Attribution)

After an agent authenticated via `operator_token` completes a payment, report the signer wallet so AgentScore can build a cross-merchant credential↔wallet profile. Fire-and-forget — `first_seen` is informational only. `network` is the key-derivation family: `"evm"` for any EVM chain (Base, Tempo, Ethereum, …) or `"solana"` for Solana.

```typescript
await client.associateWallet({
operatorToken: "opc_...",
walletAddress: signerFromPayment, // e.g. EIP-3009 `from` or Tempo MPP DID address
network: "evm",
idempotencyKey: paymentIntentId, // optional — agent retries of the same payment no-op
});
```

## Configuration

| Option | Type | Default | Description |
Expand Down
22 changes: 11 additions & 11 deletions bun.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

4 changes: 2 additions & 2 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -51,14 +51,14 @@
},
"devDependencies": {
"@eslint/js": "^9.39.4",
"@vitest/coverage-v8": "^4.1.4",
"@vitest/coverage-v8": "^4.1.5",
"dotenv": "^17.4.2",
"eslint": "^9.39.4",
"eslint-plugin-import": "^2.32.0",
"eslint-plugin-unused-imports": "^4.4.1",
"tsup": "^8.5.1",
"typescript": "^6.0.3",
"typescript-eslint": "^8.59.0",
"vitest": "^4.1.4"
"vitest": "^4.1.5"
}
}
31 changes: 31 additions & 0 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,8 @@ import type {
AgentScoreErrorBody,
AssessOptions,
AssessResponse,
AssociateWalletOptions,
AssociateWalletResponse,
CredentialCreateOptions,
CredentialCreateResponse,
CredentialListResponse,
Expand Down Expand Up @@ -112,6 +114,35 @@ export class AgentScore {
);
}

/**
* Report that a wallet paid under an operator credential. Paid-tier merchants observing
* agent payments call this passively to build a cross-merchant credential↔wallet profile.
*
* Fire-and-forget friendly — the returned `first_seen` boolean is informational only.
*/
async associateWallet(options: AssociateWalletOptions): Promise<AssociateWalletResponse> {
const body: Record<string, unknown> = {
operator_token: options.operatorToken,
wallet_address: options.walletAddress,
network: options.network,
};
if (options.idempotencyKey) {
if (options.idempotencyKey.length > 200) {
// Server truncates to 200 chars before storing. A caller sending a longer key
// and re-sending the same long key later would still dedup (both truncate to
// the same 200 chars), but any caller generating distinct keys that share the
// first 200 chars would silently collide. Warn loud enough to catch in dev.
console.warn('[@agent-score/sdk] associateWallet: idempotencyKey is longer than 200 chars and will be truncated server-side.');
}
body.idempotency_key = options.idempotencyKey;
}
return this.request<AssociateWalletResponse>('/v1/credentials/wallets', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(body),
});
}

private async request<T>(path: string, options?: RequestInit): Promise<T> {
const url = `${this.baseUrl}${path}`;

Expand Down
23 changes: 23 additions & 0 deletions src/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -281,3 +281,26 @@ export interface CredentialRevokeResponse {
id: string;
revoked: true;
}

export interface AssociateWalletOptions {
/** Operator credential (opc_...) that the agent authenticated with on the gated endpoint. */
operatorToken: string;
/** The signer wallet recovered from the payment payload — EVM `from` from EIP-3009 for x402,
* the `did:pkh` address for Tempo MPP, or a Solana base58 pubkey. */
walletAddress: string;
/** Key-derivation family. EVM EOAs share identity across every EVM chain (Base, Tempo,
* Ethereum, …) so `"evm"` covers them all. Use `"solana"` for Solana addresses. */
network: 'evm' | 'solana';
/** Optional stable key for the logical payment (e.g., Stripe PI id, x402 tx hash). When the
* same key is seen again for the same (credential, wallet, network), the server no-ops —
* `transaction_count` isn't inflated by agent retries. */
idempotencyKey?: string;
}

export interface AssociateWalletResponse {
associated: true;
/** True if this credential↔wallet pairing was seen for the first time. False if the row already existed. */
first_seen: boolean;
/** Present and `true` when the call was deduped against a prior matching `idempotency_key`. */
deduped?: boolean;
}
84 changes: 84 additions & 0 deletions tests/sessions-credentials.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -418,3 +418,87 @@ describe('AgentScore.revokeCredential()', () => {
}
});
});

// ---------------------------------------------------------------------------
// associateWallet
// ---------------------------------------------------------------------------

const ASSOCIATE_OPTIONS = {
operatorToken: 'opc_' + 'a'.repeat(48),
walletAddress: '0xabcdef1234567890abcdef1234567890abcdef12',
network: 'evm' as const,
};

describe('AgentScore.associateWallet()', () => {
afterEach(() => vi.restoreAllMocks());

it('returns { associated, first_seen } on success', async () => {
mockFetchOk({ associated: true, first_seen: true });
const client = new AgentScore({ apiKey: API_KEY });
const result = await client.associateWallet(ASSOCIATE_OPTIONS);
expect(result).toEqual({ associated: true, first_seen: true });
});

it('sends a POST with snake_case body fields to /v1/credentials/wallets', async () => {
mockFetchOk({ associated: true, first_seen: false });
const client = new AgentScore({ apiKey: API_KEY });
await client.associateWallet(ASSOCIATE_OPTIONS);

const call = (global.fetch as ReturnType<typeof vi.fn>).mock.calls[0];
expect(call[0]).toContain('/v1/credentials/wallets');
expect(call[1].method).toBe('POST');
const body = JSON.parse(call[1].body as string);
expect(body).toEqual({
operator_token: ASSOCIATE_OPTIONS.operatorToken,
wallet_address: ASSOCIATE_OPTIONS.walletAddress,
network: ASSOCIATE_OPTIONS.network,
});
});

it('forwards idempotencyKey as snake_case idempotency_key in the body', async () => {
mockFetchOk({ associated: true, first_seen: false, deduped: true });
const client = new AgentScore({ apiKey: API_KEY });
const result = await client.associateWallet({ ...ASSOCIATE_OPTIONS, idempotencyKey: 'pi_abc' });

expect(result).toEqual({ associated: true, first_seen: false, deduped: true });
const call = (global.fetch as ReturnType<typeof vi.fn>).mock.calls[0];
const body = JSON.parse(call[1].body as string);
expect(body.idempotency_key).toBe('pi_abc');
});

it('omits idempotency_key entirely when not provided', async () => {
mockFetchOk({ associated: true, first_seen: true });
const client = new AgentScore({ apiKey: API_KEY });
await client.associateWallet(ASSOCIATE_OPTIONS);

const call = (global.fetch as ReturnType<typeof vi.fn>).mock.calls[0];
const body = JSON.parse(call[1].body as string);
expect(body).not.toHaveProperty('idempotency_key');
});

it('throws AgentScoreError on 401 invalid_credential (matches /v1/assess for anti-enumeration)', async () => {
mockFetchError(401, { error: { code: 'invalid_credential', message: 'Operator credential not found' } });
const client = new AgentScore({ apiKey: API_KEY });
await expect(client.associateWallet(ASSOCIATE_OPTIONS)).rejects.toBeInstanceOf(AgentScoreError);
});

it('throws AgentScoreError with correct code on 400 invalid_wallet', async () => {
expect.assertions(3);
mockFetchError(400, { error: { code: 'invalid_wallet', message: 'bad wallet' } });
const client = new AgentScore({ apiKey: API_KEY });
try {
await client.associateWallet({ ...ASSOCIATE_OPTIONS, walletAddress: '0xnope' });
} catch (e) {
expect(e).toBeInstanceOf(AgentScoreError);
const err = e as AgentScoreError;
expect(err.code).toBe('invalid_wallet');
expect(err.status).toBe(400);
}
});

it('throws AgentScoreError on 402 payment_required (free tier)', async () => {
mockFetchError(402, { error: { code: 'payment_required', message: 'paid only' } });
const client = new AgentScore({ apiKey: API_KEY });
await expect(client.associateWallet(ASSOCIATE_OPTIONS)).rejects.toBeInstanceOf(AgentScoreError);
});
});
Loading