Skip to content

Instantly share code, notes, and snippets.

@perfectmak
Created June 1, 2022 01:06
Show Gist options
  • Save perfectmak/417a4dab69243c517654195edf100ef9 to your computer and use it in GitHub Desktop.
Save perfectmak/417a4dab69243c517654195edf100ef9 to your computer and use it in GitHub Desktop.
Starknet Code to interact with Poster Contract on Chain
[
{
"data": [
{
"name": "address",
"type": "felt"
},
{
"name": "content_len",
"type": "felt"
},
{
"name": "content",
"type": "felt*"
},
{
"name": "tag_len",
"type": "felt"
},
{
"name": "tag",
"type": "felt*"
}
],
"keys": [],
"name": "new_post",
"type": "event"
},
{
"inputs": [
{
"name": "content_len",
"type": "felt"
},
{
"name": "content",
"type": "felt*"
},
{
"name": "tag_len",
"type": "felt"
},
{
"name": "tag",
"type": "felt*"
}
],
"name": "post",
"outputs": [],
"type": "function"
}
]
import { strToShortStringArr } from "@snapshot-labs/sx";
import { Account, ec, Contract, defaultProvider as provider } from "starknet";
import abi from "./abi.json";
const randomInt = (digits): number => {
return Math.trunc(Math.random() * 10 ** digits);
};
function toString(value: any): string {
return value.toString();
}
const accountAddress = process.env.ACCOUNT_ADDRESS || "";
const accountPk = process.env.ACCOUNT_PK || "";
const posterAddress =
process.env.POSTER_ADDRESS ||
"0x04d10712e72b971262f5df09506bbdbdd7f729724030fa909e8c8e7ac2fd0012";
async function main() {
const contentString = `This is a random post with a random number: ${randomInt(
3
)}`;
const tagString = randomInt(2) % 2 === 0 ? "public" : "private";
// uncomment to use customer account to sign
// const keypair = ec.getKeyPair(accountPk);
// const keypair = ec.genKeyPair();
// console.log(keypair.getPublic().encode("hex"));
// const account = new Account(provider, accountAddress, keypair);
//@ts-ignore
const postContract = new Contract(abi, posterAddress, provider);
const contentFelt = strToShortStringArr(contentString);
const tagFelt = strToShortStringArr(tagString);
const receipt = await postContract.post(
contentFelt.map(toString),
tagFelt.map(toString)
);
console.log("Receipt", receipt);
await provider.waitForTx(receipt.transaction_hash);
}
main().then(console.log);
{
"name": "test_starknet",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"start": "nodemon index.ts"
},
"keywords": [],
"author": "",
"license": "ISC",
"dependencies": {
"@snapshot-labs/sx": "^0.1.0-beta.0",
"@types/node": "^17.0.38",
"nodemon": "^2.0.16",
"starknet": "^3.9.0",
"ts-node": "^10.8.0",
"tsc": "^2.0.4",
"typescript": "^4.7.2"
}
}
@perfectmak
Copy link
Author

The Cairo code for the Poster Contract can be found here: https://github.com/snapshot-labs/starknet-poster

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment