@occa/sdk 0.4.0 → 0.5.0

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.
@@ -24,6 +24,7 @@ __export(instructions_exports, {
24
24
  TREASURY_INSTRUCTION_DISCRIMINATOR: () => TREASURY_INSTRUCTION_DISCRIMINATOR,
25
25
  buildCloseOperationsInstruction: () => buildCloseOperationsInstruction,
26
26
  buildCommitDailyAnchorInstruction: () => buildCommitDailyAnchorInstruction,
27
+ buildCommitTraceInstruction: () => buildCommitTraceInstruction,
27
28
  buildCreateCompanyInstruction: () => buildCreateCompanyInstruction,
28
29
  buildCreateDeploymentInstruction: () => buildCreateDeploymentInstruction,
29
30
  buildDisburseDiscretionaryInstruction: () => buildDisburseDiscretionaryInstruction,
@@ -34,6 +35,7 @@ __export(instructions_exports, {
34
35
  buildRegisterCompanyOperationsInstruction: () => buildRegisterCompanyOperationsInstruction,
35
36
  buildRetireDeploymentInstruction: () => buildRetireDeploymentInstruction,
36
37
  buildRevokeOperationsInstruction: () => buildRevokeOperationsInstruction,
38
+ buildSetAgentReceivingAddressInstruction: () => buildSetAgentReceivingAddressInstruction,
37
39
  buildSetPolicyInstruction: () => buildSetPolicyInstruction,
38
40
  buildSetReceivingAddressInstruction: () => buildSetReceivingAddressInstruction,
39
41
  buildUpdateAgentIdentityMetadataInstruction: () => buildUpdateAgentIdentityMetadataInstruction,
@@ -60,12 +62,16 @@ var POLICY_SEED = Buffer.from("policy");
60
62
  var PROTOCOL_FEES_SEED = Buffer.from("protocol_fees");
61
63
  var OPERATIONS_SEED = Buffer.from("operations");
62
64
  var DAILY_ANCHOR_SEED = Buffer.from("daily_anchor");
65
+ var TRACE_SEED = Buffer.from("trace");
63
66
  var SOL_PSEUDO_MINT = new import_web3.PublicKey(new Uint8Array(32));
67
+ var MAX_RESULT_URI_LEN = 200;
68
+ var MAX_QUALITY_SCORE = 100;
64
69
  var ACCOUNT_DISCRIMINATOR = {
65
70
  AgentIdentity: Buffer.from([11, 149, 31, 27, 186, 76, 241, 72]),
66
71
  CompanyAccount: Buffer.from([37, 215, 171, 200, 8, 141, 69, 96]),
67
72
  Deployment: Buffer.from([66, 90, 104, 89, 183, 130, 64, 178]),
68
- DailyAnchorAccount: Buffer.from([218, 106, 107, 94, 194, 48, 111, 254])
73
+ DailyAnchorAccount: Buffer.from([218, 106, 107, 94, 194, 48, 111, 254]),
74
+ TraceAnchorAccount: Buffer.from([159, 101, 186, 98, 211, 217, 119, 232])
69
75
  };
70
76
  var TREASURY_ACCOUNT_DISCRIMINATOR = {
71
77
  TreasuryAccount: Buffer.from([204, 140, 18, 173, 90, 152, 134, 123]),
@@ -145,6 +151,16 @@ function deriveDailyAnchorPda(deploymentPda, dayUnix, programId = REGISTRY_PROGR
145
151
  );
146
152
  return { pda, bump };
147
153
  }
154
+ function deriveTraceAnchorPda(taskId, programId = REGISTRY_PROGRAM_ID) {
155
+ if (taskId.length !== 32) {
156
+ throw new RangeError(`taskId must be 32 bytes, got ${taskId.length}`);
157
+ }
158
+ const [pda, bump] = import_web32.PublicKey.findProgramAddressSync(
159
+ [TRACE_SEED, Buffer.from(taskId)],
160
+ programId
161
+ );
162
+ return { pda, bump };
163
+ }
148
164
 
149
165
  // src/instructions.ts
150
166
  var INSTRUCTION_DISCRIMINATOR = {
@@ -167,7 +183,9 @@ var INSTRUCTION_DISCRIMINATOR = {
167
183
  updateDeploymentStatus: Buffer.from([225, 195, 150, 254, 178, 203, 53, 147]),
168
184
  retireDeployment: Buffer.from([45, 188, 162, 197, 136, 180, 202, 153]),
169
185
  setReceivingAddress: Buffer.from([70, 63, 44, 87, 16, 6, 156, 200]),
170
- commitDailyAnchor: Buffer.from([18, 7, 3, 65, 58, 148, 164, 0])
186
+ setAgentReceivingAddress: Buffer.from([197, 126, 122, 18, 38, 62, 179, 218]),
187
+ commitDailyAnchor: Buffer.from([18, 7, 3, 65, 58, 148, 164, 0]),
188
+ commitTrace: Buffer.from([58, 140, 230, 51, 170, 109, 228, 125])
171
189
  };
172
190
  function encodeString(s) {
173
191
  const utf8 = Buffer.from(s, "utf8");
@@ -401,6 +419,22 @@ function buildSetReceivingAddressInstruction(params) {
401
419
  });
402
420
  return { instruction };
403
421
  }
422
+ function buildSetAgentReceivingAddressInstruction(params) {
423
+ const programId = params.programId ?? REGISTRY_PROGRAM_ID;
424
+ const data = Buffer.concat([
425
+ INSTRUCTION_DISCRIMINATOR.setAgentReceivingAddress,
426
+ encodePubkey(params.newReceivingAddress)
427
+ ]);
428
+ const instruction = new import_web33.TransactionInstruction({
429
+ programId,
430
+ keys: [
431
+ { pubkey: params.identityPda, isSigner: false, isWritable: true },
432
+ { pubkey: params.owner, isSigner: true, isWritable: false }
433
+ ],
434
+ data
435
+ });
436
+ return { instruction };
437
+ }
404
438
  var TREASURY_INSTRUCTION_DISCRIMINATOR = {
405
439
  setPolicy: Buffer.from([40, 133, 12, 157, 235, 202, 2, 132]),
406
440
  disburseDiscretionary: Buffer.from([102, 176, 14, 127, 210, 4, 96, 175]),
@@ -757,12 +791,67 @@ function buildCommitDailyAnchorInstruction(params) {
757
791
  });
758
792
  return { instruction };
759
793
  }
794
+ function buildCommitTraceInstruction(params) {
795
+ const programId = params.programId ?? REGISTRY_PROGRAM_ID;
796
+ if (params.taskId.length !== 32) {
797
+ throw new RangeError(`taskId must be 32 bytes, got ${params.taskId.length}`);
798
+ }
799
+ if (params.contentHash.length !== 32) {
800
+ throw new RangeError(
801
+ `contentHash must be 32 bytes, got ${params.contentHash.length}`
802
+ );
803
+ }
804
+ if (params.evidenceHash.length !== 32) {
805
+ throw new RangeError(
806
+ `evidenceHash must be 32 bytes, got ${params.evidenceHash.length}`
807
+ );
808
+ }
809
+ if (Buffer.from(params.resultUri, "utf8").length > MAX_RESULT_URI_LEN) {
810
+ throw new RangeError(
811
+ `resultUri exceeds MAX_RESULT_URI_LEN (${MAX_RESULT_URI_LEN} bytes)`
812
+ );
813
+ }
814
+ if (params.qualityScore < 0 || params.qualityScore > MAX_QUALITY_SCORE) {
815
+ throw new RangeError(
816
+ `qualityScore out of range 0..=${MAX_QUALITY_SCORE}: ${params.qualityScore}`
817
+ );
818
+ }
819
+ const taskId = Buffer.from(params.taskId);
820
+ const { pda: traceAnchorPda } = deriveTraceAnchorPda(taskId, programId);
821
+ const data = Buffer.concat([
822
+ INSTRUCTION_DISCRIMINATOR.commitTrace,
823
+ taskId,
824
+ encodeString(params.resultUri),
825
+ Buffer.from(params.contentHash),
826
+ encodeU8(params.qualityScore),
827
+ encodeU8(params.rubricVersion),
828
+ Buffer.from(params.evidenceHash),
829
+ encodeI64(params.completedAt)
830
+ ]);
831
+ const instruction = new import_web33.TransactionInstruction({
832
+ programId,
833
+ // Order: deployment, company, anchor_signer, operations, trace_anchor,
834
+ // payer, system_program.
835
+ keys: [
836
+ { pubkey: params.deploymentPda, isSigner: false, isWritable: false },
837
+ { pubkey: params.companyPda, isSigner: false, isWritable: false },
838
+ { pubkey: params.anchorSigner, isSigner: true, isWritable: false },
839
+ { pubkey: params.operationsPda, isSigner: false, isWritable: false },
840
+ { pubkey: traceAnchorPda, isSigner: false, isWritable: true },
841
+ { pubkey: params.payer, isSigner: true, isWritable: true },
842
+ { pubkey: import_web33.SystemProgram.programId, isSigner: false, isWritable: false }
843
+ ],
844
+ data
845
+ });
846
+ return { instruction, traceAnchorPda };
847
+ }
760
848
  // Annotate the CommonJS export names for ESM import in node:
761
849
  0 && (module.exports = {
762
850
  INSTRUCTION_DISCRIMINATOR,
763
851
  TREASURY_INSTRUCTION_DISCRIMINATOR,
764
852
  buildCloseOperationsInstruction,
765
853
  buildCommitDailyAnchorInstruction,
854
+ buildCommitTraceInstruction,
766
855
  buildCreateCompanyInstruction,
767
856
  buildCreateDeploymentInstruction,
768
857
  buildDisburseDiscretionaryInstruction,
@@ -773,6 +862,7 @@ function buildCommitDailyAnchorInstruction(params) {
773
862
  buildRegisterCompanyOperationsInstruction,
774
863
  buildRetireDeploymentInstruction,
775
864
  buildRevokeOperationsInstruction,
865
+ buildSetAgentReceivingAddressInstruction,
776
866
  buildSetPolicyInstruction,
777
867
  buildSetReceivingAddressInstruction,
778
868
  buildUpdateAgentIdentityMetadataInstruction,
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/instructions.ts","../src/constants.ts","../src/pda.ts"],"sourcesContent":["import {\n PublicKey,\n SystemProgram,\n TransactionInstruction,\n} from \"@solana/web3.js\";\nimport {\n OPERATIONS_KIND,\n REGISTRY_PROGRAM_ID,\n SOL_PSEUDO_MINT,\n TREASURY_PROGRAM_ID,\n type OperationsKind,\n} from \"./constants\";\nimport {\n deriveAgentIdentityPda,\n deriveCompanyPda,\n deriveDailyAnchorPda,\n deriveDeploymentPda,\n deriveOperationsPda,\n derivePolicyPda,\n deriveProtocolFeePda,\n deriveTreasuryPda,\n u32LeBytes,\n} from \"./pda\";\n\n// Anchor instruction discriminators — copied verbatim from\n// `packages/occa-sdk/src/idl/registry.json`. If the program is rebuilt\n// with renamed instructions, regen the IDL and update both.\n//\n// Authority model: every state-changing ix is signed by `owner` (the\n// user wallet). The operator hot wallet sponsors fees only — it never\n// appears as a signer authority on any account.\nexport const INSTRUCTION_DISCRIMINATOR = {\n createCompany: Buffer.from([36, 192, 217, 147, 233, 129, 198, 18]),\n updateCompanyMetadata: Buffer.from([186, 229, 190, 16, 234, 141, 170, 89]),\n updateCompanyStatus: Buffer.from([61, 6, 101, 120, 141, 13, 125, 75]),\n registerAgentIdentity: Buffer.from([57, 31, 242, 205, 57, 129, 123, 35]),\n updateAgentIdentityMetadata: Buffer.from([\n 250, 182, 24, 200, 201, 147, 60, 183,\n ]),\n createDeployment: Buffer.from([55, 207, 186, 101, 21, 218, 102, 171]),\n updateDeploymentMetadata: Buffer.from([100, 135, 41, 32, 16, 41, 29, 76]),\n updateDeploymentStatus: Buffer.from([225, 195, 150, 254, 178, 203, 53, 147]),\n retireDeployment: Buffer.from([45, 188, 162, 197, 136, 180, 202, 153]),\n setReceivingAddress: Buffer.from([70, 63, 44, 87, 16, 6, 156, 200]),\n commitDailyAnchor: Buffer.from([18, 7, 3, 65, 58, 148, 164, 0]),\n} as const;\n\n// ── Borsh primitives ────────────────────────────────────────────────────────\n\nfunction encodeString(s: string): Buffer {\n const utf8 = Buffer.from(s, \"utf8\");\n const len = Buffer.alloc(4);\n len.writeUInt32LE(utf8.length, 0);\n return Buffer.concat([len, utf8]);\n}\n\nfunction encodePubkey(pk: PublicKey): Buffer {\n return Buffer.from(pk.toBytes());\n}\n\nfunction encodeU8(n: number): Buffer {\n if (!Number.isInteger(n) || n < 0 || n > 0xff) {\n throw new RangeError(`u8 out of range: ${n}`);\n }\n return Buffer.from([n]);\n}\n\nfunction encodeMetadataHash(hash: Uint8Array | Buffer): Buffer {\n if (hash.length !== 32) {\n throw new RangeError(`metadata_hash must be 32 bytes, got ${hash.length}`);\n }\n return Buffer.from(hash);\n}\n\n/** Borsh `Option<u32>` = 1-byte tag (0=None, 1=Some) + optional 4-byte LE. */\nfunction encodeOptionU32(value: number | null | undefined): Buffer {\n if (value === null || value === undefined) {\n return Buffer.from([0]);\n }\n return Buffer.concat([Buffer.from([1]), u32LeBytes(value)]);\n}\n\n// ── Company ────────────────────────────────────────────────────────────────\n\nexport interface CreateCompanyParams {\n /** User wallet — signer + bound into the PDA seed. Sole authority for\n * every state-changing ix on this company. Immutable. */\n owner: PublicKey;\n /** Rent payer. Typically the operator hot wallet (sponsored UX),\n * but may equal `owner`. */\n payer: PublicKey;\n nonce: number;\n name: string;\n /** BCP-47 locale tag (e.g. \"en\", \"id\"). Empty string allowed. */\n locale: string;\n /** Off-chain metadata pointer (IPFS / Arweave / HTTPS). */\n metadataUri: string;\n /** SHA-256 of canonical metadata JSON (32 bytes). Pass `Buffer.alloc(32)`\n * if metadata not yet finalized. */\n metadataHash: Uint8Array | Buffer;\n programId?: PublicKey;\n}\n\nexport function buildCreateCompanyInstruction(params: CreateCompanyParams): {\n instruction: TransactionInstruction;\n companyPda: PublicKey;\n treasuryPda: PublicKey;\n policyPda: PublicKey;\n bump: number;\n} {\n const programId = params.programId ?? REGISTRY_PROGRAM_ID;\n const { pda: companyPda, bump } = deriveCompanyPda(\n params.owner,\n params.nonce,\n programId,\n );\n // Treasury + Policy PDAs initialized atomically inside the chain ix\n // via CPI to `treasury::init_treasury` (registry/lib.rs CreateCompany\n // accounts struct). Both must be passed in the tx even though they're\n // not yet allocated — chain CPI does the `init` against them.\n const { pda: treasuryPda } = deriveTreasuryPda(companyPda);\n const { pda: policyPda } = derivePolicyPda(companyPda);\n\n const data = Buffer.concat([\n INSTRUCTION_DISCRIMINATOR.createCompany,\n u32LeBytes(params.nonce),\n encodeString(params.name),\n encodeString(params.locale),\n encodeString(params.metadataUri),\n encodeMetadataHash(params.metadataHash),\n ]);\n\n const instruction = new TransactionInstruction({\n programId,\n // Order MUST match registry/lib.rs `CreateCompany` accounts struct:\n // company, owner, payer, treasury, policy, treasury_program, system_program.\n keys: [\n { pubkey: companyPda, isSigner: false, isWritable: true },\n { pubkey: params.owner, isSigner: true, isWritable: false },\n { pubkey: params.payer, isSigner: true, isWritable: true },\n { pubkey: treasuryPda, isSigner: false, isWritable: true },\n { pubkey: policyPda, isSigner: false, isWritable: true },\n { pubkey: TREASURY_PROGRAM_ID, isSigner: false, isWritable: false },\n { pubkey: SystemProgram.programId, isSigner: false, isWritable: false },\n ],\n data,\n });\n\n return { instruction, companyPda, treasuryPda, policyPda, bump };\n}\n\nexport interface UpdateCompanyMetadataParams {\n companyPda: PublicKey;\n /** User wallet — must equal `company.owner`. */\n owner: PublicKey;\n name: string;\n locale: string;\n metadataUri: string;\n metadataHash: Uint8Array | Buffer;\n programId?: PublicKey;\n}\n\nexport function buildUpdateCompanyMetadataInstruction(\n params: UpdateCompanyMetadataParams,\n): { instruction: TransactionInstruction } {\n const programId = params.programId ?? REGISTRY_PROGRAM_ID;\n const data = Buffer.concat([\n INSTRUCTION_DISCRIMINATOR.updateCompanyMetadata,\n encodeString(params.name),\n encodeString(params.locale),\n encodeString(params.metadataUri),\n encodeMetadataHash(params.metadataHash),\n ]);\n const instruction = new TransactionInstruction({\n programId,\n keys: [\n { pubkey: params.companyPda, isSigner: false, isWritable: true },\n { pubkey: params.owner, isSigner: true, isWritable: false },\n ],\n data,\n });\n return { instruction };\n}\n\nexport interface UpdateCompanyStatusParams {\n companyPda: PublicKey;\n owner: PublicKey;\n /** 0 = Active, 1 = Paused. See `COMPANY_STATUS`. */\n newStatus: number;\n programId?: PublicKey;\n}\n\nexport function buildUpdateCompanyStatusInstruction(\n params: UpdateCompanyStatusParams,\n): { instruction: TransactionInstruction } {\n const programId = params.programId ?? REGISTRY_PROGRAM_ID;\n const data = Buffer.concat([\n INSTRUCTION_DISCRIMINATOR.updateCompanyStatus,\n encodeU8(params.newStatus),\n ]);\n const instruction = new TransactionInstruction({\n programId,\n keys: [\n { pubkey: params.companyPda, isSigner: false, isWritable: true },\n { pubkey: params.owner, isSigner: true, isWritable: false },\n ],\n data,\n });\n return { instruction };\n}\n\n// ── Agent Identity ─────────────────────────────────────────────────────────\n\nexport interface RegisterAgentIdentityParams {\n /** Stable identity key — typically a fresh keypair pubkey held by the\n * user wallet (NOT the user wallet itself). Baked into the PDA seed. */\n agentPubkey: PublicKey;\n /** Owning user wallet. Immutable — there is no transfer instruction. */\n owner: PublicKey;\n /** Rent payer (typically operator hot wallet). */\n payer: PublicKey;\n name: string;\n metadataUri: string;\n metadataHash: Uint8Array | Buffer;\n programId?: PublicKey;\n}\n\nexport function buildRegisterAgentIdentityInstruction(\n params: RegisterAgentIdentityParams,\n): {\n instruction: TransactionInstruction;\n identityPda: PublicKey;\n bump: number;\n} {\n const programId = params.programId ?? REGISTRY_PROGRAM_ID;\n const { pda: identityPda, bump } = deriveAgentIdentityPda(\n params.agentPubkey,\n programId,\n );\n\n const data = Buffer.concat([\n INSTRUCTION_DISCRIMINATOR.registerAgentIdentity,\n encodePubkey(params.agentPubkey),\n encodeString(params.name),\n encodeString(params.metadataUri),\n encodeMetadataHash(params.metadataHash),\n ]);\n\n const instruction = new TransactionInstruction({\n programId,\n keys: [\n { pubkey: identityPda, isSigner: false, isWritable: true },\n { pubkey: params.owner, isSigner: true, isWritable: false },\n { pubkey: params.payer, isSigner: true, isWritable: true },\n { pubkey: SystemProgram.programId, isSigner: false, isWritable: false },\n ],\n data,\n });\n\n return { instruction, identityPda, bump };\n}\n\nexport interface UpdateAgentIdentityMetadataParams {\n identityPda: PublicKey;\n /** User wallet — must equal `identity.owner`. */\n owner: PublicKey;\n name: string;\n metadataUri: string;\n metadataHash: Uint8Array | Buffer;\n programId?: PublicKey;\n}\n\nexport function buildUpdateAgentIdentityMetadataInstruction(\n params: UpdateAgentIdentityMetadataParams,\n): { instruction: TransactionInstruction } {\n const programId = params.programId ?? REGISTRY_PROGRAM_ID;\n const data = Buffer.concat([\n INSTRUCTION_DISCRIMINATOR.updateAgentIdentityMetadata,\n encodeString(params.name),\n encodeString(params.metadataUri),\n encodeMetadataHash(params.metadataHash),\n ]);\n const instruction = new TransactionInstruction({\n programId,\n keys: [\n { pubkey: params.identityPda, isSigner: false, isWritable: true },\n { pubkey: params.owner, isSigner: true, isWritable: false },\n ],\n data,\n });\n return { instruction };\n}\n\n// ── Deployment ─────────────────────────────────────────────────────────────\n\nexport interface CreateDeploymentParams {\n companyPda: PublicKey;\n identityPda: PublicKey;\n /** User wallet — must equal both `company.owner` and `identity.owner`. */\n owner: PublicKey;\n payer: PublicKey;\n /** Per-company u32 counter. Caller picks the next free index. */\n deploymentIndex: number;\n /** Capability persona (e.g. \"ceo\", \"sdr\"). Bounded by MAX_ROLE_LEN. */\n role: string;\n /** Reporting parent index within this company (null = top-level). */\n parentDeploymentIndex?: number | null;\n /** Pinned adapter (`PublicKey.default` = unspecified). */\n adapterId: PublicKey;\n metadataUri: string;\n metadataHash: Uint8Array | Buffer;\n programId?: PublicKey;\n}\n\nexport function buildCreateDeploymentInstruction(\n params: CreateDeploymentParams,\n): {\n instruction: TransactionInstruction;\n deploymentPda: PublicKey;\n bump: number;\n} {\n const programId = params.programId ?? REGISTRY_PROGRAM_ID;\n const { pda: deploymentPda, bump } = deriveDeploymentPda(\n params.companyPda,\n params.deploymentIndex,\n programId,\n );\n\n const data = Buffer.concat([\n INSTRUCTION_DISCRIMINATOR.createDeployment,\n u32LeBytes(params.deploymentIndex),\n encodeString(params.role),\n encodeOptionU32(params.parentDeploymentIndex),\n encodePubkey(params.adapterId),\n encodeString(params.metadataUri),\n encodeMetadataHash(params.metadataHash),\n ]);\n\n const instruction = new TransactionInstruction({\n programId,\n keys: [\n // Order matches the on-chain `CreateDeployment` accounts struct.\n { pubkey: params.companyPda, isSigner: false, isWritable: false },\n { pubkey: params.identityPda, isSigner: false, isWritable: false },\n { pubkey: params.owner, isSigner: true, isWritable: false },\n { pubkey: deploymentPda, isSigner: false, isWritable: true },\n { pubkey: params.payer, isSigner: true, isWritable: true },\n { pubkey: SystemProgram.programId, isSigner: false, isWritable: false },\n ],\n data,\n });\n\n return { instruction, deploymentPda, bump };\n}\n\nexport interface UpdateDeploymentMetadataParams {\n deploymentPda: PublicKey;\n owner: PublicKey;\n role: string;\n metadataUri: string;\n metadataHash: Uint8Array | Buffer;\n programId?: PublicKey;\n}\n\nexport function buildUpdateDeploymentMetadataInstruction(\n params: UpdateDeploymentMetadataParams,\n): { instruction: TransactionInstruction } {\n const programId = params.programId ?? REGISTRY_PROGRAM_ID;\n const data = Buffer.concat([\n INSTRUCTION_DISCRIMINATOR.updateDeploymentMetadata,\n encodeString(params.role),\n encodeString(params.metadataUri),\n encodeMetadataHash(params.metadataHash),\n ]);\n const instruction = new TransactionInstruction({\n programId,\n keys: [\n { pubkey: params.deploymentPda, isSigner: false, isWritable: true },\n { pubkey: params.owner, isSigner: true, isWritable: false },\n ],\n data,\n });\n return { instruction };\n}\n\nexport interface UpdateDeploymentStatusParams {\n deploymentPda: PublicKey;\n owner: PublicKey;\n /** 0 = Active, 1 = Paused. Use `retire_deployment` for terminal. */\n newStatus: number;\n programId?: PublicKey;\n}\n\nexport function buildUpdateDeploymentStatusInstruction(\n params: UpdateDeploymentStatusParams,\n): { instruction: TransactionInstruction } {\n const programId = params.programId ?? REGISTRY_PROGRAM_ID;\n const data = Buffer.concat([\n INSTRUCTION_DISCRIMINATOR.updateDeploymentStatus,\n encodeU8(params.newStatus),\n ]);\n const instruction = new TransactionInstruction({\n programId,\n keys: [\n { pubkey: params.deploymentPda, isSigner: false, isWritable: true },\n { pubkey: params.owner, isSigner: true, isWritable: false },\n ],\n data,\n });\n return { instruction };\n}\n\nexport interface RetireDeploymentParams {\n deploymentPda: PublicKey;\n owner: PublicKey;\n programId?: PublicKey;\n}\n\nexport function buildRetireDeploymentInstruction(\n params: RetireDeploymentParams,\n): { instruction: TransactionInstruction } {\n const programId = params.programId ?? REGISTRY_PROGRAM_ID;\n const instruction = new TransactionInstruction({\n programId,\n keys: [\n { pubkey: params.deploymentPda, isSigner: false, isWritable: true },\n { pubkey: params.owner, isSigner: true, isWritable: false },\n ],\n data: Buffer.from(INSTRUCTION_DISCRIMINATOR.retireDeployment),\n });\n return { instruction };\n}\n\nexport interface SetReceivingAddressParams {\n deploymentPda: PublicKey;\n /** User wallet — must equal `deployment.owner`. */\n owner: PublicKey;\n /** New receiving address (passive destination wallet for funds disbursed\n * *to* this agent). Pass `PublicKey.default` to clear. NEVER a signer\n * on chain — receiving address never authorizes any on-chain action. */\n newReceivingAddress: PublicKey;\n programId?: PublicKey;\n}\n\nexport function buildSetReceivingAddressInstruction(\n params: SetReceivingAddressParams,\n): { instruction: TransactionInstruction } {\n const programId = params.programId ?? REGISTRY_PROGRAM_ID;\n const data = Buffer.concat([\n INSTRUCTION_DISCRIMINATOR.setReceivingAddress,\n encodePubkey(params.newReceivingAddress),\n ]);\n const instruction = new TransactionInstruction({\n programId,\n keys: [\n { pubkey: params.deploymentPda, isSigner: false, isWritable: true },\n { pubkey: params.owner, isSigner: true, isWritable: false },\n ],\n data,\n });\n return { instruction };\n}\n\n// ── Treasury program ────────────────────────────────────────────────────────\n//\n// The treasury program is a SEPARATE program from registry — these\n// instructions target `TREASURY_PROGRAM_ID`. Discriminators copied from\n// `occa-programs/target/idl/treasury.json`.\n\nexport const TREASURY_INSTRUCTION_DISCRIMINATOR = {\n setPolicy: Buffer.from([40, 133, 12, 157, 235, 202, 2, 132]),\n disburseDiscretionary: Buffer.from([102, 176, 14, 127, 210, 4, 96, 175]),\n initProtocolFeeAccount: Buffer.from([214, 27, 184, 174, 155, 79, 141, 114]),\n registerCompanyOperations: Buffer.from([212, 173, 142, 23, 28, 221, 55, 99]),\n updateOperationsCapability: Buffer.from([21, 13, 197, 41, 92, 229, 142, 202]),\n revokeOperations: Buffer.from([141, 196, 241, 103, 182, 146, 117, 183]),\n closeOperations: Buffer.from([2, 52, 136, 225, 80, 230, 222, 120]),\n disburseRoutine: Buffer.from([45, 152, 225, 130, 133, 73, 62, 202]),\n disbursePrivileged: Buffer.from([173, 78, 248, 158, 76, 46, 88, 167]),\n} as const;\n\n// ── Borsh helpers for treasury args ─────────────────────────────────────────\n\nfunction encodeU16(n: number): Buffer {\n if (!Number.isInteger(n) || n < 0 || n > 0xffff) {\n throw new RangeError(`u16 out of range: ${n}`);\n }\n const buf = Buffer.alloc(2);\n buf.writeUInt16LE(n, 0);\n return buf;\n}\n\nfunction encodeU64(n: bigint): Buffer {\n if (n < 0n || n > 0xffff_ffff_ffff_ffffn) {\n throw new RangeError(`u64 out of range: ${n}`);\n }\n const buf = Buffer.alloc(8);\n buf.writeBigUInt64LE(n, 0);\n return buf;\n}\n\n/** A per-asset budget / balance entry. `SOL_PSEUDO_MINT` for SOL. */\nexport interface AssetBudget {\n mint: PublicKey;\n amount: bigint;\n}\n\nfunction encodeAssetBudget(b: AssetBudget): Buffer {\n return Buffer.concat([encodePubkey(b.mint), encodeU64(b.amount)]);\n}\n\n/** Borsh `Vec<T>` = 4-byte LE length + each item. */\nfunction encodeVec<T>(items: T[], encodeItem: (item: T) => Buffer): Buffer {\n return Buffer.concat([u32LeBytes(items.length), ...items.map(encodeItem)]);\n}\n\n/** Borsh `Option<T>` = 1-byte tag (0=None, 1=Some) + optional payload. */\nfunction encodeOption<T>(\n value: T | null | undefined,\n encodeSome: (v: T) => Buffer,\n): Buffer {\n if (value === null || value === undefined) return Buffer.from([0]);\n return Buffer.concat([Buffer.from([1]), encodeSome(value)]);\n}\n\n// ── set_policy ──────────────────────────────────────────────────────────────\n\nexport interface SetPolicyParams {\n companyPda: PublicKey;\n treasuryPda: PublicKey;\n policyPda: PublicKey;\n /** Must equal `company.owner` — the sole Privileged-class signer. */\n controllingAuthority: PublicKey;\n /** Per-month routine-class cap. Omit to leave unchanged. */\n routineBudgetPerMonth?: AssetBudget[];\n /** Per-month discretionary-class cap. Omit to leave unchanged. */\n discretionaryBudgetPerMonth?: AssetBudget[];\n /** SOL threshold above which Privileged-class disbursement (= owner +\n * secondary signer) is required. Omit to leave unchanged. Pass\n * `u64::MAX` (-1n cast) to disable (= secondary signer never required). */\n privilegedThresholdLamports?: bigint;\n /** Per-asset threshold variant of the above. Omit to leave unchanged. */\n privilegedThresholdPerToken?: AssetBudget[];\n /** Second signer required for Privileged-class disbursements.\n * Distinguishes three cases:\n * • `undefined` — leave unchanged\n * • `null` — clear (no secondary signer; Privileged disburse\n * then has no valid signer combination, effectively\n * disabling it)\n * • `PublicKey` — set to this pubkey */\n secondarySigner?: PublicKey | null;\n /** Agent Operating Fee in basis points. Omit to leave unchanged. */\n agentOperatingFeeBps?: number;\n /** Accepted-asset allow-list. Omit to leave unchanged. */\n acceptedAssets?: PublicKey[];\n programId?: PublicKey;\n}\n\n/**\n * Build a `set_policy` instruction. Privileged-class — signed by the\n * controlling authority (= company owner).\n *\n * Every parameter is `Option<T>`: omitted = \"leave unchanged\". For\n * `secondarySigner`, JS `null` maps to the \"clear\" case (outer Some,\n * inner None) — see the field doc above.\n */\nexport function buildSetPolicyInstruction(params: SetPolicyParams): {\n instruction: TransactionInstruction;\n} {\n const programId = params.programId ?? TREASURY_PROGRAM_ID;\n\n // Borsh `Option<Option<Pubkey>>` encoder for secondary_signer:\n // undefined → outer None (00)\n // null → outer Some, inner None (01 00)\n // pubkey → outer Some, inner Some (01 01 <32 bytes>)\n function encodeSecondarySigner(v: PublicKey | null | undefined): Buffer {\n if (v === undefined) return Buffer.from([0]);\n if (v === null) return Buffer.from([1, 0]);\n return Buffer.concat([Buffer.from([1, 1]), encodePubkey(v)]);\n }\n\n // Field order MUST match the on-chain `SetPolicyParams` struct.\n const data = Buffer.concat([\n TREASURY_INSTRUCTION_DISCRIMINATOR.setPolicy,\n // 1. routine_budget_per_month: Option<Vec<AssetBudget>>\n encodeOption(params.routineBudgetPerMonth, (v) =>\n encodeVec(v, encodeAssetBudget),\n ),\n // 2. discretionary_budget_per_month: Option<Vec<AssetBudget>>\n encodeOption(params.discretionaryBudgetPerMonth, (v) =>\n encodeVec(v, encodeAssetBudget),\n ),\n // 3. privileged_threshold_lamports: Option<u64>\n encodeOption(params.privilegedThresholdLamports, encodeU64),\n // 4. privileged_threshold_per_token: Option<Vec<AssetBudget>>\n encodeOption(params.privilegedThresholdPerToken, (v) =>\n encodeVec(v, encodeAssetBudget),\n ),\n // 5. secondary_signer: Option<Option<Pubkey>>\n encodeSecondarySigner(params.secondarySigner),\n // 6. agent_operating_fee_bps: Option<u16>\n encodeOption(params.agentOperatingFeeBps, encodeU16),\n // 7. accepted_assets: Option<Vec<Pubkey>>\n encodeOption(params.acceptedAssets, (v) => encodeVec(v, encodePubkey)),\n ]);\n\n const instruction = new TransactionInstruction({\n programId,\n // Order: company, controlling_authority, treasury, policy.\n keys: [\n { pubkey: params.companyPda, isSigner: false, isWritable: false },\n {\n pubkey: params.controllingAuthority,\n isSigner: true,\n isWritable: false,\n },\n { pubkey: params.treasuryPda, isSigner: false, isWritable: true },\n { pubkey: params.policyPda, isSigner: false, isWritable: true },\n ],\n data,\n });\n return { instruction };\n}\n\n// ── disburse_discretionary ──────────────────────────────────────────────────\n\nexport interface DisburseDiscretionaryParams {\n companyPda: PublicKey;\n treasuryPda: PublicKey;\n policyPda: PublicKey;\n /** Must equal `company.owner`. */\n controllingAuthority: PublicKey;\n /** Deployment PDA of the agent being paid — chain matches `destination`\n * against its `receiving_address`. */\n deploymentPda: PublicKey;\n /** The agent's receiving address — destination of the funds. */\n destination: PublicKey;\n /** Amount in lamports (SOL only — Phase 1). */\n amountLamports: bigint;\n /** Defaults to `SOL_PSEUDO_MINT`. */\n mint?: PublicKey;\n programId?: PublicKey;\n}\n\n/**\n * Build a `disburse_discretionary` instruction — Discretionary-class\n * payout to an agent's receiving address, signed by the controlling\n * authority. The 3% Agent Operating Fee is deducted on-chain and routed\n * to the ProtocolFeeAccount.\n */\nexport function buildDisburseDiscretionaryInstruction(\n params: DisburseDiscretionaryParams,\n): { instruction: TransactionInstruction } {\n const programId = params.programId ?? TREASURY_PROGRAM_ID;\n const mint = params.mint ?? SOL_PSEUDO_MINT;\n const { pda: protocolFeePda } = deriveProtocolFeePda();\n\n const data = Buffer.concat([\n TREASURY_INSTRUCTION_DISCRIMINATOR.disburseDiscretionary,\n encodePubkey(mint),\n encodeU64(params.amountLamports),\n ]);\n\n const instruction = new TransactionInstruction({\n programId,\n // Order: company, controlling_authority, treasury, policy,\n // deployment, destination, protocol_fee_account.\n keys: [\n { pubkey: params.companyPda, isSigner: false, isWritable: false },\n {\n pubkey: params.controllingAuthority,\n isSigner: true,\n isWritable: false,\n },\n { pubkey: params.treasuryPda, isSigner: false, isWritable: true },\n { pubkey: params.policyPda, isSigner: false, isWritable: true },\n { pubkey: params.deploymentPda, isSigner: false, isWritable: false },\n { pubkey: params.destination, isSigner: false, isWritable: true },\n { pubkey: protocolFeePda, isSigner: false, isWritable: true },\n ],\n data,\n });\n return { instruction };\n}\n\n// ── Treasury: more builders ────────────────────────────────────────────────\n\n/** Encode an i64 as little-endian 8 bytes (Borsh). */\nfunction encodeI64(n: bigint): Buffer {\n const buf = Buffer.alloc(8);\n buf.writeBigInt64LE(n, 0);\n return buf;\n}\n\n/** Encode a Borsh bool — single byte 0 or 1. */\nfunction encodeBool(b: boolean): Buffer {\n return Buffer.from([b ? 1 : 0]);\n}\n\n/** Encode an 8-byte action whitelist entry (Anchor ix discriminator). */\nfunction encodeAction(disc: Uint8Array | Buffer): Buffer {\n if (disc.length !== 8) {\n throw new RangeError(`action_whitelist entry must be 8 bytes, got ${disc.length}`);\n }\n return Buffer.from(disc);\n}\n\n// ── init_protocol_fee_account ───────────────────────────────────────────────\n\nexport interface InitProtocolFeeAccountParams {\n /** Upgrade authority of the Treasury program. Pays + signs. */\n authority: PublicKey;\n /** Long-lived withdrawal authority for accumulated fees (e.g. governance\n * multisig). Immutable after init. */\n governance: PublicKey;\n /** The Treasury program's own pubkey — passed as an account. Defaults to\n * `TREASURY_PROGRAM_ID`. */\n program?: PublicKey;\n /** The program's ProgramData PDA (BPFLoaderUpgradeable). Anchor uses this\n * to verify the signer is the upgrade authority. Caller derives:\n * `PublicKey.findProgramAddressSync([program.toBuffer()],\n * BPF_LOADER_UPGRADEABLE_PROGRAM_ID)`. */\n programData: PublicKey;\n programId?: PublicKey;\n}\n\n/**\n * Build an `init_protocol_fee_account` instruction. Singleton — call once\n * per program deployment by the upgrade authority. Subsequent calls fail\n * (PDA already initialized).\n */\nexport function buildInitProtocolFeeAccountInstruction(\n params: InitProtocolFeeAccountParams,\n): { instruction: TransactionInstruction } {\n const programId = params.programId ?? TREASURY_PROGRAM_ID;\n const programAccount = params.program ?? programId;\n const { pda: protocolFeePda } = deriveProtocolFeePda(programId);\n\n const data = Buffer.concat([\n TREASURY_INSTRUCTION_DISCRIMINATOR.initProtocolFeeAccount,\n encodePubkey(params.governance),\n ]);\n\n const instruction = new TransactionInstruction({\n programId,\n keys: [\n { pubkey: protocolFeePda, isSigner: false, isWritable: true },\n { pubkey: params.authority, isSigner: true, isWritable: true },\n { pubkey: programAccount, isSigner: false, isWritable: false },\n { pubkey: params.programData, isSigner: false, isWritable: false },\n { pubkey: SystemProgram.programId, isSigner: false, isWritable: false },\n ],\n data,\n });\n return { instruction };\n}\n\n// ── register_company_operations ─────────────────────────────────────────────\n\nexport interface RegisterCompanyOperationsParams {\n companyPda: PublicKey;\n /** Must equal `company.owner` — Privileged-class signer. */\n controllingAuthority: PublicKey;\n /** Disbursement or Anchor — determines which OperationsAccount PDA is\n * created. Order matters: enum byte is part of the seed. */\n kind: OperationsKind;\n /** Hot wallet that will sign downstream operations ix (e.g.\n * `disburse_routine` for Disbursement, `commit_daily_anchor` for Anchor). */\n signer: PublicKey;\n /** Each entry = an 8-byte Anchor instruction discriminator the signer\n * is allowed to invoke. Empty = no actions permitted (account exists\n * but is essentially disabled). */\n actionWhitelist: (Uint8Array | Buffer)[];\n /** How many disburse calls this signer may make per calendar month. */\n rateLimitPerPeriod: number;\n /** Unix seconds. `0` = never expires. */\n expiryUnix: bigint;\n /** Rent payer — typically the operator hot wallet. */\n payer: PublicKey;\n programId?: PublicKey;\n}\n\n/**\n * Build a `register_company_operations` instruction — creates an\n * OperationsAccount binding a hot wallet to a capability set. Privileged-\n * class (signed by `controlling_authority` = company owner).\n */\nexport function buildRegisterCompanyOperationsInstruction(\n params: RegisterCompanyOperationsParams,\n): { instruction: TransactionInstruction } {\n const programId = params.programId ?? TREASURY_PROGRAM_ID;\n const { pda: operationsPda } = deriveOperationsPda(\n params.companyPda,\n params.kind,\n programId,\n );\n\n const data = Buffer.concat([\n TREASURY_INSTRUCTION_DISCRIMINATOR.registerCompanyOperations,\n // kind: u8 enum byte\n Buffer.from([params.kind]),\n encodePubkey(params.signer),\n encodeVec(params.actionWhitelist, encodeAction),\n u32LeBytes(params.rateLimitPerPeriod),\n encodeI64(params.expiryUnix),\n ]);\n\n const instruction = new TransactionInstruction({\n programId,\n keys: [\n { pubkey: params.companyPda, isSigner: false, isWritable: false },\n {\n pubkey: params.controllingAuthority,\n isSigner: true,\n isWritable: false,\n },\n { pubkey: operationsPda, isSigner: false, isWritable: true },\n { pubkey: params.payer, isSigner: true, isWritable: true },\n { pubkey: SystemProgram.programId, isSigner: false, isWritable: false },\n ],\n data,\n });\n return { instruction };\n}\n\n// ── update_operations_capability ────────────────────────────────────────────\n\nexport interface UpdateOperationsCapabilityParams {\n companyPda: PublicKey;\n controllingAuthority: PublicKey;\n /** Which OperationsAccount (by kind) to update. */\n kind: OperationsKind;\n /** Each field is independently optional — omitted = \"leave unchanged\". */\n actionWhitelist?: (Uint8Array | Buffer)[];\n rateLimitPerPeriod?: number;\n /** Pass `0n` to set \"no expiry\" sentinel; `undefined` to leave unchanged. */\n expiryUnix?: bigint;\n programId?: PublicKey;\n}\n\n/**\n * Build an `update_operations_capability` instruction — Privileged-class\n * mutation of an existing OperationsAccount's whitelist / rate limit /\n * expiry. Each param is Option-encoded.\n */\nexport function buildUpdateOperationsCapabilityInstruction(\n params: UpdateOperationsCapabilityParams,\n): { instruction: TransactionInstruction } {\n const programId = params.programId ?? TREASURY_PROGRAM_ID;\n const { pda: operationsPda } = deriveOperationsPda(\n params.companyPda,\n params.kind,\n programId,\n );\n\n // Field order MUST match `UpdateOperationsCapabilityParams` struct.\n const argBody = Buffer.concat([\n encodeOption(params.actionWhitelist, (v) => encodeVec(v, encodeAction)),\n encodeOption(params.rateLimitPerPeriod, u32LeBytes),\n encodeOption(params.expiryUnix, encodeI64),\n ]);\n\n const data = Buffer.concat([\n TREASURY_INSTRUCTION_DISCRIMINATOR.updateOperationsCapability,\n argBody,\n ]);\n\n const instruction = new TransactionInstruction({\n programId,\n keys: [\n { pubkey: params.companyPda, isSigner: false, isWritable: false },\n {\n pubkey: params.controllingAuthority,\n isSigner: true,\n isWritable: false,\n },\n { pubkey: operationsPda, isSigner: false, isWritable: true },\n ],\n data,\n });\n return { instruction };\n}\n\n// ── revoke_operations ───────────────────────────────────────────────────────\n\nexport interface RevokeOperationsParams {\n companyPda: PublicKey;\n controllingAuthority: PublicKey;\n kind: OperationsKind;\n programId?: PublicKey;\n}\n\n/**\n * Build a `revoke_operations` instruction — flips the `revoked` flag on\n * the OperationsAccount. Subsequent ix attempts by the signer fail. The\n * account stays open (rent retained); call `close_operations` to reclaim.\n */\nexport function buildRevokeOperationsInstruction(\n params: RevokeOperationsParams,\n): { instruction: TransactionInstruction } {\n const programId = params.programId ?? TREASURY_PROGRAM_ID;\n const { pda: operationsPda } = deriveOperationsPda(\n params.companyPda,\n params.kind,\n programId,\n );\n\n const data = Buffer.from(TREASURY_INSTRUCTION_DISCRIMINATOR.revokeOperations);\n\n const instruction = new TransactionInstruction({\n programId,\n keys: [\n { pubkey: params.companyPda, isSigner: false, isWritable: false },\n {\n pubkey: params.controllingAuthority,\n isSigner: true,\n isWritable: false,\n },\n { pubkey: operationsPda, isSigner: false, isWritable: true },\n ],\n data,\n });\n return { instruction };\n}\n\n// ── close_operations ────────────────────────────────────────────────────────\n\nexport interface CloseOperationsParams {\n companyPda: PublicKey;\n /** Rent refund destination + signer. */\n controllingAuthority: PublicKey;\n kind: OperationsKind;\n programId?: PublicKey;\n}\n\n/**\n * Build a `close_operations` instruction — closes the OperationsAccount\n * and refunds rent to `controlling_authority`. Permanent: a new\n * register call would create a fresh account at the same PDA.\n */\nexport function buildCloseOperationsInstruction(\n params: CloseOperationsParams,\n): { instruction: TransactionInstruction } {\n const programId = params.programId ?? TREASURY_PROGRAM_ID;\n const { pda: operationsPda } = deriveOperationsPda(\n params.companyPda,\n params.kind,\n programId,\n );\n\n const data = Buffer.from(TREASURY_INSTRUCTION_DISCRIMINATOR.closeOperations);\n\n const instruction = new TransactionInstruction({\n programId,\n keys: [\n { pubkey: params.companyPda, isSigner: false, isWritable: false },\n {\n pubkey: params.controllingAuthority,\n isSigner: true,\n isWritable: true,\n },\n { pubkey: operationsPda, isSigner: false, isWritable: true },\n ],\n data,\n });\n return { instruction };\n}\n\n// ── disburse_routine ────────────────────────────────────────────────────────\n\nexport interface DisburseRoutineParams {\n companyPda: PublicKey;\n treasuryPda: PublicKey;\n policyPda: PublicKey;\n /** Disbursement-kind OperationsAccount for this company. */\n operationsPda: PublicKey;\n /** Hot wallet matching `operations.signer` — the only signer. NOT the\n * controlling authority. */\n operationsSigner: PublicKey;\n /** Deployment PDA of the agent being paid. */\n deploymentPda: PublicKey;\n /** Agent's receiving_address. Chain verifies match against deployment. */\n destination: PublicKey;\n amountLamports: bigint;\n /** Defaults to `SOL_PSEUDO_MINT`. */\n mint?: PublicKey;\n programId?: PublicKey;\n}\n\n/**\n * Build a `disburse_routine` instruction — Routine-class batched payout.\n * Signed by the Disbursement Wallet (operations_signer), NOT the company\n * owner. Whitelist + rate limit + expiry enforced on-chain by the\n * OperationsAccount. The 3% Agent Operating Fee is deducted and routed\n * to ProtocolFeeAccount.\n */\nexport function buildDisburseRoutineInstruction(\n params: DisburseRoutineParams,\n): { instruction: TransactionInstruction } {\n const programId = params.programId ?? TREASURY_PROGRAM_ID;\n const mint = params.mint ?? SOL_PSEUDO_MINT;\n const { pda: protocolFeePda } = deriveProtocolFeePda(programId);\n\n const data = Buffer.concat([\n TREASURY_INSTRUCTION_DISCRIMINATOR.disburseRoutine,\n encodePubkey(mint),\n encodeU64(params.amountLamports),\n ]);\n\n const instruction = new TransactionInstruction({\n programId,\n // Order: company, treasury, policy, operations, operations_signer,\n // deployment, destination, protocol_fee_account.\n keys: [\n { pubkey: params.companyPda, isSigner: false, isWritable: false },\n { pubkey: params.treasuryPda, isSigner: false, isWritable: true },\n { pubkey: params.policyPda, isSigner: false, isWritable: true },\n { pubkey: params.operationsPda, isSigner: false, isWritable: true },\n { pubkey: params.operationsSigner, isSigner: true, isWritable: false },\n { pubkey: params.deploymentPda, isSigner: false, isWritable: false },\n { pubkey: params.destination, isSigner: false, isWritable: true },\n { pubkey: protocolFeePda, isSigner: false, isWritable: true },\n ],\n data,\n });\n return { instruction };\n}\n\n// ── disburse_privileged ─────────────────────────────────────────────────────\n\nexport interface DisbursePrivilegedParams {\n companyPda: PublicKey;\n treasuryPda: PublicKey;\n policyPda: PublicKey;\n /** Must equal `company.owner`. */\n controllingAuthority: PublicKey;\n /** Must equal `policy.secondary_signer` (which must be set, i.e. not\n * the default pubkey, for Privileged disbursements to work). */\n secondarySigner: PublicKey;\n /** Deployment of the recipient agent when `isAgentDestination = true`.\n * Still required as a read-only account even for external destinations\n * (chain verifies it belongs to the same company). */\n deploymentPda: PublicKey;\n destination: PublicKey;\n amountLamports: bigint;\n /** Whether the destination is an in-company agent (fee applies) or an\n * external party (no fee). */\n isAgentDestination: boolean;\n mint?: PublicKey;\n programId?: PublicKey;\n}\n\n/**\n * Build a `disburse_privileged` instruction — over-threshold or\n * externally-destined payout. Requires both the controlling authority\n * (owner) AND a secondary signer. Bypasses normal budget caps; logged\n * in the policy's privileged-spent counter regardless.\n */\nexport function buildDisbursePrivilegedInstruction(\n params: DisbursePrivilegedParams,\n): { instruction: TransactionInstruction } {\n const programId = params.programId ?? TREASURY_PROGRAM_ID;\n const mint = params.mint ?? SOL_PSEUDO_MINT;\n const { pda: protocolFeePda } = deriveProtocolFeePda(programId);\n\n const data = Buffer.concat([\n TREASURY_INSTRUCTION_DISCRIMINATOR.disbursePrivileged,\n encodePubkey(mint),\n encodeU64(params.amountLamports),\n encodeBool(params.isAgentDestination),\n ]);\n\n const instruction = new TransactionInstruction({\n programId,\n // Order: company, controlling_authority, secondary_signer, treasury,\n // policy, deployment, destination, protocol_fee_account.\n keys: [\n { pubkey: params.companyPda, isSigner: false, isWritable: false },\n {\n pubkey: params.controllingAuthority,\n isSigner: true,\n isWritable: false,\n },\n { pubkey: params.secondarySigner, isSigner: true, isWritable: false },\n { pubkey: params.treasuryPda, isSigner: false, isWritable: true },\n { pubkey: params.policyPda, isSigner: false, isWritable: false },\n { pubkey: params.deploymentPda, isSigner: false, isWritable: false },\n { pubkey: params.destination, isSigner: false, isWritable: true },\n { pubkey: protocolFeePda, isSigner: false, isWritable: true },\n ],\n data,\n });\n return { instruction };\n}\n\n// ── Registry: commit_daily_anchor ───────────────────────────────────────────\n\nexport interface CommitDailyAnchorParams {\n deploymentPda: PublicKey;\n companyPda: PublicKey;\n /** Anchor Wallet — must equal `operations.signer` (kind=Anchor). */\n anchorSigner: PublicKey;\n /** Anchor-kind OperationsAccount for this company (in TREASURY program,\n * read-only here). Caller derives via `deriveOperationsPda(company,\n * OPERATIONS_KIND.Anchor)`. */\n operationsPda: PublicKey;\n /** Unix seconds aligned to 00:00:00 UTC for the day this anchor covers\n * (multiple of 86_400). Becomes part of the DailyAnchor PDA seed. */\n dayUnix: bigint;\n /** Merkle root over the day's task hashes — 32 bytes. */\n merkleRoot: Uint8Array | Buffer;\n /** Number of leaves in the Merkle tree. Must be > 0. */\n taskCount: number;\n /** Rent payer (typically the operator hot wallet). */\n payer: PublicKey;\n programId?: PublicKey;\n}\n\n/**\n * Build a `commit_daily_anchor` instruction — Anchor-class single-tx\n * commit of one agent-day's Merkle-rooted task activity. Signed by the\n * Anchor Wallet bound to the company's Anchor-kind OperationsAccount.\n *\n * Caller is responsible for:\n * 1. Hashing each task's content (Blake3) off-chain\n * 2. Building the Merkle tree\n * 3. Passing the root + leaf count here\n *\n * The on-chain handler does NOT verify the Merkle tree itself — chain\n * holds only the commitment; verification happens off-chain against the\n * trace store.\n */\nexport function buildCommitDailyAnchorInstruction(\n params: CommitDailyAnchorParams,\n): { instruction: TransactionInstruction } {\n const programId = params.programId ?? REGISTRY_PROGRAM_ID;\n if (params.merkleRoot.length !== 32) {\n throw new RangeError(\n `merkleRoot must be 32 bytes, got ${params.merkleRoot.length}`,\n );\n }\n const { pda: dailyAnchorPda } = deriveDailyAnchorPda(\n params.deploymentPda,\n params.dayUnix,\n programId,\n );\n\n const data = Buffer.concat([\n INSTRUCTION_DISCRIMINATOR.commitDailyAnchor,\n encodeI64(params.dayUnix),\n Buffer.from(params.merkleRoot),\n u32LeBytes(params.taskCount),\n ]);\n\n const instruction = new TransactionInstruction({\n programId,\n // Order: deployment, company, anchor_signer, operations, daily_anchor,\n // payer, system_program.\n keys: [\n { pubkey: params.deploymentPda, isSigner: false, isWritable: false },\n { pubkey: params.companyPda, isSigner: false, isWritable: false },\n { pubkey: params.anchorSigner, isSigner: true, isWritable: false },\n { pubkey: params.operationsPda, isSigner: false, isWritable: false },\n { pubkey: dailyAnchorPda, isSigner: false, isWritable: true },\n { pubkey: params.payer, isSigner: true, isWritable: true },\n { pubkey: SystemProgram.programId, isSigner: false, isWritable: false },\n ],\n data,\n });\n return { instruction };\n}\n","import { PublicKey } from \"@solana/web3.js\";\n\n// Registry program ID. The vanity-grinded program keypair lives at\n// `occa-programs/programs/registry/registry-keypair.json` (gitignored,\n// sibling repo). Public key is committed here so clients (server +\n// web) can derive PDAs without loading the keypair.\n//\n// NOTE: this is the devnet program ID. Mainnet will likely have a\n// different program ID — when that day comes, swap via env or config.\nexport const REGISTRY_PROGRAM_ID_BASE58 =\n \"occaTHMv5eYG5aZ85jimxTvHkBfsDCvndXC6J2k8kxr\";\n\nexport const REGISTRY_PROGRAM_ID = new PublicKey(REGISTRY_PROGRAM_ID_BASE58);\n\n// Treasury program ID — devnet. Registry's `create_company` CPIs into\n// `treasury::init_treasury` to atomically initialize the company's\n// TreasuryAccount + PolicyAccount PDAs (per design doc §6).\nexport const TREASURY_PROGRAM_ID_BASE58 =\n \"occaxyVLnurdjedWCBPrvDCCto8wGYadtTZ3nAmcVzh\";\n\nexport const TREASURY_PROGRAM_ID = new PublicKey(TREASURY_PROGRAM_ID_BASE58);\n\n// PDA seed prefixes. Must match `occa-programs/programs/registry/src/lib.rs` exactly.\nexport const COMPANY_SEED = Buffer.from(\"company\");\nexport const AGENT_IDENTITY_SEED = Buffer.from(\"agent_identity\");\nexport const DEPLOYMENT_SEED = Buffer.from(\"deployment\");\n// Treasury PDA seeds (owned by treasury program). Must match\n// `occa-programs/programs/treasury/src/lib.rs`.\nexport const TREASURY_SEED = Buffer.from(\"treasury\");\nexport const POLICY_SEED = Buffer.from(\"policy\");\nexport const PROTOCOL_FEES_SEED = Buffer.from(\"protocol_fees\");\nexport const OPERATIONS_SEED = Buffer.from(\"operations\");\n// DailyAnchor PDA seed (owned by registry program). Seeds:\n// [\"daily_anchor\", deployment_pda, day_unix_le_i64_8bytes].\nexport const DAILY_ANCHOR_SEED = Buffer.from(\"daily_anchor\");\n\n// OperationsKind discriminator byte — must match the Rust enum order in\n// `treasury/src/lib.rs`. Used as the 3rd seed byte of an OperationsAccount\n// PDA and as a u8 wire arg to `register_company_operations`.\nexport const OPERATIONS_KIND = {\n /** Disbursement Wallet — operator-held only, signs `disburse_routine`. */\n Disbursement: 0,\n /** Anchor Wallet — operator+OCCA shared, signs `commit_daily_anchor`. */\n Anchor: 1,\n} as const;\nexport type OperationsKind =\n (typeof OPERATIONS_KIND)[keyof typeof OPERATIONS_KIND];\n\n// SOL has no real SPL mint — lamports live directly on accounts. The\n// treasury program uses the default (all-zero) pubkey as the SOL marker\n// in accepted-asset lists and disbursement mint args.\nexport const SOL_PSEUDO_MINT = new PublicKey(new Uint8Array(32));\n\n// On-chain bounds — must match `occa-programs/programs/registry/src/lib.rs`.\nexport const MAX_NAME_LEN = 64;\nexport const MAX_LOCALE_LEN = 8;\nexport const MAX_ROLE_LEN = 32;\nexport const MAX_METADATA_URI_LEN = 200;\nexport const MAX_REPUTATION_URI_LEN = 200;\n\n// Status encodings — must match the on-chain constants.\nexport const COMPANY_STATUS = {\n Active: 0,\n Paused: 1,\n} as const;\nexport type CompanyStatus =\n (typeof COMPANY_STATUS)[keyof typeof COMPANY_STATUS];\n\nexport const DEPLOYMENT_STATUS = {\n Active: 0,\n Paused: 1,\n /** Terminal — retired deployments cannot be reactivated. */\n Retired: 2,\n} as const;\nexport type DeploymentStatus =\n (typeof DEPLOYMENT_STATUS)[keyof typeof DEPLOYMENT_STATUS];\n\n// Account discriminators (Anchor sha256(\"account:<Name>\")[..8]).\nexport const ACCOUNT_DISCRIMINATOR = {\n AgentIdentity: Buffer.from([11, 149, 31, 27, 186, 76, 241, 72]),\n CompanyAccount: Buffer.from([37, 215, 171, 200, 8, 141, 69, 96]),\n Deployment: Buffer.from([66, 90, 104, 89, 183, 130, 64, 178]),\n DailyAnchorAccount: Buffer.from([218, 106, 107, 94, 194, 48, 111, 254]),\n} as const;\n\n// Treasury program account discriminators — from\n// `occa-programs/target/idl/treasury.json`.\nexport const TREASURY_ACCOUNT_DISCRIMINATOR = {\n TreasuryAccount: Buffer.from([204, 140, 18, 173, 90, 152, 134, 123]),\n PolicyAccount: Buffer.from([218, 201, 183, 164, 156, 127, 81, 175]),\n ProtocolFeeAccount: Buffer.from([5, 171, 24, 9, 150, 135, 135, 201]),\n OperationsAccount: Buffer.from([185, 55, 148, 90, 151, 227, 104, 158]),\n} as const;\n","import { PublicKey } from \"@solana/web3.js\";\nimport {\n AGENT_IDENTITY_SEED,\n COMPANY_SEED,\n DAILY_ANCHOR_SEED,\n DEPLOYMENT_SEED,\n OPERATIONS_SEED,\n POLICY_SEED,\n PROTOCOL_FEES_SEED,\n REGISTRY_PROGRAM_ID,\n TREASURY_PROGRAM_ID,\n TREASURY_SEED,\n type OperationsKind,\n} from \"./constants\";\n\n/**\n * Encode a u32 as little-endian 4 bytes (matches Anchor / Borsh on-chain\n * representation when using a u32 in a PDA seed).\n */\nexport function u32LeBytes(value: number): Buffer {\n if (!Number.isInteger(value) || value < 0 || value > 0xff_ff_ff_ff) {\n throw new RangeError(`u32 out of range: ${value}`);\n }\n const buf = Buffer.alloc(4);\n buf.writeUInt32LE(value, 0);\n return buf;\n}\n\n/**\n * CompanyAccount PDA.\n *\n * seeds = [\"company\", owner, nonce_le_u32]\n *\n * Wallet-bound seed: a wallet's companies can be enumerated directly\n * from chain by probing `(owner, nonce=0..N)`. The owner is also the\n * sole authority for state-changing ix on this account.\n */\nexport function deriveCompanyPda(\n owner: PublicKey,\n nonce: number,\n programId: PublicKey = REGISTRY_PROGRAM_ID,\n): { pda: PublicKey; bump: number } {\n const [pda, bump] = PublicKey.findProgramAddressSync(\n [COMPANY_SEED, owner.toBuffer(), u32LeBytes(nonce)],\n programId,\n );\n return { pda, bump };\n}\n\n/**\n * AgentIdentity PDA.\n *\n * seeds = [\"agent_identity\", agent_pubkey]\n *\n * `agent_pubkey` is a stable identity key chosen by the caller (typically\n * a fresh keypair generated client-side). Identity is independent of any\n * company — the same identity may be deployed multiple times across the\n * same owner's companies.\n */\nexport function deriveAgentIdentityPda(\n agentPubkey: PublicKey,\n programId: PublicKey = REGISTRY_PROGRAM_ID,\n): { pda: PublicKey; bump: number } {\n const [pda, bump] = PublicKey.findProgramAddressSync(\n [AGENT_IDENTITY_SEED, agentPubkey.toBuffer()],\n programId,\n );\n return { pda, bump };\n}\n\n/**\n * Deployment PDA.\n *\n * seeds = [\"deployment\", company_pda, deployment_index_le_u32]\n *\n * `deployment_index` is a per-company u32 counter. Maintained by the\n * caller — pick the next free index. Same `agent_identity` may have\n * multiple deployments under the same company (e.g. retired then\n * re-deployed); each deployment gets its own index.\n */\nexport function deriveDeploymentPda(\n companyPda: PublicKey,\n deploymentIndex: number,\n programId: PublicKey = REGISTRY_PROGRAM_ID,\n): { pda: PublicKey; bump: number } {\n const [pda, bump] = PublicKey.findProgramAddressSync(\n [DEPLOYMENT_SEED, companyPda.toBuffer(), u32LeBytes(deploymentIndex)],\n programId,\n );\n return { pda, bump };\n}\n\n/**\n * TreasuryAccount PDA — owned by Treasury program.\n *\n * seeds = [\"treasury\", company_pda]\n *\n * Initialized atomically with PolicyAccount via Registry's `create_company`\n * CPI to `treasury::init_treasury` (design doc §6).\n */\nexport function deriveTreasuryPda(\n companyPda: PublicKey,\n programId: PublicKey = TREASURY_PROGRAM_ID,\n): { pda: PublicKey; bump: number } {\n const [pda, bump] = PublicKey.findProgramAddressSync(\n [TREASURY_SEED, companyPda.toBuffer()],\n programId,\n );\n return { pda, bump };\n}\n\n/**\n * PolicyAccount PDA — owned by Treasury program.\n *\n * seeds = [\"policy\", company_pda]\n *\n * Initialized atomically with TreasuryAccount via the same `create_company`\n * CPI flow.\n */\nexport function derivePolicyPda(\n companyPda: PublicKey,\n programId: PublicKey = TREASURY_PROGRAM_ID,\n): { pda: PublicKey; bump: number } {\n const [pda, bump] = PublicKey.findProgramAddressSync(\n [POLICY_SEED, companyPda.toBuffer()],\n programId,\n );\n return { pda, bump };\n}\n\n/**\n * ProtocolFeeAccount PDA — owned by Treasury program. Singleton: one\n * per program deployment, collects the Agent Operating Fee from every\n * intra-company agent disbursement.\n *\n * seeds = [\"protocol_fees\"]\n */\nexport function deriveProtocolFeePda(\n programId: PublicKey = TREASURY_PROGRAM_ID,\n): { pda: PublicKey; bump: number } {\n const [pda, bump] = PublicKey.findProgramAddressSync(\n [PROTOCOL_FEES_SEED],\n programId,\n );\n return { pda, bump };\n}\n\n/**\n * OperationsAccount PDA — owned by Treasury program. One per\n * (company, kind) pair, so Disbursement and Anchor capabilities never\n * share a key.\n *\n * seeds = [\"operations\", company_pda, kind_byte]\n *\n * `kind_byte` is the single-byte discriminator from `OPERATIONS_KIND`\n * (Disbursement=0, Anchor=1). Order MUST NOT change once any account\n * exists.\n */\nexport function deriveOperationsPda(\n companyPda: PublicKey,\n kind: OperationsKind,\n programId: PublicKey = TREASURY_PROGRAM_ID,\n): { pda: PublicKey; bump: number } {\n const [pda, bump] = PublicKey.findProgramAddressSync(\n [OPERATIONS_SEED, companyPda.toBuffer(), Buffer.from([kind])],\n programId,\n );\n return { pda, bump };\n}\n\n/** Encode an i64 as little-endian 8 bytes (matches Anchor / Borsh). */\nfunction i64LeBytes(value: bigint): Buffer {\n const buf = Buffer.alloc(8);\n buf.writeBigInt64LE(value, 0);\n return buf;\n}\n\n/**\n * DailyAnchorAccount PDA — owned by Registry program. One per\n * (deployment, UTC day) — captures the Merkle root over that day's\n * task hashes.\n *\n * seeds = [\"daily_anchor\", deployment_pda, day_unix_le_i64]\n *\n * `dayUnix` must be aligned to 00:00:00 UTC (multiple of 86400). The\n * on-chain handler enforces alignment; passing an unaligned value will\n * fail with a constraint error.\n */\nexport function deriveDailyAnchorPda(\n deploymentPda: PublicKey,\n dayUnix: bigint,\n programId: PublicKey = REGISTRY_PROGRAM_ID,\n): { pda: PublicKey;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AAAA,IAC1B,UAAU,OAAO,OAAO;AAAA,IACxB,OAAO,KAAK,OAAO,UAAU;AAAA,IAC7B,WAAW,OAAO,SAAS;AAAA,EAC7B,CAAC;AAED,QAAM,cAAc,IAAI,oCAAuB;AAAA,IAC7C;AAAA;AAAA;AAAA,IAGA,MAAM;AAAA,MACJ,EAAE,QAAQ,OAAO,eAAe,UAAU,OAAO,YAAY,MAAM;AAAA,MACnE,EAAE,QAAQ,OAAO,YAAY,UAAU,OAAO,YAAY,MAAM;AAAA,MAChE,EAAE,QAAQ,OAAO,cAAc,UAAU,MAAM,YAAY,MAAM;AAAA,MACjE,EAAE,QAAQ,OAAO,eAAe,UAAU,OAAO,YAAY,MAAM;AAAA,MACnE,EAAE,QAAQ,gBAAgB,UAAU,OAAO,YAAY,KAAK;AAAA,MAC5D,EAAE,QAAQ,OAAO,OAAO,UAAU,MAAM,YAAY,KAAK;AAAA,MACzD,EAAE,QAAQ,2BAAc,WAAW,UAAU,OAAO,YAAY,MAAM;AAAA,IACxE;AAAA,IACA;AAAA,EACF,CAAC;AACD,SAAO,EAAE,YAAY;AACvB;","names":["import_web3","import_web3"]}
1
+ {"version":3,"sources":["../src/instructions.ts","../src/constants.ts","../src/pda.ts"],"sourcesContent":["import {\n PublicKey,\n SystemProgram,\n TransactionInstruction,\n} from \"@solana/web3.js\";\nimport {\n MAX_QUALITY_SCORE,\n MAX_RESULT_URI_LEN,\n OPERATIONS_KIND,\n REGISTRY_PROGRAM_ID,\n SOL_PSEUDO_MINT,\n TREASURY_PROGRAM_ID,\n type OperationsKind,\n} from \"./constants\";\nimport {\n deriveAgentIdentityPda,\n deriveCompanyPda,\n deriveDailyAnchorPda,\n deriveDeploymentPda,\n deriveOperationsPda,\n derivePolicyPda,\n deriveProtocolFeePda,\n deriveTraceAnchorPda,\n deriveTreasuryPda,\n u32LeBytes,\n} from \"./pda\";\n\n// Anchor instruction discriminators — copied verbatim from\n// `packages/occa-sdk/src/idl/registry.json`. If the program is rebuilt\n// with renamed instructions, regen the IDL and update both.\n//\n// Authority model: every state-changing ix is signed by `owner` (the\n// user wallet). The operator hot wallet sponsors fees only — it never\n// appears as a signer authority on any account.\nexport const INSTRUCTION_DISCRIMINATOR = {\n createCompany: Buffer.from([36, 192, 217, 147, 233, 129, 198, 18]),\n updateCompanyMetadata: Buffer.from([186, 229, 190, 16, 234, 141, 170, 89]),\n updateCompanyStatus: Buffer.from([61, 6, 101, 120, 141, 13, 125, 75]),\n registerAgentIdentity: Buffer.from([57, 31, 242, 205, 57, 129, 123, 35]),\n updateAgentIdentityMetadata: Buffer.from([\n 250, 182, 24, 200, 201, 147, 60, 183,\n ]),\n createDeployment: Buffer.from([55, 207, 186, 101, 21, 218, 102, 171]),\n updateDeploymentMetadata: Buffer.from([100, 135, 41, 32, 16, 41, 29, 76]),\n updateDeploymentStatus: Buffer.from([225, 195, 150, 254, 178, 203, 53, 147]),\n retireDeployment: Buffer.from([45, 188, 162, 197, 136, 180, 202, 153]),\n setReceivingAddress: Buffer.from([70, 63, 44, 87, 16, 6, 156, 200]),\n setAgentReceivingAddress: Buffer.from([197, 126, 122, 18, 38, 62, 179, 218]),\n commitDailyAnchor: Buffer.from([18, 7, 3, 65, 58, 148, 164, 0]),\n commitTrace: Buffer.from([58, 140, 230, 51, 170, 109, 228, 125]),\n} as const;\n\n// ── Borsh primitives ────────────────────────────────────────────────────────\n\nfunction encodeString(s: string): Buffer {\n const utf8 = Buffer.from(s, \"utf8\");\n const len = Buffer.alloc(4);\n len.writeUInt32LE(utf8.length, 0);\n return Buffer.concat([len, utf8]);\n}\n\nfunction encodePubkey(pk: PublicKey): Buffer {\n return Buffer.from(pk.toBytes());\n}\n\nfunction encodeU8(n: number): Buffer {\n if (!Number.isInteger(n) || n < 0 || n > 0xff) {\n throw new RangeError(`u8 out of range: ${n}`);\n }\n return Buffer.from([n]);\n}\n\nfunction encodeMetadataHash(hash: Uint8Array | Buffer): Buffer {\n if (hash.length !== 32) {\n throw new RangeError(`metadata_hash must be 32 bytes, got ${hash.length}`);\n }\n return Buffer.from(hash);\n}\n\n/** Borsh `Option<u32>` = 1-byte tag (0=None, 1=Some) + optional 4-byte LE. */\nfunction encodeOptionU32(value: number | null | undefined): Buffer {\n if (value === null || value === undefined) {\n return Buffer.from([0]);\n }\n return Buffer.concat([Buffer.from([1]), u32LeBytes(value)]);\n}\n\n// ── Company ────────────────────────────────────────────────────────────────\n\nexport interface CreateCompanyParams {\n /** User wallet — signer + bound into the PDA seed. Sole authority for\n * every state-changing ix on this company. Immutable. */\n owner: PublicKey;\n /** Rent payer. Typically the operator hot wallet (sponsored UX),\n * but may equal `owner`. */\n payer: PublicKey;\n nonce: number;\n name: string;\n /** BCP-47 locale tag (e.g. \"en\", \"id\"). Empty string allowed. */\n locale: string;\n /** Off-chain metadata pointer (IPFS / Arweave / HTTPS). */\n metadataUri: string;\n /** SHA-256 of canonical metadata JSON (32 bytes). Pass `Buffer.alloc(32)`\n * if metadata not yet finalized. */\n metadataHash: Uint8Array | Buffer;\n programId?: PublicKey;\n}\n\nexport function buildCreateCompanyInstruction(params: CreateCompanyParams): {\n instruction: TransactionInstruction;\n companyPda: PublicKey;\n treasuryPda: PublicKey;\n policyPda: PublicKey;\n bump: number;\n} {\n const programId = params.programId ?? REGISTRY_PROGRAM_ID;\n const { pda: companyPda, bump } = deriveCompanyPda(\n params.owner,\n params.nonce,\n programId,\n );\n // Treasury + Policy PDAs initialized atomically inside the chain ix\n // via CPI to `treasury::init_treasury` (registry/lib.rs CreateCompany\n // accounts struct). Both must be passed in the tx even though they're\n // not yet allocated — chain CPI does the `init` against them.\n const { pda: treasuryPda } = deriveTreasuryPda(companyPda);\n const { pda: policyPda } = derivePolicyPda(companyPda);\n\n const data = Buffer.concat([\n INSTRUCTION_DISCRIMINATOR.createCompany,\n u32LeBytes(params.nonce),\n encodeString(params.name),\n encodeString(params.locale),\n encodeString(params.metadataUri),\n encodeMetadataHash(params.metadataHash),\n ]);\n\n const instruction = new TransactionInstruction({\n programId,\n // Order MUST match registry/lib.rs `CreateCompany` accounts struct:\n // company, owner, payer, treasury, policy, treasury_program, system_program.\n keys: [\n { pubkey: companyPda, isSigner: false, isWritable: true },\n { pubkey: params.owner, isSigner: true, isWritable: false },\n { pubkey: params.payer, isSigner: true, isWritable: true },\n { pubkey: treasuryPda, isSigner: false, isWritable: true },\n { pubkey: policyPda, isSigner: false, isWritable: true },\n { pubkey: TREASURY_PROGRAM_ID, isSigner: false, isWritable: false },\n { pubkey: SystemProgram.programId, isSigner: false, isWritable: false },\n ],\n data,\n });\n\n return { instruction, companyPda, treasuryPda, policyPda, bump };\n}\n\nexport interface UpdateCompanyMetadataParams {\n companyPda: PublicKey;\n /** User wallet — must equal `company.owner`. */\n owner: PublicKey;\n name: string;\n locale: string;\n metadataUri: string;\n metadataHash: Uint8Array | Buffer;\n programId?: PublicKey;\n}\n\nexport function buildUpdateCompanyMetadataInstruction(\n params: UpdateCompanyMetadataParams,\n): { instruction: TransactionInstruction } {\n const programId = params.programId ?? REGISTRY_PROGRAM_ID;\n const data = Buffer.concat([\n INSTRUCTION_DISCRIMINATOR.updateCompanyMetadata,\n encodeString(params.name),\n encodeString(params.locale),\n encodeString(params.metadataUri),\n encodeMetadataHash(params.metadataHash),\n ]);\n const instruction = new TransactionInstruction({\n programId,\n keys: [\n { pubkey: params.companyPda, isSigner: false, isWritable: true },\n { pubkey: params.owner, isSigner: true, isWritable: false },\n ],\n data,\n });\n return { instruction };\n}\n\nexport interface UpdateCompanyStatusParams {\n companyPda: PublicKey;\n owner: PublicKey;\n /** 0 = Active, 1 = Paused. See `COMPANY_STATUS`. */\n newStatus: number;\n programId?: PublicKey;\n}\n\nexport function buildUpdateCompanyStatusInstruction(\n params: UpdateCompanyStatusParams,\n): { instruction: TransactionInstruction } {\n const programId = params.programId ?? REGISTRY_PROGRAM_ID;\n const data = Buffer.concat([\n INSTRUCTION_DISCRIMINATOR.updateCompanyStatus,\n encodeU8(params.newStatus),\n ]);\n const instruction = new TransactionInstruction({\n programId,\n keys: [\n { pubkey: params.companyPda, isSigner: false, isWritable: true },\n { pubkey: params.owner, isSigner: true, isWritable: false },\n ],\n data,\n });\n return { instruction };\n}\n\n// ── Agent Identity ─────────────────────────────────────────────────────────\n\nexport interface RegisterAgentIdentityParams {\n /** Stable identity key — typically a fresh keypair pubkey held by the\n * user wallet (NOT the user wallet itself). Baked into the PDA seed. */\n agentPubkey: PublicKey;\n /** Owning user wallet. Immutable — there is no transfer instruction. */\n owner: PublicKey;\n /** Rent payer (typically operator hot wallet). */\n payer: PublicKey;\n name: string;\n metadataUri: string;\n metadataHash: Uint8Array | Buffer;\n programId?: PublicKey;\n}\n\nexport function buildRegisterAgentIdentityInstruction(\n params: RegisterAgentIdentityParams,\n): {\n instruction: TransactionInstruction;\n identityPda: PublicKey;\n bump: number;\n} {\n const programId = params.programId ?? REGISTRY_PROGRAM_ID;\n const { pda: identityPda, bump } = deriveAgentIdentityPda(\n params.agentPubkey,\n programId,\n );\n\n const data = Buffer.concat([\n INSTRUCTION_DISCRIMINATOR.registerAgentIdentity,\n encodePubkey(params.agentPubkey),\n encodeString(params.name),\n encodeString(params.metadataUri),\n encodeMetadataHash(params.metadataHash),\n ]);\n\n const instruction = new TransactionInstruction({\n programId,\n keys: [\n { pubkey: identityPda, isSigner: false, isWritable: true },\n { pubkey: params.owner, isSigner: true, isWritable: false },\n { pubkey: params.payer, isSigner: true, isWritable: true },\n { pubkey: SystemProgram.programId, isSigner: false, isWritable: false },\n ],\n data,\n });\n\n return { instruction, identityPda, bump };\n}\n\nexport interface UpdateAgentIdentityMetadataParams {\n identityPda: PublicKey;\n /** User wallet — must equal `identity.owner`. */\n owner: PublicKey;\n name: string;\n metadataUri: string;\n metadataHash: Uint8Array | Buffer;\n programId?: PublicKey;\n}\n\nexport function buildUpdateAgentIdentityMetadataInstruction(\n params: UpdateAgentIdentityMetadataParams,\n): { instruction: TransactionInstruction } {\n const programId = params.programId ?? REGISTRY_PROGRAM_ID;\n const data = Buffer.concat([\n INSTRUCTION_DISCRIMINATOR.updateAgentIdentityMetadata,\n encodeString(params.name),\n encodeString(params.metadataUri),\n encodeMetadataHash(params.metadataHash),\n ]);\n const instruction = new TransactionInstruction({\n programId,\n keys: [\n { pubkey: params.identityPda, isSigner: false, isWritable: true },\n { pubkey: params.owner, isSigner: true, isWritable: false },\n ],\n data,\n });\n return { instruction };\n}\n\n// ── Deployment ─────────────────────────────────────────────────────────────\n\nexport interface CreateDeploymentParams {\n companyPda: PublicKey;\n identityPda: PublicKey;\n /** User wallet — must equal both `company.owner` and `identity.owner`. */\n owner: PublicKey;\n payer: PublicKey;\n /** Per-company u32 counter. Caller picks the next free index. */\n deploymentIndex: number;\n /** Capability persona (e.g. \"ceo\", \"sdr\"). Bounded by MAX_ROLE_LEN. */\n role: string;\n /** Reporting parent index within this company (null = top-level). */\n parentDeploymentIndex?: number | null;\n /** Pinned adapter (`PublicKey.default` = unspecified). */\n adapterId: PublicKey;\n metadataUri: string;\n metadataHash: Uint8Array | Buffer;\n programId?: PublicKey;\n}\n\nexport function buildCreateDeploymentInstruction(\n params: CreateDeploymentParams,\n): {\n instruction: TransactionInstruction;\n deploymentPda: PublicKey;\n bump: number;\n} {\n const programId = params.programId ?? REGISTRY_PROGRAM_ID;\n const { pda: deploymentPda, bump } = deriveDeploymentPda(\n params.companyPda,\n params.deploymentIndex,\n programId,\n );\n\n const data = Buffer.concat([\n INSTRUCTION_DISCRIMINATOR.createDeployment,\n u32LeBytes(params.deploymentIndex),\n encodeString(params.role),\n encodeOptionU32(params.parentDeploymentIndex),\n encodePubkey(params.adapterId),\n encodeString(params.metadataUri),\n encodeMetadataHash(params.metadataHash),\n ]);\n\n const instruction = new TransactionInstruction({\n programId,\n keys: [\n // Order matches the on-chain `CreateDeployment` accounts struct.\n { pubkey: params.companyPda, isSigner: false, isWritable: false },\n { pubkey: params.identityPda, isSigner: false, isWritable: false },\n { pubkey: params.owner, isSigner: true, isWritable: false },\n { pubkey: deploymentPda, isSigner: false, isWritable: true },\n { pubkey: params.payer, isSigner: true, isWritable: true },\n { pubkey: SystemProgram.programId, isSigner: false, isWritable: false },\n ],\n data,\n });\n\n return { instruction, deploymentPda, bump };\n}\n\nexport interface UpdateDeploymentMetadataParams {\n deploymentPda: PublicKey;\n owner: PublicKey;\n role: string;\n metadataUri: string;\n metadataHash: Uint8Array | Buffer;\n programId?: PublicKey;\n}\n\nexport function buildUpdateDeploymentMetadataInstruction(\n params: UpdateDeploymentMetadataParams,\n): { instruction: TransactionInstruction } {\n const programId = params.programId ?? REGISTRY_PROGRAM_ID;\n const data = Buffer.concat([\n INSTRUCTION_DISCRIMINATOR.updateDeploymentMetadata,\n encodeString(params.role),\n encodeString(params.metadataUri),\n encodeMetadataHash(params.metadataHash),\n ]);\n const instruction = new TransactionInstruction({\n programId,\n keys: [\n { pubkey: params.deploymentPda, isSigner: false, isWritable: true },\n { pubkey: params.owner, isSigner: true, isWritable: false },\n ],\n data,\n });\n return { instruction };\n}\n\nexport interface UpdateDeploymentStatusParams {\n deploymentPda: PublicKey;\n owner: PublicKey;\n /** 0 = Active, 1 = Paused. Use `retire_deployment` for terminal. */\n newStatus: number;\n programId?: PublicKey;\n}\n\nexport function buildUpdateDeploymentStatusInstruction(\n params: UpdateDeploymentStatusParams,\n): { instruction: TransactionInstruction } {\n const programId = params.programId ?? REGISTRY_PROGRAM_ID;\n const data = Buffer.concat([\n INSTRUCTION_DISCRIMINATOR.updateDeploymentStatus,\n encodeU8(params.newStatus),\n ]);\n const instruction = new TransactionInstruction({\n programId,\n keys: [\n { pubkey: params.deploymentPda, isSigner: false, isWritable: true },\n { pubkey: params.owner, isSigner: true, isWritable: false },\n ],\n data,\n });\n return { instruction };\n}\n\nexport interface RetireDeploymentParams {\n deploymentPda: PublicKey;\n owner: PublicKey;\n programId?: PublicKey;\n}\n\nexport function buildRetireDeploymentInstruction(\n params: RetireDeploymentParams,\n): { instruction: TransactionInstruction } {\n const programId = params.programId ?? REGISTRY_PROGRAM_ID;\n const instruction = new TransactionInstruction({\n programId,\n keys: [\n { pubkey: params.deploymentPda, isSigner: false, isWritable: true },\n { pubkey: params.owner, isSigner: true, isWritable: false },\n ],\n data: Buffer.from(INSTRUCTION_DISCRIMINATOR.retireDeployment),\n });\n return { instruction };\n}\n\nexport interface SetReceivingAddressParams {\n deploymentPda: PublicKey;\n /** User wallet — must equal `deployment.owner`. */\n owner: PublicKey;\n /** New receiving address (passive destination wallet for funds disbursed\n * *to* this agent). Pass `PublicKey.default` to clear. NEVER a signer\n * on chain — receiving address never authorizes any on-chain action. */\n newReceivingAddress: PublicKey;\n programId?: PublicKey;\n}\n\nexport function buildSetReceivingAddressInstruction(\n params: SetReceivingAddressParams,\n): { instruction: TransactionInstruction } {\n const programId = params.programId ?? REGISTRY_PROGRAM_ID;\n const data = Buffer.concat([\n INSTRUCTION_DISCRIMINATOR.setReceivingAddress,\n encodePubkey(params.newReceivingAddress),\n ]);\n const instruction = new TransactionInstruction({\n programId,\n keys: [\n { pubkey: params.deploymentPda, isSigner: false, isWritable: true },\n { pubkey: params.owner, isSigner: true, isWritable: false },\n ],\n data,\n });\n return { instruction };\n}\n\nexport interface SetAgentReceivingAddressParams {\n /** AgentIdentity PDA whose personal receiving wallet is being set. */\n identityPda: PublicKey;\n /** User wallet — must equal `identity.owner`. */\n owner: PublicKey;\n /** New personal receiving address (passive destination for funds\n * disbursed to this agent). Pass `PublicKey.default` to clear. NEVER a\n * signer — it never authorizes any on-chain action. */\n newReceivingAddress: PublicKey;\n programId?: PublicKey;\n}\n\n// Sets the agent's PERSONAL receiving wallet on the AgentIdentity itself —\n// independent of any company/deployment (Phase 4 marketplace). The deployment\n// receiving_address defaults from this at create_deployment.\nexport function buildSetAgentReceivingAddressInstruction(\n params: SetAgentReceivingAddressParams,\n): { instruction: TransactionInstruction } {\n const programId = params.programId ?? REGISTRY_PROGRAM_ID;\n const data = Buffer.concat([\n INSTRUCTION_DISCRIMINATOR.setAgentReceivingAddress,\n encodePubkey(params.newReceivingAddress),\n ]);\n const instruction = new TransactionInstruction({\n programId,\n keys: [\n { pubkey: params.identityPda, isSigner: false, isWritable: true },\n { pubkey: params.owner, isSigner: true, isWritable: false },\n ],\n data,\n });\n return { instruction };\n}\n\n// ── Treasury program ────────────────────────────────────────────────────────\n//\n// The treasury program is a SEPARATE program from registry — these\n// instructions target `TREASURY_PROGRAM_ID`. Discriminators copied from\n// `occa-programs/target/idl/treasury.json`.\n\nexport const TREASURY_INSTRUCTION_DISCRIMINATOR = {\n setPolicy: Buffer.from([40, 133, 12, 157, 235, 202, 2, 132]),\n disburseDiscretionary: Buffer.from([102, 176, 14, 127, 210, 4, 96, 175]),\n initProtocolFeeAccount: Buffer.from([214, 27, 184, 174, 155, 79, 141, 114]),\n registerCompanyOperations: Buffer.from([212, 173, 142, 23, 28, 221, 55, 99]),\n updateOperationsCapability: Buffer.from([21, 13, 197, 41, 92, 229, 142, 202]),\n revokeOperations: Buffer.from([141, 196, 241, 103, 182, 146, 117, 183]),\n closeOperations: Buffer.from([2, 52, 136, 225, 80, 230, 222, 120]),\n disburseRoutine: Buffer.from([45, 152, 225, 130, 133, 73, 62, 202]),\n disbursePrivileged: Buffer.from([173, 78, 248, 158, 76, 46, 88, 167]),\n} as const;\n\n// ── Borsh helpers for treasury args ─────────────────────────────────────────\n\nfunction encodeU16(n: number): Buffer {\n if (!Number.isInteger(n) || n < 0 || n > 0xffff) {\n throw new RangeError(`u16 out of range: ${n}`);\n }\n const buf = Buffer.alloc(2);\n buf.writeUInt16LE(n, 0);\n return buf;\n}\n\nfunction encodeU64(n: bigint): Buffer {\n if (n < 0n || n > 0xffff_ffff_ffff_ffffn) {\n throw new RangeError(`u64 out of range: ${n}`);\n }\n const buf = Buffer.alloc(8);\n buf.writeBigUInt64LE(n, 0);\n return buf;\n}\n\n/** A per-asset budget / balance entry. `SOL_PSEUDO_MINT` for SOL. */\nexport interface AssetBudget {\n mint: PublicKey;\n amount: bigint;\n}\n\nfunction encodeAssetBudget(b: AssetBudget): Buffer {\n return Buffer.concat([encodePubkey(b.mint), encodeU64(b.amount)]);\n}\n\n/** Borsh `Vec<T>` = 4-byte LE length + each item. */\nfunction encodeVec<T>(items: T[], encodeItem: (item: T) => Buffer): Buffer {\n return Buffer.concat([u32LeBytes(items.length), ...items.map(encodeItem)]);\n}\n\n/** Borsh `Option<T>` = 1-byte tag (0=None, 1=Some) + optional payload. */\nfunction encodeOption<T>(\n value: T | null | undefined,\n encodeSome: (v: T) => Buffer,\n): Buffer {\n if (value === null || value === undefined) return Buffer.from([0]);\n return Buffer.concat([Buffer.from([1]), encodeSome(value)]);\n}\n\n// ── set_policy ──────────────────────────────────────────────────────────────\n\nexport interface SetPolicyParams {\n companyPda: PublicKey;\n treasuryPda: PublicKey;\n policyPda: PublicKey;\n /** Must equal `company.owner` — the sole Privileged-class signer. */\n controllingAuthority: PublicKey;\n /** Per-month routine-class cap. Omit to leave unchanged. */\n routineBudgetPerMonth?: AssetBudget[];\n /** Per-month discretionary-class cap. Omit to leave unchanged. */\n discretionaryBudgetPerMonth?: AssetBudget[];\n /** SOL threshold above which Privileged-class disbursement (= owner +\n * secondary signer) is required. Omit to leave unchanged. Pass\n * `u64::MAX` (-1n cast) to disable (= secondary signer never required). */\n privilegedThresholdLamports?: bigint;\n /** Per-asset threshold variant of the above. Omit to leave unchanged. */\n privilegedThresholdPerToken?: AssetBudget[];\n /** Second signer required for Privileged-class disbursements.\n * Distinguishes three cases:\n * • `undefined` — leave unchanged\n * • `null` — clear (no secondary signer; Privileged disburse\n * then has no valid signer combination, effectively\n * disabling it)\n * • `PublicKey` — set to this pubkey */\n secondarySigner?: PublicKey | null;\n /** Agent Operating Fee in basis points. Omit to leave unchanged. */\n agentOperatingFeeBps?: number;\n /** Accepted-asset allow-list. Omit to leave unchanged. */\n acceptedAssets?: PublicKey[];\n programId?: PublicKey;\n}\n\n/**\n * Build a `set_policy` instruction. Privileged-class — signed by the\n * controlling authority (= company owner).\n *\n * Every parameter is `Option<T>`: omitted = \"leave unchanged\". For\n * `secondarySigner`, JS `null` maps to the \"clear\" case (outer Some,\n * inner None) — see the field doc above.\n */\nexport function buildSetPolicyInstruction(params: SetPolicyParams): {\n instruction: TransactionInstruction;\n} {\n const programId = params.programId ?? TREASURY_PROGRAM_ID;\n\n // Borsh `Option<Option<Pubkey>>` encoder for secondary_signer:\n // undefined → outer None (00)\n // null → outer Some, inner None (01 00)\n // pubkey → outer Some, inner Some (01 01 <32 bytes>)\n function encodeSecondarySigner(v: PublicKey | null | undefined): Buffer {\n if (v === undefined) return Buffer.from([0]);\n if (v === null) return Buffer.from([1, 0]);\n return Buffer.concat([Buffer.from([1, 1]), encodePubkey(v)]);\n }\n\n // Field order MUST match the on-chain `SetPolicyParams` struct.\n const data = Buffer.concat([\n TREASURY_INSTRUCTION_DISCRIMINATOR.setPolicy,\n // 1. routine_budget_per_month: Option<Vec<AssetBudget>>\n encodeOption(params.routineBudgetPerMonth, (v) =>\n encodeVec(v, encodeAssetBudget),\n ),\n // 2. discretionary_budget_per_month: Option<Vec<AssetBudget>>\n encodeOption(params.discretionaryBudgetPerMonth, (v) =>\n encodeVec(v, encodeAssetBudget),\n ),\n // 3. privileged_threshold_lamports: Option<u64>\n encodeOption(params.privilegedThresholdLamports, encodeU64),\n // 4. privileged_threshold_per_token: Option<Vec<AssetBudget>>\n encodeOption(params.privilegedThresholdPerToken, (v) =>\n encodeVec(v, encodeAssetBudget),\n ),\n // 5. secondary_signer: Option<Option<Pubkey>>\n encodeSecondarySigner(params.secondarySigner),\n // 6. agent_operating_fee_bps: Option<u16>\n encodeOption(params.agentOperatingFeeBps, encodeU16),\n // 7. accepted_assets: Option<Vec<Pubkey>>\n encodeOption(params.acceptedAssets, (v) => encodeVec(v, encodePubkey)),\n ]);\n\n const instruction = new TransactionInstruction({\n programId,\n // Order: company, controlling_authority, treasury, policy.\n keys: [\n { pubkey: params.companyPda, isSigner: false, isWritable: false },\n {\n pubkey: params.controllingAuthority,\n isSigner: true,\n isWritable: false,\n },\n { pubkey: params.treasuryPda, isSigner: false, isWritable: true },\n { pubkey: params.policyPda, isSigner: false, isWritable: true },\n ],\n data,\n });\n return { instruction };\n}\n\n// ── disburse_discretionary ──────────────────────────────────────────────────\n\nexport interface DisburseDiscretionaryParams {\n companyPda: PublicKey;\n treasuryPda: PublicKey;\n policyPda: PublicKey;\n /** Must equal `company.owner`. */\n controllingAuthority: PublicKey;\n /** Deployment PDA of the agent being paid — chain matches `destination`\n * against its `receiving_address`. */\n deploymentPda: PublicKey;\n /** The agent's receiving address — destination of the funds. */\n destination: PublicKey;\n /** Amount in lamports (SOL only — Phase 1). */\n amountLamports: bigint;\n /** Defaults to `SOL_PSEUDO_MINT`. */\n mint?: PublicKey;\n programId?: PublicKey;\n}\n\n/**\n * Build a `disburse_discretionary` instruction — Discretionary-class\n * payout to an agent's receiving address, signed by the controlling\n * authority. The 3% Agent Operating Fee is deducted on-chain and routed\n * to the ProtocolFeeAccount.\n */\nexport function buildDisburseDiscretionaryInstruction(\n params: DisburseDiscretionaryParams,\n): { instruction: TransactionInstruction } {\n const programId = params.programId ?? TREASURY_PROGRAM_ID;\n const mint = params.mint ?? SOL_PSEUDO_MINT;\n const { pda: protocolFeePda } = deriveProtocolFeePda();\n\n const data = Buffer.concat([\n TREASURY_INSTRUCTION_DISCRIMINATOR.disburseDiscretionary,\n encodePubkey(mint),\n encodeU64(params.amountLamports),\n ]);\n\n const instruction = new TransactionInstruction({\n programId,\n // Order: company, controlling_authority, treasury, policy,\n // deployment, destination, protocol_fee_account.\n keys: [\n { pubkey: params.companyPda, isSigner: false, isWritable: false },\n {\n pubkey: params.controllingAuthority,\n isSigner: true,\n isWritable: false,\n },\n { pubkey: params.treasuryPda, isSigner: false, isWritable: true },\n { pubkey: params.policyPda, isSigner: false, isWritable: true },\n { pubkey: params.deploymentPda, isSigner: false, isWritable: false },\n { pubkey: params.destination, isSigner: false, isWritable: true },\n { pubkey: protocolFeePda, isSigner: false, isWritable: true },\n ],\n data,\n });\n return { instruction };\n}\n\n// ── Treasury: more builders ────────────────────────────────────────────────\n\n/** Encode an i64 as little-endian 8 bytes (Borsh). */\nfunction encodeI64(n: bigint): Buffer {\n const buf = Buffer.alloc(8);\n buf.writeBigInt64LE(n, 0);\n return buf;\n}\n\n/** Encode a Borsh bool — single byte 0 or 1. */\nfunction encodeBool(b: boolean): Buffer {\n return Buffer.from([b ? 1 : 0]);\n}\n\n/** Encode an 8-byte action whitelist entry (Anchor ix discriminator). */\nfunction encodeAction(disc: Uint8Array | Buffer): Buffer {\n if (disc.length !== 8) {\n throw new RangeError(`action_whitelist entry must be 8 bytes, got ${disc.length}`);\n }\n return Buffer.from(disc);\n}\n\n// ── init_protocol_fee_account ───────────────────────────────────────────────\n\nexport interface InitProtocolFeeAccountParams {\n /** Upgrade authority of the Treasury program. Pays + signs. */\n authority: PublicKey;\n /** Long-lived withdrawal authority for accumulated fees (e.g. governance\n * multisig). Immutable after init. */\n governance: PublicKey;\n /** The Treasury program's own pubkey — passed as an account. Defaults to\n * `TREASURY_PROGRAM_ID`. */\n program?: PublicKey;\n /** The program's ProgramData PDA (BPFLoaderUpgradeable). Anchor uses this\n * to verify the signer is the upgrade authority. Caller derives:\n * `PublicKey.findProgramAddressSync([program.toBuffer()],\n * BPF_LOADER_UPGRADEABLE_PROGRAM_ID)`. */\n programData: PublicKey;\n programId?: PublicKey;\n}\n\n/**\n * Build an `init_protocol_fee_account` instruction. Singleton — call once\n * per program deployment by the upgrade authority. Subsequent calls fail\n * (PDA already initialized).\n */\nexport function buildInitProtocolFeeAccountInstruction(\n params: InitProtocolFeeAccountParams,\n): { instruction: TransactionInstruction } {\n const programId = params.programId ?? TREASURY_PROGRAM_ID;\n const programAccount = params.program ?? programId;\n const { pda: protocolFeePda } = deriveProtocolFeePda(programId);\n\n const data = Buffer.concat([\n TREASURY_INSTRUCTION_DISCRIMINATOR.initProtocolFeeAccount,\n encodePubkey(params.governance),\n ]);\n\n const instruction = new TransactionInstruction({\n programId,\n keys: [\n { pubkey: protocolFeePda, isSigner: false, isWritable: true },\n { pubkey: params.authority, isSigner: true, isWritable: true },\n { pubkey: programAccount, isSigner: false, isWritable: false },\n { pubkey: params.programData, isSigner: false, isWritable: false },\n { pubkey: SystemProgram.programId, isSigner: false, isWritable: false },\n ],\n data,\n });\n return { instruction };\n}\n\n// ── register_company_operations ─────────────────────────────────────────────\n\nexport interface RegisterCompanyOperationsParams {\n companyPda: PublicKey;\n /** Must equal `company.owner` — Privileged-class signer. */\n controllingAuthority: PublicKey;\n /** Disbursement or Anchor — determines which OperationsAccount PDA is\n * created. Order matters: enum byte is part of the seed. */\n kind: OperationsKind;\n /** Hot wallet that will sign downstream operations ix (e.g.\n * `disburse_routine` for Disbursement, `commit_daily_anchor` for Anchor). */\n signer: PublicKey;\n /** Each entry = an 8-byte Anchor instruction discriminator the signer\n * is allowed to invoke. Empty = no actions permitted (account exists\n * but is essentially disabled). */\n actionWhitelist: (Uint8Array | Buffer)[];\n /** How many disburse calls this signer may make per calendar month. */\n rateLimitPerPeriod: number;\n /** Unix seconds. `0` = never expires. */\n expiryUnix: bigint;\n /** Rent payer — typically the operator hot wallet. */\n payer: PublicKey;\n programId?: PublicKey;\n}\n\n/**\n * Build a `register_company_operations` instruction — creates an\n * OperationsAccount binding a hot wallet to a capability set. Privileged-\n * class (signed by `controlling_authority` = company owner).\n */\nexport function buildRegisterCompanyOperationsInstruction(\n params: RegisterCompanyOperationsParams,\n): { instruction: TransactionInstruction } {\n const programId = params.programId ?? TREASURY_PROGRAM_ID;\n const { pda: operationsPda } = deriveOperationsPda(\n params.companyPda,\n params.kind,\n programId,\n );\n\n const data = Buffer.concat([\n TREASURY_INSTRUCTION_DISCRIMINATOR.registerCompanyOperations,\n // kind: u8 enum byte\n Buffer.from([params.kind]),\n encodePubkey(params.signer),\n encodeVec(params.actionWhitelist, encodeAction),\n u32LeBytes(params.rateLimitPerPeriod),\n encodeI64(params.expiryUnix),\n ]);\n\n const instruction = new TransactionInstruction({\n programId,\n keys: [\n { pubkey: params.companyPda, isSigner: false, isWritable: false },\n {\n pubkey: params.controllingAuthority,\n isSigner: true,\n isWritable: false,\n },\n { pubkey: operationsPda, isSigner: false, isWritable: true },\n { pubkey: params.payer, isSigner: true, isWritable: true },\n { pubkey: SystemProgram.programId, isSigner: false, isWritable: false },\n ],\n data,\n });\n return { instruction };\n}\n\n// ── update_operations_capability ────────────────────────────────────────────\n\nexport interface UpdateOperationsCapabilityParams {\n companyPda: PublicKey;\n controllingAuthority: PublicKey;\n /** Which OperationsAccount (by kind) to update. */\n kind: OperationsKind;\n /** Each field is independently optional — omitted = \"leave unchanged\". */\n actionWhitelist?: (Uint8Array | Buffer)[];\n rateLimitPerPeriod?: number;\n /** Pass `0n` to set \"no expiry\" sentinel; `undefined` to leave unchanged. */\n expiryUnix?: bigint;\n programId?: PublicKey;\n}\n\n/**\n * Build an `update_operations_capability` instruction — Privileged-class\n * mutation of an existing OperationsAccount's whitelist / rate limit /\n * expiry. Each param is Option-encoded.\n */\nexport function buildUpdateOperationsCapabilityInstruction(\n params: UpdateOperationsCapabilityParams,\n): { instruction: TransactionInstruction } {\n const programId = params.programId ?? TREASURY_PROGRAM_ID;\n const { pda: operationsPda } = deriveOperationsPda(\n params.companyPda,\n params.kind,\n programId,\n );\n\n // Field order MUST match `UpdateOperationsCapabilityParams` struct.\n const argBody = Buffer.concat([\n encodeOption(params.actionWhitelist, (v) => encodeVec(v, encodeAction)),\n encodeOption(params.rateLimitPerPeriod, u32LeBytes),\n encodeOption(params.expiryUnix, encodeI64),\n ]);\n\n const data = Buffer.concat([\n TREASURY_INSTRUCTION_DISCRIMINATOR.updateOperationsCapability,\n argBody,\n ]);\n\n const instruction = new TransactionInstruction({\n programId,\n keys: [\n { pubkey: params.companyPda, isSigner: false, isWritable: false },\n {\n pubkey: params.controllingAuthority,\n isSigner: true,\n isWritable: false,\n },\n { pubkey: operationsPda, isSigner: false, isWritable: true },\n ],\n data,\n });\n return { instruction };\n}\n\n// ── revoke_operations ───────────────────────────────────────────────────────\n\nexport interface RevokeOperationsParams {\n companyPda: PublicKey;\n controllingAuthority: PublicKey;\n kind: OperationsKind;\n programId?: PublicKey;\n}\n\n/**\n * Build a `revoke_operations` instruction — flips the `revoked` flag on\n * the OperationsAccount. Subsequent ix attempts by the signer fail. The\n * account stays open (rent retained); call `close_operations` to reclaim.\n */\nexport function buildRevokeOperationsInstruction(\n params: RevokeOperationsParams,\n): { instruction: TransactionInstruction } {\n const programId = params.programId ?? TREASURY_PROGRAM_ID;\n const { pda: operationsPda } = deriveOperationsPda(\n params.companyPda,\n params.kind,\n programId,\n );\n\n const data = Buffer.from(TREASURY_INSTRUCTION_DISCRIMINATOR.revokeOperations);\n\n const instruction = new TransactionInstruction({\n programId,\n keys: [\n { pubkey: params.companyPda, isSigner: false, isWritable: false },\n {\n pubkey: params.controllingAuthority,\n isSigner: true,\n isWritable: false,\n },\n { pubkey: operationsPda, isSigner: false, isWritable: true },\n ],\n data,\n });\n return { instruction };\n}\n\n// ── close_operations ────────────────────────────────────────────────────────\n\nexport interface CloseOperationsParams {\n companyPda: PublicKey;\n /** Rent refund destination + signer. */\n controllingAuthority: PublicKey;\n kind: OperationsKind;\n programId?: PublicKey;\n}\n\n/**\n * Build a `close_operations` instruction — closes the OperationsAccount\n * and refunds rent to `controlling_authority`. Permanent: a new\n * register call would create a fresh account at the same PDA.\n */\nexport function buildCloseOperationsInstruction(\n params: CloseOperationsParams,\n): { instruction: TransactionInstruction } {\n const programId = params.programId ?? TREASURY_PROGRAM_ID;\n const { pda: operationsPda } = deriveOperationsPda(\n params.companyPda,\n params.kind,\n programId,\n );\n\n const data = Buffer.from(TREASURY_INSTRUCTION_DISCRIMINATOR.closeOperations);\n\n const instruction = new TransactionInstruction({\n programId,\n keys: [\n { pubkey: params.companyPda, isSigner: false, isWritable: false },\n {\n pubkey: params.controllingAuthority,\n isSigner: true,\n isWritable: true,\n },\n { pubkey: operationsPda, isSigner: false, isWritable: true },\n ],\n data,\n });\n return { instruction };\n}\n\n// ── disburse_routine ────────────────────────────────────────────────────────\n\nexport interface DisburseRoutineParams {\n companyPda: PublicKey;\n treasuryPda: PublicKey;\n policyPda: PublicKey;\n /** Disbursement-kind OperationsAccount for this company. */\n operationsPda: PublicKey;\n /** Hot wallet matching `operations.signer` — the only signer. NOT the\n * controlling authority. */\n operationsSigner: PublicKey;\n /** Deployment PDA of the agent being paid. */\n deploymentPda: PublicKey;\n /** Agent's receiving_address. Chain verifies match against deployment. */\n destination: PublicKey;\n amountLamports: bigint;\n /** Defaults to `SOL_PSEUDO_MINT`. */\n mint?: PublicKey;\n programId?: PublicKey;\n}\n\n/**\n * Build a `disburse_routine` instruction — Routine-class batched payout.\n * Signed by the Disbursement Wallet (operations_signer), NOT the company\n * owner. Whitelist + rate limit + expiry enforced on-chain by the\n * OperationsAccount. The 3% Agent Operating Fee is deducted and routed\n * to ProtocolFeeAccount.\n */\nexport function buildDisburseRoutineInstruction(\n params: DisburseRoutineParams,\n): { instruction: TransactionInstruction } {\n const programId = params.programId ?? TREASURY_PROGRAM_ID;\n const mint = params.mint ?? SOL_PSEUDO_MINT;\n const { pda: protocolFeePda } = deriveProtocolFeePda(programId);\n\n const data = Buffer.concat([\n TREASURY_INSTRUCTION_DISCRIMINATOR.disburseRoutine,\n encodePubkey(mint),\n encodeU64(params.amountLamports),\n ]);\n\n const instruction = new TransactionInstruction({\n programId,\n // Order: company, treasury, policy, operations, operations_signer,\n // deployment, destination, protocol_fee_account.\n keys: [\n { pubkey: params.companyPda, isSigner: false, isWritable: false },\n { pubkey: params.treasuryPda, isSigner: false, isWritable: true },\n { pubkey: params.policyPda, isSigner: false, isWritable: true },\n { pubkey: params.operationsPda, isSigner: false, isWritable: true },\n { pubkey: params.operationsSigner, isSigner: true, isWritable: false },\n { pubkey: params.deploymentPda, isSigner: false, isWritable: false },\n { pubkey: params.destination, isSigner: false, isWritable: true },\n { pubkey: protocolFeePda, isSigner: false, isWritable: true },\n ],\n data,\n });\n return { instruction };\n}\n\n// ── disburse_privileged ─────────────────────────────────────────────────────\n\nexport interface DisbursePrivilegedParams {\n companyPda: PublicKey;\n treasuryPda: PublicKey;\n policyPda: PublicKey;\n /** Must equal `company.owner`. */\n controllingAuthority: PublicKey;\n /** Must equal `policy.secondary_signer` (which must be set, i.e. not\n * the default pubkey, for Privileged disbursements to work). */\n secondarySigner: PublicKey;\n /** Deployment of the recipient agent when `isAgentDestination = true`.\n * Still required as a read-only account even for external destinations\n * (chain verifies it belongs to the same company). */\n deploymentPda: PublicKey;\n destination: PublicKey;\n amountLamports: bigint;\n /** Whether the destination is an in-company agent (fee applies) or an\n * external party (no fee). */\n isAgentDestination: boolean;\n mint?: PublicKey;\n programId?: PublicKey;\n}\n\n/**\n * Build a `disburse_privileged` instruction — over-threshold or\n * externally-destined payout. Requires both the controlling authority\n * (owner) AND a secondary signer. Bypasses normal budget caps; logged\n * in the policy's privileged-spent counter regardless.\n */\nexport function buildDisbursePrivilegedInstruction(\n params: DisbursePrivilegedParams,\n): { instruction: TransactionInstruction } {\n const programId = params.programId ?? TREASURY_PROGRAM_ID;\n const mint = params.mint ?? SOL_PSEUDO_MINT;\n const { pda: protocolFeePda } = deriveProtocolFeePda(programId);\n\n const data = Buffer.concat([\n TREASURY_INSTRUCTION_DISCRIMINATOR.disbursePrivileged,\n encodePubkey(mint),\n encodeU64(params.amountLamports),\n encodeBool(params.isAgentDestination),\n ]);\n\n const instruction = new TransactionInstruction({\n programId,\n // Order: company, controlling_authority, secondary_signer, treasury,\n // policy, deployment, destination, protocol_fee_account.\n keys: [\n { pubkey: params.companyPda, isSigner: false, isWritable: false },\n {\n pubkey: params.controllingAuthority,\n isSigner: true,\n isWritable: false,\n },\n { pubkey: params.secondarySigner, isSigner: true, isWritable: false },\n { pubkey: params.treasuryPda, isSigner: false, isWritable: true },\n { pubkey: params.policyPda, isSigner: false, isWritable: false },\n { pubkey: params.deploymentPda, isSigner: false, isWritable: false },\n { pubkey: params.destination, isSigner: false, isWritable: true },\n { pubkey: protocolFeePda, isSigner: false, isWritable: true },\n ],\n data,\n });\n return { instruction };\n}\n\n// ── Registry: commit_daily_anchor ───────────────────────────────────────────\n\nexport interface CommitDailyAnchorParams {\n deploymentPda: PublicKey;\n companyPda: PublicKey;\n /** Anchor Wallet — must equal `operations.signer` (kind=Anchor). */\n anchorSigner: PublicKey;\n /** Anchor-kind OperationsAccount for this company (in TREASURY program,\n * read-only here). Caller derives via `deriveOperationsPda(company,\n * OPERATIONS_KIND.Anchor)`. */\n operationsPda: PublicKey;\n /** Unix seconds aligned to 00:00:00 UTC for the day this anchor covers\n * (multiple of 86_400). Becomes part of the DailyAnchor PDA seed. */\n dayUnix: bigint;\n /** Merkle root over the day's task hashes — 32 bytes. */\n merkleRoot: Uint8Array | Buffer;\n /** Number of leaves in the Merkle tree. Must be > 0. */\n taskCount: number;\n /** Rent payer (typically the operator hot wallet). */\n payer: PublicKey;\n programId?: PublicKey;\n}\n\n/**\n * Build a `commit_daily_anchor` instruction — Anchor-class single-tx\n * commit of one agent-day's Merkle-rooted task activity. Signed by the\n * Anchor Wallet bound to the company's Anchor-kind OperationsAccount.\n *\n * Caller is responsible for:\n * 1. Hashing each task's content (Blake3) off-chain\n * 2. Building the Merkle tree\n * 3. Passing the root + leaf count here\n *\n * The on-chain handler does NOT verify the Merkle tree itself — chain\n * holds only the commitment; verification happens off-chain against the\n * trace store.\n */\nexport function buildCommitDailyAnchorInstruction(\n params: CommitDailyAnchorParams,\n): { instruction: TransactionInstruction } {\n const programId = params.programId ?? REGISTRY_PROGRAM_ID;\n if (params.merkleRoot.length !== 32) {\n throw new RangeError(\n `merkleRoot must be 32 bytes, got ${params.merkleRoot.length}`,\n );\n }\n const { pda: dailyAnchorPda } = deriveDailyAnchorPda(\n params.deploymentPda,\n params.dayUnix,\n programId,\n );\n\n const data = Buffer.concat([\n INSTRUCTION_DISCRIMINATOR.commitDailyAnchor,\n encodeI64(params.dayUnix),\n Buffer.from(params.merkleRoot),\n u32LeBytes(params.taskCount),\n ]);\n\n const instruction = new TransactionInstruction({\n programId,\n // Order: deployment, company, anchor_signer, operations, daily_anchor,\n // payer, system_program.\n keys: [\n { pubkey: params.deploymentPda, isSigner: false, isWritable: false },\n { pubkey: params.companyPda, isSigner: false, isWritable: false },\n { pubkey: params.anchorSigner, isSigner: true, isWritable: false },\n { pubkey: params.operationsPda, isSigner: false, isWritable: false },\n { pubkey: dailyAnchorPda, isSigner: false, isWritable: true },\n { pubkey: params.payer, isSigner: true, isWritable: true },\n { pubkey: SystemProgram.programId, isSigner: false, isWritable: false },\n ],\n data,\n });\n return { instruction };\n}\n\nexport interface CommitTraceParams {\n deploymentPda: PublicKey;\n companyPda: PublicKey;\n /** Anchor Wallet — must equal `operations.signer` (kind=Anchor). */\n anchorSigner: PublicKey;\n /** Anchor-kind OperationsAccount for this company (in TREASURY program,\n * read-only here). Caller derives via `deriveOperationsPda(company,\n * OPERATIONS_KIND.Anchor)`. */\n operationsPda: PublicKey;\n /** 32-byte hash of the task creation params — globally unique, becomes\n * part of the TraceAnchor PDA seed. */\n taskId: Uint8Array | Buffer;\n /** Link to the deliverable (article URL, PR, etc). Max\n * `MAX_RESULT_URI_LEN` bytes. */\n resultUri: string;\n /** SHA-256 of the deliverable content at completion (32 bytes). */\n contentHash: Uint8Array | Buffer;\n /** Rubric quality score, 0..=`MAX_QUALITY_SCORE`. */\n qualityScore: number;\n /** Version of the scoring rubric that produced `qualityScore`. */\n rubricVersion: number;\n /** SHA-256 of the off-chain verification report (32 bytes). */\n evidenceHash: Uint8Array | Buffer;\n /** Unix seconds the deliverable was completed off-chain. Must be > 0 and\n * not in the future. */\n completedAt: bigint;\n /** Rent payer (typically the operator hot wallet). */\n payer: PublicKey;\n programId?: PublicKey;\n}\n\n/**\n * Build a `commit_trace` instruction — Anchor-class single-tx commit of one\n * completed, VERIFIED deliverable. Signed by the Anchor Wallet bound to the\n * company's Anchor-kind OperationsAccount (same authority as\n * `commit_daily_anchor`).\n *\n * Only deliverables that passed the off-chain verification gate should be\n * committed — the on-chain `verdict` is always Passed. Caller is\n * responsible for:\n * 1. Computing `contentHash` (SHA-256 of the deliverable)\n * 2. Running the verification gate + scoring rubric off-chain\n * 3. Computing `evidenceHash` (SHA-256 of the verification report)\n *\n * The verdict byte is fixed on-chain; it is not a caller arg.\n */\nexport function buildCommitTraceInstruction(params: CommitTraceParams): {\n instruction: TransactionInstruction;\n traceAnchorPda: PublicKey;\n} {\n const programId = params.programId ?? REGISTRY_PROGRAM_ID;\n if (params.taskId.length !== 32) {\n throw new RangeError(`taskId must be 32 bytes, got ${params.taskId.length}`);\n }\n if (params.contentHash.length !== 32) {\n throw new RangeError(\n `contentHash must be 32 bytes, got ${params.contentHash.length}`,\n );\n }\n if (params.evidenceHash.length !== 32) {\n throw new RangeError(\n `evidenceHash must be 32 bytes, got ${params.evidenceHash.length}`,\n );\n }\n if (Buffer.from(params.resultUri, \"utf8\").length > MAX_RESULT_URI_LEN) {\n throw new RangeError(\n `resultUri exceeds MAX_RESULT_URI_LEN (${MAX_RESULT_URI_LEN} bytes)`,\n );\n }\n if (params.qualityScore < 0 || params.qualityScore > MAX_QUALITY_SCORE) {\n throw new RangeError(\n `qualityScore out of range 0..=${MAX_QUALITY_SCORE}: ${params.qualityScore}`,\n );\n }\n\n const taskId = Buffer.from(params.taskId);\n const { pda: traceAnchorPda } = deriveTraceAnchorPda(taskId, programId);\n\n // Wire arg order must match the Rust handler: task_id, result_uri,\n // content_hash, quality_score, rubric_version, evidence_hash,\n // completed_at. verdict is NOT a wire arg (fixed Passed on-chain).\n const data = Buffer.concat([\n INSTRUCTION_DISCRIMINATOR.commitTrace,\n taskId,\n encodeString(params.resultUri),\n Buffer.from(params.contentHash),\n encodeU8(params.qualityScore),\n encodeU8(params.rubricVersion),\n Buffer.from(params.evidenceHash),\n encodeI64(params.completedAt),\n ]);\n\n const instruction = new TransactionInstruction({\n programId,\n // Order: deployment, company, anchor_signer, operations, trace_anchor,\n // payer, system_program.\n keys: [\n { pubkey: params.deploymentPda, isSigner: false, isWritable: false },\n { pubkey: params.companyPda, isSigner: false, isWritable: false },\n { pubkey: params.anchorSigner, isSigner: true, isWritable: false },\n { pubkey: params.operationsPda, isSigner: false, isWritable: false },\n { pubkey: traceAnchorPda, isSigner: false, isWritable: true },\n { pubkey: params.payer, isSigner: true, isWritable: true },\n { pubkey: SystemProgram.programId, isSigner: false, isWritable: false },\n ],\n data,\n });\n return { instruction, traceAnchorPda };\n}\n","import { PublicKey } from \"@solana/web3.js\";\n\n// Registry program ID. The vanity-grinded program keypair lives at\n// `occa-programs/programs/registry/registry-keypair.json` (gitignored,\n// sibling repo). Public key is committed here so clients (server +\n// web) can derive PDAs without loading the keypair.\n//\n// NOTE: this is the devnet program ID. Mainnet will likely have a\n// different program ID — when that day comes, swap via env or config.\nexport const REGISTRY_PROGRAM_ID_BASE58 =\n \"occaTHMv5eYG5aZ85jimxTvHkBfsDCvndXC6J2k8kxr\";\n\nexport const REGISTRY_PROGRAM_ID = new PublicKey(REGISTRY_PROGRAM_ID_BASE58);\n\n// Treasury program ID — devnet. Registry's `create_company` CPIs into\n// `treasury::init_treasury` to atomically initialize the company's\n// TreasuryAccount + PolicyAccount PDAs (per design doc §6).\nexport const TREASURY_PROGRAM_ID_BASE58 =\n \"occaxyVLnurdjedWCBPrvDCCto8wGYadtTZ3nAmcVzh\";\n\nexport const TREASURY_PROGRAM_ID = new PublicKey(TREASURY_PROGRAM_ID_BASE58);\n\n// PDA seed prefixes. Must match `occa-programs/programs/registry/src/lib.rs` exactly.\nexport const COMPANY_SEED = Buffer.from(\"company\");\nexport const AGENT_IDENTITY_SEED = Buffer.from(\"agent_identity\");\nexport const DEPLOYMENT_SEED = Buffer.from(\"deployment\");\n// Treasury PDA seeds (owned by treasury program). Must match\n// `occa-programs/programs/treasury/src/lib.rs`.\nexport const TREASURY_SEED = Buffer.from(\"treasury\");\nexport const POLICY_SEED = Buffer.from(\"policy\");\nexport const PROTOCOL_FEES_SEED = Buffer.from(\"protocol_fees\");\nexport const OPERATIONS_SEED = Buffer.from(\"operations\");\n// DailyAnchor PDA seed (owned by registry program). Seeds:\n// [\"daily_anchor\", deployment_pda, day_unix_le_i64_8bytes].\nexport const DAILY_ANCHOR_SEED = Buffer.from(\"daily_anchor\");\n// TraceAnchor PDA seed (owned by registry program). Seeds:\n// [\"trace\", task_id_32bytes]. One per completed, verified deliverable.\nexport const TRACE_SEED = Buffer.from(\"trace\");\n\n// OperationsKind discriminator byte — must match the Rust enum order in\n// `treasury/src/lib.rs`. Used as the 3rd seed byte of an OperationsAccount\n// PDA and as a u8 wire arg to `register_company_operations`.\nexport const OPERATIONS_KIND = {\n /** Disbursement Wallet — operator-held only, signs `disburse_routine`. */\n Disbursement: 0,\n /**\n * Anchor Wallet — operator+OCCA shared, signs `commit_daily_anchor`\n * and `commit_trace`.\n */\n Anchor: 1,\n} as const;\nexport type OperationsKind =\n (typeof OPERATIONS_KIND)[keyof typeof OPERATIONS_KIND];\n\n// SOL has no real SPL mint — lamports live directly on accounts. The\n// treasury program uses the default (all-zero) pubkey as the SOL marker\n// in accepted-asset lists and disbursement mint args.\nexport const SOL_PSEUDO_MINT = new PublicKey(new Uint8Array(32));\n\n// On-chain bounds — must match `occa-programs/programs/registry/src/lib.rs`.\nexport const MAX_NAME_LEN = 64;\nexport const MAX_LOCALE_LEN = 8;\nexport const MAX_ROLE_LEN = 32;\nexport const MAX_METADATA_URI_LEN = 200;\nexport const MAX_REPUTATION_URI_LEN = 200;\nexport const MAX_RESULT_URI_LEN = 200;\nexport const MAX_QUALITY_SCORE = 100;\n\n// TraceAnchorAccount.verdict encoding — only Passed deliverables are\n// anchored (failed/unverified work never reaches the chain).\nexport const TRACE_VERDICT = {\n Passed: 1,\n} as const;\nexport type TraceVerdict = (typeof TRACE_VERDICT)[keyof typeof TRACE_VERDICT];\n\n// Status encodings — must match the on-chain constants.\nexport const COMPANY_STATUS = {\n Active: 0,\n Paused: 1,\n} as const;\nexport type CompanyStatus =\n (typeof COMPANY_STATUS)[keyof typeof COMPANY_STATUS];\n\nexport const DEPLOYMENT_STATUS = {\n Active: 0,\n Paused: 1,\n /** Terminal — retired deployments cannot be reactivated. */\n Retired: 2,\n} as const;\nexport type DeploymentStatus =\n (typeof DEPLOYMENT_STATUS)[keyof typeof DEPLOYMENT_STATUS];\n\n// Account discriminators (Anchor sha256(\"account:<Name>\")[..8]).\nexport const ACCOUNT_DISCRIMINATOR = {\n AgentIdentity: Buffer.from([11, 149, 31, 27, 186, 76, 241, 72]),\n CompanyAccount: Buffer.from([37, 215, 171, 200, 8, 141, 69, 96]),\n Deployment: Buffer.from([66, 90, 104, 89, 183, 130, 64, 178]),\n DailyAnchorAccount: Buffer.from([218, 106, 107, 94, 194, 48, 111, 254]),\n TraceAnchorAccount: Buffer.from([159, 101, 186, 98, 211, 217, 119, 232]),\n} as const;\n\n// Treasury program account discriminators — from\n// `occa-programs/target/idl/treasury.json`.\nexport const TREASURY_ACCOUNT_DISCRIMINATOR = {\n TreasuryAccount: Buffer.from([204, 140, 18, 173, 90, 152, 134, 123]),\n PolicyAccount: Buffer.from([218, 201, 183, 164, 156, 127, 81, 175]),\n ProtocolFeeAccount: Buffer.from([5, 171, 24, 9, 150, 135, 135, 201]),\n OperationsAccount: Buffer.from([185, 55, 148, 90, 151, 227, 104, 158]),\n} as const;\n","import { PublicKey } from \"@solana/web3.js\";\nimport {\n AGENT_IDENTITY_SEED,\n COMPANY_SEED,\n DAILY_ANCHOR_SEED,\n DEPLOYMENT_SEED,\n OPERATIONS_SEED,\n POLICY_SEED,\n PROTOCOL_FEES_SEED,\n REGISTRY_PROGRAM_ID,\n TRACE_SEED,\n TREASURY_PROGRAM_ID,\n TREASURY_SEED,\n type OperationsKind,\n} from \"./constants\";\n\n/**\n * Encode a u32 as little-endian 4 bytes (matches Anchor / Borsh on-chain\n * representation when using a u32 in a PDA seed).\n */\nexport function u32LeBytes(value: number): Buffer {\n if (!Number.isInteger(value) || value < 0 || value > 0xff_ff_ff_ff) {\n throw new RangeError(`u32 out of range: ${value}`);\n }\n const buf = Buffer.alloc(4);\n buf.writeUInt32LE(value, 0);\n return buf;\n}\n\n/**\n * CompanyAccount PDA.\n *\n * seeds = [\"company\", owner, nonce_le_u32]\n *\n * Wallet-bound seed: a wallet's companies can be enumerated directly\n * from chain by probing `(owner, nonce=0..N)`. The owner is also the\n * sole authority for state-changing ix on this account.\n */\nexport function deriveCompanyPda(\n owner: PublicKey,\n nonce: number,\n programId: PublicKey = REGISTRY_PROGRAM_ID,\n): { pda: PublicKey; bump: number } {\n const [pda, bump] = PublicKey.findProgramAddressSync(\n [COMPANY_SEED, owner.toBuffer(), u32LeBytes(nonce)],\n programId,\n );\n return { pda, bump };\n}\n\n/**\n * AgentIdentity PDA.\n *\n * seeds = [\"agent_identity\", agent_pubkey]\n *\n * `agent_pubkey` is a stable identity key chosen by the caller (typically\n * a fresh keypair generated client-side). Identity is independent of any\n * company — the same identity may be deployed multiple times across the\n * same owner's companies.\n */\nexport function deriveAgentIdentityPda(\n agentPubkey: PublicKey,\n programId: PublicKey = REGISTRY_PROGRAM_ID,\n): { pda: PublicKey; bump: number } {\n const [pda, bump] = PublicKey.findProgramAddressSync(\n [AGENT_IDENTITY_SEED, agentPubkey.toBuffer()],\n programId,\n );\n return { pda, bump };\n}\n\n/**\n * Deployment PDA.\n *\n * seeds = [\"deployment\", company_pda, deployment_index_le_u32]\n *\n * `deployment_index` is a per-company u32 counter. Maintained by the\n * caller — pick the next free index. Same `agent_identity` may have\n * multiple deployments under the same company (e.g. retired then\n * re-deployed); each deployment gets its own index.\n */\nexport function deriveDeploymentPda(\n companyPda: PublicKey,\n deploymentIndex: number,\n programId: PublicKey = REGISTRY_PROGRAM_ID,\n): { pda: PublicKey; bump: number } {\n const [pda, bump] = PublicKey.findProgramAddressSync(\n [DEPLOYMENT_SEED, companyPda.toBuffer(), u32LeBytes(deploymentIndex)],\n programId,\n );\n return { pda, bump };\n}\n\n/**\n * TreasuryAccount PDA — owned by Treasury program.\n *\n * seeds = [\"treasury\", company_pda]\n *\n * Initialized atomically with PolicyAccount via Registry's `create_company`\n * CPI to `treasury::init_treasury` (design doc §6).\n */\nexport function deriveTreasuryPda(\n companyPda: PublicKey,\n programId: PublicKey = TREASURY_PROGRAM_ID,\n): { pda: PublicKey; bump: number } {\n const [pda, bump] = PublicKey.findProgramAddressSync(\n [TREASURY_SEED, companyPda.toBuffer()],\n programId,\n );\n return { pda, bump };\n}\n\n/**\n * PolicyAccount PDA — owned by Treasury program.\n *\n * seeds = [\"policy\", company_pda]\n *\n * Initialized atomically with TreasuryAccount via the same `create_company`\n * CPI flow.\n */\nexport function derivePolicyPda(\n companyPda: PublicKey,\n programId: PublicKey = TREASURY_PROGRAM_ID,\n): { pda: PublicKey; bump: number } {\n const [pda, bump] = PublicKey.findProgramAddressSync(\n [POLICY_SEED, companyPda.toBuffer()],\n programId,\n );\n return { pda, bump };\n}\n\n/**\n * ProtocolFeeAccount PDA — owned by Treasury program. Singleton: one\n * per program deployment, collects the Agent Operating Fee from every\n * intra-company agent disbursement.\n *\n * seeds = [\"protocol_fees\"]\n */\nexport function deriveProtocolFeePda(\n programId: PublicKey = TREASURY_PROGRAM_ID,\n): { pda: PublicKey; bump: number } {\n const [pda, bump] = PublicKey.findProgramAddressSync(\n [PROTOCOL_FEES_SEED],\n programId,\n );\n return { pda, bump };\n}\n\n/**\n * OperationsAccount PDA — owned by Treasury program. One per\n * (company, kind) pair, so Disbursement and Anchor capabilities never\n * share a key.\n *\n * seeds = [\"operations\", company_pda, kind_byte]\n *\n * `kind_byte` is the single-byte discriminator from `OPERATIONS_KIND`\n * (Disbursement=0, Anchor=1). Order MUST NOT change once any account\n * exists.\n */\nexport function deriveOperationsPda(\n companyPda: PublicKey,\n kind: OperationsKind,\n programId: PublicKey = TREASURY_PROGRAM_ID,\n): { pda: PublicKey; bump: number } {\n const [pda, bump] = PublicKey.findProgramAddressSync(\n [OPERATIONS_SEED, companyPda.toBuffer(), Buffer.from([kind])],\n programId,\n );\n return { pda, bump };\n}\n\n/** Encode an i64 as little-endian 8 bytes (matches Anchor / Borsh). */\nfunction i64LeBytes(value: bigint): Buffer {\n const buf = Buffer.alloc(8);\n buf.writeBigInt64LE(value, 0);\n return buf;\n}\n\n/**\n * DailyAnchorAccount PDA — owned by Registry program. One per\n * (deployment, UTC day) — captures the Merkle root over that day's\n * task hashes.\n *\n * seeds = [\"daily_anchor\", deployment_pda, day_unix_le_i64]\n *\n * `dayUnix` must be aligned to 00:00:00 UTC (multiple of 86400). The\n * on-chain handler enforces alignment; passing an unaligned value will\n * fail with a constraint error.\n */\nexport function deriveDailyAnchorPda(\n deploymentPda: PublicKey,\n dayUnix: bigint,\n programId: PublicKey = REGISTRY_PROGRAM_ID,\n): { pda: PublicKey; bump: number } {\n const [pda, bump] = PublicKey.findProgramAddressSync(\n [DAILY_ANCHOR_SEED, deploymentPda.toBuffer(), i64LeBytes(dayUnix)],\n programId,\n );\n return { pda, bump };\n}\n\n/**\n * TraceAnchorAccount PDA — owned by Registry program. One per completed,\n * verified deliverable (article, PR, etc).\n *\n * seeds = [\"trace\", task_id_32bytes]\n *\n * `taskId` is a 32-byte hash of the task creation params. Collision on the\n * same `taskId` means the task is already anchored — a re-commit fails\n * naturally (Anchor `init` rejects).\n */\nexport function deriveTraceAnchorPda(\n taskId: Uint8Array,\n programId: PublicKey = REGISTRY_PROGRAM_ID,\n): { pda: PublicKey; bump: number } {\n if (taskId.length !== 32) {\n throw new RangeError(`taskId must be 32 bytes, got ${taskId.length}`);\n }\n const [pda, bump] = PublicKey.findProgramAddressSync(\n [TRACE_SEED, Buffer.from(taskId)],\n programId,\n );\n return { pda, bump };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;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AC9B,CAAC;AAED,QAAM,cAAc,IAAI,oCAAuB;AAAA,IAC7C;AAAA;AAAA;AAAA,IAGA,MAAM;AAAA,MACJ,EAAE,QAAQ,OAAO,eAAe,UAAU,OAAO,YAAY,MAAM;AAAA,MACnE,EAAE,QAAQ,OAAO,YAAY,UAAU,OAAO,YAAY,MAAM;AAAA,MAChE,EAAE,QAAQ,OAAO,cAAc,UAAU,MAAM,YAAY,MAAM;AAAA,MACjE,EAAE,QAAQ,OAAO,eAAe,UAAU,OAAO,YAAY,MAAM;AAAA,MACnE,EAAE,QAAQ,gBAAgB,UAAU,OAAO,YAAY,KAAK;AAAA,MAC5D,EAAE,QAAQ,OAAO,OAAO,UAAU,MAAM,YAAY,KAAK;AAAA,MACzD,EAAE,QAAQ,2BAAc,WAAW,UAAU,OAAO,YAAY,MAAM;AAAA,IACxE;AAAA,IACA;AAAA,EACF,CAAC;AACD,SAAO,EAAE,aAAa,eAAe;AACvC;","names":["import_web3","import_web3"]}
@@ -12,7 +12,9 @@ declare const INSTRUCTION_DISCRIMINATOR: {
12
12
  readonly updateDeploymentStatus: Buffer<ArrayBuffer>;
13
13
  readonly retireDeployment: Buffer<ArrayBuffer>;
14
14
  readonly setReceivingAddress: Buffer<ArrayBuffer>;
15
+ readonly setAgentReceivingAddress: Buffer<ArrayBuffer>;
15
16
  readonly commitDailyAnchor: Buffer<ArrayBuffer>;
17
+ readonly commitTrace: Buffer<ArrayBuffer>;
16
18
  };
17
19
  interface CreateCompanyParams {
18
20
  /** User wallet — signer + bound into the PDA seed. Sole authority for
@@ -157,6 +159,20 @@ interface SetReceivingAddressParams {
157
159
  declare function buildSetReceivingAddressInstruction(params: SetReceivingAddressParams): {
158
160
  instruction: TransactionInstruction;
159
161
  };
162
+ interface SetAgentReceivingAddressParams {
163
+ /** AgentIdentity PDA whose personal receiving wallet is being set. */
164
+ identityPda: PublicKey;
165
+ /** User wallet — must equal `identity.owner`. */
166
+ owner: PublicKey;
167
+ /** New personal receiving address (passive destination for funds
168
+ * disbursed to this agent). Pass `PublicKey.default` to clear. NEVER a
169
+ * signer — it never authorizes any on-chain action. */
170
+ newReceivingAddress: PublicKey;
171
+ programId?: PublicKey;
172
+ }
173
+ declare function buildSetAgentReceivingAddressInstruction(params: SetAgentReceivingAddressParams): {
174
+ instruction: TransactionInstruction;
175
+ };
160
176
  declare const TREASURY_INSTRUCTION_DISCRIMINATOR: {
161
177
  readonly setPolicy: Buffer<ArrayBuffer>;
162
178
  readonly disburseDiscretionary: Buffer<ArrayBuffer>;
@@ -438,5 +454,54 @@ interface CommitDailyAnchorParams {
438
454
  declare function buildCommitDailyAnchorInstruction(params: CommitDailyAnchorParams): {
439
455
  instruction: TransactionInstruction;
440
456
  };
457
+ interface CommitTraceParams {
458
+ deploymentPda: PublicKey;
459
+ companyPda: PublicKey;
460
+ /** Anchor Wallet — must equal `operations.signer` (kind=Anchor). */
461
+ anchorSigner: PublicKey;
462
+ /** Anchor-kind OperationsAccount for this company (in TREASURY program,
463
+ * read-only here). Caller derives via `deriveOperationsPda(company,
464
+ * OPERATIONS_KIND.Anchor)`. */
465
+ operationsPda: PublicKey;
466
+ /** 32-byte hash of the task creation params — globally unique, becomes
467
+ * part of the TraceAnchor PDA seed. */
468
+ taskId: Uint8Array | Buffer;
469
+ /** Link to the deliverable (article URL, PR, etc). Max
470
+ * `MAX_RESULT_URI_LEN` bytes. */
471
+ resultUri: string;
472
+ /** SHA-256 of the deliverable content at completion (32 bytes). */
473
+ contentHash: Uint8Array | Buffer;
474
+ /** Rubric quality score, 0..=`MAX_QUALITY_SCORE`. */
475
+ qualityScore: number;
476
+ /** Version of the scoring rubric that produced `qualityScore`. */
477
+ rubricVersion: number;
478
+ /** SHA-256 of the off-chain verification report (32 bytes). */
479
+ evidenceHash: Uint8Array | Buffer;
480
+ /** Unix seconds the deliverable was completed off-chain. Must be > 0 and
481
+ * not in the future. */
482
+ completedAt: bigint;
483
+ /** Rent payer (typically the operator hot wallet). */
484
+ payer: PublicKey;
485
+ programId?: PublicKey;
486
+ }
487
+ /**
488
+ * Build a `commit_trace` instruction — Anchor-class single-tx commit of one
489
+ * completed, VERIFIED deliverable. Signed by the Anchor Wallet bound to the
490
+ * company's Anchor-kind OperationsAccount (same authority as
491
+ * `commit_daily_anchor`).
492
+ *
493
+ * Only deliverables that passed the off-chain verification gate should be
494
+ * committed — the on-chain `verdict` is always Passed. Caller is
495
+ * responsible for:
496
+ * 1. Computing `contentHash` (SHA-256 of the deliverable)
497
+ * 2. Running the verification gate + scoring rubric off-chain
498
+ * 3. Computing `evidenceHash` (SHA-256 of the verification report)
499
+ *
500
+ * The verdict byte is fixed on-chain; it is not a caller arg.
501
+ */
502
+ declare function buildCommitTraceInstruction(params: CommitTraceParams): {
503
+ instruction: TransactionInstruction;
504
+ traceAnchorPda: PublicKey;
505
+ };
441
506
 
442
- export { type AssetBudget, type CloseOperationsParams, type CommitDailyAnchorParams, type CreateCompanyParams, type CreateDeploymentParams, type DisburseDiscretionaryParams, type DisbursePrivilegedParams, type DisburseRoutineParams, INSTRUCTION_DISCRIMINATOR, type InitProtocolFeeAccountParams, type RegisterAgentIdentityParams, type RegisterCompanyOperationsParams, type RetireDeploymentParams, type RevokeOperationsParams, type SetPolicyParams, type SetReceivingAddressParams, TREASURY_INSTRUCTION_DISCRIMINATOR, type UpdateAgentIdentityMetadataParams, type UpdateCompanyMetadataParams, type UpdateCompanyStatusParams, type UpdateDeploymentMetadataParams, type UpdateDeploymentStatusParams, type UpdateOperationsCapabilityParams, buildCloseOperationsInstruction, buildCommitDailyAnchorInstruction, buildCreateCompanyInstruction, buildCreateDeploymentInstruction, buildDisburseDiscretionaryInstruction, buildDisbursePrivilegedInstruction, buildDisburseRoutineInstruction, buildInitProtocolFeeAccountInstruction, buildRegisterAgentIdentityInstruction, buildRegisterCompanyOperationsInstruction, buildRetireDeploymentInstruction, buildRevokeOperationsInstruction, buildSetPolicyInstruction, buildSetReceivingAddressInstruction, buildUpdateAgentIdentityMetadataInstruction, buildUpdateCompanyMetadataInstruction, buildUpdateCompanyStatusInstruction, buildUpdateDeploymentMetadataInstruction, buildUpdateDeploymentStatusInstruction, buildUpdateOperationsCapabilityInstruction };
507
+ export { type AssetBudget, type CloseOperationsParams, type CommitDailyAnchorParams, type CommitTraceParams, type CreateCompanyParams, type CreateDeploymentParams, type DisburseDiscretionaryParams, type DisbursePrivilegedParams, type DisburseRoutineParams, INSTRUCTION_DISCRIMINATOR, type InitProtocolFeeAccountParams, type RegisterAgentIdentityParams, type RegisterCompanyOperationsParams, type RetireDeploymentParams, type RevokeOperationsParams, type SetAgentReceivingAddressParams, type SetPolicyParams, type SetReceivingAddressParams, TREASURY_INSTRUCTION_DISCRIMINATOR, type UpdateAgentIdentityMetadataParams, type UpdateCompanyMetadataParams, type UpdateCompanyStatusParams, type UpdateDeploymentMetadataParams, type UpdateDeploymentStatusParams, type UpdateOperationsCapabilityParams, buildCloseOperationsInstruction, buildCommitDailyAnchorInstruction, buildCommitTraceInstruction, buildCreateCompanyInstruction, buildCreateDeploymentInstruction, buildDisburseDiscretionaryInstruction, buildDisbursePrivilegedInstruction, buildDisburseRoutineInstruction, buildInitProtocolFeeAccountInstruction, buildRegisterAgentIdentityInstruction, buildRegisterCompanyOperationsInstruction, buildRetireDeploymentInstruction, buildRevokeOperationsInstruction, buildSetAgentReceivingAddressInstruction, buildSetPolicyInstruction, buildSetReceivingAddressInstruction, buildUpdateAgentIdentityMetadataInstruction, buildUpdateCompanyMetadataInstruction, buildUpdateCompanyStatusInstruction, buildUpdateDeploymentMetadataInstruction, buildUpdateDeploymentStatusInstruction, buildUpdateOperationsCapabilityInstruction };