Skip to main content

knos_pay_interface/
lib.rs

1//! Fund and read a Knos work order from another Solana program.
2//!
3//! knos_pay holds a work order's money in escrow and pays it when GitHub signs that the order's terms were met
4//! (the token is verified on chain by knos-oidc). This crate is what a program needs to be a FUNDER by CPI: the
5//! program ids, the addresses, the three instructions a funder sends (FundOrderWallet, TopUp, RefundOrder) and a
6//! reader of the Order account. It depends on solana-program and nothing else, and none of knos_pay's code.
7//!
8//! The funder of an order is whoever signs FundOrderWallet. When that is a PDA of your program (a treasury), your
9//! program signs with `invoke_signed`; the order then refunds to a token account of that PDA and nowhere else, and
10//! its rent comes back to the PDA. The PDA must be a plain system account (no data): it pays the rent of the order.
11//!
12//! ```ignore
13//! use knos_pay_interface as knos;
14//! let f = knos::FundOrder { repo_id, issue, amount, wf_repo: knos::wf_repo_hash("drexthealpha/Knos"), wf_sha, ..Default::default() };
15//! let ix = knos::fund_order_wallet(&knos::ID, treasury.key, treasury_token.key, mint.key, token_program.key, &f, terms_json);
16//! invoke_signed(&ix, &[treasury, order, ov, treasury_token, mint, auth, token_program, system, pause], &[&[b"treasury", &[bump]]])?;
17//! let o = knos::Order::read(order.key, order.owner, &order.try_borrow_data()?, &knos::ID).ok_or(MyError::Order)?;
18//! assert!(o.amount == amount && o.refund_to == *treasury.key);
19//! ```
20//!
21//! The bytes this crate writes are checked against the Python client's (src/knos/settle/v2/pay.py) through
22//! tests/fixtures/pay_interface.json, which scripts/pay_interface_fixture.py generates; the Order in it is one the
23//! test build of knos_pay wrote.
24use solana_program::{
25    hash::hashv,
26    instruction::{AccountMeta, Instruction},
27    pubkey,
28    pubkey::Pubkey,
29    system_program,
30};
31
32/// knos_pay, the second deployment (devnet). Upgradeable only through a multisig with a public 48-hour delay, until
33/// an outside review. Every function here takes the program's id, so another cluster is another argument.
34pub const ID: Pubkey = pubkey!("5y7iWJ1VAMJjnnWbbdo2a2PsWJEwTExSNpzrvQSEnS8k");
35pub const ID_STR: &str = "5y7iWJ1VAMJjnnWbbdo2a2PsWJEwTExSNpzrvQSEnS8k";
36/// Fees go to a token account owned by this address. It has no other power.
37pub const FEE_OWNER: Pubkey = pubkey!("4G3cznCnwCUPBCZwzKiLupjdgB5pSoCcGWNGuFv4TYFo");
38pub const TOKEN: Pubkey = pubkey!("TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA");
39pub const TOKEN_2022: Pubkey = pubkey!("TokenzQdBNbLqP5VEhdkAS6EPFLC1PHnBqCXEpPxuEb");
40pub const ATA_PROGRAM: Pubkey = pubkey!("ATokenGPvbdGVxr1b2hvZbsiqW5xWH25efTNsLJA8knL");
41/// Circle's USDC: the only mints the public record counts as real money.
42pub const USDC_DEVNET: Pubkey = pubkey!("4zMMC9srt5Ri5X14GAgXhaHii3GnPAEERYPJgZJDncDU");
43pub const USDC_MAINNET: Pubkey = pubkey!("EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v");
44
45// Prices and bounds, in millionths of ONE WHOLE UNIT of the mint (`units` turns them into the mint's smallest units).
46// The fee is knos_pay 2.2's: one rate and a floor. A program at 2.1 (the public one until the upgrade to 2.2 executes)
47// charges its own, older fee; what an order was charged is always the `fee` its account holds (`Order::fee`).
48pub const FEE_BPS: u64 = 30; // 0.30%: the one rate of an order's fee, or the owner's Plan (no lower than 10)
49pub const ORDER_FEE_MIN: u64 = 50_000; // 0.05: the floor
50pub const ORDER_MIN_AMOUNT: u64 = 5_000_000;
51pub const MAX_AMOUNT: u64 = 100_000_000_000; // 100,000.00 per order on devnet
52pub const MIN_WORK: i64 = 60;
53pub const MAX_WORK: i64 = 90 * 86_400;
54pub const MAX_TERMS: usize = 600;
55
56pub const MERGE: u8 = 0; // mode: paid when the pull request that closes the issue is merged with the funded checks green
57pub const TESTS: u8 = 1; // mode: paid when the funded acceptance tests pass at the merged commit
58pub const OPEN: u8 = 1; // states
59pub const HELD: u8 = 3;
60pub const WARRANTY: u8 = 4;
61pub const F_FAUCET: u8 = 1; // flags; the program sets FAUCET and TOKEN2022, the funder the others (Opts)
62pub const F_PRIVATE: u8 = 2;
63pub const F_NEUTRAL: u8 = 4;
64pub const F_STANDING: u8 = 8;
65pub const F_TOKEN2022: u8 = 16;
66pub const ORDER_LEN: usize = 512;
67pub const OPTS_LEN: usize = 48;
68
69/// `micro` millionths of one whole unit of a mint with `decimals` decimals, in the mint's smallest units.
70pub fn units(micro: u64, decimals: u8) -> u64 {
71    if micro == 0 { return 0; }
72    let v = match 10u128.checked_pow(decimals as u32) { Some(p) => (micro as u128).saturating_mul(p) / 1_000_000, None => u128::MAX };
73    v.min(u64::MAX as u128) as u64
74}
75/// `bps` basis points of an amount, rounded down, without overflow.
76pub fn bps_of(amount: u64, bps: u64) -> u64 { amount / 10_000 * bps + amount % 10_000 * bps / 10_000 }
77/// The fee a funder pays ON TOP of an order's amount, exactly as knos_pay 2.2 computes it: `bps` (FEE_BPS for a
78/// wallet's order) of the amount, rounded down; at least ORDER_FEE_MIN; no maximum and no tiers. FundOrderWallet
79/// moves amount + order_fee(amount).
80pub fn order_fee(amount: u64, bps: u64, decimals: u8) -> u64 { bps_of(amount, bps).max(units(ORDER_FEE_MIN, decimals)) }
81
82/// sha256 of the terms JSON: what the order stores and a pay token must carry.
83pub fn terms_hash(json: &[u8]) -> [u8; 32] { hashv(&[json]).to_bytes() }
84/// sha256 of "owner/name": the repository that holds the workflows an order pins.
85pub fn wf_repo_hash(repository: &str) -> [u8; 32] { hashv(&[repository.as_bytes()]).to_bytes() }
86/// The scope of a public order: sha256("knos3:scope" || repo id || issue).
87pub fn scope(repo_id: u64, issue: u64) -> [u8; 32] { hashv(&[b"knos3:scope", &repo_id.to_le_bytes(), &issue.to_le_bytes()]).to_bytes() }
88/// The scope of a private order: sha256(salt || repo id || issue); the salt stays off chain.
89pub fn private_scope(salt: &[u8; 32], repo_id: u64, issue: u64) -> [u8; 32] { hashv(&[salt, &repo_id.to_le_bytes(), &issue.to_le_bytes()]).to_bytes() }
90
91/// ["auth"]: owns every token account of the program. Only the program signs for it.
92pub fn auth(program: &Pubkey) -> Pubkey { Pubkey::find_program_address(&[b"auth"], program).0 }
93/// ["pause"]: new funding is refused until the time in it. FundOrderWallet and TopUp take it; it need not exist.
94pub fn pause(program: &Pubkey) -> Pubkey { Pubkey::find_program_address(&[b"pause"], program).0 }
95/// ["ord", scope, source, seq]: `source` is the funding wallet (or PDA); `seq` is the funder's own counter, so one
96/// funder can fund an issue more than once.
97pub fn order(program: &Pubkey, scope: &[u8; 32], source: &Pubkey, seq: u32) -> Pubkey {
98    Pubkey::find_program_address(&[b"ord", scope, source.as_ref(), &seq.to_le_bytes()], program).0
99}
100/// ["ov", order]: the token account that holds one order's money and nothing else.
101pub fn ov(program: &Pubkey, order: &Pubkey) -> Pubkey { Pubkey::find_program_address(&[b"ov", order.as_ref()], program).0 }
102/// The associated token account of `owner` for `mint` (an owner off the curve, a PDA, has one too).
103pub fn ata(owner: &Pubkey, mint: &Pubkey, token_program: &Pubkey) -> Pubkey {
104    Pubkey::find_program_address(&[owner.as_ref(), token_program.as_ref(), mint.as_ref()], &ATA_PROGRAM).0
105}
106
107/// What a funder fixes beside the amount and the terms (48 bytes on the wire). Limits: holdback_bps <= 5000 and only
108/// with a warranty, warranty_days <= 90, kill_bps <= 2000; a STANDING order has a rate in 1..=amount, any other none.
109#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
110pub struct Opts {
111    pub flags: u8, pub holdback_bps: u16, pub warranty_days: u16, pub kill_bps: u16, pub reserve_days: u8, pub rate: u64, pub arbiter_id: u64,
112    pub judge_repo_id: u64, pub salted: bool,
113}
114impl Opts {
115    pub fn to_bytes(&self) -> [u8; OPTS_LEN] {
116        let mut o = [0u8; OPTS_LEN];
117        o[0] = self.flags;
118        o[1..3].copy_from_slice(&self.holdback_bps.to_le_bytes());
119        o[3..5].copy_from_slice(&self.warranty_days.to_le_bytes());
120        o[5..7].copy_from_slice(&self.kill_bps.to_le_bytes());
121        o[7] = self.reserve_days;
122        o[8..16].copy_from_slice(&self.rate.to_le_bytes());
123        o[16..24].copy_from_slice(&self.arbiter_id.to_le_bytes());
124        o[24..32].copy_from_slice(&self.judge_repo_id.to_le_bytes());
125        o[32] = self.salted as u8;
126        o
127    }
128}
129
130/// An order to fund. `amount` is what the payees receive (the fee comes on top); `work_s` is how long the order
131/// stays open before it can be refunded; `wf_repo` and `wf_sha` pin the workflows whose signed run can pay it.
132/// A PRIVATE order: `opts` with F_PRIVATE and `salted`, `private_scope` set, `repo_id` and `issue` 0, and the
133/// `terms` passed to `fund_order_wallet` are the 32-byte terms hash instead of the JSON.
134#[derive(Clone, Copy, Debug, PartialEq, Eq)]
135pub struct FundOrder {
136    pub repo_id: u64, pub issue: u64, pub amount: u64, pub mode: u8, pub work_s: i64, pub seq: u32, pub opts: Opts, pub wf_repo: [u8; 32],
137    pub wf_sha: [u8; 40], pub private_scope: Option<[u8; 32]>,
138}
139impl Default for FundOrder {
140    fn default() -> Self {
141        FundOrder { repo_id: 0, issue: 0, amount: 0, mode: MERGE, work_s: 14 * 86_400, seq: 0, opts: Opts::default(), wf_repo: [0; 32], wf_sha: [b'0'; 40],
142                    private_scope: None }
143    }
144}
145impl FundOrder {
146    pub fn scope(&self) -> [u8; 32] { self.private_scope.unwrap_or_else(|| scope(self.repo_id, self.issue)) }
147    /// The address of the order this funds from `funder`.
148    pub fn address(&self, program: &Pubkey, funder: &Pubkey) -> Pubkey { order(program, &self.scope(), funder, self.seq) }
149}
150
151/// 15 FundOrderWallet. Accounts: funder(s,w) order(w) ov(w) funder_token(w) mint auth token_program system pause.
152/// Moves amount + order_fee(amount) from `funder_token` to the order's own token account and creates both; the
153/// funder pays their rent and gets it back when the order closes.
154pub fn fund_order_wallet(program: &Pubkey, funder: &Pubkey, funder_token: &Pubkey, mint: &Pubkey, token_program: &Pubkey, f: &FundOrder,
155                         terms: &[u8]) -> Instruction {
156    let order = f.address(program, funder);
157    let mut data = Vec::with_capacity(190 + terms.len());
158    data.push(15);
159    data.extend_from_slice(&f.issue.to_le_bytes());
160    data.extend_from_slice(&f.repo_id.to_le_bytes());
161    data.extend_from_slice(&f.amount.to_le_bytes());
162    data.push(f.mode);
163    data.extend_from_slice(&f.work_s.to_le_bytes());
164    data.extend_from_slice(&f.seq.to_le_bytes());
165    data.extend_from_slice(&f.opts.to_bytes());
166    data.extend_from_slice(&f.wf_repo);
167    data.extend_from_slice(&f.wf_sha);
168    if let Some(s) = &f.private_scope { data.extend_from_slice(s); }
169    data.extend_from_slice(terms);
170    Instruction { program_id: *program, data, accounts: vec![
171        AccountMeta::new(*funder, true), AccountMeta::new(order, false), AccountMeta::new(ov(program, &order), false),
172        AccountMeta::new(*funder_token, false), AccountMeta::new_readonly(*mint, false), AccountMeta::new_readonly(auth(program), false),
173        AccountMeta::new_readonly(*token_program, false), AccountMeta::new_readonly(system_program::ID, false),
174        AccountMeta::new_readonly(pause(program), false),
175    ] }
176}
177
178/// 23 TopUp. Accounts: signer(s,w) order(w) ov(w) from_token(w) balance mint auth token_program pause. Adds `add` to
179/// an open order's amount, and the fee on the new amount less the fee already there. `signer` is the order's
180/// source (the funding wallet or PDA); `from_token`: a token account of it (default: its associated token account).
181pub fn top_up(program: &Pubkey, signer: &Pubkey, order: &Pubkey, o: &Order, add: u64, from_token: Option<&Pubkey>) -> Instruction {
182    let tp = o.token_program();
183    let from = match from_token { Some(k) => *k, None if o.from_balance => o.refund_to, None => ata(&o.source, &o.mint, &tp) };
184    let mut data = vec![23];
185    data.extend_from_slice(&add.to_le_bytes());
186    Instruction { program_id: *program, data, accounts: vec![
187        AccountMeta::new(*signer, true), AccountMeta::new(*order, false), AccountMeta::new(ov(program, order), false), AccountMeta::new(from, false),
188        AccountMeta::new_readonly(o.source, false), AccountMeta::new_readonly(o.mint, false), AccountMeta::new_readonly(auth(program), false),
189        AccountMeta::new_readonly(tp, false), AccountMeta::new_readonly(pause(program), false),
190    ] }
191}
192
193/// 22 RefundOrder. Accounts: relayer(s,w) order(w) ov(w) refund_token(w) auth rent_to(w) mint token_program. Anyone
194/// sends it and no token is needed: an open order past its deadline (or a held one past its hold) gives everything
195/// it holds back to a token account of its funder (default: the funder's associated token account).
196pub fn refund_order(program: &Pubkey, relayer: &Pubkey, order: &Pubkey, o: &Order, refund_token: Option<&Pubkey>) -> Instruction {
197    let tp = o.token_program();
198    let dest = match refund_token { Some(k) => *k, None if o.from_balance => o.refund_to, None => ata(&o.refund_to, &o.mint, &tp) };
199    Instruction { program_id: *program, data: vec![22], accounts: vec![
200        AccountMeta::new(*relayer, true), AccountMeta::new(*order, false), AccountMeta::new(ov(program, order), false), AccountMeta::new(dest, false),
201        AccountMeta::new_readonly(auth(program), false), AccountMeta::new(o.rent_to, false), AccountMeta::new_readonly(o.mint, false),
202        AccountMeta::new_readonly(tp, false),
203    ] }
204}
205
206/// A work order as knos_pay stores it (512 bytes, version 2). An order that was paid out or refunded is gone.
207#[derive(Clone, Debug, PartialEq, Eq)]
208pub struct Order {
209    pub state: u8, pub mode: u8, pub from_balance: bool, pub flags: u8, pub bump: u8, pub decimals: u8, pub reserve_days: u8, pub repo_id: u64,
210    pub issue: u64, pub scope: [u8; 32], pub seq: u32, pub holdback_bps: u16, pub kill_bps: u16, pub amount: u64, pub fee: u64, pub rate: u64,
211    pub paid: u64, pub deadline: i64, pub not_before: i64, pub hold_until: i64, pub warranty_s: i64, pub reserved_by: u64, pub reserved_until: i64,
212    pub cancel_at: i64, pub payee_id: u64, pub funder_id: u64, pub owner_id: u64, pub arbiter_id: u64, pub judge_repo_id: u64, pub source: Pubkey,
213    pub refund_to: Pubkey, pub rent_to: Pubkey, pub mint: Pubkey, pub terms: [u8; 32], pub wf_repo: [u8; 32], pub wf_sha: [u8; 40], pub fee_bps: u16,
214    /// The slot of the order's funding plus one, which its judges' markers are bound to (0: funded under 2.1).
215    pub inc: u64,
216    /// A pay token issued by the deadline is still taken for a grace after it, and no refund is taken before.
217    pub grace: bool,
218}
219impl Order {
220    /// The order's fields, with no check of where the bytes came from: only their length and version.
221    pub fn parse(d: &[u8]) -> Option<Order> {
222        if d.len() != ORDER_LEN || d[0] != 2 { return None; }
223        let u16_at = |o: usize| u16::from_le_bytes([d[o], d[o + 1]]);
224        let u64_at = |o: usize| u64::from_le_bytes(d[o..o + 8].try_into().unwrap());
225        let i64_at = |o: usize| i64::from_le_bytes(d[o..o + 8].try_into().unwrap());
226        let key = |o: usize| Pubkey::new_from_array(d[o..o + 32].try_into().unwrap());
227        Some(Order {
228            state: d[1], mode: d[2], from_balance: d[3] == 1, flags: d[4], bump: d[5], decimals: d[6], reserve_days: d[7], repo_id: u64_at(8),
229            issue: u64_at(16), scope: d[24..56].try_into().unwrap(), seq: u32::from_le_bytes(d[56..60].try_into().unwrap()), holdback_bps: u16_at(60),
230            kill_bps: u16_at(62), amount: u64_at(64), fee: u64_at(72), rate: u64_at(80), paid: u64_at(88), deadline: i64_at(96), not_before: i64_at(104),
231            hold_until: i64_at(112), warranty_s: i64_at(120), reserved_by: u64_at(128), reserved_until: i64_at(136), cancel_at: i64_at(144),
232            payee_id: u64_at(152), funder_id: u64_at(160), owner_id: u64_at(168), arbiter_id: u64_at(176), judge_repo_id: u64_at(184), source: key(192),
233            refund_to: key(224), rent_to: key(256), mint: key(288), terms: d[320..352].try_into().unwrap(), wf_repo: d[352..384].try_into().unwrap(),
234            wf_sha: d[384..424].try_into().unwrap(), fee_bps: u16_at(424), inc: u64_at(432), grace: d[440] == 1,
235        })
236    }
237    /// An order read ON CHAIN from an account another program was handed: the account's owner is `program`, and
238    /// its address is the one its own fields derive, so nothing else can pass for an order.
239    pub fn read(address: &Pubkey, owner: &Pubkey, data: &[u8], program: &Pubkey) -> Option<Order> {
240        if owner != program { return None; }
241        let o = Order::parse(data)?;
242        let at = Pubkey::create_program_address(&[b"ord", &o.scope, o.source.as_ref(), &o.seq.to_le_bytes(), &[o.bump]], program).ok()?;
243        if at == *address { Some(o) } else { None }
244    }
245    pub fn is(&self, flag: u8) -> bool { self.flags & flag != 0 }
246    pub fn token_program(&self) -> Pubkey { if self.is(F_TOKEN2022) { TOKEN_2022 } else { TOKEN } }
247    pub fn address(&self, program: &Pubkey) -> Pubkey { order(program, &self.scope, &self.source, self.seq) }
248    /// Whether RefundOrder would be accepted at `now`: open past the deadline, or held past the hold. (An order with
249    /// `grace` is refunded only once its grace has passed as well: this does not count the grace.)
250    pub fn refundable(&self, now: i64) -> bool { (self.state == OPEN && now > self.deadline) || (self.state == HELD && now > self.hold_until) }
251}